Arduino Smart Grow Box Controller Version 4.0 [OUT-DATED]with Wifi monitoring September Update


 /*     
    
   
    
   
  ************** UPDATED ON DEC 2017 *************  
   
 *************** GETTING BETTER THAN BEFORE *************  
   
    
   
    
   
    
   
  *** MAKING A MODULAR SYSTEM FOR D.I.Y. GROWBOX / GREENHOUSE   
   
   
   
     
  ***Independent Grow Box Controller that can be used to Control "" all the Important devices"" to maintain   
  *  
  *  
  the ""Grow Environment"" for example Lights, Heater,Cooler,Fan for blowing air inside the box ,Fan for exhaust,   
  Humidifier or mist maker   
  //###################################################################################   
  // For Water Pump,Level Sensor and Soil Humidity Sensor see V 5.0 of this Sketch    
      
  // https://amkdiyprojects.blogspot.com/2017/11/arduino-grow-box-green-house-controller.html   
  //###################################################################################  
     
     
     
     
  //**********************   
     
  // Arduino Nano Grow-box / Green-House Controller v 4.0 :)   
     
  //**********************   
     
 //###############################################################  
 //***************************************************************  
 
   
 // PLEASE SUBSCRIBE  
   
 // comment for any question or help with this sketch   
   
   
   
   
 //  My youtube Channel:  https://youtube.com/CrazyGuyOfficial  
   
   
 //****************************************************************  
 //################################################################ 
     
     
     
     
  //       ***Made by Ali khan from Pakistan :)   
     
     
  //**********************//**********************//**********************   
     
  // **PARTS required (for this sketch to work as it is )   
     
  //**********************//**********************//**********************   
     
  1.Arduino Nano   
     
  2.A thermistor (i used A 10K WATERPROOF ONE)   
     
  3.A resistor (matching the value of the thermistor's "nominal resistance at 25 DEGREES C" for example: 5k resistor for 5k thermistor)   
     
  4.OLED display ssd1306 (mine is ssd1306 but got it working by using sh1106 constructor also got rid of the "white line problem")   
     
  5. DHT 22 (WITH PULL UP RESISTOR I USED 10k OHM)  
     
  6.RELAY MODULE LOW LEVEL TRIGGER TYPE (5 Relays required in total for all the pins, can be seperate 4 CAN WORK TOO )   
     
  7. DS3231 RTC MODULE (RESISTOR from charging circuit REMOVED and charging DISABLED..BECAUSE I USED CR2032(NON-rechargeable)Cell   
     
  8. AN LED WITH APPROPRIATE RESISTOR FOR USING AS A STATUS LED   
     
 
  9. An ESP8266 / Wemos D1 / Node Mcu
  
     If you to want to monitor it Wirelessly using a 3.3 V Esp8266 with a 5V Arduino then Two Resistors 
     one 1K Ohm and one 2K Ohm . Using  these two resistors make a Voltage Divider Circuit by connecting 
     the Tx pin of Arduino to the 1K Resistor then on the other side of the 1K Resistor join the D1 pin(Rx) of Esp8266 
     and at the same point join the 2K Resistor and then the other side of the 2K Resistor to the Ground 
     The Ground Pin of Arduino and Esp8266 will also be joined together Directly 
     Sketch for the Esp8266 is on the blog 
*/    
 //**********************//**********************//**********************   
 // INCLUDE LIBRARIES make sure you have them all installed   
 //**********************//**********************//**********************   
     
   // Get them from within you Arduino IDE 1.6.9 that i used   
   // get the correct version  
   // by correct i mean the version that i used and   
   // because i can't guarantee that this sketch will work with  
   // other latest versions of the same libraries  
   
    
    
    
  #include "DHT.h"     // use DHTsensorLibrary // Version 1.2.3 //latest is the AdafruitUnifiedSensorLibrary    
     
  #include <U8glib.h>   // OLED   // Version 1.19.1
  #include <Wire.h>    // I2C   // Version 1.0.0
  #include <Time.h>    // Time Manipulation   // Version 1.5.0
  #include <DS1307RTC.h>  // DS1307 RTC   // Version 1.4.0
  #include <TimeAlarms.h> // time alarm library  // Version 1.5.0 
    
    
        // Changed Number of alarms " dtNBR_ALARMS to 8 "   
        // BY EDITING TIMEALARM.H FILE IN LIBRARIES FOLDER.   
          
        // increasing this number increases size of the sketch too   
        // and the use of ram  
   
        // if you don't want to change the number then remove alarms and keep only   
        // that number of Alarms that is specified in YOUR TimeAlarms Library   
          
        // I have Left 8 Alarms BELOW that Call a Function to Sync Arduino's Clock with RTC  
        // if you Uncomment the Rest you will get some Errors  
   
        // if you increase the Number in TimeAlarms.H file then   
        // Don't UN-comment Void SPrintStatusTwo   
        // That prints out Switch Status  
        // OR you will get Low Memory Error for Nano/UNO  
         
  #define DS1307_ID 0x68 //Address of the RTC   
     
     
      
     
     
     
 //**********************//**********************//**********************   
 //  TEMPERATURE and HUMIDITY DEFAULT "CONTROL PARAMETERS"              
 //**********************//**********************//**********************   
     
 //Default Temperature and Humidity Settings   
     
  byte Tmax  =  29 ;   // Set temperature Maximum point at which "Cooler" will turn ON   
  byte Tnor  =  25 ;   // Set temperature point at which "heater" and "cooler" will turn OFF   
  byte Tmin  =  19 ;   // Set temperature Minimum point at which Heater will turn ON   
  byte Hmax  =  60 ;   // set humidity max at which "bigfan" will turn ON   
  byte Hnor  =  45 ;   // Set humidity normal at which "bigfan" and "spray" will turn OFF   
  byte Hmin  =  25 ;   // Set humidity low at which "spray will turn ON   
     
     
  // Separate Temperature and Humidity Settings for Day and Night time can be done by Alarms function belowwww   
    
  // but anything done by Alarms is lost if a Reset happens or power up/down cycle   
  // and so in that case everything will return to their default state   
    
 //**********************//**********************//**********************   
 //  Light Timer ON/OFF Time Settings DEFAULT    
 //**********************//**********************//**********************   
     
     
  const byte OnTime = 14 ; // Hour when Light will turn ON (24 hr format NO zeros before single digits)   
  const byte OffTime = 8 ; // Hour when Light will turn OFF (24 hr format NO zeros before single digits)   
     
     
  // SET RTC'S TIME USING DS1307 EXAMPLE SKETCH FROM ABOVE FILE > EXAMPLE > DS1307 > SETTIME   
  // THEN UPLOAD THIS SKETCH   
     
     
   
    
    
    
 //*****************************************************************************************************************   
 //*****************************************************************************************************************   
 //*****************************************************************************************************************   
   
  //**********************//**********************//**********************   
  //  MAKING CHARACTER ARRAYS or C strings  for OLED   
  //**********************//**********************//**********************   
     
     
     
  char str[10]; // for Display   
//*****************************************************************************************************************  
 //*****************************************************************************************************************  
 //************ some important variables *************** Values NOT TO BE CHANGED MANUALLY *************************  
 //*****************************************************************************************************************  
 
 
 float t   =0;               // floats for Temperature1 and Humidity from DHT
 float h   =0;               

 float TmaxR    =   0;
 float HmaxR    =   0;
 
 
 
 
 
 float t2  =0;               // for Temperature 2 from Thermistor                   

 
 
 bool LightSts   = 0 ;       // DON'T CHANGE MANUALLY THESE ARE FOR STATUS UPDATES IN SERIAL MONITOR      
 bool CoolerSts  = 0 ;  
 bool HeaterSts  = 0 ;  
 bool BigFanSts  = 0 ;  
 bool SpraySts   = 0 ;  
 bool DHTerr     = 0 ;   
 bool RTCerr     = 0 ;
 byte TempSts    = 0 ;        // used for updating the oled display 
 byte HumSts     = 0 ;
 byte i          = 0 ;
 byte a          = 129 ;
 byte b          = 129 ;
 byte c          = 129 ; 
 
 
 unsigned long Secs = 0;  
 unsigned long SecsTwo = 0;  

//*****************************************************************************************************************  
//*****************************************************************************************************************  
//*****************************************************************************************************************  
//*****************************************************************************************************************  
//*****************************************************************************************************************  
//*****************************************************************************************************************  

 
 
 
 
//**********************//**********************//**********************  
//    PINS AND CONNECTIONS  for Relays and Arduino
//**********************//**********************//**********************  
 
 
 
 
 // Five pins used which have to be connected to five relays(optically isolated for eliminating interference)  
 // usually a 4 Relay board is available so it can be used as only one of the pins for Heater/Cooler are required   
 // and they can be swapped according to the outdoor temperature in different seasons  

 // TO optically isolate them properly Two separate power supplies have to be use 
 // one for Arduino and one for the Relay board
 // the relay board has a Removable Plastic Jumper connecting JDVCC-VCC pins, it has to be removed 
 
 // VCC pin on the Relay module is connected with the power supply one that powers Arduino    
 // the VCC on the Relay module powers the opto-isolators and the leds 
 // the In1,2,3,4 on the Relay board will be connected to Arduino's GPIOs and when the corresponding 
 // GPIO's are turned LOW and that Opto-Isolator will then turn ON because the In 1,2,3,4 pins are Ground pins 
 // for those four Isolator chips on the Relay Module and the Arduino Connects them to the Power Supply one's Ground 
 // To which the Arduinos Gnd pin is connected too 

 // Now the JDVCC pin and the Marked Gnd ground pin on the Relay module will be connected to the Second Power Supply 
 
 // and it will only power the Actual Relays on the Relay module 
 // it means the marked Ground pin on the module will not be connected to Arduino 
 // the only pins of Relay Module that connect to Arduino are VCC,IN1,IN2,IN3,IN4
 
 // LOW-level Relay board will trigger the relay when the trigger pin is LOW/off/grounded  
 // so when something has to be turned ON the trigger pin ( example IN3 ) will become LOW otherwise 
 // it will stay HIGH (asamf) all the time during which the thing is required to be  "OFF"   
   
 
 
 
 
 const byte Bigfan   = 4 ;    // Bigfan turns on at high humidity   
 const byte cooler   = 5 ;    // Cooler turn on at high temp (T1 from DHT)  
 const byte spray    = 6 ;    // Spray turns on at low humidity  
 const byte lightone = 7 ;    // Main Lights(for plants)   
   
 
 const byte heater   = 8 ;    // Heater turns ON at low temp (T1 from DHT)  
 
 const byte lighttwo = 3 ;    // pin for "status LED' indicating the loop is running when oled is turned OFF... 
 
 
 
 

   
 // ******** THERMISTOR AND DHT PINS BELOW *******  
 // Connect the RTC according to it's pinout   
 // DS3231 RTC "SDA to A4",  "SCL to A5"  "Vcc to 5V arduino pin Gnd to Gnd"

   

