#include "DHT.h"
#include <ESP8266WiFi.h>
#include "aREST.h"
#include <climits>

//If the debug macro is enabled, there's a freeMemory routine
//Check if this resolves the crashes...
#define DEBUG_MODE 1


//DHT settings:
#define DHTPIN 14     // what digital pin we're connected to

#define MEASURESECONDS 60 //shouldn't be < 2sec

// Uncomment whatever type you're using!
//#define DHTTYPE DHT11   // DHT 11
#define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)


// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors.  This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);

// Create aREST instance
aREST rest = aREST();

// WiFi settings:
const char* ssid = "Your_SSID";
const char* password = "Your_Password";

#define LISTEN_PORT 80

// Create an instance of the server
WiFiServer server(LISTEN_PORT);

// Variables to be exposed to the API
float temperature;
float humidity;


//milli counter
unsigned long millitotal = 0;
float millicounter = 0;

//Temp variables
float h, t;

//First measurement
bool firstmeasurement = true;


void setup() {
  Serial.begin(115200);
  Serial.println("Sensornode start");

  //dht driver initialization
  dht.begin();

  //Expose variables to the rest api
  rest.variable("temperature", &temperature);
  rest.variable("humidity", &humidity);

  // Set a ID (ID must be greater than 0)
  rest.set_id("1");
  rest.set_name("sensornode");


  // Connect to WiFi
  Serial.println("Connecting to wlan");
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("\nWiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
  // Wait a few seconds between measurements.
  millicounter = millis();
  
  if (millicounter >= millitotal) {
    // Reading temperature or humidity takes about 250 milliseconds!
    // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
    h = dht.readHumidity();
    // Read temperature as Celsius (the default)
    t = dht.readTemperature();
    
    // Check if any reads failed and exit early (to try again).
    if (isnan(h) || isnan(t)) {
      Serial.println("Failed to read from DHT sensor!");
      return;
    } else {
      //set the new values
      humidity = h;
      temperature = t;
    }

    //set new milli counter
    //millis will overflow after approx. 52 days. To prevent errors we're checking the limits
    if (millis() + (MEASURESECONDS * 1000) <= ULONG_MAX) {
      millitotal = millis() + (MEASURESECONDS * 1000);
    } else {
      millitotal = 0;
    }
  }
  // Handle REST calls
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  while(!client.available()){
    delay(1);
  }
  rest.handle(client);

  //Let the esp chill a bit
  delay(100);
}
