Search code examples
javaserial-portarduinognurxtx

Close serial port issue in Java


I have following Java code:

import java.io.*;
import java.util.ArrayList;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

public class SerialCommDataReading implements SerialPortEventListener {
   private static SerialPort serialPort;
   private static final String PORT_NAME = "COM5";
   private BufferedReader input;
   private static final int TIME_OUT = 2000;
   private static final int DATA_RATE = 9600;

  public void initialize() {
    CommPortIdentifier portId = null;

    try {
        portId = CommPortIdentifier.getPortIdentifier(PORT_NAME);
        serialPort = (SerialPort) portId.open("GestureData", TIME_OUT);

        serialPort.setSerialPortParams(DATA_RATE,
                SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1,
                SerialPort.PARITY_NONE);

        input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));

        System.out.println(input.read());

        serialPort.addEventListener(this);
        serialPort.notifyOnDataAvailable(true);
    } catch (Exception e) {
        System.err.println(e.toString());
    }
}

public synchronized void serialEvent(SerialPortEvent oEvent) {
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
        try {
            String inputLine = input.readLine();
            System.out.println(inputLine);
        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }
}

public static void main(String[] args) throws Exception {
    SerialCommDataReading main = new SerialCommDataReading();
    main.initialize();
    Thread t = new Thread() {
        public void run() {
            try {
                Thread.sleep(1000000);
            } catch (InterruptedException ie) {
            }
        }
    };
    t.start();
    System.out.println("Started");
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            serialPort.close();
            serialPort.removeEventListener();
            System.out.println("Stopping");
        }
    });
}
}

the code works fine fetching data from serial port.

The problem/quesion: when I stop running the code. It suppose to run serialPort.close(); and serialPort.removeEventListener() and the message Stopping shows up in the console. But when I start the code again it says

gnu.io.NoSuchPortException

So logically I expect the port will get closed so I can restart the code again with out restarting my hardware device, any idea what I am missing or doing wrong?

Info: I am using Windows 8.1 64bit / the communication is based on bluetooth, it is emulated as serial port with COM5.

Note: the code is originally from here http://playground.arduino.cc/interfacing/java I have modify it


Solution

  • I have not found any solution for closing serial port of rxtx package in windows 8.1 environment, I moved therefore to JSSC package and it works much better, the full solution including closing port and event listener can be found here.

    JSSC solution