//***********************//**********************//*********************  
//   THERMISTOR PIN and SETTINGS  
//**********************//**********************//**********************  
   
 #define THERMISTORPIN A0     // which analog pin to connect to thermistor and the resistor "joint"      
   
   
   
   
 #define THERMISTORNOMINAL 10000  // resistance at 25 degrees C     
   
 #define TEMPERATURENOMINAL 25   // temp. for nominal resistance (almost always 25 C)  
   
 #define NUMSAMPLES 5  // how many samples to take and average,takes longer gets 'smooth'  
   
 #define BCOEFFICIENT 3500 // The beta coefficient of the thermistor (usually 3000-4000)  
   
 #define SERIESRESISTOR 9700 // the value of the 'other' resistor should be close to the thermistors nominal value   
   
 int samples[NUMSAMPLES];  
   
   
 
      

//***********************//**********************//*********************  
//   DHT PIN and SETTINGS  
//**********************//**********************//**********************  
   
   
  
 #define DHTPIN A1   // what pin we're connected to  
   
   
   
 #define DHTTYPE DHT22  // DHT 22 (AM2302)  
   
 DHT dht(DHTPIN, DHTTYPE, 6);  // the number 6 is for slower chips like the one used in Arduino Nano/UNO 
   
   
   
   
   
   

                  
   
   
//**********************//**********************//**********************  
//  OLED CONSTRUCTOR / OLED PINS that are connected to  Arduino
//**********************//**********************//**********************  
 
 
 
 U8GLIB_SH1106_128X64 u8g(13, 11, 10, 9); // SW SPI Com: SCK = 13, MOSI = 11, CS = 10, A0 = 9  // OLED "constructor" and pins info.  

                         // the version of oled i had has a different chip inside so the above one works for me 
                         // before it i used the one that was supposedly for my version of oled and it was not working as expected 
                         // if this doesn't work for you then go to Example Sketches for U8glib Library it has All the Constructors 
                         // try them for your version of OLED
   

//*****************************************************************************************************************  
//*****************************************************************************************************************  
//*****************************************************************************************************************  
//*****************************************************************************************************************  
//*****************************************************************************************************************  
//*****************************************************************************************************************  

 
 
  
 //**********************//**********************//**********************//**********************//**********************//**********************  
 //       SETUP BEGINS  
 //**********************//**********************//**********************//**********************//**********************//**********************  
   
 void setup() 
 
 {  
 
  
  Serial.begin(9600);       // for initializing serial monitor  

  pinMode(Bigfan, OUTPUT);  // set output relay pins // add more if you have more relays or pins connected to something   
  pinMode(cooler, OUTPUT);  
  pinMode(heater, OUTPUT);  
  pinMode(spray,  OUTPUT);  
  pinMode(lightone,OUTPUT);  
  pinMode(lighttwo,OUTPUT);  
   
    // add more if you have more relays or pins connected to something   
  
  
  digitalWrite(Bigfan, HIGH);  // When using "LOW level trigger" type Relay module, turning a pin "HIGH" will  
  digitalWrite(cooler, HIGH);  // turn the relay "OFF" and turning the pin "LOW" turns the relay "ON"    
  digitalWrite(heater, HIGH);  // THIS WILL PREVENT STARTUP RELAY TRIGGERING PROBLEM  
  digitalWrite(spray,  HIGH);  
  digitalWrite(lightone,HIGH);  
  
    // add more if you have more relays or pins connected to something   
  
  
  analogReference(EXTERNAL);  // AREF connected to 3.3 ON BOARD for accuracy of thermistor   
                 //(go to adafruit using a thermistor tutorial )  
   
   
   

 
 //*********************************************************************  
 //************* Display at Startup    ********************************* 
 //*********************************************************************   

   
  Start();
  Alarm.delay(3000);
 
  
  
  for (i=125; i>0;)
  {
   scrollText();
   a--;
   b++;
   c--;
   i--;
  }
 
  
  for (i=10; i>0;)
  {
  
   scrollText();
   b++;
   c--;
   i--;
  
  }
   
  
  for (i=50; i>0;)
  {
   scrollText();
   c--;
   i--;
  
  }
   
  
  //Alarm.delay(3000);
  LightSet();
  Alarm.delay(6000);

  TempSet();
  Alarm.delay(6000);
  
  HumSet();
  Alarm.delay(6000);
  
  //**********************//**********************//***********************//**********************  
  //Check to see if the RTC is present.if yes then Set the ARDUINO's INTERNAL clock accordingly  
  //**********************//**********************//***********************//**********************  
    
    
  // when using timer library the Arduino's "internal clock " is used for getting "current time"   
  // Arduino's internal clock is NOT so accurate and gets off time so we use time from RTC (which IS   
  // accurate at-least for our use) and we sync Arduino's internal Clock with the time from RTC and we   
  // have to do this periodically (at-least once in every 24 hrs )so our tasks can be completed according   
  // to the correct time we can put the sync command in the Loop and Alarm Functions too   
    
  
  Wire.beginTransmission(DS1307_ID);  // i2c devices have addresses which are used to communicate with them 
  Wire.write((uint8_t)0x00);          // because same interface can be used to connect multiple i2c devices 
   setSyncProvider(RTC.get);    

   setSyncInterval(60);
                                  
  
   
    
  //***********************//**********************//***********************//**********************  
   
  // TIMER ALARM THAT RUNS OVER AND OVER AFTER SECONDS // the Alarm in the Loop are different    
                                                       // see the Example Sketches with the TimeAlarms Lib 
  //***********************//**********************//***********************//**********************  
   
   
   
  Alarm.timerRepeat(10, Repeats);  // timer for every 10 seconds blinking LIGHT TWO (status LED)  
                                   // and Serial Prints Data              
                     
                          
  Secs=SecsTwo=millis()/1000; 
  dhtCalc()  ;
    
  ThermCalc(); 
 }  
   
 
 //**********************//**********************//**********************  
 
 //*********      SETUP END  ********************************************
 
 //**********************//**********************//**********************  



//*****************************************************************************************************************  
//*****************************************************************************************************************  
//*****************************************************************************************************************  
//*****************************************************************************************************************  
//*****************************************************************************************************************  
//***************************************************************************************************************** 
 

 
 
//*************************************************
//*** Function that Syncs Arduino's Clock with Rtc 
//************************************************* 


void SyncTime(){

  
  if (Wire.endTransmission() == 0)  //Did the RTC respond?  
  
  {  
  
   setSyncProvider(RTC.get);    //Yes it did, get the time from the RTC  

   RTCerr=0;
   Serial.println("Got Time");   

  }  
  else
  {
   RTCerr=1;
   
   
  }
  
}
 
//************************************************** 
//*** Function For Display on the OLED ************* 
//************************************************** 
 void Start()
 {

       
  u8g.firstPage();          // START SCREEN "Picture loop" for OLED  
   
  do {  
   
   u8g.setFont(u8g_font_helvB08);   // set font for oled display  
   
   u8g.drawFrame(10, 12, 108, 31);  // Draw Frame and it's Size 
   u8g.drawFrame(0, 0, 128, 64);  
   u8g.drawStr(15, 25, "Grow Box"); // Draw a string mentioned in quotes " "  
   
   u8g.setPrintPos(79,32);          // Set print position for the next line
   u8g.print("V 4.0");              // Print on the oled  
   
   u8g.drawStr( 16, 40, "Controller");  
   u8g.drawStr(53, 60, "Made by:AMK");            
  
    }  
   
  while ( u8g.nextPage() );  

} 
//*************************************************************** 
//*** Function For Light Control Settings Display on the OLED *** 
//*************************************************************** 
 void LightSet()
 {

       
  u8g.firstPage();          // START SCREEN "Picture loop" for OLED  
   
  do 
  {  
   
   u8g.drawFrame(0, 0, 128, 20);    // Draw frame  
   u8g.drawFrame(0, 22, 128, 42);   // Draw frame  

   u8g.drawStr(4, 14, "Light Control Hours");  
   u8g.drawStr( 4, 34,"ON:");   
   
   u8g.setPrintPos(31,34); 
   u8g.print(OnTime); 
   
   u8g.drawStr( 4, 46,"OFF:");   
   
   u8g.setPrintPos(37,46); 
   u8g.print(OffTime);
  
  }  
   
  while ( u8g.nextPage() );  
   
 }


//********************************************************************* 
//*** Function For Temperature Control Settings Display on the OLED *** 
//********************************************************************* 
 
 void TempSet()
 {
       
  u8g.firstPage();          // //START SCREEN "Picture loop" for OLED  
   
  do 
  {  
   u8g.drawFrame(0, 0, 128, 20);   // Draw frame  
   u8g.drawFrame(0, 22, 128, 42);  // Draw frame  
   u8g.drawStr(4, 14, "Temp Control Settings");  
   
   u8g.drawStr( 4, 34,"Max:");   
   u8g.setPrintPos(39,34); 
   u8g.print(Tmax); 
   u8g.drawStr( 58, 34, "\260C");  

   u8g.drawStr( 4, 46,"Nor:");   
   u8g.setPrintPos(39,46); 
   u8g.print(Tnor);
   u8g.drawStr( 58, 46, "\260C");  
  
   u8g.drawStr( 4, 58,"Min:");   
   u8g.setPrintPos(39,58); 
   u8g.print(Tmin);  
   u8g.drawStr( 58, 58, "\260C");  
 
    
  }  
   
  while ( u8g.nextPage() );  
   
 }

