#include "kit_time.h"
#include "kit_debug.h"

#ifdef NO_OS
    uint32_t sys_tick = 0;
#elif defined UCOS2
	uint32_t sys_tick = 0;
    #include "ucos_ii.h"
#endif
    
    
void kit_time_beat(void)
{
#ifdef NO_OS
    sys_tick++;
#elif defined UCOS2
    OSTimeTick();
#endif
}    
    
uint32_t kit_time_get_tick(void)
{
#ifdef NO_OS
 return sys_tick;
#else
	sys_tick = OSTimeGet();
 return OSTimeGet();
#endif    
}


uint32_t kit_time_get_interval(uint32_t old_tick, uint32_t new_tick)
{
    uint32_t interval = 0;
    
    if(new_tick >= old_tick) 
        interval = new_tick - old_tick;
    else
        interval = new_tick + ((uint32_t)0xFFFFFFFF - old_tick);

    return interval;
}


uint32_t kit_time_get_interval_by_now(uint32_t last_tick)
{
    uint32_t interval = kit_time_get_interval(last_tick, kit_time_get_tick());
    
    return interval;
}

uint32_t kit_time_get_interval_by_now_and_update(uint32_t *last_tick)
{
    uint32_t now_tick = kit_time_get_tick();
    uint32_t interval = kit_time_get_interval(*last_tick, now_tick);
    
    *last_tick = now_tick;
    return interval;
}

#include "drv_clk.h"
//延时和主频相关，M4 1us 系数为33
void kit_time_dly_us(uint32_t dly)
{
    if(dly >= 1)
    {
		
        dly = dly * ((uint32_t)33 * 168 * 1000000 / CLOCK_SYS_FREQ);
        while(--dly);
    }
}

void kit_time_dly_100ns(void)
{
	__nop();
}

kit_ret_e kit_wait_flag(volatile uint32_t *reg, uint32_t flag_bit, int32_t timeout)
{
    kit_ret_e res = kKit_Ret_Ok;
    
    KIT_ASSERT_PARAM((reg != NULL) && (flag_bit != 0) && (timeout > 0));
    
    while((*reg & flag_bit) == 0)
    {
        if(timeout-- < 0)
        {           
            res = kKit_Ret_TimeOut;
            break;
        }
    }
    
    return res;
}

void kit_time_dly_ms(uint32_t dly)
{
#ifdef NO_OS
    uint32_t tick = kit_time_get_tick();
    while((kit_time_get_tick() - tick) < dly);
#elif defined UCOS2
    OSTimeDly(dly);
#endif            
}

void kit_time_dly_by_fix_period(uint32_t last_tick,uint16_t period)
{
    uint32_t tick_diff = 0;
    
    tick_diff = kit_time_get_interval_by_now(last_tick);
    
    if (tick_diff < period)
        kit_time_dly_ms(period - tick_diff);
    else
        kit_time_dly_ms(1);
}


//返回时间格式和time.h中定义一致
struct tm * kit_time_get_date(uint16_t start_year, uint32_t stamp)
{
	struct tm tmp;
	tmp.tm_year = start_year - 1900;
	tmp.tm_mon = 1 - 1;
	tmp.tm_mday = 1;
	tmp.tm_hour = 0;
	tmp.tm_min = 0;
	tmp.tm_sec = 0;
	tmp.tm_isdst = -1;

	stamp += mktime(&tmp);
	return localtime(&stamp);
}

uint32_t kit_time_get_stamp(uint16_t start_year, struct tm *time)
{
	struct tm tmp;
	tmp.tm_year = start_year - 1900;
	tmp.tm_mon = 1 - 1;
	tmp.tm_mday = 1;
	tmp.tm_hour = 0;
	tmp.tm_min = 0;
	tmp.tm_sec = 0;
	tmp.tm_isdst = -1;

	return mktime(time) - mktime(&tmp);
}

    
