/**
  ******************************************************************************
  * @file    main.c
  * @author  MCU Application Team
  * @brief   Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2023 Puya Semiconductor Co.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by Puya under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2016 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "py32t092xx_ll_Start_Kit.h"

/* Private define ------------------------------------------------------------*/
#define BACKUP_COUNT 8u

/* Defines related to Clock configuration */
/* ck_apre=LSIFreq/(ASYNC prediv + 1) with LSIFreq=32768Hz RC */
#define RTC_ASYNCH_PREDIV          ((uint32_t)0x7F)
/* ck_spre=ck_apre/(SYNC prediv + 1) = 1 Hz */
#define RTC_SYNCH_PREDIV           ((uint32_t)0x00FF)

/* Private variables ---------------------------------------------------------*/
__IO FlagStatus TamperStatus;

/* Buffers used for displaying Time and Date */
uint8_t aShowTime[16] = "hh:ms:ss";
uint8_t aShowDate[16] = "dd/mm/aaaa";
uint8_t aShowTimeStamp[16] = "hh:ms:ss";
uint8_t aShowDateStamp[16] = "dd-mm-yyyy";

/* Backup registers table */
uint32_t aBKPDataReg[BACKUP_COUNT] =
{
  LL_RTC_BKP_DR0, LL_RTC_BKP_DR1, LL_RTC_BKP_DR2,
  LL_RTC_BKP_DR3, LL_RTC_BKP_DR4, LL_RTC_BKP_DR5,
  LL_RTC_BKP_DR6, LL_RTC_BKP_DR7
};
/* Private user code ---------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static void APP_SystemClockConfig(void);
static void APP_RTC_Init(void);
static void APP_RTC_TamperConfig(void);

/**
  * @brief  Main program.
  * @param  None
  * @retval int
  */
int main(void)
{
  uint32_t index = 0;
  
  /* Enable SYSCFG and PWR clock */
  LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_SYSCFG);
  LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_PWR);

  /* Configure system clock */
  APP_SystemClockConfig();
  
  /* Initialize LED */
  BSP_LED_Init(LED_GREEN);
  
  /* Turn LED off */
  BSP_LED_Off(LED_GREEN);
  
  /* Initialize RTC */
  APP_RTC_Init();
  
  /* Activate Tamper */
  APP_RTC_TamperConfig();
  
  /* Write Data on the Back Up registers */
  for (index = 0; index < BACKUP_COUNT; index++)
  {
    LL_RTC_BKP_SetRegister(RTC, aBKPDataReg[index], 0xDF59 + (index * 0x5A));
  }

  /* Check Data is stored on the Back Up registers */
  for (index = 0; index < BACKUP_COUNT; index++)
  {
    if (LL_RTC_BKP_GetRegister(RTC, aBKPDataReg[index]) != (0xDF59 + (index * 0x5A)))
    {
      APP_ErrorHandler();
    }
  }

  /* Reset flag after writing of backup register in order to wait for new button press */
  TamperStatus = RESET;

  /* Turn LED on */
  BSP_LED_On(LED_GREEN);

  /* Wait for the tamper button is pressed */
  while (TamperStatus != SET);
  
  /* Deactivate the tamper  */
  LL_RTC_TAMPER_Disable(RTC, LL_RTC_TAMPER_1);
  LL_RTC_DisableIT_TAMP1(RTC);
  
  /* Check Data is cleared on the Back Up registers */
  for (index = 0; index < BACKUP_COUNT; index++)
  {
    if (LL_RTC_BKP_GetRegister(RTC, aBKPDataReg[index]) != 0x00)
    {
      APP_ErrorHandler();
    }
  }
  
  while (1)
  {
    /* LED flashing */
    BSP_LED_Toggle(LED_GREEN);
    LL_mDelay(500);
  }
}

/**
  * @brief  Configure system clock
  * @param  None
  * @retval None
  */
