/*********************************************************************************************
Copyright <2024> <Icore Technology (Nanjing)  Co.,Ltd>
All Rights Reserved,
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials provided 
with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to 
endorse or promote products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
OF THE POSSIBILITY OF SUCH DAMAGE.
**********************************************************************************************/

/*
*********************************************************************************************************
*                                              rx32h6xx
*                                           Library Function
*
*                                   Copyright 2024, RX Tech, Corp.
*                                        All Rights Reserved
*
*
* Project      : rx32h6xx
* File         : main.c
* By           : RX_SD_Team
* Version      : V1.0.0
* Description  : Only rx32h6xx
*********************************************************************************************************
*/
#include "main.h"

/*
*********************************************************************************************************
*                                           Global macro/Structure
*********************************************************************************************************
*/

/*
*********************************************************************************************************
*                                             Global variable
*********************************************************************************************************
*/

_calendar_obj calendar;//时钟结构体 
uint8_t const table_week[12]={0,3,3,6,1,4,6,2,5,0,3,5}; //月修正数据表	
const uint8_t mon_table[12]={31,28,31,30,31,30,31,31,30,31,30,31};

/*
*********************************************************************************************************
*                                           Global Function declaration
*********************************************************************************************************
*/

void Delay_us( uint32_t us )
{
	uint32_t Fsys;
	Fsys=RCC_Get_SystemClock()/1000000;
	if( us*Fsys > SysTick_LOAD_RELOAD_Msk ) return;
	SysTick->CTRL = 0;      //Disable SysTick
	SysTick->LOAD = Fsys*us;//Set count number:72*us, 72 means 1us when SystemCoreClock is 72MHz
	SysTick->VAL  = 0;      //Clear current count number and count flag
	SysTick->CTRL = 5;      //Enable SysTick and Select SystemCoreClock as SysTick clock source
	while((SysTick->CTRL&0x10000)==0);//Wait for count flag set
	SysTick->CTRL = 0;      //Disable SysTick
}

void Delay_ms( uint32_t ms )
{
	uint32_t i;
	for(i=ms;i>0;i--)
	{
		Delay_us(1000);
	}
}

void SystemClock_Config(void)
{
	// set flash lantency
	FLASH_Set_Latency(FLASH_Latency_3);
	
  RCC_Enable_HSI();
  while(RCC_Get_HSIRDY() != 1)
  {
  }
  RCC_Set_PLLMUL(RCC_CFGR_PLLMUL_10x);
  RCC_Enable_PLL();
  while(RCC_Get_PLLRDY() != 1)
  {
  }
  RCC_Set_AHBPrescaler(RCC_CFGR_HPRE_DIV1);
  RCC_Set_APB1Prescaler(RCC_CFGR_PPRE1_DIV2);
  RCC_Set_APB2Prescaler(RCC_CFGR_PPRE2_DIV1);
  RCC_Set_SysClkSource(RCC_CFGR_SW_PLL);
  while(RCC_Get_SysClkSource() != RCC_CFGR_SWS_PLL)
  {
  }
  RCC_Set_ADCClkSource(RCC_CFGR_ADCCLK_SEL_PLL2);
  RCC_Set_ADCPrescaler(RCC_CFGR_ADCPRE_DIV5);
}

//whether it is leap year
//month         1  2  3  4  5  6  7  8  9  10 11 12
//leap year     31 29 31 30 31 30 31 31 30 31 30 31
//normal year   31 28 31 30 31 30 31 31 30 31 30 31
uint8_t Is_Leap_Year(uint16_t year)
{			  
	if(year%4==0) 
	{ 
		if(year%100==0) 
		{ 
			if(year%400==0)return 1;  
			else return 0;   
		}else return 1;   
	}else return 0;	
}	

//Get Day of the work																					 
uint8_t RTC_Get_Week(uint16_t year,uint8_t month,uint8_t day)
{	
	uint16_t temp2;
	uint8_t yearH,yearL;
	
	yearH=year/100;	yearL=year%100; 
	if (yearH>19)yearL+=100;
	temp2=yearL+yearL/4;
	temp2=temp2%7; 
	temp2=temp2+day+table_week[month-1];
	if (yearL%4==0&&month<3)temp2--;
	return(temp2%7);
}	

//Get the current time
uint8_t RTC_Get(void)
{
	static uint16_t daycnt=0;
	uint32_t timecount=0; 
	uint32_t temp=0;
	uint16_t temp1=0;	  
    timecount=RTC_Get_Counter();	 
 	temp=timecount/86400;   //get the number od days
	if(daycnt!=temp)//over one day
	{	  
		daycnt=temp;
		temp1=1970;	//start from 1970
		while(temp>=365)
		{				 
			if(Is_Leap_Year(temp1))//leap year
			{
				if(temp>=366)temp-=366;//the second number of leap year 
				else {temp1++;break;}  
			}
			else temp-=365;	  //normal year
			temp1++;  
		}   
		calendar.w_year=temp1;//get year 
		temp1=0;
		while(temp>=28)//over one month
		{
			if(Is_Leap_Year(calendar.w_year)&&temp1==1)//whether it is leap year
			{
				if(temp>=29)temp-=29;//the second number of leap year 
				else break; 
			}
			else 
			{
				if(temp>=mon_table[temp1])temp-=mon_table[temp1];//normal year
				else break;
			}
			temp1++;  
		}
		calendar.w_month=temp1+1;	//get month
		calendar.w_date=temp+1;  	//get data
	}
	temp=timecount%86400;     		//get time 	   
	calendar.hour=temp/3600;     	//hour
	calendar.min=(temp%3600)/60; 	//minutes	
	calendar.sec=(temp%3600)%60; 	//second
	calendar.week=RTC_Get_Week(calendar.w_year,calendar.w_month,calendar.w_date);//获取星期   
	return 0;
}

