RTC integration with Arduino MEGA

// things to check SD card initialization  if failed power should be diconnected and connected 

//  there should be motor interrupt so that only the one who operated the motor is able to turn it off ... this is done 
// Pull UP resistor for inputs or 10k resistor connected to the groud  ... this is done 


#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>
#include "uptime.h"
#include <Dns.h>

// size of buffer used to capture HTTP requests
#define REQ_BUF_SZ   60
#define RESPONSE_BUF_SZ   15             // the byte size for HTTP/1.1 200 OK 

int trial = 0;
bool true_response = 0;
char HTTP_response[RESPONSE_BUF_SZ];   // buffered HTTP request stored as null terminated string
// MAC address from Ethernet shield sticker under board
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
// IPAddress ip(192, 168, 0, 10); // IP address, may need to change depending on network
//IPAddress ip(10, 0, 0, 10);

// use the numeric IP instead of the name for the server:
// IPAddress IFTTT(34, 236, 248, 94);  // numeric IP for Google (no DNS)
IPAddress IFTTT ;
// char IFTTT[] = "maker.ifttt.com";    // name address for Google (using DNS)


EthernetServer server(80);  // create a server at port 80
EthernetClient client2;
EthernetClient client3;

unsigned long StartTime, StartTimeOwner, StartTimeRenter, EndTime, EndTimeOwner, EndTimeRenter, timetaken, timetakenOwner, timetakenRenter;
unsigned long TotalOwnerTime_Hours, TotalOwnerTime_Minutes, TotalRenterTime_Hours, TotalRenterTime_Minutes, TotalMotorTime_Hours, TotalMotorTime_Minutes;

File webFile;               // the web page file on the SD card
char HTTP_req[REQ_BUF_SZ] = { 0 }; // buffered HTTP request stored as null terminated string
char req_index = 0;              // index into HTTP_req buffer
bool LED_state[2] = { 0 }; // stores the states of the LEDs
int sensorReading = 0;
bool LDR = 0;
bool Interrupt = 0;
bool Motor_state = 0;
bool Renter_state = 0;
bool Mega_State = 1;
bool UNO_State = 0;   // state off for the arduino UNO

// the following diffrentiators are not required internally as only i need to know who turned off the motor externally 
// but in the webpage we are already differentiating who turned the motor on/off
bool ext_Motor_interrupt_Owner = 0;    // this is used for differentiating between who turned off the motor
bool ext_Motor_interrupt_Renter = 0;    // this is used for differentiating between who turned off the motor



//  Mail requirements
int Operator = 0;
int LightOperator = 0;
bool MotorMail = 0;
bool LightMail = 0;
bool lastState_Motor = 0;
bool lastState_Light = 0;

// in switch state 
//  case 0   light off
//  case 1   light ON 
//  case 2   MotorOwnerON
//  case 3   MotorOwnerOFF
//  case 4   MotorRenterON 
//  case 5   MotorRenterOFF


String Date_Time = "" ;
File ExcelSD;

/* ============= Reset-Function ============== */
void(*resetFunc) (void) = 0;   //declare reset function at address 0

void setup()
{
   //    Serial.begin(9600);       // for debugging
     // disable Ethernet chip
    pinMode(10, OUTPUT);
    digitalWrite(10, HIGH);
    pinMode(53, OUTPUT);


    delay(2000);
    SD.begin(4);  // initializing SD card for usage
    delay(2000);

    //  initialize SD card
 //       Serial.println("Initializing SD card...");
 //       if (!SD.begin(4)) {
 //          Serial.println("ERROR - SD card initialization failed!");
 //         return;    // init failed
 //      }
 //      Serial.println("SUCCESS - SD card initialized.");
        // check for index.htm file
 //       if (!SD.exists("webpage.htm")) {
 //           Serial.println("ERROR - Can't find index.htm file!");
 //           return;  // can't find index file
   //    }
 //       Serial.println("SUCCESS - Found index.htm file.");

     // Inputs from motor Owner or Renter state

    pinMode(22, OUTPUT);  // Owner to Operate the motor                         Relay
    pinMode(23, OUTPUT);  // to turn off the motor ......                       Relay 
    pinMode(24, OUTPUT);  // Renter to turn on the motor                        Relay 

    pinMode(25, INPUT_PULLUP);  // for actual state of motor    motor is UP or down         220v Relay
    pinMode(26, INPUT_PULLUP);  // for Owner as operator        if Owner key is closed      220v Relay 
    pinMode(27, INPUT_PULLUP);  // for Renter as operator        if Renter key is closed    220v Relay   

    pinMode(32, OUTPUT); //     for resetting the UNO


//    pinMode(A0, INPUT);
    pinMode(A0, INPUT_PULLUP);

    pinMode(5, OUTPUT);  // Normal LDR relay                                 control normal automatic operation  Relay 
    pinMode(6, OUTPUT);  // to force the light off at night                                                      Relay 
    pinMode(7, OUTPUT);  // used to force light on in the morning                                                Relay 


    pinMode(30, OUTPUT); // LED Testing
    pinMode(31, INPUT); // Arduino UNO Input  
    digitalWrite(32, HIGH);  // for UNO Reset 


    digitalWrite(5, HIGH);
    digitalWrite(6, HIGH);
    digitalWrite(7, HIGH);

    digitalWrite(22, HIGH); // Owner to Operate the motor
    digitalWrite(23, HIGH);  // to turn off the motor 
    digitalWrite(24, HIGH);  // Renter to turn on the motor

    // Ethernet.begin(mac, ip, subnet, gateway);  // initialize Ethernet device
    //       delay(2000);



 //   pinMode(A4, OUTPUT); // sets the digital pin as output
 //   digitalWrite(A4, LOW);
 //   delay(1000); //for ethernet chip to reset
 //   digitalWrite(A4, HIGH);
 //  delay(1000); //for ethernet chip to reset
 //   pinMode(A4, INPUT); // sets the digital pin input
 //   delay(1000); //for ethernet chip to reset

    delay(3000);   // trying to put delay before enabling
    do {
        Ethernet.begin(mac);   // keep loop asking for DHCP
        delay(3000);
    } while (Ethernet.begin(mac) == 0);

    delay(3000);   // trying to put delay before enabling
    //print out the IP address
   //  Serial.print("IP = ");
   //  Serial.println(Ethernet.localIP());

   DNSClient dns;
   dns.begin(Ethernet.dnsServerIP());
   dns.getHostByName("maker.ifttt.com",IFTTT);
    
    
    server.begin();           // start to listen for clients
    
    Operator = 6;
    SendMail();
ExcelSD = SD.open("file.csv", FILE_WRITE);   // if the file opened okay, write to it:
if (ExcelSD) {
  String MegaStart = "MegaStart, MegaStart, MegaStart, MegaStart, MegaStart, MegaStart, MegaStart, MegaStart, MegaStart" ;  
  String WriteSD = MegaStart  ;
  ExcelSD.println(WriteSD);
  // close the file:
  ExcelSD.close();
}
}

