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

static I2C_HandleTypeDef I2C_Handler = {0};

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

  /* Peripheral clock enable */
  __HAL_RCC_GPIOC_CLK_ENABLE();                   /* Enable GPIOC clock */
  __HAL_RCC_I2C4_CLK_ENABLE();                    /* Enable I2C3 clock */

  /**I2C GPIO Configuration
  PC6  -------> I2C4_SCL
  PC7  -------> I2C4_SDA
  */
  GPIO_InitStruct.Pin = GPIO_PIN_6 | GPIO_PIN_7;
  GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;                     /* Open-drain mode */
  GPIO_InitStruct.Pull = GPIO_PULLUP;                         /* Pull-up */
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
  GPIO_InitStruct.Alternate = GPIO_AF8_I2C4;                  /* Alternate as I2C */
  HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);                     /* Initialize GPIO */
}

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

  I2C_LowLevelInit();

  I2C_Init(I2C4, &I2C_Handler);
}

static void OPENBL_I2C_DeInit(void)
{
  I2C_DeInit(&I2C_Handler);
  __HAL_RCC_I2C4_CLK_DISABLE();
  __HAL_RCC_I2C4_FORCE_RESET();
  __HAL_RCC_I2C4_RELEASE_RESET();
  HAL_GPIO_DeInit(GPIOC ,GPIO_PIN_6 | GPIO_PIN_7);
}

static void OPENBL_I2C_Read(uint8_t *buf, uint16_t size)
{
  I2C_Read(&I2C_Handler, buf, size);
}

static void OPENBL_I2C_Write(uint8_t *buf, uint16_t size)
{
  I2C_Write(&I2C_Handler, buf, size);
}

static uint8_t OPENBL_I2C_ProtocolDetection(void)
{
  return I2C_ProtocolDetection(&I2C_Handler);
}

static OPENBL_OpsTypeDef I2C_Ops =
{
  .Init = OPENBL_I2C_Init,
  .DeInit = OPENBL_I2C_DeInit,
  .Detection = OPENBL_I2C_ProtocolDetection,
  .CommandProcess = OPENBL_USART_CommandProcess,
};

static OPENBL_IOTypeDef I2C_IO =
{
  .Read = OPENBL_I2C_Read,
  .Write = OPENBL_I2C_Write,
};

OPENBL_HandleTypeDef I2C4_Handle =
{
  .p_Ops = &I2C_Ops,
  .p_IO = &I2C_IO,
};

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