platformTimer.c 996 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. #include "platformTimer.h"
  2. /**
  3. * @brief 初始化定时器
  4. *
  5. * @param platformTimer
  6. */
  7. void platformTimerInit(platformTimer_t *platformTimer)
  8. {
  9. platformTimer->time.tv_sec = 0;
  10. platformTimer->time.tv_usec = 0;
  11. }
  12. /**
  13. * @brief 添加计数时间
  14. *
  15. * @param platformTimer
  16. * @param timeout
  17. */
  18. void platformTimerCutdown(platformTimer_t *platformTimer, uint32_t timeout)
  19. {
  20. struct timeval now = {0};
  21. gettimeofday(&now, NULL);
  22. struct timeval interval = {timeout / 1000, (timeout % 1000) * 1000};
  23. timeradd(&now, &interval, &platformTimer->time);
  24. }
  25. /**
  26. * @brief 计算time还有多长时间超时,考虑了32位溢出判断
  27. *
  28. * @param platformTimer
  29. * @return uint32_t 返回剩余时间,超时返回0
  30. */
  31. uint32_t platformTimerRemain(platformTimer_t *platformTimer)
  32. {
  33. struct timeval now = {0}, res = {0};
  34. gettimeofday(&now, NULL);
  35. timersub(&platformTimer->time, &now, &res);
  36. return (res.tv_sec < 0) ? 0 : res.tv_sec * 1000 + res.tv_usec / 1000;
  37. }