#define MY_DEBUG
// Enable and select radio type attached 
#define MY_RADIO_RF24
// #define MY_RF24_PA_LEVEL RF24_PA_MIN
// #define MY_RF24_PA_LEVEL RF24_PA_LOW
#define MY_RF24_PA_LEVEL RF24_PA_HIGH
//#define MY_RF24_PA_LEVEL RF24_PA_MAX

#define MY_RF24_CHANNEL 14

// // INFO coincell optimization
// // https://www.openhardware.io/view/398/NModule-Temperature-Humidity-Light-Door-sensor-shield#tabs-source
// #define MY_TRANSPORT_UPLINK_CHECK_DISABLED

// Timeout for transport to be ready during initialization, after this duration, even if it didn't manage to enable transport the node will enter the loop() method
// For battery powered nodes, I set this to 5000 so after 5 seconds it will stop eating the battery
// 5s is long enough to connect to gateway so you should connect your node back to your computer and check the log if your node cannot connect
#define MY_TRANSPORT_WAIT_READY_MS  5000 // no more than 5 seconds of waiting for transport to be ready

// Reduce maximum delay before going to sleep, as we do not want to kill the battery if gateway is not available
// Before going to sleep MySensors will make sure we don't have a connection problem to MySensors network
// If this value is too high and you have connection problem, MySensors will never go to sleep and bye bye battery ...
// If using AA/AAA batteries you can set a longer duration like 5000ms
#define MY_SLEEP_TRANSPORT_RECONNECT_TIMEOUT_MS 2000

#define MY_SKETCH_NAME "vorke_wol"

// #define MY_SIGNING_SIMPLE_PASSWD "C@KptBi1L@5op?8!"
// #define MY_SECURITY_SIMPLE_PASSWD "C@KptBi1L@5op?8!"

#include <SPI.h>
#include <MySensors.h>


#define CHILD_ID_RELAY 1
#define CHILD_ID_STATUS 2

MyMessage msgRelay(CHILD_ID_RELAY, V_STATUS);
MyMessage msgStatus(CHILD_ID_STATUS, V_STATUS);

#define SWITCH_PIN 7  // Connects to PC817 Anode (Pin D7)
#define STATUS_PIN 3  // Connects to PC817 Anode (Pin D7)

// detecter si l'ordi est alumé (a partir des led du front panel)
// const int statusPin = A1;
// float vOUT = 0.0;
// float vIN = 0.0;
// float R1 = 10000.0;
// float R2 = 1000.0;
// int value = 0;
int status = 0;
int old_status = 0;

void presentation()  
{ 
  #ifdef MY_DEBUG
    Serial.println("- - - - - presentation - - - - -");
  #endif
  
  // Send the sketch version information to the gateway
  sendSketchInfo("vorke-wol", "0.2.4");
  
  // Register all sensors to gw (they will be created as child devices)
  present(CHILD_ID_RELAY, S_BINARY, "Button");
  present(CHILD_ID_STATUS, S_BINARY, "Status");
}

void setup(void)
{

  #ifdef MY_DEBUG
    Serial.println("- - - - - setup - - - - -");
  #endif
  // sensors.begin();

  pinMode(STATUS_PIN, INPUT);

  pinMode(SWITCH_PIN, OUTPUT);
  digitalWrite(SWITCH_PIN, LOW);   // Turn OFF the optocoupler
  send(msgRelay.set(0));

  send(msgStatus.set(0));
}

void loop(void)
{

  // #ifdef MY_DEBUG
  //   Serial.println("- - - - - loop - - - - -");
  // #endif
  

  // état de l'ordi
  // value = analogRead(statusPin);
  // vOUT = (value * 3.3) / 1024.0;
  // vIN = vOUT / (R2 / (R1 + R2));
  // if (vIN >= 0.5) {
  //   status = 1;
  // }else{
  //   status = 0;
  // }

  int value = digitalRead(STATUS_PIN);
  if (value == LOW) {
    status = 1;
  }else{
    status = 0;
  }

  if( status != old_status){
    #ifdef MY_DEBUG
      Serial.print(F("Status: "));
      // Serial.print(F("vIN: "));
      // Serial.print(vIN);
      Serial.print(F(" status: "));
      Serial.println(status);
    #endif

    old_status = status;
    send(msgStatus.set(status));
  }
  

  // digitalWrite(SWITCH_PIN, HIGH);  // Turn ON the optocoupler (Activates output)
  // send(msgRelay.set(1));
  // delay(1000);  // Wait 2 seconds
  // digitalWrite(SWITCH_PIN, LOW);   // Turn OFF the optocoupler
  // send(msgRelay.set(0));
  
  // sleep(10000);

}

// info https://www.home-assistant.io/integrations/mysensors/#light-example-sketch-for-mysensors-2x

// Handle incoming messages 
void receive(const MyMessage &message) {

  #ifdef MY_DEBUG
    Serial.println("- - - - - receive - - - - -");
  #endif

  if (message.type == V_STATUS) {
    // Write some debug info
    Serial.print("Incoming change for sensor:");
    Serial.print(message.getSensor());
    Serial.print(", New status: ");
    Serial.println(message.getBool());
    int newstatus = message.getInt();
    switch (message.sensor)
    {
      case CHILD_ID_RELAY:
        if (newstatus == 1)
        {
          if ( status == 0){
            digitalWrite(SWITCH_PIN, HIGH);  // Turn ON the optocoupler (Activates output)
            send(msgRelay.set(1));
            sleep(500);
            digitalWrite(SWITCH_PIN, LOW);  // Turn ON the optocoupler (Activates output)
          }
          send(msgRelay.set(0));
        }
        break;
      case CHILD_ID_STATUS:
        send(msgStatus.set(status));
        break;
    }

  }
}
