// Read analog inputs from TS-9700 A/D card and output formatted HTML

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

main(){
  MYSQL_RES *result;
  MYSQL_ROW row;
  MYSQL myserver;
  float reading;
  float volts;
  int i,j;
  FILE *fp;
  char outbuff[400];
    
  struct timeval now;
  long start_usec;
  long start_sec;
  long now_usec;

  int shmid;
  key_t key;
  char *shmat();
  //short *shm, *s;
  shmstruct *shm;
  
  mysql_init(&myserver);
  if (!(mysql_real_connect(&myserver,"granite","wkuhns",NULL,"sensor",0,NULL,0))){
    printf("Error Connecting\n");
    abort();
  }
  
  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;
  
  while (1){
    sprintf(&outbuff[0],"insert into logitem (ts1,apid,ch0,ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8,ch9,ch10,ch11,ch12,ch13,ch14,ch15,dio0,dio1,dio2,dio3,dio4,dio5,dio6,dio7) values (NULL,6,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%f,%d,%d,%d,%d,%d,%d,%d,%d)", shm->advalue[0],shm->advalue[1],shm->advalue[2],shm->advalue[3],shm->advalue[4],shm->advalue[5],shm->advalue[6],shm->advalue[7],shm->advalue[8],shm->advalue[9],shm->advalue[10],shm->advalue[11],shm->advalue[12],shm->advalue[13],shm->advalue[14],shm->advalue[15], shm->diovalue[0]&255, shm->diovalue[1] & 255, shm->diovalue[2] & 255, shm->diovalue[3] & 255, shm->diovalue[4]&255, shm->diovalue[5] & 255, shm->diovalue[6] & 255, shm->diovalue[7] & 255);
    //printf ("%s\n",outbuff);
    mysql_query(&myserver,outbuff);
    
    // 30 second interval
    start_usec += 30000000;
    gettimeofday(&now,NULL);
    now_usec = now.tv_sec * 1000000 + now.tv_usec;
    
    usleep(start_usec - now_usec);
  }

}
