AceTimeClock  1.0.3
Clock classes for Arduino that can synchronize from an NTP server or an RTC chip
StmRtcClock.h
1 /*
2  * MIT License
3  * Copyright (c) 2020 Brian T. Park, Anatoli Arkhipenko
4  *
5  * Requires https://github.com/stm32duino/STM32RTC
6  */
7 
8 #ifndef ACE_TIME_STM_RTC_CLOCK_H
9 #define ACE_TIME_STM_RTC_CLOCK_H
10 
11 #if ! defined(EPOXY_DUINO)
12 #if defined(ARDUINO_ARCH_STM32)
13 
14 #include <stdint.h>
15 #include <AceTime.h> // LocalDateTime
16 #include "../hw/StmRtc.h"
17 #include "../hw/HardwareDateTime.h"
18 #include "Clock.h"
19 
20 namespace ace_time {
21 namespace clock {
22 
28 class StmRtcClock: public Clock {
29  public:
30  explicit StmRtcClock() {}
31 
32  void setup() {}
33 
34  acetime_t getNow() const override {
35  hw::HardwareDateTime hardwareDateTime;
36  mStmRtc.readDateTime(&hardwareDateTime);
37  return toDateTime(hardwareDateTime).toEpochSeconds();
38  }
39 
40  void setNow(acetime_t epochSeconds) override {
41  if (epochSeconds == kInvalidSeconds) return;
42 
43  LocalDateTime now = LocalDateTime::forEpochSeconds(epochSeconds);
44  mStmRtc.setDateTime(toHardwareDateTime(now));
45  }
46 
48  bool isTimeSet() const {
49  return mStmRtc.isTimeSet();
50  }
51 
52  private:
57  static LocalDateTime toDateTime(const hw::HardwareDateTime& dt) {
58  return LocalDateTime::forComponents(
59  dt.year + LocalDate::kEpochYear, dt.month, dt.day,
60  dt.hour, dt.minute, dt.second);
61  }
62 
68  static hw::HardwareDateTime toHardwareDateTime(const LocalDateTime& dt) {
69  return hw::HardwareDateTime{(uint8_t) dt.yearTiny(), dt.month(),
70  dt.day(), dt.hour(), dt.minute(), dt.second(), dt.dayOfWeek()};
71  }
72 
73  const hw::StmRtc mStmRtc;
74 };
75 
76 } // hw
77 } // ace_time
78 
79 #endif // #if defined(ARDUINO_ARCH_STM32)
80 #endif // #if ! defined(EPOXY_DUINO)
81 #endif // #ifndef ACE_TIME_STM_RTC_CLOCK_H