/*
 * Copyright (C) 2009 - 2018 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 <string.h>
#include "lwip/err.h"
#include "lwip/tcp.h"
#include "xil_io.h"
#include "echo.h"
#include "xparameters.h"
#include "xgpio_l.h"
#include "xil_printf.h"
#include "xil_cache.h"

#include "xscugic.h"

#include "platform.h"

#include "xil_exception.h"

#define 	ADC_Data_Addr	0x01800000

#define RX_BUFFER_BASE		ADC_Data_Addr

/* Timeout loop counter for reset
 */
#define RESET_TIMEOUT_COUNTER	10000

#define TEST_START_VALUE	0xC

//XScuGic ScuGicInstance;
/*
 * Flags interrupt handlers use to notify the application context the events.
 */
extern volatile int RxDone;
extern volatile int busy;

volatile int Error;

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

void cmd_analysis(uint8_t *cmd_buffer);

u32 uiIdx = 0;
struct tcp_pcb *pcb;
extern struct tcp_pcb *serpcb;
unsigned int PLL_Reconfig;
unsigned int pll_read_data;
unsigned int

char devinfo = 0;
char Reconfig = 0;
char SD_WR = 0;

#define NUMBER_OF_TRANSFERS	1


int start_trans_data(unsigned int len)
{
	int Tries = NUMBER_OF_TRANSFERS;
	int Index;
	u8 *RxBufferPtr;
	int Status;
	RxBufferPtr = (u8 *)RX_BUFFER_BASE;

	/* Disable all interrupts before setup */

	XAxiDma_IntrDisable(&AxiDmaInstance, XAXIDMA_IRQ_ALL_MASK, XAXIDMA_DMA_TO_DEVICE);

	XAxiDma_IntrDisable(&AxiDmaInstance, XAXIDMA_IRQ_ALL_MASK, XAXIDMA_DEVICE_TO_DMA);

	XAxiDma_IntrEnable(&AxiDmaInstance, XAXIDMA_IRQ_ALL_MASK, XAXIDMA_DMA_TO_DEVICE);

	XAxiDma_IntrEnable(&AxiDmaInstance, XAXIDMA_IRQ_ALL_MASK, XAXIDMA_DEVICE_TO_DMA);

	/* Initialize flags before start transfer test  */
	RxDone = 0;
	Error = 0;

	for(Index = 0; Index < Tries; Index ++) {

		Status = XAxiDma_SimpleTransfer(&AxiDmaInstance,(UINTPTR) RxBufferPtr,
				len, XAXIDMA_DEVICE_TO_DMA);

		if (Status != XST_SUCCESS) {
			return XST_FAILURE;
		}
	}

	return XST_SUCCESS;
}

int transfer_data() {
	return 0;
}

void print_app_header()
{
#if (LWIP_IPV6==0)
	xil_printf("\n\r\n\r-----ACM9238 TCP Server ------\n\r");
#else
	xil_printf("\n\r\n\r-----lwIPv6 TCP echo server ------\n\r");
#endif
}

volatile int restart;
unsigned char ChannelSel;
unsigned int DataNum;
unsigned int Speed_Set;


err_t recv_callback(void *arg, struct tcp_pcb *tpcb,
                               struct pbuf *p, err_t err)
{
	int i;
	uiIdx = 0;
	/* do not read the packet if we are not in ESTABLISHED state */
	if (!p) {
		tcp_close(tpcb);
		tcp_recv(tpcb, NULL);
		return ERR_OK;
	}

	/* indicate that the packet has been received */
	tcp_recved(tpcb, p->len);
	unsigned char cmd_num = (p->len)/8;//ָ
	/* echo back the payload */
	/* in this case, we assume that the payload is < TCP_SND_BUF */
	if (tcp_sndbuf(tpcb) > p->len) {
		for(i=0;i<cmd_num;i++)
		{
			cmd_analysis(p->payload + 8*i);
		}

	} else
		xil_printf("no space in tcp_sndbuf\n\r");

	pbuf_free(p);

	return ERR_OK;
}


err_t accept_callback(void *arg, struct tcp_pcb *newpcb, err_t err)
{
	static int connection = 1;



	/* set the receive callback for this connection */
	tcp_recv(newpcb, recv_callback);
	/* just use an integer number indicating the connection id as the
	   callback argument */
	tcp_arg(newpcb, (void*)(UINTPTR)connection);

	/* increment for subsequent accepted connections */
	connection++;
	serpcb=newpcb; // pcbȫֱserpcb
	return ERR_OK;
}


int start_application()
{
	err_t err;
	unsigned port = 5000;

	/* create new TCP PCB structure */
	pcb = tcp_new_ip_type(IPADDR_TYPE_ANY);
	if (!pcb) {
		xil_printf("Error creating PCB. Out of Memory\n\r");
		return -1;
	}

	/* bind to specified @port */
	err = tcp_bind(pcb, IP_ANY_TYPE, port);
	if (err != ERR_OK) {
		xil_printf("Unable to bind to port %d: err = %d\n\r", port, err);
		return -2;
	}

	/* we do not need any arguments to callback functions */
	tcp_arg(pcb, NULL);

	/* listen for connections */
	pcb = tcp_listen(pcb);
	if (!pcb) {
		xil_printf("Out of memory while tcp_listen\n\r");
		return -3;
	}

	/* specify callback to use for incoming connections */
	tcp_accept(pcb, accept_callback);

	xil_printf("TCP echo server started @ port %d\n\r", port);

	return 0;
}

/*
 * ָʽ55 A5 addr data data data data F0н
 * addrĿǰЧֵ0~5Լ255ֵdataΪò
 * addr = 0,ADC俪ʼ
 * addr = 1,ADCͨѡ
 * addr = 2,
 * addr = 3,
 * addr = 4,ADCĴãADCЧ
 * addr = 5,PLLʱӷƵ
 * addr = 255,λѯADC
 *
*/
void cmd_analysis(uint8_t *cmd_buffer)
{
	unsigned char cmd[8] = {0};
	for(int i=0;i<8;i++){
		cmd[i] = *(cmd_buffer+i);
	}

	if((cmd[0] == 0x55) && (cmd[1] == 0xA5) && (cmd[7] == 0xF0))
	{
		switch(cmd[2])
		{
			case 0: restart = 1;break;
			case 1: ChannelSel = cmd[6];break;
			case 2: DataNum = (cmd[3] << 24) | (cmd[4] << 16) | (cmd[5] << 8) | cmd[6];break;
			case 3: Speed_Set = (cmd[3] << 24) | (cmd[4] << 16) | (cmd[5] << 8) | cmd[6];break;
			case 5: PLL_Reconfig = (cmd[3] << 24) | (cmd[4] << 16) | (cmd[5] << 8) | cmd[6];
					Reconfig = 1;
					break;
			case 6: SD_data = ((cmd[3] << 24) | (cmd[4] << 16) | (cmd[5] << 8) | cmd[6]);
					SD_WR = 1;
					break;
			case 255: devinfo = 1; break;
			default:break;
		}
	}
}


