Skip to content

Instantly share code, notes, and snippets.

@mvalla
Created January 30, 2021 00:02
Show Gist options
  • Save mvalla/de7cbcb4e0ae054ee33866589cedd8aa to your computer and use it in GitHub Desktop.
Save mvalla/de7cbcb4e0ae054ee33866589cedd8aa to your computer and use it in GitHub Desktop.
nrjavaserial HARDWARE_ERROR test
package org.serial.test;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.TooManyListenersException;
import gnu.io.NRSerialPort;
import gnu.io.SerialPortEvent;
public class MySerialDisconnectTest {
public static void main(String[] args) {
String version = System.getProperty("java.version");
System.out.println("Java version: " + version);
String port = "";
for (String s : NRSerialPort.getAvailableSerialPorts()) {
System.out.println("Availible port: " + s);
port = s;
}
int baudRate = 19200;
NRSerialPort serial = new NRSerialPort(port, baudRate);
serial.connect();
DataInputStream ins = new DataInputStream(serial.getInputStream());
try {
serial.addEventListener(ev -> {
if (ev.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
while (ins.available() > 0) {// read all bytes
char b = (char) ins.read();
System.out.print(b);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (ev.getEventType() == SerialPortEvent.HARDWARE_ERROR) {
System.out.println("Clean exit of hardware");
serial.disconnect();
System.out.println("$$$ serial disconnected");
System.exit(1);
}
});
} catch (TooManyListenersException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment