#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266Influxdb.h>
#include "settings.h"

int16_t idleValue = 0;
int16_t sensorValue = 0;
int8_t cutOffThreshold = cutOffTime;
int16_t cooldownRemaining = 0;
ESP8266WiFiMulti wifi;
Influxdb influxdb(INFLUXDB_HOST, INFLUXDB_PORT);


void setup() {
  pinMode(D1, OUTPUT); // Relais
  pinMode(D2, OUTPUT); // Status-LED
  // A0 = Current sensor

  digitalWrite(D1, LOW);
  digitalWrite(D2, LOW);

  // Connect to wifi
  wifi.addAP(WIFI_SSID, WIFI_PASSWORD);
  while (wifi.run() != WL_CONNECTED) {
    digitalWrite(D2, !digitalRead(D2));
    delay(200);
  }
  
  // Open DB connecton
  digitalWrite(D2, LOW);
  influxdb.opendb(INFLUXDB_DB, INFLUXDB_USER, INFLUXDB_PASS);
  delay(2000);
  
  // Open serial connection for debugging
  if (DEBUG) {
    Serial.begin(115200);
    delay(500);
  }
  
  digitalWrite(D2, HIGH);

  if (DEBUG) Serial.println("Ready for action!");
}

void loop() {
  delay(loopTime*1000);

  // Callibrate the idle value
  if (idleValue == 0) {
    if (DEBUG) Serial.println("Calibrate ...");
    uint16_t samples;
    for (uint8_t i=0; i<30; i++) {
      samples += analogRead(A0);
      digitalWrite(D2, !digitalRead(D2));
      delay(500);
    }

    idleValue = round(samples / 30);
    if (DEBUG) Serial.println("Idle value: " + String(idleValue));
    digitalWrite(D2, HIGH);
  }

  // Need to cutoff the power to the pump?
  if (cutOffThreshold <= 0) {
    digitalWrite(D1, HIGH);
    digitalWrite(D2, LOW);
    cooldownRemaining = cooldownTime - loopTime;
    cutOffThreshold = cutOffTime;

    if (DEBUG) Serial.println("The pump is cutoff, because it is running to long");

    return;
  }

  // Cooldown phase?
  if (cooldownRemaining > 0) {
    digitalWrite(D2, LOW);
    cooldownRemaining -= loopTime;
    influxdb.write("pump-action cutoff=1");

    if (DEBUG) Serial.println("Cooldown phase ... " + String(cooldownRemaining) + " seconds remaining.");
    
    return;
  }

  digitalWrite(D1, LOW);
  digitalWrite(D2, HIGH);

  // Read the sensor
  sensorValue = 0;
  for (uint8_t i=0; i<5; i++) {
    sensorValue += analogRead(A0);
    Serial.println(sensorValue);
    delay(10);
  }
  sensorValue = round(sensorValue / 5);
  

  if (DEBUG) Serial.println("Sensor value: " + String(sensorValue));

  // The pump is on!
  if (sensorValue > idleValue+10 || sensorValue < idleValue-10) {
    influxdb.write("pump-action current=" + String(sensorValue));
    cutOffThreshold -= loopTime;
    digitalWrite(D2, !digitalRead(D2));


    if (DEBUG) {
      Serial.println("Write to Influxdb: " + String(sensorValue));
      Serial.println(influxdb.response() == DB_SUCCESS ? "Success" : "Failed");
    }

  // The pump is off
  } else {
    cutOffThreshold = cutOffTime;
    digitalWrite(D2, HIGH);
  }
}
