/*
 * my_timer.c
 *
 *  Created on: gg/mmm/ccaa
 *      Author: cognome.nome
 */

//==============================================================================
// Include files

#include "string.h"
#include "stdbool.h"
#include "stdint.h"

#include "utils/lwiplib.h"

#include "driverlib/interrupt.h"
#include "driverlib/rom.h"
#include "driverlib/rom_map.h"
#include "driverlib/sysctl.h"
#include "driverlib/systick.h"
#include "driverlib/pin_map.h"
#include "driverlib/gpio.h"

#include "drivers/my_timer.h"
#include "main.h"

//==============================================================================
// Constants

#define SYSTICKHZ               100
//#define SYSTICKHZ               1562
#define SYSTICKMS               (1000 / SYSTICKHZ)

//==============================================================================
// Types

//==============================================================================
// Static global variables

static volatile unsigned long long counter_ms = 0;
static volatile double counter_s = 0;
extern uint32_t g_ui32SysTickCount;

//==============================================================================
// Static functions

//==============================================================================
// Global variables

//==============================================================================
// Global functions

// The interrupt handler for the SysTick interrupt.
void SysTickIntHandler(void)
{
	lwIPTimer(SYSTICKMS);
	g_ui32SysTickCount++;

	counter_ms++;
	//counter_s = counter_ms/1000.0;
	// Call the lwIP timer handler.
	//if((counter_ms%10) == 0)
	//{
	//	lwIPTimer(SYSTICKMS);
	//}
}

long ResetTimerMs(unsigned long long *tm)
{
	if(tm == NULL)
	{
		return -1;
	}
	(*tm) = counter_ms;

	return 0;
}

unsigned long GetTimerMs(unsigned long long tm)
{
	return((unsigned long)(counter_ms - tm));
}

long ResetTimerS(double *tm)
{
	if(tm == NULL)
	{
		return -1;
	}
	(*tm) = counter_s;

	return 0;
}

double GetTimerS(double tm)
{
	return((unsigned long)(counter_s - tm));
}

long WaitMs(unsigned long msec)
{
	unsigned long long tm;
	unsigned long time;

	ResetTimerMs(&tm);
	do
	{
		time = GetTimerMs(tm);
	}while(time < msec);

	return 0;
}

long MyTimerInit(void)
{
    // Configure SysTick for a periodic interrupt.
    ROM_SysTickPeriodSet(g_ui32SysClock / SYSTICKHZ); // 1562 millisecondi
    ROM_SysTickEnable();
    ROM_SysTickIntEnable();
    return 0;
}
