#include #include #include #include #include "timer.h" typedef struct { rt_timer_t timer; int times; int times_max; timer_fn_t fn; void *arg; int inited; }timer_handle_t; static void timer_callback(void *arg) { timer_handle_t *h=(timer_handle_t*)arg; if(h->fn) { if(h->times_max>0 && h->timestimes_max) { int last=0; h->times++; if(h->times==h->times_max) { last = 1; } h->fn(h->arg, last); } else { h->fn(h->arg, 0); } } } static int set_time(timer_handle_t *h, int t) { rt_timer_delete(h->timer); h->timer = rt_timer_create("timer", timer_callback, h, rt_tick_from_millisecond(t), RT_TIMER_FLAG_PERIODIC); return 0; } int timer_init(void) { int r; timer_handle_t *h=(timer_handle_t*)malloc(sizeof(timer_handle_t)); if(!h) { return -1; } h->timer = NULL; h->times = 0; h->times_max = 0; h->fn = NULL; h->arg = NULL; h->inited = 1; return (int)h; } int timer_deinit(int h) { int r; timer_handle_t *th=(timer_handle_t*)h; if(h==-1 || !th->inited) { return -1; } rt_timer_delete(th->timer); th->inited = 0; free(th); return r; } int timer_start(int h, int t, int times, timer_fn_t fn, void *arg) { int r; timer_handle_t *th=(timer_handle_t*)h; if(h==-1 || !th->inited) { return -1; } rt_timer_stop(th->timer); th->times = 0; th->times_max = times; th->fn = fn; th->arg = arg; r = set_time(th, t); return rt_timer_start(th->timer); } int timer_stop(int h) { int r; timer_handle_t *th=(timer_handle_t*)h; if(h==-1 || !th->inited) { return -1; } return rt_timer_stop(th->timer); }