Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions NTPClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ void NTPClient::set_server(const char* server, int port) {
nist_server_port = port;
}

time_t NTPClient::get_timestamp(int timeout) {
int NTPClient::get_timestamp(time_t &timestamp, int timeout) {
const time_t TIME1970 = (time_t)2208988800UL;
int ntp_send_values[12] = {0};
int ntp_recv_values[12] = {0};
Expand Down Expand Up @@ -58,8 +58,8 @@ time_t NTPClient::get_timestamp(int timeout) {
const int n = sock.recvfrom(&source, (void*)ntp_recv_values, sizeof(ntp_recv_values));

if (n > 10) {
return ntohl(ntp_recv_values[10]) - TIME1970;

timestamp = ntohl(ntp_recv_values[10]) - TIME1970;
return 0;
} else {
if (n < 0) {
// Network error
Expand All @@ -77,6 +77,18 @@ time_t NTPClient::get_timestamp(int timeout) {
}
}

time_t NTPClient::get_timestamp(int timeout) {
time_t timestamp;
int ret = get_timestamp(timestamp, timeout);
if (ret < 0) {
// This doesn't work with the ARM toolchain whose time_t is unsigned
// Please use the new API get_timestamp(time_t *timestamp, int timeout)
return ret;
} else {
return timestamp;
}
}

void NTPClient::network(NetworkInterface *interface) {
iface = interface;
}
Expand Down
9 changes: 9 additions & 0 deletions NTPClient.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,24 @@
*/

#include "mbed.h"
#include "platform/mbed_toolchain.h"

#define NTP_DEFULT_NIST_SERVER_ADDRESS "2.pool.ntp.org"
#define NTP_DEFULT_NIST_SERVER_PORT 123

class NTPClient {
public:
explicit NTPClient(NetworkInterface *interface = NULL);

void set_server(const char* server, int port);

int get_timestamp(time_t &timestamp, int timeout = 15000);

MBED_DEPRECATED(
"This cannot return negative error codes with ARM toolchain's unsigned time_t. "
"Please use int get_timestamp(time_t &timestamp, int timeout) instead")
time_t get_timestamp(int timeout = 15000);

void network(NetworkInterface *interface);

private:
Expand Down