#include <SPI.h>
#include <Wire.h>
#include <ESP8266WiFi.h>
#include <Adafruit_BME280.h>
#include <Adafruit_Sensor.h>
#include <ArduinoJson.h>

#define SEALEVELPRESSURE_HPA (1013.25)
Adafruit_BME280 bme; // I2C

int moisture=0;
//Rele 1=d1
int relay=D5;

// Replace with your network credentials
const char* ssid     = "SSID";
const char* password = "PASSWORD";

// Set web server port number to 80
WiFiServer server(80);
IPAddress ip(192, 168, 1, 241);     // where xx is the desired IP Address
IPAddress gateway(192, 168, 1, 1); // set gateway to match your network


// Variable to store the HTTP request
String header;

//DEEPSLEEP
// sleep for this many seconds
//const int sleepSeconds = 60;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  while(!Serial) { delay(100); }

  Serial.println("\n\nWake up");
  // Connect D0 to RST to wake up
  //pinMode(D0, WAKEUP_PULLUP);
  
  //Serial.print("Rele 1 POIS \r\n");
  pinMode(relay,OUTPUT);
  pinMode(BUILTIN_LED, OUTPUT);
  digitalWrite(relay,LOW);
  delay(200);
  digitalWrite(relay,HIGH);

  
  if (!bme.begin(0x76)) {
    Serial.println("Could not find a valid BME280 sensor, check wiring!");
    //while (1);
    //blink 2 times for failure with bme280
    digitalWrite(BUILTIN_LED, LOW);
    delay(100);
    digitalWrite(BUILTIN_LED, HIGH);
    delay(500);
    digitalWrite(BUILTIN_LED, LOW);
    delay(100);
    digitalWrite(BUILTIN_LED, HIGH);
    delay(500);
    digitalWrite(BUILTIN_LED, LOW);
    delay(100);
    digitalWrite(BUILTIN_LED, HIGH);
  } 

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  IPAddress subnet(255, 255, 255, 0); // set subnet mask to match your network
  WiFi.config(ip, gateway, subnet);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
    
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();

  //blink 20 times fast for success connection!
  for (int i = 0; i < 20; i++)
  {
    digitalWrite(BUILTIN_LED, LOW);
    delay(100);
    digitalWrite(BUILTIN_LED, HIGH);
    delay(100);
  }
  
  Serial.print("Alustettu \r\n");
}

void loop() {
  moisture = analogRead( 0);
  Serial.print(moisture);
  Serial.print("\r\n");
  if(moisture > 500) {
    digitalWrite(relay,LOW);
    Serial.print("Rele 1 PÄÄLLE \r\n");
  } else {
    digitalWrite(relay,HIGH);
    Serial.print("Rele 1 POIS \r\n");
  }

  WiFiClient client = server.available();   // Listen for incoming clients
  if (client) {                             // If a new client connects,        
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        String request = client.readStringUntil('\r');
        client.flush();
        if(request.indexOf("/json") != -1) {
          // Allocate a temporary JsonDocument
          // Use arduinojson.org/v6/assistant to compute the capacity.
          StaticJsonDocument<200> doc;
          JsonObject sensordata = doc.to<JsonObject>(); //doc.createNestedObject();
          //Comment bme read temperatures off if you have some problems with the server!
          sensordata["temperature"] = bme.readTemperature();
          sensordata["humidity"] = bme.readHumidity();
          //sensordata["pressure"] = (bme.readPressure() / 100.0F);
          sensordata["soilmoisture"] = moisture;
          serializeJson(doc, Serial);
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: application/json");
          client.println("Connection: close");
          client.print("Content-Length: ");
          client.println(measureJsonPretty(doc));
          client.println(""); //  do not forget this one
          
          // Write JSON document
          serializeJsonPretty(doc, client);
          client.println();
            // Break out of the while loop
            break;
        } else if(request.indexOf("/pumptest") != -1) {
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: application/json");
          client.println("Connection: close");
          client.print("Content-Length: ");
          client.println("pumptest ");
          client.println(""); //  do not forget this one
          for(int i=0; i < 10; i++) {
            digitalWrite(relay,LOW);
            delay(200);
            digitalWrite(relay,HIGH);
          }          
          digitalWrite(relay,HIGH);
        }
      }
    }
  
    // Clear the header variable
    header = "";
    // give the web browser time to receive the data
    delay(100);
    // Close the connection
    client.stop();
    delay(100);
    Serial.println("Client disconnected.");
    Serial.println("");
}
  
  delay(1000);
}
