-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlibusb.html
398 lines (329 loc) · 17.6 KB
/
libusb.html
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
<!DOCTYPE html>
<!--
| Generated by Apache Maven Doxia at 2014-03-19
| Rendered using Apache Maven Fluido Skin 1.3.0
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="Date-Revision-yyyymmdd" content="20140319" />
<meta http-equiv="Content-Language" content="en" />
<title>usb4java - Low-level (libusb) API</title>
<link rel="stylesheet" href="../css/apache-maven-fluido-1.3.0.min.css" />
<link rel="stylesheet" href="../css/site.css" />
<link rel="stylesheet" href="../css/print.css" media="print" />
<script type="text/javascript" src="../js/apache-maven-fluido-1.3.0.min.js"></script>
<link rel="SHORTCUT ICON" href="favicon.ico"/>
</head>
<body class="topBarDisabled">
<a href="http://github.com/usb4java">
<img style="position: absolute; top: 0; right: 0; border: 0; z-index: 10000;"
src="https://s3.amazonaws.com/github/ribbons/forkme_right_red_aa0000.png"
alt="Fork me on GitHub">
</a>
<div class="container-fluid">
<div id="banner">
<div class="pull-left">
<a href=".././" id="bannerLeft">
<img src="../images/logo.png" alt="usb4java"/>
</a>
</div>
<div class="pull-right"> </div>
<div class="clear"><hr/></div>
</div>
<div id="breadcrumbs">
<ul class="breadcrumb">
<li id="publishDate">Last Published: 2014-03-19</li>
<li class="divider">|</li> <li id="projectVersion">Version: 1.2.0</li>
<li class="divider">|</li> <li class="">
<a href=".././" title="usb4java">
usb4java</a>
</li>
<li class="divider ">/</li>
<li class="">Low-level (libusb) API</li>
<li class="pull-right"> <a href="http://libusb.info/" class="externalLink" title="libusb">
libusb</a>
</li>
<li class="divider pull-right">|</li>
<li class="pull-right"> <a href="http://javax-usb.sourceforge.net/" class="externalLink" title="javax-usb">
javax-usb</a>
</li>
</ul>
</div>
<div class="row-fluid">
<div id="leftColumn" class="span3">
<div class="well sidebar-nav">
<ul class="nav nav-list">
<li class="nav-header">usb4java</li>
<li>
<a href="../index.html" title="About">
<i class="none"></i>
About</a>
</li>
<li>
<a href="../quickstart/index.html" title="Quick start">
<i class="icon-chevron-down"></i>
Quick start</a>
<ul class="nav nav-list">
<li class="active">
<a href="#"><i class="none"></i>Low-level (libusb) API</a>
</li>
<li>
<a href="../quickstart/javax-usb.html" title="High-level (javax-usb) API">
<i class="none"></i>
High-level (javax-usb) API</a>
</li>
</ul>
</li>
<li>
<a href="../faq.html" title="FAQ">
<i class="none"></i>
FAQ</a>
</li>
<li>
<a href="../configuration.html" title="Configuration">
<i class="none"></i>
Configuration</a>
</li>
<li>
<a href="../nativelibs.html" title="Native libs">
<i class="none"></i>
Native libs</a>
</li>
<li class="nav-header">Project Documentation</li>
<li>
<a href="../project-info.html" title="Project Information">
<i class="icon-chevron-right"></i>
Project Information</a>
</li>
<li>
<a href="../project-reports.html" title="Project Reports">
<i class="icon-chevron-right"></i>
Project Reports</a>
</li>
</ul>
<hr class="divider" />
<div id="poweredBy">
<div class="clear"></div>
<div class="clear"></div>
<div class="clear"></div>
<a href="http://maven.apache.org/" title="Built by Maven" class="poweredBy">
<img class="builtBy" alt="Built by Maven" src="../images/logos/maven-feather.png" />
</a>
</div>
</div>
</div>
<div id="bodyColumn" class="span9" >
<div class="section">
<h2>Low-level (libusb) API <a name="Low-level_libusb_API"></a></h2>
<div class="section">
<h3>API design<a name="API_design"></a></h3>
<p>The low-level API of usb4java closely follows the C API of the <a class="externalLink" href="http://libusb.info/">libusb</a> project. All global functions and constants of <i>libusb</i> are defined as static members of the class <a href="../apidocs/org/usb4java/LibUsb.html">org.usb4java.LibUsb</a>. All structures of <i>libusb</i> are defined in separate classes which are named similar to the original struct names but without underscores, with camel-case names and with the <i>libusb</i> prefix removed. For example the struct <i>libusb_device_handle</i> is defined in the class <a href="../apidocs/org/usb4java/DeviceHandle.html">DeviceHandle</a>. Struct members are represented by static methods in the corresponding class.</p>
<p>The following notable differences exists between the <i>libusb 1.0 API</i> and the <i>usb4java</i> API:</p>
<ul>
<li><i>interface</i> in the configuration descriptor is named <i>iface</i> because <i>interface</i> is a reserved word in Java.</li>
<li><i>MaxPower</i> in the configuration descriptor is named <i>bMaxPower</i> to be compatible to the USB specification and because method names starting with upper-case letters are quite unusual in Java.</li>
<li>Whenever libusb expects a byte pointer and a length you have to use a direct Java NIO ByteBuffer instead.</li>
<li>Methods which are returning a string through a byte buffer which was passed as argument have additional simplified overloaded method equivalents which are returning a Java String directly.</li></ul></div>
<div class="section">
<h3>Initialization/deinitialization<a name="Initializationdeinitialization"></a></h3>
<p>Before using any usb4java functionality you must initialize libusb:</p>
<div>
<pre>Context context = new Context();
int result = LibUsb.init(context);
if (result != LibUsb.SUCCESS) throw new LibUsbException("Unable to initialize libusb.", result);</pre></div>
<p>Specifiying a context is optional. If your application only needs a single libusb context then you can specify <i>null</i> as context.</p>
<p>Before your application terminates you should deinitialize libusb:</p>
<div>
<pre>LibUsb.exit(context);</pre></div>
<p>Related libusb documentation:</p>
<ul>
<li><a class="externalLink" href="http://libusb.sourceforge.net/api-1.0/group__lib.html">Library initialization/deinitialization</a></li></ul></div>
<div class="section">
<h3>Finding USB devices<a name="Finding_USB_devices"></a></h3>
<p>Your program most likely wants to communicate with a specific device so first of all you have to find it. You have to get a list of all connected USB devices and then check the vendor/product ids. Here is a method which can be used for this purpose:</p>
<div>
<pre>public Device findDevice(short vendorId, short productId)
{
// Read the USB device list
DeviceList list = new DeviceList();
int result = LibUsb.getDeviceList(null, list);
if (result < 0) throw new LibUsbException("Unable to get device list", result);
try
{
// Iterate over all devices and scan for the right one
for (Device device: list)
{
DeviceDescriptor descriptor = new DeviceDescriptor();
result = LibUsb.getDeviceDescriptor(device, descriptor);
if (result != LibUsb.SUCCESS) throw new LibUsbException("Unable to read device descriptor", result);
if (descriptor.idVendor() == vendorId && descriptor.idProduct() == productId) return device;
}
}
finally
{
// Ensure the allocated device list is freed
LibUsb.freeDeviceList(list, false);
}
// Device not found
return null;
}</pre></div>
<p>In your application it might be a little bit more complicated. Maybe you have more than one device of the same type so you may need a list of devices. Or you have to identify your device by the product or vendor string descriptor instead of just checking the ID (In case you are using a shared vendor/product ID). But this example should bring you on the right track.</p>
<p>Related libusb documentation:</p>
<ul>
<li><a class="externalLink" href="http://libusb.sourceforge.net/api-1.0/group__dev.html">Device handling and enumeration</a></li></ul></div>
<div class="section">
<h3>Device handles<a name="Device_handles"></a></h3>
<p>For the real USB communication you must open a new device handle and you must close it again when you are finished communicating with the device. Example:</p>
<div>
<pre>DeviceHandle handle = new DeviceHandle();
int result = LibUsb.open(device, handle);
if (result != LibUsb.SUCCESS) throw new LibUsbException("Unable to open USB device", result);
try
{
// Use device handle here
}
finally
{
LibUsb.close(handle);
}</pre></div></div>
<div class="section">
<h3>Interfaces<a name="Interfaces"></a></h3>
<p>When you want to communicate with an interface or with endpoints of this interface then you have to claim it before using it and you have to release it when you are finished. Example:</p>
<div>
<pre>int result = LibUsb.claimInterface(handle, interfaceNumber);
if (result != LibUsb.SUCCESS) throw new LibUsbException("Unable to claim interface", result);
try
{
// Use interface here
}
finally
{
result = LibUsb.releaseInterface(handle, interfaceNumber);
if (result != LibUsb.SUCCESS) throw new LibUsbException("Unable to release interface", result);
}</pre></div>
<p>It is possible that the interface you want to communicate with is already used by a kernel driver. In this case you have to detach the kernel driver from the interface before claiming it. Example:</p>
<div>
<pre>// Check if kernel driver must be detached
boolean detach = LibUsb.hasCapability(LibUsb.CAP_SUPPORTS_DETACH_KERNEL_DRIVER)
&& LibUsb.kernelDriverActive(handle, interfaceNumber);
// Detach the kernel driver
if (detach)
{
int result = LibUsb.detachKernelDriver(handle, interfaceNumber);
if (result != LibUsb.SUCCESS) throw new LibUsbException("Unable to detach kernel driver", result);
}
// Communicate with the device
...
// Attach the kernel driver again if needed
if (detach)
{
int result = LibUsb.attachKernelDriver(handle, interfaceNumber);
if (result != LibUsb.SUCCESS) throw new LibUsbException("Unable to re-attach kernel driver", result);
}</pre></div>
<p>Please note that detaching kernel drivers is not supported on Windows.</p></div>
<div class="section">
<h3>Synchronous I/O<a name="Synchronous_IO"></a></h3>
<p>For the actual USB communication you usually have to create a direct byte buffer for the data to send or receive. </p>
<p>This examples sends 8 bytes to a claimed interface using a control transfer:</p>
<div>
<pre>ByteBuffer buffer = ByteBuffer.allocateDirect(8);
buffer.put(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 });
int transfered = LibUsb.controlTransfer(handle,
(byte) (LibUsb.REQUEST_TYPE_CLASS | LibUsb.RECIPIENT_INTERFACE),
(byte) 0x09, (short) 2, (short) 1, buffer, timeout);
if (transfered < 0) throw new LibUsbException("Control transfer failed", transfered);
System.out.println(transfered + " bytes sent");</pre></div>
<p>This example sends 8 bytes to endpoint 0x03 of the claimed interface using a bulk transfer:</p>
<div>
<pre>ByteBuffer buffer = ByteBuffer.allocateDirect(8);
buffer.put(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 });
IntBuffer transfered = IntBuffer.allocate(1);
int result = LibUsb.bulkTransfer(handle, 0x03, buffer, transfered, timeout);
if (result != LibUsb.SUCCESS) throw new LibUsbException("Control transfer failed", transfered);
System.out.println(transfered.get() + " bytes sent");</pre></div>
<p>Related libusb documentation:</p>
<ul>
<li><a class="externalLink" href="http://libusb.sourceforge.net/api-1.0/group__syncio.html">Synchronous device I/O</a></li></ul></div>
<div class="section">
<h3>Asynchronous I/O<a name="Asynchronous_IO"></a></h3>
<p>Asynchronous I/O is a little bit more complex than synchronous I/O. That's because libusb doesn't start its own thread to handle the actual background tasks. Instead you have to create you own worker thread like this:</p>
<div>
<pre>class EventHandlingThread extends Thread
{
/** If thread should abort. */
private volatile boolean abort;
/**
* Aborts the event handling thread.
*/
public void abort()
{
this.abort = true;
}
@Override
public void run()
{
while (!this.abort)
{
int result = LibUsb.handleEventsTimeout(null, 250000);
if (result != LibUsb.SUCCESS)
throw new LibUsbException("Unable to handle events", result);
}
}
}</pre></div>
<p>This simple thread implementation doesn't use a specific libusb context so it specified <tt>null</tt> as context. If you need contexts then you may want to pass it to the thread somehow. </p>
<p>The thread must be started after you have initialized libusb:</p>
<div>
<pre>EventHandlingThread thread = new EventHandlingThread();
thread.start();</pre></div>
<p>And it must be stopped before deinitializing libusb:</p>
<div>
<pre>thread.abort();
thread.join();</pre></div>
<p>So now with this thread running in the background you can use the asynchronous functions of libusb. If you don't like this thread and your program already has some kind of application loop then you can also simply call <tt>LibUsb.handleEventsTimeout(null, 0)</tt> inside the loop. This call returns immediately if there are no events to process.</p>
<p>An actual asynchronous transfer is submitted like this (In this case an outgoing bulk transfer to endpoint <i>0x03</i>):</p>
<div>
<pre>ByteBuffer buffer = BufferUtils.allocateByteBuffer(8);
buffer.put(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 });
Transfer transfer = LibUsb.allocTransfer();
LibUsb.fillBulkTransfer(transfer, handle, 0x03, buffer, callback, null, timeout);
int result = LibUsb.submitTransfer(transfer);
if (result != LibUsb.SUCCESS) throw new LibUsbException("Unable to submit transfer", result);</pre></div>
<p>The <tt>callback</tt> is an object implementing the <a href="../apidocs/org/usb4java/TransferCallback.html">TransferCallback</a> interface. Here is an example of such a callback:</p>
<div>
<pre>TransferCallback callback = new TransferCallback()
{
@Override
public void processTransfer(Transfer transfer)
{
System.out.println(transfer.actualLength() + " bytes sent");
LibUsb.freeTransfer(transfer);
}
};</pre></div>
<p>Related libusb documentation:</p>
<ul>
<li><a class="externalLink" href="http://libusb.sourceforge.net/api-1.0/group__asyncio.html">Asynchronous device I/O</a></li>
<li><a class="externalLink" href="http://libusb.sourceforge.net/api-1.0/mtasync.html">Multi-threaded applications and asynchronous I/O</a></li>
<li><a class="externalLink" href="http://libusb.sourceforge.net/api-1.0/io.html">Synchronous and asynchronous device I/O</a></li>
<li><a class="externalLink" href="http://libusb.sourceforge.net/api-1.0/group__poll.html">Polling and timing</a></li></ul></div>
<div class="section">
<h3>See also<a name="See_also"></a></h3>
<ul>
<li><a href="../apidocs/org/usb4java/package-summary.html">API documentation of usb4java</a></li>
<li><a class="externalLink" href="https://github.com/usb4java/usb4java-examples/">usb4java examples</a></li>
<li><a class="externalLink" href="http://libusb.sourceforge.net/api-1.0/">API documentation of libusb</a></li></ul></div></div>
</div>
</div>
</div>
<hr/>
<footer>
<div class="container-fluid">
<div class="row span12">Copyright © 2011-2014
<a href="http://usb4java.org/">usb4java Team</a>.
All Rights Reserved.
</div>
</div>
</footer>
</body>
</html>