Simple Network Time Protocol Client. This lib feature: Access to SNTP server, and get Epoch (Unix) time.

SimpleNTP.h

Committer:
AkinoriHashimoto
Date:
2015-11-27
Revision:
1:b5a2e4532331
Parent:
0:2be905de8e28

File content as of revision 1:b5a2e4532331:

#pragma once


/** Simple Network Time Protocol Client.
This lib feature: Access to SNTP server, and get Epoch (Unix) time.

When cording, I refered to:
http://www.softech.co.jp/mm_140305_firm.htm
http://www.venus.dti.ne.jp/~yoshi-o/NTP/NTP-SNTP_Format.html

 @code
#include "mbed.h"

#include "EthernetInterface.h"
#include "RealTimeClock.h"
#include "SimpleNTP.h"

EthernetInterface ether;
RealTimeClock rtc;
DigitalOut led[]= {LED1, LED2, LED3, LED4};

void setTime()
{
    ether.init();
    ether.connect();
    led[1]= 1;
    wait(2);

    SimpleNTP sntp;
    SimpleNTP::Result resultNTP;
    resultNTP= sntp.setNTPServer("ntp.sanoh.com");
    led[2]= 1;
    if(resultNTP == SimpleNTP::SUCCESS) {
        led[0]= 0;
        wait(2);
        long timeEpoch= sntp.getNetworkTime();
        if(rtc.setRealTime(timeEpoch))
            led[1]= 0;
    }
    if(sntp.close() == SimpleNTP::SUCCESS)
        led[2]= 0;
    return;
}
int main()
{
    led[0]= 1;
    setTime();
    while(1) {
        led[3]= !led[3];
        wait(0.2);
    }
}
 @endcode
 */


#include "mbed.h"
#include "UDPSocket.h"
#include <string>


class SimpleNTP
{
public:
    enum Result {
        SUCCESS,
        ERR_SocketInit, ERR_SetNTPAddr,
        ERR_SocketClose
    };

    /** Setting for NTP/SNTP server.
        @param _server; IPv4 or URL(with DNS)
        @param _port;   port of sntp server.
        @return enum.
     */
    Result setNTPServer(string _server, unsigned short _port= 123);

    /** Get NetworkTime Converted Epoch.
     *  @return epoch(UNIX) time. NOT 1900/01/01~
     */
    long getNetworkTime();     // mbed is 32bit epoch. NOT "UNSIGNED long".

    /** close the socket
     */
    Result close();

private:
    string server;
    unsigned short port;

    UDPSocket socket;
    Endpoint serverNTP;

};