#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/queue.h>
#include <termios.h>
#include <time.h>
#include "timerlist.h"
unsigned long long timer_get_now_tick(void)
{
struct timespec ts;
unsigned long long value = 0;;
clock_gettime(CLOCK_MONOTONIC, &ts);
value = ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
return value;
}
void timer_list_init(timer_list_head_t *circleq_head)
{
CIRCLEQ_INIT(circleq_head);
}
void timer_list_node_add(timer_list_head_t *circleq_head, timer_node_t *elm)
{
CIRCLEQ_INSERT_TAIL(circleq_head, elm, link);
}
void timer_list_node_del(timer_list_head_t *circleq_head, void *func)
{
timer_node_t *n;
for (n = circleq_head->cqh_first; n != (void *)circleq_head;
n = n->link.cqe_next) {
if (n->do_exe_env== func) {
CIRCLEQ_REMOVE(circleq_head, n, link);
free(n);
break;
}
}
}
void timer_list_add(int run_once, timer_list_head_t *circleq_head, int intv_ms, void *func, void *ptr)
{
timer_node_t *n = (timer_node_t *)malloc(sizeof(timer_node_t));
memset(n, 0, sizeof(timer_node_t));
n->intv_ms = intv_ms;
n->do_exe_env = func;
n->ptr = ptr;
n->run_once = run_once;
n->last_tick = timer_get_now_tick();
timer_list_node_add(circleq_head, n);
}
void timer_env_add(timer_list_head_t *circleq_head, int intv_ms, void *func, void *ptr)
{
timer_list_add(0, circleq_head,intv_ms, func, ptr);
}
void timer_env_add_once(timer_list_head_t *circleq_head, int intv_ms, void *func, void *ptr)
{
timer_list_add(1, circleq_head,intv_ms, func, ptr);
}
void timer_list_check_env(timer_list_head_t *circleq_head)
{
timer_node_t *n;
for (n = circleq_head->cqh_first; n != (void *)circleq_head;
n = n->link.cqe_next) {
unsigned long long nowtick = timer_get_now_tick();
if(abs(nowtick-n->last_tick)>=n->intv_ms) {
n->last_tick = nowtick;
if(n->do_exe_env) {
n->do_exe_env(n->ptr);
if(n->run_once) {
timer_list_node_del(circleq_head, n->do_exe_env);
}
}
}
}
}