static void APP_SystemClockConfig(void)
{
  /* Enable HSI */
  LL_RCC_HSI_Enable();
  while(LL_RCC_HSI_IsReady() != 1)
  {
  }
  /* Enable access to the backup domain */
  LL_PWR_EnableBkUpAccess();
  
  /* Reset backup domain */
  LL_RCC_ForceBackupDomainReset();
  LL_RCC_ReleaseBackupDomainReset();
  
  /* Enable LSI */
  LL_RCC_LSI_Enable();
  
  /* Wait till LSI is ready */
  while(LL_RCC_LSI_IsReady() != 1)
  {
  }
  
  /* Set AHB prescaler: HCLK = SYSCLK */
  LL_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_1);

  /* Select HSISYS as system clock source */
  LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_HSISYS);
  while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_HSISYS)
  {
  }

  /* Set APB prescaler: PCLK = HCLK */
  LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_1);
  LL_Init1msTick(8000000);

  /* Update the SystemCoreClock global variable(which can be updated also through SystemCoreClockUpdate function) */
  LL_SetSystemCoreClock(8000000);
  
  /* Set RTC Clock Source */
  LL_RCC_SetRTCClockSource(LL_RCC_RTC_CLKSOURCE_LSI);
  
  /* Enable RTC */
  LL_RCC_EnableRTC();
}

/**
  * @brief RTC Initialization Function
  * @param None
  * @retval None
  */
static void APP_RTC_Init(void)
{
  LL_RTC_InitTypeDef RTC_InitStruct = {0};
  
  /* Initialize RTC */
  RTC_InitStruct.HourFormat = LL_RTC_HOURFORMAT_24HOUR;
  RTC_InitStruct.AsynchPrescaler = RTC_ASYNCH_PREDIV;
  RTC_InitStruct.SynchPrescaler = RTC_SYNCH_PREDIV;
  LL_RTC_Init(RTC, &RTC_InitStruct);
}

/**
  * @brief  Activate Tamper.
  * @param  None
  * @retval None
  */
static void APP_RTC_TamperConfig(void)
{
  /* Disable the write protection for RTC registers */
  /* LL_RTC_DisableWriteProtection(RTC); */
  
  /* Disable tamper output */
  /* LL_RTC_DisableTamperOutput(RTC); */
  
  /* Set Calibration output frequency */
  /* LL_RTC_CAL_SetOutputFreq(RTC, LL_RTC_CALIB_OUTPUT_NONE); */
  
  /* Disable Timestamp */
  /* LL_RTC_TS_Disable(RTC); */
  
  /* Disable timestamp on tamper detection event */
  /* LL_RTC_TS_DisableOnTamper(RTC); */
  
  /* Enable the write protection for RTC registers */
  /* LL_RTC_EnableWriteProtection(RTC); */
  
  /* Enable backup register erase after Tamper event detection */
  /* LL_RTC_TAMPER_EnableEraseBKP(RTC, LL_RTC_TAMPER_NOERASE_TAMPER1); */
  
  /* Disable Tamper mask flag */
  /* LL_RTC_TAMPER_DisableMask(RTC, LL_RTC_TAMPER_MASK_TAMPER1); */
  
  /* Set RTC_TAMP1 filter count */
  /* LL_RTC_TAMPER_SetFilterCount(RTC, LL_RTC_TAMPER_FILTER_DISABLE); */
  
  /* Sampling frequency */
  /* LL_RTC_TAMPER_SetSamplingFreq(RTC, LL_RTC_TAMPER_SAMPLFREQDIV_32768); */
  
  /* Set Tamper trigger to falling edge */
  LL_RTC_TAMPER_EnableActiveLevel(RTC, LL_RTC_TAMPER_ACTIVELEVEL_TAMP1);
  
  /* Enable IT TAMPER */
  LL_RTC_EnableIT_TAMP1(RTC);
  
  /* Enable TAMPx input detection */
  LL_RTC_TAMPER_Enable(RTC, LL_RTC_TAMPER_1);
  
  /* RTC Tamper Interrupt Configuration: EXTI configuration */
  LL_EXTI_EnableIT(LL_EXTI_LINE_21);
  
  /* RTC interrupt */
  NVIC_SetPriority(RTC_TAMP_IRQn, 0);
  NVIC_EnableIRQ(RTC_TAMP_IRQn);
  
  /* Clear the Tamper interrupt pending bit */
  LL_RTC_ClearFlag_TAMP1(RTC);
}

/**
  * @brief  Timestamp callback
  * @param  hrtc : hrtc handle
  * @retval None
  */
void APP_RTCTamp1Callback(void)
{
  TamperStatus = SET;
}

/**
  * @brief  Error executing function.
  * @param  None
  * @retval None
  */
void APP_ErrorHandler(void)
{
  while (1)
  {
  }
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* Users can add their own printing information as needed,
     for example: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* Infinite loop */
  while (1)
  {
  }
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT Puya *****END OF FILE******************/
