forked from gary-rowe/hid4java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHidDeviceManager.java
More file actions
310 lines (250 loc) · 8.71 KB
/
HidDeviceManager.java
File metadata and controls
310 lines (250 loc) · 8.71 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
/*
* 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;
import org.hid4java.event.HidServicesListenerList;
import org.hid4java.jna.HidApi;
import org.hid4java.jna.HidDeviceInfoStructure;
import java.util.*;
/**
* <p>Manager to provide the following to HID services:</p>
* <ul>
* <li>Access to the underlying JNA and hidapi library</li>
* <li>Device attach/detach detection</li>
* </ul>
*
* @since 0.0.1
*
*/
class HidDeviceManager {
/**
* The HID services specification providing configuration parameters
*/
private final HidServicesSpecification hidServicesSpecification;
/**
* The currently attached devices keyed on ID
*/
private final Map<String, HidDevice> attachedDevices = Collections.synchronizedMap(new HashMap<String, HidDevice>());
/**
* HID services listener list
*/
private final HidServicesListenerList listenerList;
/**
* 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
*/
private Thread scanThread = null;
/**
* Constructs a new device manager
*
* @param listenerList The HID services providing access to the event model
* @param hidServicesSpecification Provides various parameters for configuring HID services
*
* @throws HidException If USB HID initialization fails
*/
HidDeviceManager(HidServicesListenerList listenerList, HidServicesSpecification hidServicesSpecification) throws HidException {
this.listenerList = listenerList;
this.hidServicesSpecification = hidServicesSpecification;
// Attempt to initialise and fail fast
try {
HidApi.init();
} catch (Throwable t) {
// Typically this is a linking issue with the native library
throw new HidException("Hidapi did not initialise: " + t.getMessage(), t);
}
}
/**
* 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
* 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)
*/
public void start() {
// Check for previous start
if (this.isScanning()) {
return;
}
// Perform a one-off scan to populate attached devices
scan();
// Ensure we have a scan thread available
configureScanThread(getScanRunnable());
}
/**
* Stop the scan executor and block until terminated (max 5 seconds)
*/
public synchronized void stop() {
if (isScanning()) {
scanThread.interrupt();
}
}
/**
* 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<String> removeList = new ArrayList<String>();
List<HidDevice> attachedHidDeviceList = getAttachedHidDevices();
for (HidDevice attachedDevice : attachedHidDeviceList) {
if (!this.attachedDevices.containsKey(attachedDevice.getId())) {
// Device has become attached so add it but do not open
attachedDevices.put(attachedDevice.getId(), attachedDevice);
// Fire the event on a separate thread
listenerList.fireHidDeviceAttached(attachedDevice);
}
}
for (Map.Entry<String, HidDevice> entry : attachedDevices.entrySet()) {
String deviceId = entry.getKey();
HidDevice hidDevice = entry.getValue();
if (!attachedHidDeviceList.contains(hidDevice)) {
// Keep track of removals
removeList.add(deviceId);
// Fire the event on a separate thread
listenerList.fireHidDeviceDetached(this.attachedDevices.get(deviceId));
}
}
if (!removeList.isEmpty()) {
// Update the attached devices map
this.attachedDevices.keySet().removeAll(removeList);
}
}
/**
* @return True if the scan thread is running, false otherwise.
*/
public boolean isScanning() {
return scanThread != null && scanThread.isAlive();
}
/**
* @return A list of all attached HID devices
*/
public List<HidDevice> getAttachedHidDevices() {
List<HidDevice> hidDeviceList = new ArrayList<HidDevice>();
final HidDeviceInfoStructure root;
try {
// Use 0,0 to list all attached devices
// This comes back as a linked list from hidapi
root = HidApi.enumerateDevices(0, 0);
} catch (Throwable e) {
// Could not initialise hidapi (possibly an unknown platform)
// Prevent further scanning as a fail safe
stop();
// Inform the caller that something serious has gone wrong
throw new HidException("Unable to start HidApi: " + e.getMessage());
}
if (root != null) {
HidDeviceInfoStructure hidDeviceInfoStructure = root;
do {
// Wrap in HidDevice
hidDeviceList.add(new HidDevice(hidDeviceInfoStructure, this));
// Move to the next in the linked list
hidDeviceInfoStructure = hidDeviceInfoStructure.next();
} while (hidDeviceInfoStructure != null);
// Dispose of the device list to free memory
HidApi.freeEnumeration(root);
}
return hidDeviceList;
}
/**
* Indicate that a device write has occurred which may require a change in scanning frequency
*/
public void afterDeviceWrite() {
if (ScanMode.SCAN_AT_FIXED_INTERVAL_WITH_PAUSE_AFTER_WRITE == hidServicesSpecification.getScanMode() && isScanning()) {
stop();
// Ensure we have a new scan executor service available
configureScanThread(getScanRunnable());
}
}
/**
* Configures the scan executor service to allow recovery from stop or pause
*/
private synchronized void configureScanThread(Runnable scanRunnable) {
if (isScanning()) {
stop();
}
// Require a new one
scanThread = new Thread(scanRunnable);
scanThread.setDaemon(true);
scanThread.setName("hid4java Device Scanner");
scanThread.start();
}
private synchronized Runnable getScanRunnable() {
final int scanInterval = hidServicesSpecification.getScanInterval();
final int pauseInterval = hidServicesSpecification.getPauseInterval();
switch (hidServicesSpecification.getScanMode()) {
case NO_SCAN:
return new Runnable() {
@Override
public void run() {
// Do nothing
}
};
case SCAN_AT_FIXED_INTERVAL:
return new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(scanInterval);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
scan();
}
}
};
case SCAN_AT_FIXED_INTERVAL_WITH_PAUSE_AFTER_WRITE:
return new Runnable() {
@Override
public void run() {
// Provide an initial pause
try {
Thread.sleep(pauseInterval);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
}
// Switch to continuous running
while (true) {
try {
Thread.sleep(scanInterval);
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
break;
}
scan();
}
}
};
default:
return null;
}
}
}