#include "openChargeMicro.h"

charger* chargers;

void createChargers();
void printStatus();
void checkForBattery();

int main(void) {

	serialSetup();
	serialSend("Hello World - ");
	serialSend(__DATE__ __TIME__);
	serialSend("\r\n");

	clock clk;
	ioController io;

	chargers = (charger *) malloc(CHARGER_SIZE * sizeof(charger));

	io.deactivateChargers();
	io.setActiveLED(true);
	io.activateChargers();

	createChargers();


	//loop till power off
	while (true) {

		checkForBattery();
		printStatus();
	}

	return 0;
}

void checkForBattery() {
	for (int l = 0; l < CHARGER_SIZE; l++) {

		bool zero = false;
		double tmp1 = 0.0;
		double tmp2 = 0.0;
		double difference = 5.0; //TODO after calibation

		for (int i = 0; i < 10; i++) {
			tmp2 = tmp1;
			tmp1 = chargers[l].getVoltage();

			if ((tmp1 == 0.0) || (((tmp1 - tmp2 > difference)) && i != 0)) {
				zero = true;
			}
		}

		if (!zero) {
			/*
			 char charVal[10];
			 dtostrf(chargers[0].getVoltage(), 4, 2, charVal);
			 serialSend("Charger01 - ");
			 serialSend(charVal);
			 serialSend(" Volt\r\n");
			 */
			chargers[l].setStatus(true);
		} else {
			//serialSend("blocked\r\n");
			chargers[l].setStatus(false);
		}

	}

}

void createChargers() {
	s_charger charger_settings;

	charger_settings.chU = CH0_U;
	charger_settings.chI = CH0_I;
	charger_settings.nr = CH0_NR;
	charger chrg0 = charger(charger_settings);
	chargers[0] = chrg0;

	charger_settings.chU = CH1_U;
	charger_settings.chI = CH1_I;
	charger_settings.nr = CH1_NR;
	charger chrg1 = charger(charger_settings);
	chargers[1] = chrg1;

	charger_settings.chU = CH2_U;
	charger_settings.chI = CH2_I;
	charger_settings.nr = CH2_NR;
	charger chrg2 = charger(charger_settings);
	chargers[2] = chrg2;

	charger_settings.chU = CH3_U;
	charger_settings.chI = CH3_I;
	charger_settings.nr = CH3_NR;
	charger chrg3 = charger(charger_settings);
	chargers[3] = chrg3;
}

void printStatus() {
	//serialSend("printing status .. \r\n");
	for (int i = 0; i < CHARGER_SIZE; i++) {
		if (chargers[i].getStatus()) {
			chargers[i].getInfo(); //print values
		}
	}
}

void serialSetup(void) {
	//Register settings
	//High and low bits
	UBRR0H = (BUAD_RATE_CALC >> 8);
	UBRR0L = BUAD_RATE_CALC;
	//transimit and recieve enable
	UCSR0B = (1 << TXEN0) | (1 << TXCIE0) | (1 << RXEN0) | (1 << RXCIE0);
	UCSR0C = (1 << UCSZ01) | (1 << UCSZ00);  //8 bit data format
}

void serialSend(const char* sendString) {
	for (unsigned int i = 0; i < strlen(sendString); i++) {
		while (( UCSR0A & (1 << UDRE0)) == 0) {
		};
		UDR0 = sendString[i];
	}
}

