java使用usb4java连接USB 实现数据通讯

                            java使用usb4java连接USB 实现数据通讯 

最近公司接到一个项目,需要连接usb获取/写入数据到数显盒。 查阅了很多资料,发现可以使用usb4java 来实现,然后我就来填坑了!  po代码不易,请各位小伙伴多多关注!

先上代码,代码我并没有优化,有可能有很多函数没有用到但是还写在上面,复制的时候删掉即可!只希望对大家有所帮助!

首先你的POM里需要这个 包 


   org.usb4java
   usb4java-javax
   1.2.0

其次你需要在你的项目中建立一个 javax.usb.properties 静态文件 内容就一句:

javax.usb.services = org.usb4java.javax.Services  
写好保存即可。

 

java使用usb4java连接USB 实现数据通讯_第1张图片

 

 

前期准备就完成了!

创建一个java类 xxxx.java

写一个连接方法:

/**
*
* TODO: 连接设备
*@author Zck
*@date 2020/5/20 15:48
*
*/
public Map linkDevice() throws Exception{

    Map mainMap = new HashMap<>();

    mainMap.put("code", usbConnectCSS.USB_CONNECT_TRUE.getCode());

    UsbDevice device = null;
   //去搜索特定的设备!需要用到设备的VID PID  自己百度怎么看!
    if (device == null) {

        device = findDevice(UsbHostManager.getUsbServices()
                .getRootUsbHub());

    }

    if (device == null) {

        mainMap.put("code", usbConnectCSS.USB_CONNECT_NOT_HAVE.getCode());
        mainMap.put("msg", usbConnectCSS.USB_CONNECT_NOT_HAVE.getInfo());
        System.out.println("设备未找到!");
        return mainMap;

    }
    UsbConfiguration configuration = device.getActiveUsbConfiguration();

    UsbInterface iface = null;

    if (configuration.getUsbInterfaces().size() > 0) {
        iface = configuration.getUsbInterface((byte) 0);
    } else {
        //未知错误 没有源码读不懂
        mainMap.put("code",usbConnectCSS.USB_CONNECT_NOT_KNOW.getCode());
        mainMap.put("msg", usbConnectCSS.USB_CONNECT_NOT_KNOW.getInfo());

        return mainMap;
    }
    //todo:claim连接必须打开 claim  。这里 如果设备是连接状态我们把他关闭。因为我这个项目是点对点透传txt
    if (iface.isClaimed()){
        iface.release();

    }
//再开启!
    iface.claim(new UsbInterfacePolicy()
    {
        @Override
        public boolean forceClaim(UsbInterface usbInterface)
        {
            return true;
        }
    });

    /*CacheUtils.put("iface", iface);*/
    mainMap.put("iface", iface);
    return mainMap;
}

 

/**
 * @Description 搜索特定设备
 **/