void loop()
{
    UNO_State = digitalRead(31);
    LDR_Reading();
    EthernetClient client = server.available();  // try to get client
    if (client) {  // got client?
        boolean currentLineIsBlank = true;
        while (client.connected()) {
            if (client.available()) {   // client data available to read
                char c = client.read(); // read 1 byte (character) from client
                // limit the size of the stored received HTTP request
                // buffer first part of HTTP request in HTTP_req array (string)
                // leave last element in array as 0 to null terminate string (REQ_BUF_SZ - 1)
                if (req_index < (REQ_BUF_SZ - 1)) {
                    HTTP_req[req_index] = c;          // save HTTP request character
                    req_index++;
                }
                // last line of client request is blank and ends with \n
                // respond to client only after last line received
                if (c == '\n' && currentLineIsBlank) {
                    // send a standard http response header
                    client.println("HTTP/1.1 200 OK");
                    // remainder of header follows below, depending on if
                    // web page or XML page is requested
                    // Ajax request - send XML file

                    if (StrContains(HTTP_req, "ajax")) {
                        // send rest of HTTP header
                        client.println("Content-Type: text/xml");
                        client.println("Connection: close");
                        client.println();
                        SetLEDs();
                        // send XML file containing input states
                        XML_response(client);
                    }
                    else if (StrContains(HTTP_req, "motor.jpg")) {

                        webFile = SD.open("motor.jpg");
                        cache_files(client);
                        if (webFile) {
                            while (webFile.available()) {
                                client.write(webFile.read()); // send web page to client
                            }
                            webFile.close();
                        }
                    }
                    else if (StrContains(HTTP_req, "lamp.jpg")) {

                        webFile = SD.open("lamp.jpg");
                        cache_files(client);
                        if (webFile) {
                            while (webFile.available()) {
                                client.write(webFile.read()); // send web page to client
                            }
                            webFile.close();
                        }
                    }
                    else if (StrContains(HTTP_req, "mega.jpg")) {

                        webFile = SD.open("mega.jpg");
                        cache_files(client);
                        if (webFile) {
                            while (webFile.available()) {
                                client.write(webFile.read()); // send web page to client
                            }
                            webFile.close();
                        }
                    }
                    else {  // web page request
                    // send rest of HTTP header
                        client.println("Content-Type: text/html");
                        client.println("Connection: close");
                        client.println();
                        // send web page
                        webFile = SD.open("webpage4.htm");
                        if (webFile) {
                            while (webFile.available()) {
                                client.write(webFile.read()); // send web page to client
                            }
                            webFile.close();
                        }

                    }
                    // display received HTTP request on serial port
                    //         Serial.print(HTTP_req);
                    // reset buffer index and all buffer elements to 0
                    req_index = 0;
                    StrClear(HTTP_req, REQ_BUF_SZ);
                    break;
                }
                // every line of text received from the client ends with \r\n
                if (c == '\n') {
                    // last character on line of received text
                    // starting new line with next character read
                    currentLineIsBlank = true;
                }
                else if (c != '\r') {
                    // a text character was received from client
                    currentLineIsBlank = false;
                }
            } // end if (client.available())
        } // end while (client.connected())
        client.flush();
        delay(10);
        client.stop(); // close the connection
    } // end if (client)
    // check the Input values
    LDR_State_Checker();
    MotorInputState();
     Ethernet.maintain();
}


void LDR_Reading(void)
{

    //   pinMode(A0, INPUT);
      //      sensorReading = analogRead(A0);
    sensorReading = digitalRead(A0);
    //    Serial.println(sensorReading); 
 //   delay(1000);

}
void LDR_State_Checker(void)
{
    //    if ((sensorReading < 100) && (Interrupt == 0)) {
    if ((sensorReading == 0) && (Interrupt == 0)) {              //  ACTIVE LOW "DIGITAL INPUT" IN THIS CASE
        LED_state[0] = 1;
        LDR = 1;
        LightMail = 1;        //  used to trigger mail about light status
        digitalWrite(5, LOW);  // Makes the LED glow in Dark
        digitalWrite(30, HIGH);  // for testing the arduino using LEDs

        if (LightMail != lastState_Light)
        {
            //                 Serial.println();
            //       Serial.println(" triggered 1 Automatic Conrol  ");

            LightOperator = 0;
            Light();
            lastState_Light = LightMail;
        }
        //     delay(1000);
    }
    //    else if ((sensorReading > 300) && (Interrupt == 0)) {
    else if ((sensorReading == 1) && (Interrupt == 0)) {
        LDR = 0;
        LightMail = 0;
        LED_state[0] = 0;

        digitalWrite(5, HIGH);   //Turns the LED OFF in Light.
        digitalWrite(30, LOW);  // for testing the arduino using LEDs

        if (LightMail != lastState_Light)
        {
            //       Serial.println();
           //        Serial.println(" triggered 2 Automatic Conrol  ");
            LightOperator = 1;
            Light();
            lastState_Light = LightMail;
        }
        //    delay(1000);
    }
}

