Applying AJax to my code

Hello Everyone,

Newbie here. I would like to ask for any help or advice on how to apply Ajax to my codes without creating another html file? i would like to apply an auto refresh to my temperature readings(temp), my battery reardings(in_voltage) and the states of the buttons. ive read that Ajax can do it. Im just wondering how can i apply Ajax to my codes without making major revisions, if possible. Seeking your help how to apply Ajax to my codes.

//For ethernet
#include <SPI.h>
#include <Ethernet.h>
//For relay
#include <Wire.h>
#include <Relay.h>
//For Temp
#include <OneWire.h>
#include <DallasTemperature.h>
//For GSM
#include <SoftwareSerial.h>

#include <EEPROM.h>


//For GSM---------------------------------------------------------------------------------
SoftwareSerial mySerial(2, 3);
char Rx_data[150];
unsigned char Rx_index = 0; 
int i = 0;
char msg[160];
int sig;

#define DEBUG true

//-----------------------------------------------------------------------------------------
int passFlag = 0;
int passFlag1 = 0;
int passFlag2 = 0;
int passFlag3 = 0;
//Millis timeout---------------------------------------------------------------------------

//-----------------------------------------------------------------------------------------

//Batt pin---------------------------------------------------------------------------------
#define SIGNAL_PIN A0   //battery level monitoring using 4.7K & 2.2K ohm resistor
//-----------------------------------------------------------------------------------------


//Temp Pin---------------------------------------------------------------------------------
#define ONE_WIRE_BUS 4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
float temp;
//-----------------------------------------------------------------------------------------


//Batt computation-------------------------------------------------------------------------
float adc_voltage = 0.0;
float in_voltage = 0.0;
float R1 = 30000.0;
float R2 = 7500.0;
float ref_voltage = 5.0;
int adc_value = 0;
//-----------------------------------------------------------------------------------------


//Ethernet---------------------------------------------------------------------------------
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,18, 12);

// Initialize the Ethernet server library
// with the IP address and port you want to use 
// (port 80 is default for HTTP):
EthernetServer server(80);
//-----------------------------------------------------------------------------------------

// Relay state and pin---------------------------------------------------------------------
String relay1State1 = "ON";
String relay2State2 = "ON";
const int  TempCon= 6;
const int ChgRlyCon = 7;

//-----------------------------------------------------------------------------------------


// Client variables------------------------------------------------------------------------ 
char linebuf[160];
int charcount=0;
boolean authentificated=false;
//-----------------------------------------------------------------------------------------

