Java. Reading from the COM port


There are large industrial scales, data from them comes to the computer on the com port. There is a program running on the computer that receives data from the com port and writes it to the log.

You need to connect to this port in parallel, receive data and forward it to a specific address. I use the jssc library.

SerialPort serialPort = new SerialPort("COM1"); //объявляем  
serialPort.openPort(); //открываем  
serialPort.setParams(9600, 8, 1, 0);// задаем параметры  
String from_port = serialPort.readString(); // читаем

And here the script is waiting for the data to arrive at the input. Received, sent.

serialPort.closePort(); // закрыли

As a result, we received the data and the script ended. A I need to continue listening to the com port...

I probably can't think of any simple solution... Well, don't while (true) {} use the same)

And the question is, when I opened the port programmatically, will it be available to the program that receives this data and writes to the log?

Author: MSDN.WhiteKnight, 2015-02-20

2 answers

Well, don't use while (true) {} the same)

Use something like

need_stop = true;
while (serialPort.IsOpen && !need_stop) {
   //..
}

Need_stop is a special Boolean field that can be set to false if you need to terminate the port (for example, the user decided to close the program).

 4
Author: KoVadim, 2015-02-20 14:04:12

The SerialPort class has a method getInputBufferBytesCount (). Accordingly, if it does not return 0, then the buffer is not empty and you need to pick up the data, if 0, then the program continues without any brakes.

 0
Author: Slonegd, 2018-01-11 13:35:14