John Durrell / NTPClient

Fork of NTPClient by Dieter Graef

Revision:
1:52e0f030d00e
Parent:
0:584a18640e84
Child:
2:eda6db3ada54
--- a/NTPClient.cpp	Sun Jun 19 16:24:06 2016 +0000
+++ b/NTPClient.cpp	Fri Apr 28 14:17:00 2017 +0000
@@ -35,18 +35,19 @@
 #endif
 
 #include "NTPClient.h"
-
+#include "EthernetInterface.h"
 #include "UDPSocket.h"
 
 #include "mbed.h" //time() and set_time()
-
+#include "lwip/opt.h"
+#include "lwip/def.h"
 #define NTP_PORT 123
 #define NTP_CLIENT_PORT 0 //Random port
 #define NTP_TIMESTAMP_DELTA 2208988800ull //Diff btw a UNIX timestamp (Starting Jan, 1st 1970) and a NTP timestamp (Starting Jan, 1st 1900)
 
-NTPClient::NTPClient() : m_sock()
+NTPClient::NTPClient(EthernetInterface& net_stack) : m_sock(&net_stack) 
 {
-
+ EthernetInterface  nst = net_stack;
 
 }
 
@@ -60,10 +61,10 @@
 
   //Create & bind socket
   DBG("Binding socket");
-  m_sock.bind(0); //Bind to a random port
-  
-  m_sock.set_blocking(false, timeout); //Set not blocking
-
+  SocketAddress inEndpoint("0.0.0.0", 0);
+  m_sock.bind(inEndpoint); //Bind to a random port 
+  m_sock.set_blocking(false); //Set not blocking
+  SocketAddress outEndpoint(&nst,host,port);
   struct NTPPacket pkt;
 
   //Now ping the server and wait for response
@@ -87,16 +88,14 @@
 
   pkt.refTm_f = pkt.origTm_f = pkt.rxTm_f = pkt.txTm_f = 0;
 
-  Endpoint outEndpoint;
-  
-  if( outEndpoint.set_address(host, port) < 0)
-  {
-    m_sock.close();
-    return NTP_DNS;
-  }
-  
+
+    DBG("Ping2");
+
+    
   //Set timeout, non-blocking and wait using select
-  int ret = m_sock.sendTo( outEndpoint, (char*)&pkt, sizeof(NTPPacket) );
+  int ret = m_sock.sendto(outEndpoint, &pkt, sizeof(NTPPacket));
+    DBG("Ping4");
+ 
   if (ret < 0 )
   {
     ERR("Could not send packet");
@@ -105,21 +104,22 @@
   }
 
   //Read response
-  Endpoint inEndpoint;
   // Set the inEndpoint address property
-  inEndpoint.set_address(outEndpoint.get_address(), 0);
   DBG("Pong");
-  do
-  {
-    ret = m_sock.receiveFrom( inEndpoint, (char*)&pkt, sizeof(NTPPacket) ); //FIXME need a DNS Resolver to actually compare the incoming address with the DNS name
-    if(ret < 0)
+int tries =0;
+while (true)  {  
+    ret = m_sock.recvfrom( &inEndpoint, (char*)&pkt, sizeof(NTPPacket) ); //FIXME need a DNS Resolver to actually compare the incoming address with the DNS name
+    wait(0.01);
+    if((ret < 0 && ret != -3001) || tries >100)
     {
       ERR("Could not receive packet");
       m_sock.close();
       return NTP_CONN;
     }
-  } while( strcmp(outEndpoint.get_address(), inEndpoint.get_address()) != 0 );
-
+    if (strcmp(outEndpoint.get_ip_address(), inEndpoint.get_ip_address()) == 0 ) break;
+    tries++;
+ } 
+  printf("NTP Server Address: %s \r\n",outEndpoint.get_ip_address());
   if(ret < sizeof(NTPPacket)) //TODO: Accept chunks
   {
     ERR("Receive packet size does not match");