//********************************************************************* 
//*** Function For Humidity Control Settings Display on the OLED *** 
//********************************************************************* 


void HumSet()

{
  u8g.firstPage();          // //START SCREEN "Picture loop" for OLED  
   
  do 
  {  
   u8g.drawFrame(0, 0, 128, 20);   // Draw frame  
   u8g.drawFrame(0, 22, 128, 42);  // Draw frame  
   u8g.drawStr(4, 14, "Humidity Settings");  
   
   u8g.drawStr( 4, 34,"Max:");   
   u8g.setPrintPos(39,34); 
   u8g.print(Hmax); 
   u8g.drawStr( 58, 34, "%");  

   u8g.drawStr( 4, 46,"Nor:");   
   u8g.setPrintPos(39,46); 
   u8g.print(Hnor);
   u8g.drawStr( 58, 46, "%");  
  
   u8g.drawStr( 4, 58,"Min:");   
   u8g.setPrintPos(39,58); 
   u8g.print(Hmin);  
   u8g.drawStr( 58, 58, "%");  
 
  }  
   
  while ( u8g.nextPage() );  
 
}

// Startup display

void scrollText()
{

  u8g.firstPage();          // //START SCREEN "Picture loop" for OLED  
   
  do 
  
  {  
   u8g.drawFrame(0, 0, 128, 64); // Draw frame  
   u8g.drawStr(a, 14, ">> FOR MORE <<<<<<");  
   u8g.drawStr(b, 26, "> Please SUBSCRIBE << ");  
   u8g.drawStr(c, 48, "YouTube.com/CrazyGuyOfficial");  
  }  
  while ( u8g.nextPage() );  
 
}




   
 //***********************//**********************//***********************//**********************  
 //************// Function Called When Repeating Timer alarm triggers //*******************  
 //***********************//**********************//***********************//**********************  
   
void Repeats() 
{  
    
  if(!DHTerr && !RTCerr)     // only blink the light if DHTerr is not 1 because then status LED will constantly stay ON
  
  {
    digitalWrite(lighttwo, HIGH); // it is also used to indicate Dht read failed and lights up continuously below in dht part  
    
    Alarm.delay(30);  
   
    digitalWrite(lighttwo, LOW);  
  }  
   
  
  
  
  TimeDateDisplayOne();   // Update the Clock Display on Tx line  
                            // this calls the function TimeDateDisplayOne 
                            // includes time,date,day,year only numbers 
                            // Formatted to be read by ESP8266 using Serial.Read
  
  
  SPrintStatusOne();  // SerialPrints data on the Tx line of Arduino
                     // by connecting the Rx line of Esp8266 / Wemos D1 mini
                     // that is running an html webserver
                     // that data is read and categorized in Arrays and then displayed 
                     // on a simple html page
                     
       // *************              
       // * IMPORTANT * : if anything is changed Regarding serial.print/Serial.println 
       // *************   anywhere in the Sketch it WILL effect the Results of the sketch 
             //           running in Esp8266 because of the changed position/content of the 
             //           data printed on Tx line and Read by Rx of Esp8266 so keep it in mind 

 
// TimeDateDisplayTwo(); // For Humans Only

 
// SPrintStatusTwo();    // For Humans Only


}                            
   







//*****************************************************************************************************************  
//*****************************************************************************************************************  
//*****************************************************************************************************************  
//*****************************************************************************************************************  
//*****************************************************************************************************************  
//***************************************************************************************************************** 
 
 //***********************//**********************//***********************  
 //**********************//**********************//************************  
   
 //**********     LOOP BEGINS    ******************************************  
   
 //***********************//**********************//***********************  
 //**********************//**********************//************************  
   
   
   
void loop() 
 
{  
   
   
   
  if (hour() == 0 && minute() == 0 && second() == 0)  //If it is 00:00:00  MIDNIGHT UPDATE the Arduino's INTERNAL Clock  
 
  {  
  
   SyncTime();  
   
  }  
   
   
   
   
   
    
    
    
    
    
 //***********************//**********************//***********************//************************  
   
    
 //***** LET THERE BE LIGHT  ************************************************************************   
    
   
 //**************************************************************************************************  


 // This will make sure that the light one (for plants) stays ON after reset or power down/up cycle   
 // because Alarms will trigger on a given time and will turn the pin HIGH but if after the alarm is   
 // triggered AND there is a reset the pin will turn off until next alarm that turns it ON again   
 // which can interrupt photo-period for plants So, this  makes sure that LIGHTS turn ON immediately   
 // after reset which happens DURING the LIGHT period for plants  
   
   
   
 //####################################################################################################

  // Turn Lights On/Off

  //####################################################################################################


  // if(!RTCerr)   // only if RTC error is 0 or False
  // {

  // IF Turning ON the Light is Required on one day and Turning OFF on the same day
  // within the 24 hrs of that day 00:00 --- 11:59


  if (OffTime > OnTime)  // Same Day

  { // GETS THE JOB DONE :)


    if (hour() >= OnTime && hour () <= OffTime - 1)

    {

      // if current hour is equal to or greater than ON time
      // AND equal to or less than OFF time minus 1 then turn the
      // lights ON (by turning pins LOW because of using LOW level Relays)

      // Minus 1 from OFF time because we are not using Minutes here
      // For Example turn off time is "16" (4 PM) the hour number will be "16" from
      // 16:00 till 16:59 (4:00 till 4:59)
      if (!LightSts)
      {
        digitalWrite(lightone, LOW);
        Alarm.delay(2000);
        LightSts = 1 ;
      }

    }


    else

    {
      digitalWrite(lightone, HIGH);

      LightSts = 0 ;

    }



  }


  //####################################################################################################


  if (OffTime < OnTime)  // Different Day

  {
    // IF Turning ON the Light is Required on ONE DAY and

    // Turning OFF on the SECOND DAY

    if (hour() >= OnTime || hour () <= OffTime - 1)

    {

      // if current hour is equal or greater than ON time
      // OR equal to or less than OFF time minus 1 then turn the
      // lights ON (by turning pins LOW because of using LOW level Relays)
      // Minus 1 from OFF time because we are not using Minutes here
      // For Example turn off time is "16" (4 PM) the hour number will be "16" from
      // 16:00 till 16:59 (4:00 till 4:59)
      // Minutes,Seconds even day,date,year can be used by adding code

      if (!LightSts)
      {
        digitalWrite(lightone, LOW);
        Alarm.delay(2000);
        LightSts = 1 ;
      }



    }


    else

    {

      digitalWrite(lightone, HIGH);

      LightSts = 0 ;

    }




  }



  // }
  // else
  // {
  //  digitalWrite (lighttwo,HIGH); // turn status LED indicate RTC error
  //  //Serial.println("Something Wrong with RTC.So, NOT Controlling Lights Now");

  // }


  if (RTCerr)
  {
    digitalWrite (lighttwo, HIGH); // turn status LED indicate RTC error
  }









  
  
 //********************************************************************************************************************************************  
 // *******************************************************************************************************************************************  
 //  DAILY TIMED ALARMS THAT TRIGGER ON SPECIFIED TIMES  
   
 // these alarms will trigger once and will do "stuff" mentioned in the alarm functions at the end of the loop  
   
 // *******************************************************************************************************************************************  
 
  Alarm.alarmRepeat(3, 0, 0, ON2Alarm);  // daily Alarm 1  for example // for triggering an alarm on ""03:00:00"" in the morning  
                                        // ONAlarm is the name of the function that will be called when the current time matches 
                                        // the Time you have set for the specified alarm
                                        // the ONAlarm function is defined below and the name ONAlarm can be changed 
  
  
  Alarm.alarmRepeat(6, 0, 0, ON2Alarm);  //Alarm 2  // for triggering an alarm on ""06:00:00"" in the morning  
     
  Alarm.alarmRepeat(9, 0, 0, ON2Alarm); // daily Alarm 3  
       
  Alarm.alarmRepeat(12, 0, 0, ON2Alarm);  // daily Alarm 4  
     
  Alarm.alarmRepeat(15, 0, 0, ON2Alarm);  // daily Alarm 5  
     
  Alarm.alarmRepeat(18, 0, 0, ON2Alarm); // daily Alarm 6  
     
  Alarm.alarmRepeat(21, 0, 0, ON2Alarm);  // daily Alarm 7  
   
  
  
 // Alarm.alarmRepeat(0, 0, 0, OFFAlarm);  // daily Alarm 22  
      
 // Alarm.alarmRepeat(1, 0, 0, OFFAlarm);  // daily Alarm 23  
     
 // Alarm.alarmRepeat(2, 0, 0, OFF2Alarm); // daily Alarm 24  
   
   
   
   
   
   

 
 
  if(millis()/1000 -SecsTwo > 2  ) // Every Two Seconds
  {
    
   dhtCalc()  ;  // Update Temperature and Humidity from DHT22
    
   ThermCalc();  // Update Temperature from Thermistor
    
   SecsTwo=millis()/1000;   
   
  } 


   
   
   
   
   
   
  //#########################################################################################################
  //#########################################################################################################

  // CONTROL PART turning things ON and OFF according to Temperature and Humidity (THE GOOD STUFF) "ifs"

  //#########################################################################################################
  //#########################################################################################################

  if (!DHTerr)         // only proceed to controlling things according to Temp1 and humidity
  { // if there is no DHT read error

    if (t >= Tmax )      // TURN COOLER ON IF TEMPERATURE IS EQUAL TO OR EXCEEDS "Tmax" (HEATER remains OFF)
    {
      if (!CoolerSts)
      {
        digitalWrite(cooler, LOW);// Turn Cooler Pin LOW // ON because of LOW Level trigger Relay

        Alarm.delay(2000);

        CoolerSts = 1 ;      // Cooler Status is ON // Status is used for Serial Print

      }
      TempSts = 4;      // High Temp // Status is used by Oled

    }




    if (t <= Tnor )       // Turn OFF the COOLER when TEMP GETS DOWN TO "setT" OR GOES BELOW

    {

      digitalWrite(cooler, HIGH);

      CoolerSts = 0 ;

    }




    if (t <= Tmin)       // TURN HEATER "ON" WHEN TEMPERATURE GETS TO "Tmin" OR BELOW (cooler remains OFF)

    {
      if (!HeaterSts)
      {
        digitalWrite(heater, LOW);

        Alarm.delay(2000);

        HeaterSts = 1 ;
      }


      TempSts = 1;      // Low Temp

    }




    if (t >= Tnor )     // TURN OFF HEATER WHEN TEMP GETS TO "setT" (and REMAINS LOWER THAN "Tmax")

    {

      digitalWrite (heater, HIGH);

      HeaterSts = 0 ;


    }



    //######################################/
    //######################################/
    //# Just for Setting Status of things #
    //######################################/
    //######################################\   


    if (t <= Tmax && t > Tnor)

    {
      TempSts = 3; // Upper Range
    }






    if (t <= Tnor && t > Tmin)

    {
      TempSts = 2; // normal range
    }



    if ( t > TmaxR)
    {

      TmaxR = t;   // Update Max Recorded Temperature For the Session

    }

   



    //#######################################################

    //############### Control for HUMIDITY ###############

    //#######################################################


    if (h >= Hmax)

    {
      if (!BigFanSts)
      {
        digitalWrite(Bigfan, LOW); // Turn fan on when humidity is high

        Alarm.delay(2000);

        BigFanSts = 1 ;
      }

      HumSts = 4;        // humidity max/high

    }


    if (h <= Hnor )

    {

      digitalWrite(Bigfan, HIGH);

      BigFanSts = 0;

    }



    if (h <= Hmin)
    {
      if (!SpraySts)
      {
        digitalWrite(spray, LOW); // Turn Spray on when humidity is low

        Alarm.delay(2000);

        SpraySts = 1 ;
      }
      HumSts = 1;  // humidity low

    }

    if (h >= Hnor)

    {

      digitalWrite(spray, HIGH); // Turn Spray off when humidity is normal or high

      SpraySts = 0 ;

    }





    if (h > Hnor && h < Hmax)

    {
      HumSts = 3; // upper range
    }



    if (h > Hmin && h <= Hnor)
    {
      HumSts = 2; // normal range
    }

    if ( h > HmaxR)
    {

      HmaxR = h;   // Update Max Recorded Humidity For the Session

    }
  

  }

  else       // if DHT error  

  {

    digitalWrite (lighttwo, HIGH); // turn status LED indicate DHT error
    //Serial.println("Something Wrong with DHT.So, NOT Controlling Things Now");
    digitalWrite(Bigfan, HIGH);
    digitalWrite(cooler, HIGH);
    digitalWrite(heater, HIGH);
    digitalWrite(spray, HIGH);


  }


    
Display();  // Call the Display function below for OLED
    
 if(millis()/1000 -Secs > 30  )
 {
  RecDisplay();
  Alarm.delay(3000);
  Secs=millis()/1000;

   
 } 



  
   
   
    
   
   
}  

 
 //**********************//**********************//**********************  
 //               LOOP END  
 //**********************//**********************//**********************  




