1 /*
2  * Copyright (c) 2019 Peter Bigot Consulting, LLC
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 /**
8  * @file
9  * @brief Real-time clock control based on the DS3231 counter API.
10  *
11  * The [Maxim
12  * DS3231](https://www.maximintegrated.com/en/products/analog/real-time-clocks/DS3231.html)
13  * is a high-precision real-time clock with temperature-compensated
14  * crystal oscillator and support for configurable alarms.
15  *
16  * The core Zephyr API to this device is as a counter, with the
17  * following limitations:
18  * * counter_read() and counter_*_alarm() cannot be invoked from
19  *   interrupt context, as they require communication with the device
20  *   over an I2C bus.
21  * * many other counter APIs, such as start/stop/set_top_value are not
22  *   supported as the clock is always running.
23  * * two alarm channels are supported but are not equally capable:
24  *   channel 0 supports alarms at 1 s resolution, while channel 1
25  *   supports alarms at 1 minute resolution.
26  *
27  * Most applications for this device will need to use the extended
28  * functionality exposed by this header to access the real-time-clock
29  * features.  The majority of these functions must be invoked from
30  * supervisor mode.
31  */
32 #ifndef ZEPHYR_INCLUDE_DRIVERS_RTC_DS3231_H_
33 #define ZEPHYR_INCLUDE_DRIVERS_RTC_DS3231_H_
34 
35 #include <time.h>
36 
37 #include <zephyr/drivers/counter.h>
38 #include <zephyr/kernel.h>
39 #include <zephyr/types.h>
40 #include <zephyr/sys/notify.h>
41 
42 #ifdef __cplusplus
43 extern "C" {
44 #endif
45 
46 /** @brief Bit in ctrl or ctrl_stat associated with alarm 1. */
47 #define MAXIM_DS3231_ALARM1 BIT(0)
48 
49 /** @brief Bit in ctrl or ctrl_stat associated with alarm 2. */
50 #define MAXIM_DS3231_ALARM2 BIT(1)
51 
52 /* Constants corresponding to bits in the DS3231 control register at
53  * 0x0E.
54  *
55  * See the datasheet for interpretation of these bits.
56  */
57 /** @brief ctrl bit for alarm 1 interrupt enable. */
58 #define MAXIM_DS3231_REG_CTRL_A1IE MAXIM_DS3231_ALARM1
59 
60 /** @brief ctrl bit for alarm 2 interrupt enable. */
61 #define MAXIM_DS3231_REG_CTRL_A2IE MAXIM_DS3231_ALARM2
62 
63 /** @brief ctrl bit for ISQ functionality.
64  *
65  * When clear the ISW signal provides a square wave.  When set the ISW
66  * signal indicates alarm events.
67  *
68  * @note The driver expects to be able to control this bit.
69  */
70 #define MAXIM_DS3231_REG_CTRL_INTCN BIT(2)
71 
72 /** @brief ctrl bit offset for square wave output frequency.
73  *
74  * @note The driver will control the content of this field.
75  */
76 #define MAXIM_DS3231_REG_CTRL_RS_Pos 3
77 
78 /** @brief ctrl mask to isolate RS bits. */
79 #define MAXIM_DS3231_REG_CTRL_RS_Msk (0x03 << MAXIM_DS3231_REG_CTRL_RS_Pos)
80 
81 /** @brief ctrl RS field value for 1 Hz square wave. */
82 #define MAXIM_DS3231_REG_CTRL_RS_1Hz 0x00
83 
84 /** @brief ctrl RS field value for 1024 Hz square wave. */
85 #define MAXIM_DS3231_REG_CTRL_RS_1KiHz 0x01
86 
87 /** @brief ctrl RS field value for 4096 Hz square wave. */
88 #define MAXIM_DS3231_REG_CTRL_RS_4KiHz 0x02
89 
90 /** @brief ctrl RS field value for 8192 Hz square wave. */
91 #define MAXIM_DS3231_REG_CTRL_RS_8KiHz 0x03
92 
93 /** @brief ctrl bit to write to trigger temperature conversion. */
94 #define MAXIM_DS3231_REG_CTRL_CONV BIT(5)
95 
96 /** @brief ctrl bit to write to enable square wave output in battery mode. */
97 #define MAXIM_DS3231_REG_CTRL_BBSQW BIT(6)
98 
99 /** @brief ctrl bit to write to disable the oscillator. */
100 #define MAXIM_DS3231_REG_CTRL_EOSCn BIT(7),
101 
102 /** @brief ctrl_stat bit indicating alarm1 has triggered.
103  *
104  * If an alarm callback handler is registered this bit is
105  * cleared prior to invoking the callback with the flags
106  * indicating which alarms are ready.
107  */
108 #define MAXIM_DS3231_REG_STAT_A1F MAXIM_DS3231_ALARM1
109 
110 /** @brief ctrl_stat bit indicating alarm2 has triggered.
111  *
112  * If an alarm callback handler is registered this bit is
113  * cleared prior to invoking the callback with the flags
114  * indicating which alarms are ready.
115  */
116 #define MAXIM_DS3231_REG_STAT_A2F MAXIM_DS3231_ALARM2
117 
118 /** @brief Flag indicating a temperature conversion is in progress. */
119 #define MAXIM_DS3231_REG_STAT_BSY BIT(2)
120 
121 /** @brief Set to enable 32 KiHz open drain signal.
122  *
123  * @note This is a control bit, though it is positioned within the
124  * ctrl_stat register which otherwise contains status bits.
125  */
126 #define MAXIM_DS3231_REG_STAT_EN32kHz BIT(3)
127 
128 /** @brief Flag indicating the oscillator has been off since last cleared. */
129 #define MAXIM_DS3231_REG_STAT_OSF BIT(7)
130 
131 /** @brief Control alarm behavior on match in seconds field.
132  *
133  * If clear the alarm fires only when the RTC seconds matches the
134  * alarm seconds.
135  *
136  * If set the alarm seconds field is ignored and an alarm will be
137  * triggered every second.  The bits for IGNMN, IGNHR, and IGNDA must
138  * all be set.
139  *
140  * This bit must be clear for the second alarm instance.
141  *
142  * Bit maps to A1M1 and is used in
143  * maxim_ds3231_alarm_configuration::alarm_flags.
144  */
145 #define MAXIM_DS3231_ALARM_FLAGS_IGNSE BIT(0)
146 
147 /** @brief Control alarm behavior on match in minutes field.
148  *
149  * If clear the alarm fires only when the RTC minutes matches the
150  * alarm minutes.  The bit for IGNSE must be clear.
151  *
152  * If set the alarm minutes field is ignored and alarms will be
153  * triggered based on IGNSE. The bits for IGNHR and IGNDA must both be
154  * set.
155  *
156  * Bit maps to A1M2 or A2M2 and is used in
157  * maxim_ds3231_alarm_configuration::alarm_flags.
158  */
159 #define MAXIM_DS3231_ALARM_FLAGS_IGNMN BIT(1)
160 
161 /** @brief Control alarm behavior on match in hours field.
162  *
163  * If clear the alarm fires only when the RTC hours matches the
164  * alarm hours.  The bits for IGNMN and IGNSE must be clear.
165  *
166  * If set the alarm hours field is ignored and alarms will be
167  * triggered based on IGNMN and IGNSE.  The bit for IGNDA must be set.
168  *
169  * Bit maps to A1M3 or A2M3 and is used in
170  * maxim_ds3231_alarm_configuration::alarm_flags.
171  */
172 #define MAXIM_DS3231_ALARM_FLAGS_IGNHR BIT(2)
173 
174 /** @brief Control alarm behavior on match in day/date field.
175  *
176  * If clear the alarm fires only when the RTC day/date matches the
177  * alarm day/date, mediated by MAXIM_DS3231_ALARM_FLAGS_DAY.  The bits
178  * for IGNHR, IGNMN, and IGNSE must be clear
179  *
180  * If set the alarm day/date field is ignored and an alarm will be
181  * triggered based on IGNHR, IGNMN, and IGNSE.
182  *
183  * Bit maps to A1M4 or A2M4 and is used in
184  * maxim_ds3231_alarm_configuration::alarm_flags.
185  */
186 #define MAXIM_DS3231_ALARM_FLAGS_IGNDA BIT(3)
187 
188 /** @brief Control match on day of week versus day of month
189  *
190  * Set the flag to match on day of week; clear it to match on day of
191  * month.
192  *
193  * Bit maps to DY/DTn in corresponding
194  * maxim_ds3231_alarm_configuration::alarm_flags.
195  */
196 #define MAXIM_DS3231_ALARM_FLAGS_DOW BIT(4)
197 
198 /** @brief Indicates that the alarm should be disabled once it fires.
199  *
200  * Set the flag in the maxim_ds3231_alarm_configuration::alarm_flags
201  * field to cause the alarm to be disabled when the interrupt fires,
202  * prior to invoking the corresponding handler.
203  *
204  * Leave false to allow the alarm to remain enabled so it will fire
205  * again on the next match.
206  */
207 #define MAXIM_DS3231_ALARM_FLAGS_AUTODISABLE BIT(7)
208 
209 /**
210  * @brief RTC DS3231 Driver-Specific API
211  * @defgroup rtc_ds3231_interface RTC DS3231 Interface
212  * @ingroup io_interfaces
213  * @{
214  */
215 
216 /** @brief Signature for DS3231 alarm callbacks.
217  *
218  * The alarm callback is invoked from the system work queue thread.
219  * At the point the callback is invoked the corresponding alarm flags
220  * will have been cleared from the device status register.  The
221  * callback is permitted to invoke operations on the device.
222  *
223  * @param dev the device from which the callback originated
224  * @param id the alarm id
225  * @param syncclock the value from maxim_ds3231_read_syncclock() at the
226  * time the alarm interrupt was processed.
227  * @param user_data the corresponding parameter from
228  * maxim_ds3231_alarm::user_data.
229  */
230 typedef void (*maxim_ds3231_alarm_callback_handler_t)(const struct device *dev,
231 						      uint8_t id,
232 						      uint32_t syncclock,
233 						      void *user_data);
234 
235 /** @brief Signature used to notify a user of the DS3231 that an
236  * asynchronous operation has completed.
237  *
238  * Functions compatible with this type are subject to all the
239  * constraints of #sys_notify_generic_callback.
240  *
241  * @param dev the DS3231 device pointer
242  *
243  * @param notify the notification structure provided in the call
244  *
245  * @param res the result of the operation.
246  */
247 typedef void (*maxim_ds3231_notify_callback)(const struct device *dev,
248 					     struct sys_notify *notify,
249 					     int res);
250 
251 /** @brief Information defining the alarm configuration.
252  *
253  * DS3231 alarms can be set to fire at specific times or at the
254  * rollover of minute, hour, day, or day of week.
255  *
256  * When an alarm is configured with a handler an interrupt will be
257  * generated and the handler called from the system work queue.
258  *
259  * When an alarm is configured without a handler, or a persisted alarm
260  * is present, alarms can be read using maxim_ds3231_check_alarms().
261  */
262 struct maxim_ds3231_alarm {
263 	/** @brief Time specification for an RTC alarm.
264 	 *
265 	 * Though specified as a UNIX time, the alarm parameters are
266 	 * determined by converting to civil time and interpreting the
267 	 * component hours, minutes, seconds, day-of-week, and
268 	 * day-of-month fields, mediated by the corresponding #flags.
269 	 *
270 	 * The year and month are ignored, but be aware that gmtime()
271 	 * determines day-of-week based on calendar date.  Decoded
272 	 * alarm times will fall within 1978-01 since 1978-01-01
273 	 * (first of month) was a Sunday (first of week).
274 	 */
275 	time_t time;
276 
277 	/** @brief Handler to be invoked when alarms are signalled.
278 	 *
279 	 * If this is null the alarm will not be triggered by the
280 	 * INTn/SQW GPIO.  This is a "persisted" alarm from its role
281 	 * in using the DS3231 to trigger a wake from deep sleep.  The
282 	 * application should use maxim_ds3231_check_alarms() to
283 	 * determine whether such an alarm has been triggered.
284 	 *
285 	 * If this is not null the driver will monitor the ISW GPIO
286 	 * for alarm signals and will invoke the handler with a
287 	 * parameter carrying the value returned by
288 	 * maxim_ds3231_check_alarms().  The corresponding status flags
289 	 * will be cleared in the device before the handler is
290 	 * invoked.
291 	 *
292 	 * The handler will be invoked from the system work queue.
293 	 */
294 	maxim_ds3231_alarm_callback_handler_t handler;
295 
296 	/** @brief User-provided pointer passed to alarm callback. */
297 	void *user_data;
298 
299 	/** @brief Flags controlling configuration of the alarm alarm.
300 	 *
301 	 * See MAXIM_DS3231_ALARM_FLAGS_IGNSE and related constants.
302 	 *
303 	 * Note that as described the alarm mask fields require that
304 	 * if a unit is not ignored, higher-precision units must also
305 	 * not be ignored.  For example, if match on hours is enabled,
306 	 * match on minutes and seconds must also be enabled.  Failure
307 	 * to comply with this requirement will cause
308 	 * maxim_ds3231_set_alarm() to return an error, leaving the
309 	 * alarm configuration unchanged.
310 	 */
311 	uint8_t flags;
312 };
313 
314 /** @brief Register the RTC clock against system clocks.
315  *
316  * This captures the same instant in both the RTC time scale and a
317  * stable system clock scale, allowing conversion between those
318  * scales.
319  */
320 struct maxim_ds3231_syncpoint {
321 	/** @brief Time from the DS3231.
322 	 *
323 	 * This maybe in UTC, TAI, or local offset depending on how
324 	 * the RTC is maintained.
325 	 */
326 	struct timespec rtc;
327 
328 	/** @brief Value of a local clock at the same instant as #rtc.
329 	 *
330 	 * This is captured from a stable monotonic system clock
331 	 * running at between 1 kHz and 1 MHz, allowing for
332 	 * microsecond to millisecond accuracy in synchronization.
333 	 */
334 	uint32_t syncclock;
335 };
336 
337 /** @brief Read the local synchronization clock.
338  *
339  * Synchronization aligns the DS3231 real-time clock with a stable
340  * monotonic local clock which should have a frequency between 1 kHz
341  * and 1 MHz and be itself synchronized with the primary system time
342  * clock.  The accuracy of the alignment and the maximum time between
343  * synchronization updates is affected by the resolution of this
344  * clock.
345  *
346  * On some systems the hardware clock from k_cycles_get_32() is
347  * suitable, but on others that clock advances too quickly.  The
348  * frequency of the target-specific clock is provided by
349  * maxim_ds3231_syncclock_frequency().
350  *
351  * At this time the value is captured from `k_uptime_get_32()`; future
352  * kernel extensions may make a higher-resolution clock available.
353  *
354  * @note This function is *isr-ok*.
355  *
356  * @param dev the DS3231 device pointer
357  *
358  * @return the current value of the synchronization clock.
359  */
maxim_ds3231_read_syncclock(const struct device * dev)360 static inline uint32_t maxim_ds3231_read_syncclock(const struct device *dev)
361 {
362 	return k_uptime_get_32();
363 }
364 
365 /** @brief Get the frequency of the synchronization clock.
366  *
367  * Provides the frequency of the clock used in maxim_ds3231_read_syncclock().
368  *
369  * @param dev the DS3231 device pointer
370  *
371  * @return the frequency of the selected synchronization clock.
372  */
maxim_ds3231_syncclock_frequency(const struct device * dev)373 static inline uint32_t maxim_ds3231_syncclock_frequency(const struct device *dev)
374 {
375 	return 1000U;
376 }
377 
378 /**
379  * @brief Set and clear specific bits in the control register.
380  *
381  * @note This function assumes the device register cache is valid.  It
382  * will not read the register value, and it will write to the device
383  * only if the value changes as a result of applying the set and clear
384  * changes.
385  *
386  * @note Unlike maxim_ds3231_stat_update() the return value from this
387  * function indicates the register value after changes were made.
388  * That return value is cached for use in subsequent operations.
389  *
390  * @note This function is *supervisor*.
391  *
392  * @return the non-negative updated value of the register, or a
393  * negative error code from an I2C transaction.
394  */
395 int maxim_ds3231_ctrl_update(const struct device *dev,
396 			     uint8_t set_bits,
397 			     uint8_t clear_bits);
398 
399 /**
400  * @brief Read the ctrl_stat register then set and clear bits in it.
401  *
402  * The content of the ctrl_stat register will be read, then the set
403  * and clear bits applied and the result written back to the device
404  * (regardless of whether there appears to be a change in value).
405  *
406  * OSF, A1F, and A2F will be written with 1s if the corresponding bits
407  * do not appear in either @p set_bits or @p clear_bits.  This ensures
408  * that if any flag becomes set between the read and the write that
409  * indicator will not be cleared.
410  *
411  * @note Unlike maxim_ds3231_ctrl_update() the return value from this
412  * function indicates the register value before any changes were made.
413  *
414  * @note This function is *supervisor*.
415  *
416  * @param dev the DS3231 device pointer
417  *
418  * @param set_bits bits to be set when writing back.  Setting bits
419  * other than @ref MAXIM_DS3231_REG_STAT_EN32kHz will have no effect.
420  *
421  * @param clear_bits bits to be cleared when writing back.  Include
422  * the bits for the status flags you want to clear.
423  *
424  * @return the non-negative register value as originally read
425  * (disregarding the effect of clears and sets), or a negative error
426  * code from an I2C transaction.
427  */
428 int maxim_ds3231_stat_update(const struct device *dev,
429 			     uint8_t set_bits,
430 			     uint8_t clear_bits);
431 
432 /** @brief Read a DS3231 alarm configuration.
433  *
434  * The alarm configuration data is read from the device and
435  * reconstructed into the output parameter.
436  *
437  * @note This function is *supervisor*.
438  *
439  * @param dev the DS3231 device pointer.
440  *
441  * @param id the alarm index, which must be 0 (for the 1 s resolution
442  * alarm) or 1 (for the 1 min resolution alarm).
443  *
444  * @param cfg a pointer to a structure into which the configured alarm
445  * data will be stored.
446  *
447  * @return a non-negative value indicating successful conversion, or a
448  * negative error code from an I2C transaction or invalid parameter.
449  */
450 int maxim_ds3231_get_alarm(const struct device *dev,
451 			   uint8_t id,
452 			   struct maxim_ds3231_alarm *cfg);
453 
454 /** @brief Configure a DS3231 alarm.
455  *
456  * The alarm configuration is validated and stored into the device.
457  *
458  * To cancel an alarm use counter_cancel_channel_alarm().
459  *
460  * @note This function is *supervisor*.
461  *
462  * @param dev the DS3231 device pointer.
463  *
464  * @param id 0 Analog to counter index.  @c ALARM1 is 0 and has 1 s
465  * resolution, @c ALARM2 is 1 and has 1 minute resolution.
466  *
467  * @param cfg a pointer to the desired alarm configuration.  Both
468  * alarms are configured; if only one is to change the application
469  * must supply the existing configuration for the other.
470  *
471  * @return a non-negative value on success, or a negative error code
472  * from an I2C transaction or an invalid parameter.
473  */
474 int maxim_ds3231_set_alarm(const struct device *dev,
475 			   uint8_t id,
476 			   const struct maxim_ds3231_alarm *cfg);
477 
478 /** @brief Synchronize the RTC against the local clock.
479  *
480  * The RTC advances one tick per second with no access to sub-second
481  * precision.  Synchronizing clocks at sub-second resolution requires
482  * enabling a 1pps signal then capturing the system clocks in a GPIO
483  * callback.  This function provides that operation.
484  *
485  * Synchronization is performed in asynchronously, and may take as
486  * long as 1 s to complete; notification of completion is provided
487  * through the @p notify parameter.
488  *
489  * Applications should use maxim_ds3231_get_syncpoint() to retrieve the
490  * synchronization data collected by this operation.
491  *
492  * @note This function is *supervisor*.
493  *
494  * @param dev the DS3231 device pointer.
495  *
496  * @param notify pointer to the object used to specify asynchronous
497  * function behavior and store completion information.
498  *
499  * @retval non-negative on success
500  * @retval -EBUSY if a synchronization or set is currently in progress
501  * @retval -EINVAL if notify is not provided
502  * @retval -ENOTSUP if the required interrupt is not configured
503  */
504 int maxim_ds3231_synchronize(const struct device *dev,
505 			     struct sys_notify *notify);
506 
507 /** @brief Request to update the synchronization point.
508  *
509  * This is a variant of maxim_ds3231_synchronize() for use from user
510  * threads.
511  *
512  * @param dev the DS3231 device pointer.
513  *
514  * @param signal pointer to a valid and ready-to-be-signalled
515  * k_poll_signal.  May be NULL to request a synchronization point be
516  * collected without notifying when it has been updated.
517  *
518  * @retval non-negative on success
519  * @retval -EBUSY if a synchronization or set is currently in progress
520  * @retval -ENOTSUP if the required interrupt is not configured
521  */
522 __syscall int maxim_ds3231_req_syncpoint(const struct device *dev,
523 					 struct k_poll_signal *signal);
524 
525 /** @brief Retrieve the most recent synchronization point.
526  *
527  * This function returns the synchronization data last captured using
528  * maxim_ds3231_synchronize().
529  *
530  * @param dev the DS3231 device pointer.
531  *
532  * @param syncpoint where to store the synchronization data.
533  *
534  * @retval non-negative on success
535  * @retval -ENOENT if no syncpoint has been captured
536  */
537 __syscall int maxim_ds3231_get_syncpoint(const struct device *dev,
538 					 struct maxim_ds3231_syncpoint *syncpoint);
539 
540 /** @brief Set the RTC to a time consistent with the provided
541  * synchronization.
542  *
543  * The RTC advances one tick per second with no access to sub-second
544  * precision, and setting the clock resets the internal countdown
545  * chain.  This function implements the magic necessary to set the
546  * clock while retaining as much sub-second accuracy as possible.  It
547  * requires a synchronization point that pairs sub-second resolution
548  * civil time with a local synchronization clock captured at the same
549  * instant.  The set operation may take as long as 1 second to
550  * complete; notification of completion is provided through the @p
551  * notify parameter.
552  *
553  * @note This function is *supervisor*.
554  *
555  * @param dev the DS3231 device pointer.
556  *
557  * @param syncpoint the structure providing the synchronization point.
558  *
559  * @param notify pointer to the object used to specify asynchronous
560  * function behavior and store completion information.
561  *
562  * @retval non-negative on success
563  * @retval -EINVAL if syncpoint or notify are null
564  * @retval -ENOTSUP if the required interrupt signal is not configured
565  * @retval -EBUSY if a synchronization or set is currently in progress
566  */
567 int maxim_ds3231_set(const struct device *dev,
568 		     const struct maxim_ds3231_syncpoint *syncpoint,
569 		     struct sys_notify *notify);
570 
571 /** @brief Check for and clear flags indicating that an alarm has
572  * fired.
573  *
574  * Returns a mask indicating alarms that are marked as having fired,
575  * and clears from stat the flags that it found set.  Alarms that have
576  * been configured with a callback are not represented in the return
577  * value.
578  *
579  * This API may be used when a persistent alarm has been programmed.
580  *
581  * @note This function is *supervisor*.
582  *
583  * @param dev the DS3231 device pointer.
584  *
585  * @return a non-negative value that may have MAXIM_DS3231_ALARM1 and/or
586  * MAXIM_DS3231_ALARM2 set, or a negative error code.
587  */
588 int maxim_ds3231_check_alarms(const struct device *dev);
589 
590 /**
591  * @}
592  */
593 
594 #ifdef __cplusplus
595 }
596 #endif
597 
598 /* @todo this should be syscalls/drivers/rtc/maxim_ds3231.h */
599 #include <syscalls/maxim_ds3231.h>
600 
601 #endif /* ZEPHYR_INCLUDE_DRIVERS_RTC_DS3231_H_ */
602