timer.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include "wa-inc/timer_wasm_app.h"
  8. #include "timer_api.h"
  9. #if 1
  10. #include <stdio.h>
  11. #else
  12. #define printf (...)
  13. #endif
  14. struct user_timer {
  15. struct user_timer * next;
  16. int timer_id;
  17. void (*user_timer_callback)(user_timer_t);
  18. };
  19. struct user_timer * g_timers = NULL;
  20. user_timer_t api_timer_create(int interval, bool is_period, bool auto_start,
  21. on_user_timer_update_f on_timer_update)
  22. {
  23. int timer_id = wasm_create_timer(interval, is_period, auto_start);
  24. //TODO
  25. struct user_timer * timer = (struct user_timer *) malloc(
  26. sizeof(struct user_timer));
  27. if (timer == NULL) {
  28. // TODO: remove the timer_id
  29. printf("### api_timer_create malloc faild!!! \n");
  30. return NULL;
  31. }
  32. memset(timer, 0, sizeof(*timer));
  33. timer->timer_id = timer_id;
  34. timer->user_timer_callback = on_timer_update;
  35. if (g_timers == NULL)
  36. g_timers = timer;
  37. else {
  38. timer->next = g_timers;
  39. g_timers = timer;
  40. }
  41. return timer;
  42. }
  43. void api_timer_cancel(user_timer_t timer)
  44. {
  45. user_timer_t t = g_timers, prev = NULL;
  46. wasm_timer_cancel(timer->timer_id);
  47. while (t) {
  48. if (t == timer) {
  49. if (prev == NULL) {
  50. g_timers = t->next;
  51. free(t);
  52. } else {
  53. prev->next = t->next;
  54. free(t);
  55. }
  56. return;
  57. } else {
  58. prev = t;
  59. t = t->next;
  60. }
  61. }
  62. }
  63. void api_timer_restart(user_timer_t timer, int interval)
  64. {
  65. wasm_timer_restart(timer->timer_id, interval);
  66. }
  67. void on_timer_callback(int timer_id)
  68. {
  69. struct user_timer * t = g_timers;
  70. while (t) {
  71. if (t->timer_id == timer_id) {
  72. t->user_timer_callback(t);
  73. break;
  74. }
  75. t = t->next;
  76. }
  77. }