//*****************************************************************************************************************  
//*****************************************************************************************************************  
//*****************************************************************************************************************  
//*****************************************************************************************************************  
//*****************************************************************************************************************  
//***************************************************************************************************************** 
   //***********************//**********************//***********************//**********************  
   
 //            DHT 22****** TEMPERATURE HUMIDITY CALCULATIONS  
   
 //***********************//**********************//***********************//**********************  
   
void dhtCalc()  
{  
   
   
  h = dht.readHumidity();    // READ HUMIDITY  
   
  t = dht.readTemperature(); // Read temperature as Celsius  
    
  
  // Check if any reads failed and exit early (to try again)  
     
  if (isnan(h) || isnan(t) ) 
  {  
   
   Alarm.delay(1000);  
   
    
   
   DHTerr=1;  


   
             
  }  
   
 
  else
  {    

   DHTerr=0;
  
  }
   
   
  /*Serial.print("Humidity: ");  
   Serial.print(h);  
   Serial.print(" %\t");  
   
   Serial.print("T1: ");  
   Serial.print(t);  
   Serial.print(" *C ");  
   */  
   
}
//***************************************************************************************************************  
    
 //               THERMISTOR CALCULATIONS  
    
 //***************************************************************************************************************  
   
void ThermCalc()   
{
   
   
  byte i;  
  float average =0 ;  
   
   
  for (i = 0; i < NUMSAMPLES; i++)  // take "N" number of samples in a row, with a slight delay  
  {   
  
   samples[i] = analogRead(THERMISTORPIN);  
   Alarm.delay(10);  
  
  }  
   
   
   
  
  for (i = 0; i < NUMSAMPLES; i++)  // average all the samples out  
  {   
   average += samples[i];  
  }  
  
  average /= NUMSAMPLES;  
   
   
   
   
   
  average = 1023 / average - 1;       // convert the value to resistance  
  average = SERIESRESISTOR / average;  
   
  
  
  //Serial.print("Thermistor resistance ");  
   
  //Serial.println(average);  
   
    
   
   
   
   
  t2= average / THERMISTORNOMINAL;   // (R/Ro)  
  t2 = log(t2);         // ln(R/Ro)  
  t2 /= BCOEFFICIENT;          // 1/B * ln(R/Ro)  
  t2 += 1.0 / (TEMPERATURENOMINAL + 273.15); // + (1/To)  
  t2 = 1.0 / t2;         // Invert  
  t2 -= 273.15;                               // convert to C  
   
  
  /*
  Serial.print("T2 ");         // FOR SERIAL MONITOR  
  Serial.print(t2);  
  Serial.println(" *C");  
  */  
   
   
   
}  
   
   

//***********************//**********************  
   
// OLED PART  
   
//FUNCTION FOR DISPLAY ON THE OLED  
   
//***********************//**********************  
   
   
   
   
void Display()
  
{

 char timebuf[5]; // array for Time  
   
   
 tmElements_t tm;          //formatting time and date before displaying  
    
    
  if (RTC.read(tm)) 
  {  
   sprintf(timebuf, "%02d:%02d", tm.Hour, tm.Minute); // format time  
  }
    
    
   
 u8g.firstPage();          
     
    
 
 
 
 
  do 
  {  
     
   u8g.drawFrame(0, 0, 128, 20);   // Draw frame  

    if(DHTerr)       // if DHT error is 1 or true then display dht error on oled
    {
     u8g.drawStr( 35, 14, "* DHT ERROR *");  
    }
   
  
  
//*******************************************************************************  
    else            // else display values
    {
   
     switch (HumSts)   // Display According to Humidity Status on OLED 
   
     {
    
      case 4:
             u8g.drawStr( 91, 14, "*H MX*");  // humidity is equal to max or more than max
      break;
      
      
      case 3:
             u8g.drawStr( 91, 14, "*H AN*");  // above normal
      break;
      
    
      case 2:
             u8g.drawStr( 91, 14, ">H NR<");  // Normal
      
      break;
      
      
      case 1:
             u8g.drawStr( 91, 14, "*H LW*"); // Lower than Minimum Humidity
      break;
           
     }
      
//*********************************************************************   
     switch (TempSts) // Display According to Temperature Status on OLED 
     {
      case 4:
             u8g.drawStr( 34, 14, "*HI TMP*");  
      break;
      
     
      case 3:
             u8g.drawStr( 34, 14, "*ABV NR*");  
      break;
      
      
      case 2:
             u8g.drawStr( 34, 14, ">NR TMP<"); 
      break;
      
      
      case 1:
             u8g.drawStr( 34, 14, "*LO TMP*");  
      break;
           
     }
   
   
   
   
  }
   
   
   
 //************// Display Time on OLED//**************//  
          
    if(!RTCerr)
    {      
     u8g.setPrintPos(2, 14); // set position for displaying time  
     u8g.print(timebuf);    //display time  
    }
   else
   {
     u8g.drawStr( 2, 14, "RtcEr");  

   }
   
   
   
   
   
 //******// Display CURRENT Temperature1&2,humidity , Set Tmax ,Set Tnor and Set Tmin on OLED//*********************  
   
      
   u8g.drawFrame(0, 22, 128, 42);  // Draw frame  
   
      
   u8g.drawStr(2, 32, "T  :");  // first digit is screen coordinate for X-axis and second for Y-axis  
 
                   // (it starts on left bottom corner of the text which is to be shown on the oled)  
      
                   // T1 for temperature from DHT22 and T2 is from Thermistor  
      
   u8g.drawStr( 21, 32, dtostrf(t, 5, 2, str));   
   u8g.drawStr( 51, 32, "\260C");  
     
   
   u8g.drawStr( 2, 42, "M :");  
   u8g.drawStr( 21, 42, dtostrf(Tmax, 5, 2, str));  
   u8g.drawStr( 51, 42, "\260C");  
   
   u8g.drawStr( 2, 52, "N ");  
   u8g.drawStr( 15, 52, ":");  

   u8g.drawStr( 21, 52, dtostrf(Tnor, 5, 2, str));  
   u8g.drawStr( 51, 52, "\260C");  
   
   u8g.drawStr( 2, 62, "m ");  
   u8g.drawStr( 15, 62, ":");  

   u8g.drawStr( 21, 62, dtostrf(Tmin, 5, 2, str));  
   u8g.drawStr( 51, 62, "\260C");  
   
   
   
   
   u8g.drawStr( 65, 32, "T2:");  
   u8g.drawStr( 83, 32, dtostrf(t2, 5, 2, str));   
   u8g.drawStr( 113, 32, "\260C");  
      
      
   u8g.drawStr( 65, 42, "H  :");  
   u8g.drawStr( 83, 42, dtostrf(h, 5, 2, str));  
   u8g.drawStr( 117, 42, "%");  
      
   u8g.drawStr( 65, 52, "M :");  
   u8g.drawStr( 83, 52, dtostrf(Hmax, 5, 2, str));  
   u8g.drawStr( 117, 52, "%");  

   u8g.drawStr( 65, 62, "m ");  
   u8g.drawStr( 78, 62, ":");  

   u8g.drawStr( 83, 62, dtostrf(Hmin, 5, 2, str));  
   u8g.drawStr( 117,62, "%");  


  
   
      
   //Alarm.delay(300);    // Comment this line to make the oled display as fast as possible   
                        // Keep in mind that thermistor values change really fast 
                        // and are not so accurate so this is necessary to make the display smooth
 
 
  } 
  
  while ( u8g.nextPage() );  
    
   
}
   

   
   
   
 void RecDisplay()
 {
       
  u8g.firstPage();          
   
  do 
  {  
   u8g.drawFrame(0, 0, 128, 20);   // Draw frame  
   u8g.drawFrame(0, 22, 128, 42);  // Draw frame  
   u8g.drawStr(4, 14, "Max Recorded");  
   
   u8g.drawStr( 4, 34,"T Max:");   
   u8g.setPrintPos(47,34); 
   u8g.print(TmaxR); 
   u8g.drawStr( 75, 34, "\260C");  

   u8g.drawStr( 4, 46,"H Max:");   
   u8g.setPrintPos(47,46); 
   u8g.print(HmaxR);
   u8g.drawStr( 79, 46, "%");  
  
   
    
  }  
   
  while ( u8g.nextPage() );  
   
 }  
   
   
   
   
 //**********************//**********************//**********************//**********************  
   
 //Functions called when daily time specific alarms (above in the loop) triggers:   
   
 //***********************************************//**********************//**********************  
   
