/*PURPOSE*/
/*	This file will open the serial port at "/dev/ttyUSB0", which */
/*	corresponds to a mouser USB to serial converter.  	     */
/*	It initializes the serial converte 			     */

#include <errno.h>		/* Include Error Definitions*/	
#include <fcntl.h>		/* File control definitions */	
#include <sys/file.h>		/* Not sure */
#include <unistd.h>		/* File control definitions */
#include <stdio.h>		/* Standard Input Output */
#include <termio.h>		/* File control definitions */
#include <termios.h>
#include <sys/ioctl.h>
#include <string.h>
#include <sys/fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>

int main(int argc, char *argv[]){
  
  int fd, written, bytes, flags, status, returned;
 
  int phex=0x70;	/*Hexidecimal Value for Pressure*/
  int shex=0x73;	/*Hexidecimal Value for Start over*/
  int thex=0x74;	/*Hexidecimal Value for Temperature*/
  int hhex=0x68;	/*Hexidecimal Value for Humidity*/

  int *pphex,*pshex,*pthex,*phhex; 
 
  unsigned char rmessage[60];	/*The array to temporarily hold the data */
  struct termios options;	/*Structure containing the terminal settings*/
  
  FILE *datafile;		/*File for the data output*/
  int i=0;

  pphex=&phex;		/*pphex points to phex */
  pshex=&shex;		/*pshex points to shex */
  pthex=&thex;		/*pthex points to thex */
  phhex=&hhex;

  int Values[6]={*pshex,*pphex,*pshex,*pthex,*pshex,*phhex};

  #define TTY_SPEED B9600
  #define TTY_IFLAG IGNBRK
  #define TTY_OFLAG 0
  #define TTY_CFLAG (CS8|CREAD|CLOCAL)
  #define TTY_LFLAG 0
  #define TTY_CC_VMIN  1
  #define TTY_CC_VTIME 0


  if ((fd=open("/dev/ttyUSB0", O_RDWR | O_NONBLOCK)) == -1){
 	printf("Failed to Open Port");
  	return (-1);
  }
  if (lockf(fd,F_TEST, 0) == -1) {
        printf("Serial Port is locked");
   	return(-1);
  }
 if(tcgetattr(fd, &options) != 0) {
      printf("tcgetattr failed");
      close(fd);
      return (-1);
   }
 
  int olflags=fcntl(fd,F_GETFL);
  printf("%X\n",olflags);

  
  perror("Getting Serial Port attributes:"); 
  //cfmakeraw(&options);
  cfsetispeed(&options, B9600);  //This command Works!!
  cfsetospeed(&options, B9600);  //This command Works~~
  
  if(cfsetospeed(&options, TTY_SPEED) == -1) {
      printf("cfsetospeed failed");
      close(fd);
      return (-1);
   }
   if(cfsetispeed(&options, TTY_SPEED) == -1) {
      printf("cfsetispeed failed");
      close(fd);
      return (-1);

  }

  options.c_iflag = TTY_IFLAG;
  options.c_oflag = TTY_OFLAG;
  options.c_cflag = TTY_CFLAG;
  options.c_lflag = TTY_LFLAG;
  options.c_cc[VMIN] = TTY_CC_VMIN;
  options.c_cc[VTIME] = TTY_CC_VTIME;

  if(cfsetospeed(&options, B0) == -1) {
      printf("cfsetospeed failed");
      close(fd);
      return (-1);
   }
   if(cfsetispeed(&options, B0) == -1) {
      printf("cfsetispeed failed");
      close(fd);
      return (-1);

  }

  if(tcflush(fd, TCIOFLUSH) == -1) {
      printf("tcflush failed");
      close(fd);
      return (-1);
   }
   if(tcsetattr(fd, TCSANOW, &options) == -1) {
      printf("tcsetattr failed");
      close(fd);
      return (-1);
   }

  /*MAIN LOOP: CYCLE THROUGH TEMP, HUMIDITY, PRESSURE */
  /*ONLY BREAK IF A CONTROL-C IS ISSUED*/
  while (1){
 
	    /*SEND START CONVERSION iHARACTER */
            written=write(fd,&Values[i],1);
            sleep(2);
            if ((returned=read(fd,&rmessage[i],1)) == -1){
		printf("Reset Uncsuccesful\n");
	    }
	    else{
                printf("Reset Successful=%ld\n",rmessage[i]);    
 	    }
	    i++;

            /*GET PRESSURE */ 
 	    written=write(fd,&Values[i],1);
            sleep(1);
            if ((returned=read(fd,&rmessage[i],1)) == -1){
                printf("Read Unsuccessfull\n");
            }
            else{
                if (i==1){
		 printf("Current Pressure:\t\t%ld\n",rmessage[i]);    
            	 i++;
		}
		else if(i==3){
		 printf("Current Temperature:\t\t%ld\n",rmessage[i]);
		 i++;
		}
	   	else if(i==5){
		 FILE *datafile;
		 time_t rawtime;
		 struct tm *ptr;
  		 size_t strtime;
  		 int h,m,s;
		 char datestring[50];
 		 rawtime=time(NULL);
		 ptr=localtime(&rawtime);
  		 s=ptr->tm_sec;
		 h=ptr->tm_hour;
		 m=ptr->tm_min;

 		 strtime=strftime(datestring,20,"%b_%d_%G",ptr);
		 char day[strtime];
		 char basedir[]="/weather_data/";
		 strncpy(day,datestring,strtime);
		 strcat(basedir,datestring);
		 datafile=fopen(basedir,"a");
		 printf("Current Humidit:\t\t%ld\n",rmessage[i]);
		i=0;
		sleep(3);
	    	}			
	    }
	    
  
  }
  return 0;

}

