/**
 *******************************************************************************
 * @file    i2c.c
 *
 * @brief   i2c program body.
 *
 * @author  DPM
 *
 * @version V1.0.0
 *
 * @date    2024-5-6
 *
 *******************************************************************************/

/*
    Copyright (c) 2024, DP Microelectronics Inc.

    Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this
       list of conditions and the following disclaimer.
    2. Redistributions in binary form must reproduce the above copyright notice,
       this list of conditions and the following disclaimer in the documentation
       and/or other materials provided with the distribution.
    3. Neither the name of the copyright holder nor the names of its contributors
       may be used to endorse or promote products derived from this software without
       specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
*/

#include "i2c.h"
#include "dpm32m0xx.h"
#include "systick.h"

#define I2C_PAGE_SIZE 8

/**
 *******************************************************************************
 * @brief   Configure the I2C interface.
 * @param   None.
 * @retval  None.
 ******************************************************************************/
void I2C_Config(void)
{
  RCC_Unlock();
  RCC_AHBPeriphClockCmd(RCC_AHB_PERIPH_GPIO, ENABLE);
  RCC_APBPeriphClockCmd(RCC_APB_PERIPH_I2C, ENABLE);
  RCC_Lock();

  /* Cofig I2C GPIO */
  GPIO_InitTypeStruct GPIO_InitStruct;
  GPIO_InitStruct.GPIO_Mode = GPIO_MODE_ALT_FUNC;
  GPIO_InitStruct.GPIO_Speed = GPIO_SPEED_HIGH;
  GPIO_InitStruct.GPIO_OType = GPIO_OTYPE_OD;
  GPIO_InitStruct.GPIO_PuPd = GPIO_PUPD_NOPULL;
  GPIO_InitStruct.GPIO_Pin = GPIO_PIN_4 | GPIO_PIN_5;
  GPIO_Init(GPIOD, &GPIO_InitStruct);
  GPIO_AltFuncConfig(GPIOD, GPIO_PIN_4 | GPIO_PIN_5, GPIO_ALT_FUNC_1);

  /* Config I2C */
  I2C_DeInit();
  I2C_InitTypeStruct I2C_InitStruct;
  I2C_StructInit(&I2C_InitStruct);
  I2C_InitStruct.I2C_OwnAddress = 0x00;
  I2C_InitStruct.I2C_Prescaler = 0x16;
  I2C_InitStruct.I2C_Timing = 0x00420F13;
  I2C_InitStruct.I2C_DigitalFilter = 0x0F;
  I2C_InitStruct.I2C_Mode = I2C_MODE_MASTER;
  I2C_InitStruct.I2C_AddressingMode = I2C_ADDRESSING_MODE_7BIT;
  I2C_Init(&I2C_InitStruct);

  I2C_Cmd(ENABLE);
}

/**
 *******************************************************************************
 * @brief   I2C bus reset.
 * @param   None.
 * @retval  None.
 ******************************************************************************/
void I2C_BusReset(void)
{
  I2C_DeInit();
  GPIO_InitTypeStruct GPIO_InitStruct;
  GPIO_InitStruct.GPIO_Mode = GPIO_MODE_OUTPUT;
  GPIO_InitStruct.GPIO_Speed = GPIO_SPEED_HIGH;
  GPIO_InitStruct.GPIO_OType = GPIO_OTYPE_PP;
  GPIO_InitStruct.GPIO_PuPd = GPIO_PUPD_NOPULL;
  GPIO_InitStruct.GPIO_Pin = GPIO_PIN_4 | GPIO_PIN_5;
  GPIO_Init(GPIOD, &GPIO_InitStruct);
  __NOP();
  __NOP();
  __NOP();
  __NOP();
  __NOP();
  GPIO_SetBit(GPIOD, GPIO_PIN_4);
  __NOP();
  __NOP();
  __NOP();
  __NOP();
  __NOP();
  GPIO_SetBit(GPIOD, GPIO_PIN_5);

  I2C_Config();
}

/**
 *******************************************************************************
 * @brief   I2C transmit a page with timeout.
 * @param   [in]  SlaveAddress: Slave I2C address.
 * @param   [in]  WriteAddr: Data write address.
 * @param   [in]  Buf: Data buffer.
 * @param   [in]  Len: Data len.
 * @param   [in]  Timeout: Timeout time.
 * @retval  uint8_t OK retrun 0, Fail return 1.
 ******************************************************************************/
