/**
  ******************************************************************************
  * @file    otp_interface.c
  * @author  MCD Application Team
  * @brief   Contains One-time programmable access functions
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2023 Puya Semiconductor Co.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by Puya under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "platform.h"

#include "openbl_mem.h"

#include "openbootloader.h"
#include "common_interface.h"
#include "otp_interface.h"
#include "flash_interface.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Exported variables --------------------------------------------------------*/
OPENBL_MemoryTypeDef OTP_Descriptor =
{
  .StartAddress = OTP_START_ADDRESS,
  .EndAddress = OTP_END_ADDRESS,
  .Size = OTP_END_ADDRESS - OTP_START_ADDRESS,
  .Type = AREA_OTP,
  .Read = OPENBL_OTP_Read,
  .Write = OPENBL_OTP_Write,
  .EraseChip = NULL,
  .EraseBank = NULL,
  .EraseBlock = NULL,
  .EraseSector = OPENBL_OTP_EraseSector,
  .ErasePage = OPENBL_OTP_ErasePage,
  .JumpToAddress = NULL,
};

/* Exported functions --------------------------------------------------------*/

void OPENBL_OTP_Read(uint32_t Address, uint8_t *Data, uint32_t DataLength)
{
  for(uint32_t i = 0; i < DataLength; i++)
  {
    *Data++ = (*(uint8_t *)(Address++));
  }
}

/**
  * @brief  This function is used to write data in OTP.
  * @param  Address The address where that data will be written.
  * @param  Data The data to be written.
  * @param  DataLength The length of the data to be written.
  * @retval None.
  */
void OPENBL_OTP_Write(uint32_t Address, uint8_t *Data, uint32_t DataLength)
{
  OPENBL_FLASH_Write(Address, Data, DataLength);
}

/*
 *  Erase Sector in OTP Memory
 *    Parameter:      Address:  Erase Address
 *    Return Value:   0 - OK,  1 - Failed
 */
ErrorStatus OPENBL_OTP_ErasePage(uint32_t Address)
{
  return OPENBL_FLASH_ErasePage(Address);
}

ErrorStatus OPENBL_OTP_EraseSector(uint32_t Address)
{
  if(OPENBL_OTP_ErasePage(OTP_START_ADDRESS) != SUCCESS)
  {
    return ERROR;
  }

  return OPENBL_OTP_ErasePage(OTP_START_ADDRESS + FLASH_PAGE_SIZE);
}

