/*
    Sources:
    https://randomnerdtutorials.com/esp32-esp8266-web-server-physical-button/
    https://randomnerdtutorials.com/esp32-pushover-notifications-arduino/
*/

#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebSrv.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <WiFiClientSecure.h>

const char* ssid     = "LeWe";
const char* password = "5275274365464843";

const char* apiToken = "a9k1uyzypuaz1yszqqdzmp17s6r5q2";
const char* userToken = "ukja84pd2n2cmxvdrnfwdrf8eo1wc5";
const char* pushoverApiEndpoint = "https://api.pushover.net/1/messages.json";

const char *PUSHOVER_ROOT_CA = "-----BEGIN CERTIFICATE-----\n"
                               "MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n"
                               "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n"
                               "d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n"
                               "QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n"
                               "MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n"
                               "b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n"
                               "9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n"
                               "CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n"
                               "nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n"
                               "43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n"
                               "T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n"
                               "gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n"
                               "BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n"
                               "TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n"
                               "DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n"
                               "hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n"
                               "06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n"
                               "PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n"
                               "YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n"
                               "CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n"
                               "-----END CERTIFICATE-----\n";


const int PIN_LED = 2;                // esp32 dev board integrated LED
const int PIN_GARAGE_BUTTON = 4;      // button to open/close the garage door
const int PIN_GATE_BUTTON = 16;       // button to open/close the gate
const int PIN_MOWER_ACTIVE = 12;      // only contact mower if pin is LOW
const int PIN_GARAGE = 22;            // relais pin for garage door
const int PIN_GATE = 23;              // relais pin for gate
const int PIN_DOOR_OPEN = 18;         // sensor pin for garage door in position 'open'
const int PIN_DOOR_CLOSED = 19;       // sensor pin for garage door in position 'closed'
const int PIN_SENSOR_GATE = 21;       // sensor pin for gate (HIGH is open)
const int PIN_SPRINKLER1 = 25;        // relais pin for sprinkler 1
const int PIN_SPRINKLER2 = 33;        // relais pin for sprinkler 2
const int PIN_SPRINKLER3 = 32;        // relais pin for sprinkler 3
const int PIN_SPRINKLER4 = 26;        // relais pin for sprinkler 4
const int PIN_MOISTURE_ANALOG = 14;   // moisture sensor analog value  // XXX currently blocked by WiFi
const int PIN_MOISTURE_DIGITAL = 27;  // moisture sensor digital value

AsyncWebServer server(80);
const char* PARAM_MESSAGE = "message";

WiFiClient webClient;
HTTPClient http;

unsigned long sprinklerDuration = 0;
unsigned long sprinklerStartMillis;
int programStatus = 0;


void pushover(String message) {
  StaticJsonDocument<512> notification;
  notification["token"] = apiToken;
  notification["user"] = userToken;
  notification["title"] = "Garage"; //optional
  notification["message"] = message;

  // Serialize the JSON object to a string
  String jsonStringNotification;
  serializeJson(notification, jsonStringNotification);

  WiFiClientSecure client;
  client.setCACert(PUSHOVER_ROOT_CA);

  HTTPClient https;
  https.begin(client, pushoverApiEndpoint);
  https.addHeader("Content-Type", "application/json");
  int httpResponseCode = https.POST(jsonStringNotification);

  if (httpResponseCode > 0) {
    String response = https.getString();
    Serial.println("Pushover response: " + String(httpResponseCode) + ", " + String(response));
  } else {
    Serial.printf("Pushover HTTP response code: %d\n", httpResponseCode);
  }

  https.end();
}

void notFound(AsyncWebServerRequest *request) {
  request->send(404, "text/plain", "Not found");
}

