/*
 * Copyright (c) 2006-2019, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-05-24                  the first version
 */

#include <rthw.h>
#include <rtthread.h>

#include "main.h"

#define USING_RTT_AS_CONSOLE
#ifdef USING_RTT_AS_CONSOLE
#include "SEGGER_RTT.h"
#else
#include "usart.h"  // 包含UART句柄
#endif
#if defined(RT_USING_USER_MAIN) && defined(RT_USING_HEAP)
/*
 * Please modify RT_HEAP_SIZE if you enable RT_USING_HEAP
 * the RT_HEAP_SIZE max value = (sram size - ZI size), 1024 means 1024 bytes
 */
#define RT_HEAP_SIZE (15 * 1024)
static rt_uint8_t rt_heap[RT_HEAP_SIZE];

RT_WEAK void *rt_heap_begin_get(void)
{
    return rt_heap;
}

RT_WEAK void *rt_heap_end_get(void)
{
    return rt_heap + RT_HEAP_SIZE;
}
#endif

void SysTick_Handler(void)
{
    rt_interrupt_enter();

    rt_tick_increase();

    rt_interrupt_leave();
}

#ifdef RT_USING_FINSH
#include <finsh.h>
static void reboot(uint8_t argc, char **argv)
{
    rt_hw_cpu_reset();
}
MSH_CMD_EXPORT(reboot, Reboot System);
#endif /* RT_USING_FINSH */

/**
 * This function will initial your board.
 */
void rt_hw_board_init(void)
{
    extern void SystemClock_Config(void);

    HAL_Init();
    SystemClock_Config();
    SystemCoreClockUpdate();
    /* 
     * 1: OS Tick Configuration
     * Enable the hardware timer and call the rt_os_tick_callback function
     * periodically with the frequency RT_TICK_PER_SECOND. 
     */
    HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq() / RT_TICK_PER_SECOND);
#ifdef USING_RTT_AS_CONSOLE
    SEGGER_RTT_Init();
#else
    // 在UART模式下，确保UART1已经初始化用于控制台输出
    extern void MX_USART1_UART_Init(void);
    MX_USART1_UART_Init();
#endif
    /* Call components board initial (use INIT_BOARD_EXPORT()) */
#ifdef RT_USING_COMPONENTS_INIT
    rt_components_board_init();
#endif

#if defined(RT_USING_USER_MAIN) && defined(RT_USING_HEAP)
    rt_system_heap_init(rt_heap_begin_get(), rt_heap_end_get());
#endif
}

#ifdef RT_USING_CONSOLE

#ifdef USING_RTT_AS_CONSOLE

void rt_hw_console_output(const char *str)
{
    SEGGER_RTT_WriteString(0, str);
}
#else

void rt_hw_console_output(const char *str)
{
    rt_size_t size = rt_strlen(str);
    
    // 使用外部定义的huart1句柄，超时时间设为1000ms
    HAL_UART_Transmit(&huart1, (uint8_t *)str, size, 1000);
}
#endif /* USING_RTT_AS_CONSOLE */
#endif

#ifdef RT_USING_FINSH

char rt_hw_console_getchar(void)
{
    /* Note: the initial value of ch must < 0 */
    int ch = -1;
#ifdef USING_RTT_AS_CONSOLE
    if (SEGGER_RTT_Read(0, &ch, 1) == 0)
    {
        rt_thread_mdelay(10); // 未读到数据时主动让出CPU
    }
#else
    if (__HAL_UART_GET_FLAG(&huart1, UART_FLAG_RXNE) != RESET)
    {
        ch = huart1.Instance->DR & 0xff;
    }
    else
    {
        rt_thread_mdelay(10);
    }
#endif
    return ch;
}
#endif