/*   
void ONAlarm() 
{  
    
//   Tmax = 29;                 // set day time temperatures  
//   setT = 25;  
//   Tmin = 19;  
   
    
}  
   
void OFFAlarm() 
{  
//   Tmax = 26;                // set night time temperatures  
//   setT = 23;  
//   Tmin = 19;  
  
 }  
      
*/

void ON2Alarm() 
{  

 SyncTime();    

}  
   
   



   
   
void OFF2Alarm() 
{  
 
 SyncTime();    

}  

//************************************************************************************** 
//*** Function for Serial Printing status of switches and other values ** FOR ESP8266  * 
//**************************************************************************************   
   
   
void SPrintStatusOne()

 {            
  Serial.print ('L');  
  Serial.print (LightSts);  

  Serial.print ('C');  
  Serial.print (CoolerSts);  
   
  Serial.print('H');  
  Serial.print(HeaterSts);
   
  Serial.print('B'); 
  Serial.print(BigFanSts);

  Serial.print('S');
  Serial.print(SpraySts);   
  
  Serial.print('E'); 
  Serial.print(DHTerr);
  Serial.print(RTCerr);
  
  Serial.print('t');
  Serial.print(t);
 
  Serial.print('h');
  Serial.print(h);

  Serial.print('r');
  Serial.println(t2);
 

 }


 
//************************************************************************************* 
//*** Function for Serial Printing status of switches and other values ** FOR HUMAN *** 
//*************************************************************************************     
   
/*
 void SPrintStatusTwo()
 {
   Serial.print("T1: ");
   Serial.println(t);
 
   Serial.print("H: ");
   Serial.println(h);
   
  
   Serial.print("T2: ");
   Serial.println(t2);





  
     if(LightSts)
  {
   Serial.println ("Light ON");  
  }
  
  else
  {
   Serial.println("Light OFF");
  }
  
  
  if(CoolerSts)  
  {
  Serial.println("Cooler ON");   
  }
  
  else
  {
   Serial.println("Cooler OFF");
  }
  
  if(HeaterSts)  
  {
  Serial.println("Heater ON");   
  }
  
  else
  {
   Serial.println("Heater OFF");
  }
  
  if(BigFanSts)  
  {
  Serial.println("Fan ON");   
  }
  
  else
  {
   Serial.println("Fan OFF");
  }
  
  if(SpraySts)
  {
   Serial.println("Spray ON");
  }
  
  else
  {
   Serial.println("Spray OFF");
  }
  
 
 
 
 }
   

*/


//**********************//**********************//********************************  
   
//Function for digital clock display (in the SERIAL MONITOR   ***  FOR ESP8266 ***
   
//**********************//**********************//********************************  
   
   
   
   
void TimeDateDisplayOne()  // digital clock display  24hr format // for ESP-8266 and HUM-an too :)

{            
   
 Serial.print("Z");  

 PrintZD(hour());          // Print Hour Digit and add a zero before single digits  
   
 PrintCD(minute());        // Print a colon sign ":" and add zero before single digits
   
 PrintCD(second());   
 
  
 Serial.print('W');
 Serial.print(weekday());   // there are no double digits only 7 days in a week
 
 Serial.print('D');
 PrintZD(day());           // Print the Day of the month and add zero before single digits 
                           
 
 Serial.print('M');        // add zero before single digit month numbers 
 PrintZD(month());
 
 Serial.print('Y');
 Serial.print(year()); 

}  
   


//**********************//**********************//**********************//*****

//Function for digital clock display (in the SERIAL MONITOR   *** FOR HUMAN ***   
   
//**********************//**********************//**********************//*****  
   
   
/*

void TimeDateDisplayTwo() // digital clock display of the time 24hr format // for HUM-an
{
 
 Serial.println("****>> 10 second timer<< ****");  
 
 Serial.println("TIME");                                
 
 PrintZD(hour());  
   
 PrintCD(minute());  
   
 PrintCD(second());  
   
 Serial.println();
 
 Serial.println("DATE");  
   
 Serial.print(dayStr(weekday()));  
    
 Serial.print("-");  

   
 Serial.print(day());  
  
 Serial.print("-");  
  
 Serial.print(monthStr(month()));  

 Serial.print("-");  

 Serial.println(year());  

}  



*/












//***********************************************************************
//** Function for adding Zero before single digits before Serial print **
//***********************************************************************

void PrintZD(int D)   

{  
  if(D < 10)         // don't add brackets for this if statement it will not work
 
   
   Serial.print('0');
 
   Serial.print(D);  
   

}  

//*********************************************************************************
//** Function for adding a Colon & Zero before single digits before Serial print **
//*********************************************************************************
 
void PrintCD(int digits) 
{  
  Serial.print(":");  

  if (digits < 10)    // don't add brackets for this if statement it will not work
                      
   Serial.print('0');  
 
   Serial.print(digits);  
  

}  
 
 
 
 
 
 //******************************  
 //***************  THE END *****
 //****************************** 

