我有一个用Java开发的应用程序,第二个正在用Ruby on Rails开发,需要通过串行通信连接到Arduino。虽然我可以根据自己的计算机输入字符串来寻址正确的串行端口,但字符串的变化甚至取决于我使用的USB端口,这使我认为用户能够从他们自己的计算机上扫描的列表中选择一个有效的串行端口会更好,而不是我预定义的一个。有没有人有一个策略,我可以使用允许用户扫描他们的计算机的所有串行端口,并选择正确的一个数组/列表,无论是在Java或Ruby on Rails?
From List the ports:
import java.util.Enumeration;
import javax.comm.CommPortIdentifier;
/**
* List the ports.
*
* @author Ian F. Darwin, http://www.darwinsys.com/
* @version $Id: CommPortLister.java,v 1.4 2004/02/09 03:33:51 ian Exp $
*/
public class CommPortLister {
/** Simple test program. */
public static void main(String[] ap) {
new CommPortLister().list();
}
/** Ask the Java Communications API * what ports it thinks it has. */
protected void list() {
// get list of ports available on this particular computer,
// by calling static method in CommPortIdentifier.
Enumeration pList = CommPortIdentifier.getPortIdentifiers();
// Process the list.
while (pList.hasMoreElements()) {
CommPortIdentifier cpi = (CommPortIdentifier) pList.nextElement();
System.out.print("Port " + cpi.getName() + " ");
if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL) {
System.out.println("is a Serial Port: " + cpi);
} else if (cpi.getPortType() == CommPortIdentifier.PORT_PARALLEL) {
System.out.println("is a Parallel Port: " + cpi);
} else {
System.out.println("is an Unknown Port: " + cpi);
}
}
}
}