JAndrassy / WiFiEspAT

Arduino networking library. Standard Arduino WiFi networking API over ESP8266 or ESP32 AT commands.
GNU Lesser General Public License v2.1
271 stars 44 forks source link

Defer rx timeout clearing until we are sure the firmware is responding #43

Closed JiriBilek closed 3 years ago

JiriBilek commented 3 years ago

Covers the issue when the firmware responds only with one character and then timeouts due to firmware error.

The issue is quite improbable but I was able to observe it. It might be bad voltage or whatever but the ESP rebooted while connecting. Then the STATUS response is missing (see code below) and due to default ATE1 on reset, the ESP echoes the '?' character send from the library as a 'keep-alive'. Echoing the '?' character fools the library and it waits a big amount of time (70 timeouts) before it recognizes the error. The fix ensures that when the ESP haven't respond with more than one characters, the data is not considered as a valid response. Regardless of improbability of the issue, we should definitely not evaluate the input buffer when we are not sure about its contents - see lines buffer[1] == '\n' etc. immediately after my fix.

There is a snippet of code where I observed the issue. Here, this library is wrapped into a C code but it should be understandable.

    // Enable the ESP module
    HAL_GPIO_WritePin(ESP_ENABLE_GPIO_Port, ESP_ENABLE_Pin, GPIO_PIN_SET);
    HAL_Delay(200);

    WiFi_init(WIFI_EXTERNAL_RESET);

    if (WiFi_status() == WL_NO_MODULE)
    {
        xprint("[WiFi] Communication with WiFi module failed!\r\n");

        // Disable the ESP module
        HAL_GPIO_WritePin(ESP_ENABLE_GPIO_Port, ESP_ENABLE_Pin, GPIO_PIN_RESET);
        return false;
    }
    else
    {
        // Wait for connection
        xprint("[WiFi] Waiting for connection.\r\n");

        uint32_t tick = HAL_GetTick();

#define CONNECT_TIMEOUT  5000UL
        while (WiFi_status() != WL_CONNECTED && HAL_GetTick() - tick < CONNECT_TIMEOUT)
        {
            HAL_Delay(100);
        }
    }

I observed the missed data in the last loop "Waiting for connection" where the library stayed in the readRX function for more than a minute.

JAndrassy commented 3 years ago

good fix. thank you