Transitioning ESP32 sketch code to webserver based format [SOLVED!]

Goal: transition current ESP32 code to webserver based format where HTML can be
incorporated with the existing simple client.print() based webpage display I now use.

I plagiarized some code off the web and created my 1st very very basic webpage using an HTML file with the #include function. This was done with an ESP8266 and everything worked just fine.
Now I want to modify my existing ESP32 sketch code that currently uses client.print commands to send data to a webpage and do some simple things like borders and background color changes.
In my current ESP code I only reference library file "WiFi.h" and use the following:

void setup(){
 WiFi.begin(wifissid, wifipass);
server.begin();
}
void loop(){
 if (WiFi.status() == WL_CONNECTED && restart_Flag == true) {
    restart_Flag = false;
    startup_Millis = millis();
    server.begin();
  }
  int rssi = WiFi.RSSI();
  WiFiClient client = server.available();  // listen for incoming clients
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    currentLineIsBlank = true;

    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        if (c == '\n')  //     && currentLineIsBlank)
        {
          client.print("       ");
          client.print(rssi);
          StackString<75> XString = StackString<75>(" dBm Signal Strength [RSSI] ");
          XString.append("/ RTC Hr: ");
          XString.append(time_hour);
          XString.append(" : Min: ");
          XString.append(time_min);
          XString.append(" : Sec: ");
          XString.append(time_sec);
          client.println(XString.c_str());
          client.println();
    break;
        }
      }
    }
    delay(2000);  
    client.stop(); 
    Serial.println("client disonnected");
  }
  if (!client.connected() && lastConnected) {
    if (DEBUG) { Serial.println(); }
    if (DEBUG) { Serial.println("             disconnecting"); }
    client.stop();
  }
  lastConnected = client.connected();
}

The ESP8266 code is obviously different and includes:

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include "index.h"  // HTML webpage contents
const char* ssid = "Homestead-LAN_EXT";
const char* password = "********";
ESP8266WebServer server(80);  //Server on port 80
void handleRoot() {                  // executed when you open its IP in browser
  String s = MAIN_page;              // read HTML contents
  server.send(200, "text/html", s);  //send web page
}
void setup(){
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
WiFi.begin(ssid, password);  //connect to WiFi router
Serial.println("");
while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
server.on("/", handleRoot);  //which routine to handle at root location
server.begin();              //start server
Serial.println("HTTP server started");
}
void loop(void) {
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  server.handleClient();  //handle client requests
}

I found "simpleserver.ino" in the IDE Examples for ESP32 and it looks like what I might need to accomplish my goal but I am not sure. As long as I can still pass my field data through the client.print commands while using the webserver format I will hopefully be good to go. Any suggestions or links is appreciated. This is one in a row for me at this point. Thanks.

Believe I offered this to you once before; it’s the absolute best !

One example:

It may be the "Best" but I am driving a Yugo while he is in a Lamborghini. I have no interest in wading into Javascript and all that stuff. Its overkill for my hillbilly needs. But I appreciate the suggestion.

I saw what you drive !

:wink:

BTW I’ve been very good this year.

I have not seen that work, and also it is really clumsy,

You can create whatever HTML yourself with the bounds of the webserver.
instead of printing line by line you can create a buffer and send it pretty much in one go. (or chunked if the page is really big) the webserver also offers the ability to read the arguments and does the parsing for you.

#if defined(ARDUINO_ARCH_ESP8266)

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

ESP8266WebServer server(80);

#elif defined(ARDUINO_ARCH_ESP32)

#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>

WebServer server(80);

#endif

#include <PatchDNSServer.h>
DNSServer dnsServer;
#define DNS_PORT 53

const char *ssid = "xxx";
const char *password = "xxxxxxxx";
const char *apname = "ESPLed";
const char *appass = "password"; // minimum length 8 characters



const int ledpin = 2;  // I'm running this on an ESP-01
// i have a led connected to this active LOW
// i can't use the internal (pin 1) for the use of Serial

uint8_t ledstatus = 0; // this is keeping track of the state (of our statemachine)

const char   // like this these lines are statically declared and const, so we can't change them at all
*pageheader = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">",
 *htmlhead = "<html><head><title>ESPwebserver</title><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ></head>",
  *bodystyle = "<body style=\"color: wheat; background-color: teal; font-size: 12pt; font-family: sans-serif;\">",
   *accessIP = "http://192.168.4.1",
    *htmlclose = "</body></html>";

String webIP;

void setup() {
  webIP.reserve(30);  // prevent fragments
  digitalWrite(ledpin, HIGH);
  pinMode(ledpin, OUTPUT);

  Serial.begin(115200);

  WiFi.softAP(apname, appass); // start AP mode
  webIP = accessIP;
  Serial.print("Started Access Point \"");
  Serial.print(apname);
  Serial.println("\"");
  Serial.print("With password \"");
  Serial.print(appass);
  Serial.println("\"");
  WiFi.begin(ssid, password);  // attempt starting STA mode
  Serial.println("Attempting to start Station mode");

  uint32_t moment = millis();
  while ((WiFi.status() != WL_CONNECTED) && (millis() < moment + 8000)) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  if (WiFi.status() == WL_CONNECTED) {
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

    if (MDNS.begin("espled")) {  // type esp8266.local/ in your browser
      Serial.println("MDNS responder started, type espled.local/ in your browser");
    }
    webIP = "/"; //StationIP();
  }
  else if (WiFi.status() == WL_CONNECT_FAILED) {
    Serial.print("Connecting to ");
    Serial.print(ssid);
    Serial.println(" Unsuccessful.");
  }
  else if (WiFi.status() == WL_NO_SSID_AVAIL) {
    Serial.print("Network ");
    Serial.print(ssid);
    Serial.println(" not available.");
  }
  WiFi.reconnect();   // reconnect AP after attempting to connect STA

  dnsServer.start(DNS_PORT, "Thepage", IPAddress(192, 168, 4, 1));

  server.on("/", handleRoot);
  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();
  dnsServer.processNextRequest();
  checkLedStatus();
}

