Simple Network Time Protocol Client. This lib feature: Access to SNTP server, and get Epoch (Unix) time.
Embed:
(wiki syntax)
Show/hide line numbers
SimpleNTP.h
00001 #pragma once 00002 00003 00004 /** Simple Network Time Protocol Client. 00005 This lib feature: Access to SNTP server, and get Epoch (Unix) time. 00006 00007 When cording, I refered to: 00008 http://www.softech.co.jp/mm_140305_firm.htm 00009 http://www.venus.dti.ne.jp/~yoshi-o/NTP/NTP-SNTP_Format.html 00010 00011 @code 00012 #include "mbed.h" 00013 00014 #include "EthernetInterface.h" 00015 #include "RealTimeClock.h" 00016 #include "SimpleNTP.h" 00017 00018 EthernetInterface ether; 00019 RealTimeClock rtc; 00020 DigitalOut led[]= {LED1, LED2, LED3, LED4}; 00021 00022 void setTime() 00023 { 00024 ether.init(); 00025 ether.connect(); 00026 led[1]= 1; 00027 wait(2); 00028 00029 SimpleNTP sntp; 00030 SimpleNTP::Result resultNTP; 00031 resultNTP= sntp.setNTPServer("ntp.sanoh.com"); 00032 led[2]= 1; 00033 if(resultNTP == SimpleNTP::SUCCESS) { 00034 led[0]= 0; 00035 wait(2); 00036 long timeEpoch= sntp.getNetworkTime(); 00037 if(rtc.setRealTime(timeEpoch)) 00038 led[1]= 0; 00039 } 00040 if(sntp.close() == SimpleNTP::SUCCESS) 00041 led[2]= 0; 00042 return; 00043 } 00044 int main() 00045 { 00046 led[0]= 1; 00047 setTime(); 00048 while(1) { 00049 led[3]= !led[3]; 00050 wait(0.2); 00051 } 00052 } 00053 @endcode 00054 */ 00055 00056 00057 #include "mbed.h" 00058 #include "UDPSocket.h" 00059 #include <string> 00060 00061 00062 class SimpleNTP 00063 { 00064 public: 00065 enum Result { 00066 SUCCESS, 00067 ERR_SocketInit, ERR_SetNTPAddr, 00068 ERR_SocketClose 00069 }; 00070 00071 /** Setting for NTP/SNTP server. 00072 @param _server; IPv4 or URL(with DNS) 00073 @param _port; port of sntp server. 00074 @return enum. 00075 */ 00076 Result setNTPServer(string _server, unsigned short _port= 123); 00077 00078 /** Get NetworkTime Converted Epoch. 00079 * @return epoch(UNIX) time. NOT 1900/01/01~ 00080 */ 00081 long getNetworkTime(); // mbed is 32bit epoch. NOT "UNSIGNED long". 00082 00083 /** close the socket 00084 */ 00085 Result close(); 00086 00087 private: 00088 string server; 00089 unsigned short port; 00090 00091 UDPSocket socket; 00092 Endpoint serverNTP; 00093 00094 };
Generated on Fri Jul 15 2022 06:22:07 by 1.7.2