/**
  ******************************************************************************
 *
 * @file        Sample_MID_RTC_PerpetualCalendar.c
 *
 * @brief       Sample RTC calendar initial.
 *
 * @par         Project
 *              MG32
 * @version     V1.02
 * @date        2025/06/16
 * @author      Megawin Software Center
 * @copyright   Copyright (c) 2017 MegaWin Technology Co., Ltd.
 *              All rights reserved.
 *
 ******************************************************************************
* @par Disclaimer
 * The Demo software is provided "AS IS" without any warranty, either
 * expressed or implied, including, but not limited to, the implied warranties
 * of merchantability and fitness for a particular purpose. The author will
 * not be liable for any special, incidental, consequential or indirect
 * damages due to loss of data or any other reason.
 * These statements agree with the world wide and local dictated laws about
 * authorship and violence against these laws.
 *******************************************************************************
 ******************************************************************************
 */


/* Includes ------------------------------------------------------------------*/
#include "MG32_DRV.h"
#include "MG32_RTC_MID.h"
#include "stdio.h"
#if defined(__ICCARM__) && (__VER__ >= 9020001)
    #define _ICCARM_9020000
    #include "LowLevelIOInterface.h"
#endif
/* Wizard menu ---------------------------------------------------------------*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/


/* Private function prototypes -----------------------------------------------*/
/* Exported variables --------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
void Sample_MID_RTC_PerpetualCalendar(void);
void Sample_Calendar_DateOutput(void);
/* External vairables --------------------------------------------------------*/



/**
 *******************************************************************************
 * @brief  	    fputc
 * @details     Check transmit data buffer empty and Write transmit data.
 * @return	    	
 * @note        
 * @par         Example
 * @code
 * @endcode
 *******************************************************************************
 */
static volatile uint8_t gURT0_First = 0;

#if defined(_ICCARM_9020000)
    size_t __write(int handle, const unsigned char *buffer, size_t size)
    {
        /* Remove the #if #endif pair to enable the implementation */
        //comment out for custome implmenztation of __write
        //#ifdef
        size_t nChars = 0;
        if (buffer == 0)
        {
            /*
             * This means that we should flush internal buffers.  Since we
             * don't we just return.  (Remember, "handle" == -1 means that all
             * handles should be flushed.)
             */
            return 0;
        }
        /* This template only writes to "standard out" and "standard err",
         * for all other file handles it returns failure. */
        if (handle != _LLIO_STDOUT && handle != _LLIO_STDERR)
        {
            return _LLIO_ERROR;
        }
        //comment out for custome implmenztation of __write
        //#else
        for (/* Empty */; size != 0; --size)
        {
          
            // User need to replace MyLowLevelPutchar with application specific version
            // Must return the character outputed
            // if (UART1_PutCharByPolling(*buffer++) < 0)
            // {
            //   return _LLIO_ERROR;
            // }
            if(gURT0_First == 0)
                gURT0_First = 1;
            else
                while(URT_GetITSingleFlagStatus(URT0, URT_IT_TC) == DRV_UnHappened);
            
            URT_ClearITFlag(URT0, URT_IT_TC);
            URT_SetTXData(URT0, 1, (uint8_t)*buffer);
            
            ++buffer; 
            ++nChars;
        }
        
        return nChars;
        //comment out for custome implmenztation of __write
        //#endif
        /* Always return error code when implementation is disabled. */
        //return _LLIO_ERROR;
    }
#else
    int fputc(int ch, FILE *f)
    {
        UNUSED(f);
        
        if(gURT0_First == 0)
            gURT0_First = 1;
        else
            while(URT_GetITSingleFlagStatus(URT0, URT_IT_TC) == DRV_UnHappened);
        
        URT_ClearITFlag(URT0, URT_IT_TC);
        URT_SetTXData(URT0, 1, (uint16_t)ch);
        return ch;
    }
#endif
/**
 *******************************************************************************
 * @brief       RTC perpetual calendar initial
 * @details     1.Initial RTC perpetual calendar
 *    \n        2.Initial clock.
 *    \n        3.Initial UART0
 * @return      None
 *******************************************************************************
 */
void Sample_MID_RTC_PerpetualCalendar(void)
{
    RTC_HandleTypeDef mRTC;
    
    // make sure :
    
    //===Set CSC init====
    //MG32_CSC_Init.h(Configuration Wizard)
    //CK_LS clock can from ILRCO or external XTAL(One second time domain, use 32.768kHz XTAL please, then enable XTAL in MG32_CSC_Init)
    //If change RTC_RLR will changed RTC count time range suggest write 0x00000000
    //Can select RTC_HOURFORMAT_12 or RTC_HOURFORMAT_24
    //===Set URT0 init===
    //URT0 GPIO initialize by MG32_GPIO_Init (PB8, PB9, PC10, PC11)
    //URT0 Baudrate initialize by MG32_URT_Init
    // ------------------------------------------------------------------------
    // 1.Initial RTC. 
    // ------------------------------------------------------------------------
    mRTC.Instance = RTC;
    mRTC.Init.RTC_CK_SEL = RTC_CLK_LS;         //RTC clock source select
    mRTC.Init.RTC_RLR = 0x00000000;             //RTC reload register set 0~0xFFFFFFFE, 0xFFFFFFFF forbidden.
    
    // ------------------------------------------------------------------------
    // 1.Initial calendar date. 
    // ------------------------------------------------------------------------
    mRTC.sTime.Seconds = 58U;
    mRTC.sTime.Minutes = 59U;
    mRTC.sTime.Hours = 23U;
    
    mRTC.sDate.Date = 28U;
    mRTC.sDate.Month = February;
    mRTC.sDate.Year = 2010U;
    mRTC.Init.HourFormat = RTC_HOURFORMAT_12;      /*!< Date hours format set.(0 = 24hr, 1 = 12hr) */
    
    MID_RTC_Init(&mRTC);
    MID_RTC_GetTime(&mRTC);
    
    // ------------------------------------------------------------------------
    // 1.Output calendar date.
    // ------------------------------------------------------------------------
    printf("\n %04d /",mRTC.sDate.Year);
    printf("%02d / ",mRTC.sDate.Month);
    printf("%02d / ",mRTC.sDate.Date);
    printf("%02d : ",mRTC.sTime.Hours);
    printf("%02d : ",mRTC.sTime.Minutes);
    printf("%02d ",mRTC.sTime.Seconds);
    
    if(mRTC.Init.HourFormat==1U)
    {
        if(mRTC.sTime.TimeFormat==1U)
            printf(".PM\n");
        else
            printf(".AM\n");
    }
}

/**
 *******************************************************************************
 * @brief       RTC Calendar Date Output
 * @details     1. Output Calendar Date 
 *    \n        2.
 *    \n        3.
 * @return      None
 *******************************************************************************
 */
void Sample_Calendar_DateOutput(void)
{
    RTC_HandleTypeDef mRTC;
    
    MID_RTC_GetTime(&mRTC);
    // ------------------------------------------------------------------------
    // 1.Output calendar date.
    // ------------------------------------------------------------------------
    printf("\n %04d /",mRTC.sDate.Year);
    printf("%02d / ",mRTC.sDate.Month);
    printf("%02d / ",mRTC.sDate.Date);
    printf("%02d : ",mRTC.sTime.Hours);
    printf("%02d : ",mRTC.sTime.Minutes);
    printf("%02d ",mRTC.sTime.Seconds);
    
    if(mRTC.Init.HourFormat==1U)
    {
        if(mRTC.sTime.TimeFormat==1U)
            printf(".PM\n");
        else
            printf(".AM\n");
    }
    
}
