#include <stdarg.h>
#include "../User/include/includes.h"

volatile uint32_t SysTick_100us = 0;
volatile uint32_t SysTick_1ms = 0;
volatile uint32_t SysTick_1s = 0;

void WDT_Init(void)
{
    WWDG_ResetCfg(ENABLE);
    WWDG_SetCounter(WDT_NUM);
}

void WDT_Feed(void)
{
    WWDG_ClearFlag();
    WWDG_SetCounter(WDT_NUM);
}




__INTERRUPT
__HIGH_CODE
void SysTick_Handler(void)
{
    SysTick->SR = 0;                    //清除中断标志

    static uint8_t NUM = 0;
    static uint16_t NUM_s = 0;
    SysTick_100us++;
    NUM++;

    if(NUM >= 10){
        NUM = 0;
        SysTick_1ms++;
        NUM_s++;
        if(NUM_s == 1000)
        {
            NUM_s = 0;
            SysTick_1s++;
        }
    }
}


#ifdef DEBUG
int _write(int fd, char *buf, int size)
{
    int i;
    for(i = 0; i < size; i++)
    {
#if DEBUG == Debug_UART0
        while(R8_UART_TFC == UART_FIFO_SIZE);                  /* 等待数据发送 */
            R8_UART_THR = *buf++; /* 发送数据 */
#endif
    }
    return size;
}
#endif




/*Debug输出打印相关变量*/
uint32_t SysTick_Now = 0, SysTick_Last = 0, SysTick_Diff = 0;
char Dbg_Buffer[100];

uint32_t Dbg_Switch = (DBG_OPT_Debug_STATUS << DBG_BIT_Debug_STATUS)
        + (DBG_OPT_PC_COMM << DBG_BIT_PC_COMM)
        + (DBG_OPT_BLE_STATUS << DBG_BIT_BLE_STATUS)
        + (DBG_OPT_DEVICE_STATUS << DBG_BIT_DEVICE_STATUS)
        + (DBG_OPT_SYS_STATUS << DBG_BIT_SYS_STATUS);


void Dbg_NoTick_Println(int DbgOptBit, const char *cmd, ...) {
    if (DBG_LOG_EN && (Dbg_Switch & (1 << DbgOptBit))) {
        va_list args;       //定义一个va_list类型的变量，用来储存单个参数
        va_start(args, cmd); //使args指向可变参数的第一个参数
        vprintf(cmd, args);  //必须用vprintf等带V的
        va_end(args);       //结束可变参数的获取
        DBG_Printf("\r\n");
    }
}

void Dbg_Println(int DbgOptBit, const char *cmd, ...) {
    if (DBG_LOG_EN && (Dbg_Switch & (1 << DbgOptBit))) {
        SysTick_Now = SysTick_1ms;
        SysTick_Diff = SysTick_Now - SysTick_Last;      //上一次打印时间差
        SysTick_Last = SysTick_Now;
        sprintf(Dbg_Buffer, "%8d [%6d]: ", SysTick_Now, SysTick_Diff);
        DBG_Printf("%s", Dbg_Buffer);
        va_list args;       //定义一个va_list类型的变量，用来储存单个参数
        va_start(args, cmd); //使args指向可变参数的第一个参数
        vprintf(cmd, args);  //必须用vprintf等带V的
        va_end(args);       //结束可变参数的获取
        DBG_Printf("\r\n");

    }
}

void Dbg_Print_Buff(int DbgOptBit, const char *cmd, uint8_t *buff, uint32_t len) {
    if (DBG_LOG_EN && (Dbg_Switch & (1 << DbgOptBit))) {
        SysTick_Now = SysTick_1ms;
        SysTick_Diff = SysTick_Now - SysTick_Last;      //上一次打印时间差
        SysTick_Last = SysTick_Now;
        sprintf(Dbg_Buffer, "%8d [%6d]: ", SysTick_Now, SysTick_Diff);
        DBG_Printf("%s%s", Dbg_Buffer, cmd);
        for (uint32_t i = 0; i < len; i++) {
            DBG_Printf("%02X ", buff[i]);
        }
        DBG_Printf("\r\n");
    }
}



