//============================================================================
// Name        : hw1.cpp
// Author      : Gene M
// Version     :
// Copyright   : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <stdlib.h>

using namespace std;

void WhiteSpTo0( char *in, char *out)
{
	int i;

	for(i=0; i<(int)strlen(in); i++)
	{
		if(in[i] == ' ')
			in[i] = '0';
	}
	strcpy(out, in);
}

int main()
{
	char 	chIn,
				data[20],
				outString[20],
				inString[20],
				stemp[20];
	int 	i, j,
			fd,
			n,
			charCnt = 0;
	float pressure;
	struct termios options;

	fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);  //Read and write, Not a "controlling terminal", DCD don't care
	if( fd == -1)
		perror("unable to open port");
	else
	{
		fcntl(fd, F_SETFL, 0);					  // Set blocking behavior
		cout << "Port 1 open with FD " << fd << endl;
	}

	tcgetattr(fd, &options);					  // Get current serial port setting
	cfsetispeed(&options, B9600);		  // Set in baud rate
	cfsetospeed(&options, B9600);		  // Set out baud rate

	options.c_cflag |= (CLOCAL | CREAD);		//Do not change port owner, Enable receiver
	options.c_cflag &= ~PARENB;					//No parity
	options.c_cflag &= ~CSTOPB;					//1 stop bit
	options.c_cflag &= ~CSIZE;						//Clear data size bits
	options.c_cflag |= CS8;							//8 bits per character
	options.c_cflag &= ~CRTSCTS;				//No hardware handshaking

	options.c_iflag &= ~(INLCR | IGNCR | ICRNL);					//Don't change NL, Don't ignore CR, Don't change CR
	options.c_iflag &= ~(IXON | IXOFF | IXANY);					//No Xon/Xoff
	options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);	//Disable canonical reads: read function waits for chars

	options.c_oflag &= ~OPOST;											//Don't process output

	tcflush(fd, TCIOFLUSH);													//Flush input and output buffers
	tcsetattr(fd, TCSANOW, &options);								//Make the changes

	for(i=0; i<10; i++)
	{
		strcpy(outString, "*01P1\x0D");
		n = write(fd, outString, strlen(outString));
		cout << "Wrote command " << outString << "Bytes written = " << n << endl;

		chIn = 0;
		charCnt = 0;
		j = 0;
		while( chIn != 0x0D )
		{
			read(fd, &chIn, sizeof(chIn));
			inString[charCnt] = chIn;
			charCnt = charCnt + 1;
			j = j + 1;
			inString[charCnt] = '\0';
		}
		cout << inString << endl;
		strcpy(stemp, inString);
		strcpy(data, strtok(stemp, "="));
		strcpy(data, strtok(NULL, "\x0D"));
		WhiteSpTo0(data, stemp);
		pressure  = atof(stemp);
		cout << "Pressure (float) = " << pressure << endl;
		printf("Pressure (float) from printf %f\n", pressure);
	}

	cout << "Closing port" << endl;
	close(fd);
	cout << "End" << endl;
	return 0;
}
