/*
 * 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 "netif/xadapter.h"

#include "platform.h"
#include "platform_config.h"
#if defined (__arm__) || defined(__aarch64__)
#include "xil_printf.h"
#endif

#include "lwip/tcp.h"
#include "xil_cache.h"

#include "sii9022_init_table.h"
#include "ov5640_init_table.h"
#include <xiicps.h>
#include "xaxivdma.h"
#include "xvtc.h"
#include "xil_cache.h"
#include "sleep.h"
#include "xaxivdma_hw.h"
#include "xil_io.h"

#if LWIP_IPV6==1
#include "lwip/ip.h"
#else
#if LWIP_DHCP==1
#include "lwip/dhcp.h"
#endif
#endif

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

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

#if LWIP_IPV6==0
#if LWIP_DHCP==1
extern volatile int dhcp_timoutcntr;
err_t dhcp_start(struct netif *netif);
#endif
#endif

extern volatile int TcpFastTmrFlag;
extern volatile int TcpSlowTmrFlag;
static struct netif server_netif;
struct netif *echo_netif;


int run_triple_frame_buffer(XAxiVdma* InstancePtr, int DeviceId, int hsize,
                int vsize, int buf_base_addr, int number_frame_count,
                int enable_frm_cnt_intr);

unsigned int srcBuffer = (XPAR_PS7_DDR_0_S_AXI_BASEADDR + 0x1000000);


#define IIC_SCLK_RATE		100000

XIicPs I2C0;		/* The instance of the IIC device. */
XIicPs I2C1;		/* The instance of the IIC device. */

u8 WriteBuffer[10];

struct tcp_pcb *serpcb;
extern volatile uint8_t recv_flag;
int image_num = 1280*720*2;       //һͼĴС
u32 uiIdx = 0;

XAxiVdma Vdma_Inst;

#if LWIP_IPV6==1
void print_ip6(char *msg, ip_addr_t *ip)
{
	print(msg);
	xil_printf(" %x:%x:%x:%x:%x:%x:%x:%x\n\r",
			IP6_ADDR_BLOCK1(&ip->u_addr.ip6),
			IP6_ADDR_BLOCK2(&ip->u_addr.ip6),
			IP6_ADDR_BLOCK3(&ip->u_addr.ip6),
			IP6_ADDR_BLOCK4(&ip->u_addr.ip6),
			IP6_ADDR_BLOCK5(&ip->u_addr.ip6),
			IP6_ADDR_BLOCK6(&ip->u_addr.ip6),
			IP6_ADDR_BLOCK7(&ip->u_addr.ip6),
			IP6_ADDR_BLOCK8(&ip->u_addr.ip6));

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

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);
}
#endif

#if defined (__arm__) && !defined (ARMR5)
#if XPAR_GIGE_PCS_PMA_SGMII_CORE_PRESENT == 1 || XPAR_GIGE_PCS_PMA_1000BASEX_CORE_PRESENT == 1
int ProgramSi5324(void);
int ProgramSfpPhy(void);
#endif
#endif

#ifdef XPS_BOARD_ZCU102
#ifdef XPAR_XIICPS_0_DEVICE_ID
int IicPhyReset(void);
#endif
#endif

int sii9022_init(void)
{

	s32 Status;
	XIicPs_Config *ConfigPtr;	/* Pointer to configuration data */
	u8 Index;

	//ʼI2C
	ConfigPtr = XIicPs_LookupConfig(XPAR_PS7_I2C_0_DEVICE_ID);
	if (ConfigPtr == NULL) {
		return XST_FAILURE;
	}

	Status = XIicPs_CfgInitialize(&I2C0, ConfigPtr,
					ConfigPtr->BaseAddress);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

	//ʱƵ
	XIicPs_SetSClk(&I2C0, IIC_SCLK_RATE);

	/****************üĴ****************/
	for (Index = 0; Index < 42; Index++) {
		WriteBuffer[0] = sii9022_table[0 + Index*2];
		WriteBuffer[1] = sii9022_table[1 + Index*2];

		Status = XIicPs_MasterSendPolled(&I2C0, WriteBuffer, 2, 0x39);
		if (Status != XST_SUCCESS) {
			return XST_FAILURE;
		}

		/*
		 * Wait until bus is idle to start another transfer.
		 */
		while (XIicPs_BusIsBusy(&I2C0));
	}
	return XST_SUCCESS;
}

int ov5640_init(void)
{

	s32 Status;
	XIicPs_Config *ConfigPtr1;	/* Pointer to configuration data */
	u8 Index;

	//ʼI2C
	ConfigPtr1 = XIicPs_LookupConfig(XPAR_PS7_I2C_1_DEVICE_ID);
	if (ConfigPtr1 == NULL) {
		return XST_FAILURE;
	}

	Status = XIicPs_CfgInitialize(&I2C1, ConfigPtr1,
			ConfigPtr1->BaseAddress);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

	//ʱƵ
	XIicPs_SetSClk(&I2C1, IIC_SCLK_RATE);

	/****************üĴ****************/
	for (Index = 0; Index < 252; Index++) {
		WriteBuffer[0] = ov5640_table[0 + Index*3];
		WriteBuffer[1] = ov5640_table[1 + Index*3];
		WriteBuffer[2] = ov5640_table[2 + Index*3];

		Status = XIicPs_MasterSendPolled(&I2C1, WriteBuffer, 3, 0x3C);
		if (Status != XST_SUCCESS) {
			return XST_FAILURE;
		}

		/*
		 * Wait until bus is idle to start another transfer.
		 */
		while (XIicPs_BusIsBusy(&I2C1));
		if(Index<3)
		{
			usleep(10000);
		}
	}
	return XST_SUCCESS;
}