void MotorInputState(void)
{
    bool MotorActualState = digitalRead(25);
    bool MotorInputReadingOwner = digitalRead(26);
    bool MotorInputReadingRenter = digitalRead(27);
    if (MotorInputReadingOwner == 0 && MotorActualState == 0)
    {
        MotorMail = 1;
        LED_state[1] = 1;
        Motor_state = 1;

        if (MotorMail != lastState_Motor)
        {
            StartTimeOwner = millis();
            ext_Motor_interrupt_Owner = 1;
            Operator = 2;
            SendMail();
            lastState_Motor = MotorMail;

        }
    }
    else if (MotorActualState == 1 && (ext_Motor_interrupt_Owner == 1 || Motor_state == 1))    // 1 in ext_motor_interrupt doesnot mean 5 volt from outside it is internal variable
    {
        ext_Motor_interrupt_Owner = 0;
        MotorMail = 0;
        LED_state[1] = 0;
        Motor_state = 0;
        if (MotorMail != lastState_Motor)
        {
            Operator = 3;
            SendMail();
            lastState_Motor = MotorMail;
        }
    }
    else if (MotorInputReadingRenter == 0 && MotorActualState == 0)
    {
        ext_Motor_interrupt_Renter = 1;
        MotorMail = 1;
        Renter_state = 1;

        if (MotorMail != lastState_Motor)
        {
            StartTimeRenter = millis();
            Operator = 4;
            SendMail();
            lastState_Motor = MotorMail;

        }
    }
    else if (MotorActualState == 1 && (ext_Motor_interrupt_Renter == 1 || Renter_state == 1))
    {
        ext_Motor_interrupt_Renter = 0;
        MotorMail = 0;
        Renter_state = 0;
        if (MotorMail != lastState_Motor)
        {
            Operator = 5;
            SendMail();
            lastState_Motor = MotorMail;
        }
    }

}

// checks if received HTTP request is switching on/off LEDs
// also saves the state of the LEDs
void SetLEDs(void)
{
    //  Serial.println();
    //  Serial.println("LDR:");
    // Serial.println(LDR);  
        // LED 1 (pin 6)
    if (StrContains(HTTP_req, "LED1=1") && (LDR == 1)) {
        LED_state[0] = 1;  // save LED state
        digitalWrite(6, HIGH); // will make LDR continue working at night
        Interrupt = 0;
        LightMail = 1;
        if (LightMail != lastState_Light)
        {
            //       Serial.println();
            //       Serial.println(" triggered 1 case of LDR web control  ");
            LightOperator = 0;
            Light();
            lastState_Light = LightMail;
        }
    }
    else if (StrContains(HTTP_req, "LED1=1") && LDR == 0) {
        LED_state[0] = 1;  // save LED state
       // digitalWrite(8, LOW); // will force light to turn up at daylight by admin
        digitalWrite(7, LOW); // will force light to turn up at daylight by admin
        Interrupt = 1;
        LightMail = 1;
        StartTime = millis();
        if (LightMail != lastState_Light)
        {
            //        Serial.println();
           //         Serial.println(" triggered 2 case of LDR web control  ");
            LightOperator = 0;
            Light();
            lastState_Light = LightMail;
        }
    }
    else if (StrContains(HTTP_req, "LED1=0") && LDR == 1) {
        LED_state[0] = 0;  // save LED state
        digitalWrite(6, LOW); // will turn Off the light at night by admin
        Interrupt = 1;
        LightMail = 0;
        //  EndTime = millis();
        if (LightMail != lastState_Light)
        {
            //        Serial.println();
            //        Serial.println(" triggered 3 case of LDR web control  ");
            LightOperator = 1;
            Light();
            lastState_Light = LightMail;
        }
    }
    else if (StrContains(HTTP_req, "LED1=0") && LDR == 0) {
        LED_state[0] = 0;  // save LED state
   //     digitalWrite(8, HIGH);
        digitalWrite(7, HIGH);
        Interrupt = 0;
        LightMail = 0;
        //    EndTime = millis();

        if (LightMail != lastState_Light)
        {
            //       Serial.println();
            //       Serial.println(" triggered 4 case of LDR web control  ");
            LightOperator = 1;
            Light();
            lastState_Light = LightMail;
        }
    }
    // Motor Owner (pin 7)
    else if (StrContains(HTTP_req, "Owner=1") && Motor_state == 0) { // here to control web page to power on motor by contacting relay 3 sec then disconnect it
        LED_state[1] = 1;  // save LED state for revealing this motor state on the webpage
        Motor_state = 1;  // bec the next connection need the actual state of the motor in the program
        MotorMail = 1;
        ext_Motor_interrupt_Owner = 1;
        StartTimeOwner = millis();
        digitalWrite(22, LOW);
        delay(3000);
        digitalWrite(22, HIGH);
        if (MotorMail != lastState_Motor)
        {
            Operator = 2;
            SendMail();
            lastState_Motor = MotorMail;
        }

    }
    else if (StrContains(HTTP_req, "Owner=1") && Motor_state == 1) {
        //      LED_state[1] = 1;  // save LED state
        Motor_state = 1;
    }
    else if (StrContains(HTTP_req, "Owner=0") && Motor_state == 1) {
        LED_state[1] = 0;  // save LED state for revealing this motor state on the webpage
        Motor_state = 0; //  bec the next connection need the actual state of the motor in the program
        MotorMail = 0;
        ext_Motor_interrupt_Owner = 0;

        digitalWrite(23, LOW);
        delay(3000);
        digitalWrite(23, HIGH);
        if (MotorMail != lastState_Motor)
        {
            Operator = 3;
            SendMail();
            lastState_Motor = MotorMail;
        }

    }
    else if (StrContains(HTTP_req, "Owner=0") && Motor_state == 0) {
        //     LED_state[1] = 0;  // save LED state
        Motor_state = 0;
    }

    // Motor Renter (pin ----)
    else if (StrContains(HTTP_req, "Renter=1") && Renter_state == 0) { // here to control web page to power on motor by contacting relay 3 sec then disconnect it
        Renter_state = 1;  // save LED state for revealing this motor state on the webpage
        MotorMail = 1;
        ext_Motor_interrupt_Renter = 1;
        StartTimeRenter = millis();
        digitalWrite(24, LOW);
        delay(3000);
        digitalWrite(24, HIGH);
        if (MotorMail != lastState_Motor)
        {
            Operator = 4;
            SendMail();
            lastState_Motor = MotorMail;
        }


    }
    else if (StrContains(HTTP_req, "Renter=1") && Renter_state == 1) {
        Renter_state = 1;  // save LED state
    }
    else if (StrContains(HTTP_req, "Renter=0") && Renter_state == 1) {
        Renter_state = 0;  // save LED state for revealing this motor state on the webpage
        MotorMail = 0;
        ext_Motor_interrupt_Renter = 0;
        if (MotorMail != lastState_Motor)
        {
            Operator = 5;
            SendMail();
            lastState_Motor = MotorMail;
        }
        digitalWrite(23, LOW);
        delay(3000);
        digitalWrite(23, HIGH);
    }
    else if (StrContains(HTTP_req, "Renter=0") && Renter_state == 0) {
        Renter_state = 0;  // save LED state
    }
    else if (StrContains(HTTP_req, "RestartMega")) {
        resetFunc(); // call reset       
    }
    else if (StrContains(HTTP_req, "RestartUNO")) {
        digitalWrite(32, LOW);
        delay(2000);
        digitalWrite(32, HIGH);
    }
}

