/*!
 * @file        main.c
 *
 * @brief       Main program body
 *
 * @version     V1.0.0
 *
 * @date        2026-02-25
 *
 * @attention
 *
 *  Copyright (C) 2026 Geehy Semiconductor
 *
 *  You may not use this file except in compliance with the
 *  GEEHY COPYRIGHT NOTICE (Geehy Semiconductor Software License Agreement).
 *
 *  The program is only for reference, which is distributed in the hope
 *  that it will be useful and instructional for customers to develop
 *  their software. Unless required by applicable law or agreed to in
 *  writing, the program is distributed on an "AS IS" BASIS, WITHOUT
 *  ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the Geehy Semiconductor Software License Agreement for the governing permissions
 *  and limitations under the License.
 */

/* Includes */
#include "Board.h"
#include "main.h"
#include <string.h>
#include "g32a10xx_misc.h"

/** @addtogroup Examples
  @{
  */

/** @addtogroup IAP_Examples
  @{
*/

/** @addtogroup IAP_BootLoader
  @{
  */

/** @defgroup IAP_BootLoader_Variables Variables
  @{
*/

static Iap_JumpAddrType g_jumpAddress = {0U};
static Iap_pFunction JumpToApplication = NULL;
static App_DefType appType= APP1;
/**@} end of group IAP_BootLoader_Variables */

/** @defgroup IAP_BootLoader_Functions Functions
  @{
*/

/*!
 * @brief       Main program
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
int main(void)
{
    uint8_t key = 0U;
    
    Board_ComInit(COM1);
    Nvic_DisableIrqRequest(USART1_IRQn);
    Board_LedInit(LED1);
    Board_LedInit(LED2);
    Board_LedInit(LED3);
    Board_LedOn(LED1);
    Board_LedOff(LED2);
    Board_LedOff(LED3);

    /* Configure the Flash to re-program the Flash */
    Flash_IapInit();
    
    /* Display Select menu */
    SendString("\r\n***************************************************************");
    SendString("\r\n*      g32a1085 In-Application Programming Application       *");
    SendString("\r\n*                                              (Version 1.0.0)*");
    SendString("\r\n***************************************************************");
    SendString("\r\n");

    /* Checks whether the FLASH Write Protection Status is set or not */
    if (Fmc_ReadPflashWriteProtection() != 0xFFFFFFFFU)
    {
        SendString("Chip write protection is set, unable to download program !***\r\n");
        SendString(">> Jump to user application 1\r\n");
        Iap_JumpToApp((uint8_t)APP1);
    }
    else
    {
        /* do nothing */
    }
    
    while(1)
    {
        SendString("\r\n** Please select an operation item \r\n");
        SendString("*  1.Download Flash application 1 -----------------------> 1  *\r\n");
        SendString("*  2.Jump to user application 1   -----------------------> 2  *\r\n");
        SendString("*  3.Download Flash application 2 -----------------------> 3  *\r\n");
        SendString("*  4.Jump to user application 2   -----------------------> 4  *\r\n");
        SendString("***************************************************************\r\n");

        /* Receive key */
        key = Iap_ReadKeyTimeOut(MENU_WAIT_TIMEOUT);

        switch (key)
        {
            case (uint8_t)0x31:/* Download user application in the Flash */
                appType = APP1;
                Iap_Download(appType);
                break;

            case (uint8_t)0x32:/* execute the new program */
            case (uint8_t)0xFF:/* execute the new program */
                SendString(">> Jump to user application 1 \r\n");
                /* Wait all the string output */
                Iap_Delay(1000U);
                Iap_JumpToApp((uint8_t)APP1);
                break;

            case (uint8_t)0x33:/* Download the new program */
                appType = APP2;
                Iap_Download(appType);
                break;

            case (uint8_t)0x34:/* execute the new program */
                SendString(">> Jump to user application 2 \r\n");
                /* Wait all the string output */
                Iap_Delay(1000U);
                Iap_JumpToApp((uint8_t)APP2);
                break;
                
            default:
                SendString(">> Invalid Number ! ==> The number should be either 1, 2 3 4 5 or 6\r\n");
                break;
        }
    }
}

/*!
 * @brief       Jump to user application
 *
 * @param       Application : APP1 or APP2
 *
 * @retval      None
 *
 * @note
 */
void Iap_JumpToApp(uint8_t Application)
{
    uint32_t address;

    if (Application == (uint8_t)APP1)
    {
        address = USER_APP1_START_ADDRESS;
    }
    else
    {
        address = USER_APP2_START_ADDRESS;
    }

    /* Jump to user application */
    g_jumpAddress.Iap_JumpUnion.jumpAddr = *(__IO uint32_t*)(address + (uint32_t)4U);
    JumpToApplication = g_jumpAddress.Iap_JumpUnion.jumpFunAddr;

    /* Initialize user application's Stack Pointer */
    __set_MSP(*(__IO uint32_t*) address);

    /* Jump to application */
    JumpToApplication();
}

void Iap_Delay(volatile uint32_t Value)
{
    volatile uint32_t delay = Value;

    while(delay > 0U)
    {
        delay -= 1U;
    }
}

#if defined (__CC_ARM) || defined (__ICCARM__) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050))

/*!
* @brief       Redirect C Library function printf to serial port.
*              After Redirection, you can use printf function.
*
* @param       ch:  The characters that need to be send.
*
* @param       *f:  pointer to a FILE that can recording all information
*              needed to control a stream
*
* @retval      The characters that need to be send.
*
* @note
*/
int fputc(int ch, FILE* f)
{
    /* send a byte of data to the serial port */
    Usart_TxData(USART_COM, (uint8_t)ch);

    /* wait for the data to be send  */
    while (Usart_ReadStatusFlag(USART_COM, USART_FLAG_TXBE) == 0U)
    {
        /* do nothing */
    }

    return (ch);
}

#elif defined (__GNUC__)

/*!
* @brief       Redirect C Library function printf to serial port.
*              After Redirection, you can use printf function.
*
* @param       ch:  The characters that need to be send.
*
* @retval      The characters that need to be send.
*
* @note
*/
int __io_putchar(int ch)
{
    /* send a byte of data to the serial port */
    Usart_TxData(USART_COM, ch);

    /* wait for the data to be send  */
    while (Usart_ReadStatusFlag(USART_COM, USART_FLAG_TXBE) == RESET);

    return ch;
}

/*!
* @brief       Redirect C Library function printf to serial port.
*              After Redirection, you can use printf function.
*
* @param       file:  Meaningless in this function.
*
* @param       *ptr:  Buffer pointer for data to be sent.
*
* @param       len:  Length of data to be sent.
*
* @retval      The characters that need to be send.
*
* @note
*/
int _write(int file, char* ptr, int len)
{
    int i;
    for (i = 0; i < len; i++)
    {
        __io_putchar(*ptr++);
    }

    return len;
}

#else
#pragma message("Not supported compiler type")
#endif

/**@} end of group IAP_BootLoader_Functions */
/**@} end of group IAP_BootLoader */
/**@} end of group IAP_Examples */
/**@} end of group Examples */
