/*!
 * @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
 *  WARRANTIES 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 "stdio.h"
#include "inttypes.h"
#include "user_fls_config.h"

/** @addtogroup Examples
  @{
*/

/** @addtogroup FLASH_Examples
  @{
*/

/** @addtogroup FMC_Flash_ReadProtection
  @{
  */

/** @defgroup FMC_Flash_ReadProtection_Variables Variables
  @{
  */

/* Global flag: Trigger READPROT restore by key */
static volatile uint8_t g_restore_rdp_flag = 0U;

/**@} end of group FMC_Flash_ReadProtection_Variables */

/** @defgroup FMC_Flash_ReadProtection_Functions Functions
  @{
  */

/**
 * @brief  READPROT restore interface (back to normal state)
 *
 * @param  None
 *
 * @retval None
 */
void Fmc_RestoreREADPROT(void);

/**
 * @brief  READPROT restore interface (back to normal state)
 */
void Fmc_RestoreREADPROT(void)
{
    printf("READPROT restored!\r\n");
    
    /* Unlock FMC and Option Byte */
    Fmc_Unlock();
    Fmc_UnlockOptionByte();
    
    /* Erase Option Byte */
    Fmc_EraseOptionByte();
    
    /* Configure Option Byte to default value */
    Fmc_ConfigOptionByteUser(&g_ob_default_config);
    
    /* Lock Option Byte */
    Fmc_LockOptionByte();
    
    /* Launch Option Byte loading and prompt reset */
    Fmc_LaunchOptionByte();
}

/*!
 * @brief       Main program
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
int main(void)
{
    uint32_t addr;

    Board_ComInit(COM1);
    Board_ButtonInit(BUTTON_KEY1, BUTTON_MODE_EINT);
    
    Fmc_Unlock();
    
    /* Check READPROT status */
    if(Fmc_GetReadProtectionStatus() == 1U)
    {
        printf("\r\nREADPROT already enabled!\r\n");

        addr  = FLS_OPTION_BYTE_ADDR;
        printf("Turn on READ protection,       0x%08" PRIx32 " value = 0x%08" PRIx32 "\r\n", addr, *(volatile uint32_t*)addr);
    }
    else
    {
        addr  = FLS_OPTION_BYTE_ADDR;

        Fmc_UnlockOptionByte();

        /* Reset Page data*/
        Fmc_EraseOptionByte();

        /* Read Address data*/
        printf("After Erase,       0x%08" PRIx32 " value = 0x%08" PRIx32 "\r\n", addr, *(volatile uint32_t*)addr);

        /* Write data in address*/
        Fmc_ConfigOptionByteUser(&g_ob_readprot_config);

        /* Read data again*/
        printf("After Write,       0x%08" PRIx32 " value = 0x%08" PRIx32 "\r\n", addr, *(volatile uint32_t*)addr);

        /* Lock option byte*/
        Fmc_LockOptionByte();

        /* Launch the option byte loading*/
        Fmc_LaunchOptionByte();
    }

    /* Main loop: Check READPROT restore flag */
    for (;;)
    {
        if(1U == g_restore_rdp_flag)
        {
            g_restore_rdp_flag = 0U;
            
            /* Call restore interface */
            Fmc_RestoreREADPROT(); 
        }
        else
        {
            /* nothing */
        }
        __NOP();
    }
}

/*!
 * @brief    KEY1 interrupt service function: Trigger READPROT restore
 *
 * @param    None
 *
 * @retval   None
 *
 * @note
 */
void Eint_RestoreReadProtIsr(void)
{
    if (Eint_ReadStatusFlag((uint32_t)EINT_LINE0) == 1U)
    {
        g_restore_rdp_flag = 1U;
        Eint_ClearStatusFlag((uint32_t)EINT_LINE0);
    }
	else
	{
		/* nothing */
	}

    if (Eint_ReadStatusFlag((uint32_t)EINT_LINE1) == 1U)
    {
        Eint_ClearStatusFlag((uint32_t)EINT_LINE1);
    }
	else
	{
		/* nothing */
	}
}

#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(DEBUG_USART, (uint8_t)ch);

    /* wait for the data to be send  */
    while (Usart_ReadStatusFlag(DEBUG_USART, 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(DEBUG_USART, ch);

    /* wait for the data to be send  */
    while (Usart_ReadStatusFlag(DEBUG_USART, 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 FMC_Flash_ReadProtection_Functions */
/**@} end of group FMC_Flash_ReadProtection */
/**@} end of group FLASH_Examples */
/**@} end of group Examples */
