From 647b4f5e8d3568f997b9430860e8d07f4abc6ce2 Mon Sep 17 00:00:00 2001 From: David Schroeder Date: Mon, 27 Feb 2017 12:08:53 -0500 Subject: [PATCH] Revise WiFiClient::Write to handle EAGAIN The send call may return EAGAIN. This indicates a recoverable error and a retry should be attempted. The current implementation treats this as a fatal error. Further, the current implementation strips the error code, setting it to 0, which prevents the caller from handling it directly. This change utilizes select to verify the socket is available prior to calling send and will retry on an EAGAIN condition. --- libraries/WiFi/src/WiFiClient.cpp | 44 ++++++++++++++++++++++++++----- 1 file changed, 38 insertions(+), 6 deletions(-) diff --git a/libraries/WiFi/src/WiFiClient.cpp b/libraries/WiFi/src/WiFiClient.cpp index ec92acc145c..00db698fcc1 100644 --- a/libraries/WiFi/src/WiFiClient.cpp +++ b/libraries/WiFi/src/WiFiClient.cpp @@ -22,6 +22,9 @@ #include #include +#define WIFI_CLIENT_MAX_WRITE_RETRY (10) +#define WIFI_CLIENT_SELECT_TIMEOUT_US (100000) + #undef connect #undef write #undef read @@ -160,14 +163,43 @@ int WiFiClient::read() size_t WiFiClient::write(const uint8_t *buf, size_t size) { - if(!_connected) { + int res =0; + int retry = WIFI_CLIENT_MAX_WRITE_RETRY; + int socketFileDescriptor = fd(); + + if(!_connected || (socketFileDescriptor < 0)) { return 0; } - int res = send(sockfd, (void*)buf, size, MSG_DONTWAIT); - if(res < 0) { - log_e("%d", errno); - stop(); - res = 0; + + while(retry) { + //use select to make sure the socket is ready for writing + fd_set set; + struct timeval tv; + FD_ZERO(&set); // empties the set + FD_SET(socketFileDescriptor, &set); // adds FD to the set + tv.tv_sec = 0; + tv.tv_usec = WIFI_CLIENT_SELECT_TIMEOUT_US; + retry--; + + if(select(socketFileDescriptor + 1, NULL, &set, NULL, &tv) < 0) { + return 0; + } + + if(FD_ISSET(socketFileDescriptor, &set)) { + res = send(socketFileDescriptor, (void*) buf, size, MSG_DONTWAIT); + if(res < 0) { + log_e("%d", errno); + if(errno != EAGAIN) { + //if resource was busy, can try again, otherwise give up + stop(); + res = 0; + retry = 0; + } + } else { + //completed successfully + retry = 0; + } + } } return res; }