#include <TinyPower.h>
#include <Tiny.h>

// Pins
#define SWITCH 0
#define SENDER 2

ContactSensor sensor = ContactSensor(WINDOW2, SENDER);

volatile int counter = 0;
volatile bool shouldSend = true;
bool currentState = false;

void setup() {
    
  pinMode(SWITCH, INPUT_PULLUP);

  sensor.setup();

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

void loop() {
  if (shouldSend) {
	  shouldSend = false;
	  currentState = digitalRead(SWITCH);
	  sensor.sendState(currentState);
  }
  TinyPower::sleep();
}

ISR(PCINT0_vect) {
  shouldSend = true;
  wdt_reset();
  counter = 0;
  TinyPower::enableWdt(WDTO_8S);
}

ISR(WDT_vect) {
  counter++;
  if (counter == 1) {
	  shouldSend = true;
	  return;
  }
  if (counter % 75 == 0) {
	  shouldSend = true;
  }
  if (!currentState && counter >= 225) {
	  TinyPower::disableWdt();
  }
}
