新客网WWW.XKER.COM:致力做中国最专业的网络学院!
学院: 操作系统 - 网络应用 - 服务器 - 网络安全 - 工具软件 - 办公软件 - Web开发 - 数据库 - 网页设计 - 图形图像 - 媒体动画 - 硬件学堂 - 存储频道 - QQ专区
您的位置:首页 > 软件开发 > JAVA > 正文:在Java应用程序中访问USB设备

在Java应用程序中访问USB设备

新客网 XKER.COM 2006-05-16 来源: 收藏本文

UsbEndpointDescriptor USB 端点描述符的接口
UsbHub USB hub 的接口
UsbInterface USB 接口的接口
UsbInterfaceDescriptor USB 接口描述符的接口
UsbPipe USB 管道的接口
UsbPort USB 端口的接口
UsbServices  javax.usb实现的接口
UsbHostManager  javax.usb 的入口点


  用 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);

收藏】 【评论】 【推荐】 【投稿】 【打印】 【关闭
发表评论
要记得去论坛讨论,点击注册新会员匿名评论
评论内容:不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
阅读排行
随机推荐
实用信息推荐