/*
 * 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 "low_power_adc.h"

#include "fsl_clock_manager.h"

#include "fsl_gpio_driver.h"
#include "fsl_adc_driver.h"

#include "fsl_device_registers.h"
#include "fsl_adc_hal.h"
#include "fsl_smc_manager.h"
#include "fsl_smc_hal.h"
#include "fsl_sim_hal.h"
#include "fsl_pit_driver.h"
#include "fsl_interrupt_manager.h"

#include "board.h"


/*******************************************************************************
 * Definitions
 ******************************************************************************/
#define ADC_1                   (1)
#define MUXGROUP_0              (0)
#define LED_ON                  (0)
#define LED_OFF                 (1)
/*!
* @brief These values are used to get the temperature. DO NOT MODIFY
*/
#define VTEMP25_ADC             (14219)
#define K                       (10000)
#define M1                      (250000)
#define M2                      (311)

#define UPPER_VALUE_LIMIT       (1)     /*! This value/10 is going to be added to current Temp to set the upper boundary*/
#define LOWER_VALUE_LIMIT       (1)     /*! This Value/10 is going to be subtracted from current Temp to set the lower boundary*/
#define LPTMR_COMPARE_VALUE     (500)   /*! Low Power Timer interrupt time in miliseconds */
#define UPDATE_BOUNDARIES_TIME  (20)    /*! This value indicates the number of cycles needed to update boundaries. To know the Time it will take, multiply this value times LPTMR_COMPARE_VALUE*/
/*******************************************************************************
 * Variables
 ******************************************************************************/

static uint32_t adcValue = 0;   /*! ADC value */
volatile bool conversionCompleted = false; /*! Conversion is completed Flag */

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

/* Init clock manager for ADC, PORT, and LPTIMER */
void init_hardware(void)
{
    uint16_t i;

    hardware_init();
    /* open IO Port moudle clock */
    for (i = 0; i < HW_PORT_INSTANCE_COUNT; i++)
    {
        clock_manager_set_gate(kClockModulePORT, i, true);
    }
    /* open ADC module clock */
    clock_manager_set_gate(kClockModuleADC, ADC_1, true);

    /* open LPT moduel clock */
    clock_hal_set_gate(kSimClockModuleLPTIMER, MUXGROUP_0, true);
}

/* LPTMR interrupt handler */
void LowPowerTimerIRQHandler(void)
{
    LPTMR0_CSR|=LPTMR_CSR_TCF_MASK;  /* Clear LPT Compare flag */
}

/* Initialize low power timer */
void InitLowPowerTmr(void)
{
    /* Reset LPTMR settings */
    LPTMR0_CSR = 0;

    /* Set compare value (in ms) */
    LPTMR0_CMR = LPTMR_CMR_COMPARE(LPTMR_COMPARE_VALUE);

     /* Use 1kHz LPO with no prescaler */
    LPTMR0_PSR = LPTMR_PSR_PCS(0x1) | LPTMR_PSR_PBYP_MASK;

    /* Enable LPT interrupt */
    LPTMR0_CSR=LPTMR_CSR_TIE_MASK;

    /* Interrupt handler is registered */
    interrupt_register_handler(LPTimer_IRQn, &LowPowerTimerIRQHandler);

    /* Enable the interrupt */
    interrupt_enable(LPTimer_IRQn);

    /* Turn on LPTMR and start counting */
    LPTMR0_CSR|=LPTMR_CSR_TEN_MASK;
}

/* ADC Interrupt Handler */
void ADC1IRQHandler(void)
{
    /* Get current ADC value */
    adcValue = adc_hal_get_conversion_value (ADC_1, MUXGROUP_0);
    /* Set conversionCompleted flag. This prevents an wrong conversion in main function */
    conversionCompleted = true;
}

/* Calculate the current temperature */
uint32_t GetCurrentTempValue(void)
{
    uint32_t currentTemperature = 0;
    currentTemperature = (M1 - (adcValue - VTEMP25_ADC) * M2)/K;
    return currentTemperature;
}

/* Calculate the average temperature and set boundaries */
lowPowerAdcBoundaries_t TempSensorCalibration(uint32_t updateBoundariesCounter,
                                                     uint32_t *tempArray)
{
    uint32_t avgTemp = 0;
    lowPowerAdcBoundaries_t boundaries;

    for(int i = 0; i < updateBoundariesCounter; i++)
    {
        avgTemp += tempArray[i];
    }
    /* Get average temperature */
    avgTemp /= updateBoundariesCounter;

    /* Set upper boundary*/
    boundaries.upperBoundary = avgTemp + UPPER_VALUE_LIMIT;

    /* Set lower boundary */
    boundaries.lowerBoundary = avgTemp - LOWER_VALUE_LIMIT;

    return boundaries;
}

