用 JSR-80 API 访问 USB 设备的正常过程如下:
1.通过从 UsbHostManager 得到相应的 UsbServices 进行 Bootstrap。
2.通过 UsbServices 访问 root hub。在应用程序中 root hub 就是一个 UsbHub。
3.获得连接到 root hub 的 UsbDevices 清单。遍历所有低级 hub 以找到正确的 UsbDevice。
4.用控制消息(UsbControlIrp)与 UsbDevice 直接交互,或者从 UsbDevice 的相应 UsbConfiguration 中要求一个 UsbInterface 并与该 UsbInterface 上可用的 UsbEndpoint 进行 I/O。
5.如果一个 UsbEndpoint 用于进行 I/O,那么打开与它关联的 UsbPipe。通过这个 UsbPipe 可以同步或者异步提交上行数据(从 USB 设备到主计算机)和下行数据(从主计算机到 USB 设备)。
6.当应用程序不再需要访问该 UsbDevice 时,关闭这个 UsbPipe 并释放相应的 UsbInterface。
在清单 3 中,我们用 JSR-80 API 获得 USB 系统的内容。这个程序递归地遍历 USB 系统上的所有 USB hub 并找出连接到主机计算机上的所有 USB 设备。这段代码对应于上述步骤 1 到步骤 3。
清单 3. 用 JSR-80 API 获得 USB 系统的内容
import javax.usb.*;
import java.util.List;
public class TraverseUSB
{
public static void main(String argv[])
{
try
{
// Access the system USB services, and access to the root
// hub. Then traverse through the root hub.
UsbServices services = UsbHostManager.getUsbServices();
UsbHub rootHub = services.getRootUsbHub();
traverse(rootHub);
} catch (Exception e) {}
}
public static void traverse(UsbDevice device)
{
if (device.isUsbHub())
{
// This is a USB Hub, traverse through the hub.
List attachedDevices = ((UsbHub) device).getAttachedUsbDevices();
for (int i=0; i {
traverse((UsbDevice) attachedDevices.get(i));
}
}
else
{
// This is a USB function, not a hub.
// Do something.
}
}
}
清单 4 展示了在应用程序成功地找到 Device 后,如何与 Interface 和 EndPoint 进行 I/O。这段代码还可以修改为进行所有四种数据传输类型的 I/O。它对应于上述步骤 4 到步骤 6。
清单 4. 用 JSR-80 API 进行 I/O
public static void testIO(UsbDevice device)
{
try
{
// Access to the active configuration of the USB device, obtain
// all the interfaces available in that configuration.
UsbConfiguration config = device.getActiveUsbConfiguration();
List totalInterfaces = config.getUsbInterfaces();
// Traverse through all the interfaces, and access the endpoints
// available to that interface for I/O.
for (int i=0; i {
UsbInterface interf = (UsbInterface) totalInterfaces.get(i);
interf.claim();
List totalEndpoints = interf.getUsbEndpoints();
for (int j=0; j {
// Access the particular endpoint, determine the direction
// of its data flow, and type of data transfer, and open the
// data pipe for I/O.
UsbEndpoint ep = (UsbEndpoint) totalEndpoints.get(i);
最新相关文章
发表评论