uint8_t RTC_Set(uint16_t syear,uint8_t smon,uint8_t sday,uint8_t hour,uint8_t min,uint8_t sec)
{
	uint16_t t;
	uint32_t seccount=0;
	if(syear<1970||syear>2099)return 1;	   
	for(t=1970;t<syear;t++)	//all year second plus
	{
		if(Is_Leap_Year(t))seccount+=31622400;//the second number of leap year
		else seccount+=31536000;			  //the second number of normal year
	}
	smon-=1;
	for(t=0;t<smon;t++)	   //previous month second plus
	{
		seccount+=(uint32_t)mon_table[t]*86400;//month second plus
		if(Is_Leap_Year(syear)&&t==1)seccount+=86400;//increase one day seconds	of February leap year  
	}
	seccount+=(uint32_t)(sday-1)*86400;//previous data second plus
	seccount+=(uint32_t)hour*3600;//hour seconds
    seccount+=(uint32_t)min*60;	 //minute seconds
	seccount+=sec;//last second plus

	RCC_Enable_APB1Clock(RCC_APB1ENR_PWREN);
	PWR_Enable_BkUpAccess();
	RTC_Set_Counter(seccount);	//set RTC_CNT
	return 0;	    
}

void UART2_Init_Async( uint32_t baudrate )
{
	GPIO_InitTypeDef GPIO_InitStruct  = {0};
	UART_InitTypeDef UART_InitStruct = {0};
	
	RCC_Enable_AHBClock(RCC_AHBENR_IOPDEN);
  RCC_Enable_AHBClock(RCC_AHBENR_IOPAEN);
	RCC_Enable_APB1Clock(RCC_APB1ENR_UART2EN);

	UART_InitStruct.BaudRate             = baudrate;
	UART_InitStruct.DataWidth            = UART_DATAWIDTH_8B;
	UART_InitStruct.Parity               = UART_PARITY_NONE;
	UART_InitStruct.StopBits             = UART_STOPBITS_1;
	UART_InitStruct.TransferDirection    = UART_DIRECTION_TX_RX;
	UART_Init(UART2,&UART_InitStruct);

  //PD5  -> UART2_TX
	//PD4  -> UART2_RX
	GPIO_InitStruct.Alternate = GPIO_AF5;
	GPIO_InitStruct.Mode      = GPIO_MODE_AF_PP;
  GPIO_InitStruct.Pull      = GPIO_PUPDR_Pullup;
	GPIO_InitStruct.Speed     = GPIO_OSPEEDR_High;
	GPIO_InitStruct.Pin       = GPIO_PIN_4;
	GPIO_Init(GPIOD, &GPIO_InitStruct);
	GPIO_InitStruct.Pull      = GPIO_PUPDR_Floating;
	GPIO_InitStruct.Pin       = GPIO_PIN_5;
	GPIO_Init(GPIOD, &GPIO_InitStruct);

	UART_Enable(UART2);
}

uint8_t RTC_Init(void)
{
	RCC_Enable_APB1Clock(RCC_APB1ENR_PWREN);  //Enable PWR/BKP  APB1Clock
	PWR_Enable_BkUpAccess();	//Enable BKP 
	RCC_Enable_LSI();  //Enable RTC
  while(RCC_Get_LSIRDY() != 1)
  {
  }
	RCC_Enable_RTC();   
	RTC_Enable_IT(RTC_IT_SEC|RTC_IT_ALR|RTC_IT_OW);	//Enable RTC IT  
  RTC_Wait_LastTask();
  RTC_Wait_Synchro();
  RTC_Set_Prescaler(32000);  
  RTC_Set_Alarm(0xfffffffB);
  RTC_Set(2024,1,1,1,1,1); 
  RTC_Enable_WriteProtection(RTC);
  RTC_Wait_LastTask();
  RTC_Wait_Synchro();
	NVIC_EnableIRQ(RTC_IRQn); 	 
	return 0;
}		

int main(void)
{
  uint8_t t=0;
  SystemClock_Config();

  UART2_Init_Async(115200);
  
  RTC_Init();  
  
  printf("**************START**************\r\n");

  while(1)
  {
    if(t!=calendar.sec)
		{
			printf("###################\r\n");
			printf("year=%d\r\n",calendar.w_year);
			printf("month=%d\r\n",calendar.w_month);
			printf("date=%d\r\n",calendar.w_date);
			t=calendar.sec;
			switch(calendar.week)
			{
				case 0:
					printf("Sunday\r\n");
					break;
				case 1:
					printf("Monday\r\n");
					break;
				case 2:
					printf("Tuesday\r\n");
					break;
				case 3:
					printf("Wednesday\r\n");
					break;
				case 4:
					printf("Thursday\r\n");
					break;
				case 5:
					printf("Friday\r\n");
					break;
				case 6:
					printf("Saturday\r\n");
					break;  
			}
			printf("hour=%d\r\n",calendar.hour);
			printf("min=%d\r\n",calendar.min);
			printf("sec=%d\r\n",calendar.sec);
		}		
  }
}