void pinStatus(AsyncWebServerRequest *request) {
  String status = "esp32garage\n\nPIN_LED (" + String(PIN_LED) + ") = " + String(digitalRead(PIN_LED)) + "\n" +
                  "PIN_GARAGE_BUTTON (" + String(PIN_GARAGE_BUTTON) + ") = " + String(digitalRead(PIN_GARAGE_BUTTON)) + "\n" +
                  "PIN_GATE_BUTTON (" + String(PIN_GATE_BUTTON) + ") = " + String(digitalRead(PIN_GATE_BUTTON)) + "\n" +
                  "PIN_MOWER_ACTIVE (" + String(PIN_MOWER_ACTIVE) + ") = " + String(digitalRead(PIN_MOWER_ACTIVE)) + "\n" +
                  "PIN_GARAGE (" + String(PIN_GARAGE) + ") = " + String(digitalRead(PIN_GARAGE)) + "\n" +
                  "PIN_GATE (" + String(PIN_GATE) + ") = " + String(digitalRead(PIN_GATE)) + "\n" +
                  "PIN_DOOR_OPEN (" + String(PIN_DOOR_OPEN) + ") = " + String(digitalRead(PIN_DOOR_OPEN)) + "\n" +
                  "PIN_DOOR_CLOSED (" + String(PIN_DOOR_CLOSED) + ") = " + String(digitalRead(PIN_DOOR_CLOSED)) + "\n" +
                  "PIN_SENSOR_GATE (" + String(PIN_SENSOR_GATE) + ") = " + String(digitalRead(PIN_SENSOR_GATE)) + "\n" +
                  "PIN_SPRINKLER1 (" + String(PIN_SPRINKLER1) + ") = " + String(digitalRead(PIN_SPRINKLER1)) + "\n" +
                  "PIN_SPRINKLER2 (" + String(PIN_SPRINKLER2) + ") = " + String(digitalRead(PIN_SPRINKLER2)) + "\n" +
                  "PIN_SPRINKLER3 (" + String(PIN_SPRINKLER3) + ") = " + String(digitalRead(PIN_SPRINKLER3)) + "\n" +
                  "PIN_SPRINKLER4 (" + String(PIN_SPRINKLER4) + ") = " + String(digitalRead(PIN_SPRINKLER4)) + "\n" +
                  "PIN_MOISTURE_ANALOG (" + String(PIN_MOISTURE_ANALOG) + ") = " + String(analogRead(PIN_MOISTURE_ANALOG)) + "\n" +
                  "PIN_MOISTURE_DIGITAL (" + String(PIN_MOISTURE_DIGITAL) + ") = " + String(digitalRead(PIN_MOISTURE_DIGITAL)) + "\n\n" +
                  "programStatus = " + String(programStatus) + "\n" +
                  "sprinklerDuration = " + String(sprinklerDuration) + "\n" +
                  "sprinklerStartMillis = " + String(sprinklerStartMillis) + "\n\n" +
                  "/ \n" +
                  "/garage[?action=(open|close)] \n" +
                  "/gate[?action=(open|close)] \n" +
                  "/sprinkler[?action=(stop|(start&device={int}&duration={int}))] \n" +
                  "/sprinkler/program[?action=(stop|(start&duration={int}))] \n";

  request->send(200, "text/plain", status);
}

void mowerSafety() {
  Serial.println("mowerSafety()");

  if (http.begin(webClient, "http://192.168.178.54/json?cmd=status&user=lewe&pass=nFdcX3sMD115WAap")) {
    int httpCode = http.GET();

    if (httpCode > 0) {
      if (httpCode == HTTP_CODE_OK) {
        String payload = http.getString();
        String statusStr = payload.substring(payload.indexOf("\"status\": {\"status\": ") + 21);
        statusStr = statusStr.substring(0, statusStr.indexOf(","));

        Serial.println(statusStr);

        if (statusStr.equals("2") or statusStr.equals("3") or statusStr.equals("5") or statusStr.equals("17")) {
          Serial.println("Stop mower");
          if (http.begin(webClient, "http://192.168.178.54/json?cmd=stop&user=lewe&pass=nFdcX3sMD115WAap")) {
            int httpCode = http.GET();

            if (httpCode < 0) {
              Serial.printf("Mower (STOP) HTTP Error: ", http.errorToString(httpCode).c_str());
              pushover("Mower (STOP) HTTP Error: " + http.errorToString(httpCode));
            }
            http.end();
          }
          else {
            Serial.println("Could not send HTTP request (STOP) to mower");
            pushover("Could not send HTTP request (STOP) to mower");
          }
        }
        else {
          Serial.println("no status to be stopped");
        }
      }
    }
    else {
      Serial.printf("Mower (STATUS) HTTP Error: ", http.errorToString(httpCode).c_str());
      pushover("Mower (STATUS) HTTP Error: " + http.errorToString(httpCode));
    }
    http.end();
  }
  else {
    Serial.println("Could not send HTTP request (STATUS) to mower");
    pushover("Could not send HTTP request (STATUS) to mower");
  }
}

void mowerAuto() {
  Serial.println("mowerAuto()");

  if (http.begin(webClient, "http://192.168.178.54/json?cmd=mode&mode=auto&user=lewe&pass=nFdcX3sMD115WAap")) {
    int httpCode = http.GET();

    if (httpCode < 0) {
      Serial.printf("Mower (AUTO) HTTP Error: ", http.errorToString(httpCode).c_str());
      pushover("Mower (AUTO) HTTP Error: " + http.errorToString(httpCode));
    }
    http.end();
  }
  else {
    Serial.println("Could not send HTTP request (AUTO) to mower");
    pushover("Could not send HTTP request (AUTO) to mower");
  }
}

void triggerGarage() {
  Serial.println("Trigger garage door");

  digitalWrite(PIN_GARAGE, LOW);
  digitalWrite(PIN_LED, HIGH);
  delay(400);
  digitalWrite(PIN_GARAGE, HIGH);
  digitalWrite(PIN_LED, LOW);
}

