/*
 * 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 "i2c_dac_mstr.h"
#include "fsl_uart_driver.h"

/*******************************************************************************
 * Global Variables
 ******************************************************************************/
uint8_t i2c0_txData[TX_DEPTH] = {0,0,0,0,0,0,0,0,0,0,0};   // Buffer for transmitted data. 
/* @param i2c0_rxData Buffer for received data from I2C bus*/
uint8_t i2c0_rxData[RX_DEPTH] = {0,0,0,0,0,0,0,0,0,0,0};

/*******************************************************************************
 * Prototypes
 ******************************************************************************/

/********************************************************************/
int main (void)
{
    // General Variables
    char cmd = 0, i2cSlaveVar = 0;
    int r_val = 0, g_val = 0, b_val = 0; 
    i2c_master_t master;
    i2c_status_t error;
   
    i2c_device_t slave = 
    {
        .address = DEFAULT_SLAVE_ADDRESS,
        .baudRate_kbps = 50
    };
    
    // Initialize hardware
    hardware_init();
    // Init uart driver for stdio.
    dbg_uart_init();

    sw_timer_init_service();

    
#ifdef __GCC
  // If we are using a GCC based compiler, we must call this function to change
  // the buffer behavior such that a new line character, "\n", is not 
  // required to print characters to the terminal.  
  setvbuf(stdout, NULL, _IONBF, 0);
#endif
  
#if (defined(CPU_MKL25Z128VLK4))
    /* Enable the UART0 Source clock */
    SIM->SOPT2 |= SIM_SOPT2_UART0SRC(1);
    
    /* Set the PLLFLLSEL bit to 1 to select the PLL as the source */
    SIM->SOPT2 |= SIM_SOPT2_PLLFLLSEL_MASK;
#endif     
    
    printf("Starting I2C DAC demo (master)...\n\r");
    
    // Init I2C driver.
    i2c_master_init(BOARD_DAC_I2C_INSTANCE, &master);
    
    printf("I2C master initialization complete.  \n\n\r");
    
    printf("Please ensure that you have made the connections specified\n\r");
    printf("in the I2C_DAC user guide and then select from the following\n\r");
    printf("commands.\n\n\r");
    
    while(1)
    {
        printf("Select from the following menu: \n\r");
        printf("**************************************************\n\r");
        printf("* 1:  Set new RGB value                          *\n\r");
        printf("* 2:  Output RGB value                           *\n\r");
        printf("* 3:  Latch new address without resetting        *\n\r");
        printf("* 4:  Set DAC to sleep mode                      *\n\r");
        printf("**************************************************\n\n\r");

        while(!uart_hal_is_receive_data_register_full(BOARD_DEBUG_UART_INSTANCE)) 
        {}
        cmd = getchar(); 
        
        switch(cmd) {
          case '1':
            /* Get the RGB value input the user wants to send */
            printf("\n\rEnter R value:  ");
            
            while(!uart_hal_is_receive_data_register_full(BOARD_DEBUG_UART_INSTANCE)) 
            {}
            /*scanf_num = scanf("%d", &r_val);*/
            r_val = getchar();
            
            /* Echo R value */
            printf("%d\n\n\r", r_val - 48);
            
            printf("Enter G value:  ");
            
            while(!uart_hal_is_receive_data_register_full(BOARD_DEBUG_UART_INSTANCE)) 
            {}

            g_val = getchar();
            /* Echo R value */
            printf("%d\n\n\r", g_val - 48);
            
            printf("Enter B value:  ");
            
            while(!uart_hal_is_receive_data_register_full(BOARD_DEBUG_UART_INSTANCE)) 
            {}
            b_val = getchar();
            
            /* Echo R value */
            printf("%d\n\n\r", b_val - 48);
            
            /* Set the send buffer */
            i2c0_txData[0] = I2C_DAC_BUFFER_CMD;
            i2c0_txData[1] = r_val - 48;
            i2c0_txData[2] = g_val - 48;
            i2c0_txData[3] = b_val - 48; 
            
            /* Send RGB value to DAC buffer */
            error = i2c_master_transfer(&master, &slave, kI2CWrite, true, 0, 0, i2c0_txData, 4, NULL, 200);
            
            /* Print error message if transfer was not successful */
            if(error != kStatus_I2C_Success)
            {
                printf("Error while sending RGB values to the buffer!\n\n\r");
            }
            
            break;
          case '2':
            /* Latch DAC buffer to output */
            printf("Sending latch command.  \n\n\r");
            
            /* Set the send buffer */
            i2c0_txData[0] = I2C_DAC_LATCH_CMD;
            
            /* Send command to DAC buffer */
            error = i2c_master_transfer(&master, &slave, kI2CWrite, true, 0, 0, i2c0_txData, 1, NULL, 200);
            
            /* Print error message if transfer was not successful */
            if(error != kStatus_I2C_Success)
            {
                printf("Error while sending latch command!\n\n\r");
            }
            
            break;
          case '3':
            /* Command DAC to get new address */
            printf("Sending Address Sample Command to the general call address.  \n\n\r");
            
            /* Set the send buffer */
            i2c0_txData[0] = I2C_DAC_SET_NEW_ADDR_CMD;
            
            /*  Set slave address to the general call address */
            slave.address = GENERAL_CALL_ADDR;
            
            /* Send command to DAC buffer */
            error = i2c_master_transfer(&master, &slave, kI2CWrite, true, 0, 0, i2c0_txData, 1, NULL, 200);
            
            if(error != kStatus_I2C_Success)
            {
                printf("Error while transferring General Call!\n\n\r");
                
                slave.address = DEFAULT_SLAVE_ADDRESS;
                break;
            }
            
            /* Edit transfer data buffer to send "ping packet" to slave */
            i2c0_txData[0] = 0xAA;
            
            /* Find the new Address */
            do
            {
                slave.address = (i2cSlaveVar);
                slave.address |= SLAVE_BASE;
                error = i2c_master_transfer(&master, &slave, kI2CWrite, true, 0, 0, i2c0_txData, 1, NULL, 200);
                if(error != kStatus_I2C_Success)
                {
                    i2cSlaveVar++;
                }
            }while ((error == kStatus_I2C_ReceivedNak) && (i2cSlaveVar < 4));
            
            /* If a new slave address was found, change slave address to new
               address.  
            
               Otherwise, revert to the default slave address
               and report error */
            if(i2cSlaveVar < 4)
            {
                /*  Configure new slave address */
                slave.address = (i2cSlaveVar);
                slave.address |= SLAVE_BASE;
                printf("The new slave address is:  0x%X\n\n\r", slave.address);
                
                i2cSlaveVar = 0;
            }
            else
            {
                /* Slave was not found; configure slave address to default slave
                   address.  */
                slave.address = DEFAULT_SLAVE_ADDRESS;
                
                printf("No slave found!!!\n\n\r");
                
                i2cSlaveVar = 0;
            }
            
            break;
          case '4':
            /* Command DAC to transition to sleep mode */
            printf("Putting slave to sleep.  \n\n\r");
            
            /* Set the send buffer */
            i2c0_txData[0] = I2C_DAC_SLEEP_CMD;
            
            /* Send command to DAC buffer */
            error = i2c_master_transfer(&master, &slave, kI2CWrite, true, 0, 0, i2c0_txData, 1, NULL, 200);
            
            /* Print error message if transfer was not successful */
            if(error != kStatus_I2C_Success)
            {
                printf("Error while sending latch command!\n\n\r");
            }
            break;
          default:
            /* An invalid command was entered.  Report to user */
            printf("Invalid command entered! \n\n\r");
            break;
        }
        
    }
}
/********************************************************************/
/********************************************************************/
