#include "nodeCodeHeader.h"

nodeReadings::nodeReadings() {

  //Making all the new object as defined in the .h file
  dht = new DHT(DHTPIN, DHTTYPE);
  display = new Adafruit_SH1106G(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
  webSocket = new websockets();
  sgp = new Adafruit_SGP30();

  //setting the reding for every 5 sec
  interval = 5000;
  resetValues();  

}

//Script for simpley reseting every value to 0
void nodeReadings::resetValues() {
    counter = 0;
    eCO2 = 0;
    TVOC = 0;
    temperature = 0;
    humidity = 0;
    currentMillis = 0;
    lastMillis = 0;
    errorSGP30 = false;
    errorDHT11 = false;
    noise = false;
}

//Setup for initilising the dht and sgp sensors. Also the display is set up.
void nodeReadings::setup(){
    // make serial connection at 115200 baud
    Serial.begin(115200);

    // tell display what settings to use
    display->begin(i2c_adress, true);
    display->clearDisplay();

    // tell sensors to start reading
    dht->begin();
    sgp->begin();

    pinMode(MICPIN, INPUT);
    pinMode(DHTPIN, INPUT);
    
    webSocket->websocketSetup();

}

void nodeReadings::loop() {
    // update when interval is met
    if (currentMillis - lastMillis >= interval){
        lastMillis = millis();
        update();
    }

    // update the counter
    currentMillis = millis();

    // loop the websocket connection so it stays alive
    webSocket->loop();
}

void nodeReadings::update(){

  // display sensordata on oled screen
  displayData();
  
  //send the data to the websockets
  webSocket->sendMyText("{\"node\": \"" + String(WiFi.macAddress()) + "\", \"Temp\":\"" + String(temperature) + "\",\"Humi\":\"" + String(humidity) + "\",\"eCO2\":\"" + String(sgp->eCO2) + "\",\"TVOC\":\"" + String(sgp->TVOC) + "\"}");

  sgp->getIAQBaseline(&eCO2_base, &TVOC_base);

  // read dht11 sensor
  temperature = float(dht->readTemperature());
  humidity = float(dht->readHumidity());

  // check if any errors occured when reading sensors
  checkForError();
}

void nodeReadings::displayData() {
  // clear display for new info
  display->clearDisplay();

  // display the data on the oled screen
  display->setTextSize(2);
  display->setTextColor(SH110X_WHITE);
  display->setCursor(0,0);
  display->println("Temp: " + String(int(temperature)) + "C");
  display->println("Humi: " + String(int(humidity)) + "%");
  display->println("eCO2: " + String(sgp->eCO2));// + " ppm");
  display->println("TVOC: " + String(sgp->TVOC));// + " ppb");
  display->display();
}

//function 
void nodeReadings::checkForError(){
  if (!sgp->IAQmeasure()) {
    Serial.println("SGP30: BAD");
    errorSGP30 = true;
  } else {
    Serial.println("SGP30: OK");
    errorSGP30 = false;
  }

  if (isnan(temperature) || isnan(humidity)){
    Serial.println("DHT11: BAD");
    errorDHT11 = true;
  } else {
    Serial.println("DHT11: OK");
    errorDHT11 = false;
  }
}