1 /*
2  * Copyright (c) 2020 Raspberry Pi (Trading) Ltd.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #ifndef _PICO_TIME_H
8 #define _PICO_TIME_H
9 
10 #include "pico.h"
11 #include "hardware/timer.h"
12 
13 #ifdef __cplusplus
14 extern "C" {
15 #endif
16 
17 /** \file time.h
18  *  \defgroup pico_time pico_time
19  *
20  * API for accurate timestamps, sleeping, and time based callbacks
21  *
22  * \note The functions defined here provide a much more powerful and user friendly wrapping around the
23  * low level hardware timer functionality. For these functions (and any other SDK functionality
24  * e.g. timeouts, that relies on them) to work correctly, the hardware timer should not be modified. i.e. it is expected
25  * to be monotonically increasing once per microsecond. Fortunately there is no need to modify the hardware
26  * timer as any functionality you can think of that isn't already covered here can easily be modelled
27  * by adding or subtracting a constant value from the unmodified hardware timer.
28  *
29  * \sa \ref hardware_timer
30  */
31 
32 // PICO_CONFIG: PARAM_ASSERTIONS_ENABLED_TIME, Enable/disable assertions in the time module, type=bool, default=0, group=pico_time
33 #ifndef PARAM_ASSERTIONS_ENABLED_TIME
34 #define PARAM_ASSERTIONS_ENABLED_TIME 0
35 #endif
36 
37 // PICO_CONFIG: PICO_TIME_SLEEP_OVERHEAD_ADJUST_US, How many microseconds to wake up early (and then busy_wait) to account for timer overhead when sleeping in low power mode, type=int, default=6, group=pico_time
38 #ifndef PICO_TIME_SLEEP_OVERHEAD_ADJUST_US
39 #define PICO_TIME_SLEEP_OVERHEAD_ADJUST_US 6
40 #endif
41 /*!
42  * \defgroup timestamp timestamp
43  *  \ingroup pico_time
44  * \brief Timestamp functions relating to points in time (including the current time)
45  *
46  * These are functions for dealing with timestamps (i.e. instants in time) represented by the type absolute_time_t. This opaque
47  * type is provided to help prevent accidental mixing of timestamps and relative time values.
48  */
49 
50 /*! \brief Return a representation of the current time.
51  * \ingroup timestamp
52  *
53  * Returns an opaque high fidelity representation of the current time sampled during the call.
54  *
55  * \return the absolute time (now) of the hardware timer
56  *
57  * \sa absolute_time_t
58  * \sa sleep_until()
59  * \sa time_us_64()
60  */
get_absolute_time(void)61 static inline absolute_time_t get_absolute_time(void) {
62     absolute_time_t t;
63     update_us_since_boot(&t, time_us_64());
64     return t;
65 }
66 
us_to_ms(uint64_t us)67 static inline uint32_t us_to_ms(uint64_t us) {
68     if (us >> 32u) {
69         return (uint32_t)(us / 1000u);
70     } else {
71         return ((uint32_t)us) / 1000u;
72     }
73 }
74 
75 /*! fn to_ms_since_boot
76  * \ingroup timestamp
77  * \brief Convert a timestamp into a number of milliseconds since boot.
78  * \param t an absolute_time_t value to convert
79  * \return the number of milliseconds since boot represented by t
80  * \sa to_us_since_boot()
81  */
to_ms_since_boot(absolute_time_t t)82 static inline uint32_t to_ms_since_boot(absolute_time_t t) {
83     uint64_t us = to_us_since_boot(t);
84     return us_to_ms(us);
85 }
86 
87 /*! \brief Return a timestamp value obtained by adding a number of microseconds to another timestamp
88  * \ingroup timestamp
89  *
90  * \param t the base timestamp
91  * \param us the number of microseconds to add
92  * \return the timestamp representing the resulting time
93  */
delayed_by_us(const absolute_time_t t,uint64_t us)94 static inline absolute_time_t delayed_by_us(const absolute_time_t t, uint64_t us) {
95     absolute_time_t t2;
96     uint64_t base = to_us_since_boot(t);
97     uint64_t delayed = base + us;
98     if ((int64_t)delayed < 0) {
99         // absolute_time_t (to allow for signed time deltas) is never greater than INT64_MAX which == at_the_end_of_time
100         delayed = INT64_MAX;
101     }
102     update_us_since_boot(&t2, delayed);
103     return t2;
104 }
105 
106 /*! \brief Return a timestamp value obtained by adding a number of milliseconds to another timestamp
107  * \ingroup timestamp
108  *
109  * \param t the base timestamp
110  * \param ms the number of milliseconds to add
111  * \return the timestamp representing the resulting time
112  */
delayed_by_ms(const absolute_time_t t,uint32_t ms)113 static inline absolute_time_t delayed_by_ms(const absolute_time_t t, uint32_t ms) {
114     absolute_time_t t2;
115     uint64_t base = to_us_since_boot(t);
116     uint64_t delayed = base + ms * 1000ull;
117     if ((int64_t)delayed < 0) {
118         // absolute_time_t (to allow for signed time deltas) is never greater than INT64_MAX which == at_the_end_of_time
119         delayed = INT64_MAX;
120     }
121     update_us_since_boot(&t2, delayed);
122     return t2;
123 }
124 
125 /*! \brief Convenience method to get the timestamp a number of microseconds from the current time
126  * \ingroup timestamp
127  *
128  * \param us the number of microseconds to add to the current timestamp
129  * \return the future timestamp
130  */
make_timeout_time_us(uint64_t us)131 static inline absolute_time_t make_timeout_time_us(uint64_t us) {
132     return delayed_by_us(get_absolute_time(), us);
133 }
134 
135 /*! \brief Convenience method to get the timestamp a number of milliseconds from the current time
136  * \ingroup timestamp
137  *
138  * \param ms the number of milliseconds to add to the current timestamp
139  * \return the future timestamp
140  */
make_timeout_time_ms(uint32_t ms)141 static inline absolute_time_t make_timeout_time_ms(uint32_t ms) {
142     return delayed_by_ms(get_absolute_time(), ms);
143 }
144 
145 /*! \brief Return the difference in microseconds between two timestamps
146  * \ingroup timestamp
147  *
148  * \note be careful when diffing against large timestamps (e.g. \ref at_the_end_of_time)
149  * as the signed integer may overflow.
150  *
151  * \param from the first timestamp
152  * \param to the second timestamp
153  * \return the number of microseconds between the two timestamps (positive if `to` is after `from` except
154  * in case of overflow)
155  */
absolute_time_diff_us(absolute_time_t from,absolute_time_t to)156 static inline int64_t absolute_time_diff_us(absolute_time_t from, absolute_time_t to) {
157     return (int64_t)(to_us_since_boot(to) - to_us_since_boot(from));
158 }
159 
160 /*! \brief Return the earlier of two timestamps
161  * \ingroup timestamp
162  *
163  * \param a the first timestamp
164  * \param b the second timestamp
165  * \return the earlier of the two timestamps
166  */
absolute_time_min(absolute_time_t a,absolute_time_t b)167 static inline absolute_time_t absolute_time_min(absolute_time_t a, absolute_time_t b) {
168     return to_us_since_boot(a) < to_us_since_boot(b) ? a : b;
169 }
170 
171 /*! \brief The timestamp representing the end of time; this is actually not the maximum possible
172  * timestamp, but is set to 0x7fffffff_ffffffff microseconds to avoid sign overflows with time
173  * arithmetic. This is almost 300,000 years, so should be sufficient.
174  * \ingroup timestamp
175  */
176 extern const absolute_time_t at_the_end_of_time;
177 
178 /*! \brief Determine if the given timestamp is "at_the_end_of_time"
179  * \ingroup timestamp
180  *  \param t the timestamp
181  *  \return true if the timestamp is at_the_end_of_time
182  *  \sa at_the_end_of_time
183  */
is_at_the_end_of_time(absolute_time_t t)184 static inline bool is_at_the_end_of_time(absolute_time_t t) {
185     return to_us_since_boot(t) == to_us_since_boot(at_the_end_of_time);
186 }
187 
188 /*! \brief The timestamp representing a null timestamp
189  * \ingroup timestamp
190  */
191 extern const absolute_time_t nil_time;
192 
193 /*! \brief Determine if the given timestamp is nil
194  * \ingroup timestamp
195  *  \param t the timestamp
196  *  \return true if the timestamp is nil
197  *  \sa nil_time
198  */
is_nil_time(absolute_time_t t)199 static inline bool is_nil_time(absolute_time_t t) {
200     return !to_us_since_boot(t);
201 }
202 
203 /*!
204  * \defgroup sleep sleep
205  * \ingroup pico_time
206  * \brief Sleep functions for delaying execution in a lower power state.
207  *
208  * These functions allow the calling core to sleep. This is a lower powered sleep; waking and re-checking time on every processor
209  * event (WFE)
210  *
211  * \note  These functions should not be called from an IRQ handler.
212  *
213  * \note  Lower powered sleep requires use of the \link alarm_pool_get_default default alarm pool\endlink which may
214  * be disabled by the PICO_TIME_DEFAULT_ALARM_POOL_DISABLED #define or currently full in which case these functions
215  * become busy waits instead.
216  *
217  * \note  Whilst \a sleep_ functions are preferable to \a busy_wait functions from a power perspective, the \a busy_wait equivalent function
218  * may return slightly sooner after the target is reached.
219  *
220  * \sa busy_wait_until() \sa busy_wait_us() \sa busy_wait_us_32()
221  */
222 
223 /*! \brief Wait until after the given timestamp to return
224  * \ingroup sleep
225  *
226  * \note  This method attempts to perform a lower power (WFE) sleep
227  *
228  * \param target the time after which to return
229  * \sa sleep_us()
230  * \sa busy_wait_until()
231  * */
232 void sleep_until(absolute_time_t target);
233 
234 /*! \brief Wait for the given number of microseconds before returning
235  * \ingroup sleep
236  *
237  * \note This method attempts to perform a lower power (WFE) sleep
238  *
239  * \param us the number of microseconds to sleep
240  * \sa busy_wait_us()
241  */
242 void sleep_us(uint64_t us);
243 
244 /*! \brief Wait for the given number of milliseconds before returning
245  * \ingroup sleep
246  *
247  * \note This method attempts to perform a lower power sleep (using WFE) as much as possible.
248  *
249  * \param ms the number of milliseconds to sleep
250  */
251 void sleep_ms(uint32_t ms);
252 
253 /*! \brief Helper method for blocking on a timeout
254  * \ingroup sleep
255  *
256  * This method will return in response to an event (as per __wfe) or
257  * when the target time is reached, or at any point before.
258  *
259  * This method can be used to implement a lower power polling loop waiting on
260  * some condition signalled by an event (__sev()).
261  *
262  * This is called \a best_effort because under certain circumstances (notably the default timer pool
263  * being disabled or full) the best effort is simply to return immediately without a __wfe, thus turning the calling
264  * code into a busy wait.
265  *
266  * Example usage:
267  * ```c
268  * bool my_function_with_timeout_us(uint64_t timeout_us) {
269  *     absolute_time_t timeout_time = make_timeout_time_us(timeout_us);
270  *     do {
271  *         // each time round the loop, we check to see if the condition
272  *         // we are waiting on has happened
273  *         if (my_check_done()) {
274  *             // do something
275  *             return true;
276  *         }
277  *         // will try to sleep until timeout or the next processor event
278  *     } while (!best_effort_wfe_or_timeout(timeout_time));
279  *     return false; // timed out
280  * }
281  * ```
282  *
283  * @param timeout_timestamp the timeout time
284  * @return true if the target time is reached, false otherwise
285  */
286 bool best_effort_wfe_or_timeout(absolute_time_t timeout_timestamp);
287 
288 /*!
289  * \defgroup alarm alarm
290  * \ingroup pico_time
291  * \brief Alarm functions for scheduling future execution
292  *
293  *  Alarms are added to alarm pools, which may hold a certain fixed number of active alarms. Each alarm pool
294  *  utilizes one of four underlying hardware alarms, thus you may have up to four alarm pools. An alarm pool
295  *  calls (except when the callback would happen before or during being set) the callback on the core from which
296  *  the alarm pool was created. Callbacks are called from the hardware alarm IRQ handler, so care must
297  *  be taken in their implementation.
298  *
299  *  A default pool is created  the core specified by PICO_TIME_DEFAULT_ALARM_POOL_HARDWARE_ALARM_NUM
300  *  on core 0, and may be used by the method variants that take no alarm pool parameter.
301  *
302  * \sa struct alarm_pool
303  * \sa hardware_timer
304  */
305 
306 // PICO_CONFIG: PICO_TIME_DEFAULT_ALARM_POOL_DISABLED, Disable the default alarm pool, type=bool, default=0, advanced=true, group=pico_time
307 #ifndef PICO_TIME_DEFAULT_ALARM_POOL_DISABLED
308 /*!
309  * \brief If 1 then the default alarm pool is disabled (so no hardware alarm is claimed for the pool)
310  *
311  * \note Setting to 1 may cause some code not to compile as default timer pool related methods are removed
312  *
313  * \note When the default alarm pool is disabled, \a sleep_ methods and timeouts are no longer lower powered
314  * (they become \a busy_wait_)
315  *
316  * \ingroup alarm
317  * \sa #PICO_TIME_DEFAULT_ALARM_POOL_HARDWARE_ALARM_NUM
318  * \sa alarm_pool_get_default()
319  */
320 #define PICO_TIME_DEFAULT_ALARM_POOL_DISABLED 0
321 #endif
322 
323 // PICO_CONFIG: PICO_TIME_DEFAULT_ALARM_POOL_HARDWARE_ALARM_NUM, Select which HW alarm is used for the default alarm pool, min=0, max=3, default=3, advanced=true, group=pico_time
324 #ifndef PICO_TIME_DEFAULT_ALARM_POOL_HARDWARE_ALARM_NUM
325 /*!
326  * \brief Selects which hardware alarm is used for the default alarm pool
327  * \ingroup alarm
328  * \sa alarm_pool_get_default()
329  */
330 #define PICO_TIME_DEFAULT_ALARM_POOL_HARDWARE_ALARM_NUM 3
331 #endif
332 
333 // PICO_CONFIG: PICO_TIME_DEFAULT_ALARM_POOL_MAX_TIMERS, Selects the maximum number of concurrent timers in the default alarm pool, min=0, max=255, default=16, advanced=true, group=pico_time
334 #ifndef PICO_TIME_DEFAULT_ALARM_POOL_MAX_TIMERS
335 /*!
336  * \brief Selects the maximum number of concurrent timers in the default alarm pool
337  * \ingroup alarm
338  *
339  * \note For implementation reasons this is limited to PICO_PHEAP_MAX_ENTRIES which defaults to 255
340  * \sa #PICO_TIME_DEFAULT_ALARM_POOL_HARDWARE_ALARM_NUM
341  * \sa alarm_pool_get_default()
342  */
343 #define PICO_TIME_DEFAULT_ALARM_POOL_MAX_TIMERS 16
344 #endif
345 
346 /**
347  * \brief The identifier for an alarm
348  *
349  * \note this identifier is signed because -1 is used as an error condition when creating alarms
350  *
351  * \note alarm ids may be reused, however for convenience the implementation makes an attempt to defer
352  * reusing as long as possible. You should certainly expect it to be hundreds of ids before one is
353  * reused, although in most cases it is more. Nonetheless care must still be taken when cancelling
354  * alarms or other functionality based on alarms when the alarm may have expired, as eventually
355  * the alarm id may be reused for another alarm.
356  *
357  * \ingroup alarm
358  */
359 typedef int32_t alarm_id_t; // note this is signed because we use -1 as a meaningful error value
360 
361 /**
362  * \brief User alarm callback
363  * \ingroup alarm
364  * \param id the alarm_id as returned when the alarm was added
365  * \param user_data the user data passed when the alarm was added
366  * \return <0 to reschedule the same alarm this many us from the time the alarm was previously scheduled to fire
367  * \return >0 to reschedule the same alarm this many us from the time this method returns
368  * \return 0 to not reschedule the alarm
369  */
370 typedef int64_t (*alarm_callback_t)(alarm_id_t id, void *user_data);
371 
372 typedef struct alarm_pool alarm_pool_t;
373 
374 /**
375  * \brief Create the default alarm pool (if not already created or disabled)
376  * \ingroup alarm
377  */
378 void alarm_pool_init_default(void);
379 
380 #if !PICO_TIME_DEFAULT_ALARM_POOL_DISABLED
381 /*!
382  * \brief The default alarm pool used when alarms are added without specifying an alarm pool,
383  *        and also used by the SDK to support lower power sleeps and timeouts.
384  *
385  * \ingroup alarm
386  * \sa #PICO_TIME_DEFAULT_ALARM_POOL_HARDWARE_ALARM_NUM
387  */
388 alarm_pool_t *alarm_pool_get_default(void);
389 #endif
390 
391 /**
392  * \brief Create an alarm pool
393  *
394  * The alarm pool will call callbacks from an alarm IRQ Handler on the core of this function is called from.
395  *
396  * In many situations there is never any need for anything other than the default alarm pool, however you
397  * might want to create another if you want alarm callbacks on core 1 or require alarm pools of
398  * different priority (IRQ priority based preemption of callbacks)
399  *
400  * \note This method will hard assert if the hardware alarm is already claimed.
401  *
402  * \ingroup alarm
403  * \param hardware_alarm_num the hardware alarm to use to back this pool
404  * \param max_timers the maximum number of timers
405  *        \note For implementation reasons this is limited to PICO_PHEAP_MAX_ENTRIES which defaults to 255
406  * \sa alarm_pool_get_default()
407  * \sa hardware_claiming
408  */
409 alarm_pool_t *alarm_pool_create(uint hardware_alarm_num, uint max_timers);
410 
411 /**
412  * \brief Create an alarm pool, claiming an used hardware alarm to back it.
413  *
414  * The alarm pool will call callbacks from an alarm IRQ Handler on the core of this function is called from.
415  *
416  * In many situations there is never any need for anything other than the default alarm pool, however you
417  * might want to create another if you want alarm callbacks on core 1 or require alarm pools of
418  * different priority (IRQ priority based preemption of callbacks)
419  *
420  * \note This method will hard assert if the there is no free hardware to claim.
421  *
422  * \ingroup alarm
423  * \param max_timers the maximum number of timers
424  *        \note For implementation reasons this is limited to PICO_PHEAP_MAX_ENTRIES which defaults to 255
425  * \sa alarm_pool_get_default()
426  * \sa hardware_claiming
427  */
428 alarm_pool_t *alarm_pool_create_with_unused_hardware_alarm(uint max_timers);
429 
430 /**
431  * \brief Return the hardware alarm used by an alarm pool
432  * \ingroup alarm
433  * \param pool the pool
434  * \return the hardware alarm used by the pool
435  */
436 uint alarm_pool_hardware_alarm_num(alarm_pool_t *pool);
437 
438 /**
439  * \brief Return the core number the alarm pool was initialized on (and hence callbacks are called on)
440  * \ingroup alarm
441  * \param pool the pool
442  * \return the core used by the pool
443  */
444 uint alarm_pool_core_num(alarm_pool_t *pool);
445 
446 /**
447  * \brief Destroy the alarm pool, cancelling all alarms and freeing up the underlying hardware alarm
448  * \ingroup alarm
449  * \param pool the pool
450  */
451 void alarm_pool_destroy(alarm_pool_t *pool);
452 
453 /*!
454  * \brief Add an alarm callback to be called at a specific time
455  * \ingroup alarm
456  *
457  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
458  * on the core the alarm pool was created on. If the callback is in the past or happens before
459  * the alarm setup could be completed, then this method will optionally call the callback itself
460  * and then return a return code to indicate that the target time has passed.
461  *
462  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
463  *
464  * @param pool the alarm pool to use for scheduling the callback (this determines which hardware alarm is used, and which core calls the callback)
465  * @param time the timestamp when (after which) the callback should fire
466  * @param callback the callback function
467  * @param user_data user data to pass to the callback function
468  * @param fire_if_past if true, and the alarm time falls before or during this call before the alarm can be set,
469  *                     then the callback should be called during (by) this function instead
470  * @return >0 the alarm id for an active (at the time of return) alarm
471  * @return 0 if the alarm time passed before or during the call AND there is no active alarm to return the id of.
472  *           The latter can either happen because fire_if_past was false (i.e. no timer was ever created),
473  *           or if the callback <i>was</i> called during this method but the callback cancelled itself by returning 0
474  * @return -1 if there were no alarm slots available
475  */
476 alarm_id_t alarm_pool_add_alarm_at(alarm_pool_t *pool, absolute_time_t time, alarm_callback_t callback, void *user_data, bool fire_if_past);
477 
478 /*!
479  * \brief Add an alarm callback to be called at or after a specific time
480  * \ingroup alarm
481  *
482  * The callback is called as soon as possible after the time specified from an IRQ handler
483  * on the core the alarm pool was created on. Unlike \ref alarm_pool_add_alarm_at, this method
484  * guarantees to call the callback from that core even if the time is during this method call or in the past.
485  *
486  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
487  *
488  * @param pool the alarm pool to use for scheduling the callback (this determines which hardware alarm is used, and which core calls the callback)
489  * @param time the timestamp when (after which) the callback should fire
490  * @param callback the callback function
491  * @param user_data user data to pass to the callback function
492  * @return >0 the alarm id for an active (at the time of return) alarm
493  * @return -1 if there were no alarm slots available
494  */
495 alarm_id_t alarm_pool_add_alarm_at_force_in_context(alarm_pool_t *pool, absolute_time_t time, alarm_callback_t callback,
496                                                     void *user_data);
497 /*!
498  * \brief Add an alarm callback to be called after a delay specified in microseconds
499  * \ingroup alarm
500  *
501  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
502  * on the core the alarm pool was created on. If the callback is in the past or happens before
503  * the alarm setup could be completed, then this method will optionally call the callback itself
504  * and then return a return code to indicate that the target time has passed.
505  *
506  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
507  *
508  * @param pool the alarm pool to use for scheduling the callback (this determines which hardware alarm is used, and which core calls the callback)
509  * @param us the delay (from now) in microseconds when (after which) the callback should fire
510  * @param callback the callback function
511  * @param user_data user data to pass to the callback function
512  * @param fire_if_past if true, and the alarm time falls during this call before the alarm can be set,
513  *                     then the callback should be called during (by) this function instead
514  * @return >0 the alarm id
515  * @return 0 if the alarm time passed before or during the call AND there is no active alarm to return the id of.
516  *           The latter can either happen because fire_if_past was false (i.e. no timer was ever created),
517  *           or if the callback <i>was</i> called during this method but the callback cancelled itself by returning 0
518  * @return -1 if there were no alarm slots available
519  */
alarm_pool_add_alarm_in_us(alarm_pool_t * pool,uint64_t us,alarm_callback_t callback,void * user_data,bool fire_if_past)520 static inline alarm_id_t alarm_pool_add_alarm_in_us(alarm_pool_t *pool, uint64_t us, alarm_callback_t callback, void *user_data, bool fire_if_past) {
521     return alarm_pool_add_alarm_at(pool, delayed_by_us(get_absolute_time(), us), callback, user_data, fire_if_past);
522 }
523 
524 /*!
525  * \brief Add an alarm callback to be called after a delay specified in milliseconds
526  * \ingroup alarm
527  *
528  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
529  * on the core the alarm pool was created on. If the callback is in the past or happens before
530  * the alarm setup could be completed, then this method will optionally call the callback itself
531  * and then return a return code to indicate that the target time has passed.
532  *
533  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
534  *
535  * @param pool the alarm pool to use for scheduling the callback (this determines which hardware alarm is used, and which core calls the callback)
536  * @param ms the delay (from now) in milliseconds when (after which) the callback should fire
537  * @param callback the callback function
538  * @param user_data user data to pass to the callback function
539  * @param fire_if_past if true, and the alarm time falls before or during this call before the alarm can be set,
540  *                     then the callback should be called during (by) this function instead
541  * @return >0 the alarm id
542  * @return 0 if the alarm time passed before or during the call AND there is no active alarm to return the id of.
543  *           The latter can either happen because fire_if_past was false (i.e. no timer was ever created),
544  *           or if the callback <i>was</i> called during this method but the callback cancelled itself by returning 0
545  * @return -1 if there were no alarm slots available
546  */
alarm_pool_add_alarm_in_ms(alarm_pool_t * pool,uint32_t ms,alarm_callback_t callback,void * user_data,bool fire_if_past)547 static inline alarm_id_t alarm_pool_add_alarm_in_ms(alarm_pool_t *pool, uint32_t ms, alarm_callback_t callback, void *user_data, bool fire_if_past) {
548     return alarm_pool_add_alarm_at(pool, delayed_by_ms(get_absolute_time(), ms), callback, user_data, fire_if_past);
549 }
550 
551 /*!
552  * \brief Cancel an alarm
553  * \ingroup alarm
554  * \param pool the alarm_pool containing the alarm
555  * \param alarm_id the alarm
556  * \return true if the alarm was cancelled, false if it didn't exist
557  * \sa alarm_id_t for a note on reuse of IDs
558  */
559 bool alarm_pool_cancel_alarm(alarm_pool_t *pool, alarm_id_t alarm_id);
560 
561 #if !PICO_TIME_DEFAULT_ALARM_POOL_DISABLED
562 /*!
563  * \brief Add an alarm callback to be called at a specific time
564  * \ingroup alarm
565  *
566  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
567  * on the core of the default alarm pool (generally core 0). If the callback is in the past or happens before
568  * the alarm setup could be completed, then this method will optionally call the callback itself
569  * and then return a return code to indicate that the target time has passed.
570  *
571  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
572  *
573  * @param time the timestamp when (after which) the callback should fire
574  * @param callback the callback function
575  * @param user_data user data to pass to the callback function
576  * @param fire_if_past if true, and the alarm time falls before or during this call before the alarm can be set,
577  *                     then the callback should be called during (by) this function instead
578  * @return >0 the alarm id
579  * @return 0 if the alarm time passed before or during the call AND there is no active alarm to return the id of.
580  *           The latter can either happen because fire_if_past was false (i.e. no timer was ever created),
581  *           or if the callback <i>was</i> called during this method but the callback cancelled itself by returning 0
582  * @return -1 if there were no alarm slots available
583  */
add_alarm_at(absolute_time_t time,alarm_callback_t callback,void * user_data,bool fire_if_past)584 static inline alarm_id_t add_alarm_at(absolute_time_t time, alarm_callback_t callback, void *user_data, bool fire_if_past) {
585     return alarm_pool_add_alarm_at(alarm_pool_get_default(), time, callback, user_data, fire_if_past);
586 }
587 
588 /*!
589  * \brief Add an alarm callback to be called after a delay specified in microseconds
590  * \ingroup alarm
591  *
592  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
593  * on the core of the default alarm pool (generally core 0). If the callback is in the past or happens before
594  * the alarm setup could be completed, then this method will optionally call the callback itself
595  * and then return a return code to indicate that the target time has passed.
596  *
597  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
598  *
599  * @param us the delay (from now) in microseconds when (after which) the callback should fire
600  * @param callback the callback function
601  * @param user_data user data to pass to the callback function
602  * @param fire_if_past if true, and the alarm time falls during this call before the alarm can be set,
603  *                     then the callback should be called during (by) this function instead
604  * @return >0 the alarm id
605  * @return 0 if the alarm time passed before or during the call AND there is no active alarm to return the id of.
606  *           The latter can either happen because fire_if_past was false (i.e. no timer was ever created),
607  *           or if the callback <i>was</i> called during this method but the callback cancelled itself by returning 0
608  * @return -1 if there were no alarm slots available
609  */
add_alarm_in_us(uint64_t us,alarm_callback_t callback,void * user_data,bool fire_if_past)610 static inline alarm_id_t add_alarm_in_us(uint64_t us, alarm_callback_t callback, void *user_data, bool fire_if_past) {
611     return alarm_pool_add_alarm_in_us(alarm_pool_get_default(), us, callback, user_data, fire_if_past);
612 }
613 
614 /*!
615  * \brief Add an alarm callback to be called after a delay specified in milliseconds
616  * \ingroup alarm
617  *
618  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
619  * on the core of the default alarm pool (generally core 0). If the callback is in the past or happens before
620  * the alarm setup could be completed, then this method will optionally call the callback itself
621  * and then return a return code to indicate that the target time has passed.
622  *
623  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
624  *
625  * @param ms the delay (from now) in milliseconds when (after which) the callback should fire
626  * @param callback the callback function
627  * @param user_data user data to pass to the callback function
628  * @param fire_if_past if true, and the alarm time falls during this call before the alarm can be set,
629  *                     then the callback should be called during (by) this function instead
630  * @return >0 the alarm id
631  * @return 0 if the alarm time passed before or during the call AND there is no active alarm to return the id of.
632  *           The latter can either happen because fire_if_past was false (i.e. no timer was ever created),
633  *           or if the callback <i>was</i> called during this method but the callback cancelled itself by returning 0
634  * @return -1 if there were no alarm slots available
635  */
add_alarm_in_ms(uint32_t ms,alarm_callback_t callback,void * user_data,bool fire_if_past)636 static inline alarm_id_t add_alarm_in_ms(uint32_t ms, alarm_callback_t callback, void *user_data, bool fire_if_past) {
637     return alarm_pool_add_alarm_in_ms(alarm_pool_get_default(), ms, callback, user_data, fire_if_past);
638 }
639 /*!
640  * \brief Cancel an alarm from the default alarm pool
641  * \ingroup alarm
642  * \param alarm_id the alarm
643  * \return true if the alarm was cancelled, false if it didn't exist
644  * \sa alarm_id_t for a note on reuse of IDs
645  */
cancel_alarm(alarm_id_t alarm_id)646 static inline bool cancel_alarm(alarm_id_t alarm_id) {
647     return alarm_pool_cancel_alarm(alarm_pool_get_default(), alarm_id);
648 }
649 
650 #endif
651 
652 /*!
653  * \defgroup repeating_timer repeating_timer
654  * \ingroup pico_time
655  * \brief Repeating Timer functions for simple scheduling of repeated execution
656  *
657  * \note The regular \a alarm_ functionality can be used to make repeating alarms (by return non zero from the callback),
658  * however these methods abstract that further (at the cost of a user structure to store the repeat delay in (which
659  * the alarm framework does not have space for).
660  */
661 
662 typedef struct repeating_timer repeating_timer_t;
663 
664 /**
665  * \brief Callback for a repeating timer
666  * \ingroup repeating_timer
667  * \param rt repeating time structure containing information about the repeating time. user_data is of primary important to the user
668  * \return true to continue repeating, false to stop.
669  */
670 typedef bool (*repeating_timer_callback_t)(repeating_timer_t *rt);
671 
672 /**
673  * \brief Information about a repeating timer
674  * \ingroup repeating_timer
675  * \return
676  */
677 struct repeating_timer {
678     int64_t delay_us;
679     alarm_pool_t *pool;
680     alarm_id_t alarm_id;
681     repeating_timer_callback_t callback;
682     void *user_data;
683 };
684 
685 /*!
686  * \brief Add a repeating timer that is called repeatedly at the specified interval in microseconds
687  * \ingroup repeating_timer
688  *
689  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
690  * on the core the alarm pool was created on. If the callback is in the past or happens before
691  * the alarm setup could be completed, then this method will optionally call the callback itself
692  * and then return a return code to indicate that the target time has passed.
693  *
694  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
695  *
696  * @param pool the alarm pool to use for scheduling the repeating timer (this determines which hardware alarm is used, and which core calls the callback)
697  * @param delay_us the repeat delay in microseconds; if >0 then this is the delay between one callback ending and the next starting; if <0 then this is the negative of the time between the starts of the callbacks. The value of 0 is treated as 1
698  * @param callback the repeating timer callback function
699  * @param user_data user data to pass to store in the repeating_timer structure for use by the callback.
700  * @param out the pointer to the user owned structure to store the repeating timer info in. BEWARE this storage location must outlive the repeating timer, so be careful of using stack space
701  * @return false if there were no alarm slots available to create the timer, true otherwise.
702  */
703 bool alarm_pool_add_repeating_timer_us(alarm_pool_t *pool, int64_t delay_us, repeating_timer_callback_t callback, void *user_data, repeating_timer_t *out);
704 
705 /*!
706  * \brief Add a repeating timer that is called repeatedly at the specified interval in milliseconds
707  * \ingroup repeating_timer
708  *
709  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
710  * on the core the alarm pool was created on. If the callback is in the past or happens before
711  * the alarm setup could be completed, then this method will optionally call the callback itself
712  * and then return a return code to indicate that the target time has passed.
713  *
714  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
715  *
716  * @param pool the alarm pool to use for scheduling the repeating timer (this determines which hardware alarm is used, and which core calls the callback)
717  * @param delay_ms the repeat delay in milliseconds; if >0 then this is the delay between one callback ending and the next starting; if <0 then this is the negative of the time between the starts of the callbacks. The value of 0 is treated as 1 microsecond
718  * @param callback the repeating timer callback function
719  * @param user_data user data to pass to store in the repeating_timer structure for use by the callback.
720  * @param out the pointer to the user owned structure to store the repeating timer info in. BEWARE this storage location must outlive the repeating timer, so be careful of using stack space
721  * @return false if there were no alarm slots available to create the timer, true otherwise.
722  */
alarm_pool_add_repeating_timer_ms(alarm_pool_t * pool,int32_t delay_ms,repeating_timer_callback_t callback,void * user_data,repeating_timer_t * out)723 static inline bool alarm_pool_add_repeating_timer_ms(alarm_pool_t *pool, int32_t delay_ms, repeating_timer_callback_t callback, void *user_data, repeating_timer_t *out) {
724     return alarm_pool_add_repeating_timer_us(pool, delay_ms * (int64_t)1000, callback, user_data, out);
725 }
726 
727 #if !PICO_TIME_DEFAULT_ALARM_POOL_DISABLED
728 /*!
729  * \brief Add a repeating timer that is called repeatedly at the specified interval in microseconds
730  * \ingroup repeating_timer
731  *
732  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
733  * on the core of the default alarm pool (generally core 0). If the callback is in the past or happens before
734  * the alarm setup could be completed, then this method will optionally call the callback itself
735  * and then return a return code to indicate that the target time has passed.
736  *
737  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
738  *
739  * @param delay_us the repeat delay in microseconds; if >0 then this is the delay between one callback ending and the next starting; if <0 then this is the negative of the time between the starts of the callbacks. The value of 0 is treated as 1
740  * @param callback the repeating timer callback function
741  * @param user_data user data to pass to store in the repeating_timer structure for use by the callback.
742  * @param out the pointer to the user owned structure to store the repeating timer info in. BEWARE this storage location must outlive the repeating timer, so be careful of using stack space
743  * @return false if there were no alarm slots available to create the timer, true otherwise.
744  */
add_repeating_timer_us(int64_t delay_us,repeating_timer_callback_t callback,void * user_data,repeating_timer_t * out)745 static inline bool add_repeating_timer_us(int64_t delay_us, repeating_timer_callback_t callback, void *user_data, repeating_timer_t *out) {
746     return alarm_pool_add_repeating_timer_us(alarm_pool_get_default(), delay_us, callback, user_data, out);
747 }
748 
749 /*!
750  * \brief Add a repeating timer that is called repeatedly at the specified interval in milliseconds
751  * \ingroup repeating_timer
752  *
753  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
754  * on the core of the default alarm pool (generally core 0). If the callback is in the past or happens before
755  * the alarm setup could be completed, then this method will optionally call the callback itself
756  * and then return a return code to indicate that the target time has passed.
757  *
758  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
759  *
760  * @param delay_ms the repeat delay in milliseconds; if >0 then this is the delay between one callback ending and the next starting; if <0 then this is the negative of the time between the starts of the callbacks. The value of 0 is treated as 1 microsecond
761  * @param callback the repeating timer callback function
762  * @param user_data user data to pass to store in the repeating_timer structure for use by the callback.
763  * @param out the pointer to the user owned structure to store the repeating timer info in. BEWARE this storage location must outlive the repeating timer, so be careful of using stack space
764  * @return false if there were no alarm slots available to create the timer, true otherwise.
765  */
add_repeating_timer_ms(int32_t delay_ms,repeating_timer_callback_t callback,void * user_data,repeating_timer_t * out)766 static inline bool add_repeating_timer_ms(int32_t delay_ms, repeating_timer_callback_t callback, void *user_data, repeating_timer_t *out) {
767     return alarm_pool_add_repeating_timer_us(alarm_pool_get_default(), delay_ms * (int64_t)1000, callback, user_data, out);
768 }
769 #endif
770 
771 /**
772  * \brief Cancel a repeating timer
773  * \ingroup repeating_timer
774  * \param timer the repeating timer to cancel
775  * \return true if the repeating timer was cancelled, false if it didn't exist
776  * \sa alarm_id_t for a note on reuse of IDs
777  */
778 bool cancel_repeating_timer(repeating_timer_t *timer);
779 
780 #ifdef __cplusplus
781 }
782 #endif
783 
784 #endif
785