Advertisement
noam76

Irrigation with ESP8266WebServer

Jan 28th, 2018
419
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Arduino 13.70 KB | None | 0 0
  1. #include <ESP8266WiFi.h>
  2. #include <ESP8266WebServer.h>
  3. #include <ESP8266mDNS.h>
  4. #include <WiFiClient.h>
  5. #include <ArduinoJson.h>
  6. #include <FS.h>
  7. #include <dampermotor.h>
  8.  
  9. // const char *host = "serverweb1";
  10. const char* ssid = "SSID";
  11. const char* password = "PASSWORD";
  12. const char* CONFIG_HTML = "/html/config.html";
  13. const char* UPDATE_HTML = "/html/Update.html";
  14. const char* DISPLAY_DATA_HTML = "/html/display_data.html";
  15. const char* configUsername = "admin";
  16. const char* configPwd = "admin";
  17. ESP8266WebServer server(80);
  18.  
  19. #define SoilSensor A0
  20. #define SoilSensorEnablePin1 D0
  21. #define SoilSensorEnablePin2 D1
  22. #define SoilSensorEnablePin3 D2
  23. #define SoilSensorEnablePin4 D3
  24. #define tap_solenoid_timeout 1500 // delay for 3 sec.
  25. #define PumpPin 2
  26.  
  27. //Configure the soil moisture
  28. int MintSoilMoisture = 250;//Menth
  29. const int ParsleySoilMoisture = 230;//Persil
  30. const int BasilSoilMoisture = 260;//Basilic
  31. const int CorianderSoilMoisture = 300;//Coriande, Cousbara
  32. const int DillSoilMoisture = 2700;//Aneth, shamir
  33. const int SageSoilMoisture = 310;//Sauge, Marva
  34. const int rosemarySoilMoisture = 200;//Romarin
  35.  
  36. int PlantSensor1,PlantSensor2,PlantSensor3,PlantSensor4; //User final target after converted from WebForm
  37. int read_sensor_value1,read_sensor_value2,read_sensor_value3,read_sensor_value4; //read data from sensor
  38. boolean electric_tap_motor1,electric_tap_motor2,electric_tap_motor3,electric_tap_motor4; //Off or On motor's electric tap
  39. const int onTime = 1000; // in ms
  40. const int offTime = 5000; // in ms
  41. boolean currentlyOn = false;
  42. unsigned long startTime;
  43. char WebTemp_itoa[10],*TargetTempChar;
  44.  
  45. String XML;
  46. dampermotor tap_motor_sensor1(D4,D5,tap_solenoid_timeout); // define pin 4,5 to drive the tap_motor_sensor1
  47. dampermotor tap_motor_sensor2(D6,D7,tap_solenoid_timeout); // define pin 6,7 to drive the tap_motor_sensor1
  48. dampermotor tap_motor_sensor3(D8,D9,tap_solenoid_timeout); // define pin 8,9 to drive the tap_motor_sensor1
  49. //dampermotor tap_motor_sensor4(D10,11,tap_solenoid_timeout); // define pin 10,11 to drive the tap_motor_sensor1
  50.  
  51. /**
  52. * racine du site.
  53. */
  54. void handleRoot() {
  55.   server.send(200, "text/plain", "Welcome to my Irrigation System!");
  56. }
  57.  
  58. /**
  59. * Affiche la page de configuration.
  60. */
  61. void handleConfig()
  62. {
  63.  String form = "";
  64.  File f = SPIFFS.open(CONFIG_HTML, "r");
  65.  if (!f){
  66.   Serial.println("Can't open config html file");
  67.   server.send(404, "text/html", "File not found");    
  68.   }
  69.   else{
  70.    char buf[1024];
  71.    int siz = f.size();
  72.    while(siz > 0) {
  73.     size_t len = std::min((int)(sizeof(buf) - 1), siz);
  74.     f.read((uint8_t *)buf, len);
  75.     buf[len] = 0;
  76.     form += buf;
  77.     siz -= sizeof(buf) - 1;
  78.    }
  79.    f.close();
  80.    server.send(200, "text/html", form);
  81.   }
  82. }
  83.  
  84. /**
  85. * Affiche la page Update.
  86. */
  87. void handleUpdate()
  88. {
  89.  String form = "";
  90.  File f = SPIFFS.open(UPDATE_HTML, "r");
  91.  if (!f){
  92.   Serial.println("Can't open update html file");
  93.   server.send(404, "text/html", "File not found");    
  94.   }
  95.   else{
  96.    char buf[1024];
  97.    int siz = f.size();
  98.    while(siz > 0) {
  99.     size_t len = std::min((int)(sizeof(buf) - 1), siz);
  100.     f.read((uint8_t *)buf, len);
  101.     buf[len] = 0;
  102.     form += buf;
  103.     siz -= sizeof(buf) - 1;
  104.    }
  105.    f.close();
  106.    server.send(200, "text/html", form);
  107.   }
  108. }
  109.  
  110. /**
  111. * Affiche la page display data.
  112. */
  113. void DisplayData()
  114. {
  115.  String form = "";
  116.  File f = SPIFFS.open(DISPLAY_DATA_HTML, "r");
  117.  if (!f){
  118.   Serial.println("Can't open update html file");
  119.   server.send(404, "text/html", "File not found");    
  120.   }
  121.   else{
  122.    char buf[1024];
  123.    int siz = f.size();
  124.    while(siz > 0) {
  125.     size_t len = std::min((int)(sizeof(buf) - 1), siz);
  126.     f.read((uint8_t *)buf, len);
  127.     buf[len] = 0;
  128.     form += buf;
  129.     siz -= sizeof(buf) - 1;
  130.    }
  131.    f.close();
  132.    server.send(200, "text/html", form);
  133.   }
  134. }
  135.  
  136. void handleXML(){
  137.   XML="<?xml version='1.0'?>";
  138.   XML+="<xml>";
  139.   XML+="<sens1>";
  140.   XML+= read_sensor_value1;
  141.   XML+="</sens1>";  
  142.   XML+="<sens2>";
  143.   XML+= read_sensor_value2;
  144.   XML+="</sens2>";
  145.   XML+="<sens3>";
  146.   XML+= read_sensor_value3;
  147.   XML+="</sens3>";
  148.   XML+="<sens4>";
  149.   XML+= read_sensor_value4;
  150.   XML+="</sens4>";
  151.   XML+="</xml>";
  152.  server.send(200,"text/xml",XML);
  153. }
  154.  
  155. /*void upgrade()
  156. {
  157.   // update the file on SPIFFS
  158. }*/
  159.  
  160. void handleReadUserPlantSelected(){
  161.  // Read Value from the User selected from the Html WebForm to String
  162.  PlantSensor1 = server.arg("sensor1").toInt();
  163.  PlantSensor2 = server.arg("sensor2").toInt();
  164.  PlantSensor3 = server.arg("sensor3").toInt();
  165.  PlantSensor4 = server.arg("sensor4").toInt();
  166.  
  167.  /*
  168.  Serial.println("Before Convert");
  169.  Serial.println(PlantSensor1);
  170.  Serial.println(PlantSensor2);
  171.  Serial.println(PlantSensor3);
  172.  Serial.println(PlantSensor4);
  173.  */
  174.  
  175. // Assign the correct Soil Target
  176.  PlantSensor1 = SoilSensorWebUser(PlantSensor1);
  177.  PlantSensor2 = SoilSensorWebUser(PlantSensor2);
  178.  PlantSensor3 = SoilSensorWebUser(PlantSensor3);
  179.  PlantSensor4 = SoilSensorWebUser(PlantSensor4);
  180.  
  181.  /*
  182.  Serial.println("The Final Target Soil After switch case");
  183.  Serial.println(PlantSensor1);
  184.  Serial.println(PlantSensor2);
  185.  Serial.println(PlantSensor3);
  186.  Serial.println(PlantSensor4);
  187.  */
  188.   server.sendHeader("Location","/config");
  189.   server.send(303);
  190.  
  191.   if (!saveConfig())
  192.    {Serial.println("Failed to save config");}
  193.   else
  194.    {Serial.println("Config saved");}
  195. }
  196.  
  197. void initWebserver()
  198. {
  199.  server.on("/", handleRoot);
  200.  
  201.  /* --- configure the config page, main page --- */
  202.  /*server.on("/config", [](){
  203.  if(!server.authenticate(configUsername, configPwd)){
  204.   return server.requestAuthentication();
  205.  }else{
  206.   handleConfig(); // display the page
  207.  }
  208. });*/
  209.  server.on("/config",handleConfig);
  210.  
  211. /* --- configure the update page --- */
  212.   /*server.on("/update", [](){
  213.     if(!server.authenticate(configUsername, configPwd)){
  214.       return server.requestAuthentication();
  215.   } else {
  216.     handleUpdate(); // display the page
  217.   }
  218.   });*/
  219.  server.on("/update",handleUpdate);
  220.   /* --- After press update on system page run upgrade function --- */
  221.  //server.on("/save", upgrade);
  222.  
  223.   /* --- After press submit button for sensor --- */
  224.  /*server.on("/postindex", [](){
  225.   handleReadUserPlantSelected(); // receive form's data from the form tag where action=postindex
  226.  });*/
  227.  server.on("/postindex",handleReadUserPlantSelected);
  228.  
  229.  /* --- After press display data on Menu run DisplayData()--- */
  230.  /*server.on("/display_data", [](){
  231.     if(!server.authenticate(configUsername, configPwd)){
  232.       return server.requestAuthentication();
  233.   } else {
  234.     DisplayData(); // display the page
  235.   }
  236.   });*/
  237.  server.on("/display_data",DisplayData);
  238.  
  239.  server.on("/reqEtatVariables",handleXML);
  240.  
  241.  server.serveStatic("/css", SPIFFS, "/html/css");
  242.  server.serveStatic("/config.html", SPIFFS, "/html/config.html");
  243.  server.serveStatic("/Update.html", SPIFFS, "/html/Update.html");
  244.  server.serveStatic("/display_data.html", SPIFFS, "/html/display_data.html");
  245.  /*server.serveStatic("/images/1.png", SPIFFS, "/html/images/1.png");
  246.  server.serveStatic("/images/2.png", SPIFFS, "/html/images/2.png");
  247.  server.serveStatic("/images/3.png", SPIFFS, "/html/images/3.png");
  248.  server.serveStatic("/images/4.png", SPIFFS, "/html/images/4.png");
  249.  server.serveStatic("/images/5.png", SPIFFS, "/html/images/5.png");
  250.  server.serveStatic("/images/bg.png", SPIFFS, "/html/images/bg.png");*/
  251. }
  252.  
  253. /**
  254. * Assign the correct Soil Target for the Plant Sensor connected after user choice from the WebForm
  255. */
  256. int SoilSensorWebUser(int WebSoilSensor)
  257. {
  258.  switch(WebSoilSensor)
  259.  {
  260.   case 0:
  261.     return(0);
  262.   break;
  263.   case 1:
  264.     return(MintSoilMoisture);
  265.   break;
  266.   case 2:
  267.     return(ParsleySoilMoisture);
  268.   break;
  269.   case 3:
  270.     return(BasilSoilMoisture);
  271.   break;
  272.   case 4:
  273.     return(CorianderSoilMoisture);
  274.   break;
  275.   case 5:
  276.     return(DillSoilMoisture);
  277.   break;
  278.   case 6:
  279.     return(SageSoilMoisture);
  280.   break;
  281.   case 7:
  282.     return(rosemarySoilMoisture);
  283.   break;
  284.  }
  285. }
  286.  
  287. /**
  288. * Read Datas from all Sensors
  289. */
  290. int read_Sensors_Values(int EnableSoilPin)
  291. {
  292.  int ReadSensor;
  293.  digitalWrite(EnableSoilPin,HIGH);
  294.  for(int SensorReading = 0;SensorReading < 5;SensorReading++)
  295.  {
  296.   ReadSensor = analogRead(SoilSensor);
  297.  }
  298.  digitalWrite(EnableSoilPin,LOW);
  299.  return ReadSensor;
  300. }
  301.  
  302. void WaterController()
  303. {
  304.  if(read_sensor_value1 < PlantSensor1)
  305.  {
  306.   tap_motor_sensor1.open_damper(); //turn one side solenoid with motortimeout delay
  307.   electric_tap_motor1 = HIGH ;
  308.   if(digitalRead(PumpPin) == LOW);
  309.   {
  310.    digitalWrite(PumpPin,HIGH);
  311.   }
  312.  }
  313.  else
  314.  {
  315.   tap_motor_sensor1.close_damper(); //turn other side solenoid with motortimeout delay
  316.   electric_tap_motor1 = LOW ;
  317.  }
  318.  
  319.  if(read_sensor_value2 < PlantSensor2)
  320.  {
  321.   tap_motor_sensor2.open_damper(); //turn one side solenoid with motortimeout delay
  322.   electric_tap_motor2 = HIGH ;
  323.   if(digitalRead(PumpPin) == LOW)
  324.   {
  325.    digitalWrite(PumpPin,HIGH);
  326.   }
  327.  }
  328.  else
  329.  {
  330.   tap_motor_sensor2.close_damper(); //turn other side solenoid with motortimeout delay
  331.   electric_tap_motor2 = LOW ;
  332.  }
  333.  
  334.  if(read_sensor_value3 < PlantSensor3)
  335.  {
  336.   tap_motor_sensor3.open_damper(); //turn one side solenoid with motortimeout delay
  337.   electric_tap_motor3 = HIGH ;
  338.   if(digitalRead(PumpPin) == LOW)
  339.   {
  340.    digitalWrite(PumpPin,HIGH);
  341.   }
  342.  }
  343.  else
  344.  {
  345.   tap_motor_sensor3.close_damper(); //turn other side solenoid with motortimeout delay
  346.   electric_tap_motor3 = LOW ;
  347.  }
  348.  
  349.  if(read_sensor_value4 < PlantSensor4)
  350.  {
  351.   //tap_motor_sensor4.open_damper(); //turn one side solenoid with motortimeout delay
  352.   electric_tap_motor4 = HIGH ;
  353.   if(digitalRead(PumpPin) == LOW)
  354.   {
  355.    digitalWrite(PumpPin,HIGH);
  356.   }
  357.  }
  358.  else
  359.  {
  360.  // tap_motor_sensor4.close_damper(); //turn other side solenoid with motortimeout delay
  361.   electric_tap_motor4 = LOW ;
  362.  }
  363.  
  364.  // check if all Tap is OFF then turn OFF the Pump
  365.  if(electric_tap_motor1 == LOW && electric_tap_motor2 == LOW && electric_tap_motor3 == LOW && electric_tap_motor4 == LOW)
  366.  {
  367.   digitalWrite(PumpPin,LOW);
  368.  }
  369. }
  370.  
  371. bool loadConfig()
  372. {
  373.  File configFile = SPIFFS.open("/config.json", "r");
  374.  if (!configFile)
  375.  {
  376.   Serial.println("Failed to open config file");
  377.   return false;
  378.  }
  379.  size_t size = configFile.size();
  380.  if (size > 1024)
  381.  {
  382.   Serial.println("Config file size is too large");
  383.   return false;
  384.  }
  385.  // Allocate a buffer to store contents of the file.
  386.  std::unique_ptr<char[]> buf(new char[size]);
  387.  
  388.  // We don't use String here because ArduinoJson library requires the input
  389.  // buffer to be mutable. If you don't use ArduinoJson, you may as well
  390.  // use configFile.readString instead.
  391.  configFile.readBytes(buf.get(), size);
  392.  
  393.  StaticJsonBuffer<200> jsonBuffer;
  394.  JsonObject& json = jsonBuffer.parseObject(buf.get());
  395.  if (!json.success())
  396.  {
  397.   Serial.println("Failed to parse config file");
  398.   return false;
  399.  }
  400.  *TargetTempChar = json["TargetTempChar"];
  401.  // Real world application would store these values in some variables for
  402.  // later use.
  403.  Serial.print("Loaded TargetTempChar: ");
  404.  Serial.println(TargetTempChar);
  405.  MintSoilMoisture = *TargetTempChar;
  406.  Serial.print("The MintSoilMoisture: ");
  407.  Serial.println(MintSoilMoisture);
  408.  return true;
  409. }
  410.  
  411. bool saveConfig()
  412. {
  413.  StaticJsonBuffer<200> jsonBuffer;
  414.  JsonObject& json = jsonBuffer.createObject();
  415.  itoa(MintSoilMoisture,WebTemp_itoa,10);
  416.  json["TargetTempChar"] = WebTemp_itoa;
  417.  File configFile = SPIFFS.open("/config.json", "w");
  418.  if (!configFile)
  419.  {
  420.   Serial.println("Failed to open config file for writing");
  421.   return false;
  422.  }
  423.  json.printTo(configFile);
  424.  return true;
  425. }
  426.  
  427. void setup(){
  428.  Serial.begin(115200);
  429.  pinMode(A0, INPUT);
  430.  pinMode(PumpPin, INPUT);
  431.  pinMode(SoilSensorEnablePin1, OUTPUT);
  432.  pinMode(SoilSensorEnablePin2, OUTPUT);
  433.  pinMode(SoilSensorEnablePin3, OUTPUT);
  434.  pinMode(SoilSensorEnablePin4, OUTPUT);
  435.  Serial.println("...");
  436.  Serial.println("Mounting FS...");
  437.  if (!SPIFFS.begin()) {
  438.   Serial.println("Failed to mount file system");
  439.   return;
  440.   }
  441.   else
  442.   {Serial.println("Mounting FS Successfully");}
  443.  
  444.   // Read Data From SPIFFS File or EEPROM
  445.   /*if (!loadConfig())
  446.   {Serial.println("Failed to load config");}
  447.  else
  448.   {Serial.println("Config loaded");}*/
  449.    
  450.  WiFi.begin(ssid, password);
  451.  Serial.println("");
  452.  // Wait for connection
  453.  while (WiFi.status() != WL_CONNECTED) {
  454.   delay(500);
  455.   Serial.print(".");
  456.   }
  457.  Serial.println("");
  458.  Serial.print("Connected to ");
  459.  Serial.println(ssid);
  460.  Serial.print("IP address: ");
  461.  Serial.println(WiFi.localIP());
  462.  Serial.println("TCP server started");
  463.  
  464.  /*if (!MDNS.begin(host)){
  465.   Serial.println("Error setting up MDNS responder!");
  466.   while(1){
  467.    delay(1000);
  468.   }
  469.  }*/
  470.  //Serial.println("mDNS responder started");
  471.  
  472.   initWebserver();
  473.  // Start TCP (HTTP) server
  474.  server.begin();
  475.  // Add service to MDNS-SD
  476.  //MDNS.addService("http", "tcp", 80);
  477.  startTime=millis(); // Initialisation
  478. }
  479.  
  480. void loop()
  481. {
  482.  server.handleClient();
  483.  // --- read sensors value Every 5sec for 1sec --- //
  484.  if (currentlyOn && millis()>startTime+onTime) // Switch resistor off
  485.  {
  486.   currentlyOn = false;
  487.   startTime=millis(); // Reset timer
  488.  }
  489.  if (!currentlyOn && millis()>startTime+offTime) // Switch resistor on
  490.  {
  491.   read_sensor_value1 = read_Sensors_Values(SoilSensorEnablePin1);
  492.   read_sensor_value2 = read_Sensors_Values(SoilSensorEnablePin2);
  493.   read_sensor_value3 = read_Sensors_Values(SoilSensorEnablePin3);
  494.   read_sensor_value4 = read_Sensors_Values(SoilSensorEnablePin4);
  495.   currentlyOn = true;
  496.   startTime=millis(); // Reset timer
  497.  }
  498.  
  499.  // --- drive motor for stop after running --- //
  500.  tap_motor_sensor1.damper_motor_driver();
  501.  tap_motor_sensor2.damper_motor_driver();
  502.  tap_motor_sensor3.damper_motor_driver();
  503.  //tap_motor_sensor4.damper_motor_driver();
  504.  
  505.  // --- water the plant turn on/off tap and pump --- //
  506.  //WaterController();
  507. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement