/*
 * @Description: 
 * @Date: 2021-03-09 10:21:58
 * @LastEditors: CK.Zh
 * @LastEditTime: 2021-03-10 11:15:23
 * @FilePath: \NaviKit_EC_stm32\App\Src\isp.c
 */
#include <isp.h>
#include "cmsis_os2.h"                  // ::CMSIS:RTOS2

void ISP_Jump(){
    typedef  void (*pFunction)(void);
    pFunction Jump_to_ISP;
    Jump_to_ISP = (pFunction) (*(__IO uint32_t*)(ISP_ADDRESS + 4));//ISP's program's reset vector (pc pointer initial value)
    __set_MSP(*(__IO uint32_t*) ISP_ADDRESS);
    Jump_to_ISP();
    while(1);
}

void ISP_Judge()
{//Judge that if need jump to ISP area
	RTC_HandleTypeDef hrtc;
	hrtc.Instance = RTC;
	if(HAL_RTCEx_BKUPRead(&hrtc,MAGIC_VALUE_ADDRESS) == MAGIC_VALUE)
  {
    __HAL_RCC_PWR_CLK_ENABLE();
    __HAL_RCC_BKP_CLK_ENABLE();
    __HAL_RCC_RTC_CONFIG(RCC_RTCCLKSOURCE_HSE_DIV128);
    __HAL_RCC_RTC_ENABLE();
    HAL_PWR_EnableBkUpAccess();

    HAL_RTCEx_BKUPWrite(&hrtc,MAGIC_VALUE_ADDRESS,0x0000);

    __HAL_RCC_RTC_DISABLE();
    __HAL_RCC_PWR_CLK_DISABLE();
    __HAL_RCC_BKP_CLK_DISABLE();

    HAL_PWR_DisableBkUpAccess();

    ISP_Jump();
  }
}


bool ISP_Prepare(){
	RTC_HandleTypeDef hrtc;

	hrtc.Instance = RTC;

    __HAL_RCC_PWR_CLK_ENABLE();
    __HAL_RCC_BKP_CLK_ENABLE();
    __HAL_RCC_RTC_CONFIG(RCC_RTCCLKSOURCE_HSE_DIV128);
    __HAL_RCC_RTC_ENABLE();
    HAL_PWR_EnableBkUpAccess();

    HAL_RTCEx_BKUPWrite(&hrtc,MAGIC_VALUE_ADDRESS,MAGIC_VALUE);

    osDelay(10);
    if(HAL_RTCEx_BKUPRead(&hrtc,MAGIC_VALUE_ADDRESS) == MAGIC_VALUE)
    {//write successful
        log_v("Enter to EC update state.");
        log_i("EC will reboot ,then run ISP automatic.");
		TaskBeep(400,5);
        HAL_NVIC_SystemReset();
        return true;
    }
    else{
        log_e("Backup register writen error, can not enter EC update state.");
        return false;
    }
}