Esp8266 Wemos D1 Mini Serial to Wifi Html WebServer Monitor for Arduino Smart Grow Box Controller [OUT-DATED]

 /* #########################################################################  
   #################### Esp8266 Serial to WiFi Monitor #####################  
   ########################## WEMOS D1 MINI ################################  
   ############################### for #####################################  
   ################### ARDUINO NANO SMART GROW CONTROLLER ##################  
   #################                              ##########################  
   ############################ |WWWW| #####################################  
   ############################ \O_O/ ######################################  
   #  CAN BE USED AS A GENERAL PURPOSE MONITOR FOR ANYTHING WITH A TX PIN ##  
   #############        AFTER SOME MODIFICATIONS        ####################  
 */  
     
   
   
 /* #########################################################################  
 I'll improve it as i learn more  
  #########################################################################  
 // PLEASE LIKE AND SUBSCRIBE   
 // MY YOUTUBE CHANNEL   
 // YOUTUBE.COM/CRAZYGUYOFFICIAL  
 // Visit Blog for Sketch Updates and more Sketches and "things"  
   
   
 // Set Port forward from your router to this Webserver at port 80  
 // to monitor it from anywhere**  
   
 // This server is not secure   
 // controlling things should NEVER be done using   
 // an UN-encrypted webserver like this  
 // It's only good for Monitoring   
 // Subscribe to my channel for updates for this sketch   
 // and other sketches related to this project   
 // because i'll add more things to it gradually   
   
  #########################################################################  
  #########################################################################  
   
   
 */  
   
 #include <ESP8266WiFi.h>  // Version 1.0.0  
 #include <SoftwareSerial.h>  // Version 1.0.0
   
   
   
 const char* ssid = "SQUANCHY01";  
 const char* password ="c137gsasotf";  
   
   
   
   
   
   
   
 char Time[9];           // Character Arrays or C-strings   
 char Day;             // size should be the total number of Chars to be stored +1 for null char  
 char Date[3];  
 char Mon[3];  
 char Year[5];  
 char Status[13];  
 char Temp1[6];  
 char Temp2[6];  
 char Hum[6];  
   
 unsigned long Secs = 0;   
   
 bool newData = 0;  
 bool err =1;  
   
 bool Lsts =0;  
 bool Csts =0;  
 bool Hsts =0;  
 bool Fsts =0;  
 bool Ssts =0;  
 bool DHTerr=0;  
 bool RTCerr=0;  
   
 WiFiServer server(80);  
   
 SoftwareSerial swSer(D1, D2, false, 256);   // "swSer can be changed it will be the name for the Software Serial   
                        // Software Serial Library Enables Esp8266's GPIO D1 and D2   
                        // to be used as Rx and Tx pins RESPECTIVELY   
                        // ONLY Rx is used and is connected to the Tx of a 5V Arduino Nano   
 void setup() {                // using a Voltage Divider circuit 1K and 2K Resistors   
                        // And Ground of esp to Ground of Arduino   
   
   
 Serial.begin(115200);             // This is the baud rate for ESP's Serial at USB which can be viewed in Arduino IDE Serial monitor  
    
 swSer.begin(9600);              // This is the baud rate for esps Software serial at pins D1 and D2 so it can communicate with arduino   
                        // it's slow because of Arduino Nano's slow speed as compared to Esp  
                        // can change the name swSer from above  
 delay(10);  
   
    
    
 Serial.println();  
    
 Serial.print("Connecting to ");  
    
 Serial.println(ssid);  
    
     
     
 WiFi.mode(WIFI_STA);           
                       
 WiFi.begin(ssid, password);  
    
    
    
    
 while (WiFi.status() != WL_CONNECTED)   
    
  {  
      
  delay(500);  
     
  Serial.print(".");  
    
  }  
    
    
  Serial.println("");  
    
  Serial.println("WiFi connected");  
    
    
  server.begin();  
    
  Serial.println("Waiting for the IP Add...");  
    
  delay(5000);  
    
    
  Serial.println(WiFi.localIP());  
   
  }  
   
   
 /*##############################################################################################  
  ###############################################################################################  
  ################ SETUP END ####################################################################  
  ###############################################################################################  
  */  
   
   
   
   
   
   
   
 /*##############################################################################################  
  ###############################################################################################  
  ################ LOOP BEGINS ##################################################################  
  ###############################################################################################  
  */  
   
   
 void loop()   
 {    
  char data[53];  
  byte i = 0 ;  
  byte x = 0 ;  
    
  if (swSer.available() > 0 )   
   
  {    
  char Z = swSer.read();  
     
   if(Z=='Z')   // match first Character to check "validity"   
   {        // and this letter 'Z' is not stored in the array below   
   
   newData=1;  
   Secs=millis()/1000;  
    
    for(i= 0; i< 52; )   
      
    {  
     data[i] = swSer.read();  
       
     i++;  
       
     data[i] = '\0';  
    }  
   
    
    for(i=0; i<52;)  
    {                // serial print to arduino ide monitor via usb,all the chars stored in data array  
     Serial.print("char number: "); // and print char number the INDEX number starting from zero   
                    // the actual first char is the Letter "Z' which is not stored  
     Serial.println(i);  
   
     Serial.println(data[i]);                
    
     i++;         
    }  
    
   }  
  else  
  {  
   err=1;  
  }  
  }  
   
   
 //############# GET TIME #######################################################################  
   
  if(newData)  
  {  
                       // get time from the data array   
   for( i = 0; i < 8; )   
   {   
    Time[i] = data[i];  
    
    i++;   
     
   }  
   
   Serial.print("Time :");   
   
   Serial.println(Time);           // serial print all the chars stored in the time array   
    
    
 //############# GET DAY OF THE WEEK #############################################################  
    
   if( data[8]=='W' )   
    
   {  
    err=0;  
    Day = data[9];  
     
   
   Serial.print("Day :");   
   
   Serial.println(Day);           // serial print all the chars stored in the day array   
   }  
   else  
   {  
   err=1;   
   }  
   
 //############# GET DATE #######################################################################  
   
   if(data[10]=='D')  
   {  
    err=0;   
    x=0;  
    for( i = 11; i < 13; )   
    {  
     Date[x] = data[i];  
     i++;   
     x++;  
    }  
   
    Serial.print("Date :");   
   
    Serial.println(Date);         // serial print all the chars stored in the Date array   
   }  
   else  
   {  
    err=1;   
   }  
   
   
   
 //############# GET MONTH #######################################################################  
   
   
   if(data[13]=='M')  
   {  
    err=0;   
    x=0;  
    for( i =14 ; i < 16; )   
    {  
     Mon[x] = data[i];  
     i++;   
     x++;  
    }  
     
    Serial.print("Month :");   
   
    Serial.println(Mon);          // serial print all the chars stored in the month / mon array   
   }  
   else  
   {  
    err=1;   
   }  
   
 //############# GET YEAR #######################################################################  
   
   if(data[16]=='Y')  
   {  
    err=0;   
    x=0;  
    for( i = 17; i < 21; )   
    {  
     Year[x] = data[i];  
     i++;   
     x++;  
    }  
   
    Serial.print("Year :");   
   
    Serial.println(Year);         // serial print all the chars stored in the Year array   
    
   }  
   else  
   {  
    err=1;   
   }  
    
    
 //############# GET STATUS #######################################################################  
   
   if(data[21]=='L')  
   {  
    err=0;   
    x=0;  
    for( i = 22; i < 34; )   
    {  
     Status[x] = data[i];  
     i++;   
     x++;  
    }  
    
    Serial.print("Status :");   
   
    Serial.println(Status);       // serial print all the chars stored in the Status array   
   }  
   else  
   {  
    err=1;  
   }  
   
    
 //############# GET T1 ###########################################################################  
   
   if(data[34]=='t')  
   {  
    err=0;   
    x=0;  
    for( i = 35; i < 40; )   
    {  
     Temp1[x] = data[i];  
     i++;   
     x++;  
    }  
   
    Serial.print("Temp 1 :");   
   
    Serial.println(Temp1);    // serial print all the chars stored in the temperature / temp1 array   
   }  
   else  
   {  
    err=1;   
   }  
   
   
 //############# GET Hum #######################################################################  
   
   
   if(data[40]=='h')  
   {   
    err=0;  
    x=0;  
    for( i = 41; i < 46; )   
    {  
     Hum[x] = data[i];  
     i++;   
     x++;  
    }  
   
    Serial.print("Humidity :");   
   
    Serial.println(Hum);    // serial print all the chars stored in the Humidity / Hum array   
   }  
   else  
   {  
    err=1;   
   }  
   
 //############# GET T2 #######################################################################  
   
   
   if(data[46]=='r')  
   {   
    err=0;  
    x=0;  
    for( i = 47; i < 52; )   
    {  
     Temp2[x] = data[i];  
     i++;   
     x++;  
    }  
    
    Serial.print("Temp2 :");   
   
    Serial.println(Temp2); // serial print all the chars stored in time array   
   }  
   else  
   {  
    err=1;   
   }  
    
  newData=0;  
   
 }  
   
   
  setStatus();  
    
  sendHtml();  
    
    
   if(millis()/1000 -Secs > 30 )  
   {  
   Serial.println("Resetting Arrays");  
   Serial.println(Secs);  
   ResetArrays();  
   Secs=millis()/1000;  
   }   
    
    
    
    
   
 }   
   
  //####################################################################################  
  //##################### END OF LOOP #######################################  
  //####################################################################################  
   
   
   
 void setStatus()  
 {  
  if(!err)  
  {  
  Lsts=Status[0]-'0';    
  Csts=Status[2]-'0';   
  Hsts=Status[4]-'0';  
  Fsts=Status[6]-'0';  
  Ssts=Status[8]-'0';  
  DHTerr=Status[10]-'0';  
  RTCerr=Status[11]-'0';  
   
  }  
   
   
 }  
   
   
   
 void sendHtml()  
 {  
   
  WiFiClient client = server.available();  
    
  if (client)   
  {  
   Serial.println("New client");  
   boolean blank_line = true;  
     
   while (client.connected())   
   {  
    if (client.available())   
    {  
     char c = client.read();  
       
     if (c == '\n' && blank_line)   
     {  
      client.println("HTTP/1.1 200 OK");  
      client.println("Content-Type: text/html");  
      client.println("Connection: close");  
      client.println();  
      
         
       
     
      client.println("<!DOCTYPE HTML>");  
      client.println("<html>");  
      client.println("<head><meta http-equiv='refresh' content='5'/></head><body><h1>Esp8266 Serial to Wifi Monitor Ver: 1.0</h1>");  
        
      client.println("<h2>>>>> ---- Time :");  
      client.println(Time);  
      client.println("--<<< >>> ---- Day : ");  
      client.println(Day);   
      client.println("--<<< >>> ---- Date : ");  
      client.println(Date);  
      client.println("-");  
      client.println(Mon);  
      client.println("-");  
      client.println(Year);  
      client.println("---- <<<<<");  
      client.println("</h2>");  
      client.println("<br />");  
   
      client.println("<h2>Temp 1 :");  
      client.println(Temp1);  
      client.println("\260C</h2>");  
       
      client.println("<h2>Temp 2 :");  
      client.println(Temp2);  
      client.println("\260C</h2>");  
       
      client.println("<h2>Humidity :");  
      client.println(Hum);  
      client.println("%</h2>");  
       
      client.println("<br />");  
   
      client.println("<h1>Current States of Switches</h1>");  
    
      client.println("<br />");  
        
      client.println("<h3>LIGHT:>>> ");  
       if(!err)  
       {  
        if(Lsts)  
        {  
        client.println("ON </h3>");  
        }  
        else  
        {  
        client.println("OFF </h3>");  
        }  
       }  
       else  
       {  
        client.println("UNKNOWN </h3>");  
       }  
        
        
        
      client.println("<h3>COOLER:>>>");  
         
         
       if(!err)  
       {   
        if(Csts)  
        {  
        client.println("ON </h3>");  
        }  
        else  
        {  
        client.println("OFF </h3>");   
        }  
       }  
       else  
       {  
       client.println("UNKNOWN </h3>");  
       }  
        
        
        
      client.println("<h3>HEATER:>>>");  
        
       if(!err)  
       {  
        if(Hsts)  
        {  
        client.println("ON </h3>");  
        }  
        else  
        {   
        client.println("OFF </h3>");  
        }  
       }  
       else  
       {  
       client.println("UNKNOWN </h3>");  
       }  
        
        
        
      client.println("<h3>FAN:>>>");  
        
         
       if(!err)  
       {  
        if(Fsts)  
        {  
        client.println("ON </h3>");  
        }  
        else  
        {  
        client.println("OFF </h3>");    
        }  
       }  
       else  
       {  
       client.println("UNKNOWN </h3>");  
       }  
        
        
      client.println("<h3>HUMIDIFIER:>>>");  
         
       if(!err)  
       {  
        if(Ssts)  
        {  
        client.println("ON </h3>");  
        }  
        else  
        {  
        client.println("OFF </h3>");  
        }  
       }  
       else  
       {  
       client.println("UNKNOWN </h3>");  
       }  
        
        
      client.println("<br />");  
   
        
   
         
         
         
      client.println("<h4>DHT Err:>>>");  
       if(!err)  
       {  
        if(DHTerr)  
        {  
        client.println("TRUE </h4>");  
        }  
        else  
        {  
        client.println("FALSE </h4>");   
        }  
       }  
       else  
       {  
       client.println("UNKNOWN </h4>");  
       }  
        
        
        
        
      client.println("<h4>RTC Err:>>>");  
         
       if(!err)  
       {  
        if(RTCerr)  
         {  
         client.println("TRUE </h4>");  
         }  
        else  
        {  
        client.println("FALSE </h4>");   
        }  
       }  
       else  
       {  
       client.println("UNKNOWN </h4>");  
       }  
        
      client.println("<br />");  
   
      client.println("<h4>Serial Read Error:>>>");  
       if(err)  
       {  
       client.println("TRUE ----OH JEEZ </h4>");  
       }  
       else  
       {  
       client.println("FALSE </h4>");  
       }       
        
        
      char LinkOne[]= "https://youtube.com/crazyguyofficial";  
      client.println("<h3><a href=");  
      client.print(LinkOne);  
      client.print(">CHANNEL</a></h3>");  
        
      char LinkTwo[]= "https://amkdiyprojects.blogspot.com";  
      client.println("<h3><a href=");  
      client.print(LinkTwo);  
      client.print(">BLOG</a></h3>");  
        
      client.println("</body></html>");     
      break;  
      
       
     }  
       
        
     if (c == '\n')   
     {  
     blank_line = true;  
     }  
     else if (c != '\r')   
     {  
     blank_line = false;  
     }  
      
      
    }  
   }   
     
     
     
  delay(1);  
  client.stop();  // closing the client connection  
   
  Serial.println("Client disconnected.");  
     
  }  
 }  
   
   
 void ResetArrays()  
 {  
  //Serial.flush();   
  err=1;  
 // data[0]  ='\0';  
  Time[0]  ='\0';             // Character Arrays or C-strings   
  Day    ='\0';             // size should be the total number of Chars to be stored +1 for null char  
  Date[0]  ='\0';  
  Mon[0]  ='\0';  
  Year[0]  ='\0';  
  Status[0] ='\0';  
  Temp1[0] ='\0';  
  Temp2[0] ='\0';  
  Hum[0]  ='\0';  
 }  
   

