| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113 |
- #include <time.h>
- #include <signal.h>
- #include <stdlib.h>
- #include <rtthread.h>
- #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->times<h->times_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);
- }
|