/*
 *  printCon.c
 *
 *
 *  Created by Shawn Henry on Mon Mar 03 2003.
 *  Copyright (c) 2003 __MyCompanyName__. All rights reserved.
 *
 */

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/neutrino.h>
#include <fcntl.h>
#include <termios.h> /* POSIX terminal control definitions */
#include <pthread.h>
#include <string.h>
#include <hw/inout.h>

#include "sbc.h"

#define AD_BASE 0x110

struct ACCDataPacket {
	 	
};

int init_modem(int fd);

int main (void)
{
	int fd;
	char data[256];
	//char cmdStr [] = "S\rM=T\rM=A\rF1\rA\r";
	char cmdStr [] = "S\r";
	struct termios options;
	
	ThreadCtl(_NTO_TCTL_IO, 0);

    printf("Starting ACC sensor Control\n");

	fd = open("/dev/ser2", O_RDWR/* | O_NOCTTY | O_NDELAY*/);
	if (fd == -1)
	{
		perror("open_port: Unable to open /dev/ttyf1 - ");
	}
	fcntl(fd, F_SETFL, 0);

	printf("Serial Port Opened\n");
	
	//printf("\n%i\n", init_modem(fd)); 
	
	tcgetattr(fd, &options);
	
	//Set the baud rates to 9600
	cfsetispeed(&options, B9600);
	cfsetospeed(&options, B9600);

	//Enable the receiver and set local mode...
	options.c_cflag |= (CLOCAL | CREAD);
	
	//8N1 - No parity
	options.c_cflag &= ~PARENB;
	options.c_cflag &= ~CSTOPB;
	options.c_cflag &= ~CSIZE;
	options.c_cflag |= CS8;


	//Set the new options for the port...
	tcsetattr(fd, TCSANOW, &options);

	sleep(1);

	//if(read(fd, data, sizeof(data)) < 0)
	//	printf("Error reading\n");

	//printf("%s", data);

	write(fd, cmdStr, sizeof(cmdStr)-1);

	usleep(1000000);
	write(fd, "M=T\r", sizeof("M=T\r")-1);
	usleep(1000000);
	write(fd, "M=A\r", sizeof("M=A\r")-1);

	usleep(1000000);	
	write(fd, "F1\r", sizeof("F1\r")-1);
	
	usleep(1000000);
	write(fd, "A\r", sizeof("A\r")-1);
	{
		int count = 0;
		FILE *serial_in = fdopen(fd, "r");
		 
		while(1)
		{
			char buffer[256];
			int read_size;
			int str_size = 0;
			double val[5];
			int i;
			fgets(buffer, sizeof(buffer), serial_in);

			printf("%i : %s !", strlen(buffer), buffer);
			//if(strlen(buffer) == 38);
			//i = sscanf(buffer, "%f %f %f %f %f", val[0], val[1], val[2], val[3]);
			//printf("REad");
			//printf("\n\n@@@ %f, %f, %f, %f, %f @@@\n", val[0], val[1], val[2], val[3]);
			count++;

			//if(c == 0x0A) printf("   :%i\n", count);
		}
	}

	//if(read(fd, data, sizeof(data)) < 0)
	//	printf("Error\n");
	pause();
}


