/*!
 * @file        main.c
 *
 * @brief       Main program body
 *
 * @version     V1.0.3
 *
 * @date        2026-03-14
 *
 * @attention
 *
 *  Copyright (C) 2026 Geehy Semiconductor
 *
 *  You may not use this file except in compliance with the
 *  GEEHY COPYRIGHT NOTICE (Geehy Semiconductor Software License Agreement).
 *
 *  The program is only for reference, which is distributed in the hope
 *  that it will be useful and instructional for customers to develop
 *  their software. Unless required by applicable law or agreed to in
 *  writing, the program is distributed on an "AS IS" BASIS, WITHOUT
 *  ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the Geehy Semiconductor Software License Agreement for the governing permissions
 *  and limitations under the License.
 */

/* Includes */
#include "Board.h"
#include "stdio.h"
#include "gpio_i2c_host.h"
#include "user_i2c_config.h"

/** @addtogroup Examples
  @{
*/

/** @addtogroup I2C_Examples
  @{
  */

/** @addtogroup GPIO_I2C_HOST
  @{
*/

/** @defgroup GPIO_I2C_HOST_Macros Macros
  @{
*/

/* printf function configs to USART1 */
#define DEBUG_USART  USART1

/**@} end of group GPIO_I2C_HOST_Macros */

/** @defgroup GPIO_I2C_HOST_Variables
  @{
*/
static volatile uint8_t keyDowmFlag;

/**@} end of group GPIO_I2C_HOST_Variables */

/** @defgroup GPIO_I2C_HOST_Functions
  @{
*/

void I2c_DelayHost(void);
void I2c_HostKeylInputMode(void);
uint8_t I2c_HostKey1Press(void);
void I2c_HostReadAndWrite(void);

/*!
 * @brief       Main program
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
int main(void)
{
    /* Initialize LED */
    Board_LedInit(LED2);
    Board_LedInit(LED3);
    /* Initialize com1 */
    Board_ComInit(COM1);

    /* Initialize key1 gpio */
    I2c_HostKeylInputMode();
    /* Initialize the I2C gpio */
    I2c_InitGpio();
    /* i2c clock Initiate */
    I2c_InitSysClock(I2C_HOST_CLK_RATE);
    
    for (;;)
    {
        /* when key1 button press, write/read one byte/page */
        if(I2c_HostKey1Press() == 1U)
        {
            /* reset led */
            Board_LedOff(LED2);
            Board_LedOff(LED3);
            /* i2c host write/read one byte/page */
            I2c_HostReadAndWrite();
        }
        else
        {
            /* nothing */
        }
    }
}

/*!
 * @brief       Host device write and read slave device
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
void I2c_HostReadAndWrite(void)
{
    uint8_t writeBuf[32] = {0};
    uint8_t readBuf[32] = {0};
    uint8_t readByte;
    uint8_t n=0;
    /* Initialize the write buffer */
    for(n=0; n<32U; n++)
    {
        writeBuf[n] = n;
    }
    
    /* write 0x55 to address 0x0000 */
    I2c_HostWriteByteExam(0x0000, 0x55);
    /* wait a moment, let the i2c slave device finish recevie data print */
    I2c_DelayHost();

    /* read byte from address 0x0000 */
    readByte = I2c_HostReadByteExam(0x0000);
    if(readByte == 0x55U)
    {
        Board_LedOn(LED2);
        printf("Host write one byte success! \r\n");
    }
    else
    {
        Board_LedOn(LED3);
        printf("Host write one byte failed! \r\n");
    }
    /* wait a moment, let the i2c slave device finish recevie data print */
    I2c_DelayHost();
    

    printf("Host write one page then read back... \r\n");
    /* write one page */
    I2c_HostWritePageExam(0x0000, writeBuf, I2C_SLAVE_PAGE_SIZE);
    /* wait a moment, let the i2c slave device finish recevie data print */
    I2c_DelayHost();
   
    /* read one page */
    I2c_HostReadDataExam(0x0000, readBuf, I2C_SLAVE_PAGE_SIZE);
    for(n=0; n<I2C_SLAVE_PAGE_SIZE; n++)
    {
        printf("Host readBuf[%d] = %d \r\n",n,readBuf[n]);
    }
    /* wait a moment, let the i2c slave device finish recevie data print */
    I2c_DelayHost(); 
}

