Create GUI for esp32

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:

setInterval(function a() {
   
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
         drawfuntion(this);
    }
    
 
  };


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

function drawfuntion (xml){
  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 );

I am going to optimize it for you

setInterval( repeatThis, 3000 );

function repeatThis() {
 sendGetRequest ('temperature?xx=xx',function(response)   {
              drawFunction(response);
              });
} //  end function


function drawFunction(xml)  {

alert(xml);  // make sure you are able to capture this xml response here

// do something with this xml

}  //  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

Oh so that mean after the alter (xml ) I could capture the value and do the sketch of rectangle and fill it with color right?

For example after alter(xml) :
var temperature = parseFloat(xml.responseText);

Then do value compare and sketch

Second question :

sendGetRequest ('temperature?xx=xx',function(response)

For the temperature?xx=xx, what is the temperature?xx=xx mean

alert(), a dialog pop-up box, is for debugging ( to me ) in JS, It ensures the data you want retrieved is well echoed from 'server'

temperature?xx=xx 

this is a URL path, as in http://www.some_domain_name.com/temperature?xx=xx

I set the dummy variable name(xx) and value(xx) but not really needed in your case

sorry

Oh I have try your solution. The filling image not changing with the response value . I set the response at esp32 is 50 which mean the rectangle should fill up 50%.

P/S: I put the wrong url in my question . It should be /percentage not /temperature
Could it be I capture the response the wrong way ?

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 = "check";
const char* password = "buy";

// 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>

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