void checkLedStatus() {  // our statemachine
  switch (ledstatus) {
    case 0: {
        digitalWrite(ledpin, HIGH);
        return;
      }
    case 1: {
        digitalWrite(ledpin, LOW);
        return;
      }
    case 2: {
        if (ledBlink(500)) ; // here the return value (of ledBlink() ) gets discarded
        return;
      }
    case 3: {
        modulateLed();
        return;
      }
  }
}

void modulateLed() {
  static uint16_t ms = 100;
  static bool increase = true;

  if (!ledBlink(ms)) return;
  if (ms > 250) increase = false;
  if (ms < 20) increase = true;
  if (increase) ms = (ms * 10) / 9;
  else ms = (ms * 9) / 10;
}

bool ledBlink(uint32_t wait) {
  static bool pinstate = false;
  static uint32_t moment = millis();
  if (millis() > moment + wait) {
    pinstate = !pinstate;
    moment = millis();
    if (pinstate) digitalWrite(ledpin, LOW);
    else digitalWrite(ledpin, HIGH);
    return pinstate;  // if pinstate is true and the pinstate has changed, the modulator will change speed
  }
  return false;
}

void handleRoot() {
  String ledstatusupdate;
  if (server.hasArg("led")) {
    if (server.arg("led") == "off") {
      ledstatus = 0;
      ledstatusupdate = "The LED has been turned Off<br>";
    }
    else if (server.arg("led") == "on") {
      ledstatus = 1;
      ledstatusupdate = "The LED has been turned On<br>";
    }
    else if (server.arg("led") == "blink") {
      ledstatus = 2;
      ledstatusupdate = "The LED has been set to Blink<br>";
    }
    else if (server.arg("led") == "modulate") {
      ledstatus = 3;
      ledstatusupdate = "The LED has been set to Modulate<br>";
    }
  }

  String s = "";
  s += pageheader;
  s += htmlhead;
  s += bodystyle;

  s += "<h1>Welcome to ESP webserver</h1><p>From here you can control your LED making it blink or just turn on or off. ";
  s += "</p>";

  s += ledstatusupdate;
  s += "<br>";

  s += "<form action=\"";
  s += webIP;
  s += "\" method=\"get\" name=\"button\">";
  s += "<input type=\"hidden\" name=\"led\" value=\"on\">"; // the hidden parameter gets included
  s += "<input type=\"submit\" value=\" LED ON \"></form><br>"; // the button simply submits the form

  s += "<form action=\"";
  s += webIP;
  s += "\" method=\"get\" name=\"button\">";
  s += "<input type=\"hidden\" name=\"led\" value=\"off\">";
  s += "<input type=\"submit\" value=\" LED OFF\"></form><br>";

  s += "<form action=\"";
  s += webIP;
  s += "\" method=\"get\" name=\"button\">";
  s += "<input type=\"hidden\" name=\"led\" value=\"blink\">";
  s += "<input type=\"submit\" value=\"  BLINK  \"></form><br>";

  s += "<form action=\"";
  s += webIP;
  s += "\" method=\"get\" name=\"button\">";
  s += "<input type=\"hidden\" name=\"led\" value=\"modulate\">";
  s += "<input type=\"submit\" value=\"MODULATE\"></form><br>";

  s += htmlclose;
  yield();  // not stricktly neccesary, though the String class can be slow
  server.send(200, "text/html", s); //Send web page
}


String StationIP() {
  String stationIP = "http://";
  stationIP += WiFi.localIP().toString();
  return stationIP;
}

I dunno but my 16" x 16" chimney flue tile is gonna be a tight fit for ole St Nick unless he dropped some weight with these new fangled weight loss pills everybody is craving. :santa:

Just looking quickly at what you provided as a possible solution seems to be very encouraging!!! I will be testing out that code ASAP.
Thank you very much for sharing that!!!
:+1: :+1: :+1:

#include <PatchDNSServer.h>
DNSServer dnsServer;
#define DNS_PORT 53

Oh yeah i just remembered, this is a modified version of the dnsServer.h , you may need to comment it and it's depending code out

dnsServer.start(DNS_PORT, "Thepage", IPAddress(192, 168, 4, 1));  // this which creates an alias for the default AP   IP address

and

dnsServer.processNextRequest();  // which handles any requests for that alias

Ok Larry. You win!
I am going down the Super Mon rabbit hole..... lol.

No, you will win with that decision, be gentle on your self, it takes a bit of time.

Here is another example that a posted a while ago. There a few follow up posts that have more details. You may want to add a .reserve myString.reserve(size) to allocate the space for your web page. Make it a little larger than your expected web page size. This may reduce memory fragmentation from the String operations

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