void triggerGate() {
  Serial.println("Trigger gate");

  bool toSafety = false;
  if (not digitalRead(PIN_SENSOR_GATE)) {
    toSafety = true;
  }

  digitalWrite(PIN_GATE, LOW);
  digitalWrite(PIN_LED, HIGH);
  delay(400);
  digitalWrite(PIN_GATE, HIGH);
  digitalWrite(PIN_LED, LOW);

  // DEAKTIVIEREN FÜR WINTERPAUSE:
  if (digitalRead(PIN_MOWER_ACTIVE) == LOW) {
    if (toSafety) {
      mowerSafety();
    }
    else {
      mowerAuto();
    }
  }
  else {
    Serial.println("Mower set to inactive");
  }
}

void stopSprinklers() {
  Serial.println("Stopping sprinklers");

  digitalWrite(PIN_SPRINKLER1, HIGH);
  digitalWrite(PIN_SPRINKLER2, HIGH);
  digitalWrite(PIN_SPRINKLER3, HIGH);
  digitalWrite(PIN_SPRINKLER4, HIGH);
}

void setup() {
  // start serial output
  Serial.begin(115200);
  Serial.println();

  btStop(); // turn off bluetooth

  pinMode(PIN_LED, OUTPUT);
  pinMode(PIN_GARAGE_BUTTON, INPUT_PULLUP);
  pinMode(PIN_GATE_BUTTON, INPUT_PULLUP);
  pinMode(PIN_MOWER_ACTIVE, INPUT_PULLUP);
  pinMode(PIN_GARAGE, OUTPUT);
  pinMode(PIN_GATE, OUTPUT);
  pinMode(PIN_DOOR_OPEN, INPUT_PULLUP);
  pinMode(PIN_DOOR_CLOSED, INPUT_PULLUP);
  pinMode(PIN_SENSOR_GATE, INPUT_PULLUP);
  pinMode(PIN_SPRINKLER1, OUTPUT);
  pinMode(PIN_SPRINKLER2, OUTPUT);
  pinMode(PIN_SPRINKLER3, OUTPUT);
  pinMode(PIN_SPRINKLER4, OUTPUT);
  pinMode(PIN_MOISTURE_DIGITAL, INPUT);

  digitalWrite(PIN_LED, HIGH);

  digitalWrite(PIN_GARAGE, HIGH);
  digitalWrite(PIN_GATE, HIGH);
  digitalWrite(PIN_SPRINKLER1, HIGH);
  digitalWrite(PIN_SPRINKLER2, HIGH);
  digitalWrite(PIN_SPRINKLER3, HIGH);
  digitalWrite(PIN_SPRINKLER4, HIGH);

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println(WiFi.localIP());
  WiFi.setAutoReconnect(true);
  WiFi.persistent(true);

  server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
    pinStatus(request);
  });

  server.on("/garage", HTTP_GET, [] (AsyncWebServerRequest * request) {
    String action;
    if (request->hasParam("action")) {
      action = request->getParam("action")->value();

      if (action.equals("open") and digitalRead(PIN_DOOR_CLOSED) and not digitalRead(PIN_DOOR_OPEN)) {
        request->send(200, "application/json", "{ \"action\": \"open\" }");
        triggerGarage();
      }
      else if (action.equals("close") and digitalRead(PIN_DOOR_OPEN) and not digitalRead(PIN_DOOR_CLOSED)) {
        request->send(200, "application/json", "{ \"action\": \"close\" }");
        triggerGarage();
      }
      else {
        pinStatus(request);
      }
    }
    else {
      if (digitalRead(PIN_DOOR_OPEN) and not digitalRead(PIN_DOOR_CLOSED)) {
        request->send(200, "application/json", "{ \"status\": \"true\" }");
      }
      else {
        request->send(200, "application/json", "{ \"status\": \"false\" }");
      }
    }
  });

  server.on("/gate", HTTP_GET, [] (AsyncWebServerRequest * request) {
    String action;
    if (request->hasParam("action")) {
      action = request->getParam("action")->value();

      if (action.equals("open") and not digitalRead(PIN_SENSOR_GATE)) {
        request->send(200, "application/json", "{ \"action\": \"open\" }");
        triggerGate();
      }
      else if (action.equals("close") and digitalRead(PIN_SENSOR_GATE)) {
        request->send(200, "application/json", "{ \"action\": \"close\" }");
        triggerGate();
      }
      else {
        pinStatus(request);
      }
    }
    else {
      if (digitalRead(PIN_SENSOR_GATE)) {
        request->send(200, "application/json", "{ \"status\": \"true\" }");
      }
      else {
        request->send(200, "application/json", "{ \"status\": \"false\" }");
      }
    }
  });

  server.on("/sprinkler", HTTP_GET, [] (AsyncWebServerRequest * request) {
    String action;
    if (request->hasParam("action")) {
      action = request->getParam("action")->value();
      Serial.println("Sprinkler " + action);

      if (action.equals("start") and (request->hasParam("device")) and (request->hasParam("duration"))) {
        stopSprinklers(); // only run one sprinkler at a time
        String device = request->getParam("device")->value();
        String duration = request->getParam("duration")->value();
        sprinklerDuration = duration.toInt();
        sprinklerDuration = sprinklerDuration * 60 * 1000;
        sprinklerStartMillis = millis();
        if (device.equals("1")) {
          digitalWrite(PIN_SPRINKLER1, LOW);
        }
        else if (device.equals("2")) {
          digitalWrite(PIN_SPRINKLER2, LOW);
        }
        else if (device.equals("3")) {
          digitalWrite(PIN_SPRINKLER3, LOW);
        }
        else if (device.equals("4")) {
          digitalWrite(PIN_SPRINKLER4, LOW);
        }
        else {
          sprinklerDuration = 0;
        }

        request->send(200, "application/json", "{ \"action\": \"start\" }");
      }
      else {
        stopSprinklers();
        request->send(200, "application/json", "{ \"action\": \"stop\" }");
      }
    }
    else {
      stopSprinklers();
      request->send(200, "application/json", "{ \"action\": \"stop\" }");
    }
  });

  server.on("/irrigation", HTTP_GET, [] (AsyncWebServerRequest * request) {
    String action;
    if (request->hasParam("action")) {
      action = request->getParam("action")->value();

      if (action.equals("start") and request->hasParam("duration")) {
        String duration = request->getParam("duration")->value();
        sprinklerDuration = duration.toInt();
        sprinklerDuration = sprinklerDuration * 60 * 500; // XXX Terrasse nur halb so lange bewässern
        sprinklerStartMillis = millis();
        programStatus = 4;
        digitalWrite(PIN_SPRINKLER4, LOW);
        request->send(200, "application/json", "{ \"action\": \"start\" }");
      }
      else {
        stopSprinklers();
        programStatus = 0;
        request->send(200, "application/json", "{ \"action\": \"stop\" }");
      }
    }

    String statusString = "false";
    if (programStatus > 0) {
      statusString = "true";
    }
    request->send(200, "application/json", "{ \"status\": \"" + statusString + "\" }");
  });

  server.onNotFound(notFound);

  server.begin();

  digitalWrite(PIN_LED, LOW);
  Serial.println("Setup completed");
}


