/**
 * \file    sys_i2c.c
 * \brief   I2C slave process engine
 *
 * \par     Copyright (c) 2016 UWE Technologies Corp., Ltd. All Rights Reserved.
 * \author  James
 * \date    2016-05-19
 * \version 
 * 
 * \history 
 *  Date        Note
 *  2016-05-19  Original Creation
 * 
 */

#include "libc.h"
#include "drivers.h"
#include "sys_i2c.h"
#include "sys_config.h"

#if (I2C_MODULE_ENABLED && I2C_MODULE_SLA_ENABLED  && !(I2C_SLA_CB_ENABLED))

void sys_i2c_handler(DRV_I2C_ID_t i2c_id)
{
    u8_t rx_len = g_i2c_info[i2c_id].rx_data_index;
    g_i2c_info[i2c_id].tx_data_index = 0;
    for (int i = 0; i < rx_len; i++)
    {
        g_i2c_info[i2c_id].tx_data[i] = g_i2c_info[i2c_id].rx_data[i];
    }
    g_i2c_info[i2c_id].tx_data_len = rx_len;
    g_i2c_info[i2c_id].rx_data_index = 0;
    //clear I2C interrupt
    drv_i2c_clear_si(i2c_id);
    //enable I2C interrupt
    drv_i2c_interrupt_enable(i2c_id);
    if (sys_cfg_dbg_get())
    {
        drv_uart_puts("I2C ACK");
    }
    rtc_delay_us(1000);
#if CLI_ENABLED
    if (sys_cfg_dbg_get() > SYS_DEBUG_LEVEL_2)
    {
        if (rx_len)
        {
            drv_uart_puts("I2C RX:");
            drv_uart_puthex(&(g_i2c_info[i2c_id].rx_data[0]), rx_len, FALSE);
        }
        if (g_i2c_info[i2c_id].tx_data_len)
        {
            drv_uart_puts("I2C TX:");
            drv_uart_puthex(&(g_i2c_info[i2c_id].tx_data[0]), g_i2c_info[i2c_id].tx_data_len, FALSE);
        }
    }
#endif /* CLI_ENABLED */
}

#elif (I2C_MODULE_ENABLED && I2C_MODULE_SLA_ENABLED  && I2C_SLA_CB_ENABLED)

volatile u8_t i2c_sla_rx_len = 0;
volatile u8_t i2c_sla_rx_data[I2C_BUFFER_SIZE];
void sys_i2c_rx_handler(DRV_I2C_ID_t i2c_id, u8_t* received_data, u8_t received_len)
{
    i2c_sla_rx_len = received_len;
    for (int i = 0; ((i < received_len) && (i < I2C_BUFFER_SIZE)); i++)
    {
        i2c_sla_rx_data[i] = received_data[i];
    }
    drv_i2c_sla_cleanup(i2c_id);
#if CLI_ENABLED
    if (sys_cfg_dbg_get() > SYS_DEBUG_LEVEL_2)
    {
        if (received_len)
        {
            drv_uart_puts("I2C RX:");
            drv_uart_puthex(received_data, received_len, FALSE);
        }
    }
#endif /* CLI_ENABLED */
}

u8_t sys_i2c_tx_handler(DRV_I2C_ID_t i2c_id, u8_t tx_data_len_max, u8_t* transmit_data)
{
    u8_t i;
    for (i = 0; ((i < i2c_sla_rx_len) && (i < tx_data_len_max)); i++)
    {
        transmit_data[i] = i2c_sla_rx_data[i];
    }
#if CLI_ENABLED
    if (sys_cfg_dbg_get() > SYS_DEBUG_LEVEL_2)
    {
        drv_uart_puts("I2C TX:");
        drv_uart_puthex(transmit_data, i, FALSE);
    }
#endif /* CLI_ENABLED */
    return i;
}

#endif

