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

#define DEBUG 0
#define RC_SWITCH 1

// Pins
#define SWITCH 0

#if DEBUG
#define RxD 3
#define TxD 4
SoftwareSerial AttinySerial(RxD,TxD);
#endif

#if RC_SWITCH
#define SENDER 2
RCSwitch mySwitch = RCSwitch();
#endif

void debug(const char* msg);

char* group = "11111";
int number = 4;
bool stateOn = false;

void setup() {
    
#if DEBUG
  AttinySerial.begin(9600);
#endif
  
#if RC_SWITCH
  pinMode(SWITCH, INPUT_PULLUP);
  mySwitch.enableTransmit(SENDER);
  mySwitch.setProtocol(1);
#endif

  TinyPower::setup();
}

void loop() {
  debug("loop");
  TinyPower::sleep();
}

void sendCommand(boolean on) {
  if (on) {
#if RC_SWITCH
    mySwitch.switchOn(group, 4);
#endif
    debug("switch on");
  } else {
#if RC_SWITCH
    mySwitch.switchOff(group, 4);
#endif
    debug("switch off");
  }
}

ISR(PCINT0_vect) {
  byte state = digitalRead(SWITCH);
  if (state == LOW) {
    debug("state is low");
    TinyPower::enableWdt(WDTO_1S);
  }
}

ISR(WDT_vect) {
  TinyPower::disableWdt();
  debug("wdt");
  byte state = digitalRead(SWITCH);
  if (state == LOW) {
    sendCommand(false);
  } else {
    sendCommand(true);
  }
}

void debug(const char* msg) {
#if DEBUG
  AttinySerial.println(msg);
#endif
}

