// Log analog inputs from shared memory to file

#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include "io.h"

main(){
  float reading;
  float volts;
  int i,j;
  FILE *fp;
  char outbuff[80];
    
  struct timeval now;
  long start_usec;
  long start_sec;
  long now_usec;
  time_t timestamp;

  int shmid;
  key_t key;
  char *shmat();
  //short *shm, *s;
  shmstruct *shm;
   
  // Key for our shared memory is 9700
  
  key = 9700;
  
  // Create our shared memory
  if ((shmid = shmget(key, sizeof(shmstruct), 0666)) < 0) {
    perror("shmget");
    exit(1);
  }
  
  // Link to our shared memory
  if ((shm=shmat(shmid, NULL, 0)) == (char *) -1) {
    perror("shmat");
    exit(1);
  }
  
  gettimeofday(&now,NULL);
  start_sec = now.tv_sec;
  start_usec = now.tv_sec * 1000000 + now.tv_usec;
   
  // Do forever
  while (1){
    fp = fopen("/home/projects/boiler/data/logfile.csv","a");
    timestamp = time(NULL);   
    // Cycle through channels
    printf("%ld\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%d\n",timestamp,shm->ad[0].value,shm->ad[1].value,shm->ad[2].value,shm->ad[3].value,shm->ad[4].value,shm->ad[5].value,shm->ad[6].value,shm->ad[7].value,shm->dio[1]);
    fprintf(fp,"%d\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%f\t%d\n",now.tv_sec-start_sec,shm->ad[0].value,shm->ad[1].value,shm->ad[2].value,shm->ad[3].value,shm->ad[4].value,shm->ad[5].value,shm->ad[6].value,shm->ad[7].value,shm->dio[1]);
    
    fclose(fp);
    
    // 30 second interval
    start_usec += 30000000;
    gettimeofday(&now,NULL);
    now_usec = now.tv_sec * 1000000 + now.tv_usec;
    
    usleep(start_usec - now_usec);
  }
}

