////////////////////////////////////////////////////////////////////////////////////////////
//
//     TEA2 Module for the IPAQ
//
//             by Kristof Van Laerhoven, kristof@starlab.net
//
//     version history: 
//
////////////////////////////////////////////////////////////////////////////////////////////

///// includes /////////////////////////////////////////////////////////////////////////////

#include <stdio.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/signal.h>
#include <sys/types.h>
#include "Fifo.h"

///// defines //////////////////////////////////////////////////////////////////////////////

#define MODEMDEVICE "/dev/ttySA0"     /* /dev/ttySA0 uses a different UART */   

#ifndef FALSE 
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE  1
#endif

///// globals //////////////////////////////////////////////////////////////////////////////

struct termios  orig, new_t;  				// new and old terminal

unsigned int index;
unsigned int numsensors;

static int	peek = -1;				// kbhit/getch           


////// translate the serial buffer /////////////////////////////////////////////////////////

void translate_buffer(unsigned char chr, unsigned char *sensorarray, Fifo *farr) {
	
	if (index == 0 ) {
		if (chr==255) index++;
	} else
        if (index == numsensors) {
            sensorarray[numsensors-1] = chr;
			farr[numsensors-1].add(chr);
			index=0;
        } else
        {
			if (chr==255) index=0;
			sensorarray[index-1] = chr;
			farr[index-1].add(chr);
			index++;
        }
}

////// check for a key-pressed event //////////////////////////////////////////////////////

int  kbhit(void)
{
   	char ch;
    int nread;
    
    if (peek != -1) {
        return 1;        
    }
    
    new_t.c_cc[VMIN]=0;
    tcsetattr(0,TCSANOW, &new_t);
    nread = read(0, &ch, 1);
    new_t.c_cc[VMIN]=1;
    tcsetattr(0, TCSANOW, &new_t);        
	
    if (nread==1) {
        peek = ch;
		return 1;
    }
    
    return 0;
}

////// get character from input ///////////////////////////////////////////////////////////

int  getch(void)
{
   	char ch;
	
	if (peek != -1) {
		ch = peek;
		peek = -1;
		return ch;           
	}
	
	read(0,&ch,1);
	return ch;
}

////// main function //////////////////////////////////////////////////////////////////////

int main(int ac, char **args) {
	
	int fd,c,i, res, baudrate;
	unsigned char ch;
	char *datafile;
	FILE *fp;
	char ascii; // boolean
	unsigned int bufsize, interval;
	
	unsigned int current_label = 0;
	
	char feed = FALSE;
	
	struct termios oldtio,newtio;
	
	// terminal input properties (for getch & kbhit)
	tcgetattr(0, &orig);
	new_t = orig;
	new_t.c_lflag &= ~ICANON; 		// no canonical input
	new_t.c_lflag &= ~ECHO;		// no echo 
	new_t.c_lflag &= ~ISIG;		// no ISIG
	new_t.c_cc[VMIN] = 1;
	new_t.c_cc[VTIME] = 0;
	tcsetattr(0, TCSANOW, &new_t);
	
	// 
	datafile = args[1];
	
	numsensors = 10; // standard TEA2 protocol
	baudrate = B9600; // default
	bufsize = 1024;            
	ascii = FALSE;
	interval = 0; 
	int numcues = 4;
	
	unsigned char *buf;
	buf = new unsigned char [bufsize];
	
	unsigned char* sensor;
	sensor = new unsigned char [numsensors];
	
	float* cue;
	cue = new float[numsensors*numcues];
	
	// open the device to be non-blocking (read will return immediatly) 
	printf("Opening the serial port... ");
	fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY | O_NONBLOCK);
	if (fd <0) {
		perror(MODEMDEVICE); 
		exit(-1); 
	}
	else {
		printf("Success.\n\r");
	}
	
	tcgetattr(fd,&oldtio); // save current port settings 
	printf("Saved current port settings.\n\r");
	
	// set new port settings for canonical input processing 
	newtio.c_cflag = baudrate | CRTSCTS | CS8 | CLOCAL | CREAD;
	newtio.c_iflag = IGNPAR ;
	newtio.c_oflag = 0;
	newtio.c_lflag = 0;
	newtio.c_cc[VMIN]=1;
	newtio.c_cc[VTIME]=0;
	res = tcflush(fd, TCIFLUSH);
	printf("flush returned %i\n\r",res);
	res = tcsetattr(fd,TCSANOW,&newtio);
	printf("set attr returned %i\n\r",res);
	
	ch = 0; 
	index = 0;
	
	Fifo fifo[numsensors];
	
	while (ch!='q' && ch!='Q') {        
		
		// read values from serial port (and record them)
		usleep(interval);	// wait	<interval> microsecs 
		res = read(fd,buf,bufsize);		// read buffer 
		buf[res]=0;	// set a null-char at the end so we can printf %s in debugmode 
		if (res==-1) {
			//debug: perror(MODEMDEVICE);
		}
		else {
			// debug: 
			//printf("*%i*",res);
			
			for (i=0; i<res; i++) {
				translate_buffer(buf[i], sensor, fifo);
			}
			// print all of it in a console
			for (i=0; i<numsensors;i++) 
				printf("%3i.",sensor[i]);
			
			printf("\n\r");
			
		}
        // check for input          
		if (kbhit()) {
			ch = getch();
		}      
		
	} //while no q or Q has been typed
	
	// restore old settings 
	tcsetattr(fd,TCSANOW,&oldtio);
	tcsetattr(0, TCSANOW, &orig);
	
	printf("deleting sensor array\n\r");
	delete []sensor;
	printf("deleting buffer array\n\r");
	delete []buf;
	printf("deleting cue array\n\r");
	delete []cue;
}