public UsbDevice findDevice(UsbHub hub)
{
    UsbDevice device = null;
    List list = (List) hub.getAttachedUsbDevices();
    for (int i = 0;i 
  

 

/**
*
* TODO: 通讯入口
*@author Zck
*@date 2020/5/21 10:29
*map参数 中包含 拼装头(类型,读写,等) data:数据主体
*/
public   static  Map communicate(Map map){
    try {
        /*String data = String.valueOf(map.get("data"));
        map.remove("data");*/
        /**获取usb通讯通道*/
        Map returnMap = new UsbUntil().useUsb(map);

        /**如果code不是连接成功返回错误代码*/
        if (!returnMap.get("code").equals(usbConnectCSS.USB_CONNECT_TRUE.getCode())){
            return returnMap;
        }

        /**连接成功,获取sendUsbPipe*/
        UsbPipe sendUsbPipe = (UsbPipe)returnMap.get("sendUsbPipe");
        
        /**校验sendUsbPipe是否为空*/
        if (sendUsbPipe != null) {
            /**可能有多个包用list装载*/
           // List list = new ArrayList<>();

            /**先判断读还是写,大家可以无视这些判断,这是我自己的业务逻辑*/
            if (map.get("ReadOrWrite").equals(UsbTypeConstants.WRITE.getCode())){
                //时间不会超过 64字节所以不用考虑包数
                if (map.get("type").equals(UsbTypeConstants.WRITE_TYPE_TIME.getCode())){
                    /**不为空new一个64位字节*/
                    byte[] buff = new byte[64];
                    buff[0] = (byte)0xAA;

                   /**16进制数据 64位发送一次,这里我删除了一点我的逻辑代码。 把buff函数换成你要发送的16进制数据包就行了*/
                    Log.info("进入sendMassge发送数据");
                    sendMassge(sendUsbPipe, buff);

                } 
            }


        } else {
            returnMap.put("code", usbConnectCSS.USB_CONNECT_NOT_KNOW.getCode());
            returnMap.put("msg", usbConnectCSS.USB_CONNECT_NOT_KNOW.getInfo());
        }

        return returnMap;

    } catch (Exception e) {
        CacheUtils.remove("xxxxx","routeData");
        CacheUtils.remove("thisRouteDataFlag","thisRouteDataFlag");
        CacheUtils.remove("xxxxxx","switchData");
        CacheUtils.remove("thisSwitchDataFlag","thisSwitchDataFlag");
        e.printStackTrace();
        Map eroMap = new HashMap<>();
        eroMap.put("code",usbConnectCSS.USB_CONNECT_NOT_OPEN.getCode());
        eroMap.put("msg",usbConnectCSS.USB_CONNECT_NOT_OPEN.getInfo());
        return eroMap;
        }

} 
  

 

public  Map useUsb(Map map) throws Exception{
    //连接设备
    Map ifaceMap = new HashMap<>();

        ifaceMap = linkDevice();
    UsbInterface iface = (UsbInterface)ifaceMap.get("iface");
     //大家可以无视判断和 map里的参数
        if (!ifaceMap.get("code").equals(usbConnectCSS.USB_CONNECT_TRUE.getCode())){
            return ifaceMap;
        }






    if (iface == null) {
        ifaceMap.put("code",usbConnectCSS.USB_CONNECT_IS_NULL.getCode());
        ifaceMap.put("msg",usbConnectCSS.USB_CONNECT_IS_NULL.getInfo());
        return ifaceMap;
    }
    UsbEndpoint receivedUsbEndpoint,sendUsbEndpoint;

    sendUsbEndpoint = (UsbEndpoint)iface.getUsbEndpoints().get(0);
    if (!sendUsbEndpoint.getUsbEndpointDescriptor().toString().contains("OUT")) {
        receivedUsbEndpoint = sendUsbEndpoint;
        sendUsbEndpoint = (UsbEndpoint)iface.getUsbEndpoints().get(1);
    } else {
        receivedUsbEndpoint = (UsbEndpoint)iface.getUsbEndpoints().get(1);
    }
    //发送:
    UsbPipe sendUsbPipe =  sendUsbEndpoint.getUsbPipe();
    //打开发送通道
    if (sendUsbPipe.isOpen()){
        sendUsbPipe.close();
        sendUsbPipe.open();
      

    } else {
        sendUsbPipe.open();
    }

    //接收
     final UsbPipe receivedUsbPipe =  receivedUsbEndpoint.getUsbPipe();
  
//打开接收通道
    if (!receivedUsbPipe.isOpen()){
      
        receivedUsbPipe.open();
    }
  
    Thread th=  new Thread(new Runnable() {
        public  void run() {
            try {
          //这里不需要map参数,因为业务问题所以我加入了map
                receivedMassge(receivedUsbPipe,map);


            } catch (Exception e) {


                e.printStackTrace();

                return;
            } finally {
                receivedUsbPipe.abortAllSubmissions();
                try {
                    receivedUsbPipe.close();
                }catch (Exception e){

                }
            }

        }
    });
    th.start();
    if (sendUsbPipe.isOpen()){
        ifaceMap.put("sendUsbPipe", sendUsbPipe);

    }
   //这里我监听了线程是否跑完了,所以 map里放了 th
    ifaceMap.put("th",th);
    return ifaceMap;
}
public int syncSubmit(final byte[] data,UsbPipe usbPipe) throws UsbException
{
    final UsbIrp irp = usbPipe.asyncSubmit(data);
   //这里一定要注意,若果你设置的接收时间太短了,你硬件还没反应过来通讯就结束了。建议设置为15秒。
    irp.waitUntilComplete(30000);
    if (irp.isUsbException()) throw irp.getUsbException();
    return irp.getActualLength();
}

 

public  void  receivedMassge(UsbPipe usbPipe,Map map) throws Exception{
//无视这个map
byte[] b = new byte[64];
int length = 0;
length = syncSubmit(b,usbPipe);//返回数据的长度,我们规定的协议是64位,这里我没有写死循环来监听到底传送完了没有,因为我们的模式是我发一个数据,盒子返回给我一个数据
//这里就是硬件返回给你的数据自己进行10进制处理吧!
for (int i = 0; i < length; i++) {
    System.out.print(Byte.toUnsignedInt(b[i])+" ");
}
}

你可能感兴趣的:(java,usb对接,JAVA)