/*
 * main.c
 *
 *  Created on: 1.10.2013
 *      Author: Stefan
 */

#include <system.h>
#include <stdlib.h>

#include "netconf.h"
#include "eth_opts.h"
#include "tcpip.h"

#include "httpd.h"

#include "leds.h"
#include "supply.h"
#include "sensors.h"


void startup_delay_with_anim(
	void
)
{
	uint32_t d, round, delay;
	uint16_t l_int[4], l_init[4] = {0x0000, 0x4000, 0x8000, 0xC000};
	enum {
		Led_UP,
		Led_DOWN
	}l_mode[4];

	l_int[0] = 0x0000;
	l_int[1] = 0x0000;
	l_int[2] = 0x0000;
	l_int[3] = 0x0000;

	l_mode[0] = Led_UP;
	l_mode[1] = Led_UP;
	l_mode[2] = Led_UP;
	l_mode[3] = Led_UP;


	d = 4;
	do
	{
		d --;
		while(l_int[d] < l_init[d])
		{
			l_int[d] ++;
			leds_set(d, l_int[d]);
			for(delay = 0; delay < 100; delay++)
			{
			}
		}
	}while(d != 0);

	round = 0;
	while(round < 2)
	{
		for(d = 0; d < 4; d ++)
		{
			switch (l_mode[d])
			{
			case Led_UP:
				if(l_int[d] < 65535)
				{
					l_int[d] ++;

				}
				else
				{
					if(d == 0)
					{
						round ++;
					}
					l_mode[d] = Led_DOWN;
				}
				break;
			case Led_DOWN:
				if(l_int[d] > 0)
				{
					l_int[d] --;
				}
				else
				{
					l_mode[d] = Led_UP;
				}
				break;
			}

			leds_set(d, l_int[d]);

		}
		for(delay = 0; delay < 100; delay++)
		{
		}
	}

	for(d = 0; d < 4; d ++)
	{
		while(l_int[d] > 0)
		{
			l_int[d] --;
			leds_set(d, l_int[d]);
			for(delay = 0; delay < 100; delay++)
			{
			}
		}
	}
}



void StartThread(void * argument);


int main(void)
{
	TaskHandle_t usr_task;

	leds_init();
	supply_init();

	supply_charge(FALSE);


	supply_power(FALSE);
	startup_delay_with_anim();

	supply_power(TRUE);


    sensors_start();



	leds_set(LEDS_1, 65535);
	leds_set(LEDS_2, 0);
	leds_set(LEDS_3, 0);
	leds_set(LEDS_4, 0);


	xTaskCreate(StartThread,
        (const char *)"usr",
        2 * configMINIMAL_STACK_SIZE,
        0,
        0,
        &usr_task);

	/* Start scheduler */
	vTaskStartScheduler();


	while(1)
	{

	}

}



void StartThread(void * argument) {

    /* configure ethernet (GPIOs, clocks, MAC, DMA) */
	ETH_BSP_Config();

	/* Initilaize the LwIP stack */
	LwIP_Init();

	/* Initialize tcp echo server */
	httpd_start();

    for(;;)
    {
	    vTaskDelay(100);
    }
}