uint8_t I2C_BufferTransmitTimeOut(uint8_t SlaveAddress, uint8_t WriteAddr, uint8_t *Buf, uint16_t Len, uint32_t Timeout)
{
  uint32_t cnt = 0;
  uint32_t time = GetTick() + Timeout;

  /* Clear send buffer */
  I2C_ClearTxBuffer();
  /* Config target address */
  I2C_TargetAddressConfig(SlaveAddress);
  /* Config direction */
  I2C_TransferDirectionConfig(I2C_DIRECTION_TRANSMITTER);

  /* Send START signal */
  I2C_GenerateSTART();

  /* Waiting for the START signal end flag */
  while(I2C_GetIntFlagStatus(I2C_INT_FLAG_STARTF) != SET && (time > GetTick()));

  if(time <= GetTick())
  {
    goto TRANSMITERR;
  }

  /* Clear START signal end flag */
  I2C_ClearIntFlag(I2C_INT_FLAG_STARTF);

  if(time <= GetTick())
  {
    goto TRANSMITERR;
  }

  /* Send write addr */
  I2C_SendData(WriteAddr);

  while(I2C_GetIntFlagStatus(I2C_INT_FLAG_TXE) != SET && (time > GetTick()));

  /* Send data */
  while(cnt < Len)
  {
    while(I2C_GetIntFlagStatus(I2C_INT_FLAG_TXE) != SET && (time > GetTick()));

    I2C_SendData(Buf[cnt++]);

    if(time <= GetTick())
    {
      goto TRANSMITERR;
    }
  }

  /* Waiting for sending completion flag */
  while(I2C_GetIntFlagStatus(I2C_INT_FLAG_TXE) != SET && (time > GetTick()));

  if(time <= GetTick())
  {
    goto TRANSMITERR;
  }

  I2C_ClearIntFlag(I2C_INT_FLAG_TXE);
  /* Send STOP signal */
  I2C_GenerateSTOP();

  /* Waiting for the STOP signal end flag */
  while(I2C_GetIntFlagStatus(I2C_INT_FLAG_STOPF) != SET && (time > GetTick()));

  if(time <= GetTick())
  {
    goto TRANSMITERR;
  }

  /* Clear STOP flag */
  I2C_ClearIntFlag(I2C_INT_FLAG_STOPF);

  return 0;
TRANSMITERR:
  I2C_GenerateSTOP();
  return 1;
}

/**
 *******************************************************************************
 * @brief   I2C receive a buffer with timeout.
 * @param   [in]  SlaveAddress: Slave I2C address.
 * @param   [in]  ReadAddr: Data read address.
 * @param   [out] Buf: Data buffer.
 * @param   [in]  Len: Data len.
 * @param   [in]  Timeout: Timeout time.
 * @retval  uint8_t OK retrun 0, Fail return 1.
 ******************************************************************************/
uint8_t I2C_BufferReceiveTimeOut(uint8_t SlaveAddress, uint8_t ReadAddr, uint8_t *Buf, uint16_t Len, uint32_t Timeout)
{
  uint32_t cnt = 0;
  uint32_t time = GetTick() + Timeout;

  /* Clear send buffer */
  I2C_ClearTxBuffer();
  /* Config target address */
  I2C_TargetAddressConfig(SlaveAddress);
  /* Config direction */
  I2C_TransferDirectionConfig(I2C_DIRECTION_TRANSMITTER);
  /* Send START signal */
  I2C_GenerateSTART();

  /* Waiting for the START signal end flag */
  while(I2C_GetIntFlagStatus(I2C_INT_FLAG_STARTF) != SET && (time > GetTick()));

  if(time <= GetTick())
  {
    goto RECEIVEERR;
  }

  /* Clear START signal end flag */
  I2C_ClearIntFlag(I2C_INT_FLAG_STARTF);

  /* Send read addr */
  I2C_SendData(ReadAddr);

  while(I2C_GetIntFlagStatus(I2C_INT_FLAG_TXE) != SET && (time > GetTick()));

  if(time <= GetTick())
  {
    goto RECEIVEERR;
  }

  /* Config direction */
  I2C_TransferDirectionConfig(I2C_DIRECTION_RECEIVER);
  /* Config bytes received */
  I2C_NumberOfBytesConfig(Len);
  /* Send START signal */
  I2C_GenerateSTART();

  /* Waiting for the START signal end flag */
  while(I2C_GetIntFlagStatus(I2C_INT_FLAG_STARTF) != SET&& (time > GetTick()));

  if(time <= GetTick())
  {
    goto RECEIVEERR;
  }

  /* Clear START signal end flag */
  I2C_ClearIntFlag(I2C_INT_FLAG_STARTF);

  /* Receive data */
  while(cnt < Len)
  {
    /* Receive data buffer is not empty detection flag */
    if(I2C_GetIntFlagStatus(I2C_INT_FLAG_RXNE) == SET&& (time > GetTick()))
    {
      Buf[cnt++] = I2C_ReceiveData();
    }

    if(time <= GetTick())
    {
      goto RECEIVEERR;
    }
  }

  /* Send STOP signal */
  I2C_GenerateSTOP();

  /* Waiting for the STOP signal end flag */
  while(I2C_GetIntFlagStatus(I2C_INT_FLAG_STOPF) != SET&& (time > GetTick()));

  if(time <= GetTick())
  {
    goto RECEIVEERR;
  }

  /* Clear STOP flag */
  I2C_ClearIntFlag(I2C_INT_FLAG_STOPF);

  return 0;

RECEIVEERR:

  I2C_GenerateSTOP();
  I2C_ClearIntFlag(I2C_INT_FLAG_STOPF);

  return 1;
}


