timer.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. /*
  2. * Copyright (C) 2019 Intel Corporation. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "timer_wasm_app.h"
  17. #include "native_interface.h"
  18. #include <stdlib.h>
  19. #include <string.h>
  20. #if 1
  21. #include <stdio.h>
  22. #else
  23. #define printf (...)
  24. #endif
  25. struct user_timer {
  26. struct user_timer * next;
  27. int timer_id;
  28. void (*user_timer_callback)(user_timer_t);
  29. };
  30. struct user_timer * g_timers = NULL;
  31. user_timer_t api_timer_create(int interval, bool is_period, bool auto_start,
  32. void (*on_timer_update)(user_timer_t))
  33. {
  34. int timer_id = wasm_create_timer(interval, is_period, auto_start);
  35. //TODO
  36. struct user_timer * timer = (struct user_timer *) malloc(
  37. sizeof(struct user_timer));
  38. if (timer == NULL) {
  39. // TODO: remove the timer_id
  40. printf("### api_timer_create malloc faild!!! \n");
  41. return NULL;
  42. }
  43. memset(timer, 0, sizeof(*timer));
  44. timer->timer_id = timer_id;
  45. timer->user_timer_callback = on_timer_update;
  46. if (g_timers == NULL)
  47. g_timers = timer;
  48. else {
  49. timer->next = g_timers;
  50. g_timers = timer;
  51. }
  52. return timer;
  53. }
  54. void api_timer_cancel(user_timer_t timer)
  55. {
  56. user_timer_t t = g_timers, prev = NULL;
  57. wasm_timer_cancel(timer->timer_id);
  58. while (t) {
  59. if (t == timer) {
  60. if (prev == NULL) {
  61. g_timers = t->next;
  62. free(t);
  63. } else {
  64. prev->next = t->next;
  65. free(t);
  66. }
  67. return;
  68. } else {
  69. prev = t;
  70. t = t->next;
  71. }
  72. }
  73. }
  74. void api_timer_restart(user_timer_t timer, int interval)
  75. {
  76. wasm_timer_restart(timer->timer_id, interval);
  77. }
  78. void on_timer_callback(int timer_id)
  79. {
  80. struct user_timer * t = g_timers;
  81. while (t) {
  82. if (t->timer_id == timer_id) {
  83. t->user_timer_callback(t);
  84. break;
  85. }
  86. t = t->next;
  87. }
  88. }