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  * \return the hardware alarm used by the pool
451  */
452 void alarm_pool_destroy(alarm_pool_t *pool);
453 
454 /*!
455  * \brief Add an alarm callback to be called at a specific time
456  * \ingroup alarm
457  *
458  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
459  * on the core the alarm pool was created on. If the callback is in the past or happens before
460  * the alarm setup could be completed, then this method will optionally call the callback itself
461  * and then return a return code to indicate that the target time has passed.
462  *
463  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
464  *
465  * @param pool the alarm pool to use for scheduling the callback (this determines which hardware alarm is used, and which core calls the callback)
466  * @param time the timestamp when (after which) the callback should fire
467  * @param callback the callback function
468  * @param user_data user data to pass to the callback function
469  * @param fire_if_past if true, and the alarm time falls before or during this call before the alarm can be set,
470  *                     then the callback should be called during (by) this function instead
471  * @return >0 the alarm id for an active (at the time of return) alarm
472  * @return 0 if the alarm time passed before or during the call AND there is no active alarm to return the id of.
473  *           The latter can either happen because fire_if_past was false (i.e. no timer was ever created),
474  *           or if the callback <i>was</i> called during this method but the callback cancelled itself by returning 0
475  * @return -1 if there were no alarm slots available
476  */
477 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);
478 
479 /*!
480  * \brief Add an alarm callback to be called at or after a specific time
481  * \ingroup alarm
482  *
483  * The callback is called as soon as possible after the time specified from an IRQ handler
484  * on the core the alarm pool was created on. Unlike \ref alarm_pool_add_alarm_at, this method
485  * guarantees to call the callback from that core even if the time is during this method call or in the past.
486  *
487  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
488  *
489  * @param pool the alarm pool to use for scheduling the callback (this determines which hardware alarm is used, and which core calls the callback)
490  * @param time the timestamp when (after which) the callback should fire
491  * @param callback the callback function
492  * @param user_data user data to pass to the callback function
493  * @return >0 the alarm id for an active (at the time of return) alarm
494  * @return -1 if there were no alarm slots available
495  */
496 alarm_id_t alarm_pool_add_alarm_at_force_in_context(alarm_pool_t *pool, absolute_time_t time, alarm_callback_t callback,
497                                                     void *user_data);
498 /*!
499  * \brief Add an alarm callback to be called after a delay specified in microseconds
500  * \ingroup alarm
501  *
502  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
503  * on the core the alarm pool was created on. If the callback is in the past or happens before
504  * the alarm setup could be completed, then this method will optionally call the callback itself
505  * and then return a return code to indicate that the target time has passed.
506  *
507  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
508  *
509  * @param pool the alarm pool to use for scheduling the callback (this determines which hardware alarm is used, and which core calls the callback)
510  * @param us the delay (from now) in microseconds when (after which) the callback should fire
511  * @param callback the callback function
512  * @param user_data user data to pass to the callback function
513  * @param fire_if_past if true, and the alarm time falls during this call before the alarm can be set,
514  *                     then the callback should be called during (by) this function instead
515  * @return >0 the alarm id
516  * @return 0 if the alarm time passed before or during the call AND there is no active alarm to return the id of.
517  *           The latter can either happen because fire_if_past was false (i.e. no timer was ever created),
518  *           or if the callback <i>was</i> called during this method but the callback cancelled itself by returning 0
519  * @return -1 if there were no alarm slots available
520  */
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 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) {
522     return alarm_pool_add_alarm_at(pool, delayed_by_us(get_absolute_time(), us), callback, user_data, fire_if_past);
523 }
524 
525 /*!
526  * \brief Add an alarm callback to be called after a delay specified in milliseconds
527  * \ingroup alarm
528  *
529  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
530  * on the core the alarm pool was created on. If the callback is in the past or happens before
531  * the alarm setup could be completed, then this method will optionally call the callback itself
532  * and then return a return code to indicate that the target time has passed.
533  *
534  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
535  *
536  * @param pool the alarm pool to use for scheduling the callback (this determines which hardware alarm is used, and which core calls the callback)
537  * @param ms the delay (from now) in milliseconds when (after which) the callback should fire
538  * @param callback the callback function
539  * @param user_data user data to pass to the callback function
540  * @param fire_if_past if true, and the alarm time falls before or during this call before the alarm can be set,
541  *                     then the callback should be called during (by) this function instead
542  * @return >0 the alarm id
543  * @return 0 if the alarm time passed before or during the call AND there is no active alarm to return the id of.
544  *           The latter can either happen because fire_if_past was false (i.e. no timer was ever created),
545  *           or if the callback <i>was</i> called during this method but the callback cancelled itself by returning 0
546  * @return -1 if there were no alarm slots available
547  */
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 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) {
549     return alarm_pool_add_alarm_at(pool, delayed_by_ms(get_absolute_time(), ms), callback, user_data, fire_if_past);
550 }
551 
552 /*!
553  * \brief Cancel an alarm
554  * \ingroup alarm
555  * \param pool the alarm_pool containing the alarm
556  * \param alarm_id the alarm
557  * \return true if the alarm was cancelled, false if it didn't exist
558  * \sa alarm_id_t for a note on reuse of IDs
559  */
560 bool alarm_pool_cancel_alarm(alarm_pool_t *pool, alarm_id_t alarm_id);
561 
562 #if !PICO_TIME_DEFAULT_ALARM_POOL_DISABLED
563 /*!
564  * \brief Add an alarm callback to be called at a specific time
565  * \ingroup alarm
566  *
567  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
568  * on the core of the default alarm pool (generally core 0). If the callback is in the past or happens before
569  * the alarm setup could be completed, then this method will optionally call the callback itself
570  * and then return a return code to indicate that the target time has passed.
571  *
572  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
573  *
574  * @param time the timestamp when (after which) the callback should fire
575  * @param callback the callback function
576  * @param user_data user data to pass to the callback function
577  * @param fire_if_past if true, and the alarm time falls before or during this call before the alarm can be set,
578  *                     then the callback should be called during (by) this function instead
579  * @return >0 the alarm id
580  * @return 0 if the alarm time passed before or during the call AND there is no active alarm to return the id of.
581  *           The latter can either happen because fire_if_past was false (i.e. no timer was ever created),
582  *           or if the callback <i>was</i> called during this method but the callback cancelled itself by returning 0
583  * @return -1 if there were no alarm slots available
584  */
add_alarm_at(absolute_time_t time,alarm_callback_t callback,void * user_data,bool fire_if_past)585 static inline alarm_id_t add_alarm_at(absolute_time_t time, alarm_callback_t callback, void *user_data, bool fire_if_past) {
586     return alarm_pool_add_alarm_at(alarm_pool_get_default(), time, callback, user_data, fire_if_past);
587 }
588 
589 /*!
590  * \brief Add an alarm callback to be called after a delay specified in microseconds
591  * \ingroup alarm
592  *
593  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
594  * on the core of the default alarm pool (generally core 0). If the callback is in the past or happens before
595  * the alarm setup could be completed, then this method will optionally call the callback itself
596  * and then return a return code to indicate that the target time has passed.
597  *
598  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
599  *
600  * @param us the delay (from now) in microseconds when (after which) the callback should fire
601  * @param callback the callback function
602  * @param user_data user data to pass to the callback function
603  * @param fire_if_past if true, and the alarm time falls during this call before the alarm can be set,
604  *                     then the callback should be called during (by) this function instead
605  * @return >0 the alarm id
606  * @return 0 if the alarm time passed before or during the call AND there is no active alarm to return the id of.
607  *           The latter can either happen because fire_if_past was false (i.e. no timer was ever created),
608  *           or if the callback <i>was</i> called during this method but the callback cancelled itself by returning 0
609  * @return -1 if there were no alarm slots available
610  */
add_alarm_in_us(uint64_t us,alarm_callback_t callback,void * user_data,bool fire_if_past)611 static inline alarm_id_t add_alarm_in_us(uint64_t us, alarm_callback_t callback, void *user_data, bool fire_if_past) {
612     return alarm_pool_add_alarm_in_us(alarm_pool_get_default(), us, callback, user_data, fire_if_past);
613 }
614 
615 /*!
616  * \brief Add an alarm callback to be called after a delay specified in milliseconds
617  * \ingroup alarm
618  *
619  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
620  * on the core of the default alarm pool (generally core 0). If the callback is in the past or happens before
621  * the alarm setup could be completed, then this method will optionally call the callback itself
622  * and then return a return code to indicate that the target time has passed.
623  *
624  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
625  *
626  * @param ms the delay (from now) in milliseconds when (after which) the callback should fire
627  * @param callback the callback function
628  * @param user_data user data to pass to the callback function
629  * @param fire_if_past if true, and the alarm time falls during this call before the alarm can be set,
630  *                     then the callback should be called during (by) this function instead
631  * @return >0 the alarm id
632  * @return 0 if the alarm time passed before or during the call AND there is no active alarm to return the id of.
633  *           The latter can either happen because fire_if_past was false (i.e. no timer was ever created),
634  *           or if the callback <i>was</i> called during this method but the callback cancelled itself by returning 0
635  * @return -1 if there were no alarm slots available
636  */
add_alarm_in_ms(uint32_t ms,alarm_callback_t callback,void * user_data,bool fire_if_past)637 static inline alarm_id_t add_alarm_in_ms(uint32_t ms, alarm_callback_t callback, void *user_data, bool fire_if_past) {
638     return alarm_pool_add_alarm_in_ms(alarm_pool_get_default(), ms, callback, user_data, fire_if_past);
639 }
640 /*!
641  * \brief Cancel an alarm from the default alarm pool
642  * \ingroup alarm
643  * \param alarm_id the alarm
644  * \return true if the alarm was cancelled, false if it didn't exist
645  * \sa alarm_id_t for a note on reuse of IDs
646  */
cancel_alarm(alarm_id_t alarm_id)647 static inline bool cancel_alarm(alarm_id_t alarm_id) {
648     return alarm_pool_cancel_alarm(alarm_pool_get_default(), alarm_id);
649 }
650 
651 #endif
652 
653 /*!
654  * \defgroup repeating_timer repeating_timer
655  * \ingroup pico_time
656  * \brief Repeating Timer functions for simple scheduling of repeated execution
657  *
658  * \note The regular \a alarm_ functionality can be used to make repeating alarms (by return non zero from the callback),
659  * however these methods abstract that further (at the cost of a user structure to store the repeat delay in (which
660  * the alarm framework does not have space for).
661  */
662 
663 typedef struct repeating_timer repeating_timer_t;
664 
665 /**
666  * \brief Callback for a repeating timer
667  * \ingroup repeating_timer
668  * \param rt repeating time structure containing information about the repeating time. user_data is of primary important to the user
669  * \return true to continue repeating, false to stop.
670  */
671 typedef bool (*repeating_timer_callback_t)(repeating_timer_t *rt);
672 
673 /**
674  * \brief Information about a repeating timer
675  * \ingroup repeating_timer
676  * \return
677  */
678 struct repeating_timer {
679     int64_t delay_us;
680     alarm_pool_t *pool;
681     alarm_id_t alarm_id;
682     repeating_timer_callback_t callback;
683     void *user_data;
684 };
685 
686 /*!
687  * \brief Add a repeating timer that is called repeatedly at the specified interval in microseconds
688  * \ingroup repeating_timer
689  *
690  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
691  * on the core the alarm pool was created on. If the callback is in the past or happens before
692  * the alarm setup could be completed, then this method will optionally call the callback itself
693  * and then return a return code to indicate that the target time has passed.
694  *
695  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
696  *
697  * @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)
698  * @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
699  * @param callback the repeating timer callback function
700  * @param user_data user data to pass to store in the repeating_timer structure for use by the callback.
701  * @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
702  * @return false if there were no alarm slots available to create the timer, true otherwise.
703  */
704 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);
705 
706 /*!
707  * \brief Add a repeating timer that is called repeatedly at the specified interval in milliseconds
708  * \ingroup repeating_timer
709  *
710  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
711  * on the core the alarm pool was created on. If the callback is in the past or happens before
712  * the alarm setup could be completed, then this method will optionally call the callback itself
713  * and then return a return code to indicate that the target time has passed.
714  *
715  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
716  *
717  * @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)
718  * @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
719  * @param callback the repeating timer callback function
720  * @param user_data user data to pass to store in the repeating_timer structure for use by the callback.
721  * @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
722  * @return false if there were no alarm slots available to create the timer, true otherwise.
723  */
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 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) {
725     return alarm_pool_add_repeating_timer_us(pool, delay_ms * (int64_t)1000, callback, user_data, out);
726 }
727 
728 #if !PICO_TIME_DEFAULT_ALARM_POOL_DISABLED
729 /*!
730  * \brief Add a repeating timer that is called repeatedly at the specified interval in microseconds
731  * \ingroup repeating_timer
732  *
733  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
734  * on the core of the default alarm pool (generally core 0). If the callback is in the past or happens before
735  * the alarm setup could be completed, then this method will optionally call the callback itself
736  * and then return a return code to indicate that the target time has passed.
737  *
738  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
739  *
740  * @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
741  * @param callback the repeating timer callback function
742  * @param user_data user data to pass to store in the repeating_timer structure for use by the callback.
743  * @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
744  * @return false if there were no alarm slots available to create the timer, true otherwise.
745  */
add_repeating_timer_us(int64_t delay_us,repeating_timer_callback_t callback,void * user_data,repeating_timer_t * out)746 static inline bool add_repeating_timer_us(int64_t delay_us, repeating_timer_callback_t callback, void *user_data, repeating_timer_t *out) {
747     return alarm_pool_add_repeating_timer_us(alarm_pool_get_default(), delay_us, callback, user_data, out);
748 }
749 
750 /*!
751  * \brief Add a repeating timer that is called repeatedly at the specified interval in milliseconds
752  * \ingroup repeating_timer
753  *
754  * Generally the callback is called as soon as possible after the time specified from an IRQ handler
755  * on the core of the default alarm pool (generally core 0). If the callback is in the past or happens before
756  * the alarm setup could be completed, then this method will optionally call the callback itself
757  * and then return a return code to indicate that the target time has passed.
758  *
759  * \note It is safe to call this method from an IRQ handler (including alarm callbacks), and from either core.
760  *
761  * @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
762  * @param callback the repeating timer callback function
763  * @param user_data user data to pass to store in the repeating_timer structure for use by the callback.
764  * @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
765  * @return false if there were no alarm slots available to create the timer, true otherwise.
766  */
add_repeating_timer_ms(int32_t delay_ms,repeating_timer_callback_t callback,void * user_data,repeating_timer_t * out)767 static inline bool add_repeating_timer_ms(int32_t delay_ms, repeating_timer_callback_t callback, void *user_data, repeating_timer_t *out) {
768     return alarm_pool_add_repeating_timer_us(alarm_pool_get_default(), delay_ms * (int64_t)1000, callback, user_data, out);
769 }
770 #endif
771 
772 /**
773  * \brief Cancel a repeating timer
774  * \ingroup repeating_timer
775  * \param timer the repeating timer to cancel
776  * \return true if the repeating timer was cancelled, false if it didn't exist
777  * \sa alarm_id_t for a note on reuse of IDs
778  */
779 bool cancel_repeating_timer(repeating_timer_t *timer);
780 
781 #ifdef __cplusplus
782 }
783 #endif
784 
785 #endif
786