/*
 * @Author       : stark1898y 1658608470@qq.com
 * @Date         : 2024-12-15 15:01:15
 * @LastEditors  : stark1898y 1658608470@qq.com
 * @LastEditTime : 2025-05-16 18:21:05
 * @FilePath     : \BLE_TYQ_CH584M\BSP\src\bsp_tim.c
 * @Description  :
 *
 * Copyright (c) 2024 by yzy, All Rights Reserved.
 */
#include "bsp_tim.h"

// tick_1ms_cnt在SysTick_Handler()中1ms +1
volatile uint32_t tick_1ms_cnt = 0;

#if 0
// 要是用32k做差，可以这样
// 最大就是一天
__HIGH_CODE
uint32_t plat_rtc_get(void)
{
    volatile uint32_t i;
    do {
        i = R32_RTC_CNT_32K;
    } while (i != R32_RTC_CNT_32K);
    return (i);
}

__HIGH_CODE
uint32_t ch5xx_get_rtc_gap(uint32_t last, uint32_t current)
{
    if (current > last)
    {
        return (current - last);
    }
    else
    {
        return (32768 * 3600 * 24UL - last + current);
    }
}

uint32_t last_rtc_cnt = plat_rtc_get();
// do sleep
uint32_t current_rtc_cnt = plat_rtc_get();

if (ch5xx_get_rtc_gap(last_rtc_cnt, current_rtc_cnt) > 32768 * 10)
{
    // do bat level sample
}
#endif

// return local time in seconds, max 44 year
__HIGH_CODE
uint32_t CH5XX_GetTimeStamp(uint16_t *tick)
{
    uint32_t t, t32k;
    uint16_t day, sec2;
    do {
        t32k = R32_RTC_CNT_32K;
        day  = R32_RTC_CNT_DAY & 0x3FFF;
        sec2 = R16_RTC_CNT_2S;
    } while (t32k != R32_RTC_CNT_32K);

    t = day * 86400 + (sec2 << 1) + ((t32k < 0x8000) ? 0 : 1);
    if (tick != NULL)
    {
        *tick = t32k & 0X7FFF;
    }
    return t;
}

/**
 * @description: 以SysTick（1ms）为基础
 * @return {uint32_t}
 */
uint32_t BSP_Get_Tick(void)
{
    /* Platform implementation */
    // current system clock (in 0.625ms)
    // return (uint32_t)((double)TMOS_GetSystemClock() / 1.6);

    uint32_t seconds = 0;
    uint16_t tick_1sec = 0;
    seconds = CH5XX_GetTimeStamp(&tick_1sec);
    return (seconds * 1000 + (tick_1sec * 1000 / 32768));
    // logDebug("seconds = %d.%d", seconds, tick_1sec * 1000 / 32768);
}

// SysTick中断函数
__INTERRUPT
__HIGH_CODE
void SysTick_Handler()
{
    static uint8_t cnt_ms = 0;

    SysTick->SR = 0; // 清除中断标志
    tick_1ms_cnt++;

    cnt_ms++;
}
