Как получить результаты команды из непрерывных входных потоков? - PullRequest
0 голосов
/ 05 июня 2019

Извините за мой плохой английский.Я пытаюсь прочитать данные из температурного модуля, который подключен к последовательному порту (RS232).Модуль отправляет данные о температуре через равные промежутки времени.Я могу отправлять команды модулю, такие как текущее состояние, номер модуля и т. Д.

Что я хотел бы сделать, так это получать непрерывные данные о температуре и состоянии модуля, отправляя команду в одном потоке.

Я попробовал приведенный ниже код, но он останавливается и возвращает ошибку JVM.

public class SerialReader implements Runnable {
    InputStream in;
    boolean onCommand = false;
    int stByte;
    byte[] command;
    char[] temp = new char[8];
    int commandCnt;
    int temperatureCnt;

    public SerialReader(InputStream in) {
        this.in = in;
    }

    // After Sending command, receive the result
    public String commandResult(int size, int stByte) {
        command = new byte[size];
        this.commandCnt = 0;
        this.stByte = stByte;
        onCommand = true;
        while (onCommand) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//          System.out.println("onCommand: " + onCommand);
        }
        String result = new String(command);
        return result;
    }

    public void run() {
        int n = 0;
        try {
            while (true) {
                n = in.read();
                if (n == -1) {
                    continue;
                }
                // When command has sent, change the state
                if (onCommand) {
                    if (stByte != 0) {
                        if (stByte == n) {
                            stByte = 0;
                        } else {
                            continue;
                        }
                    }
                    command[commandCnt++] = (byte) n;
                    if (commandCnt == command.length) {
                        onCommand = false;
                    }
                    continue;
                }
//              System.out.print((char) n);

                // end of temperature data per 1 seconds
                if (n == '(') {
                    System.out.println("1CH: " + (temp[0] == '0' ? "+" : "-") + temp[1] + temp[2] + "." + temp[3] + "℃, 2CH: " + (temp[0] == '0' ? "+" : "-") + temp[5] + temp[6] + "." + temp[7] + "℃");
//                  System.out.println(new String(temperatureBytes));
                } else if (n == ')') {
                    temperatureCnt = 0;
                } else {
                    if (temperatureCnt < temp.length) {
                        temp[temperatureCnt++] = (char) n;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Ошибка ниже

#
# A fatal error has been detected by the Java Runtime Environment:
#
#  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0000000180005b6b, pid=14892, tid=0x0000000000002e6c
#
# JRE version: Java(TM) SE Runtime Environment (8.0_201-b09) (build 1.8.0_201-b09)
# Java VM: Java HotSpot(TM) 64-Bit Server VM (25.201-b09 mixed mode windows-amd64 compressed oops)
# Problematic frame:
# C  [rxtxSerial.dll+0x5b6b]
#
# Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
#
# An error report file with more information is saved as:
# D:\workspace\sensor\hs_err_pid14892.log
#
# If you would like to submit a bug report, please visit:
#   http://bugreport.java.com/bugreport/crash.jsp
# The crash happened outside the Java Virtual Machine in native code.
# See problematic frame for where to report the bug.
#

Любая идея приветствуется.

...