electronicsguy / ESP8266

ESP8266 Projects
242 stars 183 forks source link

Internet Connection Lost Handling #64

Closed ercoleg closed 5 years ago

ercoleg commented 6 years ago

Hello, taking inspiration to your GoogleDocs.ino I have written this code in order to launch a google script:

void loop() {
  static int error_count = 0;
  static int connect_count = 0;
  const unsigned int MAX_CONNECT = 20;
  static bool flag = false;
  String payload;
  String response;

  if (!flag) {
    client = new HTTPSRedirect(HTTPS_PORT);
    Serial.println("Client object created!");
    flag = true;
  }

  if (client != nullptr) {
    if (!client->connected()) {
      client->connect(HOST, HTTPS_PORT);
    }
  }
  else {
    Serial.println("Error creating client object!");
    error_count = 5;
  }

  if (connect_count > MAX_CONNECT) {
    Serial.println("Reset client object following MAX_CONNECT iteration");
    connect_count = 0;
    flag = false;
    delete client;
    return;
  }

  Serial.println("Google Script Launch");

    if (client->GET(URL, HOST)) {
      ++connect_count;
      payload = client->getResponseBody();
      Serial.print("HTTP Response: ");
      Serial.println(payload);
    }
    else {
      ++error_count;
      Serial.print("Error-count while connecting: ");
      Serial.println(error_count);
    }

my problem is that in case the internet connection is lost the client->GET(URL, HOST) dosn't return 0 and program is stuck. The same happens with your GoogleDocs.ino example. Switching on debug options of your library, when internet connection is lost, the program is stuck at this level:

Chunk Size: 0
GET Data from cell 'A1':
GET /macros/s/AKfycbzYw5G-oxvnwHpAJfDsS0PWNrO0KTBMiCW78lHUcEO6ZnFHvSw/exec?read HTTP/1.1
Host: script.google.com
User-Agent: ESP8266

The only workaround I found to handle internet connection lost is to repeat client->connect(HOST, HTTPS_PORT); at each cycle and handle the error at this level.

my background is Mechanical Engineering, no C++ programmig skills... please be patient if it is a stupid question.

Thank you

electronicsguy commented 5 years ago

Yes that's right. If it loses connection, you need to use connect() again. You can check if it's connected or not before repeating it.