#include <avr/dtostrf.h>
#include <RFM69.h>            //https://www.github.com/lowpowerlab/rfm69
#include <RFM69_ATC.h>        //https://github.com/lowpowerlab/RFM69
#include <SPIFlash.h>         //get it here: https://www.github.com/lowpowerlab/spiflash
#include <SPI.h>              //included with Arduino IDE (www.arduino.cc)
#include <DHT.h>              //https://github.com/adafruit/DHT-sensor-library
#include <SparkFunBME280.h>
#include <Wire.h>
#include <RTCZero.h>

#define FREQUENCY             RF69_433MHZ
#define ATC_RSSI              -80
#define FLASH_SS              8 // SPI Flash

#define REQ_MAX_SIZE          7
#define DHTTYPE               DHT22   // DHT 22  (AM2302), AM2321
#define PIN_STATE_SIZE        4
#define DHT_SIZE              12
#define BME_SIZE              18
#define GATEWAYID             1    //unique ID of the gateway/receiver
#define NODEID                2
#define NETWORKID             110  //the same on all nodes that talk to each other
#define ENCRYPTKEY            "supersecure" //exactly the same 16 characters/bytes on all nodes!
#define NOTIFICATION_TIME     5
#define INPUT_SIZE    11
#define BME_ENABLED
//#define DHT_ENABLED

RTCZero zerortc;

const byte alarmSeconds = 5;
const byte alarmMinutes = 0;
const byte alarmHours = 0;

volatile bool alarmFlag = false; // Start awake

#ifdef DHT_ENABLED
#define DHT_PIN               4
DHT dht(DHT_PIN, DHTTYPE);
#endif
#define SERIAL_ENABLED             //comment this out when deploying to an installed Mote to save a few KB of sketch size

#ifdef SERIAL_ENABLED
#define SERIAL_BAUD    115200
#define Serial SERIAL_PORT_USBVIRTUAL // Required for Serial on Zero based boards
#define DEBUG(input)   {SerialUSB.print(input); delay(1);}
#define DEBUG_Format(input, format)   {SerialUSB.print(input, format); delay(1);}
#define DEBUGln(input) {SerialUSB.println(input); delay(1);}
#define DEBUG_Flush() { SerialUSB.flush(); }
#else
#define DEBUG(input);
#define DEBUG_Format(input, format);
#define DEBUGln(input);
#define DEBUG_Flush();
#endif

byte LEDSTATE = LOW; //LOW=0
RFM69_ATC radio;
SPIFlash flash(FLASH_SS, 0xEF30);
char request[REQ_MAX_SIZE];

#ifdef BME_ENABLED
BME280 bme280;
double F,P,H;
char Pstr[10];
char Fstr[10];
char Hstr[10];
#endif

char buffer[BME_SIZE];

void setup() {
  hardwareSetup();
  flashSetup();
  radioSetup();

  zerortc.begin(); // Set up clocks and such
  
  resetAlarm();  // Set alarm
  zerortc.attachInterrupt(alarmMatch); // Set up a handler for the alarm
}

void loop() {
  if (alarmFlag == true) {
    alarmFlag = false;  // Clear flag
    DEBUGln("Alarm went off - I'm awake!");
    blink(4, 1000);
  }

  Receive();
  if (request[0] != (char)0) {
    blink(2, 1000);
    DEBUG("Request Receieved: ");
    DEBUGln(request);
    char reqType = request[0];

    switch (reqType) {
      case 'B':
        DEBUG("Button Request on Pin: ");
        DEBUGln(request[1]);
        break;
      case 'W':
        DEBUGln("Weather Request");
        handleWeatherRequest();
        break;
      case 'T':
        DEBUG("Toggle Request on Pin: ");
        DEBUGln(request[1]);
        break;
      case 'P':
        DEBUG("Set Pin State Request on Pin: ");
        uint8_t pin = (request[1] & 0x0f);
        uint8_t state = (request[2] & 0x0f);
        DEBUG(pin);
        DEBUG(" state: ");
        DEBUGln(state);
        
        handleSetPinRequest(pin, state);
        break;
    }

    request[0] = (char)0;
  }
  else {
    DEBUGln("No Data");
  }

  DEBUG_Flush(); //make sure all serial data is clocked out before sleeping the MCU

  resetAlarm();  // Reset alarm before returning to sleep
  DEBUGln("Alarm set, going to sleep now.");
  zerortc.standbyMode();    // Sleep until next alarm match

  //delay(5000);
  //flash.sleep();
  //radio.sleep(); //you can comment out this line if you want this node to listen for wireless programming requests


#endif
}

void handleSetPinRequest(uint8_t pin, uint8_t state) {
  char pinData[PIN_STATE_SIZE];
  pinData[0] = 'P';
  
  pinMode(pin, OUTPUT);
  
  if(state == 0){
    digitalWrite(pin, LOW);
  }else{
    digitalWrite(pin, HIGH);
  }
  
  int currentState = digitalRead(pin);   // read the input pin

  if(state == currentState){
    pinData[1] = '1';
  } else{
    pinData[1] = '0';
  }
  
  if(currentState == 0){
    pinData[2] = '0';
  }else{
    pinData[2] = '1';
  }

  pinData[3] = 0x00;

  DEBUGln(pinData);

  radio.sendWithRetry(GATEWAYID, pinData, strlen(pinData), 1); //retry one time
}