void dashboardPage(EthernetClient &client) {
  client.println(F("HTTP/1.1 200 OK"));
  client.println(F("Content-Type: text/html"));
  client.println(F("Connnection: close"));
  client.println();
  client.println(F("<!DOCTYPE HTML><html><style>body {background-image: url(\"https://geloautomationworks.files.wordpress.com/2023/08/bb1.jpg\");  background-size: 100vw 100vh; background-repeat: no-repeat;  text-align: center; font-family: \"Trebuchet MS\", Arial;}</style>"));
  client.println(F("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"></head>"));
  client.println(F("<h3>SERVER TEMPERATURE</a></h3>"));
  client.println(F("<br>"));
  client.println(F("<p><meta http-equiv=\"refresh\" content=\"2\">"));
  client.println(temp);
  client.println(F("</p>"));
  client.println(F("</br>"));
  // Generates buttons to control the relay 
  client.println(F("<br>"));
  if(relay1State1 == "ON"){
  client.println(F("Aircon is <font color=’green’>ON</font>"));
  }
  else {
  client.println(F("Aircon is <font color=’black’>OFF</font>"));
  }
  client.println(F("</br>"));  
  client.println(F("<a href=\"/ACON\"><button>ON</button></a>&nbsp;&nbsp"));  
  client.println(F("<a href=\"/ACOFF\"><button>OFF</button></a>"));
  client.println(F("<h3>SERVER BATTERY LEVEL</h3>"));
  client.println(F("<br>"));
  client.println(in_voltage);
  client.println(F("</br>"));
  // Generates buttons to control the relay  
  client.println(F("<br>"));
  if(relay2State2 == "ON"){
  client.println(F("Battery is <font color=’green’>CHARGING</font>"));
  }
  else {
  client.println(F("Battery is <font color='black’>NOT CHARGING</font>"));
  }
  client.println(F("</br>"));  
  client.println(F("<a href=\"/DCON\"><button>ON</button></a>&nbsp;&nbsp"));
  client.println(F("<a href=\"/DCOFF\"><button>OFF</button></a></center>"));
  client.println(F("</body></html>")); 
}

void SendAuthentificationpage(EthernetClient &client)
{
  client.println(F("HTTP/1.1 401 Authorization Required"));
  client.println(F("WWW-Authenticate: Basic realm=\"Secure Area\""));
  client.println(F("Content-Type: text/html"));
  client.println("Connnection: close");
  client.println();
  client.println(F("<!DOCTYPE HTML>"));
  client.println(F("<HTML>  <HEAD>   <TITLE>Error</TITLE>"));
  client.println(F(" </HEAD> <BODY><H1>401 Unauthorized.</H1></BODY> </HTML>"));
}



void setup()
{
  // For GSM
  Serial.begin(9600);
  mySerial.begin(19200);


  //---------------------------------------------------------------------------------------

  //For ethernet
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
  //---------------------------------------------------------------------------------------

  //For relay pins
  pinMode(ChgRlyCon, OUTPUT);
  digitalWrite(ChgRlyCon, HIGH);
  pinMode(TempCon, OUTPUT);
  digitalWrite(TempCon, HIGH);
  //---------------------------------------------------------------------------------------


}


//-------------------------------------------------------------------------------------------

void loop() {
  
//----GSM------------------------------------------------------------------------------------  
   if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
  // listen for incoming clients
//------------------------------------------------------------------------------------------  
  
//----TEMP SENSOR---------------------------------------------------------------------------  
  sensors.requestTemperatures(); // Send the command to get temperatures
  temp = sensors.getTempCByIndex(0);
  sensors.requestTemperatures(); // Send the command to get temperatures
  temp = sensors.getTempCByIndex(0);
//------------------------------------------------------------------------------------------  
  
  
//----BATT SENSOR---------------------------------------------------------------------------
// Why "byIndex"? 
  // You can have more than one IC on the same bus. 
  // 0 refers to the first IC on the wire
  // Read the Analog Input
  adc_value = analogRead(SIGNAL_PIN);

  // Determine voltage at ADC input
  adc_voltage  = (adc_value * ref_voltage) / 1024.0;

  // Calculate voltage at divider input
  in_voltage = adc_voltage / (R2 / (R1 + R2)) ;
//------------------------------------------------------------------------------------------


//----BASIC AUTHENTICATION------------------------------------------------------------------
 // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    memset(linebuf, 0, sizeof(linebuf));
    charcount = 0;
    authentificated = false;
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        linebuf[charcount] = c;
        if (charcount < sizeof(linebuf) - 1) charcount++;
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the HTTP request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // decide what to do
          if (strstr(linebuf, "Authorization: Basic") > 0 && strstr(linebuf, "YWRtaW46RGF5d2Fsa2VyQDAwMg==") > 0)
            authentificated = true;
           
            if (authentificated) {
            dashboardPage(client);

          if (strstr(linebuf, "GET /ACON") > 0 && authentificated) {
            digitalWrite(TempCon, HIGH);
            relay1State1="ON";
            init_GSM();
            send_msg("***********", "AC HAS BEEN TURNED ON BY ADMIN");
          }

          else if (strstr(linebuf, "GET /ACOFF") > 0 && authentificated) {
            digitalWrite(TempCon, LOW);
            relay1State1="OFF";
            init_GSM();
            send_msg("***********", "AC HAS BEEN TURNED OFF BY ADMIN");
          }

          else if (strstr(linebuf, "GET /DCON") > 0 && authentificated) {
            digitalWrite(ChgRlyCon, HIGH);
            relay2State2="ON";
            init_GSM();
            send_msg("***********", "CHARGING THE BATTERY HAS BEEN CONNECTED BY ADMIN");
          }

          else if (strstr(linebuf, "GET /DCOFF") > 0 && authentificated) {
            digitalWrite(ChgRlyCon, LOW);
            relay2State2="OFF";
            init_GSM();
            send_msg("***********", "CHARGING THE BATTERY HAS BEEN DISCONNECTED BY ADMIN");
          }
          }
          
          else {
            SendAuthentificationpage(client);
          }

          break;

        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
//------------------------------------------------------------------------------------------

//----TEMP CONDITION------------------------------------------------------------------------ 
  if( temp >= 35){
    digitalWrite(TempCon, HIGH);
    relay1State1 = "ON";
    if(passFlag == 0){
      init_GSM();
      send_msg("***********", "AIRCON HAS BEEN TURNED ON");
      passFlag = 1;
      passFlag1 = 0;
    }
  }
  if (temp <= 14){
    digitalWrite(TempCon, LOW);
    relay1State1 = "OFF";
    if(passFlag1 == 0){
      init_GSM();
      send_msg("***********", "AIRCON HAS BEEN TURNED OFF");
      passFlag1 = 1;
      passFlag = 0;
    } 
//------------------------------------------------------------------------------------------


//----BATT CONDITION------------------------------------------------------------------------
  //--------------------------- bms 0, batt lt 13.4v--------------
  if(in_voltage >= 15){
    digitalWrite(ChgRlyCon, LOW);
    relay2State2 = "OFF";
    if(passFlag2 == 0){
      init_GSM();
      send_msg("***********", "CHARGING THE BATTERY HAS BEEN DISCONNECTED");
      passFlag2 = 1;
      passFlag3 = 0;
    }
  }
  //--------------------------- bms 0, batt is charged at 13.4V -------
  if(in_voltage <= 6){
    digitalWrite(ChgRlyCon, HIGH);
    relay2State2 = "ON";
    if(passFlag3 == 0){
      init_GSM();
      send_msg("***********", "CHARGING THE BATTERY HAS BEEN CONNECTED");
      passFlag3 = 1;
      passFlag2 = 0;
    }
  }
 }
//------------------------------------------------------------------------------------------
}


//---------------------------------------------------------------------------------------------- 


//---SEND GSM STRING----

void send_msg(char *number, char *msg)
{
  char at_cmgs_cmd[30] = {
    '\0'  };
  char msg1[160] = {
    '\0'  };
  char ctl_z = 0x1A;

  sprintf(msg1, "%s%c", msg, ctl_z);
  sprintf(at_cmgs_cmd, "AT+CMGS=\"%s\"\r\n",number);

  sendGSM(at_cmgs_cmd);
  delay(100);
  delay(100);
  delay(100);
  sendGSM(msg1);
  delay(100);
}

void sendGSM(char *string){
  mySerial.write(string);
  delay(90);
}

void clearString(char *strArray) {
  int j;
  for (j = 100; j > 0; j--)
    strArray[j] = 0x00;
}

void send_cmd(char *at_cmd, char clr){
  char *stat = '\0';
  while(!stat){
    sendGSM(at_cmd);
    delay(200);
    readSerialString(Rx_data);
    Serial.write(Rx_data);

    stat = strstr(Rx_data, "OK");
    Serial.println("Success");
    delay(50000);
  }
  if (clr){
    clearString(Rx_data);
    delay(200);
    stat = '\0';
  }
}

void init_GSM(){


  sendData("AT\r\n",1000,DEBUG); // AT

  sendData("AT+CMGF=1\r\n",1000,DEBUG); //AT+CMGF=1
  sendData("AT+CMGD=1\r\n",1000,DEBUG); //AT+CMGD=1

  delay(1000);
  delay(1000);
  delay(1000);
}

void readSerialString (char *strArray) {

  if(!mySerial.available()) {
    return;
  }

  while(mySerial.available()) {
    strArray[i] = mySerial.read();
    i++;
  }
}

String sendData(String command, const int timeout, boolean debug)
{
  String response = "";

  mySerial.print(command); 

  long int time = millis();

  while( (time+timeout) > millis())
  {
    while(mySerial.available())
    {


      char c = mySerial.read();
      response+=c;
    }  
  }

  if(debug)
  {
    Serial.print(response);
  }

  return response;
}





Thank you.

Hello gelorivera0214

I assume that you have written the programme by yourself, then it is quite easy to find the error:

There's a trick to figuring out why something isn't working:

Use a logic analyzer to see what happens.
Put Serial.print statements at various places in the code to see the values of variables and determine whether they meet your expectations.

Have a nice day and enjoy coding in C++.

you'll have to modify the html to

  • modify the sections that will need update so that they have a ID in the DOM
  • include javascript stuff to trigger an update every n second
  • this update triggers a function that triggers an XMLHttpRequest, get some data back in a format you'll have to define and update the DOM with the response.

you'll have to modify the C++ code to

  • identify that you got a GET from the XMLHttpRequest
  • build an answer in the right format and send it back

I've a tutorial in French for an ESP8266 that walks through those steps. Using google translate you can probably get the main part and see how this is managed in code

Hello Guys,

Apologies for the late reply. Im currently studying Ajax and to be honest, it will take me a long time to understand it and how to implement it as i dont have any background on javascript. Ill do my best to figure this out and how to implement it and ill update you as soon as i can.

thanks again for your inputs.

Hello @J-M-L ,

Im starting to play and work with Ajax. However, im lost and i can think what's wrong with my code. I manage to display the temperature dynamically but it duplicates the content of the webpage when ajax is implemented. Can you guide me what's my mistake?

My codes:

//For ethernet
#include <SPI.h>
#include <Ethernet.h>
//For relay
#include <Wire.h>
#include <Relay.h>
//For Temp
#include <OneWire.h>
#include <DallasTemperature.h>
//For GSM
#include <SoftwareSerial.h>

#include <EEPROM.h>


//For GSM---------------------------------------------------------------------------------
SoftwareSerial mySerial(2, 3);
char Rx_data[150];
unsigned char Rx_index = 0; 
int i = 0;
char msg[160];
int sig;

#define DEBUG true

//-----------------------------------------------------------------------------------------
int passFlag = 0;
int passFlag1 = 0;
int passFlag2 = 0;
int passFlag3 = 0;
//Millis timeout---------------------------------------------------------------------------

//-----------------------------------------------------------------------------------------

//Batt pin---------------------------------------------------------------------------------
#define SIGNAL_PIN A0   //battery level monitoring using 4.7K & 2.2K ohm resistor
//-----------------------------------------------------------------------------------------


//Temp Pin---------------------------------------------------------------------------------
#define ONE_WIRE_BUS 4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
float temp;
//-----------------------------------------------------------------------------------------


//Batt computation-------------------------------------------------------------------------
float adc_voltage = 0.0;
float in_voltage = 0.0;
float R1 = 30000.0;
float R2 = 7500.0;
float ref_voltage = 5.0;
int adc_value = 0;
//-----------------------------------------------------------------------------------------


//Ethernet---------------------------------------------------------------------------------
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,18, 12);

// Initialize the Ethernet server library
// with the IP address and port you want to use 
// (port 80 is default for HTTP):
EthernetServer server(80);

//-----------------------------------------------------------------------------------------

// Relay state and pin---------------------------------------------------------------------
String relay1State1 = "ON";
String relay2State2 = "ON";
const int  TempCon= 6;
const int ChgRlyCon = 7;

//-----------------------------------------------------------------------------------------


// Client variables------------------------------------------------------------------------ 
char linebuf[160];
int charcount=0;
boolean authentificated=false;
//-----------------------------------------------------------------------------------------

void dashboardPage(EthernetClient &client) {
  client.println(F("HTTP/1.1 200 OK")); 
  client.println(F("Content-Type: text/html"));
  client.println(F("Connnection: close"));
  client.println();
  client.println(F("<!DOCTYPE HTML><html>"));
  client.println(F("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"));
  client.println(F("<script>"));
  client.println(F("setInterval(function()"));
  client.println(F("{"));
  client.println(F("getReadingsVals();"));
  client.println(F("}, 2000);"));
  client.println(F("function getReadingsVals()"));
  client.println(F("{"));
  client.println(F("var ReadingsRequest = new XMLHttpRequest();"));
  client.println(F("ReadingsRequest.onreadystatechange = function()"));
  client.println(F("{"));
  client.println(F("if(this.readyState == 4 && this.status == 200)"));
  client.println(F("{"));
  client.println(F("document.getElementById(\"ReadingsVals\").innerHTML = this.responseText;"));
  client.println(F("}"));
  client.println(F("};"));
  client.println(F("ReadingsRequest.open(\"GET\", \"readReadings\", true);"));
  client.println(F("ReadingsRequest.send();"));
  client.println(F("}"));
  client.println(F("</script>"));
  client.println(F("</head>"));
  client.println(F("<style>body {background-image: url(\"https://geloautomationworks.files.wordpress.com/2023/08/bb1.jpg\");  background-size: 100vw 100vh; background-repeat: no-repeat;  text-align: center; font-family: \"Trebuchet MS\", Arial;}</style>"));
  client.println(F("<div id=\"time\">"));
  client.println(F("</div>"));
  client.println(F("<center><a href=\"/\">Refresh</a>"));
  client.println(F("<h3>SERVER TEMPERATURE</a></h3>"));
  client.println(F("<br>"));
  client.println(F("<span id=\"ReadingsVals\">"));
  client.println(F("</span>"));
  client.println(F("</br>"));
 // Generates buttons to control the relay 
  client.println(F("<br>"));
  if(relay1State1 == "ON"){
  client.println(F("Aircon is <font color=\"green\">ON</font>"));
  }
  else if (relay1State1 == "OFF") {
  client.println(F("Aircon is <font color=\"red\">OFF</font>"));
  }
  client.println(F("</br>"));  
  client.println(F("<a href=\"/ACON\"><button>ON</button></a>&nbsp;&nbsp"));  
  client.println(F("<a href=\"/ACOFF\"><button>OFF</button></a>"));
  client.println(F("<h3>SERVER BATTERY LEVEL</h3>"));
  client.println(F("<br>"));
  client.println(in_voltage);
  client.println(F("</br>"));
  // Generates buttons to control the relay  
  client.println(F("<br>"));
  if(relay2State2 == "ON"){
  client.println(F("Battery is <font color=\"green\"’>CHARGING</font>"));
  }
  else if (relay2State2 == "OFF") {
  client.println(F("Battery is <font color=\"red\">NOT CHARGING</font>"));
  }
  client.println(F("</br>"));  
  client.println(F("<a href=\"/DCON\"><button>ON</button></a>&nbsp;&nbsp"));
  client.println(F("<a href=\"/DCOFF\"><button>OFF</button></a></center>"));
  client.println(F("</body></html>")); 
  
}

void SendAuthentificationpage(EthernetClient &client)
{
  client.println(F("HTTP/1.1 401 Authorization Required"));
  client.println(F("WWW-Authenticate: Basic realm=\"Secure Area\""));
  client.println(F("Content-Type: text/html"));
  client.println("Connnection: close");
  client.println();
  client.println(F("<!DOCTYPE HTML>"));
  client.println(F("<HTML>  <HEAD>   <TITLE>Error</TITLE>"));
  client.println(F(" </HEAD> <BODY><H1>401 Unauthorized.</H1></BODY> </HTML>"));
}

void AJAX_request(EthernetClient  client)
{
client.println(temp);
client.println(F("°C"));
}

void setup()
{
  // For GSM
  Serial.begin(9600);
  mySerial.begin(19200);


  //---------------------------------------------------------------------------------------

  //For ethernet
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
  //---------------------------------------------------------------------------------------

  //For relay pins
  pinMode(ChgRlyCon, OUTPUT);
  digitalWrite(ChgRlyCon, HIGH);
  pinMode(TempCon, OUTPUT);
  digitalWrite(TempCon, HIGH);
  //---------------------------------------------------------------------------------------


}


//-------------------------------------------------------------------------------------------

void loop() {
  
//----GSM------------------------------------------------------------------------------------  
   if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
  // listen for incoming clients
//------------------------------------------------------------------------------------------  
  
//----TEMP SENSOR---------------------------------------------------------------------------  
  sensors.requestTemperatures(); // Send the command to get temperatures
  temp = sensors.getTempCByIndex(0);
  sensors.requestTemperatures(); // Send the command to get temperatures
  temp = sensors.getTempCByIndex(0);
//------------------------------------------------------------------------------------------  
  
  
//----BATT SENSOR---------------------------------------------------------------------------
// Why "byIndex"? 
  // You can have more than one IC on the same bus. 
  // 0 refers to the first IC on the wire
  // Read the Analog Input
  adc_value = analogRead(SIGNAL_PIN);

  // Determine voltage at ADC input
  adc_voltage  = (adc_value * ref_voltage) / 1024.0;

  // Calculate voltage at divider input
  in_voltage = adc_voltage / (R2 / (R1 + R2)) ;
//------------------------------------------------------------------------------------------


//----BASIC AUTHENTICATION------------------------------------------------------------------
 // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    memset(linebuf, 0, sizeof(linebuf));
    charcount = 0;
    authentificated = false;
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        linebuf[charcount] = c;
        if (charcount < sizeof(linebuf) - 1) charcount++;
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the HTTP request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // decide what to do
          
          
          if (strstr(linebuf, "Authorization: Basic") > 0 && strstr(linebuf, "YWRtaW46RGF5d2Fsa2VyQDAwMg==") > 0)
            authentificated = true;
            
           
            if (authentificated) {
            dashboardPage(client);
            
           if (strstr(linebuf, "readReadings") > 0 && authentificated) {
             AJAX_request(client);
          }
            
          
          else if (strstr(linebuf, "GET /ACON") > 0 && authentificated) {
            digitalWrite(TempCon, HIGH);
            relay1State1="ON";
            init_GSM();
            send_msg("***********", "AC HAS BEEN TURNED ON BY ADMIN");
          }

          else if (strstr(linebuf, "GET /ACOFF") > 0 && authentificated) {
            digitalWrite(TempCon, LOW);
            relay1State1="OFF";
            init_GSM();
            send_msg("***********", "AC HAS BEEN TURNED OFF BY ADMIN");
          }

          else if (strstr(linebuf, "GET /DCON") > 0 && authentificated) {
            digitalWrite(ChgRlyCon, HIGH);
            relay2State2="ON";
            init_GSM();
            send_msg("***********", "CHARGING THE BATTERY HAS BEEN CONNECTED BY ADMIN");
          }

          else if (strstr(linebuf, "GET /DCOFF") > 0 && authentificated) {
            digitalWrite(ChgRlyCon, LOW);
            relay2State2="OFF";
            init_GSM();
            send_msg("***********", "CHARGING THE BATTERY HAS BEEN DISCONNECTED BY ADMIN");
          }
          }
          
          else {
            SendAuthentificationpage(client);
          }
          
          break;
          
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
//------------------------------------------------------------------------------------------

//----TEMP CONDITION------------------------------------------------------------------------ 
  if( temp >= 35){
    digitalWrite(TempCon, HIGH);
    relay1State1 = "ON";
    if(passFlag == 0){
      init_GSM();
      send_msg("***********", "AIRCON HAS BEEN TURNED ON");
      passFlag = 1;
      passFlag1 = 0;
    }
  }
  if (temp <= 14){
    digitalWrite(TempCon, LOW);
    relay1State1 = "OFF";
    if(passFlag1 == 0){
      init_GSM();
      send_msg("***********", "AIRCON HAS BEEN TURNED OFF");
      passFlag1 = 1;
      passFlag = 0;
    } 
//------------------------------------------------------------------------------------------


//----BATT CONDITION------------------------------------------------------------------------
  //--------------------------- bms 0, batt lt 13.4v--------------
  if(in_voltage >= 15){
    digitalWrite(ChgRlyCon, LOW);
    relay2State2 = "OFF";
    if(passFlag2 == 0){
      init_GSM();
      send_msg("***********", "CHARGING THE BATTERY HAS BEEN DISCONNECTED");
      passFlag2 = 1;
      passFlag3 = 0;
    }
  }
  //--------------------------- bms 0, batt is charged at 13.4V -------
  if(in_voltage <= 6){
    digitalWrite(ChgRlyCon, HIGH);
    relay2State2 = "ON";
    if(passFlag3 == 0){
      init_GSM();
      send_msg("***********", "CHARGING THE BATTERY HAS BEEN CONNECTED");
      passFlag3 = 1;
      passFlag2 = 0;
    }
  }
 }
//------------------------------------------------------------------------------------------
}


//---------------------------------------------------------------------------------------------- 


//---SEND GSM STRING----

void send_msg(char *number, char *msg)
{
  char at_cmgs_cmd[30] = {
    '\0'  };
  char msg1[160] = {
    '\0'  };
  char ctl_z = 0x1A;

  sprintf(msg1, "%s%c", msg, ctl_z);
  sprintf(at_cmgs_cmd, "AT+CMGS=\"%s\"\r\n",number);

  sendGSM(at_cmgs_cmd);
  delay(100);
  delay(100);
  delay(100);
  sendGSM(msg1);
  delay(100);
}

void sendGSM(char *string){
  mySerial.write(string);
  delay(90);
}

void clearString(char *strArray) {
  int j;
  for (j = 100; j > 0; j--)
    strArray[j] = 0x00;
}

void send_cmd(char *at_cmd, char clr){
  char *stat = '\0';
  while(!stat){
    sendGSM(at_cmd);
    delay(200);
    readSerialString(Rx_data);
    Serial.write(Rx_data);

    stat = strstr(Rx_data, "OK");
    Serial.println("Success");
    delay(50000);
  }
  if (clr){
    clearString(Rx_data);
    delay(200);
    stat = '\0';
  }
}

void init_GSM(){


  sendData("AT\r\n",1000,DEBUG); // AT

  sendData("AT+CMGF=1\r\n",1000,DEBUG); //AT+CMGF=1
  sendData("AT+CMGD=1\r\n",1000,DEBUG); //AT+CMGD=1

  delay(1000);
  delay(1000);
  delay(1000);
}

void readSerialString (char *strArray) {

  if(!mySerial.available()) {
    return;
  }

  while(mySerial.available()) {
    strArray[i] = mySerial.read();
    i++;
  }
}

String sendData(String command, const int timeout, boolean debug)
{
  String response = "";

  mySerial.print(command); 

  long int time = millis();

  while( (time+timeout) > millis())
  {
    while(mySerial.available())
    {


      char c = mySerial.read();
      response+=c;
    }  
  }

  if(debug)
  {
    Serial.print(response);
  }

  return response;
}

My page when ajax is implemented:

Without ajax:
1 new

Thank you!

your span is defined as this

      <span id="ReadingsVals">
      </span>

so with

         document.getElementById("ReadingsVals").innerHTML = this.responseText;

you inject within the empty span whatever you got as an answer

➜ the span should be around the existing text (and you should send a full update for that text)

Sorry. Im confuse. Can you tell me what to do with the span? Im lost. In the span, it should reflect the reading of the temp only and not the whole content of the page. I guess in the span it shows all the content of my page which it shouldnt and only the temperature readings only.

Say you have

<span id="ReadingsVals">
XXX
YYY
ZZZ
</span>

The call

document.getElementById("ReadingsVals").innerHTML = "HELLO";

Will replace everything inside the span, your HTML will become

<span id="ReadingsVals">
HELLO
</span>

➜ you need to have whatever HTML you are sending back already within the span so that it gets overwritten, otherwise you just replace the Empty content of your first span by what you sent and you get the text twice

So if instead of


  client.println(F("<center><a href=\"/\">Refresh</a>"));
  client.println(F("<h3>SERVER TEMPERATURE</a></h3>"));
  client.println(F("<br>"));
  client.println(F("<span id=\"ReadingsVals\">"));
  client.println(F("</span>"));

You do

  client.println(F("<span id=\"ReadingsVals\">"));
//===================================
// this part is within the span with ID ReadingsVals
  client.println(F("<center><a href=\"/\">Refresh</a>"));
  client.println(F("<h3>SERVER TEMPERATURE</a></h3>"));
  client.println(F("<br>"));
 //==================================
  client.println(F("</span>"));

Then what gets replaced by the JavaScript call

document.getElementById("ReadingsVals").innerHTML = this.responseText;"));

is the HTML generated by

  client.println(F("<center><a href=\"/\">Refresh</a>"));
  client.println(F("<h3>SERVER TEMPERATURE</a></h3>"));
  client.println(F("<br>"));

And it gets replaced (textually) by what was in this.responseText

(I’m typing on my iPhone so can’t extract and type your HTML code exactly)

Hi @J-M-L,

You are amazing! The content of the page did not duplicate. Thank you. However, the reading of the temperature is printed below but it should be at the top of the "Aircon is ON" word. i followed what you instructed, and yes, the contents did not duplicate, but the temperature reading is at the end of the page. How can i possibly move it to the top?

Here's my code:

//For ethernet
#include <SPI.h>
#include <Ethernet.h>
//For relay
#include <Wire.h>
#include <Relay.h>
//For Temp
#include <OneWire.h>
#include <DallasTemperature.h>
//For GSM
#include <SoftwareSerial.h>

#include <EEPROM.h>


//For GSM---------------------------------------------------------------------------------
SoftwareSerial mySerial(2, 3);
char Rx_data[150];
unsigned char Rx_index = 0; 
int i = 0;
char msg[160];
int sig;

#define DEBUG true

//-----------------------------------------------------------------------------------------
int passFlag = 0;
int passFlag1 = 0;
int passFlag2 = 0;
int passFlag3 = 0;
//Millis timeout---------------------------------------------------------------------------

//-----------------------------------------------------------------------------------------

//Batt pin---------------------------------------------------------------------------------
#define SIGNAL_PIN A0   //battery level monitoring using 4.7K & 2.2K ohm resistor
//-----------------------------------------------------------------------------------------


//Temp Pin---------------------------------------------------------------------------------
#define ONE_WIRE_BUS 4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
float temp;
//-----------------------------------------------------------------------------------------


//Batt computation-------------------------------------------------------------------------
float adc_voltage = 0.0;
float in_voltage = 0.0;
float R1 = 30000.0;
float R2 = 7500.0;
float ref_voltage = 5.0;
int adc_value = 0;
//-----------------------------------------------------------------------------------------


//Ethernet---------------------------------------------------------------------------------
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1, 12);

