HTTP Timeout Not WOrking

I am trying to set a timeout on an HTTP get but it does't seem to work. I pasted the code segment below.

          Serial.print("[Weatherflow] http.begin ");  
          unsigned long httpStart = millis();                                       // time how long the GET takes
          http.begin(TempestRequest);
          http.setConnectTimeout(1500);                                             // set times out to fix issues with NINA timeout

         
        
        int httpCode = http.GET();                                                  // start connection and send HTTP header

        Serial.printf("GET Finished %dms ",millis()-httpStart);
        

I get [Weatherflow] http.begin GET Finished 2260ms so it didn't timeout. I can't stand very long delays in my code.

Thanks
Kurt

That's your error:: You didn't post the complete code. Experience shows that the error is most often in that part of the code that people are hiding from us. Even in the other cases we need the rest of the code to understand what's happening and why.

Ok. I thought I had the essential part.

#include "WeatherFlow.h" 
#include <HTTPClient.h>
#include <ArduinoJson.h>
////////////////  ESPnow Definations for message from ThermalSkymonitor
bool WeatherFlowGetSuccess = false;                          // Set True if success
/*******************************************************/
                   void getWeatherFlow(Tempest *T) {
/*******************************************************/


  HTTPClient http;
  
//       Serial.println("\nStarting connection to server...");
  String TempestRequest = "https://swd.weatherflow.com/swd/rest/observations/station/";
         TempestRequest =  TempestRequest + SECRET_STATION +"?";
         TempestRequest =  TempestRequest +  "token="+SECRET_APIKEY;
//       Serial.println(TempestRequest);  //https://swd.weatherflow.com/swd/rest/observations/station/27577?token=7729732b-7418-497d-8ed4-ff1ad9607a0d


 
          Serial.print("[Weatherflow] http.begin ");  
          unsigned long httpStart = millis();                                       // time how long the GET takes
          http.begin(TempestRequest);
          http.setConnectTimeout(1500);                                             // set times out to fix issues with NINA timeout

         
        
        int httpCode = http.GET();                                                  // start connection and send HTTP header

        Serial.printf("GET Finished %dms ",millis()-httpStart);
        

        if(httpCode > 0) {                                                          // httpCode will be negative on error
            
//         Serial.printf("[HTTP] GET... code: %7d\n", httpCode);                    // HTTP header has been send and Server response header has been handled

            
            if(httpCode == HTTP_CODE_OK) {                                         // file found at server
              WeatherFlowGetSuccess = true;                                        // set success
                String payload = http.getString();
                http.end(); 
                DynamicJsonDocument doc(3072) ;                                   // Allocate JSON document on heap
                 
//              payload.toCharArray(buffer,3072);
//              DeserializationError error = deserializeJson(doc, buffer);
                DeserializationError error = deserializeJson(doc, payload);       // Deserialize the JSON document
                
                   if (error) {                                                   // Test if parsing succeeds.
                        Serial.print(F("deserializeJson() failed: "));
                        Serial.print(error.f_str());
                        WeatherFlowGetSuccess = false;                            // set flag so bad data is ignored
                        http.end(); 
                        return;
                     }
                       
                      // Fetch values.
                      //
                      // Most of the time, you can rely on the implicit casts.
                      // In other case, you can do doc["time"].as<long>();

                    
                      T->station_name                              = doc["station_name"];
                      T->station_id                                = doc["station_id"];   
                      T->station_name                              = doc["station_name"];     
                      T->public_name                               = doc["public_name"];     
                      T->Latitude                                  = doc["latitude"];     
                      T->Longitude                                 = doc["longitude"];    
                      T->timezone                                  = doc["timezone"];    
                      T->elevation                                 = doc["elevation"];    
                      T->is_public                                 = doc["is_public"];     
                      T->Status                                    = doc["status"];    
                      T->status_message                            = doc["status_message"];     
                      T->units_temp                                = doc["station_units"]["units_temp"];
                      T->units_wind                                = doc["station_units"]["units_wind"];   
                      T->units_precip                              = doc["station_units"]["units_precip"];    
                      T->units_pressure                            = doc["station_units"]["units_pressure"];     
                      T->units_distance                            = doc["station_units"]["units_distance"];    
                      T->units_direction                           = doc["station_units"]["units_direction"];   
                      T->units_other                               = doc["station_units"]["units_other"];            
                      T->timestamp                                 = doc["obs"][0]["timestamp"];
                      T->air_temperature                           = doc["obs"][0]["air_temperature"];
                      T->barometric_pressure                       = doc["obs"][0]["barometric_pressure"];
                      T->station_pressure                          = doc["obs"][0]["station_pressure"];
                      T->sea_level_pressure                        = doc["obs"][0]["sea_level_pressure"];
                      T->relative_humidity                         = doc["obs"][0]["relative_humidity"];
                      T->precip                                    = doc["obs"][0]["precip"];
                      T->precip_accum_last_1hr                     = doc["obs"][0]["precip_accum_last_1hr"];
                      T->precip_accum_local_day                    = doc["obs"][0]["precip_accum_local_day"];
                      T->precip_accum_local_day_final              = doc["obs"][0]["precip_accum_local_day_final"];
                      T->precip_accum_local_yesterday              = doc["obs"][0]["precip_accum_local_yesterday"];
                      T->precip_accum_local_yesterday_final        = doc["obs"][0]["precip_accum_local_yesterday_final"];
                      T->precip_minutes_local_day                  = doc["obs"][0]["precip_minutes_local_day"];
                      T->precip_minutes_local_yesterday            = doc["obs"][0]["precip_minutes_local_yesterday"];
                      T->precip_minutes_local_yesterday_final      = doc["obs"][0]["precip_minutes_local_yesterday_final"];
                      T->precip_analysis_type_yesterday            = doc["obs"][0]["precip_analysis_type_yesterday"];
                      T->wind_avg                                  = doc["obs"][0]["wind_avg"];
                      T->wind_direction                            = doc["obs"][0]["wind_direction"];  
                      T->wind_gust                                 = doc["obs"][0]["wind_gust"];
                      T->wind_lull                                 = doc["obs"][0]["wind_lull"];
                      T->solar_radiation                           = doc["obs"][0]["solar_radiation"];  
                      T->uv                                        = doc["obs"][0]["uv"];  
                      T->brightness                                = doc["obs"][0]["brightness"];
                      T->lightning_strike_last_epoch               = doc["obs"][0]["lightning_strike_last_epoch"];
                      T->lightning_strike_last_distance            = doc["obs"][0]["lightning_strike_last_distance"];
                      T->lightning_strike_count                    = doc["obs"][0]["lightning_strike_count"];
                      T->lightning_strike_count_last_1hr           = doc["obs"][0]["lightning_strike_count_last_1hr"];
                      T->lightning_strike_count_last_3hr           = doc["obs"][0]["lightning_strike_count_last_3hr"];
                      T->feels_like                                = doc["obs"][0]["feels_like"];
                      T->heat_index                                = doc["obs"][0]["heat_index"];
                      T->wind_chill                                = doc["obs"][0]["wind_chill"];
                      T->dew_point                                 = doc["obs"][0]["dew_point"];
                      T->wet_bulb_temperature                      = doc["obs"][0]["wet_bulb_temperature"];
                      T->delta_t                                   = doc["obs"][0]["delta_t"];
                      T->air_density                               = doc["obs"][0]["air_density"];
                      T->pressure_trend                            = doc["obs"][0]["pressure_trend"];
                      
                     


#ifdef  LOOPDEBUG
                      Serial.print("wind_avg ");Serial.println(T->wind_avg);
                      Serial.print("station_pressure ");Serial.println(T->station_pressure);                      
                      Serial.printf("JSON String Length: %d JSON String: %s\n",payload.length(),payload.c_str());
                      Serial.print("station_name ");Serial.println(T->station_name);
                      Serial.print("air_temperature ");Serial.println(T->air_temperature);
                      Serial.print("barometric_pressure ");Serial.println(T->barometric_pressure);
                      Serial.print("station_pressure ");Serial.println(T->station_pressure);                      
                      Serial.print("relative_humidity ");Serial.println(T->relative_humidity);
                      Serial.print("precip ");Serial.println(T->precip);
                      Serial.print("wind_direction ");Serial.println(T->wind_direction);
                      Serial.print("wind_gust ");Serial.println(T->wind_gust);
                      Serial.print("wind_lull ");Serial.println(T->wind_lull);
                      Serial.print("wind_avg ");Serial.println(T->wind_avg);
                      Serial.print("lightning_strike_count_last_1hr ");Serial.println(T->lightning_strike_count_last_1hr);
                      Serial.print("dew_point ");Serial.println(T->dew_point);
                      Serial.print("delta_t ");Serial.println(T->delta_t);
                      Serial.print("units_temp ");Serial.println(T->units_temp);
                      Serial.print("units_precip ");Serial.println(T->units_precip);
                      Serial.print("units_pressure ");Serial.println(T->units_pressure);
                      Serial.print("units_distance ");Serial.println(T->units_distance);
                      Serial.print("units_direction ");Serial.println(T->units_direction);
                      Serial.print("units_other ");Serial.println(T->units_other);
                      Serial.println();
 #endif
                      
            }
        } else {
            Serial.printf("getWeatherFlow [HTTP] GET... failed code=%d, error: %s\n",httpCode, http.errorToString(httpCode).c_str());
            WeatherFlowGetSuccess = false;
        }



        return;
    }