Home Assistant Basic Sun Automations Sunrise / Sunset Mqtt Lights On / Off

##############################################
## First the Switches in Configuration.yaml file #####
##############################################


###############################################################
# MOSQUITTO MQTT ##########################################
###############################################################

mqtt:
  broker: localhost
  port: 1883
  client_id: home-assistant-1
  keepalive: 60
  username: newuser
  password: 12345
  protocol: 3.1

###############################################################
# SWITCHES ##################################################
###############################################################


switch 1:
  - platform: mqtt
    name: "Wall Light"
    state_topic: "/house/switchConfirm1/"
    command_topic: "/house/switch1/"
    payload_on: "1"
    payload_off: "0"
    qos: 0
    retain: true
#####################

switch 2:
  - platform: mqtt
    name: "Garage Light One"
    state_topic: "/house/switchConfirm2/"
    command_topic: "/house/switch2/"
    payload_on: "1"
    payload_off: "0"
    qos: 0
    retain: true
#####################

switch 3:
  - platform: mqtt
    name: "Garage Light Two"
    state_topic: "/house/switchConfirm3/"
    command_topic: "/house/switch3/"
    payload_on: "1"
    payload_off: "0"
    qos: 0
    retain: true
#####################

switch 4:
  - platform: mqtt
    name: "Garage Light Three"
    state_topic: "/house/switchConfirm4/"
    command_topic: "/house/switch4/"
    payload_on: "1"
    payload_off: "0"
    qos: 0
    retain: true


####################

switch 5:
  - platform: mqtt
    name: "Switch Sleep"
    state_topic: "/house/switchSleepConfirm/"
    command_topic: "/house/switchSleep/"
    payload_on: "1"
    payload_off: "0"
    qos: 0
    retain: true
####################

switch 6:
  - platform: mqtt
    name: "Switch Reset"
    state_topic: "/house/switchResetConfirm/"
    command_topic: "/house/switchReset/"
    payload_on: "1"
    payload_off: "0"
    qos: 0
    retain: true
######################


##########################################################################
##########################################################################


# NOTE : when using "switch " like above the Service "switch.turn_on" will work
# but if you use " light " the "light.turn_on" will work with it 
# for example : if mqtt switches are defined as "light" below:





################################################################
# LIGHTS ######################################################
###############################################################
#light 1:
# - platform: mqtt
#  name: "Light 01"
#    state_topic: "/house/switchConfirm5/"
#    command_topic: "/house/switch5/"
#    payload_on: "1"
#    payload_off: "0"
#    qos: 0
#    retain: true
#####################


####################################################################
# in the " light 1 " example above the  name: "Light 01 " can be changed but 
# the top light 1 is important here as it will change the service name too 
# see at the end of this post 
####################################################################








###########################################
## This is my Automations.yaml file right now ##
###########################################



#############################################################
## TURN ON OUTSIDE LIGHTS AT SUN-SET ###################
############################################################################


## Copy it so that the minus sign before " id:" is on extreme left the rest should be as it is 
## for example the letter "a" in alias should be beneath the letter " i" in id 

############################################################################

- id: auto_one
  alias: 'Turn On Outside Lights at Sunset'
  trigger:
  - platform: sun
    event: sunset
    offset: '+00:17:00'
  action:
  - service: switch.turn_on
    entity_id: switch.garage_light_one
  - delay: 00:02:00
  - service: switch.turn_on
    entity_id: switch.garage_light_two
  - delay: 00:02:00
  - service: switch.turn_on
    entity_id: switch.garage_light_three
  - delay: 00:03:00
  - service: switch.turn_on
    entity_id: switch.wall_light

#############################################################
## TURN OFF OUTSIDE LIGHTS AT SUN-RISE #################
#############################################################

############################################################################
## Note that the dash/minus sign " - " before id is on extreme left with NO spaces from left
############################################################################

- id: auto_two
  alias: 'Turn Off Outside Lights at Sunrise'
  trigger:
  - platform: sun
    event: sunrise
    offset: '-00:25:00'
  action:
  - service: switch.turn_off
    entity_id: switch.wall_light
  - delay: 00:05:00
  - service: switch.turn_off
    entity_id: switch.garage_light_one
  - delay: 00:04:00
  - service: switch.turn_off
    entity_id: switch.garage_light_two
  - delay: 00:03:00
  - service: switch.turn_off
    entity_id: switch.garage_light_three


###########################################################################

###########################################################################
#############################################################
## TURN ON LIGHTS AT SUNSET ###           Using light            #####
#############################################################



#- id: auto
#  alias: 'Turn On Lights'
#  trigger:
#  - platform: sun
#    event: sunset
#    offset: '-02:44:00'
#  action:
#  - service: light.turn_on
#    entity_id: light.light_01
#  - delay: 00:00:05
#  - service: light.turn_on
#    entity_id: light.light_02
#  - delay: 00:00:05
#  - service: light.turn_on
#    entity_id: light.light_03
#  - delay: 00:00:05
#  - service: light.turn_on
#    entity_id: light.light_04


