/* Copyright Statement:
 *
 * This software/firmware and related documentation ("AutoChips Software") are
 * protected under relevant copyright laws. The information contained herein is
 * confidential and proprietary to AutoChips Inc. and/or its licensors. Without
 * the prior written permission of AutoChips inc. and/or its licensors, any
 * reproduction, modification, use or disclosure of AutoChips Software, and
 * information contained herein, in whole or in part, shall be strictly
 * prohibited.
 *
 * AutoChips Inc. (C) 2024. All rights reserved.
 *
 * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
 * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("AUTOCHIPS SOFTWARE")
 * RECEIVED FROM AUTOCHIPS AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
 * ON AN "AS-IS" BASIS ONLY. AUTOCHIPS EXPRESSLY DISCLAIMS ANY AND ALL
 * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
 * NONINFRINGEMENT. NEITHER DOES AUTOCHIPS PROVIDE ANY WARRANTY WHATSOEVER WITH
 * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
 * INCORPORATED IN, OR SUPPLIED WITH THE AUTOCHIPS SOFTWARE, AND RECEIVER AGREES
 * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
 * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
 * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN AUTOCHIPS
 * SOFTWARE. AUTOCHIPS SHALL ALSO NOT BE RESPONSIBLE FOR ANY AUTOCHIPS SOFTWARE
 * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
 * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND AUTOCHIPS'S
 * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE AUTOCHIPS SOFTWARE
 * RELEASED HEREUNDER WILL BE, AT AUTOCHIPS'S OPTION, TO REVISE OR REPLACE THE
 * AUTOCHIPS SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
 * CHARGE PAID BY RECEIVER TO AUTOCHIPS FOR SUCH AUTOCHIPS SOFTWARE AT ISSUE.
 */
/******************************************************************************
 * @version: V3.1.0  AC7840x  Demo
 ******************************************************************************/

/*!
 * @file i2c_master_dma_sample.c
 *
 * @brief i2c_master_dma_sample源文件
 */
/* ===========================================  Includes  =========================================== */
#include <string.h>
#include "i2c_drv.h"
#include "gpio_drv.h"
#include "Dma_Config.h"
#include "i2c_master_sample.h"

/* ============================================  Define  ============================================ */
#define I2C0_INSTANCE        0               /* i2c 序列号 */
#define I2C_SLAVE_ADDRESS    0x50            /* i2c从机地址 */

#define AT24C02_MAX_SIZE        (256)
#define AT24C02_WR_TST_ADDR     (0x00)
#define AT24C02_TST_BUF_LEN     (256)

/* ===========================================  Typedef  ============================================ */


/* ==========================================  Variables  =========================================== */
i2c_master_state_t   g_i2c_master_state;      /* i2c0 主机状态结构体 */

uint8_t g_eepromTstDataBuf[AT24C02_MAX_SIZE] = {0};

bool g_TxFinishFlag = false;
/* ====================================  Functions declaration  ===================================== */


/* ======================================  Functions define  ======================================== */

void I2C0_CallBack(uint32_t event, void *userData)
{
    if(event == I2C_MASTER_EVENT_END_TRANSFER)
    {
        g_TxFinishFlag = true;
    }
}

/*!
* @brief I2C0 初始化
*
* @param[in] none
* @return none
*/
void I2C0_Init(void)
{
    /* I2C 配置结构体 */
    i2c_master_user_config_t i2c_master_config;
    
    /* 清I2C 配置结构体 */
    memset(&i2c_master_config, 0, sizeof(i2c_master_user_config_t));
    memset(&g_i2c_master_state, 0, sizeof(i2c_master_state_t));
    
    /* PA2->SDA, PPA3->SCL */
    GPIO_DRV_SetMuxModeSel(PORTA, (gpio_channel_type_t)2U, PORT_MUX_ALT3);
    GPIO_DRV_SetMuxModeSel(PORTA, (gpio_channel_type_t)3U, PORT_MUX_ALT3);
    
    i2c_master_config.is10bitAddr    = false;                /* 7bit地址模式 */
    i2c_master_config.slaveAddress   = I2C_SLAVE_ADDRESS;    /* i2c 从机地址 */
    i2c_master_config.dmaChannel     = DMA_I2C_CHANNEL;    /* dma 通道 */
    i2c_master_config.transferType   = I2C_USING_DMA;        /* 使用i2c DMA模式 */
    i2c_master_config.syncEn         = false;                /* i2c 同步禁能 */
    i2c_master_config.arbitration    = true;                 /* i2c 仲裁禁能 */
    i2c_master_config.baudRate       = 100000;               /* i2c 波特率 */
    i2c_master_config.callback       = I2C0_CallBack;                 /* 无回调函数 */
   
    I2C_DRV_MasterInit(I2C0_INSTANCE,&i2c_master_config,&g_i2c_master_state);  /* I2C0 主机初始化 */
}