// send the XML file with analog values, switch status
//  and LED status
void XML_response(EthernetClient cl)
{
    //   Serial.println("LED_state[1]");
    //  Serial.println(LED_state[1]);
    cl.print("<?xml version=\"1.0\" ?>");
    cl.print("<inputs>");
    // checkbox LED states
    // LED1
    cl.print("<LED>");
    if (LED_state[0] == 1) {
        cl.print("checked");
    }
    else if (LED_state[0] == 0) {
        cl.print("unchecked");
    }
    cl.println("</LED> ");
    // button LED states
    // LED3
    cl.print("<Motor>");
    if (LED_state[1] == 1) {
        cl.print("on");
    }
    else if (LED_state[1] == 0) {
        cl.print("off");
    }
    cl.println("</Motor>");
    cl.print("<Renter>");
    if (Renter_state == 1) {
        cl.print("on");
    }
    else if (Renter_state == 0) {
        cl.print("off");
    }
    cl.println("</Renter>");
    cl.print("<UNO_State1>");
    if (UNO_State == 1) {
        cl.print("on");
    }
    else if (UNO_State == 0) {
        cl.print("off");
    }
    cl.println("</UNO_State1>");

    cl.print("<Mega_State1>");
    if (Mega_State == 1) {
        cl.print("on");
    }
    else if (Mega_State == 0) {
        cl.print("off");
    }
    cl.println("</Mega_State1>");
    cl.print("</inputs>");
}

// sets every element of str to 0 (clears array)
void StrClear(char* str, char length)
{
    for (int i = 0; i < length; i++) {
        str[i] = 0;
    }
}

// searches for the string sfind in the string str
// returns 1 if string found
// returns 0 if string not found
char StrContains(char* str, char* sfind)
{
    char found = 0;
    char index = 0;
    char len;

    len = strlen(str);

    if (strlen(sfind) > len) {
        return 0;
    }
    while (index < len) {
        if (str[index] == sfind[found]) {
            found++;
            if (strlen(sfind) == found) {
                return 1;
            }
        }
        else {
            found = 0;
        }
        index++;
    }

    return 0;
}
void cache_files(EthernetClient cf)
{
    cf.println("Cache-Control: public,max-age=31536000,immutable");
    cf.println("Content-Type: image/jpeg");
    cf.println("Connection: close");
    cf.println();
}

