/*
 * SerialPortControl.java
 *
 * Created on April 6, 2004, 9:39 AM
 */


import java.io.*;
import java.util.*;
import javax.comm.*;


/**
 * Class declaration
 * @author Jeff Craighead
 */
public class SerialPortControl implements Runnable, SerialPortEventListener {
    static CommPortIdentifier portId;
    static Enumeration        serialPortList;
    OutputStream              outputStream;
    InputStream		      inputStream;
    SerialPort		      serialPort;
    Thread		      readWriteThread;
    byte[]                    responsePacket;
   

    /**
     * Method declaration
     *
     *
     * @param args
     *
     * @see
     */


    /**
     * Constructor declaration
     * @param commPort A commPort object.  This specifies what comm port you will use.  See the JavaDoc for the commAPI for details on the commPort object.
     */
    public SerialPortControl(CommPortIdentifier commPort) {
        portId = commPort;
        responsePacket = new byte[18];
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL){
            try {
                serialPort = (SerialPort) portId.open("SerialPortControl", 2000);
            } catch (PortInUseException e) {}

            try {
                inputStream = serialPort.getInputStream();
            } catch (IOException e) {}
            
            try {
                outputStream = serialPort.getOutputStream();
            } catch (IOException e) {}

            try {
                serialPort.addEventListener(this);
            } catch (TooManyListenersException e) {}

            serialPort.notifyOnDataAvailable(true);
            serialPort.notifyOnOutputEmpty(true);

            try {
                serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, 
                    			   SerialPort.STOPBITS_1, 
                    			   SerialPort.PARITY_NONE);
                serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
            } catch (UnsupportedCommOperationException e) {}

            readWriteThread = new Thread(this);

            readWriteThread.start();
        }
    }

    /**
     * Method declaration
     */
    public void run() {
	try {
	    Thread.sleep(20000);
	} catch (InterruptedException e) {}
    } 

    /**
     * Method declaration
     * @param event A serial port event. See the JavaDoc for the Java CommAPI for details.
     */
    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:
            boolean packetFound = false;
            
            try {
                Thread.sleep(25);
            } catch (InterruptedException e){}
            
            
	    try {
		while ((inputStream.available() > 0) && (packetFound==false)) {
                    inputStream.read(responsePacket,0,1);
                    if(responsePacket[0]==0x72) packetFound = true;		    
		} 
                int numBytes = inputStream.read(responsePacket,1,17);
//                System.out.println("I read " + numBytes + " bytes...");
//                System.out.println("checksum: " + responsePacket[17]);
	    } catch (IOException e) {}
                                   
	    break;
	}
    } 
    
    /**
     * Sends a packet of bytes over a serial port.
     * @param packet This is the command packet to be sent to the VGTV OCU.
     */    
    public void sendCommand(byte[] packet){
        try {
            outputStream.write(packet);
        } catch (IOException e) {}
    }
    
    /**
     * This returns the response packet from the OCU to you.
     * @return This byte array is the response packet. Give it to decodeResponsePacket() in CPC.
     */    
    public byte[] getResponsePacket(){
        return responsePacket;        
    }
    
    /**
     * This clears the input serial port input stream.  I use this to clear incomplete data from the buffer.
     */    
    public void clearStream(){
        try{
            inputStream.skip(inputStream.available());        
        }catch(IOException e){}
     }
    

    }





