Home > other >  ESP32 no HTTP response
ESP32 no HTTP response

Time:01-23

I want to let my ESP32 get information from my homepage. But I get an error code -5 in the serial monitor output. I can't figure out what is wrong?

Is there something wrong with the code? Does the server not allow ESP32 to receive data and how do I find out of this?

You can see the output further down.

Code:

#include <WiFi.h>          // Replace with WiFi.h for ESP32
#include <WebServer.h>     // Replace with WebServer.h for ESP32
#include <AutoConnect.h>   // For AutoConnect Wifi
#include <time.h>          // For NTP time

//for display
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

//DISPLAY
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// The pins for I2C are defined by the Wire-library. 
// On an arduino UNO:       A4(SDA), A5(SCL)
// On an arduino MEGA 2560: 20(SDA), 21(SCL)
// On an arduino LEONARDO:   2(SDA),  3(SCL), ...
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

int x,minX;
IPAddress ip; 

//AUTOCONNECT
WebServer Server;          // Replace with WebServer for ESP32
AutoConnect      Portal(Server);
AutoConnectConfig Config;

//Webside fra ESP
void rootPage() {
  char content[] = "Kapsejlads.nu - HORN";
  Server.send(200, "text/plain", content);
}

//SKRIV NTP TID
void printLocalTime(){
  struct tm timeinfo; //skriv tiden til timeinfo som tidskode
  if(!getLocalTime(&timeinfo)){ //kontroller om tid er modtaget
    Serial.println("Failed to obtain time");
    return;
  }
  Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S"); //skriv tid til monitor
}

//SÆT TIDSZONE
void setTimezone(String timezone){
  Serial.printf("  Setting Timezone to %s\n",timezone.c_str()); //skriv til monitor
  setenv("TZ",timezone.c_str(),1);  //  Now adjust the TZ.  Clock settings are adjusted to show the new local time. Indstil til CPH
  tzset(); //indstil tidszonen
}

//HENT NTP TID
void initTime(String timezone){
  struct tm timeinfo; //skriv tiden til timeinfo

  Serial.println("Setting up time"); 
  configTime(0, 0, "europe.pool.ntp.org");    // First connect to NTP server, with 0 TZ offset. Ingen tidszone eller sommertidskorrektion
  if(!getLocalTime(&timeinfo)){ //hvis NTP ikke kan hentes
    Serial.println("  Failed to obtain time");
    return;
  }
  Serial.println("  Got the time from NTP"); //NTP tid er hentet
  // Now we can set the real timezone
  setTimezone(timezone); //sæt tidszonen og dermed evt. sommertid
}


void setup() {
//DISPLAY  
  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS);
  //delay(2000); // Pause for 2 seconds
  display.setTextSize(1); //font størrelse
  display.setTextColor(WHITE); //skrift farve
  display.setTextWrap(false); //skift ikke linje
  display.clearDisplay(); //ryd display
  display.setCursor(0, 10); //start position
  display.print("Kapsejlads.nu"); //sæt tekst
  display.setCursor(0, 20); //ny position
  display.print("by Frank Larsen"); //sæt tekst
  display.display(); //skriv til display
  x=display.width(); //sæt x = display bredde.
  
  //AUTOCONNECT
  Serial.begin(115200);
  Serial.println();
  Config.apid = "Kapsejlads-horn";
  Config.psk = "Kapsejlads.nu";
  Portal.config(Config);

  //FORBIND WIFI    
  Server.on("/", rootPage);
  if (Portal.begin()) {
    Serial.println("WiFi connected: "   WiFi.localIP().toString());
  }

  //hent NTP tid  
  delay(500);  //vent 0,5 s, så wifi er klar
  initTime("CET-1CEST,M3.5.0,M10.5.0/3"); //hent tid for københavn, https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv

  //hent klub navn
  String serverName = "https://kapsejlads.nu/hide-horn-esp.php";
  if(WiFi.status()== WL_CONNECTED){
      WiFiClient client;
      HTTPClient http;

      String serverPath = serverName   "?klubid=13";
      Serial.println(serverPath);
      
      // Your Domain name with URL path or IP address with path
      http.begin(client, serverPath.c_str());
  
      // If you need Node-RED/server authentication, insert user and password below
      //http.setAuthorization("REPLACE_WITH_SERVER_USERNAME", "REPLACE_WITH_SERVER_PASSWORD");
        
      // Send HTTP GET request
      int httpResponseCode = http.GET();
      
      if (httpResponseCode>0) {
        Serial.print("HTTP Response code: ");
        Serial.println(httpResponseCode);
        String payload = http.getString();
        Serial.println(payload);
      }
      else {
        Serial.print("Error code: ");
        Serial.println(httpResponseCode);
      }
      // Free resources
      http.end();
    }
    else {
      Serial.println("WiFi Disconnected");
    }
}

void loop() {
  Portal.handleClient();

  //Hent lokal NTP fra ESP
  struct tm timeinfo;
  getLocalTime(&timeinfo);

  //vis rulletekst
  char message[]="Dette er min tekst";
  //minX=-12*strlen(message);
  minX=-12*25; //12 karakter i disp med denne font, 25 karakter tekst at vise
  display.setTextSize(2);
  display.clearDisplay();
  display.setCursor(x,10);
  display.print(WiFi.localIP().toString() " - "); //viser IP i display
  display.print(&timeinfo, "%H:%M:%S"); //viser tiden bagefter i display
  //display.print(message); //viser tekst i display
  display.display(); //skriv til display
  x=x-1;
  if(x<minX)x=display.width();
  //Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S"); //skriv tid til monitor

}

Output: WiFi connected: 192.168.1.118 Setting up time Got the time from NTP Setting Timezone to CET-1CEST,M3.5.0,M10.5.0/3 https://kapsejlads.nu/hide-horn-esp.php?klubid=13 Error code: -5

I have tried to move the http code to the loop part without results.

When I run the homepage link I get "Demo klub" as result. This is just simple text. I expected the ESP32 to put this output to the Serial Monitor. But no.

I have also tried to format the output from the homepage as html, but it gives me same result:

echo '<html>';
    echo '<head></head>';
    echo '<body>';
    
    echo $klub[0]['klub'];
    
    echo '</body></html>';

CodePudding user response:

HTTPClient is open source, so you can read the code to find out what a -5 on return means - "Connection Lost".

In this case the connection is lost because you're trying to perform a GET from an HTTPS URL. Unfortunately, your code is using WiFiClient as the client object, which does not support SSL and HTTPS. You need to use WiFiClientSecure for HTTPS.

When you use WiFiClientSecure you need to either provide information about the certificates that the server is using or to set the connection as insecure. An insecure connection will still perform all the encryption associated with HTTPS, it just won't attempt to verify the identity of the web server. While you really should properly secure the connection, insecure may be acceptable for testing or very limited use projects.

So your code could look like this:

 if(WiFi.status()== WL_CONNECTED){
   WiFiClientSecure client;
   HTTPClient http;

   client.setInsecure();

You can learn more about how to do this in the examples that come with the HTTPClient library. You can learn more about how to configure WiFiClientSecure in its README and examples.

  • Related