void main(void)
{
    uint32_t currentTemperature = 0;
    uint32_t updateBoundariesCounter = 0;
    uint32_t tempArray[UPDATE_BOUNDARIES_TIME * 2];
    lowPowerAdcBoundaries_t boundaries;

    /* Init hardware for TWR-K70F120M */
    init_hardware();

    /* Initialize GPIO pins */
    gpio_init(accelIntPins, ledPins);

    /* ADC Configuration */
    adc_user_config_t tempSnseAdcConfig =
    {
        .clockSourceMode = kAdcClockSourceAsynchrounous,
        .clockSourceDividerMode = kAdcClockDivider8,
        .resolutionMode = kAdcSingleDiff16,
        .referenceVoltageMode = kAdcVoltageVref,
        .isContinuousEnabled = false
    };

    /* ADC Channel Configuration */
    adc_channel_config_t tempSnseChannelConfig =
    {
        .channelId = kAdcChannelTemperature,
        .muxSelect = kAdcChannelMuxA,
        .isDifferentialEnabled = false,
        .isInterruptEnabled = true
    };

    /* ADC Extended Configuration */
    adc_extend_config_t adcExtConfig =
    {
        .isLowPowerEnabled      = false,
        .isLongSampleEnabled    = false,
        .hwLongSampleMode       = kAdcLongSampleExtra20,
        .isHighSpeedEnabled     = false,
        .isAsynClockEnabled     = true,
        .isHwTriggerEnabled     = true,
        .isHwCompareEnabled     = false,
        .isHwCompareGreaterEnabled = false,
        .isHwCompareRangeEnabled= false,
        .hwCompareValue1        = 0,
        .hwCompareValue2        = 0,
        .isHwAverageEnabled     = true,
        .hwAverageSampleMode    = kAdcHwAverageCount32,
        .isDmaEnabled           = false
    };

    /* Low Power Configuration */
    smc_power_mode_config_t smcConfig;
    smc_power_mode_protection_config_t smcProtConfig;

    /* set to allow entering specific modes*/
    smcProtConfig.vlpProt = true;
    smc_hal_config_power_mode_protection(&smcProtConfig);

    /* set power mode to specific Run mode*/
    smcConfig.lpwuiOption = false;
    smcConfig.porOption = false;
    smcConfig.powerModeName = kPowerModeVlps;

    /* configure the SIM to select trigger source */
    BW_SIM_SOPT7_ADC1TRGSEL(0xE);
    BW_SIM_SOPT7_ADC1ALTTRGEN(0x1);

    /* Initialize ADC */
    adc_init(1, &tempSnseAdcConfig);

    /* Initialize ADC Extended */
    adc_init_extend(ADC_1, &adcExtConfig);

    /* registe a user-defined ADC isr*/
    adc_register_user_callback_isr(ADC_1, ADC1IRQHandler);

    InitLowPowerTmr();

    /* ADC starts conversion */
    adc_start_conversion(ADC_1, &tempSnseChannelConfig);

    /* Warm up microcontroller and allow to set first boundaries*/
    while(updateBoundariesCounter < (UPDATE_BOUNDARIES_TIME * 2))
    {
        while(!conversionCompleted)
        {}
        currentTemperature = GetCurrentTempValue();
        tempArray[updateBoundariesCounter] = currentTemperature;
        updateBoundariesCounter++;
        conversionCompleted = false;
    }

    /* Temp Sensor Calibration */
    boundaries = TempSensorCalibration(updateBoundariesCounter, tempArray);
    updateBoundariesCounter = 0;

    /* Green LED is turned on indicating calibration is done */
    gpio_write_pin_output(kGpioLED1, LED_ON);

    for(;;)
    {
        /* Prevents the use of wrong values */
        while(!conversionCompleted)
        {}

        /* Get current Temperature Value */
        currentTemperature = GetCurrentTempValue();

        /* Store temperature values that are going to be use to calculate average temperature */
        tempArray[updateBoundariesCounter] = currentTemperature;

        /* Show how fast is each cycle */
        gpio_toggle_pin_output(kGpioLED1);

        /* Select which LED is going to be turned on and off */
        if(currentTemperature > boundaries.upperBoundary)
        {
            gpio_write_pin_output(kGpioLED2, LED_ON);
            gpio_write_pin_output(kGpioLED3, LED_OFF);
        }
        else if(currentTemperature < boundaries.lowerBoundary)
        {
            gpio_write_pin_output(kGpioLED2, LED_OFF);
            gpio_write_pin_output(kGpioLED3, LED_ON);
        }
        else
        {
            gpio_write_pin_output(kGpioLED2, LED_OFF);
            gpio_write_pin_output(kGpioLED3, LED_OFF);
        }
        /* Call update function */
        if(updateBoundariesCounter >= (UPDATE_BOUNDARIES_TIME))
        {
            boundaries = TempSensorCalibration(updateBoundariesCounter, tempArray);
            updateBoundariesCounter = 0;
        }
        else
        {
            updateBoundariesCounter++;
        }

        /* Clear conversionCompleted flag */
        conversionCompleted = false;

        /* Entry to Low Power Mode */
        smc_set_power_mode(&smcConfig);
    }
}
/* END OF CODE */