/**
* @prototype AT24C0X_ReadBytes(uint8_t startAddr, uint8_t *pDataBuf, uint16_t dataLen)
*
* @param[in] startAddr:Read data starting address
* @param[in] pDataBuf: Read Data Cache
* @param[in] dataLen:  Read data length
* @return    void
*
* @brief     Reading data from EEPROM.
*/
void AT24C0X_ReadBytes(uint8_t startAddr, uint8_t *pDataBuf, uint16_t dataLen)
{
    g_i2cTxBuff[0] = startAddr;
    I2C_DRV_MasterSendData(I2C0_INSTANCE, &g_i2cTxBuff[0], 1, false); /*Send Read Address*/
    while(!g_TxFinishFlag);
    g_TxFinishFlag = false;
    
    I2C_DRV_MasterReceiveData(I2C0_INSTANCE, pDataBuf, dataLen, true);       /*read data*/
    while(!g_TxFinishFlag);
    g_TxFinishFlag = false;
}

/**
* @prototype AT24C0X_WriteBytes(uint8_t startAddr, uint8_t *pDataBuf, uint16_t dataLen)
*
* @param[in] startAddr:Write data start address
* @param[in] pDataBuf: Write data buffer
* @param[in] dataLen:  Write data length
* @return    void
*
* @brief     Write data to EEPROM.
*/
void AT24C0X_WriteBytes(uint8_t startAddr, uint8_t *pDataBuf, uint16_t dataLen)
{
    uint8_t ii, restLen, wrTimes;

    if ((startAddr + (dataLen - 1)) > AT24C02_ADDR_MAX) 
    {
        return; /*Address out of range exit*/
    }

    restLen = (dataLen % 8);
    wrTimes = (dataLen / 8);

    for (ii = 0; ii < wrTimes; ii++)
    {
        g_i2cTxBuff[0] = startAddr;
        startAddr   += AT24C02_PAGE_SIZ;
        memcpy(&g_i2cTxBuff[1], &pDataBuf[ii * AT24C02_PAGE_SIZ], AT24C02_PAGE_SIZ);  /*Single page write 8 bytes*/
        I2C_DRV_MasterSendData(I2C0_INSTANCE, g_i2cTxBuff, (AT24C02_PAGE_SIZ + 1), ENABLE);
        while(!g_TxFinishFlag);
        g_TxFinishFlag = false;
        
        OSIF_TimeDelay(5);/*Need to wait for 5ms to send the next write command*/
    }

    if (restLen > 0)/*Not full page, requires single byte write*/
    {
        for (ii = 0; ii < restLen; ii++)
        {
            g_i2cTxBuff[0] = startAddr++;
            memcpy(&g_i2cTxBuff[1], &pDataBuf[wrTimes * AT24C02_PAGE_SIZ + ii], 1);
            I2C_DRV_MasterSendData(I2C0_INSTANCE, g_i2cTxBuff, 2, ENABLE);/*Write 1 byte at a time*/
            while(!g_TxFinishFlag);
            g_TxFinishFlag = false;
            
            OSIF_TimeDelay(5);/*Need to wait for 5ms to send the next write command*/
        }
    }
}

/**
* @prototype AT24C0X_WriteDataTest(void)
*
* @param[in] void
* @return    void
*
* @brief     Write data to EEPROM for testing.
*/
void AT24C0X_WriteDataTest(void)
{
    /*Prepare data.*/
    for (uint16_t ii = 0; ii < AT24C02_TST_BUF_LEN; ii++)
    {
        g_eepromTstDataBuf[ii] = ii;
        printf("%d ", g_eepromTstDataBuf[ii]);
    }
    printf("\r\n");

    /*Write data.*/
    AT24C0X_WriteBytes(AT24C02_WR_TST_ADDR, g_eepromTstDataBuf, AT24C02_TST_BUF_LEN);
}

/**
* @prototype AT24C0X_ReadDataTest(void)
*
* @param[in] void
* @return    void
*
* @brief     Test reading data from EEPROM.
*/
void AT24C0X_ReadDataTest(void)
{
    /*Read data.*/
    memset(g_i2cRxBuff, 0x00, AT24C02_TST_BUF_LEN);
    AT24C0X_ReadBytes(AT24C02_WR_TST_ADDR, g_i2cRxBuff, AT24C02_TST_BUF_LEN);

    /*Print data*/
    for (uint16_t ii = 0; ii < AT24C02_TST_BUF_LEN; ii++)
    {
        printf("%d ", g_i2cRxBuff[ii]);
    }
}

/*!
* @brief  Communication test of W25x16
*
* @param[in] none
* @return none
*/
void AT24C02_Test(void)
{
    AT24C0X_WriteDataTest();
    OSIF_TimeDelay(100);
    AT24C0X_ReadDataTest();
    OSIF_TimeDelay(100);
}
