kelevra88
kelevra88

Reputation: 1562

Serial Data Event Listener Java

I would be really grateful if someone could point me in the right direction

How would i go about triggering an event that is called when no data is received from the serial communication example below?

Thank you, Maria.

    public void connect(String portName) throws Exception {
     CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if (portIdentifier.isCurrentlyOwned()) {
            System.out.println("Error: Port is currently in use");
        } else {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),
                    2000);
            if (commPort instanceof SerialPort) {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();
                theSerialWriter = new SerialWriter(this, out);
                new Thread(theSerialWriter).start();

                serialPort.addEventListener(new SerialReader(this, in));
                serialPort.notifyOnDataAvailable(true);
            } else {
                System.out.println("Error: Only serial ports are handled by this                          example.");
            }
        }
    }
        public void serialEvent(SerialPortEvent arg0) {
            int data;
            // boolean setFlagDoorLock = false ;
            // if(arg0= 1){}
            try {
                int len = 0;
                while ((data = in.read()) > -1) {

                    if (data == '\n') {
                        break;
                    }
                    buffer[len++] = (byte) data;
                    asHexStr = DatatypeConverter.printHexBinary(buffer);
                    if (asHexStr.contains("FB1")) {
                        // Thread.sleep(1000);
                        ActivateSystem = true;
                        if ((asHexStr.contains("FB1") && (ActivateSystem == true))) {
                            ActivateSystem = false;
                            asHexStr = "";
                        } else {
                            System.out.println("Here2");
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(-1);
            }
            System.out.println("Received"); 
        }
    }
    public static class SerialWriter implements Runnable {
        OutputStream out;
        SerialPortConnector main = null;

        public SerialWriter(SerialPortConnector twoWaySerialComm,
                OutputStream out) {
            main = twoWaySerialComm;
            this.out = out;
        }    
        public void send(String stringToSend) {
            try {
                int intToSend = Integer.parseInt(stringToSend);
                this.out.write(intToSend);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        public void run() {
            try {
                int c = 0;
                Thread.sleep(1000);

                if (asHexStr == "") {
                    System.out.println("Here");
                    // ActivateSystem = false;
                }  
            }
            // catch ( IOException e )
            catch (Exception e) {
                e.printStackTrace();
                System.exit(-1);
            }
        }
    }  
    public static void main(String[] args) {
        try {
            (new SerialPortConnector()).connect("COM12");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Upvotes: 0

Views: 8187

Answers (1)

dic19
dic19

Reputation: 17971

You have stated this in a comment:

I need to be able to detect that the id has stopped and after a timeout(or after it not detecting the id a few times in a row) then send a url call( i already have a class to send the call)-this should only be sent once.while it is reading the id however another url call should be sent again-once only

If I understand this right then you need to check for two different things:

  • The device stops at sending the ID.
  • The device sends a number of empty ID's.

This requirement is a kind of tricky. As I've said if no data arrives to the serial port then no serial port event will be fired. I think you can use a Timer to check the timeout and use a counter to register the number of empty ID's arrived. Something like this:

int numberOfEmptyIds = 0;
int maxNumberOfAttempts = 5;
boolean urlSent = false;
long timeoutInMillis = 10000; // let's say 10000 millis, equivalent to 10 seconds
Timer timer = null;

public void connect(String portName) throws Exception {
    ...
    scheduleTimer();
}

public void serialEvent(SerialPortEvent evt) {
    if(evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
        try {
            while(in.read(buffer) > -1) {
                String asHexStr = DatatypeConverter.printHexBinary(buffer);
                if(asHexStr.contains("FB1")) {
                    scheduleTimer();
                    numberOfEmptyIds = 0;

                } else {
                    numberOfEmtyIds++;
                    if(numberOfEmptyIds == maxNumberOfAttempts && !urlSent) {
                        // send the url here
                    }
                }             
            }
        } catch (IOException ex) {
           // Log the exception here
        }
    }
}

private void scheduleTimer() {
    if(timer != null) {
        timer.cancel();
    }
    timer = new Timer("Timeout");
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            if(!urlSent) {
                // send the url here
            }
        }
    };
    timer.schedule(task, timeoutInMillis);
}

I don't know if this is exactly what you need but hope it be helpful.

Upvotes: 1

Related Questions