#include <string.h>
#include "../util/myprintf.h"
#include "../mcu/types.h"
#include "../mcu/timer.h"
#include "../mcu/delay.h"
#include "../mcu/serial.h"
#include "../iinchip/socket.h"
#include "../evb/lcd.h"
#include "../evb/led.h"
#include "../evb/evb.h"
#include "../evb/manage.h"
#include "../evb/channel.h"
#include "../evb/config.h"
#include "../inet/dhcp.h"
#include "../app/webserver.h"
#include "../app/loopback.h"
#include "../app/ping_app.h"
#include "main.h"

int main(void)
{
	SOCKET i;
	evb_init();
	check_manage();
	init_timer();

	for (i = 0; i < MAX_SOCK_NUM; i++)
	{
		switch(ChConf.ch[i].type)
		{
		case NOTUSE: unregister_channel_handler(i);
			break;

		case DHCP_CLIENT: printf("%d : DHCP Client Start.\r\n",i);
			evb_set_lcd_text(0,"< DHCP  CLIENT >");
			evb_set_lcd_text(1," Wait a minute ");
			get_netconf(&NetConf);
			memcpy(SRC_MAC_ADDR,NetConf.mac,6);
			init_dhcp_client(i, evb_soft_reset,evb_soft_reset);
			if(!getIP_DHCPS())
			{
				evb_set_lcd_text(1," Fail to get IP ");
				printf("Fail to get a IP adress from DHCP server\r\n");
				printf("Apply the default network information!!!\r\n");
				ChConf.ch[i].type =  NOTUSE;	// Disable DHCPC;
				unregister_channel_handler(i);
				wait_10ms(100);
			}
			else
			{
				memcpy((u_char*)&NetConf.sip, GET_SIP, 4);
				memcpy((u_char*)&NetConf.gwip, GET_GW_IP, 4);
				memcpy((u_char*)&NetConf.sn, GET_SN_MASK, 4);
				memcpy((u_char*)&NetConf.dns, GET_DNS_IP, 4);
				printf("Get network information from DHCP Server...\r\n");	
				register_channel_handler(i,check_DHCP_state);
			}
			set_netconf(&NetConf);
			break;
		case LB_TCPS:
			register_channel_handler(i,loopback_tcps);
			break;
		case LB_TCPC:
			register_channel_handler(i,loopback_tcpc);
			break;
		case LB_UDP:
			register_channel_handler(i,loopback_udp);
			break;
		case WEB_SERVER:
			register_channel_handler(i,web_server);
			break;
		}
	}
	
	net_init();
	evb_logo();
	
	while (1)
	{
		for (i = 0 ; i < MAX_SOCK_NUM ; i++ )
			if(ChannelHandler[i].Handler) (*ChannelHandler[i].Handler)(i);
	}		
}