// Initialize the Ethernet server library
// with the IP address and port you want to use 
// (port 80 is default for HTTP):
EthernetServer server(80);

//-----------------------------------------------------------------------------------------

// Relay state and pin---------------------------------------------------------------------
String relay1State1 = "ON";
String relay2State2 = "ON";
const int  TempCon= 6;
const int ChgRlyCon = 7;

//-----------------------------------------------------------------------------------------


// Client variables------------------------------------------------------------------------ 
char linebuf[160];
int charcount=0;
boolean authentificated=false;
//-----------------------------------------------------------------------------------------

void dashboardPage(EthernetClient &client) {
  client.println(F("HTTP/1.1 200 OK")); 
  client.println(F("Content-Type: text/html"));
  client.println(F("Connnection: close"));
  client.println();
  client.println(F("<!DOCTYPE HTML><html>"));
  client.println(F("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"));
  client.println(F("<script>"));
  client.println(F("setInterval(function()"));
  client.println(F("{"));
  client.println(F("getReadingsVals();"));
  client.println(F("}, 1000);"));
  client.println(F("function getReadingsVals()"));
  client.println(F("{"));
  client.println(F("var ReadingsRequest = new XMLHttpRequest();"));
  client.println(F("ReadingsRequest.onreadystatechange = function()"));
  client.println(F("{"));
  client.println(F("if(this.readyState == 4 && this.status == 200)"));
  client.println(F("{"));
  client.println(F("document.getElementById(\"ReadingsVals\").innerHTML = this.responseText;"));
  client.println(F("}"));
  client.println(F("};"));
  client.println(F("ReadingsRequest.open(\"GET\", \"readReadings\", true);"));
  client.println(F("ReadingsRequest.send();"));
  client.println(F("}"));
  client.println(F("</script>"));
  client.println(F("</head>"));
  client.println(F("<style>body {background-image: url(\"https://geloautomationworks.files.wordpress.com/2023/08/bb1.jpg\");  background-size: 100vw 100vh; background-repeat: no-repeat;  text-align: center; font-family: \"Trebuchet MS\", Arial;}</style>"));
  client.println(F("<span id=\"ReadingsVals\">"));
  client.println(F("<center><a href=\"/\">Refresh</a>"));
  client.println(F("<h3>SERVER TEMPERATURE</a></h3>"));
  client.println(F("<br>"));
  client.println(F("</span>"));
  client.println(F("</br>"));
 // Generates buttons to control the relay 
  client.println(F("<br>"));
  if(relay1State1 == "ON"){
  client.println(F("Aircon is <font color=\"green\">ON</font>"));
  }
  else if (relay1State1 == "OFF") {
  client.println(F("Aircon is <font color=\"red\">OFF</font>"));
  }
  client.println(F("</br>"));  
  client.println(F("<a href=\"/ACON\"><button>ON</button></a>&nbsp;&nbsp"));  
  client.println(F("<a href=\"/ACOFF\"><button>OFF</button></a>"));
  client.println(F("<h3>SERVER BATTERY LEVEL</h3>"));
  client.println(F("<br>"));
  client.println(in_voltage);
  client.println(F("</br>"));
  // Generates buttons to control the relay  
  client.println(F("<br>"));
  if(relay2State2 == "ON"){
  client.println(F("Battery is <font color=\"green\"’>CHARGING</font>"));
  }
  else if (relay2State2 == "OFF") {
  client.println(F("Battery is <font color=\"red\">NOT CHARGING</font>"));
  }
  client.println(F("</br>"));  
  client.println(F("<a href=\"/DCON\"><button>ON</button></a>&nbsp;&nbsp"));
  client.println(F("<a href=\"/DCOFF\"><button>OFF</button></a></center>"));
  client.println(F("</body></html>")); 
  
}

