#include <Arduino.h>
#include <TinyPower.h>
#include "Tmp36Sensor.h"
#include "Dht22Sensor.h"

#define SEND_INTERVAL 450						// 450*8s = ~60min
#define SEND_VCC_INTERVAL (SEND_INTERVAL*12)	// every 12 hours

// Pins
#define SENDER PIN_B2

#if !DHT_SENSOR
TempSensor &tempSensor = *(new Tmp36Sensor(TEMP_SENSOR));
#else
TempSensor& tempSensor = *(new Dht22Sensor(TEMP_SENSOR));
#endif

volatile int counter = 0;

void setup() {

	tempSensor.setup();

	TinySwitch::setup(SENDER);
	TinyPower::setup();
	TinyPower::enableWdt(WDTO_8S);
}

void loop() {
	static bool retry = false;

	if (retry || (counter % SEND_INTERVAL == 0)) {
		bool success = tempSensor.readTemp();
		if (success) {
			if (counter % SEND_VCC_INTERVAL == 0) {
				tempSensor.sendValues(true);
				counter = 0;
			} else {
				tempSensor.sendValues();
			}

			tempSensor.turnOffSensor();
		}
		if (retry && !success) {
			tempSensor.turnOffSensor();
		}
		retry = !retry && !success;
	}
	TinyPower::sleep();
}

ISR(WDT_vect) {
	counter++;
	if (((counter + 1) % SEND_INTERVAL == 0) || ((counter + 1) % SEND_VCC_INTERVAL == 0)) {
		tempSensor.turnOnSensor();
	}
}
