#include "boot_flash.h"
//uint32_t PAGE_OFFSET = ((uint32_t)((4-1) * 0x0400));
uint32_t PAGE_NUMB = 127;


HAL_StatusTypeDef FLASH_Erase_App(void) //
{
	HAL_StatusTypeDef res;
	uint32_t PageError = 0x00;
	
	res = HAL_FLASH_Unlock();
	
	if (res != HAL_OK) return res;
	
  FLASH_EraseInitTypeDef EraseInitStruct;
  
	EraseInitStruct.TypeErase   = FLASH_TYPEERASE_PAGES;// erase pages
	EraseInitStruct.Banks = 1;
	EraseInitStruct.PageAddress = MAIN_APP_START_ADR;   //address
	EraseInitStruct.NbPages     = MAIN_APP_NUM_OF_PAGE;// num of erased  pages
	
	res = HAL_FLASHEx_Erase(&EraseInitStruct, &PageError);
	
	if (res != HAL_OK) return res;
	
	res = HAL_FLASH_Lock();
	
	return res;
}




uint8_t *FLASH_Read(uint32_t add)
{
	return (uint8_t *)add;
}

HAL_StatusTypeDef FLASH_Write_Word(uint32_t Address, uint64_t Data) //Куда записывать
{
	HAL_StatusTypeDef res;
	
	res = HAL_FLASH_Unlock();
	
	if (res != HAL_OK) return res;
	
	res = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, Address, (uint32_t)(Data));
	
	if (res != HAL_OK) return res;

	res = HAL_FLASH_Lock();
	
	return res;
}
uint32_t word_data;




HAL_StatusTypeDef FLASH_Write_Page(uint32_t *Address, uint8_t *Data, int Data_size)
{
		//GPIOB->ODR^=(0x2000);
//		GPIOB->ODR|=0x4000;
	
	HAL_StatusTypeDef res;
	int data_cnt = 0;
	uint32_t adr;
	
	
	res = HAL_FLASH_Unlock();
	
	if (res != HAL_OK) return res;
	
	for (adr = *Address; adr < *Address + Data_size; adr = adr+4)
	{
		word_data = (
				Data[data_cnt]|
				Data[data_cnt+1]<<8|
				Data[data_cnt+2]<<16|
				Data[data_cnt+3]<<24);
		
		res = HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, adr, word_data);
		
		if (res != HAL_OK) return res;
		
		data_cnt +=4;
	}
	
	*Address += Data_size;
	res = HAL_FLASH_Lock();
	
	return res;
}

