#include <asf.h>
#include "conf_aon_sleep_timer.h"

// Callback Func to enable LED
static void aon_sleep_timer_callback(void)
{
	gpio_pin_set_output_level(LED_0_PIN, LED_0_ACTIVE);
}

static void configure_gpio_pins(void)
{
	struct gpio_config config_gpio_pin;
	gpio_get_config_defaults(&config_gpio_pin);
	config_gpio_pin.direction = GPIO_PIN_DIR_OUTPUT;
	gpio_pin_set_config(LED_0_PIN, &config_gpio_pin);
	gpio_pin_set_output_level(LED_0_PIN, LED_0_INACTIVE);
}
// Configure Timer with 10sec to overflow
static void configure_aon_sleep_timer(void)
{
	struct aon_sleep_timer_config config_aon_sleep_timer;
	aon_sleep_timer_get_config_defaults(&config_aon_sleep_timer);
	config_aon_sleep_timer.counter = 320000; // Wait about 10sec
	aon_sleep_timer_init(&config_aon_sleep_timer);
}
// Configure Callback and enable Interrupt
static void configure_aon_sleep_timer_callback(void)
{
	aon_sleep_timer_register_callback(aon_sleep_timer_callback);
	NVIC_EnableIRQ(AON_SLEEP_TIMER_IRQn);
}

int main(void)
{
	// Setup Clock, LED and Timer
	system_clock_config(CLOCK_RESOURCE_XO_26_MHZ, CLOCK_FREQ_26_MHZ);
	configure_gpio_pins();
	configure_aon_sleep_timer();
	configure_aon_sleep_timer_callback();

	// wait for timer to be active
	while(!aon_sleep_timer_sleep_timer_active());
	// Go to sleep
	asm volatile ("wfi");
	asm volatile ("nop");
	// Enable LED immediately if sleep doesn't work
	gpio_pin_set_output_level(LED_0_PIN, LED_0_ACTIVE);
	while (true) {}
}
