sc_timer_service.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. /*
  2. * sc_timer_service.c
  3. *
  4. * Created on: 13.04.2016
  5. * Author: korsinski, terfloth
  6. */
  7. #include <stdlib.h>
  8. #include <stdio.h>
  9. #include "sc_timer_service.h"
  10. /*! \file Implementation of YAKINDU SCT timer functionality based on POSIX threads. */
  11. /*! Callback that is called when a timer fires. */
  12. static void sc_timer_fired(sc_timer_t *timer) {
  13. timer->service->raise_event(timer->handle, timer->pt_evid);
  14. }
  15. /*! Starts a timer with the specified parameters. */
  16. void sc_timer_start(sc_timer_service_t *this, void* handle, const sc_eventid evid,
  17. const sc_integer time_ms, const sc_boolean periodic) {
  18. /* go through all timers ... */
  19. for (int i = 0; i < this->timer_count; i++) {
  20. /* ... and find an unused one. */
  21. if (this->timers[i].pt_evid == NULL) {
  22. /* set timer properties */
  23. this->timers[i].pt_evid = evid;
  24. this->timers[i].time_ms = time_ms;
  25. this->timers[i].periodic = periodic;
  26. this->timers[i].handle = handle;
  27. this->timers[i].service = this;
  28. // reset the elapsed time ...
  29. this->timers[i].elapsed_time_ms = 0;
  30. break;
  31. }
  32. }
  33. }
  34. /*! Cancels a timer for the specified time event. */
  35. void sc_timer_cancel(sc_timer_service_t *this, const sc_eventid evid) {
  36. int i;
  37. for (i = 0; i < this->timer_count; i++) {
  38. if (this->timers[i].pt_evid == evid) {
  39. this->timers[i].pt_evid = NULL;
  40. this->timers[i].handle = NULL;
  41. break;
  42. }
  43. }
  44. }
  45. /*! Initializes a timer service with a set of timers. */
  46. void sc_timer_service_init(sc_timer_service_t *tservice,
  47. sc_timer_t *timers,
  48. sc_integer count,
  49. sc_raise_time_event_fp raise_event) {
  50. tservice->timers = timers;
  51. tservice->timer_count = count;
  52. for (int i=0; i<count; i++) {
  53. tservice->timers->pt_evid = NULL;
  54. tservice->timers->service = tservice;
  55. }
  56. tservice->raise_event = raise_event;
  57. }
  58. void sc_timer_service_proceed(sc_timer_service_t *this, const sc_integer time_ms) {
  59. /* go through all timers ... */
  60. for (int i = 0; i < this->timer_count; i++) {
  61. /* ... and process all used. */
  62. if (this->timers[i].pt_evid != NULL) {
  63. if (this->timers[i].elapsed_time_ms < this->timers[i].time_ms) {
  64. this->timers[i].elapsed_time_ms += time_ms;
  65. if (this->timers[i].elapsed_time_ms >= this->timers[i].time_ms) {
  66. sc_timer_fired(&(this->timers[i]));
  67. if (this->timers[i].periodic) {
  68. this->timers[i].elapsed_time_ms -= this->timers[i].time_ms;
  69. }
  70. }
  71. }
  72. }
  73. }
  74. }