app_timer2.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. /**
  2. * Copyright (c) 2018, Nordic Semiconductor ASA
  3. *
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without modification,
  7. * are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form, except as embedded into a Nordic
  13. * Semiconductor ASA integrated circuit in a product or a software update for
  14. * such product, must reproduce the above copyright notice, this list of
  15. * conditions and the following disclaimer in the documentation and/or other
  16. * materials provided with the distribution.
  17. *
  18. * 3. Neither the name of Nordic Semiconductor ASA nor the names of its
  19. * contributors may be used to endorse or promote products derived from this
  20. * software without specific prior written permission.
  21. *
  22. * 4. This software, with or without modification, must only be used with a
  23. * Nordic Semiconductor ASA integrated circuit.
  24. *
  25. * 5. Any software provided in binary form under this license must not be reverse
  26. * engineered, decompiled, modified and/or disassembled.
  27. *
  28. * THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
  29. * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  30. * OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
  31. * DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
  32. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  33. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  34. * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  35. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  36. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  37. * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  38. *
  39. */
  40. #include "app_timer.h"
  41. #include "nrf_atfifo.h"
  42. #include "nrf_sortlist.h"
  43. #include "nrf_delay.h"
  44. #if APP_TIMER_CONFIG_USE_SCHEDULER
  45. #include "app_scheduler.h"
  46. #endif
  47. #include <stddef.h>
  48. #define NRF_LOG_MODULE_NAME APP_TIMER_LOG_NAME
  49. #if APP_TIMER_CONFIG_LOG_ENABLED
  50. #define NRF_LOG_LEVEL APP_TIMER_CONFIG_LOG_LEVEL
  51. #define NRF_LOG_INFO_COLOR APP_TIMER_CONFIG_INFO_COLOR
  52. #define NRF_LOG_DEBUG_COLOR APP_TIMER_CONFIG_DEBUG_COLOR
  53. #else //APP_TIMER_CONFIG_LOG_ENABLED
  54. #define NRF_LOG_LEVEL 0
  55. #endif //APP_TIMER_CONFIG_LOG_ENABLED
  56. #include "nrf_log.h"
  57. NRF_LOG_MODULE_REGISTER();
  58. #include "drv_rtc.h"
  59. /**
  60. * Maximum possible relative value is limited by safe window to detect cases when requested
  61. * compare event has already occured.
  62. */
  63. #define APP_TIMER_SAFE_WINDOW APP_TIMER_TICKS(APP_TIMER_SAFE_WINDOW_MS)
  64. #define APP_TIMER_RTC_MAX_VALUE (DRV_RTC_MAX_CNT - APP_TIMER_SAFE_WINDOW)
  65. static drv_rtc_t m_rtc_inst = DRV_RTC_INSTANCE(1);
  66. /**
  67. * @brief Timer requests types.
  68. */
  69. typedef enum
  70. {
  71. TIMER_REQ_START,
  72. TIMER_REQ_STOP,
  73. TIMER_REQ_STOP_ALL
  74. } app_timer_req_type_t;
  75. /**
  76. * @brief Operation request structure.
  77. */
  78. typedef struct
  79. {
  80. app_timer_req_type_t type; /**< Request type. */
  81. app_timer_t * p_timer; /**< Timer instance. */
  82. } timer_req_t;
  83. static app_timer_t * volatile mp_active_timer; /**< Timer currently handled by RTC driver. */
  84. static bool m_global_active; /**< Flag used to globally disable all timers. */
  85. /* Request FIFO instance. */
  86. NRF_ATFIFO_DEF(m_req_fifo, timer_req_t, APP_TIMER_CONFIG_OP_QUEUE_SIZE);
  87. /* Sortlist instance. */
  88. static bool compare_func(nrf_sortlist_item_t * p_item0, nrf_sortlist_item_t *p_item1);
  89. NRF_SORTLIST_DEF(m_app_timer_sortlist, compare_func); /**< Sortlist used for storing queued timers. */
  90. /**
  91. * @brief Function used for comparing items in sorted list.
  92. */
  93. static inline bool compare_func(nrf_sortlist_item_t * p_item0, nrf_sortlist_item_t *p_item1)
  94. {
  95. app_timer_t * p0 = CONTAINER_OF(p_item0, app_timer_t, list_item);
  96. app_timer_t * p1 = CONTAINER_OF(p_item1, app_timer_t, list_item);
  97. uint32_t p0_end = p0->end_val;
  98. uint32_t p1_end = p1->end_val;
  99. return (p0_end <= p1_end) ? true : false;
  100. }
  101. #if APP_TIMER_CONFIG_USE_SCHEDULER
  102. static void scheduled_timeout_handler(void * p_event_data, uint16_t event_size)
  103. {
  104. ASSERT(event_size == sizeof(app_timer_event_t));
  105. app_timer_event_t const * p_timer_event = (app_timer_event_t *)p_event_data;
  106. p_timer_event->timeout_handler(p_timer_event->p_context);
  107. }
  108. #endif
  109. /**
  110. * @brief Function called on timer expiration
  111. *
  112. * Function calls user handler if timer was not stopped before. If timer is in repeated mode then
  113. * timer is rescheduled.
  114. *
  115. * @param p_timer Timer instance.
  116. *
  117. * @return True if reevaluation of sortlist needed (becasue it was updated).
  118. */
  119. static bool timer_expire(app_timer_t * p_timer)
  120. {
  121. ASSERT(p_timer->handler);
  122. bool ret = false;
  123. if ((m_global_active == true) && (p_timer != NULL) && (p_timer->active))
  124. {
  125. if (p_timer->repeat_period == 0)
  126. {
  127. p_timer->active = false;
  128. }
  129. #if APP_TIMER_CONFIG_USE_SCHEDULER
  130. app_timer_event_t timer_event;
  131. timer_event.timeout_handler = p_timer->handler;
  132. timer_event.p_context = p_timer->p_context;
  133. uint32_t err_code = app_sched_event_put(&timer_event,
  134. sizeof(timer_event),
  135. scheduled_timeout_handler);
  136. APP_ERROR_CHECK(err_code);
  137. #else
  138. p_timer->handler(p_timer->p_context);
  139. #endif
  140. if ((p_timer->repeat_period) && (p_timer->active))
  141. {
  142. p_timer->end_val += p_timer->repeat_period;
  143. nrf_sortlist_add(&m_app_timer_sortlist, &p_timer->list_item);
  144. ret = true;
  145. }
  146. }
  147. return ret;
  148. }
  149. /**
  150. * @brief Function is configuring RTC driver to trigger timeout interrupt for given timer.
  151. *
  152. * It is possible that RTC driver will indicate that timeout already occured. In that case timer
  153. * expires and function indicates that RTC was not configured.
  154. *
  155. * @param p_timer Timer instance.
  156. * @param [in,out] p_rerun Flag indicating that sortlist reevaluation is required.
  157. *
  158. * @return True if RTC was successfully configured, false if timer already expired and RTC was not
  159. * configured.
  160. *
  161. */
  162. static bool rtc_schedule(app_timer_t * p_timer, bool * p_rerun)
  163. {
  164. ret_code_t ret = NRF_SUCCESS;
  165. *p_rerun = false;
  166. ret = drv_rtc_windowed_compare_set(&m_rtc_inst, 0, p_timer->end_val, APP_TIMER_SAFE_WINDOW);
  167. if (ret == NRF_SUCCESS)
  168. {
  169. return true;
  170. }
  171. else if (ret == NRF_ERROR_TIMEOUT)
  172. {
  173. *p_rerun = timer_expire(p_timer);
  174. }
  175. else
  176. {
  177. ASSERT(0);
  178. }
  179. return false;
  180. }
  181. static inline app_timer_t * sortlist_pop(void)
  182. {
  183. nrf_sortlist_item_t * p_next_item = nrf_sortlist_pop(&m_app_timer_sortlist);
  184. return p_next_item ? CONTAINER_OF(p_next_item, app_timer_t, list_item) : NULL;
  185. }
  186. static inline app_timer_t * sortlist_peek(void)
  187. {
  188. nrf_sortlist_item_t const * p_next_item = nrf_sortlist_peek(&m_app_timer_sortlist);
  189. return p_next_item ? CONTAINER_OF(p_next_item, app_timer_t, list_item) : NULL;
  190. }
  191. static inline app_timer_t * sortlist_next(app_timer_t * p_item)
  192. {
  193. nrf_sortlist_item_t const * p_next_item = nrf_sortlist_next(&p_item->list_item);
  194. return p_next_item ? CONTAINER_OF(p_next_item, app_timer_t, list_item) : NULL;
  195. }
  196. /**
  197. * @brief Function for deactivating all timers which are in the sorted list (active timers).
  198. */
  199. static void sorted_list_stop_all(void)
  200. {
  201. app_timer_t * p_next;
  202. do
  203. {
  204. p_next = sortlist_pop();
  205. if (p_next)
  206. {
  207. p_next->active = false;
  208. }
  209. } while (p_next);
  210. }
  211. /**
  212. * @brief Function for handling RTC counter overflow.
  213. *
  214. * In case of overflow all active timers must have end value adjusted (reduced to 24 bit range).
  215. */
  216. static void on_overflow_evt(void)
  217. {
  218. NRF_LOG_DEBUG("Overflow EVT");
  219. if (mp_active_timer)
  220. {
  221. uint32_t end_val = mp_active_timer->end_val;
  222. mp_active_timer->end_val = end_val & RTC_COUNTER_COUNTER_Msk;
  223. }
  224. app_timer_t * p_next;
  225. p_next = sortlist_peek();
  226. while (p_next)
  227. {
  228. if (p_next->end_val <= RTC_COUNTER_COUNTER_Msk)
  229. {
  230. //If overflow occurs then all timers with value lower than max value expires immediately.
  231. UNUSED_RETURN_VALUE(timer_expire(p_next));
  232. }
  233. else
  234. {
  235. p_next->end_val &= RTC_COUNTER_COUNTER_Msk;
  236. }
  237. p_next = sortlist_next(p_next);
  238. }
  239. }
  240. /**
  241. * #brief Function for handling RTC compare event - active timer expiration.
  242. */
  243. static void on_compare_evt(drv_rtc_t const * const p_instance)
  244. {
  245. if (mp_active_timer)
  246. {
  247. //If assert fails it suggests that safe window should be increased.
  248. ASSERT(app_timer_cnt_diff_compute(drv_rtc_counter_get(p_instance),
  249. mp_active_timer->end_val & RTC_COUNTER_COUNTER_Msk) < APP_TIMER_SAFE_WINDOW);
  250. NRF_LOG_INST_DEBUG(mp_active_timer->p_log, "Compare EVT");
  251. UNUSED_RETURN_VALUE(timer_expire(mp_active_timer));
  252. mp_active_timer = NULL;
  253. }
  254. else
  255. {
  256. NRF_LOG_WARNING("Compare event but no active timer (already stopped?)");
  257. }
  258. }
  259. /**
  260. * @brief Function updates RTC.
  261. *
  262. * Function is called at the end of RTC interrupt when all new user request and/or timer expiration
  263. * occured. It configures RTC if there is any pending timer, reconfigures if the are timers with
  264. * shorted timeout than active one or stops RTC if there is no active timers.
  265. */
  266. static void rtc_update(drv_rtc_t const * const p_instance)
  267. {
  268. while(1)
  269. {
  270. app_timer_t * p_next = sortlist_peek();
  271. bool rtc_reconf = false;
  272. if (p_next) //Candidate for active timer
  273. {
  274. uint32_t next_end_val = p_next->end_val;
  275. uint32_t active_end_val = mp_active_timer->end_val;
  276. if (mp_active_timer == NULL)
  277. {
  278. //There is no active timer so candidate will become active timer.
  279. rtc_reconf = true;
  280. }
  281. else if (mp_active_timer &&
  282. (active_end_val > next_end_val))
  283. {
  284. //Candidate has shorter timeout than current active timer. Candidate will replace active timer.
  285. //Active timer is put back into sorted list.
  286. rtc_reconf = true;
  287. if (mp_active_timer->active)
  288. {
  289. NRF_LOG_INST_DEBUG(mp_active_timer->p_log, "Timer preempted.");
  290. nrf_sortlist_add(&m_app_timer_sortlist, &mp_active_timer->list_item);
  291. }
  292. }
  293. if (rtc_reconf)
  294. {
  295. bool rerun;
  296. p_next = sortlist_pop();
  297. NRF_LOG_INST_DEBUG(p_next->p_log, "Activating timer (CC:%d).", next_end_val);
  298. if (rtc_schedule(p_next, &rerun))
  299. {
  300. if (!APP_TIMER_KEEPS_RTC_ACTIVE && (mp_active_timer == NULL))
  301. {
  302. drv_rtc_start(p_instance);
  303. }
  304. mp_active_timer = p_next;
  305. if (rerun == false)
  306. {
  307. //RTC was successfully updated and sortlist was not updated. Function can be terminated.
  308. break;
  309. }
  310. }
  311. else
  312. {
  313. //If RTC driver indicated that timeout already occured a new candidate will be taken from sorted list.
  314. NRF_LOG_INST_DEBUG(p_next->p_log,"Timer expired before scheduled to RTC.");
  315. }
  316. }
  317. else
  318. {
  319. //RTC will not be updated. Function can terminate.
  320. break;
  321. }
  322. }
  323. else //No candidate for active timer.
  324. {
  325. if (!APP_TIMER_KEEPS_RTC_ACTIVE && mp_active_timer == NULL)
  326. {
  327. drv_rtc_stop(p_instance);
  328. }
  329. break;
  330. }
  331. }
  332. }
  333. /**
  334. * @brief Function for processing user requests.
  335. *
  336. * Function is called only in the context of RTC interrupt.
  337. */
  338. static void timer_req_process(drv_rtc_t const * const p_instance)
  339. {
  340. nrf_atfifo_item_get_t fifo_ctx;
  341. timer_req_t * p_req = nrf_atfifo_item_get(m_req_fifo, &fifo_ctx);
  342. while (p_req)
  343. {
  344. switch (p_req->type)
  345. {
  346. case TIMER_REQ_START:
  347. if (!p_req->p_timer->active)
  348. {
  349. p_req->p_timer->active = true;
  350. if (p_req->p_timer->end_val - drv_rtc_counter_get(p_instance) > APP_TIMER_RTC_MAX_VALUE)
  351. {
  352. //A little trick to handle case when timer was scheduled just before overflow.
  353. p_req->p_timer->end_val &= RTC_COUNTER_COUNTER_Msk;
  354. }
  355. nrf_sortlist_add(&m_app_timer_sortlist, &(p_req->p_timer->list_item));
  356. NRF_LOG_INST_DEBUG(p_req->p_timer->p_log,"Start request (CC:%d).",
  357. p_req->p_timer->end_val);
  358. }
  359. break;
  360. case TIMER_REQ_STOP:
  361. if (p_req->p_timer == mp_active_timer)
  362. {
  363. mp_active_timer = NULL;
  364. }
  365. UNUSED_RETURN_VALUE(nrf_sortlist_remove(&m_app_timer_sortlist, &(p_req->p_timer->list_item)));
  366. NRF_LOG_INST_DEBUG(p_req->p_timer->p_log,"Stop request.");
  367. break;
  368. case TIMER_REQ_STOP_ALL:
  369. sorted_list_stop_all();
  370. m_global_active = true;
  371. NRF_LOG_INFO("Stop all request.");
  372. break;
  373. default:
  374. break;
  375. }
  376. UNUSED_RETURN_VALUE(nrf_atfifo_item_free(m_req_fifo, &fifo_ctx));
  377. p_req = nrf_atfifo_item_get(m_req_fifo, &fifo_ctx);
  378. }
  379. }
  380. static void rtc_irq(drv_rtc_t const * const p_instance)
  381. {
  382. if (drv_rtc_overflow_pending(p_instance))
  383. {
  384. on_overflow_evt();
  385. }
  386. if (drv_rtc_compare_pending(p_instance, 0))
  387. {
  388. on_compare_evt(p_instance);
  389. }
  390. timer_req_process(p_instance);
  391. rtc_update(p_instance);
  392. }
  393. /**
  394. * @brief Function for triggering processing user requests.
  395. *
  396. * @note All user requests are processed in a single context - RTC interrupt.
  397. */
  398. static inline void timer_request_proc_trigger(void)
  399. {
  400. drv_rtc_irq_trigger(&m_rtc_inst);
  401. }
  402. /**
  403. * @brief Function for putting user request into the request queue
  404. */
  405. static ret_code_t timer_req_schedule(app_timer_req_type_t type, app_timer_t * p_timer)
  406. {
  407. nrf_atfifo_item_put_t fifo_ctx;
  408. timer_req_t * p_req = nrf_atfifo_item_alloc(m_req_fifo, &fifo_ctx);
  409. if (p_req)
  410. {
  411. p_req->type = type;
  412. p_req->p_timer = p_timer;
  413. if (nrf_atfifo_item_put(m_req_fifo, &fifo_ctx))
  414. {
  415. timer_request_proc_trigger();
  416. }
  417. else
  418. {
  419. NRF_LOG_WARNING("Scheduling interrupted another scheduling.");
  420. }
  421. return NRF_SUCCESS;
  422. }
  423. else
  424. {
  425. return NRF_ERROR_NO_MEM;
  426. }
  427. }
  428. ret_code_t app_timer_init(void)
  429. {
  430. ret_code_t err_code;
  431. drv_rtc_config_t config = {
  432. .prescaler = APP_TIMER_CONFIG_RTC_FREQUENCY,
  433. .interrupt_priority = APP_TIMER_CONFIG_IRQ_PRIORITY
  434. };
  435. err_code = NRF_ATFIFO_INIT(m_req_fifo);
  436. if (err_code != NRFX_SUCCESS)
  437. {
  438. return err_code;
  439. }
  440. err_code = drv_rtc_init(&m_rtc_inst, &config, rtc_irq);
  441. if (err_code != NRFX_SUCCESS)
  442. {
  443. return err_code;
  444. }
  445. drv_rtc_overflow_enable(&m_rtc_inst, true);
  446. if (APP_TIMER_KEEPS_RTC_ACTIVE)
  447. {
  448. drv_rtc_start(&m_rtc_inst);
  449. }
  450. m_global_active = true;
  451. return err_code;
  452. }
  453. ret_code_t app_timer_create(app_timer_id_t const * p_timer_id,
  454. app_timer_mode_t mode,
  455. app_timer_timeout_handler_t timeout_handler)
  456. {
  457. ASSERT(p_timer_id);
  458. ASSERT(timeout_handler);
  459. if (timeout_handler == NULL)
  460. {
  461. return NRF_ERROR_INVALID_PARAM;
  462. }
  463. app_timer_t * p_t = (app_timer_t *) *p_timer_id;
  464. p_t->handler = timeout_handler;
  465. p_t->repeat_period = (mode == APP_TIMER_MODE_REPEATED) ? 1 : 0;
  466. return NRF_SUCCESS;
  467. }
  468. ret_code_t app_timer_start(app_timer_t * p_timer, uint32_t timeout_ticks, void * p_context)
  469. {
  470. ASSERT(p_timer);
  471. app_timer_t * p_t = (app_timer_t *) p_timer;
  472. if (timeout_ticks > APP_TIMER_RTC_MAX_VALUE)
  473. {
  474. return NRF_ERROR_INVALID_PARAM;
  475. }
  476. if (p_t->active)
  477. {
  478. return NRF_SUCCESS;
  479. }
  480. p_t->p_context = p_context;
  481. p_t->end_val = drv_rtc_counter_get(&m_rtc_inst) + timeout_ticks;
  482. if (p_t->repeat_period)
  483. {
  484. p_t->repeat_period = timeout_ticks;
  485. }
  486. return timer_req_schedule(TIMER_REQ_START, p_t);
  487. }
  488. ret_code_t app_timer_stop(app_timer_t * p_timer)
  489. {
  490. ASSERT(p_timer);
  491. app_timer_t * p_t = (app_timer_t *) p_timer;
  492. p_t->active = false;
  493. return timer_req_schedule(TIMER_REQ_STOP, p_t);
  494. }
  495. ret_code_t app_timer_stop_all(void)
  496. {
  497. //block timer globally
  498. m_global_active = false;
  499. return timer_req_schedule(TIMER_REQ_STOP_ALL, NULL);
  500. }
  501. uint8_t app_timer_op_queue_utilization_get(void)
  502. {
  503. /* Currently not supported by ATFIFO */
  504. return 0;
  505. }
  506. uint32_t app_timer_cnt_diff_compute(uint32_t ticks_to,
  507. uint32_t ticks_from)
  508. {
  509. return ((ticks_to - ticks_from) & RTC_COUNTER_COUNTER_Msk);
  510. }
  511. uint32_t app_timer_cnt_get(void)
  512. {
  513. return drv_rtc_counter_get(&m_rtc_inst);
  514. }
  515. void app_timer_pause(void)
  516. {
  517. drv_rtc_stop(&m_rtc_inst);
  518. }
  519. void app_timer_resume(void)
  520. {
  521. drv_rtc_start(&m_rtc_inst);
  522. }