#include "NewPing.h"
#include <ESP8266WiFi.h>
#include <FirebaseESP8266.h>
#include <Servo.h>
#include <math.h>

// Set these to run example.
#define FIREBASE_HOST "ifarm-4ec55-default-rtdb.firebaseio.com"
#define FIREBASE_AUTH "0XoTKCHRo5iB63DShpRfq5Q545GQfDlTcBxQrEkP"
#define WIFI_SSID "Dialog 4G CB3"
#define WIFI_PASSWORD "BMy7M977"
#define LED1 D1
#define LED2 D2
#define TRIGGER_PIN D7
#define ECHO_PIN D8

#define MAX_DISTANCE 400


NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);


// Declare the Firebase Data object in the global scope
FirebaseData firebaseData;

// Declare global variable to store value
int val = 0;
Servo servo;
const int AirValue = 1024.0;   //you need to replace this value with Value_1
const int WaterValue = 950.0;  //you need to replace this value with Value_2
float foodMoistureValue = 0.0;
float foodmoisturepercent = 0.0;
float foodpercent = 0.0;


//Change product number here
String productnumber = "001";


void setup() {
  Serial.begin(9600);
  pinMode(LED1, OUTPUT);
  digitalWrite(LED1, HIGH);
  pinMode(LED2, OUTPUT);
digitalWrite(LED2, LOW);
  // connect to wifi.
  servo.attach(2); //D4
  servo.write(90);

  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("connected: ");
  digitalWrite(LED1, LOW);
  digitalWrite(LED2, HIGH);
  Serial.println(WiFi.localIP());

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.setInt(firebaseData, "/Food/"+productnumber+"/SERVO", 0);

  Serial.println("Sensor Data\n");
}


int s = 0;
void loop() {
float  foodlimit;



float dis = sonar.ping_cm();
if(dis == 9 ){
  foodlimit = 0;
  }else if(dis <= 1){
    foodlimit = 100;
    }
    else if(dis > 1 || dis < 9){
      foodlimit = round(((8 - dis )/8)*100);
      }
Firebase.setFloat(firebaseData, "/Food/"+productnumber+"/dis",foodlimit);

  foodMoistureValue = analogRead(A0);
  foodmoisturepercent = map(foodMoistureValue, AirValue, WaterValue, 0, 100);

  if(foodmoisturepercent >= 100.0){
    foodpercent = 100.0;
    }else if(foodmoisturepercent <= 0.0){
      foodpercent = 0.0;
      }else if (foodmoisturepercent >0.0 && foodmoisturepercent < 100.0){
        foodpercent = foodmoisturepercent;
        }
  Serial.print(" Soil Moisture: ");  Serial.print(foodpercent);  Serial.print("%");

  Firebase.setFloat(firebaseData, "/Food/"+productnumber+"/Moist/foodMoist", foodpercent);
  if (Firebase.getInt(firebaseData, "/Food/"+productnumber+"/SERVO")) {
    s = firebaseData.intData();
    Serial.print(" Servo: "); Serial.println(s);
  }
  if (s == 0) {
    servo.write(0);              // tell servo to go to position in variable 'pos'
    delay(2000); return;

  }
  else {
    servo.write(180);
    delay(2000);
    return;
  }

  delay(1000);
}
