You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

88 lines
1.9 KiB

  1. #include "timer.h"
  2. #include <stdlib.h>
  3. struct tm time_current = {
  4. .tm_sec = 0,
  5. .tm_min = 0,
  6. .tm_hour = 0
  7. };
  8. struct timer_hooks {
  9. hook_callback callback;
  10. enum timer_hook_level level;
  11. struct timer_hooks* next;
  12. };
  13. struct timer_hooks* hooks = NULL;
  14. void timer_hook_node_exec(struct timer_hooks* node, enum timer_hook_level level)
  15. {
  16. if (node->level == level && node->callback != NULL) {
  17. node->callback();
  18. }
  19. if (node->next != NULL) {
  20. timer_hook_node_exec(node->next, level);
  21. }
  22. }
  23. void timer_hook_exec(enum timer_hook_level level)
  24. {
  25. if (hooks != NULL)
  26. timer_hook_node_exec(hooks, level);
  27. }
  28. void timer_update()
  29. {
  30. struct tm time_last = time_current;
  31. time_t t = time(NULL);
  32. time_current = *localtime(&t);
  33. if (time_last.tm_sec != time_current.tm_sec)
  34. timer_hook_exec(HOOK_SECOND);
  35. if (time_last.tm_min != time_current.tm_min)
  36. timer_hook_exec(HOOK_MINUTE);
  37. if (time_last.tm_hour != time_current.tm_hour)
  38. timer_hook_exec(HOOK_HOUR);
  39. if (time_last.tm_mday != time_current.tm_mday)
  40. timer_hook_exec(HOOK_DAY);
  41. if (time_last.tm_mon != time_current.tm_mon)
  42. timer_hook_exec(HOOK_MONTH);
  43. }
  44. void timer_add_hook(enum timer_hook_level level, hook_callback callback)
  45. {
  46. struct timer_hooks* node = malloc(sizeof(struct timer_hooks));
  47. node->level = level;
  48. node->callback = callback;
  49. node->next = NULL;
  50. if (hooks == NULL) {
  51. hooks = node;
  52. } else {
  53. struct timer_hooks* t = hooks;
  54. do {
  55. if (!t->next) {
  56. t->next = node;
  57. break;
  58. } else {
  59. t = t->next;
  60. }
  61. } while (1);
  62. }
  63. }
  64. void timer_hook_free_node(struct timer_hooks* node)
  65. {
  66. if (node->next)
  67. timer_hook_free_node(node->next);
  68. free(node);
  69. }
  70. void timer_hook_free()
  71. {
  72. if (hooks)
  73. timer_hook_free_node(hooks);
  74. hooks = NULL;
  75. }