unsigned long lastDebounceTime = 0;
unsigned long debounceDelay = 80;
int lastValGarage = HIGH;
int lastValGate = HIGH;

void loop() {

  if ((sprinklerDuration > 0) and ((millis() - sprinklerStartMillis) > sprinklerDuration)) {
    stopSprinklers();
    if (programStatus > 0) {
      
      if (programStatus == 4) {
        sprinklerDuration = sprinklerDuration * 2; // XXX Terrasse nur halb so lange bewässern
      }
      
      programStatus--;
      sprinklerStartMillis = millis();

      if (programStatus == 3) {
        digitalWrite(PIN_SPRINKLER3, LOW);
      }
      else if (programStatus == 2) {
        digitalWrite(PIN_SPRINKLER2, LOW);
      }
      else if  (programStatus == 1) {
        digitalWrite(PIN_SPRINKLER1, LOW);
      }
    }
    else {
      sprinklerDuration = 0;
      sprinklerStartMillis = 0;
    }
  }

  int newVal = digitalRead(PIN_GARAGE_BUTTON);
  if (newVal != lastValGarage) {
    Serial.println("Garage Button");
    lastDebounceTime = millis();
    while (((millis() - lastDebounceTime) < debounceDelay) and digitalRead(PIN_GARAGE_BUTTON) != lastValGarage) {
      delay(1);
    }
    if (digitalRead(PIN_GARAGE_BUTTON) != lastValGarage) {
      lastValGarage = newVal;
      if (newVal == LOW) {
        triggerGarage();
      }
    }
    else {
      Serial.println("fluke");
    }
  }

  newVal = digitalRead(PIN_GATE_BUTTON);
  if (newVal != lastValGate) {
    Serial.print("Gate Button");
    lastDebounceTime = millis();
    while (((millis() - lastDebounceTime) < debounceDelay) and digitalRead(PIN_GATE_BUTTON) != lastValGate) {
      delay(1);
    }
    if (digitalRead(PIN_GATE_BUTTON) != lastValGate) {
      lastValGate = newVal;
      if (newVal == LOW) {
        triggerGate();
      }
    }
    else {
      Serial.println("fluke");
    }
  }
}
