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:
+```
+
* High level wrapper to provide the following to API consumers: - *
+ * *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
- *
* 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
- *
+ * 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
- *
+ * 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
- *
* 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
- *
* 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 + *Manager to provide the following to HID services:
+ * Manager to provide the following to HID services: *Caught exception to provide the following to API consumers:
+ * Caught exception to provide the following to API consumers: *Factory to provide the following to API consumers:
+ * Factory to provide the following to API consumers: *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: *signal11/hidapi via JNARequires 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 ListInterface to provide the following to API consumers:
+ * Interface to provide the following to API consumers: *Specification to provide the following to API consumers:
+ * Specification to provide the following to API consumers: *Event to provide the following to API consumers:
+ * Event to provide the following to API consumers: *HID services listener list
+ * HID services listener list * * @since 0.0.1 - * Â */ public class HidServicesListenerList { @@ -97,11 +96,11 @@ protected final ListFire 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)}. + *JNA utility class to provide the following to low level operations:
+ * JNA utility class to provide the following to low level operations: *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. + *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 + *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
- * - *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 + *Send a Feature report to the device using a simplified interface
- * - *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. + *Write an Output report to a HID device using a simplified interface
- * - *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)
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 + *[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. + *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 ListLow 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 Listhidapi 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 + *
+ * 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