#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <Servo.h>

#define ServoPort D1   // Defining Servo Port
#define soilPin A0     // Analog input pin for soil moisture sensor

const char* ssid = "ROBOHUB";       // Your SSID
const char* password = "R@==++oor"; // WiFi Password

Servo myservo;                           // Create a servo object to control the servo
ESP8266WebServer server(80);              // Server on port 80

#include "PageIndex.h" // Include the contents of the User Interface Web page, stored in the same folder as the .ino file

void handleRoot() {
  int moistureLevel = map(analogRead(soilPin), 0, 1000, 10, 0);
  String s = MAIN_page;
  s.replace("{{moistureLevel}}", String(moistureLevel));
  server.send(200, "text/html", s);
}

void handleServo() {
  String servoPos = server.arg("pos");
  int pos = servoPos.toInt();
  myservo.write(pos);   // Move the servo motor according to the pos value
  delay(15);
  server.send(200, "text/plain", "");
}

void setup() {
  Serial.begin(115200);
  delay(500);
  myservo.attach(ServoPort); // Attach the servo on D1 to the servo object

  WiFi.begin(ssid, password);
  Serial.print("Connect your WiFi laptop/mobile phone to this NodeMCU Access Point: ");
  Serial.println(ssid);
  Serial.println("Connecting to WiFi");

  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

  server.on("/", handleRoot);             // Routine to handle the root location. This displays the web page.
  server.on("/servo", handleServo);       // Sets servo position from the web request
  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();
}
