3

i use RXTXcomm Library to connect COM port

if COM port connection is loss(physically) while application is running

I don't know whether Port is connect or not.

even the signal is still alive when the COM port is physically disconnected.

How i can detect COM port connection loss??

here my code

public class SerialSample implements SerialPortEventListener{

    private InputStream in;
    private OutputStream out;

    public SerialSample() {
        super();
    }

    void connect(String portName) throws Exception {
        CommPortIdentifier portIdentifier = CommPortIdentifier
                .getPortIdentifier(portName);
        if (portIdentifier.isCurrentlyOwned()) {



        } else {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),
                    2000);

            if (commPort instanceof SerialPort) {
                //System.out.println("connect");
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);

                in = serialPort.getInputStream();
            out = serialPort.getOutputStream();



            } else {
                System.out.println("Error: Only serial ports are handled by this example.");
            }
        }
    }

    @Override
    public synchronized void serialEvent(SerialPortEvent arg0) {
        // TODO Auto-generated method stub

        if (arg0.getEventType() == SerialPortEvent.DATA_AVAILABLE){
            try{
                int a = in.available();
                byte chunk[] = new byte[a];
                in.read(chunk, 0, a);
                System.out.println(new String(chunk) + " , " + a);

                inputSignal();
            }catch(Exception e){
                System.out.println(e.toString());
            }
        }

    }
tokhi
  • 135
  • 1
  • 8

0 Answers0