diff --git a/include/Clock.h b/include/Clock.h index a8bcba3..5ea27e4 100644 --- a/include/Clock.h +++ b/include/Clock.h @@ -13,6 +13,7 @@ typedef std::chrono::time_point kernel_timepoint; std::chrono::microseconds kernel_to_real_time(kernel_timepoint time); +kernel_timepoint real_to_kernel_time(std::chrono::microseconds time); void clock_setup(void); SNTPError clock_sync(NetworkInterface &net); diff --git a/src/Clock.cpp b/src/Clock.cpp index aabc005..8a6c4fa 100644 --- a/src/Clock.cpp +++ b/src/Clock.cpp @@ -8,6 +8,10 @@ using namespace std::chrono; +// The kernel's internal clock duration +// As of writing this is a millisecond +typedef Kernel::Clock::duration kernel_duration; + // The time the system started in microseconds since 1970 microseconds boot_start; // Always use this lock to access boot_start @@ -35,6 +39,18 @@ return real_time; } +// Converts microseconds since 1970 to a kernel timepoint +// This is done by subtracting boot_start from the real time passed +// The microseconds will be rounded to the clock's kernel duration +kernel_timepoint real_to_kernel_time(microseconds real_time) { + boot_start_access.lock(); + microseconds uptime = real_time - boot_start; + boot_start_access.unlock(); + kernel_duration uptime_rounded = round(uptime); + kernel_timepoint kernel_time(uptime_rounded); + return kernel_time; +} + // Initializes the clock, run once at boot void clock_setup(void) { // Get RTC time diff --git a/src/main.cpp b/src/main.cpp index 8eb1434..985c200 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -90,6 +90,14 @@ tr_info("The new time is %s", clock_iso8601string_now()); } + // Wait until the nearest second + std::chrono::microseconds future = clock_now(); + future += std::chrono::seconds(1); + future = std::chrono::floor( + future); + kernel_timepoint target = real_to_kernel_time(future); + ThisThread::sleep_until(target); + tr_info("Waited to %s", clock_iso8601string_now()); } }