/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package serial;

import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import structures.Constants;

/*class SerialPortListener
 * Listens to the serial port for a response from the OBD
 */
public class SerialPortListener implements SerialPortEventListener {


     public void serialEvent(SerialPortEvent event) {

      switch (event.getEventType()) {
      case SerialPortEvent.BI:
      case SerialPortEvent.OE:
      case SerialPortEvent.FE:
      case SerialPortEvent.PE:
      case SerialPortEvent.CD:
      case SerialPortEvent.CTS:
      case SerialPortEvent.DSR:
      case SerialPortEvent.RI:
      case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
         break;
      case SerialPortEvent.DATA_AVAILABLE:
         // we get here if data has been received

        byte[] response = new byte[32];
        byte byteRead;

        try {
            int i = 0;
            while (true) {  //Read in the next byte

                //Read in the next byte
                byteRead = (byte) SerialComm.getInputStream().read();

                //Check to see if it is the commpand prompt;
                if(byteRead == Constants.PROMPT[0])
                {
                    break;
                }

                else { //keep reading

                    response[i] = byteRead;
                    i++;
                }
            }

            SerialComm.setCAN_response(response);
            SerialComm.setWaitingforData(false);

            } catch (IOException ex) {
                Logger.getLogger(SerialPortListener.class.getName()).log(Level.SEVERE, null, ex);
            }
            break;
      }

     }
}
