/* Standard includes. */
#include "string.h"
#include "board.h"

/* FreeRTOS includes. */
#include "FreeRTOS.h"

#include "task.h"

#include "FreeRTOS_IP.h"
#include "FreeRTOS_UDP_IP.h"
#include "FreeRTOS_Sockets.h"

char data[2500];
uint8_t ucMACAddress[6];

static void prvSetupHardware( void )
{
	Board_Init();
	SystemCoreClockUpdate();
	Board_LED_Set(LED_GREEN, 0);
	Board_LED_Set(LED_AMBER, 1);
	
}



static void mainTask1( void *pvParameters )
{

	xSocket_t xSocket;
	struct freertos_sockaddr saddr;
	const TickType_t xReceiveTimeOut = 10 / portTICK_RATE_MS;
	int i;
	static int cnt = 0;

	saddr.sin_port = FreeRTOS_htons(55443);
	saddr.sin_addr = FreeRTOS_inet_addr_quick(134,89,32,3);

	xSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_DGRAM,
	  FREERTOS_IPPROTO_UDP );
	configASSERT( xSocket != FREERTOS_INVALID_SOCKET );

	/* Set a time out so a missing reply does not cause the task to block
		indefinitely. */
	FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_RCVTIMEO, &xReceiveTimeOut,
	  sizeof( xReceiveTimeOut ) );

	for (;;) {

		for (i = 0; i < 1000; i++)
			data[i] = (cnt % 26) + 97;
		data[i++] = '\n';
		data[i] = 0;
		cnt++;

		FreeRTOS_sendto(
		  xSocket,				/* The socket being sent to. */
		  (void *) data,	/* The data being sent. */
		  strlen(data) + 1,/* The length of the data being sent. */
		  0,						/* ulFlags with the FREERTOS_ZERO_COPY bit clear. */
		  &saddr,	/* The destination address. */
		  sizeof( saddr ) );
		vTaskDelay( 500 / portTICK_PERIOD_MS);

//		Board_LED_Set(LED_GREEN, 0);
//		Board_LED_Set(LED_AMBER, 1);
//		Board_LED_Set(LED_GREEN, 1);
//		Board_LED_Set(LED_AMBER, 0);
//		vTaskDelay( 500 / portTICK_PERIOD_MS);
	};
}

static void mainTask( void *pvParameters )
{

	xSocket_t xSocket, xConnSocket;
	struct freertos_sockaddr saddr, caddr;
	uint32_t caddr_size;
	const TickType_t xReceiveTimeOut = 10 / portTICK_RATE_MS;

	static int xxx;

  xxx	= xPortGetFreeHeapSize();
	if (xxx < 1) {
		xxx = 1;
	}
	saddr.sin_port = FreeRTOS_htons(55443);
	saddr.sin_addr = FreeRTOS_inet_addr_quick(134,89,32,3);

	xSocket = FreeRTOS_socket( FREERTOS_AF_INET, FREERTOS_SOCK_STREAM,
	  FREERTOS_IPPROTO_TCP );
	configASSERT( xSocket != FREERTOS_INVALID_SOCKET );
	xxx = xPortGetFreeHeapSize();

	/* Set a time out so a missing reply does not cause the task to block
		indefinitely. */
	FreeRTOS_setsockopt( xSocket, 0, FREERTOS_SO_RCVTIMEO, &xReceiveTimeOut,
	  sizeof( xReceiveTimeOut ) );
	xxx = xPortGetFreeHeapSize();
	
	FreeRTOS_bind(xSocket, &saddr, sizeof(saddr));
	FreeRTOS_listen(xSocket, 2);
	xxx = xPortGetFreeHeapSize();

	for (;;) {
		int rxbytes, tosend, sent;
		xConnSocket = FreeRTOS_accept(xSocket, &caddr, &caddr_size);
		//configASSERT(xConnSocket != FREERTOS_INVALID_SOCKET );
		if (!xConnSocket || xConnSocket == FREERTOS_INVALID_SOCKET) continue;
		
		xxx = xPortGetFreeHeapSize();

		for (;;) {
			int totalbytes = 0;
			int packets = 0;
			do {
				rxbytes = FreeRTOS_recv(xConnSocket, &data[totalbytes], 2000, 0 );
				totalbytes += rxbytes;
				packets++;
				//xxx = xPortGetFreeHeapSize();
				if (rxbytes < 0) {
					FreeRTOS_shutdown(xConnSocket, FREERTOS_SHUT_RDWR );
					break;
				}
			} while ( rxbytes > 0);
			packets -= 1;
		
			tosend = totalbytes;
			while (tosend > 0) {
				//char *end = &data[totalbytes];
				//tosend += sprintf(end, " bytes: %d, packets: %d\r\n", totalbytes, packets);
				sent = FreeRTOS_send(xConnSocket, data, tosend, 0);
				tosend -= sent;
			}
			totalbytes = packets = 0;
		}
	};
	
	if (xxx == 0){
		xxx = 0;
	}
}

