0

我遇到了一个奇怪的问题,即我的软件在使用真正的 COM5 或 COM6 时没有读取它发送的字节,但是当使用 RS232 tot USB 电缆(在 Windows 中作为 COM12 出现)时它确实有效。连接到 COM 端口的是两根电线,可以判断设备的门是否打开。

下面的代码怎么能在 COM12(虚拟 COM 端口)上工作,但不能在 COM5 和 COM6(真正的 COM 端口)上工作,并且当使用腻子并在门关闭时输入字符时,所有三个都显示输入的字符。使用 putty 的所有 3 个端口的行为相同,但该软件仅在连接到由 Serial2USB 电缆组成的 vrtual COM 端口时才有效...

该问题出现在装有 32 位版本的 Windows 7 Embedded 的计算机上。

public void continuouslyCheckConnection() {
    new Thread() {
        public void run() {
            while(true) {
                if (hasStarted) {
                    sendByte();
                    int newStatus = readWithPossibleDelay(100);
                    logger.debug("new doorreader status: " + newStatus);
                    if (latestStatus != newStatus) {
                        latestStatus = newStatus;
                        if (newStatus == 0)
                            mainController.getScreensController().doorOpened();
                    }
                }

                try {
                    Thread.sleep(100);
                } catch(InterruptedException ie) {
                    logger.error("DoorReader; InterruptedException in continuouslyCheckConnection: " + ie.getMessage());
                }
            }
        }
    }.start();
}

public void sendByte() {
    try {
        serialPort.writeByte((byte)0x01);
    } catch(SerialPortException spe) {
        logger.error("DoorReader; SerialPortException in sendByte: " + spe.getMessage());
    }
}

private synchronized int readWithPossibleDelay(int delay) {
    Callable<Integer> readTask = new Callable<Integer>() {
        @Override
        public Integer call() throws Exception {
            byte[] byteArray = serialPort.readBytes(1);
            int readInt = byteArray[0];
            return readInt;
        }
    };
    Future<Integer> future = executor.submit(readTask);
    try {
        return future.get(delay, TimeUnit.MILLISECONDS);
    } catch (ExecutionException ee) {
        logger.error("DoorReader; ExecutionException in readWithPossibleDelay: " + ee.getMessage());
    } catch (InterruptedException ie) {
        logger.error("DoorReader; InterruptedException in readWithPossibleDelay: " + ie.getMessage());
    } catch (TimeoutException te) {
        // ignore, this returns 0 which is okay
    }
    return 0;
}

我还找到了明确设置的地方

serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);

可能有帮助,但它没有改变任何东西

4

0 回答 0