#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <wiringPi.h>
#include <mysql/mysql.h>

// compile with: gcc -o heizungserver heizungserver.c -lwiringPi -lmysqlclient

#define BUTTON_PIN 8

// the event counter
volatile int eventCounter = 0;

// -------------------------------------------------------------------------
// myInterrupt:  called every time an event occurs
void myInterrupt(void) {
    eventCounter++;
}


// -------------------------------------------------------------------------
// main
int main(void) {
	double verbrauch = 0;
	double total = 0 ;

	MYSQL *conn;
	char *server = "db-ip";
	char *user = "db-user";
	char *password = "db-password"; 
	char *database = "db-name";
	char query [255];
	conn = mysql_init(NULL);

	/* Connect to database */
	if (!mysql_real_connect(conn, server, user, password, database, 0, NULL, 0)) {
		printf(stderr, "%s\n", mysql_error(conn));
		return 1;
	}

	// sets up the wiringPi library
	if (wiringPiSetup () < 0) {
		fprintf (stderr, "Unable to setup wiringPi: %s\n", strerror (errno));
		return 1;
	}

	// set Pin to generate an interrupt on high-to-low transitions
	// and attach myInterrupt() to the interrupt
	if ( wiringPiISR (BUTTON_PIN, INT_EDGE_FALLING, &myInterrupt) < 0 ) {
		fprintf (stderr, "Unable to setup ISR: %s\n", strerror (errno));
		return 1;
	}
  
    // display counter value every second.
	while ( 1 ) {
		eventCounter = 0;
		delay( 60000 );
		verbrauch = (eventCounter * 60);
		total = total + eventCounter ;

		// neue daten einfuen
		sprintf(query, "INSERT INTO stromverbrauch SET datum = NOW(), verbrauch = '%d' ", eventCounter);
		mysql_query(conn, query);

		// alte daten loeschen
		sprintf(query, "DELETE FROM stromverbrauch WHERE DATE_SUB(now(), INTERVAL 60 DAY) >= datum");
		mysql_query(conn, query);

		//    printf( "Verbrauch der letzten 60 sec %f Wh\n", verbrauch );
		//    printf( "TotalVerbrauch seit Programmstart %f kW\n\n", total / 1000);
  }

  return 0;
  mysql_close(conn);
}


