/*
 * clock.cpp
 *
 *  Created on: 22.11.2018
 *      Author: Hendrik Schutter
 */

#include "openChargeMicro.h"

uint32_t systemTime; // 0 to 4294967295 sec

/* Only call once */
clock::clock() {
	//TODO Singleton
	systemTime = 0;
	clock_init();
	serialSend("init clock\r\n");
}

clock::~clock() {

}

void clock::clock_init() {
	OCR1A = 0x3D08; // --> 1 sec
	TCCR1B |= (1 << WGM12);
	// Mode 4, CTC on OCR1A
	TIMSK1 |= (1 << OCIE1A);
	//Set interrupt on compare match
	TCCR1B |= (1 << CS12) | (1 << CS10);
	// set prescaler to 1024 and start the timer
	sei(); //enable interrupts
}
/* get seconds since boot*/
uint32_t clock::getTime() {
	return systemTime;
}

/* get time struct since time stamp */
struct time_t clock::getTime(struct time_t pTime) {

	struct time_t ret;

	ret.seconds = (getTime() - pTime.seconds);
	ret.diffSecond = ret.seconds;
	ret.diffMinute = 0;
	ret.diffHour = 0;

	while (ret.diffSecond > 59) {
		ret.diffSecond = ret.diffSecond - 60;
		ret.diffMinute++;
	}

	while (ret.diffMinute > 59) {
		ret.diffMinute = ret.diffMinute - 60;
		ret.diffHour++;
	}

	return ret;
}

/* get time struct as time stamp */
struct time_t clock::getTimeStamp() {
	struct time_t ret;

	ret.seconds = getTime();
	ret.diffSecond = ret.seconds;
	ret.diffMinute = 0;
	ret.diffHour = 0;

	while (ret.diffSecond > 59) {
		ret.diffSecond = -60;
		ret.diffMinute++;
	}

	while (ret.diffMinute > 59) {
		ret.diffMinute = -60;
		ret.diffHour++;
	}

	return ret;
}

ISR (TIMER1_COMPA_vect) {
	// action to be done every 1 sec
	systemTime++; //increase system time
}

ISR(__vector_default) {
}
