diff --git a/third_party/sntp/sntp.cpp b/third_party/sntp/sntp.cpp index e50243a..e92d977 100644 --- a/third_party/sntp/sntp.cpp +++ b/third_party/sntp/sntp.cpp @@ -7,9 +7,49 @@ #include "sntp.h" #include "UDPSocket.h" +#include "mbed.h" #include "mbed_trace.h" #define TRACE_GROUP "SNTP" +EventFlags dns_arrived; // Holds a flag used to signal DNS arrival +nsapi_value_or_error_t dns_result; // Result from the DNS callback +SocketAddress dns_addr; // DNS address from the DNS callback + +void gethostbyname_callback(nsapi_value_or_error_t result, SocketAddress *address) { + dns_result = result; + dns_addr = *address; + dns_arrived.set(1); +} + +nsapi_error_t gethostbyname_timeout(NetworkInterface &net, const char* server, SocketAddress &addr, uint32_t timeout_ms) { + // Clear flags before call in case we had an unexpected callback + dns_arrived.clear(); + + // dns_id will be an ID for the async transaction or an error + nsapi_value_or_error_t dns_id; + dns_id = net.gethostbyname_async(server, gethostbyname_callback); + + if(dns_id < 0) { + // dns_id is an error, creating the async transaction failed + return dns_id; + } + + if(dns_arrived.wait_any(1, timeout_ms) != 1) { + // We timed out, cancel the transaction + net.gethostbyname_async_cancel(dns_id); + return NSAPI_ERROR_TIMEOUT; + } + + if (dns_result < 0) { + // The result itself errored, return that value + return dns_result; + } + + // Everything is fine, set the address and return + addr = dns_addr; + return NSAPI_ERROR_OK; +} + time_t ntp_seconds_to_unix(uint32_t ntp_time) { // NTP time starts at 1900, our time starts at 1970 // Subtract 70 years from NTP time to compensate @@ -62,7 +102,7 @@ tr_info("Getting SNTP time from %s", server); - err = net.gethostbyname(server, &addr); + err = gethostbyname_timeout(net, server, addr, 1000); if (err != NSAPI_ERROR_OK) { tr_err("gethostbyname error: %i", err); return SNTPDnsError;