/*
 * Copyright (C) 2009 - 2019 Xilinx, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
 * SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
 * OF SUCH DAMAGE.
 *
 */

#include <stdio.h>
#include "xparameters.h"
#include "platform_config.h"
#if defined (__arm__) || defined(__aarch64__)
#include "xil_printf.h"
#endif
#include "netif/xadapter.h"
#include "lwipopts.h"
#include "sleep.h"
#include "lwip/priv/tcp_priv.h"
#include "lwip/init.h"
#include "lwip/inet.h"
#include "xil_cache.h"
extern void tcp_tmr(void);  /* declared in tcp_priv.h, not in public tcp.h */
#include "xil_cache.h"

#if LWIP_DHCP==1
#include "lwip/dhcp.h"
extern volatile int dhcp_timoutcntr;
#endif

#include "GPIO_Driv.h"
#include "SPI_Driv.h"
#include "cal_meas.h"
#include "uart_IO.h"
#include "CPLD_Con.h"
#include "lwip_server.h"

#define MAJORV 0
#define MINORV 1
#define FIXV 3

#define DEFAULT_IP_ADDRESS	"192.168.100.110"
#define DEFAULT_IP_MASK		"255.255.255.0"
#define DEFAULT_GW_ADDRESS	"192.168.100.1"

u8 recvbuffer[1024] = {0};

extern volatile int TcpFastTmrFlag;
extern volatile int TcpSlowTmrFlag;

/* defined by each RAW mode application */
void print_app_header();
int start_application();
int transfer_data();

/* missing declaration in lwIP */
void lwip_init();

struct netif server_netif;
struct netif *netif;

static void print_ip(char *msg, ip_addr_t *ip)
{
	print(msg);
	xil_printf("%d.%d.%d.%d\r\n", ip4_addr1(ip), ip4_addr2(ip),
			ip4_addr3(ip), ip4_addr4(ip));
}

static void print_ip_settings(ip_addr_t *ip, ip_addr_t *mask, ip_addr_t *gw)
{
	print_ip("Board IP:       ", ip);
	print_ip("Netmask :       ", mask);
	print_ip("Gateway :       ", gw);
}

static void assign_default_ip(ip_addr_t *ip, ip_addr_t *mask, ip_addr_t *gw)
{
	int err;

	xil_printf("Configuring default IP %s \r\n", DEFAULT_IP_ADDRESS);

	err = inet_aton(DEFAULT_IP_ADDRESS, ip);
	if (!err)
		xil_printf("Invalid default IP address: %d\r\n", err);

	err = inet_aton(DEFAULT_IP_MASK, mask);
	if (!err)
		xil_printf("Invalid default IP MASK: %d\r\n", err);

	err = inet_aton(DEFAULT_GW_ADDRESS, gw);
	if (!err)
		xil_printf("Invalid default gateway address: %d\r\n", err);
}

static int net_is_available(void)
{
	if (netif == NULL)
		return 0;
	if (!netif_is_up(netif))
		return 0;
	if (netif->ip_addr.addr == 0)
		return 0;
	return 1;
}

int main()
{
	int iMainCom = 1;
	int iStatus = -255;
	ip_addr_t ipaddr, netmask, gw;
	unsigned char mac_ethernet_address[] = { 0x00, 0x0a, 0x35, 0x00, 0x01, 0x01 };

	netif = &server_netif;

	init_platform();

//LWIP Related Init Start
	lwip_init();

	/* Add network interface to the netif_list, and set it as default */
	if (!xemac_add(netif, NULL, NULL, NULL, mac_ethernet_address,
				PLATFORM_EMAC_BASEADDR)) {
		xil_printf("Error adding N/W interface\r\n");
		return -1;
	}
	netif_set_default(netif);

#ifndef SDT
	/* now enable interrupts */
	platform_enable_interrupts();
#endif

	/* specify that the network if is up */
	netif_set_up(netif);

#if (LWIP_DHCP==1)
	/* Create a new DHCP client for this interface.
	 * Note: you must call dhcp_fine_tmr() and dhcp_coarse_tmr() at
	 * the predefined regular intervals after starting the client.
	 */
	dhcp_start(netif);
	dhcp_timoutcntr = 3;
	while (((netif->ip_addr.addr) == 0) && (dhcp_timoutcntr > 0))
		xemacif_input(netif);

	if (dhcp_timoutcntr <= 0) {
		if ((netif->ip_addr.addr) == 0) {
			xil_printf("ERROR: DHCP request timed out\r\n");
			assign_default_ip(&(netif->ip_addr),
					&(netif->netmask), &(netif->gw));
		}
	}

	/* print IP address, netmask and gateway */
#else
	assign_default_ip(&(netif->ip_addr), &(netif->netmask), &(netif->gw));
#endif
	print_ip_settings(&(netif->ip_addr), &(netif->netmask), &(netif->gw));

	xil_printf("\r\n");

	/* start the application (web server, rxtest, txtest, etc..) */
	start_application();

//LWIP Related Init END

	/* Check if network is actually available, fallback to UART if not */
	if (!net_is_available()) {
		xil_printf("[W] Network unavailable, falling back to UART\r\n");
		iMainCom = 0;
	}

	xil_printf("\r\n=====================[I] System Init Done!=====================\r\n");
	xil_printf("\r\n[I] Zynq Version:NewInstCal v%d.%d.%d\r\n\r\n",MAJORV,MINORV,FIXV);
	
	xil_printf("[D] Start EMIO Config\r\n");
	EMIO_config();
	xil_printf("[D] End of EMIO Config\r\n");

	xil_printf("[D] Start CPLD Reset\r\n");
	rst_CPLD(CPLD_U1,4);
	rst_CPLD(CPLD_U2,4);
	rst_CPLD(CPLD_U3,4);
	xil_printf("[D] End of CPLD Reset\r\n");

	xil_printf("[D] Config CPLD SPI to known state\r\n");
	interface_initial(CPLD_U1);
	interface_initial(CPLD_U2);
	interface_initial(CPLD_U3);

	iStatus = CPLD_Checkin();
	if (iStatus != XST_SUCCESS)
	{
		xil_printf("[E] main() stopped!\r\n");
		return XST_FAILURE;
	}
	else
	{
		xil_printf("[I] All 3/3 CPLD Checked In!\r\n");
	}


	xil_printf("\r\n=====================[I] Board Init Complete!=====================\r\n[I] Waiting for Command...\r\n");

	/* receive and process Instructions */
	if (iMainCom == 1)
	{
		print_app_header();
		while (1) {
			if (TcpFastTmrFlag) {
				tcp_fasttmr();
				TcpFastTmrFlag = 0;
			}
			if (TcpSlowTmrFlag) {
				tcp_slowtmr();
				TcpSlowTmrFlag = 0;
			}
			xemacif_input(netif);
		}
	}
	else
	{
		while (1) 
		{
			int Status = -255;
			Status = UART_RecvInstr(recvbuffer);
			if (Status < 0)
			{
				xil_printf("[E] UART Receive ERROR!!! Check PrintOut Ahead\r\n");
			}
			else if (Status > 0)
			{
				Command_Parser(recvbuffer,Status);		//Here Status should equal to length
			}
			
		}
	}

	/* never reached */
	cleanup_platform();

	return 0;
}