int main( void )
{

	int i = 0;
	const uint8_t ucIPAddress[4] = {134, 89, 32, 4};
	const uint8_t ucNetMask[4] = {255, 255, 254, 0};
	const uint8_t ucGatewayAddress[4] = {134, 89, 32, 1};
	const uint8_t ucDNSServerAddress[4] = {10, 0, 0, 1};
  const uint8_t ucMACAddressLocal[6] = {0x00, 0x0c, 0x6a, 0x01, 0x03, 0x10};

	memcpy(ucMACAddress, ucMACAddressLocal, 6);
	const HeapRegion_t xHeapRegions[] =
	{
		{ ( uint8_t * ) 0x2007C000UL, 0x8000 },
		{ NULL, 0 } /* Terminates the array. */
	};

	/* Pass the array into vPortDefineHeapRegions(). */
	vPortDefineHeapRegions( xHeapRegions );
	
	

	/* Prepare the hardware to run this demo. */
	prvSetupHardware();
	xTaskCreate( mainTask, "TX", configMINIMAL_STACK_SIZE, ( void * ) i, tskIDLE_PRIORITY + 1, NULL );

	/* Start the tasks and timer running. */
	vTaskStartScheduler();


	FreeRTOS_IPInit( ucIPAddress, ucNetMask, ucGatewayAddress, ucDNSServerAddress, ucMACAddress );

	/* If all is well, the scheduler will now be running, and the following
	line will never be reached.  If the following line does execute, then
	there was insufficient FreeRTOS heap memory available for the idle and/or
	timer tasks	to be created.  See the memory management section on the
	FreeRTOS web site for more details. */
	for( ;; ) {
		
		i = 0;
		
	};


}





/*-----------------------------------------------------------*/

void vApplicationMallocFailedHook( void )
{
	/* vApplicationMallocFailedHook() will only be called if
	configUSE_MALLOC_FAILED_HOOK is set to 1 in FreeRTOSConfig.h.  It is a hook
	function that will get called if a call to pvPortMalloc() fails.
	pvPortMalloc() is called internally by the kernel whenever a task, queue,
	timer or semaphore is created.  It is also called by various parts of the
	demo application.  If heap_1.c or heap_2.c are used, then the size of the
	heap available to pvPortMalloc() is defined by configTOTAL_HEAP_SIZE in
	FreeRTOSConfig.h, and the xPortGetFreeHeapSize() API function can be used
	to query the size of free heap space that remains (although it does not
	provide information on how the remaining heap might be fragmented). */
	size_t x = xPortGetFreeHeapSize();
	x = x;
	taskDISABLE_INTERRUPTS();
	for( ;; ) {
		x = x;
	};
}
/*-----------------------------------------------------------*/

void vApplicationIdleHook( void )
{
	/* vApplicationIdleHook() will only be called if configUSE_IDLE_HOOK is set
	to 1 in FreeRTOSConfig.h.  It will be called on each iteration of the idle
	task.  It is essential that code added to this hook function never attempts
	to block in any way (for example, call xQueueReceive() with a block time
	specified, or call vTaskDelay()).  If the application makes use of the
	vTaskDelete() API function (as this demo application does) then it is also
	important that vApplicationIdleHook() is permitted to return to its calling
	function, because it is the responsibility of the idle task to clean up
	memory allocated by the kernel to any task that has since been deleted. */
}
/*-----------------------------------------------------------*/

void vApplicationStackOverflowHook( TaskHandle_t pxTask, char *pcTaskName )
{
	( void ) pcTaskName;
	( void ) pxTask;

	/* Run time stack overflow checking is performed if
	configCHECK_FOR_STACK_OVERFLOW is defined to 1 or 2.  This hook
	function is called if a stack overflow is detected. */
	taskDISABLE_INTERRUPTS();
	for( ;; );
}
/*-----------------------------------------------------------*/

void vApplicationTickHook( void )
{

	/* This function will be called by each tick interrupt if
	configUSE_TICK_HOOK is set to 1 in FreeRTOSConfig.h.  User code can be
	added here, but the tick hook is called from an interrupt context, so
	code must not attempt to block, and only the interrupt safe FreeRTOS API
	functions can be used (those that end in FromISR()). */

}
/*-----------------------------------------------------------*/

/* Called by FreeRTOS+UDP when the network connects. */
void vApplicationIPNetworkEventHook( eIPCallbackEvent_t eNetworkEvent )
{
static BaseType_t xTaskAlreadyCreated = pdFALSE;

	if( eNetworkEvent == eNetworkUp )
	{
		/* Create the tasks that transmit to and receive from a standard
		echo server (see the web documentation for this port) in both
		standard and zero copy mode. */
		if( xTaskAlreadyCreated == pdFALSE )
		{
			//vStartEchoClientTasks( mainECHO_CLIENT_TASK_STACK_SIZE, mainECHO_CLIENT_TASK_PRIORITY );
			//xTaskAlreadyCreated = pdTRUE;
		}
	}
}
/*-----------------------------------------------------------*/

/* Called by FreeRTOS+UDP when a reply is received to an outgoing ping request. */
void vApplicationPingReplyHook( ePingReplyStatus_t eStatus, uint16_t usIdentifier )
{
}





