From bb300d390ad555e98543c7376166c68d366ca0dc Mon Sep 17 00:00:00 2001 From: RobertGnz Date: Sat, 26 Nov 2022 16:19:54 +0100 Subject: [PATCH] API in WiFiClient to save heap memory When used by a server heap memory decrease drastically after numero client acces. Sockets in TIME_WAIT stay after the server issues a Client.stop which causes a server crash (and reboot) after some hours or some minutes. Note that the proposed method tcpCleanup in #1923 does not work because the instruction "extern struct tcp_pcb* tcp_tw_pcbs;" does NOT initialise tcp_tw_pcbs to the one used by the Client. It is only a declaration and because it is only a declaration, tcp_tw_pcbs is set to NULL. Consecuently tcp_abort(tcp_tw_pcbs) is never called. --- libraries/ESP8266WiFi/src/WiFiClient.cpp | 9 +++++++++ libraries/ESP8266WiFi/src/WiFiClient.h | 11 +++++++++++ 2 files changed, 20 insertions(+) diff --git a/libraries/ESP8266WiFi/src/WiFiClient.cpp b/libraries/ESP8266WiFi/src/WiFiClient.cpp index 6cdd5d1803..fb1105cada 100644 --- a/libraries/ESP8266WiFi/src/WiFiClient.cpp +++ b/libraries/ESP8266WiFi/src/WiFiClient.cpp @@ -313,6 +313,15 @@ bool WiFiClient::flush(unsigned int maxWaitMs) return _client->wait_until_acked(maxWaitMs); } +// Api for heap saving. Must be call just before WiFiClient::stop(). +void WiFiClient::abortTimeWait() +{ + if (!_client) return; + tcp_pcb* p; + p = _client->getPCB(); + if (p) tcp_abort(p); +} + bool WiFiClient::stop(unsigned int maxWaitMs) { if (!_client) diff --git a/libraries/ESP8266WiFi/src/WiFiClient.h b/libraries/ESP8266WiFi/src/WiFiClient.h index 170c983c0e..8b80e28a7a 100644 --- a/libraries/ESP8266WiFi/src/WiFiClient.h +++ b/libraries/ESP8266WiFi/src/WiFiClient.h @@ -103,6 +103,17 @@ class WiFiClient : public Client, public SList { friend class WiFiServer; using Print::write; + + // Api for saving precious heap. + // When Client class is used by a Server: Client = Server.available(), sockets in TIME_WAIT remain after + // issuing Client.stop by the Server application. + // This reduce drastically the heap memory in case of multiple client connections to the server ending + // with a Server shutdown and an ESP8266 reboot after some hours because of insufficient heap memory. + // This API is provided to free heap memory by mean of closing sockets just before issuing a Client.stop + // by the Server. + // The Server must use this API just before calling Client.stop + // Note: none of the proposed methode e.g. tcpCleanup and tcp_kill_timewait works properly. + void abortTimeWait(); static void stopAll(); static void stopAllExcept(WiFiClient * c);