/*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>
#include <stdlib.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*/

  //MAKE SURE TO DECLARE POINTERS OUTSIDE OF LOOP OR ELSE MEM ALLOCATION ERR 
  FILE *datafile;		/*File for the data output*/
  int i=0;			/*Index*/
  time_t rawtime;		/*Time from computer*/
  struct tm *ptr;		/*Structure to hold time*/
  size_t strtime;		/*String for time*/
  int h,m,s;			/*Numbers for time*/
  char datestring[50];		/*String for date*/
  char BaseDir[] = "/weather_data/";
  char day[strtime];		

  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){
 		 rawtime=time(NULL);
		 ptr=localtime(&rawtime);
  		 s=ptr->tm_sec;
		 h=ptr->tm_hour;
		 m=ptr->tm_min;
		 printf("Made it This Far \n");
 		 strtime=strftime(datestring,20,"%b_%d_%G",ptr);
                 printf("Made it This Far \n");
		 char *basedir;
		 if ((basedir = malloc(sizeof(char) * 500)) == NULL){
		    printf("Bad Allocation\n");
  		 }
		 strcpy(basedir,BaseDir);
		 printf("%s\n",basedir);
		 strncpy(day,datestring,strtime);
                 printf("Made it This Far \n");
		 strcat(basedir,datestring);
                 printf("Made it This Far,Yeh \n");
		 datafile=fopen(basedir,"a");
		 printf("Current Humidit:\t\t%ld\n",rmessage[i]);
		 datafile=fopen(basedir,"a");
           	 fprintf(datafile,"%ld\t%ld\t%ld\t%d\t%d\t%d\n",rmessage[1],rmessage[3],rmessage[5],h,m,s); 
		 fclose(datafile);
		i=0;
		sleep(60);
	    	}			
	    }
	    
  
  }
  return 0;

}

