/*
 * 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 <stdlib.h>
#include <assert.h>
#include <string.h>

#include "fsl_device_registers.h"
#include "fsl_clock_manager.h"
#include "fsl_interrupt_manager.h"
#include "fsl_rtc_driver.h"
#include "fsl_uart_driver.h"
#include "board.h"


/*******************************************************************************
 * Definitions
 ******************************************************************************/

/*******************************************************************************
 * Global Variables
 ******************************************************************************/
volatile bool secondsFlag=0;

/*******************************************************************************
 * Prototypes
 ******************************************************************************/
extern void hardware_init(void);
static void rtc_seconds_ISR(void);
extern IRQn_Type rtc_irq_ids[FSL_FEATURE_RTC_INTERRUPT_COUNT];

/*******************************************************************************
 * Code
 ******************************************************************************/

/*!
 * @brief RTC Seconds ISR
 *
 * Seconds RTC Interrupt function. Toggles an LED and turns on a flag
 *
 */

static void rtc_seconds_ISR(void)
{
  gpio_toggle_pin_output(kGpioLED3); /* Toggle LED each Second*/
  secondsFlag = true;
}

/*!
 * @brief RTC demo main routine
 *
 * Run a simple application which enables RTC timer. Each second time
 * is refreshed on a UART terminal unsing the seconds interrupt. Alarm
 * functionality is currently not enabled.
 *
 */

void main(void)
{

    /* UART TX buffers */
    uint8_t sourceBuff[19] = {"\r\n\nRTC Demo\n\n\r"};

    /* UART configuration structures */
    uart_user_config_t uartConfig;
    uart_state_t uartState;

    /* RTC configuration structures */
    rtc_datetime_t rtcDatetime;
    hw_rtc_ier_t interruptEnable;

    /* Call General Hardware Initialization */
    hardware_init();
    /* init the gpio pins */
    gpio_init(NULL, ledPins);

    /* Configure the UART for 115200, 8 data bits, No parity, and one stop bit*/
    uartConfig.baudRate = 115200;
    uartConfig.bitCountPerChar = kUart8BitsPerChar;
    uartConfig.parityMode = kUartParityDisabled;
    uartConfig.stopBitCount = kUartOneStopBit;

    /* Initialize the UART module */
    uart_init(BOARD_DEBUG_UART_INSTANCE, &uartState, &uartConfig);

    /* Set the Clock Gates on RTC */
    clock_manager_set_gate(kClockModuleRTC, 0, true);

    /* Configure the RTC date and time */
    rtcDatetime.day = 12;
    rtcDatetime.hour = 5;
    rtcDatetime.minute = 22;
    rtcDatetime.month = 11;
    rtcDatetime.second = 0;
    rtcDatetime.year = 2013;

    /* Stop timer just in case */
    rtc_stop_time_counter();
    /* Turn on the RTC Oscillator */
    rtc_hal_config_oscillator(true);
    /* Install the ISR function for seconds */
    /*Register rtc isr callback function.*/
    rtc_register_isr_callback_function(1, rtc_seconds_ISR);

    /* Set the Date and Time */
    if(!rtc_set_datetime(&rtcDatetime, false))
    {
        return;
    }

    /* Configure RTC Interrupt */
    interruptEnable.U = 0;
    interruptEnable.B.TSIE = true;
    rtc_configure_int(&interruptEnable);

    /* Start the timer */
    rtc_start_time_counter();

    /*  Print the initial banner */
    uart_send_data(&uartState, sourceBuff, 13, 1);

    for(;;)
    {
        /* If seconds interrupt ocurred, print new time */
        if(secondsFlag)
        {
          /* Build up the word */
          secondsFlag = false;
          sourceBuff[0] = '\r';
          sourceBuff[1] = ' ';
          sourceBuff[2] = ' ';
          sourceBuff[3] = ' ';
          rtc_get_datetime(&rtcDatetime);
          sourceBuff[4] = ((rtcDatetime.hour/10)+0x30);
          sourceBuff[5] = ((rtcDatetime.hour%10)+0x30);
          sourceBuff[6] = (rtcDatetime.second & 0x01) ? ':':' ';
          sourceBuff[7] = ((rtcDatetime.minute/10) +0x30);
          sourceBuff[8] = ((rtcDatetime.minute%10) +0x30);
          sourceBuff[9] = ' ';
          sourceBuff[10] = ' ';
          sourceBuff[11] = ' ';
          sourceBuff[12] = ((rtcDatetime.second/10) +0x30);
          sourceBuff[13] = ((rtcDatetime.second%10) +0x30);
          sourceBuff[14] = ' ';
          sourceBuff[15] = 'S';
          sourceBuff[16] = 'e';
          sourceBuff[17] = 'c';
          /*  Print the Time */
          uart_send_data(&uartState, sourceBuff, 18, 1);
        }

    }

}