Still not complete code, it wont' compile. At least we can guess now that you're using an ESP32 board. If not mentioned we always assume an Arduino UNO to be used. Remember, it's you which has to provide the information!

The setConnectTimeout() method just sets the timeout for the establishing of the connection. Once connected the timeout set by the setTimeout() method applies and that's rounded to seconds.

The code is maybe 30,000 lines and a few libraries so I think it would be a lot of work to compile.

Am I understanding you right that if I want a 2 second timeout I could do this:

http.setConnectTimeout(1500);                                             // set times out to fix issues with NINA           http.begin(TempestRequest);
http.setTimeout(2);
 int httpCode = http.GET();                                                  // start connection and send HTTP header

         
 

Using this code you give the library 1.5 seconds for the connection and then 2 seconds while connected. You cannot set an overall timeout.

Thanks. I read a few discussions on http.setTimeout(2) and I didn't know that you needed both. One discussion on GitHub was a argument over if the argument was in seconds or milliseconds. It seems to be in milliseconds. If I set it to 2 it does a read timeout every time. If I set it to 2000 it seems to work. The connect and Get commands in total seem to run around 1200-1500 ms when they succeed.

Yes, sorry overlooked that. Both arguments are in milliseconds but the setTimeout() value is always round to seconds (there's no comment explaining why this is done).

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