#include "flash_tools.h"

void Put_Program_to_FLESH(uint8_t * Address, uint32_t Length)
{	
  FLASH_EraseInitTypeDef erase;
  uint32_t adr = FLASH_PROGRAM_BASE;
  uint32_t i,Len64, Sects;	
  uint64_t* Adr64;
  uint32_t pageError = 0x0;
  HAL_StatusTypeDef	flash_ok = HAL_ERROR;	
	
	Sects = Length / 0x40000; if(Sects * 0x40000 < Length) Sects++;
	Len64 = Length/8; if(Len64*8 < Length) Len64++;
	Adr64 = (uint64_t *)Address;
/*
	while(flash_ok != HAL_OK)
	{
		flash_ok = HAL_FLASH_Unlock();
	}
*/			
	erase.TypeErase = FLASH_TYPEERASE_SECTORS;
	erase.Banks = FLASH_BANK_2;
	erase.Sector = FLASH_SECTOR_12;
	erase.NbSectors = Sects;
	erase.VoltageRange = FLASH_VOLTAGE_RANGE_3;
	flash_ok = HAL_FLASHEx_Erase(&erase, &pageError);		
		
	flash_ok = HAL_ERROR;
	while(flash_ok != HAL_OK)			
	{			
		for(i=0; i<Len64; i++)
		{
			flash_ok = HAL_FLASH_Program(FLASH_TYPEPROGRAM_DOUBLEWORD, adr, *Adr64);
			Adr64++;
			adr += 0x8;
		}
	}
/*	
	flash_ok = HAL_ERROR;
	while(flash_ok != HAL_OK)
	{
		flash_ok = HAL_FLASH_Lock();
	}
*/
}


void putIntoEeprom(uint16_t lenght, uint16_t* param)
{	
  uint32_t adr = FLASH_MODBUS_BASE;

  HAL_StatusTypeDef	flash_ok = HAL_ERROR;	
	
	while(flash_ok != HAL_OK)
	{
		flash_ok = HAL_FLASH_Unlock();
	}
			
	FLASH_EraseInitTypeDef erase;
	uint32_t pageError = 0x0;
	erase.TypeErase = FLASH_TYPEERASE_SECTORS;
	erase.Banks = FLASH_BANK_1;
	erase.Sector = FLASH_SECTOR_4;
	erase.NbSectors = 1;
	erase.VoltageRange = FLASH_VOLTAGE_RANGE_3;
	
	flash_ok = HAL_FLASHEx_Erase(&erase, &pageError);		
		
	flash_ok = HAL_ERROR;
	while(flash_ok != HAL_OK)			
	{			
		for(int i=0; i<(lenght+1); i++)
		{
			flash_ok = HAL_FLASH_Program(FLASH_TYPEPROGRAM_HALFWORD, adr, *param);
			param++;
			adr += 0x2;
		}
	}
	
	flash_ok = HAL_ERROR;
	while(flash_ok != HAL_OK)
	{
		flash_ok = HAL_FLASH_Lock();
	}
}

uint16_t watInTheFlash(uint32_t adress)
{	
	return (*(uint32_t*) adress);	
}