void handleWeatherRequest(){
#ifdef DHT_ENABLED
  
  char float_bufF[6];
  char float_bufH[6];
  float temp;
  float humidity;

  //read values from the DHT22 sensor, convert floats to string, assign to struct
  temp = dht.readTemperature(true);
  humidity = dht.readHumidity();
  dtostrf(temp, 2, 2, float_bufF);
  dtostrf(humidity, 2, 2, float_bufH);
  sprintf(buffer, "W1%s%s", float_bufF, float_bufH);
#else
  DEBUGln("No DHT Device setup.");
  #ifdef BME_ENABLED
  #else
    strcat(buffer, "W0");
  #endif
#endif

#ifdef BME_ENABLED

  bme280.setMode(MODE_FORCED); //Wake up sensor and take reading
  P = bme280.readFloatPressure() * 0.0002953; //read Pa and convert to inHg
  F = bme280.readTempF();
  H = bme280.readFloatHumidity();
  bme280.setMode(MODE_SLEEP);

  dtostrf(F, 3,2, Fstr);
  dtostrf(H, 3,2, Hstr);
  dtostrf(P, 3,2, Pstr);

  sprintf(buffer, "W1%s%s%s", Fstr, Hstr, Pstr);
  //DEBUGln(buffer);
#else
  DEBUGln("No BME Device setup.");
  #ifdef DHT_ENABLED
  #else
    strcat(buffer, "W0");
  #endif
#endif

  radio.sendWithRetry(GATEWAYID, buffer, strlen(buffer), 1); //retry one time
  DEBUGln(buffer);

  blink(2, 1000);
}

void Receive() {

  //sprintf(request, "%s", "W");
  
  //check for any received packets
  if (radio.receiveDone())
  {
    for (byte i = 0; i < radio.DATALEN; i++) {
      request[i] = (char)radio.DATA[i];
    }

    DEBUG('['); DEBUG_Format(radio.SENDERID, DEC); DEBUGln("] ");
    DEBUGln(request);
    DEBUG("   [RX_RSSI:"); DEBUG(radio.RSSI); DEBUGln("]");

    if (radio.ACKRequested())
    {
      radio.sendACK();
      DEBUG(" - ACK sent");
    }

    blink(1, NOTIFICATION_TIME);
    DEBUGln();
  }

#ifdef SERIAL_ENABLED
    static boolean recvInProgress = false;
    static boolean nodeIdFound = false;
    static byte ndx = 0;
    static byte nodeIndex = 0;
    char startMarker = '[';
    char endMarker = ']';
    char rc;
    
  while (SerialUSB.available() > 0) {
    rc = SerialUSB.read();
    if (recvInProgress == true) {
        if (rc != endMarker) {
            request[ndx] = rc;
            ndx++;
            if (ndx >= INPUT_SIZE) {
                ndx = INPUT_SIZE - 1;
            }
        }
        else {
            request[ndx] = '\0'; // terminate the string
            recvInProgress = false;
            nodeIdFound = false;
            ndx = 0;
            //DEBUG(request);
        }
    }
    else if (rc == startMarker) {
        recvInProgress = true;
    }
  }
#endif
}

void hardwareSetup() {
#ifdef SERIAL_ENABLED
  SerialUSB.begin(SERIAL_BAUD);
  delay(500);
#endif
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(0, INPUT_PULLUP); //using internal pullup, makes pin 0 active low

#ifdef DHT_ENABLED
  dht.begin();
#endif

#ifdef BME_ENABLED
  bmeSetup();
#endif

  blink(3, 500);
  delay(100);
}

void flashSetup() {
  if (flash.initialize()) {
    flash.sleep();
  }
}


void radioSetup() {
  radio.initialize(FREQUENCY, NODEID, NETWORKID);
  radio.setHighPower(); //only for RFM69HW!
  radio.encrypt(ENCRYPTKEY);
  radio.enableAutoPower(ATC_RSSI);
  radio.sleep();
}

void bmeSetup() {
#ifdef BME_ENABLED
  Wire.begin();
  Wire.setClock(400000); //Increase to fast I2C speed!

  bme280.setI2CAddress(0x77); //0x76,0x77 is valid.
  bme280.beginI2C();
  bme280.setMode(MODE_FORCED); //MODE_SLEEP, MODE_FORCED, MODE_NORMAL is valid. See 3.3
  bme280.setStandbyTime(0); //0 to 7 valid. Time between readings. See table 27.
  bme280.setFilter(0); //0 to 4 is valid. Filter coefficient. See 3.4.4
  bme280.setTempOverSample(1); //0 to 16 are valid. 0 disables temp sensing. See table 24.
  bme280.setPressureOverSample(1); //0 to 16 are valid. 0 disables pressure sensing. See table 23.
  bme280.setHumidityOverSample(1); //0 to 16 are valid. 0 disables humidity sensing. See table 19.
  P = bme280.readFloatPressure() * 0.0002953; //read Pa and convert to inHg
  F = bme280.readTempF();
  H = bme280.readFloatHumidity();
  bme280.setMode(MODE_SLEEP);
#endif
}

void blink(byte times, byte mseconds) {
  for (byte i = 0; i < times; i++) {
    if (i > 0) delay(mseconds);
    digitalWrite(LED_BUILTIN, HIGH);
    delay(mseconds);
    digitalWrite(LED_BUILTIN, LOW);
  }
}

void alarmMatch(void)
{
  alarmFlag = true; // Set flag
}

void resetAlarm(void) {
  byte seconds = 0;
  byte minutes = 0;
  byte hours = 0;
  byte day = 1;
  byte month = 1;
  byte year = 1;
  
  zerortc.setTime(hours, minutes, seconds);
  zerortc.setDate(day, month, year);

  zerortc.setAlarmTime(alarmHours, alarmMinutes, alarmSeconds);
  zerortc.enableAlarm(zerortc.MATCH_HHMMSS);
}
