AceTimeClock  1.3.0
Clock classes for Arduino that can synchronize from an NTP server or an RTC chip
DS3231Clock.h
1 /*
2  * MIT License
3  * Copyright (c) 2018 Brian T. Park
4  */
5 
6 #ifndef ACE_TIME_DS3231_CLOCK_H
7 #define ACE_TIME_DS3231_CLOCK_H
8 
9 #include <stdint.h>
10 #include <AceTime.h>
11 #include "../hw/DS3231.h"
12 #include "../hw/HardwareDateTime.h"
13 #include "Clock.h"
14 
15 namespace ace_time {
16 namespace clock {
17 
23 template<typename T_WIREI>
24 class DS3231Clock : public Clock {
25  public:
27  explicit DS3231Clock(const T_WIREI& wireInterface) :
28  mDS3231(wireInterface)
29  {}
30 
32  void setup() {}
33 
34  acetime_t getNow() const override {
35  hw::HardwareDateTime hardwareDateTime;
36  mDS3231.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  mDS3231.setDateTime(toHardwareDateTime(now));
45  }
46 
47  private:
52  static LocalDateTime toDateTime(const hw::HardwareDateTime& dt) {
53  return LocalDateTime::forComponents(
55  dt.month,
56  dt.day,
57  dt.hour,
58  dt.minute,
59  dt.second);
60  }
61 
68  static hw::HardwareDateTime toHardwareDateTime(const LocalDateTime& dt) {
69  return hw::HardwareDateTime{
70  (uint8_t) (dt.year() - hw::HardwareDateTime::kBaseYear),
71  dt.month(),
72  dt.day(),
73  dt.hour(),
74  dt.minute(),
75  dt.second(),
76  dt.dayOfWeek()};
77  }
78 
79  private:
80  const hw::DS3231<T_WIREI> mDS3231;
81 };
82 
83 }
84 }
85 
86 #endif
Abstract base class for objects that provide and store time.
Definition: Clock.h:19
static const acetime_t kInvalidSeconds
Error value returned by getNow() and other methods when this object is not yet initialized.
Definition: Clock.h:25
An implementation of Clock that uses a DS3231 RTC chip.
Definition: DS3231Clock.h:24
acetime_t getNow() const override
Return the number of seconds since the AceTime epoch (2000-01-01T00:00:00Z).
Definition: DS3231Clock.h:34
void setup()
Setup that currently does nothing.
Definition: DS3231Clock.h:32
DS3231Clock(const T_WIREI &wireInterface)
Constructor.
Definition: DS3231Clock.h:27
void setNow(acetime_t epochSeconds) override
Set the time to the indicated seconds.
Definition: DS3231Clock.h:40
The date (year, month, day) and time (hour, minute, second) fields supported by the DS3231 RTC chip.
static const int16_t kBaseYear
Base year of the DS3231 chip.
uint8_t year
[00, 99], year - 2000