/*
 *  Copyright (C) 2015 Texas Instruments Incorporated - http://www.ti.com/ 
 *  
 *  Redistribution and use in source and binary forms, with or without 
 *  modification, are permitted provided that the following conditions 
 *  are met:
 *
 *    Redistributions of source code must retain the above copyright 
 *    notice, this list of conditions and the following disclaimer.
 *
 *    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.
 *
 *    Neither the name of Texas Instruments Incorporated 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 
 *  OWNER 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.
 *  
 */
 
/*
 *  ======== PowerCC3200_tirtos_policy.c ========
 */

#include <stdint.h>

/* driverlib header files */
#include <inc/hw_types.h>
#include <driverlib/prcm.h>
#include <driverlib/cpu.h>
#include <driverlib/rom.h>
#include <driverlib/rom_map.h>

#include <ti/drivers/Power.h>
#include <ti/drivers/power/PowerCC3200.h>
#include <ti/drivers/ports/ClockP.h>
#include "FreeRTOS.h"
#include "task.h"
#include "oslib/osi.h"

/* bitmask of constraints that disallow LPDS */
#define LPDS_DISALLOWED (1 << PowerCC3200_DISALLOW_LPDS)

/* macro to pick two matching count values */
#define COUNT_WITHIN_TRESHOLD(a, b, c, th) \
        ((((b) - (a)) <= (th)) ? (b) : (c))

#define TRUE    1
#define FALSE   0

extern void prvStartTickInterruptTimer();
extern void prvStopTickInterruptTimer();

static volatile uint32_t IdleTime = 0;

void PowerCC3200_sleepPolicy()
{
    unsigned long ulKey;
    int i = 0;
    bool returnFromSleep = FALSE;
    unsigned long constraintMask;
    unsigned long long ullLowPowerTimeBeforeSleep, ullLowPowerTimeAfterSleep;
    unsigned long long count[3];
    unsigned long long ullSleepTime;
    unsigned long long time;
    unsigned long long remain;
    eSleepModeStatus eSleepStatus;

    /* query the declared constraints */
    constraintMask = Power_getConstraintMask();

    /* check if we are allowed to go to LPDS */
	if ((constraintMask & LPDS_DISALLOWED) == 0)
	{
	    /* Enter a critical section that will not effect interrupts bringing the MCU
	     out of sleep mode. */
	    ulKey = osi_EnterCritical();

		/* Read the current time from a time source that will remain operational
		while the microcontroller is in a low power state. */
	    /*
	     *  get the current RTC count, using the fast interface; to use the
	     *  fast interface the count must be read three times, and then
	     *  the value that matches on at least two of the reads is chosen
	     */
	    for (i = 0; i < 3; i++) {
	        count[i] = PRCMSlowClkCtrFastGet();
	    }
	    ullLowPowerTimeBeforeSleep = COUNT_WITHIN_TRESHOLD(count[0], count[1], count[2], 1);

		/* Stop the timer that is generating the tick interrupt. */
		prvStopTickInterruptTimer();

	    /* Ensure it is still ok to enter the sleep mode. */
	    eSleepStatus = eTaskConfirmSleepModeStatus();

	    if( eSleepStatus == eAbortSleep )
	    {
	        /* A task has been moved out of the Blocked state since this macro was
	        executed, or a context siwth is being held pending.  Do not enter a
	        sleep state.  Restart the tick and exit the critical section. */
	        prvStartTickInterruptTimer();
	        osi_ExitCritical(ulKey);
	        returnFromSleep = FALSE;
	    }
	    else
	    {
	    	/* convert ticks to microseconds */
	    	time = IdleTime * ClockP_getSystemTickPeriod();

	    	/* check if can go to LPDS */
			if (time > Power_getTransitionLatency(PowerCC3200_LPDS, Power_TOTAL)) {
				remain = ((time - PowerCC3200_TOTALTIMELPDS) * 32768) / 1000000;

				/* set the LPDS wakeup time interval */
				MAP_PRCMLPDSIntervalSet(remain);

				/* enable the wake source to be timer */
				MAP_PRCMLPDSWakeupSourceEnable(PRCM_LPDS_TIMER);

				/* go to LPDS mode */
				Power_sleep(PowerCC3200_LPDS);

				/* set 'returnFromSleep' to TRUE*/
				returnFromSleep = TRUE;
			}
			else
			{
				prvStartTickInterruptTimer();
				osi_ExitCritical(ulKey);
				returnFromSleep = FALSE;
			}

	    }
	}

	if(returnFromSleep){
		/* Determine how long the microcontroller was actually in a low power
		state for, which will be less than xExpectedIdleTime if the
		microcontroller was brought out of low power mode by an interrupt
		other than that configured by the vSetWakeTimeInterrupt() call.
		Note that the scheduler is suspended before
		portSUPPRESS_TICKS_AND_SLEEP() is called, and resumed when
		portSUPPRESS_TICKS_AND_SLEEP() returns.  Therefore no other tasks will
		execute until this function completes. */
	    for (i = 0; i < 3; i++) {
	        count[i] = PRCMSlowClkCtrFastGet();
	    }
		ullLowPowerTimeAfterSleep = COUNT_WITHIN_TRESHOLD(count[0], count[1], count[2], 1);

		ullSleepTime = ullLowPowerTimeAfterSleep - ullLowPowerTimeBeforeSleep;

		ullSleepTime = ullSleepTime*1000;
		ullSleepTime = ullSleepTime/32768;

		/* Correct the kernels tick count to account for the time the
		microcontroller spent in its low power state. */
		vTaskStepTick((unsigned long)ullSleepTime);

		/* Restart the timer that is generating the tick interrupt. */
		prvStartTickInterruptTimer();
		/* Exit the critical section - it might be possible to do this immediately
		after the prvSleep() calls. */
		osi_ExitCritical(ulKey);
    }else{
    	MAP_PRCMSleepEnter();
    }

}

/* Tickless Hook */
void vApplicationTicklessIdleHook(TickType_t xExpectedIdleTime)
{
    IdleTime = xExpectedIdleTime;
    Power_idleFunc();
}

/*
 *  ======== PowerCC3200_initPolicy ========
 */
void PowerCC3200_initPolicy()
{
}
