Agasthya Valluri
Agasthya Valluri

Reputation: 11

ESP32 Webpage not finding uploaded JavaScript file

I am working to create a slider on a webpage that can return the value to the ESP32. Everything seems right but for some reason the webpage doesn't recognize the JavaScript file (see image)

FIX - Add command server.serveStatic("/",LittleFS,"/");

enter image description here

and no file called script2.js is added (naming it script.js gave me the same issue).

I am using LittleFS on the ESP32 to upload the file and it is showing me that it has been uploaded successfully.

enter image description here

Not sure why this is happening, I have my html, js and .ino code below.

<!DOCTYPE html>
<html>

<head>
  <title>DASHBOARD</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="styles.css">
  <script src="node_modules\chart.js\dist\chart.umd.js"></script>
</head>

<body>
  <div class="topnav">
    <h1 id="header"> Pressure Waveform and Control Data</h1>
  </div>

  <div class="container">
    <canvas id="pressuregraph" width="800" height="400"></canvas>
  </div>
  <div class="slider-group">
    <div class="slider-container">
    <label for="pressureSlider">Pressure (cmH20)</label>
    <span id="pressliderValue">%SLIDERVALUE%</span>
      <input type="range" onchange="updateslider(this)" id="pressureSlider" min="0" max="50" value="%SLIDERVALUE%"
        step="1" class="slider">
    </div>
  </div>
  <button class="download-button">Download Data</button>
  <button class="user-manual">User Manual</button>

  <script src="script2.js"></script>

</body>

</html> 
window.addEventListener('load', getReadings);
 

function updateslider(element) {
    var sliderValue = document.getElementById("pressureSlider").value;
    document.getElementById("pressliderValue").innerHTML = sliderValue;
    console.log(sliderValue);
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "/slider?value="+sliderValue, true);
    xhr.send();
} 
window.updateslider = updateslider;



const pressureData = [];

function updateChart(newValue) {
    pressureData.push(parseFloat(newValue)); // Ensure numerical values

    if (pressureData.length > 20) {
        pressureData.shift();
        pressureChart.data.labels.shift(); // Remove oldest label
    }

    // Update labels dynamically to match data points
    pressureChart.data.labels = pressureData.map((_, index) => index + 1);

    // Explicitly update the dataset reference
    pressureChart.data.datasets[0].data = [...pressureData];

    // Ensure Chart.js properly detects the update
    pressureChart.update('none');

}

const ctx = document.getElementById('pressuregraph').getContext('2d');
const pressureChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: [],
        datasets: [{
            label: 'Pressure (cmH20)',
            data: [],
            borderColor: 'blue',
            borderWidth: 2,
            fill: false,
            tension: 0.2
        }]
    },
    options: {
        responsive: false,
        scales: {
            x: { title: { display: true, text: 'Data Points' } },
            y: { title: { display: true, text: 'Pressure (cmH20)' } }
        }
    }
});


function getReadings() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
        }
    };
    xhr.open("GET", "/readings", true);
    xhr.send();
}

if (!!window.EventSource) {
    var source = new EventSource('/events');

    source.addEventListener('open', function (e) {
        console.log("Events Connected");
    }, false);

    source.addEventListener('error', function (e) {
        if (e.target.readyState != EventSource.OPEN) {
            console.log("Events Disconnected");
        }
    }, false);

    source.addEventListener('pressure', function (e) {

        updateChart(e.data);
    }, false);
} 
#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <LittleFS.h>
#include <Arduino_JSON.h>

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

AsyncWebServer server(80);
AsyncEventSource events("/events");

String sliderValue = "0";
const char* PARAM_INPUT = "value";
unsigned long lastTime = 0;
unsigned long timerDelay = 750;

String processor(const String& var){
  //Serial.println(var);
  if (var == "SLIDERVALUE"){
    return sliderValue;
  }
  return String();
}

void initLittleFS() {
  if (!LittleFS.begin()) {
    Serial.println("An error has occurred while mounting LittleFS");
  }
  else{
    Serial.println("LittleFS mounted successfully");
  }
}

void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("Connecting to WiFi ..");
  //Serial.println(cmH20)
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

void setup() {
  Serial.begin(115200);
  initWiFi();
  Serial.println();
  initLittleFS();

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

  server.on("/pressureslider", HTTP_GET, [] (AsyncWebServerRequest *request) {
    String inputMessage;
    // GET input1 value on <ESP_IP>/slider?value=<inputMessage>
    if (request->hasParam(PARAM_INPUT)) {
      inputMessage = request->getParam(PARAM_INPUT)->value();
      sliderValue = inputMessage;
    }
    else {
      inputMessage = "No message sent";
    }
    Serial.println(inputMessage);
    request->send(200, "text/plain", "OK");
  });

  server.on("/readings", HTTP_GET, [](AsyncWebServerRequest *request){
    String json = "sample";
    request->send(200, "application/json", json);
    json = String();
  });
  events.onConnect([](AsyncEventSourceClient *client){
    if(client->lastId()){
      Serial.printf("Client reconnected! Last message ID that it got is: %u\n", client->lastId());
    }
    // send event with message "hello!", id current millis
    // and set reconnect delay to 1 second
    client->send("hello!", NULL, millis(), 10000);
  });
  server.addHandler(&events);

  // Start server
  server.begin();

}

void loop() {
  String pressuredata = "sample";
  if ((millis() - lastTime) > timerDelay) {
    // Send Events to the client with the Sensor Readings Every 10 seconds
    events.send("ping",NULL,millis());
    events.send(pressuredata.c_str(),"pressure",millis());
    lastTime = millis();
  }
  delay(100);
} 

When running the HTML file directly (locally), the script is recognized. So it can't be a naming issue. Ienter image description here

I have run out of ideas that I could implement.

Upvotes: 0

Views: 36

Answers (0)

Related Questions