首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RXTX getPortIdentifiers()卡住

RXTX getPortIdentifiers()卡住
EN

Stack Overflow用户
提问于 2011-02-24 22:21:28
回答 2查看 7.6K关注 0票数 1

我在CommPortIdentifier.getPortIdentifier()上读到串行ports.when程序时遇到了问题,它被卡住了将近5分钟。据我观察,延迟可能是由于扫描系统中的所有端口造成的。那么如何避免这5分钟的延迟呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-02-24 22:40:28

如何扫描可用端口?

例如,以下代码将返回可用串行端口的字符串列表:

代码语言:javascript
复制
public List<String> getAvailablePorts() {

    List<String> list = new ArrayList<String>();

    Enumeration portList = CommPortIdentifier.getPortIdentifiers();

    while (portList.hasMoreElements()) {
        CommPortIdentifier portId = (CommPortIdentifier) portList.nextElement();
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            list.add(portId.getName());
        }
    }

    return list;
}

编辑:因为实际的解决方案是在注释中挖掘出来的,所以我在这里添加:

在某些情况下,commPortIdentifier.getPortIdentifier(portName)似乎确实会重新扫描端口;快速解决方法是通过gnu.io.rxtx.SerialPorts系统属性手动设置固定端口列表。

票数 4
EN

Stack Overflow用户

发布于 2015-08-07 02:08:52

这可能不适用于所有情况,但它对我有效,它只需要不到一秒钟的时间就可以获得我想要的端口。我从命令行开始使用Windows的devcon实用程序。

代码语言:javascript
复制
devcon find "usb\vid_067B&PID_2303*"

这将列出连接多产PL2303 USB串行电缆的端口。然后我解析了结果。我通常得到的结果很少,因为我只在我的计算机上插入一到两根电缆。

这段代码可能不是可移植的和有限的,但它非常适合我的目的,而且它的速度比使用CommPortIdentifier.getPortIdentifiers()快得多。

下面是我的代码的一部分:

代码语言:javascript
复制
public List<String> getAvailablePorts() {        
    List<String> list = new ArrayList<String>();        
    String res="";
    BufferedReader br;
    String cmd;
    Process proc;

    try {
        /*search for ports where Prolific PL2303 cable is attached*/
        cmd = "devcon find \"usb\\vid_067B&PID_2303*\"";
        proc = Runtime.getRuntime().exec(cmd);

        /* parse the command line results*/
        br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        do {
            try {
                res = br.readLine();
                if (res == null)
                    break;

                if (res.contains((CharSequence)("Prolific USB")))
                    list.add(res.substring(res.indexOf("(COM")+1, res.indexOf(")")));
            } catch(Exception e) {
                e.printStackTrace();
            }
        } while (!res.equals("null"));
        br.close();

    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return list;
}

只需确保devcon.exe文件是正确的(32位或64位),并且它位于应用程序可以访问它的正确文件夹中。

这在64位WinXP和Win7/8上有效,但对于32位Win7/8,应用程序可能需要以管理员权限启动(以管理员身份运行)。我在最终的可执行文件中添加了一个.manifest文件,这样就不需要在32位Windows上“右键单击并以管理员身份运行”。

在Ubuntu 14.04 Linux上,我使用了终端命令

代码语言:javascript
复制
ls /dev/ttyUSB*

列出USB-Serial端口,然后解析结果。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5105857

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档