用 jUSB API 访问一台 USB 设备的正常过程如下:
·通过从 HostFactory 得到 USB Host 进行 Bootstrap。
·从 Host 访问 USB Bus,然后从这个 Bus 访问 USB root hub(即 USB Device)。
·得到 hub 上可用的 USB 端口数量,遍历所有端口以找到正确的 Device。
·访问附加到特定端口上的 USB Device。可以用一台 Device 的 PortIdentifier 直接从 Host 访问它,也可以通过从 root hub 开始遍历 USB Bus 找到它。
·用 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()); } } |
上一页 [1] [2] [3] [4] [5] [6] [7] 下一页

【责编:Ken】