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

#define SEND_INTERVAL 37						// 37*8s = ~5min
#define SEND_VCC_INTERVAL (SEND_INTERVAL*6)		// every half hour

// Pins
#define SENDER PIN_B2

TempSensor& tempSensor = *(new Dht22Sensor(TEMP_SENSOR));

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();
	}
}
