/**
  ******************************************************************************
  * @file    SPI1_interface.c
  * @author  MCD Application Team
  * @brief   Contains SPI HW configuration
  ******************************************************************************
  * @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
  *
  ******************************************************************************
  */

#include "iwdg_interface.h"
#include "wwdg_interface.h"
#include "spi_common_interface.h"
#include "openbl_usart_cmd.h"
#include "openbl_core.h"

static SPI_HandleTypeDef SPI_Handler = {0};

static void SPI_LowLevelInit(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  /* Peripheral clock enable */
  __HAL_RCC_SPI2_CLK_ENABLE();
  __HAL_RCC_GPIOB_CLK_ENABLE();

  /**SPI1 GPIO Configuration
  PB12     ------> SPI2_NSS
  PB13     ------> SPI2_SCK
  PB14     ------> SPI2_MISO
  PB15     ------> SPI2_MOSI
  */
  
  GPIO_InitStruct.Pin       = GPIO_PIN_12 | GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15;
  GPIO_InitStruct.Mode      = GPIO_MODE_AF_PP;
  GPIO_InitStruct.Pull      = GPIO_PULLUP;
  GPIO_InitStruct.Speed     = GPIO_SPEED_FREQ_HIGH;
  GPIO_InitStruct.Alternate = GPIO_AF5_SPI2;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}

static void OPENBL_SPI_Init(void)
{
  OPENBL_WWDG_Refresh();
  OPENBL_IWDG_Refresh();

  SPI_LowLevelInit();

  SPI_Init(SPI2, &SPI_Handler);
}

static void OPENBL_SPI_DeInit(void)
{
  SPI_DeInit(&SPI_Handler);
  __HAL_RCC_SPI2_CLK_DISABLE();
  __HAL_RCC_SPI2_FORCE_RESET();
  __HAL_RCC_SPI2_RELEASE_RESET();
  HAL_GPIO_DeInit(GPIOB, GPIO_PIN_12 | GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15);
}

static void OPENBL_SPI_Read(uint8_t *buf, uint16_t size)
{
  SPI_Read(&SPI_Handler, buf, size);
}

static void OPENBL_SPI_Write(uint8_t *buf, uint16_t size)
{
  SPI_Write(&SPI_Handler, buf, size);
}

static uint8_t OPENBL_SPI_ProtocolDetection(void)
{
  return SPI_ProtocolDetection(&SPI_Handler);
}

static const OPENBL_OpsTypeDef SPI_Ops =
{
  .Init = OPENBL_SPI_Init,
  .DeInit = OPENBL_SPI_DeInit,
  .Detection = OPENBL_SPI_ProtocolDetection,
  .CommandProcess = OPENBL_USART_CommandProcess,
};

static const OPENBL_IOTypeDef SPI_IO =
{
  .Read = OPENBL_SPI_Read,
  .Write = OPENBL_SPI_Write,
};

OPENBL_HandleTypeDef SPI2_Handle =
{
  .p_Ops = &SPI_Ops,
  .p_IO = &SPI_IO,
};

/************************ (C) COPYRIGHT Puya *****END OF FILE****/
