/*
 * flash.c
 *
 *  Created on: 2019. 7. 15.
 *      Author: parkyj
 */
#include "flash.h"
uint8_t flashinit = 0;
uint32_t Address = FLASH_USER_START_ADDR;

typedef void (*fptr)(void);
fptr jump_to_app;
uint32_t jump_addr;
void Jump_App(void){
    __HAL_RCC_TIM6_CLK_DISABLE(); // 留ㅼ씤???占쏙옙癒몌옙?? ?占쏙옙占�??占쏙옙?占쏙옙?占쏙옙
    printf("boot loader start\n");               //硫붿꽭占�? 異쒕젰
    jump_addr = *(__IO uint32_t*) (APPLICATION_ADDRESS + 4);
    jump_to_app = (fptr) jump_addr;
    
    /* init user app's sp */
    printf("jump!\n");
    __set_MSP(*(__IO uint32_t*) APPLICATION_ADDRESS);
    jump_to_app();
}


void FLASH_If_Init(void)
{
  /* Unlock the Program memory */
  HAL_FLASH_Unlock();

  /* Clear all FLASH flags */
  __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_PGERR | FLASH_FLAG_WRPERR);
  /* Unlock the Program memory */
  HAL_FLASH_Lock();
}

void Flash_InitRead(void) // ?占쏙옙湲고븿?占쏙옙
{
    uint32_t  Address = 0;
    Address = FLASH_USER_START_ADDR;
    for(uint32_t i = 0; i < 16; i++ ){
        printf("%08x : %02X \n",Address ,*(uint8_t*)Address);
        Address++;
    }
#if 0 // PYJ.2019.03.27_BEGIN -- 
    for(uint32_t i = 0; i < 13848; i++ ){
        printf("%08x : %02X \n",Address ,*(uint8_t*)Address);
        Address++;
    }
    Address = StartAddr;
    for(uint32_t i = 0; i < 13848; i++ ){
        printf("%02X ",*(uint8_t*)Address);
        Address++;
    }
#endif // PYJ.2019.03.27_END -- 

}

uint8_t Flash_RGB_Data_Write(uint8_t* data){
    uint16_t Firmdata = 0;
    uint8_t ret = 0;
    for(uint8_t i = 0; i < data[bluecell_length] - 2; i+=2){
        Firmdata  = ((data[(bluecell_length + 1) + i]) & 0x00FF);
        Firmdata  += ((data[(bluecell_length + 1) + (i + 1)] << 8) & 0xFF00);
        if(HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD,Address ,   (uint16_t)Firmdata) != HAL_OK){
            printf("HAL NOT OK \n");
            ret = 1;
        }
        Address += 2;
        //if(!(i%FirmwareUpdateDelay))
      //  HAL_Delay(1);
    }
    return ret;
}

uint8_t Flash_write(uint8_t* data) // ?占쏙옙湲고븿?占쏙옙
{

    /*Variable used for Erase procedure*/
    static FLASH_EraseInitTypeDef EraseInitStruct;
    static uint32_t PAGEError = 0;
    uint8_t ret = 0;
    /* Fill EraseInit structure*/
    EraseInitStruct.TypeErase   = FLASH_TYPEERASE_PAGES;
    EraseInitStruct.PageAddress = FLASH_USER_START_ADDR;
    EraseInitStruct.NbPages     = (FLASH_USER_END_ADDR - FLASH_USER_START_ADDR) / FLASH_PAGE_SIZE;

    __HAL_RCC_TIM6_CLK_DISABLE(); // 留ㅼ씤???占쏙옙癒몌옙?? ?占쏙옙占�??占쏙옙?占쏙옙?占쏙옙
    HAL_FLASH_Unlock(); // lock ??占�?
    if(flashinit == 0){
        flashinit= 1;
        //FLASH_PageErase(StartAddr);
        if (HAL_FLASHEx_Erase(&EraseInitStruct, &PAGEError) != HAL_OK){
            printf("Erase Failed \r\n");
        }
    }
//    FLASH_If_Erase();
    ret = Flash_RGB_Data_Write(&data[bluecell_stx]);
    HAL_FLASH_Lock(); // lock ?占쏙옙洹멸린
    __HAL_RCC_TIM6_CLK_ENABLE(); // 留ㅼ씤???占쏙옙癒몌옙?? ?占쏙옙?占쏙옙?占쏙옙?占쏙옙?占쏙옙?占쏙옙

    return ret;

}