/*!
 * @brief       KEY1 poll
 *
 * @param       None
 *
 * @retval      0 is key up,1 is key down
 *
 * @note
 */
uint8_t I2c_HostKey1Press(void)
{
    uint8_t ret = 0;
    /* key down */
    if(KEY_READ() == 0U)
    {
        if(keyDowmFlag == 0U)
        {
            /* Debouncing */
            I2c_DelayHost();
            /* key down confirmed */
            if(KEY_READ() == 0U)
            {
                printf("key1 down \r\n");
                keyDowmFlag = 1;
                ret = 1;
            }
            else
            {
                /* nothing */
            }
        }
        else
        {
            /* nothing */
        }
    }
    /* key up */
    else if(KEY_READ() == 1U)
    {
        keyDowmFlag = 0;
    }
    else
    {
        /* nothing */
    }
    return ret;
}

/*!
 * @brief       Set KEY1 pin to input mode
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
void I2c_HostKeylInputMode(void)
{
    Rcm_EnableAhbPeriphClock(KEY1_BUTTON_GPIO_CLK);
    Gpio_Config(KEY1_BUTTON_GPIO_PORT, &g_key1GpioConfig);
}

/*!
 * @brief       I2c_DelayHost
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
void I2c_DelayHost(void)
{
    volatile uint32_t delay = 0x2FFFF;

    while (delay != 0U)
    {
        delay = delay - 1U;
    }
    
}

#if defined (__CC_ARM) || defined (__ICCARM__) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050))

/*!
* @brief       Redirect C Library function printf to serial port.
*              After Redirection, you can use printf function.
*
* @param       ch:  The characters that need to be send.
*
* @param       *f:  pointer to a FILE that can recording all information
*              needed to control a stream
*
* @retval      The characters that need to be send.
*
* @note
*/
int fputc(int ch, FILE* f)
{
    /* send a byte of data to the serial port */
    Usart_TxData(DEBUG_USART, (uint8_t)ch);

    /* wait for the data to be send  */
    while (Usart_ReadStatusFlag(DEBUG_USART, USART_FLAG_TXBE) == (uint8_t)RESET)
    {
        /* nothing */
    }

    return (ch);
}

#elif defined (__GNUC__)

/*!
* @brief       Redirect C Library function printf to serial port.
*              After Redirection, you can use printf function.
*
* @param       ch:  The characters that need to be send.
*
* @retval      The characters that need to be send.
*
* @note
*/
int __io_putchar(int ch)
{
    /* send a byte of data to the serial port */
    Usart_TxData(DEBUG_USART, ch);

    /* wait for the data to be send  */
    while (Usart_ReadStatusFlag(DEBUG_USART, USART_FLAG_TXBE) == RESET);

    return ch;
}

/*!
* @brief       Redirect C Library function printf to serial port.
*              After Redirection, you can use printf function.
*
* @param       file:  Meaningless in this function.
*
* @param       *ptr:  Buffer pointer for data to be sent.
*
* @param       len:  Length of data to be sent.
*
* @retval      The characters that need to be send.
*
* @note
*/
int _write(int file, char* ptr, int len)
{
    int i;
    for (i = 0; i < len; i++)
    {
        __io_putchar(*ptr++);
    }

    return len;
}

#else
#pragma message("Not supported compiler type")
#endif

/**@} end of group GPIO_I2C_HOST_Functions */
/**@} end of group GPIO_I2C_HOST */
/**@} end of group I2C_Examples */
/**@} end of group Examples */
