forked from gary-rowe/hid4java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHidApi.java
More file actions
465 lines (387 loc) · 14.4 KB
/
HidApi.java
File metadata and controls
465 lines (387 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
/*
* 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.Platform;
import com.sun.jna.Pointer;
import com.sun.jna.WString;
/**
* <p>JNA utility class to provide the following to low level operations:</p>
* <ul>
* <li>Direct access to the HID API library through JNA</li>
* </ul>
*
* @since 0.0.1
*
*/
public class HidApi {
/**
* Default length for wide string buffer
*/
private static int WSTR_LEN = 512;
/**
* Error message if device is not initialised
*/
private static final String DEVICE_NULL = "Device not initialised";
/**
* Device error code
*/
private static final int DEVICE_ERROR = -2;
/**
* The HID API library
*/
private static final HidApiLibrary hidApiLibrary = HidApiLibrary.INSTANCE;
/**
* <p>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.</p>
*
* <p>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.</p>
*
* <p>See https://github.com/gary-rowe/hid4java/issues/36 for more information.</p>
*/
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;
}
}
}
/**
* <p>Open a HID device using a Vendor ID (VID), Product ID (PID) and optionally a serial number</p>
*
* @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) {
// Attempt to open the device
Pointer p = hidApiLibrary.hid_open(
(short) vendor,
(short) product,
serialNumber == null ? null : new WString(serialNumber)
);
if (p != null) {
// Wrap the structure
return new HidDeviceStructure(p);
}
return null;
}
/**
* <p>Initialise the HID API library</p>
* <p>Required if the consuming application is using multiple threads
* containing device handles.</p>
*/
public static void init() {
hidApiLibrary.hid_init();
}
/**
* <p>Finalise the HID API library</p>
*/
public static void exit() {
hidApiLibrary.hid_exit();
}
/**
* <p>Open a HID device by its path name</p>
*
* @param path The device path (e.g. "0003:0002:00")
*
* @return The device or null if not found
*/
public static HidDeviceStructure open(String path) {
Pointer p = hidApiLibrary.hid_open_path(path);
return (p == null ? null : new HidDeviceStructure(p));
}
/**
* <p>Close a HID device</p>
*/
public static void close(HidDeviceStructure device) {
if (device != null) {
hidApiLibrary.hid_close(device.ptr());
}
}
/**
* <p>Enumerate the attached HID devices</p>
*
* @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) {
return hidApiLibrary.hid_enumerate((short) vendor, (short) product);
}
/**
* <p>Free an enumeration linked list</p>
*
* @param list The list to free
*/
public static void freeEnumeration(HidDeviceInfoStructure list) {
hidApiLibrary.hid_free_enumeration(list.getPointer());
}
/**
* @return A string describing the last error which occurred
*/
public static String getLastErrorMessage(HidDeviceStructure device) {
if (device == null) {
return DEVICE_NULL;
}
Pointer p = hidApiLibrary.hid_error(device.ptr());
return p == null ? null : new WideStringBuffer(p.getByteArray(0, WSTR_LEN)).toString();
}
/**
* @param device The HID device
*
* @return The device manufacturer string
*/
public static String getManufacturer(HidDeviceStructure device) {
if (device == null) {
return DEVICE_NULL;
}
WideStringBuffer wStr = new WideStringBuffer(WSTR_LEN);
hidApiLibrary.hid_get_manufacturer_string(device.ptr(), wStr, WSTR_LEN);
return wStr.toString();
}
/**
* @param device The HID device
*
* @return The device product ID
*/
public static String getProductId(HidDeviceStructure device) {
if (device == null) {
return DEVICE_NULL;
}
WideStringBuffer wBuffer = new WideStringBuffer(WSTR_LEN);
hidApiLibrary.hid_get_product_string(device.ptr(), wBuffer, WSTR_LEN);
return wBuffer.toString();
}
/**
* @param device The HID device
*
* @return The device serial number
*/
public static String getSerialNumber(HidDeviceStructure device) {
if (device == null) {
return DEVICE_NULL;
}
WideStringBuffer wBuffer = new WideStringBuffer(WSTR_LEN);
hidApiLibrary.hid_get_serial_number_string(device.ptr(), wBuffer, WSTR_LEN);
return wBuffer.toString();
}
/**
* <p>Set the device handle to be non-blocking</p>
*
* <p>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</p>
*
* <p>Non-blocking can be turned on and off at any time</p>
*
* @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) {
return device != null && 0 == hidApiLibrary.hid_set_nonblocking(device.ptr(), nonBlocking ? 1 : 0);
}
/**
* <p>Read an Input report from a HID device</p>
* <p>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.</p>
*
* @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.
*/
public static int read(HidDeviceStructure device, byte[] buffer) {
if (device == null || buffer == null) {
return DEVICE_ERROR;
}
WideStringBuffer wBuffer = new WideStringBuffer(buffer);
return hidApiLibrary.hid_read(device.ptr(), wBuffer, wBuffer.buffer.length);
}
/**
* <p>Read an Input report from a HID device with timeout</p>
*
* @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.
*/
public static int read(HidDeviceStructure device, byte[] buffer, int timeoutMillis) {
if (device == null || buffer == null) {
return DEVICE_ERROR;
}
WideStringBuffer wBuffer = new WideStringBuffer(buffer);
return hidApiLibrary.hid_read_timeout(device.ptr(), wBuffer, buffer.length, timeoutMillis);
}
/**
* <p>Get a feature report from a HID device</p>
*
* <h3>HID API notes</h3>
*
* <p>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]</p>
* <p>This method handles all the wide string and array manipulation for you</p>
*
* @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) {
if (device == null || data == null) {
return DEVICE_ERROR;
}
// Create a large buffer
WideStringBuffer report = new WideStringBuffer(WSTR_LEN);
report.buffer[0] = reportId;
int res = hidApiLibrary.hid_get_feature_report(device.ptr(), report, data.length + 1);
if (res == -1) {
return res;
}
// Avoid index out of bounds exception
System.arraycopy(report.buffer, 1, data, 0, res > data.length ? data.length : res);
return res;
}
/**
* <p>Send a Feature report to the device using a simplified interface</p>
*
* <h3>HID API notes</h3>
*
* <p>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</p>
* <p>Since the Report ID is mandatory, calls to hid_send_feature_report() will always contain one more byte than
* the report contains.</p>
*
* <p>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.</p>
*
* <p>This method handles all the array manipulation for you</p>
*
* @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) {
if (device == null || data == null) {
return DEVICE_ERROR;
}
WideStringBuffer report = new WideStringBuffer(data.length + 1);
report.buffer[0] = reportId;
System.arraycopy(data, 0, report.buffer, 1, data.length);
return hidApiLibrary.hid_send_feature_report(device.ptr(), report, report.buffer.length);
}
/**
* <p>Write an Output report to a HID device using a simplified interface</p>
*
* <h3>HID API notes</h3>
*
* <p>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 <code>hid_write()</code> will always contain one more byte than the report
* contains.</p>
*
* <p>For example, if a hid report is 16 bytes long, 17 bytes must be passed to <code>hid_write()</code>,
* 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</p>
*
* <p><code>hid_write()</code> 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)</p>
*
* @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) {
// Fail fast
if (device == null || data == null) {
return DEVICE_ERROR;
}
// Precondition checks
if (data.length < len) {
len = data.length;
}
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);
}
}
return hidApiLibrary.hid_write(device.ptr(), report, report.buffer.length);
}
/**
* <p>Get a string from a HID device, based on its string index</p>
*
* @param device The HID device
* @param idx The index
*
* @return The string
*/
public static String getIndexedString(HidDeviceStructure device, int idx) {
if (device == null) {
return DEVICE_NULL;
}
WideStringBuffer wStr = new WideStringBuffer(WSTR_LEN);
int res = hidApiLibrary.hid_get_indexed_string(device.ptr(), idx, wStr, WSTR_LEN);
return res == -1 ? null : wStr.toString();
}
}