/*
 * Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * o Redistributions of source code must retain the above copyright notice, this list
 *   of conditions and the following disclaimer.
 *
 * o 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.
 *
 * o Neither the name of Freescale Semiconductor, Inc. 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 "fsl_i2c_master_driver.h"
#include "fsl_uart_driver.h"
#include "i2c_rtos.h"
#include "shell.h"

/*******************************************************************************
 * Defination
 ******************************************************************************/

/*******************************************************************************
 * Global Variables
 ******************************************************************************/
extern uint32_t gSlaveId;

/********************************************************************************
 * Variables
 ******************************************************************************/
/* i2c master driver control block */
static i2c_master_t master;
/* i2c slave info */
static i2c_device_t slave =
{
    .address = I2C_RTOS_SLAVE_ADDRESS,
    .baudRate_kbps = 50
};

static uart_state_t gUARTState;
static uart_user_config_t gShellUARTConfig =        //!< global uart config struct
{
    115200,
    kUartParityDisabled,
    kUartOneStopBit,
    kUart8BitsPerChar
};

static uint8_t Getchar(void);
static void Putchar(uint8_t ch);

static shell_io_install_t gShellIO =
{
    .sh_getc = Getchar,
    .sh_putc = Putchar,
};

/*******************************************************************************
 * Prototypes
 ******************************************************************************/
extern const cmd_tbl_t CommandFun_Help;

static int cmd_read_temperature(int argc, char * const argv[])
{
    i2c_status_t i2c_ret;
    int16_t temperature;
    uint32_t cntRecv;
    /* Buffers for send and recv data to/from I2C bus */
    uint8_t bufRecv[4] = {0};
    uint8_t bufSend[2] = {0};

    if (argc != 1)
    {
        return CMD_RET_USAGE;
    }

    bufSend[0] = I2C_RTOS_MAGIC;
    bufSend[1] = I2C_RTOS_TEMP_CMD;

    /* Send read temperature request to slave */
    i2c_ret = i2c_master_transfer(&master, &slave, kI2CWrite, true,
                                  0, 0, bufSend, 2, NULL, 20);
    if (i2c_ret != kStatus_I2C_Success)
    {
        printf("Error while sending request to slave:%d\r\n", i2c_ret);
        return CMD_RET_FAILURE;
    }

    /* wait for slave prepare the data */
    time_delay(200);

    /* read from slave */
    i2c_master_transfer(&master, &slave, kI2CRead, true,
                        0,0, bufRecv, 4, &cntRecv, 20);
    if (cntRecv != 4)
    {
        printf("Failed to get temperature from slave:%d\r\n", cntRecv);
        return CMD_RET_FAILURE;
    }

    temperature = *(int32_t *)&bufRecv[0];
    /* get data, and convert to C degree */
    printf("Client Chip Temperature:%hdC\r\n", temperature);
    return CMD_RET_SUCCESS;
}

static int cmd_light_led(int argc, char * const argv[])
{
    uint8_t on;
    i2c_status_t i2c_ret;
    /* Buffer for transmitted data.  */
    uint8_t bufSend[4] = {0};

    if (argc != 3)
    {
        return CMD_RET_USAGE;
    }

    /* get value */
    if (*argv[1] != 'R' && *argv[1] != 'G' && *argv[1] != 'B')
    {
        return CMD_RET_USAGE;
    }

    if (strncmp(argv[2], "on", 2) == 0)
    {
        on = 1;
    }
    else if (strncmp(argv[2], "off", 3) == 0)
    {
        on = 0;
    }
    else
    {
        return CMD_RET_USAGE;
    }
    /* Set the send buffer */
    bufSend[0] = I2C_RTOS_MAGIC;
    bufSend[1] = I2C_RTOS_LIGHT_CMD;
    bufSend[2] = *argv[1];
    bufSend[3] = on;

    /* Send RGB value to slave */
    i2c_ret = i2c_master_transfer(&master, &slave,
                                  kI2CWrite, true, 0, 0, bufSend, 4, NULL, 20);
    /* print error message if transfer was not successful */
    if (i2c_ret != kStatus_I2C_Success)
    {
        printf("Error while sending RGB values to slave:%d\r\n", i2c_ret);
        return CMD_RET_SUCCESS;
    }
    return CMD_RET_SUCCESS;
}