void SendAuthentificationpage(EthernetClient &client)
{
  client.println(F("HTTP/1.1 401 Authorization Required"));
  client.println(F("WWW-Authenticate: Basic realm=\"Secure Area\""));
  client.println(F("Content-Type: text/html"));
  client.println("Connnection: close");
  client.println();
  client.println(F("<!DOCTYPE HTML>"));
  client.println(F("<HTML>  <HEAD>   <TITLE>Error</TITLE>"));
  client.println(F(" </HEAD> <BODY><H1>401 Unauthorized.</H1></BODY> </HTML>"));
}

void AJAX_request(EthernetClient  &client)
{
client.println(temp);
client.println(F("°C"));
}

void setup()
{
  // For GSM
  Serial.begin(9600);
  mySerial.begin(19200);


  //---------------------------------------------------------------------------------------

  //For ethernet
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
  //---------------------------------------------------------------------------------------

  //For relay pins
  pinMode(ChgRlyCon, OUTPUT);
  digitalWrite(ChgRlyCon, HIGH);
  pinMode(TempCon, OUTPUT);
  digitalWrite(TempCon, HIGH);
  //---------------------------------------------------------------------------------------


}


//-------------------------------------------------------------------------------------------

void loop() {
  
//----GSM------------------------------------------------------------------------------------  
   if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
  // listen for incoming clients
//------------------------------------------------------------------------------------------  
  
//----TEMP SENSOR---------------------------------------------------------------------------  
  sensors.requestTemperatures(); // Send the command to get temperatures
  temp = sensors.getTempCByIndex(0);
  sensors.requestTemperatures(); // Send the command to get temperatures
  temp = sensors.getTempCByIndex(0);
//------------------------------------------------------------------------------------------  
  
  
//----BATT SENSOR---------------------------------------------------------------------------
// Why "byIndex"? 
  // You can have more than one IC on the same bus. 
  // 0 refers to the first IC on the wire
  // Read the Analog Input
  adc_value = analogRead(SIGNAL_PIN);

  // Determine voltage at ADC input
  adc_voltage  = (adc_value * ref_voltage) / 1024.0;

  // Calculate voltage at divider input
  in_voltage = adc_voltage / (R2 / (R1 + R2)) ;
//------------------------------------------------------------------------------------------


//----BASIC AUTHENTICATION------------------------------------------------------------------
 // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    memset(linebuf, 0, sizeof(linebuf));
    charcount = 0;
    authentificated = false;
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        linebuf[charcount] = c;
        if (charcount < sizeof(linebuf) - 1) charcount++;
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the HTTP request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // decide what to do
          
          
          if (strstr(linebuf, "Authorization: Basic") > 0 && strstr(linebuf, "YWRtaW46RGF5d2Fsa2VyQDAwMg==") > 0)
            authentificated = true;
            
           
            if (authentificated) {
            dashboardPage(client);
            
           if (strstr(linebuf, "readReadings") > 0 && authentificated) {
             AJAX_request(client);
          }
            
          
          else if (strstr(linebuf, "GET /ACON") > 0 && authentificated) {
            digitalWrite(TempCon, HIGH);
            relay1State1="ON";
            init_GSM();
            send_msg("***********", "AC HAS BEEN TURNED ON BY ADMIN");
          }

          else if (strstr(linebuf, "GET /ACOFF") > 0 && authentificated) {
            digitalWrite(TempCon, LOW);
            relay1State1="OFF";
            init_GSM();
            send_msg("***********", "AC HAS BEEN TURNED OFF BY ADMIN");
          }

          else if (strstr(linebuf, "GET /DCON") > 0 && authentificated) {
            digitalWrite(ChgRlyCon, HIGH);
            relay2State2="ON";
            init_GSM();
            send_msg("***********", "CHARGING THE BATTERY HAS BEEN CONNECTED BY ADMIN");
          }

          else if (strstr(linebuf, "GET /DCOFF") > 0 && authentificated) {
            digitalWrite(ChgRlyCon, LOW);
            relay2State2="OFF";
            init_GSM();
            send_msg("***********", "CHARGING THE BATTERY HAS BEEN DISCONNECTED BY ADMIN");
          }
          }
          
          else {
            SendAuthentificationpage(client);
          }
          
          break;
          
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
//------------------------------------------------------------------------------------------

//----TEMP CONDITION------------------------------------------------------------------------ 
  if( temp >= 35){
    digitalWrite(TempCon, HIGH);
    relay1State1 = "ON";
    if(passFlag == 0){
      init_GSM();
      send_msg("***********", "AIRCON HAS BEEN TURNED ON");
      passFlag = 1;
      passFlag1 = 0;
    }
  }
  if (temp <= 14){
    digitalWrite(TempCon, LOW);
    relay1State1 = "OFF";
    if(passFlag1 == 0){
      init_GSM();
      send_msg("***********", "AIRCON HAS BEEN TURNED OFF");
      passFlag1 = 1;
      passFlag = 0;
    } 
//------------------------------------------------------------------------------------------


//----BATT CONDITION------------------------------------------------------------------------
  //--------------------------- bms 0, batt lt 13.4v--------------
  if(in_voltage >= 15){
    digitalWrite(ChgRlyCon, LOW);
    relay2State2 = "OFF";
    if(passFlag2 == 0){
      init_GSM();
      send_msg("***********", "CHARGING THE BATTERY HAS BEEN DISCONNECTED");
      passFlag2 = 1;
      passFlag3 = 0;
    }
  }
  //--------------------------- bms 0, batt is charged at 13.4V -------
  if(in_voltage <= 6){
    digitalWrite(ChgRlyCon, HIGH);
    relay2State2 = "ON";
    if(passFlag3 == 0){
      init_GSM();
      send_msg("***********", "CHARGING THE BATTERY HAS BEEN CONNECTED");
      passFlag3 = 1;
      passFlag2 = 0;
    }
  }
 }
//------------------------------------------------------------------------------------------
}


