Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/helpers/AutoDiscoverRTCClock.cpp
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
#include "AutoDiscoverRTCClock.h"
#include "RTCValidity.h"
#include "RTClib.h"
#include <Melopero_RV3028.h>
#include "RTC_RX8130CE.h"
Expand Down Expand Up @@ -30,6 +31,10 @@ void AutoDiscoverRTCClock::begin(TwoWire& wire) {
#if !defined(DISABLE_DS3231_PROBE)
if (i2c_probe(wire, DS3231_ADDRESS)) {
ds3231_success = rtc_3231.begin(&wire);
if (ds3231_success && mesh::seedRTCIfLostPower(rtc_3231.lostPower(), _fallback->getCurrentTime(),
[](uint32_t time) { rtc_3231.adjust(DateTime(time)); })) {
MESH_DEBUG_PRINTLN("DS3231: Lost power, initialized from fallback clock");
}
}
#endif

Expand All @@ -44,6 +49,10 @@ void AutoDiscoverRTCClock::begin(TwoWire& wire) {
if (i2c_probe(wire, PCF8563_ADDRESS)) {
MESH_DEBUG_PRINTLN("PCF8563: Found");
rtc_8563_success = rtc_8563.begin(&wire);
if (rtc_8563_success && mesh::seedRTCIfLostPower(rtc_8563.lostPower(), _fallback->getCurrentTime(),
[](uint32_t time) { rtc_8563.adjust(DateTime(time)); })) {
MESH_DEBUG_PRINTLN("PCF8563: Lost power, initialized from fallback clock");
}
}

if (i2c_probe(wire, RX8130CE_ADDRESS)) {
Expand Down
14 changes: 14 additions & 0 deletions src/helpers/RTCValidity.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#pragma once

#include <stdint.h>

namespace mesh {

template <typename AdjustClock>
bool seedRTCIfLostPower(bool lost_power, uint32_t fallback_time, AdjustClock adjust_clock) {
if (!lost_power) return false;
adjust_clock(fallback_time);
return true;
}

} // namespace mesh
28 changes: 28 additions & 0 deletions test/test_rtc_validity/test_rtc_validity.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#include <gtest/gtest.h>

#include <helpers/RTCValidity.h>

TEST(RTCValidity, SeedsLostPowerClockFromFallback) {
uint32_t adjusted_to = 0;

bool seeded = mesh::seedRTCIfLostPower(true, 1715770351,
[&](uint32_t time) { adjusted_to = time; });

EXPECT_TRUE(seeded);
EXPECT_EQ(1715770351u, adjusted_to);
}

TEST(RTCValidity, PreservesValidBatteryBackedClock) {
bool adjusted = false;

bool seeded = mesh::seedRTCIfLostPower(false, 1715770351,
[&](uint32_t) { adjusted = true; });

EXPECT_FALSE(seeded);
EXPECT_FALSE(adjusted);
}

int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}