3

I have an ESP32 application that uses a web server as a user interface. For auditing and debugging during development I use Serial; however, that is impractical in the installed system. So, I decided to use Telnet (TCP/IP) to monitor what is happening when Serial is impractical.

The issue is that once a TCP/IP session has been established, when a HTTP request is received, the TCP/IP session is aborted.

I have reproduced the issue in a minimal sketch here:

#include "Arduino.h"
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>

WiFiClient telnetClient;
WebServer server(80);
WiFiServer telnetServer(23);

void telnetPrint(const char* text)
{
  if (telnetClient)
  {
    telnetClient.print(text);
  }
}

void telnetPrintln(const char *text)
{
  telnetPrint(text);
  telnetPrint("\r\n");
}

void _print(const char* text)
{
  Serial.print(text);
  telnetPrint(text);
}

void _println(const char* text)
{
  Serial.println(text);
  telnetPrintln(text);
}

void _println(IPAddress myIP)
{
  char rgIPTxt[32];
  sprintf(rgIPTxt,"%u.%u.%u.%u",myIP[0],myIP[1],myIP[2],myIP[3]);
  _println(rgIPTxt);
}

const char *rootFmt="\
<html>\
  <head>\
    <title>Test</title>\
  </head>\
  <body>\
    <h1>Test</h1>\
    <div>\
      <h2>Heap size=%d<br><br>\
    </div>\
  </body>\
</html>\
";

char rootMessage[1024];

void updateRootMessage()
{
  _println("updateRoot");
  snprintf(rootMessage, sizeof(rootMessage), rootFmt,
           heap_caps_get_free_size(MALLOC_CAP_8BIT)
           );
}

void handleRoot() 
{
  _println("Entered handleRoot");
  updateRootMessage();
  server.send(200, "text/html", rootMessage);
  _println("Leaving handleRoot");
}

void wifiSTASetup(const char*ssid, const char*password)
{
  WiFi.mode(WIFI_AP_STA);
  WiFi.begin(ssid, password);
  telnetServer.begin();
  telnetClient=telnetServer.available();
  _println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
    _print(".");
  }
  _println("");
  _print("Connected to ");
  _println(ssid);
  _print("IP address: ");
  _println(WiFi.localIP());
  server.on("/", handleRoot);
  server.begin();
}

#define BAND    915E6

void setup() 
{
  Serial.begin(115200);
  wifiSTASetup("your ssid", "your password");
}

void loop() 
{
  server.handleClient();
  if (!telnetClient)
  {
    telnetClient=telnetServer.available();
    if (telnetClient)
    {
      _println("telnetClient obtained");
    }
  }

}
2

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.