void SendMail()
{
    uptime::calculateUptime();
    int h, m, s, ms;
    int TMT_m, TMT_h, TMT_over, TOT_m, TOT_h, TOT_over, TRT_m, TRT_h, TRT_over;
    unsigned long over;
    unsigned long day = (uptime::getDays());
    unsigned long hour = (uptime::getHours());
    unsigned long minute = (uptime::getMinutes());
    String days = String(day);
    String hours = String(hour);
    String minutes = String(minute);

    switch (Operator) {
    case 2:
    {
        String url = "GET /trigger/Farm/with/key/kqotITniP1OKyJb3SHv44Ebj6XWr3_lILvz75wjMBIg?value1=%22%20Owner%20:%20Motor%20ON%20&value2=%22%20Arduino_Up_Time%20:%20";
        String UpTime = days + "%20days,%20" + hours + "%20hours,%20" + minutes + "%20minutes%20";
        String end_of_request = "%20%22%20 HTTP/1.1";
        String GetRequest = url + UpTime + end_of_request;

        String url_excel = "GET /trigger/MotorTime/with/key/kqotITniP1OKyJb3SHv44Ebj6XWr3_lILvz75wjMBIg?value1=%22%20Owner%20:%20Motor%20ON%20";
        String end_of_request_excel = "%22%20 HTTP/1.1";
        String GetRequest_excel = url_excel + end_of_request_excel;

        client3.stop();
        if (client3.connect(IFTTT, 80)) {

            while(true_response == 0 && trial <= 10)
            {
                client3.println(GetRequest);
                client3.println("Host: maker.ifttt.com");
                client3.println("Connection: close");
                client3.println();
              delay(500);
                if (client3.available())
                {
                    client3.read(HTTP_response, 15);

                    if (StrContains(HTTP_response, "200 OK"))
                    {
                        true_response = 1;
                    } else {
                        true_response = 0;
                        trial++;
                     }
                }
       //         Serial.println("ON_Owner_EXCEL_true_response: ");
      //          Serial.print(true_response);
     //           Serial.println();
            }
            trial = 0;
            true_response = 0;
            StrClear(HTTP_response, RESPONSE_BUF_SZ);
           } else if (!client3.connected()) {
            //    Serial.println();
            //    Serial.println("disconnecting.");
            client3.stop();
             }
            delay(50);
            client3.stop();
           if (client3.connect(IFTTT, 80)) {
            while(true_response == 0 && trial <= 10)
            {
                client3.println(GetRequest_excel);
                client3.println("Host: maker.ifttt.com");
                client3.println("Connection: close");
                client3.println();
                delay(500);
                if (client3.available())
                {
                    client3.read(HTTP_response, 15);

                    if (StrContains(HTTP_response, "200 OK"))
                    {
                        true_response = 1;
                    }
                    else {
                        true_response = 0;
                        trial++;
                    }
                }
      //          Serial.println("ON_Owner_Mail_true_response: ");
    //            Serial.print(true_response);
    //            Serial.println();
            }  
            trial = 0;
            true_response = 0;
            StrClear(HTTP_response, RESPONSE_BUF_SZ);
           } else if (!client3.connected()) {
            //    Serial.println();
            //    Serial.println("disconnecting.");
            client3.stop();
         }
ExcelSD = SD.open("file.csv", FILE_WRITE);   // if the file opened okay, write to it:
if (ExcelSD) {
  String WriteSD = Date_Time + ", " + "Owner" + ", " + "Motor ON " ;
  ExcelSD.println(WriteSD);
  // close the file:
  ExcelSD.close();
}
        break;
    }
    case 3:
    {
        //           Serial.println();
       //   Serial.println("Matched case 3 of Motor Owner");
       //  Serial.print("Motor Owner OFF mail.... ");
        //    SerialDebug1();
        EndTimeOwner = millis();
        timetakenOwner = EndTimeOwner - StartTimeOwner;
        //TotalOwnerTime = TotalOwnerTime + timetakenOwner ;
        //TotalMotorTime = TotalOwnerTime + TotalRenterTime ;

        h = int(timetakenOwner / 3600000);
        over = timetakenOwner % 3600000;
        m = int(over / 60000);
        over = over % 60000;
        s = int(over / 1000);
        ms = over % 1000;

        // TOT_h = int(timetakenOwner/3600000);
        TOT_h = h;
        TotalOwnerTime_Hours = TotalOwnerTime_Hours + TOT_h;
        TOT_over = timetakenOwner % 3600000;
        //  TOT_m= int(TOT_over/60000);
        TOT_m = m;
        TotalOwnerTime_Minutes = TotalOwnerTime_Minutes + TOT_m;

        while (TotalOwnerTime_Minutes >= 60)                                  // migirating min to hours 
        {
            TotalOwnerTime_Hours++;                                             // incrementing hrs vlaue by 1 
            TotalOwnerTime_Minutes = TotalOwnerTime_Minutes - 60;
        }

        TotalMotorTime_Hours = TotalMotorTime_Hours + TOT_h;                // for calculating the total motor time by hours
        TotalMotorTime_Minutes = TotalMotorTime_Minutes + TOT_m;          // for calculating the total motor time by mins

        while (TotalMotorTime_Minutes >= 60)                // migirating min to hours 
        {
            TotalMotorTime_Hours++;       // incrementing vlaue by 1 
            TotalMotorTime_Minutes = TotalMotorTime_Minutes - 60;
        }


        //  Serial.println();
        //  Serial.println();
         // Serial.print("Raw timetakenOwner: ");
         // Serial.println(timetakenOwner);
        //  Serial.print("timetaken : ");
        //  Serial.print(h,0);
         // Serial.print("h ");
         // Serial.print(m,0);
         // Serial.print("m ");
         // Serial.print(s,0);
         // Serial.print("s ");
         // Serial.print(ms,0);
         // Serial.println("ms");
         // Serial.println(); 
        String hh = String(h);
        String mm = String(m);


        String TOT_h0 = String(TotalOwnerTime_Hours);
        String TOT_m0 = String(TotalOwnerTime_Minutes);

        String TMT_h0 = String(TotalMotorTime_Hours);
        String TMT_m0 = String(TotalMotorTime_Minutes);

        String Time = hh + "h" + "%20" + mm + "m" + "%20";
        String TotalOwnerHours = "Total%20Owner%20hours%20:" + TOT_h0 + "h" + "%20" + TOT_m0 + "m" + "%20";
        String TotalTime = "%20||%20Total%20Motor%20hours%20:" + TMT_h0 + "h" + "%20" + TMT_m0 + "m" + "%20||%20";

        String url = "GET /trigger/Farm/with/key/kqotITniP1OKyJb3SHv44Ebj6XWr3_lILvz75wjMBIg?value1=%22%20Owner%20:%20MoTor%20OFF%20%22%20||%20&value2=%22%20Owner-Motor-Time%20:%20";

        String UpTime = "%20Arduino_Up_Time%20:%20" + days + "%20days,%20" + hours + "%20hours,%20" + minutes + "%20minutes%20";  // arduino UpTime

        String API = url + Time + TotalOwnerHours + TotalTime + UpTime + "%20%22%20 HTTP/1.1";

        String url_excel = "GET /trigger/MotorTime/with/key/kqotITniP1OKyJb3SHv44Ebj6XWr3_lILvz75wjMBIg?value1=%22%20Owner_MoTor%20:%20OFF%20%22%20&value2=";
        String value3 = "%20&value3=";
        String API_excel = url_excel + Time + value3 + TotalOwnerHours + TotalTime + UpTime + "%20%22%20 HTTP/1.1";

        client3.stop();
        if (client3.connect(IFTTT, 80)) {
            //       Serial.print("connected to ");
            //       Serial.println(client3.remoteIP());
                   // Make a HTTP request:


            while(true_response == 0 && trial <= 10)
            {
                client3.println(API);
                client3.println("Host: maker.ifttt.com");
                client3.println("Connection: close");
                client3.println();
                delay(500);
                if (client3.available())
                {
                    client3.read(HTTP_response, 15);

                    if (StrContains(HTTP_response, "200 OK"))
                    {
                        true_response = 1;
                    } else {
                        true_response = 0;
                        trial++;
                    }
                }
      //          Serial.println("Off_Owner_Mail_true_response: ");
    //            Serial.print(true_response);
    //            Serial.println();
            }
            trial = 0;
            true_response = 0;
            StrClear(HTTP_response, RESPONSE_BUF_SZ);
            } else if (!client3.connected()) {
            //  Serial.println();
           //   Serial.println("disconnecting.");
            client3.stop();
              }

            delay(50);
            client3.stop();
          if (client3.connect(IFTTT, 80)) {
              while(true_response == 0 && trial <= 10)
              {
                client3.println(API_excel);
                client3.println("Host: maker.ifttt.com");
                client3.println("Connection: close");
                client3.println();
                delay(500);
                if (client3.available())
                {
                    client3.read(HTTP_response, 15);

                    if (StrContains(HTTP_response, "200 OK"))
                    {
                        true_response = 1;
                    } else {
                        true_response = 0;
                        trial++;
                     }
                }
       //         Serial.println("Off_Owner_Excel_true_response: ");
     //           Serial.print(true_response);
       //         Serial.println();

              }
              trial = 0;
              true_response = 0;
              StrClear(HTTP_response, RESPONSE_BUF_SZ);
        } else if (!client3.connected()) {
            //   Serial.println();
            //   Serial.println("disconnecting.");
            client3.stop();
        }

ExcelSD = SD.open("file.csv", FILE_WRITE);   // if the file opened okay, write to it:
if (ExcelSD) {
  String WriteSD = Date_Time + ", " + "Owner" + ", " + "Motor OFF" + ", " + TOT_h0 + " " + TOT_m0 + ", " + TMT_h0 + "h" + " " + TMT_m0 + "m" ;
  ExcelSD.println(WriteSD);
  // close the file:
  ExcelSD.close();
}

        break;
    }
    case 4:
    {
        String UpTime = days + "%20days,%20" + hours + "%20hours,%20" + minutes + "%20minutes%20";
        String end_of_request = "%20%22%20 HTTP/1.1";
        // String url = "GET /trigger/Farm/with/key/kqotITniP1OKyJb3SHv44Ebj6XWr3_lILvz75wjMBIg?value1=%22%20Renter%20:%20Motor%20ON%20||%20&value2=%22%20Arduino_Up_Time%20:%20";
        //   String url = "GET /trigger/Farm/with/key/kqotITniP1OKyJb3SHv44Ebj6XWr3_lILvz75wjMBIg?value1=%22%20Renter%20:%20Motor%20ON%20";    -- 1 st try 
        String url = "GET /trigger/Farm/with/key/kqotITniP1OKyJb3SHv44Ebj6XWr3_lILvz75wjMBIg?value1=%22%20Renter%20:%20Motor%20ON%20&value2=%22%20Arduino_Up_Time%20:%20";  // 2 nd try
        String GetRequest = url + UpTime + end_of_request;

        String url_excel = "GET /trigger/MotorTime/with/key/kqotITniP1OKyJb3SHv44Ebj6XWr3_lILvz75wjMBIg?value1=%22%20Renter%20:%20Motor%20ON%20";
        String end_of_request_excel = "%20%22%20 HTTP/1.1";
        String GetRequest_excel = url_excel + end_of_request_excel;

        client3.stop();                            
       if (client3.connect(IFTTT, 80)) {
            while(true_response == 0 && trial <= 10)
            {
                client3.println(GetRequest);
                client3.println("Host: maker.ifttt.com");
                client3.println("Connection: close");
                client3.println();
                delay(500);
                if (client3.available())
                {
                    client3.read(HTTP_response, 15);

                    if (StrContains(HTTP_response, "200 OK"))
                    {
                        true_response = 1;
                    }
                    else {
                        true_response = 0;
                        trial++;
                    }
                }
      //          Serial.println("ON_Motor_Mail_true_response: ");
    //            Serial.print(true_response);
   //             Serial.println();
             }
            trial = 0;
            true_response = 0;
            StrClear(HTTP_response, RESPONSE_BUF_SZ);
              } else if (!client3.connected()) {
            //    Serial.println();
            //    Serial.println("disconnecting.");
                     client3.stop();
               }

            delay(50);
            client3.stop();
          if (client3.connect(IFTTT, 80)) {
            while(true_response == 0 && trial <= 10)
            {
                client3.println(GetRequest_excel);
                client3.println("Host: maker.ifttt.com");
                client3.println("Connection: close");
                client3.println();
                delay(500);
                if (client3.available())
                {
                    client3.read(HTTP_response, 15);

                    if (StrContains(HTTP_response, "200 OK"))
                    {
                        true_response = 1;
                    } else {
                        true_response = 0;
                        trial++;
                    }
                }
    //            Serial.println("Off_Motor_Excel_true_response: ");
  //              Serial.print(true_response);
  //              Serial.println();
            }
            trial = 0;
            true_response = 0;
            StrClear(HTTP_response, RESPONSE_BUF_SZ);
            } else if (!client3.connected()) {
            //    Serial.println();
            //    Serial.println("disconnecting.");
                 client3.stop();
               }
ExcelSD = SD.open("file.csv", FILE_WRITE);   // if the file opened okay, write to it:
if (ExcelSD) {
  String WriteSD = Date_Time + ", " + "Renter" + ", " + "Motor ON"  ;
  ExcelSD.println(WriteSD);
  // close the file:
  ExcelSD.close();
}

               
        break;
    }
    case 5:
    {
        //       Serial.println();
        //   Serial.println("Matched case 5 of Motor Renter");
       //  Serial.print("Motor Renter OFF mail.... ");
        //    SerialDebug1();

        EndTimeRenter = millis();
        timetakenRenter = EndTimeRenter - StartTimeRenter;

        h = int(timetakenRenter / 3600000);
        over = timetakenRenter % 3600000;
        m = int(over / 60000);
        over = over % 60000;
        s = int(over / 1000);
        ms = over % 1000;

        //  TRT_h = int(timetakenRenter/3600000);
        TRT_h = h;
        TotalRenterTime_Hours = TotalRenterTime_Hours + TRT_h;
        TRT_over = timetakenRenter % 3600000;
        //  TRT_m= int(TRT_over/60000);
        TRT_m = m;
        TotalRenterTime_Minutes = TotalRenterTime_Minutes + TRT_m;

        while (TotalRenterTime_Minutes >= 60)                                  // migirating min to hours 
        {
            TotalRenterTime_Hours++;                                             // incrementing hrs vlaue by 1 
            TotalRenterTime_Minutes = TotalRenterTime_Minutes - 60;
        }


        TotalMotorTime_Hours = TotalMotorTime_Hours + TRT_h;                // for calculating the total motor time by hours
        TotalMotorTime_Minutes = TotalMotorTime_Minutes + TRT_m;          // for calculating the total motor time by mins

        while (TotalMotorTime_Minutes >= 60)                // migirating min to hours 
        {
            TotalMotorTime_Hours++;       // incrementing vlaue by 1 
            TotalMotorTime_Minutes = TotalMotorTime_Minutes - 60;
        }



        //   Serial.println();
        //   Serial.println();
         //  Serial.print("Raw timetakenRenter: ");
         //  Serial.println(timetakenRenter);
         //  Serial.print("timetaken : ");
          // Serial.print(h,0);
          // Serial.print("h ");
         //  Serial.print(m,0);
         //  Serial.print("m ");
         //  Serial.print(s,0);
         //  Serial.print("s ");
         //  Serial.print(ms,0);
          // Serial.println("ms");
          // Serial.println(); 
        String hh = String(h);
        String mm = String(m);

        String TRT_h0 = String(TotalRenterTime_Hours);
        String TRT_m0 = String(TotalRenterTime_Minutes);


        String TMT_h0 = String(TotalMotorTime_Hours);
        String TMT_m0 = String(TotalMotorTime_Minutes);

        String Time = hh + "h" + "%20" + mm + "m" + "%20";
        String TotalRenterHours = "Total%20Renter%20hours%20:" + TRT_h0 + "h" + "%20" + TRT_m0 + "m" + "%20";
        String TotalTime = "Total%20Motor%20hours%20:" + TMT_h0 + "h" + "%20" + TMT_m0 + "m" + "%20";

        String url = "GET /trigger/Farm/with/key/kqotITniP1OKyJb3SHv44Ebj6XWr3_lILvz75wjMBIg?value1=%22%20Renter%20:%20MoTor%20OFF%20%22%20||%20&value2=%22%20Renter-Motor-Time%20:%20";

        String UpTime = "%20||%20Arduino_Up_Time%20:%20" + days + "%20days,%20" + hours + "%20hours,%20" + minutes + "%20minutes%20";

        String API = url + Time + TotalRenterHours + TotalTime + UpTime + "%20%22%20 HTTP/1.1";

        String url_excel = "GET /trigger/MotorTime/with/key/kqotITniP1OKyJb3SHv44Ebj6XWr3_lILvz75wjMBIg?value1=%22%20Renter%20:%20MoTor%20OFF%20%22%20&value2=";
        String value3 = "%20&value3=";
        String API_excel = url_excel + Time + value3 + TotalRenterHours + TotalTime + UpTime + "%20%22%20 HTTP/1.1";

        client3.stop();
          if (client3.connect(IFTTT, 80)) {
            //       Serial.print("connected to ");
           //          Serial.println(client3.remoteIP());
                   // Make a HTTP request:


            //           Serial.println();
            //           Serial.println("Renter TIME in GET");
             //          Serial.println(Time);                
            while(true_response == 0 && trial <= 10)
            {
                client3.println(API);
                client3.println("Host: maker.ifttt.com");
                client3.println("Connection: close");
                client3.println();
                delay(500);
                if (client3.available())
                {
                    client3.read(HTTP_response, 15);

                    if (StrContains(HTTP_response, "200 OK"))
                    {
                        true_response = 1;
                    }
                    else {
                        true_response = 0;
                        trial++;
                    }
                }
      //          Serial.println("SendingMotortMail_true_response: ");
    //            Serial.print(true_response);
  //              Serial.println();
            }
            trial = 0;
            true_response = 0;
            StrClear(HTTP_response, RESPONSE_BUF_SZ);
        } else if (!client3.connected()) {
            //   Serial.println();
             //  Serial.println("disconnecting.");
            client3.stop();
             }

            delay(50);
            client3.stop();
          if (client3.connect(IFTTT, 80)) {
            while(true_response == 0 && trial <= 10)
            {
                client3.println(API_excel);
                client3.println("Host: maker.ifttt.com");
                client3.println("Connection: close");
                client3.println();
                delay(500);
                if (client3.available())
                {
                    client3.read(HTTP_response, 15);

                    if (StrContains(HTTP_response, "200 OK"))
                    {
                        true_response = 1;
                    } else {
                        true_response = 0;
                        trial++;
                    }
                }
    //            Serial.println("OFF_MotorExcel_true_response: ");
   //             Serial.print(true_response);
   //             Serial.println();

            }
            trial = 0;
            true_response = 0;
            StrClear(HTTP_response, RESPONSE_BUF_SZ);
        } else if (!client3.connected()) {
            //   Serial.println();
             //  Serial.println("disconnecting.");
            client3.stop();
        }
ExcelSD = SD.open("file.csv", FILE_WRITE);   // if the file opened okay, write to it:
if (ExcelSD) {
  String WriteSD = Date_Time + ", " + "Renter" + ", " + "Motor OFF" + ", " + TRT_h0 + " " + TRT_m0 + ", " + TMT_h0 + "h" + " " + TMT_m0 + "m" ;
  ExcelSD.println(WriteSD);
  // close the file:
  ExcelSD.close();
  }
        
        break;
    }

    case 6:
    {   client3.stop();
      if (client3.connect(IFTTT, 80)) {
        String Mega = "GET /trigger/MotorTime/with/key/kqotITniP1OKyJb3SHv44Ebj6XWr3_lILvz75wjMBIg?value1=%22%20Arduino_Mega%20:%20%22%20&value2=START";
        String MegaStart = Mega + "%20%22%20 HTTP/1.1";
          while(true_response == 0 && trial <= 10)
         {
            client3.println(MegaStart);
            client3.println("Host: maker.ifttt.com");
            client3.println("Connection: close");
            client3.println();
                delay(500);
            if (client3.available())
            {
                client3.read(HTTP_response, 15);

                if (StrContains(HTTP_response, "200 OK"))
                {
                    true_response = 1;
                } else {
                    true_response = 0;
                    trial++;
                }
            }
  //          Serial.println("MegaStart_true_response: ");
    //        Serial.print(true_response);
 //           Serial.println();
           }
          trial = 0;
          true_response = 0;
          StrClear(HTTP_response, RESPONSE_BUF_SZ);
       } else if (!client3.connected()) {
          //  Serial.println();
         //   Serial.println("disconnecting.");
          client3.stop();
        }

    break;
         }
     }
}
//  void SerialDebug1()
// {
//    Serial.println();
 //   Serial.print("connecting to ");
 //   Serial.print();
 //   Serial.println("...");
