Station API

Dependents:   GMCStation

Revision:
1:a22e390c70b3
Child:
2:a9d1a9c92927
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/NTPClient.h	Mon Dec 12 02:33:21 2011 +0000
@@ -0,0 +1,56 @@
+/*
+Copyright (c) 2011, Senio Networks, Inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+*/
+
+#include "SimpleSocket.h"
+
+class NTPClient {
+public:
+    NTPClient(char *server = "pool.ntp.org", float timeout = 3.0)
+            : server(server), timeout(timeout) {}
+            
+    bool setTime() {
+        Timer timer;
+        timer.start();
+        while (timer.read() < timeout) {
+            DatagramSocket datagram;
+            char buf[48] = {0x23}; // 00100011 LI(0), Version(4), Mode(3: Client)
+            datagram.write(buf, sizeof(buf));
+            datagram.send(server, 123);
+
+            if (datagram.receive(0, timeout) > 0) {
+                if (datagram.read(buf, sizeof(buf))) {
+                    unsigned long seconds = 0;
+                    for (int i = 40; i <= 43; i++)
+                        seconds = (seconds << 8) | buf[i];
+                    set_time(time_t(seconds - 2208988800ULL));
+                    return true;
+                }
+            }
+        }
+
+        return false;
+    }
+
+private:
+    char *server;
+    float timeout;
+};
\ No newline at end of file