/**************************************************************************//**
 * @file     main.c
 * @brief    Main program body
 * @version  V4.0.1
 * @date     30-July-2026
 *
 * @note
 * Copyright (C) 2022 Spintrol Electronic Technology (Shanghai) Co., Ltd.. All rights reserved.
 *
 * @attention
 * THIS SOFTWARE JUST PROVIDES CUSTOMERS WITH CODING INFORMATION REGARDING 
 * THEIR PRODUCTS, WHICH AIMS AT SAVING TIME FOR THEM. SPINTROL SHALL NOT BE
 * LIABLE FOR THE USE OF THE SOFTWARE. SPINTROL DOES NOT GUARANTEE THE 
 * CORRECTNESS OF THIS SOFTWARE AND RESERVES THE RIGHT TO MODIFY THE SOFTWARE 
 * WITHOUT NOTIFICATION.
 *
 ******************************************************************************/

#include <stdio.h>
#include "iap.h"

#if defined(SPC1158)
#include "spc1158.h"
#elif defined(SPD1148)
#include "spd1148.h"
#elif defined(SPD1178)
#include "spd1178.h"
#elif defined(SPD1188)
#include "spd1188.h"
#elif defined(SPD1163)
#include "spd1163.h"
#else
#include "spc1168.h"
#endif



/**
 *  @brief Function pointer for jump branch
 */
typedef void (*PTRJUMP)(void);


/* Entry Point */
uint32_t *pu32Entry;




int main(void)
{
    volatile uint32_t u32TimeOut;

    /* Set Flash Timing */
    FLASH_WALLOW();

#if defined(SPC1158)
    FLASH_SetTiming(100000000);

    CLOCK_InitWithRCO(CLOCK_HCLK_100MHZ);
#else
    FLASH_SetTiming(200000000);

    CLOCK_InitWithRCO(CLOCK_HCLK_200MHZ);
#endif

    /* Delay Init */
    Delay_Init();


    /* UART Init */
    GPIO_SetPinChannel(GPIO_34, GPIO34_UART_TXD);
    GPIO_SetPinChannel(GPIO_35, GPIO35_UART_RXD);

    UART_Init(UART, 38400);

    /* Wait for handshake byte with timeout 5s */
    u32TimeOut = 50;
    while(u32TimeOut--)
    {
        /* Check the received handshake byte (0x7F) */
        if(UART_IsRxNotEmpty(UART))
        {
            if(UART->UARTRBR_UARTTHR_UARTDLL.UARTRBR.all == 0x7F)
            {
                /* Received correct handshake byte, return ACK */
                Drv_UartWriteByte(0x79);

                /* Enter application loading process */
                IAP_LoadFromUart();
            }
        }

        /* Delay 100ms */
        Delay_Ms(100);
    }

    /* Entry point */
    pu32Entry = (uint32_t *)(0x10002000 + 4);

    /* Jump to the application */
    ((PTRJUMP)(*pu32Entry))();


    while(1)
    {
    }
}

/******************* Copyright (C) 2022 Spintrol Electronic Technology (Shanghai) Co., Ltd. ***** END OF FILE ****/
