#include "soft_flash.h"
#include "string.h"
#include "main.h"
#include "config.h"
#include "usart_data_handle.h"
#include "soft_crc.h"
#include "soft_version.h"

bool write_flash_flag = false;

flash_data stor_par;
flash_data cur_par;


uint32_t sectStartAddr[12]=
{
    0x08000000,//0
    0x08004000,//1
    0x08008000,//2
    0x0800c000,//3
    0x08010000,//4
    0x08020000,//5
    0x08040000,//6
    0x08060000, //7
    0x08080000, //8
    0x080A0000, //9
    0x080C0000, //10
    0x080E0000, //11
};

int GetSectorFromAddress(uint32_t address)
{
    int sect = 0;
    if( address < 0x08000000 || address > 0x08100000 )
        return -1;
    for( int i=0; i<8; i++ )
    {
        if( address >= sectStartAddr[i] && address < sectStartAddr[i+1] )
        {
            sect = i;
            break;
        }
    }
    return sect;
}


/**
  * @file    ReadFlashNBtye
  * @brief   读flash
  * @param   none
  * @details 
  * @author  Zhang Sir 
 **/
void ReadFlashNBtye(uint32_t addr, uint8_t *pdata, uint16_t size)
{   
    if(addr + size >= 0x8010400) //65kb
    {
        return;
    }
    
    for (size_t i = 0; i < size; i++)
    {
       *(pdata + i) = *((__IO uint8_t *)addr + i);
    }
}


/**
  * @file    WriteFlashNBtye
  * @brief   写flash
  * @param   none
  * @details 
  * @author  Zhang Sir 
 **/
HAL_StatusTypeDef WriteFlashNBtye(uint32_t addr, uint8_t *pdata, uint16_t size)
{
    HAL_StatusTypeDef write_status = HAL_OK;

    __disable_irq();

    HAL_FLASH_Unlock();

    __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | 
                FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR);

    uint32_t sector = 10;
    sector = GetSectorFromAddress(addr);//获取地址所在的扇区

    FLASH_Erase_Sector(sector,FLASH_VOLTAGE_RANGE_3);//擦除指定的闪存扇区(0~11)
    
    //写flash 每次写2字节
    uint16_t TempBuf = 0;
     for(uint16_t i = 0; i < (size % 2 == 0? size/2 : size/2 +1); i++ )
    {
        TempBuf = *(pdata + 2 * i) + (*(pdata + 2 * i + 1) << 8);
        write_status = HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, addr + i * 2, TempBuf);
    }

    HAL_FLASH_Lock();
    __enable_irq();

    return write_status;
}


int plane_flash_par_check( int *par, int pardef, int parmin, int parmax )
{

    //参数超出范围报告参数异常,暂用默认值
    if ( *par < parmin || *par > parmax )
    {
        return pardef;
    }

    return *par;
}

void par_check(void)
{
    stor_par.uavtype = plane_flash_par_check(&stor_par.uavtype,0,0,20);
    stor_par.abnormal_outage_flag = plane_flash_par_check(&stor_par.abnormal_outage_flag,0,0,1);
    stor_par.voltage = plane_flash_par_check(&stor_par.voltage,0,-50,50);
}

void par_copy(void)
{
    memcpy(&cur_par,&stor_par,sizeof(flash_data));

    Int2String(cur_par.pmu_serial,dev_pmu.sn,9); //设置sn重新写入
}




/**
  * @file    write_flash_function
  * @brief   把参数写入内存
  * @param   none
  * @details 
  * @author  Zhang Sir 
 **/
void write_flash_function(void)
{   
    if(write_flash_flag == true)
    {
        if(HAL_OK == WriteFlashNBtye( FLASH_PAR_ADDR, ( uint8_t * )&stor_par, sizeof(flash_data) ))
        {
            ReadFlashNBtye( FLASH_PAR_ADDR, ( uint8_t * )&stor_par, sizeof( flash_data ) );

            par_check();
            par_copy();
            write_flash_flag = false;
        }
    }
}

/**
  * @file    get_chip_id
  * @brief   获取芯片id
  * @param   none
  * @details 
  * @author  Zhang Sir 
 **/
uint32_t chip_id[3] = {0};
uint16_t get_chip_id(void)
{
    for(uint8_t i = 0;i < 3; i++)
    {
        chip_id[i] = *((__IO uint32_t *)(FLASH_ID_ADDR + (4 * i)));
    }
    
    return Get_Crc16((uint8_t *)&chip_id[0], sizeof(chip_id));

}


/**
  * @file    load_default_param
  * @brief   加载默认参数
  * @param   none
  * @details 
  * @author  Zhang Sir 
 **/
void load_default_param(void)
{
    stor_par.flash_flag = PAR_FALG;

    stor_par.pmu_serial = PMU_SERIAL;
    stor_par.uavtype = 0;
    stor_par.abnormal_outage_flag = 0;
    stor_par.voltage = 0;

    stor_par.chip_passid = get_chip_id();

    WriteFlashNBtye(FLASH_PAR_ADDR,(uint8_t *)&stor_par,sizeof(flash_data));
    
}

/**
  * @file    flash_init
  * @brief   flash初始化
  * @param   none
  * @details 
  * @author  Zhang Sir 
 **/
bool Check_Chip_Verified = false; //检查当前芯片是否通过验证
void flash_init(void)
{
    ReadFlashNBtye( FLASH_PAR_ADDR, ( uint8_t * )&stor_par, sizeof( flash_data ) );

    if(stor_par.flash_flag != PAR_FALG)
    {
        //加载默认参数
        load_default_param();
    }

    //检查当前芯片是否通过验证
    if(get_chip_id() == stor_par.chip_passid)
        Check_Chip_Verified = true;

    par_check();
    par_copy();
}