//---------------------------------------------------------------------------------------------- 


//---SEND GSM STRING----

void send_msg(char *number, char *msg)
{
  char at_cmgs_cmd[30] = {
    '\0'  };
  char msg1[160] = {
    '\0'  };
  char ctl_z = 0x1A;

  sprintf(msg1, "%s%c", msg, ctl_z);
  sprintf(at_cmgs_cmd, "AT+CMGS=\"%s\"\r\n",number);

  sendGSM(at_cmgs_cmd);
  delay(100);
  delay(100);
  delay(100);
  sendGSM(msg1);
  delay(100);
}

void sendGSM(char *string){
  mySerial.write(string);
  delay(90);
}

void clearString(char *strArray) {
  int j;
  for (j = 100; j > 0; j--)
    strArray[j] = 0x00;
}

void send_cmd(char *at_cmd, char clr){
  char *stat = '\0';
  while(!stat){
    sendGSM(at_cmd);
    delay(200);
    readSerialString(Rx_data);
    Serial.write(Rx_data);

    stat = strstr(Rx_data, "OK");
    Serial.println("Success");
    delay(50000);
  }
  if (clr){
    clearString(Rx_data);
    delay(200);
    stat = '\0';
  }
}

void init_GSM(){


  sendData("AT\r\n",1000,DEBUG); // AT

  sendData("AT+CMGF=1\r\n",1000,DEBUG); //AT+CMGF=1
  sendData("AT+CMGD=1\r\n",1000,DEBUG); //AT+CMGD=1

  delay(1000);
  delay(1000);
  delay(1000);
}

void readSerialString (char *strArray) {

  if(!mySerial.available()) {
    return;
  }

  while(mySerial.available()) {
    strArray[i] = mySerial.read();
    i++;
  }
}

String sendData(String command, const int timeout, boolean debug)
{
  String response = "";

  mySerial.print(command); 

  long int time = millis();

  while( (time+timeout) > millis())
  {
    while(mySerial.available())
    {


      char c = mySerial.read();
      response+=c;
    }  
  }

  if(debug)
  {
    Serial.print(response);
  }

  return response;
}

Here's the output:

It should be like this:
1 new

Im sorry if i keep on asking for help as im a beginner in ajax.

really it's not an Ajax question.

You need to build your web page in such a way that what needs to be modified is clearly identified (like in a span with an ID) that surrounds the HTML that needs modification.

When the XMLHttpRequest is running every n seconds, it sends a specific request to the Arduino which needs to return the requested information and then the javascript need to modify the HTML document that is displayed in the browser and replace the content of the associated span

here when you get the request for /readReadings, you execute

void AJAX_request(EthernetClient  &client)
{
  client.println(temp);
  client.println(F("°C"));
}

which just sends something like xxx°C

your javascript gets this answer and executes

document.getElementById(\"ReadingsVals\").innerHTML = this.responseText;

so in order to know what will be replaced by xxx°C, you need to find what element in the DOM has the ID "ReadingsVals" which is at the beginning

  client.println(F("<style>body {background-image: url(\"https://geloautomationworks.files.wordpress.com/2023/08/bb1.jpg\");  background-size: 100vw 100vh; background-repeat: no-repeat;  text-align: center; font-family: \"Trebuchet MS\", Arial;}</style>"));
  client.println(F("<span id=\"ReadingsVals\">"));
  client.println(F("<center><a href=\"/\">Refresh</a>"));
  client.println(F("<h3>SERVER TEMPERATURE</a></h3>"));
  client.println(F("<br>"));
  client.println(F("</span>"));

So the whole following HTML will get replaced

<center><a href=\"/\">Refresh</a>
<h3>SERVER TEMPERATURE</a></h3>
<br>

is replaced by xxx°C

is that what you want?? I think it should be just

  <h3><span id="ReadingsVals">SERVER TEMPERATURE </span></h3>

so that you only replace the text SERVER TEMPERATURE

then as far as the look and feel is concerned, I think your HTML page is not following the HTML standard. there is no <body>statement, the style for the body is outside the <head> section,
is an empty tag, so we don't need to close this tag with a
, center is obsolete, use CSS, ... ➜ that's possibly why the text does not end up were you need it to be

So I would recommend to redesign the HTML page as you want it to look like in HTML, validate that HTML and then inject the scripts etc

Hello @J-M-L,

Apologies for the late update on this issue. I managed to make it work because of your help. Thank you so much for your help. I do appreciate it a lot. Here's my code for your reference.

//For ethernet
#include <SPI.h>
#include <Ethernet.h>
//For relay
#include <Wire.h>
#include <Relay.h>
//For Temp
#include <OneWire.h>
#include <DallasTemperature.h>
//For GSM
#include <SoftwareSerial.h>

#include <EEPROM.h>


//For GSM---------------------------------------------------------------------------------
SoftwareSerial mySerial(2, 3);
char Rx_data[150];
unsigned char Rx_index = 0; 
int i = 0;
char msg[160];
int sig;

#define DEBUG true

//-----------------------------------------------------------------------------------------
int passFlag = 0;
int passFlag1 = 0;
int passFlag2 = 0;
int passFlag3 = 0;
//Millis timeout---------------------------------------------------------------------------

//-----------------------------------------------------------------------------------------

//Batt pin---------------------------------------------------------------------------------
#define SIGNAL_PIN A0   //battery level monitoring using 4.7K & 2.2K ohm resistor
//-----------------------------------------------------------------------------------------


//Temp Pin---------------------------------------------------------------------------------
#define ONE_WIRE_BUS 4
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
float temp;
//-----------------------------------------------------------------------------------------


//Batt computation-------------------------------------------------------------------------
float adc_voltage = 0.0;
float in_voltage = 0.0;
float R1 = 30000.0;
float R2 = 7500.0;
float ref_voltage = 5.0;
int adc_value = 0;
//-----------------------------------------------------------------------------------------


//Ethernet---------------------------------------------------------------------------------
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192,168,1, 12);

// Initialize the Ethernet server library
// with the IP address and port you want to use 
// (port 80 is default for HTTP):
EthernetServer server(80);

//-----------------------------------------------------------------------------------------

// Relay state and pin---------------------------------------------------------------------
String relay1State1 = "OFF";
String relay2State2 = "OFF";
const int  TempCon= 6;
const int ChgRlyCon = 7;

//-----------------------------------------------------------------------------------------


// Client variables------------------------------------------------------------------------ 
char linebuf[160];
int charcount=0;
boolean authentificated=false;
//-----------------------------------------------------------------------------------------

void dashboardPage(EthernetClient &client) {
  client.println(F("HTTP/1.1 200 OK"));
  client.println(F("Content-Type: text/html"));
  client.println(F("Connnection: close"));
  client.println();
  client.println(F("<!DOCTYPE HTML><html><style>body {background-image: url(\"https://geloautomationworks.files.wordpress.com/2023/09/bg-2.png\");  background-size: 100vw 100vh; background-repeat: no-repeat;  text-align: center; font-family: \"Trebuchet MS\", Arial;}</style>"));
  client.println(F("<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"));
  client.println(F("<script>"));
  client.println(F("setInterval(function()"));
  client.println(F("{"));
  client.println(F("getReadingsVals();"));
  client.println(F("}, 3000);")); 
  client.println(F("function getReadingsVals()"));
  client.println(F("{"));
  client.println(F("var xhttp = new XMLHttpRequest();"));
  client.println(F("xhttp.onreadystatechange = function()"));
  client.println(F("{"));
  client.println(F("if(this.readyState == 4 && this.status == 200)"));
  client.println(F("{"));
  client.println(F("document.getElementById(\"ReadingsVals\").innerHTML = this.responseText;"));
  client.println(F("}"));
  client.println(F("};"));
  client.println(F("xhttp.open(\"GET\", \"readReadings\", true);"));
  client.println(F("xhttp.send();"));
  client.println(F("var xhttp = new XMLHttpRequest();"));
  client.println(F("xhttp.onreadystatechange = function()"));
  client.println(F("{"));
  client.println(F("if(this.readyState == 4 && this.status == 200)"));
  client.println(F("{"));
  client.println(F("document.getElementById(\"BatteryVals\").innerHTML = this.responseText;"));
  client.println(F("}"));
  client.println(F("};"));
  client.println(F("xhttp.open(\"GET\", \"readBattery\", true);"));
  client.println(F("xhttp.send();"));
  client.println(F("}"));
  client.println(F("</script>"));
  client.println(F("</head>"));
  client.println(F("<body>"));
  client.println(F("<h1>Automated Remote Monitoring and Control of Power and Temperature</h1>"));
  client.println(F("<h1>applying IoT</h>"));
  client.println(F("<br>"));
  client.println(F("</br>"));
  client.println(F("<h3>SERVER TEMPERATURE</h3>"));
  client.println(F("<br>"));
  client.println(F("<span id =\"ReadingsVals\">"));
  client.println(F(""));
  client.println(F("</span>"));
  client.println(F("<a href=\"/ACON\"><button>ON</button></a>&nbsp;&nbsp"));  
  client.println(F("<a href=\"/ACOFF\"><button>OFF</button></a>"));
  client.println(F("<br>"));
  client.println(F("</br>"));
  client.println(F("<h3>SERVER BATTERY LEVEL</h3>"));
  client.println(F("<br>"));
  client.println(F("<span id =\"BatteryVals\">"));
 client.println(F(""));
  // Generates buttons to control the relay  
client.println(F("</span>"));
client.println(F("<a href=\"/DCON\"><button>ON</button></a>&nbsp;&nbsp"));
client.println(F("<a href=\"/DCOFF\"><button>OFF</button></a></center>"));
client.println(F("<br>"));
client.println(F("</br>"));
client.println(F("<center><a href=\"/\">Refresh</a>"));
client.println(F("</body></html>"));
  
}

void SendAuthentificationpage(EthernetClient &client)
{
  client.println(F("HTTP/1.1 401 Authorization Required"));
  client.println(F("WWW-Authenticate: Basic realm=\"Secure Area\""));
  client.println(F("Content-Type: text/html"));
  client.println("Connnection: close");
  client.println();
  client.println(F("<!DOCTYPE HTML>"));
  client.println(F("<HTML>  <HEAD>   <TITLE>Error</TITLE>"));
  client.println(F(" </HEAD> <BODY><H1>401 Unauthorized.</H1></BODY> </HTML>"));
}

void AJAX_request(EthernetClient  &client)
{
client.println(F("<font face =\"radioland\", size = \"15\", color= \"black\">"));
client.println(temp);
client.println(F("°C"));
client.println(F("</font>"));
client.println(F("</br>"));
  if(relay1State1 == "ON"){
  client.println(F("Aircon is <font color=\"green\"’>ON</font>"));
  }
  else if(relay1State1 == "OFF") {
  client.println(F("Aircon is <font color=\"red\">OFF</font>"));
  }
  client.println(F("<br>"));
  client.println(F("</br>")); 

}

void BATT_request(EthernetClient  &client)
{
client.println(F("<font face =\"radioland\", size = \"15\", color= \"black\">"));
client.println(in_voltage);
client.println(F("V"));
client.println(F("</font>"));
client.println(F("</br>"));
if(relay2State2 == "ON") {
client.println(F("Battery is <font color=\"green\">CHARGING</font>"));
}
else if(relay2State2 == "OFF") {
client.println(F("Battery is <font color=\"red\">NOT CHARGING</font>"));
  }
client.println(F("<br>"));
client.println(F("</br>")); 
}