Home Assistant / Hassbian MQTT Switches Using ESP8266 / Arduino IDE v1.0



   
 /* ################################################################  
    ################################################################  
    ########## ESP 8266 MQTT Switch for Home Assistant #############  
    ################################################################  
    ###################*** MOSQUITTO ***############################  
 */  
   
   
   
 //########################################################################################  
   
  // You Can find this sketch on Home Assistant forum i have just modified it according to my 
  // Requirements as it is just a waste of time trying to re-invent the wheel 
  // so thank you for it random citizen :D  
  
  //** INCLUDE LIBRARIES ** make sure you have all the Libraries installed   
  // Get them from within the Arduino IDE Sketch > Include Libraries > Manage Libraries   
   
 //########################################################################################   
   
   
   
 #include <PubSubClient.h>  
 #include <ESP8266WiFi.h>  
 #include <ArduinoOTA.h>  
 #include <ESP8266mDNS.h>  
 #include <WiFiUdp.h>  
   
   
   
 //##################################################################  
   
   
 void callback(char* topic, byte* payload, unsigned int length);  
   
   
   
 #define MQTT_SERVER "192.168.1.3"      // IP of your MQTT Server   
   
   
 const char* ssid = "cool-spot";        // SSID for you Wifi Hotspot  
 const char* password = "12345678";     // Password for Wifi Hotspot   
   
   
 //########### ESP 8266 GPIO Pins ###########################################  
   
   
 const int switchPin1 = 4;  
 const int switchPin2 = 5;  
 const int switchPin3 = 13;  
 const int switchPin4 = 12;  
   
   
 //#########################################################################  
         
         
 // ***** MQTT Topics Defined In Home Assistant's Configuration.yaml file ***  
         
   
 //#########################################################################  
   
 char const* switchTopic1 = "/house/switch1/";      //four switches for relays  
   
 char const* switchTopic2 = "/house/switch2/";  
   
 char const* switchTopic3 = "/house/switch3/";  
   
 char const* switchTopic4 = "/house/switch4/";  
   
   
   
 char const* switchSleep  = "/house/switchSleep/";  // fifth for putting the Esp in sleep mode   
   
 char const* switchReset  = "/house/switchReset/";  // sixth for Reseting the Esp  
   
 //##########################################################################  
   
   
   
 WiFiClient wifiClient;  
   
   
 PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);  
   
   
   
   
   
   
 //#################################################################################  
 //#################################################################################  
   
 //############## SETUP BEGINS #####################################################  
   
 //#################################################################################  
 //#################################################################################  
   
   
   
 void setup() {  
   
        
                                  // These lines will keep the Relays off during start-up    
    
  pinMode(switchPin1, OUTPUT);    // Relay Switch 1    
    
  digitalWrite(switchPin1, LOW);  // Because i'm Using NPN transistors for   
   
                                  // switching the relays which are actually   
                     
                                  // LOW-level-trigger type   
   
                                  // adding the transistor will invert that logic  
   
                                  // and LOW will be OFF because Transistor is off    
                         
    
    
  pinMode(switchPin2, OUTPUT);   // Relay Switch 2  
    
  digitalWrite(switchPin2, LOW);  
   
   
   
  pinMode(switchPin3, OUTPUT);   // Relay Switch 3  
   
  digitalWrite(switchPin3, LOW);  
   
   
   
  pinMode(switchPin4, OUTPUT);   // Relay Switch 4  
   
  digitalWrite(switchPin4, LOW);  
   
   
  //####################################################################################  
   
    
    
    
  Serial.begin(115200);  
  delay(100);  
    
    
   
    
    
    
  WiFi.mode(WIFI_STA);        // Set Esp8266 in Station mode  
   
  WiFi.begin(ssid, password);       
   
    
    
    
    
   while (WiFi.waitForConnectResult() != WL_CONNECTED) {  
    
   Serial.println("Connection Failed! Rebooting...");  
     
   delay(2000);  
          

  }  
   
 //############################################################################################  
 //############################################################################################  
   
 //############# CHANGE OTA UPDATE PASSWORD ###################################################    
 //############################################################################################  
 //############################################################################################  
   
  ArduinoOTA.setPassword((const char *)"123"); // Password for OTA Update "123"  
  ArduinoOTA.begin();                          // on every reset it waits for 60 secs   
                                               // During that time it will accept OTA updates  
  Serial.println("Ready");                     // Turn Firewall off on the PC when trying to   
                                               // Over The Air update sketch  
    
  Serial.print("IP address: ");  
  Serial.println(WiFi.localIP());  
   
   
   
 }  
   
 //##########################################################################################  
   
 //############ SETUP END ###################################################################  
   
 //##########################################################################################   
   
   
  bool ota_update = true ;  // Don't change this manually   
   
   
   
   
   
 //#########################################################################################  
   
 //######### LOOP BEGINS ##################################################################  
   
 //#########################################################################################  
   
   
 void loop()  {  
   
    
    
    
    
   
 //################# WAIT FOR OTA UPDATE ON EVERY START UP #################  
    
   
    
  if(ota_update)                 // on Every Reset ota update boolean will be set to TRUE   
     
  {  
     
     
     
   while(millis()/1000 < 15 ) // then it will count to 60 seconds *******WHEN Reset Switch is Turned ON **********  
                          // it will constantly Reboot and wait for 60 Secs and then after Subscribing Reboots   
   {                      // again  
   
      
     
    ArduinoOTA.handle() ;  // During that time update ota can be done  
      
      
    Serial.println(millis()/1000);  
   
      
    delay(10);  
      
      
   }  
     
     
   Serial.println("Time up");  
   
   ota_update = false ;  // then after time up it will be set to false  
                         // and the rest of the code runs for that instance   
                         // it will happen if the reset switch is then turned off 
     
     
   }  
    
    
    
    
    
 //#########################################################  
    
    
    
    
    
    
    
  if (!client.connected() && WiFi.status() == 3)   
     
   {  
     
    reconnect(); // Reconnect if connection is lost  
      
   }   
   
    
    
    
    
    
  client.loop();  // Maintain MQTT connection  
   
   
  delay(10);      // MUST delay to allow ESP8266 WIFI functions to run  
   
   
 }  
   
   
   
   
   
 void callback(char* topic, byte* payload, unsigned int length) {  
   
    
 String topicStr = topic;   
    
   
    
  Serial.println("Callback update.");  
  Serial.print("Topic: ");  
  Serial.println(topicStr);  
   
    
  //################## Switch 1 ################### COPY THESE BLOCKS FOR MORE SWITCHES ####################   
     
   if (topicStr == "/house/switch1/")   
   {  
   
     
      
    if(payload[0] == '1'){  
      
     digitalWrite(switchPin1, HIGH);  
           
     client.publish("/house/switchConfirm1/", "1");  
     delay(700);  
     }  
   
     
      
    else if (payload[0] == '0'){  
      
     digitalWrite(switchPin1, LOW);  
       
     client.publish("/house/switchConfirm1/", "0");  
       
     }  
      
    }  
      
   
     
      
  //################## Switch 2 #####################################################   
      
      
      
      
      
      
    else if (topicStr == "/house/switch2/")   
    {  
      
     
      
    if(payload[0] == '1'){  
      
     digitalWrite(switchPin2, HIGH);  
       
     client.publish("/house/switchConfirm2/", "1");  
     delay(700);  
      
     }  
       
   
     
     else if (payload[0] == '0'){  
      
     digitalWrite(switchPin2, LOW);  
       
     client.publish("/house/switchConfirm2/", "0");  
       
     }  
       
    }  
      
      
      
  //################## Switch 3 #####################################################   
   
      
      
      
      
      
    else if (topicStr == "/house/switch3/")   
    {  
      
      
      
    if(payload[0] == '1'){  
      
     digitalWrite(switchPin3, HIGH);  
       
     client.publish("/house/switchConfirm3/", "1");  
     delay(700);  
       
     }  
   
      
      
    else if (payload[0] == '0'){  
       
     digitalWrite(switchPin3, LOW);  
       
     client.publish("/house/switchConfirm3/", "0");  
       
     }  
    }  
      
      
      
      
      
 //################## Switch 4 #####################################################   
   
      
      
      
    else if (topicStr == "/house/switch4/")   
    {  
      
      
    if(payload[0] == '1'){  
      
     digitalWrite(switchPin4, HIGH);  
       
     client.publish("/house/switchConfirm4/", "1");  
     delay(700);  
       
     }  
   
      
      
    else if (payload[0] == '0'){  
      
    digitalWrite(switchPin4, LOW);  
      
     client.publish("/house/switchConfirm4/", "0");  
     }  
    }  
   
   
   
   
    
    
    
 //################## Switch 5 Sleep Mode #######################################   
     
   
    
    
    
    
    
  else if (topicStr == "/house/switchSleep/")   
    {  
      
    
    if(payload[0] == '1'){  
   
     client.publish("/house/switchSleepConfirm/", "1");  
   
     Serial.println("going to sleep for 10 secs");  
   
       
     delay(2000);  
          ESP.deepSleep(60*1000000);  
     }  
   
    
      
    else if (payload[0] == '0'){  
      
       
     client.publish("/house/switchSleepConfirm/", "0");  
     }  
    }  
   
   
   
   
 //################## Switch 6 Reset #######################################   
   
   
  else if (topicStr == "/house/switchReset/")   
    {  
      
    
    if(payload[0] == '1'){  
   
     client.publish("/house/switchResetConfirm/", "1");  
   
     Serial.println("going to Reset ");  
   
       
     delay(2000);  
     ESP.deepSleep(5*1000000);  
  
     }  
   
    
      
    else if (payload[0] == '0'){  
      
       
     client.publish("/house/switchResetConfirm/", "0");  
     }  
    }  
   
   
   
   
   
   
   
   
   
   
      
 }  
   
   
 //#########################################################################################  
   
 //######### LOOP ENDS ##################################################################  
   
 //#########################################################################################  
   
   
   
   
   
   
 void reconnect() {  
   
    
    
  if(WiFi.status() != WL_CONNECTED){  
     
   Serial.print("Connecting to ");  
    
   Serial.println(ssid);  
   
     
     
   while (WiFi.status() != WL_CONNECTED) {  
     
    delay(500);  
      
    Serial.print(".");  
     
   }  
   
     
     
   Serial.println("");  
     
   Serial.println("WiFi connected");   
     
   Serial.println("IP address: ");  
     
   Serial.println(WiFi.localIP());  
  }  
   
    
    
    
    
  if(WiFi.status() == WL_CONNECTED){  
    
   while (!client.connected()) {  
    
    Serial.print("Attempting MQTT connection...");  
   
      
      
    // Generate client name based on MAC address and last 8 bits of microsecond counter  
    String clientName;  
    clientName += "esp8266-";  
    uint8_t mac[6];  
    WiFi.macAddress(mac);  
    clientName += macToStr(mac);  
   
       
 //#########################################################################################  
   
 //######### CHANGE MQTT USER NAME AND PASSWORD BELOW ####################################  
   
 //#########################################################################################  
    
      
      
      
    if (client.connect((char*) clientName.c_str(),"newuser", "12345")) {    
      
     Serial.print("\tMQTT Connected");  
       
       
       
       
     client.subscribe(switchReset);        // the order in which topics are arranged here  
   
       
     client.subscribe(switchSleep);        // is how ESP will Subscribe and if you put   
   
                            // relays first and also turn them on and reset or sleep too  
       
                            // the switches will turn on momentarily untill it gets the message to sleep or reset   
       
     client.subscribe(switchTopic1);       // so keep them on the top and then even if the Relay switches are turned on from the page   
       
     client.subscribe(switchTopic2);       // the switch will reset or sleep even before subscribing to the later topics in the list   
       
     client.subscribe(switchTopic3);  
       
     client.subscribe(switchTopic4);  
   
     // ##**************************########  Add MORE TOPICS FOR  SWITCHES HERE   #####################  
       
       
    }  
   
      
    else{Serial.println("\tFailed.");  
      
    delay(2000);  
   //  ESP.deepSleep(5*1000000); 
break;}  
     
   }  
    
  }  
   
 }  
   
   
   
   
   
 String macToStr(const uint8_t* mac){  
   
  String result;  
   
  for (int i = 0; i < 6; ++i) {  
   result += String(mac[i], 16);  
   
   if (i < 5){  
    result += ':';  
   }  
  }  
   
  return result;  
 }