/**
  ******************************************************************************
  * @file    usart3_interface.c
  * @author  MCD Application Team
  * @brief   Contains USART 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 "usart_common_interface.h"
#include "openbl_usart_cmd.h"
#include "openbl_core.h"

static SCI_HandleTypeDef USART_Handler = {0};

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

  /* Peripheral clock enable */
  __HAL_RCC_USART3_CLK_ENABLE();
  __HAL_RCC_GPIOC_CLK_ENABLE();

  /**USART3 GPIO Configuration
  PC10    ------> USART3_TX
  PC11    ------> USART3_RX
  */
  GPIO_InitStruct.Pin       = GPIO_PIN_10 | GPIO_PIN_11;
  GPIO_InitStruct.Mode      = GPIO_MODE_AF_PP;
  GPIO_InitStruct.Pull      = GPIO_PULLUP;
  GPIO_InitStruct.Speed     = GPIO_SPEED_FREQ_HIGH;
  GPIO_InitStruct.Alternate = GPIO_AF7_USART3;
  HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
}

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

  USART_LowLevelInit();

  USART_Init(USART3, &USART_Handler);
}

static void OPENBL_USART_DeInit(void)
{
  USART_DeInit(&USART_Handler);
  __HAL_RCC_USART3_CLK_DISABLE();
  __HAL_RCC_USART3_FORCE_RESET();
  __HAL_RCC_USART3_RELEASE_RESET();
  HAL_GPIO_DeInit(GPIOC ,GPIO_PIN_10 | GPIO_PIN_11);
}

static void OPENBL_USART_Read(uint8_t *buf, uint16_t size)
{
  USART_Read(&USART_Handler, buf, size);
}

static void OPENBL_USART_Write(uint8_t *buf, uint16_t size)
{
  USART_Write(&USART_Handler, buf, size);
}

static uint8_t OPENBL_USART_ProtocolDetection(void)
{
  return USART_ProtocolDetection(&USART_Handler);
}

static const OPENBL_OpsTypeDef USART_Ops =
{
  .Init = OPENBL_USART_Init,
  .DeInit = OPENBL_USART_DeInit,
  .Detection = OPENBL_USART_ProtocolDetection,
  .CommandProcess = OPENBL_USART_CommandProcess,
};

static const OPENBL_IOTypeDef USART_IO =
{
  .Read = OPENBL_USART_Read,
  .Write = OPENBL_USART_Write,
};

OPENBL_HandleTypeDef USART3_Handle =
{
  .p_Ops = &USART_Ops,
  .p_IO = &USART_IO,
};

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