#include "FreeRTOS.h"
#include "task.h"

#include "FreeRTOS_IP.h"
#include "FreeRTOS_Sockets.h"

void
utils_task_sleep(uint32_t ms)
{
	const TickType_t delay = ms / portTICK_PERIOD_MS;
	vTaskDelay(delay);
}

void
utils_block_sleep(uint32_t ms)
{
    volatile uint32_t i, count = ms * 1000;
	// one for loop is 6 instructions,
    int div = SystemCoreClock / 1000000 / 6;

    if (!count) count++;
    while( --count > 0 )
	{
        for( i = 0; i < div; i++ )
		{
            /* null */ ;
        }
	}
}


/* 
 * Close FreeRTOS IP socket.
 *
 * To cleanly close the socket it needs to be shut down first. If there is still
 * data to be received we make sure we clean it out beforehand until the socket
 * indicates that it is ready to be shut down.
 * If the max amount we are trying to clean out is set to the MTU of the stack
 * it should be sufficient to get it cleaned out completely.
 */
#define UTILS_SOCKET_CLOSE_BUFSZ	64 
#define UTILS_SOCKET_CLOSE_COUNT	24
void
utils_socket_close(Socket_t socket)
{
	uint8_t buf[UTILS_SOCKET_CLOSE_BUFSZ];
	uint8_t count = 0;
	
	FreeRTOS_shutdown(socket, FREERTOS_SHUT_RDWR);
	while(FreeRTOS_recv(socket, buf, UTILS_SOCKET_CLOSE_BUFSZ, 0 ) >= 0 )
    {
        vTaskDelay(20 / portTICK_PERIOD_MS);
		if (count++ > UTILS_SOCKET_CLOSE_COUNT) break;
    }
    FreeRTOS_closesocket(socket);	
}
