/** * Discovering available comm ports * Created by liuweiguo on 2018/4/10. */ publicclassDiscoveringPorts { publicstaticvoidmain(String[] args) { HashSet<CommPortIdentifier> set = getAvailableSerialPorts(); System.out.println("total:" + set.size());
for (CommPortIdentifier a : set) { System.out.println(a.getName()); }
System.out.println("finish"); }
/** * @return A HashSet containing the CommPortIdentifier for all serial ports that are not currently being used. */ publicstatic HashSet<CommPortIdentifier> getAvailableSerialPorts() { HashSet<CommPortIdentifier> h = newHashSet<>(); EnumerationthePorts= CommPortIdentifier.getPortIdentifiers(); while (thePorts.hasMoreElements()) { CommPortIdentifiercom= (CommPortIdentifier) thePorts.nextElement(); switch (com.getPortType()) { case CommPortIdentifier.PORT_SERIAL: try { CommPortthePort= com.open("CommUtil", 50); thePort.close(); h.add(com); } catch (PortInUseException e) { System.out.println("Port, " + com.getName() + ", is in use."); } catch (Exception e) { System.err.println("Failed to open port " + com.getName()); e.printStackTrace(); } } } return h; } }
/** * Created by liuweiguo on 2018/4/10. */ publicclassTwoWaySerialComm { publicTwoWaySerialComm() { super(); }
voidconnect(String portName)throws Exception { CommPortIdentifierportIdentifier= CommPortIdentifier.getPortIdentifier(portName); if (portIdentifier.isCurrentlyOwned()) { System.out.println("Error: Port is currently in use"); } else { CommPortcommPort= portIdentifier.open(this.getClass().getName(), 2000);