/*
 * main.cpp
 *
 *  Created on: 08.10.2016
 *      Author: jam
 */
#include "gnublin.h"
#include <poll.h>
#include <fcntl.h>
#include <signal.h>
#include <stropts.h>
#include <pthread.h>
#include <ctime>
#include <stdio.h>
#include <stdlib.h>

using namespace std;
void byebye(int s);
void *interrupt(void*);
void *akkustatus(void*);

pthread_mutex_t region_mutex = PTHREAD_MUTEX_INITIALIZER;

int rad;
gnublin_gpio gpio;


int main()
{
	//run byebye function on "CTRL+c"
	signal (SIGINT,byebye);
	//initialize handler
	pthread_t interrupt_thread;
	pthread_t akkustatus_thread;
	//create threads
	pthread_create(&akkustatus_thread,NULL,akkustatus,NULL);
	pthread_create(&interrupt_thread,NULL,interrupt,NULL);
	//wait until the threads are terminated.... never(while (1))....
	pthread_join(interrupt_thread,NULL);
	pthread_join(akkustatus_thread,NULL);
	cout << "main beendet!" << endl;
}



void *interrupt(void*){
	const char *file1="/sys/class/gpio/gpio11/value";
	struct pollfd fds;
	int bytes_read;
	char buf[2];
	int ret;

	//export gpios and switch 'em to input
	gpio.pinMode(11,INPUT);
	string dir = "/sys/class/gpio/gpio11/edge";
	ofstream file (dir.c_str());
	if (file < 0) {
		exit(0);
		cout << "cannot open file: "<< dir << endl;
	}
	file << "rising";
	file.close();

	/* Open STREAM devices */
	fds.fd = open(file1, O_RDWR);
	fds.events = POLLPRI;
	cout << "Start Whileschleife in Threat-Funktion" << endl;
	while(1){
		// call read systemcall on file. this has to be called before poll
		bytes_read = read(fds.fd, buf, 1);
		ret = poll(&fds, 1, -1);
		if (ret > 0) {
			// An event on one of the fds has occurred.
			if (fds.revents & POLLPRI) {
				//lock rad
				pthread_mutex_lock(&region_mutex);
				rad++;
				cout << "Taste wurde gerdrückt!" << endl;
				system ("shutdown -h now");
				//unlock rad
				pthread_mutex_unlock(&region_mutex);
			}
		}
	}
	pthread_exit(0);
	return 0;
}

void *akkustatus(void*){
	int poti_spannung;
	int impuls_anzahl = 0;
	gnublin_adc ad_2_poti;
	gnublin_gpio gpio_obj;
	gpio_obj.pinMode(14, "output");
	gpio_obj.digitalWrite(14, 0);
	while(1)
	{
		poti_spannung = ad_2_poti.getVoltage(1); //ADC1-pin
		if(poti_spannung > 3100){
			impuls_anzahl = 1;
		}
		else if(poti_spannung >= 3000 && poti_spannung < 3100){
			impuls_anzahl = 2;
		}
		else if(poti_spannung >= 2900 && poti_spannung < 3000){
			impuls_anzahl = 3;
		}
		else if(poti_spannung >= 2800 && poti_spannung < 2900){
			impuls_anzahl = 4;
		}
		else{
			impuls_anzahl = 5;
		}
		gpio_obj.digitalWrite(14, 0);
		sleep(2);
		while(impuls_anzahl){
		gpio_obj.digitalWrite(14, 1);
		usleep(100000);
		gpio_obj.digitalWrite(14, 0);
		usleep(500000);
		impuls_anzahl--;
		}
	}
	return 0;
}

void byebye(int s){
	gpio.unexport(11);
	gpio.unexport(14);
    exit(0);
}

