#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"    
#include "sys/ioctl.h"
#include "fcntl.h"     
#include "asm/etraxgpio.h"
#include "include/mysql.h" 

#define def_host_name   "192.168.0.100" // Put here the IP address of your MySQL server
#define def_user_name   "fox"           // Put here your MySQL user
#define def_password    "fox"           // Put here your MySQL password
#define def_db_name     "logger"


MYSQL  *conn;
int fd;

void led_on() {
  int iomask;
  iomask=1<<25;
  ioctl(fd,_IO(ETRAXGPIO_IOCTYPE,IO_SETBITS),iomask);
}

void led_off() {
  int iomask;
  iomask=1<<25;
  ioctl(fd,_IO(ETRAXGPIO_IOCTYPE,IO_CLRBITS),iomask);
}

void led_blink(int number) {
  int i;
  for (i=0;i<number;i++) 
  {  
    led_on();
    usleep(100000);
    led_off();
    usleep(100000);
  }
}

int get_switch() { 
  int iomask;
  int value;

  iomask=1<<16;
  value=ioctl(fd, _IO(ETRAXGPIO_IOCTYPE, IO_READBITS));

  if ((value&iomask)==0) return 1;
  else return 0;
}

int main (int argc, char *argv[])
{
  if ((fd = open("/dev/gpiog", O_RDWR))<0) {
    printf("Open error on /dev/gpiog\n");
    exit(0);
  }
  
  conn = mysql_init (NULL);
  if (conn == NULL)
  {
   fprintf (stderr, "mysql_init() failed (probably out of memory)\n");
   led_blink(6);
   exit (1);
  }
  if (mysql_real_connect (
    conn,          /* pointer to connection handler */
    def_host_name, /* host to connect to */
    def_user_name, /* user name */
    def_password,  /* password */
    def_db_name,   /* database to use */
    0,             /* port (use default) */
    NULL,          /* socket (use default) */
    0)             /* flags (none) */
    == NULL)
  {
    fprintf (stderr, "mysql_real_connect() failed:\n");
    fprintf (stderr, "Error %u (%s)\n", mysql_errno (conn), mysql_error (conn));
    led_blink(5);
    exit (1);
  }

  while (1) {
    if (get_switch()) {
      led_on();
      if (mysql_query (conn, "INSERT INTO switch (switchid,description) VALUES ('IOG16','Switch pressed')") != 0)
      {
        printf("INSERT statement failed\n");
        led_blink(4);
        exit (1);
      }
      else
      {
        printf ("INSERT statement succeeded: %lu rows affected\n",(unsigned long) mysql_affected_rows (conn));
      }
      led_blink(1);
      while(get_switch());
    }
  }

  mysql_close (conn);
  close(fd);
  exit (0);
}
