A time interface class. This class replicates the normal time functions, but goes a couple of steps further. mbed library 82 and prior has a defective gmtime function. Also, this class enables access to setting the time, and adjusting the accuracy of the RTC.
Dependents: CI-data-logger-server WattEye X10Svr SSDP_Server
Diff: TimeInterface.cpp
- Revision:
- 2:65e0a25c7551
- Parent:
- 1:2ee90f546f54
- Child:
- 3:49f36b489b64
--- a/TimeInterface.cpp Sat Jun 14 12:34:53 2014 +0000 +++ b/TimeInterface.cpp Sun Jun 22 21:00:01 2014 +0000 @@ -3,6 +3,20 @@ #include "rtc_api.h" +#define DEBUG "Time" +#include <cstdio> +#if (defined(DEBUG) && !defined(TARGET_LPC11U24)) +#define DBG(x, ...) std::printf("[DBG %s %3d] "x"\r\n", DEBUG, __LINE__, ##__VA_ARGS__); +#define WARN(x, ...) std::printf("[WRN %s %3d] "x"\r\n", DEBUG, __LINE__, ##__VA_ARGS__); +#define ERR(x, ...) std::printf("[ERR %s %3d] "x"\r\n", DEBUG, __LINE__, ##__VA_ARGS__); +#define INFO(x, ...) std::printf("[INF %s %3d] "x"\r\n", DEBUG, __LINE__, ##__VA_ARGS__); +#else +#define DBG(x, ...) +#define WARN(x, ...) +#define ERR(x, ...) +#define INFO(x, ...) +#endif + #ifdef WIN32 // Fake it out for Win32 development and testing struct LPC { @@ -25,6 +39,24 @@ { } +NTPResult TimeInterface::setTime(const char* host, uint16_t port, uint32_t timeout) +{ + NTPClient ntp; + NTPResult res; + int16_t tzomin = get_tzo_min(); + INFO("setTime(%s, %d, %d) %d\r\n", host, port, timeout, tzomin); + res = ntp.setTime(host, port, timeout); + INFO(" ret: %d\r\n", res); + if (res == NTP_OK) { + // if the time was fetched successfully, then + // let's save the time last set with the local tzo applied + // and this saves the last time set for later precision + // tuning. + set_time(std::time(NULL)); + } + return res; +} + clock_t TimeInterface::clock(void) { return std::clock(); @@ -55,7 +87,7 @@ return result; } -char * TimeInterface::asctime(const struct tm_ex *timeptr) +char * TimeInterface::asctime(const struct tm_ex * timeptr) { static const char wday_name[][4] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" @@ -130,10 +162,11 @@ void TimeInterface::set_time(time_t t, int16_t tzo_min) { - time_t tval = t - tzo_min; + time_t tval = t - (tzo_min * 60); rtc_init(); rtc_write(tval); LPC_RTC->GPREG1 = tval; + INFO("set_time(%s)", ctime(&tval)); } void TimeInterface::set_tzo_min(int16_t tzo_min)