#include <string.h>
#include "../mcu/serial.h"
#include "../mcu/pmp.h"
#include "../mcu/delay.h"
#include "../iinchip/socket.h"
#include "../iinchip/w5100.h"
#include "../util/util.h"
#include "../util/sockutil.h"
#include "../util/myprintf.h"
#include "../evb/lcd.h"
#include "../evb/led.h"
#include "../evb/config.h"
#include "../evb/seep.h"

#include "evb.h"

char evb_lcd_text[LCD_MAX_ROW][LCD_MAX_COL+1];

void evb_init(void)
{
	u_int i;
	mcu_init();
	InitPMP();
	uart_init();		// Serial Port Initialize
	led_init();
	wait_1ms(200);		// for LCD module reset time
	lcd_init();
	for(i = 0; i < LCD_MAX_ROW;i++) memset(evb_lcd_text[i],' ',LCD_MAX_COL+1);
	InitSEEP();
	init_conf_variables();	
}

void evb_soft_reset(void)
{
	printf("System Reset.\r\n");
	set_reset_flag(SYSTEM_AUTO_RESET);
	asm volatile("	RESET");
}

void evb_logo(void)
{
	printf("\r\n###########################################\r\n");
	printf("EVB-PIC24 - Test in ");
#if (__DEF_IINCHIP_BUS__ == __DEF_IINCHIP_DIRECT_MODE__)
	printf("Direct Mode\r\n");
#else
	printf("Indirect Mode\r\n");
#endif
	printf("###########################################\r\n");
	printf("Copyright : WIZnet, Inc. 2005 ~ 2006\r\n");
	printf("Homepage  : http://www.wiznet.co.kr\r\n");
	printf("Support   : support@wiznet.co.kr\r\n");
	printf("Sales     : sales@wiznet.co.kr\r\n");
	printf("-------------------------------------------\r\n");
	printf("F/W Version   : %d.%d.%d.%d\r\n",(u_char)(SysInfo.ver>>24),(u_char)(SysInfo.ver>>16),
					(u_char)(SysInfo.ver>>8),(u_char)(SysInfo.ver));
	printf("H/W Version   : TB-PIC24\r\n");

	display_netconf(&NetConf);
	printf("###########################################\r\n\r\n");
	evb_lcd_logo();
}

void evb_lcd_logo(void)
{
	char logo[17];
	lcd_clrscr();
	lcd_gotoxy(0,0);
	sprintf(logo, "<EVB-PIC24 V%d.%d>",(u_char)(SysInfo.ver>>24),(u_char)(SysInfo.ver>>16));
	evb_set_lcd_text(0,logo);
	evb_set_lcd_text(1,inet_ntoa_pad(ntohl(NetConf.sip)));
}

char* evb_get_lcd_text(u_char row)
{
	if(row < LCD_MAX_ROW)
		return evb_lcd_text[row];
	return 0;
	
}
void evb_set_lcd_text(u_char row, char* lcd)
{
	if(row < LCD_MAX_ROW && strlen(lcd) <= LCD_MAX_COL)
	{
		memset(evb_lcd_text[row],' ',LCD_MAX_COL);
		evb_lcd_text[row][LCD_MAX_COL] = 0;
		memcpy(evb_lcd_text[row],lcd,strlen(lcd));
		lcd_gotoxy(0,row);
		lcd_puts(evb_lcd_text[row]);
	}
}

void mcu_init(void) 
{
	int old_ipl;

	SET_AND_SAVE_CPU_IPL(old_ipl, 7);

#ifndef __DEF_IINCHIP_INT__	
#else
	INTCON2bits.INT0EP = 1;	// EXT. int. 0 negative edge
	IPC0bits.INT0IP = 4;	// priority 4
	IFS0bits.INT0IF = 0;	// clear flag
	IEC0bits.INT0IE = 1;	// EXT. int. 0 enable
#endif

	RESTORE_CPU_IPL(old_ipl);
}

void net_init(void)
{
	iinchip_init();
	get_netconf(&NetConf);
	setSIPR((u_char*)&NetConf.sip);
	setGAR((u_char*)&NetConf.gwip);
	setSUBR((u_char*)&NetConf.sn);
	setSHAR(NetConf.mac);
#ifdef __DEF_IINCHIP_INT__
	setIMR(0xEF);
#endif	
	sysinit(NetConf.Mem_alloc,NetConf.Mem_alloc);
}
