#include "CONFIG.h"
#include "HAL.h"
#include "gattprofile.h"
#include "peripheral.h"

#include "bsp_adc.h"

#include "bsp_key.h"

#include "bsp_beep_led_emv.h"

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

#include "bsp_i2c.h"

#include "bsp_iwdg.h"
#include "bsp_flash.h"

#include "bsp_valve.h"

#include "bsp_bat.h"

#undef LOG_ENABLE
#define LOG_ENABLE 1

#undef LOG_TAG
#define LOG_TAG "main"

__attribute__((aligned(4))) uint32_t MEM_BUF[BLE_MEMHEAP_SIZE / 4];

static uint8_t key_press_cnt = 0;

// __HIGH_CODE
void app_task_handler(TeAppEvtType app_evt_type)
{
    // FEED_IWDG();

    BSP_BlockSleep();
    BSP_RequestBoost();

#if 1
    switch (app_evt_type)
    {
        case kKeyShort:
        {
            logDebug("button short press");

            key_press_cnt++;
            logDebug("key_press_cnt = %d", key_press_cnt);
        #if 1
            // tmos_set_event(vavle_task_id, VAVLE_DECT_SWITCH_START_EVT);
            if (key_press_cnt == 1)
            {
                logDebug("LED显示状态");
                // tmos_set_event(led_task_id, LED_SHOW_START_EVT);
                BSP_BlockSleep();
                // BSP_RequestBoost();
                DelayMs(3);
                ShowLed();
                // tmos_stop_task(led_task_id, LED_SHOW_ONCE_EVT);
                // tmos_start_task(led_task_id, LED_SHOW_ONCE_EVT, 1000);
            }
            else if (key_press_cnt == 2)
            {
                if (gValveData.switch_status == kClosed)
                {
                    logDebug("kClosed-->kOpened");
                    // tmos_set_event(led_task_id, LED_SHOW_START_EVT);
                    gValveData.switch_status = kOpened;
                    BSP_BlockSleep();
                    // BSP_RequestBoost();
                    DelayMs(3);
                    ShowLed();
                    // tmos_stop_task(led_task_id, LED_SHOW_ONCE_EVT);
                    // tmos_start_task(led_task_id, LED_SHOW_ONCE_EVT, 1000);
                }
                else if (gValveData.switch_status != kClosed)
                {
                    logDebug("kOpened-->kClosed");
                    gValveData.switch_status = kClosed;
                    tmos_set_event(vavle_task_id, VAVLE_CLOSE_START_EVT);

                    // tmos_set_event(led_task_id, LED_SHOW_START_EVT);
                    BSP_BlockSleep();
                    // BSP_RequestBoost();
                    DelayMs(3);
                    ShowLed();
                    // tmos_stop_task(led_task_id, LED_SHOW_ONCE_EVT);
                    // tmos_start_task(led_task_id, LED_SHOW_ONCE_EVT, 1000);
                }
            }
        #endif
            break;
        }
        case kKeyLong:
            logDebug("button long press");

            break;
        case kKeyRelease:
            // BSP_KEY_EnterLowpower();
            // DelayMs(10);
            key_press_cnt = 0;
            // BSP_RequestSleep();
            // tmos_set_event(led_task_id, LED_SHOW_END_EVT);

            LED_ALL_OFF_DEINIT;
            BEEP_OFF_DEINIT;

            BSP_NoNeedBoost();
            BSP_RequestSleep();

            logDebug("gpio relase;BSP_RequestSleep");

            break;
        default:
            break;
    }
#endif

}

/*********************************************************************
 * @fn      Main_Circulation
 *
 * @brief   主循环
 *
 * @return  none
 */
__HIGH_CODE
__attribute__((noinline)) void Main_Circulation()
{
    while (1)
    {
        TMOS_SystemProcess();
        KEY_ProcessLoop();
        BSP_UART1_TxLoop();
        // FEED_IWDG();
    }
}

// https://www.cnblogs.com/gscw/p/18530905
// 在连接间隔和广播间隔到来时，会进入该回调，可以在回调函数加上其他执行逻辑代码，如喂狗等。
void BLE_AdvertiseEventCB(uint32_t timeUs)
{
    FEED_IWDG();
    logDebug("BLE_AdvertiseEventCB");
}

void BLE_ConnectEventCB(uint32_t timeUs)
{
    FEED_IWDG();
    logDebug("BLE_ConnectEventCB");
}

/*********************************************************************
 * @fn      main
 *
 * @brief   主函数
 *
 * @return  none
 */
int main(void)
{
#if (defined(DCDC_ENABLE)) && (DCDC_ENABLE == TRUE)
    PWR_DCDCCfg(ENABLE);
#endif
    HSECFG_Capacitance(HSECap_18p);
    SetSysClock(CLK_SOURCE_HSE_PLL_62_4MHz);

#if (defined(HAL_SLEEP)) && (HAL_SLEEP == TRUE)
    GPIOA_ModeCfg(GPIO_Pin_All, GPIO_ModeIN_PD);
    GPIOB_ModeCfg(GPIO_Pin_All, GPIO_ModeIN_PD);
#endif
#ifdef DEBUG
    // 改成 4000000 波特率了
    BSP_UART1_Init(4000000);
#endif
    DelayMs(1000 * 1);

    ShowRestartReason();

    // log打印编译时间和编译日期
    logDebug("Compile Time: %s %s", __DATE__, __TIME__);
    logDebug("GetSysClock = %d Hz", GetSysClock());
    logDebug("Start @ChipID=%02X\n", R8_CHIP_ID);
    logError("中文测试 %2.2f", 123.456);
    logDebug("%s\n", VER_LIB);

    uint8_t MacAddr[6];
    GetMACAddress(MacAddr);
    // 手机APP显示是倒序的[5-0],不是[0-5]
    logDebug("MacAddr: %02X:%02X:%02X:%02X:%02X:%02X", MacAddr[0], MacAddr[1], MacAddr[2], MacAddr[3], MacAddr[4], MacAddr[5]);

    CH58x_BLEInit();
    HAL_Init();
    GAPRole_PeripheralInit();
    Peripheral_Init();

    BSP_FLASH_Init();

    BSP_KEY_Init(app_task_handler);
    BSP_BEEP_LED_EMV_Init();
    GXHTC3C_Init();
    BSP_ADC_Init();

    BSP_BlockSleep();
    BSP_RequestBoost();
    DelayMs(100);

    BSP_VAVLE_Init();


    ShowLed();
    BEEP_ON;
    DelayMs(500);

    LED_ALL_OFF_DEINIT;
    BEEP_OFF_DEINIT;
    BSP_NoNeedBoost();
    BSP_RequestSleep();

    IWDG_Init(IWDG_TIMEOUT_MS);

    logDebug("BSP_Get_Tick1 %d", BSP_Get_Tick());
    DelayMs(1000);
    logDebug("BSP_Get_Tick2 %d", BSP_Get_Tick());

    // 在连接间隔和广播间隔到来时，会进入回调中喂狗
    // LL_AdvertiseEventRegister(BLE_AdvertiseEventCB);
    // LL_ConnectEventRegister(BLE_ConnectEventCB);

    Main_Circulation();
}

/******************************** endfile @ main ******************************/
