用 jUSB API 访问一台 USB 设备的正常过程如下:
1.通过从 HostFactory 得到 USB Host 进行 Bootstrap。
2.从 Host 访问 USB Bus,然后从这个 Bus 访问 USB root hub(即 USB Device)。
3.得到 hub 上可用的 USB 端口数量,遍历所有端口以找到正确的 Device。
4.访问附加到特定端口上的 USB Device。可以用一台 Device 的 PortIdentifier 直接从 Host 访问它,也可以通过从 root hub 开始遍历 USB Bus 找到它。
5.用 ControlMessage 与该 Device 直接交互,或者从该 Device 的当前 Configuration 中要求一个 Interface,并与该 Interface 上可用的 Endpoint 进行 I/O 。
清单 1 展示了如何用 jUSB API 获得 USB 系统中的内容。这个程序编写为只是查看 root hub 上可用的 USB 设备,但是很容易将它改为遍历整个 USB 树。这里的逻辑对应于上述步骤 1 到步骤 4。
清单 1. 用 jUSB API 获得 USB 系统的内容
import usb.core.*;
public class ListUSB { public static void main(String[] args) { try { // Bootstrap by getting the USB Host from the HostFactory. Host host = HostFactory.getHost();
// Obtain a list of the USB buses available on the Host. Bus[] bus = host.getBusses(); int total_bus = bus.length;
// Traverse through all the USB buses. for (int i=0; i { // Access the root hub on the USB bus and obtain the // number of USB ports available on the root hub. Device root = bus[i].getRootHub(); int total_port = root.getNumPorts();
// Traverse through all the USB ports available on the // root hub. It should be mentioned that the numbering // starts from 1, not 0. for (int j=1; j<=total_port; j++) { // Obtain the Device connected to the port. Device device = root.getChild(j); if (device != null) { // USB device available, do something here. } } } } catch (Exception e) { System.out.println(e.getMessage()); } }
清单 2 展示了在应用程序成功地找到了 Device 的条件下,如何与 Interface 和 EndPoint 进行批量 I/O。 这个代码段也可以修改为执行控制或者中断 I/O。它对应于上述步骤 5。
清单 2. 用 jUSB API 执行批量 I/O
if (device != null) { // Obtain the current Configuration of the device and the number of // Interfaces available under the current Configuration. Configuration config = device.getConfiguration(); int total_interface = config.getNumInterfaces();
// Traverse through the Interfaces for (int k=0; k { // Access the currently Interface and obtain the number of // endpoints available on the Interface. Interface itf = config.getInterface(k, 0); int total_ep = itf.getNumEndpoints();
// Traverse through all the endpoints. for (int l=0; l { // Access the endpoint, and obtain its I/O type. Endpoint ep = itf.getEndpoint(l); String io_type = ep.getType(); boolean input = ep.isInput();
// If the endpoint is an input endpoint, obtain its // InputStream and read in data. if (input) { InputStream in; in = ep.getInputStream(); // Read in data here in.close(); } // If the Endpoint is and output Endpoint, obtain its // OutputStream and write out data. else { OutputStream out; out = ep.getOutputStream(); // Write out data here. out.close(); } } } } jUSB 项目在 2000年 6月到 2001年 2月期间非常活跃。该 API 的最新的版本 0.4.4发表于 2001年 2月 14日。从那以后只提出了很少的改进,原因可能是 IBM 小组成功地成为了 Java 语言的候选扩展标准。不过,基于 jUSB 已经开发出一些第三方应用程序,包括 JPhoto 项目(这是一个用 jUSB 连接到数码照相机的应用程序)和 jSyncManager 项目(这是一个用 jUSB 与使用 Palm 操作系统的 PDA 同步的应用程序)。
|