#if 0
static int cmd_req_sleep(int argc, char * const argv[])
{
    i2c_status_t i2c_ret;
    /* Buffer for transmitted data.  */
    uint8_t bufSend[6] = {0};

    if (argc != 1)
    {
        return CMD_RET_USAGE;
    }
    /* Set the send buffer */
    bufSend[0] = I2C_RTOS_MAGIC;
    bufSend[1] = I2C_RTOS_SLEEP_CMD;
    *(uint32_t *)&bufSend[2] = gSlaveId;

    /* Send sleep request to slave */
    i2c_ret = i2c_master_transfer(&master, &slave,
                                  kI2CWrite, true, 0, 0, bufSend, 6, NULL, 20);
    /* print error message if transfer was not successful */
    if (i2c_ret != kStatus_I2C_Success)
    {
        printf("Error while sending request to slave:%d\r\n", i2c_ret);
        return CMD_RET_SUCCESS;
    }
    return CMD_RET_SUCCESS;
}
#endif

static int cmd_read_id(int argc, char * const argv[])
{
    i2c_status_t i2c_ret;
    uint32_t cntRecv;
    /* Buffers for send and recv data to/from I2C bus */
    uint8_t bufRecv[4] = {0};
    uint8_t bufSend[2] = {0};

    if (argc != 1)
    {
        return CMD_RET_USAGE;
    }

    bufSend[0] = I2C_RTOS_MAGIC;
    bufSend[1] = I2C_RTOS_READID_CMD;

    /* Send read temperature request to slave */
    i2c_ret = i2c_master_transfer(&master, &slave, kI2CWrite, true,
                                  0, 0, bufSend, 2, NULL, 200);
    if (i2c_ret != kStatus_I2C_Success)
    {
        printf("Error while sending request to slave:%d\r\n", i2c_ret);
        return CMD_RET_FAILURE;
    }

    /* wait for slave prepare the data */
    time_delay(200);

    /* read from slave */
    i2c_master_transfer(&master, &slave, kI2CRead, true,
                        0, 0, bufRecv, 4, &cntRecv, 200);
    if (cntRecv != 4)
    {
        printf("Failed to get id from slave:%d\r\n", i2c_ret);
        return CMD_RET_FAILURE;
    }

    /* get data, and convert to C degree */
    printf("Client ID:0x%x\r\n", *(uint32_t *)&bufRecv[0]);
    return CMD_RET_SUCCESS;
}

static const cmd_tbl_t light_led_cmd =
{
    .name = "led",
    .maxargs = 3,
    .repeatable = 1,
    .cmd = cmd_light_led,
    .help = "led <R/G/B> <on/off>",
    .complete = NULL,
    .usage = "Light on/off the RGB LED",
};

static const cmd_tbl_t read_temp_cmd =
{
    .name = "readtemp",
    .maxargs = 1,
    .repeatable = 1,
    .cmd = cmd_read_temperature,
    .help = "readtemp",
    .complete = NULL,
    .usage = "Get the temperature of the client",
};

#if 0
static const cmd_tbl_t req_sleep_cmd =
{
    .name = "sleep",
    .maxargs = 1,
    .repeatable = 1,
    .cmd = cmd_req_sleep,
    .help = "sleep",
    .complete = NULL,
    .usage = "Put the client into low power mode",
};
#endif

static const cmd_tbl_t read_id_cmd =
{
    .name = "readid",
    .maxargs = 1,
    .repeatable = 1,
    .cmd = cmd_read_id,
    .help = "readid",
    .complete = NULL,
    .usage = "Read the client unique id",
};

 /*!
 * @brief get a char
 */
static uint8_t Getchar(void)
{
    uint8_t ch = 0;
    while (uart_receive_data(&gUARTState, &ch, 1, kSyncWaitForever) != kStatus_UART_Success)
    {
        time_delay(10);
    }
    return ch;
}
 /*!
 * @brief put a char
 */
static void Putchar(uint8_t ch)
{
    while (uart_send_data(&gUARTState, &ch, 1, kSyncWaitForever) != kStatus_UART_Success)
    {
        time_delay(10);
    }
}

#ifdef FSL_RTOS_MQX
void task_master(uint32_t param)
#else
void task_master(void *param)
#endif
{
    /* init i2c master driver */
    i2c_master_init(I2C_RTOS_MASTER_INSTANCE, &master);

    /* Init UART */
    configure_uart_pin_mux(BOARD_DEBUG_UART_INSTANCE);
    uart_init(BOARD_DEBUG_UART_INSTANCE, &gUARTState, &gShellUARTConfig);

    /* install shell IO */
    shell_io_install(&gShellIO);
    /* install cmd */
    shell_register_function(&CommandFun_Help);
    shell_register_function(&light_led_cmd);
    shell_register_function(&read_temp_cmd);
    shell_register_function(&read_id_cmd);
    /* main loop */
    while (1)
    {
        shell_main_loop(">>");
    }
}
