Advertisement
Guest User

Untitled

a guest
Sep 5th, 2016
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 14.43 KB | None | 0 0
  1. #include <DHT.h>
  2. #include <Time.h>
  3. #include <ESP8266WiFi.h>
  4. #include <ESP8266mDNS.h>
  5. #include <ArduinoOTA.h>
  6. #include <ESP8266WebServer.h>
  7.  
  8. #include "TamaVeg_html_main.h"
  9. #include "TamaVeg_html_live.h"
  10.  
  11. const char* ssid = "GPRTWIFI";
  12. const char* password = "senhademasiadamentesecreta";
  13.  
  14. ESP8266WebServer server(80);
  15. const char* www_username = "admin";
  16. const char* www_password = "senhasecreta";
  17.  
  18. const int led = 13;
  19.  
  20. //----------RELES--------//
  21. #define rele_light1      5 // Pin to relay 1
  22. #define rele_light2      4 // Pin to relay 2
  23. #define rele_fan1        0 // Pin to relay 3
  24. #define rele_humidifier  2 // Pin to relay 4
  25.  
  26. //-------DHT Sensors-----//
  27. #define DHT1_PIN 14
  28. #define DHTTYPE DHT11
  29. DHT Dht11_1(DHT1_PIN, DHTTYPE);
  30. float sens_HumidityAr;
  31. float sens_AmbTemperature ;
  32.  
  33. //---Soil Humidity Sensor---
  34. #define SOIL1_PIN A0
  35. int sens_SoilHumidity;
  36.  
  37. //----NTP Related------------//
  38. char timeServer[] = "150.161.192.1"; // time.nist.gov NTP server
  39. const int timeZone = -3;     // Recife/America
  40. int localNtpPort = 8888;       // local port to listen for UDP packets
  41. const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
  42. byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
  43. // A UDP instance to let us send and receive packets over UDP
  44. WiFiUDP Udp;
  45.  
  46. // Profile -----------------------------------
  47. String profile_Name = String("PadraoS");
  48. int profile_OnTime = 5 ; // hour to turn on
  49. int profile_TimeOn = 12; // How many hours stay on
  50. int profile_Humidity = 60; // Himidity to reach
  51. int profile_AmbTemperature = 25; // Temperature to reach
  52. int profile_SoilHumidity = 50; // profile_Humiditydity of the soil to reach
  53.  
  54. //---PWM----
  55.  
  56. #define fanCrt1_PIN 13 //(D7)
  57.  
  58. //Varables to auxiliate--------------------
  59. int dayLight[24]; // Vetor of flags to control the light, size 24, each location represent a hour of the day, filled with 0 the light should be off the hour, oposite with 1.
  60. int flagLight; // Flag used to determine if light are ON or OFF
  61. int exaustFlag; // Flag used to determine if exausts are ON or OFF
  62. unsigned long waitSensors = 0; // Flag to delay read sensors
  63. //unsigned long waitLcdInfo = 2000; // Flag to delay LDC messages
  64. //int lcdMsgFlag = 0; // Flag to spin the messages on LCD
  65. int showAux_sens_AmbTemperature;
  66. int showAux_sens_HumidityAr;
  67. char showAux_profile_Name[10] = "Default";
  68. char showAux_bgcolor[10];
  69. int liveFlag = 0;
  70. int light1Set = 0;
  71. int fan1Set = 0;
  72. int fanCtrl1 = 255;
  73. int fanCtrl2 = 255;
  74. String bgcolor;
  75.  
  76.  
  77. void setup() {
  78.  
  79.   Serial.begin(115200);
  80.  
  81.   // Init reles off
  82.   pinMode (rele_light1, OUTPUT);
  83.   pinMode (rele_light2, OUTPUT);
  84.   pinMode (rele_fan1, OUTPUT);
  85.   pinMode (rele_humidifier, OUTPUT);
  86.   digitalWrite (rele_light1, HIGH);
  87.   digitalWrite (rele_light2, HIGH);
  88.   digitalWrite (rele_fan1, HIGH);
  89.   digitalWrite (rele_humidifier, HIGH);
  90.  
  91.   analogWriteRange(255);
  92.   analogWriteFreq(490);
  93.  
  94.   WiFi.mode(WIFI_STA);
  95.   WiFi.begin(ssid, password);
  96.   if (WiFi.waitForConnectResult() != WL_CONNECTED) {
  97.     Serial.println("Failed to configure WiFi");
  98.     Serial.println("Assuming is 00:00:00 on 4/4/1988"); // Put some Blink Led here!! or reset
  99.     setTime(00, 00, 00, 04, 04, 1988); // alternative to above, yr is 2 or 4 digit yr (2010 or 10 sets year to 2010)
  100.     //delay(1000);
  101.     //ESP.restart();
  102.   }
  103.   Serial.println(WiFi.localIP());
  104.  
  105.   Udp.begin(localNtpPort);
  106.   setSyncProvider(getNtpTime);
  107.  
  108.   SetLightVector(profile_OnTime, profile_TimeOn);
  109.  
  110.   Dht11_1.begin();
  111.  
  112.   server.on("/profile", handle_profile);  //http://<ip>/profile?profName=teste3&OnTime=4&TimeOn=20&hum=60&tmpamb=25&humtr=60
  113.   server.on("/", handle_root);
  114.   server.onNotFound ( handleNotFound );
  115.   server.on("/live", handle_live );
  116.   server.begin();
  117. }
  118.  
  119. void handle_profile() {
  120.   char temp[900];
  121.  
  122.   // Value Aquisition
  123.   server.arg("profName").toCharArray(showAux_profile_Name, server.arg("profName").length() + 1);
  124.   profile_OnTime = server.arg("OnTime").toInt(); // Hour to turn on
  125.   profile_TimeOn = server.arg("TimeOn").toInt(); // How many hours stay on
  126.   profile_Humidity = server.arg("hum").toInt(); // Humidity to reach
  127.   profile_AmbTemperature = server.arg("tmpamb").toInt(); // Amb Temperature to reach
  128.   profile_SoilHumidity = server.arg("humtr").toInt(); // Soil Humidity to reach
  129.  
  130.   //React to the new profile
  131.   SetLightVector(profile_OnTime, profile_TimeOn);
  132.   if (!liveFlag)
  133.     chkLightState();
  134.  
  135.   //Generate Response html
  136.   snprintf (temp, 900, html_page_main, showAux_bgcolor,
  137.             showAux_profile_Name, hour(), minute(), second(), flagLight, profile_OnTime, profile_TimeOn, showAux_sens_AmbTemperature, profile_AmbTemperature, showAux_sens_HumidityAr, profile_Humidity, sens_SoilHumidity, profile_SoilHumidity);
  138.  
  139.   //Send Html Response
  140.   if (!server.authenticate(www_username, www_password))
  141.     return server.requestAuthentication();
  142.   else
  143.     server.send ( 200, "text/html", temp );
  144.  
  145. }
  146.  
  147.  
  148.  
  149.  
  150. void handle_root() {
  151.   char temp[900];
  152.   //profile_Name.toCharArray(showAux_profile_Name, profile_Name.length() + 1);
  153.  
  154.   snprintf (temp, 900, html_page_main,
  155.             showAux_bgcolor, showAux_profile_Name, hour(), minute(), second(), flagLight, profile_OnTime, profile_TimeOn, showAux_sens_AmbTemperature, profile_AmbTemperature, showAux_sens_HumidityAr, profile_Humidity, sens_SoilHumidity, profile_SoilHumidity);
  156.  
  157.   if (!server.authenticate(www_username, www_password))
  158.     return server.requestAuthentication();
  159.   else
  160.     server.send ( 200, "text/html", temp );
  161. }
  162.  
  163. void handleNotFound() {
  164.   String message = "File Not Found\n\n";
  165.   message += "URI: ";
  166.   message += server.uri();
  167.   message += "\nMethod: ";
  168.   message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
  169.   message += "\nArguments: ";
  170.   message += server.args();
  171.   message += "\n";
  172.  
  173.   for ( uint8_t i = 0; i < server.args(); i++ ) {
  174.     message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
  175.   }
  176.  
  177.   server.send ( 404, "text/plain", message );
  178. }
  179.  
  180. void handle_live() {
  181.   char temp[900];
  182.  
  183.   // Value Aquisition
  184.  
  185.   liveFlag = server.arg("live").toInt();
  186.   light1Set = server.arg("light1").toInt();
  187.   fan1Set = server.arg("fan1").toInt();
  188.  
  189.   Serial.println(liveFlag);
  190.   Serial.println(light1Set);
  191.   Serial.println(fan1Set);
  192.  
  193.   if (liveFlag) {
  194.  
  195.     if (light1Set == 1) {
  196.       digitalWrite(rele_light1, LOW);
  197.     }
  198.     else if (light1Set == 0) {
  199.       digitalWrite(rele_light1, HIGH);
  200.     }
  201.  
  202.     //FANS
  203.     if (fan1Set == 1) {
  204.       digitalWrite(rele_fan1, LOW);
  205.     }
  206.     else if (fan1Set == 0) {
  207.       digitalWrite(rele_fan1, HIGH);
  208.     }
  209.   }
  210.  
  211.   //Generate Response html
  212.   snprintf (temp, 900, html_page_live, showAux_bgcolor,
  213.             hour(), minute(), second(), flagLight, profile_OnTime, profile_TimeOn, showAux_sens_AmbTemperature, profile_AmbTemperature, showAux_sens_HumidityAr, profile_Humidity, sens_SoilHumidity, profile_SoilHumidity);
  214.  
  215.   //Send Html Response
  216.   if (!server.authenticate(www_username, www_password))
  217.     return server.requestAuthentication();
  218.   else
  219.     server.send ( 200, "text/html", temp );
  220. }
  221.  
  222. void loop() {
  223.   // Update time if needed
  224.   if (timeStatus() == timeNotSet) {
  225.     setSyncProvider(getNtpTime);
  226.   }
  227.  
  228.   //Handle some http conection
  229.   server.handleClient();
  230.  
  231.   if (!liveFlag) //-----Check if the ligths state is correct and update if needed
  232.     chkLightState();
  233.  
  234.   //--------------Read the Temp and Hum Sensors--------
  235.   if (millis() >= waitSensors) {
  236.     waitSensors = millis() + 3000; //if more than 30secs since last read
  237.     readSensors();
  238.     //Serial.println(sens_SoilHumidity);
  239.   }
  240.  
  241.   //-----React to Temperature & Humidity with the fans-----------//
  242.   if (!liveFlag)
  243.     chkFanState();
  244.  
  245.   //--------React to Soil Humidity----------//
  246.   if (profile_SoilHumidity + 10 < sens_SoilHumidity) // too much moist
  247.     bgcolor = String("#6A80ED"); // Azul
  248.   else if ( profile_SoilHumidity + 10 >= sens_SoilHumidity && sens_SoilHumidity > profile_SoilHumidity - 10) // +-10% = green
  249.     bgcolor = String("#20C42B"); //Green
  250.   else if ( profile_SoilHumidity - 10 >= sens_SoilHumidity && sens_SoilHumidity > profile_SoilHumidity - 20) // Dry
  251.     bgcolor = String("#F3EF11"); //Yelow
  252.   else //if ( profile_SoilHumidity-20 >= sens_SoilHumidity ) // too much Dry
  253.     bgcolor = String("#FF0000"); //Red
  254.  
  255.   bgcolor.toCharArray(showAux_bgcolor, bgcolor.length() + 1);
  256.  
  257.   //toCharArray(showAux_profile_Name, server.arg("profName").length() + 1);
  258. }
  259.  
  260.  
  261.  
  262.  
  263. void chkFanState() {
  264.  
  265.   // Porcedure where the ajusts to temperature response are made
  266.   // the sensor readers are compared to the profile loaded and response
  267.   // changing the speed of fans according to the temperature and some fixed settings
  268.  
  269.   if ( exaustFlag == 0 && (sens_AmbTemperature > profile_AmbTemperature) ) {                  // se os fans estao desligados e temp está 1 grau acima do definido
  270.     digitalWrite(rele_fan1, LOW);                                         // liga os 2 fans, um no min e um no medio
  271.     exaustFlag = 1;
  272.     analogWrite(fanCtrl1, 64);
  273.     analogWrite(fanCtrl2, 127);
  274.   }
  275.   else if ( ( exaustFlag == 1 ) && ( sens_AmbTemperature > profile_AmbTemperature + 3 ) ) {   // se os fan tão ligado e a temp ta 4 graus acima do definido, fans no maximo
  276.     analogWrite(fanCtrl1, 255);
  277.     analogWrite(fanCtrl2, 255);
  278.   }
  279.   else if ( ( exaustFlag == 1 ) && ( sens_AmbTemperature > profile_AmbTemperature + 2 ) ) {   // se os fan tão ligado e a temp ta 3 graus acima do definido, um max e um med
  280.     analogWrite(fanCtrl1, 255);
  281.     analogWrite(fanCtrl2, 127);
  282.   }
  283.   else if ( ( exaustFlag == 1 ) && ( sens_AmbTemperature > profile_AmbTemperature + 1 ) ) {   // se os fan tão ligado e a temp ta 2 graus acima do definido, dois meds
  284.     analogWrite(fanCtrl1, 127);
  285.     analogWrite(fanCtrl2, 127);
  286.   }
  287.   else if ( ( exaustFlag == 1 ) && ( sens_AmbTemperature > profile_AmbTemperature ) ) {       // se os fan tão ligado e a temp ta 1 graus acima do definido,um fraco e um med
  288.     analogWrite(fanCtrl1, 127);
  289.     analogWrite(fanCtrl2, 64);
  290.   }
  291.   else if ( ( exaustFlag == 1 ) && ( sens_AmbTemperature == profile_AmbTemperature ) ) {      // se os fans estão ligados e a temp ta igual a setada, dois fraco
  292.     analogWrite(fanCtrl1, 64);
  293.     analogWrite(fanCtrl2, 64);
  294.   }
  295.  
  296.   if ( exaustFlag == 1 && sens_AmbTemperature < profile_AmbTemperature ) {                    // se a temp esta 1 abaixo  do definodo desligue os fans
  297.     digitalWrite(rele_fan1, HIGH);
  298.     exaustFlag = 0;
  299.   }
  300.  
  301. }
  302.  
  303.  
  304.  
  305.  
  306. void readSensors() {
  307.   //----------DHT-----------//
  308.   sens_HumidityAr = Dht11_1.readHumidity(true);
  309.   sens_AmbTemperature = Dht11_1.readTemperature();
  310.   showAux_sens_AmbTemperature = (int) sens_AmbTemperature;
  311.   showAux_sens_HumidityAr = (int) sens_HumidityAr;
  312.  
  313.   //------Soil Humidity-----//
  314.   sens_SoilHumidity = map(analogRead(SOIL1_PIN), 0, 1024, 0, 100);
  315.  
  316.  
  317. }
  318.  
  319.  
  320.  
  321. time_t getNtpTime() {
  322.   while (Udp.parsePacket() > 0) ; // discard any previously received packets
  323.   Serial.println("Transmit NTP Request");
  324.   sendNTPpacket(timeServer);
  325.   uint32_t beginWait = millis();
  326.   while (millis() - beginWait < 1500) {
  327.     int size = Udp.parsePacket();
  328.     if (size >= NTP_PACKET_SIZE) {
  329.       Serial.println("Receive NTP Response");
  330.       Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
  331.       unsigned long secsSince1900;
  332.       // convert four bytes starting at location 40 to a long integer
  333.       secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
  334.       secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
  335.       secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
  336.       secsSince1900 |= (unsigned long)packetBuffer[43];
  337.       return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
  338.     }
  339.   }
  340.   Serial.println("No NTP Response :-(");
  341.   return 0; // return 0 if unable to get the time
  342. }
  343.  
  344. void sendNTPpacket(char* address)  {
  345.   // set all bytes in the buffer to 0
  346.   memset(packetBuffer, 0, NTP_PACKET_SIZE);
  347.   // Initialize values needed to form NTP request
  348.   // (see URL above for details on the packets)
  349.   packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  350.   packetBuffer[1] = 0;     // Stratum, or type of clock
  351.   packetBuffer[2] = 6;     // Polling Interval
  352.   packetBuffer[3] = 0xEC;  // Peer Clock Precision
  353.   // 8 bytes of zero for Root Delay & Root Dispersion
  354.   packetBuffer[12]  = 49;
  355.   packetBuffer[13]  = 0x4E;
  356.   packetBuffer[14]  = 49;
  357.   packetBuffer[15]  = 52;
  358.  
  359.   // all NTP fields have been given values, now
  360.   // you can send a packet requesting a timestamp:
  361.   Udp.beginPacket(address, 123); //NTP requests are to port 123
  362.   Udp.write(packetBuffer, NTP_PACKET_SIZE);
  363.   Udp.endPacket();
  364. }
  365.  
  366.  
  367. void chkLightState() {
  368.  
  369.   if (dayLight[hour()] == 1) {
  370.     digitalWrite(rele_light1, LOW);
  371.     flagLight = 1;
  372.     //Serial.println("Ligando Lampadas");
  373.   }
  374.   else if (dayLight[hour()] == 0) {
  375.     digitalWrite(rele_light1, HIGH);
  376.     flagLight = 0;
  377.     //Serial.println("Desligando Lampadas");
  378.   }
  379. }
  380.  
  381. void SetLightVector(int I, int D) {
  382.   //--Manipulates the dayLigth vector, wich is a
  383.   //  24 int vector tha represents the hours of the
  384.   //  day, when a position is set to 1, in the
  385.   //  respective hour of the day the light will be On.
  386.   //
  387.   // Receives the Initial hour to turn on the lights and the Duration of the sun bulb
  388.  
  389.  
  390.   for (int i = 0; i <= 24; i++)                   // Reset the vector to 0
  391.     dayLight[i] = 0;                              //
  392.   if (I + D > 24) {                               // if the Initial time plus Duration is bigger the 24
  393.     for (int i = I; i <= 24; i++)                 // from I to 24
  394.       dayLight[i] = 1;                            // full of ones
  395.     for (int i = 1; i <= (D + I - 24); i++)       // D + I - 24 = the amount of initial hours of the day to complete the time when the day turn, so if "i" is smaler
  396.       dayLight[i] = 1;                            // loop ant set to one
  397.   }
  398.   else {                                          // if D+I < 24
  399.     for (int i = I; i <= I + D - 1; i++)          // loop from I to I+D-1; "-1" because we need to set 1's just to the hours that the light shoud be on, and the hour to turn off should be set to 0
  400.       dayLight[i] = 1;                            // example: if I = 5 and D = 12, at 17 the light must be off, so we just set one in vector util the 16 hour.
  401.   }
  402. }
  403.  
  404. void showTimeVector() { // Created for Debug
  405.   for (int i = 1; i <= 24; i++) {
  406.     Serial.print("POS ");
  407.     Serial.print(i);
  408.     Serial.print(" = ");
  409.     Serial.println(dayLight[i]);
  410.   }
  411. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement