Create User Interface for ESP32 WIFI

Hi I try to use AJAX to create a website. This website contain a rectangle change there filling color as variable temperature increase. For example if temperature 0-10 there will no filling color. If it is 90 -100 the rectangle is fully fill. The variable temperature will be receive value from esp32 through HTTP. However, when I create a callback to access the value is not working. Could you guy give me some advice?

Code snapshot where I have problem :

setInterval( repeatThis, 3000 );

function repeatThis() {
 sendGetRequest ('/percentage',function(response)   {
              drawFunction(response);
              });
} //  end function


function drawFunction(xml)  {
 alert(xml);  // make sure you are able to capture this xml response here
 var temperature =  parseFloat(xml.responseText);
  var canvas = document.getElementById("DemoCanvas");
  if (canvas.getContext) 
  {
    var ctx = canvas.getContext('2d');
    ctx.lineWidth = "3";
    ctx.strokeStyle = "green";
    ctx.strokeRect(5, 50, 350, 200);
    ctx.lineWidth = "3";
    ctx.strokeStyle = "green";
    ctx.lineJoin = "round";
    ctx.strokeRect(355, 140, 40, 30);
   if (temperature  === 0 ){
    ctx.fillStyle = 'rgb(102, 204, 0)';
    ctx.fillRect(9, 55, 50, 190);
    ctx.font = "100px Comic Sans MS";
    ctx.fillStyle = "red";
    ctx.fillText(temperature , 500 , 180 );
    ctx.fillText("%" , 690 , 180 );
    }
   else if (temperature  <= 30 && temperature  >= 20){
    ctx.fillStyle = 'rgb(102, 204, 0)';
    ctx.fillRect(8, 55, 150, 190);
    ctx.font = "100px Comic Sans MS";
    ctx.fillStyle = "red";
    ctx.fillText(temperature , 500 , 180 );
    ctx.fillText("%" , 690 , 180 );
    }
  else if (temperature  <= 40 && temperature  >= 31 ){
    ctx.fillStyle = 'rgb(102, 204, 0)';
    ctx.fillRect(8, 55, 155 , 190);
    ctx.font = "100px Comic Sans MS";
    ctx.fillStyle = "red";
    ctx.fillText(temperature , 500 , 180 );
    ctx.fillText("%" , 690 , 180 );
    }
  else if (temperature  <= 50 && temperature  >= 41 ){
    ctx.fillStyle = 'rgb(102, 204, 0)';
    ctx.fillRect(8, 55, 180 , 190);
    ctx.font = "100px Comic Sans MS";
    ctx.fillStyle = "red";
    ctx.fillText(temperature , 500 , 180 );
    ctx.fillText("%" , 690 , 180 );
    }
  else if (temperature  <= 60 && temperature  >= 51 ){
    ctx.fillStyle = 'rgb(102, 204, 0)';
    ctx.fillRect(8, 55, 190 , 190);
    ctx.font = "100px Comic Sans MS";
    ctx.fillStyle = "red";
    ctx.fillText(temperature , 500 , 180 );
    ctx.fillText("%" , 690 , 180 );
    }
  else if (temperature  <= 70 && temperature  >= 61 ){
    ctx.fillStyle = 'rgb(102, 204, 0)';
    ctx.fillRect(8, 55, 220 , 190);
    ctx.font = "100px Comic Sans MS";
    ctx.fillStyle = "red";
    ctx.fillText(temperature , 500 , 180 );
    ctx.fillText("%" , 690 , 180 );
    }
  else if (temperature  <= 80 && temperature  >= 71 ){
    ctx.fillStyle = 'rgb(102, 204, 0)';
    ctx.fillRect(8, 55, 250 , 190);
    ctx.font = "100px Comic Sans MS";
    ctx.fillStyle = "red";
    ctx.fillText(temperature , 500 , 180 );
    ctx.fillText("%" , 690 , 180 );
    }
  else if (temperature  <= 90 && temperature  >= 81 ){
    ctx.fillStyle = 'rgb(102, 204, 0)';
    ctx.fillRect(8, 55, 300 , 190);
    ctx.font = "100px Comic Sans MS";
    ctx.fillStyle = "red";
    ctx.fillText(temperature , 500 , 180 );
    ctx.fillText("%" , 690 , 180 );
    }
  else {
   ctx.fillStyle = 'rgb(102, 204, 0)';
   ctx.fillRect(8, 55, 340 , 190);
   ctx.font = "100px Comic Sans MS";
   ctx.fillStyle = "red";
   ctx.fillText(temperature , 500 , 180 );
   ctx.fillText("%" , 690 , 180 );
  }
 }

}  //  end function

function sendGetRequest ( url, gotResponse ) {   
                            var xhttp = new XMLHttpRequest();
                            xhttp.onreadystatechange = function() {
                            if (this.readyState == 4 && this.status == 200) {                        
                            gotResponse( this.responseText );                           
                            }
                            };
                            xhttp.open('GET', url , true);
                            xhttp.send();
                            }   // end function

ESP32 code:

#include <string.h>
#include <Arduino.h>
#include "temperature.h"
#include "charge.h"
#include "current.h"
#include <Wire.h>
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <AsyncTCP.h>
#include "SPIFFS.h"

// Replace with your network credentials
const char* ssid = "JKL";
const char* password = "privacy";

// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

String temperature_text = "25" ;
String percentage_text = "50" ;

temperature bms;
charge  battery ;
current battery_2;


void setup() {
 
  Serial.begin(115200);
  Serial.println("Hello, ESP32!");


  // Initialize SPIFFS
  if(!SPIFFS.begin()){
    Serial.println("An Error has occurred while mounting SPIFFS");
    return;
  }

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }

  // Print ESP32 Local IP Address
  Serial.println(WiFi.localIP());

  // Route for root / web page
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/index.html");
  });
  server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", temperature_text.c_str());
  });
  server.on("/percentage", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain", percentage_text.c_str() );
  });


 
  server.begin();
  
  battery.begin();
  bms.begin();
  battery_2.begin(); 
}

void loop() {

 
  bms.calculate_temperature();
  battery.pin_multiplexer();
  battery.check_voltage();
  battery.percentage(); 
  battery_2.check_current();
}

My full website code :

<!DOCTYPE HTML><html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://code.highcharts.com/highcharts.js"></script>
  <style>
    body {
      min-width: 310px;
    	max-width: 800px;
    	height: 400px;
      margin: 0 auto;
    }
    h2 {
      font-family: Arial;
      font-size: 2.5rem;
      text-align: center;
    }
  </style>
</head>
<body>
  <h2>Battery Managment System </h2>
  <div id="chart-temperature" class="container"></div>
  <p id="percentage_battery"></p>
  <canvas id="DemoCanvas" width="1000" height="600"></canvas> 
  
</body>
<script>
var chartT = new Highcharts.Chart({
  chart:{ renderTo : 'chart-temperature' },
  title: { text: ' Battery Temperature' },
  series: [{
    showInLegend: false,
    data: []
  }],
  plotOptions: {
    line: { animation: false,
      dataLabels: { enabled: true }
    },
    series: { color: '#059e8a' }
  },
  xAxis: { type: 'datetime',
    dateTimeLabelFormats: { second: '%H:%M:%S' }
  },
  yAxis: {
    title: { text: 'Temperature (Celsius)' }
    
  },
  credits: { enabled: false }
});
setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var x = (new Date()).getTime(),
          y = parseFloat(this.responseText);
      if(chartT.series[0].data.length > 40) {
        chartT.series[0].addPoint([x, y], true, true, true);
      } else {
        chartT.series[0].addPoint([x, y], true, false, true);
      }
    }
  };

  
  xhttp.open("GET", "/temperature", true);
  xhttp.send();
}, 30000 ) ;

setInterval( repeatThis, 3000 );

function repeatThis() {
 sendGetRequest ('/percentage',function(response)   {
              drawFunction(response);
              });
} //  end function


function drawFunction(xml)  {
 alert(xml);  // make sure you are able to capture this xml response here
 var temperature =  parseFloat(xml.responseText);
  var canvas = document.getElementById("DemoCanvas");
  if (canvas.getContext) 
  {
    var ctx = canvas.getContext('2d');
    ctx.lineWidth = "3";
    ctx.strokeStyle = "green";
    ctx.strokeRect(5, 50, 350, 200);
    ctx.lineWidth = "3";
    ctx.strokeStyle = "green";
    ctx.lineJoin = "round";
    ctx.strokeRect(355, 140, 40, 30);
   if (temperature  === 0 ){
    ctx.fillStyle = 'rgb(102, 204, 0)';
    ctx.fillRect(9, 55, 50, 190);
    ctx.font = "100px Comic Sans MS";
    ctx.fillStyle = "red";
    ctx.fillText(temperature , 500 , 180 );
    ctx.fillText("%" , 690 , 180 );
    }
   else if (temperature  <= 30 && temperature  >= 20){
    ctx.fillStyle = 'rgb(102, 204, 0)';
    ctx.fillRect(8, 55, 150, 190);
    ctx.font = "100px Comic Sans MS";
    ctx.fillStyle = "red";
    ctx.fillText(temperature , 500 , 180 );
    ctx.fillText("%" , 690 , 180 );
    }
  else if (temperature  <= 40 && temperature  >= 31 ){
    ctx.fillStyle = 'rgb(102, 204, 0)';
    ctx.fillRect(8, 55, 155 , 190);
    ctx.font = "100px Comic Sans MS";
    ctx.fillStyle = "red";
    ctx.fillText(temperature , 500 , 180 );
    ctx.fillText("%" , 690 , 180 );
    }
  else if (temperature  <= 50 && temperature  >= 41 ){
    ctx.fillStyle = 'rgb(102, 204, 0)';
    ctx.fillRect(8, 55, 180 , 190);
    ctx.font = "100px Comic Sans MS";
    ctx.fillStyle = "red";
    ctx.fillText(temperature , 500 , 180 );
    ctx.fillText("%" , 690 , 180 );
    }
  else if (temperature  <= 60 && temperature  >= 51 ){
    ctx.fillStyle = 'rgb(102, 204, 0)';
    ctx.fillRect(8, 55, 190 , 190);
    ctx.font = "100px Comic Sans MS";
    ctx.fillStyle = "red";
    ctx.fillText(temperature , 500 , 180 );
    ctx.fillText("%" , 690 , 180 );
    }
  else if (temperature  <= 70 && temperature  >= 61 ){
    ctx.fillStyle = 'rgb(102, 204, 0)';
    ctx.fillRect(8, 55, 220 , 190);
    ctx.font = "100px Comic Sans MS";
    ctx.fillStyle = "red";
    ctx.fillText(temperature , 500 , 180 );
    ctx.fillText("%" , 690 , 180 );
    }
  else if (temperature  <= 80 && temperature  >= 71 ){
    ctx.fillStyle = 'rgb(102, 204, 0)';
    ctx.fillRect(8, 55, 250 , 190);
    ctx.font = "100px Comic Sans MS";
    ctx.fillStyle = "red";
    ctx.fillText(temperature , 500 , 180 );
    ctx.fillText("%" , 690 , 180 );
    }
  else if (temperature  <= 90 && temperature  >= 81 ){
    ctx.fillStyle = 'rgb(102, 204, 0)';
    ctx.fillRect(8, 55, 300 , 190);
    ctx.font = "100px Comic Sans MS";
    ctx.fillStyle = "red";
    ctx.fillText(temperature , 500 , 180 );
    ctx.fillText("%" , 690 , 180 );
    }
  else {
   ctx.fillStyle = 'rgb(102, 204, 0)';
   ctx.fillRect(8, 55, 340 , 190);
   ctx.font = "100px Comic Sans MS";
   ctx.fillStyle = "red";
   ctx.fillText(temperature , 500 , 180 );
   ctx.fillText("%" , 690 , 180 );
  }
 }

}  //  end function

function sendGetRequest ( url, gotResponse ) {   
                            var xhttp = new XMLHttpRequest();
                            xhttp.onreadystatechange = function() {
                            if (this.readyState == 4 && this.status == 200) {                        
                            gotResponse( this.responseText );                           
                            }
                            };
                            xhttp.open('GET', url , true);
                            xhttp.send();
                            }   // end function
</script>
</html>

Are those your real login credentials? :wink:

my suggestion would be to make a very crude web page first to ensure the AJAX requests works.

have the ESP send just a canned XML response or one number

Once you've that going, you can make it look pretty but until this works there is no point messing with the code

Yes I have test it . It do receive the response. But when i put the canvas to draw rectangle it dont

What do u mean ?

I take advantage from example and learn how to build website from it . Do u have any other recommend on how to learn about AJAX for GUI?

I mean,

"Optus_290EFF"

etc

No, I borrow the credential from internet shop where let hiring computer

They're fine with you posting the password on the internet?

It's not a problem if it's already public. A lot of people just forget to replace it when they post. I protect myself from that in some of my sketches by making the logins an #include file.

Help with AJAX, not very likely here. Try a Java forum, tutorials, ...

Yup , thank you . I will check it out

here is a very basic example using AJAX to fetch a temperature and humidity value every second and update the web page with the numbers plus draw a rectangle which will be blue if the temperature is below 5°, green if below 25 and red after that.

the sketch has 2 files, one for the HTML raw string literal and one for the C++ code

the temperature and the humidity are just random numbers.

html.h

const char homepage[] PROGMEM = R"---(
<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <title>AJAX and XML</title>
   <style>
     canvas{ border: 1px solid black; }
   </style>
   <script>
   function readVariables() {
      var uniqueURL = "read" + "?&x=" + Math.trunc(Math.random() * 1000000);
      var request = new XMLHttpRequest(); 
      request.onreadystatechange = function() {
        if ((this.readyState == 4) && (this.status == 200) && (this.responseXML != null)) {
          var t = this.responseXML.getElementsByTagName('T')[0].childNodes[0].nodeValue;
          document.getElementById("TEMP_ID").innerHTML = t;
          document.getElementById("HUM_ID").innerHTML = this.responseXML.getElementsByTagName('H')[0].childNodes[0].nodeValue;
          var c = document.getElementById("RECT_ID");
          var ctx = c.getContext('2d');
          if (~~t < 5) ctx.fillStyle = "blue";
          else if (~~t < 25) ctx.fillStyle = "green";
          else ctx.fillStyle = "red";
          ctx.fillRect(0, 0, c.width, c.height);
        }
      }
      request.open("GET", uniqueURL , true);
      request.send(null);
      setTimeout("readVariables()", 1000);
   }
   </script>
</head>
<body onload="readVariables()">
   <p>Current Temperature is <span id="TEMP_ID">...</span> &#8451;</p>
   <canvas id="RECT_ID" width="200" height="20"></canvas>
   <p>Current Humidity is <span id="HUM_ID">...</span> %</p>
</body>
</html>
)---";

test.ino (the C++ code)

#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "html.h"

AsyncWebServer server(80);

const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

void notFound(AsyncWebServerRequest *request) {
  request->send(404, "text/plain", "Not found");
}

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  if (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.printf("WiFi Failed!\n");
    return;
  }

  Serial.print("Connect your browser to http://"); Serial.println(WiFi.localIP());

  // Homepage
  server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send(200, "text/html", homepage);
  });

  // The AJAX Handler
  server.on("/read", HTTP_GET, [] (AsyncWebServerRequest * request) {
    char buffer[64];
    snprintf(buffer, sizeof buffer, "<data><T>%ld</T><H>%ld</H></data>", random(-30, 46), random(0,101)); // 64 bytes is enough for this and trailing null
    request->send(200, "text/xml", buffer);
  });

  // error
  server.onNotFound(notFound);

  server.begin();
}

void loop() {}

update this part with your credentials

const char* ssid = "Optus_290EFF";
const char* password = "xxx";

The serial monitor will tell you where to connect

the web page will look like this


image


image


image

➜ the color is changing with the temperature

may be that can give you some ideas

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