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

#include "bsp_uart.h"
#include "log.h"

#include "SLEEP.h"

// https://www.cnblogs.com/debugdabiaoge/p/17580033.html
// https://www.cnblogs.com/risc5-ble/p/17853714.html

#undef LOG_ENABLE
#define LOG_ENABLE 1

#undef LOG_TAG
#define LOG_TAG "tim"

// 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);
}



/* 定时器0，设定100ms定时器进行IO口闪灯， PB15-LED */
void BSP_TMR0_Init()
{
    TMR0_TimerInit(FREQ_SYS / 1000 * 20); // 设置定时时间
    // TMR0_TimerInit(FREQ_SYS); // 设置定时时间
    TMR0_ITCfg(ENABLE, TMR0_3_IT_CYC_END);  // 开启中断
    PFIC_EnableIRQ(TMR0_IRQn);
}

/*********************************************************************
 * @fn      TMR0_IRQHandler
 *
 * @brief   TMR0中断函数
 *
 * @return  none
 */
__INTERRUPT
__HIGH_CODE
void TMR0_IRQHandler(void) // TMR0 定时中断
{
    if(TMR0_GetITFlag(TMR0_3_IT_CYC_END))
    {
        TMR0_ClearITFlag(TMR0_3_IT_CYC_END); // 清除中断标志

        BSP_RequestSleep();
        PFIC_DisableIRQ(TMR0_IRQn);
    #if 0
        uint32_t v_mepc, v_mcause, v_mtval;
        logDebug("hardfault\n");

        v_mepc   = __get_MEPC();
        v_mcause = __get_MCAUSE();
        v_mtval  = __get_MTVAL();

        logDebug("mepc:%08x\n", v_mepc);
        logDebug("mcause:%08x\n", v_mcause);
        logDebug("mtval:%08x\n", v_mtval);

        FLASH_ROM_SW_RESET();
        sys_safe_access_enable();
        R16_INT32K_TUNE = 0xFFFF;
        sys_safe_access_disable();
        sys_safe_access_enable();
        R8_RST_WDOG_CTRL |= RB_SOFTWARE_RESET;
        sys_safe_access_disable();
    #endif
        // struct __MEMORY_CTL
        // {
        //     struct __MEMORY_CTL *pNext;
        //     uint16_t len;
        //     uint16_t used;
        // };
        // typedef struct __MEMORY_CTL MemoryCtl;

        // extern MemoryCtl *MemCtlStart;
        // extern MemoryCtl *MemCtlEnd;
        // MemoryCtl *MemHead;
        // MemHead = MemCtlStart;
        // while (MemHead != MemCtlEnd)
        // {
        //     logDebug("|%8x,%8x,%8d.....\n", MemHead->used, (uint32_t)MemHead,
        //         (uint32_t)(MemHead->pNext) - (uint32_t)MemHead - sizeof(struct __MEMORY_CTL));
        //     MemHead = MemHead->pNext;
        // }
        // logDebug("\n");

        uint32_t v_mepc, v_mcause, v_mtval;

        v_mepc   = __get_MEPC();
        v_mcause = __get_MCAUSE();
        v_mtval  = __get_MTVAL();

        logDebug("00000000000000000");
        logDebug("mepc:%08x", v_mepc);
        logDebug("mcause:%08x", v_mcause);
        logDebug("mtval:%08x", v_mtval);
        logDebug("1111111111111111");

    #if 0
        FLASH_ROM_SW_RESET();
        sys_safe_access_enable();
        R16_INT32K_TUNE = 0xFFFF;
        sys_safe_access_disable();
        sys_safe_access_enable();
        R8_RST_WDOG_CTRL |= RB_SOFTWARE_RESET;
        sys_safe_access_disable();
    #endif
        // while (1);
    }
}

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

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

    cnt_ms++;
}