void Vtc_Init(XVtc *Vtc_Inst)
{
        XVtc_Config *vtcConfig;
        vtcConfig = XVtc_LookupConfig(XPAR_VTC_0_DEVICE_ID);
        XVtc_CfgInitialize(Vtc_Inst, vtcConfig, vtcConfig->BaseAddress);
}

int main()
{
    XVtc Vtc_Inst;
    int Status;

    //ʼSII9022A
	sii9022_init();
	ov5640_init();
	Xil_DCacheFlush();
	Status = run_triple_frame_buffer(&Vdma_Inst, 0, 1280, 720,srcBuffer, 100, 0);
	if (Status != XST_SUCCESS) {
		return XST_FAILURE;
	}

    Vtc_Init(&Vtc_Inst);

    XVtc_EnableGenerator(&Vtc_Inst);

#if LWIP_IPV6==0
	ip_addr_t ipaddr, netmask, gw;

#endif
	/* the mac address of the board. this should be unique per board */
	unsigned char mac_ethernet_address[] =
	{ 0x00, 0x0a, 0x35, 0x01, 0xfe, 0xc0 };

	echo_netif = &server_netif;
#if defined (__arm__) && !defined (ARMR5)
#if XPAR_GIGE_PCS_PMA_SGMII_CORE_PRESENT == 1 || XPAR_GIGE_PCS_PMA_1000BASEX_CORE_PRESENT == 1
	ProgramSi5324();
	ProgramSfpPhy();
#endif
#endif

/* Define this board specific macro in order perform PHY reset on ZCU102 */
#ifdef XPS_BOARD_ZCU102
	if(IicPhyReset()) {
		xil_printf("Error performing PHY reset \n\r");
		return -1;
	}
#endif

	init_platform();

#if LWIP_IPV6==0
#if LWIP_DHCP==1
    ipaddr.addr = 0;
	gw.addr = 0;
	netmask.addr = 0;
#else
	/* initialize IP addresses to be used */
	IP4_ADDR(&ipaddr,  192, 168,   0,  2);
	IP4_ADDR(&netmask, 255, 255, 255,  0);
	IP4_ADDR(&gw,      192, 168,   0,  1);
#endif
#endif
	print_app_header();

	lwip_init();

#if (LWIP_IPV6 == 0)
	/* Add network interface to the netif_list, and set it as default */
	if (!xemac_add(echo_netif, &ipaddr, &netmask,
						&gw, mac_ethernet_address,
						PLATFORM_EMAC_BASEADDR)) {
		xil_printf("Error adding N/W interface\n\r");
		return -1;
	}
#else
	/* Add network interface to the netif_list, and set it as default */
	if (!xemac_add(echo_netif, NULL, NULL, NULL, mac_ethernet_address,
						PLATFORM_EMAC_BASEADDR)) {
		xil_printf("Error adding N/W interface\n\r");
		return -1;
	}
	echo_netif->ip6_autoconfig_enabled = 1;

	netif_create_ip6_linklocal_address(echo_netif, 1);
	netif_ip6_addr_set_state(echo_netif, 0, IP6_ADDR_VALID);

	print_ip6("\n\rBoard IPv6 address ", &echo_netif->ip6_addr[0].u_addr.ip6);

#endif
	netif_set_default(echo_netif);

	/* now enable interrupts */
	platform_enable_interrupts();

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

#if (LWIP_IPV6 == 0)
#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(echo_netif);
	dhcp_timoutcntr = 24;

	while(((echo_netif->ip_addr.addr) == 0) && (dhcp_timoutcntr > 0))
		xemacif_input(echo_netif);

	if (dhcp_timoutcntr <= 0) {
		if ((echo_netif->ip_addr.addr) == 0) {
			xil_printf("DHCP Timeout\r\n");
			xil_printf("Configuring default IP of 192.168.1.10\r\n");
			IP4_ADDR(&(echo_netif->ip_addr),  192, 168,   1, 10);
			IP4_ADDR(&(echo_netif->netmask), 255, 255, 255,  0);
			IP4_ADDR(&(echo_netif->gw),      192, 168,   1,  1);
		}
	}

	ipaddr.addr = echo_netif->ip_addr.addr;
	gw.addr = echo_netif->gw.addr;
	netmask.addr = echo_netif->netmask.addr;
#endif

	print_ip_settings(&ipaddr, &netmask, &gw);

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

	/* receive and process packets */
	while (1) {
		if (TcpFastTmrFlag) {
			tcp_fasttmr();
			TcpFastTmrFlag = 0;
		}
		if (TcpSlowTmrFlag) {
			tcp_slowtmr();
			TcpSlowTmrFlag = 0;
		}


		Set_Display_Frame();

		xemacif_input(echo_netif);
		transfer_data();
	}

	/* never reached */
	cleanup_platform();

	return 0;
}


void Set_Display_Frame(void)
{
	u32 buff;

	buff = tcp_sndbuf(serpcb);
	if(recv_flag) {
		if(buff > image_num){
			Xil_DCacheFlushRange(srcBuffer + uiIdx,send_data);
			tcp_write(serpcb,(void*)(srcBuffer + uiIdx),image_num,1);
			tcp_output(serpcb);
			recv_flag = 0;
			uiIdx = 0;
			image_num = 1280*720*2;
			pbuf_free(serpcb->refused_data);
//			Xil_DCacheFlushRange(srcBuffer,1280*720*2);
		}
		else{
			Xil_DCacheFlushRange(srcBuffer + uiIdx,buff);
			tcp_write(serpcb,(void*)(srcBuffer + uiIdx),buff,1);
			tcp_output(serpcb);
			image_num = image_num - buff;
			uiIdx += buff;
			pbuf_free(serpcb->refused_data);
		}
	}

}
