diff --git a/include/Clock.h b/include/Clock.h new file mode 100644 index 0000000..2ed163b --- /dev/null +++ b/include/Clock.h @@ -0,0 +1,22 @@ +/* +SPDX-License-Identifier: MIT +Copyright (c) 2023 John Watts and the LuminaSensum contributors +*/ + +#ifndef CLOCK_H +#define CLOCK_H + +#include "NetworkInterface.h" +#include "sntp.h" +#include + +void clock_setup(void); + +struct timeval clock_time(void); + +SNTPError clock_sync(NetworkInterface &net); + +const char *clock_timestring(const char *format); +const char *clock_iso8601string(void); + +#endif diff --git a/src/Clock.cpp b/src/Clock.cpp new file mode 100644 index 0000000..a8d6bf7 --- /dev/null +++ b/src/Clock.cpp @@ -0,0 +1,49 @@ +/* +SPDX-License-Identifier: MIT +Copyright (c) 2023 John Watts and the LuminaSensum contributors +*/ + +#include "Clock.h" + +void clock_setup(void) { + /* TODO: read RTC */ + return; +} + +struct timeval clock_time() { + /* TODO: read RTC */ + struct timeval time = {0}; + return time; +} + +SNTPError clock_sync(NetworkInterface &net) { + struct timeval time; + SNTPError err; + err = sntp(net, "time.google.com", 123, &time); + if (err != SNTPSuccess) { + return err; + } + /* TODO: set RTC */ + return SNTPSuccess; +} + +const char *clock_timestring(const char *format) { + struct timeval time = clock_time(); + struct tm *local_time = localtime(&time.tv_sec); + + static char buffer[64]; + size_t buffer_size = sizeof(buffer); + size_t buffer_written; + buffer_written = strftime(buffer, buffer_size, format, local_time); + + if (buffer_written == 0) { + // It overflowed, so return something useful + return "(time overflow)"; + } else { + return buffer; + } +} + +const char *clock_iso8601string(void) { + return clock_timestring("%Y-%m-%dT%H:%M:%S"); +}