me-no-dev / ESPAsyncWebServer

Async Web Server for ESP8266 and ESP32
3.67k stars 1.21k forks source link

events.send() fails when I sent certain values to the webpage #1197

Open Frans400 opened 2 years ago

Frans400 commented 2 years ago

Hi

Hopefully someone can help me if i send a random string of numbers like "12345678901234567890" the string reach my webpage but if I send values like "a" and so on the number don't seems to reach my webpage

code and images below to show the problem/error in my code

Thanks

Image one shows that no data is send to the webpage old array when i send something like "a"

image

Image two shows that the string of numbers is send to the webpage old array

image

My Main ino code.

/*********
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*********/

#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <Arduino_JSON.h>
#include "index.h"
#include "time.h"
#include "FS.h"
#include "SPIFFS.h"
#define FORMAT_SPIFFS_IF_FAILED true

String stringOldValues;

TaskHandle_t Task1;
TaskHandle_t Task2;
int newChart;

void listDir(fs::FS &fs, const char * dirname, uint8_t levels) {

  File root = fs.open(dirname);
  if (!root) {
    return;
  }
  if (!root.isDirectory()) {
    return;
  }

  File file = root.openNextFile();
  while (file) {
    if (file.isDirectory()) {
      if (levels) {
        listDir(fs, file.path(), levels - 1);
      }
    } else {
    }
    file = root.openNextFile();
  }
}

String readFile(fs::FS &fs, const char * path) {
  File file = fs.open(path, "r");
  if (!file || file.isDirectory()) {
    return String();
  }
  String fileContent;
  while (file.available()) {
    fileContent += String((char)file.read());
  }
  file.close();
  return fileContent;
}

void writeFile(fs::FS &fs, const char * path, const char * message) {
  File file = fs.open(path, FILE_WRITE);
  if (!file) {
    return;
  }
  if (file.print(message)) {
  } else {
  }
  file.close();
}

void appendFile(fs::FS &fs, const char * path, const char * message) {
  File file = fs.open(path, FILE_APPEND);
  if (!file) {
    return;
  }
  if (file.print(message)) {
  } else {
  }
  file.close();
}

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

const char* ntpServer = "pool.ntp.org";

unsigned long epochTime;

unsigned long getTime() {
  time_t now;
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    return (0);
  }
  time(&now);
  return now;
}

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

JSONVar readings;

String jsonStringValues() {
  readings["epoch"] = String(epochTime);
  readings["random1"] = String(random(100));
  readings["random2"] = String(random(100));
  String jsonString = JSON.stringify(readings);
  return jsonString;
}

void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
  }
}

void TaskLogAndSendNewValue( void * pvParameters ) {
  for (;;) {
    epochTime = getTime();
    if (epochTime > 0) {
      appendFile(SPIFFS, "/logger.txt", "12345678901234567890");          //this values shows on the webpage
      //appendFile(SPIFFS, "/logger.txt", "a");                           //this values does not shows on the webpage     
      //appendFile(SPIFFS, "/logger.txt", jsonStingValues().c_str());     //this values does not shows on the webpage
      //appendFile(SPIFFS, "/logger.txt", ",");                           //this values does not shows on the webpage
      events.send(jsonStringValues().c_str(), "new_readings" , millis());
    }
    vTaskDelay(2000 / portTICK_PERIOD_MS);
  }
}

void TaskSendOldValues( void * pvParameters ) {
  for (;;) {
    if (newChart != 0 ) {
      stringOldValues = "[" + readFile(SPIFFS, "/logger.txt") + "]";
      vTaskDelay(10000 / portTICK_PERIOD_MS);
      Serial.println(jsonStringValues().c_str());
      Serial.println(stringOldValues.c_str());
      Serial.println("");
      events.send(stringOldValues.c_str(), "old_readings" , millis());

      newChart = 0;
    }
    vTaskDelay(2000 / portTICK_PERIOD_MS);
  }
}

void setup() {
  Serial.begin(115200);
  if (!SPIFFS.begin(FORMAT_SPIFFS_IF_FAILED)) {
    return;
  }

  listDir(SPIFFS, "/", 0);

  //  if ((SPIFFS.exists("/logger.txt")) != 1) {
  writeFile(SPIFFS, "/logger.txt", "");
  //  }

  initWiFi();
  configTime(0, 0, ntpServer);

  server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send_P(200, "text/html", index_html);
    newChart = 1;

  });

  events.onConnect([](AsyncEventSourceClient * client) {
  });

  server.addHandler(&events);

  server.begin();
  xTaskCreatePinnedToCore(TaskLogAndSendNewValue, "Task1", 4000, NULL, 1, &Task1, 1);
  xTaskCreatePinnedToCore(TaskSendOldValues, "Task2", 4000, NULL, 1, &Task2, 1);
}

void loop() {
  vTaskDelay(1500000 / portTICK_PERIOD_MS);
}

the index.h file

const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>

<head>
<script src="https://code.highcharts.com/highcharts.js"></script>
</head>

<body>

<div><p>new string : <span id="thenewreading">no data</span></p></div>

<div><p>old array : <span id="theoldreading">no data</span></p></div>

<div id="chart-Random" class="chart-container"></div>

<script>

const chartT = new Highcharts.Chart({
  chart:{
    renderTo:'chart-Random'
  },
  series: [
    {
    data: []
    },
    {
    data: []
    },
  ],
  title: {
    text: undefined
  },
  xAxis: {
    type: 'datetime',
  },
  yAxis: {
    title: {
      text: 'yAxis 0 to 100'
    }
  },
});

function plotNewTemperature(jsonValue) {

  var keys = Object.keys(jsonValue);
  console.log(keys);
  console.log(keys.length);

  for (var i = 0; i < keys.length -1; i++){
    const key = keys[i+1];
    var x = Number(jsonValue["epoch"])*1000;
    console.log(x);
    var y = Number(jsonValue[key]);
    console.log(y);

    if(chartT.series[i].data.length > 30) {
      chartT.series[i].addPoint([x, y], true, true, true);
    } else {
      chartT.series[i].addPoint([x, y], true, false, true);
    }
  }
}

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

  source.addEventListener('old_readings', function(e) {
    console.log("old_readings", e.data);
    var myObj2 = JSON.parse(e.data);
    console.log(myObj2);
    //plotNewTemperature(myObj2);
    document.getElementById("theoldreading").innerHTML = (e.data);
  }, false);

  source.addEventListener('new_readings', function(e) {
    console.log("new_readings", e.data);
    var myObj1 = JSON.parse(e.data);
    console.log(myObj1);
    plotNewTemperature(myObj1);
    document.getElementById("thenewreading").innerHTML =(e.data);
  }, false);
}     

</script>
</body>
</html>)rawliteral";
stale[bot] commented 1 year ago

[STALE_SET] This issue has been automatically marked as stale because it has not had recent activity. It will be closed in 14 days if no further activity occurs. Thank you for your contributions.