//    }

void Light()
{
    uptime::calculateUptime();
    int h, m, s, ms;
    unsigned long over;
    unsigned long day = (uptime::getDays());
    unsigned long hour = (uptime::getHours());
    unsigned long minute = (uptime::getMinutes());
    String days = String(day);
    String hours = String(hour);
    String minutes = String(minute);

    switch (LightOperator) {
    case 0:
    {
        String url = "GET /trigger/Farm/with/key/kqotITniP1OKyJb3SHv44Ebj6XWr3_lILvz75wjMBIg?value1=%22%20Light%20:%20ON%20&value2=%22%20Arduino_Up_Time%20:%20";
        String UpTime = days + "%20days,%20" + hours + "%20hours,%20" + minutes + "%20minutes%20";
        String end_of_request = "%22%20 HTTP/1.1";
        String GetRequest = url + UpTime + end_of_request;

        String url_light = "GET /trigger/light/with/key/kqotITniP1OKyJb3SHv44Ebj6XWr3_lILvz75wjMBIg?value1=%22%20Light%20:%20ON%20&value3=%22%20Arduino_Up_Time%20:%20";
        String end_of_request_light = "%22%20 HTTP/1.1";
        String GetRequest_light = url_light + UpTime + end_of_request_light;

        client2.stop();
        if (client2.connect(IFTTT, 80)) {
            while(true_response == 0 && trial <= 10)
            {
                client2.println(GetRequest);
                client2.println("Host: maker.ifttt.com");
                client2.println("Connection: close");
                client2.println();
                delay(500);
                if (client2.available())
                {
                    client2.read(HTTP_response, 15);

                    if (StrContains(HTTP_response, "200 OK"))
                    {
                        true_response = 1;
                    } else {
                        true_response = 0;
                        trial++;
                    }
                }
    //            Serial.println("ON_LightExcel_true_response: ");
   //             Serial.print(true_response);
  //              Serial.println();

            }
            trial = 0;
            true_response = 0;
            StrClear(HTTP_response, RESPONSE_BUF_SZ);
        } else if (!client2.connected()) {
            //  Serial.println();
           //   Serial.println("disconnecting.");
            client2.stop();
        }
            
            delay(50);
            client2.stop();
         if (client2.connect(IFTTT, 80)) {           
            while(true_response == 0 && trial <= 10)
            {
                client2.println(GetRequest_light);
                client2.println("Host: maker.ifttt.com");
                client2.println("Connection: close");
                client2.println();
                delay(500);
                if (client2.available())
                {
                    client2.read(HTTP_response, 15);

                    if (StrContains(HTTP_response, "200 OK"))
                    {
                        true_response = 1;
                    } else {
                        true_response = 0;
                        trial++;
                    }
                }
     //           Serial.println("ON_LightMail_true_response: ");
  //              Serial.print(true_response);
    //            Serial.println();

            }
            trial = 0;
            true_response = 0;
            StrClear(HTTP_response, RESPONSE_BUF_SZ);
         } else if (!client2.connected()) {
            //   Serial.println();
           //    Serial.println("disconnecting.");
            client2.stop();
             }
            ExcelSD = SD.open("light.csv", FILE_WRITE);   // if the file opened okay, write to it:
            if (ExcelSD) {
               String WriteSD = Date_Time + ", " + "Light-ON" ;
               ExcelSD.println(WriteSD);
               // close the file:
                ExcelSD.close();
             }
             
        break;
    }

    case 1:
    {
        //    Serial.println();
       //   Serial.println("Matched case 1 of light");
      //  Serial.print("Light mail.... ");
      //     SerialDebug1();
        EndTime = millis();
        timetaken = EndTime - StartTime;
        h = int(timetaken / 3600000);
        over = timetaken % 3600000;
        m = int(over / 60000);
        over = over % 60000;
        s = int(over / 1000);
        ms = over % 1000;

        String hh = String(h);
        String mm = String(m);
        String Time = hh + "h" + "%20" + mm + "m" + "%20";


        String url = "GET /trigger/Farm/with/key/kqotITniP1OKyJb3SHv44Ebj6XWr3_lILvz75wjMBIg?value1=%22%20Light%20:%20OFF%20%22%20||%20&value2=%22%20Light-Work-Time%20:%20";
        String UpTime = "%20||%20Andriod_Up_Time%20:%20" + days + "%20days,%20" + hours + "%20hours,%20" + minutes + "%20minutes%20";

        String API = url + Time + UpTime + "%20%22%20 HTTP/1.1";

        String url_light = "GET /trigger/light/with/key/kqotITniP1OKyJb3SHv44Ebj6XWr3_lILvz75wjMBIg?value1=%22%20Light%20:%20OFF%20%22%20&value2=%22%20Light-Work-Time%20:%20";
        String API_light = url_light + Time + "%20%22%20 HTTP/1.1";

        client2.stop();
    if (client2.connect(IFTTT, 80)) {
        while(true_response == 0 && trial <= 10)
        {
            client2.println(API);
            client2.println("Host: maker.ifttt.com");
            client2.println("Connection: close");
            client2.println();
            delay(500);
            if (client2.available())
            {
                client2.read(HTTP_response, 15);

                if (StrContains(HTTP_response, "200 OK"))
                {
                    true_response = 1;
                } else {
                    true_response = 0;
                    trial++;
                }
            }
    //        Serial.println("WritingLightExcel_true_response: ");
   //         Serial.print(true_response);
  //          Serial.println();

        }
        trial = 0;
        true_response = 0;
        StrClear(HTTP_response, RESPONSE_BUF_SZ);

      } else if (!client2.connected()) {
        //  Serial.println();
       //   Serial.println("disconnecting.");
        client2.stop();
       }
            delay(50);
            client2.stop();
           if (client2.connect(IFTTT, 80)) {
               while(true_response == 0 && trial <= 10)
              {
                client2.println(API_light);
                client2.println("Host: maker.ifttt.com");
                client2.println("Connection: close");
                client2.println();
               delay(500);
                 if (client2.available())
                 {
                    client2.read(HTTP_response, 15);

                    if (StrContains(HTTP_response, "200 OK"))
                    {
                        true_response = 1;
                    } else {
                        true_response = 0;
                        trial++;
                         }
                 }
    //            Serial.println("SendingLightMail_true_response: ");
   //             Serial.print(true_response);
   //             Serial.println();

                }
                trial = 0;
                true_response = 0;
                StrClear(HTTP_response, RESPONSE_BUF_SZ);
        } else if (!client2.connected()) {
            //  Serial.println();
           //   Serial.println("disconnecting.");
            client2.stop();
        }
      ExcelSD = SD.open("light.csv", FILE_WRITE);   // if the file opened okay, write to it:
      if (ExcelSD) {
       String WriteSD = Date_Time + ", " + "Light-OFF" + ", " + hh + ", " + mm ;
       ExcelSD.println(WriteSD);
       // close the file:
        ExcelSD.close();
        }  
        
        break;
    }
    }
}