#include "sys.h"
#include <stdio.h> //NULL

/* 设定定时器
    @param  计时器
    @param  时间（微秒); 设定为0则关闭定时器
*/
void Timer_Set(SYSTIMER *timer, unsigned long alarm_time)
{
    gettimeofday(&timer->start_cnt, NULL);
    timer->alarm_time = alarm_time;
}

/* 查询时间是否到达
    @return 1 时间到　０　时间未到
    @param  计时器
*/
char Timer_GetReached(SYSTIMER *timer)
{
    if (timer->alarm_time != 0)
    {
        struct timeval end_cnt;
        gettimeofday(&end_cnt, NULL);
        unsigned long time_diff = (end_cnt.tv_sec - timer->start_cnt.tv_sec) * 1000000 + (end_cnt.tv_usec - timer->start_cnt.tv_usec);
        if (time_diff > timer->alarm_time)
        {
            return 1;
        }
    }
    return 0;
}

#ifdef WIN32
/* WINDOWS兼容gettimeofday */
int gettimeofday(struct timeval *tp, void *tzp)
{
    time_t clock;
    struct tm tm;
    SYSTEMTIME wtm;
    GetLocalTime(&wtm);
    tm.tm_year = wtm.wYear - 1900;
    tm.tm_mon = wtm.wMonth - 1;
    tm.tm_mday = wtm.wDay;
    tm.tm_hour = wtm.wHour;
    tm.tm_min = wtm.wMinute;
    tm.tm_sec = wtm.wSecond;
    tm.tm_isdst = -1;
    clock = mktime(&tm);
    tp->tv_sec = clock;
    tp->tv_usec = wtm.wMilliseconds * 1000;
    return (0);
}
#endif