timer.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  3. * Additions Copyright 2016 Espressif Systems (Shanghai) PTE LTD
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License").
  6. * You may not use this file except in compliance with the License.
  7. * A copy of the License is located at
  8. *
  9. * http://aws.amazon.com/apache2.0
  10. *
  11. * or in the "license" file accompanying this file. This file is distributed
  12. * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  13. * express or implied. See the License for the specific language governing
  14. * permissions and limitations under the License.
  15. */
  16. /**
  17. * @file timer.c
  18. * @brief FreeRTOS implementation of the timer interface uses ticks.
  19. */
  20. #ifdef __cplusplus
  21. extern "C" {
  22. #endif
  23. #include <limits.h>
  24. #include "timer_platform.h"
  25. #include "freertos/FreeRTOS.h"
  26. #include "freertos/task.h"
  27. #include "esp_log.h"
  28. const static char *TAG = "aws_timer";
  29. bool has_timer_expired(Timer *timer) {
  30. uint32_t now = xTaskGetTickCount();
  31. bool expired = (now - timer->start_ticks) >= timer->timeout_ticks;
  32. /* AWS IoT SDK isn't very RTOS friendly because it polls for "done
  33. timers" a lot without ever sleeping on them. So we hack in some
  34. amount of sleeping here: if it seems like the caller is polling
  35. an unexpired timer in a tight loop then we delay a tick to let
  36. things progress elsewhere.
  37. */
  38. if(!expired && now == timer->last_polled_ticks) {
  39. vTaskDelay(1);
  40. }
  41. timer->last_polled_ticks = now;
  42. return expired;
  43. }
  44. void countdown_ms(Timer *timer, uint32_t timeout) {
  45. timer->start_ticks = xTaskGetTickCount();
  46. timer->timeout_ticks = timeout / portTICK_PERIOD_MS;
  47. timer->last_polled_ticks = 0;
  48. }
  49. uint32_t left_ms(Timer *timer) {
  50. uint32_t now = xTaskGetTickCount();
  51. uint32_t elapsed = now - timer->start_ticks;
  52. if (elapsed < timer->timeout_ticks) {
  53. return (timer->timeout_ticks - elapsed) * portTICK_PERIOD_MS;
  54. } else {
  55. return 0;
  56. }
  57. }
  58. void countdown_sec(Timer *timer, uint32_t timeout) {
  59. if (timeout > UINT32_MAX / 1000) {
  60. ESP_LOGE(TAG, "timeout is out of range: %ds", timeout);
  61. }
  62. countdown_ms(timer, timeout * 1000);
  63. }
  64. void init_timer(Timer *timer) {
  65. timer->start_ticks = 0;
  66. timer->timeout_ticks = 0;
  67. timer->last_polled_ticks = 0;
  68. }
  69. #ifdef __cplusplus
  70. }
  71. #endif