/* 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_slave_int_sample.c
 *
 * @brief i2c_slave_int_sample源文件
 */
/* ===========================================  Includes  =========================================== */
#include "ac7840x.h"
#include "gpio_drv.h"
#include "gpio_hw.h"
#include "i2c_drv.h"
#include "i2c_hw.h"
#include "i2c_slave_int_sample.h"
#include <string.h>
/* ============================================  Define  ============================================ */
#define I2C0_INSTANCE     0    /* i2c 序列号 */
#define I2C_SLAVE_ADDRESS 0x56 /* i2c从机地址 */

#define I2C_CMD_BUF_LEN (2)
#define I2C_TST_BUF_LEN (256)
/* ===========================================  Typedef  ============================================ */

/* ==========================================  Variables  =========================================== */
uint8_t g_tstDataBuf[I2C_TST_BUF_LEN];
uint8_t g_cmdDataBuf[I2C_CMD_BUF_LEN];

uint8_t g_TxBuf[I2C_TST_BUF_LEN];
uint8_t g_RxBuf[I2C_TST_BUF_LEN];

i2c_slave_state_t g_i2c_slave_state;

/* ====================================  Functions declaration  ===================================== */

/* ======================================  Functions define  ======================================== */
// 复位IIC缓存
void I2C_SlaveResetBuff(void)
{
    g_i2c_slave_state.rxBuff    = g_RxBuf;
    g_i2c_slave_state.rxSize    = I2C_TST_BUF_LEN;
    g_i2c_slave_state.rxPointer = 0;
    g_i2c_slave_state.txBuff    = g_TxBuf;
    g_i2c_slave_state.txSize    = I2C_TST_BUF_LEN;
    g_i2c_slave_state.status    = STATUS_BUSY;

    memcpy(g_TxBuf, g_RxBuf, 20);
}

// IIC中断回调
void i2c_slave_callback(uint32_t event, void *userData)
{
    static uint8_t dir = 0;

    if (event == I2C_SLAVE_EVENT_STOP) // 收到停止位
    {
        uint8_t length;
        uint8_t i;

        if (dir) // TX
        {
            length = I2C_TST_BUF_LEN - g_i2c_slave_state.txSize - 1; // 已发送数据长度
            // 打印发送内容
            printf("\r\nTX Length:%d,  data:", length);
            for (i = 0; i < length; i++)
            {
                printf("%d ", g_TxBuf[i]);
            }
            printf("\r\n");
        }
        else // RX
        {
            length = g_i2c_slave_state.rxPointer; // 已接收数据长度
            // 打印接收内容
            printf("\r\nRX Length:%d,  data:", length);
            for (i = 0; i < length; i++)
            {
                printf("%d ", g_RxBuf[i]);
            }
            printf("\r\n");
        }

        I2C_SlaveResetBuff();
        
    }
    else if (event == I2C_SLAVE_EVENT_ADDRESS_MATCH) // 收到地址匹配
    {
        dir = (I2C_GetStatus0(I2C0) & I2C_STATUS0_SRW_Msk) ? 1 : 0; // 判断传输方向
    }
}

/*!
 * @brief I2C0 Init
 *
 * @param[in] none
 * @return none
 */
void I2C0_Init(void)
{
    /* I2C 配置结构体 */
    i2c_slave_user_config_t i2c_slave_config;

    /* 清I2C 配置结构体 */
    memset(&i2c_slave_config, 0, sizeof(i2c_slave_user_config_t));
    memset(&g_i2c_slave_state, 0, sizeof(i2c_slave_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_slave_config.is10bitAddr    = false;                /* 7bit地址模式 */
    i2c_slave_config.slaveAddress   = I2C_SLAVE_ADDRESS;    /* i2c 从机地址 */
    i2c_slave_config.transferType   = I2C_USING_INTERRUPTS; /* i2c 使用中断方式 */
    i2c_slave_config.stretchEn      = false;                /* i2c 同步禁能 */
    i2c_slave_config.wakeupEn       = true;                 /* i2c 仲裁禁能 */
    i2c_slave_config.slaveListening = true;                 /* i2c 一直监听 */
    i2c_slave_config.callback       = i2c_slave_callback;   /* 无回调函数 */

    I2C_DRV_SlaveInit(I2C0_INSTANCE, &i2c_slave_config, &g_i2c_slave_state); /* i2c 调用底层函数后生效 */

    // 启动IIC通讯
    I2C_DRV_SlaveReceiveData(I2C0_INSTANCE, NULL, 0);
    I2C_SlaveResetBuff();
}

/**
 * @prototype I2C_DealDataPrd(void)
 *
 * @param[in] void
 * @return	 void
 *
 * @brief  	 I2C从机处理数据.
 */
// void I2C_DealDataPrd(void)
// {
//     // uint16_t i = 0;

//     if (I2C_DRV_SlaveGetTransferStatus(I2C0_INSTANCE, NULL) == STATUS_SUCCESS) // 收发完毕
//     {
//         if (g_cmdDataBuf[0] == 0) // 从机接收
//         {
//             /*接收数据.*/
//             I2C_DRV_SlaveReceiveDataBlocking(I2C0_INSTANCE, g_tstDataBuf, g_cmdDataBuf[1], 10);
//         }
//         else // 从机发送
//         {
//             /*发送数据.*/
//             I2C_DRV_SlaveSendDataBlocking(I2C0_INSTANCE, g_tstDataBuf, g_cmdDataBuf[1], 10);
//         }

//         /*准备接收指令.*/
//         I2C_DRV_SlaveReceiveData(I2C0_INSTANCE, g_cmdDataBuf, I2C_CMD_BUF_LEN);
//     }
// }
