JSSC WriteBytes 在 Linux 上一段时间后停止工作

jssc writebytes stops working after a while on linux

提问人:JeroenV 提问时间:9/30/2013 最后编辑:JeroenV 更新时间:11/24/2016 访问量:838

问:

我正在用 Java 编程,以便与连接到 com-port 的设备(通过 USB 连接到 PC,但中间通过 RS232 转 USB 电缆)进行通信。我编写了一个与 jssc 对话的程序,并且在 Windows 下正常运行,即使什么也没发生,它也能继续工作更长的时间,就像它应该的那样。在 Linux 下,程序在 2 或 3 分钟后停止响应,我想知道为什么。

run语句如下

public void run() {
    while (stayConnected) {
        try {
            serialPort.writeBytes(pollBuf);
            readResponse(false);
            Thread.sleep(400);
            serialPort.writeBytes(readEvents);
            readResponse(true);
        } catch (InterruptedException ie) {
            logger.error("Interrupted exception: " + ie.getMessage());
        } catch (SerialPortException spe) {
            logger.error("SerialPortException: " + spe.getMessage());
        }
    }
}

为了知道程序挂在哪里,我添加了日志行,我发现最后一个正常运行的命令是对 readResponse(true) 的最后一次调用,第一个停止返回的命令是 serialPort.writeBytes(pollBuf)。 希望它能解决这个问题,我将 400 毫秒的睡眠一分为二,并将另一个睡眠放在 serialPort.writeBytes(pollBuf) 之前。这无济于事。不知何故,serialPort.writeBytes 函数永远不会返回,也不会抛出异常。

有没有人猜到失败可能是什么?这不是 stayConnected 布尔值,因为我从未调用过将其设置为如此错误的函数;

编辑:我刚刚添加了一个计数器,当我运行两次时,程序进入循环 283 次和 285 次,这非常接近,都在 2 分钟左右......

Java Linux 串口

评论


答:

1赞 Sean 12/10/2013 #1

我在 Windows 7 下遇到了非常相似的问题。我已将我的软件部署到客户端 PC,大约 5 到 6 小时后,串行端口可以打开,但无法写入。

根据示例,我的代码类似:

String readPort(字符串命令,int byteToRead) {

    String Input = null;
    if (opened == true) {
        try {
            serialPort.writeString(command);

            Input = serialPort.readString(byteToRead);

        } catch (SerialPortException ex) {
            System.out.println(ex);
        }
    }

    return Input;
}

不返回的代码行是

serialPort.writeString(命令);

0赞 Fabio Frumento 11/24/2016 #2

我遇到了完全相同的问题,原因是另一个线程关闭了端口,而主线程仍在读取,我看到您的代码片段是关于 Runnable 的,因此请仔细检查您的多线程管理。