diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..272b20e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,50 @@ +--- +name: Bug report +about: Create a report to help the project improve +title: '' +labels: '' +assignees: '' +--- +**Describe the problem** + +You may find that this issue has arisen before, so here is a checklist of useful links to provide assistance and potentially avoid duplicate issues: +- [ ] I have read the [Troubleshooting Guide](https://github.com/gary-rowe/hid4java/wiki/Troubleshooting) and this is not covered +- [ ] I have done a [quick search of previous issues](https://github.com/gary-rowe/hid4java/issues?q=is%3Aissue+hidraw) and this needs addressing + +Please provide a clear and concise description of what the problem is below: + +**Platform** + +Knowing the platform greatly narrows down the potential causes of the problem. + +- Platform (e.g. `linux-x86-64`): +- OS version (e.g. `Ubuntu 22.04`): +- `hid4java` version (e.g. `0.8.0`): + +**To Reproduce** + +Steps to reproduce the behavior: + +1. Attempting to read from device '...' +2. Code sample looks like this '...' +3. Error happens when '...' + +**Expected behavior** + +A clear and concise description of what you expected to happen. + +**Screenshots and logs** + +If applicable, add screenshots and redacted logs to help explain your problem. + +Screenshots: +Drag and drop image here if useful + +Logs: +``` + +``` + +**Additional information** +Add any other context about the problem here, including any investigative work +done and thoughts on solution. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..e48b7ae --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,28 @@ +--- +name: Feature request +about: Suggest an idea for hid4java +title: '' +labels: '' +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. + +* I'm always frustrated when [...], or +* If only you supported [...] +* Why do I always have to [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +* After a bit of research, I think this could be solved by [...] +* You support platform [...] + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've +considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/.github/ISSUE_TEMPLATE/release.md b/.github/ISSUE_TEMPLATE/release.md new file mode 100644 index 0000000..2f1fed5 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/release.md @@ -0,0 +1,29 @@ +--- +name: Release +about: Create a release checklist +title: 'Release checklist for 0.x.0' +labels: '' +assignees: 'gary-rowe' +--- +Here's what's outstanding before `0.x.0` can be released. + +**Pre-release checklist** + +- [ ] FIDO2 device verified working in all test environments +- [ ] `develop-SNAPSHOT` deployed to Maven Central (snapshots) +- [ ] Issues for release marked as "Awaiting merge" + +Feedback received from community verifying the following libraries for `develop-SNAPSHOT`: + +- [ ] `darwin-x86-64` - macOS 64-bit +- [ ] `darwin-aarch64` - macOS ARM64 +- [ ] `linux-aarch64` - Linux ARMv8 64-bit only +- [ ] `linux-amd64` - Linux AMD 64-bit only +- [ ] `linux-arm` - Linux ARMv7 hard float 32-bit only +- [ ] `linux-armel` - Linux ARMv5 soft float 32-bit +- [ ] `linux-riscv64` - Linux RISC-V 64-bit +- [ ] `linux-x86-64` - Linux x86 64-bit only +- [ ] `linux-x86` - Linux x86 32-bit only +- [ ] `win32-x86` - Windows 32-bit only +- [ ] `win32-x86-64` - Windows 64-bit only +- [ ] `win32-aarch64` - Windows 64-bit ARM64 diff --git a/.gitignore b/.gitignore index 108e0cc..1365da7 100644 --- a/.gitignore +++ b/.gitignore @@ -13,4 +13,6 @@ # Maven log/ -target/ \ No newline at end of file +target/ +/release.properties +/pom.xml.releaseBackup diff --git a/.travis.yml b/.travis.yml index e65b97d..0598631 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,5 @@ language: java jdk: - - openjdk6 \ No newline at end of file + # Test on Open JDK 11 on Travis due to EOL issues + - openjdk11 \ No newline at end of file diff --git a/AUTHORS b/AUTHORS index b6911ca..b016722 100644 --- a/AUTHORS +++ b/AUTHORS @@ -2,4 +2,6 @@ The following developers made contributions to this project: Gary Rowe (Lead developer) jbliesener - +Ktar5 +tresf +DaPutzy diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..8839e71 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,76 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, sex characteristics, gender identity and expression, +level of experience, education, socio-economic status, nationality, personal +appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at g.rowe@froot.co.uk. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see +https://www.contributor-covenant.org/faq diff --git a/README.md b/README.md index ca4a60e..683c360 100644 --- a/README.md +++ b/README.md @@ -1,26 +1,27 @@ -Status: [![Build Status](https://travis-ci.org/gary-rowe/hid4java.png?branch=master)](https://travis-ci.org/gary-rowe/hid4java) +# Project status -### Project status +[![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.hid4java/hid4java/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.hid4java/hid4java) [![Javadoc](https://javadoc.io/badge2/org.hid4java/hid4java/javadoc.svg)](https://javadoc.io/doc/org.hid4java/hid4java) -Release: Available for production work +# 🌟 Summary -Latest release: [![Maven Central](https://maven-badges.herokuapp.com/maven-central/org.hid4java/hid4java/badge.svg)](https://maven-badges.herokuapp.com/maven-central/org.hid4java/hid4java) +The `hid4java` project supports USB HID devices through a common API which is provided here under the MIT license. The API is very simple but provides great flexibility such as support for feature reports and blocking reads with timeouts. Attach/detach events are provided to allow applications to respond instantly to device availability. -### Summary +## Telegram group -The hid4java project supports USB HID devices through a common API which is provided here under the MIT license. -The API is very simple but provides great flexibility such as support for feature reports and blocking reads with -timeouts. Attach/detach events are provided to allow applications to respond instantly to device availability. +If you want to discuss `hid4java` in general please use [the Telegram chat](https://t.me/joinchat/CtU4ZBltWCAFBAjwM5KLLw). I can't guarantee +an instant response but I'm usually active on Telegram during office hours in the GMT timezone. -The wiki provides a [guide to building the project](https://github.com/gary-rowe/hid4java/wiki/How-to-build-the-project). +👀 Remember to [check the Wiki first](https://github.com/gary-rowe/hid4java/wiki/Home) before asking questions to avoid causing frustration! -### Technologies +## Technologies -* [hidapi](https://github.com/signal11/hidapi) - Native USB HID library for multiple platforms -* [JNA](https://github.com/twall/jna) - to remove the need for Java Native Interface (JNI) and greatly simplify the project -* Java 6+ - to remove dependencies on JVMs that have reached end of life +* [hidapi](https://github.com/libusb/hidapi) - Native USB HID library for multiple platforms +* [JNA](https://github.com/twall/jna) - Removes the need for Java Native Interface (JNI) and greatly simplify the project +* [dockcross](https://github.com/dockcross/dockcross) - Cross-compilation environments for multiple platforms to create hidapi libraries +* [Maven](https://maven.apache.org/) - Build environment for Java projects if you need to customise the library +* Java 8+ - to remove dependencies on JVMs that have reached end of life -### Maven dependency +## Maven dependency ```xml @@ -30,214 +31,105 @@ The wiki provides a [guide to building the project](https://github.com/gary-rowe org.hid4java hid4java - 0.4.0 + 0.8.0 ``` +If you are developing and want the latest code, you'll need to reference release candidate artifacts deployed to the Maven Central snapshot repository. These are updated more frequently as part of wider user acceptance testing, but they are not considered stable enough for production use. +Add the following `repositories` section to your project's `pom.xml` if you're using Maven for your build process. -### Code example - -Taken from [UsbHidTrezorV1Example](https://github.com/gary-rowe/hid4java/blob/develop/src/main/java/UsbHidTrezorV1Example.java) which -provides more details. See later for how to run it from the command line. - -```java -// Get HID services -hidServices = HidManager.getHidServices(); -hidServices.addHidServicesListener(this); - -// Provide a list of attached devices -for (HidDevice hidDevice : hidServices.getAttachedHidDevices()) { - System.out.println(hidDevice); -} - -// Open a Bitcoin Trezor device by Vendor ID and Product ID with wildcard serial number -HidDevice trezor = hidServices.getHidDevice(0x534c, 0x01, null); - -// Send the Initialise message -byte[] message = new byte[64]; -message[0] = 0x3f; -message[1] = 0x23; -message[2] = 0x23; - -int val = trezor.write(message, 64, (byte) 0); -if (val != -1) { - System.out.println("> [" + val + "]"); -} else { - System.err.println(trezor.getLastErrorMessage()); -} - -// Clean shutdown -hidServices.shutdown(); - -``` - -### Getting started - -If you're unfamiliar with Maven and git the wiki provides [an easy guide to creating a development environment](https://github.com/gary-rowe/hid4java/wiki/How-to-build-the-project). - -The project uses the standard Maven build process and can be used without having external hardware attached. Just do the usual - -``` -cd -mvn clean install -``` - -and you're good to go. If you're in an IDE then you can use `src/test/java/org/hid4java/UsbHidTrezorV1Example`) to verify correct -operation. From the command line: - -``` - mvn clean test exec:java -Dexec.classpathScope="test" -Dexec.mainClass="org.hid4java.UsbHidDeviceExample" -``` -If you have a Trezor device attached you'll see a "Features" message appear as a big block of hex otherwise it will be -just a simple enumeration of attached USB devices. You can plug various devices in and out to see messages. - -Use CTRL+C to quit the example. - -### Frequently asked questions (FAQ) - -#### What platforms do you support ? - -If you have a native version of `hidapi` for your platform then you'll be able to support it. - -Pre-compiled versions for Windows (32/64), OS X (10.5+) and Linux (32/64) are provided and you -must follow the JNA naming convention when adding new libraries. - -#### Why not just use usb4java ? - -The [usb4java](http://usb4java.org/) project, while superb, does not support HID devices on OS X -and apparently there are no plans to introduce HID support anytime soon. - -You will find that trying to claim the USB device on OS X will fail with permissions problems. If -you apply a workaround (such as adding a kernel extension) then it will still fall over just a -little later in the process. The bottom line is that you *must* use hidapi to communicate with HID -devices on OS X. - -#### Is the latest code in Maven Central ? - -Yes but not the older versions at present. If you need to use the older code for some -reason, you'll need to add this to your project's `pom.xml`. ```xml + - - mbhd-maven-release - https://raw.github.com/bitcoin-solutions/mbhd-maven/master/releases - - - - - - mbhd-maven-snapshot - https://raw.github.com/bitcoin-solutions/mbhd-maven/master/snapshots - + oss.sonatype.org-snapshot + https://oss.sonatype.org/content/repositories/snapshots + + false + - always + true - - - - - - - org.hid4java - hid4java - 0.4.0 - - - - ``` - -#### Can I just copy this code into my project ? -Yes. Perhaps you'd prefer to use +## Gradle dependency -``` -git submodule add https://github.com/gary-rowe/hid4java hid4java -``` -so that you can keep up to date with changes whilst still fixing the version. - - -### Troubleshooting - -The following are known issues and their solutions or workarounds. +```gradle -#### I get a `SIGSEGV (0xb)` when starting up - -This shouldn't occur unless you've been changing the code. +repositories { + mavenCentral() +} -You have probably got the `getFieldOrder` list wrong. Use the field list from Class.getFields() to get a suitable order. -Another cause is if a `Structure` has not been initialised and is being deferenced, perhaps in a `toString()` method. +dependencies { + implementation('org.hid4java:hid4java') +} -There is also the possibility that using the built-in `HidDeviceManager` code can cause problems in some applications. +``` -#### I get a "The parameter is incorrect" when writing +## 🚀 Code example -There is a special case on Windows for report ID `0x00` which can cause a misalignment during a hidapi `write()`. -To compensate for this, hid4java will detect when it is running on Windows with a report ID of `0x00` and simply copy -the `data` unmodified to the write buffer. In all other cases it will prepend the report ID to the data before submitting -it to hidapi. +Taken from [UsbHidEnumerationExample](https://github.com/gary-rowe/hid4java/blob/develop/src/test/java/org/hid4java/examples/UsbHidEnumerationExample.java) which +provides more details. -If you're seeing this then it may be that your code is attempting to second guess hid4java. +```java +// Configure to use custom specification +HidServicesSpecification hidServicesSpecification = new HidServicesSpecification(); -#### The hidapi library doesn't load +// Use the v0.7.0 manual start feature to get immediate attach events +hidServicesSpecification.setAutoStart(false); -On startup hid4java will search the classpath looking for a library that matches the machine OS and architecture (e.g. Windows running on AMD64). It uses the JNA naming conventions to do this and will report the expected path if it fails. You can add your own entry under `src/main/resources` and it should get picked up. Ideally you should [raise an issue](https://github.com/gary-rowe/hid4java/issues) on the hid4java repo so that the proper library can be put into the project so that others can avoid this problem. +// Get HID services using custom specification +HidServices hidServices = HidManager.getHidServices(hidServicesSpecification); +hidServices.addHidServicesListener(this); -#### The hidapi library loads but takes a long time on Windows +// Manually start the services to get attachment event +hidServices.start(); -You have probably terminated the JVM using a `kill -9` rather than a clean shutdown. This will have left the `HidApi` process lock on the DLL still in force and Windows will continuously check to see if it can share it with a new instance. -Just detach and re-attach the device to clear it. +// Provide a list of attached devices +for (HidDevice hidDevice : hidServices.getAttachedHidDevices()) { + System.out.println(hidDevice); +} + +``` -#### I'm seeing spurious attach/detach events occurring on Windows +# ⚙ Local build -This was a device enumeration bug in early versions of hid4java. Use 0.3.1 or higher. +If you're unfamiliar with Maven and git the wiki provides [an easy guide to creating a development environment](https://github.com/gary-rowe/hid4java/wiki/How-to-set-up-a-build-environment-from-scratch). -#### My device doesn't work on Linux +The project uses the standard Maven build process and can be used without having external hardware attached. Just do the usual -Different flavours of Linux require different settings: +```shell +cd +git clone https://github.com/gary-rowe/hid4java.git +cd hid4java -##### Ubuntu -Out of the box Ubuntu classifies HID devices as belonging to root. You can override this rule by creating your own under `/etc/udev/rules.d`: -``` -sudo gedit /etc/udev/rules.d/99-myhid.rules -``` -Make the content of this file as below (using your own discovered hex values for `idProduct` and `idVendor`): -``` -# My HID device -ATTRS{idProduct}=="0001", ATTRS{idVendor}=="abcd", MODE="0660", GROUP="plugdev" -``` -Save and exit from root, then unplug and replug your device. The rules should take effect immediately. If they're still not running it may that you're not a member of the `plugdev` group. You can fix this as follows (assuming that `plugdev` is not present on your system): -``` -sudo addgroup plugdev -sudo addgroup yourusername plugdev +# Maven build +mvn clean install ``` -##### Slackware -Edit the USB udev rules `/etc/udev/rules.d` as follows: -``` -MODE="0666", GROUP="dialout" -``` +and you're good to go. -##### ARM -Running on ARM machines you may encounter problems due to a missing library. This is just a naming issue for the `udev` library and can be resolved using the following command (or equivalent for your system): -``` -sudo ln -sf /lib/arm-linux-gnueabihf/libudev.so.1 /lib/arm-linux-gnueabihf/libudev.so.0 -``` -Thanks to @MaxRoma for that one! +Maven will place the built JAR into the `target` directory. +The Maven `install` process will also place copies of the built JARs into `~/.m2/repository/org/hid4java/hid4java//` so that other local projects can find and share them. -#### My device doesn't work on Windows +# 🤔 More information -Check that the usage page is not `0x06` which is reserved for keyboards and mice. [Windows opens these devices for its exclusive use](https://msdn.microsoft.com/en-us/library/windows/hardware/jj128406%28v=vs.85%29.aspx) and thus hid4java -cannot establish its own connection to them. You will need to use the lower level usb4java library for this. +Much of the information previously in this README has been migrated to the [project Wiki](https://github.com/gary-rowe/hid4java/wiki/Home) as it was getting rather long. Here are some useful jumping off points that should help: -### Closing notes +* [Home](https://github.com/gary-rowe/hid4java/wiki/Home) - The wiki Home page with lots of useful launch points +* [FAQ](https://github.com/gary-rowe/hid4java/wiki/FAQ) - Frequently asked questions +* [Examples](https://github.com/gary-rowe/hid4java/wiki/Examples) - Using the examples to kickstart your own project +* [Troubleshooting](https://github.com/gary-rowe/hid4java/wiki/Troubleshooting) - A comprehensive troubleshooting guide + +# 📕 Closing notes All trademarks and copyrights are acknowledged. -Many thanks to victorix who provided the basis for this library. Please see the inspiration on the mbed.org site.

+Many thanks to `victorix` who provided the basis for this library. Please [see the inspiration on the mbed site](https://os.mbed.com/cookbook/USBHID-bindings-). + +Thanks also go to everyone who has contributed their knowledge and advice during the creation and subsequent improvement of this library. diff --git a/build-hidapi.sh b/build-hidapi.sh new file mode 100755 index 0000000..883d8ef --- /dev/null +++ b/build-hidapi.sh @@ -0,0 +1,555 @@ +#!/usr/bin/env bash + +# Convenience script to build hidapi locally +# Directory structure is +# ~/Workspaces +# + Cpp +# + hidapi (https://github.com/libusb/hidapi) +# + Docker +# + dockcross (https://github.com/dockcross/dockcross) +# + Java +# + Personal +# + hid4java (https://github.com/gary-rowe/hid4java) +# +# Dependencies: +# - git +# - Docker Desktop +# - XCode v12.5.1 or higher for darwin-x86-64-aarch64 cross compiler support +# +# Place a symlink to this script in the root of ~/Workspaces +# cd ~/Workspaces +# ln -s Java/Personal/hid4java/build-hidapi.sh ./build-hidapi.sh +# +# Supported command line arguments are: +# +# all - build all variants +# windows - build all Windows variants +# linux - build all Linux variants +# darwin - build all macOS variants (not recommended) +# darwin-x86-64 - macOS 64-bit +# darwin-aarch64 - macOS ARM64 +# linux-aarch64 - Linux ARMv8 64-bit +# linux-amd64 - Linux AMD 64-bit +# linux-arm - Linux ARMv6 hard float 32-bit (RPi) +# linux-armel - Linux ARMv5 soft float 32-bit +# linux-riscv64 - Linux RISC-V 64-bit +# linux-x86-64 - Linux x86 64-bit (same as AMD64) +# linux-x86 - Linux x86 32-bit +# win32-x86 - Windows 32-bit +# win32-x86-64 - Windows 64-bit +# win32-aarch64 - Windows 64-bit ARM64 +# + +# Set environment +hid4javaDir="${HOME}/Workspaces/Java/Personal/hid4java" +hidapiDir="${HOME}/Workspaces/Cpp/hidapi" +dockcrossDir="${HOME}/Workspaces/Docker/dockcross" + +hardwareName=$(uname -m) +if [[ "${hardwareName}" == "arm64" ]] + then + platform="--platform linux/amd64" + else + platform="" +fi + +# Console colours +red="\033[31m" +yellow="\033[33m" +green="\033[32m" +plain="\033[0m" + +# Initial checks +# @Tresf: macOS deployment target checking +# See https://github.com/gary-rowe/hid4java/issues/120 for more details +if [[ "$1" == "all" ]] || [[ "$1" == "darwin" ]] || [[ "$1" == "darwin-aarch64" ]] || [[ "$1" == "darwin-x86-64" ]] + then + if [ -z "$SDKROOT" ] || [ -z "$MACOSX_DEPLOYMENT_TARGET" ]; + then + echo -e "${yellow}WARNING: For production builds, please set \$SDKROOT and \$MACOSX_DEPLOYMENT_TARGET before building${plain}" + echo -e "${yellow}Continuing with default values${plain}" + export SDKROOT="$(xcrun --sdk macosx --show-sdk-path)" + if [[ "$1" == "all" ]] || [[ "$1" == "darwin" ]] || [[ "$1" == "darwin-aarch64" ]] + then + # Build for darwin-aarch64 with minimum of OS Big Sur (2020) + export MACOSX_DEPLOYMENT_TARGET="11.0" + else + # Build for darwin-x86-64 with minimum of OS Mavericks (2013) + export MACOSX_DEPLOYMENT_TARGET="10.9" + fi + fi +fi + +# @Tresf: Function to do "make clean" without incurring issues during build +function git-clean { + echo -e "${yellow}Cleaning hidapi${plain}" + # Remove all untracked files (including project files) + git clean -fdx > /dev/null 2>&1 || exit + # Reset all tracked files + git reset --hard > /dev/null 2>&1 || exit +} + +# Function to provide library file details +function report { + +if [[ ! -f $1 ]] + then + echo -e "${red}File '$1' was not found.${plain}" + else + ls -la $1 + file -b $1 + echo -e "${green}---${plain}" +fi +} + +echo -e "${green}------------------------------------------------------------------------${plain}" +echo -e "${yellow}Using '$1' to perform build${plain}" + +echo -e "${green}------------------------------------------------------------------------${plain}" + +if [[ "$1" == "update" ]] + then + echo -e "${green}Updating Dockcross${plain}" + cd ${dockcrossDir} || exit + git checkout master + git pull + + # Windows cross compilers + + # 64-bit (Intel) + echo -e "${green}Configuring Windows 64-bit${plain}" + docker run ${platform} --rm dockcross/windows-shared-x64 > ./dockcross-windows-shared-x64 + chmod +x ./dockcross-windows-shared-x64 + mv ./dockcross-windows-shared-x64 /usr/local/bin + + # 32-bit (Intel) + echo -e "${green}Configuring Windows 32-bit${plain}" + docker run ${platform} --rm dockcross/windows-shared-x86 > ./dockcross-windows-shared-x86 + chmod +x ./dockcross-windows-shared-x86 + mv ./dockcross-windows-shared-x86 /usr/local/bin + + # 64-bit (ARM64) + echo -e "${green}Configuring Windows 64-bit ARM64 (aarch64)${plain}" + docker run ${platform} --rm dockcross/windows-arm64 > ./dockcross-windows-arm64 + chmod +x ./dockcross-windows-arm64 + mv ./dockcross-windows-arm64 /usr/local/bin + + echo -e "${green}Configuring Linux environments${plain}" + + # Linux cross compilers + + # 64 bit (Intel) + echo -e "${green}Configuring Linux 64-bit${plain}" + docker run ${platform} --rm dockcross/linux-x64 > ./dockcross-linux-x64 + chmod +x ./dockcross-linux-x64 + mv ./dockcross-linux-x64 /usr/local/bin + + # 32 bit (Intel) + echo -e "${green}Configuring Linux 32-bit${plain}" + docker run ${platform} --rm dockcross/linux-x86 > ./dockcross-linux-x86 + chmod +x ./dockcross-linux-x86 + mv ./dockcross-linux-x86 /usr/local/bin + + # ARM cross compilers + + # @Tresf + # 32-bit ARMv5TE EABI "armel" + echo -e "${green}Configuring ARMv5TE EABI 32-bit${plain}" + docker run ${platform} --rm dockcross/linux-armv5 > ./dockcross-linux-armv5 + chmod +x ./dockcross-linux-armv5 + mv ./dockcross-linux-armv5 /usr/local/bin + + # 32-bit ARMv6 EABI + echo -e "${green}Configuring ARMv6 EABI 32-bit${plain}" + docker run ${platform} --rm dockcross/linux-armv6 > ./dockcross-linux-armv6 + chmod +x ./dockcross-linux-armv6 + mv ./dockcross-linux-armv6 /usr/local/bin + + # 32-bit ARMv7 hard float + echo -e "${green}Configuring ARMv7 32-bit${plain}" + docker run ${platform} --rm dockcross/linux-armv7 > ./dockcross-linux-armv7 + chmod +x ./dockcross-linux-armv7 + mv ./dockcross-linux-armv7 /usr/local/bin + + # 64-bit (arm64, aarch64) + echo -e "${green}Configuring ARM 64-bit${plain}" + docker run ${platform} --rm dockcross/linux-arm64 > ./dockcross-linux-arm64 + chmod +x ./dockcross-linux-arm64 + mv ./dockcross-linux-arm64 /usr/local/bin + + # RISC-V cross compilers + + # @Tresf + # 64-bit (RISC-V) + echo -e "${green}Configuring RISC-V 64-bit${plain}" + docker run --rm dockcross/linux-riscv64 > ./dockcross-linux-riscv64 + chmod +x ./dockcross-linux-riscv64 + mv ./dockcross-linux-riscv64 /usr/local/bin + + # HIDAPI latest release + echo -e "${green}Updating HIDAPI${plain}" + cd ${hidapiDir} || exit + git checkout master + git pull + else + echo -e "${yellow}Skipping updates${plain}" +fi +echo -e "${green}------------------------------------------------------------------------${plain}" + +# Build in hidapi project directory +cd ${hidapiDir} || exit + +# Windows environments + +# 64-bit x86-64 +if [[ "$1" == "all" ]] || [[ "$1" == "windows" ]] || [[ "$1" == "win32-x86-64" ]] + then + echo -e "${green}Building Windows 64-bit${plain}" && git-clean + if ! dockcross-windows-shared-x64 bash -c 'sudo apt-get update && sudo apt-get --yes install libudev-dev libusb-1.0-0-dev && sudo ./bootstrap && sudo ./configure --host=x86_64-w64-mingw32 && sudo make'; + then + echo -e "${red}Failed${plain} - Removing damaged targets" + rm ${hid4javaDir}/src/main/resources/win32-x86-64/hidapi.dll + exit + else + echo -e "${green}OK${plain}" + mkdir -p ${hid4javaDir}/src/main/resources/win32-x86-64 + cp windows/.libs/libhidapi-0.dll ${hid4javaDir}/src/main/resources/win32-x86-64/hidapi.dll + fi + else + echo -e "${yellow}Skipping win32-x86-64${plain}" +fi +echo -e "${green}------------------------------------------------------------------------${plain}" + +# 64-bit ARM win32-aarch64 +if [[ "$1" == "all" ]] || [[ "$1" == "windows" ]] || [[ "$1" == "win32-aarch64" ]] + then + echo -e "${green}Building Windows 64-bit ARM64 (aarch64)${plain}" && git-clean + if ! dockcross-windows-arm64 bash -c 'sudo apt-get update && sudo apt-get --yes install libudev-dev libusb-1.0-0-dev && sudo ./bootstrap && sudo ./configure --host=aarch64-w64-mingw32 && sudo make'; + then + echo -e "${red}Failed${plain} - Removing damaged targets" + rm ${hid4javaDir}/src/main/resources/win32-aarch64/hidapi.dll + exit + else + echo -e "${green}OK${plain}" + mkdir -p ${hid4javaDir}/src/main/resources/win32-aarch64 + cp windows/.libs/libhidapi-0.dll ${hid4javaDir}/src/main/resources/win32-aarch64/hidapi.dll + fi + else + echo -e "${yellow}Skipping win32-aarch64${plain}" +fi +echo -e "${green}------------------------------------------------------------------------${plain}" + +# 32-bit x86 +if [[ "$1" == "all" ]] || [[ "$1" == "windows" ]] || [[ "$1" == "win32-x86" ]] + then + echo -e "${green}Building Windows 32-bit${plain}" && git-clean + if ! dockcross-windows-shared-x86 bash -c 'sudo ./bootstrap && sudo ./configure --host=i686-w64-mingw32 && sudo make'; + then + echo -e "${red}Failed${plain} - Removing damaged targets" + rm ${hid4javaDir}/src/main/resources/win32-x86/hidapi.dll + else + echo -e "${green}OK${plain}" + mkdir -p ${hid4javaDir}/src/main/resources/win32-x86 + cp windows/.libs/libhidapi-0.dll ${hid4javaDir}/src/main/resources/win32-x86/hidapi.dll + fi + else + echo -e "${yellow}Skipping win32-x86${plain}" +fi +echo -e "${green}------------------------------------------------------------------------${plain}" + +# Linux environments + +# 64-bit (x86-64/amd64) +if [[ "$1" == "all" ]] || [[ "$1" == "linux" ]] || [[ "$1" == "linux-x86-64" ]] + then + echo -e "${green}Building Linux 64-bit${plain}" && git-clean + # Note the use of a double sudo apt-get update here + if ! dockcross-linux-x64 bash -c 'sudo apt-get update || sudo apt-get update && sudo apt-get --yes install libudev-dev libusb-1.0-0-dev && sudo ./bootstrap && sudo ./configure && sudo make'; + then + echo -e "${red}Failed${plain} - Removing damaged targets" + rm ${hid4javaDir}/src/main/resources/linux-x86-64/libhidapi.so + rm ${hid4javaDir}/src/main/resources/linux-amd64/libhidapi.so + rm ${hid4javaDir}/src/main/resources/linux-x86-64/libhidapi-libusb.so + rm ${hid4javaDir}/src/main/resources/linux-amd64/libhidapi-libusb.so + else + echo -e "${green}OK${plain}" + mkdir -p ${hid4javaDir}/src/main/resources/linux-x86-64 + cp linux/.libs/libhidapi-hidraw.so ${hid4javaDir}/src/main/resources/linux-x86-64/libhidapi.so + cp linux/.libs/libhidapi-hidraw.so ${hid4javaDir}/src/main/resources/linux-amd64/libhidapi.so + cp libusb/.libs/libhidapi-libusb.so ${hid4javaDir}/src/main/resources/linux-x86-64/libhidapi-libusb.so + cp libusb/.libs/libhidapi-libusb.so ${hid4javaDir}/src/main/resources/linux-amd64/libhidapi-libusb.so + fi + else + echo -e "${yellow}Skipping linux-x86-64${plain}" +fi +echo -e "${green}------------------------------------------------------------------------${plain}" + +# 32-bit +if [[ "$1" == "all" ]] || [[ "$1" == "linux" ]] || [[ "$1" == "linux-x86" ]] + then + echo -e "${green}Building Linux 32-bit${plain}" && git-clean + if ! dockcross-linux-x86 bash -c 'sudo dpkg --add-architecture i386 && sudo apt-get update && sudo apt-get --yes install libudev-dev libusb-1.0-0-dev libudev-dev:i386 libusb-1.0-0-dev:i386 && sudo ./bootstrap && sudo ./configure && sudo make'; + then + echo -e "${red}Failed${plain} - Removing damaged targets" + rm ${hid4javaDir}/src/main/resources/linux-x86/libhidapi.so + rm ${hid4javaDir}/src/main/resources/linux-x86/libhidapi-libusb.so + else + echo -e "${green}OK${plain}" + mkdir -p ${hid4javaDir}/src/main/resources/linux-x86 + cp linux/.libs/libhidapi-hidraw.so ${hid4javaDir}/src/main/resources/linux-x86/libhidapi.so + cp libusb/.libs/libhidapi-libusb.so ${hid4javaDir}/src/main/resources/linux-x86/libhidapi-libusb.so + fi + else + echo -e "${yellow}Skipping linux-x86${plain}" +fi +echo -e "${green}------------------------------------------------------------------------${plain}" + +# ARM environments + +# 64-bit (arm64/aarch64) +if [[ "$1" == "all" ]] || [[ "$1" == "linux" ]] || [[ "$1" == "linux-aarch64" ]] + then + echo -e "${green}Building Linux ARM64/aarch64 ARMv8${plain}" && git-clean + if ! dockcross-linux-arm64 bash -c 'sudo dpkg --add-architecture arm64 && sudo apt-get update && sudo apt-get --yes install gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libudev-dev:arm64 libusb-1.0-0-dev:arm64 && sudo ./bootstrap && sudo ./configure --host=aarch64-linux-gnu CC=aarch64-linux-gnu-gcc && sudo make'; + then + echo -e "${red}Failed${plain} - Removing damaged targets" + rm ${hid4javaDir}/src/main/resources/linux-aarch64/libhidapi.so + rm ${hid4javaDir}/src/main/resources/linux-aarch64/libhidapi-libusb.so + else + echo -e "${green}OK${plain}" + mkdir -p ${hid4javaDir}/src/main/resources/linux-aarch64 + cp linux/.libs/libhidapi-hidraw.so ${hid4javaDir}/src/main/resources/linux-aarch64/libhidapi.so + cp libusb/.libs/libhidapi-libusb.so ${hid4javaDir}/src/main/resources/linux-aarch64/libhidapi-libusb.so + fi + else + echo -e "${yellow}Skipping linux-aarch64${plain}" +fi +echo -e "${green}------------------------------------------------------------------------${plain}" + +# 32-bit ARMv6 hard float (linux-arm) +if [[ "$1" == "all" ]] || [[ "$1" == "linux" ]] || [[ "$1" == "linux-arm" ]] + then + echo -e "${yellow}Skipping linux-arm (use RPi direct instead)${plain}" + # It's much easier to just use the original hardware + else + echo -e "${yellow}Skipping linux-arm${plain}" +fi +echo -e "${green}------------------------------------------------------------------------${plain}" + +# @Tresf +# 32-bit ARM soft float (linux-armel) +if [[ "$1" == "all" ]] || [[ "$1" == "linux" ]] || [[ "$1" == "linux-armel" ]] + then + echo -e "${green}Building ARM soft float${plain}" && git-clean + make clean &> /dev/null + + # Disabling building hidtest + sed -i'' -e 's/SUBDIRS \+= hidtest//g' Makefile.am + + arch="armel" + deps="echo \"Obtaining $arch dependencies...\"" + deps="$deps && sudo dpkg --add-architecture $arch" + deps="$deps && sudo apt-get update" + deps="$deps && sudo apt-get --yes install libudev-dev:$arch libusb-1.0-0-dev:$arch" + deps="$deps ; echo 'WARNING: Ignoring any errors from previous command'" + deps="$deps && cp /usr/include/libudev.h ./libudev.h" + deps="$deps && export PKG_CONFIG_PATH=/usr/lib/arm-linux-gnueabi/pkgconfig/" + if ! dockcross-linux-armv5 bash -c "$deps && sudo ./bootstrap && sudo ./configure --host=aarch64-unknown-linux-gnueabi && sudo make"; + then + echo -e "${red}Failed${plain} - Removing damaged targets" + rm ${hid4javaDir}/src/main/resources/linux-armel/libhidapi.so + rm ${hid4javaDir}/src/main/resources/linux-armel/libhidapi-libusb.so + else + echo -e "${green}OK${plain}" + mkdir -p ${hid4javaDir}/src/main/resources/linux-armel + cp linux/.libs/libhidapi-hidraw.so ${hid4javaDir}/src/main/resources/linux-armel/libhidapi.so + cp libusb/.libs/libhidapi-libusb.so ${hid4javaDir}/src/main/resources/linux-armel/libhidapi-libusb.so + fi + else + echo -e "${yellow}Skipping linux-armel${plain}" +fi +echo -e "${green}------------------------------------------------------------------------${plain}" + +# RISC-V environments + +# @Tresf +# 64-bit (riscv64) +if [[ "$1" == "all" ]] || [[ "$1" == "linux" ]] || [[ "$1" == "linux-riscv64" ]] + then + echo -e "${green}Building Linux riscv64${plain}" && git-clean + make clean &> /dev/null + + # Disabling building hidtest + sed -i'' -e 's/SUBDIRS \+= hidtest//g' Makefile.am + + # risv64 hasn't reached debian stable, fetch from "sid" + arch=riscv64 + debs=( + "libusb-1.0-0" + "libusb-1.0-0-dev" + "libhidapi-libusb0" + "libudev1" + "libudev-dev" + ) + deps="echo \"Obtaining $arch dependencies from Debian sid...\"" + deps="$deps && echo 'deb [arch=$arch] http://deb.debian.org/debian sid main' | sudo tee -a /etc/apt/sources.list" + deps="$deps && sudo apt-get update" + deps="$deps && mkdir -p debs && pushd debs" + deps="$deps && for deb in "${debs[@]}"; do echo \"- Downloading \$deb...\" && apt-get download \$deb:$arch && ar x \$deb* && tar -xf data.tar.xz && rm -f \$deb*.deb ; done" + deps="$deps && sudo cp -rf ./usr/* /usr/" + deps="$deps && popd" + deps="$deps && rm -rf debs" + deps="$deps && cp /usr/include/libudev.h ./libudev.h" + deps="$deps && export PKG_CONFIG_PATH=/usr/lib/$arch-linux-gnu/pkgconfig/" + + if ! dockcross-linux-riscv64 bash -c "sudo $deps && sudo ./bootstrap && sudo ./configure --host=riscv64-unknown-linux-gnu && sudo make"; + then + echo -e "${red}Failed${plain} - Removing damaged targets" + rm ${hid4javaDir}/src/main/resources/linux-riscv64/libhidapi.so + rm ${hid4javaDir}/src/main/resources/linux-riscv64/libhidapi-libusb.so + else + echo -e "${green}OK${plain}" + mkdir -p ${hid4javaDir}/src/main/resources/linux-riscv64 + cp linux/.libs/libhidapi-hidraw.so ${hid4javaDir}/src/main/resources/linux-riscv64/libhidapi.so + cp libusb/.libs/libhidapi-libusb.so ${hid4javaDir}/src/main/resources/linux-riscv64/libhidapi-libusb.so + fi + else + echo -e "${yellow}Skipping linux-riscv64${plain}" +fi +echo -e "${green}------------------------------------------------------------------------${plain}" + +# macOS environments (require local build) + +# Darwin ARM64 (local) +if [[ "$1" == "all" ]] || [[ "$1" == "darwin" ]] || [[ "$1" == "darwin-aarch64" ]] + then + # Check if build is possible with local environment + if [[ "${hardwareName}" == "x86_64" ]] + then + echo -e "${yellow}Building macOS Darwin x86 (x86-64) requires change of architecture.${plain}" + echo -e "${yellow} Re-run with 'arch -arm64 zsh ./build-hidapi.sh darwin-aarch64'${plain}" + else + echo -e "${green}Building macOS Darwin ARM64 (aarch64)${plain}" && git-clean + ./bootstrap + ./configure + if ! make; + then + echo -e "${red}Failed${plain} - Removing damaged targets" + rm ${hid4javaDir}/src/main/resources/darwin-aarch64/libhidapi.dylib + else + echo -e "${green}OK${plain}" + mkdir -p ${hid4javaDir}/src/main/resources/darwin-aarch64 + cp mac/.libs/libhidapi.0.dylib ${hid4javaDir}/src/main/resources/darwin-aarch64/libhidapi.dylib + fi + fi +fi + +# Darwin Intel (local) +if [[ "$1" == "all" ]] || [[ "$1" == "darwin" ]] || [[ "$1" == "darwin-x86-64" ]] + then + # Check if build is possible with local environment + if [[ "${hardwareName}" == "arm64" ]] + then + echo -e "${yellow}Building macOS Darwin x86 (x86-64) requires change of architecture.${plain}" + echo -e "${yellow} Re-run with 'arch -x86_64 zsh ./build-hidapi.sh darwin-x86-64'${plain}" + else + echo -e "${green}Building macOS Darwin Intel (x86-64)${plain}" && git-clean + make clean + ./bootstrap + ./configure + if ! make; + then + echo -e "${red}Failed${plain} - Removing damaged targets" + rm ${hid4javaDir}/src/main/resources/darwin-x86-64/libhidapi.dylib + else + echo -e "${green}OK${plain}" + mkdir -p ${hid4javaDir}/src/main/resources/darwin-x86-64 + cp mac/.libs/libhidapi.0.dylib ${hid4javaDir}/src/main/resources/darwin-x86-64/libhidapi.dylib + fi + fi + else + echo -e "${yellow}Skipping darwin-x86-64${plain}" +fi + +echo -e "${green}------------------------------------------------------------------------${plain}" + +# Report in hid4java project directory +cd ${hid4javaDir} || exit + +# List all file info +if [[ "$1" == "update" ]] + then + echo -e "${yellow}Skipping file report${plain}" + else + echo -e "${green}Reporting on current hidapi libraries in hid4java:${plain}" + + # Windows environments + echo -e "${green}Windows${plain}" + + echo -e "${green}win32-x86-64${plain}" + report "src/main/resources/win32-x86-64/hidapi.dll" + + echo -e "${green}win32-x86${plain}" + report "src/main/resources/win32-x86/hidapi.dll" + + echo -e "${green}win32-aarch64${plain}" + report "src/main/resources/win32-aarch64/hidapi.dll" + + echo -e "${green}------------------------------------------------------------------------${plain}" + + # Linux environments + echo -e "${green}Linux${plain}" + + echo -e "${green}linux-x86-64${plain}" + report "src/main/resources/linux-x86-64/libhidapi.so" + report "src/main/resources/linux-x86-64/libhidapi-libusb.so" + + echo -e "${green}linux-amd64${plain}" + report "src/main/resources/linux-amd64/libhidapi.so" + report "src/main/resources/linux-amd64/libhidapi-libusb.so" + + echo -e "${green}linux-x86${plain}" + report "src/main/resources/linux-x86/libhidapi.so" + report "src/main/resources/linux-x86/libhidapi-libusb.so" + + echo -e "${green}------------------------------------------------------------------------${plain}" + + # ARM + echo -e "${green}ARM${plain}" + + echo -e "${green}linux-arm${plain}" + report "src/main/resources/linux-arm/libhidapi.so" + report "src/main/resources/linux-arm/libhidapi-libusb.so" + + echo -e "${green}linux-armel${plain}" + report "src/main/resources/linux-armel/libhidapi.so" + report "src/main/resources/linux-armel/libhidapi-libusb.so" + + echo -e "${green}linux-aarch64${plain}" + report "src/main/resources/linux-aarch64/libhidapi.so" + report "src/main/resources/linux-aarch64/libhidapi-libusb.so" + + # RISC + + echo -e "${green}linux-riscv64${plain}" + report "src/main/resources/linux-riscv64/libhidapi.so" + report "src/main/resources/linux-riscv64/libhidapi-libusb.so" + + echo -e "${green}------------------------------------------------------------------------${plain}" + + # macOS + echo -e "${green}macOS${plain}" + + echo -e "${green}darwin-x86-64${plain}" + report "src/main/resources/darwin-x86-64/libhidapi.dylib" + otool -l src/main/resources/darwin-x86-64/libhidapi.dylib | grep -E 'LC_VERSION_MIN_MACOSX|LC_BUILD_VERSION' -A4 + + echo -e "${green}darwin-aarch64${plain}" + report "src/main/resources/darwin-aarch64/libhidapi.dylib" + otool -l src/main/resources/darwin-aarch64/libhidapi.dylib | grep -E 'LC_VERSION_MIN_MACOSX|LC_BUILD_VERSION' -A4 + + echo -e "${green}------------------------------------------------------------------------${plain}" + + echo -e "${green}Done - Check all OK in summary above.${plain}" +fi +echo -e "${green}------------------------------------------------------------------------${plain}" diff --git a/pom.xml b/pom.xml index db45a17..16a534a 100644 --- a/pom.xml +++ b/pom.xml @@ -7,31 +7,22 @@ develop-SNAPSHOT hid4java - A cross-platform Java Native Access (JNA) wrapper for the signal11/hidapi library + A cross-platform Java Native Access (JNA) wrapper for the libusb/hidapi library - http://github.com/gary-rowe/hid4java + https://github.com/gary-rowe/hid4java 2014 - - Bitcoin Solutions Ltd - http://bitcoin-solutions.co.uk - - Gary Rowe - gary.rowe@bitcoin-solutions.co.uk - - - Jim Burton - jim.burton@bitcoin-solutions.co.uk + g.rowe@froot.co.uk MIT - http://www.opensource.org/licenses/mit-license.php + https://www.opensource.org/licenses/mit-license.php repo All source code is under the MIT license. @@ -46,12 +37,12 @@ sonatype-nexus-snapshots Sonatype Nexus Snapshots - http://oss.sonatype.org/content/repositories/snapshots + https://oss.sonatype.org/content/repositories/snapshots sonatype-nexus-staging Nexus Release Repository - http://oss.sonatype.org/service/local/staging/deploy/maven2/ + https://oss.sonatype.org/service/local/staging/deploy/maven2/ https://oss.sonatype.org/content/groups/public/org/hid4java @@ -66,25 +57,23 @@ UTF-8 + + 1.8 + + 1.8 - + release-sign-artifacts - - - performRelease - true - - org.apache.maven.plugins maven-gpg-plugin - 1.4 + 3.2.3 sign-artifacts @@ -103,36 +92,19 @@ - - - org.apache.maven.plugins - maven-compiler-plugin - 3.1 - - 1.6 - 1.6 - true - true - - - + org.apache.maven.plugins maven-surefire-plugin - 2.16 - - - **/*FunctionalTest.java - - + 3.1.2 org.apache.maven.plugins maven-source-plugin - 2.2.1 + 3.3.0 attach-sources @@ -143,16 +115,50 @@ + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.6.3 + + 8 + + + + attach-javadocs + + jar + + + + + org.apache.maven.plugins maven-release-plugin - 2.5.1 + 3.0.1 true forked-path + release-sign-artifacts + + + + org.apache.maven.plugins + maven-jar-plugin + 3.3.0 + + + + true + + + + + @@ -161,8 +167,20 @@ net.java.dev.jna jna - 4.1.0 + + + + [5.8.0,) + + + + org.junit.jupiter + junit-jupiter + 5.10.2 + test + +
diff --git a/release.sh b/release.sh new file mode 100755 index 0000000..11610d2 --- /dev/null +++ b/release.sh @@ -0,0 +1,151 @@ +#!/usr/bin/env bash + +# Work out the appropriate service name from the repo directory +PROJECT_NAME=$(basename `pwd`) + +# Work out the local branch for version tagging +if BRANCH=$(git symbolic-ref --short -q HEAD) +then + echo -e "Releasing \033[32m${PROJECT_NAME}-${BRANCH}\033[0m" +else + echo -e "\033[31mFailed\033[0m - not on any branch.\n" + exit -1 +fi + +# Check local branch for staged files +if git diff-index --quiet HEAD --; then + echo -e "\033[32mOK\033[0m - No staged files awaiting commit." +else + echo -e "\033[31mFailed\033[0m - Your issue branch contains files that are staged and not committed.\n" + exit -1 +fi + +# Check local branch relative to remote +UPSTREAM=${1:-'@{u}'} +LOCAL=$(git rev-parse "@{0}") +REMOTE=$(git rev-parse "$UPSTREAM") +BASE=$(git merge-base "@{0}" "$UPSTREAM") + +if [ ${LOCAL} = ${REMOTE} ]; then + echo -e "\033[32mOK\033[0m - Your branch can be released." +elif [ ${LOCAL} = ${BASE} ]; then + echo -e "\033[31mFailed\033[0m - You need to pull from upstream.\n" + exit -1 +elif [ ${REMOTE} = ${BASE} ]; then + echo -e "\033[31mFailed\033[0m - You need to push to upstream.\n" + exit -1 +else + echo -e "\033[31mFailed\033[0m - Your local branch has diverged from the remote.\n" + exit -1 +fi + +BEHIND_MASTER=$(git rev-list --left-right --count master...@) +BEHIND_DEVELOP=$(git rev-list --left-right --count develop...@) + +# Check issue branch rules +if [[ "$BRANCH" =~ ^issue.* ]]; then + echo -e "\nApplying release rules for 'issue' to 'develop'." + + if [[ "$BEHIND_DEVELOP" =~ ^0 ]]; then + echo -e "\033[32mOK\033[0m - This branch is ahead of 'develop'." + else + echo -e "\033[31mFailed\033[0m - Your issue branch is behind develop. You should rebase and resolve conflicts.\n" + exit -1 + fi + + if grep -s -q ":issue-" "./pom.xml"; then + echo -e "\033[31mFailed\033[0m - The pom.xml contains ':issue-' implying an issue dependency which is not allowed in the develop branch.\n" + exit -1 + else + echo -e "\033[32mOK\033[0m - No 'issue' dependencies in './pom.xml'" + fi + + # Force user to be sure about releasing + read -p "Please enter the project name to confirm the release ($PROJECT_NAME): " userInput + if [[ "$userInput" == "$PROJECT_NAME" ]]; then + echo -e "\033[32mOK\033[0m - Releasing to '$userInput'" + git checkout develop + git merge ${BRANCH} + git push + else + echo -e "\033[31mFailed\033[0m - Project name did not match. Aborting with no changes.\n" + exit -1 + fi +fi + +# Check develop branch rules +if [[ "$BRANCH" =~ ^develop ]]; then + echo -e "\nApplying release rules for 'develop' to a release branch." + + if [[ "$BEHIND_MASTER" =~ ^0 ]]; then + echo -e "\033[32mOK\033[0m - This branch is ahead of 'master'." + else + echo -e "\033[31mFailed\033[0m - Your release branch is behind 'master'. You should rebase and resolve conflicts.\n" + exit -1 + fi + + if grep -s ":.*\-SNAPSHOT" "./pom.xml"; then + echo -e "\033[31mFailed\033[0m - The pom.xml contains '-SNAPSHOT' implying a SNAPSHOT dependency which is not allowed in a release branch.\n" + exit -1 + else + echo -e "\033[32mOK\033[0m - No SNAPSHOT dependencies in './pom.xml'" + fi + + echo -e "Most recent tagged version:\n$(git describe --abbrev=0 --tags)" + + # Force user to be sure about releasing + read -p "Please enter the agreed version number (e.g. 1.2.3) to confirm the release: " userInput + echo -e "\033[32mOK\033[0m - Releasing to '$userInput'" + git branch ${userInput} + git checkout ${userInput} + git merge develop + git push --set-upstream origin ${userInput} + +fi + +# Check release branch rules (0.0.0 format) +if [[ "$BRANCH" =~ ^[0-9] ]]; then + echo -e "\nApplying release rules for release branch to master and develop." + + if [[ "$BEHIND_MASTER" =~ ^0 ]]; then + echo -e "\033[32mOK\033[0m - This branch is ahead of 'master'." + else + echo -e "\033[31mFailed\033[0m - Your release branch is behind master. You should rebase and resolve conflicts.\n" + exit -1 + fi + + if grep -s ":.*\-SNAPSHOT" "./pom.xml"; then + echo -e "\033[31mFailed\033[0m - The pom.xml contains '-SNAPSHOT' implying a SNAPSHOT dependency which is not allowed in a release branch.\n" + exit -1 + else + echo -e "\033[32mOK\033[0m - No SNAPSHOT dependencies in './build.gradle'" + fi + + # Force user to be sure about releasing + read -p "Please enter the project name to confirm the release ($PROJECT_NAME): " userInput + if [[ "$userInput" == "$PROJECT_NAME" ]]; then + echo -e "\033[32mOK\033[0m - Releasing to '$userInput' on 'master'" + git checkout master + git merge ${BRANCH} + # Use prefix to avoid branch naming problems when rebuilding release branches + git tag -a version-${BRANCH} -m "version-${BRANCH}" + git push --follow-tags + fi + + # Check if merge to develop to retrofit fixes can be applied safely + if [[ "$BEHIND_DEVELOP" =~ ^0 ]]; then + echo -e "\033[32mOK\033[0m - This branch is ahead of 'develop'." + echo -e "\033[32mOK\033[0m - Merging ${BRANCH} into 'develop'" + git checkout develop + git merge ${BRANCH} + git push + else + echo -e "\033[33mWarning\033[0m - Your release branch is behind 'develop'. You should resolve conflicts.\n" + git checkout develop + git merge ${BRANCH} + git push + fi + +fi + +echo -e "Done." \ No newline at end of file diff --git a/src/main/java/org/hid4java/HidDevice.java b/src/main/java/org/hid4java/HidDevice.java index a4abc14..6a0328a 100644 --- a/src/main/java/org/hid4java/HidDevice.java +++ b/src/main/java/org/hid4java/HidDevice.java @@ -29,45 +29,69 @@ import org.hid4java.jna.HidDeviceInfoStructure; import org.hid4java.jna.HidDeviceStructure; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Arrays; + /** - *

* High level wrapper to provide the following to API consumers: - *

+ * * * - * @since 0.0.1   + * @since 0.0.1 */ public class HidDevice { private final HidDeviceManager hidDeviceManager; private HidDeviceStructure hidDeviceStructure; - private String path; - private short vendorId; - private short productId; + private final String path; + private final int vendorId; + private final int productId; private String serialNumber; - private int releaseNumber; + private final int releaseNumber; private String manufacturer; private String product; - private int usagePage; - private int usage; - private int interfaceNumber; + private final int usagePage; + private final int usage; + private final int interfaceNumber; + + private final boolean autoDataRead; + private final int dataReadInterval; + + /** + * The data read thread + * We use a Thread instead of Executor since it may be stopped/paused/restarted frequently + * and executors are more heavyweight in this regard + */ + private Thread dataReadThread = null; /** - * @param infoStructure The HID device info structure providing details - * @param hidDeviceManager The HID device manager providing access to device enumeration for post IO scanning + * @param infoStructure The HID device info structure providing details + * @param hidDeviceManager The HID device manager providing access to device enumeration for post IO scanning + * @param hidServicesSpecification The HID services specification providing configuration details + * @since 0.1.0 */ - public HidDevice(HidDeviceInfoStructure infoStructure, HidDeviceManager hidDeviceManager) { + public HidDevice(HidDeviceInfoStructure infoStructure, HidDeviceManager hidDeviceManager, HidServicesSpecification hidServicesSpecification) { this.hidDeviceManager = hidDeviceManager; + this.dataReadInterval = hidServicesSpecification.getDataReadInterval(); + this.autoDataRead = hidServicesSpecification.isAutoDataRead(); + this.hidDeviceStructure = null; this.path = infoStructure.path; - this.vendorId = infoStructure.vendor_id; - this.productId = infoStructure.product_id; + + // Note that the low-level HidDeviceInfoStructure is directly written to by + // the JNA library and implies an unsigned short which is not available in Java. + // The bitmask converts from [-32768, 32767] to [0,65535] + // In Java 8 Short.toUnsignedInt() is available. + this.vendorId = infoStructure.vendor_id & 0xffff; + this.productId = infoStructure.product_id & 0xffff; + this.releaseNumber = infoStructure.release_number; if (infoStructure.serial_number != null) { this.serialNumber = infoStructure.serial_number.toString(); @@ -83,50 +107,177 @@ public HidDevice(HidDeviceInfoStructure infoStructure, HidDeviceManager hidDevic this.interfaceNumber = infoStructure.interface_number; } + /** + * Handles the process of starting the data read thread + */ + private void startDataReadThread() { + + // Check for previous start + if (this.isDataRead()) { + return; + } + + // Perform an immediate data read + dataRead(); + + // Ensure we have a scan thread available + configureDataReadThread(getDataReadRunnable()); + + } + + /** + * Stop the data read thread + */ + private synchronized void stopDataReadThread() { + + if (isDataRead()) { + dataReadThread.interrupt(); + } + + } + + /** + * Configures the data read thread to allow recovery from stop or pause + */ + private synchronized void configureDataReadThread(Runnable dataReadRunnable) { + + if (autoDataRead) { + stopDataReadThread(); + } + + // Require a new one + dataReadThread = new Thread(dataReadRunnable); + dataReadThread.setDaemon(true); + dataReadThread.setName("hid4java data reader"); + dataReadThread.start(); + + } + + private synchronized Runnable getDataReadRunnable() { + + return new Runnable() { + @Override + public void run() { + + while (true) { + try { + //noinspection BusyWait + Thread.sleep(dataReadInterval); + } catch (final InterruptedException e) { + Thread.currentThread().interrupt(); + break; + } + dataRead(); + } + } + }; + + } + + /** + * @return True if the data read thread is running + */ + private boolean isDataRead() { + return dataReadThread != null && dataReadThread.isAlive(); + } + + + /** + * Attempt to read all data from the device input buffer as part + * of the automatic data read process + *
+ * Will fire attach/detach events as appropriate. + */ + private synchronized void dataRead() { + + byte[] dataRead = readAll(100); + + // Fire the event on a separate thread + hidDeviceManager.afterDeviceDataRead(this, dataRead); + + } + /** * The "path" is well-supported across Windows, Mac and Linux so makes a * better choice for a unique ID - * - * See #8 for details + *
+ * See hid4java issue #8 for details * * @return A unique device ID made up from vendor ID, product ID and serial number + * @since 0.1.0 */ public String getId() { return path; } + /** + * @return The device path + * @since 0.1.0 + */ public String getPath() { return path; } - public short getVendorId() { + /** + * @return Int version of vendor ID + * @since 0.1.0 + */ + public int getVendorId() { return vendorId; } - public short getProductId() { + /** + * @return Int version of product ID + * @since 0.1.0 + */ + public int getProductId() { return productId; } + /** + * @return The device serial number + * @since 0.1.0 + */ public String getSerialNumber() { return serialNumber; } + /** + * @return The release number + * @since 0.1.0 + */ public int getReleaseNumber() { return releaseNumber; } + /** + * @return The manufacturer + * @since 0.1.0 + */ public String getManufacturer() { return manufacturer; } + /** + * @return The product + * @since 0.1.0 + */ public String getProduct() { return product; } + /** + * @return The usage page + * @since 0.1.0 + */ public int getUsagePage() { return usagePage; } + /** + * @return The usage information + * @since 0.1.0 + */ public int getUsage() { return usage; } @@ -136,94 +287,174 @@ public int getInterfaceNumber() { } /** - *

Open this device and obtain a device structure

+ * Open this device and obtain a device structure + * * @return True if the device was successfully opened + * @since 0.1.0 */ public boolean open() { hidDeviceStructure = HidApi.open(path); + + // Configure automatic data read + if (autoDataRead) { + startDataReadThread(); + } + return hidDeviceStructure != null; } /** * @return True if the device structure is present + * @since 0.1.0 + * @deprecated Use isClosed() instead of !isOpen() to improve code clarity */ + @Deprecated public boolean isOpen() { - return hidDeviceStructure != null; + return !isClosed(); + } + + /** + * @return True if the device structure is not present (device closed) + * @since 0.8.0 + */ + public boolean isClosed() { + return hidDeviceStructure == null; } /** - *

* Close this device freeing the HidApi resources - *

+ * + * @since 0.1.0 */ public void close() { - if (!isOpen()) { + if (isClosed()) { return; } + + // Prevent further automatic data read attempts + stopDataReadThread(); + + // Close the Hidapi reference HidApi.close(hidDeviceStructure); + + // Ensure structure is removed from memory and prevent further interaction hidDeviceStructure = null; } /** - *

* Set the device handle to be non-blocking - *

- * - *

+ *
* In non-blocking mode calls to hid_read() will return immediately with a * value of 0 if there is no data to be read. In blocking mode, hid_read() * will wait (block) until there is data to read before returning - *

- * - *

+ *
* Non-blocking can be turned on and off at any time - *

* * @param nonBlocking True if non-blocking mode is required + * @since 0.1.0 */ public void setNonBlocking(boolean nonBlocking) { - if (!isOpen()) { + if (isClosed()) { throw new IllegalStateException("Device has not been opened"); } HidApi.setNonBlocking(hidDeviceStructure, nonBlocking); } /** - *

* Read an Input report from a HID device - *

- *

+ *
* Input reports are returned to the host through the INTERRUPT IN endpoint. * The first byte will contain the Report number if the device uses numbered * reports - *

* * @param data The buffer to read into - * * @return The actual number of bytes read and -1 on error. If no packet was * available to be read and the handle is in non-blocking mode, this * function returns 0. + * @since 0.1.0 */ public int read(byte[] data) { - if (!isOpen()) { + if (isClosed()) { throw new IllegalStateException("Device has not been opened"); } return HidApi.read(hidDeviceStructure, data); } /** - *

+ * Read an Input report from a HID device + *
+ * Input reports are returned to the host through the INTERRUPT IN endpoint. + * The first byte will contain the Report number if the device uses numbered + * reports + * + * @param amountToRead the number of bytes to read + * @param timeoutMillis The number of milliseconds to wait before giving up + * @return a Byte array of the read data + * @since 0.1.0 + */ + public Byte[] read(int amountToRead, int timeoutMillis) { + if (isClosed()) { + throw new IllegalStateException("Device has not been opened"); + } + + byte[] bytes = new byte[amountToRead]; + int read = HidApi.read(hidDeviceStructure, bytes, timeoutMillis); + Byte[] retData = new Byte[read]; + for (int i = 0; i < read; i++) { + retData[i] = bytes[i]; + } + return retData; + } + + /** + * Read an Input report from a HID device + * Input reports are returned to the host through the INTERRUPT IN endpoint. + * The first byte will contain the Report number if the device uses numbered + * reports + * + * @param amountToRead the number of bytes to read. + * @return a Byte array of the read data + * @since 0.1.0 + */ + public Byte[] read(int amountToRead) { + if (isClosed()) { + throw new IllegalStateException("Device has not been opened"); + } + + byte[] bytes = new byte[amountToRead]; + int read = HidApi.read(hidDeviceStructure, bytes); + Byte[] retData = new Byte[read]; + for (int i = 0; i < read; i++) { + retData[i] = bytes[i]; + } + return retData; + } + + /** + * Read an Input report (64 bytes) from a HID device with a 1000ms timeout. + *
+ * Input reports are returned to the host through the INTERRUPT IN endpoint. + * The first byte will contain the Report number if the device uses numbered + * reports. + * + * @return A Byte array of the read data + * @since 0.1.0 + */ + public Byte[] read() { + return read(64, 1000); + } + + /** * Read an Input report from a HID device with timeout - *

* * @param bytes The buffer to read into * @param timeoutMillis The number of milliseconds to wait before giving up - * * @return The actual number of bytes read and -1 on error. If no packet was * available to be read within the timeout period returns 0. + * @since 0.1.0 */ public int read(byte[] bytes, int timeoutMillis) { - if (!isOpen()) { + if (isClosed()) { throw new IllegalStateException("Device has not been opened"); } return HidApi.read(hidDeviceStructure, bytes, timeoutMillis); @@ -231,92 +462,181 @@ public int read(byte[] bytes, int timeoutMillis) { } /** - *

+ * Read an Input report from a HID device with timeout + * + * @param timeoutMillis The number of milliseconds to wait before giving up + * @return A byte[] of the read data + * @since 0.8.0 + */ + public byte[] readAll(int timeoutMillis) { + if (isClosed()) { + throw new IllegalStateException("Device has not been opened"); + } + + // Overall data storage + ByteArrayOutputStream output = new ByteArrayOutputStream(); + + // Prepare to read a single HID packet + boolean morePackets = true; + while (morePackets) { + byte[] packet = new byte[64]; + + // This method will block while awaiting data + int bytesRead = read(packet, timeoutMillis); + + if (bytesRead > 0) { + try { + output.write(packet); + } catch (IOException e) { + morePackets = false; + } + } else { + morePackets = false; + } + } + + return output.toByteArray(); + } + + + /** * Get a feature report from a HID device - *

- *

* Under the covers the HID library will set the first byte of data[] to the * Report ID of the report to be read. Upon return, the first byte will * still contain the Report ID, and the report data will start in data[1] - *

- *

+ *
* This method handles all the wide string and array manipulation for you - *

* * @param data The buffer to contain the report * @param reportId The report ID (or (byte) 0x00) - * * @return The number of bytes read plus one for the report ID (which has * been removed from the first byte), or -1 on error. + * @since 0.1.0 */ public int getFeatureReport(byte[] data, byte reportId) { - if (!isOpen()) { + if (isClosed()) { throw new IllegalStateException("Device has not been opened"); } return HidApi.getFeatureReport(hidDeviceStructure, data, reportId); } /** - *

* Send a Feature report to the device - *

- * - *

+ *
* Under the covers, feature reports are sent over the Control endpoint as a * Set_Report transfer. The first byte of data[] must contain the Report ID. * For devices which only support a single report, this must be set to 0x0. * The remaining bytes contain the report data - *

- *

+ *
* Since the Report ID is mandatory, calls to hid_send_feature_report() will * always contain one more byte than the report contains. For example, if a * hid report is 16 bytes long, 17 bytes must be passed to * hid_send_feature_report(): the Report ID (or 0x0, for devices which do * not use numbered reports), followed by the report data (16 bytes). In * this example, the length passed in would be 17 - *

- * - *

+ *
* This method handles all the array manipulation for you - *

* * @param data The feature report data (will be widened and have the report * ID pre-pended) * @param reportId The report ID (or (byte) 0x00) - * * @return This function returns the actual number of bytes written and -1 * on error. + * @since 0.1.0 */ public int sendFeatureReport(byte[] data, byte reportId) { - if (!isOpen()) { + if (isClosed()) { throw new IllegalStateException("Device has not been opened"); } return HidApi.sendFeatureReport(hidDeviceStructure, data, reportId); } /** - *

* Get a string from a HID device, based on its string index - *

* * @param index The index - * * @return The string + * @since 0.1.0 */ public String getIndexedString(int index) { + if (isClosed()) { + throw new IllegalStateException("Device has not been opened"); + } return HidApi.getIndexedString(hidDeviceStructure, index); } + /** + * Get a report descriptor from a HID device + *
+ * A report descriptor provides significant detail on the characteristics of + * an attached device using a defined format. + *
+ * You may find these supporting documents helpful: + * HID Usage Tables 1.5 (PDF) + *
+ * Device Class Definition HID 1.11 (PDF) + * + * @param buffer The buffer for descriptor (4096 bytes recommended). + * @return A non-negative number of bytes actually copied, or -1 on error. + * @since 0.14.0 hidapi + */ + public int getReportDescriptor(byte[] buffer) { + if (isClosed()) { + throw new IllegalStateException("Device has not been opened"); + } + return HidApi.getReportDescriptor(hidDeviceStructure, buffer, buffer.length); + } + + /** + * Write the message to the HID API without zero byte padding. + *
+ * Note that the report ID will be prefixed to the HID packet as per HID rules. + * + * @param message The message + * @param packetLength The packet length + * @param reportId The report ID (will be prefixed to the HID packet) + * @return The number of bytes written (including report ID), or -1 if an error occurs + * @since 0.1.0 + */ public int write(byte[] message, int packetLength, byte reportId) { - if (!isOpen()) { + if (isClosed()) { + throw new IllegalStateException("Device has not been opened"); + } + return write(message, packetLength, reportId, false); + } + + /** + * Write the message to the HID API with optional zero byte padding to packet length. + *
+ * Note that the report ID will be prefixed to the HID packet as per HID rules. + * + * @param message The message + * @param packetLength The packet length + * @param reportId The report ID + * @param applyPadding True if the message should be filled with zero bytes to the packet length + * @return The number of bytes written (including report ID), or -1 if an error occurs + * @since 0.8.0 + */ + public int write(byte[] message, int packetLength, byte reportId, boolean applyPadding) { + if (isClosed()) { throw new IllegalStateException("Device has not been opened"); } + + if (applyPadding) { + message = Arrays.copyOf(message, packetLength + 1); + } + int result = HidApi.write(hidDeviceStructure, message, packetLength, reportId); // Update HID manager hidDeviceManager.afterDeviceWrite(); return result; + } + /** + * @return The last error message from HID API + * @since 0.1.0 + */ public String getLastErrorMessage() { return HidApi.getLastErrorMessage(hidDeviceStructure); } @@ -325,13 +645,17 @@ public String getLastErrorMessage() { * @param vendorId The vendor ID * @param productId The product ID * @param serialNumber The serial number - * - * @return True if the device matches the given the combination + * @return True if the device matches the given the combination with vendorId, productId being zero acting as a wildcard + * @since 0.1.0 */ public boolean isVidPidSerial(int vendorId, int productId, String serialNumber) { - return (vendorId == 0 || this.vendorId == vendorId) - && (productId == 0 || this.productId == productId) - && (serialNumber == null || this.serialNumber.equals(serialNumber)); + if (serialNumber == null) + return (vendorId == 0 || this.vendorId == vendorId) + && (productId == 0 || this.productId == productId); + else + return (vendorId == 0 || this.vendorId == vendorId) + && (productId == 0 || this.productId == productId) + && (this.serialNumber.equals(serialNumber)); } @Override diff --git a/src/main/java/org/hid4java/HidDeviceManager.java b/src/main/java/org/hid4java/HidDeviceManager.java index 1452c22..e835f4d 100644 --- a/src/main/java/org/hid4java/HidDeviceManager.java +++ b/src/main/java/org/hid4java/HidDeviceManager.java @@ -32,14 +32,14 @@ import java.util.*; /** - *

Manager to provide the following to HID services:

+ * Manager to provide the following to HID services: * * * @since 0.0.1 - *   */ class HidDeviceManager { @@ -60,7 +60,7 @@ class HidDeviceManager { /** * The device enumeration thread - * + *
* We use a Thread instead of Executor since it may be stopped/paused/restarted frequently * and executors are more heavyweight in this regard */ @@ -91,10 +91,10 @@ class HidDeviceManager { /** * Starts the manager - * + *
* If already started (scanning) it will immediately return without doing anything - * - * Otherwise this will perform a one-off scan of all devices then if the scan interval + *
+ * Otherwise, this will perform a one-off scan of all devices then if the scan interval * is zero will stop there or will start the scanning daemon thread at the required interval. * * @throws HidException If something goes wrong (such as Hidapi not initialising correctly) @@ -115,25 +115,34 @@ public void start() { } /** - * Stop the scan executor and block until terminated (max 5 seconds) + * Stop the scan thread and close all attached devices + *
+ * This is normally part of a general application shutdown and will + * also clear the attached devices map */ public synchronized void stop() { - if (isScanning()) { - scanThread.interrupt(); + stopScanThread(); + + // Close all attached devices + for (HidDevice hidDevice: attachedDevices.values()) { + hidDevice.close(); } + // Remove all entries from the attached devices + attachedDevices.clear(); + } /** * Updates the device list by adding newly connected devices to it and by * removing no longer connected devices. - * + *
* Will fire attach/detach events as appropriate. */ public synchronized void scan() { - List removeList = new ArrayList(); + List removeList = new ArrayList<>(); List attachedHidDeviceList = getAttachedHidDevices(); @@ -185,7 +194,7 @@ public boolean isScanning() { */ public List getAttachedHidDevices() { - List hidDeviceList = new ArrayList(); + List hidDeviceList = new ArrayList<>(); final HidDeviceInfoStructure root; try { @@ -194,7 +203,7 @@ public List getAttachedHidDevices() { root = HidApi.enumerateDevices(0, 0); } catch (Throwable e) { // Could not initialise hidapi (possibly an unknown platform) - // Prevent further scanning as a fail safe + // Trigger a general stop as something serious has happened stop(); // Inform the caller that something serious has gone wrong throw new HidException("Unable to start HidApi: " + e.getMessage()); @@ -205,7 +214,10 @@ public List getAttachedHidDevices() { HidDeviceInfoStructure hidDeviceInfoStructure = root; do { // Wrap in HidDevice - hidDeviceList.add(new HidDevice(hidDeviceInfoStructure, this)); + hidDeviceList.add(new HidDevice( + hidDeviceInfoStructure, + this, + hidServicesSpecification)); // Move to the next in the linked list hidDeviceInfoStructure = hidDeviceInfoStructure.next(); } while (hidDeviceInfoStructure != null); @@ -223,7 +235,7 @@ public List getAttachedHidDevices() { public void afterDeviceWrite() { if (ScanMode.SCAN_AT_FIXED_INTERVAL_WITH_PAUSE_AFTER_WRITE == hidServicesSpecification.getScanMode() && isScanning()) { - stop(); + stopScanThread(); // Ensure we have a new scan executor service available configureScanThread(getScanRunnable()); @@ -232,18 +244,52 @@ public void afterDeviceWrite() { } /** - * Configures the scan executor service to allow recovery from stop or pause + * Indicate that an automatic data read has occurred which may require an event to be fired + * + * @param hidDevice The device that has received data + * @param dataReceived The data received + * @since 0.8.0 + */ + public void afterDeviceDataRead(HidDevice hidDevice, byte[] dataReceived) { + + if (dataReceived != null && dataReceived.length > 0) { + this.listenerList.fireHidDataReceived(hidDevice, dataReceived); + } + + } + + /** + * Stop the scan thread + */ + private synchronized void stopScanThread() { + + if (isScanning()) { + scanThread.interrupt(); + // Wait up to 50ms for scanThread to terminate to avoid + // spurious return values from isScanning() + // See hid4java issue #125 + try { + scanThread.join(50); + } catch (InterruptedException e) { + // Ignore and continue + } + } + + } + + /** + * Configures the scan thread to allow recovery from stop or pause */ private synchronized void configureScanThread(Runnable scanRunnable) { if (isScanning()) { - stop(); + stopScanThread(); } // Require a new one scanThread = new Thread(scanRunnable); scanThread.setDaemon(true); - scanThread.setName("hid4java Device Scanner"); + scanThread.setName("hid4java device scanner"); scanThread.start(); } @@ -268,6 +314,7 @@ public void run() { while (true) { try { + //noinspection BusyWait Thread.sleep(scanInterval); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); @@ -291,6 +338,7 @@ public void run() { // Switch to continuous running while (true) { try { + //noinspection BusyWait Thread.sleep(scanInterval); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); @@ -307,4 +355,4 @@ public void run() { } -} \ No newline at end of file +} diff --git a/src/main/java/org/hid4java/HidException.java b/src/main/java/org/hid4java/HidException.java index d4dadef..77977ce 100644 --- a/src/main/java/org/hid4java/HidException.java +++ b/src/main/java/org/hid4java/HidException.java @@ -26,13 +26,12 @@ package org.hid4java; /** - *

Caught exception to provide the following to API consumers:

+ * Caught exception to provide the following to API consumers: *
    *
  • Notification of a serious problem with HID
  • *
* * @since 0.0.1 - *   */ public class HidException extends RuntimeException { diff --git a/src/main/java/org/hid4java/HidManager.java b/src/main/java/org/hid4java/HidManager.java index 2d4b343..e6cb0c9 100644 --- a/src/main/java/org/hid4java/HidManager.java +++ b/src/main/java/org/hid4java/HidManager.java @@ -26,13 +26,12 @@ package org.hid4java; /** - *

Factory to provide the following to API consumers:

+ * Factory to provide the following to API consumers: *
    *
  • Access to configured HID services
  • *
* * @since 0.0.1 - *   */ public class HidManager { @@ -41,8 +40,8 @@ public class HidManager { private static HidServices hidServices = null; /** - *

Simple service provider providing generally safe defaults. If you find you are experiencing problems, particularly - * with constrained devices, consider exploring the {@link HidServicesSpecification} options.

+ * Simple service provider providing generally safe defaults. If you find you are experiencing problems, particularly + * with constrained devices, consider exploring the {@link HidServicesSpecification} options. * * @return A single instance of the HID services using the default specification */ @@ -60,12 +59,10 @@ public static HidServices getHidServices() throws HidException { } /** - *

Fully configurable service provider

+ * Fully configurable service provider * * @param hidServicesSpecification Provides various parameters for configuring HID services - * * @return A single instance of the HID services using specified parameters - * * @since 0.5.0 */ public static HidServices getHidServices(HidServicesSpecification hidServicesSpecification) throws HidException { diff --git a/src/main/java/org/hid4java/HidServices.java b/src/main/java/org/hid4java/HidServices.java index 9901e8a..10eb595 100644 --- a/src/main/java/org/hid4java/HidServices.java +++ b/src/main/java/org/hid4java/HidServices.java @@ -28,17 +28,20 @@ import org.hid4java.event.HidServicesListenerList; import org.hid4java.jna.HidApi; +import java.io.IOException; +import java.net.URL; import java.util.List; +import java.util.jar.Attributes; +import java.util.jar.Manifest; /** - *

JNA bridge class to provide the following to USB HID:

+ * JNA bridge class to provide the following to USB HID: *
    *
  • Access to the signal11/hidapi via JNA
  • *
- *

Requires the hidapi to be present on the classpath or the system library search path.

+ * Requires the hidapi to be present on the classpath or the system library search path. * * @since 0.0.1 - *   */ public class HidServices { @@ -52,6 +55,15 @@ public class HidServices { */ private final HidDeviceManager hidDeviceManager; + /** + * Jar entry point to allow for version interrogation + * + * @param args Nothing required + */ + public static void main(String[] args) { + System.out.println("Version: " + getVersion()); + } + /** * Initialise with a default HID specification * @@ -63,12 +75,17 @@ public HidServices() throws HidException { /** * @param hidServicesSpecification Provides various parameters for configuring HID services - * * @throws HidException If something goes wrong (see {@link HidDeviceManager#HidDeviceManager(HidServicesListenerList, HidServicesSpecification)} */ public HidServices(HidServicesSpecification hidServicesSpecification) { hidDeviceManager = new HidDeviceManager(listeners, hidServicesSpecification); - hidDeviceManager.start(); + + // Check for automatic start (default behaviour for 0.6.0 and below) + // which will prevent an attachment event firing if the device is already + // attached since listeners will not have been registered at this point + if (hidServicesSpecification.isAutoStart()) { + hidDeviceManager.start(); + } if (hidServicesSpecification.isAutoShutdown()) { // Ensure we release resources during shutdown @@ -84,7 +101,7 @@ public void run() { } /** - * Stop scanning for devices and shut down the {@link HidApi} + * Stop all device threads and shut down the {@link HidApi} */ public void shutdown() { stop(); @@ -96,14 +113,18 @@ public void shutdown() { } /** - * Stop scanning for devices + * Stop all threads (enumeration, data read etc), close all devices + * and clear all listeners + * + * Normally part of an application shutdown */ public void stop() { hidDeviceManager.stop(); + this.listeners.clear(); } /** - * Start scanning for devices (if not already scanning) + * Start all threads (enumeration, data read etc) as configured */ public void start() { hidDeviceManager.start(); @@ -119,7 +140,7 @@ public void addHidServicesListener(final HidServicesListener listener) { /** * @param listener The listener to remove */ - public void removeUsbServicesListener(final HidServicesListener listener) { + public void removeHidServicesListener(final HidServicesListener listener) { this.listeners.remove(listener); } @@ -141,7 +162,6 @@ public List getAttachedHidDevices() { * @param vendorId The vendor ID * @param productId The product ID * @param serialNumber The serial number (use null for wildcard) - * * @return The device if attached, null if detached */ public HidDevice getHidDevice(int vendorId, int productId, String serialNumber) { @@ -149,14 +169,49 @@ public HidDevice getHidDevice(int vendorId, int productId, String serialNumber) List devices = hidDeviceManager.getAttachedHidDevices(); for (HidDevice device : devices) { if (device.isVidPidSerial(vendorId, productId, serialNumber)) { - if (device.open()) { - return device; - } else { - return null; - } + device.open(); + return device; } } return null; } -} \ No newline at end of file + + /** + * @return The current library version from the manifest or 0.0.x if an error occurs + */ + public static String getVersion() { + + Class clazz = HidServices.class; + String className = clazz.getSimpleName() + ".class"; + String classPath = clazz.getResource(className).toString(); + if (!classPath.startsWith("jar")) { + // Class not from JAR + return "0.0.1"; + } + String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + + "/META-INF/MANIFEST.MF"; + Manifest manifest; + try { + manifest = new Manifest(new URL(manifestPath).openStream()); + } catch (IOException e) { + return "0.0.2"; + } + Attributes attr = manifest.getMainAttributes(); + String value = attr.getValue("Implementation-Version"); + if (null == value) { + return "0.0.3"; + } else { + return value; + } + } + + /** + * Returns the full version of the underlying hidapi library + * + * @return The version in major.minor.patch format + */ + public static String getNativeVersion() { + return HidApi.getVersion(); + } +} diff --git a/src/main/java/org/hid4java/HidServicesListener.java b/src/main/java/org/hid4java/HidServicesListener.java index 04c94c8..abef1dc 100644 --- a/src/main/java/org/hid4java/HidServicesListener.java +++ b/src/main/java/org/hid4java/HidServicesListener.java @@ -30,34 +30,40 @@ import java.util.EventListener; /** - *

Interface to provide the following to API consumers:

+ * Interface to provide the following to API consumers: *
    *
  • Notification of a HID event
  • *
* * @since 0.0.1 - *   */ public interface HidServicesListener extends EventListener { /** - * A HID device was attached + * A HID was attached * * @param event The event */ void hidDeviceAttached(HidServicesEvent event); /** - * A HID device was detached + * A HID was detached * * @param event The event */ void hidDeviceDetached(HidServicesEvent event); /** - * A HID failure occurred during scanning + * A HID failure occurred (enumeration, data transfer etc) * * @param event The event */ void hidFailure(HidServicesEvent event); + /** + * A HID input data buffer was populated + * + * @param event The event + */ + void hidDataReceived(HidServicesEvent event); + } \ No newline at end of file diff --git a/src/main/java/org/hid4java/HidServicesSpecification.java b/src/main/java/org/hid4java/HidServicesSpecification.java index 7b29129..1a13068 100644 --- a/src/main/java/org/hid4java/HidServicesSpecification.java +++ b/src/main/java/org/hid4java/HidServicesSpecification.java @@ -26,13 +26,12 @@ package org.hid4java; /** - *

Specification to provide the following to API consumers:

+ * Specification to provide the following to API consumers: *
    *
  • Flexible configuration of HID services parameters
  • *
* * @since 0.5.0 - *   */ public class HidServicesSpecification { @@ -40,6 +39,9 @@ public class HidServicesSpecification { private boolean autoShutdown = true; private int scanInterval = 500; private int pauseInterval = 5000; + private boolean autoStart = true; + private boolean autoDataRead = false; + private int dataReadInterval = 500; public ScanMode getScanMode() { return scanMode; @@ -94,4 +96,40 @@ public boolean isAutoShutdown() { public void setAutoShutdown(boolean autoShutdown) { this.autoShutdown = autoShutdown; } + + + public boolean isAutoStart() { + return autoStart; + } + + /** + * @param autoStart True if the HidServices should start before any listeners are registered (default is backwards compatible to 0.6.0 and below) + */ + public void setAutoStart(boolean autoStart) { + this.autoStart = autoStart; + } + + public boolean isAutoDataRead() { + return autoDataRead; + } + + /** + * @param autoDataRead True if device input buffer should be automatically checked and read + * @since 0.8.0 + */ + public void setAutoDataRead(boolean autoDataRead) { + this.autoDataRead = autoDataRead; + } + + public int getDataReadInterval() { + return dataReadInterval; + } + + /** + * + * @param dataReadInterval The interval in milliseconds between attempts to read device input buffer + */ + public void setDataReadInterval(int dataReadInterval) { + this.dataReadInterval = dataReadInterval; + } } diff --git a/src/main/java/org/hid4java/event/HidServicesEvent.java b/src/main/java/org/hid4java/event/HidServicesEvent.java index 6128a15..a10f974 100644 --- a/src/main/java/org/hid4java/event/HidServicesEvent.java +++ b/src/main/java/org/hid4java/event/HidServicesEvent.java @@ -27,25 +27,38 @@ import org.hid4java.HidDevice; +import java.util.Arrays; + /** - *

Event to provide the following to API consumers:

+ * Event to provide the following to API consumers: *
    *
  • Provision of HID device information
  • *
* * @since 0.0.1 - *   */ public class HidServicesEvent { private final HidDevice hidDevice; + private final byte[] dataReceived; /** * @param device The HidDevice involved in the event */ public HidServicesEvent(HidDevice device) { hidDevice = device; + dataReceived = null; + } + + /** + * @param device The HidDevice involved in the event + * @param dataReceived The contents of all data read + * @since 0.8.0 + */ + public HidServicesEvent(HidDevice device, byte[] dataReceived) { + hidDevice = device; + this.dataReceived = Arrays.copyOf(dataReceived, dataReceived.length); } /** @@ -55,6 +68,13 @@ public HidDevice getHidDevice() { return hidDevice; } + /** + * @return The data received (might be multiple packets of data) + */ + public byte[] getDataReceived() { + return dataReceived; + } + @Override public String toString() { return "HidServicesEvent{" + diff --git a/src/main/java/org/hid4java/event/HidServicesListenerList.java b/src/main/java/org/hid4java/event/HidServicesListenerList.java index 48d83c4..bc8433b 100644 --- a/src/main/java/org/hid4java/event/HidServicesListenerList.java +++ b/src/main/java/org/hid4java/event/HidServicesListenerList.java @@ -36,10 +36,9 @@ import java.util.concurrent.ThreadFactory; /** - *

HID services listener list

+ * HID services listener list * * @since 0.0.1 - *   */ public class HidServicesListenerList { @@ -97,11 +96,11 @@ protected final List getListeners() { * @return Array with registered listeners. */ public HidServicesListener[] toArray() { - return getListeners().toArray(new HidServicesListener[getListeners().size()]); + return getListeners().toArray(new HidServicesListener[0]); } /** - *

Fire the HID device attached event

+ * Fire the HID device attached event * * @param hidDevice The device that was attached */ @@ -125,7 +124,7 @@ public void run() { } /** - *

Fire the HID device detached event

+ * Fire the HID device detached event * * @param hidDevice The device that was detached */ @@ -149,7 +148,7 @@ public void run() { } /** - *

Fire the HID failure event

+ * Fire the HID failure event * * @param hidDevice The device that caused the error if known */ @@ -171,5 +170,31 @@ public void run() { }); } + + /** + * Fire the HID data received event + * + * @param hidDevice The device that triggered the data input + * @param dataReceived The buffer with the data received + */ + public void fireHidDataReceived(final HidDevice hidDevice, final byte[] dataReceived) { + + // Broadcast on a different thread + executorService.submit( + new Runnable() { + @Override + public void run() { + + HidServicesEvent event = new HidServicesEvent(hidDevice, dataReceived); + + for (final HidServicesListener listener : toArray()) { + listener.hidDataReceived(event); + } + + } + }); + + } + } diff --git a/src/main/java/org/hid4java/jna/DarwinHidApiLibrary.java b/src/main/java/org/hid4java/jna/DarwinHidApiLibrary.java new file mode 100644 index 0000000..7998fc1 --- /dev/null +++ b/src/main/java/org/hid4java/jna/DarwinHidApiLibrary.java @@ -0,0 +1,24 @@ +package org.hid4java.jna; + +import com.sun.jna.Native; +import com.sun.jna.WString; + +public interface DarwinHidApiLibrary extends HidrawHidApiLibrary { + + DarwinHidApiLibrary INSTANCE = Native.load("hidapi", DarwinHidApiLibrary.class); + + /** + * Changes the behavior of all further calls to {@link #hid_open(short, short, WString)} or {@link #hid_open_path(String)}. + *
+ * All devices opened by HIDAPI with {@link #hid_open(short, short, WString)} or {@link #hid_open_path(String)} + * are opened in exclusive mode per default. + *
+ * Calling this function before {@link #hid_init()} or after {@link #hid_exit()} has no effect. + * + * @since hidapi 0.12.0 + * @param openExclusive When set to 0 - all further devices will be opened in non-exclusive mode. + * Otherwise - all further devices will be opened in exclusive mode. + */ + void hid_darwin_set_open_exclusive(int openExclusive); + +} diff --git a/src/main/java/org/hid4java/jna/HidApi.java b/src/main/java/org/hid4java/jna/HidApi.java index fd822c0..d950e8e 100644 --- a/src/main/java/org/hid4java/jna/HidApi.java +++ b/src/main/java/org/hid4java/jna/HidApi.java @@ -30,20 +30,19 @@ import com.sun.jna.WString; /** - *

JNA utility class to provide the following to low level operations:

+ * JNA utility class to provide the following to low level operations: *
    *
  • Direct access to the HID API library through JNA
  • *
* * @since 0.0.1 - *   */ public class HidApi { /** * Default length for wide string buffer */ - private static int WSTR_LEN = 512; + private static final int WSTR_LEN = 512; /** * Error message if device is not initialised @@ -56,46 +55,41 @@ public class HidApi { private static final int DEVICE_ERROR = -2; /** - * The HID API library + * Enables use of the libusb variant of the hidapi native library when running on a Linux platform. + *
+ * The default is hidraw which enables Bluetooth devices but requires udev rules. */ - private static final HidApiLibrary hidApiLibrary = HidApiLibrary.INSTANCE; + public static boolean useLibUsbVariant = false; /** - *

True if the report ID should be dropped from the write buffer - * Normally this should be false but on Windows 8, 10 it appears to be - * necessary when the device only has a single report available.

- * - *

After this class has initialised this value can be modified at - * any time if you find that you do need the report ID to be included.

- * - *

See https://github.com/gary-rowe/hid4java/issues/36 for more information.

+ * When false - all devices will be opened in exclusive mode. (Default) + * When true - all devices will be opened in non-exclusive mode. + *
+ * See {@link DarwinHidApiLibrary#hid_darwin_set_open_exclusive(int)} for more information. */ - public static boolean dropReportIdZero = false; - - static { - - // Determine a suitable starting value for the drop report ID flag - // so that downstream code can expect the same behaviour as in earlier - // versions by default, with a bug fix for Windows 7 - if (Platform.isWindows()) { - // Report ID 0x00 problems have been seen on Windows 8, 10 only so far - String osVersion = System.getProperty("os.version"); - if ("6.2".equals(osVersion) || - "6.3".equals(osVersion)) { - // Windows 8, 10 - dropReportIdZero = true; - } - } + public static boolean darwinOpenDevicesNonExclusive = false; - } + /** + * Enables HID traffic logging to stdout to assist debugging. This will show all bytes (including the extra report ID) + * that were sent or received via HIDAPI buffers. It does not log direct string calls (e.g. getEnumeratedString()). + *
+ * Format is '>' for host to device then '[count]' then hex bytes. + *
+ * This may present a security issue if left enabled in production, although a packet sniffer would see the same data. + */ + public static boolean logTraffic = false; /** - *

Open a HID device using a Vendor ID (VID), Product ID (PID) and optionally a serial number

+ * The HID API library + */ + private static HidApiLibrary hidApiLibrary; + + /** + * Open a HID device using a Vendor ID (VID), Product ID (PID) and optionally a serial number * * @param vendor The vendor ID * @param product The product ID * @param serialNumber The serial number - * * @return The device or null if not found */ public static HidDeviceStructure open(int vendor, int product, String serialNumber) { @@ -117,26 +111,36 @@ public static HidDeviceStructure open(int vendor, int product, String serialNumb } /** - *

Initialise the HID API library

- *

Required if the consuming application is using multiple threads - * containing device handles.

+ * Initialise the HID API library. Should always be called before using any other API calls. */ public static void init() { + + if (useLibUsbVariant && Platform.isLinux()) { + hidApiLibrary = LibusbHidApiLibrary.INSTANCE; + } else if (Platform.isMac()) { + hidApiLibrary = DarwinHidApiLibrary.INSTANCE; + } else { + hidApiLibrary = HidrawHidApiLibrary.INSTANCE; + } + hidApiLibrary.hid_init(); + + if (hidApiLibrary instanceof DarwinHidApiLibrary) { + ((DarwinHidApiLibrary) hidApiLibrary).hid_darwin_set_open_exclusive(darwinOpenDevicesNonExclusive ? 0 : 1); + } } /** - *

Finalise the HID API library

+ * Finalise the HID API library */ public static void exit() { hidApiLibrary.hid_exit(); } /** - *

Open a HID device by its path name

+ * Open a HID device by its path name * * @param path The device path (e.g. "0003:0002:00") - * * @return The device or null if not found */ public static HidDeviceStructure open(String path) { @@ -145,7 +149,9 @@ public static HidDeviceStructure open(String path) { } /** - *

Close a HID device

+ * Close a HID device + * + * @param device The HID device structure */ public static void close(HidDeviceStructure device) { @@ -156,11 +162,10 @@ public static void close(HidDeviceStructure device) { } /** - *

Enumerate the attached HID devices

+ * Enumerate the attached HID devices * * @param vendor The vendor ID * @param product The product ID - * * @return The device info of the matching device */ public static HidDeviceInfoStructure enumerateDevices(int vendor, int product) { @@ -170,7 +175,7 @@ public static HidDeviceInfoStructure enumerateDevices(int vendor, int product) { } /** - *

Free an enumeration linked list

+ * Free an enumeration linked list * * @param list The list to free */ @@ -181,6 +186,7 @@ public static void freeEnumeration(HidDeviceInfoStructure list) { } /** + * @param device The HID device structure * @return A string describing the last error which occurred */ public static String getLastErrorMessage(HidDeviceStructure device) { @@ -196,7 +202,6 @@ public static String getLastErrorMessage(HidDeviceStructure device) { /** * @param device The HID device - * * @return The device manufacturer string */ public static String getManufacturer(HidDeviceStructure device) { @@ -213,7 +218,6 @@ public static String getManufacturer(HidDeviceStructure device) { /** * @param device The HID device - * * @return The device product ID */ public static String getProductId(HidDeviceStructure device) { @@ -230,7 +234,6 @@ public static String getProductId(HidDeviceStructure device) { /** * @param device The HID device - * * @return The device serial number */ public static String getSerialNumber(HidDeviceStructure device) { @@ -247,16 +250,15 @@ public static String getSerialNumber(HidDeviceStructure device) { } /** - *

Set the device handle to be non-blocking

- * - *

In non-blocking mode calls to hid_read() will return immediately with a value of 0 if there is no data to be read. - * In blocking mode, hid_read() will wait (block) until there is data to read before returning

- * - *

Non-blocking can be turned on and off at any time

+ * Set the device handle to be non-blocking + *
+ * In non-blocking mode calls to hid_read() will return immediately with a value of 0 if there is no data to be read. + * In blocking mode, hid_read() will wait (block) until there is data to read before returning + *
+ * Non-blocking can be turned on and off at any time * * @param device The HID device * @param nonBlocking True if non-blocking mode is required - * * @return True if successful */ public static boolean setNonBlocking(HidDeviceStructure device, boolean nonBlocking) { @@ -266,13 +268,12 @@ public static boolean setNonBlocking(HidDeviceStructure device, boolean nonBlock } /** - *

Read an Input report from a HID device

- *

Input reports are returned to the host through the INTERRUPT IN endpoint. The first byte - * will contain the Report ID if the device uses numbered reports.

+ * Read an Input report from a HID device + * Input reports are returned to the host through the INTERRUPT IN endpoint. The first byte + * will contain the Report ID if the device uses numbered reports. * * @param device The HID device * @param buffer The buffer to read into (allow an extra byte if device supports multiple report IDs) - * * @return The actual number of bytes read and -1 on error. If no packet was available to be read * and the handle is in non-blocking mode, this function returns 0. */ @@ -284,16 +285,22 @@ public static int read(HidDeviceStructure device, byte[] buffer) { WideStringBuffer wBuffer = new WideStringBuffer(buffer); - return hidApiLibrary.hid_read(device.ptr(), wBuffer, wBuffer.buffer.length); + int result = hidApiLibrary.hid_read(device.ptr(), wBuffer, wBuffer.buffer.length); + + if (result > 0) { + logTraffic(wBuffer, false); + } + + return result; + } /** - *

Read an Input report from a HID device with timeout

+ * Read an Input report from a HID device with timeout * * @param device The HID device * @param buffer The buffer to read into * @param timeoutMillis The number of milliseconds to wait before giving up - * * @return The actual number of bytes read and -1 on error. If no packet was available to be read within * the timeout period returns 0. */ @@ -305,23 +312,27 @@ public static int read(HidDeviceStructure device, byte[] buffer, int timeoutMill WideStringBuffer wBuffer = new WideStringBuffer(buffer); - return hidApiLibrary.hid_read_timeout(device.ptr(), wBuffer, buffer.length, timeoutMillis); + int result = hidApiLibrary.hid_read_timeout(device.ptr(), wBuffer, buffer.length, timeoutMillis); + + if (result > 0) { + logTraffic(wBuffer, false); + } + + return result; } /** - *

Get a feature report from a HID device

- * - *

HID API notes

- * - *

Under the covers the HID library will set the first byte of data[] to the Report ID of the report to be read. - * Upon return, the first byte will still contain the Report ID, and the report data will start in data[1]

- *

This method handles all the wide string and array manipulation for you

+ * Get a feature report from a HID device + * HID API notes + *
+ * Under the covers the HID library will set the first byte of data[] to the Report ID of the report to be read. + * Upon return, the first byte will still contain the Report ID, and the report data will start in data[1] + * This method handles all the wide string and array manipulation for you * * @param device The HID device * @param data The buffer to contain the report * @param reportId The report ID (or (byte) 0x00) - * * @return The number of bytes read plus one for the report ID (which has been removed from the first byte), or -1 on error. */ public static int getFeatureReport(HidDeviceStructure device, byte[] data, byte reportId) { @@ -340,33 +351,33 @@ public static int getFeatureReport(HidDeviceStructure device, byte[] data, byte } // Avoid index out of bounds exception - System.arraycopy(report.buffer, 1, data, 0, res > data.length ? data.length : res); + System.arraycopy(report.buffer, 1, data, 0, Math.min(res, data.length)); + + logTraffic(report, false); return res; } /** - *

Send a Feature report to the device using a simplified interface

- * - *

HID API notes

- * - *

Under the covers, feature reports are sent over the Control endpoint as a Set_Report transfer. + * Send a Feature report to the device using a simplified interface + * HID API notes + *
+ * Under the covers, feature reports are sent over the Control endpoint as a Set_Report transfer. * The first byte of data[] must contain the Report ID. For devices which only support a single report, - * this must be set to 0x0. The remaining bytes contain the report data

- *

Since the Report ID is mandatory, calls to hid_send_feature_report() will always contain one more byte than - * the report contains.

- * - *

For example, if a hid report is 16 bytes long, 17 bytes must be passed to + * this must be set to 0x0. The remaining bytes contain the report data + * Since the Report ID is mandatory, calls to hid_send_feature_report() will always contain one more byte than + * the report contains. + *
+ * For example, if a hid report is 16 bytes long, 17 bytes must be passed to * hid_send_feature_report(): the Report ID (or 0x00, for devices which do not use numbered reports), followed by - * the report data (16 bytes). In this example, the bytes written would be 17.

- * - *

This method handles all the array manipulation for you

+ * the report data (16 bytes). In this example, the bytes written would be 17. + *
+ * This method handles all the array manipulation for you * * @param device The HID device * @param data The feature report data (will be widened and have the report ID pre-pended) * @param reportId The report ID (or (byte) 0x00) - * * @return This function returns the actual number of bytes written and -1 on error. */ public static int sendFeatureReport(HidDeviceStructure device, byte[] data, byte reportId) { @@ -379,33 +390,33 @@ public static int sendFeatureReport(HidDeviceStructure device, byte[] data, byte report.buffer[0] = reportId; System.arraycopy(data, 0, report.buffer, 1, data.length); + + logTraffic(report, true); + return hidApiLibrary.hid_send_feature_report(device.ptr(), report, report.buffer.length); } /** - *

Write an Output report to a HID device using a simplified interface

- * - *

HID API notes

- * - *

In USB HID the first byte of the data packet must contain the Report ID. + * Write an Output report to a HID device using a simplified interface + * HID API notes + *
+ * In USB HID the first byte of the data packet must contain the Report ID. * For devices which only support a single report, this must be set to 0x00. * The remaining bytes contain the report data. Since the Report ID is mandatory, * calls to hid_write() will always contain one more byte than the report - * contains.

- * - *

For example, if a hid report is 16 bytes long, 17 bytes must be passed to hid_write(), + * contains. + *
+ * For example, if a HID report is 16 bytes long, 17 bytes must be passed to hid_write(), * the Report ID (or 0x00, for devices with a single report), followed by the report data (16 bytes). - * In this example, the length passed in would be 17

- * - *

hid_write() will send the data on the first OUT endpoint, if one exists. - * If it does not, it will send the data through the Control Endpoint (Endpoint 0)

+ * In this example, the length passed in would be 17. + * hid_write() will send the data on the first OUT endpoint, if one exists. + * If it does not, it will send the data through the Control Endpoint (Endpoint 0) * * @param device The device * @param data The report data to write (should not include the Report ID) * @param len The length of the report data (should not include the Report ID) * @param reportId The report ID (or (byte) 0x00) - * * @return The number of bytes written, or -1 if an error occurs */ public static int write(HidDeviceStructure device, byte[] data, int len, byte reportId) { @@ -422,34 +433,24 @@ public static int write(HidDeviceStructure device, byte[] data, int len, byte re final WideStringBuffer report; - if (dropReportIdZero && reportId == 0) { - // Use the alternative buffer representation that does - // not include report ID 0x00 - // This overcomes "The parameter is incorrect" errors on - // Windows 8 and 10 - // See the commentary on the dropReportIdZero flag for more info - report = new WideStringBuffer(len); - if (len > 1) { - System.arraycopy(data, 0, report.buffer, 0, len); - } - } else { - // Put report ID into position 0 and fill out buffer - report = new WideStringBuffer(len + 1); - report.buffer[0] = reportId; - if (len > 1) { - System.arraycopy(data, 0, report.buffer, 1, len); - } + // Put report ID into position 0 and fill out buffer + report = new WideStringBuffer(len + 1); + report.buffer[0] = reportId; + if (len >= 1) { + System.arraycopy(data, 0, report.buffer, 1, len); } + + logTraffic(report, true); + return hidApiLibrary.hid_write(device.ptr(), report, report.buffer.length); } /** - *

Get a string from a HID device, based on its string index

+ * Get a string from a HID device, based on its string index * * @param device The HID device * @param idx The index - * * @return The string */ public static String getIndexedString(HidDeviceStructure device, int idx) { @@ -462,4 +463,56 @@ public static String getIndexedString(HidDeviceStructure device, int idx) { return res == -1 ? null : wStr.toString(); } + + /** + * Get a report descriptor from a HID device + *
+ * User has to provide a preallocated buffer (4096 bytes recommended) where descriptor will be copied to + *
+ * @param device The HID device + * @param buffer The buffer to copy descriptor into. + * @param size The size of the buffer in bytes. + * @return A non-negative number of bytes actually copied, or -1 on error. + * @since 0.14.0 hidapi + */ + public static int getReportDescriptor(HidDeviceStructure device, byte[] buffer, int size) { + + if (device == null) { + return -1; + } + return hidApiLibrary.hid_get_report_descriptor(device.ptr(), buffer, size); + } + + /** + * @param buffer The buffer to serialise for traffic + * @param isWrite True if writing (from host to device) + */ + private static void logTraffic(WideStringBuffer buffer, boolean isWrite) { + if (HidApi.logTraffic && buffer != null && buffer.size() > 0) { + if (isWrite) { + System.out.print("> "); + } else { + System.out.print("< "); + } + System.out.printf("[%02x]:", buffer.buffer.length); + for (byte b : buffer.buffer) { + System.out.printf(" %02x", b); + } + System.out.println(); + } + } + + /** + * Returns the full version of the underlying hidapi library + * + * @return The version in major.minor.patch format + * @see org.hid4java.HidServices#getNativeVersion + */ + public static String getVersion() { + if (hidApiLibrary == null) { + init(); + } + return hidApiLibrary.hid_version_str(); + } + } diff --git a/src/main/java/org/hid4java/jna/HidApiLibrary.java b/src/main/java/org/hid4java/jna/HidApiLibrary.java index 7993e30..88266c5 100644 --- a/src/main/java/org/hid4java/jna/HidApiLibrary.java +++ b/src/main/java/org/hid4java/jna/HidApiLibrary.java @@ -25,58 +25,43 @@ package org.hid4java.jna; -/** - *

[Pattern] to provide the following to {@link Object}:

- *
    - *
  • - *
- *

Example:

- *
- * 
- * - * @since 0.0.1 - *   - */ - import com.sun.jna.Library; -import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.WString; /** - *

JNA library interface to act as the proxy for the underlying native library

- *

This approach removes the need for any JNI or native code

+ * JNA library interface to act as the proxy for the underlying native library + * This approach removes the need for any JNI or native code + * + * @since 0.1.0 */ public interface HidApiLibrary extends Library { - HidApiLibrary INSTANCE = (HidApiLibrary) Native.loadLibrary("hidapi", HidApiLibrary.class); - /** - *

Initialize the HIDAPI library.

- *

This function initializes the HIDAPI library. Calling it is not strictly necessary, + * Initialize the HIDAPI library. + * This function initializes the HIDAPI library. Calling it is not strictly necessary, * as it will be called automatically by hid_enumerate() and any of the hid_open_*() functions * if it is needed. This function should be called at the beginning of execution however, - * if there is a chance of HIDAPI handles being opened by different threads simultaneously.

+ * if there is a chance of HIDAPI handles being opened by different threads simultaneously. */ void hid_init(); /** - *

Finalize the HIDAPI library.

- * - *

This function frees all of the static data associated with HIDAPI. It should be called - * at the end of execution to avoid memory leaks.

+ * Finalize the HIDAPI library. + *
+ * This function frees all the static data associated with HIDAPI. It should be called + * at the end of execution to avoid memory leaks. */ void hid_exit(); /** * Open a HID device using a Vendor ID (VID), Product ID (PID) and optionally a serial number. - * + *
* If serial_number is NULL, the first device with the specified VID and PID is opened. * - * @param vendor_id The vendor ID - * @param product_id The product ID + * @param vendor_id The vendor ID + * @param product_id The product ID * @param serial_number The serial number (or null for wildcard) - * * @return A pointer to a HidDevice on success or null on failure */ Pointer hid_open(short vendor_id, short product_id, WString serial_number); @@ -92,21 +77,19 @@ public interface HidApiLibrary extends Library { * Get a string describing the last error which occurred. * * @param device A device handle - * * @return A string containing the last error which occurred or null if none has occurred. */ Pointer hid_error(Pointer device); /** * Read an Input report from a HID device. - * + *
* Input reports are returned to the host through the INTERRUPT IN endpoint. The first byte will contain the Report number * if the device uses numbered reports. * * @param device A device handle returned from hid_open(). * @param bytes A buffer to put the read data into. * @param length The number of bytes to read. For devices with multiple reports, make sure to read an extra byte for the report number. - * * @return This function returns the actual number of bytes read and -1 on error. If no packet was available to be read * and the handle is in non-blocking mode this function returns 0. */ @@ -114,7 +97,7 @@ public interface HidApiLibrary extends Library { /** * Read an Input report from a HID device with timeout. - * + *
* Input reports are returned to the host through the INTERRUPT IN endpoint. The first byte will contain the Report number * if the device uses numbered reports. * @@ -122,7 +105,6 @@ public interface HidApiLibrary extends Library { * @param bytes A buffer to put the read data into. * @param length The number of bytes to read. For devices with multiple reports, make sure to read an extra byte for the report number. * @param timeout The timeout in milliseconds or -1 for blocking wait. - * * @return This function returns the actual number of bytes read and -1 on error. If no packet was available to be read within * the timeout period, this function returns 0. */ @@ -130,59 +112,56 @@ public interface HidApiLibrary extends Library { /** * Write an Output report to a HID device. - * + *
* The first byte of data[] must contain the Report ID. For devices which only support a single report, this must be set to 0x0. * The remaining bytes contain the report data. - * + *
* Since the Report ID is mandatory, calls to hid_write() will always contain one more byte than the report contains. - * + *
* For example, if a hid report is 16 bytes long, 17 bytes must be passed to hid_write(), the Report ID (or 0x0, for devices with * a single report), followed by the report data (16 bytes). In this example, the length passed in would be 17. - * + *
* hid_write() will send the data on the first OUT endpoint, if one exists. If it does not, it will send the data through the * Control Endpoint (Endpoint 0). * * @param device A device handle * @param data the data to send, including the report number as the first byte * @param len The length in bytes of the data to send - * * @return The actual number of bytes written, -1 on error */ int hid_write(Pointer device, WideStringBuffer.ByReference data, int len); /** * Get a feature report from a HID device. - * + *
* Set the first byte of data[] to the Report ID of the report to be read. Make sure to allow space for this extra byte in data[]. * Upon return, the first byte will still contain the Report ID, and the report data will start in data[1]. * * @param device A device handle * @param data A buffer to put the read data into, including the Report ID. Set the first byte of data[] to the Report ID of the report to be read, or set it to zero if your device does not use numbered reports. * @param length The number of bytes to read, including an extra byte for the report ID. The buffer can be longer than the actual report. - * * @return The number of bytes read plus one for the report ID (which is still in the first byte), or -1 on error */ int hid_get_feature_report(Pointer device, WideStringBuffer.ByReference data, int length); /** * Send a Feature report to the device. - * + *
* Feature reports are sent over the Control endpoint as a Set_Report transfer. - * + *
* The first byte of data[] must contain the Report ID. For devices which only support a single report, this must be set to 0x0. - * + *
* The remaining bytes contain the report data. - * + *
* Since the Report ID is mandatory, calls to hid_send_feature_report() will always contain one more byte than the report contains. - * + *
* For example, if a hid report is 16 bytes long, 17 bytes must be passed to hid_send_feature_report(): * the Report ID (or 0x0, for devices which do not use numbered reports), followed by the report data (16 bytes). * In this example, the length passed in would be 17. * * @param device The device handle * @param data The data to send, including the report number as the first byte - * @param length The length inbytes of the data to send, including the report number - * + * @param length The length in bytes of the data to send, including the report number * @return The actual number of bytes written, -1 on error */ int hid_send_feature_report(Pointer device, WideStringBuffer.ByReference data, int length); @@ -194,20 +173,30 @@ public interface HidApiLibrary extends Library { * @param idx The index of the string to get * @param string A wide string buffer to put the data into * @param len The length of the buffer in multiples of wchar_t - * * @return 0 on success, -1 on failure */ int hid_get_indexed_string(Pointer device, int idx, WideStringBuffer.ByReference string, int len); + /** + * Get the manufacturer string from a HID device + * + * @param device the device handle + * @param buffer A byte buffer to put the data into + * @param size The length of the buffer in multiple of wchar_t + * @return 0 on success, -1 on failure + */ + @SuppressWarnings("UnusedReturnValue") + int hid_get_report_descriptor(Pointer device, byte[] buffer, int size); + /** * Get the manufacturer string from a HID device * * @param device the device handle * @param str A wide string buffer to put the data into * @param len The length of the buffer in multiple of wchar_t - * * @return 0 on success, -1 on failure */ + @SuppressWarnings("UnusedReturnValue") int hid_get_manufacturer_string(Pointer device, WideStringBuffer.ByReference str, int len); /** @@ -216,9 +205,9 @@ public interface HidApiLibrary extends Library { * @param device the device handle * @param str A wide string buffer to put the data into * @param len The length of the buffer in multiple of wchar_t - * * @return 0 on success, -1 on failure */ + @SuppressWarnings("UnusedReturnValue") int hid_get_product_string(Pointer device, WideStringBuffer.ByReference str, int len); /** @@ -227,39 +216,37 @@ public interface HidApiLibrary extends Library { * @param device the device handle * @param str A wide string buffer to put the data into * @param len The length of the buffer in multiple of wchar_t - * * @return 0 on success, -1 on failure */ + @SuppressWarnings("UnusedReturnValue") int hid_get_serial_number_string(Pointer device, WideStringBuffer.ByReference str, int len); /** * Set the device handle to be non-blocking. - * + *
* In non-blocking mode calls to hid_read() will return immediately with a value of 0 if there is no data to be read. - * + *
* In blocking mode, hid_read() will wait (block) until there is data to read before returning. - * + *
* Nonblocking can be turned on and off at any time. * * @param device The device handle * @param nonblock 0 disables non-blocking, 1 enables non-blocking - * * @return 0 on success, -1 on error */ int hid_set_nonblocking(Pointer device, int nonblock); /** * Enumerate the HID Devices. - * + *
* This function returns a linked list of all the HID devices attached to the system which match vendor_id and product_id. - * + *
* If vendor_id is set to 0 then any vendor matches. If product_id is set to 0 then any product matches. - * + *
* If vendor_id and product_id are both set to 0, then all HID devices will be returned. * * @param vendor_id The vendor ID * @param product_id The product ID - * * @return A linked list of all discovered matching devices */ HidDeviceInfoStructure hid_enumerate(short vendor_id, short product_id); @@ -273,12 +260,18 @@ public interface HidApiLibrary extends Library { /** * Open a HID device by its path name. - * + *
* The path name be determined by calling hid_enumerate(), or a platform-specific path name can be used (eg: "/dev/hidraw0" on Linux). * * @param path The path name - * * @return The pointer if successful or null */ Pointer hid_open_path(String path); -} \ No newline at end of file + + /** + * Get version of hidapi library + * + * @return Version in major.minor.patch format + */ + String hid_version_str(); +} diff --git a/src/main/java/org/hid4java/jna/HidDeviceInfoStructure.java b/src/main/java/org/hid4java/jna/HidDeviceInfoStructure.java index c6cb9f1..df5f7ca 100644 --- a/src/main/java/org/hid4java/jna/HidDeviceInfoStructure.java +++ b/src/main/java/org/hid4java/jna/HidDeviceInfoStructure.java @@ -32,7 +32,8 @@ import java.util.List; /** - *

Value object to provide HID device information

+ * Value object to provide HID device information + * @since 0.1.0 */ public class HidDeviceInfoStructure extends Structure implements Structure.ByReference { @@ -96,7 +97,7 @@ public boolean hasNext() { } @Override - protected List getFieldOrder() { + protected List getFieldOrder() { // If this precise order is not specified you get "SIGSEGV (0xb)" return Arrays.asList( diff --git a/src/main/java/org/hid4java/jna/HidDeviceStructure.java b/src/main/java/org/hid4java/jna/HidDeviceStructure.java index 649bdf5..bcf9e47 100644 --- a/src/main/java/org/hid4java/jna/HidDeviceStructure.java +++ b/src/main/java/org/hid4java/jna/HidDeviceStructure.java @@ -32,7 +32,8 @@ import java.util.List; /** - *

Low level JNA value object to provide a HID device pointer

+ * Low level JNA value object to provide a HID device pointer + * @since 0.1.0 */ public class HidDeviceStructure extends Structure implements Structure.ByReference { diff --git a/src/main/java/org/hid4java/jna/HidrawHidApiLibrary.java b/src/main/java/org/hid4java/jna/HidrawHidApiLibrary.java new file mode 100644 index 0000000..b3f3887 --- /dev/null +++ b/src/main/java/org/hid4java/jna/HidrawHidApiLibrary.java @@ -0,0 +1,39 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2015 Gary Rowe + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package org.hid4java.jna; + +import com.sun.jna.Native; + +/** + * JNA library interface to act as the proxy for the underlying native library + * This approach removes the need for any JNI or native code + * @since 0.7.0 + */ +public interface HidrawHidApiLibrary extends HidApiLibrary { + + HidApiLibrary INSTANCE = Native.load("hidapi", HidApiLibrary.class); + +} \ No newline at end of file diff --git a/src/main/java/org/hid4java/jna/LibusbHidApiLibrary.java b/src/main/java/org/hid4java/jna/LibusbHidApiLibrary.java new file mode 100644 index 0000000..275fd68 --- /dev/null +++ b/src/main/java/org/hid4java/jna/LibusbHidApiLibrary.java @@ -0,0 +1,39 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2015 Gary Rowe + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package org.hid4java.jna; + +import com.sun.jna.Native; + +/** + * JNA library interface to act as the proxy for the underlying native library + * This approach removes the need for any JNI or native code + * @since 0.7.0 + */ +public interface LibusbHidApiLibrary extends HidrawHidApiLibrary { + + LibusbHidApiLibrary INSTANCE = Native.load("hidapi-libusb", LibusbHidApiLibrary.class); + +} \ No newline at end of file diff --git a/src/main/java/org/hid4java/jna/WideStringBuffer.java b/src/main/java/org/hid4java/jna/WideStringBuffer.java index df784fc..21aa55f 100644 --- a/src/main/java/org/hid4java/jna/WideStringBuffer.java +++ b/src/main/java/org/hid4java/jna/WideStringBuffer.java @@ -27,15 +27,16 @@ import com.sun.jna.Structure; -import java.util.Arrays; +import java.util.Collections; import java.util.List; /** - *

Wrapper for a wide character (WCHAR) structure

+ * Wrapper for a wide character (WCHAR) structure + * @since 0.1.0 */ public class WideStringBuffer extends Structure implements Structure.ByReference { - public byte[] buffer = null; + public byte[] buffer; public WideStringBuffer(int len) { buffer = new byte[len]; @@ -46,18 +47,18 @@ public WideStringBuffer(byte[] bytes) { } @Override - protected List getFieldOrder() { - return Arrays.asList("buffer"); + protected List getFieldOrder() { + return Collections.singletonList("buffer"); } /** - *

hidapi uses wchar_t which is written l i k e t h i s (with '\0' in between)

+ * HIDAPI uses wchar_t which is written l i k e t h i s (with '\0' in between) */ public String toString() { - String str = ""; + StringBuilder str = new StringBuilder(); for (int i = 0; i < buffer.length && buffer[i] != 0; i += 2) - str += (char) (buffer[i] | buffer[i + 1] << 8); - return str; + str.append((char) (buffer[i] | buffer[i + 1] << 8)); + return str.toString(); } } diff --git a/src/main/resources/darwin-aarch64/libhidapi.dylib b/src/main/resources/darwin-aarch64/libhidapi.dylib new file mode 100755 index 0000000..696717b Binary files /dev/null and b/src/main/resources/darwin-aarch64/libhidapi.dylib differ diff --git a/src/main/resources/darwin-x86-64/libhidapi.dylib b/src/main/resources/darwin-x86-64/libhidapi.dylib new file mode 100755 index 0000000..b285171 Binary files /dev/null and b/src/main/resources/darwin-x86-64/libhidapi.dylib differ diff --git a/src/main/resources/darwin/libhidapi.dylib b/src/main/resources/darwin/libhidapi.dylib deleted file mode 100755 index c0b74d9..0000000 Binary files a/src/main/resources/darwin/libhidapi.dylib and /dev/null differ diff --git a/src/main/resources/libhidapipi.so b/src/main/resources/libhidapipi.so deleted file mode 100755 index 648a3c5..0000000 Binary files a/src/main/resources/libhidapipi.so and /dev/null differ diff --git a/src/main/resources/linux-aarch64/libhidapi-libusb.so b/src/main/resources/linux-aarch64/libhidapi-libusb.so new file mode 100755 index 0000000..5b94a91 Binary files /dev/null and b/src/main/resources/linux-aarch64/libhidapi-libusb.so differ diff --git a/src/main/resources/linux-aarch64/libhidapi.so b/src/main/resources/linux-aarch64/libhidapi.so new file mode 100755 index 0000000..f43f900 Binary files /dev/null and b/src/main/resources/linux-aarch64/libhidapi.so differ diff --git a/src/main/resources/linux-amd64/libhidapi-libusb.so b/src/main/resources/linux-amd64/libhidapi-libusb.so new file mode 100755 index 0000000..cb202de Binary files /dev/null and b/src/main/resources/linux-amd64/libhidapi-libusb.so differ diff --git a/src/main/resources/linux-amd64/libhidapi.so b/src/main/resources/linux-amd64/libhidapi.so index 13d4a9c..19da5ba 100755 Binary files a/src/main/resources/linux-amd64/libhidapi.so and b/src/main/resources/linux-amd64/libhidapi.so differ diff --git a/src/main/resources/linux-arm/libhidapi-libusb.so b/src/main/resources/linux-arm/libhidapi-libusb.so new file mode 100755 index 0000000..784dea8 Binary files /dev/null and b/src/main/resources/linux-arm/libhidapi-libusb.so differ diff --git a/src/main/resources/linux-arm/libhidapi.so b/src/main/resources/linux-arm/libhidapi.so index 648a3c5..b5c2780 100755 Binary files a/src/main/resources/linux-arm/libhidapi.so and b/src/main/resources/linux-arm/libhidapi.so differ diff --git a/src/main/resources/linux-armel/libhidapi-libusb.so b/src/main/resources/linux-armel/libhidapi-libusb.so new file mode 100755 index 0000000..de0468d Binary files /dev/null and b/src/main/resources/linux-armel/libhidapi-libusb.so differ diff --git a/src/main/resources/linux-armel/libhidapi.so b/src/main/resources/linux-armel/libhidapi.so new file mode 100755 index 0000000..d029e26 Binary files /dev/null and b/src/main/resources/linux-armel/libhidapi.so differ diff --git a/src/main/resources/linux-riscv64/libhidapi-libusb.so b/src/main/resources/linux-riscv64/libhidapi-libusb.so new file mode 100755 index 0000000..6222aee Binary files /dev/null and b/src/main/resources/linux-riscv64/libhidapi-libusb.so differ diff --git a/src/main/resources/linux-riscv64/libhidapi.so b/src/main/resources/linux-riscv64/libhidapi.so new file mode 100755 index 0000000..3055d7b Binary files /dev/null and b/src/main/resources/linux-riscv64/libhidapi.so differ diff --git a/src/main/resources/linux-x86-64/libhidapi-libusb.so b/src/main/resources/linux-x86-64/libhidapi-libusb.so new file mode 100755 index 0000000..cb202de Binary files /dev/null and b/src/main/resources/linux-x86-64/libhidapi-libusb.so differ diff --git a/src/main/resources/linux-x86-64/libhidapi.so b/src/main/resources/linux-x86-64/libhidapi.so index 9d6fc90..19da5ba 100755 Binary files a/src/main/resources/linux-x86-64/libhidapi.so and b/src/main/resources/linux-x86-64/libhidapi.so differ diff --git a/src/main/resources/linux-x86/libhidapi-libusb.so b/src/main/resources/linux-x86/libhidapi-libusb.so new file mode 100755 index 0000000..cb202de Binary files /dev/null and b/src/main/resources/linux-x86/libhidapi-libusb.so differ diff --git a/src/main/resources/linux-x86/libhidapi.so b/src/main/resources/linux-x86/libhidapi.so index 259f353..19da5ba 100755 Binary files a/src/main/resources/linux-x86/libhidapi.so and b/src/main/resources/linux-x86/libhidapi.so differ diff --git a/src/main/resources/win32-aarch64/hidapi.dll b/src/main/resources/win32-aarch64/hidapi.dll new file mode 100755 index 0000000..2ef6f34 Binary files /dev/null and b/src/main/resources/win32-aarch64/hidapi.dll differ diff --git a/src/main/resources/win32-amd64/hidapi.dll b/src/main/resources/win32-amd64/hidapi.dll deleted file mode 100644 index c371eca..0000000 Binary files a/src/main/resources/win32-amd64/hidapi.dll and /dev/null differ diff --git a/src/main/resources/win32-x86-64/hidapi.dll b/src/main/resources/win32-x86-64/hidapi.dll index c371eca..b842f88 100755 Binary files a/src/main/resources/win32-x86-64/hidapi.dll and b/src/main/resources/win32-x86-64/hidapi.dll differ diff --git a/src/main/resources/win32-x86/hidapi.dll b/src/main/resources/win32-x86/hidapi.dll index cf8d428..1731e89 100755 Binary files a/src/main/resources/win32-x86/hidapi.dll and b/src/main/resources/win32-x86/hidapi.dll differ diff --git a/src/test/java/org/hid4java/HidDeviceTest.java b/src/test/java/org/hid4java/HidDeviceTest.java new file mode 100644 index 0000000..60cabc1 --- /dev/null +++ b/src/test/java/org/hid4java/HidDeviceTest.java @@ -0,0 +1,79 @@ +package org.hid4java; + +import com.sun.jna.WString; +import org.hid4java.jna.HidDeviceInfoStructure; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class HidDeviceTest { + + HidDeviceInfoStructure mockStructure = new HidDeviceInfoStructure(); + + @Test + void isVidPidSerial_UnsignedShort_Simple() { + + // Arrange + mockStructure.vendor_id = 0x01; + mockStructure.product_id = 0x02; + mockStructure.serial_number = new WString("1234"); + + // Act + HidDevice testObject = new HidDevice(mockStructure, null, new HidServicesSpecification()); + + // Assert + assertTrue(testObject.isVidPidSerial(0x01, 0x02, "1234")); + + } + + @Test + void isVidPidSerial_UnsignedShort_Overflow() { + + // Arrange + mockStructure.vendor_id = 0xffff8001; + mockStructure.product_id = 0xffff8002; + mockStructure.serial_number = new WString("1234"); + + // Act + HidDevice testObject = new HidDevice(mockStructure, null, new HidServicesSpecification()); + + // Assert + assertTrue(testObject.isVidPidSerial(0x8001, 0x8002, "1234")); + + } + + @Test + void verifyFields() { + + // Arrange + mockStructure.path="path"; + mockStructure.vendor_id=1; + mockStructure.product_id=2; + mockStructure.serial_number=new WString("serial"); + mockStructure.release_number=3; + mockStructure.manufacturer_string=new WString("manufacturer"); + mockStructure.product_string = new WString("product"); + mockStructure.usage_page=4; + mockStructure.usage=5; + mockStructure.interface_number=6; + mockStructure.next=null; + + // Act + HidDevice testObject = new HidDevice(mockStructure, null, new HidServicesSpecification()); + + // Assert + assertEquals("path", testObject.getPath()); + assertEquals(1, testObject.getVendorId()); + assertEquals(2, testObject.getProductId()); + assertEquals("serial", testObject.getSerialNumber()); + assertEquals(3, testObject.getReleaseNumber()); + assertEquals("manufacturer", testObject.getManufacturer()); + assertEquals("product", testObject.getProduct()); + assertEquals(4,testObject.getUsagePage()); + assertEquals(5, testObject.getUsage()); + assertEquals(6, testObject.getInterfaceNumber()); + + } + +} \ No newline at end of file diff --git a/src/test/java/org/hid4java/UsbHidDeviceExample.java b/src/test/java/org/hid4java/UsbHidDeviceExample.java deleted file mode 100644 index 512e5de..0000000 --- a/src/test/java/org/hid4java/UsbHidDeviceExample.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * The MIT License (MIT) - * - * Copyright (c) 2014-2016 Gary Rowe - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all - * copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - * SOFTWARE. - * - */ - -package org.hid4java;import org.hid4java.event.HidServicesEvent; - -import java.util.concurrent.TimeUnit; - -import static java.util.concurrent.TimeUnit.NANOSECONDS; - -/** - *

Demonstrate the USB HID interface using a production Bitcoin Trezor

- * - * @since 0.0.1 - *   - */ -public class UsbHidDeviceExample implements HidServicesListener { - - private static final Integer VENDOR_ID = 0x534c; - private static final Integer PRODUCT_ID = 0x01; - private static final int PACKET_LENGTH = 64; - public static final String SERIAL_NUMBER = null; - - public static void main(String[] args) throws HidException { - - UsbHidDeviceExample example = new UsbHidDeviceExample(); - example.executeExample(); - - } - - public void executeExample() throws HidException { - - // Configure to use custom specification - HidServicesSpecification hidServicesSpecification = new HidServicesSpecification(); - hidServicesSpecification.setAutoShutdown(true); - hidServicesSpecification.setScanInterval(500); - hidServicesSpecification.setPauseInterval(5000); - hidServicesSpecification.setScanMode(ScanMode.SCAN_AT_FIXED_INTERVAL_WITH_PAUSE_AFTER_WRITE); - - // Get HID services using custom specification - HidServices hidServices = HidManager.getHidServices(hidServicesSpecification); - hidServices.addHidServicesListener(this); - - // Start the services - System.out.println("Starting HID services."); - hidServices.start(); - - System.out.println("Enumerating attached devices..."); - - // Provide a list of attached devices - for (HidDevice hidDevice : hidServices.getAttachedHidDevices()) { - System.out.println(hidDevice); - } - - // Open the device device by Vendor ID and Product ID with wildcard serial number - HidDevice hidDevice = hidServices.getHidDevice(VENDOR_ID, PRODUCT_ID, SERIAL_NUMBER); - if (hidDevice != null) { - // Consider overriding dropReportIdZero on Windows - // if you see "The parameter is incorrect" - // HidApi.dropReportIdZero = true; - - // Device is already attached and successfully opened so send message - sendMessage(hidDevice); - } - - System.out.printf("Waiting 30s to demonstrate attach/detach handling. Watch for slow response after write if configured.%n"); - - // Stop the main thread to demonstrate attach and detach events - sleepUninterruptibly(30, TimeUnit.SECONDS); - - // Shut down and rely on auto-shutdown hook to clear HidApi resources - hidServices.shutdown(); - - } - - @Override - public void hidDeviceAttached(HidServicesEvent event) { - - System.out.println("Device attached: " + event); - - // Add serial number when more than one device with the same - // vendor ID and product ID will be present at the same time - if (event.getHidDevice().isVidPidSerial(VENDOR_ID, PRODUCT_ID, null)) { - sendMessage(event.getHidDevice()); - } - - } - - @Override - public void hidDeviceDetached(HidServicesEvent event) { - - System.err.println("Device detached: " + event); - - } - - @Override - public void hidFailure(HidServicesEvent event) { - - System.err.println("HID failure: " + event); - - } - - private void sendMessage(HidDevice hidDevice) { - - // Ensure device is open after an attach/detach event - if (!hidDevice.isOpen()) { - hidDevice.open(); - } - - // Send the Initialise message - byte[] message = new byte[PACKET_LENGTH]; - message[0] = 0x3f; // USB: Payload 63 bytes - message[1] = 0x23; // Device: '#' - message[2] = 0x23; // Device: '#' - message[3] = 0x00; // INITIALISE - - int val = hidDevice.write(message, PACKET_LENGTH, (byte) 0x00); - if (val >= 0) { - System.out.println("> [" + val + "]"); - } else { - System.err.println(hidDevice.getLastErrorMessage()); - } - - // Prepare to read a single data packet - boolean moreData = true; - while (moreData) { - byte data[] = new byte[PACKET_LENGTH]; - // This method will now block for 500ms or until data is read - val = hidDevice.read(data, 500); - switch (val) { - case -1: - System.err.println(hidDevice.getLastErrorMessage()); - break; - case 0: - moreData = false; - break; - default: - System.out.print("< ["); - for (byte b : data) { - System.out.printf(" %02x", b); - } - System.out.println("]"); - break; - } - } - } - - /** - * Invokes {@code unit.}{@link java.util.concurrent.TimeUnit#sleep(long) sleep(sleepFor)} - * uninterruptibly. - */ - public static void sleepUninterruptibly(long sleepFor, TimeUnit unit) { - boolean interrupted = false; - try { - long remainingNanos = unit.toNanos(sleepFor); - long end = System.nanoTime() + remainingNanos; - while (true) { - try { - // TimeUnit.sleep() treats negative timeouts just like zero. - NANOSECONDS.sleep(remainingNanos); - return; - } catch (InterruptedException e) { - interrupted = true; - remainingNanos = end - System.nanoTime(); - } - } - } finally { - if (interrupted) { - Thread.currentThread().interrupt(); - } - } - } - -} diff --git a/src/test/java/org/hid4java/examples/BaseExample.java b/src/test/java/org/hid4java/examples/BaseExample.java new file mode 100644 index 0000000..6a28505 --- /dev/null +++ b/src/test/java/org/hid4java/examples/BaseExample.java @@ -0,0 +1,135 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2020 Gary Rowe + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package org.hid4java.examples; + +import com.sun.jna.Platform; +import org.hid4java.HidServices; +import org.hid4java.HidServicesListener; +import org.hid4java.event.HidServicesEvent; + +import java.util.concurrent.TimeUnit; + +import static java.util.concurrent.TimeUnit.NANOSECONDS; + +public abstract class BaseExample implements HidServicesListener { + + public static final String ANSI_RESET = "\u001B[0m"; + public static final String ANSI_BLACK = "\u001B[30m"; + public static final String ANSI_RED = "\u001B[31m"; + public static final String ANSI_GREEN = "\u001B[32m"; + public static final String ANSI_YELLOW = "\u001B[33m"; + public static final String ANSI_BLUE = "\u001B[34m"; + public static final String ANSI_PURPLE = "\u001B[35m"; + public static final String ANSI_CYAN = "\u001B[36m"; + public static final String ANSI_WHITE = "\u001B[37m"; + + public void printPlatform() { + + // System info to assist with library detection + System.out.println("Platform architecture: " + Platform.ARCH); + System.out.println("Resource prefix: " + Platform.RESOURCE_PREFIX); + System.out.println("Libusb activation: " + Platform.isLinux()); + + } + + public static void printAsHex(byte[] dataReceived) { + System.out.printf("< [%02x]:", dataReceived.length); + for (byte b : dataReceived) { + System.out.printf(" %02x", b); + } + System.out.println(ANSI_RESET); + } + + public void waitAndShutdown(HidServices hidServices) { + + System.out.printf(ANSI_YELLOW + "Waiting 30s to demonstrate attach/detach handling. Watch for slow response after write if configured.%n" + ANSI_RESET); + + // Stop the main thread to demonstrate attach and detach events + sleepNoInterruption(); + + // Shut down and rely on auto-shutdown hook to clear HidApi resources + System.out.printf(ANSI_YELLOW + "Triggering shutdown...%n" + ANSI_RESET); + hidServices.shutdown(); + } + + /** + * Invokes {@code unit.}{@link TimeUnit#sleep(long) sleep(sleepFor)} + * uninterruptibly. + */ + public static void sleepNoInterruption() { + boolean interrupted = false; + try { + long remainingNanos = TimeUnit.SECONDS.toNanos(30); + long end = System.nanoTime() + remainingNanos; + while (true) { + try { + // TimeUnit.sleep() treats negative timeouts just like zero. + NANOSECONDS.sleep(remainingNanos); + return; + } catch (InterruptedException e) { + interrupted = true; + remainingNanos = end - System.nanoTime(); + } + } + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + } + + @Override + public void hidDeviceAttached(HidServicesEvent event) { + + System.out.println(ANSI_BLUE + "Device attached: " + event + ANSI_RESET); + + } + + @Override + public void hidDeviceDetached(HidServicesEvent event) { + + System.out.println(ANSI_YELLOW + "Device detached: " + event + ANSI_RESET); + + } + + @Override + public void hidFailure(HidServicesEvent event) { + + System.out.println(ANSI_RED + "HID failure: " + event + ANSI_RESET); + + } + + @Override + public void hidDataReceived(HidServicesEvent event) { + + System.out.printf(ANSI_PURPLE + "Data received:%n"); + byte[] dataReceived = event.getDataReceived(); + + printAsHex(dataReceived); + + } + +} diff --git a/src/test/java/org/hid4java/examples/Fido2AuthenticationExample.java b/src/test/java/org/hid4java/examples/Fido2AuthenticationExample.java new file mode 100644 index 0000000..9805436 --- /dev/null +++ b/src/test/java/org/hid4java/examples/Fido2AuthenticationExample.java @@ -0,0 +1,302 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2020 Gary Rowe + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package org.hid4java.examples; + +import org.hid4java.*; +import org.hid4java.event.HidServicesEvent; +import org.hid4java.jna.HidApi; + +import java.security.SecureRandom; + +/** + * Demonstrate the USB HID interface using a FIDO2 USB device + *
+ * If you have a FIDO2 U2F authentication device (e.g. a HyperFIDO, Yubikey, Solokey, Trezor or Ledger) + * you may wish to explore its capabilities using this example. Simply plug it in and run the example to + * see the initial handshake to select a channel and basic device information. + *
+ * You can see some of hid4java features in use such as: + *
    + *
      + *
    • device enumeration and selection
    • + *
    • automatic data read events (new for 0.8.0)
    • + *
    • low level HID traffic to System.out to assist early stage debugging
    • + *
    • manual start to enable attach/detach events
    • + *
    + *
    + * Use the following command to try it out: + *
    + * + * mvn clean test exec:java -Dexec.classpathScope="test" -Dexec.mainClass="org.hid4java.examples.Fido2AuthenticationExample" + * + * + * @since 0.8.0 + */ +public class Fido2AuthenticationExample extends BaseExample { + + // The FIDO2 scaffolding code will get included in later versions of this example + + // Authentication data flags + // private static byte CTAP_AUTHDATA_USER_PRESENT = 0x01; + // private static byte CTAP_AUTHDATA_USER_VERIFIED = 0x04; + // private static byte CTAP_AUTHDATA_ATT_CRED = 0x40; + // private static byte CTAP_AUTHDATA_EXT_DATA = (byte) 0x80; + // + // // CTAPHID command opcodes + // private static byte CTAP_CMD_PING = 0x01; + // private static byte CTAP_CMD_MSG = 0x03; + // private static byte CTAP_CMD_LOCK = 0x04; + private static final byte CTAP_CMD_INIT = 0x06; + // private static byte CTAP_CMD_WINK = 0x08; + // private static byte CTAP_CMD_CBOR = 0x10; + // private static byte CTAP_CMD_CANCEL = 0x11; + // private static byte CTAP_KEEPALIVE = 0x3b; + // private static byte CTAP_FRAME_INIT = (byte) 0x80; + // + // // CTAPHID CBOR command opcodes + // private static byte CTAP_CBOR_MAKECRED = 0x01; + // private static byte CTAP_CBOR_ASSERT = 0x02; + // private static byte CTAP_CBOR_GETINFO = 0x04; + // private static byte CTAP_CBOR_CLIENT_PIN = 0x06; + // private static byte CTAP_CBOR_RESET = 0x07; + // private static byte CTAP_CBOR_NEXT_ASSERT = 0x08; + // private static byte CTAP_CBOR_BIO_ENROLL_PRE = 0x40; + // private static byte CTAP_CBOR_CRED_MGMT_PRE = 0x41; + // + // // U2F command opcodes + // private static byte U2F_CMD_REGISTER = 0x01; + // private static byte U2F_CMD_AUTH = 0x02; + // + // // U2F command flags + // private static byte U2F_AUTH_SIGN = 0x03; + // private static byte U2F_AUTH_CHECK = 0x07; + // + // // ISO7816-4 status words + // private static int SW_CONDITIONS_NOT_SATISFIED = 0x6985; + // private static int SW_WRONG_DATA = 0x6a80; + // private static int SW_NO_ERROR = 0x9000; + // + // // HID Broadcast channel ID + // private static int CTAP_CID_BROADCAST = 0xffffffff; + // + // private static int CTAP_INIT_HEADER_LEN = 7; + // private static int CTAP_CONT_HEADER_LEN = 5; + // + // // Maximum length of a CTAP HID report in bytes + private static final int CTAP_MAX_REPORT_LEN = 64; + // + // // Minimum length of a CTAP HID report in bytes + // private static int CTAP_MIN_REPORT_LEN = CTAP_INIT_HEADER_LEN + 1; + // + // // Maximum message size in bytes + // private static int FIDO_MAXMSG = 2048; + // + // // CTAP capability bits (set means supported) + // private static byte FIDO_CAP_WINK = 0x01; + // private static byte FIDO_CAP_CBOR = 0x04; + // private static byte FIDO_CAP_NMSG = 0x08; + // + // // Supported COSE algorithms + // private static int COSE_ES256 = -7; + // private static int COSE_EDDSA = -8; + // private static int COSE_ECDH_ES256 = -25; + // private static int COSE_RS256 = -257; + // + // // Supported COSE types + // private static int COSE_KTY_OKP = 1; + // private static int COSE_KTY_EC2 = 2; + // private static int COSE_KTY_RSA = 3; + // + // // Supported curves + // private static int COSE_P256 = 1; + // private static int COSE_ED25519 = 6; + // + // // Supported extensions + // private static byte FIDO_EXT_HMAC_SECRET = 0x01; + // private static byte FIDO_EXT_CRED_PROTECT = 0x02; + // + // // Supported credential protection policies + // private static int FIDO_CRED_PROT_UV_OPTIONAL = 0x01; + // private static int FIDO_CRED_PROT_UV_OPTIONAL_WITH_ID = 0x02; + // private static int FIDO_CRED_PROT_UV_REQUIRED = 0x03; + + // Secure random source for nonce + private static final SecureRandom secureRandom = new SecureRandom(); + + // Instance variables + private final byte[] nonce = new byte[8]; + //private final byte[] fidoChannel = new byte[4]; + + public static void main(String[] args) throws HidException { + + Fido2AuthenticationExample example = new Fido2AuthenticationExample(); + example.executeExample(); + + } + + private void executeExample() throws HidException { + + printPlatform(); + + // Demonstrate low level traffic logging + HidApi.logTraffic = true; + + // Configure to use custom specification + HidServicesSpecification hidServicesSpecification = new HidServicesSpecification(); + + // Use manual start + hidServicesSpecification.setAutoStart(false); + + // Use data received events + hidServicesSpecification.setAutoDataRead(true); + hidServicesSpecification.setDataReadInterval(500); + + // Get HID services using custom specification + HidServices hidServices = HidManager.getHidServices(hidServicesSpecification); + + // Register for service events + hidServices.addHidServicesListener(this); + + // Manually start HID services + hidServices.start(); + + // Enumerate devices looking for usage page = 0xf1d0 (FIDO...) + HidDevice fidoDevice = null; + for (HidDevice hidDevice : hidServices.getAttachedHidDevices()) { + if (hidDevice.getUsage() == 0x01 && hidDevice.getUsagePage() == 0xfffff1d0) { + System.out.println(ANSI_GREEN + "Using FIDO2 device: " + hidDevice.getPath() + ANSI_RESET); + fidoDevice = hidDevice; + break; + } + } + + if (fidoDevice == null) { + // Shut down and rely on auto-shutdown hook to clear HidApi resources + System.out.println(ANSI_YELLOW + "No FIDO2 devices attached." + ANSI_RESET); + } else { + + // Open the device + if (fidoDevice.isClosed()) { + if (!fidoDevice.open()) { + throw new IllegalStateException("Unable to open device"); + } + } + + // Perform a USB ReportDescriptor operation to determine general device capabilities + // This requires complex decoding defined in the referenced documents + // Reports can be up to 4096 bytes for complex devices so 64 is quite low + byte[] reportDescriptor = new byte[64]; + if (fidoDevice.getReportDescriptor(reportDescriptor) > 0) { + System.out.println(ANSI_GREEN + "FIDO2 device report descriptor (first 64 bytes): " + fidoDevice.getPath() + ANSI_RESET); + printAsHex(reportDescriptor); + } + + // Perform a FIDO Initialise operation + handleInitialise(fidoDevice); + + // TODO Consider further operations such as Registration to illustrate state machine + + } + + waitAndShutdown(hidServices); + + } + + /** + * Generate a random set of 8 bytes for use as a nonce + */ + private void generateNonce() { + + secureRandom.nextBytes(nonce); + + } + + /** + * Initialise the FIDO2 device and set a communications channel + * + * @param hidDevice The device to use + * @return True if the device is now initialised for use + */ + private boolean handleInitialise(HidDevice hidDevice) { + + generateNonce(); + + // Initialise + byte[] initialiseRequest = new byte[]{ + (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, // Broadcast channel + (byte) ((byte) 0x80 + CTAP_CMD_INIT), // Initialise command + 0x00, 0x08, // Payload byte count (BCNT) + nonce[0], nonce[1], nonce[2], nonce[3], nonce[4], nonce[5], nonce[6], nonce[7] + }; + + // Write message to device with zero byte padding + System.out.println(ANSI_GREEN + "Sending CTAPHID_INIT..." + ANSI_RESET); + int bytesWritten = hidDevice.write(initialiseRequest, CTAP_MAX_REPORT_LEN, (byte) 0x00, true); + if (bytesWritten < 0) { + System.out.println(ANSI_RED + hidDevice.getLastErrorMessage() + ANSI_RESET); + return false; + } + + return true; + + } + + @Override + public void hidDataReceived(HidServicesEvent event) { + super.hidDataReceived(event); + + // Analyse the response + byte[] initialiseResponse = event.getDataReceived(); + + // Decode the response + System.out.println(ANSI_GREEN + "Response is:" + ANSI_RESET); + System.out.printf("Channel id: %02x %02x %02x %02x%n", + initialiseResponse[0], initialiseResponse[1], initialiseResponse[2], initialiseResponse[3] + ); + System.out.printf("Command (0x86): %02x%n", initialiseResponse[4]); + System.out.printf("Byte count (0x00 0x11): %02x %02x%n", initialiseResponse[5], initialiseResponse[6]); + System.out.printf("Nonce (%02x %02x %02x %02x %02x %02x %02x %02x): %02x %02x %02x %02x %02x %02x %02x %02x%n", + nonce[0], nonce[1], nonce[2], nonce[3], nonce[4], nonce[5], nonce[6], nonce[7], + initialiseResponse[7], initialiseResponse[8], initialiseResponse[9], initialiseResponse[10], + initialiseResponse[11], initialiseResponse[12], initialiseResponse[13], initialiseResponse[14] + ); + System.out.printf("New channel id: %02x %02x %02x %02x%n", + initialiseResponse[15], initialiseResponse[16], initialiseResponse[17], initialiseResponse[18] + ); + System.out.printf("Protocol (0x02): %02x%n", initialiseResponse[19]); + System.out.printf("Major: %02x%n", initialiseResponse[20]); + System.out.printf("Minor: %02x%n", initialiseResponse[21]); + System.out.printf("Build: %02x%n", initialiseResponse[22]); + System.out.printf("Capabilities: %02x%n", initialiseResponse[23]); + + // TODO Copy the channel for ongoing communications +// fidoChannel[0] = initialiseResponse[15]; +// fidoChannel[1] = initialiseResponse[16]; +// fidoChannel[2] = initialiseResponse[17]; +// fidoChannel[3] = initialiseResponse[18]; + + } +} diff --git a/src/test/java/org/hid4java/examples/LibusbEnumerationExample.java b/src/test/java/org/hid4java/examples/LibusbEnumerationExample.java new file mode 100644 index 0000000..5d830c1 --- /dev/null +++ b/src/test/java/org/hid4java/examples/LibusbEnumerationExample.java @@ -0,0 +1,70 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2020 Gary Rowe + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package org.hid4java.examples; + +import org.hid4java.*; +import org.hid4java.jna.HidApi; + +/** + * Demonstrate the USB HID interface with older libusb Linux library variant + * + * @since 0.7.0 + */ +public class LibusbEnumerationExample extends BaseExample { + + public static void main(String[] args) throws HidException { + + LibusbEnumerationExample example = new LibusbEnumerationExample(); + example.executeExample(); + + } + + private void executeExample() throws HidException { + + printPlatform(); + + // Configure to use default specification + HidServicesSpecification hidServicesSpecification = new HidServicesSpecification(); + + // Set the libusb variant (only needed for older Linux platforms) + HidApi.useLibUsbVariant = true; + + // Get HID services using custom specification + HidServices hidServices = HidManager.getHidServices(hidServicesSpecification); + hidServices.addHidServicesListener(this); + + System.out.println(ANSI_GREEN + "Enumerating attached devices..." + ANSI_RESET); + + // Provide a list of attached devices + for (HidDevice hidDevice : hidServices.getAttachedHidDevices()) { + System.out.println(hidDevice); + } + + waitAndShutdown(hidServices); + + } + +} diff --git a/src/test/java/org/hid4java/examples/UsbHidEnumerationExample.java b/src/test/java/org/hid4java/examples/UsbHidEnumerationExample.java new file mode 100644 index 0000000..fc09b58 --- /dev/null +++ b/src/test/java/org/hid4java/examples/UsbHidEnumerationExample.java @@ -0,0 +1,72 @@ +/* + * The MIT License (MIT) + * + * Copyright (c) 2014-2020 Gary Rowe + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + */ + +package org.hid4java.examples; + +import org.hid4java.*; + +/** + * Demonstrate the USB HID interface using a Satoshi Labs Trezor + * + * @since 0.0.1 + */ +public class UsbHidEnumerationExample extends BaseExample { + + public static void main(String[] args) throws HidException { + + UsbHidEnumerationExample example = new UsbHidEnumerationExample(); + example.executeExample(); + + } + + private void executeExample() throws HidException { + + printPlatform(); + + // Configure to use custom specification + HidServicesSpecification hidServicesSpecification = new HidServicesSpecification(); + // Use the v0.7.0 manual start feature to get immediate attach events + hidServicesSpecification.setAutoStart(false); + + // Get HID services using custom specification + HidServices hidServices = HidManager.getHidServices(hidServicesSpecification); + hidServices.addHidServicesListener(this); + + // Manually start the services to get attachment event + System.out.println(ANSI_GREEN + "Manually starting HID services." + ANSI_RESET); + hidServices.start(); + + System.out.println(ANSI_GREEN + "Enumerating attached devices..." + ANSI_RESET); + + // Provide a list of attached devices + for (HidDevice hidDevice : hidServices.getAttachedHidDevices()) { + System.out.println(hidDevice); + } + + waitAndShutdown(hidServices); + + } + +} diff --git a/src/test/java/org/hid4java/jna/HidDeviceInfoStructureTest.java b/src/test/java/org/hid4java/jna/HidDeviceInfoStructureTest.java new file mode 100644 index 0000000..6b48b0a --- /dev/null +++ b/src/test/java/org/hid4java/jna/HidDeviceInfoStructureTest.java @@ -0,0 +1,77 @@ +package org.hid4java.jna; + +import com.sun.jna.WString; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +class HidDeviceInfoStructureTest { + + @Test + void getFieldOrder() { + + // Arrange + HidDeviceInfoStructure testObject = new HidDeviceInfoStructure(); + List expectedFieldOrder = Arrays.asList( + "path", + "vendor_id", + "product_id", + "serial_number", + "release_number", + "manufacturer_string", + "product_string", + "usage_page", + "usage", + "interface_number", + "next" + ); + + // Act + List actualFieldOrder = testObject.getFieldOrder(); + + // Assert + assertEquals(11, actualFieldOrder.size()); + assertEquals(expectedFieldOrder, actualFieldOrder); + + } + + @Test + void show() { + + // Arrange + HidDeviceInfoStructure testObject = new HidDeviceInfoStructure(); + testObject.path = "path"; + testObject.vendor_id = 0x01; + testObject.product_id = 0x02; + testObject.serial_number = new WString("serial"); + testObject.release_number = 0x03; + testObject.manufacturer_string = new WString("manufacturer"); + testObject.product_string = new WString("product"); + testObject.usage_page = 0x04; + testObject.usage = 0x05; + testObject.interface_number = 0x06; + testObject.next = null; + + String expectedShow = "HidDevice\n" + + "\tpath:path>\n" + + "\tvendor_id: 1\n" + + "\tproduct_id: 2\n" + + "\tserial_number: serial>\n" + + "\trelease_number: 3\n" + + "\tmanufacturer_string: manufacturer>\n" + + "\tproduct_string: product>\n" + + "\tusage_page: 4\n" + + "\tusage: 5\n" + + "\tinterface_number: 6\n"; + + // Act + String actualShow = testObject.show(); + + // Assert + assertEquals(expectedShow, actualShow); + + } +} \ No newline at end of file diff --git a/src/test/java/org/hid4java/jna/WideStringBufferTest.java b/src/test/java/org/hid4java/jna/WideStringBufferTest.java new file mode 100644 index 0000000..66307d0 --- /dev/null +++ b/src/test/java/org/hid4java/jna/WideStringBufferTest.java @@ -0,0 +1,39 @@ +package org.hid4java.jna; + +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class WideStringBufferTest { + + @Test + void getFieldOrder() { + + // Arrange + WideStringBuffer testObject = new WideStringBuffer(new byte[] {0x61, 0x00, 0x62, 0x00, 0x63, 0x00}); + + // Act + List fieldOrder = testObject.getFieldOrder(); + + // Assert + assertEquals(1, fieldOrder.size()); + assertEquals("buffer", fieldOrder.get(0)); + + } + + @Test + void testToString() { + + // Arrange + WideStringBuffer testObject = new WideStringBuffer(new byte[] {0x61, 0x00, 0x62, 0x00, 0x63, 0x00}); + + // Act + String wchar_t = testObject.toString(); + + // Assert + assertEquals("abc", wchar_t); + + } +} \ No newline at end of file