0

我有以下例程,它是在 windows 中运行的usb4java API 中访问串行端口的入口点。任何想法可能是错误的。

import javax.comm.*
public class SimpleJSComRead 
    public static void main(String[] args) {
      portList = CommPortIdentifier.getPortIdentifiers();
      if (portList.nextElement()==null) System.out.println("Is Null");
  }

}

同时,这可以使用jssc。我可以通过这个接口读取有效数据。

import jssc.SerialPort;
import jssc.SerialPortException;

public class SimpleJSComRead {

  public static void main(String[] args) {
      SerialPort serialPort = new SerialPort("COM6");
      try { serialPort.openPort();
      } catch (SerialPortException e) {
          e.printStackTrace();
      }
      if (serialPort.isOpened()) System.out.println("opened successfully");
      try { serialPort.closePort();
      } catch (SerialPortException e) {
          e.printStackTrace();
      }
    }
}
4

1 回答 1

0

我追查到 javax.comm 库没有完全实现支持的事实。我觉得奇怪的是,像从串行端口读取这样的基本功能对于 Java 来说应该是一项艰巨的任务,而托管 Web 应用程序却被各种 API 复制。我希望 Python 和 C++ 很好地支持串行通信,因为科学界更多地使用它们。

我发现的另一个解决方案是利用 RXTX API... onetwo 。该过程涉及下载压缩分发并将 dll 和 jar 提取到文件系统上的某个库站点。然后声明对Jar文件的依赖。例如在 Gradle 中

compile files( 'C:/..path../lib/jars/RXTXcomm.jar').

并设置 dll 库路径并加载 dll

System.setProperty("java.library.path", "C:/..path../lib/dlls_x64")
System.loadLibrary("rxtxSerial")

最后,串口 API 不在 javax.comm 包中,而是在 gnu.io 包中。

import gnu.io.CommPortIdentifier
import io.FileMgr

//this one is based on RXTX and dlls are in library (gnu.io)
fun main(args: Array<String>) {
  FileMgr.setDllLibraryPath("C:/..path../lib/dlls_x64")
  System.loadLibrary("rxtxSerial")

  val portList = CommPortIdentifier.getPortIdentifiers()

  while (portList.hasMoreElements()) {
    val x = portList.nextElement() as CommPortIdentifier
    println("Port Name = " + x.name + ", type= " + x.portType)

  }
  if (portList.nextElement() == null) println("Is Null")
}

fun setDllLibraryPath(resourceStr: String) {
  try {
    System.setProperty("java.library.path", resourceStr)
    //System.setProperty("java.library.path", "/lib/x64");//for example

    val fieldSysPath = 
ClassLoader::class.java.getDeclaredField("sys_paths")
    fieldSysPath.isAccessible = true
    fieldSysPath.set(null, null)//next time path is accessed, the new path 
will be imported
  } catch (ex: Exception) {
    ex.printStackTrace()
    throw RuntimeException(ex)
  }
}
于 2018-09-13T16:45:14.140 回答