SNTP Client
Fork of SNTPClient by
Diff: SNTPClient.cpp
- Revision:
- 1:a5a91530712d
- Parent:
- 0:137fc24033c4
diff -r 137fc24033c4 -r a5a91530712d SNTPClient.cpp --- a/SNTPClient.cpp Fri Dec 19 05:46:22 2014 +0000 +++ b/SNTPClient.cpp Thu Jun 15 20:17:11 2017 +0000 @@ -1,4 +1,5 @@ #include "SNTPClient.h" +#include "DNSClient.h" #define MAX_TRY_WRITE 20 #define MAX_TRY_READ 10 @@ -16,27 +17,43 @@ #define INFO(x, ...) printf("[SNTPClient : INFO]"x"\r\n", ##__VA_ARGS__); -SNTPClient::SNTPClient(char * url, uint8_t time_zone) { - memcpy(host, url, strlen(url)); - host[strlen(url)] = '\0'; +SNTPClient::SNTPClient(NetworkStack *ns, const char* url, uint8_t time_zone) { + DNSClient dns(ns); + + if (dns.lookup(url)) { + const char* dns_addr = dns.get_ip_address(); + memcpy(host, dns_addr, strlen(dns_addr)); + host[strlen(dns_addr)] = '\0'; + } else { + memcpy(host, url, strlen(url)); + host[strlen(url)] = '\0'; + } + port = ntp_port; - socket.set_blocking(false, 3000); - + m_ns = ns; + m_udp = NULL; tz = time_zone; } bool SNTPClient::connect() { - socket.init(); - socket.bind(0); - if(sntp_server.set_address(host, port) < 0) - return false; + if (m_udp == NULL) { + m_udp = new UDPSocket; + m_udp->open(m_ns); + } + + m_udp->set_blocking(false); + m_udp->set_timeout(3000); + m_udp->bind(rand()&0x7fff); - uint32_t ip = str_to_ip(sntp_server.get_address()); - NTPformat.dstaddr[0] = (uint8_t)(ip >> 24); - NTPformat.dstaddr[1] = (uint8_t)(ip >> 16); - NTPformat.dstaddr[2] = (uint8_t)(ip >> 8); - NTPformat.dstaddr[3] = (uint8_t)(ip >> 0); - DBG("NTP Server: %s\r\n", sntp_server.get_address()); + sntp_server.set_ip_address(host); + sntp_server.set_port(port); + + nsapi_addr_t na = sntp_server.get_addr(); + NTPformat.dstaddr[0] = na.bytes[0]; + NTPformat.dstaddr[1] = na.bytes[1]; + NTPformat.dstaddr[2] = na.bytes[2]; + NTPformat.dstaddr[3] = na.bytes[3]; + DBG("NTP Server: %s\r\n", sntp_server.get_ip_address()); uint8_t Flag; NTPformat.leap = 0; /* leap indicator */ @@ -60,15 +77,18 @@ } bool SNTPClient::getTime(datetime *time) { + if (!m_udp) return false; + uint16_t startindex = 40; //last 8-byte of data_buf[size is 48 byte] is xmt, so the startindex should be 40 - socket.sendTo(sntp_server, (char *)ntpmessage, sizeof(ntpmessage)); - + int n = m_udp->sendto(sntp_server, (char *)ntpmessage, sizeof(ntpmessage)); + char in_buffer[MAX_SNTP_BUF_SIZE]; - int n = socket.receiveFrom(sntp_server, in_buffer, sizeof(in_buffer)); + n = m_udp->recvfrom(&sntp_server, in_buffer, sizeof(in_buffer)); - if(n <= 0) + if(n <= 0) { return false; + } get_seconds_from_ntp_server((uint8_t *)in_buffer,startindex); @@ -83,10 +103,9 @@ } bool SNTPClient::close() { - int ret = socket.close(); - if (ret < 0) { - ERR("Could not close"); - return false; + if (m_udp) { + delete m_udp; + m_udp = NULL; } return true; }