void setup()
{
  // For GSM
  Serial.begin(9600);
  mySerial.begin(19200);


  //---------------------------------------------------------------------------------------

  //For ethernet
  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
  //---------------------------------------------------------------------------------------

  //For relay pins
  pinMode(ChgRlyCon, OUTPUT);
  digitalWrite(ChgRlyCon, LOW);
  pinMode(TempCon, OUTPUT);
  digitalWrite(TempCon, LOW);
  //---------------------------------------------------------------------------------------


}


//-------------------------------------------------------------------------------------------

void loop() {
  
//----GSM------------------------------------------------------------------------------------  
   if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
  // listen for incoming clients
//------------------------------------------------------------------------------------------  
  
//----TEMP SENSOR---------------------------------------------------------------------------  
  sensors.requestTemperatures(); // Send the command to get temperatures
  temp = sensors.getTempCByIndex(0);
  sensors.requestTemperatures(); // Send the command to get temperatures
  temp = sensors.getTempCByIndex(0);
//------------------------------------------------------------------------------------------  
  
  
//----BATT SENSOR---------------------------------------------------------------------------
// Why "byIndex"? 
  // You can have more than one IC on the same bus. 
  // 0 refers to the first IC on the wire
  // Read the Analog Input
  adc_value = analogRead(SIGNAL_PIN);

  // Determine voltage at ADC input
  adc_voltage  = (adc_value * ref_voltage) / 1024.0;

  // Calculate voltage at divider input
  in_voltage = adc_voltage / (R2 / (R1 + R2)) ;
//------------------------------------------------------------------------------------------


//----BASIC AUTHENTICATION------------------------------------------------------------------
 // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    memset(linebuf, 0, sizeof(linebuf));
    charcount = 0;
    authentificated = false;
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        linebuf[charcount] = c;
        if (charcount < sizeof(linebuf) - 1) charcount++;
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the HTTP request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // decide what to do
          
          
          

          if (strstr(linebuf, "Authorization: Basic") > 0 && strstr(linebuf, "YWRtaW46RGF5d2Fsa2VyQDAwMg==") > 0)
            authentificated = true;
            
          if (strstr(linebuf, "readReadings") > 0) {
             AJAX_request(client);
          }
          
          else if (strstr(linebuf, "readBattery") > 0) {
             BATT_request(client);
          }
            

          else if (authentificated) {
            dashboardPage(client);
            
          
            
          
          if (strstr(linebuf, "GET /ACON") > 0 && authentificated) {
            digitalWrite(TempCon, HIGH);
            relay1State1="ON";
            init_GSM();
            send_msg("09168583128", "AC HAS BEEN TURNED ON BY ADMIN");
          }

          else if (strstr(linebuf, "GET /ACOFF") > 0 && authentificated) {
            digitalWrite(TempCon, LOW);
            relay1State1="OFF";
            init_GSM();
            send_msg("09168583128", "AC HAS BEEN TURNED OFF BY ADMIN");
          }

          else if (strstr(linebuf, "GET /DCON") > 0 && authentificated) {
            digitalWrite(ChgRlyCon, HIGH);
            relay2State2="ON";
            init_GSM();
            send_msg("09168583128", "CHARGING THE BATTERY HAS BEEN CONNECTED BY ADMIN");
          }

          else if (strstr(linebuf, "GET /DCOFF") > 0 && authentificated) {
            digitalWrite(ChgRlyCon, LOW);
            relay2State2="OFF";
            init_GSM();
            send_msg("09168583128", "CHARGING THE BATTERY HAS BEEN DISCONNECTED BY ADMIN");
          }
          }
          
          else {
            SendAuthentificationpage(client);
          }
          
          break;
          
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
//------------------------------------------------------------------------------------------

//----TEMP CONDITION------------------------------------------------------------------------ 
  if( temp >= 35){
    digitalWrite(TempCon, HIGH);
    relay1State1 = "ON";
    if(passFlag == 0){
      init_GSM();
      send_msg("09168583128", "AIRCON HAS BEEN TURNED ON");
      passFlag = 1;
      passFlag1 = 0;
    }
  }
  if (temp <= 29){
    digitalWrite(TempCon, LOW);
    relay1State1 = "OFF";
    if(passFlag1 == 0){
      init_GSM();
      send_msg("09168583128", "AIRCON HAS BEEN TURNED OFF");
      passFlag1 = 1;
      passFlag = 0;
    } 
//------------------------------------------------------------------------------------------


//----BATT CONDITION------------------------------------------------------------------------
  //--------------------------- bms 0, batt lt 13.4v--------------
  if(in_voltage >= 15){
    digitalWrite(ChgRlyCon, LOW);
    relay2State2 = "OFF";
    if(passFlag2 == 0){
      init_GSM();
      send_msg("09168583128", "CHARGING THE BATTERY HAS BEEN DISCONNECTED");
      passFlag2 = 1;
      passFlag3 = 0;
    }
  }
  //--------------------------- bms 0, batt is charged at 13.4V -------
  if(in_voltage <= 6){
    digitalWrite(ChgRlyCon, HIGH);
    relay2State2 = "ON";
    if(passFlag3 == 0){
      init_GSM();
      send_msg("09168583128", "CHARGING THE BATTERY HAS BEEN CONNECTED");
      passFlag3 = 1;
      passFlag2 = 0;
    }
  }
 }
//------------------------------------------------------------------------------------------
}


//---------------------------------------------------------------------------------------------- 


//---SEND GSM STRING----

void send_msg(char *number, char *msg)
{
  char at_cmgs_cmd[30] = {
    '\0'  };
  char msg1[160] = {
    '\0'  };
  char ctl_z = 0x1A;

  sprintf(msg1, "%s%c", msg, ctl_z);
  sprintf(at_cmgs_cmd, "AT+CMGS=\"%s\"\r\n",number);

  sendGSM(at_cmgs_cmd);
  delay(100);
  delay(100);
  delay(100);
  sendGSM(msg1);
  delay(100);
}

void sendGSM(char *string){
  mySerial.write(string);
  delay(90);
}

void clearString(char *strArray) {
  int j;
  for (j = 100; j > 0; j--)
    strArray[j] = 0x00;
}

void send_cmd(char *at_cmd, char clr){
  char *stat = '\0';
  while(!stat){
    sendGSM(at_cmd);
    delay(200);
    readSerialString(Rx_data);
    Serial.write(Rx_data);

    stat = strstr(Rx_data, "OK");
    Serial.println("Success");
    delay(50000);
  }
  if (clr){
    clearString(Rx_data);
    delay(200);
    stat = '\0';
  }
}

void init_GSM(){


  sendData("AT\r\n",1000,DEBUG); // AT

  sendData("AT+CMGF=1\r\n",1000,DEBUG); //AT+CMGF=1
  sendData("AT+CMGD=1\r\n",1000,DEBUG); //AT+CMGD=1

  delay(1000);
  delay(1000);
  delay(1000);
}

void readSerialString (char *strArray) {

  if(!mySerial.available()) {
    return;
  }

  while(mySerial.available()) {
    strArray[i] = mySerial.read();
    i++;
  }
}

String sendData(String command, const int timeout, boolean debug)
{
  String response = "";

  mySerial.print(command); 

  long int time = millis();

  while( (time+timeout) > millis())
  {
    while(mySerial.available())
    {


      char c = mySerial.read();
      response+=c;
    }  
  }

  if(debug)
  {
    Serial.print(response);
  }

  return response;
}

Congrats !

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.