Update revision to use TI's mqtt and Freertos.

Dependencies:   mbed client server

Fork of cc3100_Test_mqtt_CM3 by David Fletcher

Files at this revision

API Documentation at this revision

Comitter:
dflet
Date:
Thu Sep 03 14:02:37 2015 +0000
Parent:
2:241bff9fe406
Commit message:
SPI Mode change 1 to 0

Changed in this revision

FreeRTOS_V8_2_1.lib Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/FreeRTOSConfig.h Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/croutine.c Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/event_groups.c Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/include/FreeRTOS.h Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/include/StackMacros.h Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/include/croutine.h Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/include/deprecated_definitions.h Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/include/event_groups.h Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/include/list.h Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/include/mpu_wrappers.h Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/include/portable.h Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/include/projdefs.h Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/include/queue.h Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/include/semphr.h Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/include/stdint.readme Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/include/task.h Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/include/timers.h Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/list.c Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/portable/MemMang/heap_1.c Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/portable/RVDS/ARM_CM3/port.c Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/portable/RVDS/ARM_CM3/portmacro.h Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/queue.c Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/readme.txt Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/tasks.c Show annotated file Show diff for this revision Revisions of this file
FreeRTOS_V8_2_1/source/timers.c Show annotated file Show diff for this revision Revisions of this file
cli_uart.cpp Show annotated file Show diff for this revision Revisions of this file
main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed.bld Show annotated file Show diff for this revision Revisions of this file
mqtt_V1.lib Show diff for this revision Revisions of this file
mqtt_V1/client.lib Show annotated file Show diff for this revision Revisions of this file
mqtt_V1/common/mqtt_common.cpp Show annotated file Show diff for this revision Revisions of this file
mqtt_V1/common/mqtt_common.h Show annotated file Show diff for this revision Revisions of this file
mqtt_V1/include/sl_mqtt_client.h Show annotated file Show diff for this revision Revisions of this file
mqtt_V1/include/sl_mqtt_server.h Show annotated file Show diff for this revision Revisions of this file
mqtt_V1/platform/cc31xx_sl_net.cpp Show annotated file Show diff for this revision Revisions of this file
mqtt_V1/platform/cc31xx_sl_net.h Show annotated file Show diff for this revision Revisions of this file
mqtt_V1/platform/cc3200_platform.cpp Show annotated file Show diff for this revision Revisions of this file
mqtt_V1/platform/cc3200_platform.h Show annotated file Show diff for this revision Revisions of this file
mqtt_V1/server.lib Show annotated file Show diff for this revision Revisions of this file
mqtt_V1/sl/sl_mqtt_client.cpp Show annotated file Show diff for this revision Revisions of this file
mqtt_V1/sl/sl_mqtt_server.cpp Show annotated file Show diff for this revision Revisions of this file
simplelink_V2.lib Show diff for this revision Revisions of this file
simplelink_V2/G_functions/fPtr_func.cpp Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/G_functions/fPtr_func.h Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100.cpp Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100.h Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_driver.cpp Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_driver.h Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_fs.cpp Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_fs.h Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_netapp.cpp Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_netapp.h Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_netcfg.cpp Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_netcfg.h Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_nonos.cpp Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_nonos.h Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_objInclusion.h Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_protocol.h Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_simplelink.h Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_sl_common.h Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_socket.cpp Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_socket.h Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_spawn.cpp Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_spawn.h Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_spi.cpp Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_spi.h Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_trace.h Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_user.h Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_wlan.cpp Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_wlan.h Show annotated file Show diff for this revision Revisions of this file
simplelink_V2/cc3100_wlan_rx_filters.h Show annotated file Show diff for this revision Revisions of this file
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1.lib
--- a/FreeRTOS_V8_2_1.lib	Sat Jun 06 14:06:49 2015 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
-http://developer.mbed.org/users/dflet/code/FreeRTOS_V8_2_1/#91ad48ad5687
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/FreeRTOSConfig.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/FreeRTOSConfig.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,163 @@
+/*
+    FreeRTOS V7.6.0 - Copyright (C) 2013 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that has become a de facto standard.             *
+     *                                                                       *
+     *    Help yourself get started quickly and support the FreeRTOS         *
+     *    project by purchasing a FreeRTOS tutorial book, reference          *
+     *    manual, or both from: http://www.FreeRTOS.org/Documentation        *
+     *                                                                       *
+     *    Thank you!                                                         *
+     *                                                                       *
+    ***************************************************************************
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    >>! NOTE: The modification to the GPL is included to allow you to distribute
+    >>! a combined work that includes FreeRTOS without being obliged to provide
+    >>! the source code for proprietary components outside of the FreeRTOS
+    >>! kernel.
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available from the following
+    link: http://www.freertos.org/a00114.html
+
+    1 tab == 4 spaces!
+
+    ***************************************************************************
+     *                                                                       *
+     *    Having a problem?  Start by reading the FAQ "My application does   *
+     *    not run, what could be wrong?"                                     *
+     *                                                                       *
+     *    http://www.FreeRTOS.org/FAQHelp.html                               *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org - Documentation, books, training, latest versions,
+    license and Real Time Engineers Ltd. contact details.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High
+    Integrity Systems to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+#ifndef FREERTOS_CONFIG_H
+#define FREERTOS_CONFIG_H
+
+/*-----------------------------------------------------------
+ * Application specific definitions.
+ *
+ * These definitions should be adjusted for your particular hardware and
+ * application requirements.
+ *
+ * THESE PARAMETERS ARE DESCRIBED WITHIN THE 'CONFIGURATION' SECTION OF THE
+ * FreeRTOS API DOCUMENTATION AVAILABLE ON THE FreeRTOS.org WEB SITE.
+ *----------------------------------------------------------*/
+
+#include <stdint.h>
+#include "myBoardInit.h"
+extern uint32_t SystemCoreClock;
+//#define vPortYieldProcessor swi_handler
+
+#define configUSE_PREEMPTION		1
+#define configUSE_IDLE_HOOK			0
+#define configMAX_PRIORITIES		( ( unsigned portBASE_TYPE ) 5 )
+#define configUSE_TICK_HOOK			0
+#define configCPU_CLOCK_HZ			( ( unsigned long ) SystemCoreClock )
+#define configTICK_RATE_HZ			( ( portTickType ) 1000 )
+#define configMINIMAL_STACK_SIZE	( ( unsigned short ) 80 )
+#define configTOTAL_HEAP_SIZE		( ( size_t ) ( 10 * 1024 ) )
+#define configMAX_TASK_NAME_LEN		( 16 )
+#define configUSE_TRACE_FACILITY	1
+#define configUSE_16_BIT_TICKS		0
+#define configIDLE_SHOULD_YIELD		1//0
+#define configUSE_CO_ROUTINES 		0
+#define configUSE_MUTEXES			1
+
+//#define configMAX_PRIORITIES			( 10UL )
+/* Co-routine definitions. */
+#define configUSE_CO_ROUTINES 		0
+#define configMAX_CO_ROUTINE_PRIORITIES ( 2 )
+
+#define configUSE_COUNTING_SEMAPHORES 	1//0
+#define configUSE_ALTERNATIVE_API 		1//0
+#define configCHECK_FOR_STACK_OVERFLOW	0
+#define configUSE_RECURSIVE_MUTEXES		1
+#define configQUEUE_REGISTRY_SIZE		10
+#define configGENERATE_RUN_TIME_STATS	0
+
+/* Timer related defines. */
+#define configUSE_TIMERS				0
+#define configTIMER_TASK_PRIORITY		2
+#define configTIMER_QUEUE_LENGTH		20
+#define configTIMER_TASK_STACK_DEPTH	( configMINIMAL_STACK_SIZE * 2 )
+#define configUSE_MALLOC_FAILED_HOOK    0//1
+#define configENABLE_BACKWARD_COMPATIBILITY 1//0
+
+/* Set the following definitions to 1 to include the API function, or zero
+to exclude the API function. */
+
+#define INCLUDE_vTaskPrioritySet				1
+#define INCLUDE_uxTaskPriorityGet				1
+#define INCLUDE_vTaskDelete						1
+#define INCLUDE_vTaskCleanUpResources			1
+#define INCLUDE_vTaskSuspend					1
+#define INCLUDE_vTaskDelayUntil					1
+#define INCLUDE_vTaskDelay						1
+#define INCLUDE_uxTaskGetStackHighWaterMark		0
+#define INCLUDE_xTaskGetSchedulerState			1
+#define INCLUDE_xTimerGetTimerDaemonTaskHandle	0
+#define INCLUDE_xTaskGetIdleTaskHandle			1
+#define INCLUDE_pcTaskGetTaskName				1
+#define INCLUDE_eTaskGetState					1
+#define INCLUDE_xSemaphoreGetMutexHolder		0
+
+
+/* Use the system definition, if there is one */
+#ifdef __NVIC_PRIO_BITS
+	#define configPRIO_BITS       __NVIC_PRIO_BITS
+#else
+	#define configPRIO_BITS       5        /* 32 priority levels */
+#endif
+
+/* Define to trap errors during development. */
+//void vAssertCalled( const char *pcFile, unsigned long ulLine );
+//	#define configASSERT( x ) if( x == 0 ) vAssertCalled( __FILE__, __LINE__ );
+
+/* The lowest priority. */
+#define configKERNEL_INTERRUPT_PRIORITY 	( 31 << (8 - configPRIO_BITS) )
+/* Priority 5, or 160 as only the top three bits are implemented. */
+/* !!!! configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to zero !!!!
+See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html. */
+#define configMAX_SYSCALL_INTERRUPT_PRIORITY 	( 5 << (8 - configPRIO_BITS) )
+
+/* Definitions that map the FreeRTOS port interrupt handlers to their CMSIS
+standard names - or at least those used in the unmodified vector table. */
+#define vPortSVCHandler SVC_Handler
+#define xPortPendSVHandler PendSV_Handler
+#define xPortSysTickHandler SysTick_Handler
+
+
+#endif /* FREERTOS_CONFIG_H */
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/croutine.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/croutine.c	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,396 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+#include "FreeRTOS.h"
+#include "task.h"
+#include "croutine.h"
+
+/* Remove the whole file is co-routines are not being used. */
+#if( configUSE_CO_ROUTINES != 0 )
+
+/*
+ * Some kernel aware debuggers require data to be viewed to be global, rather
+ * than file scope.
+ */
+#ifdef portREMOVE_STATIC_QUALIFIER
+	#define static
+#endif
+
+
+/* Lists for ready and blocked co-routines. --------------------*/
+static List_t pxReadyCoRoutineLists[ configMAX_CO_ROUTINE_PRIORITIES ];	/*< Prioritised ready co-routines. */
+static List_t xDelayedCoRoutineList1;									/*< Delayed co-routines. */
+static List_t xDelayedCoRoutineList2;									/*< Delayed co-routines (two lists are used - one for delays that have overflowed the current tick count. */
+static List_t * pxDelayedCoRoutineList;									/*< Points to the delayed co-routine list currently being used. */
+static List_t * pxOverflowDelayedCoRoutineList;							/*< Points to the delayed co-routine list currently being used to hold co-routines that have overflowed the current tick count. */
+static List_t xPendingReadyCoRoutineList;								/*< Holds co-routines that have been readied by an external event.  They cannot be added directly to the ready lists as the ready lists cannot be accessed by interrupts. */
+
+/* Other file private variables. --------------------------------*/
+CRCB_t * pxCurrentCoRoutine = NULL;
+static UBaseType_t uxTopCoRoutineReadyPriority = 0;
+static TickType_t xCoRoutineTickCount = 0, xLastTickCount = 0, xPassedTicks = 0;
+
+/* The initial state of the co-routine when it is created. */
+#define corINITIAL_STATE	( 0 )
+
+/*
+ * Place the co-routine represented by pxCRCB into the appropriate ready queue
+ * for the priority.  It is inserted at the end of the list.
+ *
+ * This macro accesses the co-routine ready lists and therefore must not be
+ * used from within an ISR.
+ */
+#define prvAddCoRoutineToReadyQueue( pxCRCB )																		\
+{																													\
+	if( pxCRCB->uxPriority > uxTopCoRoutineReadyPriority )															\
+	{																												\
+		uxTopCoRoutineReadyPriority = pxCRCB->uxPriority;															\
+	}																												\
+	vListInsertEnd( ( List_t * ) &( pxReadyCoRoutineLists[ pxCRCB->uxPriority ] ), &( pxCRCB->xGenericListItem ) );	\
+}
+
+/*
+ * Utility to ready all the lists used by the scheduler.  This is called
+ * automatically upon the creation of the first co-routine.
+ */
+static void prvInitialiseCoRoutineLists( void );
+
+/*
+ * Co-routines that are readied by an interrupt cannot be placed directly into
+ * the ready lists (there is no mutual exclusion).  Instead they are placed in
+ * in the pending ready list in order that they can later be moved to the ready
+ * list by the co-routine scheduler.
+ */
+static void prvCheckPendingReadyList( void );
+
+/*
+ * Macro that looks at the list of co-routines that are currently delayed to
+ * see if any require waking.
+ *
+ * Co-routines are stored in the queue in the order of their wake time -
+ * meaning once one co-routine has been found whose timer has not expired
+ * we need not look any further down the list.
+ */
+static void prvCheckDelayedList( void );
+
+/*-----------------------------------------------------------*/
+
+BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, UBaseType_t uxPriority, UBaseType_t uxIndex )
+{
+BaseType_t xReturn;
+CRCB_t *pxCoRoutine;
+
+	/* Allocate the memory that will store the co-routine control block. */
+	pxCoRoutine = ( CRCB_t * ) pvPortMalloc( sizeof( CRCB_t ) );
+	if( pxCoRoutine )
+	{
+		/* If pxCurrentCoRoutine is NULL then this is the first co-routine to
+		be created and the co-routine data structures need initialising. */
+		if( pxCurrentCoRoutine == NULL )
+		{
+			pxCurrentCoRoutine = pxCoRoutine;
+			prvInitialiseCoRoutineLists();
+		}
+
+		/* Check the priority is within limits. */
+		if( uxPriority >= configMAX_CO_ROUTINE_PRIORITIES )
+		{
+			uxPriority = configMAX_CO_ROUTINE_PRIORITIES - 1;
+		}
+
+		/* Fill out the co-routine control block from the function parameters. */
+		pxCoRoutine->uxState = corINITIAL_STATE;
+		pxCoRoutine->uxPriority = uxPriority;
+		pxCoRoutine->uxIndex = uxIndex;
+		pxCoRoutine->pxCoRoutineFunction = pxCoRoutineCode;
+
+		/* Initialise all the other co-routine control block parameters. */
+		vListInitialiseItem( &( pxCoRoutine->xGenericListItem ) );
+		vListInitialiseItem( &( pxCoRoutine->xEventListItem ) );
+
+		/* Set the co-routine control block as a link back from the ListItem_t.
+		This is so we can get back to the containing CRCB from a generic item
+		in a list. */
+		listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xGenericListItem ), pxCoRoutine );
+		listSET_LIST_ITEM_OWNER( &( pxCoRoutine->xEventListItem ), pxCoRoutine );
+
+		/* Event lists are always in priority order. */
+		listSET_LIST_ITEM_VALUE( &( pxCoRoutine->xEventListItem ), ( ( TickType_t ) configMAX_CO_ROUTINE_PRIORITIES - ( TickType_t ) uxPriority ) );
+
+		/* Now the co-routine has been initialised it can be added to the ready
+		list at the correct priority. */
+		prvAddCoRoutineToReadyQueue( pxCoRoutine );
+
+		xReturn = pdPASS;
+	}
+	else
+	{
+		xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
+	}
+
+	return xReturn;
+}
+/*-----------------------------------------------------------*/
+
+void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay, List_t *pxEventList )
+{
+TickType_t xTimeToWake;
+
+	/* Calculate the time to wake - this may overflow but this is
+	not a problem. */
+	xTimeToWake = xCoRoutineTickCount + xTicksToDelay;
+
+	/* We must remove ourselves from the ready list before adding
+	ourselves to the blocked list as the same list item is used for
+	both lists. */
+	( void ) uxListRemove( ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) );
+
+	/* The list item will be inserted in wake time order. */
+	listSET_LIST_ITEM_VALUE( &( pxCurrentCoRoutine->xGenericListItem ), xTimeToWake );
+
+	if( xTimeToWake < xCoRoutineTickCount )
+	{
+		/* Wake time has overflowed.  Place this item in the
+		overflow list. */
+		vListInsert( ( List_t * ) pxOverflowDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) );
+	}
+	else
+	{
+		/* The wake time has not overflowed, so we can use the
+		current block list. */
+		vListInsert( ( List_t * ) pxDelayedCoRoutineList, ( ListItem_t * ) &( pxCurrentCoRoutine->xGenericListItem ) );
+	}
+
+	if( pxEventList )
+	{
+		/* Also add the co-routine to an event list.  If this is done then the
+		function must be called with interrupts disabled. */
+		vListInsert( pxEventList, &( pxCurrentCoRoutine->xEventListItem ) );
+	}
+}
+/*-----------------------------------------------------------*/
+
+static void prvCheckPendingReadyList( void )
+{
+	/* Are there any co-routines waiting to get moved to the ready list?  These
+	are co-routines that have been readied by an ISR.  The ISR cannot access
+	the	ready lists itself. */
+	while( listLIST_IS_EMPTY( &xPendingReadyCoRoutineList ) == pdFALSE )
+	{
+		CRCB_t *pxUnblockedCRCB;
+
+		/* The pending ready list can be accessed by an ISR. */
+		portDISABLE_INTERRUPTS();
+		{
+			pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( (&xPendingReadyCoRoutineList) );
+			( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) );
+		}
+		portENABLE_INTERRUPTS();
+
+		( void ) uxListRemove( &( pxUnblockedCRCB->xGenericListItem ) );
+		prvAddCoRoutineToReadyQueue( pxUnblockedCRCB );
+	}
+}
+/*-----------------------------------------------------------*/
+
+static void prvCheckDelayedList( void )
+{
+CRCB_t *pxCRCB;
+
+	xPassedTicks = xTaskGetTickCount() - xLastTickCount;
+	while( xPassedTicks )
+	{
+		xCoRoutineTickCount++;
+		xPassedTicks--;
+
+		/* If the tick count has overflowed we need to swap the ready lists. */
+		if( xCoRoutineTickCount == 0 )
+		{
+			List_t * pxTemp;
+
+			/* Tick count has overflowed so we need to swap the delay lists.  If there are
+			any items in pxDelayedCoRoutineList here then there is an error! */
+			pxTemp = pxDelayedCoRoutineList;
+			pxDelayedCoRoutineList = pxOverflowDelayedCoRoutineList;
+			pxOverflowDelayedCoRoutineList = pxTemp;
+		}
+
+		/* See if this tick has made a timeout expire. */
+		while( listLIST_IS_EMPTY( pxDelayedCoRoutineList ) == pdFALSE )
+		{
+			pxCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedCoRoutineList );
+
+			if( xCoRoutineTickCount < listGET_LIST_ITEM_VALUE( &( pxCRCB->xGenericListItem ) ) )
+			{
+				/* Timeout not yet expired. */
+				break;
+			}
+
+			portDISABLE_INTERRUPTS();
+			{
+				/* The event could have occurred just before this critical
+				section.  If this is the case then the generic list item will
+				have been moved to the pending ready list and the following
+				line is still valid.  Also the pvContainer parameter will have
+				been set to NULL so the following lines are also valid. */
+				( void ) uxListRemove( &( pxCRCB->xGenericListItem ) );
+
+				/* Is the co-routine waiting on an event also? */
+				if( pxCRCB->xEventListItem.pvContainer )
+				{
+					( void ) uxListRemove( &( pxCRCB->xEventListItem ) );
+				}
+			}
+			portENABLE_INTERRUPTS();
+
+			prvAddCoRoutineToReadyQueue( pxCRCB );
+		}
+	}
+
+	xLastTickCount = xCoRoutineTickCount;
+}
+/*-----------------------------------------------------------*/
+
+void vCoRoutineSchedule( void )
+{
+	/* See if any co-routines readied by events need moving to the ready lists. */
+	prvCheckPendingReadyList();
+
+	/* See if any delayed co-routines have timed out. */
+	prvCheckDelayedList();
+
+	/* Find the highest priority queue that contains ready co-routines. */
+	while( listLIST_IS_EMPTY( &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) ) )
+	{
+		if( uxTopCoRoutineReadyPriority == 0 )
+		{
+			/* No more co-routines to check. */
+			return;
+		}
+		--uxTopCoRoutineReadyPriority;
+	}
+
+	/* listGET_OWNER_OF_NEXT_ENTRY walks through the list, so the co-routines
+	 of the	same priority get an equal share of the processor time. */
+	listGET_OWNER_OF_NEXT_ENTRY( pxCurrentCoRoutine, &( pxReadyCoRoutineLists[ uxTopCoRoutineReadyPriority ] ) );
+
+	/* Call the co-routine. */
+	( pxCurrentCoRoutine->pxCoRoutineFunction )( pxCurrentCoRoutine, pxCurrentCoRoutine->uxIndex );
+
+	return;
+}
+/*-----------------------------------------------------------*/
+
+static void prvInitialiseCoRoutineLists( void )
+{
+UBaseType_t uxPriority;
+
+	for( uxPriority = 0; uxPriority < configMAX_CO_ROUTINE_PRIORITIES; uxPriority++ )
+	{
+		vListInitialise( ( List_t * ) &( pxReadyCoRoutineLists[ uxPriority ] ) );
+	}
+
+	vListInitialise( ( List_t * ) &xDelayedCoRoutineList1 );
+	vListInitialise( ( List_t * ) &xDelayedCoRoutineList2 );
+	vListInitialise( ( List_t * ) &xPendingReadyCoRoutineList );
+
+	/* Start with pxDelayedCoRoutineList using list1 and the
+	pxOverflowDelayedCoRoutineList using list2. */
+	pxDelayedCoRoutineList = &xDelayedCoRoutineList1;
+	pxOverflowDelayedCoRoutineList = &xDelayedCoRoutineList2;
+}
+/*-----------------------------------------------------------*/
+
+BaseType_t xCoRoutineRemoveFromEventList( const List_t *pxEventList )
+{
+CRCB_t *pxUnblockedCRCB;
+BaseType_t xReturn;
+
+	/* This function is called from within an interrupt.  It can only access
+	event lists and the pending ready list.  This function assumes that a
+	check has already been made to ensure pxEventList is not empty. */
+	pxUnblockedCRCB = ( CRCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList );
+	( void ) uxListRemove( &( pxUnblockedCRCB->xEventListItem ) );
+	vListInsertEnd( ( List_t * ) &( xPendingReadyCoRoutineList ), &( pxUnblockedCRCB->xEventListItem ) );
+
+	if( pxUnblockedCRCB->uxPriority >= pxCurrentCoRoutine->uxPriority )
+	{
+		xReturn = pdTRUE;
+	}
+	else
+	{
+		xReturn = pdFALSE;
+	}
+
+	return xReturn;
+}
+
+#endif /* configUSE_CO_ROUTINES == 0 */
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/event_groups.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/event_groups.c	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,684 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+/* Standard includes. */
+#include <stdlib.h>
+
+/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
+all the API functions to use the MPU wrappers.  That should only be done when
+task.h is included from an application file. */
+#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
+
+/* FreeRTOS includes. */
+#include "FreeRTOS.h"
+#include "task.h"
+#include "timers.h"
+#include "event_groups.h"
+
+/* Lint e961 and e750 are suppressed as a MISRA exception justified because the
+MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined for the
+header files above, but not in this file, in order to generate the correct
+privileged Vs unprivileged linkage and placement. */
+#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750. */
+
+#if ( INCLUDE_xEventGroupSetBitFromISR == 1 ) && ( configUSE_TIMERS == 0 )
+	#error configUSE_TIMERS must be set to 1 to make the xEventGroupSetBitFromISR() function available.
+#endif
+
+#if ( INCLUDE_xEventGroupSetBitFromISR == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 0 )
+	#error INCLUDE_xTimerPendFunctionCall must also be set to one to make the xEventGroupSetBitFromISR() function available.
+#endif
+
+/* The following bit fields convey control information in a task's event list
+item value.  It is important they don't clash with the
+taskEVENT_LIST_ITEM_VALUE_IN_USE definition. */
+#if configUSE_16_BIT_TICKS == 1
+	#define eventCLEAR_EVENTS_ON_EXIT_BIT	0x0100U
+	#define eventUNBLOCKED_DUE_TO_BIT_SET	0x0200U
+	#define eventWAIT_FOR_ALL_BITS			0x0400U
+	#define eventEVENT_BITS_CONTROL_BYTES	0xff00U
+#else
+	#define eventCLEAR_EVENTS_ON_EXIT_BIT	0x01000000UL
+	#define eventUNBLOCKED_DUE_TO_BIT_SET	0x02000000UL
+	#define eventWAIT_FOR_ALL_BITS			0x04000000UL
+	#define eventEVENT_BITS_CONTROL_BYTES	0xff000000UL
+#endif
+
+typedef struct xEventGroupDefinition
+{
+	EventBits_t uxEventBits;
+	List_t xTasksWaitingForBits;		/*< List of tasks waiting for a bit to be set. */
+
+	#if( configUSE_TRACE_FACILITY == 1 )
+		UBaseType_t uxEventGroupNumber;
+	#endif
+
+} EventGroup_t;
+
+/*-----------------------------------------------------------*/
+
+/*
+ * Test the bits set in uxCurrentEventBits to see if the wait condition is met.
+ * The wait condition is defined by xWaitForAllBits.  If xWaitForAllBits is
+ * pdTRUE then the wait condition is met if all the bits set in uxBitsToWaitFor
+ * are also set in uxCurrentEventBits.  If xWaitForAllBits is pdFALSE then the
+ * wait condition is met if any of the bits set in uxBitsToWait for are also set
+ * in uxCurrentEventBits.
+ */
+static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits, const EventBits_t uxBitsToWaitFor, const BaseType_t xWaitForAllBits );
+
+/*-----------------------------------------------------------*/
+
+EventGroupHandle_t xEventGroupCreate( void )
+{
+EventGroup_t *pxEventBits;
+
+	pxEventBits = ( EventGroup_t * ) pvPortMalloc( sizeof( EventGroup_t ) );
+	if( pxEventBits != NULL )
+	{
+		pxEventBits->uxEventBits = 0;
+		vListInitialise( &( pxEventBits->xTasksWaitingForBits ) );
+		traceEVENT_GROUP_CREATE( pxEventBits );
+	}
+	else
+	{
+		traceEVENT_GROUP_CREATE_FAILED();
+	}
+
+	return ( EventGroupHandle_t ) pxEventBits;
+}
+/*-----------------------------------------------------------*/
+
+EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, const EventBits_t uxBitsToWaitFor, TickType_t xTicksToWait )
+{
+EventBits_t uxOriginalBitValue, uxReturn;
+EventGroup_t *pxEventBits = ( EventGroup_t * ) xEventGroup;
+BaseType_t xAlreadyYielded;
+BaseType_t xTimeoutOccurred = pdFALSE;
+
+	configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 );
+	configASSERT( uxBitsToWaitFor != 0 );
+	#if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) )
+	{
+		configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) );
+	}
+	#endif
+
+	vTaskSuspendAll();
+	{
+		uxOriginalBitValue = pxEventBits->uxEventBits;
+
+		( void ) xEventGroupSetBits( xEventGroup, uxBitsToSet );
+
+		if( ( ( uxOriginalBitValue | uxBitsToSet ) & uxBitsToWaitFor ) == uxBitsToWaitFor )
+		{
+			/* All the rendezvous bits are now set - no need to block. */
+			uxReturn = ( uxOriginalBitValue | uxBitsToSet );
+
+			/* Rendezvous always clear the bits.  They will have been cleared
+			already unless this is the only task in the rendezvous. */
+			pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
+
+			xTicksToWait = 0;
+		}
+		else
+		{
+			if( xTicksToWait != ( TickType_t ) 0 )
+			{
+				traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor );
+
+				/* Store the bits that the calling task is waiting for in the
+				task's event list item so the kernel knows when a match is
+				found.  Then enter the blocked state. */
+				vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | eventCLEAR_EVENTS_ON_EXIT_BIT | eventWAIT_FOR_ALL_BITS ), xTicksToWait );
+
+				/* This assignment is obsolete as uxReturn will get set after
+				the task unblocks, but some compilers mistakenly generate a
+				warning about uxReturn being returned without being set if the
+				assignment is omitted. */
+				uxReturn = 0;
+			}
+			else
+			{
+				/* The rendezvous bits were not set, but no block time was
+				specified - just return the current event bit value. */
+				uxReturn = pxEventBits->uxEventBits;
+			}
+		}
+	}
+	xAlreadyYielded = xTaskResumeAll();
+
+	if( xTicksToWait != ( TickType_t ) 0 )
+	{
+		if( xAlreadyYielded == pdFALSE )
+		{
+			portYIELD_WITHIN_API();
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+
+		/* The task blocked to wait for its required bits to be set - at this
+		point either the required bits were set or the block time expired.  If
+		the required bits were set they will have been stored in the task's
+		event list item, and they should now be retrieved then cleared. */
+		uxReturn = uxTaskResetEventItemValue();
+
+		if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 )
+		{
+			/* The task timed out, just return the current event bit value. */
+			taskENTER_CRITICAL();
+			{
+				uxReturn = pxEventBits->uxEventBits;
+
+				/* Although the task got here because it timed out before the
+				bits it was waiting for were set, it is possible that since it
+				unblocked another task has set the bits.  If this is the case
+				then it needs to clear the bits before exiting. */
+				if( ( uxReturn & uxBitsToWaitFor ) == uxBitsToWaitFor )
+				{
+					pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			taskEXIT_CRITICAL();
+
+			xTimeoutOccurred = pdTRUE;
+		}
+		else
+		{
+			/* The task unblocked because the bits were set. */
+		}
+
+		/* Control bits might be set as the task had blocked should not be
+		returned. */
+		uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES;
+	}
+
+	traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred );
+
+	return uxReturn;
+}
+/*-----------------------------------------------------------*/
+
+EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToWaitFor, const BaseType_t xClearOnExit, const BaseType_t xWaitForAllBits, TickType_t xTicksToWait )
+{
+EventGroup_t *pxEventBits = ( EventGroup_t * ) xEventGroup;
+EventBits_t uxReturn, uxControlBits = 0;
+BaseType_t xWaitConditionMet, xAlreadyYielded;
+BaseType_t xTimeoutOccurred = pdFALSE;
+
+	/* Check the user is not attempting to wait on the bits used by the kernel
+	itself, and that at least one bit is being requested. */
+	configASSERT( xEventGroup );
+	configASSERT( ( uxBitsToWaitFor & eventEVENT_BITS_CONTROL_BYTES ) == 0 );
+	configASSERT( uxBitsToWaitFor != 0 );
+	#if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) )
+	{
+		configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) );
+	}
+	#endif
+
+	vTaskSuspendAll();
+	{
+		const EventBits_t uxCurrentEventBits = pxEventBits->uxEventBits;
+
+		/* Check to see if the wait condition is already met or not. */
+		xWaitConditionMet = prvTestWaitCondition( uxCurrentEventBits, uxBitsToWaitFor, xWaitForAllBits );
+
+		if( xWaitConditionMet != pdFALSE )
+		{
+			/* The wait condition has already been met so there is no need to
+			block. */
+			uxReturn = uxCurrentEventBits;
+			xTicksToWait = ( TickType_t ) 0;
+
+			/* Clear the wait bits if requested to do so. */
+			if( xClearOnExit != pdFALSE )
+			{
+				pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		else if( xTicksToWait == ( TickType_t ) 0 )
+		{
+			/* The wait condition has not been met, but no block time was
+			specified, so just return the current value. */
+			uxReturn = uxCurrentEventBits;
+		}
+		else
+		{
+			/* The task is going to block to wait for its required bits to be
+			set.  uxControlBits are used to remember the specified behaviour of
+			this call to xEventGroupWaitBits() - for use when the event bits
+			unblock the task. */
+			if( xClearOnExit != pdFALSE )
+			{
+				uxControlBits |= eventCLEAR_EVENTS_ON_EXIT_BIT;
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+
+			if( xWaitForAllBits != pdFALSE )
+			{
+				uxControlBits |= eventWAIT_FOR_ALL_BITS;
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+
+			/* Store the bits that the calling task is waiting for in the
+			task's event list item so the kernel knows when a match is
+			found.  Then enter the blocked state. */
+			vTaskPlaceOnUnorderedEventList( &( pxEventBits->xTasksWaitingForBits ), ( uxBitsToWaitFor | uxControlBits ), xTicksToWait );
+
+			/* This is obsolete as it will get set after the task unblocks, but
+			some compilers mistakenly generate a warning about the variable
+			being returned without being set if it is not done. */
+			uxReturn = 0;
+
+			traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor );
+		}
+	}
+	xAlreadyYielded = xTaskResumeAll();
+
+	if( xTicksToWait != ( TickType_t ) 0 )
+	{
+		if( xAlreadyYielded == pdFALSE )
+		{
+			portYIELD_WITHIN_API();
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+
+		/* The task blocked to wait for its required bits to be set - at this
+		point either the required bits were set or the block time expired.  If
+		the required bits were set they will have been stored in the task's
+		event list item, and they should now be retrieved then cleared. */
+		uxReturn = uxTaskResetEventItemValue();
+
+		if( ( uxReturn & eventUNBLOCKED_DUE_TO_BIT_SET ) == ( EventBits_t ) 0 )
+		{
+			taskENTER_CRITICAL();
+			{
+				/* The task timed out, just return the current event bit value. */
+				uxReturn = pxEventBits->uxEventBits;
+
+				/* It is possible that the event bits were updated between this
+				task leaving the Blocked state and running again. */
+				if( prvTestWaitCondition( uxReturn, uxBitsToWaitFor, xWaitForAllBits ) != pdFALSE )
+				{
+					if( xClearOnExit != pdFALSE )
+					{
+						pxEventBits->uxEventBits &= ~uxBitsToWaitFor;
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			taskEXIT_CRITICAL();
+
+			/* Prevent compiler warnings when trace macros are not used. */
+			xTimeoutOccurred = pdFALSE;
+		}
+		else
+		{
+			/* The task unblocked because the bits were set. */
+		}
+
+		/* The task blocked so control bits may have been set. */
+		uxReturn &= ~eventEVENT_BITS_CONTROL_BYTES;
+	}
+	traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred );
+
+	return uxReturn;
+}
+/*-----------------------------------------------------------*/
+
+EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear )
+{
+EventGroup_t *pxEventBits = ( EventGroup_t * ) xEventGroup;
+EventBits_t uxReturn;
+
+	/* Check the user is not attempting to clear the bits used by the kernel
+	itself. */
+	configASSERT( xEventGroup );
+	configASSERT( ( uxBitsToClear & eventEVENT_BITS_CONTROL_BYTES ) == 0 );
+
+	taskENTER_CRITICAL();
+	{
+		traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear );
+
+		/* The value returned is the event group value prior to the bits being
+		cleared. */
+		uxReturn = pxEventBits->uxEventBits;
+
+		/* Clear the bits. */
+		pxEventBits->uxEventBits &= ~uxBitsToClear;
+	}
+	taskEXIT_CRITICAL();
+
+	return uxReturn;
+}
+/*-----------------------------------------------------------*/
+
+#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) )
+
+	BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear )
+	{
+		BaseType_t xReturn;
+
+		traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear );
+		xReturn = xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL );
+
+		return xReturn;
+	}
+
+#endif
+/*-----------------------------------------------------------*/
+
+EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup )
+{
+UBaseType_t uxSavedInterruptStatus;
+EventGroup_t *pxEventBits = ( EventGroup_t * ) xEventGroup;
+EventBits_t uxReturn;
+
+	uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
+	{
+		uxReturn = pxEventBits->uxEventBits;
+	}
+	portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
+
+	return uxReturn;
+}
+/*-----------------------------------------------------------*/
+
+EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet )
+{
+ListItem_t *pxListItem, *pxNext;
+ListItem_t const *pxListEnd;
+List_t *pxList;
+EventBits_t uxBitsToClear = 0, uxBitsWaitedFor, uxControlBits;
+EventGroup_t *pxEventBits = ( EventGroup_t * ) xEventGroup;
+BaseType_t xMatchFound = pdFALSE;
+
+	/* Check the user is not attempting to set the bits used by the kernel
+	itself. */
+	configASSERT( xEventGroup );
+	configASSERT( ( uxBitsToSet & eventEVENT_BITS_CONTROL_BYTES ) == 0 );
+
+	pxList = &( pxEventBits->xTasksWaitingForBits );
+	pxListEnd = listGET_END_MARKER( pxList ); /*lint !e826 !e740 The mini list structure is used as the list end to save RAM.  This is checked and valid. */
+	vTaskSuspendAll();
+	{
+		traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet );
+
+		pxListItem = listGET_HEAD_ENTRY( pxList );
+
+		/* Set the bits. */
+		pxEventBits->uxEventBits |= uxBitsToSet;
+
+		/* See if the new bit value should unblock any tasks. */
+		while( pxListItem != pxListEnd )
+		{
+			pxNext = listGET_NEXT( pxListItem );
+			uxBitsWaitedFor = listGET_LIST_ITEM_VALUE( pxListItem );
+			xMatchFound = pdFALSE;
+
+			/* Split the bits waited for from the control bits. */
+			uxControlBits = uxBitsWaitedFor & eventEVENT_BITS_CONTROL_BYTES;
+			uxBitsWaitedFor &= ~eventEVENT_BITS_CONTROL_BYTES;
+
+			if( ( uxControlBits & eventWAIT_FOR_ALL_BITS ) == ( EventBits_t ) 0 )
+			{
+				/* Just looking for single bit being set. */
+				if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) != ( EventBits_t ) 0 )
+				{
+					xMatchFound = pdTRUE;
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			else if( ( uxBitsWaitedFor & pxEventBits->uxEventBits ) == uxBitsWaitedFor )
+			{
+				/* All bits are set. */
+				xMatchFound = pdTRUE;
+			}
+			else
+			{
+				/* Need all bits to be set, but not all the bits were set. */
+			}
+
+			if( xMatchFound != pdFALSE )
+			{
+				/* The bits match.  Should the bits be cleared on exit? */
+				if( ( uxControlBits & eventCLEAR_EVENTS_ON_EXIT_BIT ) != ( EventBits_t ) 0 )
+				{
+					uxBitsToClear |= uxBitsWaitedFor;
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+
+				/* Store the actual event flag value in the task's event list
+				item before removing the task from the event list.  The
+				eventUNBLOCKED_DUE_TO_BIT_SET bit is set so the task knows
+				that is was unblocked due to its required bits matching, rather
+				than because it timed out. */
+				( void ) xTaskRemoveFromUnorderedEventList( pxListItem, pxEventBits->uxEventBits | eventUNBLOCKED_DUE_TO_BIT_SET );
+			}
+
+			/* Move onto the next list item.  Note pxListItem->pxNext is not
+			used here as the list item may have been removed from the event list
+			and inserted into the ready/pending reading list. */
+			pxListItem = pxNext;
+		}
+
+		/* Clear any bits that matched when the eventCLEAR_EVENTS_ON_EXIT_BIT
+		bit was set in the control word. */
+		pxEventBits->uxEventBits &= ~uxBitsToClear;
+	}
+	( void ) xTaskResumeAll();
+
+	return pxEventBits->uxEventBits;
+}
+/*-----------------------------------------------------------*/
+
+void vEventGroupDelete( EventGroupHandle_t xEventGroup )
+{
+EventGroup_t *pxEventBits = ( EventGroup_t * ) xEventGroup;
+const List_t *pxTasksWaitingForBits = &( pxEventBits->xTasksWaitingForBits );
+
+	vTaskSuspendAll();
+	{
+		traceEVENT_GROUP_DELETE( xEventGroup );
+
+		while( listCURRENT_LIST_LENGTH( pxTasksWaitingForBits ) > ( UBaseType_t ) 0 )
+		{
+			/* Unblock the task, returning 0 as the event list is being deleted
+			and	cannot therefore have any bits set. */
+			configASSERT( pxTasksWaitingForBits->xListEnd.pxNext != ( ListItem_t * ) &( pxTasksWaitingForBits->xListEnd ) );
+			( void ) xTaskRemoveFromUnorderedEventList( pxTasksWaitingForBits->xListEnd.pxNext, eventUNBLOCKED_DUE_TO_BIT_SET );
+		}
+
+		vPortFree( pxEventBits );
+	}
+	( void ) xTaskResumeAll();
+}
+/*-----------------------------------------------------------*/
+
+/* For internal use only - execute a 'set bits' command that was pended from
+an interrupt. */
+void vEventGroupSetBitsCallback( void *pvEventGroup, const uint32_t ulBitsToSet )
+{
+	( void ) xEventGroupSetBits( pvEventGroup, ( EventBits_t ) ulBitsToSet );
+}
+/*-----------------------------------------------------------*/
+
+/* For internal use only - execute a 'clear bits' command that was pended from
+an interrupt. */
+void vEventGroupClearBitsCallback( void *pvEventGroup, const uint32_t ulBitsToClear )
+{
+	( void ) xEventGroupClearBits( pvEventGroup, ( EventBits_t ) ulBitsToClear );
+}
+/*-----------------------------------------------------------*/
+
+static BaseType_t prvTestWaitCondition( const EventBits_t uxCurrentEventBits, const EventBits_t uxBitsToWaitFor, const BaseType_t xWaitForAllBits )
+{
+BaseType_t xWaitConditionMet = pdFALSE;
+
+	if( xWaitForAllBits == pdFALSE )
+	{
+		/* Task only has to wait for one bit within uxBitsToWaitFor to be
+		set.  Is one already set? */
+		if( ( uxCurrentEventBits & uxBitsToWaitFor ) != ( EventBits_t ) 0 )
+		{
+			xWaitConditionMet = pdTRUE;
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+	else
+	{
+		/* Task has to wait for all the bits in uxBitsToWaitFor to be set.
+		Are they set already? */
+		if( ( uxCurrentEventBits & uxBitsToWaitFor ) == uxBitsToWaitFor )
+		{
+			xWaitConditionMet = pdTRUE;
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+
+	return xWaitConditionMet;
+}
+/*-----------------------------------------------------------*/
+
+#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 1 ) )
+
+	BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken )
+	{
+	BaseType_t xReturn;
+
+		traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet );
+		xReturn = xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken );
+
+		return xReturn;
+	}
+
+#endif
+/*-----------------------------------------------------------*/
+
+#if (configUSE_TRACE_FACILITY == 1)
+
+	UBaseType_t uxEventGroupGetNumber( void* xEventGroup )
+	{
+	UBaseType_t xReturn;
+	EventGroup_t *pxEventBits = ( EventGroup_t * ) xEventGroup;
+
+		if( xEventGroup == NULL )
+		{
+			xReturn = 0;
+		}
+		else
+		{
+			xReturn = pxEventBits->uxEventGroupNumber;
+		}
+
+		return xReturn;
+	}
+
+#endif
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/include/FreeRTOS.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/include/FreeRTOS.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,800 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+#ifndef INC_FREERTOS_H
+#define INC_FREERTOS_H
+
+/*
+ * Include the generic headers required for the FreeRTOS port being used.
+ */
+#include <stddef.h>
+
+/*
+ * If stdint.h cannot be located then:
+ *   + If using GCC ensure the -nostdint options is *not* being used.
+ *   + Ensure the project's include path includes the directory in which your
+ *     compiler stores stdint.h.
+ *   + Set any compiler options necessary for it to support C99, as technically
+ *     stdint.h is only mandatory with C99 (FreeRTOS does not require C99 in any
+ *     other way).
+ *   + The FreeRTOS download includes a simple stdint.h definition that can be
+ *     used in cases where none is provided by the compiler.  The files only
+ *     contains the typedefs required to build FreeRTOS.  Read the instructions
+ *     in FreeRTOS/source/stdint.readme for more information.
+ */
+#include <stdint.h> /* READ COMMENT ABOVE. */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Application specific configuration options. */
+#include "FreeRTOSConfig.h"
+
+/* Basic FreeRTOS definitions. */
+#include "projdefs.h"
+
+/* Definitions specific to the port being used. */
+#include "portable.h"
+
+/*
+ * Check all the required application specific macros have been defined.
+ * These macros are application specific and (as downloaded) are defined
+ * within FreeRTOSConfig.h.
+ */
+
+#ifndef configMINIMAL_STACK_SIZE
+	#error Missing definition:  configMINIMAL_STACK_SIZE must be defined in FreeRTOSConfig.h.  configMINIMAL_STACK_SIZE defines the size (in words) of the stack allocated to the idle task.  Refer to the demo project provided for your port for a suitable value.
+#endif
+
+#ifndef configMAX_PRIORITIES
+	#error Missing definition:  configMAX_PRIORITIES must be defined in FreeRTOSConfig.h.  See the Configuration section of the FreeRTOS API documentation for details.
+#endif
+
+#ifndef configUSE_PREEMPTION
+	#error Missing definition:  configUSE_PREEMPTION must be defined in FreeRTOSConfig.h as either 1 or 0.  See the Configuration section of the FreeRTOS API documentation for details.
+#endif
+
+#ifndef configUSE_IDLE_HOOK
+	#error Missing definition:  configUSE_IDLE_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0.  See the Configuration section of the FreeRTOS API documentation for details.
+#endif
+
+#ifndef configUSE_TICK_HOOK
+	#error Missing definition:  configUSE_TICK_HOOK must be defined in FreeRTOSConfig.h as either 1 or 0.  See the Configuration section of the FreeRTOS API documentation for details.
+#endif
+
+#ifndef INCLUDE_vTaskPrioritySet
+	#error Missing definition:  INCLUDE_vTaskPrioritySet must be defined in FreeRTOSConfig.h as either 1 or 0.  See the Configuration section of the FreeRTOS API documentation for details.
+#endif
+
+#ifndef INCLUDE_uxTaskPriorityGet
+	#error Missing definition:  INCLUDE_uxTaskPriorityGet must be defined in FreeRTOSConfig.h as either 1 or 0.  See the Configuration section of the FreeRTOS API documentation for details.
+#endif
+
+#ifndef INCLUDE_vTaskDelete
+	#error Missing definition:  INCLUDE_vTaskDelete must be defined in FreeRTOSConfig.h as either 1 or 0.  See the Configuration section of the FreeRTOS API documentation for details.
+#endif
+
+#ifndef INCLUDE_vTaskSuspend
+	#error Missing definition:  INCLUDE_vTaskSuspend must be defined in FreeRTOSConfig.h as either 1 or 0.  See the Configuration section of the FreeRTOS API documentation for details.
+#endif
+
+#ifndef INCLUDE_vTaskDelayUntil
+	#error Missing definition:  INCLUDE_vTaskDelayUntil must be defined in FreeRTOSConfig.h as either 1 or 0.  See the Configuration section of the FreeRTOS API documentation for details.
+#endif
+
+#ifndef INCLUDE_vTaskDelay
+	#error Missing definition:  INCLUDE_vTaskDelay must be defined in FreeRTOSConfig.h as either 1 or 0.  See the Configuration section of the FreeRTOS API documentation for details.
+#endif
+
+#ifndef configUSE_16_BIT_TICKS
+	#error Missing definition:  configUSE_16_BIT_TICKS must be defined in FreeRTOSConfig.h as either 1 or 0.  See the Configuration section of the FreeRTOS API documentation for details.
+#endif
+
+#ifndef configMAX_PRIORITIES
+	#error configMAX_PRIORITIES must be defined to be greater than or equal to 1.
+#endif
+
+#ifndef configUSE_CO_ROUTINES
+	#define configUSE_CO_ROUTINES 0
+#endif
+
+#if configUSE_CO_ROUTINES != 0
+	#ifndef configMAX_CO_ROUTINE_PRIORITIES
+		#error configMAX_CO_ROUTINE_PRIORITIES must be greater than or equal to 1.
+	#endif
+#endif
+
+#ifndef INCLUDE_xTaskGetIdleTaskHandle
+	#define INCLUDE_xTaskGetIdleTaskHandle 0
+#endif
+
+#ifndef INCLUDE_xTimerGetTimerDaemonTaskHandle
+	#define INCLUDE_xTimerGetTimerDaemonTaskHandle 0
+#endif
+
+#ifndef INCLUDE_xQueueGetMutexHolder
+	#define INCLUDE_xQueueGetMutexHolder 0
+#endif
+
+#ifndef INCLUDE_xSemaphoreGetMutexHolder
+	#define INCLUDE_xSemaphoreGetMutexHolder INCLUDE_xQueueGetMutexHolder
+#endif
+
+#ifndef INCLUDE_pcTaskGetTaskName
+	#define INCLUDE_pcTaskGetTaskName 0
+#endif
+
+#ifndef configUSE_APPLICATION_TASK_TAG
+	#define configUSE_APPLICATION_TASK_TAG 0
+#endif
+
+#ifndef configNUM_THREAD_LOCAL_STORAGE_POINTERS
+	#define configNUM_THREAD_LOCAL_STORAGE_POINTERS 0
+#endif
+
+#ifndef INCLUDE_uxTaskGetStackHighWaterMark
+	#define INCLUDE_uxTaskGetStackHighWaterMark 0
+#endif
+
+#ifndef INCLUDE_eTaskGetState
+	#define INCLUDE_eTaskGetState 0
+#endif
+
+#ifndef configUSE_RECURSIVE_MUTEXES
+	#define configUSE_RECURSIVE_MUTEXES 0
+#endif
+
+#ifndef configUSE_MUTEXES
+	#define configUSE_MUTEXES 0
+#endif
+
+#ifndef configUSE_TIMERS
+	#define configUSE_TIMERS 0
+#endif
+
+#ifndef configUSE_COUNTING_SEMAPHORES
+	#define configUSE_COUNTING_SEMAPHORES 0
+#endif
+
+#ifndef configUSE_ALTERNATIVE_API
+	#define configUSE_ALTERNATIVE_API 0
+#endif
+
+#ifndef portCRITICAL_NESTING_IN_TCB
+	#define portCRITICAL_NESTING_IN_TCB 0
+#endif
+
+#ifndef configMAX_TASK_NAME_LEN
+	#define configMAX_TASK_NAME_LEN 16
+#endif
+
+#ifndef configIDLE_SHOULD_YIELD
+	#define configIDLE_SHOULD_YIELD		1
+#endif
+
+#if configMAX_TASK_NAME_LEN < 1
+	#error configMAX_TASK_NAME_LEN must be set to a minimum of 1 in FreeRTOSConfig.h
+#endif
+
+#ifndef INCLUDE_xTaskResumeFromISR
+	#define INCLUDE_xTaskResumeFromISR 1
+#endif
+
+#ifndef INCLUDE_xEventGroupSetBitFromISR
+	#define INCLUDE_xEventGroupSetBitFromISR 0
+#endif
+
+#ifndef INCLUDE_xTimerPendFunctionCall
+	#define INCLUDE_xTimerPendFunctionCall 0
+#endif
+
+#ifndef configASSERT
+	#define configASSERT( x )
+	#define configASSERT_DEFINED 0
+#else
+	#define configASSERT_DEFINED 1
+#endif
+
+/* The timers module relies on xTaskGetSchedulerState(). */
+#if configUSE_TIMERS == 1
+
+	#ifndef configTIMER_TASK_PRIORITY
+		#error If configUSE_TIMERS is set to 1 then configTIMER_TASK_PRIORITY must also be defined.
+	#endif /* configTIMER_TASK_PRIORITY */
+
+	#ifndef configTIMER_QUEUE_LENGTH
+		#error If configUSE_TIMERS is set to 1 then configTIMER_QUEUE_LENGTH must also be defined.
+	#endif /* configTIMER_QUEUE_LENGTH */
+
+	#ifndef configTIMER_TASK_STACK_DEPTH
+		#error If configUSE_TIMERS is set to 1 then configTIMER_TASK_STACK_DEPTH must also be defined.
+	#endif /* configTIMER_TASK_STACK_DEPTH */
+
+#endif /* configUSE_TIMERS */
+
+#ifndef INCLUDE_xTaskGetSchedulerState
+	#define INCLUDE_xTaskGetSchedulerState 0
+#endif
+
+#ifndef INCLUDE_xTaskGetCurrentTaskHandle
+	#define INCLUDE_xTaskGetCurrentTaskHandle 0
+#endif
+
+
+#ifndef portSET_INTERRUPT_MASK_FROM_ISR
+	#define portSET_INTERRUPT_MASK_FROM_ISR() 0
+#endif
+
+#ifndef portCLEAR_INTERRUPT_MASK_FROM_ISR
+	#define portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedStatusValue ) ( void ) uxSavedStatusValue
+#endif
+
+#ifndef portCLEAN_UP_TCB
+	#define portCLEAN_UP_TCB( pxTCB ) ( void ) pxTCB
+#endif
+
+#ifndef portPRE_TASK_DELETE_HOOK
+	#define portPRE_TASK_DELETE_HOOK( pvTaskToDelete, pxYieldPending )
+#endif
+
+#ifndef portSETUP_TCB
+	#define portSETUP_TCB( pxTCB ) ( void ) pxTCB
+#endif
+
+#ifndef configQUEUE_REGISTRY_SIZE
+	#define configQUEUE_REGISTRY_SIZE 0U
+#endif
+
+#if ( configQUEUE_REGISTRY_SIZE < 1 )
+	#define vQueueAddToRegistry( xQueue, pcName )
+	#define vQueueUnregisterQueue( xQueue )
+#endif
+
+#ifndef portPOINTER_SIZE_TYPE
+	#define portPOINTER_SIZE_TYPE uint32_t
+#endif
+
+/* Remove any unused trace macros. */
+#ifndef traceSTART
+	/* Used to perform any necessary initialisation - for example, open a file
+	into which trace is to be written. */
+	#define traceSTART()
+#endif
+
+#ifndef traceEND
+	/* Use to close a trace, for example close a file into which trace has been
+	written. */
+	#define traceEND()
+#endif
+
+#ifndef traceTASK_SWITCHED_IN
+	/* Called after a task has been selected to run.  pxCurrentTCB holds a pointer
+	to the task control block of the selected task. */
+	#define traceTASK_SWITCHED_IN()
+#endif
+
+#ifndef traceINCREASE_TICK_COUNT
+	/* Called before stepping the tick count after waking from tickless idle
+	sleep. */
+	#define traceINCREASE_TICK_COUNT( x )
+#endif
+
+#ifndef traceLOW_POWER_IDLE_BEGIN
+	/* Called immediately before entering tickless idle. */
+	#define traceLOW_POWER_IDLE_BEGIN()
+#endif
+
+#ifndef	traceLOW_POWER_IDLE_END
+	/* Called when returning to the Idle task after a tickless idle. */
+	#define traceLOW_POWER_IDLE_END()
+#endif
+
+#ifndef traceTASK_SWITCHED_OUT
+	/* Called before a task has been selected to run.  pxCurrentTCB holds a pointer
+	to the task control block of the task being switched out. */
+	#define traceTASK_SWITCHED_OUT()
+#endif
+
+#ifndef traceTASK_PRIORITY_INHERIT
+	/* Called when a task attempts to take a mutex that is already held by a
+	lower priority task.  pxTCBOfMutexHolder is a pointer to the TCB of the task
+	that holds the mutex.  uxInheritedPriority is the priority the mutex holder
+	will inherit (the priority of the task that is attempting to obtain the
+	muted. */
+	#define traceTASK_PRIORITY_INHERIT( pxTCBOfMutexHolder, uxInheritedPriority )
+#endif
+
+#ifndef traceTASK_PRIORITY_DISINHERIT
+	/* Called when a task releases a mutex, the holding of which had resulted in
+	the task inheriting the priority of a higher priority task.
+	pxTCBOfMutexHolder is a pointer to the TCB of the task that is releasing the
+	mutex.  uxOriginalPriority is the task's configured (base) priority. */
+	#define traceTASK_PRIORITY_DISINHERIT( pxTCBOfMutexHolder, uxOriginalPriority )
+#endif
+
+#ifndef traceBLOCKING_ON_QUEUE_RECEIVE
+	/* Task is about to block because it cannot read from a
+	queue/mutex/semaphore.  pxQueue is a pointer to the queue/mutex/semaphore
+	upon which the read was attempted.  pxCurrentTCB points to the TCB of the
+	task that attempted the read. */
+	#define traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue )
+#endif
+
+#ifndef traceBLOCKING_ON_QUEUE_SEND
+	/* Task is about to block because it cannot write to a
+	queue/mutex/semaphore.  pxQueue is a pointer to the queue/mutex/semaphore
+	upon which the write was attempted.  pxCurrentTCB points to the TCB of the
+	task that attempted the write. */
+	#define traceBLOCKING_ON_QUEUE_SEND( pxQueue )
+#endif
+
+#ifndef configCHECK_FOR_STACK_OVERFLOW
+	#define configCHECK_FOR_STACK_OVERFLOW 0
+#endif
+
+/* The following event macros are embedded in the kernel API calls. */
+
+#ifndef traceMOVED_TASK_TO_READY_STATE
+	#define traceMOVED_TASK_TO_READY_STATE( pxTCB )
+#endif
+
+#ifndef traceQUEUE_CREATE
+	#define traceQUEUE_CREATE( pxNewQueue )
+#endif
+
+#ifndef traceQUEUE_CREATE_FAILED
+	#define traceQUEUE_CREATE_FAILED( ucQueueType )
+#endif
+
+#ifndef traceCREATE_MUTEX
+	#define traceCREATE_MUTEX( pxNewQueue )
+#endif
+
+#ifndef traceCREATE_MUTEX_FAILED
+	#define traceCREATE_MUTEX_FAILED()
+#endif
+
+#ifndef traceGIVE_MUTEX_RECURSIVE
+	#define traceGIVE_MUTEX_RECURSIVE( pxMutex )
+#endif
+
+#ifndef traceGIVE_MUTEX_RECURSIVE_FAILED
+	#define traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex )
+#endif
+
+#ifndef traceTAKE_MUTEX_RECURSIVE
+	#define traceTAKE_MUTEX_RECURSIVE( pxMutex )
+#endif
+
+#ifndef traceTAKE_MUTEX_RECURSIVE_FAILED
+	#define traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex )
+#endif
+
+#ifndef traceCREATE_COUNTING_SEMAPHORE
+	#define traceCREATE_COUNTING_SEMAPHORE()
+#endif
+
+#ifndef traceCREATE_COUNTING_SEMAPHORE_FAILED
+	#define traceCREATE_COUNTING_SEMAPHORE_FAILED()
+#endif
+
+#ifndef traceQUEUE_SEND
+	#define traceQUEUE_SEND( pxQueue )
+#endif
+
+#ifndef traceQUEUE_SEND_FAILED
+	#define traceQUEUE_SEND_FAILED( pxQueue )
+#endif
+
+#ifndef traceQUEUE_RECEIVE
+	#define traceQUEUE_RECEIVE( pxQueue )
+#endif
+
+#ifndef traceQUEUE_PEEK
+	#define traceQUEUE_PEEK( pxQueue )
+#endif
+
+#ifndef traceQUEUE_PEEK_FROM_ISR
+	#define traceQUEUE_PEEK_FROM_ISR( pxQueue )
+#endif
+
+#ifndef traceQUEUE_RECEIVE_FAILED
+	#define traceQUEUE_RECEIVE_FAILED( pxQueue )
+#endif
+
+#ifndef traceQUEUE_SEND_FROM_ISR
+	#define traceQUEUE_SEND_FROM_ISR( pxQueue )
+#endif
+
+#ifndef traceQUEUE_SEND_FROM_ISR_FAILED
+	#define traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue )
+#endif
+
+#ifndef traceQUEUE_RECEIVE_FROM_ISR
+	#define traceQUEUE_RECEIVE_FROM_ISR( pxQueue )
+#endif
+
+#ifndef traceQUEUE_RECEIVE_FROM_ISR_FAILED
+	#define traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue )
+#endif
+
+#ifndef traceQUEUE_PEEK_FROM_ISR_FAILED
+	#define traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue )
+#endif
+
+#ifndef traceQUEUE_DELETE
+	#define traceQUEUE_DELETE( pxQueue )
+#endif
+
+#ifndef traceTASK_CREATE
+	#define traceTASK_CREATE( pxNewTCB )
+#endif
+
+#ifndef traceTASK_CREATE_FAILED
+	#define traceTASK_CREATE_FAILED()
+#endif
+
+#ifndef traceTASK_DELETE
+	#define traceTASK_DELETE( pxTaskToDelete )
+#endif
+
+#ifndef traceTASK_DELAY_UNTIL
+	#define traceTASK_DELAY_UNTIL()
+#endif
+
+#ifndef traceTASK_DELAY
+	#define traceTASK_DELAY()
+#endif
+
+#ifndef traceTASK_PRIORITY_SET
+	#define traceTASK_PRIORITY_SET( pxTask, uxNewPriority )
+#endif
+
+#ifndef traceTASK_SUSPEND
+	#define traceTASK_SUSPEND( pxTaskToSuspend )
+#endif
+
+#ifndef traceTASK_RESUME
+	#define traceTASK_RESUME( pxTaskToResume )
+#endif
+
+#ifndef traceTASK_RESUME_FROM_ISR
+	#define traceTASK_RESUME_FROM_ISR( pxTaskToResume )
+#endif
+
+#ifndef traceTASK_INCREMENT_TICK
+	#define traceTASK_INCREMENT_TICK( xTickCount )
+#endif
+
+#ifndef traceTIMER_CREATE
+	#define traceTIMER_CREATE( pxNewTimer )
+#endif
+
+#ifndef traceTIMER_CREATE_FAILED
+	#define traceTIMER_CREATE_FAILED()
+#endif
+
+#ifndef traceTIMER_COMMAND_SEND
+	#define traceTIMER_COMMAND_SEND( xTimer, xMessageID, xMessageValueValue, xReturn )
+#endif
+
+#ifndef traceTIMER_EXPIRED
+	#define traceTIMER_EXPIRED( pxTimer )
+#endif
+
+#ifndef traceTIMER_COMMAND_RECEIVED
+	#define traceTIMER_COMMAND_RECEIVED( pxTimer, xMessageID, xMessageValue )
+#endif
+
+#ifndef traceMALLOC
+    #define traceMALLOC( pvAddress, uiSize )
+#endif
+
+#ifndef traceFREE
+    #define traceFREE( pvAddress, uiSize )
+#endif
+
+#ifndef traceEVENT_GROUP_CREATE
+	#define traceEVENT_GROUP_CREATE( xEventGroup )
+#endif
+
+#ifndef traceEVENT_GROUP_CREATE_FAILED
+	#define traceEVENT_GROUP_CREATE_FAILED()
+#endif
+
+#ifndef traceEVENT_GROUP_SYNC_BLOCK
+	#define traceEVENT_GROUP_SYNC_BLOCK( xEventGroup, uxBitsToSet, uxBitsToWaitFor )
+#endif
+
+#ifndef traceEVENT_GROUP_SYNC_END
+	#define traceEVENT_GROUP_SYNC_END( xEventGroup, uxBitsToSet, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred
+#endif
+
+#ifndef traceEVENT_GROUP_WAIT_BITS_BLOCK
+	#define traceEVENT_GROUP_WAIT_BITS_BLOCK( xEventGroup, uxBitsToWaitFor )
+#endif
+
+#ifndef traceEVENT_GROUP_WAIT_BITS_END
+	#define traceEVENT_GROUP_WAIT_BITS_END( xEventGroup, uxBitsToWaitFor, xTimeoutOccurred ) ( void ) xTimeoutOccurred
+#endif
+
+#ifndef traceEVENT_GROUP_CLEAR_BITS
+	#define traceEVENT_GROUP_CLEAR_BITS( xEventGroup, uxBitsToClear )
+#endif
+
+#ifndef traceEVENT_GROUP_CLEAR_BITS_FROM_ISR
+	#define traceEVENT_GROUP_CLEAR_BITS_FROM_ISR( xEventGroup, uxBitsToClear )
+#endif
+
+#ifndef traceEVENT_GROUP_SET_BITS
+	#define traceEVENT_GROUP_SET_BITS( xEventGroup, uxBitsToSet )
+#endif
+
+#ifndef traceEVENT_GROUP_SET_BITS_FROM_ISR
+	#define traceEVENT_GROUP_SET_BITS_FROM_ISR( xEventGroup, uxBitsToSet )
+#endif
+
+#ifndef traceEVENT_GROUP_DELETE
+	#define traceEVENT_GROUP_DELETE( xEventGroup )
+#endif
+
+#ifndef tracePEND_FUNC_CALL
+	#define tracePEND_FUNC_CALL(xFunctionToPend, pvParameter1, ulParameter2, ret)
+#endif
+
+#ifndef tracePEND_FUNC_CALL_FROM_ISR
+	#define tracePEND_FUNC_CALL_FROM_ISR(xFunctionToPend, pvParameter1, ulParameter2, ret)
+#endif
+
+#ifndef traceQUEUE_REGISTRY_ADD
+	#define traceQUEUE_REGISTRY_ADD(xQueue, pcQueueName)
+#endif
+
+#ifndef configGENERATE_RUN_TIME_STATS
+	#define configGENERATE_RUN_TIME_STATS 0
+#endif
+
+#if ( configGENERATE_RUN_TIME_STATS == 1 )
+
+	#ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS
+		#error If configGENERATE_RUN_TIME_STATS is defined then portCONFIGURE_TIMER_FOR_RUN_TIME_STATS must also be defined.  portCONFIGURE_TIMER_FOR_RUN_TIME_STATS should call a port layer function to setup a peripheral timer/counter that can then be used as the run time counter time base.
+	#endif /* portCONFIGURE_TIMER_FOR_RUN_TIME_STATS */
+
+	#ifndef portGET_RUN_TIME_COUNTER_VALUE
+		#ifndef portALT_GET_RUN_TIME_COUNTER_VALUE
+			#error If configGENERATE_RUN_TIME_STATS is defined then either portGET_RUN_TIME_COUNTER_VALUE or portALT_GET_RUN_TIME_COUNTER_VALUE must also be defined.  See the examples provided and the FreeRTOS web site for more information.
+		#endif /* portALT_GET_RUN_TIME_COUNTER_VALUE */
+	#endif /* portGET_RUN_TIME_COUNTER_VALUE */
+
+#endif /* configGENERATE_RUN_TIME_STATS */
+
+#ifndef portCONFIGURE_TIMER_FOR_RUN_TIME_STATS
+	#define portCONFIGURE_TIMER_FOR_RUN_TIME_STATS()
+#endif
+
+#ifndef configUSE_MALLOC_FAILED_HOOK
+	#define configUSE_MALLOC_FAILED_HOOK 0
+#endif
+
+#ifndef portPRIVILEGE_BIT
+	#define portPRIVILEGE_BIT ( ( UBaseType_t ) 0x00 )
+#endif
+
+#ifndef portYIELD_WITHIN_API
+	#define portYIELD_WITHIN_API portYIELD
+#endif
+
+#ifndef pvPortMallocAligned
+	#define pvPortMallocAligned( x, puxStackBuffer ) ( ( ( puxStackBuffer ) == NULL ) ? ( pvPortMalloc( ( x ) ) ) : ( puxStackBuffer ) )
+#endif
+
+#ifndef vPortFreeAligned
+	#define vPortFreeAligned( pvBlockToFree ) vPortFree( pvBlockToFree )
+#endif
+
+#ifndef portSUPPRESS_TICKS_AND_SLEEP
+	#define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime )
+#endif
+
+#ifndef configEXPECTED_IDLE_TIME_BEFORE_SLEEP
+	#define configEXPECTED_IDLE_TIME_BEFORE_SLEEP 2
+#endif
+
+#if configEXPECTED_IDLE_TIME_BEFORE_SLEEP < 2
+	#error configEXPECTED_IDLE_TIME_BEFORE_SLEEP must not be less than 2
+#endif
+
+#ifndef configUSE_TICKLESS_IDLE
+	#define configUSE_TICKLESS_IDLE 0
+#endif
+
+#ifndef configPRE_SLEEP_PROCESSING
+	#define configPRE_SLEEP_PROCESSING( x )
+#endif
+
+#ifndef configPOST_SLEEP_PROCESSING
+	#define configPOST_SLEEP_PROCESSING( x )
+#endif
+
+#ifndef configUSE_QUEUE_SETS
+	#define configUSE_QUEUE_SETS 0
+#endif
+
+#ifndef portTASK_USES_FLOATING_POINT
+	#define portTASK_USES_FLOATING_POINT()
+#endif
+
+#ifndef configUSE_TIME_SLICING
+	#define configUSE_TIME_SLICING 1
+#endif
+
+#ifndef configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS
+	#define configINCLUDE_APPLICATION_DEFINED_PRIVILEGED_FUNCTIONS 0
+#endif
+
+#ifndef configUSE_NEWLIB_REENTRANT
+	#define configUSE_NEWLIB_REENTRANT 0
+#endif
+
+#ifndef configUSE_STATS_FORMATTING_FUNCTIONS
+	#define configUSE_STATS_FORMATTING_FUNCTIONS 0
+#endif
+
+#ifndef portASSERT_IF_INTERRUPT_PRIORITY_INVALID
+	#define portASSERT_IF_INTERRUPT_PRIORITY_INVALID()
+#endif
+
+#ifndef configUSE_TRACE_FACILITY
+	#define configUSE_TRACE_FACILITY 0
+#endif
+
+#ifndef mtCOVERAGE_TEST_MARKER
+	#define mtCOVERAGE_TEST_MARKER()
+#endif
+
+#ifndef mtCOVERAGE_TEST_DELAY
+	#define mtCOVERAGE_TEST_DELAY()
+#endif
+
+#ifndef portASSERT_IF_IN_ISR
+	#define portASSERT_IF_IN_ISR()
+#endif
+
+#ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION
+	#define configUSE_PORT_OPTIMISED_TASK_SELECTION 0
+#endif
+
+#ifndef configAPPLICATION_ALLOCATED_HEAP
+	#define configAPPLICATION_ALLOCATED_HEAP 0
+#endif
+
+#ifndef configUSE_TASK_NOTIFICATIONS
+	#define configUSE_TASK_NOTIFICATIONS 1
+#endif
+
+#ifndef portTICK_TYPE_IS_ATOMIC
+	#define portTICK_TYPE_IS_ATOMIC 0
+#endif
+
+#if( portTICK_TYPE_IS_ATOMIC == 0 )
+	/* Either variables of tick type cannot be read atomically, or
+	portTICK_TYPE_IS_ATOMIC was not set - map the critical sections used when
+	the tick count is returned to the standard critical section macros. */
+	#define portTICK_TYPE_ENTER_CRITICAL() portENTER_CRITICAL()
+	#define portTICK_TYPE_EXIT_CRITICAL() portEXIT_CRITICAL()
+	#define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() portSET_INTERRUPT_MASK_FROM_ISR()
+	#define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) portCLEAR_INTERRUPT_MASK_FROM_ISR( ( x ) )
+#else
+	/* The tick type can be read atomically, so critical sections used when the
+	tick count is returned can be defined away. */
+	#define portTICK_TYPE_ENTER_CRITICAL()
+	#define portTICK_TYPE_EXIT_CRITICAL()
+	#define portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR() 0
+	#define portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( x ) ( void ) x
+#endif
+
+/* Definitions to allow backward compatibility with FreeRTOS versions prior to
+V8 if desired. */
+#ifndef configENABLE_BACKWARD_COMPATIBILITY
+	#define configENABLE_BACKWARD_COMPATIBILITY 1
+#endif
+
+#if configENABLE_BACKWARD_COMPATIBILITY == 1
+	#define eTaskStateGet eTaskGetState
+	#define portTickType TickType_t
+	#define xTaskHandle TaskHandle_t
+	#define xQueueHandle QueueHandle_t
+	#define xSemaphoreHandle SemaphoreHandle_t
+	#define xQueueSetHandle QueueSetHandle_t
+	#define xQueueSetMemberHandle QueueSetMemberHandle_t
+	#define xTimeOutType TimeOut_t
+	#define xMemoryRegion MemoryRegion_t
+	#define xTaskParameters TaskParameters_t
+	#define xTaskStatusType	TaskStatus_t
+	#define xTimerHandle TimerHandle_t
+	#define xCoRoutineHandle CoRoutineHandle_t
+	#define pdTASK_HOOK_CODE TaskHookFunction_t
+	#define portTICK_RATE_MS portTICK_PERIOD_MS
+
+	/* Backward compatibility within the scheduler code only - these definitions
+	are not really required but are included for completeness. */
+	#define tmrTIMER_CALLBACK TimerCallbackFunction_t
+	#define pdTASK_CODE TaskFunction_t
+	#define xListItem ListItem_t
+	#define xList List_t
+#endif /* configENABLE_BACKWARD_COMPATIBILITY */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* INC_FREERTOS_H */
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/include/StackMacros.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/include/StackMacros.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,185 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+#ifndef STACK_MACROS_H
+#define STACK_MACROS_H
+
+/*
+ * Call the stack overflow hook function if the stack of the task being swapped
+ * out is currently overflowed, or looks like it might have overflowed in the
+ * past.
+ *
+ * Setting configCHECK_FOR_STACK_OVERFLOW to 1 will cause the macro to check
+ * the current stack state only - comparing the current top of stack value to
+ * the stack limit.  Setting configCHECK_FOR_STACK_OVERFLOW to greater than 1
+ * will also cause the last few stack bytes to be checked to ensure the value
+ * to which the bytes were set when the task was created have not been
+ * overwritten.  Note this second test does not guarantee that an overflowed
+ * stack will always be recognised.
+ */
+
+/*-----------------------------------------------------------*/
+
+#if( configCHECK_FOR_STACK_OVERFLOW == 0 )
+
+	/* FreeRTOSConfig.h is not set to check for stack overflows. */
+	#define taskFIRST_CHECK_FOR_STACK_OVERFLOW()
+	#define taskSECOND_CHECK_FOR_STACK_OVERFLOW()
+
+#endif /* configCHECK_FOR_STACK_OVERFLOW == 0 */
+/*-----------------------------------------------------------*/
+
+#if( configCHECK_FOR_STACK_OVERFLOW == 1 )
+
+	/* FreeRTOSConfig.h is only set to use the first method of
+	overflow checking. */
+	#define taskSECOND_CHECK_FOR_STACK_OVERFLOW()
+
+#endif
+/*-----------------------------------------------------------*/
+
+#if( ( configCHECK_FOR_STACK_OVERFLOW > 0 ) && ( portSTACK_GROWTH < 0 ) )
+
+	/* Only the current stack state is to be checked. */
+	#define taskFIRST_CHECK_FOR_STACK_OVERFLOW()														\
+	{																									\
+		/* Is the currently saved stack pointer within the stack limit? */								\
+		if( pxCurrentTCB->pxTopOfStack <= pxCurrentTCB->pxStack )										\
+		{																								\
+			vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );	\
+		}																								\
+	}
+
+#endif /* configCHECK_FOR_STACK_OVERFLOW > 0 */
+/*-----------------------------------------------------------*/
+
+#if( ( configCHECK_FOR_STACK_OVERFLOW > 0 ) && ( portSTACK_GROWTH > 0 ) )
+
+	/* Only the current stack state is to be checked. */
+	#define taskFIRST_CHECK_FOR_STACK_OVERFLOW()														\
+	{																									\
+																										\
+		/* Is the currently saved stack pointer within the stack limit? */								\
+		if( pxCurrentTCB->pxTopOfStack >= pxCurrentTCB->pxEndOfStack )									\
+		{																								\
+			vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );	\
+		}																								\
+	}
+
+#endif /* configCHECK_FOR_STACK_OVERFLOW == 1 */
+/*-----------------------------------------------------------*/
+
+#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH < 0 ) )
+
+	#define taskSECOND_CHECK_FOR_STACK_OVERFLOW()																						\
+	{																																	\
+	static const uint8_t ucExpectedStackBytes[] = {	tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,		\
+													tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,		\
+													tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,		\
+													tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,		\
+													tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE };	\
+																																		\
+																																		\
+		/* Has the extremity of the task stack ever been written over? */																\
+		if( memcmp( ( void * ) pxCurrentTCB->pxStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 )			\
+		{																																\
+			vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );									\
+		}																																\
+	}
+
+#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */
+/*-----------------------------------------------------------*/
+
+#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) && ( portSTACK_GROWTH > 0 ) )
+
+	#define taskSECOND_CHECK_FOR_STACK_OVERFLOW()																						\
+	{																																	\
+	int8_t *pcEndOfStack = ( int8_t * ) pxCurrentTCB->pxEndOfStack;																		\
+	static const uint8_t ucExpectedStackBytes[] = {	tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,		\
+													tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,		\
+													tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,		\
+													tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE,		\
+													tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE, tskSTACK_FILL_BYTE };	\
+																																		\
+																																		\
+		pcEndOfStack -= sizeof( ucExpectedStackBytes );																					\
+																																		\
+		/* Has the extremity of the task stack ever been written over? */																\
+		if( memcmp( ( void * ) pcEndOfStack, ( void * ) ucExpectedStackBytes, sizeof( ucExpectedStackBytes ) ) != 0 )					\
+		{																																\
+			vApplicationStackOverflowHook( ( TaskHandle_t ) pxCurrentTCB, pxCurrentTCB->pcTaskName );									\
+		}																																\
+	}
+
+#endif /* #if( configCHECK_FOR_STACK_OVERFLOW > 1 ) */
+/*-----------------------------------------------------------*/
+
+#endif /* STACK_MACROS_H */
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/include/croutine.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/include/croutine.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,763 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+#ifndef CO_ROUTINE_H
+#define CO_ROUTINE_H
+
+#ifndef INC_FREERTOS_H
+	#error "include FreeRTOS.h must appear in source files before include croutine.h"
+#endif
+
+#include "list.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Used to hide the implementation of the co-routine control block.  The
+control block structure however has to be included in the header due to
+the macro implementation of the co-routine functionality. */
+typedef void * CoRoutineHandle_t;
+
+/* Defines the prototype to which co-routine functions must conform. */
+typedef void (*crCOROUTINE_CODE)( CoRoutineHandle_t, UBaseType_t );
+
+typedef struct corCoRoutineControlBlock
+{
+	crCOROUTINE_CODE 	pxCoRoutineFunction;
+	ListItem_t			xGenericListItem;	/*< List item used to place the CRCB in ready and blocked queues. */
+	ListItem_t			xEventListItem;		/*< List item used to place the CRCB in event lists. */
+	UBaseType_t 		uxPriority;			/*< The priority of the co-routine in relation to other co-routines. */
+	UBaseType_t 		uxIndex;			/*< Used to distinguish between co-routines when multiple co-routines use the same co-routine function. */
+	uint16_t 			uxState;			/*< Used internally by the co-routine implementation. */
+} CRCB_t; /* Co-routine control block.  Note must be identical in size down to uxPriority with TCB_t. */
+
+/**
+ * croutine. h
+ *<pre>
+ BaseType_t xCoRoutineCreate(
+                                 crCOROUTINE_CODE pxCoRoutineCode,
+                                 UBaseType_t uxPriority,
+                                 UBaseType_t uxIndex
+                               );</pre>
+ *
+ * Create a new co-routine and add it to the list of co-routines that are
+ * ready to run.
+ *
+ * @param pxCoRoutineCode Pointer to the co-routine function.  Co-routine
+ * functions require special syntax - see the co-routine section of the WEB
+ * documentation for more information.
+ *
+ * @param uxPriority The priority with respect to other co-routines at which
+ *  the co-routine will run.
+ *
+ * @param uxIndex Used to distinguish between different co-routines that
+ * execute the same function.  See the example below and the co-routine section
+ * of the WEB documentation for further information.
+ *
+ * @return pdPASS if the co-routine was successfully created and added to a ready
+ * list, otherwise an error code defined with ProjDefs.h.
+ *
+ * Example usage:
+   <pre>
+ // Co-routine to be created.
+ void vFlashCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // Variables in co-routines must be declared static if they must maintain value across a blocking call.
+ // This may not be necessary for const variables.
+ static const char cLedToFlash[ 2 ] = { 5, 6 };
+ static const TickType_t uxFlashRates[ 2 ] = { 200, 400 };
+
+     // Must start every co-routine with a call to crSTART();
+     crSTART( xHandle );
+
+     for( ;; )
+     {
+         // This co-routine just delays for a fixed period, then toggles
+         // an LED.  Two co-routines are created using this function, so
+         // the uxIndex parameter is used to tell the co-routine which
+         // LED to flash and how int32_t to delay.  This assumes xQueue has
+         // already been created.
+         vParTestToggleLED( cLedToFlash[ uxIndex ] );
+         crDELAY( xHandle, uxFlashRates[ uxIndex ] );
+     }
+
+     // Must end every co-routine with a call to crEND();
+     crEND();
+ }
+
+ // Function that creates two co-routines.
+ void vOtherFunction( void )
+ {
+ uint8_t ucParameterToPass;
+ TaskHandle_t xHandle;
+
+     // Create two co-routines at priority 0.  The first is given index 0
+     // so (from the code above) toggles LED 5 every 200 ticks.  The second
+     // is given index 1 so toggles LED 6 every 400 ticks.
+     for( uxIndex = 0; uxIndex < 2; uxIndex++ )
+     {
+         xCoRoutineCreate( vFlashCoRoutine, 0, uxIndex );
+     }
+ }
+   </pre>
+ * \defgroup xCoRoutineCreate xCoRoutineCreate
+ * \ingroup Tasks
+ */
+BaseType_t xCoRoutineCreate( crCOROUTINE_CODE pxCoRoutineCode, UBaseType_t uxPriority, UBaseType_t uxIndex );
+
+
+/**
+ * croutine. h
+ *<pre>
+ void vCoRoutineSchedule( void );</pre>
+ *
+ * Run a co-routine.
+ *
+ * vCoRoutineSchedule() executes the highest priority co-routine that is able
+ * to run.  The co-routine will execute until it either blocks, yields or is
+ * preempted by a task.  Co-routines execute cooperatively so one
+ * co-routine cannot be preempted by another, but can be preempted by a task.
+ *
+ * If an application comprises of both tasks and co-routines then
+ * vCoRoutineSchedule should be called from the idle task (in an idle task
+ * hook).
+ *
+ * Example usage:
+   <pre>
+ // This idle task hook will schedule a co-routine each time it is called.
+ // The rest of the idle task will execute between co-routine calls.
+ void vApplicationIdleHook( void )
+ {
+	vCoRoutineSchedule();
+ }
+
+ // Alternatively, if you do not require any other part of the idle task to
+ // execute, the idle task hook can call vCoRoutineScheduler() within an
+ // infinite loop.
+ void vApplicationIdleHook( void )
+ {
+    for( ;; )
+    {
+        vCoRoutineSchedule();
+    }
+ }
+ </pre>
+ * \defgroup vCoRoutineSchedule vCoRoutineSchedule
+ * \ingroup Tasks
+ */
+void vCoRoutineSchedule( void );
+
+/**
+ * croutine. h
+ * <pre>
+ crSTART( CoRoutineHandle_t xHandle );</pre>
+ *
+ * This macro MUST always be called at the start of a co-routine function.
+ *
+ * Example usage:
+   <pre>
+ // Co-routine to be created.
+ void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // Variables in co-routines must be declared static if they must maintain value across a blocking call.
+ static int32_t ulAVariable;
+
+     // Must start every co-routine with a call to crSTART();
+     crSTART( xHandle );
+
+     for( ;; )
+     {
+          // Co-routine functionality goes here.
+     }
+
+     // Must end every co-routine with a call to crEND();
+     crEND();
+ }</pre>
+ * \defgroup crSTART crSTART
+ * \ingroup Tasks
+ */
+#define crSTART( pxCRCB ) switch( ( ( CRCB_t * )( pxCRCB ) )->uxState ) { case 0:
+
+/**
+ * croutine. h
+ * <pre>
+ crEND();</pre>
+ *
+ * This macro MUST always be called at the end of a co-routine function.
+ *
+ * Example usage:
+   <pre>
+ // Co-routine to be created.
+ void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // Variables in co-routines must be declared static if they must maintain value across a blocking call.
+ static int32_t ulAVariable;
+
+     // Must start every co-routine with a call to crSTART();
+     crSTART( xHandle );
+
+     for( ;; )
+     {
+          // Co-routine functionality goes here.
+     }
+
+     // Must end every co-routine with a call to crEND();
+     crEND();
+ }</pre>
+ * \defgroup crSTART crSTART
+ * \ingroup Tasks
+ */
+#define crEND() }
+
+/*
+ * These macros are intended for internal use by the co-routine implementation
+ * only.  The macros should not be used directly by application writers.
+ */
+#define crSET_STATE0( xHandle ) ( ( CRCB_t * )( xHandle ) )->uxState = (__LINE__ * 2); return; case (__LINE__ * 2):
+#define crSET_STATE1( xHandle ) ( ( CRCB_t * )( xHandle ) )->uxState = ((__LINE__ * 2)+1); return; case ((__LINE__ * 2)+1):
+
+/**
+ * croutine. h
+ *<pre>
+ crDELAY( CoRoutineHandle_t xHandle, TickType_t xTicksToDelay );</pre>
+ *
+ * Delay a co-routine for a fixed period of time.
+ *
+ * crDELAY can only be called from the co-routine function itself - not
+ * from within a function called by the co-routine function.  This is because
+ * co-routines do not maintain their own stack.
+ *
+ * @param xHandle The handle of the co-routine to delay.  This is the xHandle
+ * parameter of the co-routine function.
+ *
+ * @param xTickToDelay The number of ticks that the co-routine should delay
+ * for.  The actual amount of time this equates to is defined by
+ * configTICK_RATE_HZ (set in FreeRTOSConfig.h).  The constant portTICK_PERIOD_MS
+ * can be used to convert ticks to milliseconds.
+ *
+ * Example usage:
+   <pre>
+ // Co-routine to be created.
+ void vACoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // Variables in co-routines must be declared static if they must maintain value across a blocking call.
+ // This may not be necessary for const variables.
+ // We are to delay for 200ms.
+ static const xTickType xDelayTime = 200 / portTICK_PERIOD_MS;
+
+     // Must start every co-routine with a call to crSTART();
+     crSTART( xHandle );
+
+     for( ;; )
+     {
+        // Delay for 200ms.
+        crDELAY( xHandle, xDelayTime );
+
+        // Do something here.
+     }
+
+     // Must end every co-routine with a call to crEND();
+     crEND();
+ }</pre>
+ * \defgroup crDELAY crDELAY
+ * \ingroup Tasks
+ */
+#define crDELAY( xHandle, xTicksToDelay )												\
+	if( ( xTicksToDelay ) > 0 )															\
+	{																					\
+		vCoRoutineAddToDelayedList( ( xTicksToDelay ), NULL );							\
+	}																					\
+	crSET_STATE0( ( xHandle ) );
+
+/**
+ * <pre>
+ crQUEUE_SEND(
+                  CoRoutineHandle_t xHandle,
+                  QueueHandle_t pxQueue,
+                  void *pvItemToQueue,
+                  TickType_t xTicksToWait,
+                  BaseType_t *pxResult
+             )</pre>
+ *
+ * The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine
+ * equivalent to the xQueueSend() and xQueueReceive() functions used by tasks.
+ *
+ * crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas
+ * xQueueSend() and xQueueReceive() can only be used from tasks.
+ *
+ * crQUEUE_SEND can only be called from the co-routine function itself - not
+ * from within a function called by the co-routine function.  This is because
+ * co-routines do not maintain their own stack.
+ *
+ * See the co-routine section of the WEB documentation for information on
+ * passing data between tasks and co-routines and between ISR's and
+ * co-routines.
+ *
+ * @param xHandle The handle of the calling co-routine.  This is the xHandle
+ * parameter of the co-routine function.
+ *
+ * @param pxQueue The handle of the queue on which the data will be posted.
+ * The handle is obtained as the return value when the queue is created using
+ * the xQueueCreate() API function.
+ *
+ * @param pvItemToQueue A pointer to the data being posted onto the queue.
+ * The number of bytes of each queued item is specified when the queue is
+ * created.  This number of bytes is copied from pvItemToQueue into the queue
+ * itself.
+ *
+ * @param xTickToDelay The number of ticks that the co-routine should block
+ * to wait for space to become available on the queue, should space not be
+ * available immediately. The actual amount of time this equates to is defined
+ * by configTICK_RATE_HZ (set in FreeRTOSConfig.h).  The constant
+ * portTICK_PERIOD_MS can be used to convert ticks to milliseconds (see example
+ * below).
+ *
+ * @param pxResult The variable pointed to by pxResult will be set to pdPASS if
+ * data was successfully posted onto the queue, otherwise it will be set to an
+ * error defined within ProjDefs.h.
+ *
+ * Example usage:
+   <pre>
+ // Co-routine function that blocks for a fixed period then posts a number onto
+ // a queue.
+ static void prvCoRoutineFlashTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // Variables in co-routines must be declared static if they must maintain value across a blocking call.
+ static BaseType_t xNumberToPost = 0;
+ static BaseType_t xResult;
+
+    // Co-routines must begin with a call to crSTART().
+    crSTART( xHandle );
+
+    for( ;; )
+    {
+        // This assumes the queue has already been created.
+        crQUEUE_SEND( xHandle, xCoRoutineQueue, &xNumberToPost, NO_DELAY, &xResult );
+
+        if( xResult != pdPASS )
+        {
+            // The message was not posted!
+        }
+
+        // Increment the number to be posted onto the queue.
+        xNumberToPost++;
+
+        // Delay for 100 ticks.
+        crDELAY( xHandle, 100 );
+    }
+
+    // Co-routines must end with a call to crEND().
+    crEND();
+ }</pre>
+ * \defgroup crQUEUE_SEND crQUEUE_SEND
+ * \ingroup Tasks
+ */
+#define crQUEUE_SEND( xHandle, pxQueue, pvItemToQueue, xTicksToWait, pxResult )			\
+{																						\
+	*( pxResult ) = xQueueCRSend( ( pxQueue) , ( pvItemToQueue) , ( xTicksToWait ) );	\
+	if( *( pxResult ) == errQUEUE_BLOCKED )												\
+	{																					\
+		crSET_STATE0( ( xHandle ) );													\
+		*pxResult = xQueueCRSend( ( pxQueue ), ( pvItemToQueue ), 0 );					\
+	}																					\
+	if( *pxResult == errQUEUE_YIELD )													\
+	{																					\
+		crSET_STATE1( ( xHandle ) );													\
+		*pxResult = pdPASS;																\
+	}																					\
+}
+
+/**
+ * croutine. h
+ * <pre>
+  crQUEUE_RECEIVE(
+                     CoRoutineHandle_t xHandle,
+                     QueueHandle_t pxQueue,
+                     void *pvBuffer,
+                     TickType_t xTicksToWait,
+                     BaseType_t *pxResult
+                 )</pre>
+ *
+ * The macro's crQUEUE_SEND() and crQUEUE_RECEIVE() are the co-routine
+ * equivalent to the xQueueSend() and xQueueReceive() functions used by tasks.
+ *
+ * crQUEUE_SEND and crQUEUE_RECEIVE can only be used from a co-routine whereas
+ * xQueueSend() and xQueueReceive() can only be used from tasks.
+ *
+ * crQUEUE_RECEIVE can only be called from the co-routine function itself - not
+ * from within a function called by the co-routine function.  This is because
+ * co-routines do not maintain their own stack.
+ *
+ * See the co-routine section of the WEB documentation for information on
+ * passing data between tasks and co-routines and between ISR's and
+ * co-routines.
+ *
+ * @param xHandle The handle of the calling co-routine.  This is the xHandle
+ * parameter of the co-routine function.
+ *
+ * @param pxQueue The handle of the queue from which the data will be received.
+ * The handle is obtained as the return value when the queue is created using
+ * the xQueueCreate() API function.
+ *
+ * @param pvBuffer The buffer into which the received item is to be copied.
+ * The number of bytes of each queued item is specified when the queue is
+ * created.  This number of bytes is copied into pvBuffer.
+ *
+ * @param xTickToDelay The number of ticks that the co-routine should block
+ * to wait for data to become available from the queue, should data not be
+ * available immediately. The actual amount of time this equates to is defined
+ * by configTICK_RATE_HZ (set in FreeRTOSConfig.h).  The constant
+ * portTICK_PERIOD_MS can be used to convert ticks to milliseconds (see the
+ * crQUEUE_SEND example).
+ *
+ * @param pxResult The variable pointed to by pxResult will be set to pdPASS if
+ * data was successfully retrieved from the queue, otherwise it will be set to
+ * an error code as defined within ProjDefs.h.
+ *
+ * Example usage:
+ <pre>
+ // A co-routine receives the number of an LED to flash from a queue.  It
+ // blocks on the queue until the number is received.
+ static void prvCoRoutineFlashWorkTask( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // Variables in co-routines must be declared static if they must maintain value across a blocking call.
+ static BaseType_t xResult;
+ static UBaseType_t uxLEDToFlash;
+
+    // All co-routines must start with a call to crSTART().
+    crSTART( xHandle );
+
+    for( ;; )
+    {
+        // Wait for data to become available on the queue.
+        crQUEUE_RECEIVE( xHandle, xCoRoutineQueue, &uxLEDToFlash, portMAX_DELAY, &xResult );
+
+        if( xResult == pdPASS )
+        {
+            // We received the LED to flash - flash it!
+            vParTestToggleLED( uxLEDToFlash );
+        }
+    }
+
+    crEND();
+ }</pre>
+ * \defgroup crQUEUE_RECEIVE crQUEUE_RECEIVE
+ * \ingroup Tasks
+ */
+#define crQUEUE_RECEIVE( xHandle, pxQueue, pvBuffer, xTicksToWait, pxResult )			\
+{																						\
+	*( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), ( xTicksToWait ) );		\
+	if( *( pxResult ) == errQUEUE_BLOCKED ) 											\
+	{																					\
+		crSET_STATE0( ( xHandle ) );													\
+		*( pxResult ) = xQueueCRReceive( ( pxQueue) , ( pvBuffer ), 0 );				\
+	}																					\
+	if( *( pxResult ) == errQUEUE_YIELD )												\
+	{																					\
+		crSET_STATE1( ( xHandle ) );													\
+		*( pxResult ) = pdPASS;															\
+	}																					\
+}
+
+/**
+ * croutine. h
+ * <pre>
+  crQUEUE_SEND_FROM_ISR(
+                            QueueHandle_t pxQueue,
+                            void *pvItemToQueue,
+                            BaseType_t xCoRoutinePreviouslyWoken
+                       )</pre>
+ *
+ * The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the
+ * co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR()
+ * functions used by tasks.
+ *
+ * crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to
+ * pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and
+ * xQueueReceiveFromISR() can only be used to pass data between a task and and
+ * ISR.
+ *
+ * crQUEUE_SEND_FROM_ISR can only be called from an ISR to send data to a queue
+ * that is being used from within a co-routine.
+ *
+ * See the co-routine section of the WEB documentation for information on
+ * passing data between tasks and co-routines and between ISR's and
+ * co-routines.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param xCoRoutinePreviouslyWoken This is included so an ISR can post onto
+ * the same queue multiple times from a single interrupt.  The first call
+ * should always pass in pdFALSE.  Subsequent calls should pass in
+ * the value returned from the previous call.
+ *
+ * @return pdTRUE if a co-routine was woken by posting onto the queue.  This is
+ * used by the ISR to determine if a context switch may be required following
+ * the ISR.
+ *
+ * Example usage:
+ <pre>
+ // A co-routine that blocks on a queue waiting for characters to be received.
+ static void vReceivingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ char cRxedChar;
+ BaseType_t xResult;
+
+     // All co-routines must start with a call to crSTART().
+     crSTART( xHandle );
+
+     for( ;; )
+     {
+         // Wait for data to become available on the queue.  This assumes the
+         // queue xCommsRxQueue has already been created!
+         crQUEUE_RECEIVE( xHandle, xCommsRxQueue, &uxLEDToFlash, portMAX_DELAY, &xResult );
+
+         // Was a character received?
+         if( xResult == pdPASS )
+         {
+             // Process the character here.
+         }
+     }
+
+     // All co-routines must end with a call to crEND().
+     crEND();
+ }
+
+ // An ISR that uses a queue to send characters received on a serial port to
+ // a co-routine.
+ void vUART_ISR( void )
+ {
+ char cRxedChar;
+ BaseType_t xCRWokenByPost = pdFALSE;
+
+     // We loop around reading characters until there are none left in the UART.
+     while( UART_RX_REG_NOT_EMPTY() )
+     {
+         // Obtain the character from the UART.
+         cRxedChar = UART_RX_REG;
+
+         // Post the character onto a queue.  xCRWokenByPost will be pdFALSE
+         // the first time around the loop.  If the post causes a co-routine
+         // to be woken (unblocked) then xCRWokenByPost will be set to pdTRUE.
+         // In this manner we can ensure that if more than one co-routine is
+         // blocked on the queue only one is woken by this ISR no matter how
+         // many characters are posted to the queue.
+         xCRWokenByPost = crQUEUE_SEND_FROM_ISR( xCommsRxQueue, &cRxedChar, xCRWokenByPost );
+     }
+ }</pre>
+ * \defgroup crQUEUE_SEND_FROM_ISR crQUEUE_SEND_FROM_ISR
+ * \ingroup Tasks
+ */
+#define crQUEUE_SEND_FROM_ISR( pxQueue, pvItemToQueue, xCoRoutinePreviouslyWoken ) xQueueCRSendFromISR( ( pxQueue ), ( pvItemToQueue ), ( xCoRoutinePreviouslyWoken ) )
+
+
+/**
+ * croutine. h
+ * <pre>
+  crQUEUE_SEND_FROM_ISR(
+                            QueueHandle_t pxQueue,
+                            void *pvBuffer,
+                            BaseType_t * pxCoRoutineWoken
+                       )</pre>
+ *
+ * The macro's crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() are the
+ * co-routine equivalent to the xQueueSendFromISR() and xQueueReceiveFromISR()
+ * functions used by tasks.
+ *
+ * crQUEUE_SEND_FROM_ISR() and crQUEUE_RECEIVE_FROM_ISR() can only be used to
+ * pass data between a co-routine and and ISR, whereas xQueueSendFromISR() and
+ * xQueueReceiveFromISR() can only be used to pass data between a task and and
+ * ISR.
+ *
+ * crQUEUE_RECEIVE_FROM_ISR can only be called from an ISR to receive data
+ * from a queue that is being used from within a co-routine (a co-routine
+ * posted to the queue).
+ *
+ * See the co-routine section of the WEB documentation for information on
+ * passing data between tasks and co-routines and between ISR's and
+ * co-routines.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvBuffer A pointer to a buffer into which the received item will be
+ * placed.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from the queue into
+ * pvBuffer.
+ *
+ * @param pxCoRoutineWoken A co-routine may be blocked waiting for space to become
+ * available on the queue.  If crQUEUE_RECEIVE_FROM_ISR causes such a
+ * co-routine to unblock *pxCoRoutineWoken will get set to pdTRUE, otherwise
+ * *pxCoRoutineWoken will remain unchanged.
+ *
+ * @return pdTRUE an item was successfully received from the queue, otherwise
+ * pdFALSE.
+ *
+ * Example usage:
+ <pre>
+ // A co-routine that posts a character to a queue then blocks for a fixed
+ // period.  The character is incremented each time.
+ static void vSendingCoRoutine( CoRoutineHandle_t xHandle, UBaseType_t uxIndex )
+ {
+ // cChar holds its value while this co-routine is blocked and must therefore
+ // be declared static.
+ static char cCharToTx = 'a';
+ BaseType_t xResult;
+
+     // All co-routines must start with a call to crSTART().
+     crSTART( xHandle );
+
+     for( ;; )
+     {
+         // Send the next character to the queue.
+         crQUEUE_SEND( xHandle, xCoRoutineQueue, &cCharToTx, NO_DELAY, &xResult );
+
+         if( xResult == pdPASS )
+         {
+             // The character was successfully posted to the queue.
+         }
+		 else
+		 {
+			// Could not post the character to the queue.
+		 }
+
+         // Enable the UART Tx interrupt to cause an interrupt in this
+		 // hypothetical UART.  The interrupt will obtain the character
+		 // from the queue and send it.
+		 ENABLE_RX_INTERRUPT();
+
+		 // Increment to the next character then block for a fixed period.
+		 // cCharToTx will maintain its value across the delay as it is
+		 // declared static.
+		 cCharToTx++;
+		 if( cCharToTx > 'x' )
+		 {
+			cCharToTx = 'a';
+		 }
+		 crDELAY( 100 );
+     }
+
+     // All co-routines must end with a call to crEND().
+     crEND();
+ }
+
+ // An ISR that uses a queue to receive characters to send on a UART.
+ void vUART_ISR( void )
+ {
+ char cCharToTx;
+ BaseType_t xCRWokenByPost = pdFALSE;
+
+     while( UART_TX_REG_EMPTY() )
+     {
+         // Are there any characters in the queue waiting to be sent?
+		 // xCRWokenByPost will automatically be set to pdTRUE if a co-routine
+		 // is woken by the post - ensuring that only a single co-routine is
+		 // woken no matter how many times we go around this loop.
+         if( crQUEUE_RECEIVE_FROM_ISR( pxQueue, &cCharToTx, &xCRWokenByPost ) )
+		 {
+			 SEND_CHARACTER( cCharToTx );
+		 }
+     }
+ }</pre>
+ * \defgroup crQUEUE_RECEIVE_FROM_ISR crQUEUE_RECEIVE_FROM_ISR
+ * \ingroup Tasks
+ */
+#define crQUEUE_RECEIVE_FROM_ISR( pxQueue, pvBuffer, pxCoRoutineWoken ) xQueueCRReceiveFromISR( ( pxQueue ), ( pvBuffer ), ( pxCoRoutineWoken ) )
+
+/*
+ * This function is intended for internal use by the co-routine macros only.
+ * The macro nature of the co-routine implementation requires that the
+ * prototype appears here.  The function should not be used by application
+ * writers.
+ *
+ * Removes the current co-routine from its ready list and places it in the
+ * appropriate delayed list.
+ */
+void vCoRoutineAddToDelayedList( TickType_t xTicksToDelay, List_t *pxEventList );
+
+/*
+ * This function is intended for internal use by the queue implementation only.
+ * The function should not be used by application writers.
+ *
+ * Removes the highest priority co-routine from the event list and places it in
+ * the pending ready list.
+ */
+BaseType_t xCoRoutineRemoveFromEventList( const List_t *pxEventList );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CO_ROUTINE_H */
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/include/deprecated_definitions.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/include/deprecated_definitions.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,322 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+#ifndef DEPRECATED_DEFINITIONS_H
+#define DEPRECATED_DEFINITIONS_H
+
+
+/* Each FreeRTOS port has a unique portmacro.h header file.  Originally a
+pre-processor definition was used to ensure the pre-processor found the correct
+portmacro.h file for the port being used.  That scheme was deprecated in favour
+of setting the compiler's include path such that it found the correct
+portmacro.h file - removing the need for the constant and allowing the
+portmacro.h file to be located anywhere in relation to the port being used.  The
+definitions below remain in the code for backward compatibility only.  New
+projects should not use them. */
+
+#ifdef OPEN_WATCOM_INDUSTRIAL_PC_PORT
+	#include "..\..\Source\portable\owatcom\16bitdos\pc\portmacro.h"
+	typedef void ( __interrupt __far *pxISR )();
+#endif
+
+#ifdef OPEN_WATCOM_FLASH_LITE_186_PORT
+	#include "..\..\Source\portable\owatcom\16bitdos\flsh186\portmacro.h"
+	typedef void ( __interrupt __far *pxISR )();
+#endif
+
+#ifdef GCC_MEGA_AVR
+	#include "../portable/GCC/ATMega323/portmacro.h"
+#endif
+
+#ifdef IAR_MEGA_AVR
+	#include "../portable/IAR/ATMega323/portmacro.h"
+#endif
+
+#ifdef MPLAB_PIC24_PORT
+	#include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h"
+#endif
+
+#ifdef MPLAB_DSPIC_PORT
+	#include "../../Source/portable/MPLAB/PIC24_dsPIC/portmacro.h"
+#endif
+
+#ifdef MPLAB_PIC18F_PORT
+	#include "../../Source/portable/MPLAB/PIC18F/portmacro.h"
+#endif
+
+#ifdef MPLAB_PIC32MX_PORT
+	#include "../../Source/portable/MPLAB/PIC32MX/portmacro.h"
+#endif
+
+#ifdef _FEDPICC
+	#include "libFreeRTOS/Include/portmacro.h"
+#endif
+
+#ifdef SDCC_CYGNAL
+	#include "../../Source/portable/SDCC/Cygnal/portmacro.h"
+#endif
+
+#ifdef GCC_ARM7
+	#include "../../Source/portable/GCC/ARM7_LPC2000/portmacro.h"
+#endif
+
+#ifdef GCC_ARM7_ECLIPSE
+	#include "portmacro.h"
+#endif
+
+#ifdef ROWLEY_LPC23xx
+	#include "../../Source/portable/GCC/ARM7_LPC23xx/portmacro.h"
+#endif
+
+#ifdef IAR_MSP430
+	#include "..\..\Source\portable\IAR\MSP430\portmacro.h"
+#endif
+
+#ifdef GCC_MSP430
+	#include "../../Source/portable/GCC/MSP430F449/portmacro.h"
+#endif
+
+#ifdef ROWLEY_MSP430
+	#include "../../Source/portable/Rowley/MSP430F449/portmacro.h"
+#endif
+
+#ifdef ARM7_LPC21xx_KEIL_RVDS
+	#include "..\..\Source\portable\RVDS\ARM7_LPC21xx\portmacro.h"
+#endif
+
+#ifdef SAM7_GCC
+	#include "../../Source/portable/GCC/ARM7_AT91SAM7S/portmacro.h"
+#endif
+
+#ifdef SAM7_IAR
+	#include "..\..\Source\portable\IAR\AtmelSAM7S64\portmacro.h"
+#endif
+
+#ifdef SAM9XE_IAR
+	#include "..\..\Source\portable\IAR\AtmelSAM9XE\portmacro.h"
+#endif
+
+#ifdef LPC2000_IAR
+	#include "..\..\Source\portable\IAR\LPC2000\portmacro.h"
+#endif
+
+#ifdef STR71X_IAR
+	#include "..\..\Source\portable\IAR\STR71x\portmacro.h"
+#endif
+
+#ifdef STR75X_IAR
+	#include "..\..\Source\portable\IAR\STR75x\portmacro.h"
+#endif
+
+#ifdef STR75X_GCC
+	#include "..\..\Source\portable\GCC\STR75x\portmacro.h"
+#endif
+
+#ifdef STR91X_IAR
+	#include "..\..\Source\portable\IAR\STR91x\portmacro.h"
+#endif
+
+#ifdef GCC_H8S
+	#include "../../Source/portable/GCC/H8S2329/portmacro.h"
+#endif
+
+#ifdef GCC_AT91FR40008
+	#include "../../Source/portable/GCC/ARM7_AT91FR40008/portmacro.h"
+#endif
+
+#ifdef RVDS_ARMCM3_LM3S102
+	#include "../../Source/portable/RVDS/ARM_CM3/portmacro.h"
+#endif
+
+#ifdef GCC_ARMCM3_LM3S102
+	#include "../../Source/portable/GCC/ARM_CM3/portmacro.h"
+#endif
+
+#ifdef GCC_ARMCM3
+	#include "../../Source/portable/GCC/ARM_CM3/portmacro.h"
+#endif
+
+#ifdef IAR_ARM_CM3
+	#include "../../Source/portable/IAR/ARM_CM3/portmacro.h"
+#endif
+
+#ifdef IAR_ARMCM3_LM
+	#include "../../Source/portable/IAR/ARM_CM3/portmacro.h"
+#endif
+
+#ifdef HCS12_CODE_WARRIOR
+	#include "../../Source/portable/CodeWarrior/HCS12/portmacro.h"
+#endif
+
+#ifdef MICROBLAZE_GCC
+	#include "../../Source/portable/GCC/MicroBlaze/portmacro.h"
+#endif
+
+#ifdef TERN_EE
+	#include "..\..\Source\portable\Paradigm\Tern_EE\small\portmacro.h"
+#endif
+
+#ifdef GCC_HCS12
+	#include "../../Source/portable/GCC/HCS12/portmacro.h"
+#endif
+
+#ifdef GCC_MCF5235
+    #include "../../Source/portable/GCC/MCF5235/portmacro.h"
+#endif
+
+#ifdef COLDFIRE_V2_GCC
+	#include "../../../Source/portable/GCC/ColdFire_V2/portmacro.h"
+#endif
+
+#ifdef COLDFIRE_V2_CODEWARRIOR
+	#include "../../Source/portable/CodeWarrior/ColdFire_V2/portmacro.h"
+#endif
+
+#ifdef GCC_PPC405
+	#include "../../Source/portable/GCC/PPC405_Xilinx/portmacro.h"
+#endif
+
+#ifdef GCC_PPC440
+	#include "../../Source/portable/GCC/PPC440_Xilinx/portmacro.h"
+#endif
+
+#ifdef _16FX_SOFTUNE
+	#include "..\..\Source\portable\Softune\MB96340\portmacro.h"
+#endif
+
+#ifdef BCC_INDUSTRIAL_PC_PORT
+	/* A short file name has to be used in place of the normal
+	FreeRTOSConfig.h when using the Borland compiler. */
+	#include "frconfig.h"
+	#include "..\portable\BCC\16BitDOS\PC\prtmacro.h"
+    typedef void ( __interrupt __far *pxISR )();
+#endif
+
+#ifdef BCC_FLASH_LITE_186_PORT
+	/* A short file name has to be used in place of the normal
+	FreeRTOSConfig.h when using the Borland compiler. */
+	#include "frconfig.h"
+	#include "..\portable\BCC\16BitDOS\flsh186\prtmacro.h"
+    typedef void ( __interrupt __far *pxISR )();
+#endif
+
+#ifdef __GNUC__
+   #ifdef __AVR32_AVR32A__
+	   #include "portmacro.h"
+   #endif
+#endif
+
+#ifdef __ICCAVR32__
+   #ifdef __CORE__
+      #if __CORE__ == __AVR32A__
+	      #include "portmacro.h"
+      #endif
+   #endif
+#endif
+
+#ifdef __91467D
+	#include "portmacro.h"
+#endif
+
+#ifdef __96340
+	#include "portmacro.h"
+#endif
+
+
+#ifdef __IAR_V850ES_Fx3__
+	#include "../../Source/portable/IAR/V850ES/portmacro.h"
+#endif
+
+#ifdef __IAR_V850ES_Jx3__
+	#include "../../Source/portable/IAR/V850ES/portmacro.h"
+#endif
+
+#ifdef __IAR_V850ES_Jx3_L__
+	#include "../../Source/portable/IAR/V850ES/portmacro.h"
+#endif
+
+#ifdef __IAR_V850ES_Jx2__
+	#include "../../Source/portable/IAR/V850ES/portmacro.h"
+#endif
+
+#ifdef __IAR_V850ES_Hx2__
+	#include "../../Source/portable/IAR/V850ES/portmacro.h"
+#endif
+
+#ifdef __IAR_78K0R_Kx3__
+	#include "../../Source/portable/IAR/78K0R/portmacro.h"
+#endif
+
+#ifdef __IAR_78K0R_Kx3L__
+	#include "../../Source/portable/IAR/78K0R/portmacro.h"
+#endif
+
+#endif /* DEPRECATED_DEFINITIONS_H */
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/include/event_groups.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/include/event_groups.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,731 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+#ifndef EVENT_GROUPS_H
+#define EVENT_GROUPS_H
+
+#ifndef INC_FREERTOS_H
+	#error "include FreeRTOS.h" must appear in source files before "include event_groups.h"
+#endif
+
+#include "timers.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * An event group is a collection of bits to which an application can assign a
+ * meaning.  For example, an application may create an event group to convey
+ * the status of various CAN bus related events in which bit 0 might mean "A CAN
+ * message has been received and is ready for processing", bit 1 might mean "The
+ * application has queued a message that is ready for sending onto the CAN
+ * network", and bit 2 might mean "It is time to send a SYNC message onto the
+ * CAN network" etc.  A task can then test the bit values to see which events
+ * are active, and optionally enter the Blocked state to wait for a specified
+ * bit or a group of specified bits to be active.  To continue the CAN bus
+ * example, a CAN controlling task can enter the Blocked state (and therefore
+ * not consume any processing time) until either bit 0, bit 1 or bit 2 are
+ * active, at which time the bit that was actually active would inform the task
+ * which action it had to take (process a received message, send a message, or
+ * send a SYNC).
+ *
+ * The event groups implementation contains intelligence to avoid race
+ * conditions that would otherwise occur were an application to use a simple
+ * variable for the same purpose.  This is particularly important with respect
+ * to when a bit within an event group is to be cleared, and when bits have to
+ * be set and then tested atomically - as is the case where event groups are
+ * used to create a synchronisation point between multiple tasks (a
+ * 'rendezvous').
+ *
+ * \defgroup EventGroup
+ */
+
+
+
+/**
+ * event_groups.h
+ *
+ * Type by which event groups are referenced.  For example, a call to
+ * xEventGroupCreate() returns an EventGroupHandle_t variable that can then
+ * be used as a parameter to other event group functions.
+ *
+ * \defgroup EventGroupHandle_t EventGroupHandle_t
+ * \ingroup EventGroup
+ */
+typedef void * EventGroupHandle_t;
+
+/* 
+ * The type that holds event bits always matches TickType_t - therefore the
+ * number of bits it holds is set by configUSE_16_BIT_TICKS (16 bits if set to 1,
+ * 32 bits if set to 0. 
+ *
+ * \defgroup EventBits_t EventBits_t
+ * \ingroup EventGroup
+ */
+typedef TickType_t EventBits_t;
+
+/**
+ * event_groups.h
+ *<pre>
+ EventGroupHandle_t xEventGroupCreate( void );
+ </pre>
+ *
+ * Create a new event group.  This function cannot be called from an interrupt.
+ *
+ * Although event groups are not related to ticks, for internal implementation
+ * reasons the number of bits available for use in an event group is dependent
+ * on the configUSE_16_BIT_TICKS setting in FreeRTOSConfig.h.  If
+ * configUSE_16_BIT_TICKS is 1 then each event group contains 8 usable bits (bit
+ * 0 to bit 7).  If configUSE_16_BIT_TICKS is set to 0 then each event group has
+ * 24 usable bits (bit 0 to bit 23).  The EventBits_t type is used to store
+ * event bits within an event group.
+ *
+ * @return If the event group was created then a handle to the event group is
+ * returned.  If there was insufficient FreeRTOS heap available to create the
+ * event group then NULL is returned.  See http://www.freertos.org/a00111.html
+ *
+ * Example usage:
+   <pre>
+	// Declare a variable to hold the created event group.
+	EventGroupHandle_t xCreatedEventGroup;
+
+	// Attempt to create the event group.
+	xCreatedEventGroup = xEventGroupCreate();
+
+	// Was the event group created successfully?
+	if( xCreatedEventGroup == NULL )
+	{
+		// The event group was not created because there was insufficient
+		// FreeRTOS heap available.
+	}
+	else
+	{
+		// The event group was created.
+	}
+   </pre>
+ * \defgroup xEventGroupCreate xEventGroupCreate
+ * \ingroup EventGroup
+ */
+EventGroupHandle_t xEventGroupCreate( void ) PRIVILEGED_FUNCTION;
+
+/**
+ * event_groups.h
+ *<pre>
+	EventBits_t xEventGroupWaitBits( 	EventGroupHandle_t xEventGroup,
+										const EventBits_t uxBitsToWaitFor,
+										const BaseType_t xClearOnExit,
+										const BaseType_t xWaitForAllBits,
+										const TickType_t xTicksToWait );
+ </pre>
+ *
+ * [Potentially] block to wait for one or more bits to be set within a
+ * previously created event group.
+ *
+ * This function cannot be called from an interrupt.
+ *
+ * @param xEventGroup The event group in which the bits are being tested.  The
+ * event group must have previously been created using a call to
+ * xEventGroupCreate().
+ *
+ * @param uxBitsToWaitFor A bitwise value that indicates the bit or bits to test
+ * inside the event group.  For example, to wait for bit 0 and/or bit 2 set
+ * uxBitsToWaitFor to 0x05.  To wait for bits 0 and/or bit 1 and/or bit 2 set
+ * uxBitsToWaitFor to 0x07.  Etc.
+ *
+ * @param xClearOnExit If xClearOnExit is set to pdTRUE then any bits within
+ * uxBitsToWaitFor that are set within the event group will be cleared before
+ * xEventGroupWaitBits() returns if the wait condition was met (if the function
+ * returns for a reason other than a timeout).  If xClearOnExit is set to
+ * pdFALSE then the bits set in the event group are not altered when the call to
+ * xEventGroupWaitBits() returns.
+ *
+ * @param xWaitForAllBits If xWaitForAllBits is set to pdTRUE then
+ * xEventGroupWaitBits() will return when either all the bits in uxBitsToWaitFor
+ * are set or the specified block time expires.  If xWaitForAllBits is set to
+ * pdFALSE then xEventGroupWaitBits() will return when any one of the bits set
+ * in uxBitsToWaitFor is set or the specified block time expires.  The block
+ * time is specified by the xTicksToWait parameter.
+ *
+ * @param xTicksToWait The maximum amount of time (specified in 'ticks') to wait
+ * for one/all (depending on the xWaitForAllBits value) of the bits specified by
+ * uxBitsToWaitFor to become set.
+ *
+ * @return The value of the event group at the time either the bits being waited
+ * for became set, or the block time expired.  Test the return value to know
+ * which bits were set.  If xEventGroupWaitBits() returned because its timeout
+ * expired then not all the bits being waited for will be set.  If
+ * xEventGroupWaitBits() returned because the bits it was waiting for were set
+ * then the returned value is the event group value before any bits were
+ * automatically cleared in the case that xClearOnExit parameter was set to
+ * pdTRUE.
+ *
+ * Example usage:
+   <pre>
+   #define BIT_0	( 1 << 0 )
+   #define BIT_4	( 1 << 4 )
+
+   void aFunction( EventGroupHandle_t xEventGroup )
+   {
+   EventBits_t uxBits;
+   const TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS;
+
+		// Wait a maximum of 100ms for either bit 0 or bit 4 to be set within
+		// the event group.  Clear the bits before exiting.
+		uxBits = xEventGroupWaitBits(
+					xEventGroup,	// The event group being tested.
+					BIT_0 | BIT_4,	// The bits within the event group to wait for.
+					pdTRUE,			// BIT_0 and BIT_4 should be cleared before returning.
+					pdFALSE,		// Don't wait for both bits, either bit will do.
+					xTicksToWait );	// Wait a maximum of 100ms for either bit to be set.
+
+		if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
+		{
+			// xEventGroupWaitBits() returned because both bits were set.
+		}
+		else if( ( uxBits & BIT_0 ) != 0 )
+		{
+			// xEventGroupWaitBits() returned because just BIT_0 was set.
+		}
+		else if( ( uxBits & BIT_4 ) != 0 )
+		{
+			// xEventGroupWaitBits() returned because just BIT_4 was set.
+		}
+		else
+		{
+			// xEventGroupWaitBits() returned because xTicksToWait ticks passed
+			// without either BIT_0 or BIT_4 becoming set.
+		}
+   }
+   </pre>
+ * \defgroup xEventGroupWaitBits xEventGroupWaitBits
+ * \ingroup EventGroup
+ */
+EventBits_t xEventGroupWaitBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToWaitFor, const BaseType_t xClearOnExit, const BaseType_t xWaitForAllBits, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+
+/**
+ * event_groups.h
+ *<pre>
+	EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear );
+ </pre>
+ *
+ * Clear bits within an event group.  This function cannot be called from an
+ * interrupt.
+ *
+ * @param xEventGroup The event group in which the bits are to be cleared.
+ *
+ * @param uxBitsToClear A bitwise value that indicates the bit or bits to clear
+ * in the event group.  For example, to clear bit 3 only, set uxBitsToClear to
+ * 0x08.  To clear bit 3 and bit 0 set uxBitsToClear to 0x09.
+ *
+ * @return The value of the event group before the specified bits were cleared.
+ *
+ * Example usage:
+   <pre>
+   #define BIT_0	( 1 << 0 )
+   #define BIT_4	( 1 << 4 )
+
+   void aFunction( EventGroupHandle_t xEventGroup )
+   {
+   EventBits_t uxBits;
+
+		// Clear bit 0 and bit 4 in xEventGroup.
+		uxBits = xEventGroupClearBits(
+								xEventGroup,	// The event group being updated.
+								BIT_0 | BIT_4 );// The bits being cleared.
+
+		if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
+		{
+			// Both bit 0 and bit 4 were set before xEventGroupClearBits() was
+			// called.  Both will now be clear (not set).
+		}
+		else if( ( uxBits & BIT_0 ) != 0 )
+		{
+			// Bit 0 was set before xEventGroupClearBits() was called.  It will
+			// now be clear.
+		}
+		else if( ( uxBits & BIT_4 ) != 0 )
+		{
+			// Bit 4 was set before xEventGroupClearBits() was called.  It will
+			// now be clear.
+		}
+		else
+		{
+			// Neither bit 0 nor bit 4 were set in the first place.
+		}
+   }
+   </pre>
+ * \defgroup xEventGroupClearBits xEventGroupClearBits
+ * \ingroup EventGroup
+ */
+EventBits_t xEventGroupClearBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToClear ) PRIVILEGED_FUNCTION;
+
+/**
+ * event_groups.h
+ *<pre>
+	BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
+ </pre>
+ *
+ * A version of xEventGroupClearBits() that can be called from an interrupt.
+ *
+ * Setting bits in an event group is not a deterministic operation because there
+ * are an unknown number of tasks that may be waiting for the bit or bits being
+ * set.  FreeRTOS does not allow nondeterministic operations to be performed
+ * while interrupts are disabled, so protects event groups that are accessed
+ * from tasks by suspending the scheduler rather than disabling interrupts.  As
+ * a result event groups cannot be accessed directly from an interrupt service
+ * routine.  Therefore xEventGroupClearBitsFromISR() sends a message to the 
+ * timer task to have the clear operation performed in the context of the timer 
+ * task.
+ *
+ * @param xEventGroup The event group in which the bits are to be cleared.
+ *
+ * @param uxBitsToClear A bitwise value that indicates the bit or bits to clear.
+ * For example, to clear bit 3 only, set uxBitsToClear to 0x08.  To clear bit 3
+ * and bit 0 set uxBitsToClear to 0x09.
+ *
+ * @return If the request to execute the function was posted successfully then 
+ * pdPASS is returned, otherwise pdFALSE is returned.  pdFALSE will be returned 
+ * if the timer service queue was full.
+ *
+ * Example usage:
+   <pre>
+   #define BIT_0	( 1 << 0 )
+   #define BIT_4	( 1 << 4 )
+
+   // An event group which it is assumed has already been created by a call to
+   // xEventGroupCreate().
+   EventGroupHandle_t xEventGroup;
+
+   void anInterruptHandler( void )
+   {
+		// Clear bit 0 and bit 4 in xEventGroup.
+		xResult = xEventGroupClearBitsFromISR(
+							xEventGroup,	 // The event group being updated.
+							BIT_0 | BIT_4 ); // The bits being set.
+
+		if( xResult == pdPASS )
+		{
+			// The message was posted successfully.
+		}
+  }
+   </pre>
+ * \defgroup xEventGroupSetBitsFromISR xEventGroupSetBitsFromISR
+ * \ingroup EventGroup
+ */
+#if( configUSE_TRACE_FACILITY == 1 )
+	BaseType_t xEventGroupClearBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
+#else
+	#define xEventGroupClearBitsFromISR( xEventGroup, uxBitsToClear ) xTimerPendFunctionCallFromISR( vEventGroupClearBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToClear, NULL )
+#endif
+
+/**
+ * event_groups.h
+ *<pre>
+	EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet );
+ </pre>
+ *
+ * Set bits within an event group.
+ * This function cannot be called from an interrupt.  xEventGroupSetBitsFromISR()
+ * is a version that can be called from an interrupt.
+ *
+ * Setting bits in an event group will automatically unblock tasks that are
+ * blocked waiting for the bits.
+ *
+ * @param xEventGroup The event group in which the bits are to be set.
+ *
+ * @param uxBitsToSet A bitwise value that indicates the bit or bits to set.
+ * For example, to set bit 3 only, set uxBitsToSet to 0x08.  To set bit 3
+ * and bit 0 set uxBitsToSet to 0x09.
+ *
+ * @return The value of the event group at the time the call to
+ * xEventGroupSetBits() returns.  There are two reasons why the returned value
+ * might have the bits specified by the uxBitsToSet parameter cleared.  First,
+ * if setting a bit results in a task that was waiting for the bit leaving the
+ * blocked state then it is possible the bit will be cleared automatically
+ * (see the xClearBitOnExit parameter of xEventGroupWaitBits()).  Second, any
+ * unblocked (or otherwise Ready state) task that has a priority above that of
+ * the task that called xEventGroupSetBits() will execute and may change the
+ * event group value before the call to xEventGroupSetBits() returns.
+ *
+ * Example usage:
+   <pre>
+   #define BIT_0	( 1 << 0 )
+   #define BIT_4	( 1 << 4 )
+
+   void aFunction( EventGroupHandle_t xEventGroup )
+   {
+   EventBits_t uxBits;
+
+		// Set bit 0 and bit 4 in xEventGroup.
+		uxBits = xEventGroupSetBits(
+							xEventGroup,	// The event group being updated.
+							BIT_0 | BIT_4 );// The bits being set.
+
+		if( ( uxBits & ( BIT_0 | BIT_4 ) ) == ( BIT_0 | BIT_4 ) )
+		{
+			// Both bit 0 and bit 4 remained set when the function returned.
+		}
+		else if( ( uxBits & BIT_0 ) != 0 )
+		{
+			// Bit 0 remained set when the function returned, but bit 4 was
+			// cleared.  It might be that bit 4 was cleared automatically as a
+			// task that was waiting for bit 4 was removed from the Blocked
+			// state.
+		}
+		else if( ( uxBits & BIT_4 ) != 0 )
+		{
+			// Bit 4 remained set when the function returned, but bit 0 was
+			// cleared.  It might be that bit 0 was cleared automatically as a
+			// task that was waiting for bit 0 was removed from the Blocked
+			// state.
+		}
+		else
+		{
+			// Neither bit 0 nor bit 4 remained set.  It might be that a task
+			// was waiting for both of the bits to be set, and the bits were
+			// cleared as the task left the Blocked state.
+		}
+   }
+   </pre>
+ * \defgroup xEventGroupSetBits xEventGroupSetBits
+ * \ingroup EventGroup
+ */
+EventBits_t xEventGroupSetBits( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet ) PRIVILEGED_FUNCTION;
+
+/**
+ * event_groups.h
+ *<pre>
+	BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken );
+ </pre>
+ *
+ * A version of xEventGroupSetBits() that can be called from an interrupt.
+ *
+ * Setting bits in an event group is not a deterministic operation because there
+ * are an unknown number of tasks that may be waiting for the bit or bits being
+ * set.  FreeRTOS does not allow nondeterministic operations to be performed in
+ * interrupts or from critical sections.  Therefore xEventGroupSetBitFromISR()
+ * sends a message to the timer task to have the set operation performed in the
+ * context of the timer task - where a scheduler lock is used in place of a
+ * critical section.
+ *
+ * @param xEventGroup The event group in which the bits are to be set.
+ *
+ * @param uxBitsToSet A bitwise value that indicates the bit or bits to set.
+ * For example, to set bit 3 only, set uxBitsToSet to 0x08.  To set bit 3
+ * and bit 0 set uxBitsToSet to 0x09.
+ *
+ * @param pxHigherPriorityTaskWoken As mentioned above, calling this function
+ * will result in a message being sent to the timer daemon task.  If the
+ * priority of the timer daemon task is higher than the priority of the
+ * currently running task (the task the interrupt interrupted) then
+ * *pxHigherPriorityTaskWoken will be set to pdTRUE by
+ * xEventGroupSetBitsFromISR(), indicating that a context switch should be
+ * requested before the interrupt exits.  For that reason
+ * *pxHigherPriorityTaskWoken must be initialised to pdFALSE.  See the
+ * example code below.
+ *
+ * @return If the request to execute the function was posted successfully then 
+ * pdPASS is returned, otherwise pdFALSE is returned.  pdFALSE will be returned 
+ * if the timer service queue was full.
+ *
+ * Example usage:
+   <pre>
+   #define BIT_0	( 1 << 0 )
+   #define BIT_4	( 1 << 4 )
+
+   // An event group which it is assumed has already been created by a call to
+   // xEventGroupCreate().
+   EventGroupHandle_t xEventGroup;
+
+   void anInterruptHandler( void )
+   {
+   BaseType_t xHigherPriorityTaskWoken, xResult;
+
+		// xHigherPriorityTaskWoken must be initialised to pdFALSE.
+		xHigherPriorityTaskWoken = pdFALSE;
+
+		// Set bit 0 and bit 4 in xEventGroup.
+		xResult = xEventGroupSetBitsFromISR(
+							xEventGroup,	// The event group being updated.
+							BIT_0 | BIT_4   // The bits being set.
+							&xHigherPriorityTaskWoken );
+
+		// Was the message posted successfully?
+		if( xResult == pdPASS )
+		{
+			// If xHigherPriorityTaskWoken is now set to pdTRUE then a context
+			// switch should be requested.  The macro used is port specific and 
+			// will be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - 
+			// refer to the documentation page for the port being used.
+			portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
+		}
+  }
+   </pre>
+ * \defgroup xEventGroupSetBitsFromISR xEventGroupSetBitsFromISR
+ * \ingroup EventGroup
+ */
+#if( configUSE_TRACE_FACILITY == 1 )
+	BaseType_t xEventGroupSetBitsFromISR( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, BaseType_t *pxHigherPriorityTaskWoken );
+#else
+	#define xEventGroupSetBitsFromISR( xEventGroup, uxBitsToSet, pxHigherPriorityTaskWoken ) xTimerPendFunctionCallFromISR( vEventGroupSetBitsCallback, ( void * ) xEventGroup, ( uint32_t ) uxBitsToSet, pxHigherPriorityTaskWoken )
+#endif
+
+/**
+ * event_groups.h
+ *<pre>
+	EventBits_t xEventGroupSync(	EventGroupHandle_t xEventGroup,
+									const EventBits_t uxBitsToSet,
+									const EventBits_t uxBitsToWaitFor,
+									TickType_t xTicksToWait );
+ </pre>
+ *
+ * Atomically set bits within an event group, then wait for a combination of
+ * bits to be set within the same event group.  This functionality is typically
+ * used to synchronise multiple tasks, where each task has to wait for the other
+ * tasks to reach a synchronisation point before proceeding.
+ *
+ * This function cannot be used from an interrupt.
+ *
+ * The function will return before its block time expires if the bits specified
+ * by the uxBitsToWait parameter are set, or become set within that time.  In
+ * this case all the bits specified by uxBitsToWait will be automatically
+ * cleared before the function returns.
+ *
+ * @param xEventGroup The event group in which the bits are being tested.  The
+ * event group must have previously been created using a call to
+ * xEventGroupCreate().
+ *
+ * @param uxBitsToSet The bits to set in the event group before determining
+ * if, and possibly waiting for, all the bits specified by the uxBitsToWait
+ * parameter are set.
+ *
+ * @param uxBitsToWaitFor A bitwise value that indicates the bit or bits to test
+ * inside the event group.  For example, to wait for bit 0 and bit 2 set
+ * uxBitsToWaitFor to 0x05.  To wait for bits 0 and bit 1 and bit 2 set
+ * uxBitsToWaitFor to 0x07.  Etc.
+ *
+ * @param xTicksToWait The maximum amount of time (specified in 'ticks') to wait
+ * for all of the bits specified by uxBitsToWaitFor to become set.
+ *
+ * @return The value of the event group at the time either the bits being waited
+ * for became set, or the block time expired.  Test the return value to know
+ * which bits were set.  If xEventGroupSync() returned because its timeout
+ * expired then not all the bits being waited for will be set.  If
+ * xEventGroupSync() returned because all the bits it was waiting for were
+ * set then the returned value is the event group value before any bits were
+ * automatically cleared.
+ *
+ * Example usage:
+ <pre>
+ // Bits used by the three tasks.
+ #define TASK_0_BIT		( 1 << 0 )
+ #define TASK_1_BIT		( 1 << 1 )
+ #define TASK_2_BIT		( 1 << 2 )
+
+ #define ALL_SYNC_BITS ( TASK_0_BIT | TASK_1_BIT | TASK_2_BIT )
+
+ // Use an event group to synchronise three tasks.  It is assumed this event
+ // group has already been created elsewhere.
+ EventGroupHandle_t xEventBits;
+
+ void vTask0( void *pvParameters )
+ {
+ EventBits_t uxReturn;
+ TickType_t xTicksToWait = 100 / portTICK_PERIOD_MS;
+
+	 for( ;; )
+	 {
+		// Perform task functionality here.
+
+		// Set bit 0 in the event flag to note this task has reached the
+		// sync point.  The other two tasks will set the other two bits defined
+		// by ALL_SYNC_BITS.  All three tasks have reached the synchronisation
+		// point when all the ALL_SYNC_BITS are set.  Wait a maximum of 100ms
+		// for this to happen.
+		uxReturn = xEventGroupSync( xEventBits, TASK_0_BIT, ALL_SYNC_BITS, xTicksToWait );
+
+		if( ( uxReturn & ALL_SYNC_BITS ) == ALL_SYNC_BITS )
+		{
+			// All three tasks reached the synchronisation point before the call
+			// to xEventGroupSync() timed out.
+		}
+	}
+ }
+
+ void vTask1( void *pvParameters )
+ {
+	 for( ;; )
+	 {
+		// Perform task functionality here.
+
+		// Set bit 1 in the event flag to note this task has reached the
+		// synchronisation point.  The other two tasks will set the other two
+		// bits defined by ALL_SYNC_BITS.  All three tasks have reached the
+		// synchronisation point when all the ALL_SYNC_BITS are set.  Wait
+		// indefinitely for this to happen.
+		xEventGroupSync( xEventBits, TASK_1_BIT, ALL_SYNC_BITS, portMAX_DELAY );
+
+		// xEventGroupSync() was called with an indefinite block time, so
+		// this task will only reach here if the syncrhonisation was made by all
+		// three tasks, so there is no need to test the return value.
+	 }
+ }
+
+ void vTask2( void *pvParameters )
+ {
+	 for( ;; )
+	 {
+		// Perform task functionality here.
+
+		// Set bit 2 in the event flag to note this task has reached the
+		// synchronisation point.  The other two tasks will set the other two
+		// bits defined by ALL_SYNC_BITS.  All three tasks have reached the
+		// synchronisation point when all the ALL_SYNC_BITS are set.  Wait
+		// indefinitely for this to happen.
+		xEventGroupSync( xEventBits, TASK_2_BIT, ALL_SYNC_BITS, portMAX_DELAY );
+
+		// xEventGroupSync() was called with an indefinite block time, so
+		// this task will only reach here if the syncrhonisation was made by all
+		// three tasks, so there is no need to test the return value.
+	}
+ }
+
+ </pre>
+ * \defgroup xEventGroupSync xEventGroupSync
+ * \ingroup EventGroup
+ */
+EventBits_t xEventGroupSync( EventGroupHandle_t xEventGroup, const EventBits_t uxBitsToSet, const EventBits_t uxBitsToWaitFor, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+
+
+/**
+ * event_groups.h
+ *<pre>
+	EventBits_t xEventGroupGetBits( EventGroupHandle_t xEventGroup );
+ </pre>
+ *
+ * Returns the current value of the bits in an event group.  This function
+ * cannot be used from an interrupt.
+ *
+ * @param xEventGroup The event group being queried.
+ *
+ * @return The event group bits at the time xEventGroupGetBits() was called.
+ *
+ * \defgroup xEventGroupGetBits xEventGroupGetBits
+ * \ingroup EventGroup
+ */
+#define xEventGroupGetBits( xEventGroup ) xEventGroupClearBits( xEventGroup, 0 )
+
+/**
+ * event_groups.h
+ *<pre>
+	EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup );
+ </pre>
+ *
+ * A version of xEventGroupGetBits() that can be called from an ISR.
+ *
+ * @param xEventGroup The event group being queried.
+ *
+ * @return The event group bits at the time xEventGroupGetBitsFromISR() was called.
+ *
+ * \defgroup xEventGroupGetBitsFromISR xEventGroupGetBitsFromISR
+ * \ingroup EventGroup
+ */
+EventBits_t xEventGroupGetBitsFromISR( EventGroupHandle_t xEventGroup );
+
+/**
+ * event_groups.h
+ *<pre>
+	void xEventGroupDelete( EventGroupHandle_t xEventGroup );
+ </pre>
+ *
+ * Delete an event group that was previously created by a call to
+ * xEventGroupCreate().  Tasks that are blocked on the event group will be
+ * unblocked and obtain 0 as the event group's value.
+ *
+ * @param xEventGroup The event group being deleted.
+ */
+void vEventGroupDelete( EventGroupHandle_t xEventGroup );
+
+/* For internal use only. */
+void vEventGroupSetBitsCallback( void *pvEventGroup, const uint32_t ulBitsToSet );
+void vEventGroupClearBitsCallback( void *pvEventGroup, const uint32_t ulBitsToClear );
+
+#if (configUSE_TRACE_FACILITY == 1)
+	UBaseType_t uxEventGroupGetNumber( void* xEventGroup );
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* EVENT_GROUPS_H */
+
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/include/list.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/include/list.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,454 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+/*
+ * This is the list implementation used by the scheduler.  While it is tailored
+ * heavily for the schedulers needs, it is also available for use by
+ * application code.
+ *
+ * list_ts can only store pointers to list_item_ts.  Each ListItem_t contains a
+ * numeric value (xItemValue).  Most of the time the lists are sorted in
+ * descending item value order.
+ *
+ * Lists are created already containing one list item.  The value of this
+ * item is the maximum possible that can be stored, it is therefore always at
+ * the end of the list and acts as a marker.  The list member pxHead always
+ * points to this marker - even though it is at the tail of the list.  This
+ * is because the tail contains a wrap back pointer to the true head of
+ * the list.
+ *
+ * In addition to it's value, each list item contains a pointer to the next
+ * item in the list (pxNext), a pointer to the list it is in (pxContainer)
+ * and a pointer to back to the object that contains it.  These later two
+ * pointers are included for efficiency of list manipulation.  There is
+ * effectively a two way link between the object containing the list item and
+ * the list item itself.
+ *
+ *
+ * \page ListIntroduction List Implementation
+ * \ingroup FreeRTOSIntro
+ */
+
+#ifndef INC_FREERTOS_H
+	#error FreeRTOS.h must be included before list.h
+#endif
+
+#ifndef LIST_H
+#define LIST_H
+
+/*
+ * The list structure members are modified from within interrupts, and therefore
+ * by rights should be declared volatile.  However, they are only modified in a
+ * functionally atomic way (within critical sections of with the scheduler
+ * suspended) and are either passed by reference into a function or indexed via
+ * a volatile variable.  Therefore, in all use cases tested so far, the volatile
+ * qualifier can be omitted in order to provide a moderate performance
+ * improvement without adversely affecting functional behaviour.  The assembly
+ * instructions generated by the IAR, ARM and GCC compilers when the respective
+ * compiler's options were set for maximum optimisation has been inspected and
+ * deemed to be as intended.  That said, as compiler technology advances, and
+ * especially if aggressive cross module optimisation is used (a use case that
+ * has not been exercised to any great extend) then it is feasible that the
+ * volatile qualifier will be needed for correct optimisation.  It is expected
+ * that a compiler removing essential code because, without the volatile
+ * qualifier on the list structure members and with aggressive cross module
+ * optimisation, the compiler deemed the code unnecessary will result in
+ * complete and obvious failure of the scheduler.  If this is ever experienced
+ * then the volatile qualifier can be inserted in the relevant places within the
+ * list structures by simply defining configLIST_VOLATILE to volatile in
+ * FreeRTOSConfig.h (as per the example at the bottom of this comment block).
+ * If configLIST_VOLATILE is not defined then the preprocessor directives below
+ * will simply #define configLIST_VOLATILE away completely.
+ *
+ * To use volatile list structure members then add the following line to
+ * FreeRTOSConfig.h (without the quotes):
+ * "#define configLIST_VOLATILE volatile"
+ */
+#ifndef configLIST_VOLATILE
+	#define configLIST_VOLATILE
+#endif /* configSUPPORT_CROSS_MODULE_OPTIMISATION */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Macros that can be used to place known values within the list structures,
+then check that the known values do not get corrupted during the execution of
+the application.   These may catch the list data structures being overwritten in
+memory.  They will not catch data errors caused by incorrect configuration or
+use of FreeRTOS.*/
+#if( configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES == 0 )
+	/* Define the macros to do nothing. */
+	#define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE
+	#define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE
+	#define listFIRST_LIST_INTEGRITY_CHECK_VALUE
+	#define listSECOND_LIST_INTEGRITY_CHECK_VALUE
+	#define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem )
+	#define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem )
+	#define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList )
+	#define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList )
+	#define listTEST_LIST_ITEM_INTEGRITY( pxItem )
+	#define listTEST_LIST_INTEGRITY( pxList )
+#else
+	/* Define macros that add new members into the list structures. */
+	#define listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE				TickType_t xListItemIntegrityValue1;
+	#define listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE				TickType_t xListItemIntegrityValue2;
+	#define listFIRST_LIST_INTEGRITY_CHECK_VALUE					TickType_t xListIntegrityValue1;
+	#define listSECOND_LIST_INTEGRITY_CHECK_VALUE					TickType_t xListIntegrityValue2;
+
+	/* Define macros that set the new structure members to known values. */
+	#define listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem )		( pxItem )->xListItemIntegrityValue1 = pdINTEGRITY_CHECK_VALUE
+	#define listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem )	( pxItem )->xListItemIntegrityValue2 = pdINTEGRITY_CHECK_VALUE
+	#define listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList )		( pxList )->xListIntegrityValue1 = pdINTEGRITY_CHECK_VALUE
+	#define listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList )		( pxList )->xListIntegrityValue2 = pdINTEGRITY_CHECK_VALUE
+
+	/* Define macros that will assert if one of the structure members does not
+	contain its expected value. */
+	#define listTEST_LIST_ITEM_INTEGRITY( pxItem )		configASSERT( ( ( pxItem )->xListItemIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxItem )->xListItemIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) )
+	#define listTEST_LIST_INTEGRITY( pxList )			configASSERT( ( ( pxList )->xListIntegrityValue1 == pdINTEGRITY_CHECK_VALUE ) && ( ( pxList )->xListIntegrityValue2 == pdINTEGRITY_CHECK_VALUE ) )
+#endif /* configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES */
+
+
+/*
+ * Definition of the only type of object that a list can contain.
+ */
+struct xLIST_ITEM
+{
+	listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE				/*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
+	configLIST_VOLATILE TickType_t xItemValue;			/*< The value being listed.  In most cases this is used to sort the list in descending order. */
+	struct xLIST_ITEM * configLIST_VOLATILE pxNext;		/*< Pointer to the next ListItem_t in the list. */
+	struct xLIST_ITEM * configLIST_VOLATILE pxPrevious;	/*< Pointer to the previous ListItem_t in the list. */
+	void * pvOwner;										/*< Pointer to the object (normally a TCB) that contains the list item.  There is therefore a two way link between the object containing the list item and the list item itself. */
+	void * configLIST_VOLATILE pvContainer;				/*< Pointer to the list in which this list item is placed (if any). */
+	listSECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE				/*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
+};
+typedef struct xLIST_ITEM ListItem_t;					/* For some reason lint wants this as two separate definitions. */
+
+struct xMINI_LIST_ITEM
+{
+	listFIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE				/*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
+	configLIST_VOLATILE TickType_t xItemValue;
+	struct xLIST_ITEM * configLIST_VOLATILE pxNext;
+	struct xLIST_ITEM * configLIST_VOLATILE pxPrevious;
+};
+typedef struct xMINI_LIST_ITEM MiniListItem_t;
+
+/*
+ * Definition of the type of queue used by the scheduler.
+ */
+typedef struct xLIST
+{
+	listFIRST_LIST_INTEGRITY_CHECK_VALUE				/*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
+	configLIST_VOLATILE UBaseType_t uxNumberOfItems;
+	ListItem_t * configLIST_VOLATILE pxIndex;		/*< Used to walk through the list.  Points to the last item returned by a call to listGET_OWNER_OF_NEXT_ENTRY (). */
+	MiniListItem_t xListEnd;						/*< List item that contains the maximum possible item value meaning it is always at the end of the list and is therefore used as a marker. */
+	listSECOND_LIST_INTEGRITY_CHECK_VALUE				/*< Set to a known value if configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
+} List_t;
+
+/*
+ * Access macro to set the owner of a list item.  The owner of a list item
+ * is the object (usually a TCB) that contains the list item.
+ *
+ * \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER
+ * \ingroup LinkedList
+ */
+#define listSET_LIST_ITEM_OWNER( pxListItem, pxOwner )		( ( pxListItem )->pvOwner = ( void * ) ( pxOwner ) )
+
+/*
+ * Access macro to get the owner of a list item.  The owner of a list item
+ * is the object (usually a TCB) that contains the list item.
+ *
+ * \page listSET_LIST_ITEM_OWNER listSET_LIST_ITEM_OWNER
+ * \ingroup LinkedList
+ */
+#define listGET_LIST_ITEM_OWNER( pxListItem )	( ( pxListItem )->pvOwner )
+
+/*
+ * Access macro to set the value of the list item.  In most cases the value is
+ * used to sort the list in descending order.
+ *
+ * \page listSET_LIST_ITEM_VALUE listSET_LIST_ITEM_VALUE
+ * \ingroup LinkedList
+ */
+#define listSET_LIST_ITEM_VALUE( pxListItem, xValue )	( ( pxListItem )->xItemValue = ( xValue ) )
+
+/*
+ * Access macro to retrieve the value of the list item.  The value can
+ * represent anything - for example the priority of a task, or the time at
+ * which a task should be unblocked.
+ *
+ * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE
+ * \ingroup LinkedList
+ */
+#define listGET_LIST_ITEM_VALUE( pxListItem )	( ( pxListItem )->xItemValue )
+
+/*
+ * Access macro to retrieve the value of the list item at the head of a given
+ * list.
+ *
+ * \page listGET_LIST_ITEM_VALUE listGET_LIST_ITEM_VALUE
+ * \ingroup LinkedList
+ */
+#define listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxList )	( ( ( pxList )->xListEnd ).pxNext->xItemValue )
+
+/*
+ * Return the list item at the head of the list.
+ *
+ * \page listGET_HEAD_ENTRY listGET_HEAD_ENTRY
+ * \ingroup LinkedList
+ */
+#define listGET_HEAD_ENTRY( pxList )	( ( ( pxList )->xListEnd ).pxNext )
+
+/*
+ * Return the list item at the head of the list.
+ *
+ * \page listGET_NEXT listGET_NEXT
+ * \ingroup LinkedList
+ */
+#define listGET_NEXT( pxListItem )	( ( pxListItem )->pxNext )
+
+/*
+ * Return the list item that marks the end of the list
+ *
+ * \page listGET_END_MARKER listGET_END_MARKER
+ * \ingroup LinkedList
+ */
+#define listGET_END_MARKER( pxList )	( ( ListItem_t const * ) ( &( ( pxList )->xListEnd ) ) )
+
+/*
+ * Access macro to determine if a list contains any items.  The macro will
+ * only have the value true if the list is empty.
+ *
+ * \page listLIST_IS_EMPTY listLIST_IS_EMPTY
+ * \ingroup LinkedList
+ */
+#define listLIST_IS_EMPTY( pxList )	( ( BaseType_t ) ( ( pxList )->uxNumberOfItems == ( UBaseType_t ) 0 ) )
+
+/*
+ * Access macro to return the number of items in the list.
+ */
+#define listCURRENT_LIST_LENGTH( pxList )	( ( pxList )->uxNumberOfItems )
+
+/*
+ * Access function to obtain the owner of the next entry in a list.
+ *
+ * The list member pxIndex is used to walk through a list.  Calling
+ * listGET_OWNER_OF_NEXT_ENTRY increments pxIndex to the next item in the list
+ * and returns that entry's pxOwner parameter.  Using multiple calls to this
+ * function it is therefore possible to move through every item contained in
+ * a list.
+ *
+ * The pxOwner parameter of a list item is a pointer to the object that owns
+ * the list item.  In the scheduler this is normally a task control block.
+ * The pxOwner parameter effectively creates a two way link between the list
+ * item and its owner.
+ *
+ * @param pxTCB pxTCB is set to the address of the owner of the next list item.
+ * @param pxList The list from which the next item owner is to be returned.
+ *
+ * \page listGET_OWNER_OF_NEXT_ENTRY listGET_OWNER_OF_NEXT_ENTRY
+ * \ingroup LinkedList
+ */
+#define listGET_OWNER_OF_NEXT_ENTRY( pxTCB, pxList )										\
+{																							\
+List_t * const pxConstList = ( pxList );													\
+	/* Increment the index to the next item and return the item, ensuring */				\
+	/* we don't return the marker used at the end of the list.  */							\
+	( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext;							\
+	if( ( void * ) ( pxConstList )->pxIndex == ( void * ) &( ( pxConstList )->xListEnd ) )	\
+	{																						\
+		( pxConstList )->pxIndex = ( pxConstList )->pxIndex->pxNext;						\
+	}																						\
+	( pxTCB ) = ( pxConstList )->pxIndex->pvOwner;											\
+}
+
+
+/*
+ * Access function to obtain the owner of the first entry in a list.  Lists
+ * are normally sorted in ascending item value order.
+ *
+ * This function returns the pxOwner member of the first item in the list.
+ * The pxOwner parameter of a list item is a pointer to the object that owns
+ * the list item.  In the scheduler this is normally a task control block.
+ * The pxOwner parameter effectively creates a two way link between the list
+ * item and its owner.
+ *
+ * @param pxList The list from which the owner of the head item is to be
+ * returned.
+ *
+ * \page listGET_OWNER_OF_HEAD_ENTRY listGET_OWNER_OF_HEAD_ENTRY
+ * \ingroup LinkedList
+ */
+#define listGET_OWNER_OF_HEAD_ENTRY( pxList )  ( (&( ( pxList )->xListEnd ))->pxNext->pvOwner )
+
+/*
+ * Check to see if a list item is within a list.  The list item maintains a
+ * "container" pointer that points to the list it is in.  All this macro does
+ * is check to see if the container and the list match.
+ *
+ * @param pxList The list we want to know if the list item is within.
+ * @param pxListItem The list item we want to know if is in the list.
+ * @return pdTRUE if the list item is in the list, otherwise pdFALSE.
+ */
+#define listIS_CONTAINED_WITHIN( pxList, pxListItem ) ( ( BaseType_t ) ( ( pxListItem )->pvContainer == ( void * ) ( pxList ) ) )
+
+/*
+ * Return the list a list item is contained within (referenced from).
+ *
+ * @param pxListItem The list item being queried.
+ * @return A pointer to the List_t object that references the pxListItem
+ */
+#define listLIST_ITEM_CONTAINER( pxListItem ) ( ( pxListItem )->pvContainer )
+
+/*
+ * This provides a crude means of knowing if a list has been initialised, as
+ * pxList->xListEnd.xItemValue is set to portMAX_DELAY by the vListInitialise()
+ * function.
+ */
+#define listLIST_IS_INITIALISED( pxList ) ( ( pxList )->xListEnd.xItemValue == portMAX_DELAY )
+
+/*
+ * Must be called before a list is used!  This initialises all the members
+ * of the list structure and inserts the xListEnd item into the list as a
+ * marker to the back of the list.
+ *
+ * @param pxList Pointer to the list being initialised.
+ *
+ * \page vListInitialise vListInitialise
+ * \ingroup LinkedList
+ */
+void vListInitialise( List_t * const pxList );
+
+/*
+ * Must be called before a list item is used.  This sets the list container to
+ * null so the item does not think that it is already contained in a list.
+ *
+ * @param pxItem Pointer to the list item being initialised.
+ *
+ * \page vListInitialiseItem vListInitialiseItem
+ * \ingroup LinkedList
+ */
+void vListInitialiseItem( ListItem_t * const pxItem );
+
+/*
+ * Insert a list item into a list.  The item will be inserted into the list in
+ * a position determined by its item value (descending item value order).
+ *
+ * @param pxList The list into which the item is to be inserted.
+ *
+ * @param pxNewListItem The item that is to be placed in the list.
+ *
+ * \page vListInsert vListInsert
+ * \ingroup LinkedList
+ */
+void vListInsert( List_t * const pxList, ListItem_t * const pxNewListItem );
+
+/*
+ * Insert a list item into a list.  The item will be inserted in a position
+ * such that it will be the last item within the list returned by multiple
+ * calls to listGET_OWNER_OF_NEXT_ENTRY.
+ *
+ * The list member pvIndex is used to walk through a list.  Calling
+ * listGET_OWNER_OF_NEXT_ENTRY increments pvIndex to the next item in the list.
+ * Placing an item in a list using vListInsertEnd effectively places the item
+ * in the list position pointed to by pvIndex.  This means that every other
+ * item within the list will be returned by listGET_OWNER_OF_NEXT_ENTRY before
+ * the pvIndex parameter again points to the item being inserted.
+ *
+ * @param pxList The list into which the item is to be inserted.
+ *
+ * @param pxNewListItem The list item to be inserted into the list.
+ *
+ * \page vListInsertEnd vListInsertEnd
+ * \ingroup LinkedList
+ */
+void vListInsertEnd( List_t * const pxList, ListItem_t * const pxNewListItem );
+
+/*
+ * Remove an item from a list.  The list item has a pointer to the list that
+ * it is in, so only the list item need be passed into the function.
+ *
+ * @param uxListRemove The item to be removed.  The item will remove itself from
+ * the list pointed to by it's pxContainer parameter.
+ *
+ * @return The number of items that remain in the list after the list item has
+ * been removed.
+ *
+ * \page uxListRemove uxListRemove
+ * \ingroup LinkedList
+ */
+UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove );
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/include/mpu_wrappers.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/include/mpu_wrappers.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,158 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+#ifndef MPU_WRAPPERS_H
+#define MPU_WRAPPERS_H
+
+/* This file redefines API functions to be called through a wrapper macro, but
+only for ports that are using the MPU. */
+#ifdef portUSING_MPU_WRAPPERS
+
+	/* MPU_WRAPPERS_INCLUDED_FROM_API_FILE will be defined when this file is
+	included from queue.c or task.c to prevent it from having an effect within
+	those files. */
+	#ifndef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
+
+		#define xTaskGenericCreate				MPU_xTaskGenericCreate
+		#define vTaskAllocateMPURegions			MPU_vTaskAllocateMPURegions
+		#define vTaskDelete						MPU_vTaskDelete
+		#define vTaskDelayUntil					MPU_vTaskDelayUntil
+		#define vTaskDelay						MPU_vTaskDelay
+		#define uxTaskPriorityGet				MPU_uxTaskPriorityGet
+		#define vTaskPrioritySet				MPU_vTaskPrioritySet
+		#define eTaskGetState					MPU_eTaskGetState
+		#define vTaskSuspend					MPU_vTaskSuspend
+		#define vTaskResume						MPU_vTaskResume
+		#define vTaskSuspendAll					MPU_vTaskSuspendAll
+		#define xTaskResumeAll					MPU_xTaskResumeAll
+		#define xTaskGetTickCount				MPU_xTaskGetTickCount
+		#define uxTaskGetNumberOfTasks			MPU_uxTaskGetNumberOfTasks
+		#define vTaskList						MPU_vTaskList
+		#define vTaskGetRunTimeStats			MPU_vTaskGetRunTimeStats
+		#define vTaskSetApplicationTaskTag		MPU_vTaskSetApplicationTaskTag
+		#define xTaskGetApplicationTaskTag		MPU_xTaskGetApplicationTaskTag
+		#define xTaskCallApplicationTaskHook	MPU_xTaskCallApplicationTaskHook
+		#define uxTaskGetStackHighWaterMark		MPU_uxTaskGetStackHighWaterMark
+		#define xTaskGetCurrentTaskHandle		MPU_xTaskGetCurrentTaskHandle
+		#define xTaskGetSchedulerState			MPU_xTaskGetSchedulerState
+		#define xTaskGetIdleTaskHandle			MPU_xTaskGetIdleTaskHandle
+		#define uxTaskGetSystemState			MPU_uxTaskGetSystemState
+
+		#define xQueueGenericCreate				MPU_xQueueGenericCreate
+		#define xQueueCreateMutex				MPU_xQueueCreateMutex
+		#define xQueueGiveMutexRecursive		MPU_xQueueGiveMutexRecursive
+		#define xQueueTakeMutexRecursive		MPU_xQueueTakeMutexRecursive
+		#define xQueueCreateCountingSemaphore	MPU_xQueueCreateCountingSemaphore
+		#define xQueueGenericSend				MPU_xQueueGenericSend
+		#define xQueueAltGenericSend			MPU_xQueueAltGenericSend
+		#define xQueueAltGenericReceive			MPU_xQueueAltGenericReceive
+		#define xQueueGenericReceive			MPU_xQueueGenericReceive
+		#define uxQueueMessagesWaiting			MPU_uxQueueMessagesWaiting
+		#define vQueueDelete					MPU_vQueueDelete
+		#define xQueueGenericReset				MPU_xQueueGenericReset
+		#define xQueueCreateSet					MPU_xQueueCreateSet
+		#define xQueueSelectFromSet				MPU_xQueueSelectFromSet
+		#define xQueueAddToSet					MPU_xQueueAddToSet
+		#define xQueueRemoveFromSet				MPU_xQueueRemoveFromSet
+		#define xQueuePeekFromISR				MPU_xQueuePeekFromISR
+		#define xQueueGetMutexHolder			MPU_xQueueGetMutexHolder
+
+		#define pvPortMalloc					MPU_pvPortMalloc
+		#define vPortFree						MPU_vPortFree
+		#define xPortGetFreeHeapSize			MPU_xPortGetFreeHeapSize
+		#define vPortInitialiseBlocks			MPU_vPortInitialiseBlocks
+
+		#if configQUEUE_REGISTRY_SIZE > 0
+			#define vQueueAddToRegistry				MPU_vQueueAddToRegistry
+			#define vQueueUnregisterQueue			MPU_vQueueUnregisterQueue
+		#endif
+
+		/* Remove the privileged function macro. */
+		#define PRIVILEGED_FUNCTION
+
+	#else /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */
+
+		/* Ensure API functions go in the privileged execution section. */
+		#define PRIVILEGED_FUNCTION __attribute__((section("privileged_functions")))
+		#define PRIVILEGED_DATA __attribute__((section("privileged_data")))
+
+	#endif /* MPU_WRAPPERS_INCLUDED_FROM_API_FILE */
+
+#else /* portUSING_MPU_WRAPPERS */
+
+	#define PRIVILEGED_FUNCTION
+	#define PRIVILEGED_DATA
+	#define portUSING_MPU_WRAPPERS 0
+
+#endif /* portUSING_MPU_WRAPPERS */
+
+
+#endif /* MPU_WRAPPERS_H */
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/include/portable.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/include/portable.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,201 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+/*-----------------------------------------------------------
+ * Portable layer API.  Each function must be defined for each port.
+ *----------------------------------------------------------*/
+
+#ifndef PORTABLE_H
+#define PORTABLE_H
+
+/* Each FreeRTOS port has a unique portmacro.h header file.  Originally a
+pre-processor definition was used to ensure the pre-processor found the correct
+portmacro.h file for the port being used.  That scheme was deprecated in favour
+of setting the compiler's include path such that it found the correct
+portmacro.h file - removing the need for the constant and allowing the
+portmacro.h file to be located anywhere in relation to the port being used.
+Purely for reasons of backward compatibility the old method is still valid, but
+to make it clear that new projects should not use it, support for the port
+specific constants has been moved into the deprecated_definitions.h header
+file. */
+#include "deprecated_definitions.h"
+
+/* If portENTER_CRITICAL is not defined then including deprecated_definitions.h
+did not result in a portmacro.h header file being included - and it should be
+included here.  In this case the path to the correct portmacro.h header file
+must be set in the compiler's include path. */
+#ifndef portENTER_CRITICAL
+	#include "portmacro.h"
+#endif
+
+#if portBYTE_ALIGNMENT == 8
+	#define portBYTE_ALIGNMENT_MASK ( 0x0007 )
+#endif
+
+#if portBYTE_ALIGNMENT == 4
+	#define portBYTE_ALIGNMENT_MASK	( 0x0003 )
+#endif
+
+#if portBYTE_ALIGNMENT == 2
+	#define portBYTE_ALIGNMENT_MASK	( 0x0001 )
+#endif
+
+#if portBYTE_ALIGNMENT == 1
+	#define portBYTE_ALIGNMENT_MASK	( 0x0000 )
+#endif
+
+#ifndef portBYTE_ALIGNMENT_MASK
+	#error "Invalid portBYTE_ALIGNMENT definition"
+#endif
+
+#ifndef portNUM_CONFIGURABLE_REGIONS
+	#define portNUM_CONFIGURABLE_REGIONS 1
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "mpu_wrappers.h"
+#include "projdefs.h"
+
+/*
+ * Setup the stack of a new task so it is ready to be placed under the
+ * scheduler control.  The registers have to be placed on the stack in
+ * the order that the port expects to find them.
+ *
+ */
+#if( portUSING_MPU_WRAPPERS == 1 )
+	StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters, BaseType_t xRunPrivileged ) PRIVILEGED_FUNCTION;
+#else
+	StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters ) PRIVILEGED_FUNCTION;
+#endif
+
+/* Used by heap_5.c. */
+typedef struct HeapRegion
+{
+	uint8_t *pucStartAddress;
+	size_t xSizeInBytes;
+} HeapRegion_t;
+
+/*
+ * Used to define multiple heap regions for use by heap_5.c.  This function
+ * must be called before any calls to pvPortMalloc() - not creating a task,
+ * queue, semaphore, mutex, software timer, event group, etc. will result in
+ * pvPortMalloc being called.
+ *
+ * pxHeapRegions passes in an array of HeapRegion_t structures - each of which
+ * defines a region of memory that can be used as the heap.  The array is
+ * terminated by a HeapRegions_t structure that has a size of 0.  The region
+ * with the lowest start address must appear first in the array.
+ */
+void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions );
+
+
+/*
+ * Map to the memory management routines required for the port.
+ */
+void *pvPortMalloc( size_t xSize ) PRIVILEGED_FUNCTION;
+void vPortFree( void *pv ) PRIVILEGED_FUNCTION;
+void vPortInitialiseBlocks( void ) PRIVILEGED_FUNCTION;
+size_t xPortGetFreeHeapSize( void ) PRIVILEGED_FUNCTION;
+size_t xPortGetMinimumEverFreeHeapSize( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * Setup the hardware ready for the scheduler to take control.  This generally
+ * sets up a tick interrupt and sets timers for the correct tick frequency.
+ */
+BaseType_t xPortStartScheduler( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * Undo any hardware/ISR setup that was performed by xPortStartScheduler() so
+ * the hardware is left in its original condition after the scheduler stops
+ * executing.
+ */
+void vPortEndScheduler( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * The structures and methods of manipulating the MPU are contained within the
+ * port layer.
+ *
+ * Fills the xMPUSettings structure with the memory region information
+ * contained in xRegions.
+ */
+#if( portUSING_MPU_WRAPPERS == 1 )
+	struct xMEMORY_REGION;
+	void vPortStoreTaskMPUSettings( xMPU_SETTINGS *xMPUSettings, const struct xMEMORY_REGION * const xRegions, StackType_t *pxBottomOfStack, uint16_t usStackDepth ) PRIVILEGED_FUNCTION;
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* PORTABLE_H */
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/include/projdefs.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/include/projdefs.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,115 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+#ifndef PROJDEFS_H
+#define PROJDEFS_H
+
+/*
+ * Defines the prototype to which task functions must conform.  Defined in this
+ * file to ensure the type is known before portable.h is included.
+ */
+typedef void (*TaskFunction_t)( void * );
+
+/* Converts a time in milliseconds to a time in ticks. */
+#define pdMS_TO_TICKS( xTimeInMs ) ( ( TickType_t ) ( ( ( TickType_t ) ( xTimeInMs ) * ( TickType_t ) configTICK_RATE_HZ ) / ( TickType_t ) 1000 ) )
+
+#define pdFALSE			( ( BaseType_t ) 0 )
+#define pdTRUE			( ( BaseType_t ) 1 )
+
+#define pdPASS			( pdTRUE )
+#define pdFAIL			( pdFALSE )
+#define errQUEUE_EMPTY	( ( BaseType_t ) 0 )
+#define errQUEUE_FULL	( ( BaseType_t ) 0 )
+
+/* FreeRTOS error definitions. */
+#define errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY	( -1 )
+#define errQUEUE_BLOCKED						( -4 )
+#define errQUEUE_YIELD							( -5 )
+
+/* Macros used for basic data corruption checks. */
+#ifndef configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES
+	#define configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES 0
+#endif
+
+#if( configUSE_16_BIT_TICKS == 1 )
+	#define pdINTEGRITY_CHECK_VALUE 0x5a5a
+#else
+	#define pdINTEGRITY_CHECK_VALUE 0x5a5a5a5aUL
+#endif
+
+/* The following endian values are used by FreeRTOS+ components, not FreeRTOS
+itself. */
+#define pdFREERTOS_LITTLE_ENDIAN	0
+#define pdFREERTOS_BIG_ENDIAN		1
+
+#endif /* PROJDEFS_H */
+
+
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/include/queue.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/include/queue.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,1692 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+
+#ifndef QUEUE_H
+#define QUEUE_H
+
+#ifndef INC_FREERTOS_H
+	#error "include FreeRTOS.h" must appear in source files before "include queue.h"
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/**
+ * Type by which queues are referenced.  For example, a call to xQueueCreate()
+ * returns an QueueHandle_t variable that can then be used as a parameter to
+ * xQueueSend(), xQueueReceive(), etc.
+ */
+typedef void * QueueHandle_t;
+
+/**
+ * Type by which queue sets are referenced.  For example, a call to
+ * xQueueCreateSet() returns an xQueueSet variable that can then be used as a
+ * parameter to xQueueSelectFromSet(), xQueueAddToSet(), etc.
+ */
+typedef void * QueueSetHandle_t;
+
+/**
+ * Queue sets can contain both queues and semaphores, so the
+ * QueueSetMemberHandle_t is defined as a type to be used where a parameter or
+ * return value can be either an QueueHandle_t or an SemaphoreHandle_t.
+ */
+typedef void * QueueSetMemberHandle_t;
+
+/* For internal use only. */
+#define	queueSEND_TO_BACK		( ( BaseType_t ) 0 )
+#define	queueSEND_TO_FRONT		( ( BaseType_t ) 1 )
+#define queueOVERWRITE			( ( BaseType_t ) 2 )
+
+/* For internal use only.  These definitions *must* match those in queue.c. */
+#define queueQUEUE_TYPE_BASE				( ( uint8_t ) 0U )
+#define queueQUEUE_TYPE_SET					( ( uint8_t ) 0U )
+#define queueQUEUE_TYPE_MUTEX 				( ( uint8_t ) 1U )
+#define queueQUEUE_TYPE_COUNTING_SEMAPHORE	( ( uint8_t ) 2U )
+#define queueQUEUE_TYPE_BINARY_SEMAPHORE	( ( uint8_t ) 3U )
+#define queueQUEUE_TYPE_RECURSIVE_MUTEX		( ( uint8_t ) 4U )
+
+/**
+ * queue. h
+ * <pre>
+ QueueHandle_t xQueueCreate(
+							  UBaseType_t uxQueueLength,
+							  UBaseType_t uxItemSize
+						  );
+ * </pre>
+ *
+ * Creates a new queue instance.  This allocates the storage required by the
+ * new queue and returns a handle for the queue.
+ *
+ * @param uxQueueLength The maximum number of items that the queue can contain.
+ *
+ * @param uxItemSize The number of bytes each item in the queue will require.
+ * Items are queued by copy, not by reference, so this is the number of bytes
+ * that will be copied for each posted item.  Each item on the queue must be
+ * the same size.
+ *
+ * @return If the queue is successfully create then a handle to the newly
+ * created queue is returned.  If the queue cannot be created then 0 is
+ * returned.
+ *
+ * Example usage:
+   <pre>
+ struct AMessage
+ {
+	char ucMessageID;
+	char ucData[ 20 ];
+ };
+
+ void vATask( void *pvParameters )
+ {
+ QueueHandle_t xQueue1, xQueue2;
+
+	// Create a queue capable of containing 10 uint32_t values.
+	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+	if( xQueue1 == 0 )
+	{
+		// Queue was not created and must not be used.
+	}
+
+	// Create a queue capable of containing 10 pointers to AMessage structures.
+	// These should be passed by pointer as they contain a lot of data.
+	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+	if( xQueue2 == 0 )
+	{
+		// Queue was not created and must not be used.
+	}
+
+	// ... Rest of task code.
+ }
+ </pre>
+ * \defgroup xQueueCreate xQueueCreate
+ * \ingroup QueueManagement
+ */
+#define xQueueCreate( uxQueueLength, uxItemSize ) xQueueGenericCreate( uxQueueLength, uxItemSize, queueQUEUE_TYPE_BASE )
+
+/**
+ * queue. h
+ * <pre>
+ BaseType_t xQueueSendToToFront(
+								   QueueHandle_t	xQueue,
+								   const void		*pvItemToQueue,
+								   TickType_t		xTicksToWait
+							   );
+ * </pre>
+ *
+ * This is a macro that calls xQueueGenericSend().
+ *
+ * Post an item to the front of a queue.  The item is queued by copy, not by
+ * reference.  This function must not be called from an interrupt service
+ * routine.  See xQueueSendFromISR () for an alternative which may be used
+ * in an ISR.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param xTicksToWait The maximum amount of time the task should block
+ * waiting for space to become available on the queue, should it already
+ * be full.  The call will return immediately if this is set to 0 and the
+ * queue is full.  The time is defined in tick periods so the constant
+ * portTICK_PERIOD_MS should be used to convert to real time if this is required.
+ *
+ * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL.
+ *
+ * Example usage:
+   <pre>
+ struct AMessage
+ {
+	char ucMessageID;
+	char ucData[ 20 ];
+ } xMessage;
+
+ uint32_t ulVar = 10UL;
+
+ void vATask( void *pvParameters )
+ {
+ QueueHandle_t xQueue1, xQueue2;
+ struct AMessage *pxMessage;
+
+	// Create a queue capable of containing 10 uint32_t values.
+	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+
+	// Create a queue capable of containing 10 pointers to AMessage structures.
+	// These should be passed by pointer as they contain a lot of data.
+	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+
+	// ...
+
+	if( xQueue1 != 0 )
+	{
+		// Send an uint32_t.  Wait for 10 ticks for space to become
+		// available if necessary.
+		if( xQueueSendToFront( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
+		{
+			// Failed to post the message, even after 10 ticks.
+		}
+	}
+
+	if( xQueue2 != 0 )
+	{
+		// Send a pointer to a struct AMessage object.  Don't block if the
+		// queue is already full.
+		pxMessage = & xMessage;
+		xQueueSendToFront( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
+	}
+
+	// ... Rest of task code.
+ }
+ </pre>
+ * \defgroup xQueueSend xQueueSend
+ * \ingroup QueueManagement
+ */
+#define xQueueSendToFront( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_FRONT )
+
+/**
+ * queue. h
+ * <pre>
+ BaseType_t xQueueSendToBack(
+								   QueueHandle_t	xQueue,
+								   const void		*pvItemToQueue,
+								   TickType_t		xTicksToWait
+							   );
+ * </pre>
+ *
+ * This is a macro that calls xQueueGenericSend().
+ *
+ * Post an item to the back of a queue.  The item is queued by copy, not by
+ * reference.  This function must not be called from an interrupt service
+ * routine.  See xQueueSendFromISR () for an alternative which may be used
+ * in an ISR.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param xTicksToWait The maximum amount of time the task should block
+ * waiting for space to become available on the queue, should it already
+ * be full.  The call will return immediately if this is set to 0 and the queue
+ * is full.  The  time is defined in tick periods so the constant
+ * portTICK_PERIOD_MS should be used to convert to real time if this is required.
+ *
+ * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL.
+ *
+ * Example usage:
+   <pre>
+ struct AMessage
+ {
+	char ucMessageID;
+	char ucData[ 20 ];
+ } xMessage;
+
+ uint32_t ulVar = 10UL;
+
+ void vATask( void *pvParameters )
+ {
+ QueueHandle_t xQueue1, xQueue2;
+ struct AMessage *pxMessage;
+
+	// Create a queue capable of containing 10 uint32_t values.
+	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+
+	// Create a queue capable of containing 10 pointers to AMessage structures.
+	// These should be passed by pointer as they contain a lot of data.
+	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+
+	// ...
+
+	if( xQueue1 != 0 )
+	{
+		// Send an uint32_t.  Wait for 10 ticks for space to become
+		// available if necessary.
+		if( xQueueSendToBack( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
+		{
+			// Failed to post the message, even after 10 ticks.
+		}
+	}
+
+	if( xQueue2 != 0 )
+	{
+		// Send a pointer to a struct AMessage object.  Don't block if the
+		// queue is already full.
+		pxMessage = & xMessage;
+		xQueueSendToBack( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
+	}
+
+	// ... Rest of task code.
+ }
+ </pre>
+ * \defgroup xQueueSend xQueueSend
+ * \ingroup QueueManagement
+ */
+#define xQueueSendToBack( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK )
+
+/**
+ * queue. h
+ * <pre>
+ BaseType_t xQueueSend(
+							  QueueHandle_t xQueue,
+							  const void * pvItemToQueue,
+							  TickType_t xTicksToWait
+						 );
+ * </pre>
+ *
+ * This is a macro that calls xQueueGenericSend().  It is included for
+ * backward compatibility with versions of FreeRTOS.org that did not
+ * include the xQueueSendToFront() and xQueueSendToBack() macros.  It is
+ * equivalent to xQueueSendToBack().
+ *
+ * Post an item on a queue.  The item is queued by copy, not by reference.
+ * This function must not be called from an interrupt service routine.
+ * See xQueueSendFromISR () for an alternative which may be used in an ISR.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param xTicksToWait The maximum amount of time the task should block
+ * waiting for space to become available on the queue, should it already
+ * be full.  The call will return immediately if this is set to 0 and the
+ * queue is full.  The time is defined in tick periods so the constant
+ * portTICK_PERIOD_MS should be used to convert to real time if this is required.
+ *
+ * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL.
+ *
+ * Example usage:
+   <pre>
+ struct AMessage
+ {
+	char ucMessageID;
+	char ucData[ 20 ];
+ } xMessage;
+
+ uint32_t ulVar = 10UL;
+
+ void vATask( void *pvParameters )
+ {
+ QueueHandle_t xQueue1, xQueue2;
+ struct AMessage *pxMessage;
+
+	// Create a queue capable of containing 10 uint32_t values.
+	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+
+	// Create a queue capable of containing 10 pointers to AMessage structures.
+	// These should be passed by pointer as they contain a lot of data.
+	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+
+	// ...
+
+	if( xQueue1 != 0 )
+	{
+		// Send an uint32_t.  Wait for 10 ticks for space to become
+		// available if necessary.
+		if( xQueueSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10 ) != pdPASS )
+		{
+			// Failed to post the message, even after 10 ticks.
+		}
+	}
+
+	if( xQueue2 != 0 )
+	{
+		// Send a pointer to a struct AMessage object.  Don't block if the
+		// queue is already full.
+		pxMessage = & xMessage;
+		xQueueSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0 );
+	}
+
+	// ... Rest of task code.
+ }
+ </pre>
+ * \defgroup xQueueSend xQueueSend
+ * \ingroup QueueManagement
+ */
+#define xQueueSend( xQueue, pvItemToQueue, xTicksToWait ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK )
+
+/**
+ * queue. h
+ * <pre>
+ BaseType_t xQueueOverwrite(
+							  QueueHandle_t xQueue,
+							  const void * pvItemToQueue
+						 );
+ * </pre>
+ *
+ * Only for use with queues that have a length of one - so the queue is either
+ * empty or full.
+ *
+ * Post an item on a queue.  If the queue is already full then overwrite the
+ * value held in the queue.  The item is queued by copy, not by reference.
+ *
+ * This function must not be called from an interrupt service routine.
+ * See xQueueOverwriteFromISR () for an alternative which may be used in an ISR.
+ *
+ * @param xQueue The handle of the queue to which the data is being sent.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @return xQueueOverwrite() is a macro that calls xQueueGenericSend(), and
+ * therefore has the same return values as xQueueSendToFront().  However, pdPASS
+ * is the only value that can be returned because xQueueOverwrite() will write
+ * to the queue even when the queue is already full.
+ *
+ * Example usage:
+   <pre>
+
+ void vFunction( void *pvParameters )
+ {
+ QueueHandle_t xQueue;
+ uint32_t ulVarToSend, ulValReceived;
+
+	// Create a queue to hold one uint32_t value.  It is strongly
+	// recommended *not* to use xQueueOverwrite() on queues that can
+	// contain more than one value, and doing so will trigger an assertion
+	// if configASSERT() is defined.
+	xQueue = xQueueCreate( 1, sizeof( uint32_t ) );
+
+	// Write the value 10 to the queue using xQueueOverwrite().
+	ulVarToSend = 10;
+	xQueueOverwrite( xQueue, &ulVarToSend );
+
+	// Peeking the queue should now return 10, but leave the value 10 in
+	// the queue.  A block time of zero is used as it is known that the
+	// queue holds a value.
+	ulValReceived = 0;
+	xQueuePeek( xQueue, &ulValReceived, 0 );
+
+	if( ulValReceived != 10 )
+	{
+		// Error unless the item was removed by a different task.
+	}
+
+	// The queue is still full.  Use xQueueOverwrite() to overwrite the
+	// value held in the queue with 100.
+	ulVarToSend = 100;
+	xQueueOverwrite( xQueue, &ulVarToSend );
+
+	// This time read from the queue, leaving the queue empty once more.
+	// A block time of 0 is used again.
+	xQueueReceive( xQueue, &ulValReceived, 0 );
+
+	// The value read should be the last value written, even though the
+	// queue was already full when the value was written.
+	if( ulValReceived != 100 )
+	{
+		// Error!
+	}
+
+	// ...
+}
+ </pre>
+ * \defgroup xQueueOverwrite xQueueOverwrite
+ * \ingroup QueueManagement
+ */
+#define xQueueOverwrite( xQueue, pvItemToQueue ) xQueueGenericSend( ( xQueue ), ( pvItemToQueue ), 0, queueOVERWRITE )
+
+
+/**
+ * queue. h
+ * <pre>
+ BaseType_t xQueueGenericSend(
+									QueueHandle_t xQueue,
+									const void * pvItemToQueue,
+									TickType_t xTicksToWait
+									BaseType_t xCopyPosition
+								);
+ * </pre>
+ *
+ * It is preferred that the macros xQueueSend(), xQueueSendToFront() and
+ * xQueueSendToBack() are used in place of calling this function directly.
+ *
+ * Post an item on a queue.  The item is queued by copy, not by reference.
+ * This function must not be called from an interrupt service routine.
+ * See xQueueSendFromISR () for an alternative which may be used in an ISR.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param xTicksToWait The maximum amount of time the task should block
+ * waiting for space to become available on the queue, should it already
+ * be full.  The call will return immediately if this is set to 0 and the
+ * queue is full.  The time is defined in tick periods so the constant
+ * portTICK_PERIOD_MS should be used to convert to real time if this is required.
+ *
+ * @param xCopyPosition Can take the value queueSEND_TO_BACK to place the
+ * item at the back of the queue, or queueSEND_TO_FRONT to place the item
+ * at the front of the queue (for high priority messages).
+ *
+ * @return pdTRUE if the item was successfully posted, otherwise errQUEUE_FULL.
+ *
+ * Example usage:
+   <pre>
+ struct AMessage
+ {
+	char ucMessageID;
+	char ucData[ 20 ];
+ } xMessage;
+
+ uint32_t ulVar = 10UL;
+
+ void vATask( void *pvParameters )
+ {
+ QueueHandle_t xQueue1, xQueue2;
+ struct AMessage *pxMessage;
+
+	// Create a queue capable of containing 10 uint32_t values.
+	xQueue1 = xQueueCreate( 10, sizeof( uint32_t ) );
+
+	// Create a queue capable of containing 10 pointers to AMessage structures.
+	// These should be passed by pointer as they contain a lot of data.
+	xQueue2 = xQueueCreate( 10, sizeof( struct AMessage * ) );
+
+	// ...
+
+	if( xQueue1 != 0 )
+	{
+		// Send an uint32_t.  Wait for 10 ticks for space to become
+		// available if necessary.
+		if( xQueueGenericSend( xQueue1, ( void * ) &ulVar, ( TickType_t ) 10, queueSEND_TO_BACK ) != pdPASS )
+		{
+			// Failed to post the message, even after 10 ticks.
+		}
+	}
+
+	if( xQueue2 != 0 )
+	{
+		// Send a pointer to a struct AMessage object.  Don't block if the
+		// queue is already full.
+		pxMessage = & xMessage;
+		xQueueGenericSend( xQueue2, ( void * ) &pxMessage, ( TickType_t ) 0, queueSEND_TO_BACK );
+	}
+
+	// ... Rest of task code.
+ }
+ </pre>
+ * \defgroup xQueueSend xQueueSend
+ * \ingroup QueueManagement
+ */
+BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQueue, TickType_t xTicksToWait, const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION;
+
+/**
+ * queue. h
+ * <pre>
+ BaseType_t xQueuePeek(
+							 QueueHandle_t xQueue,
+							 void *pvBuffer,
+							 TickType_t xTicksToWait
+						 );</pre>
+ *
+ * This is a macro that calls the xQueueGenericReceive() function.
+ *
+ * Receive an item from a queue without removing the item from the queue.
+ * The item is received by copy so a buffer of adequate size must be
+ * provided.  The number of bytes copied into the buffer was defined when
+ * the queue was created.
+ *
+ * Successfully received items remain on the queue so will be returned again
+ * by the next call, or a call to xQueueReceive().
+ *
+ * This macro must not be used in an interrupt service routine.  See
+ * xQueuePeekFromISR() for an alternative that can be called from an interrupt
+ * service routine.
+ *
+ * @param xQueue The handle to the queue from which the item is to be
+ * received.
+ *
+ * @param pvBuffer Pointer to the buffer into which the received item will
+ * be copied.
+ *
+ * @param xTicksToWait The maximum amount of time the task should block
+ * waiting for an item to receive should the queue be empty at the time
+ * of the call.	 The time is defined in tick periods so the constant
+ * portTICK_PERIOD_MS should be used to convert to real time if this is required.
+ * xQueuePeek() will return immediately if xTicksToWait is 0 and the queue
+ * is empty.
+ *
+ * @return pdTRUE if an item was successfully received from the queue,
+ * otherwise pdFALSE.
+ *
+ * Example usage:
+   <pre>
+ struct AMessage
+ {
+	char ucMessageID;
+	char ucData[ 20 ];
+ } xMessage;
+
+ QueueHandle_t xQueue;
+
+ // Task to create a queue and post a value.
+ void vATask( void *pvParameters )
+ {
+ struct AMessage *pxMessage;
+
+	// Create a queue capable of containing 10 pointers to AMessage structures.
+	// These should be passed by pointer as they contain a lot of data.
+	xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );
+	if( xQueue == 0 )
+	{
+		// Failed to create the queue.
+	}
+
+	// ...
+
+	// Send a pointer to a struct AMessage object.  Don't block if the
+	// queue is already full.
+	pxMessage = & xMessage;
+	xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 );
+
+	// ... Rest of task code.
+ }
+
+ // Task to peek the data from the queue.
+ void vADifferentTask( void *pvParameters )
+ {
+ struct AMessage *pxRxedMessage;
+
+	if( xQueue != 0 )
+	{
+		// Peek a message on the created queue.  Block for 10 ticks if a
+		// message is not immediately available.
+		if( xQueuePeek( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) )
+		{
+			// pcRxedMessage now points to the struct AMessage variable posted
+			// by vATask, but the item still remains on the queue.
+		}
+	}
+
+	// ... Rest of task code.
+ }
+ </pre>
+ * \defgroup xQueueReceive xQueueReceive
+ * \ingroup QueueManagement
+ */
+#define xQueuePeek( xQueue, pvBuffer, xTicksToWait ) xQueueGenericReceive( ( xQueue ), ( pvBuffer ), ( xTicksToWait ), pdTRUE )
+
+/**
+ * queue. h
+ * <pre>
+ BaseType_t xQueuePeekFromISR(
+									QueueHandle_t xQueue,
+									void *pvBuffer,
+								);</pre>
+ *
+ * A version of xQueuePeek() that can be called from an interrupt service
+ * routine (ISR).
+ *
+ * Receive an item from a queue without removing the item from the queue.
+ * The item is received by copy so a buffer of adequate size must be
+ * provided.  The number of bytes copied into the buffer was defined when
+ * the queue was created.
+ *
+ * Successfully received items remain on the queue so will be returned again
+ * by the next call, or a call to xQueueReceive().
+ *
+ * @param xQueue The handle to the queue from which the item is to be
+ * received.
+ *
+ * @param pvBuffer Pointer to the buffer into which the received item will
+ * be copied.
+ *
+ * @return pdTRUE if an item was successfully received from the queue,
+ * otherwise pdFALSE.
+ *
+ * \defgroup xQueuePeekFromISR xQueuePeekFromISR
+ * \ingroup QueueManagement
+ */
+BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue, void * const pvBuffer ) PRIVILEGED_FUNCTION;
+
+/**
+ * queue. h
+ * <pre>
+ BaseType_t xQueueReceive(
+								 QueueHandle_t xQueue,
+								 void *pvBuffer,
+								 TickType_t xTicksToWait
+							);</pre>
+ *
+ * This is a macro that calls the xQueueGenericReceive() function.
+ *
+ * Receive an item from a queue.  The item is received by copy so a buffer of
+ * adequate size must be provided.  The number of bytes copied into the buffer
+ * was defined when the queue was created.
+ *
+ * Successfully received items are removed from the queue.
+ *
+ * This function must not be used in an interrupt service routine.  See
+ * xQueueReceiveFromISR for an alternative that can.
+ *
+ * @param xQueue The handle to the queue from which the item is to be
+ * received.
+ *
+ * @param pvBuffer Pointer to the buffer into which the received item will
+ * be copied.
+ *
+ * @param xTicksToWait The maximum amount of time the task should block
+ * waiting for an item to receive should the queue be empty at the time
+ * of the call.	 xQueueReceive() will return immediately if xTicksToWait
+ * is zero and the queue is empty.  The time is defined in tick periods so the
+ * constant portTICK_PERIOD_MS should be used to convert to real time if this is
+ * required.
+ *
+ * @return pdTRUE if an item was successfully received from the queue,
+ * otherwise pdFALSE.
+ *
+ * Example usage:
+   <pre>
+ struct AMessage
+ {
+	char ucMessageID;
+	char ucData[ 20 ];
+ } xMessage;
+
+ QueueHandle_t xQueue;
+
+ // Task to create a queue and post a value.
+ void vATask( void *pvParameters )
+ {
+ struct AMessage *pxMessage;
+
+	// Create a queue capable of containing 10 pointers to AMessage structures.
+	// These should be passed by pointer as they contain a lot of data.
+	xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );
+	if( xQueue == 0 )
+	{
+		// Failed to create the queue.
+	}
+
+	// ...
+
+	// Send a pointer to a struct AMessage object.  Don't block if the
+	// queue is already full.
+	pxMessage = & xMessage;
+	xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 );
+
+	// ... Rest of task code.
+ }
+
+ // Task to receive from the queue.
+ void vADifferentTask( void *pvParameters )
+ {
+ struct AMessage *pxRxedMessage;
+
+	if( xQueue != 0 )
+	{
+		// Receive a message on the created queue.  Block for 10 ticks if a
+		// message is not immediately available.
+		if( xQueueReceive( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) )
+		{
+			// pcRxedMessage now points to the struct AMessage variable posted
+			// by vATask.
+		}
+	}
+
+	// ... Rest of task code.
+ }
+ </pre>
+ * \defgroup xQueueReceive xQueueReceive
+ * \ingroup QueueManagement
+ */
+#define xQueueReceive( xQueue, pvBuffer, xTicksToWait ) xQueueGenericReceive( ( xQueue ), ( pvBuffer ), ( xTicksToWait ), pdFALSE )
+
+
+/**
+ * queue. h
+ * <pre>
+ BaseType_t xQueueGenericReceive(
+									   QueueHandle_t	xQueue,
+									   void	*pvBuffer,
+									   TickType_t	xTicksToWait
+									   BaseType_t	xJustPeek
+									);</pre>
+ *
+ * It is preferred that the macro xQueueReceive() be used rather than calling
+ * this function directly.
+ *
+ * Receive an item from a queue.  The item is received by copy so a buffer of
+ * adequate size must be provided.  The number of bytes copied into the buffer
+ * was defined when the queue was created.
+ *
+ * This function must not be used in an interrupt service routine.  See
+ * xQueueReceiveFromISR for an alternative that can.
+ *
+ * @param xQueue The handle to the queue from which the item is to be
+ * received.
+ *
+ * @param pvBuffer Pointer to the buffer into which the received item will
+ * be copied.
+ *
+ * @param xTicksToWait The maximum amount of time the task should block
+ * waiting for an item to receive should the queue be empty at the time
+ * of the call.	 The time is defined in tick periods so the constant
+ * portTICK_PERIOD_MS should be used to convert to real time if this is required.
+ * xQueueGenericReceive() will return immediately if the queue is empty and
+ * xTicksToWait is 0.
+ *
+ * @param xJustPeek When set to true, the item received from the queue is not
+ * actually removed from the queue - meaning a subsequent call to
+ * xQueueReceive() will return the same item.  When set to false, the item
+ * being received from the queue is also removed from the queue.
+ *
+ * @return pdTRUE if an item was successfully received from the queue,
+ * otherwise pdFALSE.
+ *
+ * Example usage:
+   <pre>
+ struct AMessage
+ {
+	char ucMessageID;
+	char ucData[ 20 ];
+ } xMessage;
+
+ QueueHandle_t xQueue;
+
+ // Task to create a queue and post a value.
+ void vATask( void *pvParameters )
+ {
+ struct AMessage *pxMessage;
+
+	// Create a queue capable of containing 10 pointers to AMessage structures.
+	// These should be passed by pointer as they contain a lot of data.
+	xQueue = xQueueCreate( 10, sizeof( struct AMessage * ) );
+	if( xQueue == 0 )
+	{
+		// Failed to create the queue.
+	}
+
+	// ...
+
+	// Send a pointer to a struct AMessage object.  Don't block if the
+	// queue is already full.
+	pxMessage = & xMessage;
+	xQueueSend( xQueue, ( void * ) &pxMessage, ( TickType_t ) 0 );
+
+	// ... Rest of task code.
+ }
+
+ // Task to receive from the queue.
+ void vADifferentTask( void *pvParameters )
+ {
+ struct AMessage *pxRxedMessage;
+
+	if( xQueue != 0 )
+	{
+		// Receive a message on the created queue.  Block for 10 ticks if a
+		// message is not immediately available.
+		if( xQueueGenericReceive( xQueue, &( pxRxedMessage ), ( TickType_t ) 10 ) )
+		{
+			// pcRxedMessage now points to the struct AMessage variable posted
+			// by vATask.
+		}
+	}
+
+	// ... Rest of task code.
+ }
+ </pre>
+ * \defgroup xQueueReceive xQueueReceive
+ * \ingroup QueueManagement
+ */
+BaseType_t xQueueGenericReceive( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait, const BaseType_t xJustPeek ) PRIVILEGED_FUNCTION;
+
+/**
+ * queue. h
+ * <pre>UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue );</pre>
+ *
+ * Return the number of messages stored in a queue.
+ *
+ * @param xQueue A handle to the queue being queried.
+ *
+ * @return The number of messages available in the queue.
+ *
+ * \defgroup uxQueueMessagesWaiting uxQueueMessagesWaiting
+ * \ingroup QueueManagement
+ */
+UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
+
+/**
+ * queue. h
+ * <pre>UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue );</pre>
+ *
+ * Return the number of free spaces available in a queue.  This is equal to the
+ * number of items that can be sent to the queue before the queue becomes full
+ * if no items are removed.
+ *
+ * @param xQueue A handle to the queue being queried.
+ *
+ * @return The number of spaces available in the queue.
+ *
+ * \defgroup uxQueueMessagesWaiting uxQueueMessagesWaiting
+ * \ingroup QueueManagement
+ */
+UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
+
+/**
+ * queue. h
+ * <pre>void vQueueDelete( QueueHandle_t xQueue );</pre>
+ *
+ * Delete a queue - freeing all the memory allocated for storing of items
+ * placed on the queue.
+ *
+ * @param xQueue A handle to the queue to be deleted.
+ *
+ * \defgroup vQueueDelete vQueueDelete
+ * \ingroup QueueManagement
+ */
+void vQueueDelete( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
+
+/**
+ * queue. h
+ * <pre>
+ BaseType_t xQueueSendToFrontFromISR(
+										 QueueHandle_t xQueue,
+										 const void *pvItemToQueue,
+										 BaseType_t *pxHigherPriorityTaskWoken
+									  );
+ </pre>
+ *
+ * This is a macro that calls xQueueGenericSendFromISR().
+ *
+ * Post an item to the front of a queue.  It is safe to use this macro from
+ * within an interrupt service routine.
+ *
+ * Items are queued by copy not reference so it is preferable to only
+ * queue small items, especially when called from an ISR.  In most cases
+ * it would be preferable to store a pointer to the item being queued.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param pxHigherPriorityTaskWoken xQueueSendToFrontFromISR() will set
+ * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task
+ * to unblock, and the unblocked task has a priority higher than the currently
+ * running task.  If xQueueSendToFromFromISR() sets this value to pdTRUE then
+ * a context switch should be requested before the interrupt is exited.
+ *
+ * @return pdTRUE if the data was successfully sent to the queue, otherwise
+ * errQUEUE_FULL.
+ *
+ * Example usage for buffered IO (where the ISR can obtain more than one value
+ * per call):
+   <pre>
+ void vBufferISR( void )
+ {
+ char cIn;
+ BaseType_t xHigherPrioritTaskWoken;
+
+	// We have not woken a task at the start of the ISR.
+	xHigherPriorityTaskWoken = pdFALSE;
+
+	// Loop until the buffer is empty.
+	do
+	{
+		// Obtain a byte from the buffer.
+		cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );
+
+		// Post the byte.
+		xQueueSendToFrontFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken );
+
+	} while( portINPUT_BYTE( BUFFER_COUNT ) );
+
+	// Now the buffer is empty we can switch context if necessary.
+	if( xHigherPriorityTaskWoken )
+	{
+		taskYIELD ();
+	}
+ }
+ </pre>
+ *
+ * \defgroup xQueueSendFromISR xQueueSendFromISR
+ * \ingroup QueueManagement
+ */
+#define xQueueSendToFrontFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_FRONT )
+
+
+/**
+ * queue. h
+ * <pre>
+ BaseType_t xQueueSendToBackFromISR(
+										 QueueHandle_t xQueue,
+										 const void *pvItemToQueue,
+										 BaseType_t *pxHigherPriorityTaskWoken
+									  );
+ </pre>
+ *
+ * This is a macro that calls xQueueGenericSendFromISR().
+ *
+ * Post an item to the back of a queue.  It is safe to use this macro from
+ * within an interrupt service routine.
+ *
+ * Items are queued by copy not reference so it is preferable to only
+ * queue small items, especially when called from an ISR.  In most cases
+ * it would be preferable to store a pointer to the item being queued.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param pxHigherPriorityTaskWoken xQueueSendToBackFromISR() will set
+ * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task
+ * to unblock, and the unblocked task has a priority higher than the currently
+ * running task.  If xQueueSendToBackFromISR() sets this value to pdTRUE then
+ * a context switch should be requested before the interrupt is exited.
+ *
+ * @return pdTRUE if the data was successfully sent to the queue, otherwise
+ * errQUEUE_FULL.
+ *
+ * Example usage for buffered IO (where the ISR can obtain more than one value
+ * per call):
+   <pre>
+ void vBufferISR( void )
+ {
+ char cIn;
+ BaseType_t xHigherPriorityTaskWoken;
+
+	// We have not woken a task at the start of the ISR.
+	xHigherPriorityTaskWoken = pdFALSE;
+
+	// Loop until the buffer is empty.
+	do
+	{
+		// Obtain a byte from the buffer.
+		cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );
+
+		// Post the byte.
+		xQueueSendToBackFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken );
+
+	} while( portINPUT_BYTE( BUFFER_COUNT ) );
+
+	// Now the buffer is empty we can switch context if necessary.
+	if( xHigherPriorityTaskWoken )
+	{
+		taskYIELD ();
+	}
+ }
+ </pre>
+ *
+ * \defgroup xQueueSendFromISR xQueueSendFromISR
+ * \ingroup QueueManagement
+ */
+#define xQueueSendToBackFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK )
+
+/**
+ * queue. h
+ * <pre>
+ BaseType_t xQueueOverwriteFromISR(
+							  QueueHandle_t xQueue,
+							  const void * pvItemToQueue,
+							  BaseType_t *pxHigherPriorityTaskWoken
+						 );
+ * </pre>
+ *
+ * A version of xQueueOverwrite() that can be used in an interrupt service
+ * routine (ISR).
+ *
+ * Only for use with queues that can hold a single item - so the queue is either
+ * empty or full.
+ *
+ * Post an item on a queue.  If the queue is already full then overwrite the
+ * value held in the queue.  The item is queued by copy, not by reference.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param pxHigherPriorityTaskWoken xQueueOverwriteFromISR() will set
+ * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task
+ * to unblock, and the unblocked task has a priority higher than the currently
+ * running task.  If xQueueOverwriteFromISR() sets this value to pdTRUE then
+ * a context switch should be requested before the interrupt is exited.
+ *
+ * @return xQueueOverwriteFromISR() is a macro that calls
+ * xQueueGenericSendFromISR(), and therefore has the same return values as
+ * xQueueSendToFrontFromISR().  However, pdPASS is the only value that can be
+ * returned because xQueueOverwriteFromISR() will write to the queue even when
+ * the queue is already full.
+ *
+ * Example usage:
+   <pre>
+
+ QueueHandle_t xQueue;
+
+ void vFunction( void *pvParameters )
+ {
+ 	// Create a queue to hold one uint32_t value.  It is strongly
+	// recommended *not* to use xQueueOverwriteFromISR() on queues that can
+	// contain more than one value, and doing so will trigger an assertion
+	// if configASSERT() is defined.
+	xQueue = xQueueCreate( 1, sizeof( uint32_t ) );
+}
+
+void vAnInterruptHandler( void )
+{
+// xHigherPriorityTaskWoken must be set to pdFALSE before it is used.
+BaseType_t xHigherPriorityTaskWoken = pdFALSE;
+uint32_t ulVarToSend, ulValReceived;
+
+	// Write the value 10 to the queue using xQueueOverwriteFromISR().
+	ulVarToSend = 10;
+	xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken );
+
+	// The queue is full, but calling xQueueOverwriteFromISR() again will still
+	// pass because the value held in the queue will be overwritten with the
+	// new value.
+	ulVarToSend = 100;
+	xQueueOverwriteFromISR( xQueue, &ulVarToSend, &xHigherPriorityTaskWoken );
+
+	// Reading from the queue will now return 100.
+
+	// ...
+
+	if( xHigherPrioritytaskWoken == pdTRUE )
+	{
+		// Writing to the queue caused a task to unblock and the unblocked task
+		// has a priority higher than or equal to the priority of the currently
+		// executing task (the task this interrupt interrupted).  Perform a context
+		// switch so this interrupt returns directly to the unblocked task.
+		portYIELD_FROM_ISR(); // or portEND_SWITCHING_ISR() depending on the port.
+	}
+}
+ </pre>
+ * \defgroup xQueueOverwriteFromISR xQueueOverwriteFromISR
+ * \ingroup QueueManagement
+ */
+#define xQueueOverwriteFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueOVERWRITE )
+
+/**
+ * queue. h
+ * <pre>
+ BaseType_t xQueueSendFromISR(
+									 QueueHandle_t xQueue,
+									 const void *pvItemToQueue,
+									 BaseType_t *pxHigherPriorityTaskWoken
+								);
+ </pre>
+ *
+ * This is a macro that calls xQueueGenericSendFromISR().  It is included
+ * for backward compatibility with versions of FreeRTOS.org that did not
+ * include the xQueueSendToBackFromISR() and xQueueSendToFrontFromISR()
+ * macros.
+ *
+ * Post an item to the back of a queue.  It is safe to use this function from
+ * within an interrupt service routine.
+ *
+ * Items are queued by copy not reference so it is preferable to only
+ * queue small items, especially when called from an ISR.  In most cases
+ * it would be preferable to store a pointer to the item being queued.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param pxHigherPriorityTaskWoken xQueueSendFromISR() will set
+ * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task
+ * to unblock, and the unblocked task has a priority higher than the currently
+ * running task.  If xQueueSendFromISR() sets this value to pdTRUE then
+ * a context switch should be requested before the interrupt is exited.
+ *
+ * @return pdTRUE if the data was successfully sent to the queue, otherwise
+ * errQUEUE_FULL.
+ *
+ * Example usage for buffered IO (where the ISR can obtain more than one value
+ * per call):
+   <pre>
+ void vBufferISR( void )
+ {
+ char cIn;
+ BaseType_t xHigherPriorityTaskWoken;
+
+	// We have not woken a task at the start of the ISR.
+	xHigherPriorityTaskWoken = pdFALSE;
+
+	// Loop until the buffer is empty.
+	do
+	{
+		// Obtain a byte from the buffer.
+		cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );
+
+		// Post the byte.
+		xQueueSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWoken );
+
+	} while( portINPUT_BYTE( BUFFER_COUNT ) );
+
+	// Now the buffer is empty we can switch context if necessary.
+	if( xHigherPriorityTaskWoken )
+	{
+		// Actual macro used here is port specific.
+		portYIELD_FROM_ISR ();
+	}
+ }
+ </pre>
+ *
+ * \defgroup xQueueSendFromISR xQueueSendFromISR
+ * \ingroup QueueManagement
+ */
+#define xQueueSendFromISR( xQueue, pvItemToQueue, pxHigherPriorityTaskWoken ) xQueueGenericSendFromISR( ( xQueue ), ( pvItemToQueue ), ( pxHigherPriorityTaskWoken ), queueSEND_TO_BACK )
+
+/**
+ * queue. h
+ * <pre>
+ BaseType_t xQueueGenericSendFromISR(
+										   QueueHandle_t		xQueue,
+										   const	void	*pvItemToQueue,
+										   BaseType_t	*pxHigherPriorityTaskWoken,
+										   BaseType_t	xCopyPosition
+									   );
+ </pre>
+ *
+ * It is preferred that the macros xQueueSendFromISR(),
+ * xQueueSendToFrontFromISR() and xQueueSendToBackFromISR() be used in place
+ * of calling this function directly.  xQueueGiveFromISR() is an
+ * equivalent for use by semaphores that don't actually copy any data.
+ *
+ * Post an item on a queue.  It is safe to use this function from within an
+ * interrupt service routine.
+ *
+ * Items are queued by copy not reference so it is preferable to only
+ * queue small items, especially when called from an ISR.  In most cases
+ * it would be preferable to store a pointer to the item being queued.
+ *
+ * @param xQueue The handle to the queue on which the item is to be posted.
+ *
+ * @param pvItemToQueue A pointer to the item that is to be placed on the
+ * queue.  The size of the items the queue will hold was defined when the
+ * queue was created, so this many bytes will be copied from pvItemToQueue
+ * into the queue storage area.
+ *
+ * @param pxHigherPriorityTaskWoken xQueueGenericSendFromISR() will set
+ * *pxHigherPriorityTaskWoken to pdTRUE if sending to the queue caused a task
+ * to unblock, and the unblocked task has a priority higher than the currently
+ * running task.  If xQueueGenericSendFromISR() sets this value to pdTRUE then
+ * a context switch should be requested before the interrupt is exited.
+ *
+ * @param xCopyPosition Can take the value queueSEND_TO_BACK to place the
+ * item at the back of the queue, or queueSEND_TO_FRONT to place the item
+ * at the front of the queue (for high priority messages).
+ *
+ * @return pdTRUE if the data was successfully sent to the queue, otherwise
+ * errQUEUE_FULL.
+ *
+ * Example usage for buffered IO (where the ISR can obtain more than one value
+ * per call):
+   <pre>
+ void vBufferISR( void )
+ {
+ char cIn;
+ BaseType_t xHigherPriorityTaskWokenByPost;
+
+	// We have not woken a task at the start of the ISR.
+	xHigherPriorityTaskWokenByPost = pdFALSE;
+
+	// Loop until the buffer is empty.
+	do
+	{
+		// Obtain a byte from the buffer.
+		cIn = portINPUT_BYTE( RX_REGISTER_ADDRESS );
+
+		// Post each byte.
+		xQueueGenericSendFromISR( xRxQueue, &cIn, &xHigherPriorityTaskWokenByPost, queueSEND_TO_BACK );
+
+	} while( portINPUT_BYTE( BUFFER_COUNT ) );
+
+	// Now the buffer is empty we can switch context if necessary.  Note that the
+	// name of the yield function required is port specific.
+	if( xHigherPriorityTaskWokenByPost )
+	{
+		taskYIELD_YIELD_FROM_ISR();
+	}
+ }
+ </pre>
+ *
+ * \defgroup xQueueSendFromISR xQueueSendFromISR
+ * \ingroup QueueManagement
+ */
+BaseType_t xQueueGenericSendFromISR( QueueHandle_t xQueue, const void * const pvItemToQueue, BaseType_t * const pxHigherPriorityTaskWoken, const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION;
+BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
+
+/**
+ * queue. h
+ * <pre>
+ BaseType_t xQueueReceiveFromISR(
+									   QueueHandle_t	xQueue,
+									   void	*pvBuffer,
+									   BaseType_t *pxTaskWoken
+								   );
+ * </pre>
+ *
+ * Receive an item from a queue.  It is safe to use this function from within an
+ * interrupt service routine.
+ *
+ * @param xQueue The handle to the queue from which the item is to be
+ * received.
+ *
+ * @param pvBuffer Pointer to the buffer into which the received item will
+ * be copied.
+ *
+ * @param pxTaskWoken A task may be blocked waiting for space to become
+ * available on the queue.  If xQueueReceiveFromISR causes such a task to
+ * unblock *pxTaskWoken will get set to pdTRUE, otherwise *pxTaskWoken will
+ * remain unchanged.
+ *
+ * @return pdTRUE if an item was successfully received from the queue,
+ * otherwise pdFALSE.
+ *
+ * Example usage:
+   <pre>
+
+ QueueHandle_t xQueue;
+
+ // Function to create a queue and post some values.
+ void vAFunction( void *pvParameters )
+ {
+ char cValueToPost;
+ const TickType_t xTicksToWait = ( TickType_t )0xff;
+
+	// Create a queue capable of containing 10 characters.
+	xQueue = xQueueCreate( 10, sizeof( char ) );
+	if( xQueue == 0 )
+	{
+		// Failed to create the queue.
+	}
+
+	// ...
+
+	// Post some characters that will be used within an ISR.  If the queue
+	// is full then this task will block for xTicksToWait ticks.
+	cValueToPost = 'a';
+	xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait );
+	cValueToPost = 'b';
+	xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait );
+
+	// ... keep posting characters ... this task may block when the queue
+	// becomes full.
+
+	cValueToPost = 'c';
+	xQueueSend( xQueue, ( void * ) &cValueToPost, xTicksToWait );
+ }
+
+ // ISR that outputs all the characters received on the queue.
+ void vISR_Routine( void )
+ {
+ BaseType_t xTaskWokenByReceive = pdFALSE;
+ char cRxedChar;
+
+	while( xQueueReceiveFromISR( xQueue, ( void * ) &cRxedChar, &xTaskWokenByReceive) )
+	{
+		// A character was received.  Output the character now.
+		vOutputCharacter( cRxedChar );
+
+		// If removing the character from the queue woke the task that was
+		// posting onto the queue cTaskWokenByReceive will have been set to
+		// pdTRUE.  No matter how many times this loop iterates only one
+		// task will be woken.
+	}
+
+	if( cTaskWokenByPost != ( char ) pdFALSE;
+	{
+		taskYIELD ();
+	}
+ }
+ </pre>
+ * \defgroup xQueueReceiveFromISR xQueueReceiveFromISR
+ * \ingroup QueueManagement
+ */
+BaseType_t xQueueReceiveFromISR( QueueHandle_t xQueue, void * const pvBuffer, BaseType_t * const pxHigherPriorityTaskWoken ) PRIVILEGED_FUNCTION;
+
+/*
+ * Utilities to query queues that are safe to use from an ISR.  These utilities
+ * should be used only from witin an ISR, or within a critical section.
+ */
+BaseType_t xQueueIsQueueEmptyFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
+BaseType_t xQueueIsQueueFullFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
+UBaseType_t uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
+
+
+/*
+ * xQueueAltGenericSend() is an alternative version of xQueueGenericSend().
+ * Likewise xQueueAltGenericReceive() is an alternative version of
+ * xQueueGenericReceive().
+ *
+ * The source code that implements the alternative (Alt) API is much
+ * simpler	because it executes everything from within a critical section.
+ * This is	the approach taken by many other RTOSes, but FreeRTOS.org has the
+ * preferred fully featured API too.  The fully featured API has more
+ * complex	code that takes longer to execute, but makes much less use of
+ * critical sections.  Therefore the alternative API sacrifices interrupt
+ * responsiveness to gain execution speed, whereas the fully featured API
+ * sacrifices execution speed to ensure better interrupt responsiveness.
+ */
+BaseType_t xQueueAltGenericSend( QueueHandle_t xQueue, const void * const pvItemToQueue, TickType_t xTicksToWait, BaseType_t xCopyPosition );
+BaseType_t xQueueAltGenericReceive( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait, BaseType_t xJustPeeking );
+#define xQueueAltSendToFront( xQueue, pvItemToQueue, xTicksToWait ) xQueueAltGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_FRONT )
+#define xQueueAltSendToBack( xQueue, pvItemToQueue, xTicksToWait ) xQueueAltGenericSend( ( xQueue ), ( pvItemToQueue ), ( xTicksToWait ), queueSEND_TO_BACK )
+#define xQueueAltReceive( xQueue, pvBuffer, xTicksToWait ) xQueueAltGenericReceive( ( xQueue ), ( pvBuffer ), ( xTicksToWait ), pdFALSE )
+#define xQueueAltPeek( xQueue, pvBuffer, xTicksToWait ) xQueueAltGenericReceive( ( xQueue ), ( pvBuffer ), ( xTicksToWait ), pdTRUE )
+
+/*
+ * The functions defined above are for passing data to and from tasks.  The
+ * functions below are the equivalents for passing data to and from
+ * co-routines.
+ *
+ * These functions are called from the co-routine macro implementation and
+ * should not be called directly from application code.  Instead use the macro
+ * wrappers defined within croutine.h.
+ */
+BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, const void *pvItemToQueue, BaseType_t xCoRoutinePreviouslyWoken );
+BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, void *pvBuffer, BaseType_t *pxTaskWoken );
+BaseType_t xQueueCRSend( QueueHandle_t xQueue, const void *pvItemToQueue, TickType_t xTicksToWait );
+BaseType_t xQueueCRReceive( QueueHandle_t xQueue, void *pvBuffer, TickType_t xTicksToWait );
+
+/*
+ * For internal use only.  Use xSemaphoreCreateMutex(),
+ * xSemaphoreCreateCounting() or xSemaphoreGetMutexHolder() instead of calling
+ * these functions directly.
+ */
+QueueHandle_t xQueueCreateMutex( const uint8_t ucQueueType ) PRIVILEGED_FUNCTION;
+QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount ) PRIVILEGED_FUNCTION;
+void* xQueueGetMutexHolder( QueueHandle_t xSemaphore ) PRIVILEGED_FUNCTION;
+
+/*
+ * For internal use only.  Use xSemaphoreTakeMutexRecursive() or
+ * xSemaphoreGiveMutexRecursive() instead of calling these functions directly.
+ */
+BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+BaseType_t xQueueGiveMutexRecursive( QueueHandle_t pxMutex ) PRIVILEGED_FUNCTION;
+
+/*
+ * Reset a queue back to its original empty state.  The return value is now
+ * obsolete and is always set to pdPASS.
+ */
+#define xQueueReset( xQueue ) xQueueGenericReset( xQueue, pdFALSE )
+
+/*
+ * The registry is provided as a means for kernel aware debuggers to
+ * locate queues, semaphores and mutexes.  Call vQueueAddToRegistry() add
+ * a queue, semaphore or mutex handle to the registry if you want the handle
+ * to be available to a kernel aware debugger.  If you are not using a kernel
+ * aware debugger then this function can be ignored.
+ *
+ * configQUEUE_REGISTRY_SIZE defines the maximum number of handles the
+ * registry can hold.  configQUEUE_REGISTRY_SIZE must be greater than 0
+ * within FreeRTOSConfig.h for the registry to be available.  Its value
+ * does not effect the number of queues, semaphores and mutexes that can be
+ * created - just the number that the registry can hold.
+ *
+ * @param xQueue The handle of the queue being added to the registry.  This
+ * is the handle returned by a call to xQueueCreate().  Semaphore and mutex
+ * handles can also be passed in here.
+ *
+ * @param pcName The name to be associated with the handle.  This is the
+ * name that the kernel aware debugger will display.  The queue registry only
+ * stores a pointer to the string - so the string must be persistent (global or
+ * preferably in ROM/Flash), not on the stack.
+ */
+#if configQUEUE_REGISTRY_SIZE > 0
+	void vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcName ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+#endif
+
+/*
+ * The registry is provided as a means for kernel aware debuggers to
+ * locate queues, semaphores and mutexes.  Call vQueueAddToRegistry() add
+ * a queue, semaphore or mutex handle to the registry if you want the handle
+ * to be available to a kernel aware debugger, and vQueueUnregisterQueue() to
+ * remove the queue, semaphore or mutex from the register.  If you are not using
+ * a kernel aware debugger then this function can be ignored.
+ *
+ * @param xQueue The handle of the queue being removed from the registry.
+ */
+#if configQUEUE_REGISTRY_SIZE > 0
+	void vQueueUnregisterQueue( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
+#endif
+
+/*
+ * Generic version of the queue creation function, which is in turn called by
+ * any queue, semaphore or mutex creation function or macro.
+ */
+QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType ) PRIVILEGED_FUNCTION;
+
+/*
+ * Queue sets provide a mechanism to allow a task to block (pend) on a read
+ * operation from multiple queues or semaphores simultaneously.
+ *
+ * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this
+ * function.
+ *
+ * A queue set must be explicitly created using a call to xQueueCreateSet()
+ * before it can be used.  Once created, standard FreeRTOS queues and semaphores
+ * can be added to the set using calls to xQueueAddToSet().
+ * xQueueSelectFromSet() is then used to determine which, if any, of the queues
+ * or semaphores contained in the set is in a state where a queue read or
+ * semaphore take operation would be successful.
+ *
+ * Note 1:  See the documentation on http://wwwFreeRTOS.org/RTOS-queue-sets.html
+ * for reasons why queue sets are very rarely needed in practice as there are
+ * simpler methods of blocking on multiple objects.
+ *
+ * Note 2:  Blocking on a queue set that contains a mutex will not cause the
+ * mutex holder to inherit the priority of the blocked task.
+ *
+ * Note 3:  An additional 4 bytes of RAM is required for each space in a every
+ * queue added to a queue set.  Therefore counting semaphores that have a high
+ * maximum count value should not be added to a queue set.
+ *
+ * Note 4:  A receive (in the case of a queue) or take (in the case of a
+ * semaphore) operation must not be performed on a member of a queue set unless
+ * a call to xQueueSelectFromSet() has first returned a handle to that set member.
+ *
+ * @param uxEventQueueLength Queue sets store events that occur on
+ * the queues and semaphores contained in the set.  uxEventQueueLength specifies
+ * the maximum number of events that can be queued at once.  To be absolutely
+ * certain that events are not lost uxEventQueueLength should be set to the
+ * total sum of the length of the queues added to the set, where binary
+ * semaphores and mutexes have a length of 1, and counting semaphores have a
+ * length set by their maximum count value.  Examples:
+ *  + If a queue set is to hold a queue of length 5, another queue of length 12,
+ *    and a binary semaphore, then uxEventQueueLength should be set to
+ *    (5 + 12 + 1), or 18.
+ *  + If a queue set is to hold three binary semaphores then uxEventQueueLength
+ *    should be set to (1 + 1 + 1 ), or 3.
+ *  + If a queue set is to hold a counting semaphore that has a maximum count of
+ *    5, and a counting semaphore that has a maximum count of 3, then
+ *    uxEventQueueLength should be set to (5 + 3), or 8.
+ *
+ * @return If the queue set is created successfully then a handle to the created
+ * queue set is returned.  Otherwise NULL is returned.
+ */
+QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength ) PRIVILEGED_FUNCTION;
+
+/*
+ * Adds a queue or semaphore to a queue set that was previously created by a
+ * call to xQueueCreateSet().
+ *
+ * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this
+ * function.
+ *
+ * Note 1:  A receive (in the case of a queue) or take (in the case of a
+ * semaphore) operation must not be performed on a member of a queue set unless
+ * a call to xQueueSelectFromSet() has first returned a handle to that set member.
+ *
+ * @param xQueueOrSemaphore The handle of the queue or semaphore being added to
+ * the queue set (cast to an QueueSetMemberHandle_t type).
+ *
+ * @param xQueueSet The handle of the queue set to which the queue or semaphore
+ * is being added.
+ *
+ * @return If the queue or semaphore was successfully added to the queue set
+ * then pdPASS is returned.  If the queue could not be successfully added to the
+ * queue set because it is already a member of a different queue set then pdFAIL
+ * is returned.
+ */
+BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION;
+
+/*
+ * Removes a queue or semaphore from a queue set.  A queue or semaphore can only
+ * be removed from a set if the queue or semaphore is empty.
+ *
+ * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this
+ * function.
+ *
+ * @param xQueueOrSemaphore The handle of the queue or semaphore being removed
+ * from the queue set (cast to an QueueSetMemberHandle_t type).
+ *
+ * @param xQueueSet The handle of the queue set in which the queue or semaphore
+ * is included.
+ *
+ * @return If the queue or semaphore was successfully removed from the queue set
+ * then pdPASS is returned.  If the queue was not in the queue set, or the
+ * queue (or semaphore) was not empty, then pdFAIL is returned.
+ */
+BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION;
+
+/*
+ * xQueueSelectFromSet() selects from the members of a queue set a queue or
+ * semaphore that either contains data (in the case of a queue) or is available
+ * to take (in the case of a semaphore).  xQueueSelectFromSet() effectively
+ * allows a task to block (pend) on a read operation on all the queues and
+ * semaphores in a queue set simultaneously.
+ *
+ * See FreeRTOS/Source/Demo/Common/Minimal/QueueSet.c for an example using this
+ * function.
+ *
+ * Note 1:  See the documentation on http://wwwFreeRTOS.org/RTOS-queue-sets.html
+ * for reasons why queue sets are very rarely needed in practice as there are
+ * simpler methods of blocking on multiple objects.
+ *
+ * Note 2:  Blocking on a queue set that contains a mutex will not cause the
+ * mutex holder to inherit the priority of the blocked task.
+ *
+ * Note 3:  A receive (in the case of a queue) or take (in the case of a
+ * semaphore) operation must not be performed on a member of a queue set unless
+ * a call to xQueueSelectFromSet() has first returned a handle to that set member.
+ *
+ * @param xQueueSet The queue set on which the task will (potentially) block.
+ *
+ * @param xTicksToWait The maximum time, in ticks, that the calling task will
+ * remain in the Blocked state (with other tasks executing) to wait for a member
+ * of the queue set to be ready for a successful queue read or semaphore take
+ * operation.
+ *
+ * @return xQueueSelectFromSet() will return the handle of a queue (cast to
+ * a QueueSetMemberHandle_t type) contained in the queue set that contains data,
+ * or the handle of a semaphore (cast to a QueueSetMemberHandle_t type) contained
+ * in the queue set that is available, or NULL if no such queue or semaphore
+ * exists before before the specified block time expires.
+ */
+QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+
+/*
+ * A version of xQueueSelectFromSet() that can be used from an ISR.
+ */
+QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet ) PRIVILEGED_FUNCTION;
+
+/* Not public API functions. */
+void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+BaseType_t xQueueGenericReset( QueueHandle_t xQueue, BaseType_t xNewQueue ) PRIVILEGED_FUNCTION;
+void vQueueSetQueueNumber( QueueHandle_t xQueue, UBaseType_t uxQueueNumber ) PRIVILEGED_FUNCTION;
+UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
+uint8_t ucQueueGetQueueType( QueueHandle_t xQueue ) PRIVILEGED_FUNCTION;
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* QUEUE_H */
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/include/semphr.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/include/semphr.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,845 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+#ifndef SEMAPHORE_H
+#define SEMAPHORE_H
+
+#ifndef INC_FREERTOS_H
+	#error "include FreeRTOS.h" must appear in source files before "include semphr.h"
+#endif
+
+#include "queue.h"
+
+typedef QueueHandle_t SemaphoreHandle_t;
+
+#define semBINARY_SEMAPHORE_QUEUE_LENGTH	( ( uint8_t ) 1U )
+#define semSEMAPHORE_QUEUE_ITEM_LENGTH		( ( uint8_t ) 0U )
+#define semGIVE_BLOCK_TIME					( ( TickType_t ) 0U )
+
+
+/**
+ * semphr. h
+ * <pre>vSemaphoreCreateBinary( SemaphoreHandle_t xSemaphore )</pre>
+ *
+ * This old vSemaphoreCreateBinary() macro is now deprecated in favour of the
+ * xSemaphoreCreateBinary() function.  Note that binary semaphores created using
+ * the vSemaphoreCreateBinary() macro are created in a state such that the
+ * first call to 'take' the semaphore would pass, whereas binary semaphores
+ * created using xSemaphoreCreateBinary() are created in a state such that the
+ * the semaphore must first be 'given' before it can be 'taken'.
+ *
+ * <i>Macro</i> that implements a semaphore by using the existing queue mechanism.
+ * The queue length is 1 as this is a binary semaphore.  The data size is 0
+ * as we don't want to actually store any data - we just want to know if the
+ * queue is empty or full.
+ *
+ * This type of semaphore can be used for pure synchronisation between tasks or
+ * between an interrupt and a task.  The semaphore need not be given back once
+ * obtained, so one task/interrupt can continuously 'give' the semaphore while
+ * another continuously 'takes' the semaphore.  For this reason this type of
+ * semaphore does not use a priority inheritance mechanism.  For an alternative
+ * that does use priority inheritance see xSemaphoreCreateMutex().
+ *
+ * @param xSemaphore Handle to the created semaphore.  Should be of type SemaphoreHandle_t.
+ *
+ * Example usage:
+ <pre>
+ SemaphoreHandle_t xSemaphore = NULL;
+
+ void vATask( void * pvParameters )
+ {
+    // Semaphore cannot be used before a call to vSemaphoreCreateBinary ().
+    // This is a macro so pass the variable in directly.
+    vSemaphoreCreateBinary( xSemaphore );
+
+    if( xSemaphore != NULL )
+    {
+        // The semaphore was created successfully.
+        // The semaphore can now be used.
+    }
+ }
+ </pre>
+ * \defgroup vSemaphoreCreateBinary vSemaphoreCreateBinary
+ * \ingroup Semaphores
+ */
+#define vSemaphoreCreateBinary( xSemaphore )																							\
+	{																																	\
+		( xSemaphore ) = xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE );	\
+		if( ( xSemaphore ) != NULL )																									\
+		{																																\
+			( void ) xSemaphoreGive( ( xSemaphore ) );																					\
+		}																																\
+	}
+
+/**
+ * semphr. h
+ * <pre>SemaphoreHandle_t xSemaphoreCreateBinary( void )</pre>
+ *
+ * The old vSemaphoreCreateBinary() macro is now deprecated in favour of this
+ * xSemaphoreCreateBinary() function.  Note that binary semaphores created using
+ * the vSemaphoreCreateBinary() macro are created in a state such that the
+ * first call to 'take' the semaphore would pass, whereas binary semaphores
+ * created using xSemaphoreCreateBinary() are created in a state such that the
+ * the semaphore must first be 'given' before it can be 'taken'.
+ *
+ * Function that creates a semaphore by using the existing queue mechanism.
+ * The queue length is 1 as this is a binary semaphore.  The data size is 0
+ * as nothing is actually stored - all that is important is whether the queue is
+ * empty or full (the binary semaphore is available or not).
+ *
+ * This type of semaphore can be used for pure synchronisation between tasks or
+ * between an interrupt and a task.  The semaphore need not be given back once
+ * obtained, so one task/interrupt can continuously 'give' the semaphore while
+ * another continuously 'takes' the semaphore.  For this reason this type of
+ * semaphore does not use a priority inheritance mechanism.  For an alternative
+ * that does use priority inheritance see xSemaphoreCreateMutex().
+ *
+ * @return Handle to the created semaphore.
+ *
+ * Example usage:
+ <pre>
+ SemaphoreHandle_t xSemaphore = NULL;
+
+ void vATask( void * pvParameters )
+ {
+    // Semaphore cannot be used before a call to vSemaphoreCreateBinary ().
+    // This is a macro so pass the variable in directly.
+    xSemaphore = xSemaphoreCreateBinary();
+
+    if( xSemaphore != NULL )
+    {
+        // The semaphore was created successfully.
+        // The semaphore can now be used.
+    }
+ }
+ </pre>
+ * \defgroup vSemaphoreCreateBinary vSemaphoreCreateBinary
+ * \ingroup Semaphores
+ */
+#define xSemaphoreCreateBinary() xQueueGenericCreate( ( UBaseType_t ) 1, semSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_BINARY_SEMAPHORE )
+
+/**
+ * semphr. h
+ * <pre>xSemaphoreTake(
+ *                   SemaphoreHandle_t xSemaphore,
+ *                   TickType_t xBlockTime
+ *               )</pre>
+ *
+ * <i>Macro</i> to obtain a semaphore.  The semaphore must have previously been
+ * created with a call to vSemaphoreCreateBinary(), xSemaphoreCreateMutex() or
+ * xSemaphoreCreateCounting().
+ *
+ * @param xSemaphore A handle to the semaphore being taken - obtained when
+ * the semaphore was created.
+ *
+ * @param xBlockTime The time in ticks to wait for the semaphore to become
+ * available.  The macro portTICK_PERIOD_MS can be used to convert this to a
+ * real time.  A block time of zero can be used to poll the semaphore.  A block
+ * time of portMAX_DELAY can be used to block indefinitely (provided
+ * INCLUDE_vTaskSuspend is set to 1 in FreeRTOSConfig.h).
+ *
+ * @return pdTRUE if the semaphore was obtained.  pdFALSE
+ * if xBlockTime expired without the semaphore becoming available.
+ *
+ * Example usage:
+ <pre>
+ SemaphoreHandle_t xSemaphore = NULL;
+
+ // A task that creates a semaphore.
+ void vATask( void * pvParameters )
+ {
+    // Create the semaphore to guard a shared resource.
+    vSemaphoreCreateBinary( xSemaphore );
+ }
+
+ // A task that uses the semaphore.
+ void vAnotherTask( void * pvParameters )
+ {
+    // ... Do other things.
+
+    if( xSemaphore != NULL )
+    {
+        // See if we can obtain the semaphore.  If the semaphore is not available
+        // wait 10 ticks to see if it becomes free.
+        if( xSemaphoreTake( xSemaphore, ( TickType_t ) 10 ) == pdTRUE )
+        {
+            // We were able to obtain the semaphore and can now access the
+            // shared resource.
+
+            // ...
+
+            // We have finished accessing the shared resource.  Release the
+            // semaphore.
+            xSemaphoreGive( xSemaphore );
+        }
+        else
+        {
+            // We could not obtain the semaphore and can therefore not access
+            // the shared resource safely.
+        }
+    }
+ }
+ </pre>
+ * \defgroup xSemaphoreTake xSemaphoreTake
+ * \ingroup Semaphores
+ */
+#define xSemaphoreTake( xSemaphore, xBlockTime )		xQueueGenericReceive( ( QueueHandle_t ) ( xSemaphore ), NULL, ( xBlockTime ), pdFALSE )
+
+/**
+ * semphr. h
+ * xSemaphoreTakeRecursive(
+ *                          SemaphoreHandle_t xMutex,
+ *                          TickType_t xBlockTime
+ *                        )
+ *
+ * <i>Macro</i> to recursively obtain, or 'take', a mutex type semaphore.
+ * The mutex must have previously been created using a call to
+ * xSemaphoreCreateRecursiveMutex();
+ *
+ * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this
+ * macro to be available.
+ *
+ * This macro must not be used on mutexes created using xSemaphoreCreateMutex().
+ *
+ * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex
+ * doesn't become available again until the owner has called
+ * xSemaphoreGiveRecursive() for each successful 'take' request.  For example,
+ * if a task successfully 'takes' the same mutex 5 times then the mutex will
+ * not be available to any other task until it has also  'given' the mutex back
+ * exactly five times.
+ *
+ * @param xMutex A handle to the mutex being obtained.  This is the
+ * handle returned by xSemaphoreCreateRecursiveMutex();
+ *
+ * @param xBlockTime The time in ticks to wait for the semaphore to become
+ * available.  The macro portTICK_PERIOD_MS can be used to convert this to a
+ * real time.  A block time of zero can be used to poll the semaphore.  If
+ * the task already owns the semaphore then xSemaphoreTakeRecursive() will
+ * return immediately no matter what the value of xBlockTime.
+ *
+ * @return pdTRUE if the semaphore was obtained.  pdFALSE if xBlockTime
+ * expired without the semaphore becoming available.
+ *
+ * Example usage:
+ <pre>
+ SemaphoreHandle_t xMutex = NULL;
+
+ // A task that creates a mutex.
+ void vATask( void * pvParameters )
+ {
+    // Create the mutex to guard a shared resource.
+    xMutex = xSemaphoreCreateRecursiveMutex();
+ }
+
+ // A task that uses the mutex.
+ void vAnotherTask( void * pvParameters )
+ {
+    // ... Do other things.
+
+    if( xMutex != NULL )
+    {
+        // See if we can obtain the mutex.  If the mutex is not available
+        // wait 10 ticks to see if it becomes free.
+        if( xSemaphoreTakeRecursive( xSemaphore, ( TickType_t ) 10 ) == pdTRUE )
+        {
+            // We were able to obtain the mutex and can now access the
+            // shared resource.
+
+            // ...
+            // For some reason due to the nature of the code further calls to
+			// xSemaphoreTakeRecursive() are made on the same mutex.  In real
+			// code these would not be just sequential calls as this would make
+			// no sense.  Instead the calls are likely to be buried inside
+			// a more complex call structure.
+            xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
+            xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
+
+            // The mutex has now been 'taken' three times, so will not be
+			// available to another task until it has also been given back
+			// three times.  Again it is unlikely that real code would have
+			// these calls sequentially, but instead buried in a more complex
+			// call structure.  This is just for illustrative purposes.
+            xSemaphoreGiveRecursive( xMutex );
+			xSemaphoreGiveRecursive( xMutex );
+			xSemaphoreGiveRecursive( xMutex );
+
+			// Now the mutex can be taken by other tasks.
+        }
+        else
+        {
+            // We could not obtain the mutex and can therefore not access
+            // the shared resource safely.
+        }
+    }
+ }
+ </pre>
+ * \defgroup xSemaphoreTakeRecursive xSemaphoreTakeRecursive
+ * \ingroup Semaphores
+ */
+#define xSemaphoreTakeRecursive( xMutex, xBlockTime )	xQueueTakeMutexRecursive( ( xMutex ), ( xBlockTime ) )
+
+
+/*
+ * xSemaphoreAltTake() is an alternative version of xSemaphoreTake().
+ *
+ * The source code that implements the alternative (Alt) API is much
+ * simpler	because it executes everything from within a critical section.
+ * This is	the approach taken by many other RTOSes, but FreeRTOS.org has the
+ * preferred fully featured API too.  The fully featured API has more
+ * complex	code that takes longer to execute, but makes much less use of
+ * critical sections.  Therefore the alternative API sacrifices interrupt
+ * responsiveness to gain execution speed, whereas the fully featured API
+ * sacrifices execution speed to ensure better interrupt responsiveness.
+ */
+#define xSemaphoreAltTake( xSemaphore, xBlockTime )		xQueueAltGenericReceive( ( QueueHandle_t ) ( xSemaphore ), NULL, ( xBlockTime ), pdFALSE )
+
+/**
+ * semphr. h
+ * <pre>xSemaphoreGive( SemaphoreHandle_t xSemaphore )</pre>
+ *
+ * <i>Macro</i> to release a semaphore.  The semaphore must have previously been
+ * created with a call to vSemaphoreCreateBinary(), xSemaphoreCreateMutex() or
+ * xSemaphoreCreateCounting(). and obtained using sSemaphoreTake().
+ *
+ * This macro must not be used from an ISR.  See xSemaphoreGiveFromISR () for
+ * an alternative which can be used from an ISR.
+ *
+ * This macro must also not be used on semaphores created using
+ * xSemaphoreCreateRecursiveMutex().
+ *
+ * @param xSemaphore A handle to the semaphore being released.  This is the
+ * handle returned when the semaphore was created.
+ *
+ * @return pdTRUE if the semaphore was released.  pdFALSE if an error occurred.
+ * Semaphores are implemented using queues.  An error can occur if there is
+ * no space on the queue to post a message - indicating that the
+ * semaphore was not first obtained correctly.
+ *
+ * Example usage:
+ <pre>
+ SemaphoreHandle_t xSemaphore = NULL;
+
+ void vATask( void * pvParameters )
+ {
+    // Create the semaphore to guard a shared resource.
+    vSemaphoreCreateBinary( xSemaphore );
+
+    if( xSemaphore != NULL )
+    {
+        if( xSemaphoreGive( xSemaphore ) != pdTRUE )
+        {
+            // We would expect this call to fail because we cannot give
+            // a semaphore without first "taking" it!
+        }
+
+        // Obtain the semaphore - don't block if the semaphore is not
+        // immediately available.
+        if( xSemaphoreTake( xSemaphore, ( TickType_t ) 0 ) )
+        {
+            // We now have the semaphore and can access the shared resource.
+
+            // ...
+
+            // We have finished accessing the shared resource so can free the
+            // semaphore.
+            if( xSemaphoreGive( xSemaphore ) != pdTRUE )
+            {
+                // We would not expect this call to fail because we must have
+                // obtained the semaphore to get here.
+            }
+        }
+    }
+ }
+ </pre>
+ * \defgroup xSemaphoreGive xSemaphoreGive
+ * \ingroup Semaphores
+ */
+#define xSemaphoreGive( xSemaphore )		xQueueGenericSend( ( QueueHandle_t ) ( xSemaphore ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK )
+
+/**
+ * semphr. h
+ * <pre>xSemaphoreGiveRecursive( SemaphoreHandle_t xMutex )</pre>
+ *
+ * <i>Macro</i> to recursively release, or 'give', a mutex type semaphore.
+ * The mutex must have previously been created using a call to
+ * xSemaphoreCreateRecursiveMutex();
+ *
+ * configUSE_RECURSIVE_MUTEXES must be set to 1 in FreeRTOSConfig.h for this
+ * macro to be available.
+ *
+ * This macro must not be used on mutexes created using xSemaphoreCreateMutex().
+ *
+ * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex
+ * doesn't become available again until the owner has called
+ * xSemaphoreGiveRecursive() for each successful 'take' request.  For example,
+ * if a task successfully 'takes' the same mutex 5 times then the mutex will
+ * not be available to any other task until it has also  'given' the mutex back
+ * exactly five times.
+ *
+ * @param xMutex A handle to the mutex being released, or 'given'.  This is the
+ * handle returned by xSemaphoreCreateMutex();
+ *
+ * @return pdTRUE if the semaphore was given.
+ *
+ * Example usage:
+ <pre>
+ SemaphoreHandle_t xMutex = NULL;
+
+ // A task that creates a mutex.
+ void vATask( void * pvParameters )
+ {
+    // Create the mutex to guard a shared resource.
+    xMutex = xSemaphoreCreateRecursiveMutex();
+ }
+
+ // A task that uses the mutex.
+ void vAnotherTask( void * pvParameters )
+ {
+    // ... Do other things.
+
+    if( xMutex != NULL )
+    {
+        // See if we can obtain the mutex.  If the mutex is not available
+        // wait 10 ticks to see if it becomes free.
+        if( xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 ) == pdTRUE )
+        {
+            // We were able to obtain the mutex and can now access the
+            // shared resource.
+
+            // ...
+            // For some reason due to the nature of the code further calls to
+			// xSemaphoreTakeRecursive() are made on the same mutex.  In real
+			// code these would not be just sequential calls as this would make
+			// no sense.  Instead the calls are likely to be buried inside
+			// a more complex call structure.
+            xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
+            xSemaphoreTakeRecursive( xMutex, ( TickType_t ) 10 );
+
+            // The mutex has now been 'taken' three times, so will not be
+			// available to another task until it has also been given back
+			// three times.  Again it is unlikely that real code would have
+			// these calls sequentially, it would be more likely that the calls
+			// to xSemaphoreGiveRecursive() would be called as a call stack
+			// unwound.  This is just for demonstrative purposes.
+            xSemaphoreGiveRecursive( xMutex );
+			xSemaphoreGiveRecursive( xMutex );
+			xSemaphoreGiveRecursive( xMutex );
+
+			// Now the mutex can be taken by other tasks.
+        }
+        else
+        {
+            // We could not obtain the mutex and can therefore not access
+            // the shared resource safely.
+        }
+    }
+ }
+ </pre>
+ * \defgroup xSemaphoreGiveRecursive xSemaphoreGiveRecursive
+ * \ingroup Semaphores
+ */
+#define xSemaphoreGiveRecursive( xMutex )	xQueueGiveMutexRecursive( ( xMutex ) )
+
+/*
+ * xSemaphoreAltGive() is an alternative version of xSemaphoreGive().
+ *
+ * The source code that implements the alternative (Alt) API is much
+ * simpler	because it executes everything from within a critical section.
+ * This is	the approach taken by many other RTOSes, but FreeRTOS.org has the
+ * preferred fully featured API too.  The fully featured API has more
+ * complex	code that takes longer to execute, but makes much less use of
+ * critical sections.  Therefore the alternative API sacrifices interrupt
+ * responsiveness to gain execution speed, whereas the fully featured API
+ * sacrifices execution speed to ensure better interrupt responsiveness.
+ */
+#define xSemaphoreAltGive( xSemaphore )		xQueueAltGenericSend( ( QueueHandle_t ) ( xSemaphore ), NULL, semGIVE_BLOCK_TIME, queueSEND_TO_BACK )
+
+/**
+ * semphr. h
+ * <pre>
+ xSemaphoreGiveFromISR(
+                          SemaphoreHandle_t xSemaphore,
+                          BaseType_t *pxHigherPriorityTaskWoken
+                      )</pre>
+ *
+ * <i>Macro</i> to  release a semaphore.  The semaphore must have previously been
+ * created with a call to vSemaphoreCreateBinary() or xSemaphoreCreateCounting().
+ *
+ * Mutex type semaphores (those created using a call to xSemaphoreCreateMutex())
+ * must not be used with this macro.
+ *
+ * This macro can be used from an ISR.
+ *
+ * @param xSemaphore A handle to the semaphore being released.  This is the
+ * handle returned when the semaphore was created.
+ *
+ * @param pxHigherPriorityTaskWoken xSemaphoreGiveFromISR() will set
+ * *pxHigherPriorityTaskWoken to pdTRUE if giving the semaphore caused a task
+ * to unblock, and the unblocked task has a priority higher than the currently
+ * running task.  If xSemaphoreGiveFromISR() sets this value to pdTRUE then
+ * a context switch should be requested before the interrupt is exited.
+ *
+ * @return pdTRUE if the semaphore was successfully given, otherwise errQUEUE_FULL.
+ *
+ * Example usage:
+ <pre>
+ \#define LONG_TIME 0xffff
+ \#define TICKS_TO_WAIT	10
+ SemaphoreHandle_t xSemaphore = NULL;
+
+ // Repetitive task.
+ void vATask( void * pvParameters )
+ {
+    for( ;; )
+    {
+        // We want this task to run every 10 ticks of a timer.  The semaphore
+        // was created before this task was started.
+
+        // Block waiting for the semaphore to become available.
+        if( xSemaphoreTake( xSemaphore, LONG_TIME ) == pdTRUE )
+        {
+            // It is time to execute.
+
+            // ...
+
+            // We have finished our task.  Return to the top of the loop where
+            // we will block on the semaphore until it is time to execute
+            // again.  Note when using the semaphore for synchronisation with an
+			// ISR in this manner there is no need to 'give' the semaphore back.
+        }
+    }
+ }
+
+ // Timer ISR
+ void vTimerISR( void * pvParameters )
+ {
+ static uint8_t ucLocalTickCount = 0;
+ static BaseType_t xHigherPriorityTaskWoken;
+
+    // A timer tick has occurred.
+
+    // ... Do other time functions.
+
+    // Is it time for vATask () to run?
+	xHigherPriorityTaskWoken = pdFALSE;
+    ucLocalTickCount++;
+    if( ucLocalTickCount >= TICKS_TO_WAIT )
+    {
+        // Unblock the task by releasing the semaphore.
+        xSemaphoreGiveFromISR( xSemaphore, &xHigherPriorityTaskWoken );
+
+        // Reset the count so we release the semaphore again in 10 ticks time.
+        ucLocalTickCount = 0;
+    }
+
+    if( xHigherPriorityTaskWoken != pdFALSE )
+    {
+        // We can force a context switch here.  Context switching from an
+        // ISR uses port specific syntax.  Check the demo task for your port
+        // to find the syntax required.
+    }
+ }
+ </pre>
+ * \defgroup xSemaphoreGiveFromISR xSemaphoreGiveFromISR
+ * \ingroup Semaphores
+ */
+#define xSemaphoreGiveFromISR( xSemaphore, pxHigherPriorityTaskWoken )	xQueueGiveFromISR( ( QueueHandle_t ) ( xSemaphore ), ( pxHigherPriorityTaskWoken ) )
+
+/**
+ * semphr. h
+ * <pre>
+ xSemaphoreTakeFromISR(
+                          SemaphoreHandle_t xSemaphore,
+                          BaseType_t *pxHigherPriorityTaskWoken
+                      )</pre>
+ *
+ * <i>Macro</i> to  take a semaphore from an ISR.  The semaphore must have
+ * previously been created with a call to vSemaphoreCreateBinary() or
+ * xSemaphoreCreateCounting().
+ *
+ * Mutex type semaphores (those created using a call to xSemaphoreCreateMutex())
+ * must not be used with this macro.
+ *
+ * This macro can be used from an ISR, however taking a semaphore from an ISR
+ * is not a common operation.  It is likely to only be useful when taking a
+ * counting semaphore when an interrupt is obtaining an object from a resource
+ * pool (when the semaphore count indicates the number of resources available).
+ *
+ * @param xSemaphore A handle to the semaphore being taken.  This is the
+ * handle returned when the semaphore was created.
+ *
+ * @param pxHigherPriorityTaskWoken xSemaphoreTakeFromISR() will set
+ * *pxHigherPriorityTaskWoken to pdTRUE if taking the semaphore caused a task
+ * to unblock, and the unblocked task has a priority higher than the currently
+ * running task.  If xSemaphoreTakeFromISR() sets this value to pdTRUE then
+ * a context switch should be requested before the interrupt is exited.
+ *
+ * @return pdTRUE if the semaphore was successfully taken, otherwise
+ * pdFALSE
+ */
+#define xSemaphoreTakeFromISR( xSemaphore, pxHigherPriorityTaskWoken )	xQueueReceiveFromISR( ( QueueHandle_t ) ( xSemaphore ), NULL, ( pxHigherPriorityTaskWoken ) )
+
+/**
+ * semphr. h
+ * <pre>SemaphoreHandle_t xSemaphoreCreateMutex( void )</pre>
+ *
+ * <i>Macro</i> that implements a mutex semaphore by using the existing queue
+ * mechanism.
+ *
+ * Mutexes created using this macro can be accessed using the xSemaphoreTake()
+ * and xSemaphoreGive() macros.  The xSemaphoreTakeRecursive() and
+ * xSemaphoreGiveRecursive() macros should not be used.
+ *
+ * This type of semaphore uses a priority inheritance mechanism so a task
+ * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the
+ * semaphore it is no longer required.
+ *
+ * Mutex type semaphores cannot be used from within interrupt service routines.
+ *
+ * See vSemaphoreCreateBinary() for an alternative implementation that can be
+ * used for pure synchronisation (where one task or interrupt always 'gives' the
+ * semaphore and another always 'takes' the semaphore) and from within interrupt
+ * service routines.
+ *
+ * @return xSemaphore Handle to the created mutex semaphore.  Should be of type
+ *		SemaphoreHandle_t.
+ *
+ * Example usage:
+ <pre>
+ SemaphoreHandle_t xSemaphore;
+
+ void vATask( void * pvParameters )
+ {
+    // Semaphore cannot be used before a call to xSemaphoreCreateMutex().
+    // This is a macro so pass the variable in directly.
+    xSemaphore = xSemaphoreCreateMutex();
+
+    if( xSemaphore != NULL )
+    {
+        // The semaphore was created successfully.
+        // The semaphore can now be used.
+    }
+ }
+ </pre>
+ * \defgroup vSemaphoreCreateMutex vSemaphoreCreateMutex
+ * \ingroup Semaphores
+ */
+#define xSemaphoreCreateMutex() xQueueCreateMutex( queueQUEUE_TYPE_MUTEX )
+
+
+/**
+ * semphr. h
+ * <pre>SemaphoreHandle_t xSemaphoreCreateRecursiveMutex( void )</pre>
+ *
+ * <i>Macro</i> that implements a recursive mutex by using the existing queue
+ * mechanism.
+ *
+ * Mutexes created using this macro can be accessed using the
+ * xSemaphoreTakeRecursive() and xSemaphoreGiveRecursive() macros.  The
+ * xSemaphoreTake() and xSemaphoreGive() macros should not be used.
+ *
+ * A mutex used recursively can be 'taken' repeatedly by the owner. The mutex
+ * doesn't become available again until the owner has called
+ * xSemaphoreGiveRecursive() for each successful 'take' request.  For example,
+ * if a task successfully 'takes' the same mutex 5 times then the mutex will
+ * not be available to any other task until it has also  'given' the mutex back
+ * exactly five times.
+ *
+ * This type of semaphore uses a priority inheritance mechanism so a task
+ * 'taking' a semaphore MUST ALWAYS 'give' the semaphore back once the
+ * semaphore it is no longer required.
+ *
+ * Mutex type semaphores cannot be used from within interrupt service routines.
+ *
+ * See vSemaphoreCreateBinary() for an alternative implementation that can be
+ * used for pure synchronisation (where one task or interrupt always 'gives' the
+ * semaphore and another always 'takes' the semaphore) and from within interrupt
+ * service routines.
+ *
+ * @return xSemaphore Handle to the created mutex semaphore.  Should be of type
+ *		SemaphoreHandle_t.
+ *
+ * Example usage:
+ <pre>
+ SemaphoreHandle_t xSemaphore;
+
+ void vATask( void * pvParameters )
+ {
+    // Semaphore cannot be used before a call to xSemaphoreCreateMutex().
+    // This is a macro so pass the variable in directly.
+    xSemaphore = xSemaphoreCreateRecursiveMutex();
+
+    if( xSemaphore != NULL )
+    {
+        // The semaphore was created successfully.
+        // The semaphore can now be used.
+    }
+ }
+ </pre>
+ * \defgroup vSemaphoreCreateMutex vSemaphoreCreateMutex
+ * \ingroup Semaphores
+ */
+#define xSemaphoreCreateRecursiveMutex() xQueueCreateMutex( queueQUEUE_TYPE_RECURSIVE_MUTEX )
+
+/**
+ * semphr. h
+ * <pre>SemaphoreHandle_t xSemaphoreCreateCounting( UBaseType_t uxMaxCount, UBaseType_t uxInitialCount )</pre>
+ *
+ * <i>Macro</i> that creates a counting semaphore by using the existing
+ * queue mechanism.
+ *
+ * Counting semaphores are typically used for two things:
+ *
+ * 1) Counting events.
+ *
+ *    In this usage scenario an event handler will 'give' a semaphore each time
+ *    an event occurs (incrementing the semaphore count value), and a handler
+ *    task will 'take' a semaphore each time it processes an event
+ *    (decrementing the semaphore count value).  The count value is therefore
+ *    the difference between the number of events that have occurred and the
+ *    number that have been processed.  In this case it is desirable for the
+ *    initial count value to be zero.
+ *
+ * 2) Resource management.
+ *
+ *    In this usage scenario the count value indicates the number of resources
+ *    available.  To obtain control of a resource a task must first obtain a
+ *    semaphore - decrementing the semaphore count value.  When the count value
+ *    reaches zero there are no free resources.  When a task finishes with the
+ *    resource it 'gives' the semaphore back - incrementing the semaphore count
+ *    value.  In this case it is desirable for the initial count value to be
+ *    equal to the maximum count value, indicating that all resources are free.
+ *
+ * @param uxMaxCount The maximum count value that can be reached.  When the
+ *        semaphore reaches this value it can no longer be 'given'.
+ *
+ * @param uxInitialCount The count value assigned to the semaphore when it is
+ *        created.
+ *
+ * @return Handle to the created semaphore.  Null if the semaphore could not be
+ *         created.
+ *
+ * Example usage:
+ <pre>
+ SemaphoreHandle_t xSemaphore;
+
+ void vATask( void * pvParameters )
+ {
+ SemaphoreHandle_t xSemaphore = NULL;
+
+    // Semaphore cannot be used before a call to xSemaphoreCreateCounting().
+    // The max value to which the semaphore can count should be 10, and the
+    // initial value assigned to the count should be 0.
+    xSemaphore = xSemaphoreCreateCounting( 10, 0 );
+
+    if( xSemaphore != NULL )
+    {
+        // The semaphore was created successfully.
+        // The semaphore can now be used.
+    }
+ }
+ </pre>
+ * \defgroup xSemaphoreCreateCounting xSemaphoreCreateCounting
+ * \ingroup Semaphores
+ */
+#define xSemaphoreCreateCounting( uxMaxCount, uxInitialCount ) xQueueCreateCountingSemaphore( ( uxMaxCount ), ( uxInitialCount ) )
+
+/**
+ * semphr. h
+ * <pre>void vSemaphoreDelete( SemaphoreHandle_t xSemaphore );</pre>
+ *
+ * Delete a semaphore.  This function must be used with care.  For example,
+ * do not delete a mutex type semaphore if the mutex is held by a task.
+ *
+ * @param xSemaphore A handle to the semaphore to be deleted.
+ *
+ * \defgroup vSemaphoreDelete vSemaphoreDelete
+ * \ingroup Semaphores
+ */
+#define vSemaphoreDelete( xSemaphore ) vQueueDelete( ( QueueHandle_t ) ( xSemaphore ) )
+
+/**
+ * semphr.h
+ * <pre>TaskHandle_t xSemaphoreGetMutexHolder( SemaphoreHandle_t xMutex );</pre>
+ *
+ * If xMutex is indeed a mutex type semaphore, return the current mutex holder.
+ * If xMutex is not a mutex type semaphore, or the mutex is available (not held
+ * by a task), return NULL.
+ *
+ * Note: This is a good way of determining if the calling task is the mutex
+ * holder, but not a good way of determining the identity of the mutex holder as
+ * the holder may change between the function exiting and the returned value
+ * being tested.
+ */
+#define xSemaphoreGetMutexHolder( xSemaphore ) xQueueGetMutexHolder( ( xSemaphore ) )
+
+#endif /* SEMAPHORE_H */
+
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/include/stdint.readme
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/include/stdint.readme	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,28 @@
+
+#ifndef FREERTOS_STDINT
+#define FREERTOS_STDINT
+
+/*******************************************************************************
+ * THIS IS NOT A FULL stdint.h IMPLEMENTATION - It only contains the definitions
+ * necessary to build the FreeRTOS code.  It is provided to allow FreeRTOS to be
+ * built using compilers that do not provide their own stdint.h definition.
+ *
+ * To use this file:
+ *
+ *    1) Copy this file into the directory that contains your FreeRTOSConfig.h
+ *       header file, as that directory will already be in the compilers include
+ *       path.
+ *
+ *    2) Rename the copied file stdint.h.
+ *
+ */
+
+typedef signed char int8_t;
+typedef unsigned char uint8_t;
+typedef short int16_t;
+typedef unsigned short uint16_t;
+typedef long int32_t;
+typedef unsigned long uint32_t;
+
+#endif /* FREERTOS_STDINT */
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/include/task.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/include/task.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,2022 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+
+#ifndef INC_TASK_H
+#define INC_TASK_H
+
+#ifndef INC_FREERTOS_H
+	#error "include FreeRTOS.h must appear in source files before include task.h"
+#endif
+
+#include "list.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*-----------------------------------------------------------
+ * MACROS AND DEFINITIONS
+ *----------------------------------------------------------*/
+
+#define tskKERNEL_VERSION_NUMBER "V8.2.1"
+#define tskKERNEL_VERSION_MAJOR 8
+#define tskKERNEL_VERSION_MINOR 2
+#define tskKERNEL_VERSION_BUILD 1
+
+/**
+ * task. h
+ *
+ * Type by which tasks are referenced.  For example, a call to xTaskCreate
+ * returns (via a pointer parameter) an TaskHandle_t variable that can then
+ * be used as a parameter to vTaskDelete to delete the task.
+ *
+ * \defgroup TaskHandle_t TaskHandle_t
+ * \ingroup Tasks
+ */
+typedef void * TaskHandle_t;
+
+/*
+ * Defines the prototype to which the application task hook function must
+ * conform.
+ */
+typedef BaseType_t (*TaskHookFunction_t)( void * );
+
+/* Task states returned by eTaskGetState. */
+typedef enum
+{
+	eRunning = 0,	/* A task is querying the state of itself, so must be running. */
+	eReady,			/* The task being queried is in a read or pending ready list. */
+	eBlocked,		/* The task being queried is in the Blocked state. */
+	eSuspended,		/* The task being queried is in the Suspended state, or is in the Blocked state with an infinite time out. */
+	eDeleted		/* The task being queried has been deleted, but its TCB has not yet been freed. */
+} eTaskState;
+
+/* Actions that can be performed when vTaskNotify() is called. */
+typedef enum
+{
+	eNoAction = 0,				/* Notify the task without updating its notify value. */
+	eSetBits,					/* Set bits in the task's notification value. */
+	eIncrement,					/* Increment the task's notification value. */
+	eSetValueWithOverwrite,		/* Set the task's notification value to a specific value even if the previous value has not yet been read by the task. */
+	eSetValueWithoutOverwrite	/* Set the task's notification value if the previous value has been read by the task. */
+} eNotifyAction;
+
+/*
+ * Used internally only.
+ */
+typedef struct xTIME_OUT
+{
+	BaseType_t xOverflowCount;
+	TickType_t xTimeOnEntering;
+} TimeOut_t;
+
+/*
+ * Defines the memory ranges allocated to the task when an MPU is used.
+ */
+typedef struct xMEMORY_REGION
+{
+	void *pvBaseAddress;
+	uint32_t ulLengthInBytes;
+	uint32_t ulParameters;
+} MemoryRegion_t;
+
+/*
+ * Parameters required to create an MPU protected task.
+ */
+
+typedef struct xTASK_PARAMETERS
+{
+	TaskFunction_t pvTaskCode;
+	const char * const pcName;	/*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+	uint16_t usStackDepth;
+	void *pvParameters;
+	UBaseType_t uxPriority;
+	StackType_t *puxStackBuffer;
+	MemoryRegion_t xRegions[ portNUM_CONFIGURABLE_REGIONS ];
+} TaskParameters_t;
+
+
+/* Used with the uxTaskGetSystemState() function to return the state of each task
+in the system. */
+typedef struct xTASK_STATUS
+{
+	TaskHandle_t xHandle;			/* The handle of the task to which the rest of the information in the structure relates. */
+	const char *pcTaskName;			/* A pointer to the task's name.  This value will be invalid if the task was deleted since the structure was populated! */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+	UBaseType_t xTaskNumber;		/* A number unique to the task. */
+	eTaskState eCurrentState;		/* The state in which the task existed when the structure was populated. */
+	UBaseType_t uxCurrentPriority;	/* The priority at which the task was running (may be inherited) when the structure was populated. */
+	UBaseType_t uxBasePriority;		/* The priority to which the task will return if the task's current priority has been inherited to avoid unbounded priority inversion when obtaining a mutex.  Only valid if configUSE_MUTEXES is defined as 1 in FreeRTOSConfig.h. */
+	uint32_t ulRunTimeCounter;		/* The total run time allocated to the task so far, as defined by the run time stats clock.  See http://www.freertos.org/rtos-run-time-stats.html.  Only valid when configGENERATE_RUN_TIME_STATS is defined as 1 in FreeRTOSConfig.h. */
+	uint16_t usStackHighWaterMark;	/* The minimum amount of stack space that has remained for the task since the task was created.  The closer this value is to zero the closer the task has come to overflowing its stack. */
+} TaskStatus_t;
+
+/* Possible return values for eTaskConfirmSleepModeStatus(). */
+typedef enum
+{
+	eAbortSleep = 0,		/* A task has been made ready or a context switch pended since portSUPPORESS_TICKS_AND_SLEEP() was called - abort entering a sleep mode. */
+	eStandardSleep,			/* Enter a sleep mode that will not last any longer than the expected idle time. */
+	eNoTasksWaitingTimeout	/* No tasks are waiting for a timeout so it is safe to enter a sleep mode that can only be exited by an external interrupt. */
+} eSleepModeStatus;
+
+
+/**
+ * Defines the priority used by the idle task.  This must not be modified.
+ *
+ * \ingroup TaskUtils
+ */
+#define tskIDLE_PRIORITY			( ( UBaseType_t ) 0U )
+
+/**
+ * task. h
+ *
+ * Macro for forcing a context switch.
+ *
+ * \defgroup taskYIELD taskYIELD
+ * \ingroup SchedulerControl
+ */
+#define taskYIELD()					portYIELD()
+
+/**
+ * task. h
+ *
+ * Macro to mark the start of a critical code region.  Preemptive context
+ * switches cannot occur when in a critical region.
+ *
+ * NOTE: This may alter the stack (depending on the portable implementation)
+ * so must be used with care!
+ *
+ * \defgroup taskENTER_CRITICAL taskENTER_CRITICAL
+ * \ingroup SchedulerControl
+ */
+#define taskENTER_CRITICAL()		portENTER_CRITICAL()
+#define taskENTER_CRITICAL_FROM_ISR( x ) portSET_INTERRUPT_MASK_FROM_ISR( x )
+
+/**
+ * task. h
+ *
+ * Macro to mark the end of a critical code region.  Preemptive context
+ * switches cannot occur when in a critical region.
+ *
+ * NOTE: This may alter the stack (depending on the portable implementation)
+ * so must be used with care!
+ *
+ * \defgroup taskEXIT_CRITICAL taskEXIT_CRITICAL
+ * \ingroup SchedulerControl
+ */
+#define taskEXIT_CRITICAL()			portEXIT_CRITICAL()
+#define taskEXIT_CRITICAL_FROM_ISR() portCLEAR_INTERRUPT_MASK_FROM_ISR()
+/**
+ * task. h
+ *
+ * Macro to disable all maskable interrupts.
+ *
+ * \defgroup taskDISABLE_INTERRUPTS taskDISABLE_INTERRUPTS
+ * \ingroup SchedulerControl
+ */
+#define taskDISABLE_INTERRUPTS()	portDISABLE_INTERRUPTS()
+
+/**
+ * task. h
+ *
+ * Macro to enable microcontroller interrupts.
+ *
+ * \defgroup taskENABLE_INTERRUPTS taskENABLE_INTERRUPTS
+ * \ingroup SchedulerControl
+ */
+#define taskENABLE_INTERRUPTS()		portENABLE_INTERRUPTS()
+
+/* Definitions returned by xTaskGetSchedulerState().  taskSCHEDULER_SUSPENDED is
+0 to generate more optimal code when configASSERT() is defined as the constant
+is used in assert() statements. */
+#define taskSCHEDULER_SUSPENDED		( ( BaseType_t ) 0 )
+#define taskSCHEDULER_NOT_STARTED	( ( BaseType_t ) 1 )
+#define taskSCHEDULER_RUNNING		( ( BaseType_t ) 2 )
+
+
+/*-----------------------------------------------------------
+ * TASK CREATION API
+ *----------------------------------------------------------*/
+
+/**
+ * task. h
+ *<pre>
+ BaseType_t xTaskCreate(
+							  TaskFunction_t pvTaskCode,
+							  const char * const pcName,
+							  uint16_t usStackDepth,
+							  void *pvParameters,
+							  UBaseType_t uxPriority,
+							  TaskHandle_t *pvCreatedTask
+						  );</pre>
+ *
+ * Create a new task and add it to the list of tasks that are ready to run.
+ *
+ * xTaskCreate() can only be used to create a task that has unrestricted
+ * access to the entire microcontroller memory map.  Systems that include MPU
+ * support can alternatively create an MPU constrained task using
+ * xTaskCreateRestricted().
+ *
+ * @param pvTaskCode Pointer to the task entry function.  Tasks
+ * must be implemented to never return (i.e. continuous loop).
+ *
+ * @param pcName A descriptive name for the task.  This is mainly used to
+ * facilitate debugging.  Max length defined by configMAX_TASK_NAME_LEN - default
+ * is 16.
+ *
+ * @param usStackDepth The size of the task stack specified as the number of
+ * variables the stack can hold - not the number of bytes.  For example, if
+ * the stack is 16 bits wide and usStackDepth is defined as 100, 200 bytes
+ * will be allocated for stack storage.
+ *
+ * @param pvParameters Pointer that will be used as the parameter for the task
+ * being created.
+ *
+ * @param uxPriority The priority at which the task should run.  Systems that
+ * include MPU support can optionally create tasks in a privileged (system)
+ * mode by setting bit portPRIVILEGE_BIT of the priority parameter.  For
+ * example, to create a privileged task at priority 2 the uxPriority parameter
+ * should be set to ( 2 | portPRIVILEGE_BIT ).
+ *
+ * @param pvCreatedTask Used to pass back a handle by which the created task
+ * can be referenced.
+ *
+ * @return pdPASS if the task was successfully created and added to a ready
+ * list, otherwise an error code defined in the file projdefs.h
+ *
+ * Example usage:
+   <pre>
+ // Task to be created.
+ void vTaskCode( void * pvParameters )
+ {
+	 for( ;; )
+	 {
+		 // Task code goes here.
+	 }
+ }
+
+ // Function that creates a task.
+ void vOtherFunction( void )
+ {
+ static uint8_t ucParameterToPass;
+ TaskHandle_t xHandle = NULL;
+
+	 // Create the task, storing the handle.  Note that the passed parameter ucParameterToPass
+	 // must exist for the lifetime of the task, so in this case is declared static.  If it was just an
+	 // an automatic stack variable it might no longer exist, or at least have been corrupted, by the time
+	 // the new task attempts to access it.
+	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, &ucParameterToPass, tskIDLE_PRIORITY, &xHandle );
+     configASSERT( xHandle );
+
+	 // Use the handle to delete the task.
+     if( xHandle != NULL )
+     {
+	     vTaskDelete( xHandle );
+     }
+ }
+   </pre>
+ * \defgroup xTaskCreate xTaskCreate
+ * \ingroup Tasks
+ */
+#define xTaskCreate( pvTaskCode, pcName, usStackDepth, pvParameters, uxPriority, pxCreatedTask ) xTaskGenericCreate( ( pvTaskCode ), ( pcName ), ( usStackDepth ), ( pvParameters ), ( uxPriority ), ( pxCreatedTask ), ( NULL ), ( NULL ) )
+
+/**
+ * task. h
+ *<pre>
+ BaseType_t xTaskCreateRestricted( TaskParameters_t *pxTaskDefinition, TaskHandle_t *pxCreatedTask );</pre>
+ *
+ * xTaskCreateRestricted() should only be used in systems that include an MPU
+ * implementation.
+ *
+ * Create a new task and add it to the list of tasks that are ready to run.
+ * The function parameters define the memory regions and associated access
+ * permissions allocated to the task.
+ *
+ * @param pxTaskDefinition Pointer to a structure that contains a member
+ * for each of the normal xTaskCreate() parameters (see the xTaskCreate() API
+ * documentation) plus an optional stack buffer and the memory region
+ * definitions.
+ *
+ * @param pxCreatedTask Used to pass back a handle by which the created task
+ * can be referenced.
+ *
+ * @return pdPASS if the task was successfully created and added to a ready
+ * list, otherwise an error code defined in the file projdefs.h
+ *
+ * Example usage:
+   <pre>
+// Create an TaskParameters_t structure that defines the task to be created.
+static const TaskParameters_t xCheckTaskParameters =
+{
+	vATask,		// pvTaskCode - the function that implements the task.
+	"ATask",	// pcName - just a text name for the task to assist debugging.
+	100,		// usStackDepth	- the stack size DEFINED IN WORDS.
+	NULL,		// pvParameters - passed into the task function as the function parameters.
+	( 1UL | portPRIVILEGE_BIT ),// uxPriority - task priority, set the portPRIVILEGE_BIT if the task should run in a privileged state.
+	cStackBuffer,// puxStackBuffer - the buffer to be used as the task stack.
+
+	// xRegions - Allocate up to three separate memory regions for access by
+	// the task, with appropriate access permissions.  Different processors have
+	// different memory alignment requirements - refer to the FreeRTOS documentation
+	// for full information.
+	{
+		// Base address					Length	Parameters
+        { cReadWriteArray,				32,		portMPU_REGION_READ_WRITE },
+        { cReadOnlyArray,				32,		portMPU_REGION_READ_ONLY },
+        { cPrivilegedOnlyAccessArray,	128,	portMPU_REGION_PRIVILEGED_READ_WRITE }
+	}
+};
+
+int main( void )
+{
+TaskHandle_t xHandle;
+
+	// Create a task from the const structure defined above.  The task handle
+	// is requested (the second parameter is not NULL) but in this case just for
+	// demonstration purposes as its not actually used.
+	xTaskCreateRestricted( &xRegTest1Parameters, &xHandle );
+
+	// Start the scheduler.
+	vTaskStartScheduler();
+
+	// Will only get here if there was insufficient memory to create the idle
+	// and/or timer task.
+	for( ;; );
+}
+   </pre>
+ * \defgroup xTaskCreateRestricted xTaskCreateRestricted
+ * \ingroup Tasks
+ */
+#define xTaskCreateRestricted( x, pxCreatedTask ) xTaskGenericCreate( ((x)->pvTaskCode), ((x)->pcName), ((x)->usStackDepth), ((x)->pvParameters), ((x)->uxPriority), (pxCreatedTask), ((x)->puxStackBuffer), ((x)->xRegions) )
+
+/**
+ * task. h
+ *<pre>
+ void vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const pxRegions );</pre>
+ *
+ * Memory regions are assigned to a restricted task when the task is created by
+ * a call to xTaskCreateRestricted().  These regions can be redefined using
+ * vTaskAllocateMPURegions().
+ *
+ * @param xTask The handle of the task being updated.
+ *
+ * @param xRegions A pointer to an MemoryRegion_t structure that contains the
+ * new memory region definitions.
+ *
+ * Example usage:
+   <pre>
+// Define an array of MemoryRegion_t structures that configures an MPU region
+// allowing read/write access for 1024 bytes starting at the beginning of the
+// ucOneKByte array.  The other two of the maximum 3 definable regions are
+// unused so set to zero.
+static const MemoryRegion_t xAltRegions[ portNUM_CONFIGURABLE_REGIONS ] =
+{
+	// Base address		Length		Parameters
+	{ ucOneKByte,		1024,		portMPU_REGION_READ_WRITE },
+	{ 0,				0,			0 },
+	{ 0,				0,			0 }
+};
+
+void vATask( void *pvParameters )
+{
+	// This task was created such that it has access to certain regions of
+	// memory as defined by the MPU configuration.  At some point it is
+	// desired that these MPU regions are replaced with that defined in the
+	// xAltRegions const struct above.  Use a call to vTaskAllocateMPURegions()
+	// for this purpose.  NULL is used as the task handle to indicate that this
+	// function should modify the MPU regions of the calling task.
+	vTaskAllocateMPURegions( NULL, xAltRegions );
+
+	// Now the task can continue its function, but from this point on can only
+	// access its stack and the ucOneKByte array (unless any other statically
+	// defined or shared regions have been declared elsewhere).
+}
+   </pre>
+ * \defgroup xTaskCreateRestricted xTaskCreateRestricted
+ * \ingroup Tasks
+ */
+void vTaskAllocateMPURegions( TaskHandle_t xTask, const MemoryRegion_t * const pxRegions ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * <pre>void vTaskDelete( TaskHandle_t xTask );</pre>
+ *
+ * INCLUDE_vTaskDelete must be defined as 1 for this function to be available.
+ * See the configuration section for more information.
+ *
+ * Remove a task from the RTOS real time kernel's management.  The task being
+ * deleted will be removed from all ready, blocked, suspended and event lists.
+ *
+ * NOTE:  The idle task is responsible for freeing the kernel allocated
+ * memory from tasks that have been deleted.  It is therefore important that
+ * the idle task is not starved of microcontroller processing time if your
+ * application makes any calls to vTaskDelete ().  Memory allocated by the
+ * task code is not automatically freed, and should be freed before the task
+ * is deleted.
+ *
+ * See the demo application file death.c for sample code that utilises
+ * vTaskDelete ().
+ *
+ * @param xTask The handle of the task to be deleted.  Passing NULL will
+ * cause the calling task to be deleted.
+ *
+ * Example usage:
+   <pre>
+ void vOtherFunction( void )
+ {
+ TaskHandle_t xHandle;
+
+	 // Create the task, storing the handle.
+	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
+
+	 // Use the handle to delete the task.
+	 vTaskDelete( xHandle );
+ }
+   </pre>
+ * \defgroup vTaskDelete vTaskDelete
+ * \ingroup Tasks
+ */
+void vTaskDelete( TaskHandle_t xTaskToDelete ) PRIVILEGED_FUNCTION;
+
+/*-----------------------------------------------------------
+ * TASK CONTROL API
+ *----------------------------------------------------------*/
+
+/**
+ * task. h
+ * <pre>void vTaskDelay( const TickType_t xTicksToDelay );</pre>
+ *
+ * Delay a task for a given number of ticks.  The actual time that the
+ * task remains blocked depends on the tick rate.  The constant
+ * portTICK_PERIOD_MS can be used to calculate real time from the tick
+ * rate - with the resolution of one tick period.
+ *
+ * INCLUDE_vTaskDelay must be defined as 1 for this function to be available.
+ * See the configuration section for more information.
+ *
+ *
+ * vTaskDelay() specifies a time at which the task wishes to unblock relative to
+ * the time at which vTaskDelay() is called.  For example, specifying a block
+ * period of 100 ticks will cause the task to unblock 100 ticks after
+ * vTaskDelay() is called.  vTaskDelay() does not therefore provide a good method
+ * of controlling the frequency of a periodic task as the path taken through the
+ * code, as well as other task and interrupt activity, will effect the frequency
+ * at which vTaskDelay() gets called and therefore the time at which the task
+ * next executes.  See vTaskDelayUntil() for an alternative API function designed
+ * to facilitate fixed frequency execution.  It does this by specifying an
+ * absolute time (rather than a relative time) at which the calling task should
+ * unblock.
+ *
+ * @param xTicksToDelay The amount of time, in tick periods, that
+ * the calling task should block.
+ *
+ * Example usage:
+
+ void vTaskFunction( void * pvParameters )
+ {
+ // Block for 500ms.
+ const TickType_t xDelay = 500 / portTICK_PERIOD_MS;
+
+	 for( ;; )
+	 {
+		 // Simply toggle the LED every 500ms, blocking between each toggle.
+		 vToggleLED();
+		 vTaskDelay( xDelay );
+	 }
+ }
+
+ * \defgroup vTaskDelay vTaskDelay
+ * \ingroup TaskCtrl
+ */
+void vTaskDelay( const TickType_t xTicksToDelay ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * <pre>void vTaskDelayUntil( TickType_t *pxPreviousWakeTime, const TickType_t xTimeIncrement );</pre>
+ *
+ * INCLUDE_vTaskDelayUntil must be defined as 1 for this function to be available.
+ * See the configuration section for more information.
+ *
+ * Delay a task until a specified time.  This function can be used by periodic
+ * tasks to ensure a constant execution frequency.
+ *
+ * This function differs from vTaskDelay () in one important aspect:  vTaskDelay () will
+ * cause a task to block for the specified number of ticks from the time vTaskDelay () is
+ * called.  It is therefore difficult to use vTaskDelay () by itself to generate a fixed
+ * execution frequency as the time between a task starting to execute and that task
+ * calling vTaskDelay () may not be fixed [the task may take a different path though the
+ * code between calls, or may get interrupted or preempted a different number of times
+ * each time it executes].
+ *
+ * Whereas vTaskDelay () specifies a wake time relative to the time at which the function
+ * is called, vTaskDelayUntil () specifies the absolute (exact) time at which it wishes to
+ * unblock.
+ *
+ * The constant portTICK_PERIOD_MS can be used to calculate real time from the tick
+ * rate - with the resolution of one tick period.
+ *
+ * @param pxPreviousWakeTime Pointer to a variable that holds the time at which the
+ * task was last unblocked.  The variable must be initialised with the current time
+ * prior to its first use (see the example below).  Following this the variable is
+ * automatically updated within vTaskDelayUntil ().
+ *
+ * @param xTimeIncrement The cycle time period.  The task will be unblocked at
+ * time *pxPreviousWakeTime + xTimeIncrement.  Calling vTaskDelayUntil with the
+ * same xTimeIncrement parameter value will cause the task to execute with
+ * a fixed interface period.
+ *
+ * Example usage:
+   <pre>
+ // Perform an action every 10 ticks.
+ void vTaskFunction( void * pvParameters )
+ {
+ TickType_t xLastWakeTime;
+ const TickType_t xFrequency = 10;
+
+	 // Initialise the xLastWakeTime variable with the current time.
+	 xLastWakeTime = xTaskGetTickCount ();
+	 for( ;; )
+	 {
+		 // Wait for the next cycle.
+		 vTaskDelayUntil( &xLastWakeTime, xFrequency );
+
+		 // Perform action here.
+	 }
+ }
+   </pre>
+ * \defgroup vTaskDelayUntil vTaskDelayUntil
+ * \ingroup TaskCtrl
+ */
+void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * <pre>UBaseType_t uxTaskPriorityGet( TaskHandle_t xTask );</pre>
+ *
+ * INCLUDE_uxTaskPriorityGet must be defined as 1 for this function to be available.
+ * See the configuration section for more information.
+ *
+ * Obtain the priority of any task.
+ *
+ * @param xTask Handle of the task to be queried.  Passing a NULL
+ * handle results in the priority of the calling task being returned.
+ *
+ * @return The priority of xTask.
+ *
+ * Example usage:
+   <pre>
+ void vAFunction( void )
+ {
+ TaskHandle_t xHandle;
+
+	 // Create a task, storing the handle.
+	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
+
+	 // ...
+
+	 // Use the handle to obtain the priority of the created task.
+	 // It was created with tskIDLE_PRIORITY, but may have changed
+	 // it itself.
+	 if( uxTaskPriorityGet( xHandle ) != tskIDLE_PRIORITY )
+	 {
+		 // The task has changed it's priority.
+	 }
+
+	 // ...
+
+	 // Is our priority higher than the created task?
+	 if( uxTaskPriorityGet( xHandle ) < uxTaskPriorityGet( NULL ) )
+	 {
+		 // Our priority (obtained using NULL handle) is higher.
+	 }
+ }
+   </pre>
+ * \defgroup uxTaskPriorityGet uxTaskPriorityGet
+ * \ingroup TaskCtrl
+ */
+UBaseType_t uxTaskPriorityGet( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * <pre>UBaseType_t uxTaskPriorityGetFromISR( TaskHandle_t xTask );</pre>
+ *
+ * A version of uxTaskPriorityGet() that can be used from an ISR.
+ */
+UBaseType_t uxTaskPriorityGetFromISR( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * <pre>eTaskState eTaskGetState( TaskHandle_t xTask );</pre>
+ *
+ * INCLUDE_eTaskGetState must be defined as 1 for this function to be available.
+ * See the configuration section for more information.
+ *
+ * Obtain the state of any task.  States are encoded by the eTaskState
+ * enumerated type.
+ *
+ * @param xTask Handle of the task to be queried.
+ *
+ * @return The state of xTask at the time the function was called.  Note the
+ * state of the task might change between the function being called, and the
+ * functions return value being tested by the calling task.
+ */
+eTaskState eTaskGetState( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * <pre>void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority );</pre>
+ *
+ * INCLUDE_vTaskPrioritySet must be defined as 1 for this function to be available.
+ * See the configuration section for more information.
+ *
+ * Set the priority of any task.
+ *
+ * A context switch will occur before the function returns if the priority
+ * being set is higher than the currently executing task.
+ *
+ * @param xTask Handle to the task for which the priority is being set.
+ * Passing a NULL handle results in the priority of the calling task being set.
+ *
+ * @param uxNewPriority The priority to which the task will be set.
+ *
+ * Example usage:
+   <pre>
+ void vAFunction( void )
+ {
+ TaskHandle_t xHandle;
+
+	 // Create a task, storing the handle.
+	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
+
+	 // ...
+
+	 // Use the handle to raise the priority of the created task.
+	 vTaskPrioritySet( xHandle, tskIDLE_PRIORITY + 1 );
+
+	 // ...
+
+	 // Use a NULL handle to raise our priority to the same value.
+	 vTaskPrioritySet( NULL, tskIDLE_PRIORITY + 1 );
+ }
+   </pre>
+ * \defgroup vTaskPrioritySet vTaskPrioritySet
+ * \ingroup TaskCtrl
+ */
+void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * <pre>void vTaskSuspend( TaskHandle_t xTaskToSuspend );</pre>
+ *
+ * INCLUDE_vTaskSuspend must be defined as 1 for this function to be available.
+ * See the configuration section for more information.
+ *
+ * Suspend any task.  When suspended a task will never get any microcontroller
+ * processing time, no matter what its priority.
+ *
+ * Calls to vTaskSuspend are not accumulative -
+ * i.e. calling vTaskSuspend () twice on the same task still only requires one
+ * call to vTaskResume () to ready the suspended task.
+ *
+ * @param xTaskToSuspend Handle to the task being suspended.  Passing a NULL
+ * handle will cause the calling task to be suspended.
+ *
+ * Example usage:
+   <pre>
+ void vAFunction( void )
+ {
+ TaskHandle_t xHandle;
+
+	 // Create a task, storing the handle.
+	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
+
+	 // ...
+
+	 // Use the handle to suspend the created task.
+	 vTaskSuspend( xHandle );
+
+	 // ...
+
+	 // The created task will not run during this period, unless
+	 // another task calls vTaskResume( xHandle ).
+
+	 //...
+
+
+	 // Suspend ourselves.
+	 vTaskSuspend( NULL );
+
+	 // We cannot get here unless another task calls vTaskResume
+	 // with our handle as the parameter.
+ }
+   </pre>
+ * \defgroup vTaskSuspend vTaskSuspend
+ * \ingroup TaskCtrl
+ */
+void vTaskSuspend( TaskHandle_t xTaskToSuspend ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * <pre>void vTaskResume( TaskHandle_t xTaskToResume );</pre>
+ *
+ * INCLUDE_vTaskSuspend must be defined as 1 for this function to be available.
+ * See the configuration section for more information.
+ *
+ * Resumes a suspended task.
+ *
+ * A task that has been suspended by one or more calls to vTaskSuspend ()
+ * will be made available for running again by a single call to
+ * vTaskResume ().
+ *
+ * @param xTaskToResume Handle to the task being readied.
+ *
+ * Example usage:
+   <pre>
+ void vAFunction( void )
+ {
+ TaskHandle_t xHandle;
+
+	 // Create a task, storing the handle.
+	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, &xHandle );
+
+	 // ...
+
+	 // Use the handle to suspend the created task.
+	 vTaskSuspend( xHandle );
+
+	 // ...
+
+	 // The created task will not run during this period, unless
+	 // another task calls vTaskResume( xHandle ).
+
+	 //...
+
+
+	 // Resume the suspended task ourselves.
+	 vTaskResume( xHandle );
+
+	 // The created task will once again get microcontroller processing
+	 // time in accordance with its priority within the system.
+ }
+   </pre>
+ * \defgroup vTaskResume vTaskResume
+ * \ingroup TaskCtrl
+ */
+void vTaskResume( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * <pre>void xTaskResumeFromISR( TaskHandle_t xTaskToResume );</pre>
+ *
+ * INCLUDE_xTaskResumeFromISR must be defined as 1 for this function to be
+ * available.  See the configuration section for more information.
+ *
+ * An implementation of vTaskResume() that can be called from within an ISR.
+ *
+ * A task that has been suspended by one or more calls to vTaskSuspend ()
+ * will be made available for running again by a single call to
+ * xTaskResumeFromISR ().
+ *
+ * xTaskResumeFromISR() should not be used to synchronise a task with an
+ * interrupt if there is a chance that the interrupt could arrive prior to the
+ * task being suspended - as this can lead to interrupts being missed. Use of a
+ * semaphore as a synchronisation mechanism would avoid this eventuality.
+ *
+ * @param xTaskToResume Handle to the task being readied.
+ *
+ * @return pdTRUE if resuming the task should result in a context switch,
+ * otherwise pdFALSE. This is used by the ISR to determine if a context switch
+ * may be required following the ISR.
+ *
+ * \defgroup vTaskResumeFromISR vTaskResumeFromISR
+ * \ingroup TaskCtrl
+ */
+BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume ) PRIVILEGED_FUNCTION;
+
+/*-----------------------------------------------------------
+ * SCHEDULER CONTROL
+ *----------------------------------------------------------*/
+
+/**
+ * task. h
+ * <pre>void vTaskStartScheduler( void );</pre>
+ *
+ * Starts the real time kernel tick processing.  After calling the kernel
+ * has control over which tasks are executed and when.
+ *
+ * See the demo application file main.c for an example of creating
+ * tasks and starting the kernel.
+ *
+ * Example usage:
+   <pre>
+ void vAFunction( void )
+ {
+	 // Create at least one task before starting the kernel.
+	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
+
+	 // Start the real time kernel with preemption.
+	 vTaskStartScheduler ();
+
+	 // Will not get here unless a task calls vTaskEndScheduler ()
+ }
+   </pre>
+ *
+ * \defgroup vTaskStartScheduler vTaskStartScheduler
+ * \ingroup SchedulerControl
+ */
+void vTaskStartScheduler( void ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * <pre>void vTaskEndScheduler( void );</pre>
+ *
+ * NOTE:  At the time of writing only the x86 real mode port, which runs on a PC
+ * in place of DOS, implements this function.
+ *
+ * Stops the real time kernel tick.  All created tasks will be automatically
+ * deleted and multitasking (either preemptive or cooperative) will
+ * stop.  Execution then resumes from the point where vTaskStartScheduler ()
+ * was called, as if vTaskStartScheduler () had just returned.
+ *
+ * See the demo application file main. c in the demo/PC directory for an
+ * example that uses vTaskEndScheduler ().
+ *
+ * vTaskEndScheduler () requires an exit function to be defined within the
+ * portable layer (see vPortEndScheduler () in port. c for the PC port).  This
+ * performs hardware specific operations such as stopping the kernel tick.
+ *
+ * vTaskEndScheduler () will cause all of the resources allocated by the
+ * kernel to be freed - but will not free resources allocated by application
+ * tasks.
+ *
+ * Example usage:
+   <pre>
+ void vTaskCode( void * pvParameters )
+ {
+	 for( ;; )
+	 {
+		 // Task code goes here.
+
+		 // At some point we want to end the real time kernel processing
+		 // so call ...
+		 vTaskEndScheduler ();
+	 }
+ }
+
+ void vAFunction( void )
+ {
+	 // Create at least one task before starting the kernel.
+	 xTaskCreate( vTaskCode, "NAME", STACK_SIZE, NULL, tskIDLE_PRIORITY, NULL );
+
+	 // Start the real time kernel with preemption.
+	 vTaskStartScheduler ();
+
+	 // Will only get here when the vTaskCode () task has called
+	 // vTaskEndScheduler ().  When we get here we are back to single task
+	 // execution.
+ }
+   </pre>
+ *
+ * \defgroup vTaskEndScheduler vTaskEndScheduler
+ * \ingroup SchedulerControl
+ */
+void vTaskEndScheduler( void ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * <pre>void vTaskSuspendAll( void );</pre>
+ *
+ * Suspends the scheduler without disabling interrupts.  Context switches will
+ * not occur while the scheduler is suspended.
+ *
+ * After calling vTaskSuspendAll () the calling task will continue to execute
+ * without risk of being swapped out until a call to xTaskResumeAll () has been
+ * made.
+ *
+ * API functions that have the potential to cause a context switch (for example,
+ * vTaskDelayUntil(), xQueueSend(), etc.) must not be called while the scheduler
+ * is suspended.
+ *
+ * Example usage:
+   <pre>
+ void vTask1( void * pvParameters )
+ {
+	 for( ;; )
+	 {
+		 // Task code goes here.
+
+		 // ...
+
+		 // At some point the task wants to perform a long operation during
+		 // which it does not want to get swapped out.  It cannot use
+		 // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the
+		 // operation may cause interrupts to be missed - including the
+		 // ticks.
+
+		 // Prevent the real time kernel swapping out the task.
+		 vTaskSuspendAll ();
+
+		 // Perform the operation here.  There is no need to use critical
+		 // sections as we have all the microcontroller processing time.
+		 // During this time interrupts will still operate and the kernel
+		 // tick count will be maintained.
+
+		 // ...
+
+		 // The operation is complete.  Restart the kernel.
+		 xTaskResumeAll ();
+	 }
+ }
+   </pre>
+ * \defgroup vTaskSuspendAll vTaskSuspendAll
+ * \ingroup SchedulerControl
+ */
+void vTaskSuspendAll( void ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * <pre>BaseType_t xTaskResumeAll( void );</pre>
+ *
+ * Resumes scheduler activity after it was suspended by a call to
+ * vTaskSuspendAll().
+ *
+ * xTaskResumeAll() only resumes the scheduler.  It does not unsuspend tasks
+ * that were previously suspended by a call to vTaskSuspend().
+ *
+ * @return If resuming the scheduler caused a context switch then pdTRUE is
+ *		  returned, otherwise pdFALSE is returned.
+ *
+ * Example usage:
+   <pre>
+ void vTask1( void * pvParameters )
+ {
+	 for( ;; )
+	 {
+		 // Task code goes here.
+
+		 // ...
+
+		 // At some point the task wants to perform a long operation during
+		 // which it does not want to get swapped out.  It cannot use
+		 // taskENTER_CRITICAL ()/taskEXIT_CRITICAL () as the length of the
+		 // operation may cause interrupts to be missed - including the
+		 // ticks.
+
+		 // Prevent the real time kernel swapping out the task.
+		 vTaskSuspendAll ();
+
+		 // Perform the operation here.  There is no need to use critical
+		 // sections as we have all the microcontroller processing time.
+		 // During this time interrupts will still operate and the real
+		 // time kernel tick count will be maintained.
+
+		 // ...
+
+		 // The operation is complete.  Restart the kernel.  We want to force
+		 // a context switch - but there is no point if resuming the scheduler
+		 // caused a context switch already.
+		 if( !xTaskResumeAll () )
+		 {
+			  taskYIELD ();
+		 }
+	 }
+ }
+   </pre>
+ * \defgroup xTaskResumeAll xTaskResumeAll
+ * \ingroup SchedulerControl
+ */
+BaseType_t xTaskResumeAll( void ) PRIVILEGED_FUNCTION;
+
+/*-----------------------------------------------------------
+ * TASK UTILITIES
+ *----------------------------------------------------------*/
+
+/**
+ * task. h
+ * <PRE>TickType_t xTaskGetTickCount( void );</PRE>
+ *
+ * @return The count of ticks since vTaskStartScheduler was called.
+ *
+ * \defgroup xTaskGetTickCount xTaskGetTickCount
+ * \ingroup TaskUtils
+ */
+TickType_t xTaskGetTickCount( void ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * <PRE>TickType_t xTaskGetTickCountFromISR( void );</PRE>
+ *
+ * @return The count of ticks since vTaskStartScheduler was called.
+ *
+ * This is a version of xTaskGetTickCount() that is safe to be called from an
+ * ISR - provided that TickType_t is the natural word size of the
+ * microcontroller being used or interrupt nesting is either not supported or
+ * not being used.
+ *
+ * \defgroup xTaskGetTickCountFromISR xTaskGetTickCountFromISR
+ * \ingroup TaskUtils
+ */
+TickType_t xTaskGetTickCountFromISR( void ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * <PRE>uint16_t uxTaskGetNumberOfTasks( void );</PRE>
+ *
+ * @return The number of tasks that the real time kernel is currently managing.
+ * This includes all ready, blocked and suspended tasks.  A task that
+ * has been deleted but not yet freed by the idle task will also be
+ * included in the count.
+ *
+ * \defgroup uxTaskGetNumberOfTasks uxTaskGetNumberOfTasks
+ * \ingroup TaskUtils
+ */
+UBaseType_t uxTaskGetNumberOfTasks( void ) PRIVILEGED_FUNCTION;
+
+/**
+ * task. h
+ * <PRE>char *pcTaskGetTaskName( TaskHandle_t xTaskToQuery );</PRE>
+ *
+ * @return The text (human readable) name of the task referenced by the handle
+ * xTaskToQuery.  A task can query its own name by either passing in its own
+ * handle, or by setting xTaskToQuery to NULL.  INCLUDE_pcTaskGetTaskName must be
+ * set to 1 in FreeRTOSConfig.h for pcTaskGetTaskName() to be available.
+ *
+ * \defgroup pcTaskGetTaskName pcTaskGetTaskName
+ * \ingroup TaskUtils
+ */
+char *pcTaskGetTaskName( TaskHandle_t xTaskToQuery ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+
+/**
+ * task.h
+ * <PRE>UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask );</PRE>
+ *
+ * INCLUDE_uxTaskGetStackHighWaterMark must be set to 1 in FreeRTOSConfig.h for
+ * this function to be available.
+ *
+ * Returns the high water mark of the stack associated with xTask.  That is,
+ * the minimum free stack space there has been (in words, so on a 32 bit machine
+ * a value of 1 means 4 bytes) since the task started.  The smaller the returned
+ * number the closer the task has come to overflowing its stack.
+ *
+ * @param xTask Handle of the task associated with the stack to be checked.
+ * Set xTask to NULL to check the stack of the calling task.
+ *
+ * @return The smallest amount of free stack space there has been (in words, so
+ * actual spaces on the stack rather than bytes) since the task referenced by
+ * xTask was created.
+ */
+UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+
+/* When using trace macros it is sometimes necessary to include task.h before
+FreeRTOS.h.  When this is done TaskHookFunction_t will not yet have been defined,
+so the following two prototypes will cause a compilation error.  This can be
+fixed by simply guarding against the inclusion of these two prototypes unless
+they are explicitly required by the configUSE_APPLICATION_TASK_TAG configuration
+constant. */
+#ifdef configUSE_APPLICATION_TASK_TAG
+	#if configUSE_APPLICATION_TASK_TAG == 1
+		/**
+		 * task.h
+		 * <pre>void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction );</pre>
+		 *
+		 * Sets pxHookFunction to be the task hook function used by the task xTask.
+		 * Passing xTask as NULL has the effect of setting the calling tasks hook
+		 * function.
+		 */
+		void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction ) PRIVILEGED_FUNCTION;
+
+		/**
+		 * task.h
+		 * <pre>void xTaskGetApplicationTaskTag( TaskHandle_t xTask );</pre>
+		 *
+		 * Returns the pxHookFunction value assigned to the task xTask.
+		 */
+		TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+	#endif /* configUSE_APPLICATION_TASK_TAG ==1 */
+#endif /* ifdef configUSE_APPLICATION_TASK_TAG */
+
+#if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 )
+
+	/* Each task contains an array of pointers that is dimensioned by the
+	configNUM_THREAD_LOCAL_STORAGE_POINTERS setting in FreeRTOSConfig.h.  The
+	kernel does not use the pointers itself, so the application writer can use
+	the pointers for any purpose they wish.  The following two functions are
+	used to set and query a pointer respectively. */
+	void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue );
+	void *pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex );
+
+#endif
+
+/**
+ * task.h
+ * <pre>BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter );</pre>
+ *
+ * Calls the hook function associated with xTask.  Passing xTask as NULL has
+ * the effect of calling the Running tasks (the calling task) hook function.
+ *
+ * pvParameter is passed to the hook function for the task to interpret as it
+ * wants.  The return value is the value returned by the task hook function
+ * registered by the user.
+ */
+BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter ) PRIVILEGED_FUNCTION;
+
+/**
+ * xTaskGetIdleTaskHandle() is only available if
+ * INCLUDE_xTaskGetIdleTaskHandle is set to 1 in FreeRTOSConfig.h.
+ *
+ * Simply returns the handle of the idle task.  It is not valid to call
+ * xTaskGetIdleTaskHandle() before the scheduler has been started.
+ */
+TaskHandle_t xTaskGetIdleTaskHandle( void );
+
+/**
+ * configUSE_TRACE_FACILITY must be defined as 1 in FreeRTOSConfig.h for
+ * uxTaskGetSystemState() to be available.
+ *
+ * uxTaskGetSystemState() populates an TaskStatus_t structure for each task in
+ * the system.  TaskStatus_t structures contain, among other things, members
+ * for the task handle, task name, task priority, task state, and total amount
+ * of run time consumed by the task.  See the TaskStatus_t structure
+ * definition in this file for the full member list.
+ *
+ * NOTE:  This function is intended for debugging use only as its use results in
+ * the scheduler remaining suspended for an extended period.
+ *
+ * @param pxTaskStatusArray A pointer to an array of TaskStatus_t structures.
+ * The array must contain at least one TaskStatus_t structure for each task
+ * that is under the control of the RTOS.  The number of tasks under the control
+ * of the RTOS can be determined using the uxTaskGetNumberOfTasks() API function.
+ *
+ * @param uxArraySize The size of the array pointed to by the pxTaskStatusArray
+ * parameter.  The size is specified as the number of indexes in the array, or
+ * the number of TaskStatus_t structures contained in the array, not by the
+ * number of bytes in the array.
+ *
+ * @param pulTotalRunTime If configGENERATE_RUN_TIME_STATS is set to 1 in
+ * FreeRTOSConfig.h then *pulTotalRunTime is set by uxTaskGetSystemState() to the
+ * total run time (as defined by the run time stats clock, see
+ * http://www.freertos.org/rtos-run-time-stats.html) since the target booted.
+ * pulTotalRunTime can be set to NULL to omit the total run time information.
+ *
+ * @return The number of TaskStatus_t structures that were populated by
+ * uxTaskGetSystemState().  This should equal the number returned by the
+ * uxTaskGetNumberOfTasks() API function, but will be zero if the value passed
+ * in the uxArraySize parameter was too small.
+ *
+ * Example usage:
+   <pre>
+    // This example demonstrates how a human readable table of run time stats
+	// information is generated from raw data provided by uxTaskGetSystemState().
+	// The human readable table is written to pcWriteBuffer
+	void vTaskGetRunTimeStats( char *pcWriteBuffer )
+	{
+	TaskStatus_t *pxTaskStatusArray;
+	volatile UBaseType_t uxArraySize, x;
+	uint32_t ulTotalRunTime, ulStatsAsPercentage;
+
+		// Make sure the write buffer does not contain a string.
+		*pcWriteBuffer = 0x00;
+
+		// Take a snapshot of the number of tasks in case it changes while this
+		// function is executing.
+		uxArraySize = uxTaskGetNumberOfTasks();
+
+		// Allocate a TaskStatus_t structure for each task.  An array could be
+		// allocated statically at compile time.
+		pxTaskStatusArray = pvPortMalloc( uxArraySize * sizeof( TaskStatus_t ) );
+
+		if( pxTaskStatusArray != NULL )
+		{
+			// Generate raw status information about each task.
+			uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalRunTime );
+
+			// For percentage calculations.
+			ulTotalRunTime /= 100UL;
+
+			// Avoid divide by zero errors.
+			if( ulTotalRunTime > 0 )
+			{
+				// For each populated position in the pxTaskStatusArray array,
+				// format the raw data as human readable ASCII data
+				for( x = 0; x < uxArraySize; x++ )
+				{
+					// What percentage of the total run time has the task used?
+					// This will always be rounded down to the nearest integer.
+					// ulTotalRunTimeDiv100 has already been divided by 100.
+					ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalRunTime;
+
+					if( ulStatsAsPercentage > 0UL )
+					{
+						sprintf( pcWriteBuffer, "%s\t\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage );
+					}
+					else
+					{
+						// If the percentage is zero here then the task has
+						// consumed less than 1% of the total run time.
+						sprintf( pcWriteBuffer, "%s\t\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].pcTaskName, pxTaskStatusArray[ x ].ulRunTimeCounter );
+					}
+
+					pcWriteBuffer += strlen( ( char * ) pcWriteBuffer );
+				}
+			}
+
+			// The array is no longer needed, free the memory it consumes.
+			vPortFree( pxTaskStatusArray );
+		}
+	}
+	</pre>
+ */
+UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime );
+
+/**
+ * task. h
+ * <PRE>void vTaskList( char *pcWriteBuffer );</PRE>
+ *
+ * configUSE_TRACE_FACILITY and configUSE_STATS_FORMATTING_FUNCTIONS must
+ * both be defined as 1 for this function to be available.  See the
+ * configuration section of the FreeRTOS.org website for more information.
+ *
+ * NOTE 1: This function will disable interrupts for its duration.  It is
+ * not intended for normal application runtime use but as a debug aid.
+ *
+ * Lists all the current tasks, along with their current state and stack
+ * usage high water mark.
+ *
+ * Tasks are reported as blocked ('B'), ready ('R'), deleted ('D') or
+ * suspended ('S').
+ *
+ * PLEASE NOTE:
+ *
+ * This function is provided for convenience only, and is used by many of the
+ * demo applications.  Do not consider it to be part of the scheduler.
+ *
+ * vTaskList() calls uxTaskGetSystemState(), then formats part of the
+ * uxTaskGetSystemState() output into a human readable table that displays task
+ * names, states and stack usage.
+ *
+ * vTaskList() has a dependency on the sprintf() C library function that might
+ * bloat the code size, use a lot of stack, and provide different results on
+ * different platforms.  An alternative, tiny, third party, and limited
+ * functionality implementation of sprintf() is provided in many of the
+ * FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note
+ * printf-stdarg.c does not provide a full snprintf() implementation!).
+ *
+ * It is recommended that production systems call uxTaskGetSystemState()
+ * directly to get access to raw stats data, rather than indirectly through a
+ * call to vTaskList().
+ *
+ * @param pcWriteBuffer A buffer into which the above mentioned details
+ * will be written, in ASCII form.  This buffer is assumed to be large
+ * enough to contain the generated report.  Approximately 40 bytes per
+ * task should be sufficient.
+ *
+ * \defgroup vTaskList vTaskList
+ * \ingroup TaskUtils
+ */
+void vTaskList( char * pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+
+/**
+ * task. h
+ * <PRE>void vTaskGetRunTimeStats( char *pcWriteBuffer );</PRE>
+ *
+ * configGENERATE_RUN_TIME_STATS and configUSE_STATS_FORMATTING_FUNCTIONS
+ * must both be defined as 1 for this function to be available.  The application
+ * must also then provide definitions for
+ * portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() and portGET_RUN_TIME_COUNTER_VALUE()
+ * to configure a peripheral timer/counter and return the timers current count
+ * value respectively.  The counter should be at least 10 times the frequency of
+ * the tick count.
+ *
+ * NOTE 1: This function will disable interrupts for its duration.  It is
+ * not intended for normal application runtime use but as a debug aid.
+ *
+ * Setting configGENERATE_RUN_TIME_STATS to 1 will result in a total
+ * accumulated execution time being stored for each task.  The resolution
+ * of the accumulated time value depends on the frequency of the timer
+ * configured by the portCONFIGURE_TIMER_FOR_RUN_TIME_STATS() macro.
+ * Calling vTaskGetRunTimeStats() writes the total execution time of each
+ * task into a buffer, both as an absolute count value and as a percentage
+ * of the total system execution time.
+ *
+ * NOTE 2:
+ *
+ * This function is provided for convenience only, and is used by many of the
+ * demo applications.  Do not consider it to be part of the scheduler.
+ *
+ * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part of the
+ * uxTaskGetSystemState() output into a human readable table that displays the
+ * amount of time each task has spent in the Running state in both absolute and
+ * percentage terms.
+ *
+ * vTaskGetRunTimeStats() has a dependency on the sprintf() C library function
+ * that might bloat the code size, use a lot of stack, and provide different
+ * results on different platforms.  An alternative, tiny, third party, and
+ * limited functionality implementation of sprintf() is provided in many of the
+ * FreeRTOS/Demo sub-directories in a file called printf-stdarg.c (note
+ * printf-stdarg.c does not provide a full snprintf() implementation!).
+ *
+ * It is recommended that production systems call uxTaskGetSystemState() directly
+ * to get access to raw stats data, rather than indirectly through a call to
+ * vTaskGetRunTimeStats().
+ *
+ * @param pcWriteBuffer A buffer into which the execution times will be
+ * written, in ASCII form.  This buffer is assumed to be large enough to
+ * contain the generated report.  Approximately 40 bytes per task should
+ * be sufficient.
+ *
+ * \defgroup vTaskGetRunTimeStats vTaskGetRunTimeStats
+ * \ingroup TaskUtils
+ */
+void vTaskGetRunTimeStats( char *pcWriteBuffer ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+
+/**
+ * task. h
+ * <PRE>BaseType_t xTaskNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction );</PRE>
+ *
+ * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this
+ * function to be available.
+ *
+ * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
+ * "notification value", which is a 32-bit unsigned integer (uint32_t).
+ *
+ * Events can be sent to a task using an intermediary object.  Examples of such
+ * objects are queues, semaphores, mutexes and event groups.  Task notifications
+ * are a method of sending an event directly to a task without the need for such
+ * an intermediary object.
+ *
+ * A notification sent to a task can optionally perform an action, such as
+ * update, overwrite or increment the task's notification value.  In that way
+ * task notifications can be used to send data to a task, or be used as light
+ * weight and fast binary or counting semaphores.
+ *
+ * A notification sent to a task will remain pending until it is cleared by the
+ * task calling xTaskNotifyWait() or ulTaskNotifyTake().  If the task was
+ * already in the Blocked state to wait for a notification when the notification
+ * arrives then the task will automatically be removed from the Blocked state
+ * (unblocked) and the notification cleared.
+ *
+ * A task can use xTaskNotifyWait() to [optionally] block to wait for a
+ * notification to be pending, or ulTaskNotifyTake() to [optionally] block
+ * to wait for its notification value to have a non-zero value.  The task does
+ * not consume any CPU time while it is in the Blocked state.
+ *
+ * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
+ *
+ * @param xTaskToNotify The handle of the task being notified.  The handle to a
+ * task can be returned from the xTaskCreate() API function used to create the
+ * task, and the handle of the currently running task can be obtained by calling
+ * xTaskGetCurrentTaskHandle().
+ *
+ * @param ulValue Data that can be sent with the notification.  How the data is
+ * used depends on the value of the eAction parameter.
+ *
+ * @param eAction Specifies how the notification updates the task's notification
+ * value, if at all.  Valid values for eAction are as follows:
+ *
+ *	eSetBits -
+ *	The task's notification value is bitwise ORed with ulValue.  xTaskNofify()
+ * 	always returns pdPASS in this case.
+ *
+ *	eIncrement -
+ *	The task's notification value is incremented.  ulValue is not used and
+ *	xTaskNotify() always returns pdPASS in this case.
+ *
+ *	eSetValueWithOverwrite -
+ *	The task's notification value is set to the value of ulValue, even if the
+ *	task being notified had not yet processed the previous notification (the
+ *	task already had a notification pending).  xTaskNotify() always returns
+ *	pdPASS in this case.
+ *
+ *	eSetValueWithoutOverwrite -
+ *	If the task being notified did not already have a notification pending then
+ *	the task's notification value is set to ulValue and xTaskNotify() will
+ *	return pdPASS.  If the task being notified already had a notification
+ *	pending then no action is performed and pdFAIL is returned.
+ *
+ *	eNoAction -
+ *	The task receives a notification without its notification value being
+ *	updated.  ulValue is not used and xTaskNotify() always returns pdPASS in
+ *	this case.
+ *
+ *  pulPreviousNotificationValue -
+ *  Can be used to pass out the subject task's notification value before any
+ *  bits are modified by the notify function.
+ *
+ * @return Dependent on the value of eAction.  See the description of the
+ * eAction parameter.
+ *
+ * \defgroup xTaskNotify xTaskNotify
+ * \ingroup TaskNotifications
+ */
+BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue );
+#define xTaskNotify( xTaskToNotify, ulValue, eAction ) xTaskGenericNotify( ( xTaskToNotify ), ( ulValue ), ( eAction ), NULL )
+#define xTaskNotifyAndQuery( xTaskToNotify, ulValue, eAction, pulPreviousNotifyValue ) xTaskGenericNotify( ( xTaskToNotify ), ( ulValue ), ( eAction ), ( pulPreviousNotifyValue ) )
+
+/**
+ * task. h
+ * <PRE>BaseType_t xTaskNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, BaseType_t *pxHigherPriorityTaskWoken );</PRE>
+ *
+ * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this
+ * function to be available.
+ *
+ * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
+ * "notification value", which is a 32-bit unsigned integer (uint32_t).
+ *
+ * A version of xTaskNotify() that can be used from an interrupt service routine
+ * (ISR).
+ *
+ * Events can be sent to a task using an intermediary object.  Examples of such
+ * objects are queues, semaphores, mutexes and event groups.  Task notifications
+ * are a method of sending an event directly to a task without the need for such
+ * an intermediary object.
+ *
+ * A notification sent to a task can optionally perform an action, such as
+ * update, overwrite or increment the task's notification value.  In that way
+ * task notifications can be used to send data to a task, or be used as light
+ * weight and fast binary or counting semaphores.
+ *
+ * A notification sent to a task will remain pending until it is cleared by the
+ * task calling xTaskNotifyWait() or ulTaskNotifyTake().  If the task was
+ * already in the Blocked state to wait for a notification when the notification
+ * arrives then the task will automatically be removed from the Blocked state
+ * (unblocked) and the notification cleared.
+ *
+ * A task can use xTaskNotifyWait() to [optionally] block to wait for a
+ * notification to be pending, or ulTaskNotifyTake() to [optionally] block
+ * to wait for its notification value to have a non-zero value.  The task does
+ * not consume any CPU time while it is in the Blocked state.
+ *
+ * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
+ *
+ * @param xTaskToNotify The handle of the task being notified.  The handle to a
+ * task can be returned from the xTaskCreate() API function used to create the
+ * task, and the handle of the currently running task can be obtained by calling
+ * xTaskGetCurrentTaskHandle().
+ *
+ * @param ulValue Data that can be sent with the notification.  How the data is
+ * used depends on the value of the eAction parameter.
+ *
+ * @param eAction Specifies how the notification updates the task's notification
+ * value, if at all.  Valid values for eAction are as follows:
+ *
+ *	eSetBits -
+ *	The task's notification value is bitwise ORed with ulValue.  xTaskNofify()
+ * 	always returns pdPASS in this case.
+ *
+ *	eIncrement -
+ *	The task's notification value is incremented.  ulValue is not used and
+ *	xTaskNotify() always returns pdPASS in this case.
+ *
+ *	eSetValueWithOverwrite -
+ *	The task's notification value is set to the value of ulValue, even if the
+ *	task being notified had not yet processed the previous notification (the
+ *	task already had a notification pending).  xTaskNotify() always returns
+ *	pdPASS in this case.
+ *
+ *	eSetValueWithoutOverwrite -
+ *	If the task being notified did not already have a notification pending then
+ *	the task's notification value is set to ulValue and xTaskNotify() will
+ *	return pdPASS.  If the task being notified already had a notification
+ *	pending then no action is performed and pdFAIL is returned.
+ *
+ *	eNoAction -
+ *	The task receives a notification without its notification value being
+ *	updated.  ulValue is not used and xTaskNotify() always returns pdPASS in
+ *	this case.
+ *
+ * @param pxHigherPriorityTaskWoken  xTaskNotifyFromISR() will set
+ * *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the
+ * task to which the notification was sent to leave the Blocked state, and the
+ * unblocked task has a priority higher than the currently running task.  If
+ * xTaskNotifyFromISR() sets this value to pdTRUE then a context switch should
+ * be requested before the interrupt is exited.  How a context switch is
+ * requested from an ISR is dependent on the port - see the documentation page
+ * for the port in use.
+ *
+ * @return Dependent on the value of eAction.  See the description of the
+ * eAction parameter.
+ *
+ * \defgroup xTaskNotify xTaskNotify
+ * \ingroup TaskNotifications
+ */
+BaseType_t xTaskNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, BaseType_t *pxHigherPriorityTaskWoken );
+
+/**
+ * task. h
+ * <PRE>BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait );</pre>
+ *
+ * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this
+ * function to be available.
+ *
+ * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
+ * "notification value", which is a 32-bit unsigned integer (uint32_t).
+ *
+ * Events can be sent to a task using an intermediary object.  Examples of such
+ * objects are queues, semaphores, mutexes and event groups.  Task notifications
+ * are a method of sending an event directly to a task without the need for such
+ * an intermediary object.
+ *
+ * A notification sent to a task can optionally perform an action, such as
+ * update, overwrite or increment the task's notification value.  In that way
+ * task notifications can be used to send data to a task, or be used as light
+ * weight and fast binary or counting semaphores.
+ *
+ * A notification sent to a task will remain pending until it is cleared by the
+ * task calling xTaskNotifyWait() or ulTaskNotifyTake().  If the task was
+ * already in the Blocked state to wait for a notification when the notification
+ * arrives then the task will automatically be removed from the Blocked state
+ * (unblocked) and the notification cleared.
+ *
+ * A task can use xTaskNotifyWait() to [optionally] block to wait for a
+ * notification to be pending, or ulTaskNotifyTake() to [optionally] block
+ * to wait for its notification value to have a non-zero value.  The task does
+ * not consume any CPU time while it is in the Blocked state.
+ *
+ * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
+ *
+ * @param ulBitsToClearOnEntry Bits that are set in ulBitsToClearOnEntry value
+ * will be cleared in the calling task's notification value before the task
+ * checks to see if any notifications are pending, and optionally blocks if no
+ * notifications are pending.  Setting ulBitsToClearOnEntry to ULONG_MAX (if
+ * limits.h is included) or 0xffffffffUL (if limits.h is not included) will have
+ * the effect of resetting the task's notification value to 0.  Setting
+ * ulBitsToClearOnEntry to 0 will leave the task's notification value unchanged.
+ *
+ * @param ulBitsToClearOnExit If a notification is pending or received before
+ * the calling task exits the xTaskNotifyWait() function then the task's
+ * notification value (see the xTaskNotify() API function) is passed out using
+ * the pulNotificationValue parameter.  Then any bits that are set in
+ * ulBitsToClearOnExit will be cleared in the task's notification value (note
+ * *pulNotificationValue is set before any bits are cleared).  Setting
+ * ulBitsToClearOnExit to ULONG_MAX (if limits.h is included) or 0xffffffffUL
+ * (if limits.h is not included) will have the effect of resetting the task's
+ * notification value to 0 before the function exits.  Setting
+ * ulBitsToClearOnExit to 0 will leave the task's notification value unchanged
+ * when the function exits (in which case the value passed out in
+ * pulNotificationValue will match the task's notification value).
+ *
+ * @param pulNotificationValue Used to pass the task's notification value out
+ * of the function.  Note the value passed out will not be effected by the
+ * clearing of any bits caused by ulBitsToClearOnExit being non-zero.
+ *
+ * @param xTicksToWait The maximum amount of time that the task should wait in
+ * the Blocked state for a notification to be received, should a notification
+ * not already be pending when xTaskNotifyWait() was called.  The task
+ * will not consume any processing time while it is in the Blocked state.  This
+ * is specified in kernel ticks, the macro pdMS_TO_TICSK( value_in_ms ) can be
+ * used to convert a time specified in milliseconds to a time specified in
+ * ticks.
+ *
+ * @return If a notification was received (including notifications that were
+ * already pending when xTaskNotifyWait was called) then pdPASS is
+ * returned.  Otherwise pdFAIL is returned.
+ *
+ * \defgroup xTaskNotifyWait xTaskNotifyWait
+ * \ingroup TaskNotifications
+ */
+BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait );
+
+/**
+ * task. h
+ * <PRE>BaseType_t xTaskNotifyGive( TaskHandle_t xTaskToNotify );</PRE>
+ *
+ * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro
+ * to be available.
+ *
+ * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
+ * "notification value", which is a 32-bit unsigned integer (uint32_t).
+ *
+ * Events can be sent to a task using an intermediary object.  Examples of such
+ * objects are queues, semaphores, mutexes and event groups.  Task notifications
+ * are a method of sending an event directly to a task without the need for such
+ * an intermediary object.
+ *
+ * A notification sent to a task can optionally perform an action, such as
+ * update, overwrite or increment the task's notification value.  In that way
+ * task notifications can be used to send data to a task, or be used as light
+ * weight and fast binary or counting semaphores.
+ *
+ * xTaskNotifyGive() is a helper macro intended for use when task notifications
+ * are used as light weight and faster binary or counting semaphore equivalents.
+ * Actual FreeRTOS semaphores are given using the xSemaphoreGive() API function,
+ * the equivalent action that instead uses a task notification is
+ * xTaskNotifyGive().
+ *
+ * When task notifications are being used as a binary or counting semaphore
+ * equivalent then the task being notified should wait for the notification
+ * using the ulTaskNotificationTake() API function rather than the
+ * xTaskNotifyWait() API function.
+ *
+ * See http://www.FreeRTOS.org/RTOS-task-notifications.html for more details.
+ *
+ * @param xTaskToNotify The handle of the task being notified.  The handle to a
+ * task can be returned from the xTaskCreate() API function used to create the
+ * task, and the handle of the currently running task can be obtained by calling
+ * xTaskGetCurrentTaskHandle().
+ *
+ * @return xTaskNotifyGive() is a macro that calls xTaskNotify() with the
+ * eAction parameter set to eIncrement - so pdPASS is always returned.
+ *
+ * \defgroup xTaskNotifyGive xTaskNotifyGive
+ * \ingroup TaskNotifications
+ */
+#define xTaskNotifyGive( xTaskToNotify ) xTaskNotify( ( xTaskToNotify ), 0, eIncrement );
+
+/**
+ * task. h
+ * <PRE>void vTaskNotifyGiveFromISR( TaskHandle_t xTaskHandle, BaseType_t *pxHigherPriorityTaskWoken );
+ *
+ * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this macro
+ * to be available.
+ *
+ * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
+ * "notification value", which is a 32-bit unsigned integer (uint32_t).
+ *
+ * A version of xTaskNotifyGive() that can be called from an interrupt service
+ * routine (ISR).
+ *
+ * Events can be sent to a task using an intermediary object.  Examples of such
+ * objects are queues, semaphores, mutexes and event groups.  Task notifications
+ * are a method of sending an event directly to a task without the need for such
+ * an intermediary object.
+ *
+ * A notification sent to a task can optionally perform an action, such as
+ * update, overwrite or increment the task's notification value.  In that way
+ * task notifications can be used to send data to a task, or be used as light
+ * weight and fast binary or counting semaphores.
+ *
+ * vTaskNotifyGiveFromISR() is intended for use when task notifications are
+ * used as light weight and faster binary or counting semaphore equivalents.
+ * Actual FreeRTOS semaphores are given from an ISR using the
+ * xSemaphoreGiveFromISR() API function, the equivalent action that instead uses
+ * a task notification is vTaskNotifyGiveFromISR().
+ *
+ * When task notifications are being used as a binary or counting semaphore
+ * equivalent then the task being notified should wait for the notification
+ * using the ulTaskNotificationTake() API function rather than the
+ * xTaskNotifyWait() API function.
+ *
+ * See http://www.FreeRTOS.org/RTOS-task-notifications.html for more details.
+ *
+ * @param xTaskToNotify The handle of the task being notified.  The handle to a
+ * task can be returned from the xTaskCreate() API function used to create the
+ * task, and the handle of the currently running task can be obtained by calling
+ * xTaskGetCurrentTaskHandle().
+ *
+ * @param pxHigherPriorityTaskWoken  vTaskNotifyGiveFromISR() will set
+ * *pxHigherPriorityTaskWoken to pdTRUE if sending the notification caused the
+ * task to which the notification was sent to leave the Blocked state, and the
+ * unblocked task has a priority higher than the currently running task.  If
+ * vTaskNotifyGiveFromISR() sets this value to pdTRUE then a context switch
+ * should be requested before the interrupt is exited.  How a context switch is
+ * requested from an ISR is dependent on the port - see the documentation page
+ * for the port in use.
+ *
+ * \defgroup xTaskNotifyWait xTaskNotifyWait
+ * \ingroup TaskNotifications
+ */
+void vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken );
+
+/**
+ * task. h
+ * <PRE>uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait );</pre>
+ *
+ * configUSE_TASK_NOTIFICATIONS must be undefined or defined as 1 for this
+ * function to be available.
+ *
+ * When configUSE_TASK_NOTIFICATIONS is set to one each task has its own private
+ * "notification value", which is a 32-bit unsigned integer (uint32_t).
+ *
+ * Events can be sent to a task using an intermediary object.  Examples of such
+ * objects are queues, semaphores, mutexes and event groups.  Task notifications
+ * are a method of sending an event directly to a task without the need for such
+ * an intermediary object.
+ *
+ * A notification sent to a task can optionally perform an action, such as
+ * update, overwrite or increment the task's notification value.  In that way
+ * task notifications can be used to send data to a task, or be used as light
+ * weight and fast binary or counting semaphores.
+ *
+ * ulTaskNotifyTake() is intended for use when a task notification is used as a
+ * faster and lighter weight binary or counting semaphore alternative.  Actual
+ * FreeRTOS semaphores are taken using the xSemaphoreTake() API function, the
+ * equivalent action that instead uses a task notification is
+ * ulTaskNotifyTake().
+ *
+ * When a task is using its notification value as a binary or counting semaphore
+ * other tasks should send notifications to it using the xTaskNotifyGive()
+ * macro, or xTaskNotify() function with the eAction parameter set to
+ * eIncrement.
+ *
+ * ulTaskNotifyTake() can either clear the task's notification value to
+ * zero on exit, in which case the notification value acts like a binary
+ * semaphore, or decrement the task's notification value on exit, in which case
+ * the notification value acts like a counting semaphore.
+ *
+ * A task can use ulTaskNotifyTake() to [optionally] block to wait for a
+ * the task's notification value to be non-zero.  The task does not consume any
+ * CPU time while it is in the Blocked state.
+ *
+ * Where as xTaskNotifyWait() will return when a notification is pending,
+ * ulTaskNotifyTake() will return when the task's notification value is
+ * not zero.
+ *
+ * See http://www.FreeRTOS.org/RTOS-task-notifications.html for details.
+ *
+ * @param xClearCountOnExit if xClearCountOnExit is pdFALSE then the task's
+ * notification value is decremented when the function exits.  In this way the
+ * notification value acts like a counting semaphore.  If xClearCountOnExit is
+ * not pdFALSE then the task's notification value is cleared to zero when the
+ * function exits.  In this way the notification value acts like a binary
+ * semaphore.
+ *
+ * @param xTicksToWait The maximum amount of time that the task should wait in
+ * the Blocked state for the task's notification value to be greater than zero,
+ * should the count not already be greater than zero when
+ * ulTaskNotifyTake() was called.  The task will not consume any processing
+ * time while it is in the Blocked state.  This is specified in kernel ticks,
+ * the macro pdMS_TO_TICSK( value_in_ms ) can be used to convert a time
+ * specified in milliseconds to a time specified in ticks.
+ *
+ * @return The task's notification count before it is either cleared to zero or
+ * decremented (see the xClearCountOnExit parameter).
+ *
+ * \defgroup ulTaskNotifyTake ulTaskNotifyTake
+ * \ingroup TaskNotifications
+ */
+uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait );
+
+/*-----------------------------------------------------------
+ * SCHEDULER INTERNALS AVAILABLE FOR PORTING PURPOSES
+ *----------------------------------------------------------*/
+
+/*
+ * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE.  IT IS ONLY
+ * INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS
+ * AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.
+ *
+ * Called from the real time kernel tick (either preemptive or cooperative),
+ * this increments the tick count and checks if any tasks that are blocked
+ * for a finite period required removing from a blocked list and placing on
+ * a ready list.  If a non-zero value is returned then a context switch is
+ * required because either:
+ *   + A task was removed from a blocked list because its timeout had expired,
+ *     or
+ *   + Time slicing is in use and there is a task of equal priority to the
+ *     currently running task.
+ */
+BaseType_t xTaskIncrementTick( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE.  IT IS AN
+ * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.
+ *
+ * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED.
+ *
+ * Removes the calling task from the ready list and places it both
+ * on the list of tasks waiting for a particular event, and the
+ * list of delayed tasks.  The task will be removed from both lists
+ * and replaced on the ready list should either the event occur (and
+ * there be no higher priority tasks waiting on the same event) or
+ * the delay period expires.
+ *
+ * The 'unordered' version replaces the event list item value with the
+ * xItemValue value, and inserts the list item at the end of the list.
+ *
+ * The 'ordered' version uses the existing event list item value (which is the
+ * owning tasks priority) to insert the list item into the event list is task
+ * priority order.
+ *
+ * @param pxEventList The list containing tasks that are blocked waiting
+ * for the event to occur.
+ *
+ * @param xItemValue The item value to use for the event list item when the
+ * event list is not ordered by task priority.
+ *
+ * @param xTicksToWait The maximum amount of time that the task should wait
+ * for the event to occur.  This is specified in kernel ticks,the constant
+ * portTICK_PERIOD_MS can be used to convert kernel ticks into a real time
+ * period.
+ */
+void vTaskPlaceOnEventList( List_t * const pxEventList, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, const TickType_t xItemValue, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+
+/*
+ * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE.  IT IS AN
+ * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.
+ *
+ * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED.
+ *
+ * This function performs nearly the same function as vTaskPlaceOnEventList().
+ * The difference being that this function does not permit tasks to block
+ * indefinitely, whereas vTaskPlaceOnEventList() does.
+ *
+ */
+void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+
+/*
+ * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE.  IT IS AN
+ * INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.
+ *
+ * THIS FUNCTION MUST BE CALLED WITH INTERRUPTS DISABLED.
+ *
+ * Removes a task from both the specified event list and the list of blocked
+ * tasks, and places it on a ready queue.
+ *
+ * xTaskRemoveFromEventList()/xTaskRemoveFromUnorderedEventList() will be called
+ * if either an event occurs to unblock a task, or the block timeout period
+ * expires.
+ *
+ * xTaskRemoveFromEventList() is used when the event list is in task priority
+ * order.  It removes the list item from the head of the event list as that will
+ * have the highest priority owning task of all the tasks on the event list.
+ * xTaskRemoveFromUnorderedEventList() is used when the event list is not
+ * ordered and the event list items hold something other than the owning tasks
+ * priority.  In this case the event list item value is updated to the value
+ * passed in the xItemValue parameter.
+ *
+ * @return pdTRUE if the task being removed has a higher priority than the task
+ * making the call, otherwise pdFALSE.
+ */
+BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList ) PRIVILEGED_FUNCTION;
+BaseType_t xTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem, const TickType_t xItemValue ) PRIVILEGED_FUNCTION;
+
+/*
+ * THIS FUNCTION MUST NOT BE USED FROM APPLICATION CODE.  IT IS ONLY
+ * INTENDED FOR USE WHEN IMPLEMENTING A PORT OF THE SCHEDULER AND IS
+ * AN INTERFACE WHICH IS FOR THE EXCLUSIVE USE OF THE SCHEDULER.
+ *
+ * Sets the pointer to the current TCB to the TCB of the highest priority task
+ * that is ready to run.
+ */
+void vTaskSwitchContext( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * THESE FUNCTIONS MUST NOT BE USED FROM APPLICATION CODE.  THEY ARE USED BY
+ * THE EVENT BITS MODULE.
+ */
+TickType_t uxTaskResetEventItemValue( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * Return the handle of the calling task.
+ */
+TaskHandle_t xTaskGetCurrentTaskHandle( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * Capture the current time status for future reference.
+ */
+void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut ) PRIVILEGED_FUNCTION;
+
+/*
+ * Compare the time status now with that previously captured to see if the
+ * timeout has expired.
+ */
+BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait ) PRIVILEGED_FUNCTION;
+
+/*
+ * Shortcut used by the queue implementation to prevent unnecessary call to
+ * taskYIELD();
+ */
+void vTaskMissedYield( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * Returns the scheduler state as taskSCHEDULER_RUNNING,
+ * taskSCHEDULER_NOT_STARTED or taskSCHEDULER_SUSPENDED.
+ */
+BaseType_t xTaskGetSchedulerState( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * Raises the priority of the mutex holder to that of the calling task should
+ * the mutex holder have a priority less than the calling task.
+ */
+void vTaskPriorityInherit( TaskHandle_t const pxMutexHolder ) PRIVILEGED_FUNCTION;
+
+/*
+ * Set the priority of a task back to its proper priority in the case that it
+ * inherited a higher priority while it was holding a semaphore.
+ */
+BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder ) PRIVILEGED_FUNCTION;
+
+/*
+ * Generic version of the task creation function which is in turn called by the
+ * xTaskCreate() and xTaskCreateRestricted() macros.
+ */
+BaseType_t xTaskGenericCreate( TaskFunction_t pxTaskCode, const char * const pcName, const uint16_t usStackDepth, void * const pvParameters, UBaseType_t uxPriority, TaskHandle_t * const pxCreatedTask, StackType_t * const puxStackBuffer, const MemoryRegion_t * const xRegions ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+
+/*
+ * Get the uxTCBNumber assigned to the task referenced by the xTask parameter.
+ */
+UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+
+/*
+ * Set the uxTaskNumber of the task referenced by the xTask parameter to
+ * uxHandle.
+ */
+void vTaskSetTaskNumber( TaskHandle_t xTask, const UBaseType_t uxHandle ) PRIVILEGED_FUNCTION;
+
+/*
+ * Only available when configUSE_TICKLESS_IDLE is set to 1.
+ * If tickless mode is being used, or a low power mode is implemented, then
+ * the tick interrupt will not execute during idle periods.  When this is the
+ * case, the tick count value maintained by the scheduler needs to be kept up
+ * to date with the actual execution time by being skipped forward by a time
+ * equal to the idle period.
+ */
+void vTaskStepTick( const TickType_t xTicksToJump ) PRIVILEGED_FUNCTION;
+
+/*
+ * Only avilable when configUSE_TICKLESS_IDLE is set to 1.
+ * Provided for use within portSUPPRESS_TICKS_AND_SLEEP() to allow the port
+ * specific sleep function to determine if it is ok to proceed with the sleep,
+ * and if it is ok to proceed, if it is ok to sleep indefinitely.
+ *
+ * This function is necessary because portSUPPRESS_TICKS_AND_SLEEP() is only
+ * called with the scheduler suspended, not from within a critical section.  It
+ * is therefore possible for an interrupt to request a context switch between
+ * portSUPPRESS_TICKS_AND_SLEEP() and the low power mode actually being
+ * entered.  eTaskConfirmSleepModeStatus() should be called from a short
+ * critical section between the timer being stopped and the sleep mode being
+ * entered to ensure it is ok to proceed into the sleep mode.
+ */
+eSleepModeStatus eTaskConfirmSleepModeStatus( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * For internal use only.  Increment the mutex held count when a mutex is
+ * taken and return the handle of the task that has taken the mutex.
+ */
+void *pvTaskIncrementMutexHeldCount( void );
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* INC_TASK_H */
+
+
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/include/timers.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/include/timers.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,1147 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+
+#ifndef TIMERS_H
+#define TIMERS_H
+
+#ifndef INC_FREERTOS_H
+	#error "include FreeRTOS.h must appear in source files before include timers.h"
+#endif
+
+/*lint -e537 This headers are only multiply included if the application code
+happens to also be including task.h. */
+#include "task.h"
+/*lint +e537 */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*-----------------------------------------------------------
+ * MACROS AND DEFINITIONS
+ *----------------------------------------------------------*/
+
+/* IDs for commands that can be sent/received on the timer queue.  These are to
+be used solely through the macros that make up the public software timer API,
+as defined below.  The commands that are sent from interrupts must use the
+highest numbers as tmrFIRST_FROM_ISR_COMMAND is used to determine if the task
+or interrupt version of the queue send function should be used. */
+#define tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR 	( ( BaseType_t ) -2 )
+#define tmrCOMMAND_EXECUTE_CALLBACK				( ( BaseType_t ) -1 )
+#define tmrCOMMAND_START_DONT_TRACE				( ( BaseType_t ) 0 )
+#define tmrCOMMAND_START					    ( ( BaseType_t ) 1 )
+#define tmrCOMMAND_RESET						( ( BaseType_t ) 2 )
+#define tmrCOMMAND_STOP							( ( BaseType_t ) 3 )
+#define tmrCOMMAND_CHANGE_PERIOD				( ( BaseType_t ) 4 )
+#define tmrCOMMAND_DELETE						( ( BaseType_t ) 5 )
+
+#define tmrFIRST_FROM_ISR_COMMAND				( ( BaseType_t ) 6 )
+#define tmrCOMMAND_START_FROM_ISR				( ( BaseType_t ) 6 )
+#define tmrCOMMAND_RESET_FROM_ISR				( ( BaseType_t ) 7 )
+#define tmrCOMMAND_STOP_FROM_ISR				( ( BaseType_t ) 8 )
+#define tmrCOMMAND_CHANGE_PERIOD_FROM_ISR		( ( BaseType_t ) 9 )
+
+
+/**
+ * Type by which software timers are referenced.  For example, a call to
+ * xTimerCreate() returns an TimerHandle_t variable that can then be used to
+ * reference the subject timer in calls to other software timer API functions
+ * (for example, xTimerStart(), xTimerReset(), etc.).
+ */
+typedef void * TimerHandle_t;
+
+/*
+ * Defines the prototype to which timer callback functions must conform.
+ */
+typedef void (*TimerCallbackFunction_t)( TimerHandle_t xTimer );
+
+/*
+ * Defines the prototype to which functions used with the
+ * xTimerPendFunctionCallFromISR() function must conform.
+ */
+typedef void (*PendedFunction_t)( void *, uint32_t );
+
+/**
+ * TimerHandle_t xTimerCreate( 	const char * const pcTimerName,
+ * 								TickType_t xTimerPeriodInTicks,
+ * 								UBaseType_t uxAutoReload,
+ * 								void * pvTimerID,
+ * 								TimerCallbackFunction_t pxCallbackFunction );
+ *
+ * Creates a new software timer instance.  This allocates the storage required
+ * by the new timer, initialises the new timers internal state, and returns a
+ * handle by which the new timer can be referenced.
+ *
+ * Timers are created in the dormant state.  The xTimerStart(), xTimerReset(),
+ * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and
+ * xTimerChangePeriodFromISR() API functions can all be used to transition a
+ * timer into the active state.
+ *
+ * @param pcTimerName A text name that is assigned to the timer.  This is done
+ * purely to assist debugging.  The kernel itself only ever references a timer
+ * by its handle, and never by its name.
+ *
+ * @param xTimerPeriodInTicks The timer period.  The time is defined in tick
+ * periods so the constant portTICK_PERIOD_MS can be used to convert a time that
+ * has been specified in milliseconds.  For example, if the timer must expire
+ * after 100 ticks, then xTimerPeriodInTicks should be set to 100.
+ * Alternatively, if the timer must expire after 500ms, then xPeriod can be set
+ * to ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than or
+ * equal to 1000.
+ *
+ * @param uxAutoReload If uxAutoReload is set to pdTRUE then the timer will
+ * expire repeatedly with a frequency set by the xTimerPeriodInTicks parameter.
+ * If uxAutoReload is set to pdFALSE then the timer will be a one-shot timer and
+ * enter the dormant state after it expires.
+ *
+ * @param pvTimerID An identifier that is assigned to the timer being created.
+ * Typically this would be used in the timer callback function to identify which
+ * timer expired when the same callback function is assigned to more than one
+ * timer.
+ *
+ * @param pxCallbackFunction The function to call when the timer expires.
+ * Callback functions must have the prototype defined by TimerCallbackFunction_t,
+ * which is	"void vCallbackFunction( TimerHandle_t xTimer );".
+ *
+ * @return If the timer is successfully created then a handle to the newly
+ * created timer is returned.  If the timer cannot be created (because either
+ * there is insufficient FreeRTOS heap remaining to allocate the timer
+ * structures, or the timer period was set to 0) then NULL is returned.
+ *
+ * Example usage:
+ * @verbatim
+ * #define NUM_TIMERS 5
+ *
+ * // An array to hold handles to the created timers.
+ * TimerHandle_t xTimers[ NUM_TIMERS ];
+ *
+ * // An array to hold a count of the number of times each timer expires.
+ * int32_t lExpireCounters[ NUM_TIMERS ] = { 0 };
+ *
+ * // Define a callback function that will be used by multiple timer instances.
+ * // The callback function does nothing but count the number of times the
+ * // associated timer expires, and stop the timer once the timer has expired
+ * // 10 times.
+ * void vTimerCallback( TimerHandle_t pxTimer )
+ * {
+ * int32_t lArrayIndex;
+ * const int32_t xMaxExpiryCountBeforeStopping = 10;
+ *
+ * 	   // Optionally do something if the pxTimer parameter is NULL.
+ * 	   configASSERT( pxTimer );
+ *
+ *     // Which timer expired?
+ *     lArrayIndex = ( int32_t ) pvTimerGetTimerID( pxTimer );
+ *
+ *     // Increment the number of times that pxTimer has expired.
+ *     lExpireCounters[ lArrayIndex ] += 1;
+ *
+ *     // If the timer has expired 10 times then stop it from running.
+ *     if( lExpireCounters[ lArrayIndex ] == xMaxExpiryCountBeforeStopping )
+ *     {
+ *         // Do not use a block time if calling a timer API function from a
+ *         // timer callback function, as doing so could cause a deadlock!
+ *         xTimerStop( pxTimer, 0 );
+ *     }
+ * }
+ *
+ * void main( void )
+ * {
+ * int32_t x;
+ *
+ *     // Create then start some timers.  Starting the timers before the scheduler
+ *     // has been started means the timers will start running immediately that
+ *     // the scheduler starts.
+ *     for( x = 0; x < NUM_TIMERS; x++ )
+ *     {
+ *         xTimers[ x ] = xTimerCreate(    "Timer",       // Just a text name, not used by the kernel.
+ *                                         ( 100 * x ),   // The timer period in ticks.
+ *                                         pdTRUE,        // The timers will auto-reload themselves when they expire.
+ *                                         ( void * ) x,  // Assign each timer a unique id equal to its array index.
+ *                                         vTimerCallback // Each timer calls the same callback when it expires.
+ *                                     );
+ *
+ *         if( xTimers[ x ] == NULL )
+ *         {
+ *             // The timer was not created.
+ *         }
+ *         else
+ *         {
+ *             // Start the timer.  No block time is specified, and even if one was
+ *             // it would be ignored because the scheduler has not yet been
+ *             // started.
+ *             if( xTimerStart( xTimers[ x ], 0 ) != pdPASS )
+ *             {
+ *                 // The timer could not be set into the Active state.
+ *             }
+ *         }
+ *     }
+ *
+ *     // ...
+ *     // Create tasks here.
+ *     // ...
+ *
+ *     // Starting the scheduler will start the timers running as they have already
+ *     // been set into the active state.
+ *     xTaskStartScheduler();
+ *
+ *     // Should not reach here.
+ *     for( ;; );
+ * }
+ * @endverbatim
+ */
+TimerHandle_t xTimerCreate( const char * const pcTimerName, const TickType_t xTimerPeriodInTicks, const UBaseType_t uxAutoReload, void * const pvTimerID, TimerCallbackFunction_t pxCallbackFunction ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+
+/**
+ * void *pvTimerGetTimerID( TimerHandle_t xTimer );
+ *
+ * Returns the ID assigned to the timer.
+ *
+ * IDs are assigned to timers using the pvTimerID parameter of the call to
+ * xTimerCreated() that was used to create the timer, and by calling the
+ * vTimerSetTimerID() API function.
+ *
+ * If the same callback function is assigned to multiple timers then the timer
+ * ID can be used as time specific (timer local) storage.
+ *
+ * @param xTimer The timer being queried.
+ *
+ * @return The ID assigned to the timer being queried.
+ *
+ * Example usage:
+ *
+ * See the xTimerCreate() API function example usage scenario.
+ */
+void *pvTimerGetTimerID( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION;
+
+/**
+ * void vTimerSetTimerID( TimerHandle_t xTimer, void *pvNewID );
+ *
+ * Sets the ID assigned to the timer.
+ *
+ * IDs are assigned to timers using the pvTimerID parameter of the call to
+ * xTimerCreated() that was used to create the timer.
+ *
+ * If the same callback function is assigned to multiple timers then the timer
+ * ID can be used as time specific (timer local) storage.
+ *
+ * @param xTimer The timer being updated.
+ *
+ * @param pvNewID The ID to assign to the timer.
+ *
+ * Example usage:
+ *
+ * See the xTimerCreate() API function example usage scenario.
+ */
+void vTimerSetTimerID( const TimerHandle_t xTimer, void *pvNewID ) PRIVILEGED_FUNCTION;
+
+/**
+ * BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer );
+ *
+ * Queries a timer to see if it is active or dormant.
+ *
+ * A timer will be dormant if:
+ *     1) It has been created but not started, or
+ *     2) It is an expired one-shot timer that has not been restarted.
+ *
+ * Timers are created in the dormant state.  The xTimerStart(), xTimerReset(),
+ * xTimerStartFromISR(), xTimerResetFromISR(), xTimerChangePeriod() and
+ * xTimerChangePeriodFromISR() API functions can all be used to transition a timer into the
+ * active state.
+ *
+ * @param xTimer The timer being queried.
+ *
+ * @return pdFALSE will be returned if the timer is dormant.  A value other than
+ * pdFALSE will be returned if the timer is active.
+ *
+ * Example usage:
+ * @verbatim
+ * // This function assumes xTimer has already been created.
+ * void vAFunction( TimerHandle_t xTimer )
+ * {
+ *     if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )"
+ *     {
+ *         // xTimer is active, do something.
+ *     }
+ *     else
+ *     {
+ *         // xTimer is not active, do something else.
+ *     }
+ * }
+ * @endverbatim
+ */
+BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer ) PRIVILEGED_FUNCTION;
+
+/**
+ * TaskHandle_t xTimerGetTimerDaemonTaskHandle( void );
+ *
+ * xTimerGetTimerDaemonTaskHandle() is only available if
+ * INCLUDE_xTimerGetTimerDaemonTaskHandle is set to 1 in FreeRTOSConfig.h.
+ *
+ * Simply returns the handle of the timer service/daemon task.  It it not valid
+ * to call xTimerGetTimerDaemonTaskHandle() before the scheduler has been started.
+ */
+TaskHandle_t xTimerGetTimerDaemonTaskHandle( void );
+
+/**
+ * BaseType_t xTimerStart( TimerHandle_t xTimer, TickType_t xTicksToWait );
+ *
+ * Timer functionality is provided by a timer service/daemon task.  Many of the
+ * public FreeRTOS timer API functions send commands to the timer service task
+ * through a queue called the timer command queue.  The timer command queue is
+ * private to the kernel itself and is not directly accessible to application
+ * code.  The length of the timer command queue is set by the
+ * configTIMER_QUEUE_LENGTH configuration constant.
+ *
+ * xTimerStart() starts a timer that was previously created using the
+ * xTimerCreate() API function.  If the timer had already been started and was
+ * already in the active state, then xTimerStart() has equivalent functionality
+ * to the xTimerReset() API function.
+ *
+ * Starting a timer ensures the timer is in the active state.  If the timer
+ * is not stopped, deleted, or reset in the mean time, the callback function
+ * associated with the timer will get called 'n' ticks after xTimerStart() was
+ * called, where 'n' is the timers defined period.
+ *
+ * It is valid to call xTimerStart() before the scheduler has been started, but
+ * when this is done the timer will not actually start until the scheduler is
+ * started, and the timers expiry time will be relative to when the scheduler is
+ * started, not relative to when xTimerStart() was called.
+ *
+ * The configUSE_TIMERS configuration constant must be set to 1 for xTimerStart()
+ * to be available.
+ *
+ * @param xTimer The handle of the timer being started/restarted.
+ *
+ * @param xTicksToWait Specifies the time, in ticks, that the calling task should
+ * be held in the Blocked state to wait for the start command to be successfully
+ * sent to the timer command queue, should the queue already be full when
+ * xTimerStart() was called.  xTicksToWait is ignored if xTimerStart() is called
+ * before the scheduler is started.
+ *
+ * @return pdFAIL will be returned if the start command could not be sent to
+ * the timer command queue even after xTicksToWait ticks had passed.  pdPASS will
+ * be returned if the command was successfully sent to the timer command queue.
+ * When the command is actually processed will depend on the priority of the
+ * timer service/daemon task relative to other tasks in the system, although the
+ * timers expiry time is relative to when xTimerStart() is actually called.  The
+ * timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY
+ * configuration constant.
+ *
+ * Example usage:
+ *
+ * See the xTimerCreate() API function example usage scenario.
+ *
+ */
+#define xTimerStart( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START, ( xTaskGetTickCount() ), NULL, ( xTicksToWait ) )
+
+/**
+ * BaseType_t xTimerStop( TimerHandle_t xTimer, TickType_t xTicksToWait );
+ *
+ * Timer functionality is provided by a timer service/daemon task.  Many of the
+ * public FreeRTOS timer API functions send commands to the timer service task
+ * through a queue called the timer command queue.  The timer command queue is
+ * private to the kernel itself and is not directly accessible to application
+ * code.  The length of the timer command queue is set by the
+ * configTIMER_QUEUE_LENGTH configuration constant.
+ *
+ * xTimerStop() stops a timer that was previously started using either of the
+ * The xTimerStart(), xTimerReset(), xTimerStartFromISR(), xTimerResetFromISR(),
+ * xTimerChangePeriod() or xTimerChangePeriodFromISR() API functions.
+ *
+ * Stopping a timer ensures the timer is not in the active state.
+ *
+ * The configUSE_TIMERS configuration constant must be set to 1 for xTimerStop()
+ * to be available.
+ *
+ * @param xTimer The handle of the timer being stopped.
+ *
+ * @param xTicksToWait Specifies the time, in ticks, that the calling task should
+ * be held in the Blocked state to wait for the stop command to be successfully
+ * sent to the timer command queue, should the queue already be full when
+ * xTimerStop() was called.  xTicksToWait is ignored if xTimerStop() is called
+ * before the scheduler is started.
+ *
+ * @return pdFAIL will be returned if the stop command could not be sent to
+ * the timer command queue even after xTicksToWait ticks had passed.  pdPASS will
+ * be returned if the command was successfully sent to the timer command queue.
+ * When the command is actually processed will depend on the priority of the
+ * timer service/daemon task relative to other tasks in the system.  The timer
+ * service/daemon task priority is set by the configTIMER_TASK_PRIORITY
+ * configuration constant.
+ *
+ * Example usage:
+ *
+ * See the xTimerCreate() API function example usage scenario.
+ *
+ */
+#define xTimerStop( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_STOP, 0U, NULL, ( xTicksToWait ) )
+
+/**
+ * BaseType_t xTimerChangePeriod( 	TimerHandle_t xTimer,
+ *										TickType_t xNewPeriod,
+ *										TickType_t xTicksToWait );
+ *
+ * Timer functionality is provided by a timer service/daemon task.  Many of the
+ * public FreeRTOS timer API functions send commands to the timer service task
+ * through a queue called the timer command queue.  The timer command queue is
+ * private to the kernel itself and is not directly accessible to application
+ * code.  The length of the timer command queue is set by the
+ * configTIMER_QUEUE_LENGTH configuration constant.
+ *
+ * xTimerChangePeriod() changes the period of a timer that was previously
+ * created using the xTimerCreate() API function.
+ *
+ * xTimerChangePeriod() can be called to change the period of an active or
+ * dormant state timer.
+ *
+ * The configUSE_TIMERS configuration constant must be set to 1 for
+ * xTimerChangePeriod() to be available.
+ *
+ * @param xTimer The handle of the timer that is having its period changed.
+ *
+ * @param xNewPeriod The new period for xTimer. Timer periods are specified in
+ * tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time
+ * that has been specified in milliseconds.  For example, if the timer must
+ * expire after 100 ticks, then xNewPeriod should be set to 100.  Alternatively,
+ * if the timer must expire after 500ms, then xNewPeriod can be set to
+ * ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than
+ * or equal to 1000.
+ *
+ * @param xTicksToWait Specifies the time, in ticks, that the calling task should
+ * be held in the Blocked state to wait for the change period command to be
+ * successfully sent to the timer command queue, should the queue already be
+ * full when xTimerChangePeriod() was called.  xTicksToWait is ignored if
+ * xTimerChangePeriod() is called before the scheduler is started.
+ *
+ * @return pdFAIL will be returned if the change period command could not be
+ * sent to the timer command queue even after xTicksToWait ticks had passed.
+ * pdPASS will be returned if the command was successfully sent to the timer
+ * command queue.  When the command is actually processed will depend on the
+ * priority of the timer service/daemon task relative to other tasks in the
+ * system.  The timer service/daemon task priority is set by the
+ * configTIMER_TASK_PRIORITY configuration constant.
+ *
+ * Example usage:
+ * @verbatim
+ * // This function assumes xTimer has already been created.  If the timer
+ * // referenced by xTimer is already active when it is called, then the timer
+ * // is deleted.  If the timer referenced by xTimer is not active when it is
+ * // called, then the period of the timer is set to 500ms and the timer is
+ * // started.
+ * void vAFunction( TimerHandle_t xTimer )
+ * {
+ *     if( xTimerIsTimerActive( xTimer ) != pdFALSE ) // or more simply and equivalently "if( xTimerIsTimerActive( xTimer ) )"
+ *     {
+ *         // xTimer is already active - delete it.
+ *         xTimerDelete( xTimer );
+ *     }
+ *     else
+ *     {
+ *         // xTimer is not active, change its period to 500ms.  This will also
+ *         // cause the timer to start.  Block for a maximum of 100 ticks if the
+ *         // change period command cannot immediately be sent to the timer
+ *         // command queue.
+ *         if( xTimerChangePeriod( xTimer, 500 / portTICK_PERIOD_MS, 100 ) == pdPASS )
+ *         {
+ *             // The command was successfully sent.
+ *         }
+ *         else
+ *         {
+ *             // The command could not be sent, even after waiting for 100 ticks
+ *             // to pass.  Take appropriate action here.
+ *         }
+ *     }
+ * }
+ * @endverbatim
+ */
+ #define xTimerChangePeriod( xTimer, xNewPeriod, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_CHANGE_PERIOD, ( xNewPeriod ), NULL, ( xTicksToWait ) )
+
+/**
+ * BaseType_t xTimerDelete( TimerHandle_t xTimer, TickType_t xTicksToWait );
+ *
+ * Timer functionality is provided by a timer service/daemon task.  Many of the
+ * public FreeRTOS timer API functions send commands to the timer service task
+ * through a queue called the timer command queue.  The timer command queue is
+ * private to the kernel itself and is not directly accessible to application
+ * code.  The length of the timer command queue is set by the
+ * configTIMER_QUEUE_LENGTH configuration constant.
+ *
+ * xTimerDelete() deletes a timer that was previously created using the
+ * xTimerCreate() API function.
+ *
+ * The configUSE_TIMERS configuration constant must be set to 1 for
+ * xTimerDelete() to be available.
+ *
+ * @param xTimer The handle of the timer being deleted.
+ *
+ * @param xTicksToWait Specifies the time, in ticks, that the calling task should
+ * be held in the Blocked state to wait for the delete command to be
+ * successfully sent to the timer command queue, should the queue already be
+ * full when xTimerDelete() was called.  xTicksToWait is ignored if xTimerDelete()
+ * is called before the scheduler is started.
+ *
+ * @return pdFAIL will be returned if the delete command could not be sent to
+ * the timer command queue even after xTicksToWait ticks had passed.  pdPASS will
+ * be returned if the command was successfully sent to the timer command queue.
+ * When the command is actually processed will depend on the priority of the
+ * timer service/daemon task relative to other tasks in the system.  The timer
+ * service/daemon task priority is set by the configTIMER_TASK_PRIORITY
+ * configuration constant.
+ *
+ * Example usage:
+ *
+ * See the xTimerChangePeriod() API function example usage scenario.
+ */
+#define xTimerDelete( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_DELETE, 0U, NULL, ( xTicksToWait ) )
+
+/**
+ * BaseType_t xTimerReset( TimerHandle_t xTimer, TickType_t xTicksToWait );
+ *
+ * Timer functionality is provided by a timer service/daemon task.  Many of the
+ * public FreeRTOS timer API functions send commands to the timer service task
+ * through a queue called the timer command queue.  The timer command queue is
+ * private to the kernel itself and is not directly accessible to application
+ * code.  The length of the timer command queue is set by the
+ * configTIMER_QUEUE_LENGTH configuration constant.
+ *
+ * xTimerReset() re-starts a timer that was previously created using the
+ * xTimerCreate() API function.  If the timer had already been started and was
+ * already in the active state, then xTimerReset() will cause the timer to
+ * re-evaluate its expiry time so that it is relative to when xTimerReset() was
+ * called.  If the timer was in the dormant state then xTimerReset() has
+ * equivalent functionality to the xTimerStart() API function.
+ *
+ * Resetting a timer ensures the timer is in the active state.  If the timer
+ * is not stopped, deleted, or reset in the mean time, the callback function
+ * associated with the timer will get called 'n' ticks after xTimerReset() was
+ * called, where 'n' is the timers defined period.
+ *
+ * It is valid to call xTimerReset() before the scheduler has been started, but
+ * when this is done the timer will not actually start until the scheduler is
+ * started, and the timers expiry time will be relative to when the scheduler is
+ * started, not relative to when xTimerReset() was called.
+ *
+ * The configUSE_TIMERS configuration constant must be set to 1 for xTimerReset()
+ * to be available.
+ *
+ * @param xTimer The handle of the timer being reset/started/restarted.
+ *
+ * @param xTicksToWait Specifies the time, in ticks, that the calling task should
+ * be held in the Blocked state to wait for the reset command to be successfully
+ * sent to the timer command queue, should the queue already be full when
+ * xTimerReset() was called.  xTicksToWait is ignored if xTimerReset() is called
+ * before the scheduler is started.
+ *
+ * @return pdFAIL will be returned if the reset command could not be sent to
+ * the timer command queue even after xTicksToWait ticks had passed.  pdPASS will
+ * be returned if the command was successfully sent to the timer command queue.
+ * When the command is actually processed will depend on the priority of the
+ * timer service/daemon task relative to other tasks in the system, although the
+ * timers expiry time is relative to when xTimerStart() is actually called.  The
+ * timer service/daemon task priority is set by the configTIMER_TASK_PRIORITY
+ * configuration constant.
+ *
+ * Example usage:
+ * @verbatim
+ * // When a key is pressed, an LCD back-light is switched on.  If 5 seconds pass
+ * // without a key being pressed, then the LCD back-light is switched off.  In
+ * // this case, the timer is a one-shot timer.
+ *
+ * TimerHandle_t xBacklightTimer = NULL;
+ *
+ * // The callback function assigned to the one-shot timer.  In this case the
+ * // parameter is not used.
+ * void vBacklightTimerCallback( TimerHandle_t pxTimer )
+ * {
+ *     // The timer expired, therefore 5 seconds must have passed since a key
+ *     // was pressed.  Switch off the LCD back-light.
+ *     vSetBacklightState( BACKLIGHT_OFF );
+ * }
+ *
+ * // The key press event handler.
+ * void vKeyPressEventHandler( char cKey )
+ * {
+ *     // Ensure the LCD back-light is on, then reset the timer that is
+ *     // responsible for turning the back-light off after 5 seconds of
+ *     // key inactivity.  Wait 10 ticks for the command to be successfully sent
+ *     // if it cannot be sent immediately.
+ *     vSetBacklightState( BACKLIGHT_ON );
+ *     if( xTimerReset( xBacklightTimer, 100 ) != pdPASS )
+ *     {
+ *         // The reset command was not executed successfully.  Take appropriate
+ *         // action here.
+ *     }
+ *
+ *     // Perform the rest of the key processing here.
+ * }
+ *
+ * void main( void )
+ * {
+ * int32_t x;
+ *
+ *     // Create then start the one-shot timer that is responsible for turning
+ *     // the back-light off if no keys are pressed within a 5 second period.
+ *     xBacklightTimer = xTimerCreate( "BacklightTimer",           // Just a text name, not used by the kernel.
+ *                                     ( 5000 / portTICK_PERIOD_MS), // The timer period in ticks.
+ *                                     pdFALSE,                    // The timer is a one-shot timer.
+ *                                     0,                          // The id is not used by the callback so can take any value.
+ *                                     vBacklightTimerCallback     // The callback function that switches the LCD back-light off.
+ *                                   );
+ *
+ *     if( xBacklightTimer == NULL )
+ *     {
+ *         // The timer was not created.
+ *     }
+ *     else
+ *     {
+ *         // Start the timer.  No block time is specified, and even if one was
+ *         // it would be ignored because the scheduler has not yet been
+ *         // started.
+ *         if( xTimerStart( xBacklightTimer, 0 ) != pdPASS )
+ *         {
+ *             // The timer could not be set into the Active state.
+ *         }
+ *     }
+ *
+ *     // ...
+ *     // Create tasks here.
+ *     // ...
+ *
+ *     // Starting the scheduler will start the timer running as it has already
+ *     // been set into the active state.
+ *     xTaskStartScheduler();
+ *
+ *     // Should not reach here.
+ *     for( ;; );
+ * }
+ * @endverbatim
+ */
+#define xTimerReset( xTimer, xTicksToWait ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_RESET, ( xTaskGetTickCount() ), NULL, ( xTicksToWait ) )
+
+/**
+ * BaseType_t xTimerStartFromISR( 	TimerHandle_t xTimer,
+ *									BaseType_t *pxHigherPriorityTaskWoken );
+ *
+ * A version of xTimerStart() that can be called from an interrupt service
+ * routine.
+ *
+ * @param xTimer The handle of the timer being started/restarted.
+ *
+ * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most
+ * of its time in the Blocked state, waiting for messages to arrive on the timer
+ * command queue.  Calling xTimerStartFromISR() writes a message to the timer
+ * command queue, so has the potential to transition the timer service/daemon
+ * task out of the Blocked state.  If calling xTimerStartFromISR() causes the
+ * timer service/daemon task to leave the Blocked state, and the timer service/
+ * daemon task has a priority equal to or greater than the currently executing
+ * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will
+ * get set to pdTRUE internally within the xTimerStartFromISR() function.  If
+ * xTimerStartFromISR() sets this value to pdTRUE then a context switch should
+ * be performed before the interrupt exits.
+ *
+ * @return pdFAIL will be returned if the start command could not be sent to
+ * the timer command queue.  pdPASS will be returned if the command was
+ * successfully sent to the timer command queue.  When the command is actually
+ * processed will depend on the priority of the timer service/daemon task
+ * relative to other tasks in the system, although the timers expiry time is
+ * relative to when xTimerStartFromISR() is actually called.  The timer
+ * service/daemon task priority is set by the configTIMER_TASK_PRIORITY
+ * configuration constant.
+ *
+ * Example usage:
+ * @verbatim
+ * // This scenario assumes xBacklightTimer has already been created.  When a
+ * // key is pressed, an LCD back-light is switched on.  If 5 seconds pass
+ * // without a key being pressed, then the LCD back-light is switched off.  In
+ * // this case, the timer is a one-shot timer, and unlike the example given for
+ * // the xTimerReset() function, the key press event handler is an interrupt
+ * // service routine.
+ *
+ * // The callback function assigned to the one-shot timer.  In this case the
+ * // parameter is not used.
+ * void vBacklightTimerCallback( TimerHandle_t pxTimer )
+ * {
+ *     // The timer expired, therefore 5 seconds must have passed since a key
+ *     // was pressed.  Switch off the LCD back-light.
+ *     vSetBacklightState( BACKLIGHT_OFF );
+ * }
+ *
+ * // The key press interrupt service routine.
+ * void vKeyPressEventInterruptHandler( void )
+ * {
+ * BaseType_t xHigherPriorityTaskWoken = pdFALSE;
+ *
+ *     // Ensure the LCD back-light is on, then restart the timer that is
+ *     // responsible for turning the back-light off after 5 seconds of
+ *     // key inactivity.  This is an interrupt service routine so can only
+ *     // call FreeRTOS API functions that end in "FromISR".
+ *     vSetBacklightState( BACKLIGHT_ON );
+ *
+ *     // xTimerStartFromISR() or xTimerResetFromISR() could be called here
+ *     // as both cause the timer to re-calculate its expiry time.
+ *     // xHigherPriorityTaskWoken was initialised to pdFALSE when it was
+ *     // declared (in this function).
+ *     if( xTimerStartFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS )
+ *     {
+ *         // The start command was not executed successfully.  Take appropriate
+ *         // action here.
+ *     }
+ *
+ *     // Perform the rest of the key processing here.
+ *
+ *     // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch
+ *     // should be performed.  The syntax required to perform a context switch
+ *     // from inside an ISR varies from port to port, and from compiler to
+ *     // compiler.  Inspect the demos for the port you are using to find the
+ *     // actual syntax required.
+ *     if( xHigherPriorityTaskWoken != pdFALSE )
+ *     {
+ *         // Call the interrupt safe yield function here (actual function
+ *         // depends on the FreeRTOS port being used).
+ *     }
+ * }
+ * @endverbatim
+ */
+#define xTimerStartFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_START_FROM_ISR, ( xTaskGetTickCountFromISR() ), ( pxHigherPriorityTaskWoken ), 0U )
+
+/**
+ * BaseType_t xTimerStopFromISR( 	TimerHandle_t xTimer,
+ *									BaseType_t *pxHigherPriorityTaskWoken );
+ *
+ * A version of xTimerStop() that can be called from an interrupt service
+ * routine.
+ *
+ * @param xTimer The handle of the timer being stopped.
+ *
+ * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most
+ * of its time in the Blocked state, waiting for messages to arrive on the timer
+ * command queue.  Calling xTimerStopFromISR() writes a message to the timer
+ * command queue, so has the potential to transition the timer service/daemon
+ * task out of the Blocked state.  If calling xTimerStopFromISR() causes the
+ * timer service/daemon task to leave the Blocked state, and the timer service/
+ * daemon task has a priority equal to or greater than the currently executing
+ * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will
+ * get set to pdTRUE internally within the xTimerStopFromISR() function.  If
+ * xTimerStopFromISR() sets this value to pdTRUE then a context switch should
+ * be performed before the interrupt exits.
+ *
+ * @return pdFAIL will be returned if the stop command could not be sent to
+ * the timer command queue.  pdPASS will be returned if the command was
+ * successfully sent to the timer command queue.  When the command is actually
+ * processed will depend on the priority of the timer service/daemon task
+ * relative to other tasks in the system.  The timer service/daemon task
+ * priority is set by the configTIMER_TASK_PRIORITY configuration constant.
+ *
+ * Example usage:
+ * @verbatim
+ * // This scenario assumes xTimer has already been created and started.  When
+ * // an interrupt occurs, the timer should be simply stopped.
+ *
+ * // The interrupt service routine that stops the timer.
+ * void vAnExampleInterruptServiceRoutine( void )
+ * {
+ * BaseType_t xHigherPriorityTaskWoken = pdFALSE;
+ *
+ *     // The interrupt has occurred - simply stop the timer.
+ *     // xHigherPriorityTaskWoken was set to pdFALSE where it was defined
+ *     // (within this function).  As this is an interrupt service routine, only
+ *     // FreeRTOS API functions that end in "FromISR" can be used.
+ *     if( xTimerStopFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS )
+ *     {
+ *         // The stop command was not executed successfully.  Take appropriate
+ *         // action here.
+ *     }
+ *
+ *     // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch
+ *     // should be performed.  The syntax required to perform a context switch
+ *     // from inside an ISR varies from port to port, and from compiler to
+ *     // compiler.  Inspect the demos for the port you are using to find the
+ *     // actual syntax required.
+ *     if( xHigherPriorityTaskWoken != pdFALSE )
+ *     {
+ *         // Call the interrupt safe yield function here (actual function
+ *         // depends on the FreeRTOS port being used).
+ *     }
+ * }
+ * @endverbatim
+ */
+#define xTimerStopFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_STOP_FROM_ISR, 0, ( pxHigherPriorityTaskWoken ), 0U )
+
+/**
+ * BaseType_t xTimerChangePeriodFromISR( TimerHandle_t xTimer,
+ *										 TickType_t xNewPeriod,
+ *										 BaseType_t *pxHigherPriorityTaskWoken );
+ *
+ * A version of xTimerChangePeriod() that can be called from an interrupt
+ * service routine.
+ *
+ * @param xTimer The handle of the timer that is having its period changed.
+ *
+ * @param xNewPeriod The new period for xTimer. Timer periods are specified in
+ * tick periods, so the constant portTICK_PERIOD_MS can be used to convert a time
+ * that has been specified in milliseconds.  For example, if the timer must
+ * expire after 100 ticks, then xNewPeriod should be set to 100.  Alternatively,
+ * if the timer must expire after 500ms, then xNewPeriod can be set to
+ * ( 500 / portTICK_PERIOD_MS ) provided configTICK_RATE_HZ is less than
+ * or equal to 1000.
+ *
+ * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most
+ * of its time in the Blocked state, waiting for messages to arrive on the timer
+ * command queue.  Calling xTimerChangePeriodFromISR() writes a message to the
+ * timer command queue, so has the potential to transition the timer service/
+ * daemon task out of the Blocked state.  If calling xTimerChangePeriodFromISR()
+ * causes the timer service/daemon task to leave the Blocked state, and the
+ * timer service/daemon task has a priority equal to or greater than the
+ * currently executing task (the task that was interrupted), then
+ * *pxHigherPriorityTaskWoken will get set to pdTRUE internally within the
+ * xTimerChangePeriodFromISR() function.  If xTimerChangePeriodFromISR() sets
+ * this value to pdTRUE then a context switch should be performed before the
+ * interrupt exits.
+ *
+ * @return pdFAIL will be returned if the command to change the timers period
+ * could not be sent to the timer command queue.  pdPASS will be returned if the
+ * command was successfully sent to the timer command queue.  When the command
+ * is actually processed will depend on the priority of the timer service/daemon
+ * task relative to other tasks in the system.  The timer service/daemon task
+ * priority is set by the configTIMER_TASK_PRIORITY configuration constant.
+ *
+ * Example usage:
+ * @verbatim
+ * // This scenario assumes xTimer has already been created and started.  When
+ * // an interrupt occurs, the period of xTimer should be changed to 500ms.
+ *
+ * // The interrupt service routine that changes the period of xTimer.
+ * void vAnExampleInterruptServiceRoutine( void )
+ * {
+ * BaseType_t xHigherPriorityTaskWoken = pdFALSE;
+ *
+ *     // The interrupt has occurred - change the period of xTimer to 500ms.
+ *     // xHigherPriorityTaskWoken was set to pdFALSE where it was defined
+ *     // (within this function).  As this is an interrupt service routine, only
+ *     // FreeRTOS API functions that end in "FromISR" can be used.
+ *     if( xTimerChangePeriodFromISR( xTimer, &xHigherPriorityTaskWoken ) != pdPASS )
+ *     {
+ *         // The command to change the timers period was not executed
+ *         // successfully.  Take appropriate action here.
+ *     }
+ *
+ *     // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch
+ *     // should be performed.  The syntax required to perform a context switch
+ *     // from inside an ISR varies from port to port, and from compiler to
+ *     // compiler.  Inspect the demos for the port you are using to find the
+ *     // actual syntax required.
+ *     if( xHigherPriorityTaskWoken != pdFALSE )
+ *     {
+ *         // Call the interrupt safe yield function here (actual function
+ *         // depends on the FreeRTOS port being used).
+ *     }
+ * }
+ * @endverbatim
+ */
+#define xTimerChangePeriodFromISR( xTimer, xNewPeriod, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_CHANGE_PERIOD_FROM_ISR, ( xNewPeriod ), ( pxHigherPriorityTaskWoken ), 0U )
+
+/**
+ * BaseType_t xTimerResetFromISR( 	TimerHandle_t xTimer,
+ *									BaseType_t *pxHigherPriorityTaskWoken );
+ *
+ * A version of xTimerReset() that can be called from an interrupt service
+ * routine.
+ *
+ * @param xTimer The handle of the timer that is to be started, reset, or
+ * restarted.
+ *
+ * @param pxHigherPriorityTaskWoken The timer service/daemon task spends most
+ * of its time in the Blocked state, waiting for messages to arrive on the timer
+ * command queue.  Calling xTimerResetFromISR() writes a message to the timer
+ * command queue, so has the potential to transition the timer service/daemon
+ * task out of the Blocked state.  If calling xTimerResetFromISR() causes the
+ * timer service/daemon task to leave the Blocked state, and the timer service/
+ * daemon task has a priority equal to or greater than the currently executing
+ * task (the task that was interrupted), then *pxHigherPriorityTaskWoken will
+ * get set to pdTRUE internally within the xTimerResetFromISR() function.  If
+ * xTimerResetFromISR() sets this value to pdTRUE then a context switch should
+ * be performed before the interrupt exits.
+ *
+ * @return pdFAIL will be returned if the reset command could not be sent to
+ * the timer command queue.  pdPASS will be returned if the command was
+ * successfully sent to the timer command queue.  When the command is actually
+ * processed will depend on the priority of the timer service/daemon task
+ * relative to other tasks in the system, although the timers expiry time is
+ * relative to when xTimerResetFromISR() is actually called.  The timer service/daemon
+ * task priority is set by the configTIMER_TASK_PRIORITY configuration constant.
+ *
+ * Example usage:
+ * @verbatim
+ * // This scenario assumes xBacklightTimer has already been created.  When a
+ * // key is pressed, an LCD back-light is switched on.  If 5 seconds pass
+ * // without a key being pressed, then the LCD back-light is switched off.  In
+ * // this case, the timer is a one-shot timer, and unlike the example given for
+ * // the xTimerReset() function, the key press event handler is an interrupt
+ * // service routine.
+ *
+ * // The callback function assigned to the one-shot timer.  In this case the
+ * // parameter is not used.
+ * void vBacklightTimerCallback( TimerHandle_t pxTimer )
+ * {
+ *     // The timer expired, therefore 5 seconds must have passed since a key
+ *     // was pressed.  Switch off the LCD back-light.
+ *     vSetBacklightState( BACKLIGHT_OFF );
+ * }
+ *
+ * // The key press interrupt service routine.
+ * void vKeyPressEventInterruptHandler( void )
+ * {
+ * BaseType_t xHigherPriorityTaskWoken = pdFALSE;
+ *
+ *     // Ensure the LCD back-light is on, then reset the timer that is
+ *     // responsible for turning the back-light off after 5 seconds of
+ *     // key inactivity.  This is an interrupt service routine so can only
+ *     // call FreeRTOS API functions that end in "FromISR".
+ *     vSetBacklightState( BACKLIGHT_ON );
+ *
+ *     // xTimerStartFromISR() or xTimerResetFromISR() could be called here
+ *     // as both cause the timer to re-calculate its expiry time.
+ *     // xHigherPriorityTaskWoken was initialised to pdFALSE when it was
+ *     // declared (in this function).
+ *     if( xTimerResetFromISR( xBacklightTimer, &xHigherPriorityTaskWoken ) != pdPASS )
+ *     {
+ *         // The reset command was not executed successfully.  Take appropriate
+ *         // action here.
+ *     }
+ *
+ *     // Perform the rest of the key processing here.
+ *
+ *     // If xHigherPriorityTaskWoken equals pdTRUE, then a context switch
+ *     // should be performed.  The syntax required to perform a context switch
+ *     // from inside an ISR varies from port to port, and from compiler to
+ *     // compiler.  Inspect the demos for the port you are using to find the
+ *     // actual syntax required.
+ *     if( xHigherPriorityTaskWoken != pdFALSE )
+ *     {
+ *         // Call the interrupt safe yield function here (actual function
+ *         // depends on the FreeRTOS port being used).
+ *     }
+ * }
+ * @endverbatim
+ */
+#define xTimerResetFromISR( xTimer, pxHigherPriorityTaskWoken ) xTimerGenericCommand( ( xTimer ), tmrCOMMAND_RESET_FROM_ISR, ( xTaskGetTickCountFromISR() ), ( pxHigherPriorityTaskWoken ), 0U )
+
+
+/**
+ * BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend,
+ *                                          void *pvParameter1,
+ *                                          uint32_t ulParameter2,
+ *                                          BaseType_t *pxHigherPriorityTaskWoken );
+ *
+ *
+ * Used from application interrupt service routines to defer the execution of a
+ * function to the RTOS daemon task (the timer service task, hence this function
+ * is implemented in timers.c and is prefixed with 'Timer').
+ *
+ * Ideally an interrupt service routine (ISR) is kept as short as possible, but
+ * sometimes an ISR either has a lot of processing to do, or needs to perform
+ * processing that is not deterministic.  In these cases
+ * xTimerPendFunctionCallFromISR() can be used to defer processing of a function
+ * to the RTOS daemon task.
+ *
+ * A mechanism is provided that allows the interrupt to return directly to the
+ * task that will subsequently execute the pended callback function.  This
+ * allows the callback function to execute contiguously in time with the
+ * interrupt - just as if the callback had executed in the interrupt itself.
+ *
+ * @param xFunctionToPend The function to execute from the timer service/
+ * daemon task.  The function must conform to the PendedFunction_t
+ * prototype.
+ *
+ * @param pvParameter1 The value of the callback function's first parameter.
+ * The parameter has a void * type to allow it to be used to pass any type.
+ * For example, unsigned longs can be cast to a void *, or the void * can be
+ * used to point to a structure.
+ *
+ * @param ulParameter2 The value of the callback function's second parameter.
+ *
+ * @param pxHigherPriorityTaskWoken As mentioned above, calling this function
+ * will result in a message being sent to the timer daemon task.  If the
+ * priority of the timer daemon task (which is set using
+ * configTIMER_TASK_PRIORITY in FreeRTOSConfig.h) is higher than the priority of
+ * the currently running task (the task the interrupt interrupted) then
+ * *pxHigherPriorityTaskWoken will be set to pdTRUE within
+ * xTimerPendFunctionCallFromISR(), indicating that a context switch should be
+ * requested before the interrupt exits.  For that reason
+ * *pxHigherPriorityTaskWoken must be initialised to pdFALSE.  See the
+ * example code below.
+ *
+ * @return pdPASS is returned if the message was successfully sent to the
+ * timer daemon task, otherwise pdFALSE is returned.
+ *
+ * Example usage:
+ * @verbatim
+ *
+ *	// The callback function that will execute in the context of the daemon task.
+ *  // Note callback functions must all use this same prototype.
+ *  void vProcessInterface( void *pvParameter1, uint32_t ulParameter2 )
+ *	{
+ *		BaseType_t xInterfaceToService;
+ *
+ *		// The interface that requires servicing is passed in the second
+ *      // parameter.  The first parameter is not used in this case.
+ *		xInterfaceToService = ( BaseType_t ) ulParameter2;
+ *
+ *		// ...Perform the processing here...
+ *	}
+ *
+ *	// An ISR that receives data packets from multiple interfaces
+ *  void vAnISR( void )
+ *	{
+ *		BaseType_t xInterfaceToService, xHigherPriorityTaskWoken;
+ *
+ *		// Query the hardware to determine which interface needs processing.
+ *		xInterfaceToService = prvCheckInterfaces();
+ *
+ *      // The actual processing is to be deferred to a task.  Request the
+ *      // vProcessInterface() callback function is executed, passing in the
+ *		// number of the interface that needs processing.  The interface to
+ *		// service is passed in the second parameter.  The first parameter is
+ *		// not used in this case.
+ *		xHigherPriorityTaskWoken = pdFALSE;
+ *		xTimerPendFunctionCallFromISR( vProcessInterface, NULL, ( uint32_t ) xInterfaceToService, &xHigherPriorityTaskWoken );
+ *
+ *		// If xHigherPriorityTaskWoken is now set to pdTRUE then a context
+ *		// switch should be requested.  The macro used is port specific and will
+ *		// be either portYIELD_FROM_ISR() or portEND_SWITCHING_ISR() - refer to
+ *		// the documentation page for the port being used.
+ *		portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
+ *
+ *	}
+ * @endverbatim
+ */
+BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken );
+
+ /**
+  * BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend,
+  *                                    void *pvParameter1,
+  *                                    uint32_t ulParameter2,
+  *                                    TickType_t xTicksToWait );
+  *
+  *
+  * Used to defer the execution of a function to the RTOS daemon task (the timer
+  * service task, hence this function is implemented in timers.c and is prefixed
+  * with 'Timer').
+  *
+  * @param xFunctionToPend The function to execute from the timer service/
+  * daemon task.  The function must conform to the PendedFunction_t
+  * prototype.
+  *
+  * @param pvParameter1 The value of the callback function's first parameter.
+  * The parameter has a void * type to allow it to be used to pass any type.
+  * For example, unsigned longs can be cast to a void *, or the void * can be
+  * used to point to a structure.
+  *
+  * @param ulParameter2 The value of the callback function's second parameter.
+  *
+  * @param xTicksToWait Calling this function will result in a message being
+  * sent to the timer daemon task on a queue.  xTicksToWait is the amount of
+  * time the calling task should remain in the Blocked state (so not using any
+  * processing time) for space to become available on the timer queue if the
+  * queue is found to be full.
+  *
+  * @return pdPASS is returned if the message was successfully sent to the
+  * timer daemon task, otherwise pdFALSE is returned.
+  *
+  */
+BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait );
+
+/**
+ * const char * const pcTimerGetTimerName( TimerHandle_t xTimer );
+ *
+ * Returns the name that was assigned to a timer when the timer was created.
+ *
+ * @param xTimer The handle of the timer being queried.
+ *
+ * @return The name assigned to the timer specified by the xTimer parameter.
+ */
+const char * pcTimerGetTimerName( TimerHandle_t xTimer ); /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+
+/*
+ * Functions beyond this part are not part of the public API and are intended
+ * for use by the kernel only.
+ */
+BaseType_t xTimerCreateTimerTask( void ) PRIVILEGED_FUNCTION;
+BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, const BaseType_t xCommandID, const TickType_t xOptionalValue, BaseType_t * const pxHigherPriorityTaskWoken, const TickType_t xTicksToWait ) PRIVILEGED_FUNCTION;
+
+#ifdef __cplusplus
+}
+#endif
+#endif /* TIMERS_H */
+
+
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/list.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/list.c	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,241 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+
+#include <stdlib.h>
+#include "FreeRTOS.h"
+#include "list.h"
+
+/*-----------------------------------------------------------
+ * PUBLIC LIST API documented in list.h
+ *----------------------------------------------------------*/
+
+void vListInitialise( List_t * const pxList )
+{
+	/* The list structure contains a list item which is used to mark the
+	end of the list.  To initialise the list the list end is inserted
+	as the only list entry. */
+	pxList->pxIndex = ( ListItem_t * ) &( pxList->xListEnd );			/*lint !e826 !e740 The mini list structure is used as the list end to save RAM.  This is checked and valid. */
+
+	/* The list end value is the highest possible value in the list to
+	ensure it remains at the end of the list. */
+	pxList->xListEnd.xItemValue = portMAX_DELAY;
+
+	/* The list end next and previous pointers point to itself so we know
+	when the list is empty. */
+	pxList->xListEnd.pxNext = ( ListItem_t * ) &( pxList->xListEnd );	/*lint !e826 !e740 The mini list structure is used as the list end to save RAM.  This is checked and valid. */
+	pxList->xListEnd.pxPrevious = ( ListItem_t * ) &( pxList->xListEnd );/*lint !e826 !e740 The mini list structure is used as the list end to save RAM.  This is checked and valid. */
+
+	pxList->uxNumberOfItems = ( UBaseType_t ) 0U;
+
+	/* Write known values into the list if
+	configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
+	listSET_LIST_INTEGRITY_CHECK_1_VALUE( pxList );
+	listSET_LIST_INTEGRITY_CHECK_2_VALUE( pxList );
+}
+/*-----------------------------------------------------------*/
+
+void vListInitialiseItem( ListItem_t * const pxItem )
+{
+	/* Make sure the list item is not recorded as being on a list. */
+	pxItem->pvContainer = NULL;
+
+	/* Write known values into the list item if
+	configUSE_LIST_DATA_INTEGRITY_CHECK_BYTES is set to 1. */
+	listSET_FIRST_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem );
+	listSET_SECOND_LIST_ITEM_INTEGRITY_CHECK_VALUE( pxItem );
+}
+/*-----------------------------------------------------------*/
+
+void vListInsertEnd( List_t * const pxList, ListItem_t * const pxNewListItem )
+{
+ListItem_t * const pxIndex = pxList->pxIndex;
+
+	/* Only effective when configASSERT() is also defined, these tests may catch
+	the list data structures being overwritten in memory.  They will not catch
+	data errors caused by incorrect configuration or use of FreeRTOS. */
+	listTEST_LIST_INTEGRITY( pxList );
+	listTEST_LIST_ITEM_INTEGRITY( pxNewListItem );
+
+	/* Insert a new list item into pxList, but rather than sort the list,
+	makes the new list item the last item to be removed by a call to
+	listGET_OWNER_OF_NEXT_ENTRY(). */
+	pxNewListItem->pxNext = pxIndex;
+	pxNewListItem->pxPrevious = pxIndex->pxPrevious;
+
+	/* Only used during decision coverage testing. */
+	mtCOVERAGE_TEST_DELAY();
+
+	pxIndex->pxPrevious->pxNext = pxNewListItem;
+	pxIndex->pxPrevious = pxNewListItem;
+
+	/* Remember which list the item is in. */
+	pxNewListItem->pvContainer = ( void * ) pxList;
+
+	( pxList->uxNumberOfItems )++;
+}
+/*-----------------------------------------------------------*/
+
+void vListInsert( List_t * const pxList, ListItem_t * const pxNewListItem )
+{
+ListItem_t *pxIterator;
+const TickType_t xValueOfInsertion = pxNewListItem->xItemValue;
+
+	/* Only effective when configASSERT() is also defined, these tests may catch
+	the list data structures being overwritten in memory.  They will not catch
+	data errors caused by incorrect configuration or use of FreeRTOS. */
+	listTEST_LIST_INTEGRITY( pxList );
+	listTEST_LIST_ITEM_INTEGRITY( pxNewListItem );
+
+	/* Insert the new list item into the list, sorted in xItemValue order.
+
+	If the list already contains a list item with the same item value then the
+	new list item should be placed after it.  This ensures that TCB's which are
+	stored in ready lists (all of which have the same xItemValue value) get a
+	share of the CPU.  However, if the xItemValue is the same as the back marker
+	the iteration loop below will not end.  Therefore the value is checked
+	first, and the algorithm slightly modified if necessary. */
+	if( xValueOfInsertion == portMAX_DELAY )
+	{
+		pxIterator = pxList->xListEnd.pxPrevious;
+	}
+	else
+	{
+		/* *** NOTE ***********************************************************
+		If you find your application is crashing here then likely causes are
+		listed below.  In addition see http://www.freertos.org/FAQHelp.html for
+		more tips, and ensure configASSERT() is defined!
+		http://www.freertos.org/a00110.html#configASSERT
+
+			1) Stack overflow -
+			   see http://www.freertos.org/Stacks-and-stack-overflow-checking.html
+			2) Incorrect interrupt priority assignment, especially on Cortex-M
+			   parts where numerically high priority values denote low actual
+			   interrupt priorities, which can seem counter intuitive.  See
+			   http://www.freertos.org/RTOS-Cortex-M3-M4.html and the definition
+			   of configMAX_SYSCALL_INTERRUPT_PRIORITY on
+			   http://www.freertos.org/a00110.html
+			3) Calling an API function from within a critical section or when
+			   the scheduler is suspended, or calling an API function that does
+			   not end in "FromISR" from an interrupt.
+			4) Using a queue or semaphore before it has been initialised or
+			   before the scheduler has been started (are interrupts firing
+			   before vTaskStartScheduler() has been called?).
+		**********************************************************************/
+
+		for( pxIterator = ( ListItem_t * ) &( pxList->xListEnd ); pxIterator->pxNext->xItemValue <= xValueOfInsertion; pxIterator = pxIterator->pxNext ) /*lint !e826 !e740 The mini list structure is used as the list end to save RAM.  This is checked and valid. */
+		{
+			/* There is nothing to do here, just iterating to the wanted
+			insertion position. */
+		}
+	}
+
+	pxNewListItem->pxNext = pxIterator->pxNext;
+	pxNewListItem->pxNext->pxPrevious = pxNewListItem;
+	pxNewListItem->pxPrevious = pxIterator;
+	pxIterator->pxNext = pxNewListItem;
+
+	/* Remember which list the item is in.  This allows fast removal of the
+	item later. */
+	pxNewListItem->pvContainer = ( void * ) pxList;
+
+	( pxList->uxNumberOfItems )++;
+}
+/*-----------------------------------------------------------*/
+
+UBaseType_t uxListRemove( ListItem_t * const pxItemToRemove )
+{
+/* The list item knows which list it is in.  Obtain the list from the list
+item. */
+List_t * const pxList = ( List_t * ) pxItemToRemove->pvContainer;
+
+	pxItemToRemove->pxNext->pxPrevious = pxItemToRemove->pxPrevious;
+	pxItemToRemove->pxPrevious->pxNext = pxItemToRemove->pxNext;
+
+	/* Only used during decision coverage testing. */
+	mtCOVERAGE_TEST_DELAY();
+
+	/* Make sure the index is left pointing to a valid item. */
+	if( pxList->pxIndex == pxItemToRemove )
+	{
+		pxList->pxIndex = pxItemToRemove->pxPrevious;
+	}
+	else
+	{
+		mtCOVERAGE_TEST_MARKER();
+	}
+
+	pxItemToRemove->pvContainer = NULL;
+	( pxList->uxNumberOfItems )--;
+
+	return pxList->uxNumberOfItems;
+}
+/*-----------------------------------------------------------*/
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/portable/MemMang/heap_1.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/portable/MemMang/heap_1.c	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,175 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+
+/*
+ * The simplest possible implementation of pvPortMalloc().  Note that this
+ * implementation does NOT allow allocated memory to be freed again.
+ *
+ * See heap_2.c, heap_3.c and heap_4.c for alternative implementations, and the
+ * memory management pages of http://www.FreeRTOS.org for more information.
+ */
+#include <stdlib.h>
+
+/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
+all the API functions to use the MPU wrappers.  That should only be done when
+task.h is included from an application file. */
+#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
+
+#include "FreeRTOS.h"
+#include "task.h"
+
+#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
+
+/* A few bytes might be lost to byte aligning the heap start address. */
+#define configADJUSTED_HEAP_SIZE	( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT )
+
+/* Allocate the memory for the heap. */
+static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
+static size_t xNextFreeByte = ( size_t ) 0;
+
+/*-----------------------------------------------------------*/
+
+void *pvPortMalloc( size_t xWantedSize )
+{
+void *pvReturn = NULL;
+static uint8_t *pucAlignedHeap = NULL;
+
+	/* Ensure that blocks are always aligned to the required number of bytes. */
+	#if portBYTE_ALIGNMENT != 1
+		if( xWantedSize & portBYTE_ALIGNMENT_MASK )
+		{
+			/* Byte alignment required. */
+			xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );
+		}
+	#endif
+
+	vTaskSuspendAll();
+	{
+		if( pucAlignedHeap == NULL )
+		{
+			/* Ensure the heap starts on a correctly aligned boundary. */
+			pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) &ucHeap[ portBYTE_ALIGNMENT ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) );
+		}
+
+		/* Check there is enough room left for the allocation. */
+		if( ( ( xNextFreeByte + xWantedSize ) < configADJUSTED_HEAP_SIZE ) &&
+			( ( xNextFreeByte + xWantedSize ) > xNextFreeByte )	)/* Check for overflow. */
+		{
+			/* Return the next free byte then increment the index past this
+			block. */
+			pvReturn = pucAlignedHeap + xNextFreeByte;
+			xNextFreeByte += xWantedSize;
+		}
+
+		traceMALLOC( pvReturn, xWantedSize );
+	}
+	( void ) xTaskResumeAll();
+
+	#if( configUSE_MALLOC_FAILED_HOOK == 1 )
+	{
+		if( pvReturn == NULL )
+		{
+			extern void vApplicationMallocFailedHook( void );
+			vApplicationMallocFailedHook();
+		}
+	}
+	#endif
+
+	return pvReturn;
+}
+/*-----------------------------------------------------------*/
+
+void vPortFree( void *pv )
+{
+	/* Memory cannot be freed using this scheme.  See heap_2.c, heap_3.c and
+	heap_4.c for alternative implementations, and the memory management pages of
+	http://www.FreeRTOS.org for more information. */
+	( void ) pv;
+
+	/* Force an assert as it is invalid to call this function. */
+	configASSERT( pv == NULL );
+}
+/*-----------------------------------------------------------*/
+
+void vPortInitialiseBlocks( void )
+{
+	/* Only required when static memory is not cleared. */
+	xNextFreeByte = ( size_t ) 0;
+}
+/*-----------------------------------------------------------*/
+
+size_t xPortGetFreeHeapSize( void )
+{
+	return ( configADJUSTED_HEAP_SIZE - xNextFreeByte );
+}
+
+
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/portable/RVDS/ARM_CM3/port.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/portable/RVDS/ARM_CM3/port.c	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,730 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+/*-----------------------------------------------------------
+ * Implementation of functions defined in portable.h for the ARM CM3 port.
+ *----------------------------------------------------------*/
+
+/* Scheduler includes. */
+#include "FreeRTOS.h"
+#include "task.h"
+
+#ifndef configKERNEL_INTERRUPT_PRIORITY
+	#define configKERNEL_INTERRUPT_PRIORITY 255
+#endif
+
+#if configMAX_SYSCALL_INTERRUPT_PRIORITY == 0
+	#error configMAX_SYSCALL_INTERRUPT_PRIORITY must not be set to 0.  See http://www.FreeRTOS.org/RTOS-Cortex-M3-M4.html
+#endif
+
+#ifndef configSYSTICK_CLOCK_HZ
+	#define configSYSTICK_CLOCK_HZ configCPU_CLOCK_HZ
+	/* Ensure the SysTick is clocked at the same frequency as the core. */
+	#define portNVIC_SYSTICK_CLK_BIT	( 1UL << 2UL )
+#else
+	/* The way the SysTick is clocked is not modified in case it is not the same
+	as the core. */
+	#define portNVIC_SYSTICK_CLK_BIT	( 0 )
+#endif
+
+/* The __weak attribute does not work as you might expect with the Keil tools
+so the configOVERRIDE_DEFAULT_TICK_CONFIGURATION constant must be set to 1 if
+the application writer wants to provide their own implementation of
+vPortSetupTimerInterrupt().  Ensure configOVERRIDE_DEFAULT_TICK_CONFIGURATION
+is defined. */
+#ifndef configOVERRIDE_DEFAULT_TICK_CONFIGURATION
+	#define configOVERRIDE_DEFAULT_TICK_CONFIGURATION 0
+#endif
+
+/* Constants required to manipulate the core.  Registers first... */
+#define portNVIC_SYSTICK_CTRL_REG			( * ( ( volatile uint32_t * ) 0xe000e010 ) )
+#define portNVIC_SYSTICK_LOAD_REG			( * ( ( volatile uint32_t * ) 0xe000e014 ) )
+#define portNVIC_SYSTICK_CURRENT_VALUE_REG	( * ( ( volatile uint32_t * ) 0xe000e018 ) )
+#define portNVIC_SYSPRI2_REG				( * ( ( volatile uint32_t * ) 0xe000ed20 ) )
+/* ...then bits in the registers. */
+#define portNVIC_SYSTICK_INT_BIT			( 1UL << 1UL )
+#define portNVIC_SYSTICK_ENABLE_BIT			( 1UL << 0UL )
+#define portNVIC_SYSTICK_COUNT_FLAG_BIT		( 1UL << 16UL )
+#define portNVIC_PENDSVCLEAR_BIT 			( 1UL << 27UL )
+#define portNVIC_PEND_SYSTICK_CLEAR_BIT		( 1UL << 25UL )
+
+/* Masks off all bits but the VECTACTIVE bits in the ICSR register. */
+#define portVECTACTIVE_MASK					( 0xFFUL )
+
+#define portNVIC_PENDSV_PRI					( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 16UL )
+#define portNVIC_SYSTICK_PRI				( ( ( uint32_t ) configKERNEL_INTERRUPT_PRIORITY ) << 24UL )
+
+/* Constants required to check the validity of an interrupt priority. */
+#define portFIRST_USER_INTERRUPT_NUMBER		( 16 )
+#define portNVIC_IP_REGISTERS_OFFSET_16 	( 0xE000E3F0 )
+#define portAIRCR_REG						( * ( ( volatile uint32_t * ) 0xE000ED0C ) )
+#define portMAX_8_BIT_VALUE					( ( uint8_t ) 0xff )
+#define portTOP_BIT_OF_BYTE					( ( uint8_t ) 0x80 )
+#define portMAX_PRIGROUP_BITS				( ( uint8_t ) 7 )
+#define portPRIORITY_GROUP_MASK				( 0x07UL << 8UL )
+#define portPRIGROUP_SHIFT					( 8UL )
+
+/* Constants required to set up the initial stack. */
+#define portINITIAL_XPSR			( 0x01000000 )
+
+/* Constants used with memory barrier intrinsics. */
+#define portSY_FULL_READ_WRITE		( 15 )
+
+/* The systick is a 24-bit counter. */
+#define portMAX_24_BIT_NUMBER				( 0xffffffUL )
+
+/* A fiddle factor to estimate the number of SysTick counts that would have
+occurred while the SysTick counter is stopped during tickless idle
+calculations. */
+#define portMISSED_COUNTS_FACTOR			( 45UL )
+
+/* Each task maintains its own interrupt status in the critical nesting
+variable. */
+static UBaseType_t uxCriticalNesting = 0xaaaaaaaa;
+
+/*
+ * Setup the timer to generate the tick interrupts.  The implementation in this
+ * file is weak to allow application writers to change the timer used to
+ * generate the tick interrupt.
+ */
+void vPortSetupTimerInterrupt( void );
+
+/*
+ * Exception handlers.
+ */
+void xPortPendSVHandler( void );
+void xPortSysTickHandler( void );
+void vPortSVCHandler( void );
+
+/*
+ * Start first task is a separate function so it can be tested in isolation.
+ */
+static void prvStartFirstTask( void );
+
+/*
+ * Used to catch tasks that attempt to return from their implementing function.
+ */
+static void prvTaskExitError( void );
+
+/*-----------------------------------------------------------*/
+
+/*
+ * The number of SysTick increments that make up one tick period.
+ */
+#if configUSE_TICKLESS_IDLE == 1
+	static uint32_t ulTimerCountsForOneTick = 0;
+#endif /* configUSE_TICKLESS_IDLE */
+
+/*
+ * The maximum number of tick periods that can be suppressed is limited by the
+ * 24 bit resolution of the SysTick timer.
+ */
+#if configUSE_TICKLESS_IDLE == 1
+	static uint32_t xMaximumPossibleSuppressedTicks = 0;
+#endif /* configUSE_TICKLESS_IDLE */
+
+/*
+ * Compensate for the CPU cycles that pass while the SysTick is stopped (low
+ * power functionality only.
+ */
+#if configUSE_TICKLESS_IDLE == 1
+	static uint32_t ulStoppedTimerCompensation = 0;
+#endif /* configUSE_TICKLESS_IDLE */
+
+/*
+ * Used by the portASSERT_IF_INTERRUPT_PRIORITY_INVALID() macro to ensure
+ * FreeRTOS API functions are not called from interrupts that have been assigned
+ * a priority above configMAX_SYSCALL_INTERRUPT_PRIORITY.
+ */
+#if ( configASSERT_DEFINED == 1 )
+	 static uint8_t ucMaxSysCallPriority = 0;
+	 static uint32_t ulMaxPRIGROUPValue = 0;
+	 static const volatile uint8_t * const pcInterruptPriorityRegisters = ( uint8_t * ) portNVIC_IP_REGISTERS_OFFSET_16;
+#endif /* configASSERT_DEFINED */
+
+/*-----------------------------------------------------------*/
+
+/*
+ * See header file for description.
+ */
+StackType_t *pxPortInitialiseStack( StackType_t *pxTopOfStack, TaskFunction_t pxCode, void *pvParameters )
+{
+	/* Simulate the stack frame as it would be created by a context switch
+	interrupt. */
+	pxTopOfStack--; /* Offset added to account for the way the MCU uses the stack on entry/exit of interrupts. */
+	*pxTopOfStack = portINITIAL_XPSR;	/* xPSR */
+	pxTopOfStack--;
+	*pxTopOfStack = ( StackType_t ) pxCode;	/* PC */
+	pxTopOfStack--;
+	*pxTopOfStack = ( StackType_t ) prvTaskExitError;	/* LR */
+
+	pxTopOfStack -= 5;	/* R12, R3, R2 and R1. */
+	*pxTopOfStack = ( StackType_t ) pvParameters;	/* R0 */
+	pxTopOfStack -= 8;	/* R11, R10, R9, R8, R7, R6, R5 and R4. */
+
+	return pxTopOfStack;
+}
+/*-----------------------------------------------------------*/
+
+static void prvTaskExitError( void )
+{
+	/* A function that implements a task must not exit or attempt to return to
+	its caller as there is nothing to return to.  If a task wants to exit it
+	should instead call vTaskDelete( NULL ).
+
+	Artificially force an assert() to be triggered if configASSERT() is
+	defined, then stop here so application writers can catch the error. */
+	configASSERT( uxCriticalNesting == ~0UL );
+	portDISABLE_INTERRUPTS();
+	for( ;; );
+}
+/*-----------------------------------------------------------*/
+
+__asm void vPortSVCHandler( void )
+{
+	PRESERVE8
+
+	ldr	r3, =pxCurrentTCB	/* Restore the context. */
+	ldr r1, [r3]			/* Use pxCurrentTCBConst to get the pxCurrentTCB address. */
+	ldr r0, [r1]			/* The first item in pxCurrentTCB is the task top of stack. */
+	ldmia r0!, {r4-r11}		/* Pop the registers that are not automatically saved on exception entry and the critical nesting count. */
+	msr psp, r0				/* Restore the task stack pointer. */
+	isb
+	mov r0, #0
+	msr	basepri, r0
+	orr r14, #0xd
+	bx r14
+}
+/*-----------------------------------------------------------*/
+
+__asm void prvStartFirstTask( void )
+{
+	PRESERVE8
+
+	/* Use the NVIC offset register to locate the stack. */
+	ldr r0, =0xE000ED08
+	ldr r0, [r0]
+	ldr r0, [r0]
+
+	/* Set the msp back to the start of the stack. */
+	msr msp, r0
+	/* Globally enable interrupts. */
+	cpsie i
+	cpsie f
+	dsb
+	isb
+	/* Call SVC to start the first task. */
+	svc 0
+	nop
+	nop
+}
+/*-----------------------------------------------------------*/
+
+/*
+ * See header file for description.
+ */
+BaseType_t xPortStartScheduler( void )
+{
+	#if( configASSERT_DEFINED == 1 )
+	{
+		volatile uint32_t ulOriginalPriority;
+		volatile uint8_t * const pucFirstUserPriorityRegister = ( uint8_t * ) ( portNVIC_IP_REGISTERS_OFFSET_16 + portFIRST_USER_INTERRUPT_NUMBER );
+		volatile uint8_t ucMaxPriorityValue;
+
+		/* Determine the maximum priority from which ISR safe FreeRTOS API
+		functions can be called.  ISR safe functions are those that end in
+		"FromISR".  FreeRTOS maintains separate thread and ISR API functions to
+		ensure interrupt entry is as fast and simple as possible.
+
+		Save the interrupt priority value that is about to be clobbered. */
+		ulOriginalPriority = *pucFirstUserPriorityRegister;
+
+		/* Determine the number of priority bits available.  First write to all
+		possible bits. */
+		*pucFirstUserPriorityRegister = portMAX_8_BIT_VALUE;
+
+		/* Read the value back to see how many bits stuck. */
+		ucMaxPriorityValue = *pucFirstUserPriorityRegister;
+
+		/* Use the same mask on the maximum system call priority. */
+		ucMaxSysCallPriority = configMAX_SYSCALL_INTERRUPT_PRIORITY & ucMaxPriorityValue;
+
+		/* Calculate the maximum acceptable priority group value for the number
+		of bits read back. */
+		ulMaxPRIGROUPValue = portMAX_PRIGROUP_BITS;
+		while( ( ucMaxPriorityValue & portTOP_BIT_OF_BYTE ) == portTOP_BIT_OF_BYTE )
+		{
+			ulMaxPRIGROUPValue--;
+			ucMaxPriorityValue <<= ( uint8_t ) 0x01;
+		}
+
+		/* Shift the priority group value back to its position within the AIRCR
+		register. */
+		ulMaxPRIGROUPValue <<= portPRIGROUP_SHIFT;
+		ulMaxPRIGROUPValue &= portPRIORITY_GROUP_MASK;
+
+		/* Restore the clobbered interrupt priority register to its original
+		value. */
+		*pucFirstUserPriorityRegister = ulOriginalPriority;
+	}
+	#endif /* conifgASSERT_DEFINED */
+
+	/* Make PendSV and SysTick the lowest priority interrupts. */
+	portNVIC_SYSPRI2_REG |= portNVIC_PENDSV_PRI;
+	portNVIC_SYSPRI2_REG |= portNVIC_SYSTICK_PRI;
+
+	/* Start the timer that generates the tick ISR.  Interrupts are disabled
+	here already. */
+	vPortSetupTimerInterrupt();
+
+	/* Initialise the critical nesting count ready for the first task. */
+	uxCriticalNesting = 0;
+
+	/* Start the first task. */
+	prvStartFirstTask();
+
+	/* Should not get here! */
+	return 0;
+}
+/*-----------------------------------------------------------*/
+
+void vPortEndScheduler( void )
+{
+	/* Not implemented in ports where there is nothing to return to.
+	Artificially force an assert. */
+	configASSERT( uxCriticalNesting == 1000UL );
+}
+/*-----------------------------------------------------------*/
+
+void vPortYield( void )
+{
+	/* Set a PendSV to request a context switch. */
+	portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
+
+	/* Barriers are normally not required but do ensure the code is completely
+	within the specified behaviour for the architecture. */
+	__dsb( portSY_FULL_READ_WRITE );
+	__isb( portSY_FULL_READ_WRITE );
+}
+/*-----------------------------------------------------------*/
+
+void vPortEnterCritical( void )
+{
+	portDISABLE_INTERRUPTS();
+	uxCriticalNesting++;
+	__dsb( portSY_FULL_READ_WRITE );
+	__isb( portSY_FULL_READ_WRITE );
+
+	/* This is not the interrupt safe version of the enter critical function so
+	assert() if it is being called from an interrupt context.  Only API
+	functions that end in "FromISR" can be used in an interrupt.  Only assert if
+	the critical nesting count is 1 to protect against recursive calls if the
+	assert function also uses a critical section. */
+	if( uxCriticalNesting == 1 )
+	{
+		configASSERT( ( portNVIC_INT_CTRL_REG & portVECTACTIVE_MASK ) == 0 );
+	}
+}
+/*-----------------------------------------------------------*/
+
+void vPortExitCritical( void )
+{
+	configASSERT( uxCriticalNesting );
+	uxCriticalNesting--;
+	if( uxCriticalNesting == 0 )
+	{
+		portENABLE_INTERRUPTS();
+	}
+}
+/*-----------------------------------------------------------*/
+
+__asm void xPortPendSVHandler( void )
+{
+	extern uxCriticalNesting;
+	extern pxCurrentTCB;
+	extern vTaskSwitchContext;
+
+	PRESERVE8
+
+	mrs r0, psp
+	isb
+
+	ldr	r3, =pxCurrentTCB		/* Get the location of the current TCB. */
+	ldr	r2, [r3]
+
+	stmdb r0!, {r4-r11}			/* Save the remaining registers. */
+	str r0, [r2]				/* Save the new top of stack into the first member of the TCB. */
+
+	stmdb sp!, {r3, r14}
+	mov r0, #configMAX_SYSCALL_INTERRUPT_PRIORITY
+	msr basepri, r0
+	bl vTaskSwitchContext
+	mov r0, #0
+	msr basepri, r0
+	ldmia sp!, {r3, r14}
+
+	ldr r1, [r3]
+	ldr r0, [r1]				/* The first item in pxCurrentTCB is the task top of stack. */
+	ldmia r0!, {r4-r11}			/* Pop the registers and the critical nesting count. */
+	msr psp, r0
+	isb
+	bx r14
+	nop
+}
+/*-----------------------------------------------------------*/
+
+void xPortSysTickHandler( void )
+{
+	/* The SysTick runs at the lowest interrupt priority, so when this interrupt
+	executes all interrupts must be unmasked.  There is therefore no need to
+	save and then restore the interrupt mask value as its value is already
+	known. */
+	( void ) portSET_INTERRUPT_MASK_FROM_ISR();
+	{
+		/* Increment the RTOS tick. */
+		if( xTaskIncrementTick() != pdFALSE )
+		{
+			/* A context switch is required.  Context switching is performed in
+			the PendSV interrupt.  Pend the PendSV interrupt. */
+			portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT;
+		}
+	}
+	portCLEAR_INTERRUPT_MASK_FROM_ISR( 0 );
+}
+/*-----------------------------------------------------------*/
+
+#if configUSE_TICKLESS_IDLE == 1
+
+	__weak void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime )
+	{
+	uint32_t ulReloadValue, ulCompleteTickPeriods, ulCompletedSysTickDecrements, ulSysTickCTRL;
+	TickType_t xModifiableIdleTime;
+
+		/* Make sure the SysTick reload value does not overflow the counter. */
+		if( xExpectedIdleTime > xMaximumPossibleSuppressedTicks )
+		{
+			xExpectedIdleTime = xMaximumPossibleSuppressedTicks;
+		}
+
+		/* Stop the SysTick momentarily.  The time the SysTick is stopped for
+		is accounted for as best it can be, but using the tickless mode will
+		inevitably result in some tiny drift of the time maintained by the
+		kernel with respect to calendar time. */
+		portNVIC_SYSTICK_CTRL_REG &= ~portNVIC_SYSTICK_ENABLE_BIT;
+
+		/* Calculate the reload value required to wait xExpectedIdleTime
+		tick periods.  -1 is used because this code will execute part way
+		through one of the tick periods. */
+		ulReloadValue = portNVIC_SYSTICK_CURRENT_VALUE_REG + ( ulTimerCountsForOneTick * ( xExpectedIdleTime - 1UL ) );
+		if( ulReloadValue > ulStoppedTimerCompensation )
+		{
+			ulReloadValue -= ulStoppedTimerCompensation;
+		}
+
+		/* Enter a critical section but don't use the taskENTER_CRITICAL()
+		method as that will mask interrupts that should exit sleep mode. */
+		__disable_irq();
+
+		/* If a context switch is pending or a task is waiting for the scheduler
+		to be unsuspended then abandon the low power entry. */
+		if( eTaskConfirmSleepModeStatus() == eAbortSleep )
+		{
+			/* Restart from whatever is left in the count register to complete
+			this tick period. */
+			portNVIC_SYSTICK_LOAD_REG = portNVIC_SYSTICK_CURRENT_VALUE_REG;
+
+			/* Restart SysTick. */
+			portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
+
+			/* Reset the reload register to the value required for normal tick
+			periods. */
+			portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
+
+			/* Re-enable interrupts - see comments above __disable_irq() call
+			above. */
+			__enable_irq();
+		}
+		else
+		{
+			/* Set the new reload value. */
+			portNVIC_SYSTICK_LOAD_REG = ulReloadValue;
+
+			/* Clear the SysTick count flag and set the count value back to
+			zero. */
+			portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
+
+			/* Restart SysTick. */
+			portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
+
+			/* Sleep until something happens.  configPRE_SLEEP_PROCESSING() can
+			set its parameter to 0 to indicate that its implementation contains
+			its own wait for interrupt or wait for event instruction, and so wfi
+			should not be executed again.  However, the original expected idle
+			time variable must remain unmodified, so a copy is taken. */
+			xModifiableIdleTime = xExpectedIdleTime;
+			configPRE_SLEEP_PROCESSING( xModifiableIdleTime );
+			if( xModifiableIdleTime > 0 )
+			{
+				__dsb( portSY_FULL_READ_WRITE );
+				__wfi();
+				__isb( portSY_FULL_READ_WRITE );
+			}
+			configPOST_SLEEP_PROCESSING( xExpectedIdleTime );
+
+			/* Stop SysTick.  Again, the time the SysTick is stopped for is
+			accounted for as best it can be, but using the tickless mode will
+			inevitably result in some tiny drift of the time maintained by the
+			kernel with respect to calendar time. */
+			ulSysTickCTRL = portNVIC_SYSTICK_CTRL_REG;
+			portNVIC_SYSTICK_CTRL_REG = ( ulSysTickCTRL & ~portNVIC_SYSTICK_ENABLE_BIT );
+
+			/* Re-enable interrupts - see comments above __disable_irq() call
+			above. */
+			__enable_irq();
+
+			if( ( ulSysTickCTRL & portNVIC_SYSTICK_COUNT_FLAG_BIT ) != 0 )
+			{
+				uint32_t ulCalculatedLoadValue;
+
+				/* The tick interrupt has already executed, and the SysTick
+				count reloaded with ulReloadValue.  Reset the
+				portNVIC_SYSTICK_LOAD_REG with whatever remains of this tick
+				period. */
+				ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL ) - ( ulReloadValue - portNVIC_SYSTICK_CURRENT_VALUE_REG );
+
+				/* Don't allow a tiny value, or values that have somehow
+				underflowed because the post sleep hook did something
+				that took too long. */
+				if( ( ulCalculatedLoadValue < ulStoppedTimerCompensation ) || ( ulCalculatedLoadValue > ulTimerCountsForOneTick ) )
+				{
+					ulCalculatedLoadValue = ( ulTimerCountsForOneTick - 1UL );
+				}
+
+				portNVIC_SYSTICK_LOAD_REG = ulCalculatedLoadValue;
+
+				/* The tick interrupt handler will already have pended the tick
+				processing in the kernel.  As the pending tick will be
+				processed as soon as this function exits, the tick value
+				maintained by the tick is stepped forward by one less than the
+				time spent waiting. */
+				ulCompleteTickPeriods = xExpectedIdleTime - 1UL;
+			}
+			else
+			{
+				/* Something other than the tick interrupt ended the sleep.
+				Work out how long the sleep lasted rounded to complete tick
+				periods (not the ulReload value which accounted for part
+				ticks). */
+				ulCompletedSysTickDecrements = ( xExpectedIdleTime * ulTimerCountsForOneTick ) - portNVIC_SYSTICK_CURRENT_VALUE_REG;
+
+				/* How many complete tick periods passed while the processor
+				was waiting? */
+				ulCompleteTickPeriods = ulCompletedSysTickDecrements / ulTimerCountsForOneTick;
+
+				/* The reload value is set to whatever fraction of a single tick
+				period remains. */
+				portNVIC_SYSTICK_LOAD_REG = ( ( ulCompleteTickPeriods + 1 ) * ulTimerCountsForOneTick ) - ulCompletedSysTickDecrements;
+			}
+
+			/* Restart SysTick so it runs from portNVIC_SYSTICK_LOAD_REG
+			again, then set portNVIC_SYSTICK_LOAD_REG back to its standard
+			value.  The critical section is used to ensure the tick interrupt
+			can only execute once in the case that the reload register is near
+			zero. */
+			portNVIC_SYSTICK_CURRENT_VALUE_REG = 0UL;
+			portENTER_CRITICAL();
+			{
+				portNVIC_SYSTICK_CTRL_REG |= portNVIC_SYSTICK_ENABLE_BIT;
+				vTaskStepTick( ulCompleteTickPeriods );
+				portNVIC_SYSTICK_LOAD_REG = ulTimerCountsForOneTick - 1UL;
+			}
+			portEXIT_CRITICAL();
+		}
+	}
+
+#endif /* #if configUSE_TICKLESS_IDLE */
+
+/*-----------------------------------------------------------*/
+
+/*
+ * Setup the SysTick timer to generate the tick interrupts at the required
+ * frequency.
+ */
+#if configOVERRIDE_DEFAULT_TICK_CONFIGURATION == 0
+
+	void vPortSetupTimerInterrupt( void )
+	{
+		/* Calculate the constants required to configure the tick interrupt. */
+		#if configUSE_TICKLESS_IDLE == 1
+		{
+			ulTimerCountsForOneTick = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ );
+			xMaximumPossibleSuppressedTicks = portMAX_24_BIT_NUMBER / ulTimerCountsForOneTick;
+			ulStoppedTimerCompensation = portMISSED_COUNTS_FACTOR / ( configCPU_CLOCK_HZ / configSYSTICK_CLOCK_HZ );
+		}
+		#endif /* configUSE_TICKLESS_IDLE */
+
+		/* Configure SysTick to interrupt at the requested rate. */
+		portNVIC_SYSTICK_LOAD_REG = ( configSYSTICK_CLOCK_HZ / configTICK_RATE_HZ ) - 1UL;
+		portNVIC_SYSTICK_CTRL_REG = ( portNVIC_SYSTICK_CLK_BIT | portNVIC_SYSTICK_INT_BIT | portNVIC_SYSTICK_ENABLE_BIT );
+	}
+
+#endif /* configOVERRIDE_DEFAULT_TICK_CONFIGURATION */
+/*-----------------------------------------------------------*/
+
+__asm uint32_t ulPortSetInterruptMask( void )
+{
+	PRESERVE8
+
+	mrs r0, basepri
+	mov r1, #configMAX_SYSCALL_INTERRUPT_PRIORITY
+	msr basepri, r1
+	bx r14
+}
+/*-----------------------------------------------------------*/
+
+__asm void vPortClearInterruptMask( uint32_t ulNewMask )
+{
+	PRESERVE8
+
+	msr basepri, r0
+	bx r14
+}
+/*-----------------------------------------------------------*/
+
+__asm uint32_t vPortGetIPSR( void )
+{
+	PRESERVE8
+
+	mrs r0, ipsr
+	bx r14
+}
+/*-----------------------------------------------------------*/
+
+#if( configASSERT_DEFINED == 1 )
+
+	void vPortValidateInterruptPriority( void )
+	{
+	uint32_t ulCurrentInterrupt;
+	uint8_t ucCurrentPriority;
+
+		/* Obtain the number of the currently executing interrupt. */
+		ulCurrentInterrupt = vPortGetIPSR();
+
+		/* Is the interrupt number a user defined interrupt? */
+		if( ulCurrentInterrupt >= portFIRST_USER_INTERRUPT_NUMBER )
+		{
+			/* Look up the interrupt's priority. */
+			ucCurrentPriority = pcInterruptPriorityRegisters[ ulCurrentInterrupt ];
+
+			/* The following assertion will fail if a service routine (ISR) for
+			an interrupt that has been assigned a priority above
+			configMAX_SYSCALL_INTERRUPT_PRIORITY calls an ISR safe FreeRTOS API
+			function.  ISR safe FreeRTOS API functions must *only* be called
+			from interrupts that have been assigned a priority at or below
+			configMAX_SYSCALL_INTERRUPT_PRIORITY.
+
+			Numerically low interrupt priority numbers represent logically high
+			interrupt priorities, therefore the priority of the interrupt must
+			be set to a value equal to or numerically *higher* than
+			configMAX_SYSCALL_INTERRUPT_PRIORITY.
+
+			Interrupts that	use the FreeRTOS API must not be left at their
+			default priority of	zero as that is the highest possible priority,
+			which is guaranteed to be above configMAX_SYSCALL_INTERRUPT_PRIORITY,
+			and	therefore also guaranteed to be invalid.
+
+			FreeRTOS maintains separate thread and ISR API functions to ensure
+			interrupt entry is as fast and simple as possible.
+
+			The following links provide detailed information:
+			http://www.freertos.org/RTOS-Cortex-M3-M4.html
+			http://www.freertos.org/FAQHelp.html */
+			configASSERT( ucCurrentPriority >= ucMaxSysCallPriority );
+		}
+
+		/* Priority grouping:  The interrupt controller (NVIC) allows the bits
+		that define each interrupt's priority to be split between bits that
+		define the interrupt's pre-emption priority bits and bits that define
+		the interrupt's sub-priority.  For simplicity all bits must be defined
+		to be pre-emption priority bits.  The following assertion will fail if
+		this is not the case (if some bits represent a sub-priority).
+
+		If the application only uses CMSIS libraries for interrupt
+		configuration then the correct setting can be achieved on all Cortex-M
+		devices by calling NVIC_SetPriorityGrouping( 0 ); before starting the
+		scheduler.  Note however that some vendor specific peripheral libraries
+		assume a non-zero priority group setting, in which cases using a value
+		of zero will result in unpredicable behaviour. */
+		configASSERT( ( portAIRCR_REG & portPRIORITY_GROUP_MASK ) <= ulMaxPRIGROUPValue );
+	}
+
+#endif /* configASSERT_DEFINED */
+
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/portable/RVDS/ARM_CM3/portmacro.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/portable/RVDS/ARM_CM3/portmacro.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,194 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+
+#ifndef PORTMACRO_H
+#define PORTMACRO_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*-----------------------------------------------------------
+ * Port specific definitions.
+ *
+ * The settings in this file configure FreeRTOS correctly for the
+ * given hardware and compiler.
+ *
+ * These settings should not be altered.
+ *-----------------------------------------------------------
+ */
+
+/* Type definitions. */
+#define portCHAR		char
+#define portFLOAT		float
+#define portDOUBLE		double
+#define portLONG		long
+#define portSHORT		short
+#define portSTACK_TYPE	uint32_t
+#define portBASE_TYPE	long
+
+typedef portSTACK_TYPE StackType_t;
+typedef long BaseType_t;
+typedef unsigned long UBaseType_t;
+
+#if( configUSE_16_BIT_TICKS == 1 )
+	typedef uint16_t TickType_t;
+	#define portMAX_DELAY ( TickType_t ) 0xffff
+#else
+	typedef uint32_t TickType_t;
+	#define portMAX_DELAY ( TickType_t ) 0xffffffffUL
+
+	/* 32-bit tick type on a 32-bit architecture, so reads of the tick count do
+	not need to be guarded with a critical section. */
+	#define portTICK_TYPE_IS_ATOMIC 1
+#endif
+/*-----------------------------------------------------------*/
+
+/* Architecture specifics. */
+#define portSTACK_GROWTH			( -1 )
+#define portTICK_PERIOD_MS			( ( TickType_t ) 1000 / configTICK_RATE_HZ )
+#define portBYTE_ALIGNMENT			8
+/*-----------------------------------------------------------*/
+
+/* Scheduler utilities. */
+extern void vPortYield( void );
+#define portNVIC_INT_CTRL_REG		( * ( ( volatile uint32_t * ) 0xe000ed04 ) )
+#define portNVIC_PENDSVSET_BIT		( 1UL << 28UL )
+#define portYIELD()					vPortYield()
+#define portEND_SWITCHING_ISR( xSwitchRequired ) if( xSwitchRequired ) portNVIC_INT_CTRL_REG = portNVIC_PENDSVSET_BIT
+#define portYIELD_FROM_ISR( x ) portEND_SWITCHING_ISR( x )
+/*-----------------------------------------------------------*/
+
+/* Critical section management. */
+extern uint32_t ulPortSetInterruptMask( void );
+extern void vPortClearInterruptMask( uint32_t ulNewMask );
+extern void vPortEnterCritical( void );
+extern void vPortExitCritical( void );
+
+#define portDISABLE_INTERRUPTS()				ulPortSetInterruptMask()
+#define portENABLE_INTERRUPTS()					vPortClearInterruptMask( 0 )
+#define portENTER_CRITICAL()					vPortEnterCritical()
+#define portEXIT_CRITICAL()						vPortExitCritical()
+#define portSET_INTERRUPT_MASK_FROM_ISR()		ulPortSetInterruptMask()
+#define portCLEAR_INTERRUPT_MASK_FROM_ISR(x)	vPortClearInterruptMask(x)
+/*-----------------------------------------------------------*/
+
+/* Tickless idle/low power functionality. */
+#ifndef portSUPPRESS_TICKS_AND_SLEEP
+	extern void vPortSuppressTicksAndSleep( TickType_t xExpectedIdleTime );
+	#define portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime ) vPortSuppressTicksAndSleep( xExpectedIdleTime )
+#endif
+/*-----------------------------------------------------------*/
+
+/* Port specific optimisations. */
+//#ifndef configUSE_PORT_OPTIMISED_TASK_SELECTION
+//	#define configUSE_PORT_OPTIMISED_TASK_SELECTION 1
+//#endif
+
+#if configUSE_PORT_OPTIMISED_TASK_SELECTION == 1
+
+	/* Check the configuration. */
+	#if( configMAX_PRIORITIES > 32 )
+		#error configUSE_PORT_OPTIMISED_TASK_SELECTION can only be set to 1 when configMAX_PRIORITIES is less than or equal to 32.  It is very rare that a system requires more than 10 to 15 difference priorities as tasks that share a priority will time slice.
+	#endif
+
+	/* Store/clear the ready priorities in a bit map. */
+	#define portRECORD_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) |= ( 1UL << ( uxPriority ) )
+	#define portRESET_READY_PRIORITY( uxPriority, uxReadyPriorities ) ( uxReadyPriorities ) &= ~( 1UL << ( uxPriority ) )
+
+	/*-----------------------------------------------------------*/
+
+	#define portGET_HIGHEST_PRIORITY( uxTopPriority, uxReadyPriorities ) uxTopPriority = ( 31 - __clz( ( uxReadyPriorities ) ) )
+
+#endif /* taskRECORD_READY_PRIORITY */
+/*-----------------------------------------------------------*/
+
+/* Task function macros as described on the FreeRTOS.org WEB site.  These are
+not necessary for to use this port.  They are defined so the common demo files
+(which build with all the ports) will build. */
+#define portTASK_FUNCTION_PROTO( vFunction, pvParameters ) void vFunction( void *pvParameters )
+#define portTASK_FUNCTION( vFunction, pvParameters ) void vFunction( void *pvParameters )
+/*-----------------------------------------------------------*/
+
+#ifdef configASSERT
+	void vPortValidateInterruptPriority( void );
+	#define portASSERT_IF_INTERRUPT_PRIORITY_INVALID() 	vPortValidateInterruptPriority()
+#endif
+
+/* portNOP() is not required by this port. */
+#define portNOP()
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* PORTMACRO_H */
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/queue.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/queue.c	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,2613 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+#include <stdlib.h>
+#include <string.h>
+
+/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
+all the API functions to use the MPU wrappers.  That should only be done when
+task.h is included from an application file. */
+#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
+
+#include "FreeRTOS.h"
+#include "task.h"
+#include "queue.h"
+
+#if ( configUSE_CO_ROUTINES == 1 )
+	#include "croutine.h"
+#endif
+
+/* Lint e961 and e750 are suppressed as a MISRA exception justified because the
+MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined for the
+header files above, but not in this file, in order to generate the correct
+privileged Vs unprivileged linkage and placement. */
+#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750. */
+
+
+/* Constants used with the xRxLock and xTxLock structure members. */
+#define queueUNLOCKED					( ( BaseType_t ) -1 )
+#define queueLOCKED_UNMODIFIED			( ( BaseType_t ) 0 )
+
+/* When the Queue_t structure is used to represent a base queue its pcHead and
+pcTail members are used as pointers into the queue storage area.  When the
+Queue_t structure is used to represent a mutex pcHead and pcTail pointers are
+not necessary, and the pcHead pointer is set to NULL to indicate that the
+pcTail pointer actually points to the mutex holder (if any).  Map alternative
+names to the pcHead and pcTail structure members to ensure the readability of
+the code is maintained despite this dual use of two structure members.  An
+alternative implementation would be to use a union, but use of a union is
+against the coding standard (although an exception to the standard has been
+permitted where the dual use also significantly changes the type of the
+structure member). */
+#define pxMutexHolder					pcTail
+#define uxQueueType						pcHead
+#define queueQUEUE_IS_MUTEX				NULL
+
+/* Semaphores do not actually store or copy data, so have an item size of
+zero. */
+#define queueSEMAPHORE_QUEUE_ITEM_LENGTH ( ( UBaseType_t ) 0 )
+#define queueMUTEX_GIVE_BLOCK_TIME		 ( ( TickType_t ) 0U )
+
+#if( configUSE_PREEMPTION == 0 )
+	/* If the cooperative scheduler is being used then a yield should not be
+	performed just because a higher priority task has been woken. */
+	#define queueYIELD_IF_USING_PREEMPTION()
+#else
+	#define queueYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API()
+#endif
+
+/*
+ * Definition of the queue used by the scheduler.
+ * Items are queued by copy, not reference.  See the following link for the
+ * rationale: http://www.freertos.org/Embedded-RTOS-Queues.html
+ */
+typedef struct QueueDefinition
+{
+	int8_t *pcHead;					/*< Points to the beginning of the queue storage area. */
+	int8_t *pcTail;					/*< Points to the byte at the end of the queue storage area.  Once more byte is allocated than necessary to store the queue items, this is used as a marker. */
+	int8_t *pcWriteTo;				/*< Points to the free next place in the storage area. */
+
+	union							/* Use of a union is an exception to the coding standard to ensure two mutually exclusive structure members don't appear simultaneously (wasting RAM). */
+	{
+		int8_t *pcReadFrom;			/*< Points to the last place that a queued item was read from when the structure is used as a queue. */
+		UBaseType_t uxRecursiveCallCount;/*< Maintains a count of the number of times a recursive mutex has been recursively 'taken' when the structure is used as a mutex. */
+	} u;
+
+	List_t xTasksWaitingToSend;		/*< List of tasks that are blocked waiting to post onto this queue.  Stored in priority order. */
+	List_t xTasksWaitingToReceive;	/*< List of tasks that are blocked waiting to read from this queue.  Stored in priority order. */
+
+	volatile UBaseType_t uxMessagesWaiting;/*< The number of items currently in the queue. */
+	UBaseType_t uxLength;			/*< The length of the queue defined as the number of items it will hold, not the number of bytes. */
+	UBaseType_t uxItemSize;			/*< The size of each items that the queue will hold. */
+
+	volatile BaseType_t xRxLock;	/*< Stores the number of items received from the queue (removed from the queue) while the queue was locked.  Set to queueUNLOCKED when the queue is not locked. */
+	volatile BaseType_t xTxLock;	/*< Stores the number of items transmitted to the queue (added to the queue) while the queue was locked.  Set to queueUNLOCKED when the queue is not locked. */
+
+	#if ( configUSE_TRACE_FACILITY == 1 )
+		UBaseType_t uxQueueNumber;
+		uint8_t ucQueueType;
+	#endif
+
+	#if ( configUSE_QUEUE_SETS == 1 )
+		struct QueueDefinition *pxQueueSetContainer;
+	#endif
+
+} xQUEUE;
+
+/* The old xQUEUE name is maintained above then typedefed to the new Queue_t
+name below to enable the use of older kernel aware debuggers. */
+typedef xQUEUE Queue_t;
+
+/*-----------------------------------------------------------*/
+
+/*
+ * The queue registry is just a means for kernel aware debuggers to locate
+ * queue structures.  It has no other purpose so is an optional component.
+ */
+#if ( configQUEUE_REGISTRY_SIZE > 0 )
+
+	/* The type stored within the queue registry array.  This allows a name
+	to be assigned to each queue making kernel aware debugging a little
+	more user friendly. */
+	typedef struct QUEUE_REGISTRY_ITEM
+	{
+		const char *pcQueueName; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+		QueueHandle_t xHandle;
+	} xQueueRegistryItem;
+
+	/* The old xQueueRegistryItem name is maintained above then typedefed to the
+	new xQueueRegistryItem name below to enable the use of older kernel aware
+	debuggers. */
+	typedef xQueueRegistryItem QueueRegistryItem_t;
+
+	/* The queue registry is simply an array of QueueRegistryItem_t structures.
+	The pcQueueName member of a structure being NULL is indicative of the
+	array position being vacant. */
+	QueueRegistryItem_t xQueueRegistry[ configQUEUE_REGISTRY_SIZE ];
+
+#endif /* configQUEUE_REGISTRY_SIZE */
+
+/*
+ * Unlocks a queue locked by a call to prvLockQueue.  Locking a queue does not
+ * prevent an ISR from adding or removing items to the queue, but does prevent
+ * an ISR from removing tasks from the queue event lists.  If an ISR finds a
+ * queue is locked it will instead increment the appropriate queue lock count
+ * to indicate that a task may require unblocking.  When the queue in unlocked
+ * these lock counts are inspected, and the appropriate action taken.
+ */
+static void prvUnlockQueue( Queue_t * const pxQueue ) PRIVILEGED_FUNCTION;
+
+/*
+ * Uses a critical section to determine if there is any data in a queue.
+ *
+ * @return pdTRUE if the queue contains no items, otherwise pdFALSE.
+ */
+static BaseType_t prvIsQueueEmpty( const Queue_t *pxQueue ) PRIVILEGED_FUNCTION;
+
+/*
+ * Uses a critical section to determine if there is any space in a queue.
+ *
+ * @return pdTRUE if there is no space, otherwise pdFALSE;
+ */
+static BaseType_t prvIsQueueFull( const Queue_t *pxQueue ) PRIVILEGED_FUNCTION;
+
+/*
+ * Copies an item into the queue, either at the front of the queue or the
+ * back of the queue.
+ */
+static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, const void *pvItemToQueue, const BaseType_t xPosition ) PRIVILEGED_FUNCTION;
+
+/*
+ * Copies an item out of a queue.
+ */
+static void prvCopyDataFromQueue( Queue_t * const pxQueue, void * const pvBuffer ) PRIVILEGED_FUNCTION;
+
+#if ( configUSE_QUEUE_SETS == 1 )
+	/*
+	 * Checks to see if a queue is a member of a queue set, and if so, notifies
+	 * the queue set that the queue contains data.
+	 */
+	static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue, const BaseType_t xCopyPosition ) PRIVILEGED_FUNCTION;
+#endif
+
+/*-----------------------------------------------------------*/
+
+/*
+ * Macro to mark a queue as locked.  Locking a queue prevents an ISR from
+ * accessing the queue event lists.
+ */
+#define prvLockQueue( pxQueue )								\
+	taskENTER_CRITICAL();									\
+	{														\
+		if( ( pxQueue )->xRxLock == queueUNLOCKED )			\
+		{													\
+			( pxQueue )->xRxLock = queueLOCKED_UNMODIFIED;	\
+		}													\
+		if( ( pxQueue )->xTxLock == queueUNLOCKED )			\
+		{													\
+			( pxQueue )->xTxLock = queueLOCKED_UNMODIFIED;	\
+		}													\
+	}														\
+	taskEXIT_CRITICAL()
+/*-----------------------------------------------------------*/
+
+BaseType_t xQueueGenericReset( QueueHandle_t xQueue, BaseType_t xNewQueue )
+{
+Queue_t * const pxQueue = ( Queue_t * ) xQueue;
+
+	configASSERT( pxQueue );
+
+	taskENTER_CRITICAL();
+	{
+		pxQueue->pcTail = pxQueue->pcHead + ( pxQueue->uxLength * pxQueue->uxItemSize );
+		pxQueue->uxMessagesWaiting = ( UBaseType_t ) 0U;
+		pxQueue->pcWriteTo = pxQueue->pcHead;
+		pxQueue->u.pcReadFrom = pxQueue->pcHead + ( ( pxQueue->uxLength - ( UBaseType_t ) 1U ) * pxQueue->uxItemSize );
+		pxQueue->xRxLock = queueUNLOCKED;
+		pxQueue->xTxLock = queueUNLOCKED;
+
+		if( xNewQueue == pdFALSE )
+		{
+			/* If there are tasks blocked waiting to read from the queue, then
+			the tasks will remain blocked as after this function exits the queue
+			will still be empty.  If there are tasks blocked waiting to write to
+			the queue, then one should be unblocked as after this function exits
+			it will be possible to write to it. */
+			if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE )
+			{
+				if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) == pdTRUE )
+				{
+					queueYIELD_IF_USING_PREEMPTION();
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		else
+		{
+			/* Ensure the event queues start in the correct state. */
+			vListInitialise( &( pxQueue->xTasksWaitingToSend ) );
+			vListInitialise( &( pxQueue->xTasksWaitingToReceive ) );
+		}
+	}
+	taskEXIT_CRITICAL();
+
+	/* A value is returned for calling semantic consistency with previous
+	versions. */
+	return pdPASS;
+}
+/*-----------------------------------------------------------*/
+
+QueueHandle_t xQueueGenericCreate( const UBaseType_t uxQueueLength, const UBaseType_t uxItemSize, const uint8_t ucQueueType )
+{
+Queue_t *pxNewQueue;
+size_t xQueueSizeInBytes;
+QueueHandle_t xReturn = NULL;
+int8_t *pcAllocatedBuffer;
+
+	/* Remove compiler warnings about unused parameters should
+	configUSE_TRACE_FACILITY not be set to 1. */
+	( void ) ucQueueType;
+
+	configASSERT( uxQueueLength > ( UBaseType_t ) 0 );
+
+	if( uxItemSize == ( UBaseType_t ) 0 )
+	{
+		/* There is not going to be a queue storage area. */
+		xQueueSizeInBytes = ( size_t ) 0;
+	}
+	else
+	{
+		/* The queue is one byte longer than asked for to make wrap checking
+		easier/faster. */
+		xQueueSizeInBytes = ( size_t ) ( uxQueueLength * uxItemSize ) + ( size_t ) 1; /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+	}
+
+	/* Allocate the new queue structure and storage area. */
+	pcAllocatedBuffer = ( int8_t * ) pvPortMalloc( sizeof( Queue_t ) + xQueueSizeInBytes );
+
+	if( pcAllocatedBuffer != NULL )
+	{
+		pxNewQueue = ( Queue_t * ) pcAllocatedBuffer; /*lint !e826 MISRA The buffer cannot be too small because it was dimensioned by sizeof( Queue_t ) + xQueueSizeInBytes. */
+
+		if( uxItemSize == ( UBaseType_t ) 0 )
+		{
+			/* No RAM was allocated for the queue storage area, but PC head
+			cannot be set to NULL because NULL is used as a key to say the queue
+			is used as a mutex.  Therefore just set pcHead to point to the queue
+			as a benign value that is known to be within the memory map. */
+			pxNewQueue->pcHead = ( int8_t * ) pxNewQueue;
+		}
+		else
+		{
+			/* Jump past the queue structure to find the location of the queue
+			storage area - adding the padding bytes to get a better alignment. */
+			pxNewQueue->pcHead = pcAllocatedBuffer + sizeof( Queue_t );
+		}
+
+		/* Initialise the queue members as described above where the queue type
+		is defined. */
+		pxNewQueue->uxLength = uxQueueLength;
+		pxNewQueue->uxItemSize = uxItemSize;
+		( void ) xQueueGenericReset( pxNewQueue, pdTRUE );
+
+		#if ( configUSE_TRACE_FACILITY == 1 )
+		{
+			pxNewQueue->ucQueueType = ucQueueType;
+		}
+		#endif /* configUSE_TRACE_FACILITY */
+
+		#if( configUSE_QUEUE_SETS == 1 )
+		{
+			pxNewQueue->pxQueueSetContainer = NULL;
+		}
+		#endif /* configUSE_QUEUE_SETS */
+
+		traceQUEUE_CREATE( pxNewQueue );
+		xReturn = pxNewQueue;
+	}
+	else
+	{
+		mtCOVERAGE_TEST_MARKER();
+	}
+
+	configASSERT( xReturn );
+
+	return xReturn;
+}
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_MUTEXES == 1 )
+
+	QueueHandle_t xQueueCreateMutex( const uint8_t ucQueueType )
+	{
+	Queue_t *pxNewQueue;
+
+		/* Prevent compiler warnings about unused parameters if
+		configUSE_TRACE_FACILITY does not equal 1. */
+		( void ) ucQueueType;
+
+		/* Allocate the new queue structure. */
+		pxNewQueue = ( Queue_t * ) pvPortMalloc( sizeof( Queue_t ) );
+		if( pxNewQueue != NULL )
+		{
+			/* Information required for priority inheritance. */
+			pxNewQueue->pxMutexHolder = NULL;
+			pxNewQueue->uxQueueType = queueQUEUE_IS_MUTEX;
+
+			/* Queues used as a mutex no data is actually copied into or out
+			of the queue. */
+			pxNewQueue->pcWriteTo = NULL;
+			pxNewQueue->u.pcReadFrom = NULL;
+
+			/* Each mutex has a length of 1 (like a binary semaphore) and
+			an item size of 0 as nothing is actually copied into or out
+			of the mutex. */
+			pxNewQueue->uxMessagesWaiting = ( UBaseType_t ) 0U;
+			pxNewQueue->uxLength = ( UBaseType_t ) 1U;
+			pxNewQueue->uxItemSize = ( UBaseType_t ) 0U;
+			pxNewQueue->xRxLock = queueUNLOCKED;
+			pxNewQueue->xTxLock = queueUNLOCKED;
+
+			#if ( configUSE_TRACE_FACILITY == 1 )
+			{
+				pxNewQueue->ucQueueType = ucQueueType;
+			}
+			#endif
+
+			#if ( configUSE_QUEUE_SETS == 1 )
+			{
+				pxNewQueue->pxQueueSetContainer = NULL;
+			}
+			#endif
+
+			/* Ensure the event queues start with the correct state. */
+			vListInitialise( &( pxNewQueue->xTasksWaitingToSend ) );
+			vListInitialise( &( pxNewQueue->xTasksWaitingToReceive ) );
+
+			traceCREATE_MUTEX( pxNewQueue );
+
+			/* Start with the semaphore in the expected state. */
+			( void ) xQueueGenericSend( pxNewQueue, NULL, ( TickType_t ) 0U, queueSEND_TO_BACK );
+		}
+		else
+		{
+			traceCREATE_MUTEX_FAILED();
+		}
+
+		configASSERT( pxNewQueue );
+		return pxNewQueue;
+	}
+
+#endif /* configUSE_MUTEXES */
+/*-----------------------------------------------------------*/
+
+#if ( ( configUSE_MUTEXES == 1 ) && ( INCLUDE_xSemaphoreGetMutexHolder == 1 ) )
+
+	void* xQueueGetMutexHolder( QueueHandle_t xSemaphore )
+	{
+	void *pxReturn;
+
+		/* This function is called by xSemaphoreGetMutexHolder(), and should not
+		be called directly.  Note:  This is a good way of determining if the
+		calling task is the mutex holder, but not a good way of determining the
+		identity of the mutex holder, as the holder may change between the
+		following critical section exiting and the function returning. */
+		taskENTER_CRITICAL();
+		{
+			if( ( ( Queue_t * ) xSemaphore )->uxQueueType == queueQUEUE_IS_MUTEX )
+			{
+				pxReturn = ( void * ) ( ( Queue_t * ) xSemaphore )->pxMutexHolder;
+			}
+			else
+			{
+				pxReturn = NULL;
+			}
+		}
+		taskEXIT_CRITICAL();
+
+		return pxReturn;
+	} /*lint !e818 xSemaphore cannot be a pointer to const because it is a typedef. */
+
+#endif
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_RECURSIVE_MUTEXES == 1 )
+
+	BaseType_t xQueueGiveMutexRecursive( QueueHandle_t xMutex )
+	{
+	BaseType_t xReturn;
+	Queue_t * const pxMutex = ( Queue_t * ) xMutex;
+
+		configASSERT( pxMutex );
+
+		/* If this is the task that holds the mutex then pxMutexHolder will not
+		change outside of this task.  If this task does not hold the mutex then
+		pxMutexHolder can never coincidentally equal the tasks handle, and as
+		this is the only condition we are interested in it does not matter if
+		pxMutexHolder is accessed simultaneously by another task.  Therefore no
+		mutual exclusion is required to test the pxMutexHolder variable. */
+		if( pxMutex->pxMutexHolder == ( void * ) xTaskGetCurrentTaskHandle() ) /*lint !e961 Not a redundant cast as TaskHandle_t is a typedef. */
+		{
+			traceGIVE_MUTEX_RECURSIVE( pxMutex );
+
+			/* uxRecursiveCallCount cannot be zero if pxMutexHolder is equal to
+			the task handle, therefore no underflow check is required.  Also,
+			uxRecursiveCallCount is only modified by the mutex holder, and as
+			there can only be one, no mutual exclusion is required to modify the
+			uxRecursiveCallCount member. */
+			( pxMutex->u.uxRecursiveCallCount )--;
+
+			/* Have we unwound the call count? */
+			if( pxMutex->u.uxRecursiveCallCount == ( UBaseType_t ) 0 )
+			{
+				/* Return the mutex.  This will automatically unblock any other
+				task that might be waiting to access the mutex. */
+				( void ) xQueueGenericSend( pxMutex, NULL, queueMUTEX_GIVE_BLOCK_TIME, queueSEND_TO_BACK );
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+
+			xReturn = pdPASS;
+		}
+		else
+		{
+			/* The mutex cannot be given because the calling task is not the
+			holder. */
+			xReturn = pdFAIL;
+
+			traceGIVE_MUTEX_RECURSIVE_FAILED( pxMutex );
+		}
+
+		return xReturn;
+	}
+
+#endif /* configUSE_RECURSIVE_MUTEXES */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_RECURSIVE_MUTEXES == 1 )
+
+	BaseType_t xQueueTakeMutexRecursive( QueueHandle_t xMutex, TickType_t xTicksToWait )
+	{
+	BaseType_t xReturn;
+	Queue_t * const pxMutex = ( Queue_t * ) xMutex;
+
+		configASSERT( pxMutex );
+
+		/* Comments regarding mutual exclusion as per those within
+		xQueueGiveMutexRecursive(). */
+
+		traceTAKE_MUTEX_RECURSIVE( pxMutex );
+
+		if( pxMutex->pxMutexHolder == ( void * ) xTaskGetCurrentTaskHandle() ) /*lint !e961 Cast is not redundant as TaskHandle_t is a typedef. */
+		{
+			( pxMutex->u.uxRecursiveCallCount )++;
+			xReturn = pdPASS;
+		}
+		else
+		{
+			xReturn = xQueueGenericReceive( pxMutex, NULL, xTicksToWait, pdFALSE );
+
+			/* pdPASS will only be returned if the mutex was successfully
+			obtained.  The calling task may have entered the Blocked state
+			before reaching here. */
+			if( xReturn == pdPASS )
+			{
+				( pxMutex->u.uxRecursiveCallCount )++;
+			}
+			else
+			{
+				traceTAKE_MUTEX_RECURSIVE_FAILED( pxMutex );
+			}
+		}
+
+		return xReturn;
+	}
+
+#endif /* configUSE_RECURSIVE_MUTEXES */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_COUNTING_SEMAPHORES == 1 )
+
+	QueueHandle_t xQueueCreateCountingSemaphore( const UBaseType_t uxMaxCount, const UBaseType_t uxInitialCount )
+	{
+	QueueHandle_t xHandle;
+
+		configASSERT( uxMaxCount != 0 );
+		configASSERT( uxInitialCount <= uxMaxCount );
+
+		xHandle = xQueueGenericCreate( uxMaxCount, queueSEMAPHORE_QUEUE_ITEM_LENGTH, queueQUEUE_TYPE_COUNTING_SEMAPHORE );
+
+		if( xHandle != NULL )
+		{
+			( ( Queue_t * ) xHandle )->uxMessagesWaiting = uxInitialCount;
+
+			traceCREATE_COUNTING_SEMAPHORE();
+		}
+		else
+		{
+			traceCREATE_COUNTING_SEMAPHORE_FAILED();
+		}
+
+		configASSERT( xHandle );
+		return xHandle;
+	}
+
+#endif /* configUSE_COUNTING_SEMAPHORES */
+/*-----------------------------------------------------------*/
+
+BaseType_t xQueueGenericSend( QueueHandle_t xQueue, const void * const pvItemToQueue, TickType_t xTicksToWait, const BaseType_t xCopyPosition )
+{
+BaseType_t xEntryTimeSet = pdFALSE, xYieldRequired;
+TimeOut_t xTimeOut;
+Queue_t * const pxQueue = ( Queue_t * ) xQueue;
+
+	configASSERT( pxQueue );
+	configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) );
+	configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) );
+	#if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) )
+	{
+		configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) );
+	}
+	#endif
+
+
+	/* This function relaxes the coding standard somewhat to allow return
+	statements within the function itself.  This is done in the interest
+	of execution time efficiency. */
+	for( ;; )
+	{
+		taskENTER_CRITICAL();
+		{
+			/* Is there room on the queue now?  The running task must be the
+			highest priority task wanting to access the queue.  If the head item
+			in the queue is to be overwritten then it does not matter if the
+			queue is full. */
+			if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) )
+			{
+				traceQUEUE_SEND( pxQueue );
+				xYieldRequired = prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition );
+
+				#if ( configUSE_QUEUE_SETS == 1 )
+				{
+					if( pxQueue->pxQueueSetContainer != NULL )
+					{
+						if( prvNotifyQueueSetContainer( pxQueue, xCopyPosition ) == pdTRUE )
+						{
+							/* The queue is a member of a queue set, and posting
+							to the queue set caused a higher priority task to
+							unblock. A context switch is required. */
+							queueYIELD_IF_USING_PREEMPTION();
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+					}
+					else
+					{
+						/* If there was a task waiting for data to arrive on the
+						queue then unblock it now. */
+						if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
+						{
+							if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) == pdTRUE )
+							{
+								/* The unblocked task has a priority higher than
+								our own so yield immediately.  Yes it is ok to
+								do this from within the critical section - the
+								kernel takes care of that. */
+								queueYIELD_IF_USING_PREEMPTION();
+							}
+							else
+							{
+								mtCOVERAGE_TEST_MARKER();
+							}
+						}
+						else if( xYieldRequired != pdFALSE )
+						{
+							/* This path is a special case that will only get
+							executed if the task was holding multiple mutexes
+							and the mutexes were given back in an order that is
+							different to that in which they were taken. */
+							queueYIELD_IF_USING_PREEMPTION();
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+					}
+				}
+				#else /* configUSE_QUEUE_SETS */
+				{
+					/* If there was a task waiting for data to arrive on the
+					queue then unblock it now. */
+					if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
+					{
+						if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) == pdTRUE )
+						{
+							/* The unblocked task has a priority higher than
+							our own so yield immediately.  Yes it is ok to do
+							this from within the critical section - the kernel
+							takes care of that. */
+							queueYIELD_IF_USING_PREEMPTION();
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+					}
+					else if( xYieldRequired != pdFALSE )
+					{
+						/* This path is a special case that will only get
+						executed if the task was holding multiple mutexes and
+						the mutexes were given back in an order that is
+						different to that in which they were taken. */
+						queueYIELD_IF_USING_PREEMPTION();
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				#endif /* configUSE_QUEUE_SETS */
+
+				taskEXIT_CRITICAL();
+				return pdPASS;
+			}
+			else
+			{
+				if( xTicksToWait == ( TickType_t ) 0 )
+				{
+					/* The queue was full and no block time is specified (or
+					the block time has expired) so leave now. */
+					taskEXIT_CRITICAL();
+
+					/* Return to the original privilege level before exiting
+					the function. */
+					traceQUEUE_SEND_FAILED( pxQueue );
+					return errQUEUE_FULL;
+				}
+				else if( xEntryTimeSet == pdFALSE )
+				{
+					/* The queue was full and a block time was specified so
+					configure the timeout structure. */
+					vTaskSetTimeOutState( &xTimeOut );
+					xEntryTimeSet = pdTRUE;
+				}
+				else
+				{
+					/* Entry time was already set. */
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+		}
+		taskEXIT_CRITICAL();
+
+		/* Interrupts and other tasks can send to and receive from the queue
+		now the critical section has been exited. */
+
+		vTaskSuspendAll();
+		prvLockQueue( pxQueue );
+
+		/* Update the timeout state to see if it has expired yet. */
+		if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE )
+		{
+			if( prvIsQueueFull( pxQueue ) != pdFALSE )
+			{
+				traceBLOCKING_ON_QUEUE_SEND( pxQueue );
+				vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToSend ), xTicksToWait );
+
+				/* Unlocking the queue means queue events can effect the
+				event list.  It is possible	that interrupts occurring now
+				remove this task from the event	list again - but as the
+				scheduler is suspended the task will go onto the pending
+				ready last instead of the actual ready list. */
+				prvUnlockQueue( pxQueue );
+
+				/* Resuming the scheduler will move tasks from the pending
+				ready list into the ready list - so it is feasible that this
+				task is already in a ready list before it yields - in which
+				case the yield will not cause a context switch unless there
+				is also a higher priority task in the pending ready list. */
+				if( xTaskResumeAll() == pdFALSE )
+				{
+					portYIELD_WITHIN_API();
+				}
+			}
+			else
+			{
+				/* Try again. */
+				prvUnlockQueue( pxQueue );
+				( void ) xTaskResumeAll();
+			}
+		}
+		else
+		{
+			/* The timeout has expired. */
+			prvUnlockQueue( pxQueue );
+			( void ) xTaskResumeAll();
+
+			/* Return to the original privilege level before exiting the
+			function. */
+			traceQUEUE_SEND_FAILED( pxQueue );
+			return errQUEUE_FULL;
+		}
+	}
+}
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_ALTERNATIVE_API == 1 )
+
+	BaseType_t xQueueAltGenericSend( QueueHandle_t xQueue, const void * const pvItemToQueue, TickType_t xTicksToWait, BaseType_t xCopyPosition )
+	{
+	BaseType_t xEntryTimeSet = pdFALSE;
+	TimeOut_t xTimeOut;
+	Queue_t * const pxQueue = ( Queue_t * ) xQueue;
+
+		configASSERT( pxQueue );
+		configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) );
+
+		for( ;; )
+		{
+			taskENTER_CRITICAL();
+			{
+				/* Is there room on the queue now?  To be running we must be
+				the highest priority task wanting to access the queue. */
+				if( pxQueue->uxMessagesWaiting < pxQueue->uxLength )
+				{
+					traceQUEUE_SEND( pxQueue );
+					prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition );
+
+					/* If there was a task waiting for data to arrive on the
+					queue then unblock it now. */
+					if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
+					{
+						if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) == pdTRUE )
+						{
+							/* The unblocked task has a priority higher than
+							our own so yield immediately. */
+							portYIELD_WITHIN_API();
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+
+					taskEXIT_CRITICAL();
+					return pdPASS;
+				}
+				else
+				{
+					if( xTicksToWait == ( TickType_t ) 0 )
+					{
+						taskEXIT_CRITICAL();
+						return errQUEUE_FULL;
+					}
+					else if( xEntryTimeSet == pdFALSE )
+					{
+						vTaskSetTimeOutState( &xTimeOut );
+						xEntryTimeSet = pdTRUE;
+					}
+				}
+			}
+			taskEXIT_CRITICAL();
+
+			taskENTER_CRITICAL();
+			{
+				if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE )
+				{
+					if( prvIsQueueFull( pxQueue ) != pdFALSE )
+					{
+						traceBLOCKING_ON_QUEUE_SEND( pxQueue );
+						vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToSend ), xTicksToWait );
+						portYIELD_WITHIN_API();
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				else
+				{
+					taskEXIT_CRITICAL();
+					traceQUEUE_SEND_FAILED( pxQueue );
+					return errQUEUE_FULL;
+				}
+			}
+			taskEXIT_CRITICAL();
+		}
+	}
+
+#endif /* configUSE_ALTERNATIVE_API */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_ALTERNATIVE_API == 1 )
+
+	BaseType_t xQueueAltGenericReceive( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait, BaseType_t xJustPeeking )
+	{
+	BaseType_t xEntryTimeSet = pdFALSE;
+	TimeOut_t xTimeOut;
+	int8_t *pcOriginalReadPosition;
+	Queue_t * const pxQueue = ( Queue_t * ) xQueue;
+
+		configASSERT( pxQueue );
+		configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) );
+
+		for( ;; )
+		{
+			taskENTER_CRITICAL();
+			{
+				if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 )
+				{
+					/* Remember our read position in case we are just peeking. */
+					pcOriginalReadPosition = pxQueue->u.pcReadFrom;
+
+					prvCopyDataFromQueue( pxQueue, pvBuffer );
+
+					if( xJustPeeking == pdFALSE )
+					{
+						traceQUEUE_RECEIVE( pxQueue );
+
+						/* Data is actually being removed (not just peeked). */
+						--( pxQueue->uxMessagesWaiting );
+
+						#if ( configUSE_MUTEXES == 1 )
+						{
+							if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX )
+							{
+								/* Record the information required to implement
+								priority inheritance should it become necessary. */
+								pxQueue->pxMutexHolder = ( int8_t * ) xTaskGetCurrentTaskHandle();
+							}
+							else
+							{
+								mtCOVERAGE_TEST_MARKER();
+							}
+						}
+						#endif
+
+						if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE )
+						{
+							if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) == pdTRUE )
+							{
+								portYIELD_WITHIN_API();
+							}
+							else
+							{
+								mtCOVERAGE_TEST_MARKER();
+							}
+						}
+					}
+					else
+					{
+						traceQUEUE_PEEK( pxQueue );
+
+						/* The data is not being removed, so reset our read
+						pointer. */
+						pxQueue->u.pcReadFrom = pcOriginalReadPosition;
+
+						/* The data is being left in the queue, so see if there are
+						any other tasks waiting for the data. */
+						if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
+						{
+							/* Tasks that are removed from the event list will get added to
+							the pending ready list as the scheduler is still suspended. */
+							if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
+							{
+								/* The task waiting has a higher priority than this task. */
+								portYIELD_WITHIN_API();
+							}
+							else
+							{
+								mtCOVERAGE_TEST_MARKER();
+							}
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+					}
+
+					taskEXIT_CRITICAL();
+					return pdPASS;
+				}
+				else
+				{
+					if( xTicksToWait == ( TickType_t ) 0 )
+					{
+						taskEXIT_CRITICAL();
+						traceQUEUE_RECEIVE_FAILED( pxQueue );
+						return errQUEUE_EMPTY;
+					}
+					else if( xEntryTimeSet == pdFALSE )
+					{
+						vTaskSetTimeOutState( &xTimeOut );
+						xEntryTimeSet = pdTRUE;
+					}
+				}
+			}
+			taskEXIT_CRITICAL();
+
+			taskENTER_CRITICAL();
+			{
+				if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE )
+				{
+					if( prvIsQueueEmpty( pxQueue ) != pdFALSE )
+					{
+						traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue );
+
+						#if ( configUSE_MUTEXES == 1 )
+						{
+							if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX )
+							{
+								taskENTER_CRITICAL();
+								{
+									vTaskPriorityInherit( ( void * ) pxQueue->pxMutexHolder );
+								}
+								taskEXIT_CRITICAL();
+							}
+							else
+							{
+								mtCOVERAGE_TEST_MARKER();
+							}
+						}
+						#endif
+
+						vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait );
+						portYIELD_WITHIN_API();
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				else
+				{
+					taskEXIT_CRITICAL();
+					traceQUEUE_RECEIVE_FAILED( pxQueue );
+					return errQUEUE_EMPTY;
+				}
+			}
+			taskEXIT_CRITICAL();
+		}
+	}
+
+
+#endif /* configUSE_ALTERNATIVE_API */
+/*-----------------------------------------------------------*/
+
+BaseType_t xQueueGenericSendFromISR( QueueHandle_t xQueue, const void * const pvItemToQueue, BaseType_t * const pxHigherPriorityTaskWoken, const BaseType_t xCopyPosition )
+{
+BaseType_t xReturn;
+UBaseType_t uxSavedInterruptStatus;
+Queue_t * const pxQueue = ( Queue_t * ) xQueue;
+
+	configASSERT( pxQueue );
+	configASSERT( !( ( pvItemToQueue == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) );
+	configASSERT( !( ( xCopyPosition == queueOVERWRITE ) && ( pxQueue->uxLength != 1 ) ) );
+
+	/* RTOS ports that support interrupt nesting have the concept of a maximum
+	system call (or maximum API call) interrupt priority.  Interrupts that are
+	above the maximum system call priority are kept permanently enabled, even
+	when the RTOS kernel is in a critical section, but cannot make any calls to
+	FreeRTOS API functions.  If configASSERT() is defined in FreeRTOSConfig.h
+	then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
+	failure if a FreeRTOS API function is called from an interrupt that has been
+	assigned a priority above the configured maximum system call priority.
+	Only FreeRTOS functions that end in FromISR can be called from interrupts
+	that have been assigned a priority at or (logically) below the maximum
+	system call	interrupt priority.  FreeRTOS maintains a separate interrupt
+	safe API to ensure interrupt entry is as fast and as simple as possible.
+	More information (albeit Cortex-M specific) is provided on the following
+	link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */
+	portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+	/* Similar to xQueueGenericSend, except without blocking if there is no room
+	in the queue.  Also don't directly wake a task that was blocked on a queue
+	read, instead return a flag to say whether a context switch is required or
+	not (i.e. has a task with a higher priority than us been woken by this
+	post). */
+	uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
+	{
+		if( ( pxQueue->uxMessagesWaiting < pxQueue->uxLength ) || ( xCopyPosition == queueOVERWRITE ) )
+		{
+			traceQUEUE_SEND_FROM_ISR( pxQueue );
+
+			/* Semaphores use xQueueGiveFromISR(), so pxQueue will not be a
+			semaphore or mutex.  That means prvCopyDataToQueue() cannot result
+			in a task disinheriting a priority and prvCopyDataToQueue() can be
+			called here even though the disinherit function does not check if
+			the scheduler is suspended before accessing the ready lists. */
+			( void ) prvCopyDataToQueue( pxQueue, pvItemToQueue, xCopyPosition );
+
+			/* The event list is not altered if the queue is locked.  This will
+			be done when the queue is unlocked later. */
+			if( pxQueue->xTxLock == queueUNLOCKED )
+			{
+				#if ( configUSE_QUEUE_SETS == 1 )
+				{
+					if( pxQueue->pxQueueSetContainer != NULL )
+					{
+						if( prvNotifyQueueSetContainer( pxQueue, xCopyPosition ) == pdTRUE )
+						{
+							/* The queue is a member of a queue set, and posting
+							to the queue set caused a higher priority task to
+							unblock.  A context switch is required. */
+							if( pxHigherPriorityTaskWoken != NULL )
+							{
+								*pxHigherPriorityTaskWoken = pdTRUE;
+							}
+							else
+							{
+								mtCOVERAGE_TEST_MARKER();
+							}
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+					}
+					else
+					{
+						if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
+						{
+							if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
+							{
+								/* The task waiting has a higher priority so
+								record that a context switch is required. */
+								if( pxHigherPriorityTaskWoken != NULL )
+								{
+									*pxHigherPriorityTaskWoken = pdTRUE;
+								}
+								else
+								{
+									mtCOVERAGE_TEST_MARKER();
+								}
+							}
+							else
+							{
+								mtCOVERAGE_TEST_MARKER();
+							}
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+					}
+				}
+				#else /* configUSE_QUEUE_SETS */
+				{
+					if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
+					{
+						if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
+						{
+							/* The task waiting has a higher priority so record that a
+							context	switch is required. */
+							if( pxHigherPriorityTaskWoken != NULL )
+							{
+								*pxHigherPriorityTaskWoken = pdTRUE;
+							}
+							else
+							{
+								mtCOVERAGE_TEST_MARKER();
+							}
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				#endif /* configUSE_QUEUE_SETS */
+			}
+			else
+			{
+				/* Increment the lock count so the task that unlocks the queue
+				knows that data was posted while it was locked. */
+				++( pxQueue->xTxLock );
+			}
+
+			xReturn = pdPASS;
+		}
+		else
+		{
+			traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue );
+			xReturn = errQUEUE_FULL;
+		}
+	}
+	portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
+
+	return xReturn;
+}
+/*-----------------------------------------------------------*/
+
+BaseType_t xQueueGiveFromISR( QueueHandle_t xQueue, BaseType_t * const pxHigherPriorityTaskWoken )
+{
+BaseType_t xReturn;
+UBaseType_t uxSavedInterruptStatus;
+Queue_t * const pxQueue = ( Queue_t * ) xQueue;
+
+	/* Similar to xQueueGenericSendFromISR() but used with semaphores where the
+	item size is 0.  Don't directly wake a task that was blocked on a queue
+	read, instead return a flag to say whether a context switch is required or
+	not (i.e. has a task with a higher priority than us been woken by this
+	post). */
+
+	configASSERT( pxQueue );
+
+	/* xQueueGenericSendFromISR() should be used instead of xQueueGiveFromISR()
+	if the item size is not 0. */
+	configASSERT( pxQueue->uxItemSize == 0 );
+
+	/* Normally a mutex would not be given from an interrupt, and doing so is
+	definitely wrong if there is a mutex holder as priority inheritance makes no
+	sense for an interrupts, only tasks. */
+	configASSERT( !( ( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX ) && ( pxQueue->pxMutexHolder != NULL ) ) );
+
+	/* RTOS ports that support interrupt nesting have the concept of a maximum
+	system call (or maximum API call) interrupt priority.  Interrupts that are
+	above the maximum system call priority are kept permanently enabled, even
+	when the RTOS kernel is in a critical section, but cannot make any calls to
+	FreeRTOS API functions.  If configASSERT() is defined in FreeRTOSConfig.h
+	then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
+	failure if a FreeRTOS API function is called from an interrupt that has been
+	assigned a priority above the configured maximum system call priority.
+	Only FreeRTOS functions that end in FromISR can be called from interrupts
+	that have been assigned a priority at or (logically) below the maximum
+	system call	interrupt priority.  FreeRTOS maintains a separate interrupt
+	safe API to ensure interrupt entry is as fast and as simple as possible.
+	More information (albeit Cortex-M specific) is provided on the following
+	link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */
+	portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+	uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
+	{
+		/* When the queue is used to implement a semaphore no data is ever
+		moved through the queue but it is still valid to see if the queue 'has
+		space'. */
+		if( pxQueue->uxMessagesWaiting < pxQueue->uxLength )
+		{
+			traceQUEUE_SEND_FROM_ISR( pxQueue );
+
+			/* A task can only have an inherited priority if it is a mutex
+			holder - and if there is a mutex holder then the mutex cannot be
+			given from an ISR.  As this is the ISR version of the function it
+			can be assumed there is no mutex holder and no need to determine if
+			priority disinheritance is needed.  Simply increase the count of
+			messages (semaphores) available. */
+			++( pxQueue->uxMessagesWaiting );
+
+			/* The event list is not altered if the queue is locked.  This will
+			be done when the queue is unlocked later. */
+			if( pxQueue->xTxLock == queueUNLOCKED )
+			{
+				#if ( configUSE_QUEUE_SETS == 1 )
+				{
+					if( pxQueue->pxQueueSetContainer != NULL )
+					{
+						if( prvNotifyQueueSetContainer( pxQueue, queueSEND_TO_BACK ) == pdTRUE )
+						{
+							/* The semaphore is a member of a queue set, and
+							posting	to the queue set caused a higher priority
+							task to	unblock.  A context switch is required. */
+							if( pxHigherPriorityTaskWoken != NULL )
+							{
+								*pxHigherPriorityTaskWoken = pdTRUE;
+							}
+							else
+							{
+								mtCOVERAGE_TEST_MARKER();
+							}
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+					}
+					else
+					{
+						if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
+						{
+							if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
+							{
+								/* The task waiting has a higher priority so
+								record that a context switch is required. */
+								if( pxHigherPriorityTaskWoken != NULL )
+								{
+									*pxHigherPriorityTaskWoken = pdTRUE;
+								}
+								else
+								{
+									mtCOVERAGE_TEST_MARKER();
+								}
+							}
+							else
+							{
+								mtCOVERAGE_TEST_MARKER();
+							}
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+					}
+				}
+				#else /* configUSE_QUEUE_SETS */
+				{
+					if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
+					{
+						if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
+						{
+							/* The task waiting has a higher priority so record that a
+							context	switch is required. */
+							if( pxHigherPriorityTaskWoken != NULL )
+							{
+								*pxHigherPriorityTaskWoken = pdTRUE;
+							}
+							else
+							{
+								mtCOVERAGE_TEST_MARKER();
+							}
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				#endif /* configUSE_QUEUE_SETS */
+			}
+			else
+			{
+				/* Increment the lock count so the task that unlocks the queue
+				knows that data was posted while it was locked. */
+				++( pxQueue->xTxLock );
+			}
+
+			xReturn = pdPASS;
+		}
+		else
+		{
+			traceQUEUE_SEND_FROM_ISR_FAILED( pxQueue );
+			xReturn = errQUEUE_FULL;
+		}
+	}
+	portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
+
+	return xReturn;
+}
+/*-----------------------------------------------------------*/
+
+BaseType_t xQueueGenericReceive( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait, const BaseType_t xJustPeeking )
+{
+BaseType_t xEntryTimeSet = pdFALSE;
+TimeOut_t xTimeOut;
+int8_t *pcOriginalReadPosition;
+Queue_t * const pxQueue = ( Queue_t * ) xQueue;
+
+	configASSERT( pxQueue );
+	configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) );
+	#if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) )
+	{
+		configASSERT( !( ( xTaskGetSchedulerState() == taskSCHEDULER_SUSPENDED ) && ( xTicksToWait != 0 ) ) );
+	}
+	#endif
+
+	/* This function relaxes the coding standard somewhat to allow return
+	statements within the function itself.  This is done in the interest
+	of execution time efficiency. */
+
+	for( ;; )
+	{
+		taskENTER_CRITICAL();
+		{
+			/* Is there data in the queue now?  To be running the calling task
+			must be	the highest priority task wanting to access the queue. */
+			if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 )
+			{
+				/* Remember the read position in case the queue is only being
+				peeked. */
+				pcOriginalReadPosition = pxQueue->u.pcReadFrom;
+
+				prvCopyDataFromQueue( pxQueue, pvBuffer );
+
+				if( xJustPeeking == pdFALSE )
+				{
+					traceQUEUE_RECEIVE( pxQueue );
+
+					/* Actually removing data, not just peeking. */
+					--( pxQueue->uxMessagesWaiting );
+
+					#if ( configUSE_MUTEXES == 1 )
+					{
+						if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX )
+						{
+							/* Record the information required to implement
+							priority inheritance should it become necessary. */
+							pxQueue->pxMutexHolder = ( int8_t * ) pvTaskIncrementMutexHeldCount(); /*lint !e961 Cast is not redundant as TaskHandle_t is a typedef. */
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+					}
+					#endif /* configUSE_MUTEXES */
+
+					if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE )
+					{
+						if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) == pdTRUE )
+						{
+							queueYIELD_IF_USING_PREEMPTION();
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				else
+				{
+					traceQUEUE_PEEK( pxQueue );
+
+					/* The data is not being removed, so reset the read
+					pointer. */
+					pxQueue->u.pcReadFrom = pcOriginalReadPosition;
+
+					/* The data is being left in the queue, so see if there are
+					any other tasks waiting for the data. */
+					if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
+					{
+						if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
+						{
+							/* The task waiting has a higher priority than this task. */
+							queueYIELD_IF_USING_PREEMPTION();
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+
+				taskEXIT_CRITICAL();
+				return pdPASS;
+			}
+			else
+			{
+				if( xTicksToWait == ( TickType_t ) 0 )
+				{
+					/* The queue was empty and no block time is specified (or
+					the block time has expired) so leave now. */
+					taskEXIT_CRITICAL();
+					traceQUEUE_RECEIVE_FAILED( pxQueue );
+					return errQUEUE_EMPTY;
+				}
+				else if( xEntryTimeSet == pdFALSE )
+				{
+					/* The queue was empty and a block time was specified so
+					configure the timeout structure. */
+					vTaskSetTimeOutState( &xTimeOut );
+					xEntryTimeSet = pdTRUE;
+				}
+				else
+				{
+					/* Entry time was already set. */
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+		}
+		taskEXIT_CRITICAL();
+
+		/* Interrupts and other tasks can send to and receive from the queue
+		now the critical section has been exited. */
+
+		vTaskSuspendAll();
+		prvLockQueue( pxQueue );
+
+		/* Update the timeout state to see if it has expired yet. */
+		if( xTaskCheckForTimeOut( &xTimeOut, &xTicksToWait ) == pdFALSE )
+		{
+			if( prvIsQueueEmpty( pxQueue ) != pdFALSE )
+			{
+				traceBLOCKING_ON_QUEUE_RECEIVE( pxQueue );
+
+				#if ( configUSE_MUTEXES == 1 )
+				{
+					if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX )
+					{
+						taskENTER_CRITICAL();
+						{
+							vTaskPriorityInherit( ( void * ) pxQueue->pxMutexHolder );
+						}
+						taskEXIT_CRITICAL();
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				#endif
+
+				vTaskPlaceOnEventList( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait );
+				prvUnlockQueue( pxQueue );
+				if( xTaskResumeAll() == pdFALSE )
+				{
+					portYIELD_WITHIN_API();
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			else
+			{
+				/* Try again. */
+				prvUnlockQueue( pxQueue );
+				( void ) xTaskResumeAll();
+			}
+		}
+		else
+		{
+			prvUnlockQueue( pxQueue );
+			( void ) xTaskResumeAll();
+			traceQUEUE_RECEIVE_FAILED( pxQueue );
+			return errQUEUE_EMPTY;
+		}
+	}
+}
+/*-----------------------------------------------------------*/
+
+BaseType_t xQueueReceiveFromISR( QueueHandle_t xQueue, void * const pvBuffer, BaseType_t * const pxHigherPriorityTaskWoken )
+{
+BaseType_t xReturn;
+UBaseType_t uxSavedInterruptStatus;
+Queue_t * const pxQueue = ( Queue_t * ) xQueue;
+
+	configASSERT( pxQueue );
+	configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) );
+
+	/* RTOS ports that support interrupt nesting have the concept of a maximum
+	system call (or maximum API call) interrupt priority.  Interrupts that are
+	above the maximum system call priority are kept permanently enabled, even
+	when the RTOS kernel is in a critical section, but cannot make any calls to
+	FreeRTOS API functions.  If configASSERT() is defined in FreeRTOSConfig.h
+	then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
+	failure if a FreeRTOS API function is called from an interrupt that has been
+	assigned a priority above the configured maximum system call priority.
+	Only FreeRTOS functions that end in FromISR can be called from interrupts
+	that have been assigned a priority at or (logically) below the maximum
+	system call	interrupt priority.  FreeRTOS maintains a separate interrupt
+	safe API to ensure interrupt entry is as fast and as simple as possible.
+	More information (albeit Cortex-M specific) is provided on the following
+	link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */
+	portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+	uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
+	{
+		/* Cannot block in an ISR, so check there is data available. */
+		if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 )
+		{
+			traceQUEUE_RECEIVE_FROM_ISR( pxQueue );
+
+			prvCopyDataFromQueue( pxQueue, pvBuffer );
+			--( pxQueue->uxMessagesWaiting );
+
+			/* If the queue is locked the event list will not be modified.
+			Instead update the lock count so the task that unlocks the queue
+			will know that an ISR has removed data while the queue was
+			locked. */
+			if( pxQueue->xRxLock == queueUNLOCKED )
+			{
+				if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE )
+				{
+					if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE )
+					{
+						/* The task waiting has a higher priority than us so
+						force a context switch. */
+						if( pxHigherPriorityTaskWoken != NULL )
+						{
+							*pxHigherPriorityTaskWoken = pdTRUE;
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			else
+			{
+				/* Increment the lock count so the task that unlocks the queue
+				knows that data was removed while it was locked. */
+				++( pxQueue->xRxLock );
+			}
+
+			xReturn = pdPASS;
+		}
+		else
+		{
+			xReturn = pdFAIL;
+			traceQUEUE_RECEIVE_FROM_ISR_FAILED( pxQueue );
+		}
+	}
+	portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
+
+	return xReturn;
+}
+/*-----------------------------------------------------------*/
+
+BaseType_t xQueuePeekFromISR( QueueHandle_t xQueue,  void * const pvBuffer )
+{
+BaseType_t xReturn;
+UBaseType_t uxSavedInterruptStatus;
+int8_t *pcOriginalReadPosition;
+Queue_t * const pxQueue = ( Queue_t * ) xQueue;
+
+	configASSERT( pxQueue );
+	configASSERT( !( ( pvBuffer == NULL ) && ( pxQueue->uxItemSize != ( UBaseType_t ) 0U ) ) );
+	configASSERT( pxQueue->uxItemSize != 0 ); /* Can't peek a semaphore. */
+
+	/* RTOS ports that support interrupt nesting have the concept of a maximum
+	system call (or maximum API call) interrupt priority.  Interrupts that are
+	above the maximum system call priority are kept permanently enabled, even
+	when the RTOS kernel is in a critical section, but cannot make any calls to
+	FreeRTOS API functions.  If configASSERT() is defined in FreeRTOSConfig.h
+	then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
+	failure if a FreeRTOS API function is called from an interrupt that has been
+	assigned a priority above the configured maximum system call priority.
+	Only FreeRTOS functions that end in FromISR can be called from interrupts
+	that have been assigned a priority at or (logically) below the maximum
+	system call	interrupt priority.  FreeRTOS maintains a separate interrupt
+	safe API to ensure interrupt entry is as fast and as simple as possible.
+	More information (albeit Cortex-M specific) is provided on the following
+	link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */
+	portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+	uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
+	{
+		/* Cannot block in an ISR, so check there is data available. */
+		if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 )
+		{
+			traceQUEUE_PEEK_FROM_ISR( pxQueue );
+
+			/* Remember the read position so it can be reset as nothing is
+			actually being removed from the queue. */
+			pcOriginalReadPosition = pxQueue->u.pcReadFrom;
+			prvCopyDataFromQueue( pxQueue, pvBuffer );
+			pxQueue->u.pcReadFrom = pcOriginalReadPosition;
+
+			xReturn = pdPASS;
+		}
+		else
+		{
+			xReturn = pdFAIL;
+			traceQUEUE_PEEK_FROM_ISR_FAILED( pxQueue );
+		}
+	}
+	portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
+
+	return xReturn;
+}
+/*-----------------------------------------------------------*/
+
+UBaseType_t uxQueueMessagesWaiting( const QueueHandle_t xQueue )
+{
+UBaseType_t uxReturn;
+
+	configASSERT( xQueue );
+
+	taskENTER_CRITICAL();
+	{
+		uxReturn = ( ( Queue_t * ) xQueue )->uxMessagesWaiting;
+	}
+	taskEXIT_CRITICAL();
+
+	return uxReturn;
+} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */
+/*-----------------------------------------------------------*/
+
+UBaseType_t uxQueueSpacesAvailable( const QueueHandle_t xQueue )
+{
+UBaseType_t uxReturn;
+Queue_t *pxQueue;
+
+	pxQueue = ( Queue_t * ) xQueue;
+	configASSERT( pxQueue );
+
+	taskENTER_CRITICAL();
+	{
+		uxReturn = pxQueue->uxLength - pxQueue->uxMessagesWaiting;
+	}
+	taskEXIT_CRITICAL();
+
+	return uxReturn;
+} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */
+/*-----------------------------------------------------------*/
+
+UBaseType_t uxQueueMessagesWaitingFromISR( const QueueHandle_t xQueue )
+{
+UBaseType_t uxReturn;
+
+	configASSERT( xQueue );
+
+	uxReturn = ( ( Queue_t * ) xQueue )->uxMessagesWaiting;
+
+	return uxReturn;
+} /*lint !e818 Pointer cannot be declared const as xQueue is a typedef not pointer. */
+/*-----------------------------------------------------------*/
+
+void vQueueDelete( QueueHandle_t xQueue )
+{
+Queue_t * const pxQueue = ( Queue_t * ) xQueue;
+
+	configASSERT( pxQueue );
+
+	traceQUEUE_DELETE( pxQueue );
+	#if ( configQUEUE_REGISTRY_SIZE > 0 )
+	{
+		vQueueUnregisterQueue( pxQueue );
+	}
+	#endif
+	vPortFree( pxQueue );
+}
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_TRACE_FACILITY == 1 )
+
+	UBaseType_t uxQueueGetQueueNumber( QueueHandle_t xQueue )
+	{
+		return ( ( Queue_t * ) xQueue )->uxQueueNumber;
+	}
+
+#endif /* configUSE_TRACE_FACILITY */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_TRACE_FACILITY == 1 )
+
+	void vQueueSetQueueNumber( QueueHandle_t xQueue, UBaseType_t uxQueueNumber )
+	{
+		( ( Queue_t * ) xQueue )->uxQueueNumber = uxQueueNumber;
+	}
+
+#endif /* configUSE_TRACE_FACILITY */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_TRACE_FACILITY == 1 )
+
+	uint8_t ucQueueGetQueueType( QueueHandle_t xQueue )
+	{
+		return ( ( Queue_t * ) xQueue )->ucQueueType;
+	}
+
+#endif /* configUSE_TRACE_FACILITY */
+/*-----------------------------------------------------------*/
+
+static BaseType_t prvCopyDataToQueue( Queue_t * const pxQueue, const void *pvItemToQueue, const BaseType_t xPosition )
+{
+BaseType_t xReturn = pdFALSE;
+
+	if( pxQueue->uxItemSize == ( UBaseType_t ) 0 )
+	{
+		#if ( configUSE_MUTEXES == 1 )
+		{
+			if( pxQueue->uxQueueType == queueQUEUE_IS_MUTEX )
+			{
+				/* The mutex is no longer being held. */
+				xReturn = xTaskPriorityDisinherit( ( void * ) pxQueue->pxMutexHolder );
+				pxQueue->pxMutexHolder = NULL;
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		#endif /* configUSE_MUTEXES */
+	}
+	else if( xPosition == queueSEND_TO_BACK )
+	{
+		( void ) memcpy( ( void * ) pxQueue->pcWriteTo, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 MISRA exception as the casts are only redundant for some ports, plus previous logic ensures a null pointer can only be passed to memcpy() if the copy size is 0. */
+		pxQueue->pcWriteTo += pxQueue->uxItemSize;
+		if( pxQueue->pcWriteTo >= pxQueue->pcTail ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */
+		{
+			pxQueue->pcWriteTo = pxQueue->pcHead;
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+	else
+	{
+		( void ) memcpy( ( void * ) pxQueue->u.pcReadFrom, pvItemToQueue, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+		pxQueue->u.pcReadFrom -= pxQueue->uxItemSize;
+		if( pxQueue->u.pcReadFrom < pxQueue->pcHead ) /*lint !e946 MISRA exception justified as comparison of pointers is the cleanest solution. */
+		{
+			pxQueue->u.pcReadFrom = ( pxQueue->pcTail - pxQueue->uxItemSize );
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+
+		if( xPosition == queueOVERWRITE )
+		{
+			if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 )
+			{
+				/* An item is not being added but overwritten, so subtract
+				one from the recorded number of items in the queue so when
+				one is added again below the number of recorded items remains
+				correct. */
+				--( pxQueue->uxMessagesWaiting );
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+
+	++( pxQueue->uxMessagesWaiting );
+
+	return xReturn;
+}
+/*-----------------------------------------------------------*/
+
+static void prvCopyDataFromQueue( Queue_t * const pxQueue, void * const pvBuffer )
+{
+	if( pxQueue->uxItemSize != ( UBaseType_t ) 0 )
+	{
+		pxQueue->u.pcReadFrom += pxQueue->uxItemSize;
+		if( pxQueue->u.pcReadFrom >= pxQueue->pcTail ) /*lint !e946 MISRA exception justified as use of the relational operator is the cleanest solutions. */
+		{
+			pxQueue->u.pcReadFrom = pxQueue->pcHead;
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+		( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.pcReadFrom, ( size_t ) pxQueue->uxItemSize ); /*lint !e961 !e418 MISRA exception as the casts are only redundant for some ports.  Also previous logic ensures a null pointer can only be passed to memcpy() when the count is 0. */
+	}
+}
+/*-----------------------------------------------------------*/
+
+static void prvUnlockQueue( Queue_t * const pxQueue )
+{
+	/* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED. */
+
+	/* The lock counts contains the number of extra data items placed or
+	removed from the queue while the queue was locked.  When a queue is
+	locked items can be added or removed, but the event lists cannot be
+	updated. */
+	taskENTER_CRITICAL();
+	{
+		/* See if data was added to the queue while it was locked. */
+		while( pxQueue->xTxLock > queueLOCKED_UNMODIFIED )
+		{
+			/* Data was posted while the queue was locked.  Are any tasks
+			blocked waiting for data to become available? */
+			#if ( configUSE_QUEUE_SETS == 1 )
+			{
+				if( pxQueue->pxQueueSetContainer != NULL )
+				{
+					if( prvNotifyQueueSetContainer( pxQueue, queueSEND_TO_BACK ) == pdTRUE )
+					{
+						/* The queue is a member of a queue set, and posting to
+						the queue set caused a higher priority task to unblock.
+						A context switch is required. */
+						vTaskMissedYield();
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				else
+				{
+					/* Tasks that are removed from the event list will get added to
+					the pending ready list as the scheduler is still suspended. */
+					if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
+					{
+						if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
+						{
+							/* The task waiting has a higher priority so record that a
+							context	switch is required. */
+							vTaskMissedYield();
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+					}
+					else
+					{
+						break;
+					}
+				}
+			}
+			#else /* configUSE_QUEUE_SETS */
+			{
+				/* Tasks that are removed from the event list will get added to
+				the pending ready list as the scheduler is still suspended. */
+				if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
+				{
+					if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
+					{
+						/* The task waiting has a higher priority so record that a
+						context	switch is required. */
+						vTaskMissedYield();
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				else
+				{
+					break;
+				}
+			}
+			#endif /* configUSE_QUEUE_SETS */
+
+			--( pxQueue->xTxLock );
+		}
+
+		pxQueue->xTxLock = queueUNLOCKED;
+	}
+	taskEXIT_CRITICAL();
+
+	/* Do the same for the Rx lock. */
+	taskENTER_CRITICAL();
+	{
+		while( pxQueue->xRxLock > queueLOCKED_UNMODIFIED )
+		{
+			if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE )
+			{
+				if( xTaskRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE )
+				{
+					vTaskMissedYield();
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+
+				--( pxQueue->xRxLock );
+			}
+			else
+			{
+				break;
+			}
+		}
+
+		pxQueue->xRxLock = queueUNLOCKED;
+	}
+	taskEXIT_CRITICAL();
+}
+/*-----------------------------------------------------------*/
+
+static BaseType_t prvIsQueueEmpty( const Queue_t *pxQueue )
+{
+BaseType_t xReturn;
+
+	taskENTER_CRITICAL();
+	{
+		if( pxQueue->uxMessagesWaiting == ( UBaseType_t )  0 )
+		{
+			xReturn = pdTRUE;
+		}
+		else
+		{
+			xReturn = pdFALSE;
+		}
+	}
+	taskEXIT_CRITICAL();
+
+	return xReturn;
+}
+/*-----------------------------------------------------------*/
+
+BaseType_t xQueueIsQueueEmptyFromISR( const QueueHandle_t xQueue )
+{
+BaseType_t xReturn;
+
+	configASSERT( xQueue );
+	if( ( ( Queue_t * ) xQueue )->uxMessagesWaiting == ( UBaseType_t ) 0 )
+	{
+		xReturn = pdTRUE;
+	}
+	else
+	{
+		xReturn = pdFALSE;
+	}
+
+	return xReturn;
+} /*lint !e818 xQueue could not be pointer to const because it is a typedef. */
+/*-----------------------------------------------------------*/
+
+static BaseType_t prvIsQueueFull( const Queue_t *pxQueue )
+{
+BaseType_t xReturn;
+
+	taskENTER_CRITICAL();
+	{
+		if( pxQueue->uxMessagesWaiting == pxQueue->uxLength )
+		{
+			xReturn = pdTRUE;
+		}
+		else
+		{
+			xReturn = pdFALSE;
+		}
+	}
+	taskEXIT_CRITICAL();
+
+	return xReturn;
+}
+/*-----------------------------------------------------------*/
+
+BaseType_t xQueueIsQueueFullFromISR( const QueueHandle_t xQueue )
+{
+BaseType_t xReturn;
+
+	configASSERT( xQueue );
+	if( ( ( Queue_t * ) xQueue )->uxMessagesWaiting == ( ( Queue_t * ) xQueue )->uxLength )
+	{
+		xReturn = pdTRUE;
+	}
+	else
+	{
+		xReturn = pdFALSE;
+	}
+
+	return xReturn;
+} /*lint !e818 xQueue could not be pointer to const because it is a typedef. */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_CO_ROUTINES == 1 )
+
+	BaseType_t xQueueCRSend( QueueHandle_t xQueue, const void *pvItemToQueue, TickType_t xTicksToWait )
+	{
+	BaseType_t xReturn;
+	Queue_t * const pxQueue = ( Queue_t * ) xQueue;
+
+		/* If the queue is already full we may have to block.  A critical section
+		is required to prevent an interrupt removing something from the queue
+		between the check to see if the queue is full and blocking on the queue. */
+		portDISABLE_INTERRUPTS();
+		{
+			if( prvIsQueueFull( pxQueue ) != pdFALSE )
+			{
+				/* The queue is full - do we want to block or just leave without
+				posting? */
+				if( xTicksToWait > ( TickType_t ) 0 )
+				{
+					/* As this is called from a coroutine we cannot block directly, but
+					return indicating that we need to block. */
+					vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToSend ) );
+					portENABLE_INTERRUPTS();
+					return errQUEUE_BLOCKED;
+				}
+				else
+				{
+					portENABLE_INTERRUPTS();
+					return errQUEUE_FULL;
+				}
+			}
+		}
+		portENABLE_INTERRUPTS();
+
+		portDISABLE_INTERRUPTS();
+		{
+			if( pxQueue->uxMessagesWaiting < pxQueue->uxLength )
+			{
+				/* There is room in the queue, copy the data into the queue. */
+				prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK );
+				xReturn = pdPASS;
+
+				/* Were any co-routines waiting for data to become available? */
+				if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
+				{
+					/* In this instance the co-routine could be placed directly
+					into the ready list as we are within a critical section.
+					Instead the same pending ready list mechanism is used as if
+					the event were caused from within an interrupt. */
+					if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
+					{
+						/* The co-routine waiting has a higher priority so record
+						that a yield might be appropriate. */
+						xReturn = errQUEUE_YIELD;
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			else
+			{
+				xReturn = errQUEUE_FULL;
+			}
+		}
+		portENABLE_INTERRUPTS();
+
+		return xReturn;
+	}
+
+#endif /* configUSE_CO_ROUTINES */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_CO_ROUTINES == 1 )
+
+	BaseType_t xQueueCRReceive( QueueHandle_t xQueue, void *pvBuffer, TickType_t xTicksToWait )
+	{
+	BaseType_t xReturn;
+	Queue_t * const pxQueue = ( Queue_t * ) xQueue;
+
+		/* If the queue is already empty we may have to block.  A critical section
+		is required to prevent an interrupt adding something to the queue
+		between the check to see if the queue is empty and blocking on the queue. */
+		portDISABLE_INTERRUPTS();
+		{
+			if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0 )
+			{
+				/* There are no messages in the queue, do we want to block or just
+				leave with nothing? */
+				if( xTicksToWait > ( TickType_t ) 0 )
+				{
+					/* As this is a co-routine we cannot block directly, but return
+					indicating that we need to block. */
+					vCoRoutineAddToDelayedList( xTicksToWait, &( pxQueue->xTasksWaitingToReceive ) );
+					portENABLE_INTERRUPTS();
+					return errQUEUE_BLOCKED;
+				}
+				else
+				{
+					portENABLE_INTERRUPTS();
+					return errQUEUE_FULL;
+				}
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		portENABLE_INTERRUPTS();
+
+		portDISABLE_INTERRUPTS();
+		{
+			if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 )
+			{
+				/* Data is available from the queue. */
+				pxQueue->u.pcReadFrom += pxQueue->uxItemSize;
+				if( pxQueue->u.pcReadFrom >= pxQueue->pcTail )
+				{
+					pxQueue->u.pcReadFrom = pxQueue->pcHead;
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+				--( pxQueue->uxMessagesWaiting );
+				( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.pcReadFrom, ( unsigned ) pxQueue->uxItemSize );
+
+				xReturn = pdPASS;
+
+				/* Were any co-routines waiting for space to become available? */
+				if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE )
+				{
+					/* In this instance the co-routine could be placed directly
+					into the ready list as we are within a critical section.
+					Instead the same pending ready list mechanism is used as if
+					the event were caused from within an interrupt. */
+					if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE )
+					{
+						xReturn = errQUEUE_YIELD;
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			else
+			{
+				xReturn = pdFAIL;
+			}
+		}
+		portENABLE_INTERRUPTS();
+
+		return xReturn;
+	}
+
+#endif /* configUSE_CO_ROUTINES */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_CO_ROUTINES == 1 )
+
+	BaseType_t xQueueCRSendFromISR( QueueHandle_t xQueue, const void *pvItemToQueue, BaseType_t xCoRoutinePreviouslyWoken )
+	{
+	Queue_t * const pxQueue = ( Queue_t * ) xQueue;
+
+		/* Cannot block within an ISR so if there is no space on the queue then
+		exit without doing anything. */
+		if( pxQueue->uxMessagesWaiting < pxQueue->uxLength )
+		{
+			prvCopyDataToQueue( pxQueue, pvItemToQueue, queueSEND_TO_BACK );
+
+			/* We only want to wake one co-routine per ISR, so check that a
+			co-routine has not already been woken. */
+			if( xCoRoutinePreviouslyWoken == pdFALSE )
+			{
+				if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToReceive ) ) == pdFALSE )
+				{
+					if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToReceive ) ) != pdFALSE )
+					{
+						return pdTRUE;
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+
+		return xCoRoutinePreviouslyWoken;
+	}
+
+#endif /* configUSE_CO_ROUTINES */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_CO_ROUTINES == 1 )
+
+	BaseType_t xQueueCRReceiveFromISR( QueueHandle_t xQueue, void *pvBuffer, BaseType_t *pxCoRoutineWoken )
+	{
+	BaseType_t xReturn;
+	Queue_t * const pxQueue = ( Queue_t * ) xQueue;
+
+		/* We cannot block from an ISR, so check there is data available. If
+		not then just leave without doing anything. */
+		if( pxQueue->uxMessagesWaiting > ( UBaseType_t ) 0 )
+		{
+			/* Copy the data from the queue. */
+			pxQueue->u.pcReadFrom += pxQueue->uxItemSize;
+			if( pxQueue->u.pcReadFrom >= pxQueue->pcTail )
+			{
+				pxQueue->u.pcReadFrom = pxQueue->pcHead;
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+			--( pxQueue->uxMessagesWaiting );
+			( void ) memcpy( ( void * ) pvBuffer, ( void * ) pxQueue->u.pcReadFrom, ( unsigned ) pxQueue->uxItemSize );
+
+			if( ( *pxCoRoutineWoken ) == pdFALSE )
+			{
+				if( listLIST_IS_EMPTY( &( pxQueue->xTasksWaitingToSend ) ) == pdFALSE )
+				{
+					if( xCoRoutineRemoveFromEventList( &( pxQueue->xTasksWaitingToSend ) ) != pdFALSE )
+					{
+						*pxCoRoutineWoken = pdTRUE;
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+
+			xReturn = pdPASS;
+		}
+		else
+		{
+			xReturn = pdFAIL;
+		}
+
+		return xReturn;
+	}
+
+#endif /* configUSE_CO_ROUTINES */
+/*-----------------------------------------------------------*/
+
+#if ( configQUEUE_REGISTRY_SIZE > 0 )
+
+	void vQueueAddToRegistry( QueueHandle_t xQueue, const char *pcQueueName ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+	{
+	UBaseType_t ux;
+
+		/* See if there is an empty space in the registry.  A NULL name denotes
+		a free slot. */
+		for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ )
+		{
+			if( xQueueRegistry[ ux ].pcQueueName == NULL )
+			{
+				/* Store the information on this queue. */
+				xQueueRegistry[ ux ].pcQueueName = pcQueueName;
+				xQueueRegistry[ ux ].xHandle = xQueue;
+
+				traceQUEUE_REGISTRY_ADD( xQueue, pcQueueName );
+				break;
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+	}
+
+#endif /* configQUEUE_REGISTRY_SIZE */
+/*-----------------------------------------------------------*/
+
+#if ( configQUEUE_REGISTRY_SIZE > 0 )
+
+	void vQueueUnregisterQueue( QueueHandle_t xQueue )
+	{
+	UBaseType_t ux;
+
+		/* See if the handle of the queue being unregistered in actually in the
+		registry. */
+		for( ux = ( UBaseType_t ) 0U; ux < ( UBaseType_t ) configQUEUE_REGISTRY_SIZE; ux++ )
+		{
+			if( xQueueRegistry[ ux ].xHandle == xQueue )
+			{
+				/* Set the name to NULL to show that this slot if free again. */
+				xQueueRegistry[ ux ].pcQueueName = NULL;
+				break;
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+
+	} /*lint !e818 xQueue could not be pointer to const because it is a typedef. */
+
+#endif /* configQUEUE_REGISTRY_SIZE */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_TIMERS == 1 )
+
+	void vQueueWaitForMessageRestricted( QueueHandle_t xQueue, TickType_t xTicksToWait )
+	{
+	Queue_t * const pxQueue = ( Queue_t * ) xQueue;
+
+		/* This function should not be called by application code hence the
+		'Restricted' in its name.  It is not part of the public API.  It is
+		designed for use by kernel code, and has special calling requirements.
+		It can result in vListInsert() being called on a list that can only
+		possibly ever have one item in it, so the list will be fast, but even
+		so it should be called with the scheduler locked and not from a critical
+		section. */
+
+		/* Only do anything if there are no messages in the queue.  This function
+		will not actually cause the task to block, just place it on a blocked
+		list.  It will not block until the scheduler is unlocked - at which
+		time a yield will be performed.  If an item is added to the queue while
+		the queue is locked, and the calling task blocks on the queue, then the
+		calling task will be immediately unblocked when the queue is unlocked. */
+		prvLockQueue( pxQueue );
+		if( pxQueue->uxMessagesWaiting == ( UBaseType_t ) 0U )
+		{
+			/* There is nothing in the queue, block for the specified period. */
+			vTaskPlaceOnEventListRestricted( &( pxQueue->xTasksWaitingToReceive ), xTicksToWait );
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+		prvUnlockQueue( pxQueue );
+	}
+
+#endif /* configUSE_TIMERS */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_QUEUE_SETS == 1 )
+
+	QueueSetHandle_t xQueueCreateSet( const UBaseType_t uxEventQueueLength )
+	{
+	QueueSetHandle_t pxQueue;
+
+		pxQueue = xQueueGenericCreate( uxEventQueueLength, sizeof( Queue_t * ), queueQUEUE_TYPE_SET );
+
+		return pxQueue;
+	}
+
+#endif /* configUSE_QUEUE_SETS */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_QUEUE_SETS == 1 )
+
+	BaseType_t xQueueAddToSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet )
+	{
+	BaseType_t xReturn;
+
+		taskENTER_CRITICAL();
+		{
+			if( ( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer != NULL )
+			{
+				/* Cannot add a queue/semaphore to more than one queue set. */
+				xReturn = pdFAIL;
+			}
+			else if( ( ( Queue_t * ) xQueueOrSemaphore )->uxMessagesWaiting != ( UBaseType_t ) 0 )
+			{
+				/* Cannot add a queue/semaphore to a queue set if there are already
+				items in the queue/semaphore. */
+				xReturn = pdFAIL;
+			}
+			else
+			{
+				( ( Queue_t * ) xQueueOrSemaphore )->pxQueueSetContainer = xQueueSet;
+				xReturn = pdPASS;
+			}
+		}
+		taskEXIT_CRITICAL();
+
+		return xReturn;
+	}
+
+#endif /* configUSE_QUEUE_SETS */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_QUEUE_SETS == 1 )
+
+	BaseType_t xQueueRemoveFromSet( QueueSetMemberHandle_t xQueueOrSemaphore, QueueSetHandle_t xQueueSet )
+	{
+	BaseType_t xReturn;
+	Queue_t * const pxQueueOrSemaphore = ( Queue_t * ) xQueueOrSemaphore;
+
+		if( pxQueueOrSemaphore->pxQueueSetContainer != xQueueSet )
+		{
+			/* The queue was not a member of the set. */
+			xReturn = pdFAIL;
+		}
+		else if( pxQueueOrSemaphore->uxMessagesWaiting != ( UBaseType_t ) 0 )
+		{
+			/* It is dangerous to remove a queue from a set when the queue is
+			not empty because the queue set will still hold pending events for
+			the queue. */
+			xReturn = pdFAIL;
+		}
+		else
+		{
+			taskENTER_CRITICAL();
+			{
+				/* The queue is no longer contained in the set. */
+				pxQueueOrSemaphore->pxQueueSetContainer = NULL;
+			}
+			taskEXIT_CRITICAL();
+			xReturn = pdPASS;
+		}
+
+		return xReturn;
+	} /*lint !e818 xQueueSet could not be declared as pointing to const as it is a typedef. */
+
+#endif /* configUSE_QUEUE_SETS */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_QUEUE_SETS == 1 )
+
+	QueueSetMemberHandle_t xQueueSelectFromSet( QueueSetHandle_t xQueueSet, TickType_t const xTicksToWait )
+	{
+	QueueSetMemberHandle_t xReturn = NULL;
+
+		( void ) xQueueGenericReceive( ( QueueHandle_t ) xQueueSet, &xReturn, xTicksToWait, pdFALSE ); /*lint !e961 Casting from one typedef to another is not redundant. */
+		return xReturn;
+	}
+
+#endif /* configUSE_QUEUE_SETS */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_QUEUE_SETS == 1 )
+
+	QueueSetMemberHandle_t xQueueSelectFromSetFromISR( QueueSetHandle_t xQueueSet )
+	{
+	QueueSetMemberHandle_t xReturn = NULL;
+
+		( void ) xQueueReceiveFromISR( ( QueueHandle_t ) xQueueSet, &xReturn, NULL ); /*lint !e961 Casting from one typedef to another is not redundant. */
+		return xReturn;
+	}
+
+#endif /* configUSE_QUEUE_SETS */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_QUEUE_SETS == 1 )
+
+	static BaseType_t prvNotifyQueueSetContainer( const Queue_t * const pxQueue, const BaseType_t xCopyPosition )
+	{
+	Queue_t *pxQueueSetContainer = pxQueue->pxQueueSetContainer;
+	BaseType_t xReturn = pdFALSE;
+
+		/* This function must be called form a critical section. */
+
+		configASSERT( pxQueueSetContainer );
+		configASSERT( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength );
+
+		if( pxQueueSetContainer->uxMessagesWaiting < pxQueueSetContainer->uxLength )
+		{
+			traceQUEUE_SEND( pxQueueSetContainer );
+
+			/* The data copied is the handle of the queue that contains data. */
+			xReturn = prvCopyDataToQueue( pxQueueSetContainer, &pxQueue, xCopyPosition );
+
+			if( pxQueueSetContainer->xTxLock == queueUNLOCKED )
+			{
+				if( listLIST_IS_EMPTY( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) == pdFALSE )
+				{
+					if( xTaskRemoveFromEventList( &( pxQueueSetContainer->xTasksWaitingToReceive ) ) != pdFALSE )
+					{
+						/* The task waiting has a higher priority. */
+						xReturn = pdTRUE;
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			else
+			{
+				( pxQueueSetContainer->xTxLock )++;
+			}
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+
+		return xReturn;
+	}
+
+#endif /* configUSE_QUEUE_SETS */
+
+
+
+
+
+
+
+
+
+
+
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/readme.txt
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/readme.txt	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,17 @@
+Each real time kernel port consists of three files that contain the core kernel
+components and are common to every port, and one or more files that are 
+specific to a particular microcontroller and or compiler.
+
++ The FreeRTOS/Source directory contains the three files that are common to 
+every port - list.c, queue.c and tasks.c.  The kernel is contained within these 
+three files.  croutine.c implements the optional co-routine functionality - which
+is normally only used on very memory limited systems.
+
++ The FreeRTOS/Source/Portable directory contains the files that are specific to 
+a particular microcontroller and or compiler.
+
++ The FreeRTOS/Source/include directory contains the real time kernel header 
+files.
+
+See the readme file in the FreeRTOS/Source/Portable directory for more 
+information.
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/tasks.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/tasks.c	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,4388 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+/* Standard includes. */
+#include <stdlib.h>
+#include <string.h>
+
+/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
+all the API functions to use the MPU wrappers.  That should only be done when
+task.h is included from an application file. */
+#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
+
+/* FreeRTOS includes. */
+#include "FreeRTOS.h"
+#include "task.h"
+#include "timers.h"
+#include "StackMacros.h"
+
+/* Lint e961 and e750 are suppressed as a MISRA exception justified because the
+MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined for the
+header files above, but not in this file, in order to generate the correct
+privileged Vs unprivileged linkage and placement. */
+#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750. */
+
+/* Set configUSE_STATS_FORMATTING_FUNCTIONS to 2 to include the stats formatting
+functions but without including stdio.h here. */
+#if ( configUSE_STATS_FORMATTING_FUNCTIONS == 1 )
+	/* At the bottom of this file are two optional functions that can be used
+	to generate human readable text from the raw data generated by the
+	uxTaskGetSystemState() function.  Note the formatting functions are provided
+	for convenience only, and are NOT considered part of the kernel. */
+	#include <stdio.h>
+#endif /* configUSE_STATS_FORMATTING_FUNCTIONS == 1 ) */
+
+/* Sanity check the configuration. */
+#if configUSE_TICKLESS_IDLE != 0
+	#if INCLUDE_vTaskSuspend != 1
+		#error INCLUDE_vTaskSuspend must be set to 1 if configUSE_TICKLESS_IDLE is not set to 0
+	#endif /* INCLUDE_vTaskSuspend */
+#endif /* configUSE_TICKLESS_IDLE */
+
+/*
+ * Defines the size, in words, of the stack allocated to the idle task.
+ */
+#define tskIDLE_STACK_SIZE	configMINIMAL_STACK_SIZE
+
+#if( configUSE_PREEMPTION == 0 )
+	/* If the cooperative scheduler is being used then a yield should not be
+	performed just because a higher priority task has been woken. */
+	#define taskYIELD_IF_USING_PREEMPTION()
+#else
+	#define taskYIELD_IF_USING_PREEMPTION() portYIELD_WITHIN_API()
+#endif
+
+/* Value that can be assigned to the eNotifyState member of the TCB. */
+typedef enum
+{
+	eNotWaitingNotification = 0,
+	eWaitingNotification,
+	eNotified
+} eNotifyValue;
+
+/*
+ * Task control block.  A task control block (TCB) is allocated for each task,
+ * and stores task state information, including a pointer to the task's context
+ * (the task's run time environment, including register values)
+ */
+typedef struct tskTaskControlBlock
+{
+	volatile StackType_t	*pxTopOfStack;	/*< Points to the location of the last item placed on the tasks stack.  THIS MUST BE THE FIRST MEMBER OF THE TCB STRUCT. */
+
+	#if ( portUSING_MPU_WRAPPERS == 1 )
+		xMPU_SETTINGS	xMPUSettings;		/*< The MPU settings are defined as part of the port layer.  THIS MUST BE THE SECOND MEMBER OF THE TCB STRUCT. */
+		BaseType_t		xUsingStaticallyAllocatedStack; /* Set to pdTRUE if the stack is a statically allocated array, and pdFALSE if the stack is dynamically allocated. */
+	#endif
+
+	ListItem_t			xGenericListItem;	/*< The list that the state list item of a task is reference from denotes the state of that task (Ready, Blocked, Suspended ). */
+	ListItem_t			xEventListItem;		/*< Used to reference a task from an event list. */
+	UBaseType_t			uxPriority;			/*< The priority of the task.  0 is the lowest priority. */
+	StackType_t			*pxStack;			/*< Points to the start of the stack. */
+	char				pcTaskName[ configMAX_TASK_NAME_LEN ];/*< Descriptive name given to the task when created.  Facilitates debugging only. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+
+	#if ( portSTACK_GROWTH > 0 )
+		StackType_t		*pxEndOfStack;		/*< Points to the end of the stack on architectures where the stack grows up from low memory. */
+	#endif
+
+	#if ( portCRITICAL_NESTING_IN_TCB == 1 )
+		UBaseType_t 	uxCriticalNesting; 	/*< Holds the critical section nesting depth for ports that do not maintain their own count in the port layer. */
+	#endif
+
+	#if ( configUSE_TRACE_FACILITY == 1 )
+		UBaseType_t		uxTCBNumber;		/*< Stores a number that increments each time a TCB is created.  It allows debuggers to determine when a task has been deleted and then recreated. */
+		UBaseType_t  	uxTaskNumber;		/*< Stores a number specifically for use by third party trace code. */
+	#endif
+
+	#if ( configUSE_MUTEXES == 1 )
+		UBaseType_t 	uxBasePriority;		/*< The priority last assigned to the task - used by the priority inheritance mechanism. */
+		UBaseType_t 	uxMutexesHeld;
+	#endif
+
+	#if ( configUSE_APPLICATION_TASK_TAG == 1 )
+		TaskHookFunction_t pxTaskTag;
+	#endif
+
+	#if( configNUM_THREAD_LOCAL_STORAGE_POINTERS > 0 )
+		void *pvThreadLocalStoragePointers[ configNUM_THREAD_LOCAL_STORAGE_POINTERS ];
+	#endif
+
+	#if ( configGENERATE_RUN_TIME_STATS == 1 )
+		uint32_t		ulRunTimeCounter;	/*< Stores the amount of time the task has spent in the Running state. */
+	#endif
+
+	#if ( configUSE_NEWLIB_REENTRANT == 1 )
+		/* Allocate a Newlib reent structure that is specific to this task.
+		Note Newlib support has been included by popular demand, but is not
+		used by the FreeRTOS maintainers themselves.  FreeRTOS is not
+		responsible for resulting newlib operation.  User must be familiar with
+		newlib and must provide system-wide implementations of the necessary
+		stubs. Be warned that (at the time of writing) the current newlib design
+		implements a system-wide malloc() that must be provided with locks. */
+		struct 	_reent xNewLib_reent;
+	#endif
+
+	#if ( configUSE_TASK_NOTIFICATIONS == 1 )
+		volatile uint32_t ulNotifiedValue;
+		volatile eNotifyValue eNotifyState;
+	#endif
+
+} tskTCB;
+
+/* The old tskTCB name is maintained above then typedefed to the new TCB_t name
+below to enable the use of older kernel aware debuggers. */
+typedef tskTCB TCB_t;
+
+/*
+ * Some kernel aware debuggers require the data the debugger needs access to to
+ * be global, rather than file scope.
+ */
+#ifdef portREMOVE_STATIC_QUALIFIER
+	#define static
+#endif
+
+/*lint -e956 A manual analysis and inspection has been used to determine which
+static variables must be declared volatile. */
+
+PRIVILEGED_DATA TCB_t * volatile pxCurrentTCB = NULL;
+
+/* Lists for ready and blocked tasks. --------------------*/
+PRIVILEGED_DATA static List_t pxReadyTasksLists[ configMAX_PRIORITIES ];/*< Prioritised ready tasks. */
+PRIVILEGED_DATA static List_t xDelayedTaskList1;						/*< Delayed tasks. */
+PRIVILEGED_DATA static List_t xDelayedTaskList2;						/*< Delayed tasks (two lists are used - one for delays that have overflowed the current tick count. */
+PRIVILEGED_DATA static List_t * volatile pxDelayedTaskList;				/*< Points to the delayed task list currently being used. */
+PRIVILEGED_DATA static List_t * volatile pxOverflowDelayedTaskList;		/*< Points to the delayed task list currently being used to hold tasks that have overflowed the current tick count. */
+PRIVILEGED_DATA static List_t xPendingReadyList;						/*< Tasks that have been readied while the scheduler was suspended.  They will be moved to the ready list when the scheduler is resumed. */
+
+#if ( INCLUDE_vTaskDelete == 1 )
+
+	PRIVILEGED_DATA static List_t xTasksWaitingTermination;				/*< Tasks that have been deleted - but their memory not yet freed. */
+	PRIVILEGED_DATA static volatile UBaseType_t uxTasksDeleted = ( UBaseType_t ) 0U;
+
+#endif
+
+#if ( INCLUDE_vTaskSuspend == 1 )
+
+	PRIVILEGED_DATA static List_t xSuspendedTaskList;					/*< Tasks that are currently suspended. */
+
+#endif
+
+#if ( INCLUDE_xTaskGetIdleTaskHandle == 1 )
+
+	PRIVILEGED_DATA static TaskHandle_t xIdleTaskHandle = NULL;			/*< Holds the handle of the idle task.  The idle task is created automatically when the scheduler is started. */
+
+#endif
+
+/* Other file private variables. --------------------------------*/
+PRIVILEGED_DATA static volatile UBaseType_t uxCurrentNumberOfTasks 	= ( UBaseType_t ) 0U;
+PRIVILEGED_DATA static volatile TickType_t xTickCount 				= ( TickType_t ) 0U;
+PRIVILEGED_DATA static volatile UBaseType_t uxTopReadyPriority 		= tskIDLE_PRIORITY;
+PRIVILEGED_DATA static volatile BaseType_t xSchedulerRunning 		= pdFALSE;
+PRIVILEGED_DATA static volatile UBaseType_t uxPendedTicks 			= ( UBaseType_t ) 0U;
+PRIVILEGED_DATA static volatile BaseType_t xYieldPending 			= pdFALSE;
+PRIVILEGED_DATA static volatile BaseType_t xNumOfOverflows 			= ( BaseType_t ) 0;
+PRIVILEGED_DATA static UBaseType_t uxTaskNumber 					= ( UBaseType_t ) 0U;
+PRIVILEGED_DATA static volatile TickType_t xNextTaskUnblockTime		= portMAX_DELAY;
+
+/* Context switches are held pending while the scheduler is suspended.  Also,
+interrupts must not manipulate the xGenericListItem of a TCB, or any of the
+lists the xGenericListItem can be referenced from, if the scheduler is suspended.
+If an interrupt needs to unblock a task while the scheduler is suspended then it
+moves the task's event list item into the xPendingReadyList, ready for the
+kernel to move the task from the pending ready list into the real ready list
+when the scheduler is unsuspended.  The pending ready list itself can only be
+accessed from a critical section. */
+PRIVILEGED_DATA static volatile UBaseType_t uxSchedulerSuspended	= ( UBaseType_t ) pdFALSE;
+
+#if ( configGENERATE_RUN_TIME_STATS == 1 )
+
+	PRIVILEGED_DATA static uint32_t ulTaskSwitchedInTime = 0UL;	/*< Holds the value of a timer/counter the last time a task was switched in. */
+	PRIVILEGED_DATA static uint32_t ulTotalRunTime = 0UL;		/*< Holds the total amount of execution time as defined by the run time counter clock. */
+
+#endif
+
+/*lint +e956 */
+
+/* Debugging and trace facilities private variables and macros. ------------*/
+
+/*
+ * The value used to fill the stack of a task when the task is created.  This
+ * is used purely for checking the high water mark for tasks.
+ */
+#define tskSTACK_FILL_BYTE	( 0xa5U )
+
+/*
+ * Macros used by vListTask to indicate which state a task is in.
+ */
+#define tskBLOCKED_CHAR		( 'B' )
+#define tskREADY_CHAR		( 'R' )
+#define tskDELETED_CHAR		( 'D' )
+#define tskSUSPENDED_CHAR	( 'S' )
+
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_PORT_OPTIMISED_TASK_SELECTION == 0 )
+
+	/* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 0 then task selection is
+	performed in a generic way that is not optimised to any particular
+	microcontroller architecture. */
+
+	/* uxTopReadyPriority holds the priority of the highest priority ready
+	state task. */
+	#define taskRECORD_READY_PRIORITY( uxPriority )														\
+	{																									\
+		if( ( uxPriority ) > uxTopReadyPriority )														\
+		{																								\
+			uxTopReadyPriority = ( uxPriority );														\
+		}																								\
+	} /* taskRECORD_READY_PRIORITY */
+
+	/*-----------------------------------------------------------*/
+
+	#define taskSELECT_HIGHEST_PRIORITY_TASK()															\
+	{																									\
+		/* Find the highest priority queue that contains ready tasks. */								\
+		while( listLIST_IS_EMPTY( &( pxReadyTasksLists[ uxTopReadyPriority ] ) ) )						\
+		{																								\
+			configASSERT( uxTopReadyPriority );															\
+			--uxTopReadyPriority;																		\
+		}																								\
+																										\
+		/* listGET_OWNER_OF_NEXT_ENTRY indexes through the list, so the tasks of						\
+		the	same priority get an equal share of the processor time. */									\
+		listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopReadyPriority ] ) );		\
+	} /* taskSELECT_HIGHEST_PRIORITY_TASK */
+
+	/*-----------------------------------------------------------*/
+
+	/* Define away taskRESET_READY_PRIORITY() and portRESET_READY_PRIORITY() as
+	they are only required when a port optimised method of task selection is
+	being used. */
+	#define taskRESET_READY_PRIORITY( uxPriority )
+	#define portRESET_READY_PRIORITY( uxPriority, uxTopReadyPriority )
+
+#else /* configUSE_PORT_OPTIMISED_TASK_SELECTION */
+
+	/* If configUSE_PORT_OPTIMISED_TASK_SELECTION is 1 then task selection is
+	performed in a way that is tailored to the particular microcontroller
+	architecture being used. */
+
+	/* A port optimised version is provided.  Call the port defined macros. */
+	#define taskRECORD_READY_PRIORITY( uxPriority )	portRECORD_READY_PRIORITY( uxPriority, uxTopReadyPriority )
+
+	/*-----------------------------------------------------------*/
+
+	#define taskSELECT_HIGHEST_PRIORITY_TASK()														\
+	{																								\
+	UBaseType_t uxTopPriority;																		\
+																									\
+		/* Find the highest priority queue that contains ready tasks. */							\
+		portGET_HIGHEST_PRIORITY( uxTopPriority, uxTopReadyPriority );								\
+		configASSERT( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ uxTopPriority ] ) ) > 0 );		\
+		listGET_OWNER_OF_NEXT_ENTRY( pxCurrentTCB, &( pxReadyTasksLists[ uxTopPriority ] ) );		\
+	} /* taskSELECT_HIGHEST_PRIORITY_TASK() */
+
+	/*-----------------------------------------------------------*/
+
+	/* A port optimised version is provided, call it only if the TCB being reset
+	is being referenced from a ready list.  If it is referenced from a delayed
+	or suspended list then it won't be in a ready list. */
+	#define taskRESET_READY_PRIORITY( uxPriority )														\
+	{																									\
+		if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ ( uxPriority ) ] ) ) == ( UBaseType_t ) 0 )	\
+		{																								\
+			portRESET_READY_PRIORITY( ( uxPriority ), ( uxTopReadyPriority ) );							\
+		}																								\
+	}
+
+#endif /* configUSE_PORT_OPTIMISED_TASK_SELECTION */
+
+/*-----------------------------------------------------------*/
+
+/* pxDelayedTaskList and pxOverflowDelayedTaskList are switched when the tick
+count overflows. */
+#define taskSWITCH_DELAYED_LISTS()																	\
+{																									\
+	List_t *pxTemp;																					\
+																									\
+	/* The delayed tasks list should be empty when the lists are switched. */						\
+	configASSERT( ( listLIST_IS_EMPTY( pxDelayedTaskList ) ) );										\
+																									\
+	pxTemp = pxDelayedTaskList;																		\
+	pxDelayedTaskList = pxOverflowDelayedTaskList;													\
+	pxOverflowDelayedTaskList = pxTemp;																\
+	xNumOfOverflows++;																				\
+	prvResetNextTaskUnblockTime();																	\
+}
+
+/*-----------------------------------------------------------*/
+
+/*
+ * Place the task represented by pxTCB into the appropriate ready list for
+ * the task.  It is inserted at the end of the list.
+ */
+#define prvAddTaskToReadyList( pxTCB )																\
+	traceMOVED_TASK_TO_READY_STATE( pxTCB );														\
+	taskRECORD_READY_PRIORITY( ( pxTCB )->uxPriority );												\
+	vListInsertEnd( &( pxReadyTasksLists[ ( pxTCB )->uxPriority ] ), &( ( pxTCB )->xGenericListItem ) )
+/*-----------------------------------------------------------*/
+
+/*
+ * Several functions take an TaskHandle_t parameter that can optionally be NULL,
+ * where NULL is used to indicate that the handle of the currently executing
+ * task should be used in place of the parameter.  This macro simply checks to
+ * see if the parameter is NULL and returns a pointer to the appropriate TCB.
+ */
+#define prvGetTCBFromHandle( pxHandle ) ( ( ( pxHandle ) == NULL ) ? ( TCB_t * ) pxCurrentTCB : ( TCB_t * ) ( pxHandle ) )
+
+/* The item value of the event list item is normally used to hold the priority
+of the task to which it belongs (coded to allow it to be held in reverse
+priority order).  However, it is occasionally borrowed for other purposes.  It
+is important its value is not updated due to a task priority change while it is
+being used for another purpose.  The following bit definition is used to inform
+the scheduler that the value should not be changed - in which case it is the
+responsibility of whichever module is using the value to ensure it gets set back
+to its original value when it is released. */
+#if configUSE_16_BIT_TICKS == 1
+	#define taskEVENT_LIST_ITEM_VALUE_IN_USE	0x8000U
+#else
+	#define taskEVENT_LIST_ITEM_VALUE_IN_USE	0x80000000UL
+#endif
+
+/* Callback function prototypes. --------------------------*/
+#if configCHECK_FOR_STACK_OVERFLOW > 0
+	extern void vApplicationStackOverflowHook( TaskHandle_t xTask, char *pcTaskName );
+#endif
+
+#if configUSE_TICK_HOOK > 0
+	extern void vApplicationTickHook( void );
+#endif
+
+/* File private functions. --------------------------------*/
+
+/*
+ * Utility to ready a TCB for a given task.  Mainly just copies the parameters
+ * into the TCB structure.
+ */
+static void prvInitialiseTCBVariables( TCB_t * const pxTCB, const char * const pcName, UBaseType_t uxPriority, const MemoryRegion_t * const xRegions, const uint16_t usStackDepth ) PRIVILEGED_FUNCTION; /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+
+/**
+ * Utility task that simply returns pdTRUE if the task referenced by xTask is
+ * currently in the Suspended state, or pdFALSE if the task referenced by xTask
+ * is in any other state.
+ */
+#if ( INCLUDE_vTaskSuspend == 1 )
+	static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask ) PRIVILEGED_FUNCTION;
+#endif /* INCLUDE_vTaskSuspend */
+
+/*
+ * Utility to ready all the lists used by the scheduler.  This is called
+ * automatically upon the creation of the first task.
+ */
+static void prvInitialiseTaskLists( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * The idle task, which as all tasks is implemented as a never ending loop.
+ * The idle task is automatically created and added to the ready lists upon
+ * creation of the first user task.
+ *
+ * The portTASK_FUNCTION_PROTO() macro is used to allow port/compiler specific
+ * language extensions.  The equivalent prototype for this function is:
+ *
+ * void prvIdleTask( void *pvParameters );
+ *
+ */
+static portTASK_FUNCTION_PROTO( prvIdleTask, pvParameters );
+
+/*
+ * Utility to free all memory allocated by the scheduler to hold a TCB,
+ * including the stack pointed to by the TCB.
+ *
+ * This does not free memory allocated by the task itself (i.e. memory
+ * allocated by calls to pvPortMalloc from within the tasks application code).
+ */
+#if ( INCLUDE_vTaskDelete == 1 )
+
+	static void prvDeleteTCB( TCB_t *pxTCB ) PRIVILEGED_FUNCTION;
+
+#endif
+
+/*
+ * Used only by the idle task.  This checks to see if anything has been placed
+ * in the list of tasks waiting to be deleted.  If so the task is cleaned up
+ * and its TCB deleted.
+ */
+static void prvCheckTasksWaitingTermination( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * The currently executing task is entering the Blocked state.  Add the task to
+ * either the current or the overflow delayed task list.
+ */
+static void prvAddCurrentTaskToDelayedList( const TickType_t xTimeToWake ) PRIVILEGED_FUNCTION;
+
+/*
+ * Allocates memory from the heap for a TCB and associated stack.  Checks the
+ * allocation was successful.
+ */
+static TCB_t *prvAllocateTCBAndStack( const uint16_t usStackDepth, StackType_t * const puxStackBuffer ) PRIVILEGED_FUNCTION;
+
+/*
+ * Fills an TaskStatus_t structure with information on each task that is
+ * referenced from the pxList list (which may be a ready list, a delayed list,
+ * a suspended list, etc.).
+ *
+ * THIS FUNCTION IS INTENDED FOR DEBUGGING ONLY, AND SHOULD NOT BE CALLED FROM
+ * NORMAL APPLICATION CODE.
+ */
+#if ( configUSE_TRACE_FACILITY == 1 )
+
+	static UBaseType_t prvListTaskWithinSingleList( TaskStatus_t *pxTaskStatusArray, List_t *pxList, eTaskState eState ) PRIVILEGED_FUNCTION;
+
+#endif
+
+/*
+ * When a task is created, the stack of the task is filled with a known value.
+ * This function determines the 'high water mark' of the task stack by
+ * determining how much of the stack remains at the original preset value.
+ */
+#if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) )
+
+	static uint16_t prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte ) PRIVILEGED_FUNCTION;
+
+#endif
+
+/*
+ * Return the amount of time, in ticks, that will pass before the kernel will
+ * next move a task from the Blocked state to the Running state.
+ *
+ * This conditional compilation should use inequality to 0, not equality to 1.
+ * This is to ensure portSUPPRESS_TICKS_AND_SLEEP() can be called when user
+ * defined low power mode implementations require configUSE_TICKLESS_IDLE to be
+ * set to a value other than 1.
+ */
+#if ( configUSE_TICKLESS_IDLE != 0 )
+
+	static TickType_t prvGetExpectedIdleTime( void ) PRIVILEGED_FUNCTION;
+
+#endif
+
+/*
+ * Set xNextTaskUnblockTime to the time at which the next Blocked state task
+ * will exit the Blocked state.
+ */
+static void prvResetNextTaskUnblockTime( void );
+
+#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) )
+
+	/*
+	 * Helper function used to pad task names with spaces when printing out
+	 * human readable tables of task information.
+	 */
+	static char *prvWriteNameToBuffer( char *pcBuffer, const char *pcTaskName );
+
+#endif
+/*-----------------------------------------------------------*/
+
+BaseType_t xTaskGenericCreate( TaskFunction_t pxTaskCode, const char * const pcName, const uint16_t usStackDepth, void * const pvParameters, UBaseType_t uxPriority, TaskHandle_t * const pxCreatedTask, StackType_t * const puxStackBuffer, const MemoryRegion_t * const xRegions ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+{
+BaseType_t xReturn;
+TCB_t * pxNewTCB;
+StackType_t *pxTopOfStack;
+
+	configASSERT( pxTaskCode );
+	configASSERT( ( ( uxPriority & ( UBaseType_t ) ( ~portPRIVILEGE_BIT ) ) < ( UBaseType_t ) configMAX_PRIORITIES ) );
+
+	/* Allocate the memory required by the TCB and stack for the new task,
+	checking that the allocation was successful. */
+	pxNewTCB = prvAllocateTCBAndStack( usStackDepth, puxStackBuffer );
+
+	if( pxNewTCB != NULL )
+	{
+		#if( portUSING_MPU_WRAPPERS == 1 )
+			/* Should the task be created in privileged mode? */
+			BaseType_t xRunPrivileged;
+			if( ( uxPriority & portPRIVILEGE_BIT ) != 0U )
+			{
+				xRunPrivileged = pdTRUE;
+			}
+			else
+			{
+				xRunPrivileged = pdFALSE;
+			}
+			uxPriority &= ~portPRIVILEGE_BIT;
+
+			if( puxStackBuffer != NULL )
+			{
+				/* The application provided its own stack.  Note this so no
+				attempt is made to delete the stack should that task be
+				deleted. */
+				pxNewTCB->xUsingStaticallyAllocatedStack = pdTRUE;
+			}
+			else
+			{
+				/* The stack was allocated dynamically.  Note this so it can be
+				deleted again if the task is deleted. */
+				pxNewTCB->xUsingStaticallyAllocatedStack = pdFALSE;
+			}
+		#endif /* portUSING_MPU_WRAPPERS == 1 */
+
+		/* Calculate the top of stack address.  This depends on whether the
+		stack grows from high memory to low (as per the 80x86) or vice versa.
+		portSTACK_GROWTH is used to make the result positive or negative as
+		required by the port. */
+		#if( portSTACK_GROWTH < 0 )
+		{
+			pxTopOfStack = pxNewTCB->pxStack + ( usStackDepth - ( uint16_t ) 1 );
+			pxTopOfStack = ( StackType_t * ) ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) ); /*lint !e923 MISRA exception.  Avoiding casts between pointers and integers is not practical.  Size differences accounted for using portPOINTER_SIZE_TYPE type. */
+
+			/* Check the alignment of the calculated top of stack is correct. */
+			configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxTopOfStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) );
+		}
+		#else /* portSTACK_GROWTH */
+		{
+			pxTopOfStack = pxNewTCB->pxStack;
+
+			/* Check the alignment of the stack buffer is correct. */
+			configASSERT( ( ( ( portPOINTER_SIZE_TYPE ) pxNewTCB->pxStack & ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) == 0UL ) );
+
+			/* If we want to use stack checking on architectures that use
+			a positive stack growth direction then we also need to store the
+			other extreme of the stack space. */
+			pxNewTCB->pxEndOfStack = pxNewTCB->pxStack + ( usStackDepth - 1 );
+		}
+		#endif /* portSTACK_GROWTH */
+
+		/* Setup the newly allocated TCB with the initial state of the task. */
+		prvInitialiseTCBVariables( pxNewTCB, pcName, uxPriority, xRegions, usStackDepth );
+
+		/* Initialize the TCB stack to look as if the task was already running,
+		but had been interrupted by the scheduler.  The return address is set
+		to the start of the task function. Once the stack has been initialised
+		the	top of stack variable is updated. */
+		#if( portUSING_MPU_WRAPPERS == 1 )
+		{
+			pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters, xRunPrivileged );
+		}
+		#else /* portUSING_MPU_WRAPPERS */
+		{
+			pxNewTCB->pxTopOfStack = pxPortInitialiseStack( pxTopOfStack, pxTaskCode, pvParameters );
+		}
+		#endif /* portUSING_MPU_WRAPPERS */
+
+		if( ( void * ) pxCreatedTask != NULL )
+		{
+			/* Pass the TCB out - in an anonymous way.  The calling function/
+			task can use this as a handle to delete the task later if
+			required.*/
+			*pxCreatedTask = ( TaskHandle_t ) pxNewTCB;
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+
+		/* Ensure interrupts don't access the task lists while they are being
+		updated. */
+		taskENTER_CRITICAL();
+		{
+			uxCurrentNumberOfTasks++;
+			if( pxCurrentTCB == NULL )
+			{
+				/* There are no other tasks, or all the other tasks are in
+				the suspended state - make this the current task. */
+				pxCurrentTCB =  pxNewTCB;
+
+				if( uxCurrentNumberOfTasks == ( UBaseType_t ) 1 )
+				{
+					/* This is the first task to be created so do the preliminary
+					initialisation required.  We will not recover if this call
+					fails, but we will report the failure. */
+					prvInitialiseTaskLists();
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			else
+			{
+				/* If the scheduler is not already running, make this task the
+				current task if it is the highest priority task to be created
+				so far. */
+				if( xSchedulerRunning == pdFALSE )
+				{
+					if( pxCurrentTCB->uxPriority <= uxPriority )
+					{
+						pxCurrentTCB = pxNewTCB;
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+
+			uxTaskNumber++;
+
+			#if ( configUSE_TRACE_FACILITY == 1 )
+			{
+				/* Add a counter into the TCB for tracing only. */
+				pxNewTCB->uxTCBNumber = uxTaskNumber;
+			}
+			#endif /* configUSE_TRACE_FACILITY */
+			traceTASK_CREATE( pxNewTCB );
+
+			prvAddTaskToReadyList( pxNewTCB );
+
+			xReturn = pdPASS;
+			portSETUP_TCB( pxNewTCB );
+		}
+		taskEXIT_CRITICAL();
+	}
+	else
+	{
+		xReturn = errCOULD_NOT_ALLOCATE_REQUIRED_MEMORY;
+		traceTASK_CREATE_FAILED();
+	}
+
+	if( xReturn == pdPASS )
+	{
+		if( xSchedulerRunning != pdFALSE )
+		{
+			/* If the created task is of a higher priority than the current task
+			then it should run now. */
+			if( pxCurrentTCB->uxPriority < uxPriority )
+			{
+				taskYIELD_IF_USING_PREEMPTION();
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+
+	return xReturn;
+}
+/*-----------------------------------------------------------*/
+
+#if ( INCLUDE_vTaskDelete == 1 )
+
+	void vTaskDelete( TaskHandle_t xTaskToDelete )
+	{
+	TCB_t *pxTCB;
+
+		taskENTER_CRITICAL();
+		{
+			/* If null is passed in here then it is the calling task that is
+			being deleted. */
+			pxTCB = prvGetTCBFromHandle( xTaskToDelete );
+
+			/* Remove task from the ready list and place in the	termination list.
+			This will stop the task from be scheduled.  The idle task will check
+			the termination list and free up any memory allocated by the
+			scheduler for the TCB and stack. */
+			if( uxListRemove( &( pxTCB->xGenericListItem ) ) == ( UBaseType_t ) 0 )
+			{
+				taskRESET_READY_PRIORITY( pxTCB->uxPriority );
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+
+			/* Is the task waiting on an event also? */
+			if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
+			{
+				( void ) uxListRemove( &( pxTCB->xEventListItem ) );
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+
+			vListInsertEnd( &xTasksWaitingTermination, &( pxTCB->xGenericListItem ) );
+
+			/* Increment the ucTasksDeleted variable so the idle task knows
+			there is a task that has been deleted and that it should therefore
+			check the xTasksWaitingTermination list. */
+			++uxTasksDeleted;
+
+			/* Increment the uxTaskNumberVariable also so kernel aware debuggers
+			can detect that the task lists need re-generating. */
+			uxTaskNumber++;
+
+			traceTASK_DELETE( pxTCB );
+		}
+		taskEXIT_CRITICAL();
+
+		/* Force a reschedule if it is the currently running task that has just
+		been deleted. */
+		if( xSchedulerRunning != pdFALSE )
+		{
+			if( pxTCB == pxCurrentTCB )
+			{
+				configASSERT( uxSchedulerSuspended == 0 );
+
+				/* The pre-delete hook is primarily for the Windows simulator,
+				in which Windows specific clean up operations are performed,
+				after which it is not possible to yield away from this task -
+				hence xYieldPending is used to latch that a context switch is
+				required. */
+				portPRE_TASK_DELETE_HOOK( pxTCB, &xYieldPending );
+				portYIELD_WITHIN_API();
+			}
+			else
+			{
+				/* Reset the next expected unblock time in case it referred to
+				the task that has just been deleted. */
+				taskENTER_CRITICAL();
+				{
+					prvResetNextTaskUnblockTime();
+				}
+				taskEXIT_CRITICAL();
+			}
+		}
+	}
+
+#endif /* INCLUDE_vTaskDelete */
+/*-----------------------------------------------------------*/
+
+#if ( INCLUDE_vTaskDelayUntil == 1 )
+
+	void vTaskDelayUntil( TickType_t * const pxPreviousWakeTime, const TickType_t xTimeIncrement )
+	{
+	TickType_t xTimeToWake;
+	BaseType_t xAlreadyYielded, xShouldDelay = pdFALSE;
+
+		configASSERT( pxPreviousWakeTime );
+		configASSERT( ( xTimeIncrement > 0U ) );
+		configASSERT( uxSchedulerSuspended == 0 );
+
+		vTaskSuspendAll();
+		{
+			/* Minor optimisation.  The tick count cannot change in this
+			block. */
+			const TickType_t xConstTickCount = xTickCount;
+
+			/* Generate the tick time at which the task wants to wake. */
+			xTimeToWake = *pxPreviousWakeTime + xTimeIncrement;
+
+			if( xConstTickCount < *pxPreviousWakeTime )
+			{
+				/* The tick count has overflowed since this function was
+				lasted called.  In this case the only time we should ever
+				actually delay is if the wake time has also	overflowed,
+				and the wake time is greater than the tick time.  When this
+				is the case it is as if neither time had overflowed. */
+				if( ( xTimeToWake < *pxPreviousWakeTime ) && ( xTimeToWake > xConstTickCount ) )
+				{
+					xShouldDelay = pdTRUE;
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			else
+			{
+				/* The tick time has not overflowed.  In this case we will
+				delay if either the wake time has overflowed, and/or the
+				tick time is less than the wake time. */
+				if( ( xTimeToWake < *pxPreviousWakeTime ) || ( xTimeToWake > xConstTickCount ) )
+				{
+					xShouldDelay = pdTRUE;
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+
+			/* Update the wake time ready for the next call. */
+			*pxPreviousWakeTime = xTimeToWake;
+
+			if( xShouldDelay != pdFALSE )
+			{
+				traceTASK_DELAY_UNTIL();
+
+				/* Remove the task from the ready list before adding it to the
+				blocked list as the same list item is used for both lists. */
+				if( uxListRemove( &( pxCurrentTCB->xGenericListItem ) ) == ( UBaseType_t ) 0 )
+				{
+					/* The current task must be in a ready list, so there is
+					no need to check, and the port reset macro can be called
+					directly. */
+					portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority );
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+
+				prvAddCurrentTaskToDelayedList( xTimeToWake );
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		xAlreadyYielded = xTaskResumeAll();
+
+		/* Force a reschedule if xTaskResumeAll has not already done so, we may
+		have put ourselves to sleep. */
+		if( xAlreadyYielded == pdFALSE )
+		{
+			portYIELD_WITHIN_API();
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+
+#endif /* INCLUDE_vTaskDelayUntil */
+/*-----------------------------------------------------------*/
+
+#if ( INCLUDE_vTaskDelay == 1 )
+
+	void vTaskDelay( const TickType_t xTicksToDelay )
+	{
+	TickType_t xTimeToWake;
+	BaseType_t xAlreadyYielded = pdFALSE;
+
+
+		/* A delay time of zero just forces a reschedule. */
+		if( xTicksToDelay > ( TickType_t ) 0U )
+		{
+			configASSERT( uxSchedulerSuspended == 0 );
+			vTaskSuspendAll();
+			{
+				traceTASK_DELAY();
+
+				/* A task that is removed from the event list while the
+				scheduler is suspended will not get placed in the ready
+				list or removed from the blocked list until the scheduler
+				is resumed.
+
+				This task cannot be in an event list as it is the currently
+				executing task. */
+
+				/* Calculate the time to wake - this may overflow but this is
+				not a problem. */
+				xTimeToWake = xTickCount + xTicksToDelay;
+
+				/* We must remove ourselves from the ready list before adding
+				ourselves to the blocked list as the same list item is used for
+				both lists. */
+				if( uxListRemove( &( pxCurrentTCB->xGenericListItem ) ) == ( UBaseType_t ) 0 )
+				{
+					/* The current task must be in a ready list, so there is
+					no need to check, and the port reset macro can be called
+					directly. */
+					portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority );
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+				prvAddCurrentTaskToDelayedList( xTimeToWake );
+			}
+			xAlreadyYielded = xTaskResumeAll();
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+
+		/* Force a reschedule if xTaskResumeAll has not already done so, we may
+		have put ourselves to sleep. */
+		if( xAlreadyYielded == pdFALSE )
+		{
+			portYIELD_WITHIN_API();
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+
+#endif /* INCLUDE_vTaskDelay */
+/*-----------------------------------------------------------*/
+
+#if ( INCLUDE_eTaskGetState == 1 )
+
+	eTaskState eTaskGetState( TaskHandle_t xTask )
+	{
+	eTaskState eReturn;
+	List_t *pxStateList;
+	const TCB_t * const pxTCB = ( TCB_t * ) xTask;
+
+		configASSERT( pxTCB );
+
+		if( pxTCB == pxCurrentTCB )
+		{
+			/* The task calling this function is querying its own state. */
+			eReturn = eRunning;
+		}
+		else
+		{
+			taskENTER_CRITICAL();
+			{
+				pxStateList = ( List_t * ) listLIST_ITEM_CONTAINER( &( pxTCB->xGenericListItem ) );
+			}
+			taskEXIT_CRITICAL();
+
+			if( ( pxStateList == pxDelayedTaskList ) || ( pxStateList == pxOverflowDelayedTaskList ) )
+			{
+				/* The task being queried is referenced from one of the Blocked
+				lists. */
+				eReturn = eBlocked;
+			}
+
+			#if ( INCLUDE_vTaskSuspend == 1 )
+				else if( pxStateList == &xSuspendedTaskList )
+				{
+					/* The task being queried is referenced from the suspended
+					list.  Is it genuinely suspended or is it block
+					indefinitely? */
+					if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL )
+					{
+						eReturn = eSuspended;
+					}
+					else
+					{
+						eReturn = eBlocked;
+					}
+				}
+			#endif
+
+			#if ( INCLUDE_vTaskDelete == 1 )
+				else if( pxStateList == &xTasksWaitingTermination )
+				{
+					/* The task being queried is referenced from the deleted
+					tasks list. */
+					eReturn = eDeleted;
+				}
+			#endif
+
+			else /*lint !e525 Negative indentation is intended to make use of pre-processor clearer. */
+			{
+				/* If the task is not in any other state, it must be in the
+				Ready (including pending ready) state. */
+				eReturn = eReady;
+			}
+		}
+
+		return eReturn;
+	} /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */
+
+#endif /* INCLUDE_eTaskGetState */
+/*-----------------------------------------------------------*/
+
+#if ( INCLUDE_uxTaskPriorityGet == 1 )
+
+	UBaseType_t uxTaskPriorityGet( TaskHandle_t xTask )
+	{
+	TCB_t *pxTCB;
+	UBaseType_t uxReturn;
+
+		taskENTER_CRITICAL();
+		{
+			/* If null is passed in here then we are changing the
+			priority of the calling function. */
+			pxTCB = prvGetTCBFromHandle( xTask );
+			uxReturn = pxTCB->uxPriority;
+		}
+		taskEXIT_CRITICAL();
+
+		return uxReturn;
+	}
+
+#endif /* INCLUDE_uxTaskPriorityGet */
+/*-----------------------------------------------------------*/
+
+#if ( INCLUDE_uxTaskPriorityGet == 1 )
+
+	UBaseType_t uxTaskPriorityGetFromISR( TaskHandle_t xTask )
+	{
+	TCB_t *pxTCB;
+	UBaseType_t uxReturn, uxSavedInterruptState;
+
+		/* RTOS ports that support interrupt nesting have the concept of a
+		maximum	system call (or maximum API call) interrupt priority.
+		Interrupts that are	above the maximum system call priority are keep
+		permanently enabled, even when the RTOS kernel is in a critical section,
+		but cannot make any calls to FreeRTOS API functions.  If configASSERT()
+		is defined in FreeRTOSConfig.h then
+		portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
+		failure if a FreeRTOS API function is called from an interrupt that has
+		been assigned a priority above the configured maximum system call
+		priority.  Only FreeRTOS functions that end in FromISR can be called
+		from interrupts	that have been assigned a priority at or (logically)
+		below the maximum system call interrupt priority.  FreeRTOS maintains a
+		separate interrupt safe API to ensure interrupt entry is as fast and as
+		simple as possible.  More information (albeit Cortex-M specific) is
+		provided on the following link:
+		http://www.freertos.org/RTOS-Cortex-M3-M4.html */
+		portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+		uxSavedInterruptState = portSET_INTERRUPT_MASK_FROM_ISR();
+		{
+			/* If null is passed in here then it is the priority of the calling
+			task that is being queried. */
+			pxTCB = prvGetTCBFromHandle( xTask );
+			uxReturn = pxTCB->uxPriority;
+		}
+		portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptState );
+
+		return uxReturn;
+	}
+
+#endif /* INCLUDE_uxTaskPriorityGet */
+/*-----------------------------------------------------------*/
+
+#if ( INCLUDE_vTaskPrioritySet == 1 )
+
+	void vTaskPrioritySet( TaskHandle_t xTask, UBaseType_t uxNewPriority )
+	{
+	TCB_t *pxTCB;
+	UBaseType_t uxCurrentBasePriority, uxPriorityUsedOnEntry;
+	BaseType_t xYieldRequired = pdFALSE;
+
+		configASSERT( ( uxNewPriority < configMAX_PRIORITIES ) );
+
+		/* Ensure the new priority is valid. */
+		if( uxNewPriority >= ( UBaseType_t ) configMAX_PRIORITIES )
+		{
+			uxNewPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U;
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+
+		taskENTER_CRITICAL();
+		{
+			/* If null is passed in here then it is the priority of the calling
+			task that is being changed. */
+			pxTCB = prvGetTCBFromHandle( xTask );
+
+			traceTASK_PRIORITY_SET( pxTCB, uxNewPriority );
+
+			#if ( configUSE_MUTEXES == 1 )
+			{
+				uxCurrentBasePriority = pxTCB->uxBasePriority;
+			}
+			#else
+			{
+				uxCurrentBasePriority = pxTCB->uxPriority;
+			}
+			#endif
+
+			if( uxCurrentBasePriority != uxNewPriority )
+			{
+				/* The priority change may have readied a task of higher
+				priority than the calling task. */
+				if( uxNewPriority > uxCurrentBasePriority )
+				{
+					if( pxTCB != pxCurrentTCB )
+					{
+						/* The priority of a task other than the currently
+						running task is being raised.  Is the priority being
+						raised above that of the running task? */
+						if( uxNewPriority >= pxCurrentTCB->uxPriority )
+						{
+							xYieldRequired = pdTRUE;
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+					}
+					else
+					{
+						/* The priority of the running task is being raised,
+						but the running task must already be the highest
+						priority task able to run so no yield is required. */
+					}
+				}
+				else if( pxTCB == pxCurrentTCB )
+				{
+					/* Setting the priority of the running task down means
+					there may now be another task of higher priority that
+					is ready to execute. */
+					xYieldRequired = pdTRUE;
+				}
+				else
+				{
+					/* Setting the priority of any other task down does not
+					require a yield as the running task must be above the
+					new priority of the task being modified. */
+				}
+
+				/* Remember the ready list the task might be referenced from
+				before its uxPriority member is changed so the
+				taskRESET_READY_PRIORITY() macro can function correctly. */
+				uxPriorityUsedOnEntry = pxTCB->uxPriority;
+
+				#if ( configUSE_MUTEXES == 1 )
+				{
+					/* Only change the priority being used if the task is not
+					currently using an inherited priority. */
+					if( pxTCB->uxBasePriority == pxTCB->uxPriority )
+					{
+						pxTCB->uxPriority = uxNewPriority;
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+
+					/* The base priority gets set whatever. */
+					pxTCB->uxBasePriority = uxNewPriority;
+				}
+				#else
+				{
+					pxTCB->uxPriority = uxNewPriority;
+				}
+				#endif
+
+				/* Only reset the event list item value if the value is not
+				being used for anything else. */
+				if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL )
+				{
+					listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxNewPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+
+				/* If the task is in the blocked or suspended list we need do
+				nothing more than change it's priority variable. However, if
+				the task is in a ready list it needs to be removed and placed
+				in the list appropriate to its new priority. */
+				if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ uxPriorityUsedOnEntry ] ), &( pxTCB->xGenericListItem ) ) != pdFALSE )
+				{
+					/* The task is currently in its ready list - remove before adding
+					it to it's new ready list.  As we are in a critical section we
+					can do this even if the scheduler is suspended. */
+					if( uxListRemove( &( pxTCB->xGenericListItem ) ) == ( UBaseType_t ) 0 )
+					{
+						/* It is known that the task is in its ready list so
+						there is no need to check again and the port level
+						reset macro can be called directly. */
+						portRESET_READY_PRIORITY( uxPriorityUsedOnEntry, uxTopReadyPriority );
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+					prvAddTaskToReadyList( pxTCB );
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+
+				if( xYieldRequired == pdTRUE )
+				{
+					taskYIELD_IF_USING_PREEMPTION();
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+
+				/* Remove compiler warning about unused variables when the port
+				optimised task selection is not being used. */
+				( void ) uxPriorityUsedOnEntry;
+			}
+		}
+		taskEXIT_CRITICAL();
+	}
+
+#endif /* INCLUDE_vTaskPrioritySet */
+/*-----------------------------------------------------------*/
+
+#if ( INCLUDE_vTaskSuspend == 1 )
+
+	void vTaskSuspend( TaskHandle_t xTaskToSuspend )
+	{
+	TCB_t *pxTCB;
+
+		taskENTER_CRITICAL();
+		{
+			/* If null is passed in here then it is the running task that is
+			being suspended. */
+			pxTCB = prvGetTCBFromHandle( xTaskToSuspend );
+
+			traceTASK_SUSPEND( pxTCB );
+
+			/* Remove task from the ready/delayed list and place in the
+			suspended list. */
+			if( uxListRemove( &( pxTCB->xGenericListItem ) ) == ( UBaseType_t ) 0 )
+			{
+				taskRESET_READY_PRIORITY( pxTCB->uxPriority );
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+
+			/* Is the task waiting on an event also? */
+			if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
+			{
+				( void ) uxListRemove( &( pxTCB->xEventListItem ) );
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+
+			vListInsertEnd( &xSuspendedTaskList, &( pxTCB->xGenericListItem ) );
+		}
+		taskEXIT_CRITICAL();
+
+		if( pxTCB == pxCurrentTCB )
+		{
+			if( xSchedulerRunning != pdFALSE )
+			{
+				/* The current task has just been suspended. */
+				configASSERT( uxSchedulerSuspended == 0 );
+				portYIELD_WITHIN_API();
+			}
+			else
+			{
+				/* The scheduler is not running, but the task that was pointed
+				to by pxCurrentTCB has just been suspended and pxCurrentTCB
+				must be adjusted to point to a different task. */
+				if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == uxCurrentNumberOfTasks )
+				{
+					/* No other tasks are ready, so set pxCurrentTCB back to
+					NULL so when the next task is created pxCurrentTCB will
+					be set to point to it no matter what its relative priority
+					is. */
+					pxCurrentTCB = NULL;
+				}
+				else
+				{
+					vTaskSwitchContext();
+				}
+			}
+		}
+		else
+		{
+			if( xSchedulerRunning != pdFALSE )
+			{
+				/* A task other than the currently running task was suspended,
+				reset the next expected unblock time in case it referred to the
+				task that is now in the Suspended state. */
+				taskENTER_CRITICAL();
+				{
+					prvResetNextTaskUnblockTime();
+				}
+				taskEXIT_CRITICAL();
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+	}
+
+#endif /* INCLUDE_vTaskSuspend */
+/*-----------------------------------------------------------*/
+
+#if ( INCLUDE_vTaskSuspend == 1 )
+
+	static BaseType_t prvTaskIsTaskSuspended( const TaskHandle_t xTask )
+	{
+	BaseType_t xReturn = pdFALSE;
+	const TCB_t * const pxTCB = ( TCB_t * ) xTask;
+
+		/* Accesses xPendingReadyList so must be called from a critical
+		section. */
+
+		/* It does not make sense to check if the calling task is suspended. */
+		configASSERT( xTask );
+
+		/* Is the task being resumed actually in the suspended list? */
+		if( listIS_CONTAINED_WITHIN( &xSuspendedTaskList, &( pxTCB->xGenericListItem ) ) != pdFALSE )
+		{
+			/* Has the task already been resumed from within an ISR? */
+			if( listIS_CONTAINED_WITHIN( &xPendingReadyList, &( pxTCB->xEventListItem ) ) == pdFALSE )
+			{
+				/* Is it in the suspended list because it is in the	Suspended
+				state, or because is is blocked with no timeout? */
+				if( listIS_CONTAINED_WITHIN( NULL, &( pxTCB->xEventListItem ) ) != pdFALSE )
+				{
+					xReturn = pdTRUE;
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+
+		return xReturn;
+	} /*lint !e818 xTask cannot be a pointer to const because it is a typedef. */
+
+#endif /* INCLUDE_vTaskSuspend */
+/*-----------------------------------------------------------*/
+
+#if ( INCLUDE_vTaskSuspend == 1 )
+
+	void vTaskResume( TaskHandle_t xTaskToResume )
+	{
+	TCB_t * const pxTCB = ( TCB_t * ) xTaskToResume;
+
+		/* It does not make sense to resume the calling task. */
+		configASSERT( xTaskToResume );
+
+		/* The parameter cannot be NULL as it is impossible to resume the
+		currently executing task. */
+		if( ( pxTCB != NULL ) && ( pxTCB != pxCurrentTCB ) )
+		{
+			taskENTER_CRITICAL();
+			{
+				if( prvTaskIsTaskSuspended( pxTCB ) == pdTRUE )
+				{
+					traceTASK_RESUME( pxTCB );
+
+					/* As we are in a critical section we can access the ready
+					lists even if the scheduler is suspended. */
+					( void ) uxListRemove(  &( pxTCB->xGenericListItem ) );
+					prvAddTaskToReadyList( pxTCB );
+
+					/* We may have just resumed a higher priority task. */
+					if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority )
+					{
+						/* This yield may not cause the task just resumed to run,
+						but will leave the lists in the correct state for the
+						next yield. */
+						taskYIELD_IF_USING_PREEMPTION();
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			taskEXIT_CRITICAL();
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+
+#endif /* INCLUDE_vTaskSuspend */
+
+/*-----------------------------------------------------------*/
+
+#if ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) )
+
+	BaseType_t xTaskResumeFromISR( TaskHandle_t xTaskToResume )
+	{
+	BaseType_t xYieldRequired = pdFALSE;
+	TCB_t * const pxTCB = ( TCB_t * ) xTaskToResume;
+	UBaseType_t uxSavedInterruptStatus;
+
+		configASSERT( xTaskToResume );
+
+		/* RTOS ports that support interrupt nesting have the concept of a
+		maximum	system call (or maximum API call) interrupt priority.
+		Interrupts that are	above the maximum system call priority are keep
+		permanently enabled, even when the RTOS kernel is in a critical section,
+		but cannot make any calls to FreeRTOS API functions.  If configASSERT()
+		is defined in FreeRTOSConfig.h then
+		portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
+		failure if a FreeRTOS API function is called from an interrupt that has
+		been assigned a priority above the configured maximum system call
+		priority.  Only FreeRTOS functions that end in FromISR can be called
+		from interrupts	that have been assigned a priority at or (logically)
+		below the maximum system call interrupt priority.  FreeRTOS maintains a
+		separate interrupt safe API to ensure interrupt entry is as fast and as
+		simple as possible.  More information (albeit Cortex-M specific) is
+		provided on the following link:
+		http://www.freertos.org/RTOS-Cortex-M3-M4.html */
+		portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+		uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
+		{
+			if( prvTaskIsTaskSuspended( pxTCB ) == pdTRUE )
+			{
+				traceTASK_RESUME_FROM_ISR( pxTCB );
+
+				/* Check the ready lists can be accessed. */
+				if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
+				{
+					/* Ready lists can be accessed so move the task from the
+					suspended list to the ready list directly. */
+					if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority )
+					{
+						xYieldRequired = pdTRUE;
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+
+					( void ) uxListRemove(  &( pxTCB->xGenericListItem ) );
+					prvAddTaskToReadyList( pxTCB );
+				}
+				else
+				{
+					/* The delayed or ready lists cannot be accessed so the task
+					is held in the pending ready list until the scheduler is
+					unsuspended. */
+					vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) );
+				}
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
+
+		return xYieldRequired;
+	}
+
+#endif /* ( ( INCLUDE_xTaskResumeFromISR == 1 ) && ( INCLUDE_vTaskSuspend == 1 ) ) */
+/*-----------------------------------------------------------*/
+
+void vTaskStartScheduler( void )
+{
+BaseType_t xReturn;
+
+	/* Add the idle task at the lowest priority. */
+	#if ( INCLUDE_xTaskGetIdleTaskHandle == 1 )
+	{
+		/* Create the idle task, storing its handle in xIdleTaskHandle so it can
+		be returned by the xTaskGetIdleTaskHandle() function. */
+		xReturn = xTaskCreate( prvIdleTask, "IDLE", tskIDLE_STACK_SIZE, ( void * ) NULL, ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), &xIdleTaskHandle ); /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */
+	}
+	#else
+	{
+		/* Create the idle task without storing its handle. */
+		xReturn = xTaskCreate( prvIdleTask, "IDLE", tskIDLE_STACK_SIZE, ( void * ) NULL, ( tskIDLE_PRIORITY | portPRIVILEGE_BIT ), NULL );  /*lint !e961 MISRA exception, justified as it is not a redundant explicit cast to all supported compilers. */
+	}
+	#endif /* INCLUDE_xTaskGetIdleTaskHandle */
+
+	#if ( configUSE_TIMERS == 1 )
+	{
+		if( xReturn == pdPASS )
+		{
+			xReturn = xTimerCreateTimerTask();
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+	#endif /* configUSE_TIMERS */
+
+	if( xReturn == pdPASS )
+	{
+		/* Interrupts are turned off here, to ensure a tick does not occur
+		before or during the call to xPortStartScheduler().  The stacks of
+		the created tasks contain a status word with interrupts switched on
+		so interrupts will automatically get re-enabled when the first task
+		starts to run. */
+		portDISABLE_INTERRUPTS();
+
+		#if ( configUSE_NEWLIB_REENTRANT == 1 )
+		{
+			/* Switch Newlib's _impure_ptr variable to point to the _reent
+			structure specific to the task that will run first. */
+			_impure_ptr = &( pxCurrentTCB->xNewLib_reent );
+		}
+		#endif /* configUSE_NEWLIB_REENTRANT */
+
+		xSchedulerRunning = pdTRUE;
+		xTickCount = ( TickType_t ) 0U;
+
+		/* If configGENERATE_RUN_TIME_STATS is defined then the following
+		macro must be defined to configure the timer/counter used to generate
+		the run time counter time base. */
+		portCONFIGURE_TIMER_FOR_RUN_TIME_STATS();
+
+		/* Setting up the timer tick is hardware specific and thus in the
+		portable interface. */
+		if( xPortStartScheduler() != pdFALSE )
+		{
+			/* Should not reach here as if the scheduler is running the
+			function will not return. */
+		}
+		else
+		{
+			/* Should only reach here if a task calls xTaskEndScheduler(). */
+		}
+	}
+	else
+	{
+		/* This line will only be reached if the kernel could not be started,
+		because there was not enough FreeRTOS heap to create the idle task
+		or the timer task. */
+		configASSERT( xReturn );
+	}
+}
+/*-----------------------------------------------------------*/
+
+void vTaskEndScheduler( void )
+{
+	/* Stop the scheduler interrupts and call the portable scheduler end
+	routine so the original ISRs can be restored if necessary.  The port
+	layer must ensure interrupts enable	bit is left in the correct state. */
+	portDISABLE_INTERRUPTS();
+	xSchedulerRunning = pdFALSE;
+	vPortEndScheduler();
+}
+/*----------------------------------------------------------*/
+
+void vTaskSuspendAll( void )
+{
+	/* A critical section is not required as the variable is of type
+	BaseType_t.  Please read Richard Barry's reply in the following link to a
+	post in the FreeRTOS support forum before reporting this as a bug! -
+	http://goo.gl/wu4acr */
+	++uxSchedulerSuspended;
+}
+/*----------------------------------------------------------*/
+
+#if ( configUSE_TICKLESS_IDLE != 0 )
+
+	static TickType_t prvGetExpectedIdleTime( void )
+	{
+	TickType_t xReturn;
+
+		if( pxCurrentTCB->uxPriority > tskIDLE_PRIORITY )
+		{
+			xReturn = 0;
+		}
+		else if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > 1 )
+		{
+			/* There are other idle priority tasks in the ready state.  If
+			time slicing is used then the very next tick interrupt must be
+			processed. */
+			xReturn = 0;
+		}
+		else
+		{
+			xReturn = xNextTaskUnblockTime - xTickCount;
+		}
+
+		return xReturn;
+	}
+
+#endif /* configUSE_TICKLESS_IDLE */
+/*----------------------------------------------------------*/
+
+BaseType_t xTaskResumeAll( void )
+{
+TCB_t *pxTCB;
+BaseType_t xAlreadyYielded = pdFALSE;
+
+	/* If uxSchedulerSuspended is zero then this function does not match a
+	previous call to vTaskSuspendAll(). */
+	configASSERT( uxSchedulerSuspended );
+
+	/* It is possible that an ISR caused a task to be removed from an event
+	list while the scheduler was suspended.  If this was the case then the
+	removed task will have been added to the xPendingReadyList.  Once the
+	scheduler has been resumed it is safe to move all the pending ready
+	tasks from this list into their appropriate ready list. */
+	taskENTER_CRITICAL();
+	{
+		--uxSchedulerSuspended;
+
+		if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
+		{
+			if( uxCurrentNumberOfTasks > ( UBaseType_t ) 0U )
+			{
+				/* Move any readied tasks from the pending list into the
+				appropriate ready list. */
+				while( listLIST_IS_EMPTY( &xPendingReadyList ) == pdFALSE )
+				{
+					pxTCB = ( TCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( ( &xPendingReadyList ) );
+					( void ) uxListRemove( &( pxTCB->xEventListItem ) );
+					( void ) uxListRemove( &( pxTCB->xGenericListItem ) );
+					prvAddTaskToReadyList( pxTCB );
+
+					/* If the moved task has a priority higher than the current
+					task then a yield must be performed. */
+					if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority )
+					{
+						xYieldPending = pdTRUE;
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+
+				/* If any ticks occurred while the scheduler was suspended then
+				they should be processed now.  This ensures the tick count does
+				not	slip, and that any delayed tasks are resumed at the correct
+				time. */
+				if( uxPendedTicks > ( UBaseType_t ) 0U )
+				{
+					while( uxPendedTicks > ( UBaseType_t ) 0U )
+					{
+						if( xTaskIncrementTick() != pdFALSE )
+						{
+							xYieldPending = pdTRUE;
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+						--uxPendedTicks;
+					}
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+
+				if( xYieldPending == pdTRUE )
+				{
+					#if( configUSE_PREEMPTION != 0 )
+					{
+						xAlreadyYielded = pdTRUE;
+					}
+					#endif
+					taskYIELD_IF_USING_PREEMPTION();
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+	taskEXIT_CRITICAL();
+
+	return xAlreadyYielded;
+}
+/*-----------------------------------------------------------*/
+
+TickType_t xTaskGetTickCount( void )
+{
+TickType_t xTicks;
+
+	/* Critical section required if running on a 16 bit processor. */
+	portTICK_TYPE_ENTER_CRITICAL();
+	{
+		xTicks = xTickCount;
+	}
+	portTICK_TYPE_EXIT_CRITICAL();
+
+	return xTicks;
+}
+/*-----------------------------------------------------------*/
+
+TickType_t xTaskGetTickCountFromISR( void )
+{
+TickType_t xReturn;
+UBaseType_t uxSavedInterruptStatus;
+
+	/* RTOS ports that support interrupt nesting have the concept of a maximum
+	system call (or maximum API call) interrupt priority.  Interrupts that are
+	above the maximum system call priority are kept permanently enabled, even
+	when the RTOS kernel is in a critical section, but cannot make any calls to
+	FreeRTOS API functions.  If configASSERT() is defined in FreeRTOSConfig.h
+	then portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
+	failure if a FreeRTOS API function is called from an interrupt that has been
+	assigned a priority above the configured maximum system call priority.
+	Only FreeRTOS functions that end in FromISR can be called from interrupts
+	that have been assigned a priority at or (logically) below the maximum
+	system call	interrupt priority.  FreeRTOS maintains a separate interrupt
+	safe API to ensure interrupt entry is as fast and as simple as possible.
+	More information (albeit Cortex-M specific) is provided on the following
+	link: http://www.freertos.org/RTOS-Cortex-M3-M4.html */
+	portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+	uxSavedInterruptStatus = portTICK_TYPE_SET_INTERRUPT_MASK_FROM_ISR();
+	{
+		xReturn = xTickCount;
+	}
+	portTICK_TYPE_CLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
+
+	return xReturn;
+}
+/*-----------------------------------------------------------*/
+
+UBaseType_t uxTaskGetNumberOfTasks( void )
+{
+	/* A critical section is not required because the variables are of type
+	BaseType_t. */
+	return uxCurrentNumberOfTasks;
+}
+/*-----------------------------------------------------------*/
+
+#if ( INCLUDE_pcTaskGetTaskName == 1 )
+
+	char *pcTaskGetTaskName( TaskHandle_t xTaskToQuery ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+	{
+	TCB_t *pxTCB;
+
+		/* If null is passed in here then the name of the calling task is being queried. */
+		pxTCB = prvGetTCBFromHandle( xTaskToQuery );
+		configASSERT( pxTCB );
+		return &( pxTCB->pcTaskName[ 0 ] );
+	}
+
+#endif /* INCLUDE_pcTaskGetTaskName */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_TRACE_FACILITY == 1 )
+
+	UBaseType_t uxTaskGetSystemState( TaskStatus_t * const pxTaskStatusArray, const UBaseType_t uxArraySize, uint32_t * const pulTotalRunTime )
+	{
+	UBaseType_t uxTask = 0, uxQueue = configMAX_PRIORITIES;
+
+		vTaskSuspendAll();
+		{
+			/* Is there a space in the array for each task in the system? */
+			if( uxArraySize >= uxCurrentNumberOfTasks )
+			{
+				/* Fill in an TaskStatus_t structure with information on each
+				task in the Ready state. */
+				do
+				{
+					uxQueue--;
+					uxTask += prvListTaskWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &( pxReadyTasksLists[ uxQueue ] ), eReady );
+
+				} while( uxQueue > ( UBaseType_t ) tskIDLE_PRIORITY ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+
+				/* Fill in an TaskStatus_t structure with information on each
+				task in the Blocked state. */
+				uxTask += prvListTaskWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxDelayedTaskList, eBlocked );
+				uxTask += prvListTaskWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), ( List_t * ) pxOverflowDelayedTaskList, eBlocked );
+
+				#if( INCLUDE_vTaskDelete == 1 )
+				{
+					/* Fill in an TaskStatus_t structure with information on
+					each task that has been deleted but not yet cleaned up. */
+					uxTask += prvListTaskWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xTasksWaitingTermination, eDeleted );
+				}
+				#endif
+
+				#if ( INCLUDE_vTaskSuspend == 1 )
+				{
+					/* Fill in an TaskStatus_t structure with information on
+					each task in the Suspended state. */
+					uxTask += prvListTaskWithinSingleList( &( pxTaskStatusArray[ uxTask ] ), &xSuspendedTaskList, eSuspended );
+				}
+				#endif
+
+				#if ( configGENERATE_RUN_TIME_STATS == 1)
+				{
+					if( pulTotalRunTime != NULL )
+					{
+						#ifdef portALT_GET_RUN_TIME_COUNTER_VALUE
+							portALT_GET_RUN_TIME_COUNTER_VALUE( ( *pulTotalRunTime ) );
+						#else
+							*pulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE();
+						#endif
+					}
+				}
+				#else
+				{
+					if( pulTotalRunTime != NULL )
+					{
+						*pulTotalRunTime = 0;
+					}
+				}
+				#endif
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		( void ) xTaskResumeAll();
+
+		return uxTask;
+	}
+
+#endif /* configUSE_TRACE_FACILITY */
+/*----------------------------------------------------------*/
+
+#if ( INCLUDE_xTaskGetIdleTaskHandle == 1 )
+
+	TaskHandle_t xTaskGetIdleTaskHandle( void )
+	{
+		/* If xTaskGetIdleTaskHandle() is called before the scheduler has been
+		started, then xIdleTaskHandle will be NULL. */
+		configASSERT( ( xIdleTaskHandle != NULL ) );
+		return xIdleTaskHandle;
+	}
+
+#endif /* INCLUDE_xTaskGetIdleTaskHandle */
+/*----------------------------------------------------------*/
+
+/* This conditional compilation should use inequality to 0, not equality to 1.
+This is to ensure vTaskStepTick() is available when user defined low power mode
+implementations require configUSE_TICKLESS_IDLE to be set to a value other than
+1. */
+#if ( configUSE_TICKLESS_IDLE != 0 )
+
+	void vTaskStepTick( const TickType_t xTicksToJump )
+	{
+		/* Correct the tick count value after a period during which the tick
+		was suppressed.  Note this does *not* call the tick hook function for
+		each stepped tick. */
+		configASSERT( ( xTickCount + xTicksToJump ) <= xNextTaskUnblockTime );
+		xTickCount += xTicksToJump;
+		traceINCREASE_TICK_COUNT( xTicksToJump );
+	}
+
+#endif /* configUSE_TICKLESS_IDLE */
+/*----------------------------------------------------------*/
+
+BaseType_t xTaskIncrementTick( void )
+{
+TCB_t * pxTCB;
+TickType_t xItemValue;
+BaseType_t xSwitchRequired = pdFALSE;
+
+	/* Called by the portable layer each time a tick interrupt occurs.
+	Increments the tick then checks to see if the new tick value will cause any
+	tasks to be unblocked. */
+	traceTASK_INCREMENT_TICK( xTickCount );
+	if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
+	{
+		/* Increment the RTOS tick, switching the delayed and overflowed
+		delayed lists if it wraps to 0. */
+		++xTickCount;
+
+		{
+			/* Minor optimisation.  The tick count cannot change in this
+			block. */
+			const TickType_t xConstTickCount = xTickCount;
+
+			if( xConstTickCount == ( TickType_t ) 0U )
+			{
+				taskSWITCH_DELAYED_LISTS();
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+
+			/* See if this tick has made a timeout expire.  Tasks are stored in
+			the	queue in the order of their wake time - meaning once one task
+			has been found whose block time has not expired there is no need to
+			look any further down the list. */
+			if( xConstTickCount >= xNextTaskUnblockTime )
+			{
+				for( ;; )
+				{
+					if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE )
+					{
+						/* The delayed list is empty.  Set xNextTaskUnblockTime
+						to the maximum possible value so it is extremely
+						unlikely that the
+						if( xTickCount >= xNextTaskUnblockTime ) test will pass
+						next time through. */
+						xNextTaskUnblockTime = portMAX_DELAY;
+						break;
+					}
+					else
+					{
+						/* The delayed list is not empty, get the value of the
+						item at the head of the delayed list.  This is the time
+						at which the task at the head of the delayed list must
+						be removed from the Blocked state. */
+						pxTCB = ( TCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList );
+						xItemValue = listGET_LIST_ITEM_VALUE( &( pxTCB->xGenericListItem ) );
+
+						if( xConstTickCount < xItemValue )
+						{
+							/* It is not time to unblock this item yet, but the
+							item value is the time at which the task at the head
+							of the blocked list must be removed from the Blocked
+							state -	so record the item value in
+							xNextTaskUnblockTime. */
+							xNextTaskUnblockTime = xItemValue;
+							break;
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+
+						/* It is time to remove the item from the Blocked state. */
+						( void ) uxListRemove( &( pxTCB->xGenericListItem ) );
+
+						/* Is the task waiting on an event also?  If so remove
+						it from the event list. */
+						if( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) != NULL )
+						{
+							( void ) uxListRemove( &( pxTCB->xEventListItem ) );
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+
+						/* Place the unblocked task into the appropriate ready
+						list. */
+						prvAddTaskToReadyList( pxTCB );
+
+						/* A task being unblocked cannot cause an immediate
+						context switch if preemption is turned off. */
+						#if (  configUSE_PREEMPTION == 1 )
+						{
+							/* Preemption is on, but a context switch should
+							only be performed if the unblocked task has a
+							priority that is equal to or higher than the
+							currently executing task. */
+							if( pxTCB->uxPriority >= pxCurrentTCB->uxPriority )
+							{
+								xSwitchRequired = pdTRUE;
+							}
+							else
+							{
+								mtCOVERAGE_TEST_MARKER();
+							}
+						}
+						#endif /* configUSE_PREEMPTION */
+					}
+				}
+			}
+		}
+
+		/* Tasks of equal priority to the currently running task will share
+		processing time (time slice) if preemption is on, and the application
+		writer has not explicitly turned time slicing off. */
+		#if ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) )
+		{
+			if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ pxCurrentTCB->uxPriority ] ) ) > ( UBaseType_t ) 1 )
+			{
+				xSwitchRequired = pdTRUE;
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		#endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configUSE_TIME_SLICING == 1 ) ) */
+
+		#if ( configUSE_TICK_HOOK == 1 )
+		{
+			/* Guard against the tick hook being called when the pended tick
+			count is being unwound (when the scheduler is being unlocked). */
+			if( uxPendedTicks == ( UBaseType_t ) 0U )
+			{
+				vApplicationTickHook();
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		#endif /* configUSE_TICK_HOOK */
+	}
+	else
+	{
+		++uxPendedTicks;
+
+		/* The tick hook gets called at regular intervals, even if the
+		scheduler is locked. */
+		#if ( configUSE_TICK_HOOK == 1 )
+		{
+			vApplicationTickHook();
+		}
+		#endif
+	}
+
+	#if ( configUSE_PREEMPTION == 1 )
+	{
+		if( xYieldPending != pdFALSE )
+		{
+			xSwitchRequired = pdTRUE;
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+	#endif /* configUSE_PREEMPTION */
+
+	return xSwitchRequired;
+}
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_APPLICATION_TASK_TAG == 1 )
+
+	void vTaskSetApplicationTaskTag( TaskHandle_t xTask, TaskHookFunction_t pxHookFunction )
+	{
+	TCB_t *xTCB;
+
+		/* If xTask is NULL then it is the task hook of the calling task that is
+		getting set. */
+		if( xTask == NULL )
+		{
+			xTCB = ( TCB_t * ) pxCurrentTCB;
+		}
+		else
+		{
+			xTCB = ( TCB_t * ) xTask;
+		}
+
+		/* Save the hook function in the TCB.  A critical section is required as
+		the value can be accessed from an interrupt. */
+		taskENTER_CRITICAL();
+			xTCB->pxTaskTag = pxHookFunction;
+		taskEXIT_CRITICAL();
+	}
+
+#endif /* configUSE_APPLICATION_TASK_TAG */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_APPLICATION_TASK_TAG == 1 )
+
+	TaskHookFunction_t xTaskGetApplicationTaskTag( TaskHandle_t xTask )
+	{
+	TCB_t *xTCB;
+	TaskHookFunction_t xReturn;
+
+		/* If xTask is NULL then we are setting our own task hook. */
+		if( xTask == NULL )
+		{
+			xTCB = ( TCB_t * ) pxCurrentTCB;
+		}
+		else
+		{
+			xTCB = ( TCB_t * ) xTask;
+		}
+
+		/* Save the hook function in the TCB.  A critical section is required as
+		the value can be accessed from an interrupt. */
+		taskENTER_CRITICAL();
+		{
+			xReturn = xTCB->pxTaskTag;
+		}
+		taskEXIT_CRITICAL();
+
+		return xReturn;
+	}
+
+#endif /* configUSE_APPLICATION_TASK_TAG */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_APPLICATION_TASK_TAG == 1 )
+
+	BaseType_t xTaskCallApplicationTaskHook( TaskHandle_t xTask, void *pvParameter )
+	{
+	TCB_t *xTCB;
+	BaseType_t xReturn;
+
+		/* If xTask is NULL then we are calling our own task hook. */
+		if( xTask == NULL )
+		{
+			xTCB = ( TCB_t * ) pxCurrentTCB;
+		}
+		else
+		{
+			xTCB = ( TCB_t * ) xTask;
+		}
+
+		if( xTCB->pxTaskTag != NULL )
+		{
+			xReturn = xTCB->pxTaskTag( pvParameter );
+		}
+		else
+		{
+			xReturn = pdFAIL;
+		}
+
+		return xReturn;
+	}
+
+#endif /* configUSE_APPLICATION_TASK_TAG */
+/*-----------------------------------------------------------*/
+
+void vTaskSwitchContext( void )
+{
+	if( uxSchedulerSuspended != ( UBaseType_t ) pdFALSE )
+	{
+		/* The scheduler is currently suspended - do not allow a context
+		switch. */
+		xYieldPending = pdTRUE;
+	}
+	else
+	{
+		xYieldPending = pdFALSE;
+		traceTASK_SWITCHED_OUT();
+
+		#if ( configGENERATE_RUN_TIME_STATS == 1 )
+		{
+				#ifdef portALT_GET_RUN_TIME_COUNTER_VALUE
+					portALT_GET_RUN_TIME_COUNTER_VALUE( ulTotalRunTime );
+				#else
+					ulTotalRunTime = portGET_RUN_TIME_COUNTER_VALUE();
+				#endif
+
+				/* Add the amount of time the task has been running to the
+				accumulated	time so far.  The time the task started running was
+				stored in ulTaskSwitchedInTime.  Note that there is no overflow
+				protection here	so count values are only valid until the timer
+				overflows.  The guard against negative values is to protect
+				against suspect run time stat counter implementations - which
+				are provided by the application, not the kernel. */
+				if( ulTotalRunTime > ulTaskSwitchedInTime )
+				{
+					pxCurrentTCB->ulRunTimeCounter += ( ulTotalRunTime - ulTaskSwitchedInTime );
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+				ulTaskSwitchedInTime = ulTotalRunTime;
+		}
+		#endif /* configGENERATE_RUN_TIME_STATS */
+
+		/* Check for stack overflow, if configured. */
+		taskFIRST_CHECK_FOR_STACK_OVERFLOW();
+		taskSECOND_CHECK_FOR_STACK_OVERFLOW();
+
+		/* Select a new task to run using either the generic C or port
+		optimised asm code. */
+		taskSELECT_HIGHEST_PRIORITY_TASK();
+		traceTASK_SWITCHED_IN();
+
+		#if ( configUSE_NEWLIB_REENTRANT == 1 )
+		{
+			/* Switch Newlib's _impure_ptr variable to point to the _reent
+			structure specific to this task. */
+			_impure_ptr = &( pxCurrentTCB->xNewLib_reent );
+		}
+		#endif /* configUSE_NEWLIB_REENTRANT */
+	}
+}
+/*-----------------------------------------------------------*/
+
+void vTaskPlaceOnEventList( List_t * const pxEventList, const TickType_t xTicksToWait )
+{
+TickType_t xTimeToWake;
+
+	configASSERT( pxEventList );
+
+	/* THIS FUNCTION MUST BE CALLED WITH EITHER INTERRUPTS DISABLED OR THE
+	SCHEDULER SUSPENDED AND THE QUEUE BEING ACCESSED LOCKED. */
+
+	/* Place the event list item of the TCB in the appropriate event list.
+	This is placed in the list in priority order so the highest priority task
+	is the first to be woken by the event.  The queue that contains the event
+	list is locked, preventing simultaneous access from interrupts. */
+	vListInsert( pxEventList, &( pxCurrentTCB->xEventListItem ) );
+
+	/* The task must be removed from from the ready list before it is added to
+	the blocked list as the same list item is used for both lists.  Exclusive
+	access to the ready lists guaranteed because the scheduler is locked. */
+	if( uxListRemove( &( pxCurrentTCB->xGenericListItem ) ) == ( UBaseType_t ) 0 )
+	{
+		/* The current task must be in a ready list, so there is no need to
+		check, and the port reset macro can be called directly. */
+		portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority );
+	}
+	else
+	{
+		mtCOVERAGE_TEST_MARKER();
+	}
+
+	#if ( INCLUDE_vTaskSuspend == 1 )
+	{
+		if( xTicksToWait == portMAX_DELAY )
+		{
+			/* Add the task to the suspended task list instead of a delayed task
+			list to ensure the task is not woken by a timing event.  It will
+			block indefinitely. */
+			vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB->xGenericListItem ) );
+		}
+		else
+		{
+			/* Calculate the time at which the task should be woken if the event
+			does not occur.  This may overflow but this doesn't matter, the
+			scheduler will handle it. */
+			xTimeToWake = xTickCount + xTicksToWait;
+			prvAddCurrentTaskToDelayedList( xTimeToWake );
+		}
+	}
+	#else /* INCLUDE_vTaskSuspend */
+	{
+			/* Calculate the time at which the task should be woken if the event does
+			not occur.  This may overflow but this doesn't matter, the scheduler
+			will handle it. */
+			xTimeToWake = xTickCount + xTicksToWait;
+			prvAddCurrentTaskToDelayedList( xTimeToWake );
+	}
+	#endif /* INCLUDE_vTaskSuspend */
+}
+/*-----------------------------------------------------------*/
+
+void vTaskPlaceOnUnorderedEventList( List_t * pxEventList, const TickType_t xItemValue, const TickType_t xTicksToWait )
+{
+TickType_t xTimeToWake;
+
+	configASSERT( pxEventList );
+
+	/* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED.  It is used by
+	the event groups implementation. */
+	configASSERT( uxSchedulerSuspended != 0 );
+
+	/* Store the item value in the event list item.  It is safe to access the
+	event list item here as interrupts won't access the event list item of a
+	task that is not in the Blocked state. */
+	listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE );
+
+	/* Place the event list item of the TCB at the end of the appropriate event
+	list.  It is safe to access the event list here because it is part of an
+	event group implementation - and interrupts don't access event groups
+	directly (instead they access them indirectly by pending function calls to
+	the task level). */
+	vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) );
+
+	/* The task must be removed from the ready list before it is added to the
+	blocked list.  Exclusive access can be assured to the ready list as the
+	scheduler is locked. */
+	if( uxListRemove( &( pxCurrentTCB->xGenericListItem ) ) == ( UBaseType_t ) 0 )
+	{
+		/* The current task must be in a ready list, so there is no need to
+		check, and the port reset macro can be called directly. */
+		portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority );
+	}
+	else
+	{
+		mtCOVERAGE_TEST_MARKER();
+	}
+
+	#if ( INCLUDE_vTaskSuspend == 1 )
+	{
+		if( xTicksToWait == portMAX_DELAY )
+		{
+			/* Add the task to the suspended task list instead of a delayed task
+			list to ensure it is not woken by a timing event.  It will block
+			indefinitely. */
+			vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB->xGenericListItem ) );
+		}
+		else
+		{
+			/* Calculate the time at which the task should be woken if the event
+			does not occur.  This may overflow but this doesn't matter, the
+			kernel will manage it correctly. */
+			xTimeToWake = xTickCount + xTicksToWait;
+			prvAddCurrentTaskToDelayedList( xTimeToWake );
+		}
+	}
+	#else /* INCLUDE_vTaskSuspend */
+	{
+			/* Calculate the time at which the task should be woken if the event does
+			not occur.  This may overflow but this doesn't matter, the kernel
+			will manage it correctly. */
+			xTimeToWake = xTickCount + xTicksToWait;
+			prvAddCurrentTaskToDelayedList( xTimeToWake );
+	}
+	#endif /* INCLUDE_vTaskSuspend */
+}
+/*-----------------------------------------------------------*/
+
+#if configUSE_TIMERS == 1
+
+	void vTaskPlaceOnEventListRestricted( List_t * const pxEventList, const TickType_t xTicksToWait )
+	{
+	TickType_t xTimeToWake;
+
+		configASSERT( pxEventList );
+
+		/* This function should not be called by application code hence the
+		'Restricted' in its name.  It is not part of the public API.  It is
+		designed for use by kernel code, and has special calling requirements -
+		it should be called with the scheduler suspended. */
+
+
+		/* Place the event list item of the TCB in the appropriate event list.
+		In this case it is assume that this is the only task that is going to
+		be waiting on this event list, so the faster vListInsertEnd() function
+		can be used in place of vListInsert. */
+		vListInsertEnd( pxEventList, &( pxCurrentTCB->xEventListItem ) );
+
+		/* We must remove this task from the ready list before adding it to the
+		blocked list as the same list item is used for both lists.  This
+		function is called with the scheduler locked so interrupts will not
+		access the lists at the same time. */
+		if( uxListRemove( &( pxCurrentTCB->xGenericListItem ) ) == ( UBaseType_t ) 0 )
+		{
+			/* The current task must be in a ready list, so there is no need to
+			check, and the port reset macro can be called directly. */
+			portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority );
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+
+		/* Calculate the time at which the task should be woken if the event does
+		not occur.  This may overflow but this doesn't matter. */
+		xTimeToWake = xTickCount + xTicksToWait;
+
+		traceTASK_DELAY_UNTIL();
+		prvAddCurrentTaskToDelayedList( xTimeToWake );
+	}
+
+#endif /* configUSE_TIMERS */
+/*-----------------------------------------------------------*/
+
+BaseType_t xTaskRemoveFromEventList( const List_t * const pxEventList )
+{
+TCB_t *pxUnblockedTCB;
+BaseType_t xReturn;
+
+	/* THIS FUNCTION MUST BE CALLED FROM A CRITICAL SECTION.  It can also be
+	called from a critical section within an ISR. */
+
+	/* The event list is sorted in priority order, so the first in the list can
+	be removed as it is known to be the highest priority.  Remove the TCB from
+	the delayed list, and add it to the ready list.
+
+	If an event is for a queue that is locked then this function will never
+	get called - the lock count on the queue will get modified instead.  This
+	means exclusive access to the event list is guaranteed here.
+
+	This function assumes that a check has already been made to ensure that
+	pxEventList is not empty. */
+	pxUnblockedTCB = ( TCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxEventList );
+	configASSERT( pxUnblockedTCB );
+	( void ) uxListRemove( &( pxUnblockedTCB->xEventListItem ) );
+
+	if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
+	{
+		( void ) uxListRemove( &( pxUnblockedTCB->xGenericListItem ) );
+		prvAddTaskToReadyList( pxUnblockedTCB );
+	}
+	else
+	{
+		/* The delayed and ready lists cannot be accessed, so hold this task
+		pending until the scheduler is resumed. */
+		vListInsertEnd( &( xPendingReadyList ), &( pxUnblockedTCB->xEventListItem ) );
+	}
+
+	if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority )
+	{
+		/* Return true if the task removed from the event list has a higher
+		priority than the calling task.  This allows the calling task to know if
+		it should force a context switch now. */
+		xReturn = pdTRUE;
+
+		/* Mark that a yield is pending in case the user is not using the
+		"xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function. */
+		xYieldPending = pdTRUE;
+	}
+	else
+	{
+		xReturn = pdFALSE;
+	}
+
+	#if( configUSE_TICKLESS_IDLE == 1 )
+	{
+		/* If a task is blocked on a kernel object then xNextTaskUnblockTime
+		might be set to the blocked task's time out time.  If the task is
+		unblocked for a reason other than a timeout xNextTaskUnblockTime is
+		normally left unchanged, because it is automatically get reset to a new
+		value when the tick count equals xNextTaskUnblockTime.  However if
+		tickless idling is used it might be more important to enter sleep mode
+		at the earliest possible time - so reset xNextTaskUnblockTime here to
+		ensure it is updated at the earliest possible time. */
+		prvResetNextTaskUnblockTime();
+	}
+	#endif
+
+	return xReturn;
+}
+/*-----------------------------------------------------------*/
+
+BaseType_t xTaskRemoveFromUnorderedEventList( ListItem_t * pxEventListItem, const TickType_t xItemValue )
+{
+TCB_t *pxUnblockedTCB;
+BaseType_t xReturn;
+
+	/* THIS FUNCTION MUST BE CALLED WITH THE SCHEDULER SUSPENDED.  It is used by
+	the event flags implementation. */
+	configASSERT( uxSchedulerSuspended != pdFALSE );
+
+	/* Store the new item value in the event list. */
+	listSET_LIST_ITEM_VALUE( pxEventListItem, xItemValue | taskEVENT_LIST_ITEM_VALUE_IN_USE );
+
+	/* Remove the event list form the event flag.  Interrupts do not access
+	event flags. */
+	pxUnblockedTCB = ( TCB_t * ) listGET_LIST_ITEM_OWNER( pxEventListItem );
+	configASSERT( pxUnblockedTCB );
+	( void ) uxListRemove( pxEventListItem );
+
+	/* Remove the task from the delayed list and add it to the ready list.  The
+	scheduler is suspended so interrupts will not be accessing the ready
+	lists. */
+	( void ) uxListRemove( &( pxUnblockedTCB->xGenericListItem ) );
+	prvAddTaskToReadyList( pxUnblockedTCB );
+
+	if( pxUnblockedTCB->uxPriority > pxCurrentTCB->uxPriority )
+	{
+		/* Return true if the task removed from the event list has
+		a higher priority than the calling task.  This allows
+		the calling task to know if it should force a context
+		switch now. */
+		xReturn = pdTRUE;
+
+		/* Mark that a yield is pending in case the user is not using the
+		"xHigherPriorityTaskWoken" parameter to an ISR safe FreeRTOS function. */
+		xYieldPending = pdTRUE;
+	}
+	else
+	{
+		xReturn = pdFALSE;
+	}
+
+	return xReturn;
+}
+/*-----------------------------------------------------------*/
+
+void vTaskSetTimeOutState( TimeOut_t * const pxTimeOut )
+{
+	configASSERT( pxTimeOut );
+	pxTimeOut->xOverflowCount = xNumOfOverflows;
+	pxTimeOut->xTimeOnEntering = xTickCount;
+}
+/*-----------------------------------------------------------*/
+
+BaseType_t xTaskCheckForTimeOut( TimeOut_t * const pxTimeOut, TickType_t * const pxTicksToWait )
+{
+BaseType_t xReturn;
+
+	configASSERT( pxTimeOut );
+	configASSERT( pxTicksToWait );
+
+	taskENTER_CRITICAL();
+	{
+		/* Minor optimisation.  The tick count cannot change in this block. */
+		const TickType_t xConstTickCount = xTickCount;
+
+		#if ( INCLUDE_vTaskSuspend == 1 )
+			/* If INCLUDE_vTaskSuspend is set to 1 and the block time specified is
+			the maximum block time then the task should block indefinitely, and
+			therefore never time out. */
+			if( *pxTicksToWait == portMAX_DELAY )
+			{
+				xReturn = pdFALSE;
+			}
+			else /* We are not blocking indefinitely, perform the checks below. */
+		#endif
+
+		if( ( xNumOfOverflows != pxTimeOut->xOverflowCount ) && ( xConstTickCount >= pxTimeOut->xTimeOnEntering ) ) /*lint !e525 Indentation preferred as is to make code within pre-processor directives clearer. */
+		{
+			/* The tick count is greater than the time at which vTaskSetTimeout()
+			was called, but has also overflowed since vTaskSetTimeOut() was called.
+			It must have wrapped all the way around and gone past us again. This
+			passed since vTaskSetTimeout() was called. */
+			xReturn = pdTRUE;
+		}
+		else if( ( xConstTickCount - pxTimeOut->xTimeOnEntering ) < *pxTicksToWait )
+		{
+			/* Not a genuine timeout. Adjust parameters for time remaining. */
+			*pxTicksToWait -= ( xConstTickCount -  pxTimeOut->xTimeOnEntering );
+			vTaskSetTimeOutState( pxTimeOut );
+			xReturn = pdFALSE;
+		}
+		else
+		{
+			xReturn = pdTRUE;
+		}
+	}
+	taskEXIT_CRITICAL();
+
+	return xReturn;
+}
+/*-----------------------------------------------------------*/
+
+void vTaskMissedYield( void )
+{
+	xYieldPending = pdTRUE;
+}
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_TRACE_FACILITY == 1 )
+
+	UBaseType_t uxTaskGetTaskNumber( TaskHandle_t xTask )
+	{
+	UBaseType_t uxReturn;
+	TCB_t *pxTCB;
+
+		if( xTask != NULL )
+		{
+			pxTCB = ( TCB_t * ) xTask;
+			uxReturn = pxTCB->uxTaskNumber;
+		}
+		else
+		{
+			uxReturn = 0U;
+		}
+
+		return uxReturn;
+	}
+
+#endif /* configUSE_TRACE_FACILITY */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_TRACE_FACILITY == 1 )
+
+	void vTaskSetTaskNumber( TaskHandle_t xTask, const UBaseType_t uxHandle )
+	{
+	TCB_t *pxTCB;
+
+		if( xTask != NULL )
+		{
+			pxTCB = ( TCB_t * ) xTask;
+			pxTCB->uxTaskNumber = uxHandle;
+		}
+	}
+
+#endif /* configUSE_TRACE_FACILITY */
+
+/*
+ * -----------------------------------------------------------
+ * The Idle task.
+ * ----------------------------------------------------------
+ *
+ * The portTASK_FUNCTION() macro is used to allow port/compiler specific
+ * language extensions.  The equivalent prototype for this function is:
+ *
+ * void prvIdleTask( void *pvParameters );
+ *
+ */
+static portTASK_FUNCTION( prvIdleTask, pvParameters )
+{
+	/* Stop warnings. */
+	( void ) pvParameters;
+
+	for( ;; )
+	{
+		/* See if any tasks have been deleted. */
+		prvCheckTasksWaitingTermination();
+
+		#if ( configUSE_PREEMPTION == 0 )
+		{
+			/* If we are not using preemption we keep forcing a task switch to
+			see if any other task has become available.  If we are using
+			preemption we don't need to do this as any task becoming available
+			will automatically get the processor anyway. */
+			taskYIELD();
+		}
+		#endif /* configUSE_PREEMPTION */
+
+		#if ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) )
+		{
+			/* When using preemption tasks of equal priority will be
+			timesliced.  If a task that is sharing the idle priority is ready
+			to run then the idle task should yield before the end of the
+			timeslice.
+
+			A critical region is not required here as we are just reading from
+			the list, and an occasional incorrect value will not matter.  If
+			the ready list at the idle priority contains more than one task
+			then a task other than the idle task is ready to execute. */
+			if( listCURRENT_LIST_LENGTH( &( pxReadyTasksLists[ tskIDLE_PRIORITY ] ) ) > ( UBaseType_t ) 1 )
+			{
+				taskYIELD();
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		#endif /* ( ( configUSE_PREEMPTION == 1 ) && ( configIDLE_SHOULD_YIELD == 1 ) ) */
+
+		#if ( configUSE_IDLE_HOOK == 1 )
+		{
+			extern void vApplicationIdleHook( void );
+
+			/* Call the user defined function from within the idle task.  This
+			allows the application designer to add background functionality
+			without the overhead of a separate task.
+			NOTE: vApplicationIdleHook() MUST NOT, UNDER ANY CIRCUMSTANCES,
+			CALL A FUNCTION THAT MIGHT BLOCK. */
+			vApplicationIdleHook();
+		}
+		#endif /* configUSE_IDLE_HOOK */
+
+		/* This conditional compilation should use inequality to 0, not equality
+		to 1.  This is to ensure portSUPPRESS_TICKS_AND_SLEEP() is called when
+		user defined low power mode	implementations require
+		configUSE_TICKLESS_IDLE to be set to a value other than 1. */
+		#if ( configUSE_TICKLESS_IDLE != 0 )
+		{
+		TickType_t xExpectedIdleTime;
+
+			/* It is not desirable to suspend then resume the scheduler on
+			each iteration of the idle task.  Therefore, a preliminary
+			test of the expected idle time is performed without the
+			scheduler suspended.  The result here is not necessarily
+			valid. */
+			xExpectedIdleTime = prvGetExpectedIdleTime();
+
+			if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP )
+			{
+				vTaskSuspendAll();
+				{
+					/* Now the scheduler is suspended, the expected idle
+					time can be sampled again, and this time its value can
+					be used. */
+					configASSERT( xNextTaskUnblockTime >= xTickCount );
+					xExpectedIdleTime = prvGetExpectedIdleTime();
+
+					if( xExpectedIdleTime >= configEXPECTED_IDLE_TIME_BEFORE_SLEEP )
+					{
+						traceLOW_POWER_IDLE_BEGIN();
+						portSUPPRESS_TICKS_AND_SLEEP( xExpectedIdleTime );
+						traceLOW_POWER_IDLE_END();
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+				}
+				( void ) xTaskResumeAll();
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		#endif /* configUSE_TICKLESS_IDLE */
+	}
+}
+/*-----------------------------------------------------------*/
+
+#if configUSE_TICKLESS_IDLE != 0
+
+	eSleepModeStatus eTaskConfirmSleepModeStatus( void )
+	{
+	eSleepModeStatus eReturn = eStandardSleep;
+
+		if( listCURRENT_LIST_LENGTH( &xPendingReadyList ) != 0 )
+		{
+			/* A task was made ready while the scheduler was suspended. */
+			eReturn = eAbortSleep;
+		}
+		else if( xYieldPending != pdFALSE )
+		{
+			/* A yield was pended while the scheduler was suspended. */
+			eReturn = eAbortSleep;
+		}
+		else
+		{
+			#if configUSE_TIMERS == 0
+			{
+				/* The idle task exists in addition to the application tasks. */
+				const UBaseType_t uxNonApplicationTasks = 1;
+
+				/* If timers are not being used and all the tasks are in the
+				suspended list (which might mean they have an infinite block
+				time rather than actually being suspended) then it is safe to
+				turn all clocks off and just wait for external interrupts. */
+				if( listCURRENT_LIST_LENGTH( &xSuspendedTaskList ) == ( uxCurrentNumberOfTasks - uxNonApplicationTasks ) )
+				{
+					eReturn = eNoTasksWaitingTimeout;
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			#endif /* configUSE_TIMERS */
+		}
+
+		return eReturn;
+	}
+#endif /* configUSE_TICKLESS_IDLE */
+/*-----------------------------------------------------------*/
+
+static void prvInitialiseTCBVariables( TCB_t * const pxTCB, const char * const pcName, UBaseType_t uxPriority, const MemoryRegion_t * const xRegions, const uint16_t usStackDepth ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+{
+UBaseType_t x;
+
+	/* Store the task name in the TCB. */
+	for( x = ( UBaseType_t ) 0; x < ( UBaseType_t ) configMAX_TASK_NAME_LEN; x++ )
+	{
+		pxTCB->pcTaskName[ x ] = pcName[ x ];
+
+		/* Don't copy all configMAX_TASK_NAME_LEN if the string is shorter than
+		configMAX_TASK_NAME_LEN characters just in case the memory after the
+		string is not accessible (extremely unlikely). */
+		if( pcName[ x ] == 0x00 )
+		{
+			break;
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+
+	/* Ensure the name string is terminated in the case that the string length
+	was greater or equal to configMAX_TASK_NAME_LEN. */
+	pxTCB->pcTaskName[ configMAX_TASK_NAME_LEN - 1 ] = '\0';
+
+	/* This is used as an array index so must ensure it's not too large.  First
+	remove the privilege bit if one is present. */
+	if( uxPriority >= ( UBaseType_t ) configMAX_PRIORITIES )
+	{
+		uxPriority = ( UBaseType_t ) configMAX_PRIORITIES - ( UBaseType_t ) 1U;
+	}
+	else
+	{
+		mtCOVERAGE_TEST_MARKER();
+	}
+
+	pxTCB->uxPriority = uxPriority;
+	#if ( configUSE_MUTEXES == 1 )
+	{
+		pxTCB->uxBasePriority = uxPriority;
+		pxTCB->uxMutexesHeld = 0;
+	}
+	#endif /* configUSE_MUTEXES */
+
+	vListInitialiseItem( &( pxTCB->xGenericListItem ) );
+	vListInitialiseItem( &( pxTCB->xEventListItem ) );
+
+	/* Set the pxTCB as a link back from the ListItem_t.  This is so we can get
+	back to	the containing TCB from a generic item in a list. */
+	listSET_LIST_ITEM_OWNER( &( pxTCB->xGenericListItem ), pxTCB );
+
+	/* Event lists are always in priority order. */
+	listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+	listSET_LIST_ITEM_OWNER( &( pxTCB->xEventListItem ), pxTCB );
+
+	#if ( portCRITICAL_NESTING_IN_TCB == 1 )
+	{
+		pxTCB->uxCriticalNesting = ( UBaseType_t ) 0U;
+	}
+	#endif /* portCRITICAL_NESTING_IN_TCB */
+
+	#if ( configUSE_APPLICATION_TASK_TAG == 1 )
+	{
+		pxTCB->pxTaskTag = NULL;
+	}
+	#endif /* configUSE_APPLICATION_TASK_TAG */
+
+	#if ( configGENERATE_RUN_TIME_STATS == 1 )
+	{
+		pxTCB->ulRunTimeCounter = 0UL;
+	}
+	#endif /* configGENERATE_RUN_TIME_STATS */
+
+	#if ( portUSING_MPU_WRAPPERS == 1 )
+	{
+		vPortStoreTaskMPUSettings( &( pxTCB->xMPUSettings ), xRegions, pxTCB->pxStack, usStackDepth );
+	}
+	#else /* portUSING_MPU_WRAPPERS */
+	{
+		( void ) xRegions;
+		( void ) usStackDepth;
+	}
+	#endif /* portUSING_MPU_WRAPPERS */
+
+	#if( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 )
+	{
+		for( x = 0; x < ( UBaseType_t ) configNUM_THREAD_LOCAL_STORAGE_POINTERS; x++ )
+		{
+			pxTCB->pvThreadLocalStoragePointers[ x ] = NULL;
+		}
+	}
+	#endif
+
+	#if ( configUSE_TASK_NOTIFICATIONS == 1 )
+	{
+		pxTCB->ulNotifiedValue = 0;
+		pxTCB->eNotifyState = eNotWaitingNotification;
+	}
+	#endif
+
+	#if ( configUSE_NEWLIB_REENTRANT == 1 )
+	{
+		/* Initialise this task's Newlib reent structure. */
+		_REENT_INIT_PTR( ( &( pxTCB->xNewLib_reent ) ) );
+	}
+	#endif /* configUSE_NEWLIB_REENTRANT */
+}
+/*-----------------------------------------------------------*/
+
+#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 )
+
+	void vTaskSetThreadLocalStoragePointer( TaskHandle_t xTaskToSet, BaseType_t xIndex, void *pvValue )
+	{
+	TCB_t *pxTCB;
+
+		if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS )
+		{
+			pxTCB = prvGetTCBFromHandle( xTaskToSet );
+			pxTCB->pvThreadLocalStoragePointers[ xIndex ] = pvValue;
+		}
+	}
+
+#endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */
+/*-----------------------------------------------------------*/
+
+#if ( configNUM_THREAD_LOCAL_STORAGE_POINTERS != 0 )
+
+	void *pvTaskGetThreadLocalStoragePointer( TaskHandle_t xTaskToQuery, BaseType_t xIndex )
+	{
+	void *pvReturn = NULL;
+	TCB_t *pxTCB;
+
+		if( xIndex < configNUM_THREAD_LOCAL_STORAGE_POINTERS )
+		{
+			pxTCB = prvGetTCBFromHandle( xTaskToQuery );
+			pvReturn = pxTCB->pvThreadLocalStoragePointers[ xIndex ];
+		}
+		else
+		{
+			pvReturn = NULL;
+		}
+
+		return pvReturn;
+	}
+
+#endif /* configNUM_THREAD_LOCAL_STORAGE_POINTERS */
+/*-----------------------------------------------------------*/
+
+#if ( portUSING_MPU_WRAPPERS == 1 )
+
+	void vTaskAllocateMPURegions( TaskHandle_t xTaskToModify, const MemoryRegion_t * const xRegions )
+	{
+	TCB_t *pxTCB;
+
+		/* If null is passed in here then we are deleting ourselves. */
+		pxTCB = prvGetTCBFromHandle( xTaskToModify );
+
+        vPortStoreTaskMPUSettings( &( pxTCB->xMPUSettings ), xRegions, NULL, 0 );
+	}
+
+#endif /* portUSING_MPU_WRAPPERS */
+/*-----------------------------------------------------------*/
+
+static void prvInitialiseTaskLists( void )
+{
+UBaseType_t uxPriority;
+
+	for( uxPriority = ( UBaseType_t ) 0U; uxPriority < ( UBaseType_t ) configMAX_PRIORITIES; uxPriority++ )
+	{
+		vListInitialise( &( pxReadyTasksLists[ uxPriority ] ) );
+	}
+
+	vListInitialise( &xDelayedTaskList1 );
+	vListInitialise( &xDelayedTaskList2 );
+	vListInitialise( &xPendingReadyList );
+
+	#if ( INCLUDE_vTaskDelete == 1 )
+	{
+		vListInitialise( &xTasksWaitingTermination );
+	}
+	#endif /* INCLUDE_vTaskDelete */
+
+	#if ( INCLUDE_vTaskSuspend == 1 )
+	{
+		vListInitialise( &xSuspendedTaskList );
+	}
+	#endif /* INCLUDE_vTaskSuspend */
+
+	/* Start with pxDelayedTaskList using list1 and the pxOverflowDelayedTaskList
+	using list2. */
+	pxDelayedTaskList = &xDelayedTaskList1;
+	pxOverflowDelayedTaskList = &xDelayedTaskList2;
+}
+/*-----------------------------------------------------------*/
+
+static void prvCheckTasksWaitingTermination( void )
+{
+	#if ( INCLUDE_vTaskDelete == 1 )
+	{
+		BaseType_t xListIsEmpty;
+
+		/* ucTasksDeleted is used to prevent vTaskSuspendAll() being called
+		too often in the idle task. */
+		while( uxTasksDeleted > ( UBaseType_t ) 0U )
+		{
+			vTaskSuspendAll();
+			{
+				xListIsEmpty = listLIST_IS_EMPTY( &xTasksWaitingTermination );
+			}
+			( void ) xTaskResumeAll();
+
+			if( xListIsEmpty == pdFALSE )
+			{
+				TCB_t *pxTCB;
+
+				taskENTER_CRITICAL();
+				{
+					pxTCB = ( TCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( ( &xTasksWaitingTermination ) );
+					( void ) uxListRemove( &( pxTCB->xGenericListItem ) );
+					--uxCurrentNumberOfTasks;
+					--uxTasksDeleted;
+				}
+				taskEXIT_CRITICAL();
+
+				prvDeleteTCB( pxTCB );
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+	}
+	#endif /* vTaskDelete */
+}
+/*-----------------------------------------------------------*/
+
+static void prvAddCurrentTaskToDelayedList( const TickType_t xTimeToWake )
+{
+	/* The list item will be inserted in wake time order. */
+	listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xGenericListItem ), xTimeToWake );
+
+	if( xTimeToWake < xTickCount )
+	{
+		/* Wake time has overflowed.  Place this item in the overflow list. */
+		vListInsert( pxOverflowDelayedTaskList, &( pxCurrentTCB->xGenericListItem ) );
+	}
+	else
+	{
+		/* The wake time has not overflowed, so the current block list is used. */
+		vListInsert( pxDelayedTaskList, &( pxCurrentTCB->xGenericListItem ) );
+
+		/* If the task entering the blocked state was placed at the head of the
+		list of blocked tasks then xNextTaskUnblockTime needs to be updated
+		too. */
+		if( xTimeToWake < xNextTaskUnblockTime )
+		{
+			xNextTaskUnblockTime = xTimeToWake;
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+}
+/*-----------------------------------------------------------*/
+
+static TCB_t *prvAllocateTCBAndStack( const uint16_t usStackDepth, StackType_t * const puxStackBuffer )
+{
+TCB_t *pxNewTCB;
+
+	/* If the stack grows down then allocate the stack then the TCB so the stack
+	does not grow into the TCB.  Likewise if the stack grows up then allocate
+	the TCB then the stack. */
+	#if( portSTACK_GROWTH > 0 )
+	{
+		/* Allocate space for the TCB.  Where the memory comes from depends on
+		the implementation of the port malloc function. */
+		pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) );
+
+		if( pxNewTCB != NULL )
+		{
+			/* Allocate space for the stack used by the task being created.
+			The base of the stack memory stored in the TCB so the task can
+			be deleted later if required. */
+			pxNewTCB->pxStack = ( StackType_t * ) pvPortMallocAligned( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ), puxStackBuffer ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+
+			if( pxNewTCB->pxStack == NULL )
+			{
+				/* Could not allocate the stack.  Delete the allocated TCB. */
+				vPortFree( pxNewTCB );
+				pxNewTCB = NULL;
+			}
+		}
+	}
+	#else /* portSTACK_GROWTH */
+	{
+	StackType_t *pxStack;
+
+		/* Allocate space for the stack used by the task being created. */
+		pxStack = ( StackType_t * ) pvPortMallocAligned( ( ( ( size_t ) usStackDepth ) * sizeof( StackType_t ) ), puxStackBuffer ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+
+		if( pxStack != NULL )
+		{
+			/* Allocate space for the TCB.  Where the memory comes from depends
+			on the implementation of the port malloc function. */
+			pxNewTCB = ( TCB_t * ) pvPortMalloc( sizeof( TCB_t ) );
+
+			if( pxNewTCB != NULL )
+			{
+				/* Store the stack location in the TCB. */
+				pxNewTCB->pxStack = pxStack;
+			}
+			else
+			{
+				/* The stack cannot be used as the TCB was not created.  Free it
+				again. */
+				vPortFree( pxStack );
+			}
+		}
+		else
+		{
+			pxNewTCB = NULL;
+		}
+	}
+	#endif /* portSTACK_GROWTH */
+
+	if( pxNewTCB != NULL )
+	{
+		/* Avoid dependency on memset() if it is not required. */
+		#if( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) || ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) )
+		{
+			/* Just to help debugging. */
+			( void ) memset( pxNewTCB->pxStack, ( int ) tskSTACK_FILL_BYTE, ( size_t ) usStackDepth * sizeof( StackType_t ) );
+		}
+		#endif /* ( ( configCHECK_FOR_STACK_OVERFLOW > 1 ) || ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) ) ) */
+	}
+
+	return pxNewTCB;
+}
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_TRACE_FACILITY == 1 )
+
+	static UBaseType_t prvListTaskWithinSingleList( TaskStatus_t *pxTaskStatusArray, List_t *pxList, eTaskState eState )
+	{
+	volatile TCB_t *pxNextTCB, *pxFirstTCB;
+	UBaseType_t uxTask = 0;
+
+		if( listCURRENT_LIST_LENGTH( pxList ) > ( UBaseType_t ) 0 )
+		{
+			listGET_OWNER_OF_NEXT_ENTRY( pxFirstTCB, pxList );
+
+			/* Populate an TaskStatus_t structure within the
+			pxTaskStatusArray array for each task that is referenced from
+			pxList.  See the definition of TaskStatus_t in task.h for the
+			meaning of each TaskStatus_t structure member. */
+			do
+			{
+				listGET_OWNER_OF_NEXT_ENTRY( pxNextTCB, pxList );
+
+				pxTaskStatusArray[ uxTask ].xHandle = ( TaskHandle_t ) pxNextTCB;
+				pxTaskStatusArray[ uxTask ].pcTaskName = ( const char * ) &( pxNextTCB->pcTaskName [ 0 ] );
+				pxTaskStatusArray[ uxTask ].xTaskNumber = pxNextTCB->uxTCBNumber;
+				pxTaskStatusArray[ uxTask ].eCurrentState = eState;
+				pxTaskStatusArray[ uxTask ].uxCurrentPriority = pxNextTCB->uxPriority;
+
+				#if ( INCLUDE_vTaskSuspend == 1 )
+				{
+					/* If the task is in the suspended list then there is a chance
+					it is actually just blocked indefinitely - so really it should
+					be reported as being in the Blocked state. */
+					if( eState == eSuspended )
+					{
+						if( listLIST_ITEM_CONTAINER( &( pxNextTCB->xEventListItem ) ) != NULL )
+						{
+							pxTaskStatusArray[ uxTask ].eCurrentState = eBlocked;
+						}
+					}
+				}
+				#endif /* INCLUDE_vTaskSuspend */
+
+				#if ( configUSE_MUTEXES == 1 )
+				{
+					pxTaskStatusArray[ uxTask ].uxBasePriority = pxNextTCB->uxBasePriority;
+				}
+				#else
+				{
+					pxTaskStatusArray[ uxTask ].uxBasePriority = 0;
+				}
+				#endif
+
+				#if ( configGENERATE_RUN_TIME_STATS == 1 )
+				{
+					pxTaskStatusArray[ uxTask ].ulRunTimeCounter = pxNextTCB->ulRunTimeCounter;
+				}
+				#else
+				{
+					pxTaskStatusArray[ uxTask ].ulRunTimeCounter = 0;
+				}
+				#endif
+
+				#if ( portSTACK_GROWTH > 0 )
+				{
+					pxTaskStatusArray[ uxTask ].usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxNextTCB->pxEndOfStack );
+				}
+				#else
+				{
+					pxTaskStatusArray[ uxTask ].usStackHighWaterMark = prvTaskCheckFreeStackSpace( ( uint8_t * ) pxNextTCB->pxStack );
+				}
+				#endif
+
+				uxTask++;
+
+			} while( pxNextTCB != pxFirstTCB );
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+
+		return uxTask;
+	}
+
+#endif /* configUSE_TRACE_FACILITY */
+/*-----------------------------------------------------------*/
+
+#if ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) )
+
+	static uint16_t prvTaskCheckFreeStackSpace( const uint8_t * pucStackByte )
+	{
+	uint32_t ulCount = 0U;
+
+		while( *pucStackByte == ( uint8_t ) tskSTACK_FILL_BYTE )
+		{
+			pucStackByte -= portSTACK_GROWTH;
+			ulCount++;
+		}
+
+		ulCount /= ( uint32_t ) sizeof( StackType_t ); /*lint !e961 Casting is not redundant on smaller architectures. */
+
+		return ( uint16_t ) ulCount;
+	}
+
+#endif /* ( ( configUSE_TRACE_FACILITY == 1 ) || ( INCLUDE_uxTaskGetStackHighWaterMark == 1 ) ) */
+/*-----------------------------------------------------------*/
+
+#if ( INCLUDE_uxTaskGetStackHighWaterMark == 1 )
+
+	UBaseType_t uxTaskGetStackHighWaterMark( TaskHandle_t xTask )
+	{
+	TCB_t *pxTCB;
+	uint8_t *pucEndOfStack;
+	UBaseType_t uxReturn;
+
+		pxTCB = prvGetTCBFromHandle( xTask );
+
+		#if portSTACK_GROWTH < 0
+		{
+			pucEndOfStack = ( uint8_t * ) pxTCB->pxStack;
+		}
+		#else
+		{
+			pucEndOfStack = ( uint8_t * ) pxTCB->pxEndOfStack;
+		}
+		#endif
+
+		uxReturn = ( UBaseType_t ) prvTaskCheckFreeStackSpace( pucEndOfStack );
+
+		return uxReturn;
+	}
+
+#endif /* INCLUDE_uxTaskGetStackHighWaterMark */
+/*-----------------------------------------------------------*/
+
+#if ( INCLUDE_vTaskDelete == 1 )
+
+	static void prvDeleteTCB( TCB_t *pxTCB )
+	{
+		/* This call is required specifically for the TriCore port.  It must be
+		above the vPortFree() calls.  The call is also used by ports/demos that
+		want to allocate and clean RAM statically. */
+		portCLEAN_UP_TCB( pxTCB );
+
+		/* Free up the memory allocated by the scheduler for the task.  It is up
+		to the task to free any memory allocated at the application level. */
+		#if ( configUSE_NEWLIB_REENTRANT == 1 )
+		{
+			_reclaim_reent( &( pxTCB->xNewLib_reent ) );
+		}
+		#endif /* configUSE_NEWLIB_REENTRANT */
+
+		#if( portUSING_MPU_WRAPPERS == 1 )
+		{
+			/* Only free the stack if it was allocated dynamically in the first
+			place. */
+			if( pxTCB->xUsingStaticallyAllocatedStack == pdFALSE )
+			{
+				vPortFreeAligned( pxTCB->pxStack );
+			}
+		}
+		#else
+		{
+			vPortFreeAligned( pxTCB->pxStack );
+		}
+		#endif
+
+		vPortFree( pxTCB );
+	}
+
+#endif /* INCLUDE_vTaskDelete */
+/*-----------------------------------------------------------*/
+
+static void prvResetNextTaskUnblockTime( void )
+{
+TCB_t *pxTCB;
+
+	if( listLIST_IS_EMPTY( pxDelayedTaskList ) != pdFALSE )
+	{
+		/* The new current delayed list is empty.  Set xNextTaskUnblockTime to
+		the maximum possible value so it is	extremely unlikely that the
+		if( xTickCount >= xNextTaskUnblockTime ) test will pass until
+		there is an item in the delayed list. */
+		xNextTaskUnblockTime = portMAX_DELAY;
+	}
+	else
+	{
+		/* The new current delayed list is not empty, get the value of
+		the item at the head of the delayed list.  This is the time at
+		which the task at the head of the delayed list should be removed
+		from the Blocked state. */
+		( pxTCB ) = ( TCB_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxDelayedTaskList );
+		xNextTaskUnblockTime = listGET_LIST_ITEM_VALUE( &( ( pxTCB )->xGenericListItem ) );
+	}
+}
+/*-----------------------------------------------------------*/
+
+#if ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) )
+
+	TaskHandle_t xTaskGetCurrentTaskHandle( void )
+	{
+	TaskHandle_t xReturn;
+
+		/* A critical section is not required as this is not called from
+		an interrupt and the current TCB will always be the same for any
+		individual execution thread. */
+		xReturn = pxCurrentTCB;
+
+		return xReturn;
+	}
+
+#endif /* ( ( INCLUDE_xTaskGetCurrentTaskHandle == 1 ) || ( configUSE_MUTEXES == 1 ) ) */
+/*-----------------------------------------------------------*/
+
+#if ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) )
+
+	BaseType_t xTaskGetSchedulerState( void )
+	{
+	BaseType_t xReturn;
+
+		if( xSchedulerRunning == pdFALSE )
+		{
+			xReturn = taskSCHEDULER_NOT_STARTED;
+		}
+		else
+		{
+			if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
+			{
+				xReturn = taskSCHEDULER_RUNNING;
+			}
+			else
+			{
+				xReturn = taskSCHEDULER_SUSPENDED;
+			}
+		}
+
+		return xReturn;
+	}
+
+#endif /* ( ( INCLUDE_xTaskGetSchedulerState == 1 ) || ( configUSE_TIMERS == 1 ) ) */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_MUTEXES == 1 )
+
+	void vTaskPriorityInherit( TaskHandle_t const pxMutexHolder )
+	{
+	TCB_t * const pxTCB = ( TCB_t * ) pxMutexHolder;
+
+		/* If the mutex was given back by an interrupt while the queue was
+		locked then the mutex holder might now be NULL. */
+		if( pxMutexHolder != NULL )
+		{
+			/* If the holder of the mutex has a priority below the priority of
+			the task attempting to obtain the mutex then it will temporarily
+			inherit the priority of the task attempting to obtain the mutex. */
+			if( pxTCB->uxPriority < pxCurrentTCB->uxPriority )
+			{
+				/* Adjust the mutex holder state to account for its new
+				priority.  Only reset the event list item value if the value is
+				not	being used for anything else. */
+				if( ( listGET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ) ) & taskEVENT_LIST_ITEM_VALUE_IN_USE ) == 0UL )
+				{
+					listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+
+				/* If the task being modified is in the ready state it will need
+				to be moved into a new list. */
+				if( listIS_CONTAINED_WITHIN( &( pxReadyTasksLists[ pxTCB->uxPriority ] ), &( pxTCB->xGenericListItem ) ) != pdFALSE )
+				{
+					if( uxListRemove( &( pxTCB->xGenericListItem ) ) == ( UBaseType_t ) 0 )
+					{
+						taskRESET_READY_PRIORITY( pxTCB->uxPriority );
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+
+					/* Inherit the priority before being moved into the new list. */
+					pxTCB->uxPriority = pxCurrentTCB->uxPriority;
+					prvAddTaskToReadyList( pxTCB );
+				}
+				else
+				{
+					/* Just inherit the priority. */
+					pxTCB->uxPriority = pxCurrentTCB->uxPriority;
+				}
+
+				traceTASK_PRIORITY_INHERIT( pxTCB, pxCurrentTCB->uxPriority );
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+
+#endif /* configUSE_MUTEXES */
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_MUTEXES == 1 )
+
+	BaseType_t xTaskPriorityDisinherit( TaskHandle_t const pxMutexHolder )
+	{
+	TCB_t * const pxTCB = ( TCB_t * ) pxMutexHolder;
+	BaseType_t xReturn = pdFALSE;
+
+		if( pxMutexHolder != NULL )
+		{
+			/* A task can only have an inherited priority if it holds the mutex.
+			If the mutex is held by a task then it cannot be given from an
+			interrupt, and if a mutex is given by the holding task then it must
+			be the running state task. */
+			configASSERT( pxTCB == pxCurrentTCB );
+
+			configASSERT( pxTCB->uxMutexesHeld );
+			( pxTCB->uxMutexesHeld )--;
+
+			/* Has the holder of the mutex inherited the priority of another
+			task? */
+			if( pxTCB->uxPriority != pxTCB->uxBasePriority )
+			{
+				/* Only disinherit if no other mutexes are held. */
+				if( pxTCB->uxMutexesHeld == ( UBaseType_t ) 0 )
+				{
+					/* A task can only have an inherited priority if it holds
+					the mutex.  If the mutex is held by a task then it cannot be
+					given from an interrupt, and if a mutex is given by the
+					holding	task then it must be the running state task.  Remove
+					the	holding task from the ready	list. */
+					if( uxListRemove( &( pxTCB->xGenericListItem ) ) == ( UBaseType_t ) 0 )
+					{
+						taskRESET_READY_PRIORITY( pxTCB->uxPriority );
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+
+					/* Disinherit the priority before adding the task into the
+					new	ready list. */
+					traceTASK_PRIORITY_DISINHERIT( pxTCB, pxTCB->uxBasePriority );
+					pxTCB->uxPriority = pxTCB->uxBasePriority;
+
+					/* Reset the event list item value.  It cannot be in use for
+					any other purpose if this task is running, and it must be
+					running to give back the mutex. */
+					listSET_LIST_ITEM_VALUE( &( pxTCB->xEventListItem ), ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxTCB->uxPriority ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+					prvAddTaskToReadyList( pxTCB );
+
+					/* Return true to indicate that a context switch is required.
+					This is only actually required in the corner case whereby
+					multiple mutexes were held and the mutexes were given back
+					in an order different to that in which they were taken.
+					If a context switch did not occur when the first mutex was
+					returned, even if a task was waiting on it, then a context
+					switch should occur when the last mutex is returned whether
+					a task is waiting on it or not. */
+					xReturn = pdTRUE;
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+
+		return xReturn;
+	}
+
+#endif /* configUSE_MUTEXES */
+/*-----------------------------------------------------------*/
+
+#if ( portCRITICAL_NESTING_IN_TCB == 1 )
+
+	void vTaskEnterCritical( void )
+	{
+		portDISABLE_INTERRUPTS();
+
+		if( xSchedulerRunning != pdFALSE )
+		{
+			( pxCurrentTCB->uxCriticalNesting )++;
+
+			/* This is not the interrupt safe version of the enter critical
+			function so	assert() if it is being called from an interrupt
+			context.  Only API functions that end in "FromISR" can be used in an
+			interrupt.  Only assert if the critical nesting count is 1 to
+			protect against recursive calls if the assert function also uses a
+			critical section. */
+			if( pxCurrentTCB->uxCriticalNesting == 1 )
+			{
+				portASSERT_IF_IN_ISR();
+			}
+
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+
+#endif /* portCRITICAL_NESTING_IN_TCB */
+/*-----------------------------------------------------------*/
+
+#if ( portCRITICAL_NESTING_IN_TCB == 1 )
+
+	void vTaskExitCritical( void )
+	{
+		if( xSchedulerRunning != pdFALSE )
+		{
+			if( pxCurrentTCB->uxCriticalNesting > 0U )
+			{
+				( pxCurrentTCB->uxCriticalNesting )--;
+
+				if( pxCurrentTCB->uxCriticalNesting == 0U )
+				{
+					portENABLE_INTERRUPTS();
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+
+#endif /* portCRITICAL_NESTING_IN_TCB */
+/*-----------------------------------------------------------*/
+
+#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) )
+
+	static char *prvWriteNameToBuffer( char *pcBuffer, const char *pcTaskName )
+	{
+	BaseType_t x;
+
+		/* Start by copying the entire string. */
+		strcpy( pcBuffer, pcTaskName );
+
+		/* Pad the end of the string with spaces to ensure columns line up when
+		printed out. */
+		for( x = strlen( pcBuffer ); x < ( configMAX_TASK_NAME_LEN - 1 ); x++ )
+		{
+			pcBuffer[ x ] = ' ';
+		}
+
+		/* Terminate. */
+		pcBuffer[ x ] = 0x00;
+
+		/* Return the new end of string. */
+		return &( pcBuffer[ x ] );
+	}
+
+#endif /* ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) */
+/*-----------------------------------------------------------*/
+
+#if ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) )
+
+	void vTaskList( char * pcWriteBuffer )
+	{
+	TaskStatus_t *pxTaskStatusArray;
+	volatile UBaseType_t uxArraySize, x;
+	char cStatus;
+
+		/*
+		 * PLEASE NOTE:
+		 *
+		 * This function is provided for convenience only, and is used by many
+		 * of the demo applications.  Do not consider it to be part of the
+		 * scheduler.
+		 *
+		 * vTaskList() calls uxTaskGetSystemState(), then formats part of the
+		 * uxTaskGetSystemState() output into a human readable table that
+		 * displays task names, states and stack usage.
+		 *
+		 * vTaskList() has a dependency on the sprintf() C library function that
+		 * might bloat the code size, use a lot of stack, and provide different
+		 * results on different platforms.  An alternative, tiny, third party,
+		 * and limited functionality implementation of sprintf() is provided in
+		 * many of the FreeRTOS/Demo sub-directories in a file called
+		 * printf-stdarg.c (note printf-stdarg.c does not provide a full
+		 * snprintf() implementation!).
+		 *
+		 * It is recommended that production systems call uxTaskGetSystemState()
+		 * directly to get access to raw stats data, rather than indirectly
+		 * through a call to vTaskList().
+		 */
+
+
+		/* Make sure the write buffer does not contain a string. */
+		*pcWriteBuffer = 0x00;
+
+		/* Take a snapshot of the number of tasks in case it changes while this
+		function is executing. */
+		uxArraySize = uxCurrentNumberOfTasks;
+
+		/* Allocate an array index for each task. */
+		pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) );
+
+		if( pxTaskStatusArray != NULL )
+		{
+			/* Generate the (binary) data. */
+			uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, NULL );
+
+			/* Create a human readable table from the binary data. */
+			for( x = 0; x < uxArraySize; x++ )
+			{
+				switch( pxTaskStatusArray[ x ].eCurrentState )
+				{
+					case eReady:		cStatus = tskREADY_CHAR;
+										break;
+
+					case eBlocked:		cStatus = tskBLOCKED_CHAR;
+										break;
+
+					case eSuspended:	cStatus = tskSUSPENDED_CHAR;
+										break;
+
+					case eDeleted:		cStatus = tskDELETED_CHAR;
+										break;
+
+					default:			/* Should not get here, but it is included
+										to prevent static checking errors. */
+										cStatus = 0x00;
+										break;
+				}
+
+				/* Write the task name to the string, padding with spaces so it
+				can be printed in tabular form more easily. */
+				pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName );
+
+				/* Write the rest of the string. */
+				sprintf( pcWriteBuffer, "\t%c\t%u\t%u\t%u\r\n", cStatus, ( unsigned int ) pxTaskStatusArray[ x ].uxCurrentPriority, ( unsigned int ) pxTaskStatusArray[ x ].usStackHighWaterMark, ( unsigned int ) pxTaskStatusArray[ x ].xTaskNumber );
+				pcWriteBuffer += strlen( pcWriteBuffer );
+			}
+
+			/* Free the array again. */
+			vPortFree( pxTaskStatusArray );
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+
+#endif /* ( ( configUSE_TRACE_FACILITY == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) */
+/*----------------------------------------------------------*/
+
+#if ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) )
+
+	void vTaskGetRunTimeStats( char *pcWriteBuffer )
+	{
+	TaskStatus_t *pxTaskStatusArray;
+	volatile UBaseType_t uxArraySize, x;
+	uint32_t ulTotalTime, ulStatsAsPercentage;
+
+		#if( configUSE_TRACE_FACILITY != 1 )
+		{
+			#error configUSE_TRACE_FACILITY must also be set to 1 in FreeRTOSConfig.h to use vTaskGetRunTimeStats().
+		}
+		#endif
+
+		/*
+		 * PLEASE NOTE:
+		 *
+		 * This function is provided for convenience only, and is used by many
+		 * of the demo applications.  Do not consider it to be part of the
+		 * scheduler.
+		 *
+		 * vTaskGetRunTimeStats() calls uxTaskGetSystemState(), then formats part
+		 * of the uxTaskGetSystemState() output into a human readable table that
+		 * displays the amount of time each task has spent in the Running state
+		 * in both absolute and percentage terms.
+		 *
+		 * vTaskGetRunTimeStats() has a dependency on the sprintf() C library
+		 * function that might bloat the code size, use a lot of stack, and
+		 * provide different results on different platforms.  An alternative,
+		 * tiny, third party, and limited functionality implementation of
+		 * sprintf() is provided in many of the FreeRTOS/Demo sub-directories in
+		 * a file called printf-stdarg.c (note printf-stdarg.c does not provide
+		 * a full snprintf() implementation!).
+		 *
+		 * It is recommended that production systems call uxTaskGetSystemState()
+		 * directly to get access to raw stats data, rather than indirectly
+		 * through a call to vTaskGetRunTimeStats().
+		 */
+
+		/* Make sure the write buffer does not contain a string. */
+		*pcWriteBuffer = 0x00;
+
+		/* Take a snapshot of the number of tasks in case it changes while this
+		function is executing. */
+		uxArraySize = uxCurrentNumberOfTasks;
+
+		/* Allocate an array index for each task. */
+		pxTaskStatusArray = pvPortMalloc( uxCurrentNumberOfTasks * sizeof( TaskStatus_t ) );
+
+		if( pxTaskStatusArray != NULL )
+		{
+			/* Generate the (binary) data. */
+			uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalTime );
+
+			/* For percentage calculations. */
+			ulTotalTime /= 100UL;
+
+			/* Avoid divide by zero errors. */
+			if( ulTotalTime > 0 )
+			{
+				/* Create a human readable table from the binary data. */
+				for( x = 0; x < uxArraySize; x++ )
+				{
+					/* What percentage of the total run time has the task used?
+					This will always be rounded down to the nearest integer.
+					ulTotalRunTimeDiv100 has already been divided by 100. */
+					ulStatsAsPercentage = pxTaskStatusArray[ x ].ulRunTimeCounter / ulTotalTime;
+
+					/* Write the task name to the string, padding with
+					spaces so it can be printed in tabular form more
+					easily. */
+					pcWriteBuffer = prvWriteNameToBuffer( pcWriteBuffer, pxTaskStatusArray[ x ].pcTaskName );
+
+					if( ulStatsAsPercentage > 0UL )
+					{
+						#ifdef portLU_PRINTF_SPECIFIER_REQUIRED
+						{
+							sprintf( pcWriteBuffer, "\t%lu\t\t%lu%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter, ulStatsAsPercentage );
+						}
+						#else
+						{
+							/* sizeof( int ) == sizeof( long ) so a smaller
+							printf() library can be used. */
+							sprintf( pcWriteBuffer, "\t%u\t\t%u%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter, ( unsigned int ) ulStatsAsPercentage );
+						}
+						#endif
+					}
+					else
+					{
+						/* If the percentage is zero here then the task has
+						consumed less than 1% of the total run time. */
+						#ifdef portLU_PRINTF_SPECIFIER_REQUIRED
+						{
+							sprintf( pcWriteBuffer, "\t%lu\t\t<1%%\r\n", pxTaskStatusArray[ x ].ulRunTimeCounter );
+						}
+						#else
+						{
+							/* sizeof( int ) == sizeof( long ) so a smaller
+							printf() library can be used. */
+							sprintf( pcWriteBuffer, "\t%u\t\t<1%%\r\n", ( unsigned int ) pxTaskStatusArray[ x ].ulRunTimeCounter );
+						}
+						#endif
+					}
+
+					pcWriteBuffer += strlen( pcWriteBuffer );
+				}
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+
+			/* Free the array again. */
+			vPortFree( pxTaskStatusArray );
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+
+#endif /* ( ( configGENERATE_RUN_TIME_STATS == 1 ) && ( configUSE_STATS_FORMATTING_FUNCTIONS > 0 ) ) */
+/*-----------------------------------------------------------*/
+
+TickType_t uxTaskResetEventItemValue( void )
+{
+TickType_t uxReturn;
+
+	uxReturn = listGET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ) );
+
+	/* Reset the event list item to its normal value - so it can be used with
+	queues and semaphores. */
+	listSET_LIST_ITEM_VALUE( &( pxCurrentTCB->xEventListItem ), ( ( TickType_t ) configMAX_PRIORITIES - ( TickType_t ) pxCurrentTCB->uxPriority ) ); /*lint !e961 MISRA exception as the casts are only redundant for some ports. */
+
+	return uxReturn;
+}
+/*-----------------------------------------------------------*/
+
+#if ( configUSE_MUTEXES == 1 )
+
+	void *pvTaskIncrementMutexHeldCount( void )
+	{
+		/* If xSemaphoreCreateMutex() is called before any tasks have been created
+		then pxCurrentTCB will be NULL. */
+		if( pxCurrentTCB != NULL )
+		{
+			( pxCurrentTCB->uxMutexesHeld )++;
+		}
+
+		return pxCurrentTCB;
+	}
+
+#endif /* configUSE_MUTEXES */
+/*-----------------------------------------------------------*/
+
+#if( configUSE_TASK_NOTIFICATIONS == 1 )
+
+	uint32_t ulTaskNotifyTake( BaseType_t xClearCountOnExit, TickType_t xTicksToWait )
+	{
+	TickType_t xTimeToWake;
+	uint32_t ulReturn;
+
+		taskENTER_CRITICAL();
+		{
+			/* Only block if the notification count is not already non-zero. */
+			if( pxCurrentTCB->ulNotifiedValue == 0UL )
+			{
+				/* Mark this task as waiting for a notification. */
+				pxCurrentTCB->eNotifyState = eWaitingNotification;
+
+				if( xTicksToWait > ( TickType_t ) 0 )
+				{
+					/* The task is going to block.  First it must be removed
+					from the ready list. */
+					if( uxListRemove( &( pxCurrentTCB->xGenericListItem ) ) == ( UBaseType_t ) 0 )
+					{
+						/* The current task must be in a ready list, so there is
+						no need to check, and the port reset macro can be called
+						directly. */
+						portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority );
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+
+					#if ( INCLUDE_vTaskSuspend == 1 )
+					{
+						if( xTicksToWait == portMAX_DELAY )
+						{
+							/* Add the task to the suspended task list instead
+							of a delayed task list to ensure the task is not
+							woken by a timing event.  It will block
+							indefinitely. */
+							vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB->xGenericListItem ) );
+						}
+						else
+						{
+							/* Calculate the time at which the task should be
+							woken if no notification events occur.  This may
+							overflow but this doesn't matter, the scheduler will
+							handle it. */
+							xTimeToWake = xTickCount + xTicksToWait;
+							prvAddCurrentTaskToDelayedList( xTimeToWake );
+						}
+					}
+					#else /* INCLUDE_vTaskSuspend */
+					{
+							/* Calculate the time at which the task should be
+							woken if the event does not occur.  This may
+							overflow but this doesn't matter, the scheduler will
+							handle it. */
+							xTimeToWake = xTickCount + xTicksToWait;
+							prvAddCurrentTaskToDelayedList( xTimeToWake );
+					}
+					#endif /* INCLUDE_vTaskSuspend */
+
+					/* All ports are written to allow a yield in a critical
+					section (some will yield immediately, others wait until the
+					critical section exits) - but it is not something that
+					application code should ever do. */
+					portYIELD_WITHIN_API();
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		taskEXIT_CRITICAL();
+
+		taskENTER_CRITICAL();
+		{
+			ulReturn = pxCurrentTCB->ulNotifiedValue;
+
+			if( ulReturn != 0UL )
+			{
+				if( xClearCountOnExit != pdFALSE )
+				{
+					pxCurrentTCB->ulNotifiedValue = 0UL;
+				}
+				else
+				{
+					( pxCurrentTCB->ulNotifiedValue )--;
+				}
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+
+			pxCurrentTCB->eNotifyState = eNotWaitingNotification;
+		}
+		taskEXIT_CRITICAL();
+
+		return ulReturn;
+	}
+
+#endif /* configUSE_TASK_NOTIFICATIONS */
+/*-----------------------------------------------------------*/
+
+#if( configUSE_TASK_NOTIFICATIONS == 1 )
+
+	BaseType_t xTaskNotifyWait( uint32_t ulBitsToClearOnEntry, uint32_t ulBitsToClearOnExit, uint32_t *pulNotificationValue, TickType_t xTicksToWait )
+	{
+	TickType_t xTimeToWake;
+	BaseType_t xReturn;
+
+		taskENTER_CRITICAL();
+		{
+			/* Only block if a notification is not already pending. */
+			if( pxCurrentTCB->eNotifyState != eNotified )
+			{
+				/* Clear bits in the task's notification value as bits may get
+				set	by the notifying task or interrupt.  This can be used to
+				clear the value to zero. */
+				pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnEntry;
+
+				/* Mark this task as waiting for a notification. */
+				pxCurrentTCB->eNotifyState = eWaitingNotification;
+
+				if( xTicksToWait > ( TickType_t ) 0 )
+				{
+					/* The task is going to block.  First it must be removed
+					from the	ready list. */
+					if( uxListRemove( &( pxCurrentTCB->xGenericListItem ) ) == ( UBaseType_t ) 0 )
+					{
+						/* The current task must be in a ready list, so there is
+						no need to check, and the port reset macro can be called
+						directly. */
+						portRESET_READY_PRIORITY( pxCurrentTCB->uxPriority, uxTopReadyPriority );
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+
+					#if ( INCLUDE_vTaskSuspend == 1 )
+					{
+						if( xTicksToWait == portMAX_DELAY )
+						{
+							/* Add the task to the suspended task list instead
+							of a delayed task list to ensure the task is not
+							woken by a timing event.  It will block
+							indefinitely. */
+							vListInsertEnd( &xSuspendedTaskList, &( pxCurrentTCB->xGenericListItem ) );
+						}
+						else
+						{
+							/* Calculate the time at which the task should be
+							woken if no notification events occur.  This may
+							overflow but this doesn't matter, the scheduler will
+							handle it. */
+							xTimeToWake = xTickCount + xTicksToWait;
+							prvAddCurrentTaskToDelayedList( xTimeToWake );
+						}
+					}
+					#else /* INCLUDE_vTaskSuspend */
+					{
+							/* Calculate the time at which the task should be
+							woken if the event does not occur.  This may
+							overflow but this doesn't matter, the scheduler will
+							handle it. */
+							xTimeToWake = xTickCount + xTicksToWait;
+							prvAddCurrentTaskToDelayedList( xTimeToWake );
+					}
+					#endif /* INCLUDE_vTaskSuspend */
+
+					/* All ports are written to allow a yield in a critical
+					section (some will yield immediately, others wait until the
+					critical section exits) - but it is not something that
+					application code should ever do. */
+					portYIELD_WITHIN_API();
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		taskEXIT_CRITICAL();
+
+		taskENTER_CRITICAL();
+		{
+			if( pulNotificationValue != NULL )
+			{
+				/* Output the current notification value, which may or may not
+				have changed. */
+				*pulNotificationValue = pxCurrentTCB->ulNotifiedValue;
+			}
+
+			/* If eNotifyValue is set then either the task never entered the
+			blocked state (because a notification was already pending) or the
+			task unblocked because of a notification.  Otherwise the task
+			unblocked because of a timeout. */
+			if( pxCurrentTCB->eNotifyState == eWaitingNotification )
+			{
+				/* A notification was not received. */
+				xReturn = pdFALSE;
+			}
+			else
+			{
+				/* A notification was already pending or a notification was
+				received while the task was waiting. */
+				pxCurrentTCB->ulNotifiedValue &= ~ulBitsToClearOnExit;
+				xReturn = pdTRUE;
+			}
+
+			pxCurrentTCB->eNotifyState = eNotWaitingNotification;
+		}
+		taskEXIT_CRITICAL();
+
+		return xReturn;
+	}
+
+#endif /* configUSE_TASK_NOTIFICATIONS */
+/*-----------------------------------------------------------*/
+
+#if( configUSE_TASK_NOTIFICATIONS == 1 )
+
+	BaseType_t xTaskGenericNotify( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, uint32_t *pulPreviousNotificationValue )
+	{
+	TCB_t * pxTCB;
+	eNotifyValue eOriginalNotifyState;
+	BaseType_t xReturn = pdPASS;
+
+		configASSERT( xTaskToNotify );
+		pxTCB = ( TCB_t * ) xTaskToNotify;
+
+		taskENTER_CRITICAL();
+		{
+			if( pulPreviousNotificationValue != NULL )
+			{
+				*pulPreviousNotificationValue = pxTCB->ulNotifiedValue;
+			}
+
+			eOriginalNotifyState = pxTCB->eNotifyState;
+
+			pxTCB->eNotifyState = eNotified;
+
+			switch( eAction )
+			{
+				case eSetBits	:
+					pxTCB->ulNotifiedValue |= ulValue;
+					break;
+
+				case eIncrement	:
+					( pxTCB->ulNotifiedValue )++;
+					break;
+
+				case eSetValueWithOverwrite	:
+					pxTCB->ulNotifiedValue = ulValue;
+					break;
+
+				case eSetValueWithoutOverwrite :
+					if( eOriginalNotifyState != eNotified )
+					{
+						pxTCB->ulNotifiedValue = ulValue;
+					}
+					else
+					{
+						/* The value could not be written to the task. */
+						xReturn = pdFAIL;
+					}
+					break;
+
+				case eNoAction:
+					/* The task is being notified without its notify value being
+					updated. */
+					break;
+			}
+
+
+			/* If the task is in the blocked state specifically to wait for a
+			notification then unblock it now. */
+			if( eOriginalNotifyState == eWaitingNotification )
+			{
+				( void ) uxListRemove( &( pxTCB->xGenericListItem ) );
+				prvAddTaskToReadyList( pxTCB );
+
+				/* The task should not have been on an event list. */
+				configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL );
+
+				if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
+				{
+					/* The notified task has a priority above the currently
+					executing task so a yield is required. */
+					taskYIELD_IF_USING_PREEMPTION();
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		taskEXIT_CRITICAL();
+
+		return xReturn;
+	}
+
+#endif /* configUSE_TASK_NOTIFICATIONS */
+/*-----------------------------------------------------------*/
+
+#if( configUSE_TASK_NOTIFICATIONS == 1 )
+
+	BaseType_t xTaskNotifyFromISR( TaskHandle_t xTaskToNotify, uint32_t ulValue, eNotifyAction eAction, BaseType_t *pxHigherPriorityTaskWoken )
+	{
+	TCB_t * pxTCB;
+	eNotifyValue eOriginalNotifyState;
+	BaseType_t xReturn = pdPASS;
+	UBaseType_t uxSavedInterruptStatus;
+
+		configASSERT( xTaskToNotify );
+
+		/* RTOS ports that support interrupt nesting have the concept of a
+		maximum	system call (or maximum API call) interrupt priority.
+		Interrupts that are	above the maximum system call priority are keep
+		permanently enabled, even when the RTOS kernel is in a critical section,
+		but cannot make any calls to FreeRTOS API functions.  If configASSERT()
+		is defined in FreeRTOSConfig.h then
+		portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
+		failure if a FreeRTOS API function is called from an interrupt that has
+		been assigned a priority above the configured maximum system call
+		priority.  Only FreeRTOS functions that end in FromISR can be called
+		from interrupts	that have been assigned a priority at or (logically)
+		below the maximum system call interrupt priority.  FreeRTOS maintains a
+		separate interrupt safe API to ensure interrupt entry is as fast and as
+		simple as possible.  More information (albeit Cortex-M specific) is
+		provided on the following link:
+		http://www.freertos.org/RTOS-Cortex-M3-M4.html */
+		portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+		pxTCB = ( TCB_t * ) xTaskToNotify;
+
+		uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
+		{
+			eOriginalNotifyState = pxTCB->eNotifyState;
+
+			pxTCB->eNotifyState = eNotified;
+
+			switch( eAction )
+			{
+				case eSetBits	:
+					pxTCB->ulNotifiedValue |= ulValue;
+					break;
+
+				case eIncrement	:
+					( pxTCB->ulNotifiedValue )++;
+					break;
+
+				case eSetValueWithOverwrite	:
+					pxTCB->ulNotifiedValue = ulValue;
+					break;
+
+				case eSetValueWithoutOverwrite :
+					if( eOriginalNotifyState != eNotified )
+					{
+						pxTCB->ulNotifiedValue = ulValue;
+					}
+					else
+					{
+						/* The value could not be written to the task. */
+						xReturn = pdFAIL;
+					}
+					break;
+
+				case eNoAction :
+					/* The task is being notified without its notify value being
+					updated. */
+					break;
+			}
+
+
+			/* If the task is in the blocked state specifically to wait for a
+			notification then unblock it now. */
+			if( eOriginalNotifyState == eWaitingNotification )
+			{
+				/* The task should not have been on an event list. */
+				configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL );
+
+				if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
+				{
+					( void ) uxListRemove( &( pxTCB->xGenericListItem ) );
+					prvAddTaskToReadyList( pxTCB );
+				}
+				else
+				{
+					/* The delayed and ready lists cannot be accessed, so hold
+					this task pending until the scheduler is resumed. */
+					vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) );
+				}
+
+				if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
+				{
+					/* The notified task has a priority above the currently
+					executing task so a yield is required. */
+					if( pxHigherPriorityTaskWoken != NULL )
+					{
+						*pxHigherPriorityTaskWoken = pdTRUE;
+					}
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+		}
+		portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
+
+		return xReturn;
+	}
+
+#endif /* configUSE_TASK_NOTIFICATIONS */
+/*-----------------------------------------------------------*/
+
+#if( configUSE_TASK_NOTIFICATIONS == 1 )
+
+	void vTaskNotifyGiveFromISR( TaskHandle_t xTaskToNotify, BaseType_t *pxHigherPriorityTaskWoken )
+	{
+	TCB_t * pxTCB;
+	eNotifyValue eOriginalNotifyState;
+	UBaseType_t uxSavedInterruptStatus;
+
+		configASSERT( xTaskToNotify );
+
+		/* RTOS ports that support interrupt nesting have the concept of a
+		maximum	system call (or maximum API call) interrupt priority.
+		Interrupts that are	above the maximum system call priority are keep
+		permanently enabled, even when the RTOS kernel is in a critical section,
+		but cannot make any calls to FreeRTOS API functions.  If configASSERT()
+		is defined in FreeRTOSConfig.h then
+		portASSERT_IF_INTERRUPT_PRIORITY_INVALID() will result in an assertion
+		failure if a FreeRTOS API function is called from an interrupt that has
+		been assigned a priority above the configured maximum system call
+		priority.  Only FreeRTOS functions that end in FromISR can be called
+		from interrupts	that have been assigned a priority at or (logically)
+		below the maximum system call interrupt priority.  FreeRTOS maintains a
+		separate interrupt safe API to ensure interrupt entry is as fast and as
+		simple as possible.  More information (albeit Cortex-M specific) is
+		provided on the following link:
+		http://www.freertos.org/RTOS-Cortex-M3-M4.html */
+		portASSERT_IF_INTERRUPT_PRIORITY_INVALID();
+
+		pxTCB = ( TCB_t * ) xTaskToNotify;
+
+		uxSavedInterruptStatus = portSET_INTERRUPT_MASK_FROM_ISR();
+		{
+			eOriginalNotifyState = pxTCB->eNotifyState;
+			pxTCB->eNotifyState = eNotified;
+
+			/* 'Giving' is equivalent to incrementing a count in a counting
+			semaphore. */
+			( pxTCB->ulNotifiedValue )++;
+
+			/* If the task is in the blocked state specifically to wait for a
+			notification then unblock it now. */
+			if( eOriginalNotifyState == eWaitingNotification )
+			{
+				/* The task should not have been on an event list. */
+				configASSERT( listLIST_ITEM_CONTAINER( &( pxTCB->xEventListItem ) ) == NULL );
+
+				if( uxSchedulerSuspended == ( UBaseType_t ) pdFALSE )
+				{
+					( void ) uxListRemove( &( pxTCB->xGenericListItem ) );
+					prvAddTaskToReadyList( pxTCB );
+				}
+				else
+				{
+					/* The delayed and ready lists cannot be accessed, so hold
+					this task pending until the scheduler is resumed. */
+					vListInsertEnd( &( xPendingReadyList ), &( pxTCB->xEventListItem ) );
+				}
+
+				if( pxTCB->uxPriority > pxCurrentTCB->uxPriority )
+				{
+					/* The notified task has a priority above the currently
+					executing task so a yield is required. */
+					if( pxHigherPriorityTaskWoken != NULL )
+					{
+						*pxHigherPriorityTaskWoken = pdTRUE;
+					}
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+		}
+		portCLEAR_INTERRUPT_MASK_FROM_ISR( uxSavedInterruptStatus );
+	}
+
+#endif /* configUSE_TASK_NOTIFICATIONS */
+
+/*-----------------------------------------------------------*/
+
+
+#ifdef FREERTOS_MODULE_TEST
+	#include "tasks_test_access_functions.h"
+#endif
+
+
diff -r 241bff9fe406 -r a8c249046181 FreeRTOS_V8_2_1/source/timers.c
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/FreeRTOS_V8_2_1/source/timers.c	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,918 @@
+/*
+    FreeRTOS V8.2.1 - Copyright (C) 2015 Real Time Engineers Ltd.
+    All rights reserved
+
+    VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
+
+    This file is part of the FreeRTOS distribution.
+
+    FreeRTOS is free software; you can redistribute it and/or modify it under
+    the terms of the GNU General Public License (version 2) as published by the
+    Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.
+
+    ***************************************************************************
+    >>!   NOTE: The modification to the GPL is included to allow you to     !<<
+    >>!   distribute a combined work that includes FreeRTOS without being   !<<
+    >>!   obliged to provide the source code for proprietary components     !<<
+    >>!   outside of the FreeRTOS kernel.                                   !<<
+    ***************************************************************************
+
+    FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
+    WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+    FOR A PARTICULAR PURPOSE.  Full license text is available on the following
+    link: http://www.freertos.org/a00114.html
+
+    ***************************************************************************
+     *                                                                       *
+     *    FreeRTOS provides completely free yet professionally developed,    *
+     *    robust, strictly quality controlled, supported, and cross          *
+     *    platform software that is more than just the market leader, it     *
+     *    is the industry's de facto standard.                               *
+     *                                                                       *
+     *    Help yourself get started quickly while simultaneously helping     *
+     *    to support the FreeRTOS project by purchasing a FreeRTOS           *
+     *    tutorial book, reference manual, or both:                          *
+     *    http://www.FreeRTOS.org/Documentation                              *
+     *                                                                       *
+    ***************************************************************************
+
+    http://www.FreeRTOS.org/FAQHelp.html - Having a problem?  Start by reading
+    the FAQ page "My application does not run, what could be wrong?".  Have you
+    defined configASSERT()?
+
+    http://www.FreeRTOS.org/support - In return for receiving this top quality
+    embedded software for free we request you assist our global community by
+    participating in the support forum.
+
+    http://www.FreeRTOS.org/training - Investing in training allows your team to
+    be as productive as possible as early as possible.  Now you can receive
+    FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
+    Ltd, and the world's leading authority on the world's leading RTOS.
+
+    http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
+    including FreeRTOS+Trace - an indispensable productivity tool, a DOS
+    compatible FAT file system, and our tiny thread aware UDP/IP stack.
+
+    http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
+    Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
+
+    http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
+    Integrity Systems ltd. to sell under the OpenRTOS brand.  Low cost OpenRTOS
+    licenses offer ticketed support, indemnification and commercial middleware.
+
+    http://www.SafeRTOS.com - High Integrity Systems also provide a safety
+    engineered and independently SIL3 certified version for use in safety and
+    mission critical applications that require provable dependability.
+
+    1 tab == 4 spaces!
+*/
+
+/* Standard includes. */
+#include <stdlib.h>
+
+/* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
+all the API functions to use the MPU wrappers.  That should only be done when
+task.h is included from an application file. */
+#define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
+
+#include "FreeRTOS.h"
+#include "task.h"
+#include "queue.h"
+#include "timers.h"
+
+#if ( INCLUDE_xTimerPendFunctionCall == 1 ) && ( configUSE_TIMERS == 0 )
+	#error configUSE_TIMERS must be set to 1 to make the xTimerPendFunctionCall() function available.
+#endif
+
+/* Lint e961 and e750 are suppressed as a MISRA exception justified because the
+MPU ports require MPU_WRAPPERS_INCLUDED_FROM_API_FILE to be defined for the
+header files above, but not in this file, in order to generate the correct
+privileged Vs unprivileged linkage and placement. */
+#undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE /*lint !e961 !e750. */
+
+
+/* This entire source file will be skipped if the application is not configured
+to include software timer functionality.  This #if is closed at the very bottom
+of this file.  If you want to include software timer functionality then ensure
+configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */
+#if ( configUSE_TIMERS == 1 )
+
+/* Misc definitions. */
+#define tmrNO_DELAY		( TickType_t ) 0U
+
+/* The definition of the timers themselves. */
+typedef struct tmrTimerControl
+{
+	const char				*pcTimerName;		/*<< Text name.  This is not used by the kernel, it is included simply to make debugging easier. */ /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+	ListItem_t				xTimerListItem;		/*<< Standard linked list item as used by all kernel features for event management. */
+	TickType_t				xTimerPeriodInTicks;/*<< How quickly and often the timer expires. */
+	UBaseType_t				uxAutoReload;		/*<< Set to pdTRUE if the timer should be automatically restarted once expired.  Set to pdFALSE if the timer is, in effect, a one-shot timer. */
+	void 					*pvTimerID;			/*<< An ID to identify the timer.  This allows the timer to be identified when the same callback is used for multiple timers. */
+	TimerCallbackFunction_t	pxCallbackFunction;	/*<< The function that will be called when the timer expires. */
+	#if( configUSE_TRACE_FACILITY == 1 )
+		UBaseType_t			uxTimerNumber;		/*<< An ID assigned by trace tools such as FreeRTOS+Trace */
+	#endif
+} xTIMER;
+
+/* The old xTIMER name is maintained above then typedefed to the new Timer_t
+name below to enable the use of older kernel aware debuggers. */
+typedef xTIMER Timer_t;
+
+/* The definition of messages that can be sent and received on the timer queue.
+Two types of message can be queued - messages that manipulate a software timer,
+and messages that request the execution of a non-timer related callback.  The
+two message types are defined in two separate structures, xTimerParametersType
+and xCallbackParametersType respectively. */
+typedef struct tmrTimerParameters
+{
+	TickType_t			xMessageValue;		/*<< An optional value used by a subset of commands, for example, when changing the period of a timer. */
+	Timer_t *			pxTimer;			/*<< The timer to which the command will be applied. */
+} TimerParameter_t;
+
+
+typedef struct tmrCallbackParameters
+{
+	PendedFunction_t	pxCallbackFunction;	/* << The callback function to execute. */
+	void *pvParameter1;						/* << The value that will be used as the callback functions first parameter. */
+	uint32_t ulParameter2;					/* << The value that will be used as the callback functions second parameter. */
+} CallbackParameters_t;
+
+/* The structure that contains the two message types, along with an identifier
+that is used to determine which message type is valid. */
+typedef struct tmrTimerQueueMessage
+{
+	BaseType_t			xMessageID;			/*<< The command being sent to the timer service task. */
+	union
+	{
+		TimerParameter_t xTimerParameters;
+
+		/* Don't include xCallbackParameters if it is not going to be used as
+		it makes the structure (and therefore the timer queue) larger. */
+		#if ( INCLUDE_xTimerPendFunctionCall == 1 )
+			CallbackParameters_t xCallbackParameters;
+		#endif /* INCLUDE_xTimerPendFunctionCall */
+	} u;
+} DaemonTaskMessage_t;
+
+/*lint -e956 A manual analysis and inspection has been used to determine which
+static variables must be declared volatile. */
+
+/* The list in which active timers are stored.  Timers are referenced in expire
+time order, with the nearest expiry time at the front of the list.  Only the
+timer service task is allowed to access these lists. */
+PRIVILEGED_DATA static List_t xActiveTimerList1;
+PRIVILEGED_DATA static List_t xActiveTimerList2;
+PRIVILEGED_DATA static List_t *pxCurrentTimerList;
+PRIVILEGED_DATA static List_t *pxOverflowTimerList;
+
+/* A queue that is used to send commands to the timer service task. */
+PRIVILEGED_DATA static QueueHandle_t xTimerQueue = NULL;
+
+#if ( INCLUDE_xTimerGetTimerDaemonTaskHandle == 1 )
+
+	PRIVILEGED_DATA static TaskHandle_t xTimerTaskHandle = NULL;
+
+#endif
+
+/*lint +e956 */
+
+/*-----------------------------------------------------------*/
+
+/*
+ * Initialise the infrastructure used by the timer service task if it has not
+ * been initialised already.
+ */
+static void prvCheckForValidListAndQueue( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * The timer service task (daemon).  Timer functionality is controlled by this
+ * task.  Other tasks communicate with the timer service task using the
+ * xTimerQueue queue.
+ */
+static void prvTimerTask( void *pvParameters ) PRIVILEGED_FUNCTION;
+
+/*
+ * Called by the timer service task to interpret and process a command it
+ * received on the timer queue.
+ */
+static void	prvProcessReceivedCommands( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * Insert the timer into either xActiveTimerList1, or xActiveTimerList2,
+ * depending on if the expire time causes a timer counter overflow.
+ */
+static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, const TickType_t xNextExpiryTime, const TickType_t xTimeNow, const TickType_t xCommandTime ) PRIVILEGED_FUNCTION;
+
+/*
+ * An active timer has reached its expire time.  Reload the timer if it is an
+ * auto reload timer, then call its callback.
+ */
+static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, const TickType_t xTimeNow ) PRIVILEGED_FUNCTION;
+
+/*
+ * The tick count has overflowed.  Switch the timer lists after ensuring the
+ * current timer list does not still reference some timers.
+ */
+static void prvSwitchTimerLists( void ) PRIVILEGED_FUNCTION;
+
+/*
+ * Obtain the current tick count, setting *pxTimerListsWereSwitched to pdTRUE
+ * if a tick count overflow occurred since prvSampleTimeNow() was last called.
+ */
+static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched ) PRIVILEGED_FUNCTION;
+
+/*
+ * If the timer list contains any active timers then return the expire time of
+ * the timer that will expire first and set *pxListWasEmpty to false.  If the
+ * timer list does not contain any timers then return 0 and set *pxListWasEmpty
+ * to pdTRUE.
+ */
+static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty ) PRIVILEGED_FUNCTION;
+
+/*
+ * If a timer has expired, process it.  Otherwise, block the timer service task
+ * until either a timer does expire or a command is received.
+ */
+static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, const BaseType_t xListWasEmpty ) PRIVILEGED_FUNCTION;
+
+/*-----------------------------------------------------------*/
+
+BaseType_t xTimerCreateTimerTask( void )
+{
+BaseType_t xReturn = pdFAIL;
+
+	/* This function is called when the scheduler is started if
+	configUSE_TIMERS is set to 1.  Check that the infrastructure used by the
+	timer service task has been created/initialised.  If timers have already
+	been created then the initialisation will already have been performed. */
+	prvCheckForValidListAndQueue();
+
+	if( xTimerQueue != NULL )
+	{
+		#if ( INCLUDE_xTimerGetTimerDaemonTaskHandle == 1 )
+		{
+			/* Create the timer task, storing its handle in xTimerTaskHandle so
+			it can be returned by the xTimerGetTimerDaemonTaskHandle() function. */
+			xReturn = xTaskCreate( prvTimerTask, "Tmr Svc", ( uint16_t ) configTIMER_TASK_STACK_DEPTH, NULL, ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, &xTimerTaskHandle );
+		}
+		#else
+		{
+			/* Create the timer task without storing its handle. */
+			xReturn = xTaskCreate( prvTimerTask, "Tmr Svc", ( uint16_t ) configTIMER_TASK_STACK_DEPTH, NULL, ( ( UBaseType_t ) configTIMER_TASK_PRIORITY ) | portPRIVILEGE_BIT, NULL);
+		}
+		#endif
+	}
+	else
+	{
+		mtCOVERAGE_TEST_MARKER();
+	}
+
+	configASSERT( xReturn );
+	return xReturn;
+}
+/*-----------------------------------------------------------*/
+
+TimerHandle_t xTimerCreate( const char * const pcTimerName, const TickType_t xTimerPeriodInTicks, const UBaseType_t uxAutoReload, void * const pvTimerID, TimerCallbackFunction_t pxCallbackFunction ) /*lint !e971 Unqualified char types are allowed for strings and single characters only. */
+{
+Timer_t *pxNewTimer;
+
+	/* Allocate the timer structure. */
+	if( xTimerPeriodInTicks == ( TickType_t ) 0U )
+	{
+		pxNewTimer = NULL;
+	}
+	else
+	{
+		pxNewTimer = ( Timer_t * ) pvPortMalloc( sizeof( Timer_t ) );
+		if( pxNewTimer != NULL )
+		{
+			/* Ensure the infrastructure used by the timer service task has been
+			created/initialised. */
+			prvCheckForValidListAndQueue();
+
+			/* Initialise the timer structure members using the function parameters. */
+			pxNewTimer->pcTimerName = pcTimerName;
+			pxNewTimer->xTimerPeriodInTicks = xTimerPeriodInTicks;
+			pxNewTimer->uxAutoReload = uxAutoReload;
+			pxNewTimer->pvTimerID = pvTimerID;
+			pxNewTimer->pxCallbackFunction = pxCallbackFunction;
+			vListInitialiseItem( &( pxNewTimer->xTimerListItem ) );
+
+			traceTIMER_CREATE( pxNewTimer );
+		}
+		else
+		{
+			traceTIMER_CREATE_FAILED();
+		}
+	}
+
+	/* 0 is not a valid value for xTimerPeriodInTicks. */
+	configASSERT( ( xTimerPeriodInTicks > 0 ) );
+
+	return ( TimerHandle_t ) pxNewTimer;
+}
+/*-----------------------------------------------------------*/
+
+BaseType_t xTimerGenericCommand( TimerHandle_t xTimer, const BaseType_t xCommandID, const TickType_t xOptionalValue, BaseType_t * const pxHigherPriorityTaskWoken, const TickType_t xTicksToWait )
+{
+BaseType_t xReturn = pdFAIL;
+DaemonTaskMessage_t xMessage;
+
+	/* Send a message to the timer service task to perform a particular action
+	on a particular timer definition. */
+	if( xTimerQueue != NULL )
+	{
+		/* Send a command to the timer service task to start the xTimer timer. */
+		xMessage.xMessageID = xCommandID;
+		xMessage.u.xTimerParameters.xMessageValue = xOptionalValue;
+		xMessage.u.xTimerParameters.pxTimer = ( Timer_t * ) xTimer;
+
+		if( xCommandID < tmrFIRST_FROM_ISR_COMMAND )
+		{
+			if( xTaskGetSchedulerState() == taskSCHEDULER_RUNNING )
+			{
+				xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait );
+			}
+			else
+			{
+				xReturn = xQueueSendToBack( xTimerQueue, &xMessage, tmrNO_DELAY );
+			}
+		}
+		else
+		{
+			xReturn = xQueueSendToBackFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken );
+		}
+
+		traceTIMER_COMMAND_SEND( xTimer, xCommandID, xOptionalValue, xReturn );
+	}
+	else
+	{
+		mtCOVERAGE_TEST_MARKER();
+	}
+
+	return xReturn;
+}
+/*-----------------------------------------------------------*/
+
+#if ( INCLUDE_xTimerGetTimerDaemonTaskHandle == 1 )
+
+	TaskHandle_t xTimerGetTimerDaemonTaskHandle( void )
+	{
+		/* If xTimerGetTimerDaemonTaskHandle() is called before the scheduler has been
+		started, then xTimerTaskHandle will be NULL. */
+		configASSERT( ( xTimerTaskHandle != NULL ) );
+		return xTimerTaskHandle;
+	}
+
+#endif
+/*-----------------------------------------------------------*/
+
+const char * pcTimerGetTimerName( TimerHandle_t xTimer )
+{
+Timer_t *pxTimer = ( Timer_t * ) xTimer;
+
+	return pxTimer->pcTimerName;
+}
+/*-----------------------------------------------------------*/
+
+static void prvProcessExpiredTimer( const TickType_t xNextExpireTime, const TickType_t xTimeNow )
+{
+BaseType_t xResult;
+Timer_t * const pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList );
+
+	/* Remove the timer from the list of active timers.  A check has already
+	been performed to ensure the list is not empty. */
+	( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
+	traceTIMER_EXPIRED( pxTimer );
+
+	/* If the timer is an auto reload timer then calculate the next
+	expiry time and re-insert the timer in the list of active timers. */
+	if( pxTimer->uxAutoReload == ( UBaseType_t ) pdTRUE )
+	{
+		/* The timer is inserted into a list using a time relative to anything
+		other than the current time.  It will therefore be inserted into the
+		correct list relative to the time this task thinks it is now. */
+		if( prvInsertTimerInActiveList( pxTimer, ( xNextExpireTime + pxTimer->xTimerPeriodInTicks ), xTimeNow, xNextExpireTime ) == pdTRUE )
+		{
+			/* The timer expired before it was added to the active timer
+			list.  Reload it now.  */
+			xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY );
+			configASSERT( xResult );
+			( void ) xResult;
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+	else
+	{
+		mtCOVERAGE_TEST_MARKER();
+	}
+
+	/* Call the timer callback. */
+	pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
+}
+/*-----------------------------------------------------------*/
+
+static void prvTimerTask( void *pvParameters )
+{
+TickType_t xNextExpireTime;
+BaseType_t xListWasEmpty;
+
+	/* Just to avoid compiler warnings. */
+	( void ) pvParameters;
+
+	for( ;; )
+	{
+		/* Query the timers list to see if it contains any timers, and if so,
+		obtain the time at which the next timer will expire. */
+		xNextExpireTime = prvGetNextExpireTime( &xListWasEmpty );
+
+		/* If a timer has expired, process it.  Otherwise, block this task
+		until either a timer does expire, or a command is received. */
+		prvProcessTimerOrBlockTask( xNextExpireTime, xListWasEmpty );
+
+		/* Empty the command queue. */
+		prvProcessReceivedCommands();
+	}
+}
+/*-----------------------------------------------------------*/
+
+static void prvProcessTimerOrBlockTask( const TickType_t xNextExpireTime, const BaseType_t xListWasEmpty )
+{
+TickType_t xTimeNow;
+BaseType_t xTimerListsWereSwitched;
+
+	vTaskSuspendAll();
+	{
+		/* Obtain the time now to make an assessment as to whether the timer
+		has expired or not.  If obtaining the time causes the lists to switch
+		then don't process this timer as any timers that remained in the list
+		when the lists were switched will have been processed within the
+		prvSampleTimeNow() function. */
+		xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched );
+		if( xTimerListsWereSwitched == pdFALSE )
+		{
+			/* The tick count has not overflowed, has the timer expired? */
+			if( ( xListWasEmpty == pdFALSE ) && ( xNextExpireTime <= xTimeNow ) )
+			{
+				( void ) xTaskResumeAll();
+				prvProcessExpiredTimer( xNextExpireTime, xTimeNow );
+			}
+			else
+			{
+				/* The tick count has not overflowed, and the next expire
+				time has not been reached yet.  This task should therefore
+				block to wait for the next expire time or a command to be
+				received - whichever comes first.  The following line cannot
+				be reached unless xNextExpireTime > xTimeNow, except in the
+				case when the current timer list is empty. */
+				vQueueWaitForMessageRestricted( xTimerQueue, ( xNextExpireTime - xTimeNow ) );
+
+				if( xTaskResumeAll() == pdFALSE )
+				{
+					/* Yield to wait for either a command to arrive, or the
+					block time to expire.  If a command arrived between the
+					critical section being exited and this yield then the yield
+					will not cause the task to block. */
+					portYIELD_WITHIN_API();
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+		}
+		else
+		{
+			( void ) xTaskResumeAll();
+		}
+	}
+}
+/*-----------------------------------------------------------*/
+
+static TickType_t prvGetNextExpireTime( BaseType_t * const pxListWasEmpty )
+{
+TickType_t xNextExpireTime;
+
+	/* Timers are listed in expiry time order, with the head of the list
+	referencing the task that will expire first.  Obtain the time at which
+	the timer with the nearest expiry time will expire.  If there are no
+	active timers then just set the next expire time to 0.  That will cause
+	this task to unblock when the tick count overflows, at which point the
+	timer lists will be switched and the next expiry time can be
+	re-assessed.  */
+	*pxListWasEmpty = listLIST_IS_EMPTY( pxCurrentTimerList );
+	if( *pxListWasEmpty == pdFALSE )
+	{
+		xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList );
+	}
+	else
+	{
+		/* Ensure the task unblocks when the tick count rolls over. */
+		xNextExpireTime = ( TickType_t ) 0U;
+	}
+
+	return xNextExpireTime;
+}
+/*-----------------------------------------------------------*/
+
+static TickType_t prvSampleTimeNow( BaseType_t * const pxTimerListsWereSwitched )
+{
+TickType_t xTimeNow;
+PRIVILEGED_DATA static TickType_t xLastTime = ( TickType_t ) 0U; /*lint !e956 Variable is only accessible to one task. */
+
+	xTimeNow = xTaskGetTickCount();
+
+	if( xTimeNow < xLastTime )
+	{
+		prvSwitchTimerLists();
+		*pxTimerListsWereSwitched = pdTRUE;
+	}
+	else
+	{
+		*pxTimerListsWereSwitched = pdFALSE;
+	}
+
+	xLastTime = xTimeNow;
+
+	return xTimeNow;
+}
+/*-----------------------------------------------------------*/
+
+static BaseType_t prvInsertTimerInActiveList( Timer_t * const pxTimer, const TickType_t xNextExpiryTime, const TickType_t xTimeNow, const TickType_t xCommandTime )
+{
+BaseType_t xProcessTimerNow = pdFALSE;
+
+	listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xNextExpiryTime );
+	listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer );
+
+	if( xNextExpiryTime <= xTimeNow )
+	{
+		/* Has the expiry time elapsed between the command to start/reset a
+		timer was issued, and the time the command was processed? */
+		if( ( xTimeNow - xCommandTime ) >= pxTimer->xTimerPeriodInTicks )
+		{
+			/* The time between a command being issued and the command being
+			processed actually exceeds the timers period.  */
+			xProcessTimerNow = pdTRUE;
+		}
+		else
+		{
+			vListInsert( pxOverflowTimerList, &( pxTimer->xTimerListItem ) );
+		}
+	}
+	else
+	{
+		if( ( xTimeNow < xCommandTime ) && ( xNextExpiryTime >= xCommandTime ) )
+		{
+			/* If, since the command was issued, the tick count has overflowed
+			but the expiry time has not, then the timer must have already passed
+			its expiry time and should be processed immediately. */
+			xProcessTimerNow = pdTRUE;
+		}
+		else
+		{
+			vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) );
+		}
+	}
+
+	return xProcessTimerNow;
+}
+/*-----------------------------------------------------------*/
+
+static void	prvProcessReceivedCommands( void )
+{
+DaemonTaskMessage_t xMessage;
+Timer_t *pxTimer;
+BaseType_t xTimerListsWereSwitched, xResult;
+TickType_t xTimeNow;
+
+	while( xQueueReceive( xTimerQueue, &xMessage, tmrNO_DELAY ) != pdFAIL ) /*lint !e603 xMessage does not have to be initialised as it is passed out, not in, and it is not used unless xQueueReceive() returns pdTRUE. */
+	{
+		#if ( INCLUDE_xTimerPendFunctionCall == 1 )
+		{
+			/* Negative commands are pended function calls rather than timer
+			commands. */
+			if( xMessage.xMessageID < ( BaseType_t ) 0 )
+			{
+				const CallbackParameters_t * const pxCallback = &( xMessage.u.xCallbackParameters );
+
+				/* The timer uses the xCallbackParameters member to request a
+				callback be executed.  Check the callback is not NULL. */
+				configASSERT( pxCallback );
+
+				/* Call the function. */
+				pxCallback->pxCallbackFunction( pxCallback->pvParameter1, pxCallback->ulParameter2 );
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+		}
+		#endif /* INCLUDE_xTimerPendFunctionCall */
+
+		/* Commands that are positive are timer commands rather than pended
+		function calls. */
+		if( xMessage.xMessageID >= ( BaseType_t ) 0 )
+		{
+			/* The messages uses the xTimerParameters member to work on a
+			software timer. */
+			pxTimer = xMessage.u.xTimerParameters.pxTimer;
+
+			if( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) == pdFALSE )
+			{
+				/* The timer is in a list, remove it. */
+				( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
+			}
+			else
+			{
+				mtCOVERAGE_TEST_MARKER();
+			}
+
+			traceTIMER_COMMAND_RECEIVED( pxTimer, xMessage.xMessageID, xMessage.u.xTimerParameters.xMessageValue );
+
+			/* In this case the xTimerListsWereSwitched parameter is not used, but
+			it must be present in the function call.  prvSampleTimeNow() must be
+			called after the message is received from xTimerQueue so there is no
+			possibility of a higher priority task adding a message to the message
+			queue with a time that is ahead of the timer daemon task (because it
+			pre-empted the timer daemon task after the xTimeNow value was set). */
+			xTimeNow = prvSampleTimeNow( &xTimerListsWereSwitched );
+
+			switch( xMessage.xMessageID )
+			{
+				case tmrCOMMAND_START :
+			    case tmrCOMMAND_START_FROM_ISR :
+			    case tmrCOMMAND_RESET :
+			    case tmrCOMMAND_RESET_FROM_ISR :
+				case tmrCOMMAND_START_DONT_TRACE :
+					/* Start or restart a timer. */
+					if( prvInsertTimerInActiveList( pxTimer,  xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, xTimeNow, xMessage.u.xTimerParameters.xMessageValue ) == pdTRUE )
+					{
+						/* The timer expired before it was added to the active
+						timer list.  Process it now. */
+						pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
+						traceTIMER_EXPIRED( pxTimer );
+
+						if( pxTimer->uxAutoReload == ( UBaseType_t ) pdTRUE )
+						{
+							xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xMessage.u.xTimerParameters.xMessageValue + pxTimer->xTimerPeriodInTicks, NULL, tmrNO_DELAY );
+							configASSERT( xResult );
+							( void ) xResult;
+						}
+						else
+						{
+							mtCOVERAGE_TEST_MARKER();
+						}
+					}
+					else
+					{
+						mtCOVERAGE_TEST_MARKER();
+					}
+					break;
+
+				case tmrCOMMAND_STOP :
+				case tmrCOMMAND_STOP_FROM_ISR :
+					/* The timer has already been removed from the active list.
+					There is nothing to do here. */
+					break;
+
+				case tmrCOMMAND_CHANGE_PERIOD :
+				case tmrCOMMAND_CHANGE_PERIOD_FROM_ISR :
+					pxTimer->xTimerPeriodInTicks = xMessage.u.xTimerParameters.xMessageValue;
+					configASSERT( ( pxTimer->xTimerPeriodInTicks > 0 ) );
+
+					/* The new period does not really have a reference, and can be
+					longer or shorter than the old one.  The command time is
+					therefore set to the current time, and as the period cannot be
+					zero the next expiry time can only be in the future, meaning
+					(unlike for the xTimerStart() case above) there is no fail case
+					that needs to be handled here. */
+					( void ) prvInsertTimerInActiveList( pxTimer, ( xTimeNow + pxTimer->xTimerPeriodInTicks ), xTimeNow, xTimeNow );
+					break;
+
+				case tmrCOMMAND_DELETE :
+					/* The timer has already been removed from the active list,
+					just free up the memory. */
+					vPortFree( pxTimer );
+					break;
+
+				default	:
+					/* Don't expect to get here. */
+					break;
+			}
+		}
+	}
+}
+/*-----------------------------------------------------------*/
+
+static void prvSwitchTimerLists( void )
+{
+TickType_t xNextExpireTime, xReloadTime;
+List_t *pxTemp;
+Timer_t *pxTimer;
+BaseType_t xResult;
+
+	/* The tick count has overflowed.  The timer lists must be switched.
+	If there are any timers still referenced from the current timer list
+	then they must have expired and should be processed before the lists
+	are switched. */
+	while( listLIST_IS_EMPTY( pxCurrentTimerList ) == pdFALSE )
+	{
+		xNextExpireTime = listGET_ITEM_VALUE_OF_HEAD_ENTRY( pxCurrentTimerList );
+
+		/* Remove the timer from the list. */
+		pxTimer = ( Timer_t * ) listGET_OWNER_OF_HEAD_ENTRY( pxCurrentTimerList );
+		( void ) uxListRemove( &( pxTimer->xTimerListItem ) );
+		traceTIMER_EXPIRED( pxTimer );
+
+		/* Execute its callback, then send a command to restart the timer if
+		it is an auto-reload timer.  It cannot be restarted here as the lists
+		have not yet been switched. */
+		pxTimer->pxCallbackFunction( ( TimerHandle_t ) pxTimer );
+
+		if( pxTimer->uxAutoReload == ( UBaseType_t ) pdTRUE )
+		{
+			/* Calculate the reload value, and if the reload value results in
+			the timer going into the same timer list then it has already expired
+			and the timer should be re-inserted into the current list so it is
+			processed again within this loop.  Otherwise a command should be sent
+			to restart the timer to ensure it is only inserted into a list after
+			the lists have been swapped. */
+			xReloadTime = ( xNextExpireTime + pxTimer->xTimerPeriodInTicks );
+			if( xReloadTime > xNextExpireTime )
+			{
+				listSET_LIST_ITEM_VALUE( &( pxTimer->xTimerListItem ), xReloadTime );
+				listSET_LIST_ITEM_OWNER( &( pxTimer->xTimerListItem ), pxTimer );
+				vListInsert( pxCurrentTimerList, &( pxTimer->xTimerListItem ) );
+			}
+			else
+			{
+				xResult = xTimerGenericCommand( pxTimer, tmrCOMMAND_START_DONT_TRACE, xNextExpireTime, NULL, tmrNO_DELAY );
+				configASSERT( xResult );
+				( void ) xResult;
+			}
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+
+	pxTemp = pxCurrentTimerList;
+	pxCurrentTimerList = pxOverflowTimerList;
+	pxOverflowTimerList = pxTemp;
+}
+/*-----------------------------------------------------------*/
+
+static void prvCheckForValidListAndQueue( void )
+{
+	/* Check that the list from which active timers are referenced, and the
+	queue used to communicate with the timer service, have been
+	initialised. */
+	taskENTER_CRITICAL();
+	{
+		if( xTimerQueue == NULL )
+		{
+			vListInitialise( &xActiveTimerList1 );
+			vListInitialise( &xActiveTimerList2 );
+			pxCurrentTimerList = &xActiveTimerList1;
+			pxOverflowTimerList = &xActiveTimerList2;
+			xTimerQueue = xQueueCreate( ( UBaseType_t ) configTIMER_QUEUE_LENGTH, sizeof( DaemonTaskMessage_t ) );
+			configASSERT( xTimerQueue );
+
+			#if ( configQUEUE_REGISTRY_SIZE > 0 )
+			{
+				if( xTimerQueue != NULL )
+				{
+					vQueueAddToRegistry( xTimerQueue, "TmrQ" );
+				}
+				else
+				{
+					mtCOVERAGE_TEST_MARKER();
+				}
+			}
+			#endif /* configQUEUE_REGISTRY_SIZE */
+		}
+		else
+		{
+			mtCOVERAGE_TEST_MARKER();
+		}
+	}
+	taskEXIT_CRITICAL();
+}
+/*-----------------------------------------------------------*/
+
+BaseType_t xTimerIsTimerActive( TimerHandle_t xTimer )
+{
+BaseType_t xTimerIsInActiveList;
+Timer_t *pxTimer = ( Timer_t * ) xTimer;
+
+	/* Is the timer in the list of active timers? */
+	taskENTER_CRITICAL();
+	{
+		/* Checking to see if it is in the NULL list in effect checks to see if
+		it is referenced from either the current or the overflow timer lists in
+		one go, but the logic has to be reversed, hence the '!'. */
+		xTimerIsInActiveList = ( BaseType_t ) !( listIS_CONTAINED_WITHIN( NULL, &( pxTimer->xTimerListItem ) ) );
+	}
+	taskEXIT_CRITICAL();
+
+	return xTimerIsInActiveList;
+} /*lint !e818 Can't be pointer to const due to the typedef. */
+/*-----------------------------------------------------------*/
+
+void *pvTimerGetTimerID( const TimerHandle_t xTimer )
+{
+Timer_t * const pxTimer = ( Timer_t * ) xTimer;
+void *pvReturn;
+
+	configASSERT( xTimer );
+
+	taskENTER_CRITICAL();
+	{
+		pvReturn = pxTimer->pvTimerID;
+	}
+	taskEXIT_CRITICAL();
+
+	return pvReturn;
+}
+/*-----------------------------------------------------------*/
+
+void vTimerSetTimerID( const TimerHandle_t xTimer, void *pvNewID )
+{
+Timer_t * const pxTimer = ( Timer_t * ) xTimer;
+
+	configASSERT( xTimer );
+
+	taskENTER_CRITICAL();
+	{
+		pxTimer->pvTimerID = pvNewID;
+	}
+	taskEXIT_CRITICAL();
+}
+/*-----------------------------------------------------------*/
+
+#if( INCLUDE_xTimerPendFunctionCall == 1 )
+
+	BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, BaseType_t *pxHigherPriorityTaskWoken )
+	{
+	DaemonTaskMessage_t xMessage;
+	BaseType_t xReturn;
+
+		/* Complete the message with the function parameters and post it to the
+		daemon task. */
+		xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK_FROM_ISR;
+		xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend;
+		xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1;
+		xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2;
+
+		xReturn = xQueueSendFromISR( xTimerQueue, &xMessage, pxHigherPriorityTaskWoken );
+
+		tracePEND_FUNC_CALL_FROM_ISR( xFunctionToPend, pvParameter1, ulParameter2, xReturn );
+
+		return xReturn;
+	}
+
+#endif /* INCLUDE_xTimerPendFunctionCall */
+/*-----------------------------------------------------------*/
+
+#if( INCLUDE_xTimerPendFunctionCall == 1 )
+
+	BaseType_t xTimerPendFunctionCall( PendedFunction_t xFunctionToPend, void *pvParameter1, uint32_t ulParameter2, TickType_t xTicksToWait )
+	{
+	DaemonTaskMessage_t xMessage;
+	BaseType_t xReturn;
+
+		/* This function can only be called after a timer has been created or
+		after the scheduler has been started because, until then, the timer
+		queue does not exist. */
+		configASSERT( xTimerQueue );
+
+		/* Complete the message with the function parameters and post it to the
+		daemon task. */
+		xMessage.xMessageID = tmrCOMMAND_EXECUTE_CALLBACK;
+		xMessage.u.xCallbackParameters.pxCallbackFunction = xFunctionToPend;
+		xMessage.u.xCallbackParameters.pvParameter1 = pvParameter1;
+		xMessage.u.xCallbackParameters.ulParameter2 = ulParameter2;
+
+		xReturn = xQueueSendToBack( xTimerQueue, &xMessage, xTicksToWait );
+
+		tracePEND_FUNC_CALL( xFunctionToPend, pvParameter1, ulParameter2, xReturn );
+
+		return xReturn;
+	}
+
+#endif /* INCLUDE_xTimerPendFunctionCall */
+/*-----------------------------------------------------------*/
+
+/* This entire source file will be skipped if the application is not configured
+to include software timer functionality.  If you want to include software timer
+functionality then ensure configUSE_TIMERS is set to 1 in FreeRTOSConfig.h. */
+#endif /* configUSE_TIMERS == 1 */
+
+
+
+
diff -r 241bff9fe406 -r a8c249046181 cli_uart.cpp
--- a/cli_uart.cpp	Sat Jun 06 14:06:49 2015 +0000
+++ b/cli_uart.cpp	Thu Sep 03 14:02:37 2015 +0000
@@ -12,6 +12,9 @@
 Serial uart(p37, p31);
 #elif (THIS_BOARD == MBED_BOARD_LPC1768)
 Serial uart(p13, p14);
+#elif (THIS_BOARD == LPCXpresso4337)
+Serial uart(P3_4, P1_14);
+Serial uart0(UART0_TX, UART0_RX);
 #endif
 
 int Uart_Write(unsigned char *inBuff)
@@ -40,7 +43,7 @@
 
         RTOS_MUTEX_RELEASE(&g_printLock);
     } else {
-        printf("Uart Write failed [uart not writeable] now trying printf\r\n");
+//        printf("Uart Write failed [uart not writeable] now trying printf\r\n");
         while (usLength) {
             printf("%c",*inBuff);
             usLength--;
@@ -56,6 +59,7 @@
 void CLI_Configure(void)
 {
     uart.baud(115200);
+//    uart0.baud(115200);
 
     RTOS_MUTEX_CREATE(&g_printLock);
 
diff -r 241bff9fe406 -r a8c249046181 main.cpp
--- a/main.cpp	Sat Jun 06 14:06:49 2015 +0000
+++ b/main.cpp	Thu Sep 03 14:02:37 2015 +0000
@@ -45,10 +45,10 @@
 #include "myBoardInit.h"
 
 /* Free-RTOS includes */
-#include "FreeRTOS.h"
-#include "task.h"
-#include "semphr.h"
-#include "portmacro.h"
+//#include "FreeRTOS.h"
+//#include "task.h"
+//#include "semphr.h"
+//#include "portmacro.h"
 
 #include "osi.h"
 
@@ -91,16 +91,18 @@
 Serial pc(SERIAL_TX, SERIAL_RX);
 cc3100 _cc3100(PA_9, PC_7, PB_6, SPI(PA_7, PA_6, PA_5));//nucleoF103  irq, nHib, cs, mosi, miso, sck
 #elif (THIS_BOARD == Seeed_Arch_Max)
-Serial pc(USBTX, USBRX);
-  DigitalOut led1(LED1);
-  DigitalOut led2(LED2);
-  InterruptIn  button1(PC_13);
-cc3100 _cc3100(PE_5, PE_4, PE_6, SPI(PB_5, PB_4, PB_3));//Seeed_Arch_Max  irq, nHib, cs, mosi, miso, sck
+/* Off board leds */
+  DigitalOut led1(PB_15);
+  DigitalOut led2(PB_14);
+cc3100 _cc3100(PC_13, PC_6, PE_5, PE_4, PE_6, SPI(PB_5, PB_4, PB_3));//Seeed_Arch_Max  irq, nHib, cs, mosi, miso, sck
 //SDFileSystem sd(PE_2, PD_11, SPI(PC_3, PC_2, PB_10), "sd", SDFileSystem::SWITCH_NEG_NC, 25000000);
 #elif (THIS_BOARD == LPCXpresso4337)
 /* LPCXpresso4337 not working due to mbed lib */
-//Serial pc(UART0_TX, UART0_RX);
-cc3100 _cc3100(P2_2, P3_5, P1_2, SPI(P1_4, P1_3, PF_4));//LPCXpresso4337  irq, nHib, cs, mosi, miso, sck
+Serial pc(UART0_TX, UART0_RX);
+  DigitalOut led1(LED1);
+  DigitalOut led2(LED2);
+  DigitalOut led3(LED3);
+cc3100 _cc3100(P2_12, P2_9, P2_2, P3_5, P1_2, SPI(P1_4, P1_3, PF_4));//LPCXpresso4337  irq, nHib, cs, mosi, miso, sck
 #else
 
 #endif
@@ -219,6 +221,10 @@
     led2 = 1;
     led3 = 0;
     led4 = 0;   
+#elif (THIS_BOARD == LPCXpresso4337)
+    led1 = 0;
+    led2 = 0;
+    led3 = 0;
 #else
     led1 = 0;
     led2 = 0;
@@ -786,11 +792,15 @@
 	int rv = 0;
 //    SCB->SHCSR |= 0x00070000;//Enable fault handler.  
 //    pc.baud(115200);
+    initLEDs();
     
     CLI_Configure();
+
+    
+    printf(" \r\nSystemCoreClock = %dMHz\r\n ", SystemCoreClock /1000000);
     
     memset(print_buf, 0x00, PRINT_BUF_LEN);
-    sprintf((char*) print_buf, " \r\nSystemCoreClock = %dMHz\r\n ", SystemCoreClock /1000000);
+    sprintf((char*) print_buf, " \r\nSystemCoreClock = %dMHz\r\n ", SystemCoreClock /1000000);    
     rv = Uart_Write((uint8_t *) print_buf);
     if(rv < 0){
     	while(1){
diff -r 241bff9fe406 -r a8c249046181 mbed.bld
--- a/mbed.bld	Sat Jun 06 14:06:49 2015 +0000
+++ b/mbed.bld	Thu Sep 03 14:02:37 2015 +0000
@@ -1,1 +1,1 @@
-http://mbed.org/users/mbed_official/code/mbed/builds/cbbeb26dbd92
\ No newline at end of file
+http://mbed.org/users/mbed_official/code/mbed/builds/ba1f97679dad
\ No newline at end of file
diff -r 241bff9fe406 -r a8c249046181 mqtt_V1.lib
--- a/mqtt_V1.lib	Sat Jun 06 14:06:49 2015 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
-http://developer.mbed.org/users/dflet/code/mqtt_V1/#673880ad39ad
diff -r 241bff9fe406 -r a8c249046181 mqtt_V1/client.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mqtt_V1/client.lib	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,1 @@
+http://developer.mbed.org/users/dflet/code/client/#087b5655778d
diff -r 241bff9fe406 -r a8c249046181 mqtt_V1/common/mqtt_common.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mqtt_V1/common/mqtt_common.cpp	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,532 @@
+/******************************************************************************
+*
+*   Copyright (C) 2014 Texas Instruments Incorporated
+*
+*   All rights reserved. Property of Texas Instruments Incorporated.
+*   Restricted rights to use, duplicate or disclose this code are
+*   granted through contract.
+*
+*   The program may not be used without the written permission of
+*   Texas Instruments Incorporated or against the terms and conditions
+*   stipulated in the agreement under which this program has been supplied,
+*   and under no circumstances can it be used with non-TI connectivity device.
+*
+******************************************************************************/
+
+/*
+   mqtt_common.c
+
+   This module implements routines that are common to both client and server
+   components.
+*/
+
+#include "mqtt_common.h"
+#include "cli_uart.h"
+
+namespace mbed_mqtt {
+
+static void free_mqp(struct mqtt_packet *mqp)
+{
+        if((NULL != mqp->free) && (0 == --mqp->n_refs))
+                mqp->free(mqp);
+
+        return;
+}
+
+void mqp_free(struct mqtt_packet *mqp)
+{
+        free_mqp(mqp);
+}
+
+static void reset_mqp(struct mqtt_packet *mqp)
+{
+
+        /* Fields not handled here are meant to be left unaltered. */
+        mqp->msg_type = 0x00;
+        mqp->fh_byte1 = 0x00;
+        mqp->msg_id   = 0;
+        mqp->fh_len   = 0x00;
+        mqp->vh_len   = 0;
+        mqp->pl_len   = 0;
+        mqp->private_  = 0;
+}
+
+void mqp_reset(struct mqtt_packet *mqp)
+{
+        reset_mqp(mqp);
+}
+
+void mqp_init(struct mqtt_packet *mqp, uint8_t offset)
+{
+        reset_mqp(mqp);
+
+        mqp->offset = offset;
+        mqp->n_refs = 0x01;
+        mqp->next   = NULL;
+}
+
+static int32_t buf_wr_utf8(uint8_t *buf, const struct utf8_string *utf8)
+{
+        uint8_t *ref = buf;
+
+        buf += buf_wr_nbo_2B(buf,      utf8->length);
+        buf += buf_wr_nbytes(buf, (uint8_t*)utf8->buffer, utf8->length);
+
+        return buf - ref;
+}
+
+int32_t mqp_buf_wr_utf8(uint8_t *buf, const struct utf8_string *utf8)
+{
+        return buf_wr_utf8(buf, utf8);
+}
+
+#define MAX_REMLEN_BYTES  (MAX_FH_LEN - 1)
+
+static int32_t buf_tail_wr_remlen(uint8_t *buf, uint32_t remlen)
+{
+
+        uint8_t val[MAX_REMLEN_BYTES], i = 0;
+
+        do {
+                val[i] = remlen & 0x7F; /* MOD 128 */
+                remlen = remlen >> 7;   /* DIV 128 */
+
+                if(remlen)
+                        val[i] |= 0x80;
+
+                i++;
+
+        } while(remlen > 0);
+
+        buf_wr_nbytes(buf + MAX_REMLEN_BYTES - i, val, i);
+        
+        return i;       /* # bytes written in buf */
+}
+
+int32_t mqp_buf_tail_wr_remlen(uint8_t *buf, uint32_t remlen)
+{
+        return buf_tail_wr_remlen(buf, remlen);
+}
+
+static int32_t buf_rd_remlen(uint8_t *buf, uint32_t *remlen)
+{
+        uint32_t val = 0, mul = 0;
+        int32_t i = 0;
+
+        do {
+                val += (buf[i] & 0x7F) << mul;
+                mul += 7;
+
+        } while((buf[i++] & 0x80)       &&
+                (i < MAX_REMLEN_BYTES));
+
+        *remlen = val;
+
+        /* Return -1 if value was not found */
+        return (buf[i - 1] & 0x80)? -1 : i;
+}
+
+int32_t mqp_buf_rd_remlen(uint8_t *buf, uint32_t *remlen)
+{
+        return buf_rd_remlen(buf, remlen);
+}
+
+int32_t mqp_pub_append_topic(struct mqtt_packet *mqp, const struct utf8_string *topic,
+                     uint16_t msg_id)
+{
+        uint8_t *buf = MQP_VHEADER_BUF(mqp), *ref = buf;
+
+        if(0 != mqp->vh_len){
+                Uart_Write((uint8_t*)"Topic has been already added\r\n");
+                return -1; /* Topic has been already added */
+        }
+        if(MQP_FREEBUF_LEN(mqp) < (topic + msg_id? 2 : 0)){
+                Uart_Write((uint8_t*)"Can't WR topic\r\n");
+                return MQP_ERR_PKT_LEN; /* Can't WR topic */
+        }
+        buf += buf_wr_utf8(buf, topic);
+
+        if(0 != msg_id) {  /* MSG ID 0 indicates ==> QoS0 */
+                mqp->msg_id = msg_id;
+                buf += buf_wr_nbo_2B(buf, mqp->msg_id);
+        }
+
+        mqp->vh_len += buf - ref;
+
+        return buf - ref;
+}
+
+int32_t mqp_pub_append_data(struct mqtt_packet *mqp, const uint8_t *data_buf,
+                        uint32_t data_len)
+{
+        uint8_t *buf = MQP_PAYLOAD_BUF(mqp) + mqp->pl_len, *ref = buf;
+
+        if(0 == mqp->vh_len)
+                return -1;    /* Must include topic first */
+
+        if(MQP_FREEBUF_LEN(mqp) < data_len)
+                return MQP_ERR_PKT_LEN; /* Can't WR  data */
+
+        /* Including payload info for PUBLISH */
+        buf += buf_wr_nbytes(buf, data_buf, data_len);
+        mqp->pl_len += buf - ref;
+
+        return buf - ref;
+}
+
+static bool proc_vh_msg_id_rx(struct mqtt_packet *mqp_raw)
+{
+        uint8_t *buf = MQP_VHEADER_BUF(mqp_raw);
+
+        if(mqp_raw->pl_len < 2)
+                return false;    /* Bytes for MSG ID not available */
+
+        buf += buf_rd_nbo_2B(buf, &mqp_raw->msg_id);
+        mqp_raw->vh_len += 2;
+        mqp_raw->pl_len -= 2;
+
+        return true;
+}
+
+bool mqp_proc_vh_msg_id_rx(struct mqtt_packet *mqp_raw)
+{
+        return proc_vh_msg_id_rx(mqp_raw);
+}
+
+bool mqp_proc_msg_id_ack_rx(struct mqtt_packet *mqp_raw, bool has_pl)
+{
+        if((false == proc_vh_msg_id_rx(mqp_raw)) ||
+           (has_pl ^ (!!mqp_raw->pl_len)))
+                return false;
+
+        return true;
+}
+
+bool mqp_proc_pub_rx(struct mqtt_packet *mqp_raw)
+{
+        uint8_t *buf = MQP_VHEADER_BUF(mqp_raw), *ref = buf;
+        uint16_t tmp = 0;
+
+        if(mqp_raw->pl_len < (buf - ref + 2))    /* Length Check  */
+                return false;      /* No space to hold Topic size */
+
+        buf += buf_rd_nbo_2B(buf, &tmp);         /* Topic  Length */
+        buf += tmp;                              /* Topic Content */
+
+        if(MQTT_QOS0 != ENUM_QOS(mqp_raw->fh_byte1)) {
+                if(mqp_raw->pl_len < (buf - ref + 2))
+                        return false;  /* No space to hold MSG ID */
+
+                buf += buf_rd_nbo_2B(buf, &mqp_raw->msg_id);
+        }
+
+        mqp_raw->vh_len += buf - ref;
+        mqp_raw->pl_len -= buf - ref;
+
+        return true;
+}
+
+bool mqp_ack_wlist_append(struct mqtt_ack_wlist *list,
+                          struct mqtt_packet    *elem)
+{
+        elem->next = NULL;
+
+        if(list->tail) {
+                list->tail->next = elem;
+                list->tail = elem;
+        } else {
+                list->tail = elem;
+                list->head = elem;
+        }
+
+        return true;
+}
+
+struct mqtt_packet *mqp_ack_wlist_remove(struct mqtt_ack_wlist *list,
+                                          uint16_t msg_id)
+{
+        struct mqtt_packet *elem = list->head, *prev = NULL;
+
+        while(elem) {
+                if(msg_id == elem->msg_id) {
+                        if(prev)
+                                prev->next = elem->next;
+                        else
+                                list->head = elem->next;
+
+                        if(NULL == list->head)
+                                list->tail = NULL;
+
+                        if(list->tail == elem)
+                                list->tail = prev;
+
+                        break;
+                }
+
+                prev = elem;
+                elem = elem->next;
+        }
+
+        return elem;
+}
+
+void mqp_ack_wlist_purge(struct mqtt_ack_wlist *list)
+{
+
+        struct mqtt_packet *elem = list->head;
+
+        while(elem) {
+                struct mqtt_packet *next = elem->next;
+                free_mqp(elem);
+                elem = next;
+        }
+
+        list->head = NULL;
+        list->tail = NULL;
+
+        return;
+}
+
+void secure_conn_struct_init(struct secure_conn *nw_security)
+{
+        nw_security->method = nw_security->cipher = NULL; 
+        nw_security->files  = NULL;
+        nw_security->n_file = 0;
+
+        return;
+}
+
+int32_t mqp_prep_fh(struct mqtt_packet *mqp, uint8_t flags)
+{
+
+        uint32_t remlen = mqp->vh_len + mqp->pl_len;
+        uint8_t *buf    = mqp->buffer + mqp->offset;
+        uint8_t *ref    = buf;
+
+        buf -= buf_tail_wr_remlen(buf - MAX_REMLEN_BYTES, remlen);
+
+        buf -= 1; /* Make space for FH Byte1 */        
+        mqp->fh_byte1 = *buf = MAKE_FH_BYTE1(mqp->msg_type, flags);
+
+        mqp->fh_len   = ref - buf;
+        mqp->offset  -= ref - buf;
+        
+        return ref - buf;
+}
+
+/*
+    Since, the network connection is a TCP socket stream, it is imperative that
+    adequate checks are put in place to identify a MQTT packet and isolate it
+    for further processing. The intent of following routine is to read just one
+    packet from continuous stream and leave rest for the next iteration.
+*/
+
+#define RET_IF_ERR_IN_NET_RECV(net, buf, len, wait_secs, timed_out, ctx)\
+        rv = net_ops->recv(net, buf, len, wait_secs, timed_out, ctx);   \
+        if(rv < 1)                                                      \
+                return MQP_ERR_NETWORK;
+
+int32_t mqp_recv(int32_t net, const struct device_net_services *net_ops,
+             struct mqtt_packet *mqp, uint32_t wait_secs, bool *timed_out,
+             void *ctx)
+{
+        uint8_t *buf = MQP_FHEADER_BUF(mqp), *ref = buf, fh_len = mqp->fh_len;
+        uint32_t pl_len = mqp->pl_len, remlen = 0;
+        int32_t rv;
+
+        while(2 > fh_len) {
+                RET_IF_ERR_IN_NET_RECV(net, buf + fh_len, 1, wait_secs,
+                                       timed_out, ctx);
+
+                mqp->fh_len = ++fh_len;
+        }
+
+        while(buf[fh_len - 1] & 0x80) {
+                if(fh_len > MAX_FH_LEN)
+                        return MQP_ERR_NOT_DEF;/* Shouldn't happen */
+                
+                 RET_IF_ERR_IN_NET_RECV(net, buf + fh_len, 1, wait_secs,
+                                        timed_out, ctx);
+
+                 mqp->fh_len = ++fh_len;
+        }
+
+        mqp_buf_rd_remlen(buf + 1, &remlen);
+        if(mqp->maxlen < (remlen + fh_len))
+                return MQP_ERR_PKT_LEN;  /* Inadequate free buffer */
+
+        buf += fh_len;     /* Try to read all data that follows FH */
+        while(pl_len < remlen) {
+               RET_IF_ERR_IN_NET_RECV(net, buf + pl_len, remlen - pl_len,
+                                      wait_secs, timed_out, ctx);
+
+               mqp->pl_len = pl_len += rv;
+        }
+
+        /* Set up MQTT Packet for received data from broker */
+        buf_wr_nbytes(MQP_FHEADER_BUF(mqp), ref, fh_len);
+        mqp->fh_byte1 = *ref;
+        mqp->msg_type = MSG_TYPE(*ref);
+
+        return fh_len + remlen;
+}
+
+/*----------------------------------------------------------------------------
+ * QoS2 PUB RX Message handling mechanism and associated house-keeping
+ *--------------------------------------------------------------------------*/
+void qos2_pub_cq_reset(struct pub_qos2_cq *cq)
+{
+
+        //        memset(cq->id_vec, 0, sizeof(cq->id_vec));
+        buf_set((uint8_t*)cq->id_vec, 0, sizeof(cq->id_vec));
+        cq->n_free = MAX_PUBREL_INFLT;
+        cq->rd_idx = 0;
+        cq->wr_idx = 0;
+
+        return;
+}
+
+bool qos2_pub_cq_logup(struct pub_qos2_cq *cq, uint16_t msg_id)
+{
+        if(0 != cq->n_free) {
+                cq->id_vec[cq->wr_idx++]  = msg_id;
+                cq->wr_idx &= MAX_PUBREL_INFLT - 1;
+                cq->n_free--;
+                return true;
+        }
+
+        /* Must ensure through an out-of-band arrangement that a remote doesn't
+           push more than MAX_PUBREL_INFLT in-flight QOS2 PUB packets to local.
+           If it still happens that the local receives more in-flight messages,
+           then it has no option but to close the network connection.
+
+           Closing of network connection is left to invoker to of this service.
+        */
+
+        return false;
+}
+
+bool qos2_pub_cq_unlog(struct pub_qos2_cq *cq, uint16_t msg_id)
+{
+        /* Simple implementation. Should be good for embedded system */
+        if(cq->n_free < MAX_PUBREL_INFLT) {
+                /* Follow-up messages for QOS2 PUB must be transacted in the
+                   same order as the initial sequence of QOS2 PUB dispatches.
+                   Therefore, checking the first entry should be OK
+                */
+                if(msg_id == cq->id_vec[cq->rd_idx++]) {
+                        cq->rd_idx &= MAX_PUBREL_INFLT - 1;
+                        cq->n_free++;
+                        return true;
+                }
+        }
+
+        return false;
+}
+
+bool qos2_pub_cq_check(struct pub_qos2_cq *cq, uint16_t msg_id)
+{
+        uint8_t rd_idx = cq->rd_idx;
+        uint8_t n_free = cq->n_free;
+        uint8_t i = 0;
+
+        /* Go through the vector to see if packet ID is still active */
+        for(i = 0; i < (MAX_PUBREL_INFLT - n_free); i++) {
+                    if(msg_id == cq->id_vec[rd_idx++]) 
+                            return true;
+
+                    rd_idx &= MAX_PUBREL_INFLT - 1;
+        }
+
+        return false;
+}
+
+/*----------------------------------------------------------------------------
+ * Client Context related details and associated house-keeping
+ *--------------------------------------------------------------------------*/
+void cl_ctx_reset(struct client_ctx *cl_ctx)
+{
+        cl_ctx->usr       = NULL;
+        cl_ctx->net       = -1;
+        cl_ctx->ip_length = 16;
+
+        cl_ctx->timeout   = 0;
+        cl_ctx->ka_secs   = 0;
+
+        cl_ctx->flags     = 0;
+
+        return;
+}
+
+void cl_ctx_timeout_insert(struct client_ctx **head, struct client_ctx *elem)
+{
+
+        struct client_ctx *curr, *prev = NULL;
+
+        if(NULL == *head) {
+                *head = elem;
+                return;
+        }
+
+        curr = *head;
+        while(curr) {
+                if(elem->timeout < curr->timeout) {
+                        if(NULL == prev) {
+                                elem->next = *head;
+                                *head = elem;
+                        } else {
+                                prev->next = elem;
+                                elem->next = curr;
+                        }
+
+                        break;
+                }
+                
+                prev = curr;
+                curr = curr->next;
+        }
+
+        if(NULL == curr)
+                prev->next = elem;
+}
+
+void cl_ctx_remove(struct client_ctx **head, struct client_ctx *elem)
+{
+        struct client_ctx *curr = *head, *prev = NULL;
+
+        while(curr) {
+                if(curr == elem) {
+                        if(NULL == prev) {
+                                *head = elem->next;
+                                prev  = *head;
+                        } else {
+                                prev->next = elem->next;
+                        }
+
+                        elem->next = NULL;
+                        break;
+                }
+
+                prev = curr;
+                curr = curr->next;
+        }
+}
+
+void cl_ctx_timeout_update(struct client_ctx *cl_ctx, uint32_t now_secs)
+{
+        uint32_t timeout = KA_TIMEOUT_NONE;
+        uint16_t ka_secs = cl_ctx->ka_secs;
+
+        if((0 == ka_secs) && (KA_TIMEOUT_NONE == cl_ctx->timeout))
+                return;
+
+        if(0 != ka_secs)
+                timeout = now_secs + ka_secs;
+
+        cl_ctx->timeout = timeout;
+
+        return;
+}
+
+}//namespace mbed_mqtt 
+
diff -r 241bff9fe406 -r a8c249046181 mqtt_V1/common/mqtt_common.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mqtt_V1/common/mqtt_common.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,789 @@
+/******************************************************************************
+*
+*   Copyright (C) 2014 Texas Instruments Incorporated
+*
+*   All rights reserved. Property of Texas Instruments Incorporated.
+*   Restricted rights to use, duplicate or disclose this code are
+*   granted through contract.
+*
+*   The program may not be used without the written permission of
+*   Texas Instruments Incorporated or against the terms and conditions
+*   stipulated in the agreement under which this program has been supplied,
+*   and under no circumstances can it be used with non-TI connectivity device.
+*
+******************************************************************************/
+
+/*
+  mqtt_common.h
+
+  This module outlines the interfaces that are common to both client amd
+  server components. The applications are not expected to utilize the
+  services outlined in this module.
+*/
+
+#ifndef __MQTT_COMMON_H__
+#define __MQTT_COMMON_H__
+
+/** @file mqtt_common.h 
+    This file incorporates constructs that are common to both client and server
+    implementation. 
+
+    The applications are not expected to utlize the routines made available in
+    this module module. 
+
+    @note the routines in this module do not check for availability and 
+    correctness of the input parameters
+
+    @warning The module is expected to under-go changes whilst incorporating
+    support for the server. Therefore, it is suggested that applications do
+    not rely on the services provided in this module.
+*/
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdbool.h>
+
+#include "platform.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+namespace mbed_mqtt {
+
+#define MQTT_COMMON_VERSTR "1.1.1" /**< Version of Common LIB */
+
+#define MIN(a, b) ((a > b)? b : a)
+
+/** MQTT Message Types */
+#define MQTT_CONNECT      0x01
+#define MQTT_CONNACK      0x02
+#define MQTT_PUBLISH      0x03
+#define MQTT_PUBACK       0x04
+#define MQTT_PUBREC       0x05
+#define MQTT_PUBREL       0x06
+#define MQTT_PUBCOMP      0x07
+#define MQTT_SUBSCRIBE    0x08
+#define MQTT_SUBACK       0x09
+#define MQTT_UNSUBSCRIBE  0x0A
+#define MQTT_UNSUBACK     0x0B
+#define MQTT_PINGREQ      0x0C
+#define MQTT_PINGRSP      0x0D
+#define MQTT_DISCONNECT   0x0E
+
+#define MAX_FH_LEN        0x05    /**< MAX Length of Fixed Header */
+
+/** Max number of bytes in remaining length field */
+#define MAX_REMLEN_BYTES  (MAX_FH_LEN - 1)  
+
+#define MAKE_FH_BYTE1(msg_type,  flags) (uint8_t)((msg_type << 4) | flags)
+
+#define MAKE_FH_FLAGS(bool_dup, enum_qos, bool_retain)                  \
+        (uint8_t)(((bool_dup << 3) | (enum_qos << 1) | bool_retain) & 0xF)
+
+#define QID_VMASK           0x3
+#define QOS_VALUE(enum_qos) (uint8_t)(enum_qos & QID_VMASK)
+#define QFL_VALUE           0x80  /**< QOS Failure value (SUBACK) */
+
+#define DUP_FLAG_VAL(bool_val) (uint8_t)(bool_val << 3)
+
+#define BOOL_RETAIN(fh_byte1)  ((fh_byte1 & 0x1)? true : false)
+#define BOOL_DUP(fh_byte1)     ((fh_byte1 & 0x8)? true : false)
+#define ENUM_QOS(fh_byte1)     (enum mqtt_qos)((fh_byte1 & 0x6) >> 1)
+
+#define MSG_TYPE(fh_byte1)  (uint8_t)((fh_byte1 & 0xf0) >> 4)
+
+static inline uint32_t buf_wr_nbytes(uint8_t *dst, const uint8_t *src, uint32_t n)
+{
+//        printf("buf_wr_nbytes\r\n");
+        uint32_t c = n; 
+        while(c--)
+                *dst++ = *src++;
+
+        return n;
+}
+
+static inline uint32_t buf_set(uint8_t *dst, uint8_t val, uint32_t n)
+{
+        uint32_t c = n; 
+        while(c--)
+                *dst++ = val;
+
+        return n;
+}
+
+/** Writing 2 bytes entity in network byte order */
+static inline uint32_t buf_wr_nbo_2B(uint8_t *buf, uint16_t val)
+{
+        buf[0] = (uint8_t)((val >> 8) & 0xFF); /* MSB */
+        buf[1] = (uint8_t)((val)      & 0xFF); /* LSB */
+        return 2;
+}
+
+/** Reading 2 bytes entity in network byte order */
+static inline uint32_t buf_rd_nbo_2B(const uint8_t *buf, uint16_t *val)
+{
+        *val = (uint16_t)((buf[0] << 8) | (buf[1]));
+        return 2;
+}
+
+/** @defgroup mqp_group MQTT Packet (MQP) Buffer structure
+    The core construct to encapsulate, construct and process a message
+
+    @{
+*/
+struct mqtt_packet {
+
+        uint8_t                     msg_type;   /**< MQTT  Message  Type */
+        uint8_t                     fh_byte1;   /**< Fixed Header: Byte1 */
+
+        uint16_t                    msg_id;     /**< Msg transaction  ID */
+
+        uint8_t                     n_refs;     /**< # users of this msg */
+        uint8_t                     pad[3];
+
+        uint8_t                     offset;     /**< Start of data index */
+        uint8_t                     fh_len;     /**< Fix Header Length   */
+        uint16_t                    vh_len;     /**< Var Header Length   */
+        uint32_t                    pl_len;     /**< Pay Load   Length   */
+
+        uint32_t                    private_;
+
+        uint32_t                    maxlen;     /**< Maximum buffer size */
+        uint8_t                    *buffer;     /**< The attached buffer */
+
+        /** Method to free this packet to a particular pool */
+        void                  (*free)(struct mqtt_packet *mqp);
+
+        struct mqtt_packet    *next;
+};
+
+/** @} */
+
+#define MQP_FHEADER_BUF(mqp)  (mqp->buffer + mqp->offset)
+#define MQP_VHEADER_BUF(mqp)  (MQP_FHEADER_BUF(mqp) + mqp->fh_len)
+#define MQP_PAYLOAD_BUF(mqp)  (MQP_VHEADER_BUF(mqp) + mqp->vh_len)
+
+#define MQP_CONTENT_LEN(mqp)  (mqp->fh_len + mqp->vh_len + mqp->pl_len)
+#define MQP_FREEBUF_LEN(mqp)  (mqp->maxlen - mqp->offset -      \
+                               MQP_CONTENT_LEN(mqp))
+
+#define MQP_FHEADER_VAL(mqp)  (mqp->fh_byte1)
+#define MQP_FHEADER_MSG(mqp)  (MSG_TYPE(MQP_FHEADER_VAL(mqp)))
+#define MQP_FHEADER_FLG(mqp)  (MSG_FLAGS(MQP_FHEADER_VAL(mqp)))
+
+#define DEFINE_MQP_VEC(num_mqp, mqp_vec)                \
+        static struct mqtt_packet mqp_vec[num_mqp];
+
+#define DEFINE_MQP_BUF_VEC(num_mqp, mqp_vec, buf_len, buf_vec)        \
+        DEFINE_MQP_VEC(num_mqp, mqp_vec);                             \
+        static uint8_t buf_vec[num_mqp][buf_len];
+
+/*---------------------------------------------------------------------
+ * Heleper MACROS for PUBLISH-RX Message Processing
+ *---------------------------------------------------------------------
+ */
+
+/** @defgroup rxpub_help_group Helper Macros for RX PUBLISH
+    @{
+*/
+
+/** Yields pointer to topic content */
+#define MQP_PUB_TOP_BUF(mqp) (MQP_VHEADER_BUF(mqp) + 2)
+
+/** Length or size of topic content */
+#define MQP_PUB_TOP_LEN(mqp) (mqp->vh_len - 2 - (mqp->msg_id? 2 : 0))
+
+/** Yields pointer to payload data */
+#define MQP_PUB_PAY_BUF(mqp) (mqp->pl_len? MQP_PAYLOAD_BUF(mqp) : NULL)
+
+/** Length or size of payload data */
+#define MQP_PUB_PAY_LEN(mqp) (mqp->pl_len)
+
+/** @} */
+
+/** @cond
+    CONNECT Message Flags, as outined in the MQTT Specification
+*/
+#define WILL_RETAIN_VAL 0x20
+#define WILL_CONFIG_VAL 0x04
+#define CLEAN_START_VAL 0x02
+#define USER_NAME_OPVAL 0x80
+#define PASS_WORD_OPVAL 0x40
+/**
+    @endcond
+*/
+
+/** @cond
+    CONNACK 8bit Return Code, as outlined in the MQTT Specification
+*/
+#define CONNACK_RC_REQ_ACCEPT   0x00
+#define CONNACK_RC_BAD_PROTOV   0x01
+#define CONNACK_RC_CLI_REJECT   0x02
+#define CONNACK_RC_SVR_UNAVBL   0x03
+#define CONNACK_RC_BAD_USRPWD   0x04
+#define CONNACK_RC_NOT_AUTHED   0x05
+/**
+   @endcond
+*/
+
+/** @defgroup lib_err_group LIBRARY Generated Error Codes
+    Library provides these codes as return values in several routines
+
+    @{
+*/
+#define MQP_ERR_NETWORK   (-1)  /**< Problem in network (sock err) */
+#define MQP_ERR_TIMEOUT   (-2)  /**< Net transaction has timed out */
+#define MQP_ERR_NET_OPS   (-3)  /**< Platform Net Ops un-available */
+#define MQP_ERR_FNPARAM   (-4)  /**< Invalid parameter(s) provided */
+#define MQP_ERR_PKT_AVL   (-5)  /**< No pkts are available in pool */
+#define MQP_ERR_PKT_LEN   (-6)  /**< Inadequate free buffer in pkt */
+#define MQP_ERR_NOTCONN   (-7)  /**< Lib isn't CONNECTED to server */
+#define MQP_ERR_BADCALL   (-8)  /**< Irrelevant call for LIB state */
+#define MQP_ERR_CONTENT   (-9)  /**< MSG / Data content has errors */
+#define MQP_ERR_LIBQUIT  (-10)  /**< Needs reboot library has quit */
+
+
+#define MQP_ERR_NOT_DEF  (-32)  /**< Value other than defined ones */
+
+/** @} */
+
+/*---------------------------------------------------------------------
+ * Common Operations
+ *---------------------------------------------------------------------
+ */
+
+/** Free a MQTT Packet Buffer 
+    Puts back the packet buffer in to the appropriate pool.
+    
+    @param[in] mqp packet buffer to be freed
+    @return none
+*/
+void mqp_free(struct mqtt_packet *mqp);
+
+/** Resets the attributes of MQTT Packet Holder to its init state
+    Not all fields are reset - entities such as offset, n_refs in addition
+    to buffer information are not updated.
+
+    @param[in] mqp packet buffer to be reset
+    @return none
+
+    @see mqp_init
+*/
+void mqp_reset(struct mqtt_packet *mqp);
+
+/** Initializes attributes of the MQTT Packet Holder.
+    This routine sets number of users of the MQTT Packet Holder to 1. However,
+    it leaves, if already provisioned, the reference to buffer and its size
+    un-altered.
+
+    @param[in] mqp packet buffer to be initialized
+    @param[in] offset index in buffer to indicate start of the contents
+    @return none
+*/
+void mqp_init(struct mqtt_packet *mqp, uint8_t offset);
+
+/** Initialize MQTT Packet Holder and attach the buffer */
+static 
+inline void mqp_buffer_attach(struct mqtt_packet *mqp, uint8_t *buffer, uint32_t length,
+                              uint8_t offset)
+{
+        mqp_init(mqp, offset);
+
+        mqp->buffer = buffer;
+        mqp->maxlen = length;
+        mqp->free   = NULL;
+
+        return;
+}
+
+/** Description of UTF8 information as used by MQTT Library. */
+struct utf8_string {
+        
+        const char *buffer;   /**< Refers to UTF8 content */
+        uint16_t       length;   /**< Length of UTF8 content */
+};
+
+/** Write UTF8 information into the buffer. 
+    The UTF8 information includes content and its length.
+
+    @warning The routine does not check for correctness of the paramters.
+
+    @param[in] buf refers to memory to write UTF8 information into
+    @param[in] utf8 contains UTF8 information to be written
+    @return on success, number of bytes written, otherwise -1 on error.
+*/
+int32_t mqp_buf_wr_utf8(uint8_t *buf, const struct utf8_string *utf8);
+
+/** Write the MQTT construct 'Remaining Length' into trailing end of buffer.
+    The 'remaining length' is written in the format as outlined in the MQTT
+    specification. 
+
+    The implementation assumes availability of at-least 4 bytes in the buffer.
+    Depending on the value of 'Remaining Length' appropriate trailing bytes in
+    the buffer would be used.
+    
+    @param[in] buf refers to memory to tail-write 'Remaining Length' into
+    @param[in] remlen The 'Remaining Length' value
+    @return in success, number of trailing bytes used, otherwise -1 on error
+*/
+int32_t mqp_buf_tail_wr_remlen(uint8_t *buf, uint32_t remlen);
+
+/** Read MQTT construct 'Remaining Length' from leading bytes of the buffer.
+    The 'remaining length' is written in the format as outlined in the MQTT
+    specification.
+     
+    @param[in] buf refers to memory to head-read 'Remaining Length' from
+    @param[in] remlen place-holder for The 'Remaining Length' value
+    @return in success, number of header bytes read, otherwise -1 on error
+*/   
+int32_t mqp_buf_rd_remlen(uint8_t *buf, uint32_t *remlen);
+
+/** Include variable header Topic as part of PUB Message construction.
+    Inclusion of a Topic also encompasses incorporation of the message ID.
+
+    The topic refers to the subject for which data will be published by
+    the client or the server. The topic entity must be appended into the
+    packet buffer prior to the inclusion of the payload (data).
+
+    @warning This routine does not check for correctness of the input
+    parameters.
+
+    @param[in] mqp packet buffer in which topic must be included.
+    @param[in] topic UTF8 information
+    @param[in] msg_id Message or Packet transaction ID
+    @return on success, number of bytes appended, otherwise -1 on error.
+
+    @note A 'topic' must be appended prior to inclusion of pulished data.
+*/
+int32_t 
+mqp_pub_append_topic(struct mqtt_packet *mqp, const struct utf8_string *topic,
+                     uint16_t msg_id);
+
+/** Include payload data for publishing
+    The payload data is associated with a topic.
+    
+    @warning This routine does not check for correctness of the input
+    parameters.
+
+    @param[in] mqp packet buffer in which payload data must be included.
+    @param[in] data_buf data to be included in the packet buffer
+    @param[in] data_len length of the data to be included in the packet.
+    @return on success, number of bytes appended, otherwise -1 on error.
+
+    @note A 'topic' must be appended prior to inclusion of pulished data.
+*/
+int32_t mqp_pub_append_data(struct mqtt_packet *mqp, const uint8_t *data_buf,
+                        uint32_t data_len);
+
+/** Construct a packet for Message ID enabled ACK received from network
+    Process the raw ACK message information to update the packet holder.
+   
+    @warning This routine does not check for correctness of the input
+    parameters.
+       
+    @param[in] mqp_raw holds a raw buffer from the network
+    @param[in] has_payload asserted, if ACK message should have a payload
+    @return on success, true, otherwise false
+*/
+bool mqp_proc_msg_id_ack_rx(struct mqtt_packet *mqp_raw, bool has_payload);
+
+/** Construct a packet for PUBLISH message received from the network
+    Process the raw PUB message information to update the packet holder.
+
+    @warning This routine does not check for correctness of the input
+    parameters.
+
+    @param[in] mqp_raw holds a raw buffer from the network
+    @return on success, true, other wise false
+*/
+bool mqp_proc_pub_rx(struct mqtt_packet *mqp_raw);
+
+/*
+   Wait-List of MQTT Messages for which acknoledge is pending from remote node.
+*/
+struct mqtt_ack_wlist {
+        
+        struct mqtt_packet *head;  /* Points to head of single linked-list. */
+        struct mqtt_packet *tail;  /* Points to tail of single linked-list. */
+};
+
+static inline bool mqp_ack_wlist_is_empty(struct mqtt_ack_wlist *list)
+{
+        return (NULL == list->head) ? true : false;
+}
+
+/*
+   Add specified element into trailing end of list.
+
+   Returns, on success, true, otherwise false.
+*/
+bool mqp_ack_wlist_append(struct mqtt_ack_wlist *list,
+                          struct mqtt_packet    *elem);
+
+/*
+   Removes element that has specified msg_id from list. 
+
+   Returns, on success, pointer to removed element, otherwise NULL.
+*/
+struct mqtt_packet *mqp_ack_wlist_remove(struct mqtt_ack_wlist *list,
+                                          uint16_t msg_id);
+/* 
+   Removes and frees all elements in list. 
+*/
+void mqp_ack_wlist_purge(struct mqtt_ack_wlist *list);
+
+static inline bool is_wlist_empty(const struct mqtt_ack_wlist *list)
+{
+        return list->head? false : true;
+}
+
+/** Prepare the Fixed-Header of the MQTT Packet (before being sent to network)
+    Based on the contents of the mqtt packet and the combination of DUP, QoS
+    and Retain flags as outlined the MQTT specification, the routine updates,
+    among others, significant internal fields such as 'remaining length' and
+    'fixed header length' in the packet construct and embeds the fixed header,
+    so created, in the packet buffer.
+    
+    This service must be utilized on a packet that has been already populated
+    with all the payload data, topics and other contents. The fixed header
+    must be the final step in the compostion of MQTT packet prior to its
+    dispatch to the server.
+    
+    Returns size, in bytes, of the fixed-header, otherwise -1 on error.
+*/
+int32_t mqp_prep_fh(struct mqtt_packet *mqp, uint8_t flags);
+
+/** MQTT Quality of Service */
+enum mqtt_qos {
+        
+        MQTT_QOS0,  /**< QoS Level 0 */
+        MQTT_QOS1,  /**< QoS Level 1 */
+        MQTT_QOS2   /**< QoS Level 2 */
+};
+
+/** Construct to create Topic to SUBSCRIBE */
+struct utf8_strqos {
+
+        const char       *buffer;  /**< Refers to UTF8 content */
+        uint16_t             length;  /**< Length of UTF8 content */
+        enum mqtt_qos   qosreq;  /**< QoS Level  for content */
+};
+
+
+/** @defgroup mqtt_netsec_grp Information to establish a secure connection.
+    This is implementation specific and is targeted for the network services.
+
+    Specifically, the MQTT implementation makes no assumption or use of this
+    construct. The client library merely passes information from the app to
+    the network service layer.
+    Note: value of n_file can vary from 1 to 4, with corresponding pointers to
+    the files in files field. Value of 1(n_file) will assume the corresponding
+    pointer is for CA File Name. Any other value of n_file expects the files to
+    be in following order:
+    1.  Private Key File
+    2.  Certificate File Name
+    3.  CA File Name
+    4.  DH Key File Name
+
+example: 
+If you want to provide only CA File Name, following are the two way of doing it:
+for n_file = 1
+char *security_file_list[] = {"/cert/testcacert.der"};
+for n_file = 4
+char *security_file_list[] = {NULL, NULL, "/cert/testcacert.der", NULL};
+
+where files = security_file_list
+    @{
+*/
+struct secure_conn {
+        
+        void *method;  /**< Reference to information about protocol or methods */
+        void *cipher;  /**< Reference to information about cryptograph ciphers */
+        uint32_t   n_file;  /**< Count of secure connection related files, certs... */
+        char   **files;  /**< Reference to array of file-names used for security */
+};
+
+/** @} */
+
+/* Initialize the struct secure_conn data */
+void secure_conn_struct_init(struct secure_conn *nw_security);
+
+/** @defgroup net_ops_group Abstraction of Network Services on a platform
+    Services to enable the MQTT Client-Server communication over network
+   
+    These services are invoked by the MQTT Library.
+    
+    @{
+*/ 
+struct device_net_services {
+
+       /** @defgroup dev_netconn_opt_grp Options for platform to configure network
+           @{
+        */
+#define DEV_NETCONN_OPT_TCP  0x01  /**< Assert to indicate TCP net connection  */
+#define DEV_NETCONN_OPT_UDP  0x02  /**< Assert to create a local UDP port bind */
+#define DEV_NETCONN_OPT_IP6  0x04  /**< Assert for IPv6, otherwise it is IPv4  */
+#define DEV_NETCONN_OPT_URL  0x08  /**< Assert if the network address is a URL */
+#define DEV_NETCONN_OPT_SEC  0x10  /**< Assert to indicate a secure connection */
+        /** @} */
+
+        /** Set up a communication channel with a server or set up a local port.
+            This routine opens up either a "connection oriented" communication
+            channel with the specified server or set up a local configuration for
+            "connectionless" transactions.
+
+            @param[in] nwconn_opts Implementation specific construct to enumerate
+            server address and / or connection related details
+            @param[in] server_addr URL or IP address (string) or other server
+            reference. For setting up a local (UDP) port, set it to NULL.
+            @param[in] port_number Network port number, typically, 1883 or 8883
+            for remote severs. For setting up a local (UDP) port, use an intended
+            port number.
+            @param[in] nw_security Information to establish a secure connection
+            with server. Set it to NULL, if not used. @ref mqtt_netsec_grp
+            @return a valid handle to connection, otherwise NULL
+        */
+        int32_t (*open)(uint32_t nwconn_opts, const char *server_addr, uint16_t port_number,
+                    const struct secure_conn *nw_security);
+
+        /** Send data onto the "connection oriented" network.
+            The routine blocks till the time, the data has been copied into the
+            network stack for dispatch on to the "connection oriented" network.
+
+            @param[in] comm handle to network connection as returned by open().
+            @param[in] buf refers to the data that is intended to be sent
+            @param[in] len length of the data
+            @param[in] ctx reference to the MQTT connection context
+            @return on success, the number of bytes sent, 0 on connection reset,
+            otherwise -1
+        */
+        int32_t   (*send)(int32_t comm, const uint8_t *buf, uint32_t len, void *ctx);
+
+        /** Receive data from the "connection oriented" channel.
+            The routine blocks till the time, there is either a data that has
+            been received from the server or the time to await data from the
+            server has expired.
+
+            @param[in] comm Handle to network connection as returned by
+            accept().
+            @param[out] buf place-holder to which data from network should be
+            written into.
+            @param[in] len maximum length of 'buf'
+            @param[in] wait_secs maximum time to await data from network. If
+            exceeded, the routine returns error with the err_timeo flag set
+            as true.
+            @param[out] err_timeo if set, indicates that error is due to
+            timeout.
+            @param[in] ctx reference to the MQTT connection context
+            @return on success, number of bytes received, 0 on connection reset,
+            otherwise -1 on error. In case, error (-1) is due to the time-out,
+            then the implementation should set flag err_timeo as true.
+        */
+        int32_t   (*recv)(int32_t comm, uint8_t *buf, uint32_t len, uint32_t wait_secs,
+                      bool *err_timeo, void *ctx);
+
+        /** Send data to particular port on the specified network element.
+            The routine blocks till the time, the data has been copied into the
+            network stack for dispatch to the "specified" network entity.
+
+            @param[in] comm handle to network connection as returned by open().
+            @param[in] buf refers to data that is intended to be sent
+            @param[in] len length of the data
+            @param[in] dest_port network port to which data is to be sent.
+            @param[in] dest_ip IP address of the entity to which data is to be
+            sent.
+            @param[in] ip_len length of the destination IP address.
+            @return on success, the number of bytes sent, 0 on connection reset,
+            otherwise -1.
+        */
+        int32_t   (*send_dest)(int32_t comm, const uint8_t *buf, uint32_t len, uint16_t dest_port,
+                           const uint8_t *dest_ip, uint32_t ip_len);
+
+        /** Receive data on a local port sent by any network element.
+            The routine blocks till the time, data has been received on the local
+            port from any remote network element.
+
+            @param[in] comm handle to network connection as return by open().
+            @param[in] buf place-holder to which data from network should be
+            written into.
+            @param[in] len maximum lengh of 'buf'
+            @param[out] from_port place-holder for the port of the sender network
+            entity
+            @param[out] from_ip place-holder to retrieve the IP address of the
+            sender network entity. The memory space must be provisioned to store
+            atleast 16 bytes.
+            @param[in, out] ip_len length of IP address. It is provided by
+            the caller to declare the length of the place holder and updated by
+            routine to indicate the length of the remote network entity's IP
+            address.
+            @return on success, number of bytes received, 0 on connection reset,
+            otherwise -1 on errir. 
+        */
+        int32_t   (*recv_from)(int32_t comm, uint8_t *buf, uint32_t len, uint16_t *from_port,
+                           uint8_t *from_ip, uint32_t *ip_len);
+
+        /** Close communication connection */
+        int32_t   (*close)(int32_t comm);
+
+        /** Listen to incoming connection from clients.
+            This routine prepares the system to listen on the specified port
+            for the incoming network connections from the remote clients.
+
+            @param[in] nwconn_opts Implementation specific construct to
+            enumerate server address and / or connection related details
+            @param[in] port_number Network port number, typically, 1883 or 8883
+            @param[in] nw_security Information to establish a secure connection
+            with client. Set it to NULL, if not used. @ref mqtt_netsec_grp
+            @return a valid handle to listening contruct, otherwise NULL
+        */
+        int32_t (*listen)(uint32_t nwconn_opts, uint16_t port_number,
+                      const struct secure_conn *nw_security);
+
+        /** Accept an incominng connection.
+            This routine creates a new communication channel for the (remote)
+            requesting client.
+
+            @param[in] listen handle to listen for the incoming connection
+            requests from the remote clients
+            @param[out] client_ip IP address of the connected client. This value
+            is valid only on successful return of the routine. The place holder
+            must provide memory to store atleast 16 bytes.
+            @param[in, out] ip_length Length of IP address. It is provided by
+            the caller to declare the length of the place holder and updated by
+            routine to indicate the length of the connected client's IP address.
+            @return on success, a valid handle to the new connection, otherwise
+            NULL
+        */
+        int32_t (*accept)(int32_t listen, uint8_t *client_ip, uint32_t *ip_length);
+
+        /** Monitor activity on communication handles.
+            The routine blocks for the specified period of time to monitor
+            activity, if any, on each of the communication handle that has
+            been provided in one or more vector sets. At the expiry of the
+            wait time, this function must identify the handles, on which,
+            acitvities were observed.
+
+            A particular collection of communication handles are packed as
+            an array or in a vector and is passed to the routine. A NULL
+            handle in the vector indicates the termination of the vector
+            and can effectively used to account for the size of the vector.
+
+            Similarly, at end the end of the wait period, the routine must
+            provide a vector of the handles for which activity was observed.
+
+            @param[in, out] recv_hvec a vector of handles which must be
+            monitored for receive activities. 
+            @param[in, out] send_hvec a vector of handles which must be
+            monitored for send activities.
+            @param[in, out] rsvd_hvec reserved for future use.
+            @param[in] wait_secs time to wait and monitor activity on
+            communication handles provided in one or more sets. If set 
+            to 0, the routine returns immediately.
+            @return on success, the total number of handles for which activity
+            was observed. This number can be 0, if no activity was observed on
+            any of the provided handle in the specified time. Otherwise, -1 on
+            error.
+        */
+        int32_t   (*io_mon)(int32_t *recv_cvec, int32_t *send_cvec,
+                        int32_t *rsvd_cvec,  uint32_t wait_secs);
+
+        /** Get Time (in seconds).
+            Provides a monotonically incrementing value of a time  service in
+            unit of seconds. The implementation should ensure that associated
+            timer hardware or the clock module remains active through the low
+            power states of the system. Such an arrangement ensures that MQTT
+            Library is able to track the Keep-Alive time across the cycles of
+            low power states. It would be typical of battery operated systems
+            to transition to low power states during the period of inactivity
+            or otherwise to conserve battery. 
+
+            In the absence of a sustained time reference across the low power
+            states, if the system transitions away from the active state, the
+            MQTT Library, then may not be able to effectively monitor the Keep
+            Alive duration.
+
+            It is the responsbililty of the implementation to manage the roll-
+            over problem of the hardware and ensure the integrity of the time
+            value is maintained.
+
+           @return time in seconds
+        */
+        uint32_t   (*time)(void);
+};
+
+/** @} */ /* device_net_services */
+
+/* Receive data from the specified network and read into the 'mqp' */
+int32_t mqp_recv(int32_t  net,     const struct device_net_services *net_ops,
+             struct mqtt_packet *mqp, uint32_t wait_secs, bool *timed_out,
+             void *ctx);
+
+/*-----------------------------------------------------------------------------
+ * Data structure for managing the QoS2 PUB RX packets and follow-ups
+ *---------------------------------------------------------------------------*/
+
+#define MAX_PUBREL_INFLT 8 /* Must be kept as a value of 2^n */
+
+struct pub_qos2_cq { /* Circular Queue CQ to track QOS2 PUB RX messages */
+
+        uint16_t id_vec[MAX_PUBREL_INFLT];  /* Vector to store RX Message-IDs */
+        uint8_t  n_free;                    /* Num of free elements in vector */
+        uint8_t  rd_idx;                    /* Index to Read  next Message-ID */
+        uint8_t  wr_idx;                    /* Index to Write next Message-ID */
+};
+
+/* Reset the specified Circular Queue (CQ) */
+void qos2_pub_cq_reset(struct pub_qos2_cq *cq);
+
+/* Append the message-id into the CQ tail. Return true on success, else false */
+bool qos2_pub_cq_logup(struct pub_qos2_cq *cq, uint16_t msg_id);
+
+/* Remove the message-id from the CQ head. Return true on success, else false */
+bool qos2_pub_cq_unlog(struct pub_qos2_cq *cq, uint16_t msg_id);
+
+/* Is the message-id available in the CQ ? Return true on success, else false */
+bool qos2_pub_cq_check(struct pub_qos2_cq *cq, uint16_t msg_id);
+
+/* Get the count of message-ID(s) availalbe in the CQ */
+static inline int32_t qos2_pub_cq_count(struct pub_qos2_cq *cq)
+{
+        return MAX_PUBREL_INFLT - cq->n_free;
+}
+
+struct client_ctx {
+
+        void        *usr;  /* Client Usr */
+        int32_t          net;  /* Socket HND */
+
+        uint8_t           remote_ip[16];
+        uint32_t          ip_length;
+
+        uint32_t          timeout;
+        uint16_t          ka_secs;
+
+        uint32_t          flags;
+
+        struct client_ctx *next;
+};
+
+void cl_ctx_reset(struct client_ctx *cl_ctx);
+void cl_ctx_timeout_insert(struct client_ctx **head,
+                           struct client_ctx *elem);
+
+void cl_ctx_remove(struct client_ctx **head,
+                   struct client_ctx *elem);
+
+#define KA_TIMEOUT_NONE 0xffffffff  /* Different than KA SECS = 0 */
+void cl_ctx_timeout_update(struct client_ctx *cl_ctx, uint32_t now_secs);
+
+}//namespace mbed_mqtt 
+
+#ifdef __cplusplus  
+}
+#endif 
+
+#endif
+
diff -r 241bff9fe406 -r a8c249046181 mqtt_V1/include/sl_mqtt_client.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mqtt_V1/include/sl_mqtt_client.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,457 @@
+/*******************************************************************************
+Copyright (c) (2014) Texas Instruments Incorporated
+All rights reserved not granted herein.
+
+Limited License.  
+
+Texas Instruments Incorporated grants a world-wide, royalty-free, non-exclusive 
+license under copyrights and patents it now or hereafter owns or controls to make, 
+have made, use, import, offer to sell and sell ("Utilize") this software subject 
+to the terms herein.  With respect to the foregoing patent license, such license 
+is granted  solely to the extent that any such patent is necessary to Utilize the 
+software alone.  The patent license shall not apply to any combinations which 
+include this software, other than combinations with devices manufactured by or 
+for TI (�TI Devices�).  No hardware patent is licensed hereunder.
+
+Redistributions must preserve existing copyright notices and reproduce this license 
+(including the above copyright notice and the disclaimer and (if applicable) source 
+code license limitations below) in the documentation and/or other materials provided 
+with the distribution
+
+Redistribution and use in binary form, without modification, are permitted provided 
+that the following conditions are met:
+* No reverse engineering, decompilation, or disassembly of this software is 
+  permitted with respect to any software provided in binary form.
+* any redistribution and use are licensed by TI for use only with TI Devices.
+* Nothing shall obligate TI to provide you with source code for the software 
+  licensed and provided to you in object code.
+
+If software source code is provided to you, modification and redistribution of the 
+source code are permitted provided that the following conditions are met;
+* any redistribution and use of the source code, including any resulting derivative 
+  works, are licensed by TI for use only with TI Devices.
+* any redistribution and use of any object code compiled from the source code and 
+  any resulting derivative works, are licensed by TI for use only with TI Devices.
+
+Neither the name of Texas Instruments Incorporated nor the names of its suppliers 
+may be used to endorse or promote products derived from this software without 
+specific prior written permission.
+
+DISCLAIMER.
+
+THIS SOFTWARE IS PROVIDED BY TI AND TI�S LICENSORS "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 TI AND TI�S 
+LICENSORS 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 <stdbool.h>
+#include "cc3100_simplelink.h"
+
+#ifndef __SL_MQTT_H__
+#define __SL_MQTT_H__
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+namespace mbed_mqtt {
+
+        /**
+          \mainpage SimpleLink MQTT Client Layer
+          
+          * \section intro_sec Introduction
+
+          The SimpleLink MQTT Client Layer provides an easy-to-use API(s) to enable
+          constrained and deeply embedded microcontroller based products to interact
+          with cloud or network based server for telemetery. The users of SL MQTT
+          Client services, while benefiting from the abstraction of the MQTT protocol
+          would find them suitable for varied deployments of MQTT subscribers and / or
+          publishers.
+
+          The following figure outlines the composition of the SL MQTT Client Layer.
+
+          * \image html ./sl_mqtt_client_view.png
+          
+          * \section descrypt_sec Description
+
+          The SL MQTT Client Layer, in addition to providing services to the application,
+          encompasses a RTOS task to handle the incoming messages from the server. Such
+          a dedicated context to process the messages from the server facilitates the
+          apps to receive data (i.e. PUBLISH messages) even when they are blocked, whilst
+          awaiting ACK for a previous transaction with the server. The receive task in
+          the SL MQTT Layer can not be disabled anytime, however its system wide priority
+          is configurable and can be set.
+
+          Some of the salient features of the SL MQTT Layer are 
+          
+          - Easy-to-use, intuitive and small set of MQTT API
+          - App can indicate its choice to await ACK for a message transaction
+          - Supports MQTT 3.1 protocol
+
+          * \section config_sec Configuration
+          The SL implementation enables the application developers to configure the
+          following parameters using the compile line flags (-D option)
+          * - <b> CFG_SL_CL_MAX_MQP: </b> the count of TX + RX resources in the buffer pool
+	  for the library to use. \n\n
+          * - <b> CFG_SL_CL_BUF_LEN: </b> the length of the TX and RX buffers in the pool. \n\n
+          * - <b> CFG_SL_CL_STACK: </b> Max stack (bytes) for RX Task executed by SL-MQTT. \n\n
+          * - <b> CFG_CL_MQTT_CTXS: </b> the max number of simultaneous network connections
+          to one or more servers. \n\n
+
+          * \section seq_sec Sequence Diagram
+          The following sequence diagram outlines one of the possible usecases
+	  (Blocking APIs with QOS1) using the SL MQTT Client Layer
+          * \image html ./sl_mqtt_client_seq.jpg
+
+          * \note An app that has chosen not to await an ACK from the server for an
+          scheduled transaction can benefit from the availability of control to
+          pursue other activities to make overall progress in the system. However,
+          an attempt to schedule another transaction with the server, while the
+          previous one is still active, will depend on the availability of buffers for transaction.
+          
+
+          \subsection seq_subsec Typical Sequences:
+          
+          - Publishers:  INIT --> CONTEXT_CREATE --> CONNECT --> PUBLISH (TX) --> DISCONNECT --> CONTEXT_DELETE --> EXIT
+          - Subscribers: INIT --> CONTEXT_CREATE --> CONNECT --> SUBSCRIBE --> PUBLISH (RX) --> UNSUBSCRIBE --> DISCONNECT --> CONTEXT_DELETE --> EXIT
+          
+        */
+
+        /** @defgroup sl_mqtt_cl_api SL MQTT Client API
+            @{
+        */
+  
+        /** @defgroup sl_mqtt_cl_evt SL MQTT Client Events
+            @{ 
+        */
+#define SL_MQTT_CL_EVT_PUBACK   0x04  /**< PUBACK has been received from the server */
+#define SL_MQTT_CL_EVT_PUBCOMP  0x07  /**< PUBCOMP has been received from the server */
+#define SL_MQTT_CL_EVT_SUBACK   0x09  /**< SUBACK has been received from the server */
+#define SL_MQTT_CL_EVT_UNSUBACK 0x0B  /**< UNSUBACK has been received from the server */
+        /** @} */ /* End Client events */
+
+
+      /* Define server structure which holds , server address and port number.
+      These values are set by the sl_MqttSet API and retrieved by sl_MqttGet API*/
+
+        /** Callbacks Routines
+            The routines are invoked by SL Implementation onto Client application
+
+            * \note The user applications implement the callbacks that are registered 
+                    with the libraries. While using the MQTT library, invoking the 
+                    core library APIs from a callback should be avoided and 
+                    can lead to lockup scenarios. It is recommended to signal another 
+                    task from the callback routines invoked from the library 
+                    and invoke the core library API calls from that task.
+         */
+        typedef struct {
+                
+                /** Callback routine to receive a PUBLISH from the server.
+                    The client app must provide this routine for the instances where it has
+                    subscribed to certain set of topics from the server. The callback is
+                    invoked in the context of the internal SL Receive Task.
+                    
+                    \param[in] app_hndl application handle returned
+                    \param[in] topstr name of topic published by the server. Not NUL terminated.
+                    \param[in] toplen length of the topic name published by the server.
+                    \param[in] payload refers to payload published by the server.
+                    \param[in] pay_len length of the payload.
+                    \param[in] dup assert to indicate that it is re-send by the server
+                    \param[in] qoS quality of service of the published message
+                    \param[in] retain asserted to indicate that a retained message has been published
+                    \return none.
+                */
+                void (*sl_ExtLib_MqttRecv)(void *app_hndl, const char *topstr, int32_t toplen,
+                                            const void *payload, int32_t pay_len,
+                                            bool dup, unsigned char qos,
+                                            bool retain);
+                
+                /** Indication of event either from the server or implementation generated.
+                    These events are notified as part of the processing carried out by the
+                    internal recv task of the SL implementation. The application must populate
+                    the callback to receive events about the progress made by the SL Mqtt layer.
+                    
+                    This handler is used by the SL Mqtt Layer to report acknowledgements from the
+                    server, in case, the application has chosen not to block the service invokes
+                    till the arrival of the corresponding ACK.
+                    
+                    \param[in] app_hndl application handle returned
+                    \param[in] evt identifier to the reported event. Refer to @ref sl_mqtt_cl_evt
+                    \param[in] buf points to buffer
+                    \param[in] len length of buffer
+                    
+                    \note
+                */
+                void (*sl_ExtLib_MqttEvent)(void *app_hndl, int32_t evt, const void *buf, 
+                                             uint32_t len);
+
+                /** Notifies the client app about the termination of MQTT connection.
+                    After servicing this callback, the client-app can destroy associated
+                    context if it no longer required
+
+                    \param[in] app_hndl application handle returned
+                */
+                void (*sl_ExtLib_MqttDisconn)(void *app_hndl);
+
+                
+        } SlMqttClientCbs_t;
+        
+        typedef struct {
+
+                const char        *will_topic;   /**< Will Topic    */
+                const char        *will_msg;     /**< Will message  */
+                char      will_qos;     /**< Will Qos      */
+                bool               retain;       /**< Retain Flag   */
+                         
+        } SlMqttWill_t;
+        
+         
+        /** Secure Socket Parameters to open a secure connection */
+        /*
+        Note: value of n_files can vary from 1 to 4, with corresponding pointers to
+        the files in files field. Value of 1(n_files) will assume the corresponding
+        pointer is for CA File Name. Any other value of n_files expects the files to
+        be in following order:
+        1.  Private Key File
+        2.  Certificate File Name
+        3.  CA File Name
+        4.  DH Key File Name
+
+        example: 
+        If you want to provide only CA File Name, following are the two way of doing it:
+        for n_files = 1
+        char *security_file_list[] = {"/cert/testcacert.der"};
+        for n_files = 4
+        char *security_file_list[] = {NULL, NULL, "/cert/testcacert.der", NULL};
+
+        where secure_files = security_file_list
+        */
+        typedef struct {
+
+#define SL_MQTT_NETCONN_IP6  0x04  /**< Assert for IPv6 connection, otherwise  IPv4 */
+#define SL_MQTT_NETCONN_URL  0x08  /**< Server address is an URL and not IP address */
+#define SL_MQTT_NETCONN_SEC  0x10  /**< Connection to server  must  be secure (TLS) */
+
+                uint32_t         netconn_flags; /**< Enumerate connection type  */
+                const char          *server_addr;   /**< Server Address: URL or IP  */
+                uint16_t       port_number;   /**< Port number of MQTT server */
+                char        method;        /**< Method to tcp secured socket */
+                uint32_t         cipher;        /**< Cipher to tcp secured socket */
+                uint32_t         n_files;       /**< Number of files for secure transfer */
+                char * const        *secure_files;  /* SL needs 4 files*/
+
+        } SlMqttServer_t;
+
+    
+        /** MQTT Lib structure which holds Initialization Data */
+        typedef struct
+        {
+                /**< Loopback port is used to manage lib internal functioning in case of connections to 
+                     multiple servers simultaneously is desired. */
+                uint16_t  loopback_port;  /**< Loopback port = 0, implies connection to only single server */
+                                                /**< Loopback port != 0, implies connection to multiple servers */
+                uint32_t   rx_tsk_priority;  /**< Priority of the receive task */
+                uint32_t    resp_time;        /**< Reasonable response time (seconds) from server */
+                bool  aux_debug_en;               /**< Assert to indicate additional debug info */
+                int32_t (*dbg_print)(const char *pcFormat, ...); /**< Print debug information */
+
+        } SlMqttClientLibCfg_t;
+
+
+        /** MQTT client context configuration structure */
+        typedef struct
+        {
+                SlMqttServer_t  server_info;      /**< Server information */
+                bool            mqtt_mode31;      /**< Operate LIB in MQTT 3.1 mode; default is 3.1.1. false - default( 3.1.1) & true - 3.1) */
+                bool            blocking_send;    /**< Select the mode of operation for send APIs (PUB, SUB, UNSUB). false - callback, true - blocking */
+
+        } SlMqttClientCtxCfg_t;
+
+        /** Initialize the SL MQTT Implementation.
+            A caller must initialize the MQTT implementation prior to using its services.
+            
+            \param[in] cfg refers to client lib configuration parameters
+            \return Success (0) or Failure (-1)
+        */
+        int32_t sl_ExtLib_MqttClientInit(const SlMqttClientLibCfg_t  *cfg);
+
+        /** Exit the SL MQTT Implementation.
+            
+            \return Success (0) or Failure (-1)
+        */
+        int32_t sl_ExtLib_MqttClientExit();
+
+        /** Create a new client context to connect to a server.
+            A context has to be created prior to invoking the client services.
+
+            \param[in] ctx_cfg refers to client context configuration parameters
+            \param[in] msg_cbs refers to callbacks into application
+            \param[in] app refers to the application callback to be returned on callback
+        */
+        void *sl_ExtLib_MqttClientCtxCreate(const SlMqttClientCtxCfg_t *ctx_cfg,
+                                              const SlMqttClientCbs_t *msg_cbs,
+                                              void *app_hndl);
+
+        /** Deletes the specified client context.
+
+            \param[in] cli_ctx refers to client context to be deleted
+            \return Success (0) or Failure (< 0)
+        */
+        int32_t sl_ExtLib_MqttClientCtxDelete(void *cli_ctx);
+
+        /** @defgroup sl_mqtt_cl_params SL MQTT Oper Paramters
+            @{
+        */
+#define SL_MQTT_PARAM_CLIENT_ID  0x01   /**< Refers to Client ID */
+#define SL_MQTT_PARAM_USER_NAME  0x02   /**< User name of client */
+#define SL_MQTT_PARAM_PASS_WORD  0x03   /**< Pass-word of client */
+#define SL_MQTT_PARAM_TOPIC_QOS1 0x04   /**< Set a QoS1 SUB topic */
+#define SL_MQTT_PARAM_WILL_PARAM 0x05   /**< Set a WILL topic,Will Message, Will QOS,Will Retain */
+          
+          /** @} */
+        
+        /** Set parameters in SL MQTT implementation.
+            The caller must configure these paramters prior to invoking any MQTT
+            transaction.
+            
+            \note The implementation does not copy the contents referred. Therefore,
+            the caller must ensure that contents are persistent in the memory.
+            
+            \param[in] cli_ctx refers to the handle to the client context
+            \param[in] param identifies parameter to set. Refer to @ref sl_mqtt_cl_params
+            \param[in] value refers to the place-holder of value to be set
+            \param[in] len length of the value of the parameter
+            \return Success (0) or Failure (-1)          
+        */
+        int32_t sl_ExtLib_MqttClientSet(void *cli_ctx, int32_t param, const void *value, uint32_t len);
+        
+        /*\brief None defined at the moment
+        */
+        int32_t sl_ExtLib_MqttClientGet(void *cli_ctx, int32_t param, void *value, uint32_t len);
+  
+  
+        /** CONNECT to the server. 
+            This routine establishes a connection with the server for MQTT transactions.
+            The caller should specify a time-period with-in which the implementation
+            should send a message to the server to keep-alive the connection.
+            
+            \param[in] cli_ctx refers to the handle to the client context
+            \param[in] clean assert to make a clean start and purge the previous session
+            \param[in] keep_alive_time the maximum time within which client should send
+            a message to server. The unit of the interval is in seconds.
+            \return on success, variable header of CONNACK message in network byte
+            order. Lowest Byte[Byte0] contains CONNACK Return Code. Byte1 Contains 
+            Session Present Bit.  
+            on failure  returns(-1)
+        */
+        int32_t sl_ExtLib_MqttClientConnect(void *cli_ctx, bool clean, uint16_t keep_alive_time);
+        
+        /** DISCONNECT from the server.
+            The caller must use this service to close the connection with the 
+            server.
+
+            \param[in] cli_ctx refers to the handle to the client context
+         
+            \return Success (0) or Failure (< 0)
+        */
+        int32_t sl_ExtLib_MqttClientDisconnect(void *cli_ctx);
+        
+
+        /** SUBSCRIBE a set of topics.
+            To receive data about a set of topics from the server, the app through
+            this routine must subscribe to those topic names with the server. The
+            caller can indicate whether the routine should block until a time, the
+            message has been acknowledged by the server.
+
+            In case, the app has chosen not to await for the ACK from the server, 
+            the SL MQTT implementation will notify the app about the subscription
+            through the callback routine.
+            
+            \param[in] cli_ctx refers to the handle to the client context
+            \param[in] topics set of topic names to subscribe. It is an array of
+            pointers to NUL terminated strings.
+            \param[in,out] qos array of qos values for each topic in the same order
+            of the topic array. If configured to await for SUB-ACK from server, the
+            array will contain qos responses for topics from the server.
+            \param[in] count number of such topics
+  
+            \return Success(transaction Message ID) or Failure(< 0)
+        */
+        int32_t sl_ExtLib_MqttClientSub(void *cli_ctx, char* const *topics,
+                                    uint8_t *qos, int32_t count);
+
+        
+        /** UNSUBSCRIBE a set of topics.
+            The app should use this service to stop receiving data for the named
+            topics from the server. The caller can indicate whether the routine
+            should block until a time, the message has been acknowleged by the
+            server.
+
+            In case, the app has chosen not to await for the ACK from the server, 
+            the SL MQTT implementation will notify the app about the subscription
+            through the callback routine.
+            
+            \param[in] cli_ctx refers to the handle to the client context
+            \param[in] topics set of topics to be unsubscribed. It is an array of
+            pointers to NUL terminated strings.
+            \param[in] count number of topics to be unsubscribed
+
+            \return Success(transaction Message ID) or Failure(< 0) 
+        */
+        int32_t sl_ExtLib_MqttClientUnsub(void *cli_ctx, char* const *topics, int32_t count);
+        
+        
+        /** PUBLISH a named message to the server.
+            In addition to the PUBLISH specific parameters, the caller can indicate
+            whether the routine should block until the time, the message has been
+            acknowleged by the server. This is applicable only for non-QoS0 messages.
+            
+            In case, the app has chosen not to await for the ACK from the server, 
+            the SL MQTT implementation will notify the app about the subscription
+            through the callback routine.
+
+            \param[in] cli_ctx refers to the handle to the client context
+            \param[in] topic  topic of the data to be published. It is NULL terminated.
+            \param[in] data   binary data to be published
+            \param[in] len    length of the data
+            \param[in] qos    QoS for the publish message 
+            \param[in] retain assert if server should retain the message
+            \param[in] flags Command flag. Refer to @ref sl_mqtt_cl_cmdflags
+            \return Success(transaction Message ID) or Failure(< 0)
+        */
+        int32_t sl_ExtLib_MqttClientSend(void *cli_ctx, const char *topic,
+                                      const void *data, int32_t len, 
+                                      char qos, bool retain);
+        
+        /** PUBLISH a named message to the server - wrapper function.
+        */
+        static inline int32_t sl_ExtLib_MqttClientPub(void *cli_ctx, const char *topic,
+                                      const void *data, int32_t len,
+                                      char qos, bool retain)
+        {
+                return sl_ExtLib_MqttClientSend(cli_ctx, topic, data, len,
+                                          qos, retain);
+        }
+
+        /** @} */ /* End Client API */
+        
+}//namespace mbed_mqtt        
+
+#ifdef __cplusplus  
+}
+#endif  
+
+
+
+#endif // __SL_MQTT_H__
+
diff -r 241bff9fe406 -r a8c249046181 mqtt_V1/include/sl_mqtt_server.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mqtt_V1/include/sl_mqtt_server.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,317 @@
+/*******************************************************************************
+Copyright (c) (2014) Texas Instruments Incorporated
+All rights reserved not granted herein.
+
+Limited License.  
+
+Texas Instruments Incorporated grants a world-wide, royalty-free, non-exclusive 
+license under copyrights and patents it now or hereafter owns or controls to make, 
+have made, use, import, offer to sell and sell ("Utilize") this software subject 
+to the terms herein.  With respect to the foregoing patent license, such license 
+is granted  solely to the extent that any such patent is necessary to Utilize the 
+software alone.  The patent license shall not apply to any combinations which 
+include this software, other than combinations with devices manufactured by or 
+for TI (�TI Devices�).  No hardware patent is licensed hereunder.
+
+Redistributions must preserve existing copyright notices and reproduce this license 
+(including the above copyright notice and the disclaimer and (if applicable) source 
+code license limitations below) in the documentation and/or other materials provided 
+with the distribution
+
+Redistribution and use in binary form, without modification, are permitted provided 
+that the following conditions are met:
+* No reverse engineering, decompilation, or disassembly of this software is 
+  permitted with respect to any software provided in binary form.
+* any redistribution and use are licensed by TI for use only with TI Devices.
+* Nothing shall obligate TI to provide you with source code for the software 
+  licensed and provided to you in object code.
+
+If software source code is provided to you, modification and redistribution of the 
+source code are permitted provided that the following conditions are met;
+* any redistribution and use of the source code, including any resulting derivative 
+  works, are licensed by TI for use only with TI Devices.
+* any redistribution and use of any object code compiled from the source code and 
+  any resulting derivative works, are licensed by TI for use only with TI Devices.
+
+Neither the name of Texas Instruments Incorporated nor the names of its suppliers 
+may be used to endorse or promote products derived from this software without 
+specific prior written permission.
+
+DISCLAIMER.
+
+THIS SOFTWARE IS PROVIDED BY TI AND TI�S LICENSORS "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 TI AND TI�S 
+LICENSORS 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 <stdbool.h>
+#include "cc3100_simplelink.h"
+
+#ifndef __SL_MQTT_SRVR_H__
+#define __SL_MQTT_SRVR_H__
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+namespace mbed_mqtt {
+
+        /*!
+          \mainpage SimpleLink MQTT Server Layer
+          
+          \section intro_sec Introduction
+
+          The SimpleLink MQTT Server Layer provides an easy-to-use API(s) to enable
+          constrained and deeply embedded microcontroller based products to interact
+          with cloud or network based clients for telemetry. The users of SL MQTT
+          server services, while benefiting from the abstraction of the MQTT protocol
+          would find them suitable for development of MQTT Servers.
+
+                   
+          \section descrypt_sec Description
+
+          The SL MQTT Server Layer, in addition to providing services to the server
+          application, encompasses an RTOS task to handle the incoming messages from the
+          various clients conencted to the server.
+          Such a dedicated context to process the messages from the clients facilitates the
+          app to receive data (for ex. PUBLISH messages) even when it is 
+          transacting with another client. This is important considering that a server 
+          application has to manage messages from multiple clients connected
+          to it simulatneously.
+          The receive task in the SL MQTT Server Layer can not be disabled anytime, 
+          however its system wide priority is configurable and can be set.
+
+          Some of the salient features of the SL MQTT Layer are 
+          
+          - Easy-to-use, intuitive and small set of MQTT API
+          - App can indicate its choice to await ACK for a message transaction
+
+          \section config_sec Configurations
+          The SL implementation enables the application developers to configure the
+	  following parameters using the compile line flags (-D option):
+          - <b> CFG_SR_MAX_MQP_RX_LEN</b> max length of the RX buffer for the server.
+          - <b> CFG_SR_MAX_MQP_TX_LEN: </b> the constant buffer length allocated for a TX.\n\n
+          - <b> CFG_SR_MAX_SUBTOP_LEN: </b> the maximum buffer size to hold a sub-topic.
+          For e.g., in the topic /x/y/z, the phrase /x, /y and z are sub-topics. \n\n
+          - <b> CFG_SR_MAX_TOPIC_NODE: </b> the maximum number of topic nodes in server.
+          For e.g., in the topic /x/y/z, there are three nodes (/x, /y and z). \n\n
+          - <b> CFG_SR_MAX_CL_ID_SIZE: </b> the maximum length of the client-id string. \n\n
+          - <b> CFG_SR_MAX_NUM_CLIENT: </b> the maximum number of clients to be managed.
+          Note this is different from the maximum number of 'contexts'. A large number
+          of clients can be managed using fewer number of 'contexts' (connections). \n\n
+
+          \note An app that has chosen not to await an ACK from the client for a
+          scheduled transaction can benefit from the availability of control to
+          pursue other activities to make overall progress in the system. However,
+          an attempt to schedule another transaction with the client, while the
+          previous one is still active, will cause the application to block. The
+          app will unblock, once the previous transaction is completed.         
+
+        */
+
+        /** @defgroup sl_mqtt_srvr_api SL MQTT Server APIs
+            @{
+        */
+  
+        /** @defgroup sl_mqtt_srvr_evt SL MQTT Server Events
+            @{ 
+        */
+#define SL_MQTT_SRVR_EVT_PUBACK   0x11  /**< PUBACK has been received from a client */
+#define SL_MQTT_SRVR_EVT_NOCONN   0x12  /**< Server has lost network connection with a client */
+        /** @} */ /* End SL MQTT Server events */
+        
+           
+        /** Callbacks Routines
+            The routines are invoked by SL MQTT Server Implementation onto Server application
+
+            * \note The user applications implement the callbacks that are registered 
+                    with the libraries. While using the MQTT library, invoking the 
+                    core library APIs from a callback should be avoided and 
+                    can lead to lockup scenarios. It is recommended to signal another 
+                    task from the callback routines invoked from the library 
+                    and invoke the core library API calls from that task.
+         */
+        typedef struct {
+                
+                /** Connect Request: Callback routine to indicate to server application that a CONNECT 
+                request has been received by the server.
+                                        
+                    \param[in] clientId_str clientId field in the CONNECT message received.
+                    \param[in] clientId_len length of ClientId
+                    \param[in] username_str Username field in teh CONNECT message received.
+                    \param[in] username_len length of username
+                    \param[in] password_str Password field in the CONNECT message received.
+                    \param[in] password_len length of password
+                    \param[out] usr placeholder to provision app's handle to this connection.
+                    \return 0x0000 or 0x0100 for success; Otherwise 0x02, 0x04 or 0x05 
+                    refer to spec for connack codes
+                    
+                */
+                uint8_t  (*sl_ExtLib_MqttConn)(const char *clientId_str, int32_t clientId_len,
+                                            const char *username_str, int32_t username_len,
+                                            const char *password_str, int32_t password_len,
+                                            void **usr);
+
+                                      
+                /** Callback routine to receive a PUBLISH from a client.
+                    The server app must provide this routine for the instances where it 
+                    receives PUBLISH messages from clients. The callback is
+                    invoked in the context of the internal SL MQTT server Receive Task.
+                    
+                    \param[in] topstr name of topic on which PUBLISH is received by the server. Not NULL terminated.
+                    \param[in] toplen length of the topic name 
+                    \param[in] payload refers to payload published by the server.
+                    \param[in] pay_len length of the payload.
+                    \param[in] dup assert to indicate that it is a duplicate message sent by the client
+                    \param[in] qoS quality of service of the received published message.
+                    \param[in] retain asserted to indicate that a retained message has been received
+                    \return none.
+                */
+                void (*sl_ExtLib_MqttRecv)(const char *topstr,   int32_t toplen,
+                                            const void *payload, int32_t pay_len,
+                                            bool dup, uint8_t qos,
+                                            bool retain);
+
+                // Note: Double check whether retain, dup, qos would be required for a server app (with no topic management)
+
+                /** DISCONNECT: Callback routine to indicate to the Server Application
+                    that a client has disconnected.
+                
+                    \param[in] usr app's handle to this connection.
+                    \param[in] due2err set to 1, if connection has been closed, without server
+                    receiving a DISCONNECT messsage.
+                    \return none.
+                */
+                void (*sl_ExtLib_MqttDisconn)(void *usr, bool due2err);
+
+                
+                /** Indication of event either from the server library or implementation generated.
+                    TBD - Reserved for future use.
+                    
+                    \param[in] usr app's handle to this connection.
+                    \param[in] evt identifier to the reported event. Refer to @ref sl_mqtt_srvr_evt - TBD
+                    \param[in] buf points to buffer
+                    \param[in] len length of buffer   
+                    \return none.             
+                */
+                void (*sl_ExtLib_MqttEvent)(void *usr, int32_t evt, const void *buf, uint32_t len);
+                
+        } SlMqttServerCbs_t;
+
+        /** Secure Socket Parameters to open a secure connection */
+        typedef struct {
+
+                #define SL_MQTT_SRVR_NETCONN_IP6  0x01  /**< Assert for IPv6 connection, otherwise  IPv4 */
+                #define SL_MQTT_SRVR_NETCONN_URL  0x02  /**< Server address is an URL and not IP address */
+                #define SL_MQTT_SRVR_NETCONN_SEC  0x04  /**< Connection to server  must  be secure (TLS) */
+
+                uint32_t         netconn_flags; /**< Enumerate connection type  */
+                const char          *server_addr;   /**< Server Address: URL or IP  */
+                uint8_t       port_number;   /**< Port number of MQTT server */
+                uint8_t        method;        /**< Method to tcp secured socket */
+                uint32_t         cipher;        /**< Cipher to tcp secured socket */
+                uint32_t         n_files;       /**< Number of files for secure transfer */
+                char * const        *secure_files; /*SL needs 4 files*/
+                
+        } SlMqttServerParams_t;
+        
+
+        /** MQTT Server Lib structure which holds Initialization Data */
+        typedef struct
+        {
+                SlMqttServerParams_t  server_info;      /**< Server information */
+                uint8_t  loopback_port;    /**< Loopback port to manage lib internal functioning - Mandatory */
+                uint32_t   rx_tsk_priority;  /**< Priority of the receive task in server */
+                uint32_t    resp_time;        /**< Reasonable response wait time (seconds) for server */                
+                bool aux_debug_en;  /**< Assert to indicate additional debug info */
+                int32_t (*dbg_print)(const char *pcFormat, ...); /**< Print debug information */
+        } SlMqttServerCfg_t;
+    
+        /** Initialize the SL MQTT Server Implementation.
+            A caller must initialize the MQTT Server implementation prior to using its services.
+            
+            \param[in] cfg refers to configuration parameters
+            \param[in] cbs callbacks into server application 
+            \return Success (0) or Failure (-1)
+        */
+        int32_t sl_ExtLib_MqttServerInit(const SlMqttServerCfg_t *cfg,
+                                       const SlMqttServerCbs_t *cbs);
+
+        /** Enroll a topic to receive data
+            App can enroll a topic of interest and the SL layer will forward to the app any
+            data subsequently published for the enrolled topic to the server by any of the
+            connected MQTT clients.
+ 
+            This is analogous or similar to a subsription to a topic by an MQTT client.
+            
+            \param[in] topic  enrollment topic for data to be received. It is NULL terminated.
+            \return Success(0) or Failure (-1).
+        */
+        int32_t sl_ExtLib_MqttTopicEnroll(const char *topic);
+
+        static inline int32_t sl_ExtLib_MqttTopicSub(const char *topic)
+        {
+                return sl_ExtLib_MqttTopicEnroll(topic);
+        }
+        
+        /** DisEnroll a topic.
+            App can cancel the previous enrollment of a topic and the SL layer will now stop
+            forwarding data published for that topic to the server by the connected clients. 
+            This is analogous oe similar to an unsubsription by an MQTT client.
+            
+            \param[in] topic  disenrollment topic. It is NULL terminated.
+            \return Success(0) or Failure(-1).
+        */
+        int32_t sl_ExtLib_MqttTopicDisenroll(const char *topic);
+
+        static inline int32_t sl_ExtLib_MqttTopicUnsub(const char *topic)
+        {
+                return sl_ExtLib_MqttTopicDisenroll(topic);
+        }
+
+        /** PUBLISH a named message to a client.
+            In addition to the PUBLISH specific parameters, the caller can indicate
+            whether the routine should block until the time, the message has been
+            acknowleged by the client. This is applicable only for non-QoS0 messages.
+
+            In case, the app has chosen not to await for the ACK from the client, 
+            the SL MQTT Server implementation will notify the app about the received ACK
+            through the callback routine.
+
+            \note Only QoS0 and QoS1 messages are supported.
+
+            \param[in] topic  topic of the data to be published. It is NULL terminated.
+            \param[in] data   binary data to be published
+            \param[in] len    length of the data
+            \param[in] qos    QoS for the publish message
+            \param[in] retain Retain bit in the PUBLISH message sent out
+            \param[in] flags  Reserved for future use.
+            \return Success(0) or Failure(-1).
+        */
+        int32_t sl_ExtLib_MqttServerSend(const char *topic, const void *data, int32_t len,
+                                       uint8_t qos, bool retain, uint32_t flags);
+
+        /** @} */ /* End SL MQTT Server API */
+        
+}//namespace mbed_mqtt         
+
+#ifdef __cplusplus  
+}
+#endif  
+
+
+
+#endif // __SL_MQTT_SRVR_H__
+
+
+
diff -r 241bff9fe406 -r a8c249046181 mqtt_V1/platform/cc31xx_sl_net.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mqtt_V1/platform/cc31xx_sl_net.cpp	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,661 @@
+/******************************************************************************
+ *
+ *   Copyright (C) 2014 Texas Instruments Incorporated
+ *
+ *   All rights reserved. Property of Texas Instruments Incorporated.
+ *   Restricted rights to use, duplicate or disclose this code are
+ *   granted through contract.
+ *
+ *   The program may not be used without the written permission of
+ *   Texas Instruments Incorporated or against the terms and conditions
+ *   stipulated in the agreement under which this program has been supplied,
+ *   and under no circumstances can it be used with non-TI connectivity device.
+ *
+ ******************************************************************************/
+//#include "mbed.h"
+#include "cc3100_simplelink.h"
+#include "cc3100_sl_common.h"
+#include "cc31xx_sl_net.h"
+#include "sl_mqtt_client.h"
+#include "mqtt_client.h"
+#include "cc3200_platform.h"
+#include "cc3100.h"
+#include "fPtr_func.h"
+#include "myBoardInit.h"
+#include "cli_uart.h"
+
+#define PRINT_BUF_LEN    128
+extern int8_t print_buf[PRINT_BUF_LEN];
+
+using namespace mbed_cc3100;
+
+#if (THIS_BOARD == MBED_BOARD_LPC1768)
+cc3100 _cc3100_module_(p16, p17, p9, p10, p8, SPI(p5, p6, p7));//LPC1768  irq, nHib, cs, mosi, miso, sck
+//cc3100 _cc3100_module_(p9, p10, p8, SPI(p11, p12, p13));//LPC1768  irq, nHib, cs, mosi, miso, sck
+#elif (THIS_BOARD == Seeed_Arch_Max)
+class cc3100 _cc3100_module_(PE_5, PE_4, PE_6, SPI(PB_5, PB_4, PB_3));
+#elif (THIS_BOARD == ST_MBED_NUCLEOF103)
+class cc3100 _cc3100_module_(PA_9, PC_7, PB_6, SPI(PA_7, PA_6, PA_5));//nucleoF103  irq, nHib, cs, mosi, miso, sck
+#elif (THIS_BOARD == ST_MBED_NUCLEOF411)
+class cc3100 _cc3100_module_(PA_9, PC_7, PB_6, SPI(PA_7, PA_6, PA_5));//nucleoF411  irq, nHib, cs, mosi, miso, sck
+#elif (THIS_BOARD == ST_MBED_NUCLEOF401)
+class cc3100 _cc3100_module_(PA_8, PA_9, PC_7, PB_6, SPI(PA_7, PA_6, PA_5));//nucleoF401  irq, nHib, cs, mosi, miso, sck
+#elif (THIS_BOARD == EA_MBED_LPC4088)
+class cc3100 _cc3100_module_(p14, p15, p9, p10, p8, SPI(p5, p6, p7));//LPC4088  irq, nHib, cs, mosi, miso, sck
+#elif (THIS_BOARD == LPCXpresso4337)
+class cc3100 _cc3100_module_(P2_12, P2_9, P2_2, P3_5, P1_2, SPI(P1_4, P1_3, PF_4));//LPCXpresso4337  irq, nHib, cs, mosi, miso, sck
+#endif
+
+namespace mbed_mqtt {
+
+#ifdef DEBUG_NET_DEV
+extern int32_t (*debug_printf)(const char *fmt, ...);
+#define PRINTF(x,...)    debug_printf(x,##__VA_ARGS__)
+#else
+#define PRINTF(x,...)
+#endif
+/*
+ 3200 Devices specific Network Services Implementation
+ */
+
+#define LISTEN_QUE_SIZE 2
+
+//*****************************************************************************
+//                      GLOBAL VARIABLES
+//*****************************************************************************
+
+//*****************************************************************************
+//                      STATIC FUNCTIONS
+//*****************************************************************************
+
+#ifdef DEBUG_NET_DEV
+static int32_t buf_printf(const uint8_t *buf, uint32_t len, uint32_t idt)
+{
+    int32_t i = 0;
+    for(i = 0; i < len; i++)
+    {
+        memset(print_buf, 0x00, PRINT_BUF_LEN);
+        sprintf((char*) print_buf, "%02x ", *buf++);
+        Uart_Write((uint8_t *) print_buf);
+
+        if(0x03 == (i & 0x03))
+        Uart_Write((uint8_t *)" ");
+
+        if(0x0F == (i & 0x0F))
+        {
+            int32_t j = 0;
+            Uart_Write((uint8_t *)"\n\r");
+
+            for(j = 0; j < idt; j++)
+            Uart_Write((uint8_t *)" ");
+        }
+    }
+
+    Uart_Write((uint8_t *)"\n\r");
+
+    return len;
+}
+#endif
+
+/*-----------------------------------------------------------------------------
+ Open a TCP socket and modify its properties i.e security options if req.
+ Socket properties modified in this function are based on the options set
+ outside the scope of this function.
+ Returns a valid handle on success, otherwise a negative number.
+ -----------------------------------------------------------------------------*/
+
+static int32_t create_socket(uint32_t nwconn_opts, struct secure_conn *nw_security_opts)
+{
+
+    int32_t MqttSocketFd, Status;
+
+    //local variables for creating secure socket
+    uint8_t SecurityMethod;
+    uint32_t SecurityCypher;
+    int8_t i;
+
+    //If TLS is required
+    if ((nwconn_opts & DEV_NETCONN_OPT_SEC) != 0) // bit was set to 1
+            {
+        MqttSocketFd = _cc3100_module_._socket.sl_Socket(SL_AF_INET, SL_SOCK_STREAM, SL_SEC_SOCKET);
+        if (MqttSocketFd < 0) {
+            memset(print_buf, 0x00, PRINT_BUF_LEN);
+            sprintf((char*) print_buf, "MqttSocketFd  fail %i\r\n",MqttSocketFd);
+            Uart_Write((uint8_t *) print_buf);
+            return (MqttSocketFd);
+        }
+
+        SecurityMethod = *((uint8_t *) (nw_security_opts->method));
+        SecurityCypher = *((uint32_t *) (nw_security_opts->cipher));
+
+        if (nw_security_opts->n_file < 1  || nw_security_opts->n_file > 4 ) {
+            Uart_Write((uint8_t*)"\n\r ERROR: security files missing or wrong number of security files\n\r");
+            Uart_Write((uint8_t*)"\n\r ERROR: Did not create socket\n\r");
+            return (-1);
+        }
+
+        //Set Socket Options that were just defined
+        Status = _cc3100_module_._socket.sl_SetSockOpt(MqttSocketFd, SL_SOL_SOCKET, SL_SO_SECMETHOD,
+                &SecurityMethod, sizeof(SecurityMethod));
+        if (Status < 0) {
+            memset(print_buf, 0x00, PRINT_BUF_LEN);
+            sprintf((char*) print_buf, "Status error %i socket closed\n\r",Status);
+            Uart_Write((uint8_t *) print_buf);
+            _cc3100_module_._socket.sl_Close(MqttSocketFd);
+            return (Status);
+        }
+
+        Status = _cc3100_module_._socket.sl_SetSockOpt(MqttSocketFd, SL_SOL_SOCKET, SL_SO_SECURE_MASK,
+                &SecurityCypher, sizeof(SecurityCypher));
+        if (Status < 0) {
+            memset(print_buf, 0x00, PRINT_BUF_LEN);
+            sprintf((char*) print_buf, "Status error %i socket closed\n\r",Status);
+            Uart_Write((uint8_t *) print_buf);
+            _cc3100_module_._socket.sl_Close(MqttSocketFd);
+            return (Status);
+        }
+
+        if(nw_security_opts->n_file == 1){
+        	Status = _cc3100_module_._socket.sl_SetSockOpt(MqttSocketFd, SL_SOL_SOCKET, SL_SO_SECURE_FILES_CA_FILE_NAME,
+        			 nw_security_opts->files[0], strlen(nw_security_opts->files[0]));
+        	if (Status < 0) {
+        		memset(print_buf, 0x00, PRINT_BUF_LEN);
+                sprintf((char*) print_buf, "Status error %i socket closed\n\r",Status);
+                Uart_Write((uint8_t *) print_buf);
+				_cc3100_module_._socket.sl_Close(MqttSocketFd);
+				return (Status);
+			}
+        }else{
+        	for(i=0; i<nw_security_opts->n_file;i++){
+        		if(NULL != nw_security_opts->files[i]){
+        			Status = _cc3100_module_._socket.sl_SetSockOpt(MqttSocketFd, SL_SOL_SOCKET,
+        					(SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME+i),
+        			        nw_security_opts->files[i],
+        			        strlen(nw_security_opts->files[i]));
+        			if (Status < 0) {
+        				memset(print_buf, 0x00, PRINT_BUF_LEN);
+                        sprintf((char*) print_buf, "Status error %i socket closed\n\r",Status);
+                        Uart_Write((uint8_t *) print_buf);
+						_cc3100_module_._socket.sl_Close(MqttSocketFd);
+						return (Status);
+					}
+        		}
+        	}
+        }
+
+    }
+    // If no TLS required
+    else {
+        // check to create a udp or tcp socket
+        if ((nwconn_opts & DEV_NETCONN_OPT_UDP) != 0) // bit is set ; create a udp socket
+                {
+            MqttSocketFd = _cc3100_module_._socket.sl_Socket(SL_AF_INET, SL_SOCK_DGRAM, SL_IPPROTO_UDP);
+        } else // socket for tcp
+        {
+            MqttSocketFd = _cc3100_module_._socket.sl_Socket(SL_AF_INET, SL_SOCK_STREAM,
+            SL_IPPROTO_TCP); // consider putting 0 in place of SL_IPPROTO_TCP
+        }
+    }
+    
+    return (MqttSocketFd);
+
+} // end of function
+
+/*-----------------------------------------------------------------------------
+ This function takes an ipv4 address in dot format i.e "a.b.c.d" and returns the
+ ip address in Network byte Order, which can be used in connect call
+ It returns 0, if a valid ip address is not detected.
+ -----------------------------------------------------------------------------*/
+
+static uint32_t svr_addr_NB_order_IPV4(char *svr_addr_str)
+{
+    uint8_t addr[4];
+    int8_t i = 0;
+    char *token;
+    uint32_t svr_addr;
+    int32_t temp;
+
+    /*take a temporary copy of the string. strtok modifies the input string*/
+    int8_t svr_addr_size = strlen(svr_addr_str);
+    char *svr_addr_cpy = (char*)malloc(svr_addr_size + 1); //1 for null
+	if(NULL == svr_addr_cpy) return 0;
+    strcpy(svr_addr_cpy, svr_addr_str);
+
+    memset(print_buf, 0x00, PRINT_BUF_LEN);
+    sprintf((char*) print_buf, "\n\r server address = %s\n\r", svr_addr_cpy);
+    Uart_Write((uint8_t *) print_buf);
+    memset(print_buf, 0x00, PRINT_BUF_LEN);
+    sprintf((char*) print_buf, "\n\r server address string length = %d\n\r", strlen(svr_addr_cpy));
+    Uart_Write((uint8_t *) print_buf);
+
+    /* get the first token */
+    token = strtok((char*)svr_addr_cpy, ".");
+
+    /* walk through other tokens */
+    while (token != NULL) {
+        temp = atoi((const char*)token);
+
+        //check for invalid tokens or if already 4 tokens were obtained
+        if ((temp < 0) || (temp > 255) || (i >= 4)) {
+            free(svr_addr_cpy);
+            return (0);
+        }
+
+        addr[i++] = (uint8_t) temp;
+        token = strtok(NULL, ".");
+    }
+
+    // check if exactly 4 valid tokens are available or not
+    if (i != 4) {
+        free(svr_addr_cpy);
+        return (0);
+    }
+
+    //form address if above test passed
+    svr_addr = *((uint32_t *) &addr);
+    free(svr_addr_cpy);
+
+    return (svr_addr);
+
+} // end of function
+
+//*****************************************************************************
+//                      Network Services functions
+//*****************************************************************************
+
+/*-----------------------------------------------------------------------------
+ Open a TCP socket with required properties
+ Also connect to the server.
+ Returns a valid handle on success, NULL on failure.
+ -----------------------------------------------------------------------------*/
+
+int32_t comm_open(uint32_t nwconn_opts, const char *server_addr, uint16_t port_number,
+        const struct secure_conn *nw_security)
+{
+
+    int32_t Status, MqttSocketFd;
+
+    SlSockAddrIn_t LocalAddr; //address of the server to connect to
+    int32_t LocalAddrSize;
+
+    uint32_t uiIP;
+
+    // create socket
+    MqttSocketFd = create_socket(nwconn_opts,
+            (struct secure_conn*) nw_security);
+
+    if (MqttSocketFd < 0) {
+        Uart_Write((uint8_t*)"\n\r ERROR: Could not create a socket.\n\r");
+        return -1;
+    }
+
+    if ((nwconn_opts & DEV_NETCONN_OPT_UDP) != 0) // bit is set ; create a udp socket
+            {
+        //filling the UDP server socket address
+        LocalAddr.sin_family = SL_AF_INET;
+        LocalAddr.sin_port = _cc3100_module_._socket.sl_Htons((unsigned short) port_number);
+        LocalAddr.sin_addr.s_addr = 0;
+        LocalAddrSize = sizeof(SlSockAddrIn_t);
+
+        Status = _cc3100_module_._socket.sl_Bind(MqttSocketFd, (SlSockAddr_t *) &LocalAddr,
+                LocalAddrSize);
+        if (Status < 0) {
+            // error
+            Uart_Write((uint8_t*)"\n\r ERROR: Could not bind socket.\n\r");
+            _cc3100_module_._socket.sl_Close(MqttSocketFd);
+            return -1;
+        }
+    } else // do tcp connection
+    {
+        // get the ip address of server to do tcp connect
+        if ((nwconn_opts & DEV_NETCONN_OPT_URL) != 0) // server address is a URL
+                {
+            Status = _cc3100_module_._netapp.sl_NetAppDnsGetHostByName((uint8_t*) server_addr,
+                    strlen(server_addr), (uint32_t*) &uiIP, SL_AF_INET);
+
+            if (Status < 0) {
+                Uart_Write((uint8_t*)"\n\r ERROR: Could not resolve the ip address of the server \n\r");
+                return (-1);
+            }
+            // convert the address to network byte order as the function returns in host byte order
+            uiIP = _cc3100_module_._socket.sl_Htonl(uiIP);
+        } else // server address is a string in dot notation
+        {
+            if ((nwconn_opts & DEV_NETCONN_OPT_IP6) != 0) // server address is an IPV6 address string
+                    {
+                Uart_Write((uint8_t*)"\n\r ERROR: Currently do not support IPV6 addresses \n\r");
+                return (-1);
+            } else // address is an IPv4 string
+            {
+                // get the server ip address in Network Byte order
+                uiIP = svr_addr_NB_order_IPV4((char*) server_addr);
+                if (0 == uiIP) {
+                    Uart_Write((uint8_t*)"\n\r ERROR: Could not resolve the ip address of the server \n\r");
+                    return (-1);
+                }
+            }
+
+        }
+
+        LocalAddr.sin_family = SL_AF_INET;
+        LocalAddr.sin_addr.s_addr = uiIP;
+        LocalAddr.sin_port = _cc3100_module_._socket.sl_Htons(port_number);
+        LocalAddrSize = sizeof(SlSockAddrIn_t);
+
+        // do tcp connect
+        Status = _cc3100_module_._socket.sl_Connect(MqttSocketFd, (SlSockAddr_t *) &LocalAddr,
+                LocalAddrSize);
+
+        if (Status < 0) {
+            if (SL_ESECSNOVERIFY != Status) {
+                Uart_Write((uint8_t*)" \n\r ERROR: Could not establish connection to server.\n\r");Uart_Write((uint8_t*)" \n\r ERROR: Closing the socket.\n\r");
+
+                _cc3100_module_._socket.sl_Close(MqttSocketFd);
+                return (-1);
+            } else // SL_ESECSNOVERIFY == Status
+            {
+                Uart_Write((uint8_t*)" \n\r ERROR: Could not establish secure connection to server.\n\r");Uart_Write((uint8_t*)" \n\r Continuing with unsecure connection to server...\n\r");
+            }
+        }
+
+        // Success
+        Uart_Write((uint8_t*)"\n\r Connected to server ....\n\r");
+
+    } // end of doing binding port to udp socket or doing tcp connect
+
+    // set Timer for host processor
+    platform_timer_init();
+    
+    return (MqttSocketFd);
+
+} // end of function
+
+int32_t tcp_send(int32_t comm, const uint8_t *buf, uint32_t len, void *ctx)
+{
+
+    int32_t Status;
+
+    PRINTF("\n\r TCP send invoked for data with len %d\n\r", len);PRINTF("\n\r Sent Data : ");
+
+#ifdef DEBUG_NET_DEV
+    buf_printf(buf, len, 0);
+#endif
+
+    Status = _cc3100_module_._socket.sl_Send(comm, buf, len, 0);
+
+    return (Status);
+
+} // end of function
+
+int32_t tcp_recv(int32_t comm, uint8_t *buf, uint32_t len, uint32_t wait_secs, bool *timed_out, void *ctx)
+{
+    int32_t Status;
+    int32_t MqttSocketFd = comm;
+
+#ifdef SOC_RCV_TIMEOUT_OPT
+
+    // socket receive time out options
+    SlTimeval_t timeVal;
+
+    // recv time out options
+    timeVal.tv_sec = wait_secs;      // Seconds
+    timeVal.tv_usec = 0;          // Microseconds. 10000 microseconds resoultion
+
+    /*------------------- setting receive timeout option on socket ---------------------*/
+
+    Status = _cc3100_module_._socket.sl_SetSockOpt(MqttSocketFd, SOL_SOCKET, SL_SO_RCVTIMEO, &timeVal,
+            sizeof(timeVal));
+
+    if (Status == 0) {
+
+    } else if (Status < 0) {
+        Uart_Write((uint8_t*)"\n\r ERROR: setting socket recv_timeout_option unsuccessfull! \n\r");
+
+    }
+    /*--------------end of setting receive timeout option on socket ---------------------*/
+
+#endif
+
+//    printf("\n\r TCP recv invoked ...\n\r");
+    *timed_out = 0;
+
+    Status = _cc3100_module_._socket.sl_Recv(MqttSocketFd, buf, len, 0);
+
+    if (Status > 0) {
+#ifdef DEBUG_NET_DEV
+        buf_printf(buf, Status, 0);
+#endif
+    }
+
+    if (0 == Status) {
+        Uart_Write((uint8_t*)"\n\r Connection Closed by peer....\n\r");
+    }
+
+    if (SL_EAGAIN == Status) {
+        Uart_Write((uint8_t*)"\n\r ERROR: Recv Time out error on server socket \n\r");
+        *timed_out = 1;
+    }
+
+    return (Status);
+
+}             // end of function
+
+int32_t comm_close(int32_t comm) {
+    int32_t Status;
+
+    Status = _cc3100_module_._socket.sl_Close(comm);
+    return (Status);
+
+}             // end of function
+
+uint32_t rtc_secs(void) {
+    return(platform_get_time_in_secs());   
+}             // end of function
+
+//--------------------------- adding functions for server functionalities ---------------------------
+
+int32_t tcp_listen(uint32_t nwconn_info, uint16_t port_number,
+        const struct secure_conn *nw_security)
+{
+    SlSockAddrIn_t sLocalAddr;
+    int32_t iSockID, iAddrSize;
+    int32_t iStatus;
+
+    //filling the TCP server socket address
+    sLocalAddr.sin_family = SL_AF_INET;
+    sLocalAddr.sin_port = _cc3100_module_._socket.sl_Htons(port_number);
+    sLocalAddr.sin_addr.s_addr = 0;
+    iAddrSize = sizeof(SlSockAddrIn_t);
+
+    // creating a TCP socket
+    iSockID = _cc3100_module_._socket.sl_Socket(SL_AF_INET, SL_SOCK_STREAM, 0);
+    if (iSockID < 0) {
+        // error
+        return (-1);
+    }
+
+    // binding the TCP socket to the TCP server address
+    iStatus = _cc3100_module_._socket.sl_Bind(iSockID, (SlSockAddr_t *) &sLocalAddr, iAddrSize);
+    if (iStatus < 0) {
+        // error
+        _cc3100_module_._socket.sl_Close(iSockID);
+        return (-1);
+    }
+
+    // putting the socket for listening to the incoming TCP connection
+    iStatus = _cc3100_module_._socket.sl_Listen(iSockID, LISTEN_QUE_SIZE);
+    if (iStatus < 0) {
+        _cc3100_module_._socket.sl_Close(iSockID);
+        return (-1);
+    }
+
+    memset(print_buf, 0x00, PRINT_BUF_LEN);
+    sprintf((char*) print_buf, "\n\r\t Server Socket created and listening on port number: %d! \n\r", port_number);
+    Uart_Write((uint8_t *) print_buf);
+
+    return (iSockID);
+
+}             // end of function
+
+int32_t tcp_select(int32_t *recv_cvec, int32_t *send_cvec, int32_t *rsvd_cvec, uint32_t wait_secs)
+{
+
+    SlTimeval_t tv, *p_tv;
+    SlFdSet_t rdfds;
+    int32_t rd_idx = 0, wr_idx = 0, max_fd = 0;
+    int32_t rv = 0;
+
+    tv.tv_sec = wait_secs;
+    tv.tv_usec = 0;
+
+    p_tv = (0xFFFFFFFF != wait_secs) ? &tv : NULL;
+
+    _cc3100_module_._socket.SL_FD_ZERO(&rdfds);
+
+    while (-1 != recv_cvec[rd_idx]) {
+        int32_t fd = recv_cvec[rd_idx++];
+
+        _cc3100_module_._socket.SL_FD_SET(fd, &rdfds);
+
+        if (max_fd < fd){
+            max_fd = fd;
+        }    
+    }
+
+//    printf("Blocking network for (%s) %u secs to monitor %d fd(s)\n\r",
+//            p_tv? "finite" : "forever", wait_secs, rd_idx);
+
+    rv = _cc3100_module_._socket.sl_Select(max_fd + 1, &rdfds, NULL, NULL, p_tv);
+
+    if (rv <= 0) {
+//        printf("Select Failed %i\n\r",rv);
+        return rv;
+    }
+
+    rd_idx = 0;
+    while (-1 != recv_cvec[rd_idx]) {
+        int32_t fd = recv_cvec[rd_idx++];
+        if (_cc3100_module_._socket.SL_FD_ISSET(fd, &rdfds))
+            recv_cvec[wr_idx++] = fd;
+    }
+
+    recv_cvec[wr_idx] = NULL;
+
+//    printf("Number of sockets on which activity is observed = %d \n\r", wr_idx);
+
+    return (wr_idx);
+}             // end of function
+
+int32_t tcp_accept(int32_t listen_hnd, uint8_t *client_ip, uint32_t *ip_length)
+{
+    int32_t new_fd;
+    SlSockAddrIn_t client_addr = {0}; // client address
+    SlSocklen_t cl_addr_size;
+
+    cl_addr_size = sizeof(client_addr);
+
+    new_fd = _cc3100_module_._socket.sl_Accept(listen_hnd, (SlSockAddr_t *) &client_addr,
+                       &cl_addr_size);
+
+    if (new_fd < 0) {
+        Uart_Write((uint8_t*)"\n\r ERROR: in accept \n\r");
+        return (NULL);
+    }
+
+    client_ip[0] = (client_addr.sin_addr.s_addr & 0xFF000000) >> 24;
+    client_ip[1] = (client_addr.sin_addr.s_addr & 0x00FF0000) >> 16;
+    client_ip[2] = (client_addr.sin_addr.s_addr & 0x0000FF00) >> 8;
+    client_ip[3] = (client_addr.sin_addr.s_addr & 0x000000FF);
+
+    *ip_length = 4;
+
+    return new_fd;
+
+} // end of function
+
+//--------------------------- adding functions for udp functionalities ---------------------------
+
+int32_t send_dest(int32_t comm, const uint8_t *buf, uint32_t len, uint16_t dest_port,
+              const uint8_t *dest_ip, uint32_t ip_len)
+{
+
+    int32_t iSockID = (int32_t) comm;
+    int32_t iStatus, iAddrSize;
+    SlSockAddrIn_t sAddr;
+    uint32_t uiDestIp;
+
+    //get destination ip
+#if 0
+    uiDestIp = svr_addr_NB_order_IPV4((uint8_t*)dest_ip); //assuming a IPV4 address is passed in dot notation.
+    if( 0 == uiDestIp )
+    {
+        Uart_Write((uint8_t*)"\n\r ERROR: Could not resolve the ip address of the destination \n\r");
+        return(-1);
+    }
+#else
+    uiDestIp = (((uint32_t) dest_ip[0] << 24) | ((uint32_t) dest_ip[1] << 16)
+            | (dest_ip[2] << 8) | (dest_ip[3]));
+
+//    printf("Writing to %d, %08x\r\n", (int32_t)comm, uiDestIp);
+
+#endif
+
+    //filling the UDP server socket address
+    sAddr.sin_family = SL_AF_INET;
+    sAddr.sin_port = _cc3100_module_._socket.sl_Htons((unsigned short) dest_port);
+    sAddr.sin_addr.s_addr = _cc3100_module_._socket.sl_Htonl(uiDestIp);
+
+    iAddrSize = sizeof(SlSockAddrIn_t);
+
+    // sending packet
+    iStatus = _cc3100_module_._socket.sl_SendTo(iSockID, buf, len, 0, (SlSockAddr_t *) &sAddr,
+            iAddrSize);
+
+    if (iStatus <= 0) {
+        // error
+        _cc3100_module_._socket.sl_Close(iSockID);
+        Uart_Write((uint8_t*)"Error: Closed the UDP socket\n\r");
+    }
+    
+    return (iStatus);
+
+} // end of function
+
+int32_t recv_from(int32_t comm, uint8_t *buf, uint32_t len, uint16_t *from_port, uint8_t *from_ip, uint32_t *ip_len)
+{
+
+    int32_t iSockID = (int32_t) comm;
+    int32_t iStatus, iAddrSize;
+    SlSockAddrIn_t fromAddr = {0};
+
+    iAddrSize = sizeof(SlSockAddrIn_t);
+
+    iStatus = _cc3100_module_._socket.sl_RecvFrom(iSockID, buf, len, 0, (SlSockAddr_t *) &fromAddr,
+                          (SlSocklen_t*) &iAddrSize);
+
+    if (iStatus < 0) {
+        // error
+        _cc3100_module_._socket.sl_Close(iSockID);
+        Uart_Write((uint8_t*)"Error: Closed the UDP socket\n\r");
+        return (iStatus);
+    }
+
+    //else populate from ip, from_port and ip_len parameters
+    // refer to comments in .h
+    if (from_port)
+        *from_port = fromAddr.sin_port;
+
+    if (from_ip) {
+        from_ip[0] = (fromAddr.sin_addr.s_addr & 0xFF000000) >> 24;
+        from_ip[1] = (fromAddr.sin_addr.s_addr & 0x00FF0000) >> 16;
+        from_ip[2] = (fromAddr.sin_addr.s_addr & 0x0000FF00) >> 8;
+        from_ip[3] = (fromAddr.sin_addr.s_addr & 0x000000FF);
+        *ip_len = 4;
+    }
+
+    return (iStatus);
+
+}    // end of function
+
+}//namespace mbed_mqtt 
+
diff -r 241bff9fe406 -r a8c249046181 mqtt_V1/platform/cc31xx_sl_net.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mqtt_V1/platform/cc31xx_sl_net.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,107 @@
+/******************************************************************************
+*
+*   Copyright (C) 2014 Texas Instruments Incorporated
+*
+*   All rights reserved. Property of Texas Instruments Incorporated.
+*   Restricted rights to use, duplicate or disclose this code are
+*   granted through contract.
+*
+*   The program may not be used without the written permission of
+*   Texas Instruments Incorporated or against the terms and conditions
+*   stipulated in the agreement under which this program has been supplied,
+*   and under no circumstances can it be used with non-TI connectivity device.
+*
+******************************************************************************/
+
+/*
+  Network Services for General Purpose Linux environment
+*/
+
+#ifndef __CC31XX_SL_NET_H__
+#define __CC31XX_SL_NET_H__
+
+#include "cc3100_simplelink.h"
+#include "mqtt_client.h" /* conn options */
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+namespace mbed_mqtt {
+
+//*****************************************************************************
+//                      MACROS
+//*****************************************************************************
+
+// MACRO to include receive time out feature
+#define SOC_RCV_TIMEOUT_OPT 	1
+
+
+/*-----------------------------------------------------------------------------
+definitions needed for the functions in this file
+-----------------------------------------------------------------------------*/
+
+
+/*-----------------------------------------------------------------------------
+prototypes of functions
+-----------------------------------------------------------------------------*/
+
+int32_t comm_open(uint32_t nwconn_opts, const char *server_addr, uint16_t port_number,
+        		const struct secure_conn *nw_security);
+int32_t tcp_send(int32_t comm, const uint8_t *buf, uint32_t len, void *ctx);
+int32_t tcp_recv(int32_t comm, uint8_t *buf, uint32_t len, uint32_t wait_secs, bool *timed_out,
+		     void *ctx);
+int32_t comm_close(int32_t comm);
+uint32_t rtc_secs(void);
+
+/*-----------------functions added for server -----------------------------*/
+
+int32_t tcp_listen(uint32_t nwconn_info,  uint16_t port_number,
+                 const struct secure_conn *nw_security);
+
+int32_t tcp_select(int32_t *recv_cvec, int32_t *send_cvec, int32_t *rsvd_cvec,
+               uint32_t wait_secs);
+
+
+int32_t tcp_accept(int32_t listen_hnd, uint8_t *client_ip,
+                 uint32_t *ip_length);
+
+/*----------------- adding functions for udp functionalities -------------------*/
+
+/** Send a UDP packet 
+    
+    @param[in] comm communication entity handle; socket handle in this case
+    @param[in] buf buf to be sent in the udp packet
+    @param[in] len length of the buffer buf
+    @param[in] dest_port destination port number
+    @param[in] dest_ip ip address of the destination in dot notation, interpretted as a string;
+                Only IPV4 is supported currently.
+    @param[in] ip_len length of string dest_ip; currently not used
+    @return number of bytes sent or error returned by sl_SendTo call
+*/
+int32_t send_dest(int32_t, const uint8_t *buf, uint32_t len, uint16_t dest_port, const uint8_t *dest_ip, uint32_t ip_len);
+
+/** Recieve a UDP packet
+    
+    @param[in] comm communication entity handle; socket handle in this case
+    @param[out] buf buf into which received UDP packet is written
+    @param[in] maximum len length of the buffer buf
+    @param[out] from_port port number of UDP packet source
+    @param[out] from_ip ip address of the UDP packet source. 
+                The ip address is to be interpreted as a uint32_t number in network byte ordering
+                Only IPV4 is supported currently.
+    @param[out] ip_len length of string from_ip; 
+               currently always populated with 4 as the address is a IPV4 address
+    @return number of bytes received or error returned by sl_RecvFrom call
+*/
+int32_t recv_from(int32_t comm, uint8_t *buf, uint32_t len, uint16_t *from_port, uint8_t *from_ip, uint32_t *ip_len);
+
+}//namespace mbed_mqtt 
+
+#ifdef __cplusplus  
+}
+#endif 
+
+#endif
+
diff -r 241bff9fe406 -r a8c249046181 mqtt_V1/platform/cc3200_platform.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mqtt_V1/platform/cc3200_platform.cpp	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,42 @@
+/******************************************************************************
+ *
+ *   Copyright (C) 2014 Texas Instruments Incorporated
+ *
+ *   All rights reserved. Property of Texas Instruments Incorporated.
+ *   Restricted rights to use, duplicate or disclose this code are
+ *   granted through contract.
+ *
+ *   The program may not be used without the written permission of
+ *   Texas Instruments Incorporated or against the terms and conditions
+ *   stipulated in the agreement under which this program has been supplied,
+ *   and under no circumstances can it be used with non-TI connectivity device.
+ *
+ ******************************************************************************/
+
+#include "cc3200_platform.h"
+
+
+Timer t;
+
+namespace mbed_mqtt {
+
+void platform_timer_init()
+{   
+    t.start();
+}
+
+uint32_t platform_get_time_in_secs()
+{
+    uint32_t Secs = 0;
+//    uint16_t Msec = 0;
+    
+    t.stop();
+    Secs = t.read();
+//    Msec = t.read_ms();
+    t.reset();
+    t.start();
+    
+    return (Secs);
+}
+
+}//namespace mbed_mqtt 
diff -r 241bff9fe406 -r a8c249046181 mqtt_V1/platform/cc3200_platform.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mqtt_V1/platform/cc3200_platform.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,53 @@
+/******************************************************************************
+*
+*   Copyright (C) 2014 Texas Instruments Incorporated
+*
+*   All rights reserved. Property of Texas Instruments Incorporated.
+*   Restricted rights to use, duplicate or disclose this code are
+*   granted through contract.
+*
+*   The program may not be used without the written permission of
+*   Texas Instruments Incorporated or against the terms and conditions
+*   stipulated in the agreement under which this program has been supplied,
+*   and under no circumstances can it be used with non-TI connectivity device.
+*
+******************************************************************************/
+
+/*
+  platform.h
+
+  This file contains the platform specific typedefs
+*/
+
+#ifndef __PLATFORM_H__
+#define __PLATFORM_H__
+
+#include "cc3100_simplelink.h"
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+namespace mbed_mqtt {
+
+//typedef unsigned char   u8;  /* Range: 0 to 255; refers network buf */
+//typedef signed   char   i8;  /* Range: -127 to 127 and signed maths */
+//typedef char            c8;  /* ASCII string and value of 0 to 127  */
+
+//typedef unsigned short u16;
+//typedef signed short   i16;
+//typedef unsigned long  u32;
+//typedef signed long    i32;
+
+extern void platform_timer_init();
+extern uint32_t platform_get_time_in_secs();
+
+}//namespace mbed_mqtt 
+
+#ifdef __cplusplus  
+}
+#endif 
+
+#endif /* __PLATFORM_H__ */
+
diff -r 241bff9fe406 -r a8c249046181 mqtt_V1/server.lib
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mqtt_V1/server.lib	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,1 @@
+http://developer.mbed.org/users/dflet/code/server/#547251f42a60
diff -r 241bff9fe406 -r a8c249046181 mqtt_V1/sl/sl_mqtt_client.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mqtt_V1/sl/sl_mqtt_client.cpp	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,791 @@
+/******************************************************************************
+*
+*   Copyright (C) 2014 Texas Instruments Incorporated
+*
+*   All rights reserved. Property of Texas Instruments Incorporated.
+*   Restricted rights to use, duplicate or disclose this code are
+*   granted through contract.
+*
+*   The program may not be used without the written permission of
+*   Texas Instruments Incorporated or against the terms and conditions
+*   stipulated in the agreement under which this program has been supplied,
+*   and under no circumstances can it be used with non-TI connectivity device.
+*
+******************************************************************************/
+
+#include "sl_mqtt_client.h"
+#include "cc31xx_sl_net.h"
+//#include "cc3100_nonos.h"
+#include "myBoardInit.h"
+#include "cli_uart.h"
+#include "osi.h"
+
+using namespace mbed_cc3100;
+
+#if (THIS_BOARD == MBED_BOARD_LPC1768)
+//cc3100 _cc3100module(p9, p10, p8, SPI(p11, p12, p13));//LPC1768  irq, nHib, cs, mosi, miso, sck
+cc3100 _cc3100module(p16, p17, p9, p10, p8, SPI(p5, p6, p7));//LPC1768  irq, nHib, cs, mosi, miso, sck
+#elif (THIS_BOARD == Seeed_Arch_Max)
+class cc3100 _cc3100module(PE_5, PE_4, PE_6, SPI(PB_5, PB_4, PB_3));
+#elif (THIS_BOARD == ST_MBED_NUCLEOF103)
+class cc3100 _cc3100module(PA_9, PC_7, PB_6, SPI(PA_7, PA_6, PA_5));//nucleoF103  irq, nHib, cs, mosi, miso, sck
+#elif (THIS_BOARD == ST_MBED_NUCLEOF411)
+class cc3100 _cc3100module(PA_9, PC_7, PB_6, SPI(PA_7, PA_6, PA_5));//nucleoF411  irq, nHib, cs, mosi, miso, sck
+#elif (THIS_BOARD == ST_MBED_NUCLEOF401)
+class cc3100 _cc3100module(PA_8, PA_9, PC_7, PB_6, SPI(PA_7, PA_6, PA_5));//nucleoF401  irq, nHib, cs, mosi, miso, sck
+#elif (THIS_BOARD == EA_MBED_LPC4088)
+class cc3100 _cc3100module(p14, p15, p9, p10, p8, SPI(p5, p6, p7));//LPC4088  irq, nHib, cs, mosi, miso, sck
+#elif (THIS_BOARD == LPCXpresso4337)
+class cc3100 _cc3100module(P2_12, P2_9, P2_2, P3_5, P1_2, SPI(P1_4, P1_3, PF_4));//LPCXpresso4337  irq, nHib, cs, mosi, miso, sck
+#endif
+
+namespace mbed_mqtt {
+
+#ifndef CFG_SL_CL_BUF_LEN
+#define BUF_LEN          1024 /*Buffer length*/
+#else
+#define BUF_LEN          CFG_SL_CL_BUF_LEN
+#endif
+
+#ifndef CFG_SL_CL_MAX_MQP
+#define MAX_MQP          2 /* # of buffers */
+#else
+#define MAX_MQP          CFG_SL_CL_MAX_MQP
+#endif
+
+#ifndef CFG_SL_CL_STACK
+#define OSI_STACK_SIZE 2048
+#else
+#define OSI_STACK_SIZE CFG_SL_CL_STACK
+#endif
+//*****************************************************************************
+// global variables used
+//*****************************************************************************
+
+
+struct sl_client_ctx {
+        /* Client information details */
+        char *client_id;
+        char *usr_name;
+        char *usr_pwd;
+        SlMqttWill_t mqtt_will;
+
+        /* Client management variables */
+        bool in_use;
+        char awaited_ack;
+        uint16_t conn_ack;
+
+        /*Sync Object used to ensure single inflight message -
+          used in blocking mode to wait on ack*/
+        _SlSyncObj_t ack_sync_obj;
+        /* Suback QoS pointer to store passed by application */
+        char *suback_qos;
+
+        /* Application information */
+        void* app_hndl;
+        SlMqttClientCbs_t app_cbs;
+
+        /* Library information */
+        void *cli_hndl;
+        bool blocking_send;
+};
+
+#ifndef CFG_CL_MQTT_CTXS
+#define MAX_SIMULTANEOUS_SERVER_CONN 4
+#else
+#define MAX_SIMULTANEOUS_SERVER_CONN CFG_MQTT_CL_CTXS
+#endif
+
+
+static struct sl_client_ctx sl_cli_ctx[MAX_SIMULTANEOUS_SERVER_CONN];
+
+/* Lock Object to be passed to the MQTT lib */
+_SlLockObj_t mqtt_lib_lockobj;
+
+/* Creating a pool of MQTT coonstructs that can be used by the MQTT Lib
+     mqp_vec =>pointer to a pool of the mqtt packet constructs
+      buf_vec => the buffer area which is attached with each of mqp_vec*/
+DEFINE_MQP_BUF_VEC(MAX_MQP, mqp_vec, BUF_LEN, buf_vec);
+
+/*Task Priority and Response Time*/
+uint32_t g_wait_secs;
+
+bool g_multi_srvr_conn = false;
+
+/* Receive task handle */
+OsiTaskHandle g_rx_task_hndl;
+
+/* Synchronization object used between the Rx and App task */
+_SlSyncObj_t g_rx_tx_sync_obj;
+
+#define RX_TX_SIGNAL_WAIT()     _cc3100module._nonos.sl_SyncObjWait(&g_rx_tx_sync_obj, NON_OS_SYNC_OBJ_SIGNAL_VALUE, NON_OS_SYNC_OBJ_CLEAR_VALUE, SL_OS_WAIT_FOREVER)
+#define RX_TX_SIGNAL_POST()     _cc3100module._nonos.sl_SyncObjSignal(&g_rx_tx_sync_obj, NON_OS_SYNC_OBJ_SIGNAL_VALUE)
+
+/* MQTT Quality of Service */
+static const enum mqtt_qos qos[] ={
+        MQTT_QOS0,
+        MQTT_QOS1,
+        MQTT_QOS2
+};
+
+/* Network Services specific to cc3200*/
+struct device_net_services net={&comm_open,&tcp_send,&tcp_recv,&send_dest,&recv_from,&comm_close,
+                                        &tcp_listen,&tcp_accept,&tcp_select,&rtc_secs};
+        
+/* Defining Retain Flag. Getting retain flag bit from fixed header*/
+#define MQP_PUB_RETAIN(mqp)    ( ((mqp->fh_byte1 ) & 0x01)?true:false )
+
+/*Defining Duplicate flag. Getting Duplicate flag bit from fixed header*/
+#define MQP_PUB_DUP(mqp)        (((mqp->fh_byte1>>3) & 0x01)?true:false )
+
+/*Defining QOS value. Getting QOS value from fixed header*/
+#define MQP_PUB_QOS(mqp)        ((mqp->fh_byte1 >>1)  & 0x03)
+
+#define ACK_RX_SIGNAL_WAIT(ack_sync_obj)     _cc3100module._nonos.sl_SyncObjWait(ack_sync_obj, NON_OS_SYNC_OBJ_SIGNAL_VALUE, NON_OS_SYNC_OBJ_CLEAR_VALUE, SL_OS_WAIT_FOREVER)    
+#define ACK_RX_SIGNAL_POST(ack_sync_obj)     _cc3100module._nonos.sl_SyncObjSignal(ack_sync_obj, NON_OS_SYNC_OBJ_SIGNAL_VALUE)
+
+#define STR2UTF_CONV(utf_s, str) {utf_s.buffer = (char *)str; utf_s.length = strlen(str);}
+
+/*Defining Event Messages*/
+#define MQTT_ACK "Ack Received from server"
+#define MQTT_ERROR "Connection Lost with broker"
+
+//*****************************************************************************
+// process_notify_ack_cb 
+//*****************************************************************************
+static void 
+process_notify_ack_cb(void *app, uint8_t msg_type, uint16_t msg_id, uint8_t *buf, uint32_t len)
+{
+
+        struct sl_client_ctx *client_ctx = (struct sl_client_ctx *)app;
+        int32_t loopcnt;
+
+        switch(msg_type) {
+
+        case MQTT_CONNACK:
+                client_ctx->conn_ack = ((buf[0] << 8) | buf[1]);
+                client_ctx->awaited_ack = 0;
+                ACK_RX_SIGNAL_POST(&client_ctx->ack_sync_obj);
+        break;
+        case MQTT_SUBACK:
+                if(true == client_ctx->blocking_send) {
+                        for(loopcnt = 0; loopcnt < len; loopcnt++) {
+                                client_ctx->suback_qos[loopcnt] = buf[loopcnt];
+                        }
+                                
+                        if(client_ctx->awaited_ack == msg_type) {
+                                client_ctx->awaited_ack = 0;
+                                ACK_RX_SIGNAL_POST(&client_ctx->ack_sync_obj);
+                        }
+                } else {
+                        client_ctx->app_cbs.sl_ExtLib_MqttEvent(
+                                client_ctx->app_hndl,
+                                SL_MQTT_CL_EVT_SUBACK, buf, len);
+                }
+        break;
+        /* Error returns --- TBD */
+        default:
+                if(true == client_ctx->blocking_send) {
+                        if(client_ctx->awaited_ack == msg_type) {
+                                client_ctx->awaited_ack = 0;
+                                ACK_RX_SIGNAL_POST(&client_ctx->ack_sync_obj);
+                        }
+                } else {
+                        client_ctx->app_cbs.sl_ExtLib_MqttEvent(
+                                client_ctx->app_hndl,
+                                msg_type, MQTT_ACK, strlen(MQTT_ACK));
+                }
+        break;
+
+        }
+       
+        return ;
+}
+
+//*****************************************************************************
+// process_publish_rx_cb 
+//*****************************************************************************
+static bool 
+process_publish_rx_cb(void *app, bool dup, enum mqtt_qos qos, bool retain, 
+                   struct mqtt_packet *mqp)
+{
+        struct sl_client_ctx *client_ctx = (struct sl_client_ctx *)app;
+        /*If incoming message is a publish message from broker */
+        /* Invokes the event handler with topic,topic length,payload and 
+           payload length values*/
+        client_ctx->app_cbs.sl_ExtLib_MqttRecv(client_ctx->app_hndl,
+                               (char const*)MQP_PUB_TOP_BUF(mqp),
+                               MQP_PUB_TOP_LEN(mqp),MQP_PUB_PAY_BUF(mqp),
+                               MQP_PUB_PAY_LEN(mqp), dup,
+                               MQP_PUB_QOS(mqp), retain);
+        return true;
+}
+
+//*****************************************************************************
+// process_disconn_cb
+//*****************************************************************************
+static void process_disconn_cb(void *app, int32_t cause)
+{
+        struct sl_client_ctx *client_ctx = (struct sl_client_ctx *)app;
+
+        if(client_ctx->awaited_ack != 0) {
+                client_ctx->awaited_ack = MQTT_DISCONNECT;
+                ACK_RX_SIGNAL_POST(&client_ctx->ack_sync_obj);
+        } else {
+                if(false == client_ctx->blocking_send) {
+                        /* Invoke the disconnect callback */
+                        client_ctx->app_cbs.sl_ExtLib_MqttDisconn(
+                                               client_ctx->app_hndl);
+                }
+        }
+        return;
+}
+
+
+//*****************************************************************************
+// Receive Task. Invokes in the context of a task 
+//*****************************************************************************
+void 
+VMqttRecvTask(void *pArgs)  
+{
+
+        int32_t retval;
+        do {
+                if(false == g_multi_srvr_conn) {
+                        /* wait on broker connection */
+                        RX_TX_SIGNAL_WAIT();
+                        while(1) {
+                                /* Forcing to use the index 0 always - caution */
+                                retval = mqtt_client_ctx_run(
+                                                sl_cli_ctx[0].cli_hndl, 
+                                                g_wait_secs);
+                                if((retval < 0) && 
+                                        (retval != MQP_ERR_TIMEOUT)) {
+                                        break;
+                                }
+                        }
+                } else {
+                        mqtt_client_run(g_wait_secs);
+                }
+        }while(1);
+}
+
+static struct sl_client_ctx *get_available_clictx_mem()
+{
+        int32_t loopcnt, max_store;
+
+        if(false == g_multi_srvr_conn) {
+                max_store = 1;
+        } else {
+                max_store = MAX_SIMULTANEOUS_SERVER_CONN;
+        }
+
+        for(loopcnt = 0; loopcnt < max_store; loopcnt++) {
+                if(false == sl_cli_ctx[loopcnt].in_use) {
+                        sl_cli_ctx[loopcnt].in_use = true;
+                        return(&(sl_cli_ctx[loopcnt]));
+                }
+        }
+
+        return NULL;
+}
+
+//*****************************************************************************
+// sl_ExtLib_MqttClientCtxCreate
+//*****************************************************************************
+void *sl_ExtLib_MqttClientCtxCreate(const SlMqttClientCtxCfg_t *ctx_cfg,
+                                      const SlMqttClientCbs_t *msg_cbs,
+                                      void *app_hndl)
+{
+
+        struct sl_client_ctx *client_ctx_ptr;
+        struct mqtt_client_ctx_cfg lib_ctx_cfg;
+        struct mqtt_client_ctx_cbs lib_cli_cbs;
+        struct secure_conn lib_nw_security;
+        int32_t retval;
+       
+        /* Get a client context storage area */
+        client_ctx_ptr = get_available_clictx_mem();
+        if(client_ctx_ptr == NULL) {
+                return NULL;
+        }
+        
+        /* Create the sync object to signal on arrival of ACK packet */
+        _cc3100module._nonos.sl_SyncObjCreate(&client_ctx_ptr->ack_sync_obj, "AckSyncObject");
+        _cc3100module._nonos.sl_SyncObjWait(&client_ctx_ptr->ack_sync_obj, NON_OS_SYNC_OBJ_SIGNAL_VALUE, NON_OS_SYNC_OBJ_CLEAR_VALUE, SL_OS_NO_WAIT);
+        
+        /* Store the application handle */
+        client_ctx_ptr->app_hndl = app_hndl;
+        /* Initialize the ACK awaited */
+        client_ctx_ptr->awaited_ack = 0;
+        
+        /* Store the application callbacks, to be invoked later */
+        client_ctx_ptr->app_cbs.sl_ExtLib_MqttRecv = \
+                                        msg_cbs->sl_ExtLib_MqttRecv;
+        client_ctx_ptr->app_cbs.sl_ExtLib_MqttEvent = \
+                                        msg_cbs->sl_ExtLib_MqttEvent;
+        client_ctx_ptr->app_cbs.sl_ExtLib_MqttDisconn = \
+                                        msg_cbs->sl_ExtLib_MqttDisconn;
+
+        /* Initialize the client lib */
+        lib_ctx_cfg.config_opts = ctx_cfg->mqtt_mode31;
+        
+        if(true == g_multi_srvr_conn) {
+                lib_ctx_cfg.config_opts |=
+                        (MQTT_CFG_APP_HAS_RTSK | MQTT_CFG_MK_GROUP_CTX);
+        } else {
+                lib_ctx_cfg.config_opts |= MQTT_CFG_APP_HAS_RTSK;
+        }
+        
+        /* get the network connection options */
+        client_ctx_ptr->blocking_send = ctx_cfg->blocking_send;
+        lib_ctx_cfg.nwconn_opts = ctx_cfg->server_info.netconn_flags;
+        lib_ctx_cfg.nwconn_opts |= DEV_NETCONN_OPT_TCP;
+        lib_ctx_cfg.server_addr = (char*)ctx_cfg->server_info.server_addr;
+        lib_ctx_cfg.port_number = ctx_cfg->server_info.port_number;
+        /*initialize secure socket parameters */
+        if(ctx_cfg->server_info.netconn_flags & SL_MQTT_NETCONN_SEC) {
+        		lib_ctx_cfg.nw_security = &lib_nw_security;
+                /* initialize secure socket parameters */
+                lib_ctx_cfg.nw_security->cipher = 
+                        (void*)&(ctx_cfg->server_info.cipher);
+                lib_ctx_cfg.nw_security->method = 
+                        (void*)&(ctx_cfg->server_info.method);
+                lib_ctx_cfg.nw_security->n_file = 
+                        ctx_cfg->server_info.n_files;
+                lib_ctx_cfg.nw_security->files = 
+                        (char**)ctx_cfg->server_info.secure_files;
+        }
+        else {
+                lib_ctx_cfg.nw_security=NULL;
+        }
+
+        lib_cli_cbs.publish_rx = process_publish_rx_cb;
+        lib_cli_cbs.ack_notify = process_notify_ack_cb;
+        lib_cli_cbs.disconn_cb = process_disconn_cb;
+        
+        retval = mqtt_client_ctx_create(&lib_ctx_cfg,
+                                        &lib_cli_cbs, client_ctx_ptr,
+                                        &client_ctx_ptr->cli_hndl);
+        
+        if(retval < 0) {
+                Uart_Write((uint8_t*)"mqtt_client_ctx_create failed\r\n");
+                client_ctx_ptr->in_use = false;
+                return NULL;
+        }
+        
+        return (void*)client_ctx_ptr;
+}
+
+//*****************************************************************************
+// sl_ExtLib_MqttClientCtxDelete
+//*****************************************************************************
+int32_t sl_ExtLib_MqttClientCtxDelete(void *cli_ctx)
+{
+        struct sl_client_ctx *client_ctx=(struct sl_client_ctx *)cli_ctx;
+        int32_t retval;
+
+        retval = mqtt_client_ctx_delete(client_ctx->cli_hndl);
+        if(retval >= 0) {
+                /* Check for more paramaters --- TBD */
+                _cc3100module._nonos.sl_SyncObjDelete(&client_ctx->ack_sync_obj, 0);
+                /* Free up the context */
+                memset(client_ctx, 0, sizeof(struct sl_client_ctx));
+        }
+
+        return (retval < 0)? -1: 0;
+}
+
+void
+mutex_lockup(void *mqtt_lib_lock)
+{
+        _cc3100module._nonos.sl_LockObjLock((_SlLockObj_t*)mqtt_lib_lock, SL_OS_WAIT_FOREVER, NON_OS_LOCK_OBJ_LOCK_VALUE, SL_OS_WAIT_FOREVER);
+}
+
+void
+mutex_unlock(void *mqtt_lib_lock)
+{
+        _cc3100module._nonos.sl_LockObjUnlock((_SlLockObj_t*)mqtt_lib_lock, NON_OS_LOCK_OBJ_UNLOCK_VALUE);
+}
+
+//*****************************************************************************
+// sl_ExtLib_MqttClientInit
+//*****************************************************************************
+int32_t sl_ExtLib_MqttClientInit(const SlMqttClientLibCfg_t  *cfg)
+{
+
+        struct mqtt_client_lib_cfg lib_cfg;
+        /* Initialize the control variables */
+        memset(sl_cli_ctx, 0, sizeof(sl_cli_ctx));
+
+        /* Setup the MQTT client lib configurations */
+        lib_cfg.loopback_port = cfg->loopback_port;
+        /* Initializing the sync object */
+        g_rx_tx_sync_obj = 0;
+
+        if(cfg->loopback_port) {
+                g_multi_srvr_conn = true;
+                lib_cfg.grp_uses_cbfn = true;   /* Does use the group callback func */
+        } else {
+                g_multi_srvr_conn = false;
+                lib_cfg.grp_uses_cbfn = false;   /* Doesnt use the group callback func */
+                /* Create the sync object between Rx and App tasks */
+                _cc3100module._nonos.sl_SyncObjCreate(&g_rx_tx_sync_obj, "RxTxSyncObject");
+                _cc3100module._nonos.sl_SyncObjWait(&g_rx_tx_sync_obj, NON_OS_SYNC_OBJ_SIGNAL_VALUE, NON_OS_SYNC_OBJ_CLEAR_VALUE, SL_OS_NO_WAIT);
+        }
+        
+        g_wait_secs = cfg->resp_time;
+        /* Setup the mutex operations */
+        _cc3100module._nonos.sl_LockObjCreate(&mqtt_lib_lockobj,"MQTT Lock");
+        lib_cfg.mutex = (void *)&mqtt_lib_lockobj;
+        lib_cfg.mutex_lockin = mutex_lockup;
+        lib_cfg.mutex_unlock = mutex_unlock;
+        /* hooking DBG print function */
+        lib_cfg.debug_printf = cfg->dbg_print;
+        /* Initialize client library */
+        if(mqtt_client_lib_init(&lib_cfg) < 0) {
+                Uart_Write((uint8_t*)"mqtt_client_lib_init failed\r\n");
+                return -1;
+        }
+
+        /* provide MQTT Lib information to create a pool of MQTT constructs. */
+        mqtt_client_buffers_register(MAX_MQP,mqp_vec,BUF_LEN,&buf_vec[0][0]);
+        /* Register network services speicific to CC3200 */
+        mqtt_client_net_svc_register(&net);
+        /* start the receive task */
+        osi_TaskCreate( VMqttRecvTask, 
+                (const signed char *) "MQTTRecv",
+                OSI_STACK_SIZE,
+                NULL, 
+                cfg->rx_tsk_priority, &g_rx_task_hndl );
+                
+        return 0;
+}
+
+//*****************************************************************************
+// sl_ExtLib_MqttClientExit
+//*****************************************************************************
+int32_t 
+sl_ExtLib_MqttClientExit()
+{
+        int32_t retval;
+
+        /* Deinitialize the MQTT client lib */
+        retval = mqtt_client_lib_exit();
+        if(retval >= 0) {
+                if(mqtt_lib_lockobj != NULL)
+                {
+                        /* Delete the MQTT lib lock object */
+                        _cc3100module._nonos.sl_LockObjDelete(&mqtt_lib_lockobj, 0);
+                }
+                if(g_rx_task_hndl != NULL)
+                {
+                        /* Delete the Rx Task */
+                        osi_TaskDelete(&g_rx_task_hndl);
+                }
+                
+                if(g_rx_tx_sync_obj != NULL)
+                {
+                        /* Delete the Rx-Tx task sync object */
+                        _cc3100module._nonos.sl_SyncObjDelete(&g_rx_tx_sync_obj, 0);
+                }
+                
+                g_rx_task_hndl = NULL;
+                g_rx_tx_sync_obj = NULL;
+                mqtt_lib_lockobj = NULL;
+        }
+        
+        return (retval < 0)? -1: 0;
+}
+
+//*****************************************************************************
+// sl_ExtLib_MqttClientSet
+//*****************************************************************************
+int32_t 
+sl_ExtLib_MqttClientSet(void *app, int32_t param, const void *value, uint32_t len)
+{
+
+        struct sl_client_ctx *client_ctx = (struct sl_client_ctx *)app;
+        switch(param)
+        {
+        case SL_MQTT_PARAM_CLIENT_ID:
+                /* Save the reference to the Client ID */
+                client_ctx->client_id =(char*)value;
+                break;
+
+        case SL_MQTT_PARAM_USER_NAME:
+                /* Save the reference to the Username */
+                client_ctx->usr_name =(char*)value;
+                break;
+
+        case SL_MQTT_PARAM_PASS_WORD:
+                /* Save the reference to the password */
+                client_ctx->usr_pwd =(char*)value;
+                break;
+
+        case SL_MQTT_PARAM_WILL_PARAM:
+                /* Save the reference to will parameters*/
+                client_ctx->mqtt_will = *((SlMqttWill_t*)value);
+                break;
+        default:
+                break;
+        }
+
+        return 0;
+   
+}
+
+//*****************************************************************************
+// sl_ExtLib_MqttClientConnect
+//*****************************************************************************
+int32_t
+sl_ExtLib_MqttClientConnect(void *cli_ctx, bool clean, uint16_t keep_alive_time)
+{ 
+
+    
+        int32_t ret = -1;
+        struct sl_client_ctx *client_ctx = (struct sl_client_ctx *)cli_ctx;
+
+        /*utf8 strings into which client info will be stored*/
+        struct utf8_string client_id, username, usr_pwd, will_topic, will_msg;
+        struct utf8_string *usrname = NULL, *usrpasswd = NULL, *clientid=NULL;
+
+        /* Provide Client ID,user name and password into MQTT Library */
+        if(client_ctx->client_id != NULL) {
+            STR2UTF_CONV(client_id, client_ctx->client_id);
+            clientid = &client_id;
+        }
+        
+        if(client_ctx->usr_name != NULL) {
+                STR2UTF_CONV(username, client_ctx->usr_name);
+                usrname = &username;
+        }
+        if(client_ctx->usr_pwd != NULL) {
+                STR2UTF_CONV(usr_pwd, client_ctx->usr_pwd);
+                usrpasswd = &usr_pwd;
+        }
+        ret = mqtt_client_ctx_info_register(client_ctx->cli_hndl,
+                                clientid, usrname, usrpasswd);
+        if(ret < 0) {
+                goto mqtt_connect_exit1;
+        }
+        
+        /* Register a will message, if specified, into MQTT Library */
+        if(NULL != client_ctx->mqtt_will.will_topic ) {
+                STR2UTF_CONV(will_topic, client_ctx->mqtt_will.will_topic);
+                STR2UTF_CONV(will_msg, client_ctx->mqtt_will.will_msg);
+                ret = mqtt_client_ctx_will_register(client_ctx->cli_hndl,
+                                        &will_topic, &will_msg,
+                                        qos[client_ctx->mqtt_will.will_qos],
+                                        client_ctx->mqtt_will.retain);
+                if(ret < 0) {
+                        Uart_Write((uint8_t*)"mqtt_client_ctx_will_register fail\r\n");
+                        goto mqtt_connect_exit1;
+                }
+        }
+        
+        client_ctx->awaited_ack = MQTT_CONNACK;
+        client_ctx->conn_ack = 0;
+    
+        /* Connect to the server */
+        ret = mqtt_connect_msg_send(client_ctx->cli_hndl, clean, keep_alive_time);
+        /*Network or Socket Error happens*/
+        if(ret < 0) {
+                Uart_Write((uint8_t*)"mqtt_connect_msg_send failed \r\n");
+                goto mqtt_connect_exit1;
+        }
+
+        if(false == g_multi_srvr_conn) {
+                /* Unblock the receive task here */        
+                RX_TX_SIGNAL_POST();
+        }
+        
+        /* Wait for a CONNACK here */
+        ACK_RX_SIGNAL_WAIT(&client_ctx->ack_sync_obj);
+        
+        if(MQTT_DISCONNECT == client_ctx->awaited_ack) {
+                Uart_Write((uint8_t*)"sl_ExtLib_MqttClientConnect fail\r\n");        
+                ret = -1;
+        } else {
+                ret = (int32_t)client_ctx->conn_ack;
+        }
+
+mqtt_connect_exit1:
+
+        client_ctx->awaited_ack = 0;
+        client_ctx->conn_ack = 0;
+        return (ret < 0)? -1: ret;
+}
+
+//*****************************************************************************
+// sl_ExtLib_MqttClientDisconnect
+//*****************************************************************************
+int32_t
+sl_ExtLib_MqttClientDisconnect(void *cli_ctx)
+{
+        struct sl_client_ctx *client_ctx = (struct sl_client_ctx *)cli_ctx;
+        int32_t retval;
+
+        if(!(mqtt_client_is_connected(client_ctx->cli_hndl)))
+                return -1;
+
+        client_ctx->awaited_ack = MQTT_DISCONNECT;
+
+        /* send the disconnect command. */
+        retval = mqtt_disconn_send(client_ctx->cli_hndl);
+        
+        if(retval >= 0) {
+                /* wait on Rx task to acknowledge */
+                ACK_RX_SIGNAL_WAIT(&client_ctx->ack_sync_obj);
+        }
+        client_ctx->awaited_ack = 0;
+
+        return (retval < 0)? -1: 0;
+}
+
+
+//*****************************************************************************
+// sl_ExtLib_MqttClientSub
+//*****************************************************************************
+int32_t 
+sl_ExtLib_MqttClientSub(void *cli_ctx, char* const *topics,
+                        uint8_t *qos_level, int32_t count)
+{
+#define MAX_SIMULTANEOUS_SUB_TOPICS 4
+
+        int32_t ret = -1, i;
+
+        struct utf8_strqos qos_topics[MAX_SIMULTANEOUS_SUB_TOPICS];
+        struct sl_client_ctx *client_ctx = (struct sl_client_ctx *)cli_ctx;
+
+        if(!(mqtt_client_is_connected(client_ctx->cli_hndl)) || (count > MAX_SIMULTANEOUS_SUB_TOPICS)) {
+                goto mqtt_sub_exit1;  /* client not connected*/
+        }
+
+        for(i = 0; i < count; i++) {
+                qos_topics[i].buffer = topics[i];
+                qos_topics[i].qosreq = qos[qos_level[i]];
+                qos_topics[i].length = strlen(topics[i]);
+        }
+
+        /* Set up all variables to receive an ACK for the message to be sent*/
+        if(true == client_ctx->blocking_send) {      
+                /* Update the qos_level to be in-out parameter */
+                client_ctx->suback_qos = (char*)qos_level;
+                client_ctx->awaited_ack = MQTT_SUBACK;
+        }
+
+        /* Send the subscription MQTT message */
+        ret = mqtt_sub_msg_send(client_ctx->cli_hndl, qos_topics, count);
+        if(ret < 0) {
+                goto mqtt_sub_exit1;
+        }
+
+        if(true == client_ctx->blocking_send) {
+                ACK_RX_SIGNAL_WAIT(&client_ctx->ack_sync_obj);
+                if(MQTT_DISCONNECT == client_ctx->awaited_ack) {
+                        ret = -1;
+                }
+        }
+
+mqtt_sub_exit1:
+        client_ctx->awaited_ack = 0;
+        return (ret < 0)? -1: 0;
+}
+
+
+//*****************************************************************************
+// sl_ExtLib_MqttClientUnsub
+//*****************************************************************************
+int32_t
+sl_ExtLib_MqttClientUnsub(void *cli_ctx, char* const *topics, int32_t count)
+{
+#define MAX_SIMULTANEOUS_UNSUB_TOPICS 4
+
+        int32_t ret = -1, i;
+        struct utf8_string unsub_topics[MAX_SIMULTANEOUS_UNSUB_TOPICS];
+        struct sl_client_ctx *client_ctx = (struct sl_client_ctx *)cli_ctx;
+
+        if(!(mqtt_client_is_connected(client_ctx->cli_hndl)) || (count > MAX_SIMULTANEOUS_UNSUB_TOPICS)) {
+                goto mqtt_unsub_exit1; /* Check client status */
+        }
+
+        for(i = 0; i < count; i++) {
+                STR2UTF_CONV(unsub_topics[i], topics[i]);
+        }
+
+        /* Set up all variables to receive an ACK for the message to be sent*/
+        if(true == client_ctx->blocking_send) {      
+                client_ctx->awaited_ack = MQTT_UNSUBACK;
+        }
+
+        /* Send the unsubscription MQTT message */
+        ret = mqtt_unsub_msg_send(client_ctx->cli_hndl, unsub_topics, count);
+        if(ret < 0) {
+                goto mqtt_unsub_exit1;
+        }
+
+        if(true == client_ctx->blocking_send) {
+                ACK_RX_SIGNAL_WAIT(&client_ctx->ack_sync_obj);
+                if(MQTT_DISCONNECT == client_ctx->awaited_ack) {
+                        ret = -1;
+                }
+        }
+
+mqtt_unsub_exit1:
+        client_ctx->awaited_ack = 0;
+        return (ret < 0)? -1: 0;
+}
+//*****************************************************************************
+// sl_ExtLib_MqttClientSend
+//*****************************************************************************
+int32_t 
+sl_ExtLib_MqttClientSend(void *cli_ctx, const char *topic,
+                          const void *data, int32_t len, 
+                          char qos_level, bool retain)
+{
+
+        int32_t ret = -1;
+        struct utf8_string topic_utf8;
+        struct sl_client_ctx *client_ctx = (struct sl_client_ctx *)cli_ctx;
+
+        /* Check whether Client is connected or not? */
+        if(!(mqtt_client_is_connected(client_ctx->cli_hndl))) {
+                Uart_Write((uint8_t*)"mqtt client is not connected\n\r");
+                return ret;
+        }
+
+        STR2UTF_CONV(topic_utf8, topic);
+
+        /*Set up all variables to receive an ACK for the message to be sent*/
+        if(MQTT_QOS1 == qos[qos_level]) {
+                client_ctx->awaited_ack = MQTT_PUBACK;
+        } else if(MQTT_QOS2 == qos[qos_level]) {
+                client_ctx->awaited_ack = MQTT_PUBCOMP;
+        }
+        /*publish the message*/
+        ret = mqtt_client_pub_msg_send(client_ctx->cli_hndl, &topic_utf8,
+                                        (const uint8_t*)data, len,
+                                        qos[qos_level], retain);
+        if(ret < 0) {
+                Uart_Write((uint8_t*)"mqtt_client_pub_msg_send failed\n\r");
+                goto mqtt_pub_exit1;
+        }
+
+        if(MQTT_QOS0 != qos[qos_level]) {
+                if(true == client_ctx->blocking_send) {
+                        ACK_RX_SIGNAL_WAIT(&client_ctx->ack_sync_obj);
+                        if(MQTT_DISCONNECT == client_ctx->awaited_ack) {
+                                Uart_Write((uint8_t*)"MQTT_DISCONNECT\n\r");
+                                ret = -1;
+                        }
+                }
+        }
+
+mqtt_pub_exit1:
+        client_ctx->awaited_ack = 0;
+        return (ret < 0)? -1: 0;
+}
+
+}//namespace mbed_mqtt 
+
diff -r 241bff9fe406 -r a8c249046181 mqtt_V1/sl/sl_mqtt_server.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mqtt_V1/sl/sl_mqtt_server.cpp	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,180 @@
+/******************************************************************************
+*
+*   Copyright (C) 2014 Texas Instruments Incorporated
+*
+*   All rights reserved. Property of Texas Instruments Incorporated.
+*   Restricted rights to use, duplicate or disclose this code are
+*   granted through contract.
+*
+*   The program may not be used without the written permission of
+*   Texas Instruments Incorporated or against the terms and conditions
+*   stipulated in the agreement under which this program has been supplied,
+*   and under no circumstances can it be used with non-TI connectivity device.
+*
+******************************************************************************/
+#include "mbed.h"
+#include "mqtt_common.h"
+#include "sl_mqtt_server.h"
+#include "server_core.h"
+#include "client_mgmt.h"
+#include "server_util.h"
+#include "cc31xx_sl_net.h"
+#include "FreeRTOS.h"
+#include "osi.h"
+
+namespace mbed_mqtt {
+
+/*-------------------------------------------------------------------------
+ * MQTT Routines
+ *-------------------------------------------------------------------------
+ */
+OsiLockObj_t MutexLockObj;
+
+// wrapper function
+static void mutex_lock(void* mutex_hndl)
+{
+    osi_LockObjLock((OsiLockObj_t*)mutex_hndl, OSI_WAIT_FOREVER);
+}
+
+// wrapper function
+static void mutex_unlock(void* mutex_hndl)
+{
+    osi_LockObjUnlock((OsiLockObj_t*)mutex_hndl);
+}
+
+struct mqtt_server_lib_cfg server_cfg = {
+   0,
+   0,
+   &MutexLockObj,
+   mutex_lock,
+   mutex_unlock,
+   NULL             /*Debug print*/
+};
+
+struct mqtt_server_app_cfg app_config = {
+   NULL
+};
+
+
+/*Task Priority and Response Time*/
+uint32_t g_srvr_wait_secs,g_srvr_task_priority;
+struct device_net_services net_ops = {comm_open,tcp_send,tcp_recv,
+                                send_dest,recv_from,comm_close,
+                                tcp_listen,tcp_accept,tcp_select,rtc_secs};
+void VMqttServerRunTask(const signed char *pvParams);
+
+SlMqttServerCbs_t cbs_obj,*cbs_ptr=NULL;
+struct ctrl_struct{
+        const void* plugin_hndl;
+}app_hndl;
+
+
+uint16_t sl_server_connect_cb (const struct utf8_string *clientId,
+                const struct utf8_string *username,
+                const struct utf8_string *password,
+                void **app_usr)
+{
+        return( cbs_obj.sl_ExtLib_MqttConn((const char*)MQ_CONN_UTF8_BUF(clientId),
+                    MQ_CONN_UTF8_LEN(clientId), (const char*)MQ_CONN_UTF8_BUF(username),
+                    MQ_CONN_UTF8_LEN(username), (const char*)MQ_CONN_UTF8_BUF(password),
+                    MQ_CONN_UTF8_LEN(password), app_usr));
+}
+
+void sl_server_publish_cb(const struct utf8_string *topic,
+                const uint8_t *payload, uint32_t pay_len,
+                bool dup, uint8_t qos, bool retain)
+{
+        cbs_obj.sl_ExtLib_MqttRecv((const char*)MQ_CONN_UTF8_BUF(topic),
+               MQ_CONN_UTF8_LEN(topic), payload, pay_len, dup, qos, retain);
+}
+
+void sl_server_disconn_cb(const void *app_usr, bool due2err)
+{
+        cbs_obj.sl_ExtLib_MqttDisconn((void*)app_usr, due2err);
+}
+
+int32_t sl_ExtLib_MqttServerSend(const char *topic, const void *data, int32_t len,
+                               uint8_t qos, bool retain, uint32_t flags)
+{
+        struct utf8_string topic_utf8={NULL};
+        topic_utf8.buffer = (char*)topic;
+        topic_utf8.length = strlen(topic);
+        return( mqtt_server_app_pub_send(&topic_utf8,(const uint8_t*)data, len,
+                                         (enum mqtt_qos)qos, retain));
+}
+
+int32_t sl_ExtLib_MqttTopicEnroll(const char *topic)
+{
+        struct utf8_string topic_utf8={NULL};
+        topic_utf8.buffer = (char*)topic;
+        topic_utf8.length = strlen(topic);
+        return( mqtt_server_topic_enroll((void*)(app_hndl.plugin_hndl),
+                                         &topic_utf8,MQTT_QOS2));
+
+}
+
+int32_t sl_ExtLib_MqttTopicDisenroll(const char *topic)
+{
+        struct utf8_string topic_utf8={NULL};
+        topic_utf8.buffer = (char*)topic;
+        topic_utf8.length = strlen(topic);
+       return( mqtt_server_topic_disenroll((void*)&(app_hndl.plugin_hndl),
+                                           &topic_utf8));
+}
+
+struct mqtt_server_app_cbs server_appcallbacks =
+{
+        sl_server_connect_cb,
+        sl_server_publish_cb,
+        sl_server_disconn_cb
+};
+
+int32_t sl_ExtLib_MqttServerInit(const SlMqttServerCfg_t  *cfg,
+                               const SlMqttServerCbs_t  *app_cbs)
+{
+
+    int32_t ret;
+    
+    //valid loopback port has to be specified for correct operations
+    if(cfg->loopback_port == 0)
+    {
+        return -1;
+    }
+    server_cfg.listener_port=cfg->server_info.port_number;
+    server_cfg.debug_printf = cfg->dbg_print;
+    cbs_ptr=&cbs_obj;
+    memcpy(cbs_ptr,app_cbs,sizeof(SlMqttServerCbs_t ));
+   
+    g_srvr_task_priority=(uint32_t)cfg->rx_tsk_priority;
+    g_srvr_wait_secs=(uint32_t)cfg->resp_time;
+    ret = osi_LockObjCreate(&MutexLockObj);
+    if(!ret)
+    {
+        ret=mqtt_server_init(&server_cfg, &app_config);
+    }
+    else
+    { 
+        ret = osi_LockObjDelete(&MutexLockObj);
+        return(-1);
+    }
+    /* registering the device specific implementations for net operations */
+    mqtt_server_register_net_svc(&net_ops);
+    
+    /* registering the apps callbacks */
+    app_hndl.plugin_hndl = mqtt_server_app_register(&server_appcallbacks, "temp");
+    
+    /* start the Server Run task */
+    
+//    osi_TaskCreate(VMqttServerRunTask, (const signed char *) "MQTTServerRun", 2048, NULL, g_srvr_task_priority, NULL );
+        
+    return ret;
+}
+
+void VMqttServerRunTask(void *pvParams)
+{
+    mqtt_server_run(g_srvr_wait_secs);
+}
+
+}//namespace mbed_mqtt 
+
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2.lib
--- a/simplelink_V2.lib	Sat Jun 06 14:06:49 2015 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1 +0,0 @@
-http://developer.mbed.org/users/dflet/code/simplelink_V2/#9b68e650b3f6
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/G_functions/fPtr_func.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/G_functions/fPtr_func.cpp	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,1104 @@
+/*
+ *  - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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 "simplelink_V2/cc3100_simplelink.h"
+
+#include "simplelink_V2/cc3100.h"
+#include "simplelink_V2/cc3100_driver.h"
+#include "simplelink_V2/G_functions/fPtr_func.h"
+#include "simplelink_V2/cc3100_nonos.h"
+#include "cli_uart.h"
+#include "myBoardInit.h"
+
+#include "cc3100_trace.h"
+    
+using namespace mbed_cc3100;
+    
+#if (THIS_BOARD == MBED_BOARD_LPC1768)    
+cc3100 _cc3100_(p16, p17, p9, p10, p8, SPI(p5, p6, p7));//LPC1768  irq, nHib, cs, mosi, miso, sck
+#elif (THIS_BOARD == LPCXpresso4337)
+cc3100 _cc3100_(P2_12, P2_9, P2_2, P3_5, P1_2, SPI(P1_4, P1_3, PF_4));//LPCXpresso4337  irq, nHib, cs, mosi, miso, sck
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif 
+
+#define PRINT_BUF_LEN    128
+extern int8_t print_buf[PRINT_BUF_LEN];
+
+/* General Events handling*/
+#if defined (EXT_LIB_REGISTERED_GENERAL_EVENTS)
+
+typedef _SlEventPropogationStatus_e (*general_callback) (SlDeviceEvent_t *);
+
+static const general_callback  general_callbacks[] =
+{
+#ifdef SlExtLib1GeneralEventHandler
+    SlExtLib1GeneralEventHandler,
+#endif
+
+#ifdef SlExtLib2GeneralEventHandler
+    SlExtLib2GeneralEventHandler,
+#endif
+
+#ifdef SlExtLib3GeneralEventHandler
+    SlExtLib3GeneralEventHandler,
+#endif
+
+#ifdef SlExtLib4GeneralEventHandler
+    SlExtLib4GeneralEventHandler,
+#endif
+
+#ifdef SlExtLib5GeneralEventHandler
+    SlExtLib5GeneralEventHandler,
+#endif
+};
+
+#undef _SlDrvHandleGeneralEvents
+
+/********************************************************************
+  _SlDrvHandleGeneralEvents
+  Iterates through all the general(device) event handlers which are
+  registered by   the external libs/user application.
+*********************************************************************/
+void _SlDrvHandleGeneralEvents(SlDeviceEvent_t *slGeneralEvent)
+{
+    uint8_t i;
+
+    /* Iterate over all the extenal libs handlers */
+    for ( i = 0 ; i < sizeof(general_callbacks)/sizeof(general_callbacks[0]) ; i++ )
+    {
+        if (EVENT_PROPAGATION_BLOCK == general_callbacks[i](slGeneralEvent) )
+        {
+            /* exit immediately and do not call the user specific handler as well */
+            return;
+        }
+    }
+
+/* At last call the Application specific handler if registered */
+#ifdef sl_GeneralEvtHdlr
+    sl_GeneralEvtHdlr(slGeneralEvent);
+#endif
+
+}
+#endif
+
+
+
+/* WLAN Events handling*/
+
+#if defined (EXT_LIB_REGISTERED_WLAN_EVENTS)
+
+typedef _SlEventPropogationStatus_e (*wlan_callback) (SlWlanEvent_t *);
+
+static wlan_callback  wlan_callbacks[] =
+{
+#ifdef SlExtLib1WlanEventHandler
+        SlExtLib1WlanEventHandler,
+#endif
+
+#ifdef SlExtLib2WlanEventHandler
+        SlExtLib2WlanEventHandler,
+#endif
+
+#ifdef SlExtLib3WlanEventHandler
+        SlExtLib3WlanEventHandler,
+#endif
+
+#ifdef SlExtLib4WlanEventHandler
+        SlExtLib4WlanEventHandler,
+#endif
+
+#ifdef SlExtLib5WlanEventHandler
+        SlExtLib5WlanEventHandler,
+#endif
+};
+
+#undef _SlDrvHandleWlanEvents
+
+/***********************************************************
+  _SlDrvHandleWlanEvents
+  Iterates through all the wlan event handlers which are
+  registered by the external libs/user application.
+************************************************************/
+void _SlDrvHandleWlanEvents(SlWlanEvent_t *slWlanEvent)
+{
+    uint8_t i;
+
+    /* Iterate over all the extenal libs handlers */
+    for ( i = 0 ; i < sizeof(wlan_callbacks)/sizeof(wlan_callbacks[0]) ; i++ )
+    {
+        if ( EVENT_PROPAGATION_BLOCK == wlan_callbacks[i](slWlanEvent) )
+        {
+            /* exit immediately and do not call the user specific handler as well */
+            return;
+        }
+    }
+
+/* At last call the Application specific handler if registered */
+#ifdef sl_WlanEvtHdlr
+    sl_WlanEvtHdlr(slWlanEvent);
+#endif
+
+}
+#endif
+
+
+/* NetApp Events handling */
+#if defined (EXT_LIB_REGISTERED_NETAPP_EVENTS)
+
+typedef _SlEventPropogationStatus_e (*netApp_callback) (SlNetAppEvent_t *);
+
+static const netApp_callback  netApp_callbacks[] =
+{
+#ifdef SlExtLib1NetAppEventHandler
+     SlExtLib1NetAppEventHandler,
+#endif
+
+#ifdef SlExtLib2NetAppEventHandler
+     SlExtLib2NetAppEventHandler,
+#endif
+
+#ifdef SlExtLib3NetAppEventHandler
+     SlExtLib3NetAppEventHandler,
+#endif
+
+#ifdef SlExtLib4NetAppEventHandler
+     SlExtLib4NetAppEventHandler,
+#endif
+
+#ifdef SlExtLib5NetAppEventHandler
+     SlExtLib5NetAppEventHandler,
+#endif
+};
+
+#undef _SlDrvHandleNetAppEvents
+
+/************************************************************
+  _SlDrvHandleNetAppEvents
+  Iterates through all the net app event handlers which are
+  registered by   the external libs/user application.
+************************************************************/
+void _SlDrvHandleNetAppEvents(SlNetAppEvent_t *slNetAppEvent)
+{
+    uint8_t i;
+
+    /* Iterate over all the extenal libs handlers */
+    for ( i = 0 ; i < sizeof(netApp_callbacks)/sizeof(netApp_callbacks[0]) ; i++ )
+    {
+        if (EVENT_PROPAGATION_BLOCK == netApp_callbacks[i](slNetAppEvent) )
+        {
+            /* exit immediately and do not call the user specific handler as well */
+            return;
+        }
+    }
+
+/* At last call the Application specific handler if registered */
+#ifdef sl_NetAppEvtHdlr
+    sl_NetAppEvtHdlr(slNetAppEvent);
+#endif
+
+}
+#endif
+
+
+/* Http Server Events handling */
+#if defined (EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS)
+
+typedef _SlEventPropogationStatus_e (*httpServer_callback) (SlHttpServerEvent_t*, SlHttpServerResponse_t*);
+
+static const httpServer_callback  httpServer_callbacks[] =
+{
+#ifdef SlExtLib1HttpServerEventHandler
+        SlExtLib1HttpServerEventHandler,
+#endif
+
+#ifdef SlExtLib2HttpServerEventHandler
+        SlExtLib2HttpServerEventHandler,
+#endif
+
+#ifdef SlExtLib3HttpServerEventHandler
+        SlExtLib3HttpServerEventHandler,
+#endif
+
+#ifdef SlExtLib4HttpServerEventHandler
+        SlExtLib4HttpServerEventHandler,
+#endif
+
+#ifdef SlExtLib5HttpServerEventHandler
+      SlExtLib5HttpServerEventHandler,
+#endif
+};
+
+#undef _SlDrvHandleHttpServerEvents
+
+/*******************************************************************
+  _SlDrvHandleHttpServerEvents
+  Iterates through all the http server event handlers which are
+  registered by the external libs/user application.
+********************************************************************/
+void _SlDrvHandleHttpServerEvents(SlHttpServerEvent_t *slHttpServerEvent, SlHttpServerResponse_t *slHttpServerResponse)
+{
+    _u8 i;
+
+    /* Iterate over all the external libs handlers */
+    for ( i = 0 ; i < sizeof(httpServer_callbacks)/sizeof(httpServer_callbacks[0]) ; i++ )
+    {
+        if ( EVENT_PROPAGATION_BLOCK == httpServer_callbacks[i](slHttpServerEvent, slHttpServerResponse) )
+        {
+            /* exit immediately and do not call the user specific handler as well */
+            return;
+        }
+    }
+
+/* At last call the Application specific handler if registered */
+#ifdef sl_HttpServerCallback
+    sl_HttpServerCallback(slHttpServerEvent, slHttpServerResponse);
+#endif
+
+}
+#endif
+
+
+/* Socket Events */
+#if defined (EXT_LIB_REGISTERED_SOCK_EVENTS)
+
+typedef _SlEventPropogationStatus_e (*sock_callback) (SlSockEvent_t *);
+
+static const sock_callback  sock_callbacks[] =
+{
+#ifdef SlExtLib1SockEventHandler
+        SlExtLib1SockEventHandler,
+#endif
+
+#ifdef SlExtLib2SockEventHandler
+        SlExtLib2SockEventHandler,
+#endif
+
+#ifdef SlExtLib3SockEventHandler
+        SlExtLib3SockEventHandler,
+#endif
+
+#ifdef SlExtLib4SockEventHandler
+        SlExtLib4SockEventHandler,
+#endif
+
+#ifdef SlExtLib5SockEventHandler
+        SlExtLib5SockEventHandler,
+#endif
+};
+
+/*************************************************************
+  _SlDrvHandleSockEvents
+  Iterates through all the socket event handlers which are
+  registered by the external libs/user application.
+**************************************************************/
+void _SlDrvHandleSockEvents(SlSockEvent_t *slSockEvent)
+{
+    uint8_t i;
+
+    /* Iterate over all the external libs handlers */
+    for ( i = 0 ; i < sizeof(sock_callbacks)/sizeof(sock_callbacks[0]) ; i++ )
+    {
+        if ( EVENT_PROPAGATION_BLOCK == sock_callbacks[i](slSockEvent) )
+        {
+            /* exit immediately and do not call the user specific handler as well */
+            return;
+        }
+    }
+
+/* At last call the Application specific handler if registered */
+#ifdef sl_SockEvtHdlr
+    sl_SockEvtHdlr(slSockEvent);
+#endif
+
+}
+
+#endif   
+
+/*!
+    \brief This function handles ping report events
+
+    \param[in]      pPingReport holds the ping report statistics
+
+    \return         None
+
+    \note
+
+    \warning
+*/
+void SimpleLinkPingReport(SlPingReport_t *pPingReport)
+{
+    _cc3100_.SET_STATUS_BIT(g_Status, STATUS_BIT_PING_DONE);
+
+    if(pPingReport == NULL)
+        Uart_Write((uint8_t*)" [PING REPORT] NULL Pointer Error\r\n");
+
+    g_PingPacketsRecv = pPingReport->PacketsReceived;
+}
+
+
+/*******************************************************************************/
+/*   _sl_HandleAsync_Accept */
+/*******************************************************************************/
+#ifndef SL_TINY_EXT
+void _sl_HandleAsync_Accept(void *pVoidBuf)
+{
+    _SocketAddrResponse_u *pMsgArgs = (_SocketAddrResponse_u *)_SL_RESP_ARGS_START(pVoidBuf);
+
+    _cc3100_._driver._SlDrvProtectionObjLockWaitForever();
+
+    VERIFY_PROTOCOL(( pMsgArgs->IpV4.sd & BSD_SOCKET_ID_MASK) <= SL_MAX_SOCKETS);
+    VERIFY_SOCKET_CB(NULL != g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs);
+
+    memcpy(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs, pMsgArgs,sizeof(_SocketAddrResponse_u));
+    _cc3100_._driver._SlDrvSyncObjSignal(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj);
+
+    _cc3100_._driver._SlDrvProtectionObjUnLock();
+    return;
+}
+
+/*******************************************************************************/
+/*   _sl_HandleAsync_Connect */
+/*******************************************************************************/
+void _sl_HandleAsync_Connect(void *pVoidBuf)
+{
+    _SocketResponse_t *pMsgArgs = (_SocketResponse_t *)_SL_RESP_ARGS_START(pVoidBuf);
+
+    _cc3100_._driver._SlDrvProtectionObjLockWaitForever();
+
+    VERIFY_PROTOCOL((pMsgArgs->sd & BSD_SOCKET_ID_MASK) <= SL_MAX_SOCKETS);
+    VERIFY_SOCKET_CB(NULL != g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs);
+
+    ((_SocketResponse_t *)(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs))->sd = pMsgArgs->sd;
+    ((_SocketResponse_t *)(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs))->statusOrLen = pMsgArgs->statusOrLen;
+
+    _cc3100_._driver._SlDrvSyncObjSignal(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj);
+    _cc3100_._driver._SlDrvProtectionObjUnLock();
+    return;
+}
+
+/*******************************************************************************/
+/*   _sl_HandleAsync_Select */
+/*******************************************************************************/
+void _sl_HandleAsync_Select(void *pVoidBuf)
+{
+    _SelectAsyncResponse_t     *pMsgArgs   = (_SelectAsyncResponse_t *)_SL_RESP_ARGS_START(pVoidBuf);
+
+    _cc3100_._driver._SlDrvProtectionObjLockWaitForever();    
+
+    VERIFY_SOCKET_CB(NULL != g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs);
+
+    memcpy(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs, pMsgArgs, sizeof(_SelectAsyncResponse_t));
+
+    _cc3100_._driver._SlDrvSyncObjSignal(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj);
+    _cc3100_._driver._SlDrvProtectionObjUnLock();
+
+    return;
+}
+
+#endif
+
+/******************************************************************************/
+/*  _sl_HandleAsync_DnsGetHostByName */
+/******************************************************************************/
+void _sl_HandleAsync_DnsGetHostByName(void *pVoidBuf)
+{
+    _GetHostByNameIPv4AsyncResponse_t *pMsgArgs = (_GetHostByNameIPv4AsyncResponse_t *)_SL_RESP_ARGS_START(pVoidBuf);
+
+    _cc3100_._driver._SlDrvProtectionObjLockWaitForever();
+
+    VERIFY_SOCKET_CB(NULL != g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs);
+
+    /*IPv6 */
+    if(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].AdditionalData & SL_NETAPP_FAMILY_MASK) {
+        memcpy(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs, pMsgArgs, sizeof(_GetHostByNameIPv6AsyncResponse_t));
+    }
+    /*IPv4 */
+    else 
+    {
+        memcpy(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs, pMsgArgs, sizeof(_GetHostByNameIPv4AsyncResponse_t));
+    }
+    
+    _cc3100_._driver._SlDrvSyncObjSignal(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj);
+    _cc3100_._driver._SlDrvProtectionObjUnLock();
+    
+    return;
+}
+
+/******************************************************************************/
+
+/******************************************************************************
+    _sl_HandleAsync_DnsGetHostByService
+
+    CALLER          NWP - Async event on sl_DnsGetHostByService with IPv4 Family
+
+
+    DESCRIPTION:
+
+                    Async event on sl_DnsGetHostByService command with IPv4 Family.
+                    Return service attributes like IP address, port and text according to service name.
+                    The user sets a service name Full/Part (see example below), and should get the:
+                    1. IP of the service
+                    2. The port of service.
+                    3. The text of service.
+
+                    Hence it can make a connection to the specific service and use it.
+                    It is similar to get host by name method.
+
+                    It is done by a single shot query with PTR type on the service name.
+
+
+
+                    Note:
+                    1. The return's attributes are belonged to first service that is found.
+                    It can be other services with the same service name will response to
+                    the query. The results of these responses are saved in the peer cache of the NWP, and
+                    should be read by another API.
+
+
+        PARAMETERS:
+
+                  pVoidBuf - is point to opcode of the event.
+                  it contains the outputs that are given to the user
+
+                  outputs description:
+
+                   1.out_pAddr[]                    - output: Contain the IP address of the service.
+                   2.out_pPort                      - output: Contain the port of the service.
+                   3.inout_TextLen                  - Input:  Contain the max length of the text that the user wants to get.
+                                                              it means that if the test of service is bigger that its value than
+                                                              the text is cut to inout_TextLen value.
+                                                      Output: Contain the length of the text that is returned. Can be full text or part
+                                                              of the text (see above).
+
+                   4.out_pText                      - Contain the text of the service (full or part see above- inout_TextLen description).
+
+  *
+
+
+    RETURNS:        success or fail.
+
+******************************************************************************/
+#ifndef SL_TINY_EXT
+void _sl_HandleAsync_DnsGetHostByService(void *pVoidBuf)
+{
+    _GetHostByServiceAsyncResponse_t* Res;
+    uint16_t TextLen;
+    uint16_t UserTextLen;
+
+    /*pVoidBuf - is point to opcode of the event.*/
+
+    /*set pMsgArgs to point to the attribute of the event.*/
+    _GetHostByServiceIPv4AsyncResponse_t *pMsgArgs = (_GetHostByServiceIPv4AsyncResponse_t *)_SL_RESP_ARGS_START(pVoidBuf);
+
+    VERIFY_SOCKET_CB(NULL != g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs);
+
+    /*IPv6*/
+    if(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].AdditionalData & SL_NETAPP_FAMILY_MASK) {
+        return;
+    }
+    /*IPv4*/
+    else {
+        /*************************************************************************************************
+
+        1. Copy the attribute part of the evnt to the attribute part of the response
+        memcpy(g_pCB->GetHostByServiceCB.pAsyncRsp, pMsgArgs, sizeof(_GetHostByServiceIPv4AsyncResponse_t));
+
+        set to TextLen the text length of the service.*/
+        TextLen = pMsgArgs->TextLen;
+
+        /*Res pointed to mDNS global object struct */
+        Res = (_GetHostByServiceAsyncResponse_t*)g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs;
+
+
+
+        /*It is 4 bytes so we avoid from memcpy*/
+        Res->out_pAddr[0]   = pMsgArgs->Address;
+        Res->out_pPort[0]   = pMsgArgs->Port;
+        Res->Status         = pMsgArgs->Status;
+
+        /*set to TextLen the text length of the user (input fromthe user).*/
+        UserTextLen = Res->inout_TextLen[0];
+
+        /*Cut the service text if the user requested for smaller text.*/
+        UserTextLen = (TextLen <= UserTextLen) ? TextLen : UserTextLen;
+        Res->inout_TextLen[0] = UserTextLen ;
+
+        /**************************************************************************************************
+
+        2. Copy the payload part of the evnt (the text) to the payload part of the response
+        the lenght of the copy is according to the text length in the attribute part. */
+
+
+        memcpy(Res->out_pText,
+                  (int8_t *)(& pMsgArgs[1]),   /* & pMsgArgs[1] -> 1st byte after the fixed header = 1st byte of variable text.*/
+                  UserTextLen);
+
+
+        /**************************************************************************************************/
+        _cc3100_._driver._SlDrvSyncObjSignal(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj);
+        return;
+    }
+}
+#endif
+
+/*****************************************************************************/
+/*  _sl_HandleAsync_PingResponse */
+/*****************************************************************************/
+#ifndef SL_TINY_EXT
+void _sl_HandleAsync_PingResponse(void *pVoidBuf)
+{
+    _PingReportResponse_t *pMsgArgs  = (_PingReportResponse_t *)_SL_RESP_ARGS_START(pVoidBuf);
+    SlPingReport_t pingReport;
+
+    if(pPingCallBackFunc) {
+        _cc3100_._netapp.CopyPingResultsToReport(pMsgArgs,&pingReport);
+        pPingCallBackFunc(&pingReport);
+    } else {
+
+        _cc3100_._driver._SlDrvProtectionObjLockWaitForever();
+        VERIFY_SOCKET_CB(NULL != g_pCB->PingCB.PingAsync.pAsyncRsp);
+
+        if (NULL != g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs) {
+            memcpy(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs, pMsgArgs, sizeof(_PingReportResponse_t));
+            _cc3100_._driver._SlDrvSyncObjSignal(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj);
+        }
+        _cc3100_._driver._SlDrvProtectionObjUnLock();
+    }
+    return;
+}
+#endif
+
+/* ******************************************************************************/
+/*  _SlDrvMsgReadSpawnCtx                                                       */
+/* ******************************************************************************/
+
+_SlReturnVal_t _SlDrvMsgReadSpawnCtx(void *pValue)
+{
+//    Uart_Write((uint8_t*)"\n\r _SlDrvMsgReadSpawnCtx \n\r");
+#ifdef SL_POLLING_MODE_USED
+    int16_t retCode = OSI_OK;
+    //  for polling based systems 
+    do {
+        retCode = _cc3100_->_nonos.sl_LockObjLock(&g_pCB->GlobalLockObj, 0);
+        if ( OSI_OK != retCode ) {
+            if (TRUE == g_pCB->IsCmdRespWaited) {
+                OSI_RET_OK_CHECK( _cc3100_->_nonos.sl_SyncObjSignal(&g_pCB->CmdSyncObj) );
+                return SL_RET_CODE_OK;
+            }
+        }
+
+    } while (OSI_OK != retCode);
+
+#else
+    
+//    OSI_RET_OK_CHECK(_cc3100_->_nonos.sl_LockObjLock(&g_pCB->GlobalLockObj, NON_OS_LOCK_OBJ_UNLOCK_VALUE, NON_OS_LOCK_OBJ_LOCK_VALUE, SL_OS_WAIT_FOREVER) );
+    _cc3100_._driver._SlDrvObjLockWaitForever(&g_pCB->GlobalLockObj);
+    
+#endif
+    
+    g_pCB->FunctionParams.AsyncExt.pAsyncBuf = NULL;//  buffer must be allocated by _SlDrvMsgRead 
+    g_pCB->FunctionParams.AsyncExt.AsyncEvtHandler= NULL;
+    g_pCB->FunctionParams.AsyncExt.RxMsgClass = CMD_RESP_CLASS;// init to illegal value and verify it's overwritten with the valid one 
+
+    //  Messages might have been read by CmdResp context. Therefore after 
+    //  getting LockObj, check again where the Pending Rx Msg is still present. 
+    if(FALSE == (_cc3100_._driver._SL_PENDING_RX_MSG(g_pCB))) {
+        _cc3100_._driver._SlDrvObjUnLock(&g_pCB->GlobalLockObj);
+//        OSI_RET_OK_CHECK(_cc3100_->_nonos.sl_LockObjUnlock(&g_pCB->GlobalLockObj, NON_OS_LOCK_OBJ_UNLOCK_VALUE));
+        return SL_RET_CODE_OK;
+    }
+    
+    VERIFY_RET_OK(_cc3100_._driver._SlDrvMsgRead());
+    
+    g_pCB->RxDoneCnt++;
+
+    switch(g_pCB->FunctionParams.AsyncExt.RxMsgClass) {
+        case ASYNC_EVT_CLASS:
+            //  If got here and protected by LockObj a message is waiting  
+            //  to be read 
+            VERIFY_PROTOCOL(NULL != g_pCB->FunctionParams.AsyncExt.pAsyncBuf);
+            
+            _cc3100_._driver._SlAsyncEventGenericHandler();
+            
+#if (SL_MEMORY_MGMT == SL_MEMORY_MGMT_STATIC)
+            g_pCB->FunctionParams.AsyncExt.pAsyncBuf = NULL;
+#else
+            free(g_pCB->FunctionParams.AsyncExt.pAsyncBuf);
+#endif
+            break;
+        case DUMMY_MSG_CLASS:
+        case RECV_RESP_CLASS:
+            // These types are legal in this context. Do nothing 
+            break;
+        case CMD_RESP_CLASS:
+            // Command response is illegal in this context. 
+            // No 'break' here: Assert! 
+        default:
+            VERIFY_PROTOCOL(0);
+    }
+    
+    _cc3100_._driver._SlDrvObjUnLock(&g_pCB->GlobalLockObj);
+//    OSI_RET_OK_CHECK(_cc3100_->_nonos.sl_LockObjUnlock(&g_pCB->GlobalLockObj, NON_OS_LOCK_OBJ_UNLOCK_VALUE));
+    
+    return(SL_RET_CODE_OK);   
+
+}
+
+/***************************************************************************
+_sl_HandleAsync_Stop - handles stop signalling to
+a waiting object
+****************************************************************************/
+void _sl_HandleAsync_Stop(void *pVoidBuf)
+{
+    _BasicResponse_t *pMsgArgs = (_BasicResponse_t *)_SL_RESP_ARGS_START(pVoidBuf);
+
+    VERIFY_SOCKET_CB(NULL != g_pCB->StopCB.pAsyncRsp);
+
+    _cc3100_._driver._SlDrvProtectionObjLockWaitForever();
+
+    memcpy(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs, pMsgArgs, sizeof(_BasicResponse_t));
+    _cc3100_._driver._SlDrvSyncObjSignal(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj);
+    _cc3100_._driver._SlDrvProtectionObjUnLock();
+    return;
+}
+
+/******************************************************************************
+_SlDrvDeviceEventHandler - handles internally device async events
+******************************************************************************/
+void _SlDrvDeviceEventHandler(void *pArgs)
+{
+    _SlResponseHeader_t *pHdr = (_SlResponseHeader_t *)pArgs;
+   
+    switch(pHdr->GenHeader.Opcode) {
+        case SL_OPCODE_DEVICE_INITCOMPLETE:
+            _cc3100_._sl_HandleAsync_InitComplete(pHdr);
+            
+            break;
+        case SL_OPCODE_DEVICE_STOP_ASYNC_RESPONSE:
+            _sl_HandleAsync_Stop(pHdr);
+            
+            break;
+        
+
+        case SL_OPCODE_DEVICE_ABORT:
+            {
+#if defined (sl_GeneralEvtHdlr) || defined(EXT_LIB_REGISTERED_GENERAL_EVENTS)
+                SlDeviceEvent_t      devHandler;
+                devHandler.Event = SL_DEVICE_ABORT_ERROR_EVENT; 
+                devHandler.EventData.deviceReport.AbortType = *((uint32_t*)pArgs + 2);
+                devHandler.EventData.deviceReport.AbortData = *((uint32_t*)pArgs + 3);
+                _SlDrvHandleGeneralEvents(&devHandler);
+#endif      
+            }
+        break;    
+        case  SL_OPCODE_DEVICE_DEVICEASYNCFATALERROR:
+#if defined (sl_GeneralEvtHdlr) || defined(EXT_LIB_REGISTERED_GENERAL_EVENTS)
+        {
+            _BasicResponse_t *pMsgArgs = (_BasicResponse_t *)_SL_RESP_ARGS_START(pHdr);
+            SlDeviceEvent_t devHandler;
+            devHandler.Event = SL_DEVICE_FATAL_ERROR_EVENT;
+            devHandler.EventData.deviceEvent.status = pMsgArgs->status & 0xFF;
+            devHandler.EventData.deviceEvent.sender = (SlErrorSender_e)((pMsgArgs->status >> 8) & 0xFF);
+            _SlDrvHandleGeneralEvents(&devHandler);
+        }
+#endif
+        break;
+        default:
+            SL_ERROR_TRACE2(MSG_306, "ASSERT: _SlDrvDeviceEventHandler : invalid opcode = 0x%x = %i", pHdr->GenHeader.Opcode, pHdr->GenHeader.Opcode);
+            //printf("ASSERT: _SlDrvDeviceEventHandler : invalid opcode = 0x%x = %i", pHdr->GenHeader.Opcode, pHdr->GenHeader.Opcode);
+            
+    }
+}
+
+/*****************************************************************************/
+/* _SlDrvNetAppEventHandler */
+/*****************************************************************************/
+void _SlDrvNetAppEventHandler(void *pArgs)
+{
+    _SlResponseHeader_t *pHdr = (_SlResponseHeader_t *)pArgs;
+#if defined(sl_HttpServerCallback) || defined(EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS)
+    SlHttpServerEvent_t     httpServerEvent;    
+    SlHttpServerResponse_t  httpServerResponse;
+#endif
+    switch(pHdr->GenHeader.Opcode) {
+        case SL_OPCODE_NETAPP_DNSGETHOSTBYNAMEASYNCRESPONSE:
+        case SL_OPCODE_NETAPP_DNSGETHOSTBYNAMEASYNCRESPONSE_V6:
+            _sl_HandleAsync_DnsGetHostByName(pArgs);
+            break;
+#ifndef SL_TINY_EXT             
+        case SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICEASYNCRESPONSE:
+        case SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICEASYNCRESPONSE_V6:
+            _sl_HandleAsync_DnsGetHostByService(pArgs);
+            break;
+        case SL_OPCODE_NETAPP_PINGREPORTREQUESTRESPONSE:
+            _sl_HandleAsync_PingResponse(pArgs);
+            break;
+#endif
+
+#if defined(sl_HttpServerCallback) || defined(EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS)            
+        case SL_OPCODE_NETAPP_HTTPGETTOKENVALUE: {
+
+            uint8_t *pTokenName;
+            slHttpServerData_t Token_value;
+            sl_NetAppHttpServerGetToken_t *httpGetToken = (sl_NetAppHttpServerGetToken_t *)_SL_RESP_ARGS_START(pHdr);
+            pTokenName = (uint8_t *)((sl_NetAppHttpServerGetToken_t *)httpGetToken + 1);
+
+            httpServerResponse.Response = SL_NETAPP_HTTPSETTOKENVALUE;
+            httpServerResponse.ResponseData.token_value.len = MAX_TOKEN_VALUE_LEN;
+
+            /* Reuse the async buffer for getting the token value response from the user */
+            httpServerResponse.ResponseData.token_value.data = (uint8_t *)_SL_RESP_ARGS_START(pHdr) + MAX_TOKEN_NAME_LEN;
+            httpServerEvent.Event = SL_NETAPP_HTTPGETTOKENVALUE_EVENT;
+
+            httpServerEvent.EventData.httpTokenName.len = httpGetToken->token_name_len;
+            httpServerEvent.EventData.httpTokenName.data = pTokenName;
+
+            Token_value.token_name =  pTokenName;
+
+            _SlDrvHandleHttpServerEvents (&httpServerEvent, &httpServerResponse);
+
+            Token_value.value_len = httpServerResponse.ResponseData.token_value.len;
+            Token_value.name_len = httpServerEvent.EventData.httpTokenName.len;
+
+            Token_value.token_value = httpServerResponse.ResponseData.token_value.data;
+
+
+            _cc3100_._netapp.sl_NetAppSendTokenValue(&Token_value);
+#endif
+        }
+        break;
+
+        case SL_OPCODE_NETAPP_HTTPPOSTTOKENVALUE: {
+#ifdef sl_HttpServerCallback
+            uint8_t *pPostParams;
+
+            sl_NetAppHttpServerPostToken_t *httpPostTokenArgs = (sl_NetAppHttpServerPostToken_t *)_SL_RESP_ARGS_START(pHdr);
+            pPostParams = (uint8_t *)((sl_NetAppHttpServerPostToken_t *)httpPostTokenArgs + 1);
+
+            httpServerEvent.Event = SL_NETAPP_HTTPPOSTTOKENVALUE_EVENT;
+
+            httpServerEvent.EventData.httpPostData.action.len = httpPostTokenArgs->post_action_len;
+            httpServerEvent.EventData.httpPostData.action.data = pPostParams;
+            pPostParams+=httpPostTokenArgs->post_action_len;
+
+            httpServerEvent.EventData.httpPostData.token_name.len = httpPostTokenArgs->token_name_len;
+            httpServerEvent.EventData.httpPostData.token_name.data = pPostParams;
+            pPostParams+=httpPostTokenArgs->token_name_len;
+
+            httpServerEvent.EventData.httpPostData.token_value.len = httpPostTokenArgs->token_value_len;
+            httpServerEvent.EventData.httpPostData.token_value.data = pPostParams;
+
+            httpServerResponse.Response = SL_NETAPP_RESPONSE_NONE;
+
+
+            _SlDrvHandleHttpServerEvents (&httpServerEvent, &httpServerResponse);
+        }
+        break;
+#endif        
+        default:
+            SL_ERROR_TRACE2(MSG_305, "ASSERT: _SlDrvNetAppEventHandler : invalid opcode = 0x%x = %i", pHdr->GenHeader.Opcode, pHdr->GenHeader.Opcode);
+            VERIFY_PROTOCOL(0);
+    }
+}
+
+/*
+ * ASYNCHRONOUS EVENT HANDLERS -- Start
+ */
+
+/*!
+    \brief This function handles WLAN events
+
+    \param[in]      pWlanEvent is the event passed to the handler
+
+    \return         None
+
+    \note
+
+    \warning
+*/
+#if (defined(sl_WlanEvtHdlr))
+void SimpleLinkWlanEventHandler(SlWlanEvent_t *pWlanEvent)
+{
+    unsigned char  g_ucConnectionSSID[32+1]; //Connection SSID
+    unsigned char  g_ucConnectionBSSID[6]; //Connection BSSID
+    
+    if(pWlanEvent == NULL)
+        Uart_Write((uint8_t*)" [WLAN EVENT] NULL Pointer Error \n\r");
+
+    switch(pWlanEvent->Event) {
+        case SL_WLAN_CONNECT_EVENT: {
+            _cc3100_.SET_STATUS_BIT(g_Status, STATUS_BIT_CONNECTION);
+            
+            // Copy new connection SSID and BSSID to global parameters
+            memcpy(g_ucConnectionSSID,pWlanEvent->EventData.
+                   STAandP2PModeWlanConnected.ssid_name,
+                   pWlanEvent->EventData.STAandP2PModeWlanConnected.ssid_len);
+            memcpy(g_ucConnectionBSSID,
+                   pWlanEvent->EventData.STAandP2PModeWlanConnected.bssid,
+                   SL_BSSID_LENGTH);
+            
+            memset(print_buf, 0x00, PRINT_BUF_LEN);
+            sprintf((char*) print_buf, "[WLAN EVENT] STA Connected to the AP: %s ,""BSSID: %x:%x:%x:%x:%x:%x\n\r",
+                       g_ucConnectionSSID,g_ucConnectionBSSID[0],
+                       g_ucConnectionBSSID[1],g_ucConnectionBSSID[2],
+                       g_ucConnectionBSSID[3],g_ucConnectionBSSID[4],
+                       g_ucConnectionBSSID[5]);
+            Uart_Write((uint8_t *) print_buf);
+            /*
+             * Information about the connected AP (like name, MAC etc) will be
+             * available in 'slWlanConnectAsyncResponse_t' - Applications
+             * can use it if required
+             *
+             * slWlanConnectAsyncResponse_t *pEventData = NULL;
+             * pEventData = &pWlanEvent->EventData.STAandP2PModeWlanConnected;
+             *
+             */
+        }
+        break;
+
+        case SL_WLAN_DISCONNECT_EVENT: {
+            slWlanConnectAsyncResponse_t*  pEventData = NULL;
+
+            _cc3100_.CLR_STATUS_BIT(g_Status, STATUS_BIT_CONNECTION);
+            _cc3100_.CLR_STATUS_BIT(g_Status, STATUS_BIT_IP_ACQUIRED);
+
+            pEventData = &pWlanEvent->EventData.STAandP2PModeDisconnected;
+
+            /* If the user has initiated 'Disconnect' request, 'reason_code' is SL_USER_INITIATED_DISCONNECTION */
+            if(SL_USER_INITIATED_DISCONNECTION == pEventData->reason_code) {
+                memset(print_buf, 0x00, PRINT_BUF_LEN);
+                sprintf((char*) print_buf, "[WLAN EVENT]Device disconnected from the AP: %s,"
+                    "BSSID: %x:%x:%x:%x:%x:%x on application's request \n\r",
+                           g_ucConnectionSSID,g_ucConnectionBSSID[0],
+                           g_ucConnectionBSSID[1],g_ucConnectionBSSID[2],
+                           g_ucConnectionBSSID[3],g_ucConnectionBSSID[4],
+                           g_ucConnectionBSSID[5]);
+                Uart_Write((uint8_t *) print_buf);
+            } else {
+                memset(print_buf, 0x00, PRINT_BUF_LEN);
+                sprintf((char*) print_buf, "[WLAN ERROR]Device disconnected from the AP AP: %s,"
+                        "BSSID: %x:%x:%x:%x:%x:%x on an ERROR..!! \n\r",
+                           g_ucConnectionSSID,g_ucConnectionBSSID[0],
+                           g_ucConnectionBSSID[1],g_ucConnectionBSSID[2],
+                           g_ucConnectionBSSID[3],g_ucConnectionBSSID[4],
+                           g_ucConnectionBSSID[5]);
+                Uart_Write((uint8_t *) print_buf);
+            }
+            memset(g_ucConnectionSSID,0,sizeof(g_ucConnectionSSID));
+            memset(g_ucConnectionBSSID,0,sizeof(g_ucConnectionBSSID));
+        }
+        break;
+
+        case SL_WLAN_STA_CONNECTED_EVENT: {
+            _cc3100_.SET_STATUS_BIT(g_Status, STATUS_BIT_STA_CONNECTED);
+        }
+        break;
+
+        case SL_WLAN_STA_DISCONNECTED_EVENT: {
+            _cc3100_.CLR_STATUS_BIT(g_Status, STATUS_BIT_STA_CONNECTED);
+            _cc3100_.CLR_STATUS_BIT(g_Status, STATUS_BIT_IP_LEASED);
+        }
+        break;
+
+        default: {
+            memset(print_buf, 0x00, PRINT_BUF_LEN);
+            sprintf((char*) print_buf, "[WLAN EVENT] Unexpected event [0x%x]\n\r",pWlanEvent->Event);
+            Uart_Write((uint8_t *) print_buf); 
+        }
+        break;
+    }
+}
+#endif
+
+/*!
+    \brief This function handles events for IP address acquisition via DHCP
+           indication
+
+    \param[in]      pNetAppEvent is the event passed to the handler
+
+    \return         None
+
+    \note
+
+    \warning
+*/
+#if (defined(sl_NetAppEvtHdlr))
+void SimpleLinkNetAppEventHandler(SlNetAppEvent_t *pNetAppEvent)
+{
+    
+    if(pNetAppEvent == NULL){
+        Uart_Write((uint8_t *)" [NETAPP EVENT] NULL Pointer Error \n\r");
+    }
+    
+    switch(pNetAppEvent->Event) {
+        case SL_NETAPP_IPV4_IPACQUIRED_EVENT: {
+            SlIpV4AcquiredAsync_t *pEventData = NULL;
+            _cc3100_.SET_STATUS_BIT(g_Status, STATUS_BIT_IP_ACQUIRED);            
+            pEventData = &pNetAppEvent->EventData.ipAcquiredV4;           
+            g_GatewayIP = pEventData->gateway;
+            
+            memset(print_buf, 0x00, PRINT_BUF_LEN);
+            sprintf((char*) print_buf, "[NETAPP EVENT] IP Acquired: IP=%d.%d.%d.%d , ""Gateway=%d.%d.%d.%d\n\r",
+            _cc3100_._netcfg.SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,3),
+            _cc3100_._netcfg.SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,2),
+            _cc3100_._netcfg.SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,1),
+            _cc3100_._netcfg.SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,0),
+            _cc3100_._netcfg.SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,3),
+            _cc3100_._netcfg.SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,2),
+            _cc3100_._netcfg.SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,1),
+            _cc3100_._netcfg.SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,0));
+            Uart_Write((uint8_t *) print_buf);
+            
+        }
+        break;
+
+        case SL_NETAPP_IP_LEASED_EVENT: {           
+            g_StationIP = pNetAppEvent->EventData.ipLeased.ip_address;          
+            _cc3100_.SET_STATUS_BIT(g_Status, STATUS_BIT_IP_LEASED);
+                       
+        }
+        break;
+
+        default: {
+            memset(print_buf, 0x00, PRINT_BUF_LEN);
+            sprintf((char*) print_buf, "[NETAPP EVENT] Unexpected event [0x%x] \n\r",pNetAppEvent->Event);
+            Uart_Write((uint8_t *) print_buf);
+        }
+        break;
+    }
+}
+#endif 
+
+/*!
+    \brief This function handles socket events indication
+
+    \param[in]      pSock is the event passed to the handler
+
+    \return         None
+*/
+#if (defined(sl_SockEvtHdlr))
+void SimpleLinkSockEventHandler(SlSockEvent_t *pSock)
+{
+    if(pSock == NULL)
+        Uart_Write((uint8_t *)" [SOCK EVENT] NULL Pointer Error \n\r");
+    
+    switch( pSock->Event )
+    {
+        case SL_SOCKET_TX_FAILED_EVENT:
+            /*
+             * TX Failed
+             *
+             * Information about the socket descriptor and status will be
+             * available in 'SlSockEventData_t' - Applications can use it if
+             * required
+             *
+             * SlSockEventData_t *pEventData = NULL;
+             * pEventData = & pSock->EventData;
+             */
+            
+            switch( pSock->socketAsyncEvent.SockTxFailData.status )
+            {
+                case SL_ECLOSE:
+                    Uart_Write((uint8_t *)" [SOCK EVENT] Close socket operation, failed to transmit all queued packets\n\r");
+                    break;
+                default:
+                     memset(print_buf, 0x00, PRINT_BUF_LEN);
+                     sprintf((char*) print_buf, "[SOCK ERROR] - TX FAILED : socket %d , reason""(%d) \n\n", pSock->socketAsyncEvent.SockTxFailData.sd, pSock->socketAsyncEvent.SockTxFailData.status);           
+                     Uart_Write((uint8_t *) print_buf);
+                    break;
+            }
+            break;
+
+        default:
+            memset(print_buf, 0x00, PRINT_BUF_LEN);
+            sprintf((char*) print_buf, "[SOCK EVENT] - Unexpected Event [%x0x]\n\n",pSock->Event);
+            Uart_Write((uint8_t *) print_buf);
+            break;
+    }
+}
+#endif
+
+/*!
+    \brief This function handles callback for the HTTP server events
+
+    \param[in]      pHttpEvent - Contains the relevant event information
+    \param[in]      pHttpResponse - Should be filled by the user with the
+                    relevant response information
+
+    \return         None
+
+    \note
+
+    \warning
+*/
+#if (defined(sl_HttpServerCallback))
+void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pHttpEvent, SlHttpServerResponse_t *pHttpResponse)
+{
+    /*
+     * This application doesn't work with HTTP server - Hence these
+     * events are not handled here
+     */
+    Uart_Write((uint8_t *)" [HTTP EVENT] Unexpected event \n\r");
+}
+#endif
+/*!
+    \brief This function handles general error events indication
+
+    \param[in]      pDevEvent is the event passed to the handler
+
+    \return         None
+*/
+#if (defined(sl_GeneralEvtHdlr))
+void SimpleLinkGeneralEventHandler(SlDeviceEvent_t *pDevEvent)
+{
+    /*
+     * Most of the general errors are not FATAL are are to be handled
+     * appropriately by the application
+     */
+    memset(print_buf, 0x00, PRINT_BUF_LEN);
+    sprintf((char*) print_buf, "[GENERAL EVENT] - ID=[%d] Sender=[%d]\n\n", pDevEvent->EventData.deviceEvent.status, pDevEvent->EventData.deviceEvent.sender); 
+    Uart_Write((uint8_t *) print_buf);
+}
+#endif
+
+#ifdef  __cplusplus
+}
+#endif /*  __cplusplus */
+
+//}//namespace
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/G_functions/fPtr_func.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/G_functions/fPtr_func.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,241 @@
+/*
+ *  - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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.
+ *
+*/
+
+#ifndef fPtr_func_h
+#define fPtr_func_h
+
+#include "simplelink_V2/cc3100_simplelink.h"
+
+
+/* Note. C function pointers point to the functions below. */
+/* C++ member function pointers not used ?           */
+
+namespace mbed_cc3100 { 
+
+
+    extern uint32_t  g_PingPacketsRecv;
+    extern uint32_t  g_GatewayIP;
+    extern uint32_t  g_StationIP;
+    extern uint32_t  g_DestinationIP;
+    extern uint32_t  g_BytesReceived; // variable to store the file size 
+    extern uint32_t  g_Status;
+    extern uint8_t   g_buff[MAX_BUFF_SIZE+1];
+    extern int32_t   g_SockID;
+    
+}//namespace mbed_cc3100    
+    
+using namespace mbed_cc3100;
+    
+#ifdef __cplusplus
+extern "C" {
+#endif     
+    
+
+void SimpleLinkPingReport(SlPingReport_t *pPingReport);
+   
+/*!
+    \brief WLAN Async event handler
+
+    \param[out]      pSlWlanEvent   pointer to SlWlanEvent_t data
+
+    \par
+             Parameters:
+
+             - <b>pSlWlanEvent->Event = SL_WLAN_CONNECT_EVENT </b>, STA or P2P client connection indication event
+                 - pSlWlanEvent->EventData.STAandP2PModeWlanConnected main fields:
+                      - ssid_name
+                      - ssid_len
+                      - bssid
+                      - go_peer_device_name
+                      - go_peer_device_name_len
+
+             - <b>pSlWlanEvent->Event = SL_WLAN_DISCONNECT_EVENT </b>, STA or P2P client disconnection event
+                 - pSlWlanEvent->EventData.STAandP2PModeDisconnected main fields:
+                      - ssid_name
+                      - ssid_len
+                      - reason_code
+
+             - <b>pSlWlanEvent->Event = SL_WLAN_STA_CONNECTED_EVENT </b>, AP/P2P(Go) connected STA/P2P(Client)
+                  - pSlWlanEvent->EventData.APModeStaConnected fields:
+                      - go_peer_device_name
+                      - mac
+                      - go_peer_device_name_len
+                      - wps_dev_password_id
+                      - own_ssid:  relevant for event sta-connected only
+                      - own_ssid_len:  relevant for event sta-connected only
+
+             - <b>pSlWlanEvent->Event = SL_WLAN_STA_DISCONNECTED_EVENT </b>, AP/P2P(Go) disconnected STA/P2P(Client)
+                  - pSlWlanEvent->EventData.APModestaDisconnected fields:
+                      - go_peer_device_name
+                      - mac
+                      - go_peer_device_name_len
+                      - wps_dev_password_id
+                      - own_ssid:  relevant for event sta-connected only
+                      - own_ssid_len:  relevant for event sta-connected only
+
+             - <b>pSlWlanEvent->Event = SL_WLAN_SMART_CONFIG_COMPLETE_EVENT </b>
+                  - pSlWlanEvent->EventData.smartConfigStartResponse fields:
+                     - status
+                     - ssid_len
+                     - ssid
+                     - private_token_len
+                     - private_token
+
+             - <b>pSlWlanEvent->Event = SL_WLAN_SMART_CONFIG_STOP_EVENT </b>
+                     - pSlWlanEvent->EventData.smartConfigStopResponse fields:
+                         - status
+
+             - <b>pSlWlanEvent->Event = SL_WLAN_P2P_DEV_FOUND_EVENT </b>
+                     - pSlWlanEvent->EventData.P2PModeDevFound fields:
+                         - go_peer_device_name
+                         - mac
+                         - go_peer_device_name_len
+                         - wps_dev_password_id
+                         - own_ssid:  relevant for event sta-connected only
+                         - own_ssid_len:  relevant for event sta-connected only
+
+             - <b>pSlWlanEvent->Event = SL_WLAN_P2P_NEG_REQ_RECEIVED_EVENT </b>
+                      - pSlWlanEvent->EventData.P2PModeNegReqReceived fields
+                          - go_peer_device_name
+                          - mac
+                          - go_peer_device_name_len
+                          - wps_dev_password_id
+                          - own_ssid:  relevant for event sta-connected only
+
+             - <b>pSlWlanEvent->Event = SL_WLAN_CONNECTION_FAILED_EVENT </b>, P2P only
+                       - pSlWlanEvent->EventData.P2PModewlanConnectionFailure fields:
+                           - status
+*/
+#if (defined(sl_WlanEvtHdlr))
+void SimpleLinkWlanEventHandler(SlWlanEvent_t *pWlanEvent);
+#endif
+
+/*!
+    \brief NETAPP Async event handler
+
+    \param[out]      pSlNetApp   pointer to SlNetAppEvent_t data
+
+    \par
+             Parameters:
+              - <b>pSlWlanEvent->Event = SL_NETAPP_IPV4_IPACQUIRED_EVENT</b>, IPV4 acquired event
+                  - pSlWlanEvent->EventData.ipAcquiredV4 fields:
+                       - ip
+                       - gateway
+                       - dns
+
+              - <b>pSlWlanEvent->Event = SL_NETAPP_IP_LEASED_EVENT</b>, AP or P2P go dhcp lease event
+                  - pSlWlanEvent->EventData.ipLeased  fields:
+                       - ip_address
+                       - lease_time
+                       - mac
+
+              - <b>pSlWlanEvent->Event = SL_NETAPP_IP_RELEASED_EVENT</b>, AP or P2P go dhcp ip release event
+                   - pSlWlanEvent->EventData.ipReleased fields
+                       - ip_address
+                       - mac
+                       - reason
+
+*/
+#if (defined(sl_NetAppEvtHdlr))
+void SimpleLinkNetAppEventHandler(SlNetAppEvent_t *pNetAppEvent);
+#endif
+
+/*!
+    \brief Socket Async event handler
+
+    \param[out]      pSlSockEvent   pointer to SlSockEvent_t data
+
+    \par
+             Parameters:\n
+             - <b>pSlSockEvent->Event = SL_SOCKET_TX_FAILED_EVENT</b>
+                 - pSlSockEvent->EventData fields:
+                     - sd
+                     - status
+             - <b>pSlSockEvent->Event = SL_SOCKET_ASYNC_EVENT</b>
+                - pSlSockEvent->EventData fields:
+                     - sd
+                     - type: SSL_ACCEPT  or RX_FRAGMENTATION_TOO_BIG or OTHER_SIDE_CLOSE_SSL_DATA_NOT_ENCRYPTED
+                     - val
+
+*/
+#if (defined(sl_SockEvtHdlr))
+void SimpleLinkSockEventHandler(SlSockEvent_t *pSock);
+#endif
+
+void SimpleLinkGeneralEventHandler(SlDeviceEvent_t *pDevEvent);
+
+void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pHttpEvent, SlHttpServerResponse_t *pHttpResponse);
+#ifndef SL_TINY_EXT
+void _sl_HandleAsync_Accept(void *pVoidBuf);
+
+void _sl_HandleAsync_Select(void *pVoidBuf);
+
+void _sl_HandleAsync_DnsGetHostByService(void *pVoidBuf);
+
+void _sl_HandleAsync_PingResponse(void *pVoidBuf);
+#endif
+void _sl_HandleAsync_Connect(void *pVoidBuf);
+
+void _sl_HandleAsync_DnsGetHostByName(void *pVoidBuf);
+
+void _sl_HandleAsync_Stop(void *pVoidBuf);
+
+_SlReturnVal_t _SlDrvMsgReadSpawnCtx(void *pValue);
+
+void _SlDrvDeviceEventHandler(void *pArgs);
+
+void _SlDrvNetAppEventHandler(void *pArgs);
+
+void _SlDrvHandleHttpServerEvents(SlHttpServerEvent_t *slHttpServerEvent, SlHttpServerResponse_t *slHttpServerResponse);
+void _SlDrvHandleSockEvents(SlSockEvent_t *slSockEvent);
+void _SlDrvHandleNetAppEvents(SlNetAppEvent_t *slNetAppEvent);
+void _SlDrvHandleWlanEvents(SlWlanEvent_t *slWlanEvent);
+void _SlDrvHandleGeneralEvents(SlDeviceEvent_t *slGeneralEvent);
+
+#ifdef  __cplusplus
+}
+#endif /*  __cplusplus */
+
+//}//namespace mbed_cc3100
+
+#endif//fPtr_func_h
+
+
+
+
+
+
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100.cpp	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,1338 @@
+/*
+* device.c - CC31xx/CC32xx Host Driver Implementation
+*
+* Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+*
+*
+*  Redistribution and use in source and binary forms, with or without
+*  modification, are permitted provided that the following conditions
+*  are met:
+*
+*    Redistributions of source code must retain the above copyright
+*    notice, this list of conditions and the following disclaimer.
+*
+*    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.
+*
+*    Neither the name of Texas Instruments Incorporated nor the names of
+*    its contributors may be used to endorse or promote products derived
+*    from this software without specific prior written permission.
+*
+*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+*  "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 COPYRIGHT
+*  OWNER OR CONTRIBUTORS 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 files                                                             */
+/*****************************************************************************/
+#include "cc3100_simplelink.h"
+#include "cc3100_protocol.h"
+#include "cc3100_sl_common.h"
+#include "cc3100.h"
+
+#include "fPtr_func.h"
+#include "cli_uart.h"
+
+namespace mbed_cc3100 {	
+
+    uint32_t  g_PingPacketsRecv;
+    uint32_t  g_GatewayIP;
+    uint32_t  g_StationIP;
+    uint32_t  g_DestinationIP;
+    uint32_t  g_BytesReceived; // variable to store the file size 
+    uint32_t  g_Status;
+    uint8_t   g_buff[MAX_BUFF_SIZE+1];
+    int32_t   g_SockID;		
+
+
+cc3100::cc3100(PinName button1_irq, PinName button2_irq, PinName cc3100_irq, PinName cc3100_nHIB, PinName cc3100_cs, SPI cc3100_spi)
+    : _spi(button1_irq, button2_irq, cc3100_irq, cc3100_nHIB, cc3100_cs, cc3100_spi, _driver),
+      _driver(_spi, _nonos, _netapp, _flowcont), _nonos(_driver), _wlan(_driver, _wlan_filters),
+      _wlan_filters(_driver), _netapp(_driver, _nonos), _fs(_driver), _netcfg(_driver),
+      _socket(_driver, _nonos), _flowcont(_driver, _nonos)
+
+       
+{
+
+}
+
+cc3100::~cc3100()
+{
+
+}
+
+/*!
+    \brief This function initializes the application variables
+
+    \param[in]  None
+
+    \return     0 on success, negative error-code on error
+*/
+int32_t cc3100::initializeAppVariables()
+{
+    
+    g_Status = 0;
+    g_PingPacketsRecv = 0;
+    g_StationIP = 0;
+    g_GatewayIP = 0;
+    g_DestinationIP = 0;
+    g_BytesReceived = 0; /* variable to store the file size */
+    g_SockID = 0;
+    memset(g_buff, 0, sizeof(g_buff));
+
+    return SUCCESS;
+}
+    
+/*!
+    \brief Disconnecting from a WLAN Access point
+
+    This function disconnects from the connected AP
+
+    \param[in]      None
+
+    \return         none
+
+    \note
+
+    \warning        If the WLAN disconnection fails, we will be stuck in this function forever.
+*/
+int32_t cc3100::disconnectFromAP()
+{
+    int32_t retVal = -1;
+
+    /*
+     * The function returns 0 if 'Disconnected done', negative number if already disconnected
+     * Wait for 'disconnection' event if 0 is returned, Ignore other return-codes
+     */
+    retVal = _wlan.sl_WlanDisconnect();
+    if(0 == retVal)
+    {
+        /* Wait */
+        while(IS_CONNECTED(g_Status,STATUS_BIT_CONNECTION)) { _nonos._SlNonOsMainLoopTask(); }
+    }
+
+    return SUCCESS;
+}     
+
+/*!
+    \brief This function configure the SimpleLink device in its default state. It:
+           - Sets the mode to STATION
+           - Configures connection policy to Auto and AutoSmartConfig
+           - Deletes all the stored profiles
+           - Enables DHCP
+           - Disables Scan policy
+           - Sets Tx power to maximum
+           - Sets power policy to normal
+           - Unregisters mDNS services
+           - Remove all filters
+
+    \param[in]      none
+
+    \return         On success, zero is returned. On error, negative is returned
+*/
+int32_t cc3100::configureSimpleLinkToDefaultState()
+{
+
+    SlVersionFull   ver = {0};
+    _WlanRxFilterOperationCommandBuff_t  RxFilterIdMask = {0};
+
+    uint8_t           val = 1;
+    uint8_t           configOpt = 0;
+    uint8_t           configLen = 0;
+    uint8_t           power = 0;
+
+    int32_t          retVal = -1;
+    int32_t          role = -1;
+
+    role = sl_Start(0, 0, 0);
+    ASSERT_ON_ERROR(role);
+
+    /* If the device is not in station-mode, try configuring it in station-mode */
+    if (ROLE_STA != role) {
+        if (ROLE_AP == role) {
+            /* If the device is in AP mode, we need to wait for this event before doing anything */
+            while(!IS_IP_ACQUIRED(g_Status,STATUS_BIT_IP_ACQUIRED)) {
+                _nonos._SlNonOsMainLoopTask();
+            }
+        }
+        
+        /* Switch to STA role and restart */
+        retVal = _wlan.sl_WlanSetMode(ROLE_STA);
+        ASSERT_ON_ERROR(retVal);
+        
+        retVal = sl_Stop(SL_STOP_TIMEOUT);
+        ASSERT_ON_ERROR(retVal);
+
+        retVal = sl_Start(0, 0, 0);
+        ASSERT_ON_ERROR(retVal);
+
+        /* Check if the device is in station again */
+        if (ROLE_STA != retVal) {
+            /* We don't want to proceed if the device is not coming up in station-mode */
+            ASSERT_ON_ERROR(DEVICE_NOT_IN_STATION_MODE);
+        }
+    }
+    
+    /* Get the device's version-information */
+    configOpt = SL_DEVICE_GENERAL_VERSION;
+    configLen = sizeof(ver);
+    retVal = sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION, &configOpt, &configLen, (uint8_t *)(&ver));
+    ASSERT_ON_ERROR(retVal);
+    
+    /* Set connection policy to Auto + SmartConfig (Device's default connection policy) */
+    retVal = _wlan.sl_WlanPolicySet(SL_POLICY_CONNECTION, SL_CONNECTION_POLICY(1, 0, 0, 0, 1), NULL, 0);
+    ASSERT_ON_ERROR(retVal);
+    
+    /* Remove all profiles */
+    retVal = _wlan.sl_WlanProfileDel(0xFF);
+    ASSERT_ON_ERROR(retVal);
+
+    /*
+     * Device in station-mode. Disconnect previous connection if any
+     * The function returns 0 if 'Disconnected done', negative number if already disconnected
+     * Wait for 'disconnection' event if 0 is returned, Ignore other return-codes
+     */
+    retVal = _wlan.sl_WlanDisconnect();
+    if(0 == retVal) {
+        /* Wait */
+        while(IS_CONNECTED(g_Status,STATUS_BIT_CONNECTION)) {
+            _nonos._SlNonOsMainLoopTask();
+        }
+    }
+    
+    /* Enable DHCP client*/
+    retVal = _netcfg.sl_NetCfgSet(SL_IPV4_STA_P2P_CL_DHCP_ENABLE,1,1,&val);
+    ASSERT_ON_ERROR(retVal);
+    
+    /* Disable scan */
+    configOpt = SL_SCAN_POLICY(0);
+    retVal = _wlan.sl_WlanPolicySet(SL_POLICY_SCAN , configOpt, NULL, 0);
+    ASSERT_ON_ERROR(retVal);
+    
+    /* Set Tx power level for station mode
+       Number between 0-15, as dB offset from maximum power - 0 will set maximum power */
+    power = 0;
+    retVal = _wlan.sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_STA_TX_POWER, 1, (uint8_t *)&power);
+    ASSERT_ON_ERROR(retVal);
+
+    /* Set PM policy to normal */
+    retVal = _wlan.sl_WlanPolicySet(SL_POLICY_PM , SL_NORMAL_POLICY, NULL, 0);
+    ASSERT_ON_ERROR(retVal);
+
+    /* Unregister mDNS services */
+    retVal = _netapp.sl_NetAppMDNSUnRegisterService(0, 0);
+    ASSERT_ON_ERROR(retVal);
+
+    /* Remove  all 64 filters (8*8) */
+    memset(RxFilterIdMask.FilterIdMask, 0xFF, 8);
+
+    retVal = _wlan_filters.sl_WlanRxFilterSet(SL_REMOVE_RX_FILTER, (uint8_t *)&RxFilterIdMask,
+             sizeof(_WlanRxFilterOperationCommandBuff_t));
+    ASSERT_ON_ERROR(retVal);
+
+    retVal = sl_Stop(SL_STOP_TIMEOUT);
+    ASSERT_ON_ERROR(retVal);
+
+    retVal = initializeAppVariables();
+    ASSERT_ON_ERROR(retVal);
+
+    return retVal; /* Success */
+}
+
+/*!
+    \brief Create UDP socket to communicate with server.
+
+    \param[in]      none
+
+    \return         Socket descriptor for success otherwise negative
+
+    \warning
+*/
+int32_t cc3100::createUDPConnection()
+{
+    int32_t sd = 0;
+
+    sd = _socket.sl_Socket(SL_AF_INET, SL_SOCK_DGRAM, IPPROTO_UDP);
+    if( sd < 0 )
+    {
+        Uart_Write((uint8_t*)"Error creating socket\n\r\n\r");
+    }
+
+    return sd;
+}	
+
+/*!
+    \brief Create connection with server.
+
+    This function opens a socket and create the endpoint communication with server
+
+    \param[in]      DestinationIP - IP address of the server
+
+    \return         socket id for success and negative for error
+*/
+int32_t cc3100::createConnection(uint32_t DestinationIP)
+{
+    SlSockAddrIn_t  Addr = {0};
+    int32_t           Status = 0;
+    int32_t           AddrSize = 0;
+    int32_t           SockID = 0;
+
+    Addr.sin_family = SL_AF_INET;
+    Addr.sin_port = _socket.sl_Htons(80);
+    Addr.sin_addr.s_addr = _socket.sl_Htonl(DestinationIP);
+
+    AddrSize = sizeof(SlSockAddrIn_t);
+
+    SockID = _socket.sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
+    ASSERT_ON_ERROR(SockID);
+
+    Status = _socket.sl_Connect(SockID, ( SlSockAddr_t *)&Addr, AddrSize);
+    if (Status < 0)
+    {
+        _socket.sl_Close(SockID);
+        ASSERT_ON_ERROR(Status);
+    }
+
+    return SockID;
+}
+
+/*!
+    \brief Convert hex to decimal base
+
+    \param[in]      ptr - pointer to string containing number in hex
+
+    \return         number in decimal base
+
+*/
+int32_t cc3100::hexToi(unsigned char *ptr)
+{
+    uint32_t result = 0;
+    uint32_t len = 0;
+
+    int32_t  idx = -1;
+
+    len = strlen((const char*) ptr);
+
+    /* convert characters to upper case */
+    for(idx = 0; ptr[idx] != '\0'; ++idx)
+    {
+        if( (ptr[idx] >= 'a') &&
+            (ptr[idx] <= 'f') )
+        {
+            ptr[idx] -= 32;         /* Change case - ASCII 'a' = 97, 'A' = 65 => 97-65 = 32 */
+        }
+    }
+
+    for(idx = 0; ptr[idx] != '\0'; ++idx)
+    {
+        if(ptr[idx] >= '0' && ptr[idx] <= '9')
+        {
+            /* Converting '0' to '9' to their decimal value */
+            result += (ptr[idx] - '0') * (1 << (4 * (len - 1 - idx)));
+        }
+        else if(ptr[idx] >= 'A' && ptr[idx] <= 'F')
+        {
+            /* Converting hex 'A' to 'F' to their decimal value */
+            result += (ptr[idx] - 55) * (1 << (4 * (len -1 - idx))); /* .i.e. 'A' - 55 = 10, 'F' - 55 = 15 */
+        }
+        else
+        {
+            ASSERT_ON_ERROR(INVALID_HEX_STRING);
+        }
+    }
+
+    return result;
+}
+
+/*!
+    \brief Calculate the file chunk size
+
+    \param[in]      len - pointer to length of the data in the buffer
+    \param[in]      p_Buff - pointer to pointer of buffer containing data
+    \param[out]     chunk_size - pointer to variable containing chunk size
+
+    \return         0 for success, -ve for error
+
+*/
+int32_t cc3100::getChunkSize(int32_t *len, uint8_t **p_Buff, uint32_t *chunk_size)
+{
+    int32_t   idx = -1;
+    unsigned char   lenBuff[10];
+
+    idx = 0;
+    memset(lenBuff, 0, sizeof(lenBuff));
+    while(*len >= 0 && **p_Buff != 13) /* check for <CR> */
+    {
+        if(0 == *len)
+        {
+            memset(g_buff, 0, sizeof(g_buff));
+            *len = _socket.sl_Recv(g_SockID, &g_buff[0], MAX_BUFF_SIZE, 0);
+            if(*len <= 0)
+                ASSERT_ON_ERROR(TCP_RECV_ERROR);
+
+            *p_Buff = g_buff;
+        }
+
+        lenBuff[idx] = **p_Buff;
+        idx++;
+        (*p_Buff)++;
+        (*len)--;
+    }
+
+    (*p_Buff) += 2; /* skip <CR><LF> */
+    (*len) -= 2;
+    *chunk_size = hexToi(lenBuff);
+
+    return SUCCESS;
+}
+
+/*!
+    \brief Obtain the file from the server
+
+    This function requests the file from the server and save it on serial flash.
+    To request a different file for different user needs to modify the
+    PREFIX_BUFFER and POST_BUFFER macros.
+
+    \param[in]      None
+
+    \return         0 for success and negative for error
+
+*/
+/*
+int32_t cc3100::getFile()
+{
+    uint32_t Token = 0;
+    uint32_t recv_size = 0;
+    uint8_t *pBuff = 0;
+    uint8_t eof_detected = 0;
+    uint8_t isChunked = 0;
+
+    int32_t transfer_len = -1;
+    int32_t retVal = -1;
+    int32_t fileHandle = -1;
+
+    memset(g_buff, 0, sizeof(g_buff));
+
+    //Puts together the HTTP GET string.
+    strcpy((char*)g_buff, PREFIX_BUFFER);
+    strcat((char*)g_buff, POST_BUFFER);
+
+    //Send the HTTP GET string to the opened TCP/IP socket.
+    transfer_len = _socket.sl_Send(g_SockID, g_buff, strlen((const char*)g_buff), 0);
+
+    if (transfer_len < 0)
+    {
+        // error 
+        printf(" Socket Send Error\r\n");
+        ASSERT_ON_ERROR(TCP_SEND_ERROR);
+    }
+
+    memset(g_buff, 0, sizeof(g_buff));
+
+    //get the reply from the server in buffer.
+    transfer_len = _socket.sl_Recv(g_SockID, &g_buff[0], MAX_BUFF_SIZE, 0);
+
+    if(transfer_len <= 0)
+        ASSERT_ON_ERROR(TCP_RECV_ERROR);
+
+    // Check for 404 return code 
+    if(strstr((const char*)g_buff, HTTP_FILE_NOT_FOUND) != 0)
+    {
+        printf(" File not found, check the file and try again\r\n");
+        ASSERT_ON_ERROR(FILE_NOT_FOUND_ERROR);
+    }
+
+    // if not "200 OK" return error 
+    if(strstr((const char*)g_buff, HTTP_STATUS_OK) == 0)
+    {
+        printf(" Error during downloading the file\r\n");
+        ASSERT_ON_ERROR(INVALID_SERVER_RESPONSE);
+    }
+
+    // check if content length is transferred with headers 
+    pBuff = (uint8_t *)strstr((const char*)g_buff, HTTP_CONTENT_LENGTH);
+    if(pBuff != 0)
+    {
+        // not supported 
+        printf(" Server response format is not supported\r\n");
+        ASSERT_ON_ERROR(FORMAT_NOT_SUPPORTED);
+    }
+
+    // Check if data is chunked 
+    pBuff = (uint8_t *)strstr((const char*)g_buff, HTTP_TRANSFER_ENCODING);
+    if(pBuff != 0)
+    {
+        pBuff += strlen(HTTP_TRANSFER_ENCODING);
+        while(*pBuff == SPACE)
+            pBuff++;
+
+        if(memcmp(pBuff, HTTP_ENCODING_CHUNKED, strlen(HTTP_ENCODING_CHUNKED)) == 0)
+        {
+            recv_size = 0;
+            isChunked = 1;
+        }
+    }
+    else
+    {
+        // Check if connection will be closed by after sending data
+         // In this method the content length is not received and end of
+         // connection marks the end of data 
+        pBuff = (uint8_t *)strstr((const char*)g_buff, HTTP_CONNECTION);
+        if(pBuff != 0)
+        {
+            pBuff += strlen(HTTP_CONNECTION);
+            while(*pBuff == SPACE)
+                pBuff++;
+
+            if(memcmp(pBuff, HTTP_ENCODING_CHUNKED, strlen(HTTP_CONNECTION_CLOSE)) == 0)
+            {
+                // not supported 
+                printf(" Server response format is not supported\r\n");
+                ASSERT_ON_ERROR(FORMAT_NOT_SUPPORTED);
+            }
+        }
+    }
+
+    // "\r\n\r\n" marks the end of headers 
+    pBuff = (uint8_t *)strstr((const char*)g_buff, HTTP_END_OF_HEADER);
+    if(pBuff == 0)
+    {
+        printf(" Invalid response\r\n");
+        ASSERT_ON_ERROR(INVALID_SERVER_RESPONSE);
+    }
+    // Increment by 4 to skip "\r\n\r\n" 
+    pBuff += 4;
+
+    // Adjust buffer data length for header size 
+    transfer_len -= (pBuff - g_buff);
+
+    // If data in chunked format, calculate the chunk size 
+    if(isChunked == 1)
+    {
+        retVal = getChunkSize(&transfer_len, &pBuff, &recv_size);
+        if(retVal < 0)
+        {
+            // Error 
+            printf(" Problem with connection to server\r\n");
+            return retVal;
+        }
+    }
+
+    // Open file to save the downloaded file 
+    retVal = _fs.sl_FsOpen((uint8_t *)FILE_NAME,
+                       FS_MODE_OPEN_WRITE, &Token, &fileHandle);
+    if(retVal < 0)
+    {
+        // File Doesn't exit create a new of 45 KB file 
+        retVal = _fs.sl_FsOpen((uint8_t *)FILE_NAME,
+                           _fs.FS_MODE_OPEN_CREATE(SIZE_45K,_FS_FILE_OPEN_FLAG_COMMIT|_FS_FILE_PUBLIC_WRITE),
+                           &Token, &fileHandle);
+        if(retVal < 0)
+        {
+            printf(" Error during opening the file\r\n");
+            return retVal;
+        }
+    }
+
+    while (0 < transfer_len)
+    {
+        // For chunked data recv_size contains the chunk size to be received
+         // while the transfer_len contains the data in the buffer 
+        if(recv_size <= transfer_len)
+        {
+            // write the recv_size 
+            retVal = _fs.sl_FsWrite(fileHandle, g_BytesReceived,
+                    (uint8_t *)pBuff, recv_size);
+            if(retVal < recv_size)
+            {
+                // Close file without saving 
+                retVal = _fs.sl_FsClose(fileHandle, 0, (unsigned char*)"A", 1);
+                printf(" Error during writing the file\r\n");
+                return FILE_WRITE_ERROR;
+            }
+            transfer_len -= recv_size;
+            g_BytesReceived +=recv_size;
+            pBuff += recv_size;
+            recv_size = 0;
+
+            if(isChunked == 1)
+            {
+                // if data in chunked format calculate next chunk size 
+                pBuff += 2; // 2 bytes for <CR> <LF> 
+                transfer_len -= 2;
+
+                if(getChunkSize(&transfer_len, &pBuff, &recv_size) < 0)
+                {
+                    // Error 
+                    break;
+                }
+
+                // if next chunk size is zero we have received the complete file 
+                if(recv_size == 0)
+                {
+                    eof_detected = 1;
+                    break;
+                }
+
+                if(recv_size < transfer_len)
+                {
+                    // Code will enter this section if the new chunk size is less then
+                     // then the transfer size. This will the last chunk of file received
+                     
+                    retVal = _fs.sl_FsWrite(fileHandle, g_BytesReceived,
+                            (uint8_t *)pBuff, recv_size);
+                    if(retVal < recv_size)
+                    {
+                        // Close file without saving 
+                        retVal = _fs.sl_FsClose(fileHandle, 0, (unsigned char*)"A", 1);
+                        printf(" Error during writing the file\r\n");
+                        return FILE_WRITE_ERROR;
+                    }
+                    transfer_len -= recv_size;
+                    g_BytesReceived +=recv_size;
+                    pBuff += recv_size;
+                    recv_size = 0;
+
+                    pBuff += 2; // 2bytes for <CR> <LF> 
+                    transfer_len -= 2;
+
+                    // Calculate the next chunk size, should be zero 
+                    if(getChunkSize(&transfer_len, &pBuff, &recv_size) < 0)
+                    {
+                        // Error 
+                        break;
+                    }
+
+                    // if next chunk size is non zero error 
+                    if(recv_size != 0)
+                    {
+                        // Error 
+                        break;
+                    }
+                    eof_detected = 1;
+                    break;
+                }
+                else
+                {
+                    // write data on the file 
+                    retVal = _fs.sl_FsWrite(fileHandle, g_BytesReceived,
+                            (uint8_t *)pBuff, transfer_len);
+                    if(retVal < transfer_len)
+                    {
+                        // Close file without saving 
+                        retVal = _fs.sl_FsClose(fileHandle, 0, (unsigned char*)"A", 1);
+                        printf(" Error during writing the file\r\n");
+                        ASSERT_ON_ERROR(FILE_WRITE_ERROR);
+                    }
+                    recv_size -= transfer_len;
+                    g_BytesReceived +=transfer_len;
+                }
+            }
+            // complete file received exit 
+            if(recv_size == 0)
+            {
+                eof_detected = 1;
+                break;
+            }
+        }
+        else
+        {
+            // write data on the file 
+            retVal = _fs.sl_FsWrite(fileHandle, g_BytesReceived,
+                                 (uint8_t *)pBuff, transfer_len);
+            if (retVal < 0)
+            {
+                // Close file without saving 
+                retVal = _fs.sl_FsClose(fileHandle, 0, (unsigned char*)"A", 1);
+                printf(" Error during writing the file\r\n");
+                ASSERT_ON_ERROR(FILE_WRITE_ERROR);
+            }
+            g_BytesReceived +=transfer_len;
+            recv_size -= transfer_len;
+        }
+
+        memset(g_buff, 0, sizeof(g_buff));
+
+        transfer_len = _socket.sl_Recv(g_SockID, &g_buff[0], MAX_BUFF_SIZE, 0);
+        if(transfer_len <= 0)
+            ASSERT_ON_ERROR(TCP_RECV_ERROR);
+
+        pBuff = g_buff;
+    }
+
+    // If user file has checksum which can be used to verify the temporary
+     // file then file should be verified
+     // In case of invalid file (FILE_NAME) should be closed without saving to
+     // recover the previous version of file 
+    if(0 > transfer_len || eof_detected == 0)
+    {
+        // Close file without saving 
+        retVal = _fs.sl_FsClose(fileHandle, 0, (unsigned char*)"A", 1);
+        printf(" Error While File Download\r\n");
+        ASSERT_ON_ERROR(INVALID_FILE);
+    }
+    else
+    {
+        // Save and close file 
+        retVal = _fs.sl_FsClose(fileHandle, 0, 0, 0);
+        ASSERT_ON_ERROR(retVal);
+    }
+
+    return SUCCESS;;
+}
+*/
+
+/*!
+    \brief Connecting to a WLAN Access point
+
+    This function connects to the required AP (SSID_NAME).
+    The function will return once we are connected and have acquired IP address
+
+    \param[in]  None
+
+    \return     0 on success, negative error-code on error
+
+    \note
+
+    \warning    If the WLAN connection fails or we don't acquire an IP address,
+                We will be stuck in this function forever.
+*/
+int32_t cc3100::establishConnectionWithAP()
+{
+    
+    SlSecParams_t secParams = {0};
+    int32_t retVal = 0;
+
+    secParams.Key = (signed char *)PASSKEY;
+    secParams.KeyLen = strlen(PASSKEY);
+    secParams.Type = SEC_TYPE;
+
+    retVal = _wlan.sl_WlanConnect((signed char *)SSID_NAME, strlen(SSID_NAME), 0, &secParams, 0);
+    ASSERT_ON_ERROR(retVal);
+    
+    /* Wait */
+    while((!IS_CONNECTED(g_Status,STATUS_BIT_CONNECTION)) || (!IS_IP_ACQUIRED(g_Status,STATUS_BIT_IP_ACQUIRED))) { _nonos._SlNonOsMainLoopTask(); }
+
+    return SUCCESS;
+}
+
+/*!
+    \brief This function checks the LAN connection by pinging the AP's gateway
+
+    \param[in]  None
+
+    \return     0 on success, negative error-code on error
+*/
+int32_t cc3100::checkLanConnection()
+{
+    SlPingStartCommand_t pingParams = {0};
+    SlPingReport_t pingReport = {0};
+
+    int32_t retVal = -1;
+
+    CLR_STATUS_BIT(g_Status, STATUS_BIT_PING_DONE);
+    g_PingPacketsRecv = 0;
+
+    /* Set the ping parameters */
+    pingParams.PingIntervalTime = PING_INTERVAL;
+    pingParams.PingSize = PING_PKT_SIZE;
+    pingParams.PingRequestTimeout = PING_TIMEOUT;
+    pingParams.TotalNumberOfAttempts = PING_ATTEMPTS;
+    pingParams.Flags = 0;
+    pingParams.Ip = g_GatewayIP;
+
+    /* Check for LAN connection */
+    retVal = _netapp.sl_NetAppPingStart( (SlPingStartCommand_t*)&pingParams, SL_AF_INET,
+                                 (SlPingReport_t*)&pingReport, SimpleLinkPingReport);
+    ASSERT_ON_ERROR(retVal);
+
+    /* Wait */
+    while(!IS_PING_DONE(g_Status,STATUS_BIT_PING_DONE)) { _nonos._SlNonOsMainLoopTask(); }
+
+    if(0 == g_PingPacketsRecv)
+    {
+        /* Problem with LAN connection */
+        ASSERT_ON_ERROR(LAN_CONNECTION_FAILED);
+    }
+
+    /* LAN connection is successful */
+    return SUCCESS;
+}
+
+/*!
+    \brief This function checks the internet connection by pinging
+           the external-host (HOST_NAME)
+
+    \param[in]  None
+
+    \return     0 on success, negative error-code on error
+*/
+int32_t cc3100::checkInternetConnection()
+{
+    SlPingStartCommand_t pingParams = {0};
+    SlPingReport_t pingReport = {0};
+
+    uint32_t ipAddr = 0;
+
+    int32_t retVal = -1;
+
+    CLR_STATUS_BIT(g_Status, STATUS_BIT_PING_DONE);
+    g_PingPacketsRecv = 0;
+
+    /* Set the ping parameters */
+    pingParams.PingIntervalTime = PING_INTERVAL;
+    pingParams.PingSize = PING_PKT_SIZE;
+    pingParams.PingRequestTimeout = PING_TIMEOUT;
+    pingParams.TotalNumberOfAttempts = PING_ATTEMPTS;
+    pingParams.Flags = 0;
+    pingParams.Ip = g_GatewayIP;
+
+    /* Check for Internet connection */
+    retVal = _netapp.sl_NetAppDnsGetHostByName((unsigned char *)HOST_NAME, strlen(HOST_NAME), &ipAddr, SL_AF_INET);
+    ASSERT_ON_ERROR(retVal);
+
+    /* Replace the ping address to match HOST_NAME's IP address */
+    pingParams.Ip = ipAddr;
+
+    /* Try to ping HOST_NAME */
+    retVal = _netapp.sl_NetAppPingStart( (SlPingStartCommand_t*)&pingParams, SL_AF_INET,
+                                 (SlPingReport_t*)&pingReport, SimpleLinkPingReport);
+    ASSERT_ON_ERROR(retVal);
+
+    /* Wait */
+    while(!IS_PING_DONE(g_Status,STATUS_BIT_PING_DONE)) { _nonos._SlNonOsMainLoopTask(); }
+
+    if (0 == g_PingPacketsRecv)
+    {
+        /* Problem with internet connection*/
+        ASSERT_ON_ERROR(INTERNET_CONNECTION_FAILED);
+    }
+
+    /* Internet connection is successful */
+    return SUCCESS;
+}
+
+const int8_t StartResponseLUT[8] = 
+{
+    ROLE_UNKNOWN_ERR,
+    ROLE_STA,
+    ROLE_STA_ERR,
+    ROLE_AP,
+    ROLE_AP_ERR,
+    ROLE_P2P,
+    ROLE_P2P_ERR,
+    ROLE_UNKNOWN_ERR    
+};
+    
+/*****************************************************************************/
+/* Internal functions                                                        */
+/*****************************************************************************/
+
+int16_t cc3100::_sl_GetStartResponseConvert(uint32_t Status)
+{
+    return (int16_t)StartResponseLUT[Status & 0x7];
+    
+}
+
+/*****************************************************************************/
+/* API Functions                                                             */
+/*****************************************************************************/
+
+bool cc3100::IS_PING_DONE(uint32_t status_variable,const uint32_t bit){
+	
+	    g_Status = status_variable;
+	    
+	    if(0 != (g_Status & ((uint32_t)1L<<(bit)))){
+	    	return TRUE;
+        }else{
+        	return FALSE;
+        }
+}
+        
+bool cc3100::IS_CONNECTED(uint32_t status_variable,const uint32_t bit){
+	
+	    g_Status = status_variable;
+	    
+	    if(0 != (g_Status & ((uint32_t)1L<<(bit)))){
+	    	return TRUE;
+        }else{
+        	return FALSE;
+        }
+}
+        
+bool cc3100::IS_STA_CONNECTED(uint32_t status_variable,const uint32_t bit){
+	
+	    g_Status = status_variable;
+	    
+	    if(0 != (g_Status & ((uint32_t)1L<<(bit)))){
+	    	return TRUE;
+        }else{
+        	return FALSE;
+        }
+} 
+       
+bool cc3100::IS_IP_ACQUIRED(uint32_t status_variable,const uint32_t bit){
+	
+	    g_Status = status_variable;
+	    
+	    if(0 != (g_Status & ((uint32_t)1L<<(bit)))){
+	    	return TRUE;
+        }else{
+        	return FALSE;
+        }
+}
+        
+bool cc3100::IS_IP_LEASED(uint32_t status_variable,const uint32_t bit){
+	
+	    g_Status = status_variable;
+	    
+	    if(0 != (g_Status & ((uint32_t)1L<<(bit)))){
+	    	return TRUE;
+        }else{
+        	return FALSE;
+        }
+}
+        
+bool cc3100::IS_CONNECTION_FAILED(uint32_t status_variable,const uint32_t bit){
+	    
+	    g_Status = status_variable;
+	    
+	    if(0 != (g_Status & ((uint32_t)1L<<(bit)))){
+	    	return TRUE;
+        }else{
+        	return FALSE;
+        }
+}
+        
+bool cc3100::IS_P2P_NEG_REQ_RECEIVED(uint32_t status_variable,const uint32_t bit){
+	
+	    g_Status = status_variable;
+	    
+	    if(0 != (g_Status & ((uint32_t)1L<<(bit)))){
+	    	return TRUE;
+        }else{
+        	return FALSE;
+        }
+}
+        
+bool cc3100::IS_SMARTCONFIG_DONE(uint32_t status_variable,const uint32_t bit){
+	
+	    g_Status = status_variable;
+	    
+	    if(0 != (g_Status & ((uint32_t)1L<<(bit)))){
+	    	return TRUE;
+        }else{
+        	return FALSE;
+        }
+}
+        
+bool cc3100::IS_SMARTCONFIG_STOPPED(uint32_t status_variable,const uint32_t bit){
+	
+	    g_Status = status_variable;
+	    
+	    if(0 != (g_Status & ((uint32_t)1L<<(bit)))){	    	
+	    	return TRUE;
+        }else{
+        	return FALSE;       	
+        }        
+}
+
+void cc3100::CLR_STATUS_BIT(uint32_t status_variable, const uint32_t bit){
+	    
+	    g_Status = status_variable;
+	    g_Status &= ~((uint32_t)1L<<(bit));
+	    
+}
+
+void cc3100::SET_STATUS_BIT(uint32_t status_variable, const uint32_t bit){
+
+	    g_Status = status_variable;
+	    g_Status |= ((uint32_t)1L<<(bit));
+	    
+}
+	    
+/*****************************************************************************/
+/* sl_Task                                                                   */
+/*****************************************************************************/
+#if _SL_INCLUDE_FUNC(sl_Task)
+void cc3100::sl_Task(void)
+{
+#ifdef _SlTaskEntry
+//    _nonos._SlNonOsMainLoopTask;
+    _SlTaskEntry();
+    
+#endif
+}
+#endif
+
+/*****************************************************************************/
+/* sl_Start                                                                  */
+/*****************************************************************************/
+#if _SL_INCLUDE_FUNC(sl_Start)
+int16_t cc3100::sl_Start(const void* pIfHdl, int8_t*  pDevName, const P_INIT_CALLBACK pInitCallBack)
+{
+    
+    int16_t ObjIdx = MAX_CONCURRENT_ACTIONS;
+    InitComplete_t  AsyncRsp;
+
+    /* Perform any preprocessing before enable networking services */
+    sl_DeviceEnablePreamble();//stub only
+    
+    /* ControlBlock init */
+    _driver._SlDrvDriverCBInit();
+    
+    /* open the interface: usually SPI or UART */
+    if (NULL == pIfHdl) 
+    {
+        g_pCB->FD = _spi.spi_Open((int8_t *)pDevName, 0);
+    } 
+    else 
+    {
+        g_pCB->FD = (_SlFd_t)pIfHdl;
+    }
+       
+    ObjIdx = _driver._SlDrvProtectAsyncRespSetting((uint8_t *)&AsyncRsp, START_STOP_ID, SL_MAX_SOCKETS);
+    
+    if (MAX_CONCURRENT_ACTIONS == ObjIdx) 
+    {
+        Uart_Write((uint8_t*)"SL_POOL_IS_EMPTY\r\n");
+        return SL_POOL_IS_EMPTY;
+    }
+    
+    if( g_pCB->FD >= (_SlFd_t)0) {
+        _spi.CC3100_disable();
+        
+        g_pCB->pInitCallback = pInitCallBack;
+            
+        _spi.CC3100_enable();
+
+        if (NULL == pInitCallBack) {            
+            _driver._SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj);      
+            /*release Pool Object*/           
+            _driver._SlDrvReleasePoolObj(g_pCB->FunctionParams.AsyncExt.ActionIndex);                       
+            return _sl_GetStartResponseConvert(AsyncRsp.Status);
+        }
+        else
+        {
+            return SL_RET_CODE_OK;    
+        }
+    }
+    
+    return SL_BAD_INTERFACE;
+
+
+}
+#endif
+
+/***************************************************************************
+_sl_HandleAsync_InitComplete - handles init complete signalling to
+a waiting object
+****************************************************************************/
+void cc3100::_sl_HandleAsync_InitComplete(void *pVoidBuf)
+{
+
+    InitComplete_t *pMsgArgs = (InitComplete_t *)_SL_RESP_ARGS_START(pVoidBuf);
+
+    _driver._SlDrvProtectionObjLockWaitForever();
+
+    if(g_pCB->pInitCallback) {
+        g_pCB->pInitCallback(_sl_GetStartResponseConvert(pMsgArgs->Status));
+    } else {
+        memcpy(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs, pMsgArgs, sizeof(InitComplete_t));        
+        _driver._SlDrvSyncObjSignal(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj);
+    }
+    _driver._SlDrvProtectionObjUnLock();
+
+    if(g_pCB->pInitCallback) {
+        _driver._SlDrvReleasePoolObj(g_pCB->FunctionParams.AsyncExt.ActionIndex);
+    }
+
+}
+
+/*****************************************************************************
+sl_stop
+******************************************************************************/
+typedef union {
+    _DevStopCommand_t  Cmd;
+    _BasicResponse_t   Rsp;
+} _SlStopMsg_u;
+
+const _SlCmdCtrl_t _SlStopCmdCtrl = {
+    SL_OPCODE_DEVICE_STOP_COMMAND,
+    sizeof(_DevStopCommand_t),
+    sizeof(_BasicResponse_t)
+};
+
+#if _SL_INCLUDE_FUNC(sl_Stop)
+int16_t cc3100::sl_Stop(const uint16_t timeout)
+{
+    
+    int16_t RetVal=0;
+    _SlStopMsg_u      Msg;
+    _BasicResponse_t  AsyncRsp;
+    int8_t ObjIdx = MAX_CONCURRENT_ACTIONS;
+    /* if timeout is 0 the shutdown is forced immediately */
+    if( 0 == timeout ) {
+        _spi.registerInterruptHandler(NULL, NULL);
+        _spi.CC3100_disable();
+        RetVal = _spi.spi_Close(g_pCB->FD);
+
+    } else {
+        /* let the device make the shutdown using the defined timeout */
+        Msg.Cmd.Timeout = timeout;        
+        ObjIdx = _driver._SlDrvProtectAsyncRespSetting((uint8_t *)&AsyncRsp, START_STOP_ID, SL_MAX_SOCKETS);
+        
+      if (MAX_CONCURRENT_ACTIONS == ObjIdx)
+      {
+          return SL_POOL_IS_EMPTY;
+      }
+
+      VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlStopCmdCtrl, &Msg, NULL));
+
+      if(SL_OS_RET_CODE_OK == (int16_t)Msg.Rsp.status)
+      {
+         _driver._SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj);
+         Msg.Rsp.status = AsyncRsp.status;
+         RetVal = Msg.Rsp.status;
+      }
+      
+      _driver._SlDrvReleasePoolObj((uint8_t)ObjIdx);
+      _spi.registerInterruptHandler(NULL, NULL);
+      _spi.CC3100_disable();
+      _spi.spi_Close(g_pCB->FD);
+     
+    }
+    
+    _driver._SlDrvDriverCBDeinit();
+
+    return RetVal;
+}
+#endif
+
+
+/*****************************************************************************
+sl_EventMaskSet
+*****************************************************************************/
+typedef union {
+    _DevMaskEventSetCommand_t	    Cmd;
+    _BasicResponse_t	            Rsp;
+} _SlEventMaskSetMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_EventMaskSet)
+const _SlCmdCtrl_t _SlEventMaskSetCmdCtrl = {
+    SL_OPCODE_DEVICE_EVENTMASKSET,
+    sizeof(_DevMaskEventSetCommand_t),
+    sizeof(_BasicResponse_t)
+};
+
+int16_t cc3100::sl_EventMaskSet(uint8_t EventClass , uint32_t Mask)
+{
+    _SlEventMaskSetMsg_u Msg;
+    Msg.Cmd.group = EventClass;
+    Msg.Cmd.mask = Mask;
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlEventMaskSetCmdCtrl, &Msg, NULL));
+
+    return (int16_t)Msg.Rsp.status;
+}
+#endif
+
+/******************************************************************************
+sl_EventMaskGet
+******************************************************************************/
+typedef union {
+    _DevMaskEventGetCommand_t	    Cmd;
+    _DevMaskEventGetResponse_t      Rsp;
+} _SlEventMaskGetMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_EventMaskGet)
+const _SlCmdCtrl_t _SlEventMaskGetCmdCtrl = {
+    SL_OPCODE_DEVICE_EVENTMASKGET,
+    sizeof(_DevMaskEventGetCommand_t),
+    sizeof(_DevMaskEventGetResponse_t)
+};
+
+int16_t cc3100::sl_EventMaskGet(uint8_t EventClass, uint32_t *pMask)
+{
+    _SlEventMaskGetMsg_u Msg;
+
+    Msg.Cmd.group = EventClass;
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlEventMaskGetCmdCtrl, &Msg, NULL));
+
+    *pMask = Msg.Rsp.mask;
+    return SL_RET_CODE_OK;
+}
+#endif
+
+/******************************************************************************
+sl_DevGet
+******************************************************************************/
+
+typedef union {
+    _DeviceSetGet_t	    Cmd;
+    _DeviceSetGet_t	    Rsp;
+} _SlDeviceMsgGet_u;
+
+#if _SL_INCLUDE_FUNC(sl_DevGet)
+const _SlCmdCtrl_t _SlDeviceGetCmdCtrl = {
+    SL_OPCODE_DEVICE_DEVICEGET,
+    sizeof(_DeviceSetGet_t),
+    sizeof(_DeviceSetGet_t)
+};
+
+int32_t cc3100::sl_DevGet(uint8_t DeviceGetId, uint8_t *pOption,uint8_t *pConfigLen, uint8_t *pValues)
+{
+    _SlDeviceMsgGet_u         Msg;
+    _SlCmdExt_t               CmdExt;
+    
+    if (*pConfigLen == 0) {
+        return SL_EZEROLEN;
+    }
+   
+    if( pOption ) {
+        _driver._SlDrvResetCmdExt(&CmdExt);
+        CmdExt.RxPayloadLen = *pConfigLen;
+        
+        CmdExt.pRxPayload = (uint8_t *)pValues;
+        
+
+        Msg.Cmd.DeviceSetId = DeviceGetId;
+
+        Msg.Cmd.Option   = (uint16_t)*pOption;
+
+        VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlDeviceGetCmdCtrl, &Msg, &CmdExt));
+        
+        if( pOption ) {
+            *pOption = (uint8_t)Msg.Rsp.Option;
+        }
+        
+        if (CmdExt.RxPayloadLen < CmdExt.ActualRxPayloadLen) {
+            *pConfigLen = (uint8_t)CmdExt.RxPayloadLen;
+            return SL_ESMALLBUF;
+        } else {
+            *pConfigLen = (uint8_t)CmdExt.ActualRxPayloadLen;
+        }
+        
+        return (int16_t)Msg.Rsp.Status;
+    } else {
+        return -1;
+    }
+}
+#endif
+
+/******************************************************************************
+sl_DevSet
+******************************************************************************/
+typedef union {
+    _DeviceSetGet_t    Cmd;
+    _BasicResponse_t   Rsp;
+} _SlDeviceMsgSet_u;
+
+#if _SL_INCLUDE_FUNC(sl_DevSet)
+const _SlCmdCtrl_t _SlDeviceSetCmdCtrl = {
+    SL_OPCODE_DEVICE_DEVICESET,
+    sizeof(_DeviceSetGet_t),
+    sizeof(_BasicResponse_t)
+};
+
+int32_t cc3100::sl_DevSet(const uint8_t DeviceSetId, const uint8_t Option, const uint8_t ConfigLen, const uint8_t *pValues)
+{
+    _SlDeviceMsgSet_u         Msg;
+    _SlCmdExt_t               CmdExt;
+    
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.TxPayloadLen = (ConfigLen+3) & (~3);
+    
+    CmdExt.pTxPayload = (uint8_t *)pValues;
+    
+
+
+    Msg.Cmd.DeviceSetId    = DeviceSetId;
+    Msg.Cmd.ConfigLen   = ConfigLen;
+    Msg.Cmd.Option   = Option;
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlDeviceSetCmdCtrl, &Msg, &CmdExt));
+
+    return (int16_t)Msg.Rsp.status;
+}
+#endif
+
+/******************************************************************************
+sl_UartSetMode
+******************************************************************************/
+#ifdef SL_IF_TYPE_UART
+typedef union {
+    _DevUartSetModeCommand_t	  Cmd;
+    _DevUartSetModeResponse_t     Rsp;
+} _SlUartSetModeMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_UartSetMode)
+const _SlCmdCtrl_t _SlUartSetModeCmdCtrl = {
+    SL_OPCODE_DEVICE_SETUARTMODECOMMAND,
+    sizeof(_DevUartSetModeCommand_t),
+    sizeof(_DevUartSetModeResponse_t)
+};
+
+int16_t cc3100::sl_UartSetMode(const SlUartIfParams_t* pUartParams)
+{
+    _SlUartSetModeMsg_u Msg;
+    uint32_t magicCode = 0xFFFFFFFF;
+
+    Msg.Cmd.BaudRate = pUartParams->BaudRate;
+    Msg.Cmd.FlowControlEnable = pUartParams->FlowControlEnable;
+
+
+    VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&_SlUartSetModeCmdCtrl, &Msg, NULL));
+
+    /* cmd response OK, we can continue with the handshake */
+    if (SL_RET_CODE_OK == Msg.Rsp.status) {
+        sl_IfMaskIntHdlr();
+
+        /* Close the comm port */
+        sl_IfClose(g_pCB->FD);
+
+        /* Re-open the comm port */
+        sl_IfOpen((void * )pUartParams, UART_IF_OPEN_FLAG_RE_OPEN);
+        sl_IfUnMaskIntHdlr();
+
+        /* send the magic code and wait for the response */
+        sl_IfWrite(g_pCB->FD, (uint8_t* )&magicCode, 4);
+
+        magicCode = UART_SET_MODE_MAGIC_CODE;
+        sl_IfWrite(g_pCB->FD, (uint8_t* )&magicCode, 4);
+
+        /* clear magic code */
+        magicCode = 0;
+
+        /* wait (blocking) till the magic code to be returned from device */
+        sl_IfRead(g_pCB->FD, (uint8_t* )&magicCode, 4);
+
+        /* check for the received magic code matching */
+        if (UART_SET_MODE_MAGIC_CODE != magicCode) {
+            _SL_ASSERT(0);
+        }
+    }
+
+    return (int16_t)Msg.Rsp.status;
+}
+#endif
+#endif
+
+}//namespace
+
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,827 @@
+/*
+ * device.h - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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.
+ *
+*/
+
+#ifndef DEVICE_H_
+#define DEVICE_H_
+
+/*****************************************************************************/
+/* Include files                                                             */
+/*****************************************************************************/
+#include "mbed.h"
+#include "cc3100_simplelink.h"
+#include "cc3100_driver.h"
+#include "cc3100_wlan_rx_filters.h"
+
+#include "cc3100_spi.h"
+#include "cc3100_netcfg.h"
+
+namespace mbed_cc3100 {
+
+/*!
+
+    \addtogroup device
+    @{
+
+*/
+    const int16_t ROLE_UNKNOWN_ERR          =            -1;
+
+    const uint16_t   MAX_BUFF_SIZE =  1460;
+    extern uint32_t  g_PingPacketsRecv;
+    extern uint32_t  g_GatewayIP;
+    extern uint32_t  g_StationIP;
+    extern uint32_t  g_DestinationIP;
+    extern uint32_t  g_BytesReceived; // variable to store the file size 
+    extern uint32_t  g_Status;
+    extern uint8_t   g_buff[MAX_BUFF_SIZE+1];
+    extern int32_t   g_SockID;
+
+
+/* File on the serial flash */
+#define FILE_NAME "cc3000_module.pdf"
+#define HOST_NAME       "www.ti.com"
+
+#define HTTP_FILE_NOT_FOUND    "404 Not Found" /* HTTP file not found response */
+#define HTTP_STATUS_OK         "200 OK"  /* HTTP status ok response */
+#define HTTP_CONTENT_LENGTH    "Content-Length:"  /* HTTP content length header */
+#define HTTP_TRANSFER_ENCODING "Transfer-Encoding:" /* HTTP transfer encoding header */
+#define HTTP_ENCODING_CHUNKED  "chunked" /* HTTP transfer encoding header value */
+#define HTTP_CONNECTION        "Connection:" /* HTTP Connection header */
+#define HTTP_CONNECTION_CLOSE  "close"  /* HTTP Connection header value */
+#define HTTP_END_OF_HEADER  "\r\n\r\n"  /* string marking the end of headers in response */
+
+/*****************************************************************************/
+/* Macro declarations                                                        */
+/*****************************************************************************/
+
+const uint16_t IP_LEASE_TIME    =    3600;
+
+const uint16_t SIZE_45K      =  46080;  /* Serial flash file size 45 KB */
+const uint16_t READ_SIZE     =  1450;
+const uint8_t SPACE          =  32;
+
+const uint16_t PING_INTERVAL   =   1000;
+const uint8_t  PING_SIZE       =   20;
+const uint16_t PING_TIMEOUT    =   3000;
+const uint8_t  PING_ATTEMPTS   =   3;
+const uint8_t  PING_PKT_SIZE   =   20; 
+
+const uint8_t SL_STOP_TIMEOUT    =    0xFF;
+
+/* SL internal Error codes */
+
+/* Receive this error in case there are no resources to issue the command
+   If possible, increase the number of MAX_CUNCURENT_ACTIONS (result in memory increase)
+   If not, try again later */
+const int16_t SL_POOL_IS_EMPTY  = (-2000);
+
+/* Receive this error in case a given length for RX buffer was too small.
+   Receive payload was bigger than the given buffer size. Therefore, payload is cut according to receive size
+   Recommend to increase buffer size */
+const int16_t SL_ESMALLBUF      = (-2001);
+
+/* Receive this error in case zero length is supplied to a "get" API
+   Recommend to supply length according to requested information (view options defines for help) */
+const int16_t SL_EZEROLEN       = (-2002);
+
+/* User supplied invalid parameter */
+const int16_t SL_INVALPARAM     = (-2003);
+
+/* Failed to open interface  */
+const int16_t SL_BAD_INTERFACE  = (-2004);
+
+/* End of SL internal Error codes */
+
+/*****************************************************************************/
+/* Errors returned from the general error async event                        */
+/*****************************************************************************/        
+    
+/* Use bit 32: Lower bits of status variable are used for NWP events
+ *      1 in a 'status_variable', the device has completed the ping operation
+ *      0 in a 'status_variable', the device has not completed the ping operation
+ */
+//const uint32_t STATUS_BIT_PING_DONE = 31;
+
+/* Status bits - These are used to set/reset the corresponding bits in a 'status_variable' */
+typedef enum {
+    STATUS_BIT_CONNECTION =  0, /* If this bit is:
+                                 *      1 in a 'status_variable', the device is connected to the AP
+                                 *      0 in a 'status_variable', the device is not connected to the AP
+                                 */
+
+    STATUS_BIT_STA_CONNECTED,    /* If this bit is:
+                                  *      1 in a 'status_variable', client is connected to device
+                                  *      0 in a 'status_variable', client is not connected to device
+                                  */
+
+    STATUS_BIT_IP_ACQUIRED,       /* If this bit is:
+                                   *      1 in a 'status_variable', the device has acquired an IP
+                                   *      0 in a 'status_variable', the device has not acquired an IP
+                                   */
+
+    STATUS_BIT_IP_LEASED,           /* If this bit is:
+                                      *      1 in a 'status_variable', the device has leased an IP
+                                      *      0 in a 'status_variable', the device has not leased an IP
+                                      */
+
+    STATUS_BIT_CONNECTION_FAILED,   /* If this bit is:
+                                     *      1 in a 'status_variable', failed to connect to device
+                                     *      0 in a 'status_variable'
+                                     */
+
+    STATUS_BIT_P2P_NEG_REQ_RECEIVED,/* If this bit is:
+                                     *      1 in a 'status_variable', connection requested by remote wifi-direct device
+                                     *      0 in a 'status_variable',
+                                     */
+    STATUS_BIT_SMARTCONFIG_DONE,    /* If this bit is:
+                                     *      1 in a 'status_variable', smartconfig completed
+                                     *      0 in a 'status_variable', smartconfig event couldn't complete
+                                     */
+
+    STATUS_BIT_SMARTCONFIG_STOPPED,  /* If this bit is:
+                                     *      1 in a 'status_variable', smartconfig process stopped
+                                     *      0 in a 'status_variable', smartconfig process running
+                                     */
+                                     
+    STATUS_BIT_PING_DONE = 31
+                                     /* Use bit 32: Lower bits of status variable are used for NWP events
+                                      *      1 in a 'status_variable', the device has completed the ping operation
+                                      *      0 in a 'status_variable', the device has not completed the ping operation
+                                      */                                 
+
+} e_StatusBits;        
+    
+/* Application specific status/error codes */
+typedef enum {
+    LAN_CONNECTION_FAILED = -0x7D0,        /* Choosing this number to avoid overlap with host-driver's error codes */
+    INTERNET_CONNECTION_FAILED = LAN_CONNECTION_FAILED - 1,
+    DEVICE_NOT_IN_STATION_MODE = INTERNET_CONNECTION_FAILED - 1,
+    HTTP_SEND_ERROR = DEVICE_NOT_IN_STATION_MODE - 1,
+    HTTP_RECV_ERROR = HTTP_SEND_ERROR - 1,
+    HTTP_INVALID_RESPONSE = HTTP_RECV_ERROR -1,
+    SNTP_SEND_ERROR = DEVICE_NOT_IN_STATION_MODE - 1,
+    SNTP_RECV_ERROR = SNTP_SEND_ERROR - 1,
+    SNTP_SERVER_RESPONSE_ERROR = SNTP_RECV_ERROR - 1,
+    INVALID_HEX_STRING = DEVICE_NOT_IN_STATION_MODE - 1,
+    TCP_RECV_ERROR = INVALID_HEX_STRING - 1,
+    TCP_SEND_ERROR = TCP_RECV_ERROR - 1,
+    FILE_NOT_FOUND_ERROR = TCP_SEND_ERROR - 1,
+    INVALID_SERVER_RESPONSE = FILE_NOT_FOUND_ERROR - 1,
+    FORMAT_NOT_SUPPORTED = INVALID_SERVER_RESPONSE - 1,
+    FILE_WRITE_ERROR = FORMAT_NOT_SUPPORTED - 1,
+    INVALID_FILE = FILE_WRITE_ERROR - 1,
+
+    STATUS_CODE_MAX = -0xBB8
+} e_AppStatusCodes;    
+    
+    /* Send types */
+typedef enum {
+    SL_ERR_SENDER_HEALTH_MON,
+    SL_ERR_SENDER_CLI_UART,
+    SL_ERR_SENDER_SUPPLICANT,
+    SL_ERR_SENDER_NETWORK_STACK,
+    SL_ERR_SENDER_WLAN_DRV_IF,
+    SL_ERR_SENDER_WILINK,
+    SL_ERR_SENDER_INIT_APP,
+    SL_ERR_SENDER_NETX,
+    SL_ERR_SENDER_HOST_APD,
+    SL_ERR_SENDER_MDNS,
+    SL_ERR_SENDER_HTTP_SERVER,
+    SL_ERR_SENDER_DHCP_SERVER,
+    SL_ERR_SENDER_DHCP_CLIENT,
+    SL_ERR_DISPATCHER,
+    SL_ERR_NUM_SENDER_LAST=0xFF
+} SlErrorSender_e;
+
+/* Error codes */
+const int8_t SL_ERROR_STATIC_ADDR_SUBNET_ERROR                  = (-60);  /* network stack error*/
+const int8_t SL_ERROR_ILLEGAL_CHANNEL                           = (-61);  /* supplicant error */
+const int8_t SL_ERROR_SUPPLICANT_ERROR                          = (-72);  /* init error code */
+const int8_t SL_ERROR_HOSTAPD_INIT_FAIL                         = (-73);  /* init error code */
+const int8_t SL_ERROR_HOSTAPD_INIT_IF_FAIL                      = (-74);  /* init error code */
+const int8_t SL_ERROR_WLAN_DRV_INIT_FAIL                        = (-75);  /* init error code */
+const int8_t SL_ERROR_WLAN_DRV_START_FAIL                       = (-76);  /* wlan start error */
+const int8_t SL_ERROR_FS_FILE_TABLE_LOAD_FAILED                 = (-77);  /* init file system failed */
+const int8_t SL_ERROR_PREFERRED_NETWORKS_FILE_LOAD_FAILED       = (-78);  /* init file system failed */
+const int8_t SL_ERROR_HOSTAPD_BSSID_VALIDATION_ERROR            = (-79);  /* Ap configurations BSSID error */
+const int8_t SL_ERROR_HOSTAPD_FAILED_TO_SETUP_INTERFACE         = (-80);  /* Ap configurations interface error */
+const int8_t SL_ERROR_MDNS_ENABLE_FAIL                          = (-81);  /* mDNS enable failed                */
+const int8_t SL_ERROR_HTTP_SERVER_ENABLE_FAILED                 = (-82);  /* HTTP server enable failed         */
+const int8_t SL_ERROR_DHCP_SERVER_ENABLE_FAILED                 = (-83);  /* DHCP server enable failed         */
+const int8_t SL_ERROR_PREFERRED_NETWORK_LIST_FULL               = (-93);  /* supplicant error  */
+const int8_t SL_ERROR_PREFERRED_NETWORKS_FILE_WRITE_FAILED      = (-94);  /* supplicant error  */
+const int8_t SL_ERROR_DHCP_CLIENT_RENEW_FAILED                  = (-100); /* DHCP client error */
+/* WLAN Connection management status */
+const int8_t SL_ERROR_CON_MGMT_STATUS_UNSPECIFIED               = (-102);
+const int8_t SL_ERROR_CON_MGMT_STATUS_AUTH_REJECT               = (-103);
+const int8_t SL_ERROR_CON_MGMT_STATUS_ASSOC_REJECT              = (-104);
+const int8_t SL_ERROR_CON_MGMT_STATUS_SECURITY_FAILURE          = (-105);
+const int8_t SL_ERROR_CON_MGMT_STATUS_AP_DEAUTHENTICATE         = (-106);
+const int8_t SL_ERROR_CON_MGMT_STATUS_AP_DISASSOCIATE           = (-107);
+const int8_t SL_ERROR_CON_MGMT_STATUS_ROAMING_TRIGGER           = (-108);
+const int8_t SL_ERROR_CON_MGMT_STATUS_DISCONNECT_DURING_CONNECT = (-109);
+const int8_t SL_ERROR_CON_MGMT_STATUS_SG_RESELECT               = (-110);
+const int8_t SL_ERROR_CON_MGMT_STATUS_ROC_FAILURE               = (-111);
+const int8_t SL_ERROR_CON_MGMT_STATUS_MIC_FAILURE               = (-112);
+/* end of WLAN connection management error statuses */
+const int8_t SL_ERROR_WAKELOCK_ERROR_PREFIX                     = (-115);  /* Wake lock expired */
+const int8_t SL_ERROR_LENGTH_ERROR_PREFIX                       = (-116);  /* Uart header length error */
+const int8_t SL_ERROR_MDNS_CREATE_FAIL                          = (-121);  /* mDNS create failed */
+const int8_t SL_ERROR_GENERAL_ERROR                             = (-127);
+
+
+
+const int8_t SL_DEVICE_GENERAL_CONFIGURATION           = (1);
+const int8_t SL_DEVICE_GENERAL_CONFIGURATION_DATE_TIME = (11);
+const int8_t SL_DEVICE_GENERAL_VERSION                 = (12);
+const int8_t SL_DEVICE_STATUS                          = (2);
+
+/*
+    Declare the different event group classifications
+    The SimpleLink device send asynchronous events. Each event has a group
+    classification according to its nature.
+*/
+#if 1
+/* SL_EVENT_CLASS_WLAN connection user events */
+const int8_t SL_WLAN_CONNECT_EVENT                   =  (1);
+const int8_t SL_WLAN_DISCONNECT_EVENT                =  (2);
+/* WLAN Smart Config user events */
+const int8_t SL_WLAN_SMART_CONFIG_COMPLETE_EVENT     =  (3);
+const int8_t SL_WLAN_SMART_CONFIG_STOP_EVENT         =  (4);
+/* WLAN AP user events */
+const int8_t SL_WLAN_STA_CONNECTED_EVENT             =  (5);
+const int8_t SL_WLAN_STA_DISCONNECTED_EVENT          =  (6);
+/* WLAN P2P user events */
+const int8_t SL_WLAN_P2P_DEV_FOUND_EVENT             =  (7);
+const int8_t    SL_WLAN_P2P_NEG_REQ_RECEIVED_EVENT   =  (8);
+const int8_t SL_WLAN_CONNECTION_FAILED_EVENT         =  (9);
+/* SL_EVENT_CLASS_DEVICE user events */
+const int8_t SL_DEVICE_FATAL_ERROR_EVENT             =  (1);
+const int8_t SL_DEVICE_ABORT_ERROR_EVENT             =  (2);
+/* SL_EVENT_CLASS_BSD user events */
+const int8_t    SL_SOCKET_TX_FAILED_EVENT            =  (1);
+const int8_t SL_SOCKET_ASYNC_EVENT                   =  (2);
+/* SL_EVENT_CLASS_NETAPP user events */
+const int8_t    SL_NETAPP_IPV4_IPACQUIRED_EVENT      =  (1);
+const int8_t    SL_NETAPP_IPV6_IPACQUIRED_EVENT      =  (2);
+const int8_t SL_NETAPP_IP_LEASED_EVENT               =  (3);
+const int8_t SL_NETAPP_IP_RELEASED_EVENT             =  (4);
+
+/* Server Events */
+const int8_t SL_NETAPP_HTTPGETTOKENVALUE_EVENT       =   (1);
+const int8_t SL_NETAPP_HTTPPOSTTOKENVALUE_EVENT      =   (2);
+#endif
+
+/*
+    Declare the different event group classifications for sl_DevGet
+    for getting status indications
+ */
+
+/* Events list to mask/unmask*/
+const int8_t SL_EVENT_CLASS_GLOBAL                   =  (0);
+const int8_t SL_EVENT_CLASS_DEVICE                   =  (1);
+const int8_t SL_EVENT_CLASS_WLAN                     =  (2);
+const int8_t SL_EVENT_CLASS_BSD                      =  (3);
+const int8_t SL_EVENT_CLASS_NETAPP                   =  (4);
+const int8_t SL_EVENT_CLASS_NETCFG                   =  (5);
+const int8_t SL_EVENT_CLASS_FS                       =  (6);
+
+
+/******************  DEVICE CLASS status ****************/
+const uint32_t EVENT_DROPPED_DEVICE_ASYNC_GENERAL_ERROR         = (0x00000001L);
+const uint32_t STATUS_DEVICE_SMART_CONFIG_ACTIVE                = (0x80000000L);
+
+/******************  WLAN CLASS status ****************/
+const uint32_t EVENT_DROPPED_WLAN_WLANASYNCONNECTEDRESPONSE     = (0x00000001L);
+const uint32_t EVENT_DROPPED_WLAN_WLANASYNCDISCONNECTEDRESPONSE = (0x00000002L);
+const uint32_t EVENT_DROPPED_WLAN_STA_CONNECTED                 = (0x00000004L);
+const uint32_t EVENT_DROPPED_WLAN_STA_DISCONNECTED              = (0x00000008L);
+const uint32_t STATUS_WLAN_STA_CONNECTED                        = (0x80000000L);
+
+/******************  NETAPP CLASS status ****************/
+const uint32_t EVENT_DROPPED_NETAPP_IPACQUIRED                  = (0x00000001L);
+const uint32_t EVENT_DROPPED_NETAPP_IPACQUIRED_V6               = (0x00000002L);
+const uint32_t EVENT_DROPPED_NETAPP_IP_LEASED                   = (0x00000004L);
+const uint32_t EVENT_DROPPED_NETAPP_IP_RELEASED                 = (0x00000008L);
+
+/******************  BSD CLASS status ****************/
+const uint32_t EVENT_DROPPED_SOCKET_TXFAILEDASYNCRESPONSE       = (0x00000001L);
+
+/******************  FS CLASS  ****************/
+
+/*****************************************************************************/
+/* Structure/Enum declarations                                               */
+/*****************************************************************************/
+
+#ifdef SL_IF_TYPE_UART
+typedef struct {
+    uint32_t             BaudRate;
+    uint8_t              FlowControlEnable;
+    uint8_t              CommPort;
+} SlUartIfParams_t;
+#endif
+
+typedef struct {
+    uint32_t               ChipId;
+    uint32_t               FwVersion[4];
+    uint8_t                PhyVersion[4];
+} _SlPartialVersion;
+
+typedef struct {
+    _SlPartialVersion ChipFwAndPhyVersion;
+    uint32_t               NwpVersion[4];
+    uint16_t               RomVersion;
+    uint16_t               Padding;
+} SlVersionFull;
+
+typedef struct
+{
+    uint32_t                AbortType;
+    uint32_t                AbortData;
+}sl_DeviceReportAbort;
+
+typedef struct {
+    int8_t                status;
+    SlErrorSender_e        sender;
+} sl_DeviceReport;
+
+typedef union {
+    sl_DeviceReport           deviceEvent;
+    sl_DeviceReportAbort      deviceReport;
+} _SlDeviceEventData_u;
+
+typedef struct {
+    uint32_t             Event;
+    _SlDeviceEventData_u EventData;
+} SlDeviceEvent_t;
+
+typedef struct {
+    /* time */
+    uint32_t                sl_tm_sec;
+    uint32_t                sl_tm_min;
+    uint32_t                sl_tm_hour;
+    /* date */
+    uint32_t                sl_tm_day; /* 1-31 */
+    uint32_t                sl_tm_mon; /* 1-12 */
+    uint32_t                sl_tm_year; /*  YYYY 4 digits  */
+    uint32_t                sl_tm_week_day; /* not required */
+    uint32_t                sl_tm_year_day; /* not required */
+    uint32_t                reserved[3];
+} SlDateTime_t;
+
+/******************************************************************************/
+/* Type declarations                                                          */
+/******************************************************************************/
+typedef void (*P_INIT_CALLBACK)(uint32_t Status);
+
+class cc3100_netcfg;
+
+class cc3100
+{
+
+public:
+
+    cc3100(PinName button1_irq, PinName button2_irq, PinName cc3100_irq, PinName cc3100_nHIB, PinName cc3100_cs, SPI cc3100_spi);
+
+    ~cc3100();
+
+    /*****************************************************************************/
+    /* Function prototypes                                                       */
+    /*****************************************************************************/
+    int32_t initializeAppVariables();
+    
+    int32_t establishConnectionWithAP(void);
+    
+    int32_t checkLanConnection(void);
+    
+    int32_t checkInternetConnection(void);
+    
+    int32_t createUDPConnection(void);
+    
+    int32_t createConnection(uint32_t DestinationIP);
+
+    int32_t getChunkSize(int32_t *len, uint8_t **p_Buff, uint32_t *chunk_size);
+    
+    int32_t hexToi(unsigned char *ptr);
+    
+//    int32_t getFile(void);
+    
+    int32_t disconnectFromAP(void);
+    
+    uint16_t itoa(int16_t cNum, uint8_t *cString);
+    
+    int32_t configureSimpleLinkToDefaultState(void);
+    
+    int16_t _sl_GetStartResponseConvert(uint32_t Status);
+
+    void _sl_HandleAsync_InitComplete(void *pVoidBuf); 
+    
+    bool IS_PING_DONE(uint32_t status_variable,const uint32_t bit);
+    bool IS_CONNECTED(uint32_t status_variable,const uint32_t bit);
+    bool IS_STA_CONNECTED(uint32_t status_variable,const uint32_t bit);
+    bool IS_IP_ACQUIRED(uint32_t status_variable,const uint32_t bit);
+    bool IS_IP_LEASED(uint32_t status_variable,const uint32_t bit);
+    bool IS_CONNECTION_FAILED(uint32_t status_variable,const uint32_t bit);
+    bool IS_P2P_NEG_REQ_RECEIVED(uint32_t status_variable,const uint32_t bit);
+    bool IS_SMARTCONFIG_DONE(uint32_t status_variable,const uint32_t bit);
+    bool IS_SMARTCONFIG_STOPPED(uint32_t status_variable,const uint32_t bit);
+    
+    
+    
+    void CLR_STATUS_BIT(uint32_t status_variable, const uint32_t bit);
+    void SET_STATUS_BIT(uint32_t status_variable, const uint32_t bit);
+    
+
+    /*!
+        \brief Start the SimpleLink device
+
+        This function initialize the communication interface, set the enable pin
+        of the device, and call to the init complete callback.
+
+        \param[in]      pIfHdl              Opened Interface Object. In case the interface
+                                            must be opened outside the SimpleLink Driver, the
+                                            user might give the handler to be used in \n
+                                            any access of the communication interface with the
+                                            device (UART/SPI). \n
+                                            The SimpleLink driver will open an interface port
+                                            only if this parameter is null! \n
+        \param[in]      pDevName            The name of the device to open. Could be used when
+                                            the pIfHdl is null, to transfer information to the
+                                            open interface function \n
+                                            This pointer could be used to pass additional information to
+                                            sl_IfOpen in case it is required (e.g. UART com port name)
+        \param[in]      pInitCallBack       Pointer to function that would be called
+                                            on completion of the initialization process.\n
+                                            If this parameter is NULL the function is
+                                            blocked until the device initialization
+                                            is completed, otherwise the function returns
+                                            immediately.
+
+        \return         Returns the current active role (STA/AP/P2P) or an error code:
+                        - ROLE_STA, ROLE_AP, ROLE_P2P in case of success,
+                          otherwise in failure one of the following is return:
+                        - ROLE_STA_ERR  (Failure to load MAC/PHY in STA role)
+                        - ROLE_AP_ERR  (Failure to load MAC/PHY in AP role)
+                        - ROLE_P2P_ERR  (Failure to load MAC/PHY in P2P role)
+
+
+         \sa             sl_Stop
+
+        \note           belongs to \ref basic_api
+
+        \warning        This function must be called before any other SimpleLink API is used, or after sl_Stop is called for reinit the device
+        \par            Example:
+        \code
+                       An example for open interface without callback routine. The interface name and handler are
+                       handled by the sl_IfOpen routine:
+
+                        if( sl_Start(NULL, NULL, NULL) < 0 )
+                       {
+                           LOG("Error opening interface to device\n");
+                       }
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_Start)
+    int16_t sl_Start(const void* pIfHdl, int8_t*  pDevName, const P_INIT_CALLBACK pInitCallBack);
+#endif
+
+    /*!
+        \brief Stop the SimpleLink device
+
+        This function clears the enable pin of the device, closes the communication \n
+        interface and invokes the stop complete callback
+
+        \param[in]      timeout                       Stop timeout in msec. Should be used to give the device time to finish \n
+                                                      any transmission/reception that is not completed when the function was called. \n
+                        Additional options:
+                        - 0                             Enter to hibernate immediately \n
+                        - 0xFFFF                        Host waits for device's response before \n
+                                                        hibernating, without timeout protection \n
+                        - 0 < Timeout[msec] < 0xFFFF    Host waits for device's response before \n
+                                                        hibernating, with a defined timeout protection \n
+                                                        This timeout defines the max time to wait. The NWP \n
+                                                        response can be sent earlier than this timeout.
+
+        \return         On success, zero is returned. On error, -1 is returned
+
+        \sa             sl_Start
+
+        \note           This API will shutdown the device and invoke the "i/f close" function regardless \n
+                        if it was opened implicitly or explicitly. \n
+                        It is up to the platform interface library to properly handle interface close \n
+                        routine \n
+                        belongs to \ref basic_api \n
+        \warning
+    */
+#if _SL_INCLUDE_FUNC(sl_Stop)
+    int16_t sl_Stop(const uint16_t timeout);
+#endif
+
+
+    /*!
+        \brief     Internal function for setting device configurations
+
+        \return    On success, zero is returned. On error, -1 is
+                   returned
+
+        \param[in] DeviceSetId   configuration id
+        \param[in] Option         configurations option
+        \param[in] ConfigLen     configurations len
+        \param[in] pValues         configurations values
+
+        \sa
+        \note
+        \warning
+        \par   Examples:
+        \code
+             Setting device time and date example:
+
+             SlDateTime_t dateTime= {0};
+             dateTime.sl_tm_day =   (uint32_t)23;          // Day of month (DD format) range 1-13
+             dateTime.sl_tm_mon =   (uint32_t)6;           // Month (MM format) in the range of 1-12
+             dateTime.sl_tm_year =  (uint32_t)2014;        // Year (YYYY format)
+             dateTime.sl_tm_hour =  (uint32_t)17;          // Hours in the range of 0-23
+             dateTime.sl_tm_min =   (uint32_t)55;          // Minutes in the range of 0-59
+             dateTime.sl_tm_sec =   (uint32_t)22;          // Seconds in the range of  0-59
+             sl_DevSet(SL_DEVICE_GENERAL_CONFIGURATION,
+                       SL_DEVICE_GENERAL_CONFIGURATION_DATE_TIME,
+                       sizeof(SlDateTime_t),
+                       (uint8_t *)(&dateTime));
+
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_DevSet)
+    int32_t sl_DevSet(const uint8_t DeviceSetId , const uint8_t Option, const uint8_t ConfigLen, const uint8_t *pValues);
+#endif
+
+    /*!
+        \brief      Internal function for getting device configurations
+        \return     On success, zero is returned. On error, -1 is
+                    returned
+        \param[in]  DeviceGetId   configuration id - example SL_DEVICE_STATUS
+        \param[out] pOption   Get configurations option, example for get status options
+                                - SL_EVENT_CLASS_GLOBAL
+                                - SL_EVENT_CLASS_DEVICE
+                                - SL_EVENT_CLASS_WLAN
+                                - SL_EVENT_CLASS_BSD
+                                - SL_EVENT_CLASS_NETAPP
+                                - SL_EVENT_CLASS_NETCFG
+                                - SL_EVENT_CLASS_FS
+        \param[out] pConfigLen   The length of the allocated memory as input, when the
+                                 function complete, the value of this parameter would be
+                                 the len that actually read from the device.\n
+                                 If the device return length that is longer from the input
+                                 value, the function will cut the end of the returned structure
+                                 and will return SL_ESMALLBUF
+        \param[out] pValues      Get configurations values
+        \sa
+        \note
+        \warning
+        \par        Examples:
+        \code
+         Example for getting WLAN class status:
+         uint32_t statusWlan;
+         uint8_t pConfigOpt;
+         uint8_t pConfigLen;
+         pConfigLen = sizeof(_u32);
+         pConfigOpt = SL_EVENT_CLASS_WLAN;
+         sl_DevGet(SL_DEVICE_STATUS,&pConfigOpt,&pConfigLen,(uint8_t *)(&statusWlan));
+         Example for getting version:
+         SlVersionFull ver;
+         pConfigLen = sizeof(ver);
+         pConfigOpt = SL_DEVICE_GENERAL_VERSION;
+         sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION,&pConfigOpt,&pConfigLen,(uint8_t *)(&ver));
+         printf("CHIP %d\nMAC 31.%d.%d.%d.%d\nPHY %d.%d.%d.%d\nNWP %d.%d.%d.%d\nROM %d\nHOST %d.%d.%d.%d\n",
+                 ver.ChipFwAndPhyVersion.ChipId,
+                 ver.ChipFwAndPhyVersion.FwVersion[0],ver.ChipFwAndPhyVersion.FwVersion[1],
+                 ver.ChipFwAndPhyVersion.FwVersion[2],ver.ChipFwAndPhyVersion.FwVersion[3],
+                 ver.ChipFwAndPhyVersion.PhyVersion[0],ver.ChipFwAndPhyVersion.PhyVersion[1],
+                 ver.ChipFwAndPhyVersion.PhyVersion[2],ver.ChipFwAndPhyVersion.PhyVersion[3],
+                 ver.NwpVersion[0],ver.NwpVersion[1],ver.NwpVersion[2],ver.NwpVersion[3],
+                 ver.RomVersion,
+                 SL_MAJOR_VERSION_NUM,SL_MINOR_VERSION_NUM,SL_VERSION_NUM,SL_SUB_VERSION_NUM);
+
+         \endcode
+         \code
+             Getting Device time and date example:
+
+             SlDateTime_t dateTime =  {0};
+             int8_t configLen = sizeof(SlDateTime_t);
+             int8_t configOpt = SL_DEVICE_GENERAL_CONFIGURATION_DATE_TIME;
+             sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION,&configOpt, &configLen,(uint8_t *)(&dateTime));
+
+             printf("Day %d,Mon %d,Year %d,Hour %,Min %d,Sec %d\n",dateTime.sl_tm_day,dateTime.sl_tm_mon,dateTime.sl_tm_year
+                     dateTime.sl_tm_hour,dateTime.sl_tm_min,dateTime.sl_tm_sec);
+         \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_DevGet)
+    int32_t sl_DevGet(const uint8_t DeviceGetId, uint8_t *pOption,uint8_t *pConfigLen, uint8_t *pValues);
+#endif
+
+
+    /*!
+        \brief          Set asynchronous event mask
+
+        Mask asynchronous events from the device. Masked events do not
+        generate asynchronous messages from the device.
+        By default - all events are active
+
+        \param[in]      EventClass          The classification groups that the
+                                            mask is referred to. Need to be one of
+                                            the following:
+                                            - SL_EVENT_CLASS_GLOBAL
+                                            - SL_EVENT_CLASS_DEVICE
+                                            - SL_EVENT_CLASS_WLAN
+                                            - SL_EVENT_CLASS_BSD
+                                            - SL_EVENT_CLASS_NETAPP
+                                            - SL_EVENT_CLASS_NETCFG
+                                            - SL_EVENT_CLASS_FS
+
+
+        \param[in]      Mask               Event Mask bitmap. Valid mask are (per group):
+                                            - SL_EVENT_CLASS_WLAN user events
+                                              - SL_WLAN_CONNECT_EVENT
+                                              - SL_WLAN_DISCONNECT_EVENT
+                                            - SL_EVENT_CLASS_DEVICE user events
+                                              - SL_DEVICE_FATAL_ERROR_EVENT
+                                            - SL_EVENT_CLASS_BSD user events
+                                              - SL_SOCKET_TX_FAILED_EVENT
+                                              - SL_SOCKET_ASYNC_EVENT
+                                            - SL_EVENT_CLASS_NETAPP user events
+                                              - SL_NETAPP_IPV4_IPACQUIRED_EVENT
+                                              - SL_NETAPP_IPV6_IPACQUIRED_EVENT
+
+        \return         On success, zero is returned. On error, -1 is returned
+
+        \sa             sl_EventMaskGet
+
+        \note           belongs to \ref ext_api
+
+        \warning
+        \par           Example:
+        \code
+
+        An example of masking connection/disconnection async events from WLAN class:
+                       sl_EventMaskSet(SL_EVENT_CLASS_WLAN, (SL_WLAN_CONNECT_EVENT | SL_WLAN_DISCONNECT_EVENT) );
+
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_EventMaskSet)
+    int16_t sl_EventMaskSet(const uint8_t EventClass , const uint32_t Mask);
+#endif
+
+    /*!
+        \brief Get current event mask of the device
+
+        return the events bit mask from the device. In case that event is
+        masked, the device is not sending this event.
+
+        \param[in]      EventClass          The classification groups that the
+                                            mask is referred to. Need to be one of
+                                            the following:
+                                            - SL_EVENT_CLASS_GLOBAL
+                                            - SL_EVENT_CLASS_DEVICE
+                                            - SL_EVENT_CLASS_WLAN
+                                            - SL_EVENT_CLASS_BSD
+                                            - SL_EVENT_CLASS_NETAPP
+                                            - SL_EVENT_CLASS_NETCFG
+                                            - SL_EVENT_CLASS_FS
+
+        \param[out]      pMask              Pointer to Mask bitmap where the
+                                            value should be stored. Bitmasks are the same as in \ref sl_EventMaskSet
+
+        \return         On success, zero is returned. On error, -1 is returned
+
+        \sa             sl_EventMaskSet
+
+        \note           belongs to \ref ext_api
+
+        \warning
+        \par           Example:
+        \code
+
+        An example of getting an event mask for WLAN class
+        uint32_t maskWlan;
+                       sl_StatusGet(SL_EVENT_CLASS_WLAN,&maskWlan);
+
+       \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_EventMaskGet)
+    int16_t sl_EventMaskGet(const uint8_t EventClass, uint32_t *pMask);
+#endif
+
+
+    /*!
+        \brief the simple link task entry
+
+        \Param
+        This function must be called from the main loop or from dedicated thread in
+        the following cases:
+            - Non-Os Platform - should be called from the mail loop
+            - Multi Threaded Platform when the user does not implement the external spawn functions -
+               should be called from dedicated thread allocated to the simplelink driver.
+               In this mode the function never return.
+
+        \return         None
+
+        \sa             sl_Stop
+
+        \note           belongs to \ref basic_api
+
+        \warning        This function must be called from a thread that is start running before
+                        any call to other simple link API
+    */
+#if _SL_INCLUDE_FUNC(sl_Task)
+    void sl_Task(void);
+#endif
+
+
+    /*!
+        \brief Setting the internal uart mode
+
+        \param[in]      pUartParams          Pointer to the uart configuration parameter set:
+                                             baudrate     - up to 711 Kbps
+                                             flow control - enable/disable
+                                             comm port    - the comm port number
+
+        \return         On success zero is returned, otherwise - Failed.
+
+        \sa             sl_Stop
+
+        \note           belongs to \ref basic_api
+
+        \warning        This function must consider the host uart capability
+    */
+#ifdef SL_IF_TYPE_UART
+#if _SL_INCLUDE_FUNC(sl_UartSetMode)
+    int16_t sl_UartSetMode(const SlUartIfParams_t* pUartParams);
+#endif
+#endif
+
+public:
+    
+    cc3100_spi               _spi;
+    cc3100_driver            _driver;
+#ifndef SL_PLATFORM_MULTI_THREADED   
+    cc3100_nonos             _nonos;
+#endif    
+    cc3100_wlan              _wlan;
+    cc3100_wlan_rx_filters   _wlan_filters;    
+    cc3100_netapp            _netapp;
+    cc3100_fs                _fs;
+    cc3100_netcfg            _netcfg;    
+    cc3100_socket            _socket;
+    cc3100_flowcont          _flowcont;
+
+
+protected:
+    
+
+};//class
+
+}//namespace mbed_cc3100
+
+/*!
+
+ Close the Doxygen group.
+ @}
+
+ */
+
+
+#endif  /*  __DEVICE_H__ */
+
+
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_driver.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_driver.cpp	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,1432 @@
+/*
+* driver.c - CC31xx/CC32xx Host Driver Implementation
+*
+* Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+*
+*
+*  Redistribution and use in source and binary forms, with or without
+*  modification, are permitted provided that the following conditions
+*  are met:
+*
+*    Redistributions of source code must retain the above copyright
+*    notice, this list of conditions and the following disclaimer.
+*
+*    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.
+*
+*    Neither the name of Texas Instruments Incorporated nor the names of
+*    its contributors may be used to endorse or promote products derived
+*    from this software without specific prior written permission.
+*
+*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+*  "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 COPYRIGHT
+*  OWNER OR CONTRIBUTORS 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 files                                                             */
+/*****************************************************************************/
+#include "cc3100_simplelink.h"
+#include "cc3100_protocol.h"
+#include "cc3100_driver.h"
+
+#include "fPtr_func.h"
+#include "cli_uart.h"
+#include "osi.h"
+
+/*****************************************************************************/
+/* Macro declarations                                                        */
+/*****************************************************************************/
+
+namespace mbed_cc3100 {
+
+#ifndef SL_MEMORY_MGMT_DYNAMIC
+typedef struct {
+    uint32_t      Align;
+    _SlDriverCb_t DriverCB;
+    uint8_t AsyncRespBuf[SL_ASYNC_MAX_MSG_LEN];
+} _SlStatMem_t;
+
+_SlStatMem_t g_StatMem;
+#endif
+
+
+_SlDriverCb_t* g_pCB = NULL;
+
+uint8_t gFirstCmdMode = 0;
+
+const _SlSyncPattern_t g_H2NSyncPattern = H2N_SYNC_PATTERN;
+const _SlSyncPattern_t g_H2NCnysPattern = H2N_CNYS_PATTERN;
+volatile uint8_t RxIrqCnt;
+
+#ifndef SL_TINY_EXT
+const _SlActionLookup_t _SlActionLookupTable[] = {
+    {ACCEPT_ID, SL_OPCODE_SOCKET_ACCEPTASYNCRESPONSE, (_SlSpawnEntryFunc_t) &_sl_HandleAsync_Accept},
+    {CONNECT_ID, SL_OPCODE_SOCKET_CONNECTASYNCRESPONSE,(_SlSpawnEntryFunc_t) &_sl_HandleAsync_Connect},
+    {SELECT_ID, SL_OPCODE_SOCKET_SELECTASYNCRESPONSE,(_SlSpawnEntryFunc_t) &_sl_HandleAsync_Select},
+    {GETHOSYBYNAME_ID, SL_OPCODE_NETAPP_DNSGETHOSTBYNAMEASYNCRESPONSE,(_SlSpawnEntryFunc_t) &_sl_HandleAsync_DnsGetHostByName},
+    {GETHOSYBYSERVICE_ID, SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICEASYNCRESPONSE,(_SlSpawnEntryFunc_t) &_sl_HandleAsync_DnsGetHostByService},
+    {PING_ID, SL_OPCODE_NETAPP_PINGREPORTREQUESTRESPONSE, (_SlSpawnEntryFunc_t) &_sl_HandleAsync_PingResponse},
+    {START_STOP_ID, SL_OPCODE_DEVICE_STOP_ASYNC_RESPONSE,(_SlSpawnEntryFunc_t) &_sl_HandleAsync_Stop}
+
+};
+#else
+const _SlActionLookup_t _SlActionLookupTable[] = 
+{
+    {CONNECT_ID, SL_OPCODE_SOCKET_CONNECTASYNCRESPONSE,(_SlSpawnEntryFunc_t)_sl_HandleAsync_Connect},
+    {GETHOSYBYNAME_ID, SL_OPCODE_NETAPP_DNSGETHOSTBYNAMEASYNCRESPONSE,(_SlSpawnEntryFunc_t)_sl_HandleAsync_DnsGetHostByName},  
+    {START_STOP_ID, SL_OPCODE_DEVICE_STOP_ASYNC_RESPONSE,(_SlSpawnEntryFunc_t)_sl_HandleAsync_Stop}
+};
+#endif
+
+typedef struct
+{
+    uint16_t opcode;
+    uint8_t  event;
+} OpcodeKeyVal_t;
+
+/* The table translates opcode to user's event type */
+const OpcodeKeyVal_t OpcodeTranslateTable[] = 
+{
+{SL_OPCODE_WLAN_SMART_CONFIG_START_ASYNC_RESPONSE, SL_WLAN_SMART_CONFIG_COMPLETE_EVENT},
+{SL_OPCODE_WLAN_SMART_CONFIG_STOP_ASYNC_RESPONSE,SL_WLAN_SMART_CONFIG_STOP_EVENT},
+{SL_OPCODE_WLAN_STA_CONNECTED, SL_WLAN_STA_CONNECTED_EVENT},
+{SL_OPCODE_WLAN_STA_DISCONNECTED,SL_WLAN_STA_DISCONNECTED_EVENT},
+{SL_OPCODE_WLAN_P2P_DEV_FOUND,SL_WLAN_P2P_DEV_FOUND_EVENT},    
+{SL_OPCODE_WLAN_P2P_NEG_REQ_RECEIVED, SL_WLAN_P2P_NEG_REQ_RECEIVED_EVENT},
+{SL_OPCODE_WLAN_CONNECTION_FAILED, SL_WLAN_CONNECTION_FAILED_EVENT},
+{SL_OPCODE_WLAN_WLANASYNCCONNECTEDRESPONSE, SL_WLAN_CONNECT_EVENT},
+{SL_OPCODE_WLAN_WLANASYNCDISCONNECTEDRESPONSE, SL_WLAN_DISCONNECT_EVENT},
+{SL_OPCODE_NETAPP_IPACQUIRED, SL_NETAPP_IPV4_IPACQUIRED_EVENT},
+{SL_OPCODE_NETAPP_IPACQUIRED_V6, SL_NETAPP_IPV6_IPACQUIRED_EVENT},
+{SL_OPCODE_NETAPP_IP_LEASED, SL_NETAPP_IP_LEASED_EVENT},
+{SL_OPCODE_NETAPP_IP_RELEASED, SL_NETAPP_IP_RELEASED_EVENT},
+{SL_OPCODE_SOCKET_TXFAILEDASYNCRESPONSE, SL_SOCKET_TX_FAILED_EVENT},
+{SL_OPCODE_SOCKET_SOCKETASYNCEVENT, SL_SOCKET_ASYNC_EVENT}
+};
+
+/*
+
+#define SL_OPCODE_SILO_DEVICE                           ( 0x0 << SL_OPCODE_SILO_OFFSET )
+#define SL_OPCODE_SILO_WLAN                             ( 0x1 << SL_OPCODE_SILO_OFFSET )
+#define SL_OPCODE_SILO_SOCKET                           ( 0x2 << SL_OPCODE_SILO_OFFSET )
+#define SL_OPCODE_SILO_NETAPP                           ( 0x3 << SL_OPCODE_SILO_OFFSET )
+#define SL_OPCODE_SILO_NVMEM                            ( 0x4 << SL_OPCODE_SILO_OFFSET )
+#define SL_OPCODE_SILO_NETCFG                           ( 0x5 << SL_OPCODE_SILO_OFFSET )
+
+
+*/
+
+/* The Lookup table below holds the event handlers to be called according to the incoming
+    RX message SILO type */
+const _SlSpawnEntryFunc_t RxMsgClassLUT[] = {
+    (_SlSpawnEntryFunc_t)_SlDrvDeviceEventHandler, /* SL_OPCODE_SILO_DEVICE */
+#if defined(sl_WlanEvtHdlr) || defined(EXT_LIB_REGISTERED_WLAN_EVENTS)
+    (_SlSpawnEntryFunc_t)_SlDrvHandleWlanEvents,           /* SL_OPCODE_SILO_WLAN */
+#else
+    NULL,
+#endif
+#if defined (sl_SockEvtHdlr) || defined(EXT_LIB_REGISTERED_SOCK_EVENTS)
+    (_SlSpawnEntryFunc_t)_SlDrvHandleSockEvents,   /* SL_OPCODE_SILO_SOCKET */
+#else
+    NULL,
+#endif
+
+#if defined(sl_NetAppEvtHdlr) || defined(EXT_LIB_REGISTERED_NETAPP_EVENTS)
+    (_SlSpawnEntryFunc_t)_SlDrvHandleNetAppEvents, /* SL_OPCODE_SILO_NETAPP */
+#else
+    NULL,  
+#endif
+    NULL,                                          /* SL_OPCODE_SILO_NVMEM */
+    NULL,                                          /* SL_OPCODE_SILO_NETCFG */
+    NULL,
+    NULL
+};
+
+cc3100_driver::cc3100_driver(cc3100_spi &spi, cc3100_nonos &nonos, cc3100_netapp &netapp, cc3100_flowcont &flowcont)
+    :  _spi(spi), _nonos(nonos),_netapp(netapp), _flowcont(flowcont)
+{
+
+}
+
+cc3100_driver::~cc3100_driver()
+{
+
+}
+
+/*****************************************************************************/
+/* Variables                                                                 */
+/*****************************************************************************/
+
+/********************************************************************************/
+
+uint8_t cc3100_driver::_SlDrvProtectAsyncRespSetting(uint8_t *pAsyncRsp, uint8_t ActionID, uint8_t SocketID)
+{
+    uint8_t ObjIdx;
+
+
+    /* Use Obj to issue the command, if not available try later */
+    ObjIdx = _SlDrvWaitForPoolObj(ActionID, SocketID);
+
+    if (MAX_CONCURRENT_ACTIONS != ObjIdx)
+    {
+        _SlDrvProtectionObjLockWaitForever();
+        g_pCB->ObjPool[ObjIdx].pRespArgs = pAsyncRsp;
+        _SlDrvProtectionObjUnLock();
+    }
+
+    return ObjIdx;
+}
+
+
+/*****************************************************************************/
+/* Internal functions                                                        */
+/*****************************************************************************/
+bool cc3100_driver::_SL_PENDING_RX_MSG(pDriver* pDriverCB){
+	
+	if(RxIrqCnt != (pDriverCB)->RxDoneCnt){
+	    return TRUE;
+ 	}else{
+	    return FALSE;
+	}
+}
+
+/*****************************************************************************
+_SlDrvDriverCBInit - init Driver Control Block
+*****************************************************************************/
+void cc3100_driver::_SlDrvDriverCBInit(void)
+{
+    
+    uint8_t Idx = 0;
+
+#ifdef SL_MEMORY_MGMT_DYNAMIC
+
+    g_pCB = sl_Malloc(sizeof(_SlDriverCb_t));
+#else
+    g_pCB = &(g_StatMem.DriverCB);
+#endif
+   
+    MALLOC_OK_CHECK(g_pCB);
+    _SlDrvMemZero(g_pCB, sizeof(_SlDriverCb_t));
+    RxIrqCnt = 0;
+    
+    OSI_RET_OK_CHECK( _nonos.sl_SyncObjCreate(&g_pCB->CmdSyncObj, "CmdSyncObj") );
+    _nonos.sl_SyncObjClear(&g_pCB->CmdSyncObj);
+    
+    OSI_RET_OK_CHECK( _nonos.sl_LockObjCreate(&g_pCB->GlobalLockObj, "GlobalLockObj") );
+
+    OSI_RET_OK_CHECK( _nonos.sl_LockObjCreate(&g_pCB->ProtectionLockObj, "ProtectionLockObj") );
+    
+    /* Init Drv object */
+    _SlDrvMemZero(&g_pCB->ObjPool[0], MAX_CONCURRENT_ACTIONS*sizeof(_SlPoolObj_t));
+
+    /* place all Obj in the free list*/
+    g_pCB->FreePoolIdx = 0;
+
+    for (Idx = 0 ; Idx < MAX_CONCURRENT_ACTIONS ; Idx++)
+    {
+        g_pCB->ObjPool[Idx].NextIndex = Idx + 1;
+        g_pCB->ObjPool[Idx].AdditionalData = SL_MAX_SOCKETS;
+
+        OSI_RET_OK_CHECK( _nonos.sl_SyncObjCreate(&g_pCB->ObjPool[Idx].SyncObj, "SyncObj"));
+        _nonos.sl_SyncObjClear(&g_pCB->ObjPool[Idx].SyncObj);
+    }
+
+     g_pCB->ActivePoolIdx = MAX_CONCURRENT_ACTIONS;
+     g_pCB->PendingPoolIdx = MAX_CONCURRENT_ACTIONS;
+
+    /* Flow control init */
+    g_pCB->FlowContCB.TxPoolCnt = FLOW_CONT_MIN;
+    OSI_RET_OK_CHECK(_nonos.sl_LockObjCreate(&g_pCB->FlowContCB.TxLockObj, "TxLockObj"));
+    OSI_RET_OK_CHECK(_nonos.sl_SyncObjCreate(&g_pCB->FlowContCB.TxSyncObj, "TxSyncObj"));
+    
+    gFirstCmdMode = 0;  
+}
+
+/*****************************************************************************
+_SlDrvDriverCBDeinit - De init Driver Control Block
+*****************************************************************************/
+void cc3100_driver::_SlDrvDriverCBDeinit()
+{
+    uint8_t        Idx = 0;
+    
+    /* Flow control de-init */
+    g_pCB->FlowContCB.TxPoolCnt = 0;
+    OSI_RET_OK_CHECK(_nonos.sl_LockObjDelete(&g_pCB->FlowContCB.TxLockObj,0));
+    OSI_RET_OK_CHECK(_nonos.sl_SyncObjDelete(&g_pCB->FlowContCB.TxSyncObj,0));
+    
+
+    OSI_RET_OK_CHECK( _nonos.sl_SyncObjDelete(&g_pCB->CmdSyncObj, 0) );
+    OSI_RET_OK_CHECK( _nonos.sl_LockObjDelete(&g_pCB->GlobalLockObj, 0) );
+    OSI_RET_OK_CHECK( _nonos.sl_LockObjDelete(&g_pCB->ProtectionLockObj, 0) );
+    
+#ifndef SL_TINY_EXT
+    for (Idx = 0; Idx < MAX_CONCURRENT_ACTIONS; Idx++)
+#endif
+
+    g_pCB->FreePoolIdx = 0;
+    g_pCB->PendingPoolIdx = MAX_CONCURRENT_ACTIONS;
+    g_pCB->ActivePoolIdx = MAX_CONCURRENT_ACTIONS;
+
+#ifdef SL_MEMORY_MGMT_DYNAMIC
+    sl_Free(g_pCB);
+#else
+    g_pCB = NULL;
+#endif
+
+    g_pCB = NULL;
+}
+
+/*****************************************************************************
+_SlDrvRxIrqHandler - Interrupt handler
+*****************************************************************************/
+
+void cc3100_driver::_SlDrvRxIrqHandler(void *pValue)
+{
+    
+    int32_t rv = 0;
+    _spi.MaskIntHdlr();
+    
+    RxIrqCnt++;
+    
+    if (TRUE == g_pCB->IsCmdRespWaited) {
+        OSI_RET_OK_CHECK( _nonos.sl_SyncObjSignalFromIRQ(&g_pCB->CmdSyncObj, NON_OS_SYNC_OBJ_SIGNAL_VALUE) );
+    } else {
+#ifdef SL_PLATFORM_EXTERNAL_SPAWN                
+        rv = sl_Spawn((_SlSpawnEntryFunc_t)_SlDrvMsgReadSpawnCtx, NULL, 0);
+
+        if(rv <0){
+           Uart_Write((uint8_t*)"\n\r OSI_OPERATION_FAILED \n\r");
+        }   
+#else        
+        _nonos._SlNonOsSpawn((_SlSpawnEntryFunc_t)&_SlDrvMsgReadSpawnCtx, NULL, 0);
+#endif        
+    }
+    
+}
+
+/*****************************************************************************
+_SlDrvCmdOp
+*****************************************************************************/
+_SlReturnVal_t cc3100_driver::_SlDrvCmdOp(_SlCmdCtrl_t *pCmdCtrl,void* pTxRxDescBuff, _SlCmdExt_t *pCmdExt)
+{
+    
+    _SlReturnVal_t RetVal;
+    
+    _SlDrvObjLockWaitForever(&g_pCB->GlobalLockObj);
+    
+    g_pCB->IsCmdRespWaited = TRUE;
+    SL_TRACE0(DBG_MSG, MSG_312, "_SlDrvCmdOp: call _SlDrvMsgWrite");
+    
+    /* send the message */
+    RetVal = _SlDrvMsgWrite(pCmdCtrl, pCmdExt, (uint8_t*)pTxRxDescBuff);
+    
+    if(SL_OS_RET_CODE_OK == RetVal) {
+
+#ifndef SL_IF_TYPE_UART
+        /* Waiting for SPI to stabilize after first command */
+        if( 0 == gFirstCmdMode ) {           
+            gFirstCmdMode = 1;
+            wait_ms(2);
+        }
+#endif
+        
+        /* wait for respond */
+        RetVal = _SlDrvMsgReadCmdCtx(); /* will free global lock */
+        SL_TRACE0(DBG_MSG, MSG_314, "_SlDrvCmdOp: exited _SlDrvMsgReadCmdCtx");
+        
+    } else 
+    {
+        _SlDrvObjUnLock(&g_pCB->GlobalLockObj);
+    }
+    return RetVal;
+}
+
+/*****************************************************************************
+_SlDrvDataReadOp
+*****************************************************************************/
+_SlReturnVal_t cc3100_driver::_SlDrvDataReadOp(_SlSd_t Sd, _SlCmdCtrl_t *pCmdCtrl, void* pTxRxDescBuff, _SlCmdExt_t *pCmdExt)
+{
+    _SlReturnVal_t RetVal;
+    uint8_t ObjIdx = MAX_CONCURRENT_ACTIONS;
+    _SlArgsData_t pArgsData;
+
+    /* Validate input arguments */
+    VERIFY_PROTOCOL(NULL != pCmdExt->pRxPayload);
+
+    /* If zero bytes is requested, return error. */
+    /*  This allows us not to fill remote socket's IP address in return arguments */
+    VERIFY_PROTOCOL(0 != pCmdExt->RxPayloadLen);
+
+    /* Validate socket */
+    if((Sd & BSD_SOCKET_ID_MASK) >= SL_MAX_SOCKETS) {
+        return SL_EBADF;
+    }
+
+    /*Use Obj to issue the command, if not available try later*/
+    ObjIdx = (uint8_t)_SlDrvWaitForPoolObj(RECV_ID, Sd & BSD_SOCKET_ID_MASK);
+
+    if (MAX_CONCURRENT_ACTIONS == ObjIdx) {
+        return SL_POOL_IS_EMPTY;
+    }
+    
+    _SlDrvProtectionObjLockWaitForever();
+    
+    pArgsData.pData = pCmdExt->pRxPayload;
+    pArgsData.pArgs =  (uint8_t *)pTxRxDescBuff;
+    g_pCB->ObjPool[ObjIdx].pRespArgs =  (uint8_t *)&pArgsData;
+    _SlDrvProtectionObjUnLock();
+
+    /* Do Flow Control check/update for DataWrite operation */
+    _SlDrvObjLockWaitForever(&g_pCB->FlowContCB.TxLockObj);
+    
+    /* Clear SyncObj for the case it was signalled before TxPoolCnt */
+    /* dropped below '1' (last Data buffer was taken)  */
+    /* OSI_RET_OK_CHECK( sl_SyncObjClear(&g_pCB->FlowContCB.TxSyncObj) ); */
+    _nonos.sl_SyncObjClear(&g_pCB->FlowContCB.TxSyncObj);
+
+    if(g_pCB->FlowContCB.TxPoolCnt <= FLOW_CONT_MIN) {
+
+        /* If TxPoolCnt was increased by other thread at this moment,
+        TxSyncObj won't wait here */
+    _SlDrvSyncObjWaitForever(&g_pCB->FlowContCB.TxSyncObj);
+       
+    }
+
+    _SlDrvObjLockWaitForever(&g_pCB->GlobalLockObj);
+
+    VERIFY_PROTOCOL(g_pCB->FlowContCB.TxPoolCnt > FLOW_CONT_MIN);
+    g_pCB->FlowContCB.TxPoolCnt--;
+
+    _SlDrvObjUnLock(&g_pCB->FlowContCB.TxLockObj);
+
+    /* send the message */
+    RetVal =  _SlDrvMsgWrite(pCmdCtrl, pCmdExt, (uint8_t *)pTxRxDescBuff);
+
+    _SlDrvObjUnLock(&g_pCB->GlobalLockObj);
+
+    if(SL_OS_RET_CODE_OK == RetVal) {
+        /* Wait for response message. Will be signaled by _SlDrvMsgRead. */
+        _SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj);
+    }
+
+    _SlDrvReleasePoolObj(ObjIdx);
+    return RetVal;
+}
+
+/* ******************************************************************************/
+/*   _SlDrvDataWriteOp                                                          */
+/* ******************************************************************************/
+_SlReturnVal_t cc3100_driver::_SlDrvDataWriteOp(_SlSd_t Sd, _SlCmdCtrl_t *pCmdCtrl, void* pTxRxDescBuff, _SlCmdExt_t *pCmdExt)
+{
+    _SlReturnVal_t  RetVal = SL_EAGAIN; /*  initiated as SL_EAGAIN for the non blocking mode */
+    while( 1 ) {
+        /*  Do Flow Control check/update for DataWrite operation */        
+        _SlDrvObjLockWaitForever(&g_pCB->FlowContCB.TxLockObj);
+
+        /*  Clear SyncObj for the case it was signalled before TxPoolCnt */
+        /*  dropped below '1' (last Data buffer was taken) */
+        /* OSI_RET_OK_CHECK( sl_SyncObjClear(&g_pCB->FlowContCB.TxSyncObj) ); */
+        _nonos.sl_SyncObjClear(&g_pCB->FlowContCB.TxSyncObj);
+        /*  we have indication that the last send has failed - socket is no longer valid for operations  */
+        if(g_pCB->SocketTXFailure & (1<<(Sd & BSD_SOCKET_ID_MASK))) {
+            _SlDrvObjUnLock(&g_pCB->FlowContCB.TxLockObj);
+            return SL_SOC_ERROR;
+        }
+        
+        if(g_pCB->FlowContCB.TxPoolCnt <= FLOW_CONT_MIN + 1) {
+            /*  we have indication that this socket is set as blocking and we try to  */
+            /*  unblock it - return an error */
+            if( g_pCB->SocketNonBlocking & (1<< (Sd & BSD_SOCKET_ID_MASK)))
+            {
+            _SlDrvObjUnLock(&g_pCB->FlowContCB.TxLockObj);
+                return RetVal;
+            }
+            /*  If TxPoolCnt was increased by other thread at this moment, */
+            /*  TxSyncObj won't wait here */
+            _SlDrvSyncObjWaitForever(&g_pCB->FlowContCB.TxSyncObj);
+        }
+
+        if(g_pCB->FlowContCB.TxPoolCnt > FLOW_CONT_MIN + 1 ) {
+            break;
+        } 
+        else 
+        {
+        _SlDrvObjUnLock(&g_pCB->FlowContCB.TxLockObj);
+        }
+    }
+
+    _SlDrvObjLockWaitForever(&g_pCB->GlobalLockObj);
+
+
+    VERIFY_PROTOCOL(g_pCB->FlowContCB.TxPoolCnt > FLOW_CONT_MIN + 1 );
+    g_pCB->FlowContCB.TxPoolCnt--;
+
+    _SlDrvObjUnLock(&g_pCB->FlowContCB.TxLockObj);
+    
+    /* send the message */
+    RetVal =  _SlDrvMsgWrite(pCmdCtrl, pCmdExt, (uint8_t*)pTxRxDescBuff);
+
+    _SlDrvObjUnLock(&g_pCB->GlobalLockObj);
+
+    return RetVal;
+}
+
+/* ******************************************************************************/
+/*  _SlDrvMsgWrite */
+/* ******************************************************************************/
+_SlReturnVal_t cc3100_driver::_SlDrvMsgWrite(_SlCmdCtrl_t  *pCmdCtrl, _SlCmdExt_t  *pCmdExt, uint8_t *pTxRxDescBuff)
+{
+    
+    uint8_t sendRxPayload = FALSE;
+    VERIFY_PROTOCOL(NULL != pCmdCtrl);
+
+    g_pCB->FunctionParams.pCmdCtrl = pCmdCtrl;
+    g_pCB->FunctionParams.pTxRxDescBuff = pTxRxDescBuff;
+    g_pCB->FunctionParams.pCmdExt = pCmdExt;
+    
+    g_pCB->TempProtocolHeader.Opcode   = pCmdCtrl->Opcode;
+    g_pCB->TempProtocolHeader.Len   = _SL_PROTOCOL_CALC_LEN(pCmdCtrl, pCmdExt);
+
+    if (pCmdExt && pCmdExt->RxPayloadLen < 0 && pCmdExt->TxPayloadLen)
+    {
+        pCmdExt->RxPayloadLen = pCmdExt->RxPayloadLen * (-1); /* change sign */
+        sendRxPayload = TRUE;
+        g_pCB->TempProtocolHeader.Len = g_pCB->TempProtocolHeader.Len + pCmdExt->RxPayloadLen;
+    }
+    
+#ifdef SL_START_WRITE_STAT
+    sl_IfStartWriteSequence(g_pCB->FD);
+#endif
+
+#ifdef SL_IF_TYPE_UART
+    /*  Write long sync pattern */
+    _spi.spi_Write(g_pCB->FD, (uint8_t *)&g_H2NSyncPattern.Long, 2*SYNC_PATTERN_LEN);
+#else
+    /*  Write short sync pattern */
+    _spi.spi_Write(g_pCB->FD, (uint8_t *)&g_H2NSyncPattern.Short, SYNC_PATTERN_LEN);
+#endif
+    /*  Header */
+    _spi.spi_Write(g_pCB->FD, (uint8_t *)&g_pCB->TempProtocolHeader, _SL_CMD_HDR_SIZE);
+
+    /*  Descriptors */
+    if (pTxRxDescBuff && pCmdCtrl->TxDescLen > 0)
+    {
+    	_spi.spi_Write(g_pCB->FD, pTxRxDescBuff, 
+                           _SL_PROTOCOL_ALIGN_SIZE(pCmdCtrl->TxDescLen));
+    }
+
+    /*  A special mode where Rx payload and Rx length are used as Tx as well */
+    /*  This mode requires no Rx payload on the response and currently used by fs_Close and sl_Send on */
+    /*  transceiver mode */
+    if (sendRxPayload == TRUE )
+    {
+     	_spi.spi_Write(g_pCB->FD, pCmdExt->pRxPayload, _SL_PROTOCOL_ALIGN_SIZE(pCmdExt->RxPayloadLen));
+    }
+
+    /*  Payload */
+    if (pCmdExt && pCmdExt->TxPayloadLen > 0)
+    {
+        /*  If the message has payload, it is mandatory that the message's arguments are protocol aligned. */
+        /*  Otherwise the aligning of arguments will create a gap between arguments and payload. */
+        VERIFY_PROTOCOL(_SL_IS_PROTOCOL_ALIGNED_SIZE(pCmdCtrl->TxDescLen));
+
+    	_spi.spi_Write(g_pCB->FD, pCmdExt->pTxPayload, _SL_PROTOCOL_ALIGN_SIZE(pCmdExt->TxPayloadLen));
+    }
+
+    _SL_DBG_CNT_INC(MsgCnt.Write);
+
+#ifdef SL_START_WRITE_STAT
+    sl_IfEndWriteSequence(g_pCB->FD);
+#endif
+
+    return SL_OS_RET_CODE_OK;
+}
+
+/* ******************************************************************************/
+/*  _SlDrvMsgRead  */
+/* ******************************************************************************/
+_SlReturnVal_t cc3100_driver::_SlDrvMsgRead(void)
+{
+    /*  alignment for small memory models */
+    union {
+      uint8_t             TempBuf[_SL_RESP_HDR_SIZE];
+      uint32_t            DummyBuf[2];
+    } uBuf;
+    uint8_t               TailBuffer[4];
+    uint16_t              LengthToCopy;
+    uint16_t              AlignedLengthRecv;
+    uint8_t               AlignSize;
+    uint8_t               *pAsyncBuf = NULL;
+    uint16_t              OpCode;
+    uint16_t              RespPayloadLen;
+    uint8_t               sd = SL_MAX_SOCKETS;
+    _SlRxMsgClass_e   RxMsgClass;
+    
+
+    /* save params in global CB */
+    g_pCB->FunctionParams.AsyncExt.pAsyncBuf      = NULL;
+    g_pCB->FunctionParams.AsyncExt.AsyncEvtHandler= NULL;
+ 
+    
+    VERIFY_RET_OK(_SlDrvRxHdrRead((uint8_t*)(uBuf.TempBuf), &AlignSize));
+    
+    OpCode = OPCODE(uBuf.TempBuf);
+    RespPayloadLen = RSP_PAYLOAD_LEN(uBuf.TempBuf);
+
+
+    /* 'Init Compelete' message bears no valid FlowControl info */
+    if(SL_OPCODE_DEVICE_INITCOMPLETE != OpCode) {
+        g_pCB->FlowContCB.TxPoolCnt = ((_SlResponseHeader_t *)uBuf.TempBuf)->TxPoolCnt;
+        g_pCB->SocketNonBlocking = ((_SlResponseHeader_t *)uBuf.TempBuf)->SocketNonBlocking;
+        g_pCB->SocketTXFailure = ((_SlResponseHeader_t *)uBuf.TempBuf)->SocketTXFailure;
+
+        if(g_pCB->FlowContCB.TxPoolCnt > FLOW_CONT_MIN) {
+            _SlDrvSyncObjSignal(&g_pCB->FlowContCB.TxSyncObj);
+        }
+    }
+
+    /* Find the RX messaage class and set its async event handler */
+    _SlDrvClassifyRxMsg(OpCode);
+    
+    RxMsgClass = g_pCB->FunctionParams.AsyncExt.RxMsgClass;
+
+
+    switch(RxMsgClass)
+    {
+    case ASYNC_EVT_CLASS:
+
+            VERIFY_PROTOCOL(NULL == pAsyncBuf);
+
+#ifdef SL_MEMORY_MGMT_DYNAMIC
+        g_pCB->FunctionParams.AsyncExt.pAsyncBuf = sl_Malloc(SL_ASYNC_MAX_MSG_LEN);
+#else
+        g_pCB->FunctionParams.AsyncExt.pAsyncBuf = g_StatMem.AsyncRespBuf;
+#endif
+            /* set the local pointer to the allocated one */
+            pAsyncBuf = g_pCB->FunctionParams.AsyncExt.pAsyncBuf;
+
+            /* clear the async buffer */
+            _SlDrvMemZero(pAsyncBuf, SL_ASYNC_MAX_MSG_LEN);
+            
+            MALLOC_OK_CHECK(pAsyncBuf);
+
+            memcpy(pAsyncBuf, uBuf.TempBuf, _SL_RESP_HDR_SIZE);
+			if (_SL_PROTOCOL_ALIGN_SIZE(RespPayloadLen) <= SL_ASYNC_MAX_PAYLOAD_LEN)
+			{
+				AlignedLengthRecv = _SL_PROTOCOL_ALIGN_SIZE(RespPayloadLen);
+			}
+			else
+			{
+				AlignedLengthRecv = _SL_PROTOCOL_ALIGN_SIZE(SL_ASYNC_MAX_PAYLOAD_LEN);
+			}
+            if (RespPayloadLen > 0)
+            {
+                _spi.spi_Read(g_pCB->FD, pAsyncBuf + _SL_RESP_HDR_SIZE, AlignedLengthRecv);
+            }
+        /* In case ASYNC RX buffer length is smaller then the received data length, dump the rest */
+			if ((_SL_PROTOCOL_ALIGN_SIZE(RespPayloadLen) > SL_ASYNC_MAX_PAYLOAD_LEN))
+            {
+				AlignedLengthRecv = _SL_PROTOCOL_ALIGN_SIZE(RespPayloadLen) - SL_ASYNC_MAX_PAYLOAD_LEN;
+                while (AlignedLengthRecv > 0)
+                {
+                _spi.spi_Read(g_pCB->FD,TailBuffer,4);
+                AlignedLengthRecv = AlignedLengthRecv - 4;
+                }
+            }
+            
+            _SlDrvProtectionObjLockWaitForever();
+          
+			if (
+#ifndef SL_TINY_EXT               
+                (SL_OPCODE_SOCKET_ACCEPTASYNCRESPONSE == OpCode) || (SL_OPCODE_SOCKET_ACCEPTASYNCRESPONSE_V6 == OpCode) || 
+#endif                
+                (SL_OPCODE_SOCKET_CONNECTASYNCRESPONSE == OpCode)
+               )
+			{
+				/* go over the active list if exist to find obj waiting for this Async event */
+				sd = ((((_SocketResponse_t *)(pAsyncBuf + _SL_RESP_HDR_SIZE))->sd) & BSD_SOCKET_ID_MASK);
+			}
+			_SlFindAndSetActiveObj(OpCode, sd);
+            _SlDrvProtectionObjUnLock();
+
+            break;
+    case RECV_RESP_CLASS:
+        {
+            uint8_t ExpArgSize; /*  Expected size of Recv/Recvfrom arguments */
+
+            switch(OpCode)
+            {
+            case SL_OPCODE_SOCKET_RECVFROMASYNCRESPONSE:
+                ExpArgSize = RECVFROM_IPV4_ARGS_SIZE;
+                break;
+#ifndef SL_TINY_EXT                        
+            case SL_OPCODE_SOCKET_RECVFROMASYNCRESPONSE_V6:
+                ExpArgSize = RECVFROM_IPV6_ARGS_SIZE;
+                break;
+#endif                        
+            default:
+                /* SL_OPCODE_SOCKET_RECVASYNCRESPONSE: */
+                ExpArgSize = RECV_ARGS_SIZE;
+            }              
+
+            /*  Read first 4 bytes of Recv/Recvfrom response to get SocketId and actual  */
+            /*  response data length */
+            _spi.spi_Read(g_pCB->FD, &uBuf.TempBuf[4], RECV_ARGS_SIZE);
+
+            /*  Validate Socket ID and Received Length value.  */
+            VERIFY_PROTOCOL((SD(&uBuf.TempBuf[4])& BSD_SOCKET_ID_MASK) < SL_MAX_SOCKETS);
+
+            _SlDrvProtectionObjLockWaitForever();
+
+            /* go over the active list if exist to find obj waiting for this Async event */
+				VERIFY_RET_OK(_SlFindAndSetActiveObj(OpCode,SD(&uBuf.TempBuf[4]) & BSD_SOCKET_ID_MASK));
+
+            /*  Verify data is waited on this socket. The pArgs should have been set by _SlDrvDataReadOp(). */
+            VERIFY_SOCKET_CB(NULL !=  ((_SlArgsData_t *)(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pData))->pArgs);	
+
+            memcpy( ((_SlArgsData_t *)(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs))->pArgs, &uBuf.TempBuf[4], RECV_ARGS_SIZE);
+
+            if(ExpArgSize > RECV_ARGS_SIZE)
+            {
+                _spi.spi_Read(g_pCB->FD,
+                    ((_SlArgsData_t *)(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs))->pArgs + RECV_ARGS_SIZE,
+                    ExpArgSize - RECV_ARGS_SIZE);
+            }
+
+            /*  Here g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pData contains requested(expected) Recv/Recvfrom DataSize. */
+            /*  Overwrite requested DataSize with actual one. */
+            /*  If error is received, this information will be read from arguments. */
+            if(ACT_DATA_SIZE(&uBuf.TempBuf[4]) > 0)
+            {       
+                VERIFY_SOCKET_CB(NULL != ((_SlArgsData_t *)(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs))->pData);
+
+                /*  Read 4 bytes aligned from interface */
+                /*  therefore check the requested length and read only  */
+                /*  4 bytes aligned data. The rest unaligned (if any) will be read */
+                /*  and copied to a TailBuffer  */
+                LengthToCopy = ACT_DATA_SIZE(&uBuf.TempBuf[4]) & (3);
+                AlignedLengthRecv = ACT_DATA_SIZE(&uBuf.TempBuf[4]) & (~3);
+                if( AlignedLengthRecv >= 4)
+                {
+                    _spi.spi_Read(g_pCB->FD,((_SlArgsData_t *)(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs))->pData,AlignedLengthRecv );                      
+                }
+                /*  copy the unaligned part, if any */
+                if( LengthToCopy > 0) 
+                {
+                    _spi.spi_Read(g_pCB->FD,TailBuffer,4);
+                    /*  copy TailBuffer unaligned part (1/2/3 bytes) */
+                    memcpy(((_SlArgsData_t *)(g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].pRespArgs))->pData + AlignedLengthRecv,TailBuffer,LengthToCopy);                    
+                }                  
+            }
+                 _SlDrvSyncObjSignal(&g_pCB->ObjPool[g_pCB->FunctionParams.AsyncExt.ActionIndex].SyncObj);
+                 _SlDrvProtectionObjUnLock();
+        }
+        break;
+
+        case CMD_RESP_CLASS:
+
+            /*  Some commands pass a maximum arguments size. */
+            /*  In this case Driver will send extra dummy patterns to NWP if */
+            /*  the response message is smaller than maximum. */
+            /*  When RxDescLen is not exact, using RxPayloadLen is forbidden! */
+            /*  If such case cannot be avoided - parse message here to detect */
+            /*  arguments/payload border. */
+            _spi.spi_Read(g_pCB->FD, g_pCB->FunctionParams.pTxRxDescBuff, _SL_PROTOCOL_ALIGN_SIZE(g_pCB->FunctionParams.pCmdCtrl->RxDescLen));
+
+            if((NULL != g_pCB->FunctionParams.pCmdExt) && (0 != g_pCB->FunctionParams.pCmdExt->RxPayloadLen)) {
+                /*  Actual size of command's response payload: <msg_payload_len> - <rsp_args_len> */
+                int16_t    ActDataSize = RSP_PAYLOAD_LEN(uBuf.TempBuf) - g_pCB->FunctionParams.pCmdCtrl->RxDescLen;
+
+                g_pCB->FunctionParams.pCmdExt->ActualRxPayloadLen = ActDataSize;
+
+                /* Check that the space prepared by user for the response data is sufficient. */
+                if(ActDataSize <= 0) {
+                    g_pCB->FunctionParams.pCmdExt->RxPayloadLen = 0;
+                } else {
+                    /* In case the user supplied Rx buffer length which is smaller then the received data length, copy according to user length */
+                    if (ActDataSize > g_pCB->FunctionParams.pCmdExt->RxPayloadLen) {
+                        LengthToCopy = g_pCB->FunctionParams.pCmdExt->RxPayloadLen & (3);
+                        AlignedLengthRecv = g_pCB->FunctionParams.pCmdExt->RxPayloadLen & (~3);
+                    } else {
+                        LengthToCopy = ActDataSize & (3);
+                        AlignedLengthRecv = ActDataSize & (~3);
+                    }
+                    /*  Read 4 bytes aligned from interface */
+                    /*  therefore check the requested length and read only  */
+                    /*  4 bytes aligned data. The rest unaligned (if any) will be read */
+                    /*  and copied to a TailBuffer  */
+
+                    if( AlignedLengthRecv >= 4) {
+                        _spi.spi_Read(g_pCB->FD,
+                                          g_pCB->FunctionParams.pCmdExt->pRxPayload,
+                                          AlignedLengthRecv );
+
+                    }
+                    /*  copy the unaligned part, if any */
+                    if( LengthToCopy > 0) {
+                        _spi.spi_Read(g_pCB->FD,TailBuffer,4);
+                        /*  copy TailBuffer unaligned part (1/2/3 bytes) */
+                        memcpy(g_pCB->FunctionParams.pCmdExt->pRxPayload + AlignedLengthRecv,
+                                  TailBuffer,
+                                  LengthToCopy);
+                        ActDataSize = ActDataSize-4;
+                    }
+                    /* In case the user supplied Rx buffer length which is smaller then the received data length, dump the rest */
+                    if (ActDataSize > g_pCB->FunctionParams.pCmdExt->RxPayloadLen) {
+                        /* calculate the rest of the data size to dump */
+                        AlignedLengthRecv = ActDataSize - (g_pCB->FunctionParams.pCmdExt->RxPayloadLen & (~3));
+                        while( AlignedLengthRecv > 0) {
+                            _spi.spi_Read(g_pCB->FD,TailBuffer, 4 );
+                            AlignedLengthRecv = AlignedLengthRecv - 4;
+                        }
+                    }
+                }
+            }
+            break;
+
+        default:
+            /*  DUMMY_MSG_CLASS: Flow control message has no payload. */
+            break;
+    }
+
+    if(AlignSize > 0) {
+        _spi.spi_Read(g_pCB->FD, uBuf.TempBuf, AlignSize);
+    }
+
+    _SL_DBG_CNT_INC(MsgCnt.Read);
+
+    /*  Unmask Interrupt call */
+    _spi.UnMaskIntHdlr();
+    
+    return SL_OS_RET_CODE_OK;
+}
+
+/* ******************************************************************************/
+/*  _SlAsyncEventGenericHandler */
+/* ******************************************************************************/
+void cc3100_driver::_SlAsyncEventGenericHandler(void)
+{
+    uint32_t SlAsyncEvent = 0;
+    uint8_t  OpcodeFound = FALSE; 
+    uint8_t  i;
+    
+    uint32_t* pEventLocation  = NULL; /* This pointer will override the async buffer with the translated event type */
+    _SlResponseHeader_t  *pHdr       = (_SlResponseHeader_t *)g_pCB->FunctionParams.AsyncExt.pAsyncBuf;
+
+
+    /* if no async event registered nothing to do..*/
+    if (g_pCB->FunctionParams.AsyncExt.AsyncEvtHandler == NULL)
+        return;
+
+    /* Iterate through all the opcode in the table */
+    for (i=0; i< (sizeof(OpcodeTranslateTable) / sizeof(OpcodeKeyVal_t)); i++)
+    {
+        if (OpcodeTranslateTable[i].opcode == pHdr->GenHeader.Opcode)
+        {
+            SlAsyncEvent = OpcodeTranslateTable[i].event;
+            OpcodeFound = TRUE;
+            break;
+        }
+    }
+
+    /* No Async event found in the table */
+    if (OpcodeFound == FALSE)
+    {
+        /* This case handles all the async events handlers of the DEVICE & SOCK Silos which are handled internally.
+                 For these cases we send the async even buffer as is */
+        g_pCB->FunctionParams.AsyncExt.AsyncEvtHandler(g_pCB->FunctionParams.AsyncExt.pAsyncBuf);
+    }
+    else
+    {
+       /* calculate the event type location to be filled in the async buffer */
+       pEventLocation = (uint32_t*)(g_pCB->FunctionParams.AsyncExt.pAsyncBuf + sizeof (_SlResponseHeader_t) - sizeof(SlAsyncEvent) );
+
+       /* Override the async buffer (before the data starts ) with our event type  */
+       *pEventLocation = SlAsyncEvent;
+
+       /* call the event handler registered by the user with our async buffer which now holds
+                the User's event type and its related data */
+       g_pCB->FunctionParams.AsyncExt.AsyncEvtHandler(pEventLocation);
+    }
+    
+}
+
+
+/* ******************************************************************************/
+/*  _SlDrvMsgReadCmdCtx  */
+/* ******************************************************************************/
+_SlReturnVal_t cc3100_driver::_SlDrvMsgReadCmdCtx(void)
+{
+
+    /*  after command response is received and isCmdRespWaited */
+    /*  flag is set FALSE, it is necessary to read out all */
+    /*  Async messages in Commands context, because ssiDma_IsrHandleSignalFromSlave */
+    /*  could have dispatched some Async messages to g_NwpIf.CmdSyncObj */
+    /*  after command response but before this response has been processed */
+    /*  by spi_singleRead and isCmdRespWaited was set FALSE. */
+    
+    while (TRUE == g_pCB->IsCmdRespWaited) {
+        
+        if(_SL_PENDING_RX_MSG(g_pCB)) {
+                       
+            VERIFY_RET_OK(_SlDrvMsgRead());
+            g_pCB->RxDoneCnt++;
+           
+            if (CMD_RESP_CLASS == g_pCB->FunctionParams.AsyncExt.RxMsgClass) {
+                g_pCB->IsCmdRespWaited = FALSE;
+
+                /*  In case CmdResp has been read without  waiting on CmdSyncObj -  that */
+                /*  Sync object. That to prevent old signal to be processed. */
+                _nonos.sl_SyncObjClear(&g_pCB->CmdSyncObj);
+            } else if (ASYNC_EVT_CLASS == g_pCB->FunctionParams.AsyncExt.RxMsgClass) {
+                /*  If Async event has been read in CmdResp context, check whether */
+                /*  there is a handler for this event. If there is, spawn specific */
+                /*  handler. Otherwise free the event's buffer. */
+                /*  This way there will be no "dry shots" from CmdResp context to */
+                /*  temporary context, i.e less waste of CPU and faster buffer */
+                /*  release. */
+                _SlAsyncEventGenericHandler();
+
+#ifdef SL_MEMORY_MGMT_DYNAMIC
+                sl_Free(g_pCB->FunctionParams.AsyncExt.pAsyncBuf);
+#else
+                g_pCB->FunctionParams.AsyncExt.pAsyncBuf = NULL;
+#endif
+            }
+        } else {
+            /* CmdSyncObj will be signaled by IRQ */
+            _SlDrvSyncObjWaitForever(&g_pCB->CmdSyncObj);
+        }
+    }
+    
+    /*  If there are more pending Rx Msgs after CmdResp is received, */
+    /*  that means that these are Async, Dummy or Read Data Msgs. */
+    /*  Spawn _SlDrvMsgReadSpawnCtx to trigger reading these messages from */
+    /*  Temporary context. */
+    /* sl_Spawn is activated, using a different context */
+    _SlDrvObjUnLock(&g_pCB->GlobalLockObj);
+    
+    if(_SL_PENDING_RX_MSG(g_pCB)) {
+      _nonos._SlNonOsSpawn((_SlSpawnEntryFunc_t)&_SlDrvMsgReadSpawnCtx, NULL, 0);
+    }
+    
+    return SL_OS_RET_CODE_OK;
+}
+
+/* ******************************************************************************/
+/*  _SlDrvMsgReadSpawnCtx                                                       */
+/* ******************************************************************************/
+/*
+_SlReturnVal_t cc3100_driver::_SlDrvMsgReadSpawnCtx_(void *pValue)
+{
+	
+#ifdef SL_POLLING_MODE_USED
+    int16_t retCode = OSI_OK;
+    //  for polling based systems 
+    do {
+        retCode = sl_LockObjLock(&g_pCB->GlobalLockObj, 0);
+        if ( OSI_OK != retCode ) {
+            if (TRUE == g_pCB->IsCmdRespWaited) {
+                _SlDrvSyncObjSignal(&g_pCB->CmdSyncObj);
+                return SL_RET_CODE_OK;
+            }
+        }
+
+    } while (OSI_OK != retCode);
+
+#else
+    _SlDrvObjLockWaitForever(&g_pCB->GlobalLockObj);
+#endif
+
+    //  Messages might have been read by CmdResp context. Therefore after 
+    //  getting LockObj, check again where the Pending Rx Msg is still present. 
+    if(FALSE == (_SL_PENDING_RX_MSG(g_pCB))) {
+        _SlDrvObjUnLock(&g_pCB->GlobalLockObj);
+        return SL_RET_CODE_OK;
+    }
+
+    VERIFY_RET_OK(_SlDrvMsgRead());
+
+    g_pCB->RxDoneCnt++;
+
+    switch(g_pCB->FunctionParams.AsyncExt.RxMsgClass) {
+        case ASYNC_EVT_CLASS:
+            //  If got here and protected by LockObj a message is waiting  
+            //  to be read 
+            VERIFY_PROTOCOL(NULL != g_pCB->FunctionParams.AsyncExt.pAsyncBuf);
+
+            _SlAsyncEventGenericHandler();
+
+#ifdef SL_MEMORY_MGMT_DYNAMIC
+        sl_Free(g_pCB->FunctionParams.AsyncExt.pAsyncBuf);
+#else
+        g_pCB->FunctionParams.AsyncExt.pAsyncBuf = NULL;
+#endif
+            break;
+        case DUMMY_MSG_CLASS:
+        case RECV_RESP_CLASS:
+            // These types are legal in this context. Do nothing 
+            break;
+        case CMD_RESP_CLASS:
+            // Command response is illegal in this context. 
+            // No 'break' here: Assert! 
+        default:
+            VERIFY_PROTOCOL(0);
+    }
+
+    _SlDrvObjUnLock(&g_pCB->GlobalLockObj);
+
+    return(SL_RET_CODE_OK);
+}
+*/
+/* ******************************************************************************/
+/*  _SlDrvClassifyRxMsg */
+/* ******************************************************************************/
+void cc3100_driver::_SlDrvClassifyRxMsg(_SlOpcode_t Opcode)
+{
+    _SlSpawnEntryFunc_t AsyncEvtHandler = NULL;
+    _SlRxMsgClass_e     RxMsgClass  = CMD_RESP_CLASS;
+    uint8_t             Silo;
+    
+
+	if (0 == (SL_OPCODE_SYNC & Opcode))
+	{   /* Async event has received */
+        
+		if (SL_OPCODE_DEVICE_DEVICEASYNCDUMMY == Opcode)
+		{ 
+		    RxMsgClass = DUMMY_MSG_CLASS;
+		}
+		else if ( (SL_OPCODE_SOCKET_RECVASYNCRESPONSE == Opcode) || (SL_OPCODE_SOCKET_RECVFROMASYNCRESPONSE == Opcode) 
+#ifndef SL_TINY_EXT                      
+                    || (SL_OPCODE_SOCKET_RECVFROMASYNCRESPONSE_V6 == Opcode) 
+#endif                    
+                 ) 
+		{
+			RxMsgClass = RECV_RESP_CLASS;
+		}
+		else
+		{
+            /* This is Async Event class message */
+            RxMsgClass = ASYNC_EVT_CLASS;
+        
+		    /* Despite the fact that 4 bits are allocated in the SILO field, we actually have only 6 SILOs
+		      So we can use the 8 options of SILO in look up table */
+		    Silo = ((Opcode >> SL_OPCODE_SILO_OFFSET) & 0x7);
+
+            VERIFY_PROTOCOL(Silo < (sizeof(RxMsgClassLUT)/sizeof(_SlSpawnEntryFunc_t)));
+
+            /* Set the async event hander according to the LUT */
+            AsyncEvtHandler = RxMsgClassLUT[Silo];
+            
+            if ((SL_OPCODE_NETAPP_HTTPGETTOKENVALUE == Opcode) || (SL_OPCODE_NETAPP_HTTPPOSTTOKENVALUE == Opcode))
+            {
+                AsyncEvtHandler = _SlDrvNetAppEventHandler;
+            }
+#ifndef SL_TINY_EXT            
+            else if (SL_OPCODE_NETAPP_PINGREPORTREQUESTRESPONSE == Opcode)
+            {
+                AsyncEvtHandler = (_SlSpawnEntryFunc_t)_sl_HandleAsync_PingResponse;
+            }
+#endif
+		}
+	}
+
+    g_pCB->FunctionParams.AsyncExt.RxMsgClass = RxMsgClass; 
+    g_pCB->FunctionParams.AsyncExt.AsyncEvtHandler = AsyncEvtHandler;
+
+}
+
+/* ******************************************************************************/
+/*  _SlDrvRxHdrRead  */
+/* ******************************************************************************/
+_SlReturnVal_t  cc3100_driver::_SlDrvRxHdrRead(uint8_t *pBuf, uint8_t *pAlignSize)
+{
+    uint32_t       SyncCnt  = 0;
+    uint8_t        ShiftIdx;      
+    
+#ifndef SL_IF_TYPE_UART
+    /*  1. Write CNYS pattern to NWP when working in SPI mode only  */
+    _spi.spi_Write(g_pCB->FD, (uint8_t *)&g_H2NCnysPattern.Short, SYNC_PATTERN_LEN);
+#endif
+
+    /*  2. Read 4 bytes (protocol aligned) */
+    _spi.spi_Read(g_pCB->FD, &pBuf[0], 4);
+    _SL_DBG_SYNC_LOG(SyncCnt,pBuf);
+
+    /* Wait for SYNC_PATTERN_LEN from the device */
+    while ( ! N2H_SYNC_PATTERN_MATCH(pBuf, g_pCB->TxSeqNum) ) {
+        /*  3. Debug limit of scan */
+        VERIFY_PROTOCOL(SyncCnt < SL_SYNC_SCAN_THRESHOLD);
+
+        /*  4. Read next 4 bytes to Low 4 bytes of buffer */
+        if(0 == (SyncCnt % (uint32_t)SYNC_PATTERN_LEN)) {
+            _spi.spi_Read(g_pCB->FD, &pBuf[4], 4);
+            _SL_DBG_SYNC_LOG(SyncCnt,pBuf);
+        }
+
+        /*  5. Shift Buffer Up for checking if the sync is shifted */
+        for(ShiftIdx = 0; ShiftIdx< 7; ShiftIdx++)
+        {
+            pBuf[ShiftIdx] = pBuf[ShiftIdx+1];
+        }             
+        pBuf[7] = 0;
+
+        SyncCnt++;
+    }
+
+    /*  5. Sync pattern found. If needed, complete number of read bytes to multiple of 4 (protocol align) */
+    SyncCnt %= SYNC_PATTERN_LEN;
+
+    if(SyncCnt > 0) {
+        *(uint32_t *)&pBuf[0] = *(uint32_t *)&pBuf[4];
+        _spi.spi_Read(g_pCB->FD, &pBuf[SYNC_PATTERN_LEN - SyncCnt], (uint16_t)SyncCnt);
+    } else {
+        _spi.spi_Read(g_pCB->FD, &pBuf[0], 4);
+    }
+
+    /*  6. Scan for Double pattern. */
+    while ( N2H_SYNC_PATTERN_MATCH(pBuf, g_pCB->TxSeqNum) ) {
+        _SL_DBG_CNT_INC(Work.DoubleSyncPattern);
+        _spi.spi_Read(g_pCB->FD, &pBuf[0], SYNC_PATTERN_LEN);
+    }
+    g_pCB->TxSeqNum++;
+
+    /*  7. Here we've read Generic Header (4 bytes). Read the Resp Specific header (4 more bytes). */
+    _spi.spi_Read(g_pCB->FD, &pBuf[SYNC_PATTERN_LEN], _SL_RESP_SPEC_HDR_SIZE);
+
+    /*  8. Here we've read the entire Resp Header. */
+    /*     Return number bytes needed to be sent after read for NWP Rx 4-byte alignment (protocol alignment) */
+    *pAlignSize = (uint8_t)((SyncCnt > 0) ? (SYNC_PATTERN_LEN - SyncCnt) : 0);
+
+    return SL_RET_CODE_OK;
+}
+
+/* ***************************************************************************** */
+/*  _SlDrvBasicCmd */
+/* ***************************************************************************** */
+typedef union {
+    _BasicResponse_t	Rsp;
+} _SlBasicCmdMsg_u;
+
+#ifndef SL_TINY_EXT
+int16_t cc3100_driver::_SlDrvBasicCmd(_SlOpcode_t Opcode)
+{
+    _SlBasicCmdMsg_u       Msg = {0};
+    _SlCmdCtrl_t           CmdCtrl;
+
+    CmdCtrl.Opcode = Opcode;
+    CmdCtrl.TxDescLen = 0;
+    CmdCtrl.RxDescLen = sizeof(_BasicResponse_t);
+
+
+    VERIFY_RET_OK(_SlDrvCmdOp((_SlCmdCtrl_t *)&CmdCtrl, &Msg, NULL));
+
+    return (int16_t)Msg.Rsp.status;
+}
+
+/*****************************************************************************
+  _SlDrvCmdSend 
+  Send SL command without waiting for command response 
+  This function is unprotected and the caller should make 
+  sure global lock is active
+*****************************************************************************/
+_SlReturnVal_t cc3100_driver::_SlDrvCmdSend(_SlCmdCtrl_t *pCmdCtrl, void *pTxRxDescBuff, _SlCmdExt_t *pCmdExt)
+{
+    _SlReturnVal_t RetVal;
+    uint8_t        IsCmdRespWaitedOriginalVal;
+
+    _SlFunctionParams_t originalFuncParms;
+
+    /* save the current RespWait flag before clearing it */
+    IsCmdRespWaitedOriginalVal = g_pCB->IsCmdRespWaited;
+
+    /* save the current command parameters */
+    memcpy(&originalFuncParms,  &g_pCB->FunctionParams, sizeof(_SlFunctionParams_t));
+
+    g_pCB->IsCmdRespWaited = FALSE;
+  
+    SL_TRACE0(DBG_MSG, MSG_312, "_SlDrvCmdSend: call _SlDrvMsgWrite");
+
+    /* send the message */
+    RetVal = _SlDrvMsgWrite(pCmdCtrl, pCmdExt, (uint8_t*)pTxRxDescBuff);
+
+    /* restore the original RespWait flag */
+    g_pCB->IsCmdRespWaited = IsCmdRespWaitedOriginalVal;
+
+    /* restore the original command parameters  */
+    memcpy(&g_pCB->FunctionParams, &originalFuncParms, sizeof(_SlFunctionParams_t));
+
+    return RetVal;
+
+
+}
+#endif
+
+/* ***************************************************************************** */
+/*  _SlDrvWaitForPoolObj */
+/* ***************************************************************************** */
+uint8_t cc3100_driver::_SlDrvWaitForPoolObj(uint8_t ActionID, uint8_t SocketID)
+{
+    uint8_t CurrObjIndex = MAX_CONCURRENT_ACTIONS;
+    
+    /* Get free object  */
+    _SlDrvProtectionObjLockWaitForever();
+    if (MAX_CONCURRENT_ACTIONS > g_pCB->FreePoolIdx) {
+        /* save the current obj index */
+        CurrObjIndex = g_pCB->FreePoolIdx;
+        /* set the new free index */
+#ifndef SL_TINY_EXT        
+        if (MAX_CONCURRENT_ACTIONS > g_pCB->ObjPool[CurrObjIndex].NextIndex) {
+            g_pCB->FreePoolIdx = g_pCB->ObjPool[CurrObjIndex].NextIndex;
+        } 
+        else
+#endif         
+        {            
+            /* No further free actions available */
+            g_pCB->FreePoolIdx = MAX_CONCURRENT_ACTIONS;
+        }
+    } else {
+        _SlDrvProtectionObjUnLock();
+        return CurrObjIndex;
+    }
+    g_pCB->ObjPool[CurrObjIndex].ActionID = (uint8_t)ActionID;
+    if (SL_MAX_SOCKETS > SocketID) {
+        g_pCB->ObjPool[CurrObjIndex].AdditionalData = SocketID;
+    }
+#ifndef SL_TINY_EXT    
+    /*In case this action is socket related, SocketID bit will be on
+    In case SocketID is set to SL_MAX_SOCKETS, the socket is not relevant to the action. In that case ActionID bit will be on */
+    	while ( ( (SL_MAX_SOCKETS > SocketID) && (g_pCB->ActiveActionsBitmap & (1<<SocketID)) ) || 
+            ( (g_pCB->ActiveActionsBitmap & (1<<ActionID)) && (SL_MAX_SOCKETS == SocketID) ) )
+    {
+        /* action in progress - move to pending list */
+        g_pCB->ObjPool[CurrObjIndex].NextIndex = g_pCB->PendingPoolIdx;
+        g_pCB->PendingPoolIdx = CurrObjIndex;
+		_SlDrvProtectionObjUnLock();
+        
+        /* wait for action to be free */
+        _SlDrvSyncObjWaitForever(&g_pCB->ObjPool[CurrObjIndex].SyncObj);
+        
+        /* set params and move to active (remove from pending list at _SlDrvReleasePoolObj) */
+        _SlDrvProtectionObjLockWaitForever();
+    }
+#endif
+    /* mark as active. Set socket as active if action is on socket, otherwise mark action as active */
+    if (SL_MAX_SOCKETS > SocketID) {
+        g_pCB->ActiveActionsBitmap |= (1<<SocketID);
+    } else {
+        g_pCB->ActiveActionsBitmap |= (1<<ActionID);
+    }
+    /* move to active list  */
+    g_pCB->ObjPool[CurrObjIndex].NextIndex = g_pCB->ActivePoolIdx;
+    g_pCB->ActivePoolIdx = CurrObjIndex;
+    /* unlock */
+    _SlDrvProtectionObjUnLock();
+    return CurrObjIndex;
+}
+
+/* ******************************************************************************/
+/*  _SlDrvReleasePoolObj */
+/* ******************************************************************************/
+void cc3100_driver::_SlDrvReleasePoolObj(uint8_t ObjIdx)
+{
+#ifndef SL_TINY_EXT        
+    uint8_t PendingIndex;
+#endif
+
+     _SlDrvProtectionObjLockWaitForever();
+
+      /* In Tiny mode, there is only one object pool so no pending actions are available */
+#ifndef SL_TINY_EXT
+    /* go over the pending list and release other pending action if needed */
+	PendingIndex = g_pCB->PendingPoolIdx;
+        
+	while(MAX_CONCURRENT_ACTIONS > PendingIndex)
+	{
+		/* In case this action is socket related, SocketID is in use, otherwise will be set to SL_MAX_SOCKETS */
+		if ( (g_pCB->ObjPool[PendingIndex].ActionID == g_pCB->ObjPool[ObjIdx].ActionID) && 
+			( (SL_MAX_SOCKETS == (g_pCB->ObjPool[PendingIndex].AdditionalData & BSD_SOCKET_ID_MASK)) || 
+			((SL_MAX_SOCKETS > (g_pCB->ObjPool[ObjIdx].AdditionalData & BSD_SOCKET_ID_MASK)) && ( (g_pCB->ObjPool[PendingIndex].AdditionalData & BSD_SOCKET_ID_MASK) == (g_pCB->ObjPool[ObjIdx].AdditionalData & BSD_SOCKET_ID_MASK) ))) )
+		{
+			/* remove from pending list */
+			_SlRemoveFromList(&g_pCB->PendingPoolIdx, PendingIndex);
+			 _SlDrvSyncObjSignal(&g_pCB->ObjPool[PendingIndex].SyncObj);
+			 break;
+		}
+		PendingIndex = g_pCB->ObjPool[PendingIndex].NextIndex;
+	}
+#endif
+
+		if (SL_MAX_SOCKETS > (g_pCB->ObjPool[ObjIdx].AdditionalData & BSD_SOCKET_ID_MASK))
+		{
+		/* unset socketID  */
+			g_pCB->ActiveActionsBitmap &= ~(1<<(g_pCB->ObjPool[ObjIdx].AdditionalData & BSD_SOCKET_ID_MASK));
+		}
+		else
+		{
+		/* unset actionID  */
+			g_pCB->ActiveActionsBitmap &= ~(1<<g_pCB->ObjPool[ObjIdx].ActionID);
+		}
+
+    /* delete old data */
+    g_pCB->ObjPool[ObjIdx].pRespArgs = NULL;
+    g_pCB->ObjPool[ObjIdx].ActionID = 0;
+    g_pCB->ObjPool[ObjIdx].AdditionalData = SL_MAX_SOCKETS;
+
+    /* remove from active list */
+    _SlRemoveFromList(&g_pCB->ActivePoolIdx, ObjIdx);
+    /* move to free list */
+    g_pCB->ObjPool[ObjIdx].NextIndex = g_pCB->FreePoolIdx;
+    g_pCB->FreePoolIdx = ObjIdx;
+
+    _SlDrvProtectionObjUnLock();
+}
+
+/* ******************************************************************************/
+/* _SlRemoveFromList  */
+/* ******************************************************************************/
+void cc3100_driver::_SlRemoveFromList(uint8_t *ListIndex, uint8_t ItemIndex)
+{
+ #ifndef SL_TINY_EXT  
+	uint8_t Idx;
+#endif        
+        
+    if (MAX_CONCURRENT_ACTIONS == g_pCB->ObjPool[*ListIndex].NextIndex)
+    {
+        *ListIndex = MAX_CONCURRENT_ACTIONS;
+    }
+    /* As MAX_CONCURRENT_ACTIONS is equal to 1 in Tiny mode */
+#ifndef SL_TINY_EXT
+	/* need to remove the first item in the list and therefore update the global which holds this index */
+	else if (*ListIndex == ItemIndex)
+	{
+		*ListIndex = g_pCB->ObjPool[ItemIndex].NextIndex;
+	}
+	else
+	{
+              Idx = *ListIndex;
+      
+              while(MAX_CONCURRENT_ACTIONS > Idx)
+              {
+                  /* remove from list */
+                  if (g_pCB->ObjPool[Idx].NextIndex == ItemIndex)
+                  {
+                          g_pCB->ObjPool[Idx].NextIndex = g_pCB->ObjPool[ItemIndex].NextIndex;
+                          break;
+                  }
+
+                  Idx = g_pCB->ObjPool[Idx].NextIndex;
+              }
+	}
+#endif    
+}
+
+/* ******************************************************************************/
+/*  _SlFindAndSetActiveObj                                                     */
+/* ******************************************************************************/
+_SlReturnVal_t cc3100_driver::_SlFindAndSetActiveObj(_SlOpcode_t  Opcode, uint8_t Sd)
+{
+    uint8_t ActiveIndex;
+
+    ActiveIndex = g_pCB->ActivePoolIdx;
+    /* go over the active list if exist to find obj waiting for this Async event */
+    #ifndef SL_TINY_EXT    
+		while (MAX_CONCURRENT_ACTIONS > ActiveIndex){
+#else
+        /* Only one Active action is availabe in tiny mode, so we can replace the loop with if condition */
+        if (MAX_CONCURRENT_ACTIONS > ActiveIndex)
+#endif
+        /* unset the Ipv4\IPv6 bit in the opcode if family bit was set  */
+        if (g_pCB->ObjPool[ActiveIndex].AdditionalData & SL_NETAPP_FAMILY_MASK) {
+            Opcode &= ~SL_OPCODE_IPV6;
+        }
+
+        if ((g_pCB->ObjPool[ActiveIndex].ActionID == RECV_ID) && (Sd == g_pCB->ObjPool[ActiveIndex].AdditionalData) &&
+                						( (SL_OPCODE_SOCKET_RECVASYNCRESPONSE == Opcode) || (SL_OPCODE_SOCKET_RECVFROMASYNCRESPONSE == Opcode)
+#ifndef SL_TINY_EXT
+                        || (SL_OPCODE_SOCKET_RECVFROMASYNCRESPONSE_V6 == Opcode) 
+#endif
+                          ) 
+
+               )
+        {       
+            g_pCB->FunctionParams.AsyncExt.ActionIndex = ActiveIndex;
+            return SL_RET_CODE_OK;
+        }
+        /* In case this action is socket related, SocketID is in use, otherwise will be set to SL_MAX_SOCKETS */
+        if ( (_SlActionLookupTable[ g_pCB->ObjPool[ActiveIndex].ActionID - MAX_SOCKET_ENUM_IDX].ActionAsyncOpcode == Opcode) &&
+                ( ((Sd == (g_pCB->ObjPool[ActiveIndex].AdditionalData & BSD_SOCKET_ID_MASK) ) && (SL_MAX_SOCKETS > Sd)) || (SL_MAX_SOCKETS == (g_pCB->ObjPool[ActiveIndex].AdditionalData & BSD_SOCKET_ID_MASK)) ) ) {
+            /* set handler */
+            g_pCB->FunctionParams.AsyncExt.AsyncEvtHandler = _SlActionLookupTable[ g_pCB->ObjPool[ActiveIndex].ActionID - MAX_SOCKET_ENUM_IDX].AsyncEventHandler;
+            g_pCB->FunctionParams.AsyncExt.ActionIndex = ActiveIndex;
+            return SL_RET_CODE_OK;
+        }
+        ActiveIndex = g_pCB->ObjPool[ActiveIndex].NextIndex;
+    }
+
+    return SL_RET_CODE_SELF_ERROR;
+
+}
+
+/* Wrappers for the object functions */
+
+void  cc3100_driver::_SlDrvSyncObjWaitForever(_SlSyncObj_t *pSyncObj)
+{
+    OSI_RET_OK_CHECK(_nonos.sl_SyncObjWait(pSyncObj, NON_OS_SYNC_OBJ_SIGNAL_VALUE, NON_OS_SYNC_OBJ_CLEAR_VALUE, SL_OS_WAIT_FOREVER));
+}
+
+void  cc3100_driver::_SlDrvSyncObjSignal(_SlSyncObj_t *pSyncObj)
+{
+    OSI_RET_OK_CHECK(_nonos.sl_SyncObjSignal(pSyncObj, NON_OS_SYNC_OBJ_SIGNAL_VALUE));
+}
+
+void cc3100_driver::_SlDrvObjLockWaitForever(_SlLockObj_t *pLockObj)
+{
+    OSI_RET_OK_CHECK(_nonos.sl_LockObjLock(pLockObj, NON_OS_LOCK_OBJ_UNLOCK_VALUE, NON_OS_LOCK_OBJ_LOCK_VALUE, SL_OS_WAIT_FOREVER));
+    
+}
+
+void cc3100_driver::_SlDrvProtectionObjLockWaitForever()
+{
+    OSI_RET_OK_CHECK(_nonos.sl_LockObjLock(&g_pCB->ProtectionLockObj, NON_OS_LOCK_OBJ_UNLOCK_VALUE, NON_OS_LOCK_OBJ_LOCK_VALUE, SL_OS_WAIT_FOREVER));
+
+}
+
+void cc3100_driver::_SlDrvObjUnLock(_SlLockObj_t *pLockObj)
+{
+    OSI_RET_OK_CHECK(_nonos.sl_LockObjUnlock(pLockObj, NON_OS_LOCK_OBJ_UNLOCK_VALUE));
+
+}
+
+void cc3100_driver::_SlDrvProtectionObjUnLock()
+{
+    OSI_RET_OK_CHECK(_nonos.sl_LockObjUnlock(&g_pCB->ProtectionLockObj, NON_OS_LOCK_OBJ_UNLOCK_VALUE));
+}
+
+
+void cc3100_driver::_SlDrvMemZero(void* Addr, uint16_t size)
+{
+    memset(Addr, 0, size);
+}
+
+
+void cc3100_driver::_SlDrvResetCmdExt(_SlCmdExt_t* pCmdExt)
+{
+    _SlDrvMemZero(pCmdExt, sizeof (_SlCmdExt_t));
+}
+
+}//namespace mbed_cc3100
+
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_driver.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_driver.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,310 @@
+/*
+ * driver.h - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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.
+ *
+*/
+
+#ifndef DRIVER_INT_H_
+#define DRIVER_INT_H_
+
+#include "mbed.h"
+#include "cc3100_user.h"
+#include "cc3100_simplelink.h"
+
+#include "cc3100_protocol.h"
+#include "cc3100_spi.h"
+//#include "cc3100_nonos.h"
+#include "cc3100_netapp.h"
+//#include "cc3100.h"
+
+
+/*****************************************************************************/
+/* Macro declarations                                                        */
+/*****************************************************************************/
+
+/*  2 LSB of the N2H_SYNC_PATTERN are for sequence number
+only in SPI interface
+support backward sync pattern */
+#define N2H_SYNC_PATTERN_SEQ_NUM_BITS            ((uint32_t)0x00000003) /* Bits 0..1    - use the 2 LBS for seq num */
+#define N2H_SYNC_PATTERN_SEQ_NUM_EXISTS          ((uint32_t)0x00000004) /* Bit  2       - sign that sequence number exists in the sync pattern */
+#define N2H_SYNC_PATTERN_MASK                    ((uint32_t)0xFFFFFFF8) /* Bits 3..31   - constant SYNC PATTERN */
+#define N2H_SYNC_SPI_BUGS_MASK                   ((uint32_t)0x7FFF7F7F) /* Bits 7,15,31 - ignore the SPI (8,16,32 bites bus) error bits  */
+#define BUF_SYNC_SPIM(pBuf)                      ((*(uint32_t *)(pBuf)) & N2H_SYNC_SPI_BUGS_MASK)
+#define N2H_SYNC_SPIM                            (N2H_SYNC_PATTERN    & N2H_SYNC_SPI_BUGS_MASK)
+#define N2H_SYNC_SPIM_WITH_SEQ(TxSeqNum)         ((N2H_SYNC_SPIM & N2H_SYNC_PATTERN_MASK) | N2H_SYNC_PATTERN_SEQ_NUM_EXISTS | ((TxSeqNum) & (N2H_SYNC_PATTERN_SEQ_NUM_BITS)))
+#define MATCH_WOUT_SEQ_NUM(pBuf)                 ( BUF_SYNC_SPIM(pBuf) ==  N2H_SYNC_SPIM )
+#define MATCH_WITH_SEQ_NUM(pBuf, TxSeqNum)       ( BUF_SYNC_SPIM(pBuf) == (N2H_SYNC_SPIM_WITH_SEQ(TxSeqNum)) )
+#define N2H_SYNC_PATTERN_MATCH(pBuf, TxSeqNum) \
+    ( \
+    (  (*((uint32_t *)pBuf) & N2H_SYNC_PATTERN_SEQ_NUM_EXISTS) && ( MATCH_WITH_SEQ_NUM(pBuf, TxSeqNum) ) )	|| \
+    ( !(*((uint32_t *)pBuf) & N2H_SYNC_PATTERN_SEQ_NUM_EXISTS) && ( MATCH_WOUT_SEQ_NUM(pBuf          ) ) )	   \
+    )
+
+#define OPCODE(_ptr)          (((_SlResponseHeader_t *)(_ptr))->GenHeader.Opcode)
+#define RSP_PAYLOAD_LEN(_ptr) (((_SlResponseHeader_t *)(_ptr))->GenHeader.Len - _SL_RESP_SPEC_HDR_SIZE)
+#define SD(_ptr)              (((_SocketAddrResponse_u *)(_ptr))->IpV4.sd)
+/*  Actual size of Recv/Recvfrom response data  */
+#define ACT_DATA_SIZE(_ptr)   (((_SocketAddrResponse_u *)(_ptr))->IpV4.statusOrLen)
+
+#define _SL_PROTOCOL_ALIGN_SIZE(msgLen)             (((msgLen)+3) & (~3))
+#define _SL_IS_PROTOCOL_ALIGNED_SIZE(msgLen)        (!((msgLen) & 3))
+#define _SL_PROTOCOL_CALC_LEN(pCmdCtrl,pCmdExt)     ((pCmdExt) ? \
+                                                     (_SL_PROTOCOL_ALIGN_SIZE(pCmdCtrl->TxDescLen) + _SL_PROTOCOL_ALIGN_SIZE(pCmdExt->TxPayloadLen)) : \
+                                                     (_SL_PROTOCOL_ALIGN_SIZE(pCmdCtrl->TxDescLen)))
+                                                     
+
+namespace mbed_cc3100 {
+	
+//class cc3100;
+	
+/*****************************************************************************/
+/* Structure/Enum declarations                                               */
+/*****************************************************************************/
+//typedef void(*_SlSpawnEntryFunc_t)(void* pValue);
+
+typedef struct {
+    _SlOpcode_t      Opcode;
+    _SlArgSize_t     TxDescLen;
+    _SlArgSize_t     RxDescLen;
+} _SlCmdCtrl_t;
+
+typedef struct {
+    uint16_t  TxPayloadLen;
+    int16_t   RxPayloadLen;
+    int16_t   ActualRxPayloadLen;
+    uint8_t   *pTxPayload;
+    uint8_t   *pRxPayload;
+} _SlCmdExt_t;
+
+
+typedef struct _SlArgsData_t {
+    uint8_t	 *pArgs;
+    uint8_t  *pData;
+} _SlArgsData_t;
+
+typedef struct {
+    _SlSyncObj_t	      SyncObj;
+    uint8_t               *pRespArgs;
+    uint8_t			      ActionID;
+    uint8_t			      AdditionalData; /* use for socketID and one bit which indicate supprt IPV6 or not (1=support, 0 otherwise) */
+    uint8_t				  NextIndex;
+
+} _SlPoolObj_t;
+
+
+typedef enum {
+    SOCKET_0,
+    SOCKET_1,
+    SOCKET_2,
+    SOCKET_3,
+    SOCKET_4,
+    SOCKET_5,
+    SOCKET_6,
+    SOCKET_7,
+    MAX_SOCKET_ENUM_IDX,
+#ifndef SL_TINY_EXT    
+    ACCEPT_ID = MAX_SOCKET_ENUM_IDX,
+    CONNECT_ID,
+#else
+    CONNECT_ID = MAX_SOCKET_ENUM_IDX,
+#endif
+#ifndef SL_TINY_EXT    
+	SELECT_ID,
+#endif
+	GETHOSYBYNAME_ID,
+#ifndef SL_TINY_EXT    
+	GETHOSYBYSERVICE_ID,
+	PING_ID,
+#endif	
+    START_STOP_ID,
+    RECV_ID
+} _SlActionID_e;
+
+typedef struct _SlActionLookup_t {
+    uint8_t					ActionID;
+    uint16_t				ActionAsyncOpcode;
+    _SlSpawnEntryFunc_t		AsyncEventHandler;
+
+} _SlActionLookup_t;
+
+
+typedef struct {
+    uint8_t         TxPoolCnt;
+    _SlLockObj_t    TxLockObj;
+    _SlSyncObj_t    TxSyncObj;
+} _SlFlowContCB_t;
+
+typedef enum {
+    RECV_RESP_CLASS,
+    CMD_RESP_CLASS,
+    ASYNC_EVT_CLASS,
+    DUMMY_MSG_CLASS
+} _SlRxMsgClass_e;
+
+typedef struct {
+    uint8_t                 *pAsyncBuf;         /* place to write pointer to buffer with CmdResp's Header + Arguments */
+    uint8_t					ActionIndex;
+    _SlSpawnEntryFunc_t     AsyncEvtHandler;    /* place to write pointer to AsyncEvent handler (calc-ed by Opcode)   */
+    _SlRxMsgClass_e         RxMsgClass;         /* type of Rx message                                                 */
+} AsyncExt_t;
+
+typedef struct {
+    _SlCmdCtrl_t         *pCmdCtrl;
+    uint8_t              *pTxRxDescBuff;
+    _SlCmdExt_t          *pCmdExt;
+    AsyncExt_t           AsyncExt;
+} _SlFunctionParams_t;
+
+typedef void (*P_INIT_CALLBACK)(uint32_t Status);
+
+typedef struct {
+    _SlFd_t                    FD;
+    _SlLockObj_t               GlobalLockObj;
+    _SlCommandHeader_t         TempProtocolHeader;
+    P_INIT_CALLBACK            pInitCallback;
+
+    _SlPoolObj_t               ObjPool[MAX_CONCURRENT_ACTIONS];
+    uint8_t					   FreePoolIdx;
+    uint8_t					   PendingPoolIdx;
+    uint8_t					   ActivePoolIdx;
+    uint32_t				   ActiveActionsBitmap;
+    _SlLockObj_t               ProtectionLockObj;
+
+    _SlSyncObj_t               CmdSyncObj;
+    uint8_t                    IsCmdRespWaited;
+    _SlFlowContCB_t            FlowContCB;
+    uint8_t	                   TxSeqNum;
+    uint8_t	                   RxDoneCnt;
+    uint8_t	                   SocketNonBlocking;
+	uint8_t	                   SocketTXFailure;
+    /* for stack reduction the parameters are globals */
+    _SlFunctionParams_t        FunctionParams;
+
+    uint8_t	                   ActionIndex;
+}_SlDriverCb_t;
+
+extern volatile uint8_t	RxIrqCnt;
+
+extern _SlDriverCb_t* g_pCB;
+typedef uint8_t _SlSd_t;
+
+class cc3100_driver
+{
+
+public:
+
+    cc3100_driver(cc3100_spi &spi, cc3100_nonos &nonos, cc3100_netapp &netapp, cc3100_flowcont &flowcont);
+
+    ~cc3100_driver();
+
+
+    /*****************************************************************************/
+    /* Function prototypes                                                       */
+    /*****************************************************************************/
+    typedef _SlDriverCb_t pDriver;
+    
+    uint8_t _SlDrvProtectAsyncRespSetting(uint8_t *pAsyncRsp, uint8_t ActionID, uint8_t SocketID);
+    
+    bool _SL_PENDING_RX_MSG(pDriver* pDriverCB);
+    
+    void _SlDrvDriverCBInit(void);
+
+    void _SlDrvDriverCBDeinit(void);
+
+    void _SlDrvRxIrqHandler(void *pValue);
+
+    _SlReturnVal_t  _SlDrvCmdOp(_SlCmdCtrl_t *pCmdCtrl , void* pTxRxDescBuff , _SlCmdExt_t* pCmdExt);
+
+    _SlReturnVal_t  _SlDrvCmdSend(_SlCmdCtrl_t *pCmdCtrl , void* pTxRxDescBuff , _SlCmdExt_t* pCmdExt);
+
+    _SlReturnVal_t  _SlDrvDataReadOp(_SlSd_t Sd, _SlCmdCtrl_t *pCmdCtrl , void* pTxRxDescBuff , _SlCmdExt_t* pCmdExt);
+
+    _SlReturnVal_t  _SlDrvDataWriteOp(_SlSd_t Sd, _SlCmdCtrl_t *pCmdCtrl , void* pTxRxDescBuff , _SlCmdExt_t* pCmdExt);
+#ifndef SL_TINY_EXT
+    int16_t  _SlDrvBasicCmd(_SlOpcode_t Opcode);
+#endif
+    uint8_t _SlDrvWaitForPoolObj(uint8_t ActionID, uint8_t SocketID);
+
+    void _SlDrvReleasePoolObj(uint8_t pObj);
+
+//    void _SlDrvObjInit(void);
+
+    _SlReturnVal_t   _SlDrvMsgRead(void);
+    
+    _SlReturnVal_t   _SlDrvMsgWrite(_SlCmdCtrl_t  *pCmdCtrl,_SlCmdExt_t  *pCmdExt, uint8_t *pTxRxDescBuff);
+
+ //   _SlReturnVal_t   _SlDrvMsgWrite(void);
+
+    _SlReturnVal_t   _SlDrvMsgReadCmdCtx(void);
+
+    _SlReturnVal_t   _SlDrvMsgReadSpawnCtx_(void *pValue);
+
+    void             _SlDrvClassifyRxMsg(_SlOpcode_t Opcode );
+
+    _SlReturnVal_t   _SlDrvRxHdrRead(uint8_t *pBuf, uint8_t *pAlignSize);
+
+    void             _SlDrvShiftDWord(uint8_t *pBuf);
+
+    void             _SlAsyncEventGenericHandler(void);
+
+    void			 _SlDrvObjDeInit(void);
+
+    void			 _SlRemoveFromList(uint8_t* ListIndex, uint8_t ItemIndex);
+
+    _SlReturnVal_t	 _SlFindAndSetActiveObj(_SlOpcode_t  Opcode, uint8_t Sd);
+    
+    uint16_t _SlDrvAlignSize(uint16_t msgLen); 
+    void  _SlDrvSyncObjWaitForever(_SlSyncObj_t *pSyncObj);
+    void  _SlDrvSyncObjSignal(_SlSyncObj_t *pSyncObj);
+    void  _SlDrvObjLock(_SlLockObj_t *pLockObj, _SlTime_t Timeout);
+    void  _SlDrvObjLockWaitForever(_SlLockObj_t *pLockObj);
+    void  _SlDrvObjUnLock(_SlLockObj_t *pLockObj);    
+    void  _SlDrvProtectionObjLockWaitForever();
+    void  _SlDrvProtectionObjUnLock();
+    void  _SlDrvMemZero(void* Addr, uint16_t size);
+    void  _SlDrvResetCmdExt(_SlCmdExt_t* pCmdExt);
+
+
+private:
+
+    cc3100_spi        &_spi;
+    cc3100_nonos      &_nonos;
+    cc3100_netapp     &_netapp;
+    cc3100_flowcont   &_flowcont;
+
+};//class
+
+}//namespace mbed_cc3100
+
+#endif /* __DRIVER_INT_H__ */
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_fs.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_fs.cpp	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,396 @@
+/*
+ * fs.c - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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 files                                                             */
+/*****************************************************************************/
+#include "cc3100_simplelink.h"
+#include "cc3100_protocol.h"
+#include "cc3100_driver.h"
+
+#include "cc3100_fs.h"
+
+/*****************************************************************************/
+/* Macro declarations                                                        */
+/*****************************************************************************/
+#define sl_min(a,b) (((a) < (b)) ? (a) : (b))
+#define MAX_NVMEM_CHUNK_SIZE  1460
+
+namespace mbed_cc3100 {
+
+cc3100_fs::cc3100_fs(cc3100_driver &driver)
+    : _driver(driver)
+{
+
+}
+
+cc3100_fs::~cc3100_fs()
+{
+
+}
+
+#ifndef SL_TINY
+/*****************************************************************************/
+/* Internal functions                                                        */
+/*****************************************************************************/
+
+
+/*****************************************************************************/
+/* _sl_Strlen                                                                */
+/*****************************************************************************/
+uint16_t cc3100_fs::_sl_Strlen(const uint8_t *buffer)
+{
+    uint16_t len = 0;
+    if( buffer != NULL ) {
+        while(*buffer++) len++;
+    }
+    return len;
+}
+
+/*****************************************************************************/
+/* _sl_GetCreateFsMode                                                       */
+/*****************************************************************************/
+uint32_t cc3100_fs::_sl_GetCreateFsMode(uint32_t maxSizeInBytes,uint32_t accessFlags)
+{
+    uint32_t granIdx = 0;
+    uint32_t granNum = 0;
+    uint32_t granTable[_FS_MAX_MODE_SIZE_GRAN] = {256,1024,4096,16384,65536};
+    for(granIdx= _FS_MODE_SIZE_GRAN_256B ; granIdx< _FS_MAX_MODE_SIZE_GRAN; granIdx++) {
+        if( granTable[granIdx]*255 >= maxSizeInBytes )
+            break;
+    }
+    granNum = maxSizeInBytes/granTable[granIdx];
+    if( maxSizeInBytes % granTable[granIdx] != 0 )
+        granNum++;
+
+    return _FS_MODE(_FS_MODE_OPEN_WRITE_CREATE_IF_NOT_EXIST,  granIdx, granNum, accessFlags);
+}
+#endif
+
+/*****************************************************************************/
+/* API functions                                                        */
+/*****************************************************************************/
+
+/*****************************************************************************/
+/*  sl_FsOpen */
+/*****************************************************************************/
+typedef union {
+    _FsOpenCommand_t	    Cmd;
+    _FsOpenResponse_t	    Rsp;
+} _SlFsOpenMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_FsOpen)
+const _SlCmdCtrl_t _SlFsOpenCmdCtrl = {
+    SL_OPCODE_NVMEM_FILEOPEN,
+    sizeof(_FsOpenCommand_t),
+    sizeof(_FsOpenResponse_t)
+};
+
+int32_t cc3100_fs::sl_FsOpen(const uint8_t *pFileName, const uint32_t AccessModeAndMaxSize, uint32_t *pToken,int32_t *pFileHandle)
+{
+    _SlReturnVal_t        RetVal;
+    _SlFsOpenMsg_u        Msg;
+    _SlCmdExt_t           CmdExt;
+
+    CmdExt.TxPayloadLen = (_sl_Strlen(pFileName)+4) & (~3); // add 4: 1 for NULL and the 3 for align
+    CmdExt.RxPayloadLen = 0;
+    CmdExt.pTxPayload = (uint8_t *)pFileName;
+    CmdExt.pRxPayload = NULL;
+
+    Msg.Cmd.Mode          =  AccessModeAndMaxSize;
+
+    if(pToken != NULL) {
+        Msg.Cmd.Token         = *pToken;
+    } else {
+        Msg.Cmd.Token         = 0;
+    }
+
+    RetVal = _driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlFsOpenCmdCtrl, &Msg, &CmdExt);
+    *pFileHandle = Msg.Rsp.FileHandle;
+    if (pToken != NULL) {
+        *pToken =      Msg.Rsp.Token;
+    }
+
+    /* in case of an error, return the erros file handler as an error code */
+    if( *pFileHandle < 0 ) {
+        return *pFileHandle;
+    }
+    return (int32_t)RetVal;
+}
+#endif
+
+/*****************************************************************************/
+/* sl_FsClose */
+/*****************************************************************************/
+typedef union {
+    _FsCloseCommand_t	    Cmd;
+    _BasicResponse_t	    Rsp;
+} _SlFsCloseMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_FsClose)
+const _SlCmdCtrl_t _SlFsCloseCmdCtrl = {
+    SL_OPCODE_NVMEM_FILECLOSE,
+    sizeof(_FsCloseCommand_t),
+    sizeof(_FsCloseResponse_t)
+};
+
+int16_t cc3100_fs::sl_FsClose(const int32_t FileHdl, const uint8_t*  pCeritificateFileName, const uint8_t*  pSignature ,const uint32_t SignatureLen)
+{
+    _SlFsCloseMsg_u Msg = {0};
+    _SlCmdExt_t         ExtCtrl;
+
+    Msg.Cmd.FileHandle             = FileHdl;
+    if( pCeritificateFileName != NULL ) {
+        Msg.Cmd.CertificFileNameLength = (_sl_Strlen(pCeritificateFileName)+4) & (~3); /* add 4: 1 for NULL and the 3 for align */
+    }
+    Msg.Cmd.SignatureLen           = SignatureLen;
+
+    ExtCtrl.TxPayloadLen = ((SignatureLen+3) & (~3)); /* align */
+    ExtCtrl.pTxPayload   = (uint8_t*)pSignature;
+    ExtCtrl.RxPayloadLen = (int16_t)Msg.Cmd.CertificFileNameLength;
+    ExtCtrl.pRxPayload   = (uint8_t*)pCeritificateFileName; /* Add signature */
+
+    if(ExtCtrl.pRxPayload != NULL &&  ExtCtrl.RxPayloadLen != 0) {
+        ExtCtrl.RxPayloadLen = ExtCtrl.RxPayloadLen * (-1);
+    }
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlFsCloseCmdCtrl, &Msg, &ExtCtrl));
+
+    return (int16_t)((int16_t)Msg.Rsp.status);
+}
+#endif
+
+
+/*****************************************************************************/
+/* sl_FsRead */
+/*****************************************************************************/
+typedef union {
+    _FsReadCommand_t	    Cmd;
+    _FsReadResponse_t	    Rsp;
+} _SlFsReadMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_FsRead)
+const _SlCmdCtrl_t _SlFsReadCmdCtrl = {
+    SL_OPCODE_NVMEM_FILEREADCOMMAND,
+    sizeof(_FsReadCommand_t),
+    sizeof(_FsReadResponse_t)
+};
+
+int32_t cc3100_fs::sl_FsRead(const int32_t FileHdl, uint32_t Offset, uint8_t*  pData, uint32_t Len)
+{
+    _SlFsReadMsg_u      Msg;
+    _SlCmdExt_t         ExtCtrl;
+    uint16_t      ChunkLen;
+    _SlReturnVal_t      RetVal =0;
+    int32_t                RetCount = 0;
+
+    ExtCtrl.TxPayloadLen = 0;
+    ExtCtrl.pTxPayload   = NULL;
+
+    ChunkLen = (uint16_t)sl_min(MAX_NVMEM_CHUNK_SIZE,Len);
+    ExtCtrl.RxPayloadLen = ChunkLen;
+    ExtCtrl.pRxPayload   = (uint8_t *)(pData);
+    Msg.Cmd.Offset       = Offset;
+    Msg.Cmd.Len          = ChunkLen;
+    Msg.Cmd.FileHandle   = FileHdl;
+    do {
+        RetVal = _driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlFsReadCmdCtrl, &Msg, &ExtCtrl);
+        if(SL_OS_RET_CODE_OK == RetVal) {
+            if( Msg.Rsp.status < 0) {
+                if( RetCount > 0) {
+                    return RetCount;
+                } else {
+                    return Msg.Rsp.status;
+                }
+            }
+            RetCount += (int32_t)Msg.Rsp.status;
+            Len -= ChunkLen;
+            Offset += ChunkLen;
+            Msg.Cmd.Offset      = Offset;
+            ExtCtrl.pRxPayload   += ChunkLen;
+            ChunkLen = (uint16_t)sl_min(MAX_NVMEM_CHUNK_SIZE,Len);
+            ExtCtrl.RxPayloadLen  = ChunkLen;
+            Msg.Cmd.Len           = ChunkLen;
+            Msg.Cmd.FileHandle  = FileHdl;
+        } else {
+            return RetVal;
+        }
+    } while(ChunkLen > 0);
+
+    return (int32_t)RetCount;
+}
+#endif
+
+/*****************************************************************************/
+/* sl_FsWrite */
+/*****************************************************************************/
+typedef union {
+    _FsWriteCommand_t	    Cmd;
+    _FsWriteResponse_t	    Rsp;
+} _SlFsWriteMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_FsWrite)
+const _SlCmdCtrl_t _SlFsWriteCmdCtrl = {
+    SL_OPCODE_NVMEM_FILEWRITECOMMAND,
+    sizeof(_FsWriteCommand_t),
+    sizeof(_FsWriteResponse_t)
+};
+
+int32_t cc3100_fs::sl_FsWrite(const int32_t FileHdl, uint32_t Offset, uint8_t*  pData, uint32_t Len)
+{
+    _SlFsWriteMsg_u     Msg;
+    _SlCmdExt_t         ExtCtrl;
+    uint16_t      ChunkLen;
+    _SlReturnVal_t      RetVal;
+    int32_t                RetCount = 0;
+
+    ExtCtrl.RxPayloadLen = 0;
+    ExtCtrl.pRxPayload   = NULL;
+
+    ChunkLen = (uint16_t)sl_min(MAX_NVMEM_CHUNK_SIZE,Len);
+    ExtCtrl.TxPayloadLen = ChunkLen;
+    ExtCtrl.pTxPayload   = (uint8_t *)(pData);
+    Msg.Cmd.Offset      = Offset;
+    Msg.Cmd.Len          = ChunkLen;
+    Msg.Cmd.FileHandle  = FileHdl;
+
+    do {
+
+        RetVal = _driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlFsWriteCmdCtrl, &Msg, &ExtCtrl);
+        if(SL_OS_RET_CODE_OK == RetVal) {
+            if( Msg.Rsp.status < 0) {
+                if( RetCount > 0) {
+                    return RetCount;
+                } else {
+                    return Msg.Rsp.status;
+                }
+            }
+
+            RetCount += (int32_t)Msg.Rsp.status;
+            Len -= ChunkLen;
+            Offset += ChunkLen;
+            Msg.Cmd.Offset        = Offset;
+            ExtCtrl.pTxPayload   += ChunkLen;
+            ChunkLen = (uint16_t)sl_min(MAX_NVMEM_CHUNK_SIZE,Len);
+            ExtCtrl.TxPayloadLen  = ChunkLen;
+            Msg.Cmd.Len           = ChunkLen;
+            Msg.Cmd.FileHandle  = FileHdl;
+        } else {
+            return RetVal;
+        }
+    } while(ChunkLen > 0);
+
+    return (int32_t)RetCount;
+}
+#endif
+
+/*****************************************************************************/
+/* sl_FsGetInfo */
+/*****************************************************************************/
+typedef union {
+    _FsGetInfoCommand_t	    Cmd;
+    _FsGetInfoResponse_t    Rsp;
+} _SlFsGetInfoMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_FsGetInfo)
+const _SlCmdCtrl_t _SlFsGetInfoCmdCtrl = {
+    SL_OPCODE_NVMEM_FILEGETINFOCOMMAND,
+    sizeof(_FsGetInfoCommand_t),
+    sizeof(_FsGetInfoResponse_t)
+};
+
+int16_t cc3100_fs::sl_FsGetInfo(const uint8_t *pFileName, const uint32_t Token,SlFsFileInfo_t* pFsFileInfo)
+{
+    _SlFsGetInfoMsg_u    Msg;
+    _SlCmdExt_t          CmdExt;
+
+    CmdExt.TxPayloadLen = (_sl_Strlen(pFileName)+4) & (~3); /* add 4: 1 for NULL and the 3 for align  */
+    CmdExt.RxPayloadLen = 0;
+    CmdExt.pTxPayload   = (uint8_t *)pFileName;
+    CmdExt.pRxPayload   = NULL;
+    Msg.Cmd.Token       = Token;
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlFsGetInfoCmdCtrl, &Msg, &CmdExt));
+
+    pFsFileInfo->flags        = Msg.Rsp.flags;
+    pFsFileInfo->FileLen      = Msg.Rsp.FileLen;
+    pFsFileInfo->AllocatedLen = Msg.Rsp.AllocatedLen;
+    pFsFileInfo->Token[0]     = Msg.Rsp.Token[0];
+    pFsFileInfo->Token[1]     = Msg.Rsp.Token[1];
+    pFsFileInfo->Token[2]     = Msg.Rsp.Token[2];
+    pFsFileInfo->Token[3]     = Msg.Rsp.Token[3];
+    return  (int16_t)((int16_t)Msg.Rsp.Status);
+}
+#endif
+
+/*****************************************************************************/
+/* sl_FsDel */
+/*****************************************************************************/
+typedef union {
+    _FsDeleteCommand_t   	    Cmd;
+    _FsDeleteResponse_t	        Rsp;
+} _SlFsDeleteMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_FsDel)
+const _SlCmdCtrl_t _SlFsDeleteCmdCtrl = {
+    SL_OPCODE_NVMEM_FILEDELCOMMAND,
+    sizeof(_FsDeleteCommand_t),
+    sizeof(_FsDeleteResponse_t)
+};
+
+int16_t cc3100_fs::sl_FsDel(const uint8_t *pFileName, const uint32_t Token)
+{
+    _SlFsDeleteMsg_u Msg;
+    _SlCmdExt_t          CmdExt;
+
+    CmdExt.TxPayloadLen = (_sl_Strlen(pFileName)+4) & (~3); /* add 4: 1 for NULL and the 3 for align */
+    CmdExt.RxPayloadLen = 0;
+    CmdExt.pTxPayload   = (uint8_t *)pFileName;
+    CmdExt.pRxPayload   = NULL;
+    Msg.Cmd.Token       = Token;
+
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlFsDeleteCmdCtrl, &Msg, &CmdExt));
+
+    return  (int16_t)((int16_t)Msg.Rsp.status);
+}
+#endif
+
+}//namespace mbed_cc3100
+
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_fs.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_fs.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,392 @@
+/*
+ * fs.h - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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 files                                                             */
+/*****************************************************************************/
+
+#include "cc3100_simplelink.h"
+
+#ifndef FS_H_
+#define FS_H_
+
+/*!
+
+    \addtogroup FileSystem
+    @{
+
+*/
+
+/*****************************************************************************/
+/* Macro declarations                                                        */
+/*****************************************************************************/
+
+/* FS error codes */
+#define SL_FS_OK                                              (0)
+#define SL_FS_ERR_EMPTY_SFLASH                                (-67)
+#define SL_FS_ERR_FILE_IS_NOT_SECURE_AND_SIGN                 (-66)
+#define SL_FS_ERASING_FLASH                                   (-65)
+#define SL_FS_FILE_HAS_NOT_BEEN_CLOSE_CORRECTLY               (-64)
+#define SL_FS_WRONG_SIGNATURE                                 (-63)
+#define SL_FS_WRONG_SIGNATURE_OR_CERTIFIC_NAME_LENGTH         (-62)
+#define SL_FS_NOT_16_ALIGNED                                  (-61)
+#define SL_FS_CERT_CHAIN_ERROR                                (-60)
+#define SL_FS_FILE_NAME_EXIST                                 (-59)
+#define SL_FS_SECURITY_BUF_ALREADY_ALLOC                      (-58)
+#define SL_FS_SECURE_FILE_MUST_BE_COMMIT                      (-57)
+#define SL_FS_ERR_INCORRECT_OFFSET_ALIGNMENT                  (-56)
+#define SL_FS_ERR_FAILED_READ_NVMEM_HEADER                    (-55)
+#define SL_FS_WRONG_FILE_NAME                                 (-54)
+#define SL_FS_FILE_SYSTEM_IS_LOCKED                           (-53)
+#define SL_FS_SECURITY_ALLERT                                 (-52)
+#define SL_FS_FILE_UNVALID_FILE_SIZE                          (-51)
+#define SL_FS_ERR_TOKEN_IS_NOT_VALID                          (-50)
+#define SL_FS_NO_DEVICE_IS_LOADED                             (-49)
+#define SL_FS_DATA_ADDRESS_SHOUD_BE_IN_DATA_RAM               (-48)
+#define SL_FS_DATA_IS_NOT_ALIGNED                             (-47)
+#define SL_FS_ERR_OVERLAP_DETECTION_THRESHHOLD                (-46)
+#define SL_FS_FILE_HAS_RESERVED_NV_INDEX                      (-45)
+#define SL_FS_ERR_MAX_FS_FILES_IS_LARGER                      (-44)
+#define SL_FS_ERR_MAX_FS_FILES_IS_SMALLER                     (-43)
+#define SL_FS_FILE_MAX_SIZE_EXCEEDED                          (-42)
+#define SL_FS_INVALID_BUFFER_FOR_READ                         (-41)
+#define SL_FS_INVALID_BUFFER_FOR_WRITE                        (-40)
+#define SL_FS_ERR_FILE_IMAGE_IS_CORRUPTED                     (-39)
+#define SL_FS_ERR_SIZE_OF_FILE_EXT_EXCEEDED                   (-38)
+#define SL_FS_WARNING_FILE_NAME_NOT_KEPT                      (-37)
+#define SL_FS_ERR_DEVICE_IS_NOT_FORMATTED                     (-36)
+#define SL_FS_ERR_FAILED_WRITE_NVMEM_HEADER                   (-35)
+#define SL_FS_ERR_NO_AVAILABLE_NV_INDEX                       (-34)
+#define SL_FS_ERR_FAILED_TO_ALLOCATE_MEM                      (-33)
+#define SL_FS_ERR_FAILED_TO_READ_INTEGRITY_HEADER_2           (-32)
+#define SL_FS_ERR_FAILED_TO_READ_INTEGRITY_HEADER_1           (-31)
+#define SL_FS_ERR_NO_AVAILABLE_BLOCKS                         (-30)
+#define SL_FS_ERR_FILE_MAX_SIZE_BIGGER_THAN_EXISTING_FILE     (-29)
+#define SL_FS_ERR_FILE_EXISTS_ON_DIFFERENT_DEVICE_ID          (-28)
+#define SL_FS_ERR_INVALID_ACCESS_TYPE                         (-27)
+#define SL_FS_ERR_FILE_ALREADY_EXISTS                         (-26)
+#define SL_FS_ERR_PROGRAM                                     (-25)
+#define SL_FS_ERR_NO_ENTRIES_AVAILABLE                        (-24)
+#define SL_FS_ERR_FILE_ACCESS_IS_DIFFERENT                    (-23)
+#define SL_FS_ERR_BAD_FILE_MODE                               (-22)
+#define SL_FS_ERR_FAILED_READ_NVFILE                          (-21)
+#define SL_FS_ERR_FAILED_INIT_STORAGE                         (-20)
+#define SL_FS_ERR_CONTINUE_WRITE_MUST_BE_MOD_4                (-19)
+#define SL_FS_ERR_FAILED_LOAD_FILE                            (-18)
+#define SL_FS_ERR_INVALID_HANDLE                              (-17)
+#define SL_FS_ERR_FAILED_TO_WRITE                             (-16)
+#define SL_FS_ERR_OFFSET_OUT_OF_RANGE                         (-15)
+#define SL_FS_ERR_ALLOC                                       (-14)
+#define SL_FS_ERR_READ_DATA_LENGTH                            (-13)
+#define SL_FS_ERR_INVALID_FILE_ID                             (-12)
+#define SL_FS_ERR_FILE_NOT_EXISTS                             (-11)
+#define SL_FS_ERR_EMPTY_ERROR                                 (-10)
+#define SL_FS_ERR_INVALID_ARGS                                (-9)
+#define SL_FS_ERR_FAILED_TO_CREATE_FILE                       (-8)
+#define SL_FS_ERR_FS_ALREADY_LOADED                           (-7)
+#define SL_FS_ERR_UNKNOWN                                     (-6)
+#define SL_FS_ERR_FAILED_TO_CREATE_LOCK_OBJ                   (-5)
+#define SL_FS_ERR_DEVICE_NOT_LOADED                           (-4)
+#define SL_FS_ERR_INVALID_MAGIC_NUM                           (-3)
+#define SL_FS_ERR_FAILED_TO_READ                              (-2)
+#define SL_FS_ERR_NOT_SUPPORTED                               (-1)
+/* end of error codes */
+
+#define _FS_MODE_ACCESS_RESERVED_OFFSET                       (24)
+#define _FS_MODE_ACCESS_RESERVED_MASK                         (0xFF)
+#define _FS_MODE_ACCESS_FLAGS_OFFSET                          (16)
+#define _FS_MODE_ACCESS_FLAGS_MASK                            (0xFF)
+#define _FS_MODE_ACCESS_OFFSET                                (12)
+#define _FS_MODE_ACCESS_MASK                                  (0xF)
+#define _FS_MODE_OPEN_SIZE_GRAN_OFFSET                        (8)
+#define _FS_MODE_OPEN_SIZE_GRAN_MASK                          (0xF)
+#define _FS_MODE_OPEN_SIZE_OFFSET                             (0)
+#define _FS_MODE_OPEN_SIZE_MASK                               (0xFF)
+#define MAX_MODE_SIZE                                         (0xFF)
+#define _FS_MODE(Access, SizeGran, Size,Flags)        (uint32_t)(((uint32_t)((Access) & _FS_MODE_ACCESS_MASK)<<_FS_MODE_ACCESS_OFFSET) |  \
+                                                            ((uint32_t)((SizeGran) & _FS_MODE_OPEN_SIZE_GRAN_MASK)<<_FS_MODE_OPEN_SIZE_GRAN_OFFSET) | \
+                                                            ((uint32_t)((Size) & _FS_MODE_OPEN_SIZE_MASK)<<_FS_MODE_OPEN_SIZE_OFFSET) | \
+                                                            ((uint32_t)((Flags) & _FS_MODE_ACCESS_FLAGS_MASK)<<_FS_MODE_ACCESS_FLAGS_OFFSET))
+
+
+/*  sl_FsOpen options */
+/*  Open for Read */
+#define FS_MODE_OPEN_READ                                     _FS_MODE(_FS_MODE_OPEN_READ,0,0,0)
+/*  Open for Write (in case file exist) */
+#define FS_MODE_OPEN_WRITE                                    _FS_MODE(_FS_MODE_OPEN_WRITE,0,0,0)
+/* Open for Creating a new file */
+#define FS_MODE_OPEN_CREATE(maxSizeInBytes,accessModeFlags)   _sl_GetCreateFsMode(maxSizeInBytes,accessModeFlags)
+
+namespace mbed_cc3100 {
+
+/*****************************************************************************/
+/* Structure/Enum declarations                                               */
+/*****************************************************************************/
+typedef struct {
+    uint16_t flags;
+    uint32_t  FileLen;
+    uint32_t  AllocatedLen;
+    uint32_t  Token[4];
+} SlFsFileInfo_t;
+
+typedef enum {
+    _FS_MODE_OPEN_READ            = 0,
+    _FS_MODE_OPEN_WRITE,
+    _FS_MODE_OPEN_CREATE,
+    _FS_MODE_OPEN_WRITE_CREATE_IF_NOT_EXIST
+} SlFsFileOpenAccessType_e;
+
+typedef enum {
+    _FS_FILE_OPEN_FLAG_COMMIT  =  0x1,           /* MIRROR - for fail safe */
+    _FS_FILE_OPEN_FLAG_SECURE  =  0x2,           /* SECURE */
+    _FS_FILE_OPEN_FLAG_NO_SIGNATURE_TEST = 0x4,  /* Relevant to secure file only  */
+    _FS_FILE_OPEN_FLAG_STATIC  =           0x8,  /*  Relevant to secure file only */
+    _FS_FILE_OPEN_FLAG_VENDOR  =           0x10, /*  Relevant to secure file only */
+    _FS_FILE_PUBLIC_WRITE=                 0x20, /* Relevant to secure file only, the file can be opened for write without Token */
+    _FS_FILE_PUBLIC_READ =                 0x40  /* Relevant to secure file only, the file can be opened for read without Token  */
+} SlFileOpenFlags_e;
+
+typedef enum {
+    _FS_MODE_SIZE_GRAN_256B    = 0,   /*  MAX_SIZE = 64K  */
+    _FS_MODE_SIZE_GRAN_1KB,           /*  MAX_SIZE = 256K */
+    _FS_MODE_SIZE_GRAN_4KB,           /*  MAX_SZIE = 1M   */
+    _FS_MODE_SIZE_GRAN_16KB,          /*  MAX_SIZE = 4M   */
+    _FS_MODE_SIZE_GRAN_64KB,          /*  MAX_SIZE = 16M  */
+    _FS_MAX_MODE_SIZE_GRAN
+} _SlFsFileOpenMaxSizeGran_e;
+
+class cc3100_driver;
+
+class cc3100_fs
+{
+
+public:
+
+    cc3100_fs(cc3100_driver &driver);
+
+    ~cc3100_fs();
+
+    /*****************************************************************************/
+    /* Internal Function prototypes                                              */
+    /*****************************************************************************/
+    uint32_t _sl_GetCreateFsMode(uint32_t maxSizeInBytes,uint32_t accessFlags);
+    uint16_t _sl_Strlen(const uint8_t *buffer);
+
+    /*****************************************************************************/
+    /* Function prototypes                                                       */
+    /*****************************************************************************/
+
+    /*!
+        \brief open file for read or write from/to storage device
+
+        \param[in]      pFileName                  File Name buffer pointer
+        \param[in]      AccessModeAndMaxSize       Options: As described below
+        \param[in]      pToken                     Reserved for future use. Use NULL for this field
+        \param[out]     pFileHandle      Pointing on the file and used for read and write commands to the file
+
+         AccessModeAndMaxSize possible input                                                                        \n
+         FS_MODE_OPEN_READ                                        - Read a file                                                                  \n
+         FS_MODE_OPEN_WRITE                                       - Open for write for an existing file                                          \n
+         FS_MODE_OPEN_CREATE(maxSizeInBytes,accessModeFlags)      - Open for creating a new file. Max file size is defined in bytes.             \n
+                                                                    For optimal FS size, use max size in 4K-512 bytes steps (e.g. 3584,7680,117760)  \n
+                                                                    Several access modes bits can be combined together from SlFileOpenFlags_e enum
+
+        \return         On success, zero is returned. On error, an error code is returned
+
+        \sa             sl_FsRead sl_FsWrite sl_FsClose
+        \note           belongs to \ref basic_api
+        \warning
+        \par            Example:
+        \code
+           char*           DeviceFileName = "MyFile.txt";
+           unsigned long   MaxSize = 63 * 1024; //62.5K is max file size
+           long            DeviceFileHandle = -1;
+           long            RetVal;        //negative retval is an error
+           unsigned long   Offset = 0;
+           uint8_t   InputBuffer[100];
+
+           // Create a file and write data. The file in this example is secured, without signature and with a fail safe commit
+           RetVal = sl_FsOpen((uint8_t *)DeviceFileName,
+                                            FS_MODE_OPEN_CREATE(MaxSize , _FS_FILE_OPEN_FLAG_NO_SIGNATURE_TEST | _FS_FILE_OPEN_FLAG_COMMIT ),
+                                            NULL, &DeviceFileHandle);
+
+           Offset = 0;
+           //Preferred in secure file that the Offset and the length will be aligned to 16 bytes.
+           RetVal = sl_FsWrite( DeviceFileHandle, Offset, (uint8_t *)"HelloWorld", strlen("HelloWorld"));
+
+           RetVal = sl_FsClose(DeviceFileHandle, NULL, NULL , 0);
+
+           // open the same file for read, using the Token we got from the creation procedure above
+           RetVal = sl_FsOpen((uint8_t *)DeviceFileName,
+                                            FS_MODE_OPEN_READ,
+                                            NULL, &DeviceFileHandle);
+
+           Offset = 0;
+           RetVal = sl_FsRead( DeviceFileHandle, Offset, (uint8_t *)InputBuffer, strlen("HelloWorld"));
+
+           RetVal = sl_FsClose(DeviceFileHandle, NULL, NULL , 0);
+
+         \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_FsOpen)
+    int32_t sl_FsOpen(const uint8_t *pFileName, const uint32_t AccessModeAndMaxSize,uint32_t *pToken,int32_t *pFileHandle);
+#endif
+
+    /*!
+        \brief close file in storage device
+
+        \param[in]      FileHdl                 Pointer to the file (assigned from sl_FsOpen)
+        \param[in]      pCeritificateFileName   Reserved for future use. Use NULL.
+        \param[in]      pSignature              Reserved for future use. Use NULL.
+        \param[in]      SignatureLen            Reserved for future use. Use 0.
+
+
+        \return         On success, zero is returned.  On error, an error code is returned
+
+        \sa             sl_FsRead sl_FsWrite sl_FsOpen
+        \note           Call the fs_Close  with signature = 'A' signature len = 1 for activating an abort action
+        \warning
+        \par            Example:
+        \code
+        sl_FsClose(FileHandle,0,0,0);
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_FsClose)
+    int16_t sl_FsClose(const int32_t FileHdl, const uint8_t* pCeritificateFileName, const uint8_t* pSignature, const uint32_t SignatureLen);
+#endif
+
+    /*!
+        \brief Read block of data from a file in storage device
+
+        \param[in]      FileHdl Pointer to the file (assigned from sl_FsOpen)
+        \param[in]      Offset  Offset to specific read block
+        \param[out]     pData   Pointer for the received data
+        \param[in]      Len     Length of the received data
+
+        \return         On success, returns the number of read bytes. On error, negative number is returned
+
+        \sa             sl_FsClose sl_FsWrite sl_FsOpen
+        \note           belongs to \ref basic_api
+        \warning
+        \par            Example:
+        \code
+        Status = sl_FsRead(FileHandle, 0, &readBuff[0], readSize);
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_FsRead)
+    int32_t sl_FsRead(const int32_t FileHdl,uint32_t Offset ,uint8_t*  pData,uint32_t Len);
+#endif
+
+    /*!
+        \brief write block of data to a file in storage device
+
+        \param[in]      FileHdl  Pointer to the file (assigned from sl_FsOpen)
+        \param[in]      Offset   Offset to specific block to be written
+        \param[in]      pData    Pointer the transmitted data to the storage device
+        \param[in]      Len      Length of the transmitted data
+
+        \return         On success, returns the number of written bytes.  On error, an error code is returned
+
+        \sa
+        \note           belongs to \ref basic_api
+        \warning
+        \par            Example:
+        \code
+        Status = sl_FsWrite(FileHandle, 0, &buff[0], readSize);
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_FsWrite)
+    int32_t sl_FsWrite(const int32_t FileHdl,uint32_t Offset,uint8_t*  pData,uint32_t Len);
+#endif
+
+    /*!
+        \brief get info on a file
+
+        \param[in]      pFileName    File name
+        \param[in]      Token        Reserved for future use. Use 0
+        \param[out]     pFsFileInfo Returns the File's Information: flags,file size, allocated size and Tokens
+
+        \return         On success, zero is returned.   On error, an error code is returned
+
+        \sa             sl_FsOpen
+        \note           belongs to \ref basic_api
+        \warning
+        \par            Example:
+        \code
+        Status = sl_FsGetInfo("FileName.html",0,&FsFileInfo);
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_FsGetInfo)
+    int16_t sl_FsGetInfo(const uint8_t *pFileName, const uint32_t Token,SlFsFileInfo_t* pFsFileInfo);
+#endif
+
+    /*!
+        \brief Delete specific file from a storage or all files from a storage (format)
+
+        \param[in]      pFileName    File Name
+        \param[in]      Token        Reserved for future use. Use 0
+        \return         On success, zero is returned.  On error, an error code is returned
+
+        \sa
+        \note           belongs to \ref basic_api
+        \warning
+        \par            Example:
+        \code
+        Status = sl_FsDel("FileName.html",0);
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_FsDel)
+    int16_t sl_FsDel(const uint8_t *pFileName, const uint32_t Token);
+#endif
+
+private:
+
+    cc3100_driver &_driver;
+
+};//class
+
+}//namespace mbed_cc3100
+
+/*!
+
+ Close the Doxygen group.
+ @}
+
+ */
+
+#endif /*  __FS_H__ */
+
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_netapp.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_netapp.cpp	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,957 @@
+/*
+ * netapp.c - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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 files                                                             */
+/*****************************************************************************/
+#include "cc3100_simplelink.h"
+#include "cc3100_protocol.h"
+#include "cc3100_driver.h"
+
+#include "cc3100_netapp.h"
+#include "fPtr_func.h"
+#include "cli_uart.h"
+
+namespace mbed_cc3100 {
+
+/*****************************************************************************/
+/* Macro declarations                                                        */
+/*****************************************************************************/
+const uint32_t NETAPP_MDNS_OPTIONS_ADD_SERVICE_BIT			 =		 ((uint32_t)0x1 << 31);
+
+#ifdef SL_TINY
+const uint8_t NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH   =      63;
+#else
+const uint8_t NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH   =      255;
+#endif
+	
+cc3100_netapp::cc3100_netapp(cc3100_driver &driver, cc3100_nonos &nonos)
+    : _driver(driver), _nonos(nonos)
+{
+
+}
+
+cc3100_netapp::~cc3100_netapp()
+{
+
+}
+
+
+/*****************************************************************************/
+/* API functions                                                             */
+/*****************************************************************************/
+
+/*****************************************************************************
+ sl_NetAppStart
+*****************************************************************************/
+typedef union {
+    _NetAppStartStopCommand_t       Cmd;
+    _NetAppStartStopResponse_t   Rsp;
+} _SlNetAppStartStopMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_NetAppStart)
+const _SlCmdCtrl_t _SlNetAppStartCtrl = {
+    SL_OPCODE_NETAPP_START_COMMAND,
+    sizeof(_NetAppStartStopCommand_t),
+    sizeof(_NetAppStartStopResponse_t)
+};
+
+int16_t cc3100_netapp::sl_NetAppStart(const uint32_t AppBitMap)
+{
+    _SlNetAppStartStopMsg_u Msg;
+    Msg.Cmd.appId = AppBitMap;
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlNetAppStartCtrl, &Msg, NULL));
+
+    return Msg.Rsp.status;
+}
+#endif
+
+/*****************************************************************************
+ sl_NetAppStop
+*****************************************************************************/
+#if _SL_INCLUDE_FUNC(sl_NetAppStop)
+const _SlCmdCtrl_t _SlNetAppStopCtrl =
+{
+    SL_OPCODE_NETAPP_STOP_COMMAND,
+    sizeof(_NetAppStartStopCommand_t),
+    sizeof(_NetAppStartStopResponse_t)
+};
+int16_t cc3100_netapp::sl_NetAppStop(const uint32_t AppBitMap)
+{
+    _SlNetAppStartStopMsg_u Msg;
+    Msg.Cmd.appId = AppBitMap;
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlNetAppStopCtrl, &Msg, NULL));
+
+    return Msg.Rsp.status;
+}
+#endif
+
+
+/******************************************************************************/
+/* sl_NetAppGetServiceList */
+/******************************************************************************/
+typedef struct {
+    uint8_t  IndexOffest;
+    uint8_t  MaxServiceCount;
+    uint8_t  Flags;
+    int8_t  Padding;
+} NetappGetServiceListCMD_t;
+
+typedef union {
+    NetappGetServiceListCMD_t      Cmd;
+    _BasicResponse_t                Rsp;
+} _SlNetappGetServiceListMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_NetAppGetServiceList)
+const _SlCmdCtrl_t _SlGetServiceListeCtrl = {
+    SL_OPCODE_NETAPP_NETAPP_MDNS_LOOKUP_SERVICE,
+    sizeof(NetappGetServiceListCMD_t),
+    sizeof(_BasicResponse_t)
+};
+
+int16_t cc3100_netapp::sl_NetAppGetServiceList(const uint8_t  IndexOffest,
+        const uint8_t  MaxServiceCount,
+        const uint8_t  Flags,
+        int8_t  *pBuffer,
+        const uint32_t  RxBufferLength
+                                              )
+{
+    int32_t 					 retVal= 0;
+    _SlNetappGetServiceListMsg_u Msg;
+    _SlCmdExt_t                  CmdExt;
+    uint16_t               ServiceSize = 0;
+    uint16_t               BufferSize = 0;
+
+    /*
+    Calculate RX pBuffer size
+    WARNING:
+    if this size is BufferSize than 1480 error should be returned because there
+    is no place in the RX packet.
+    */
+    switch(Flags) {
+        case SL_NET_APP_FULL_SERVICE_WITH_TEXT_IPV4_TYPE:
+            ServiceSize =  sizeof(SlNetAppGetFullServiceWithTextIpv4List_t);
+            break;
+
+        case SL_NET_APP_FULL_SERVICE_IPV4_TYPE:
+            ServiceSize =  sizeof(SlNetAppGetFullServiceIpv4List_t);
+            break;
+
+        case SL_NET_APP_SHORT_SERVICE_IPV4_TYPE:
+            ServiceSize =  sizeof(SlNetAppGetShortServiceIpv4List_t);
+            break;
+
+        default:
+            ServiceSize =  sizeof(_BasicResponse_t);
+            break;
+    }
+
+
+
+    BufferSize =  MaxServiceCount * ServiceSize;
+
+    /*Check the size of the requested services is smaller than size of the user buffer.
+      If not an error is returned in order to avoid overwriting memory. */
+    if(RxBufferLength <= BufferSize) {
+        return SL_ERROR_NETAPP_RX_BUFFER_LENGTH_ERROR;
+    }
+
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.RxPayloadLen = BufferSize;
+
+    CmdExt.pRxPayload = (uint8_t *)pBuffer;
+
+    Msg.Cmd.IndexOffest		= IndexOffest;
+    Msg.Cmd.MaxServiceCount = MaxServiceCount;
+    Msg.Cmd.Flags			= Flags;
+    Msg.Cmd.Padding			= 0;
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlGetServiceListeCtrl, &Msg, &CmdExt));
+    retVal = Msg.Rsp.status;
+
+    return (int16_t)retVal;
+}
+
+#endif
+
+/*****************************************************************************/
+/* sl_mDNSRegisterService */
+/*****************************************************************************/
+/*
+ * The below struct depicts the constant parameters of the command/API RegisterService.
+ *
+   1. ServiceLen                      - The length of the service should be smaller than NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH.
+   2. TextLen                         - The length of the text should be smaller than NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH.
+   3. port                            - The port on this target host.
+   4. TTL                             - The TTL of the service
+   5. Options                         - bitwise parameters:
+                                        bit 0  - is unique (means if the service needs to be unique)
+										bit 31  - for internal use if the service should be added or deleted (set means ADD).
+                                        bit 1-30 for future.
+
+   NOTE:
+
+   1. There are another variable parameter is this API which is the service name and the text.
+   2. According to now there is no warning and Async event to user on if the service is a unique.
+*
+ */
+
+typedef struct {
+    uint8_t   ServiceNameLen;
+    uint8_t   TextLen;
+    uint16_t  Port;
+    uint32_t   TTL;
+    uint32_t   Options;
+} NetappMdnsSetService_t;
+
+typedef union {
+    NetappMdnsSetService_t         Cmd;
+    _BasicResponse_t                Rsp;
+} _SlNetappMdnsRegisterServiceMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_NetAppMDNSRegisterUnregisterService)
+const _SlCmdCtrl_t _SlRegisterServiceCtrl = {
+    SL_OPCODE_NETAPP_MDNSREGISTERSERVICE,
+    sizeof(NetappMdnsSetService_t),
+    sizeof(_BasicResponse_t)
+};
+
+/******************************************************************************
+
+    sl_NetAppMDNSRegisterService
+
+    CALLER          user from its host
+
+
+    DESCRIPTION:
+                    Add/delete  service
+					The function manipulates the command that register the service and call
+					to the NWP in order to add/delete the service to/from the mDNS package and to/from the DB.
+
+					This register service is a service offered by the application.
+					This unregister service is a service offered by the application before.
+
+					The service name should be full service name according to RFC
+                    of the DNS-SD - means the value in name field in SRV answer.
+
+					Example for service name:
+                    1. PC1._ipp._tcp.local
+                    2. PC2_server._ftp._tcp.local
+
+                    If the option is_unique is set, mDNS probes the service name to make sure
+                    it is unique before starting to announce the service on the network.
+                    Instance is the instance portion of the service name.
+
+
+
+
+    PARAMETERS:
+
+                    The command is from constant parameters and variables parameters.
+
+					Constant parameters are:
+
+                    ServiceLen                          - The length of the service.
+                    TextLen                             - The length of the service should be smaller than 64.
+                    port                                - The port on this target host.
+                    TTL                                 - The TTL of the service
+                    Options                             - bitwise parameters:
+                                                            bit 0  - is unique (means if the service needs to be unique)
+                                                            bit 31  - for internal use if the service should be added or deleted (set means ADD).
+                                                            bit 1-30 for future.
+
+                   The variables parameters are:
+
+                    Service name(full service name)     - The service name.
+                                                          Example for service name:
+                                                          1. PC1._ipp._tcp.local
+                                                          2. PC2_server._ftp._tcp.local
+
+                    Text                                - The description of the service.
+                                                          should be as mentioned in the RFC
+                                                          (according to type of the service IPP,FTP...)
+
+					NOTE - pay attention
+
+						1. Temporary -  there is an allocation on stack of internal buffer.
+						Its size is NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH.
+						It means that the sum of the text length and service name length cannot be bigger than
+						NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH.
+						If it is - An error is returned.
+
+					    2. According to now from certain constraints the variables parameters are set in the
+					    attribute part (contain constant parameters)
+
+
+
+	  RETURNS:        Status - the immediate response of the command status.
+							   0 means success.
+
+
+
+******************************************************************************/
+int16_t cc3100_netapp::sl_NetAppMDNSRegisterUnregisterService(const char* pServiceName, 
+                                                              const uint8_t ServiceNameLen, 
+                                                              const char* pText, 
+                                                              const uint8_t TextLen, 
+                                                              const uint16_t Port, 
+                                                              const uint32_t TTL, 
+                                                              const uint32_t Options)
+{
+
+    _SlNetappMdnsRegisterServiceMsg_u Msg;
+    _SlCmdExt_t	CmdExt ;
+    unsigned char ServiceNameAndTextBuffer[NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH];
+    unsigned char *TextPtr;
+
+    /*
+
+    NOTE - pay attention
+
+    	1. Temporary -  there is an allocation on stack of internal buffer.
+    	Its size is NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH.
+    	It means that the sum of the text length and service name length cannot be bigger than
+    	NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH.
+    	If it is - An error is returned.
+
+    	2. According to now from certain constraints the variables parameters are set in the
+    	attribute part (contain constant parameters)
+
+
+    */
+
+    /*build the attribute part of the command.
+      It contains the constant parameters of the command*/
+
+    Msg.Cmd.ServiceNameLen	= ServiceNameLen;
+    Msg.Cmd.Options			= Options;
+    Msg.Cmd.Port			= Port;
+    Msg.Cmd.TextLen			= TextLen;
+    Msg.Cmd.TTL				= TTL;
+
+    /*Build the payload part of the command
+     Copy the service name and text to one buffer.
+     NOTE - pay attention
+     			The size of the service length + the text length should be smaller than 255,
+     			Until the simplelink drive supports to variable length through SPI command. */
+    if(TextLen + ServiceNameLen > (NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH - 1 )) { /*-1 is for giving a place to set null termination at the end of the text*/
+        return -1;
+    }
+
+    _driver._SlDrvMemZero(ServiceNameAndTextBuffer, NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH);
+
+
+    /*Copy the service name*/
+    memcpy(ServiceNameAndTextBuffer,
+              pServiceName,
+              ServiceNameLen);
+
+    if(TextLen > 0 ) {
+
+        TextPtr = &ServiceNameAndTextBuffer[ServiceNameLen];
+        /*Copy the text just after the service name*/
+        memcpy(TextPtr, pText, TextLen);
+    }
+
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.TxPayloadLen = (TextLen + ServiceNameLen);
+    CmdExt.pTxPayload   = (uint8_t *)ServiceNameAndTextBuffer;
+
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlRegisterServiceCtrl, &Msg, &CmdExt));
+
+    return (int16_t)Msg.Rsp.status;
+
+
+}
+#endif
+
+/**********************************************************************************************/
+#if _SL_INCLUDE_FUNC(sl_NetAppMDNSRegisterService)
+int16_t cc3100_netapp::sl_NetAppMDNSRegisterService(const char* pServiceName, 
+                                                    const uint8_t ServiceNameLen, 
+                                                    const char* pText, 
+                                                    const uint8_t TextLen, 
+                                                    const uint16_t Port, 
+                                                    const uint32_t TTL, 
+                                                    uint32_t Options)
+{
+
+    /*
+
+    NOTE - pay attention
+
+    1. Temporary -  there is an allocation on stack of internal buffer.
+    Its size is NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH.
+    It means that the sum of the text length and service name length cannot be bigger than
+    NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH.
+    If it is - An error is returned.
+
+    2. According to now from certain constraints the variables parameters are set in the
+    attribute part (contain constant parameters)
+
+    */
+
+    /*Set the add service bit in the options parameter.
+      In order not use different opcodes for the register service and unregister service
+      bit 31 in option is taken for this purpose. if it is set it means in NWP that the service should be added
+      if it is cleared it means that the service should be deleted and there is only meaning to pServiceName
+      and ServiceNameLen values. */
+    Options |=  NETAPP_MDNS_OPTIONS_ADD_SERVICE_BIT;
+
+    return  (sl_NetAppMDNSRegisterUnregisterService(	pServiceName, ServiceNameLen, pText, TextLen, Port, TTL, Options));
+
+
+}
+#endif
+/**********************************************************************************************/
+
+
+
+/**********************************************************************************************/
+#if _SL_INCLUDE_FUNC(sl_NetAppMDNSUnRegisterService)
+int16_t cc3100_netapp::sl_NetAppMDNSUnRegisterService(const char* pServiceName, const uint8_t ServiceNameLen)
+{
+    uint32_t    Options = 0;
+
+    /*
+
+    NOTE - pay attention
+
+    		The size of the service length  should be smaller than 255,
+    		Until the simplelink drive supports to variable length through SPI command.
+
+
+    */
+
+    /*Clear the add service bit in the options parameter.
+      In order not use different opcodes for the register service and unregister service
+      bit 31 in option is taken for this purpose. if it is set it means in NWP that the service should be added
+      if it is cleared it means that the service should be deleted and there is only meaning to pServiceName
+      and ServiceNameLen values.*/
+
+    Options &=  (~NETAPP_MDNS_OPTIONS_ADD_SERVICE_BIT);
+
+    return  (sl_NetAppMDNSRegisterUnregisterService(pServiceName, ServiceNameLen, NULL, 0, 0, 0, Options));
+
+
+}
+#endif
+/**********************************************************************************************/
+
+
+
+/*****************************************************************************/
+/* sl_DnsGetHostByService */
+/*****************************************************************************/
+/*
+ * The below struct depicts the constant parameters of the command/API sl_DnsGetHostByService.
+ *
+   1. ServiceLen                      - The length of the service should be smaller than 255.
+   2. AddrLen                         - TIPv4 or IPv6 (SL_AF_INET , SL_AF_INET6).
+*
+ */
+
+typedef struct {
+    uint8_t   ServiceLen;
+    uint8_t   AddrLen;
+    uint16_t  Padding;
+} _GetHostByServiceCommand_t;
+
+
+
+/*
+ * The below structure depict the constant parameters that are returned in the Async event answer
+ * according to command/API sl_DnsGetHostByService for IPv4 and IPv6.
+ *
+	1Status						- The status of the response.
+	2.Address						- Contains the IP address of the service.
+	3.Port							- Contains the port of the service.
+	4.TextLen						- Contains the max length of the text that the user wants to get.
+												it means that if the test of service is bigger that its value than
+												the text is cut to inout_TextLen value.
+										Output: Contain the length of the text that is returned. Can be full text or part
+												of the text (see above).
+
+*
+ 
+typedef struct {
+    uint16_t   Status;
+    uint16_t   TextLen;
+    uint32_t    Port;
+    uint32_t    Address;
+} _GetHostByServiceIPv4AsyncResponse_t;
+*/
+
+typedef struct {
+    uint16_t   Status;
+    uint16_t   TextLen;
+    uint32_t    Port;
+    uint32_t    Address[4];
+} _GetHostByServiceIPv6AsyncResponse_t;
+
+
+typedef union {
+    _GetHostByServiceIPv4AsyncResponse_t IpV4;
+    _GetHostByServiceIPv6AsyncResponse_t IpV6;
+} _GetHostByServiceAsyncResponseAttribute_u;
+
+typedef union {
+    _GetHostByServiceCommand_t      Cmd;
+    _BasicResponse_t                Rsp;
+} _SlGetHostByServiceMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_NetAppDnsGetHostByService)
+const _SlCmdCtrl_t _SlGetHostByServiceCtrl = {
+    SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICE,
+    sizeof(_GetHostByServiceCommand_t),
+    sizeof(_BasicResponse_t)
+};
+
+int32_t cc3100_netapp::sl_NetAppDnsGetHostByService(unsigned char *pServiceName,	/* string containing all (or only part): name + subtype + service */
+        const uint8_t ServiceLen,
+        const uint8_t Family,			/* 4-IPv4 , 16-IPv6 */
+        uint32_t pAddr[],
+        uint32_t *pPort,
+        uint16_t *pTextLen, /* in: max len , out: actual len */
+        unsigned char *pText)
+{
+
+    _SlGetHostByServiceMsg_u         Msg;
+    _SlCmdExt_t                      CmdExt ;
+    _GetHostByServiceAsyncResponse_t AsyncRsp;
+    uint8_t ObjIdx = MAX_CONCURRENT_ACTIONS;
+
+    /*
+    	Note:
+    	1. The return's attributes are belonged to first service that is found.
+    	It can be other services with the same service name will response to
+    	the query. The results of these responses are saved in the peer cache of the NWP, and
+    	should be read by another API.
+
+    	2. Text length can be 120 bytes only - not more
+    	It is because of constraints in the NWP on the buffer that is allocated for the Async event.
+
+    	3.The API waits to Async event by blocking. It means that the API is finished only after an Async event
+    	is sent by the NWP.
+
+    	4.No rolling option!!! - only PTR type is sent.
+
+
+    */
+    /*build the attribute part of the command.
+      It contains the constant parameters of the command */
+
+    Msg.Cmd.ServiceLen = ServiceLen;
+    Msg.Cmd.AddrLen    = Family;
+
+    /*Build the payload part of the command
+      Copy the service name and text to one buffer.*/
+    _driver._SlDrvResetCmdExt(&CmdExt);  
+    CmdExt.TxPayloadLen = ServiceLen;
+    
+    CmdExt.pTxPayload   = (uint8_t *)pServiceName;
+    
+
+    /*set pointers to the output parameters (the returned parameters).
+      This pointers are belonged to local struct that is set to global Async response parameter.
+      It is done in order not to run more than one sl_DnsGetHostByService at the same time.
+      The API should be run only if global parameter is pointed to NULL. */
+    AsyncRsp.out_pText     = pText;
+    AsyncRsp.inout_TextLen = (uint16_t* )pTextLen;
+    AsyncRsp.out_pPort     = pPort;
+    AsyncRsp.out_pAddr     = (uint32_t *)pAddr;
+
+
+    ObjIdx = _driver._SlDrvProtectAsyncRespSetting((uint8_t*)&AsyncRsp, GETHOSYBYSERVICE_ID, SL_MAX_SOCKETS);
+
+    if (MAX_CONCURRENT_ACTIONS == ObjIdx)
+    {
+        return SL_POOL_IS_EMPTY;
+    }
+
+    if (SL_AF_INET6 == Family) {
+        g_pCB->ObjPool[ObjIdx].AdditionalData |= SL_NETAPP_FAMILY_MASK;
+    }
+    /* Send the command */
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlGetHostByServiceCtrl, &Msg, &CmdExt));
+
+
+
+    /* If the immediate reponse is O.K. than  wait for aSYNC event response. */
+    if(SL_RET_CODE_OK == Msg.Rsp.status) {
+        _driver._SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj);
+
+        /* If we are - it means that Async event was sent.
+           The results are copied in the Async handle return functions */
+
+        Msg.Rsp.status = AsyncRsp.Status;
+    }
+
+    _driver._SlDrvReleasePoolObj(ObjIdx);
+    return Msg.Rsp.status;
+}
+#endif
+
+/*****************************************************************************/
+/*  _sl_HandleAsync_DnsGetHostByAddr */
+/*****************************************************************************/
+#ifndef SL_TINY_EXT
+void cc3100_netapp::_sl_HandleAsync_DnsGetHostByAddr(void *pVoidBuf)
+{
+    SL_TRACE0(DBG_MSG, MSG_303, "STUB: _sl_HandleAsync_DnsGetHostByAddr not implemented yet!");
+    return;
+}
+#endif
+/*****************************************************************************/
+/* sl_DnsGetHostByName */
+/*****************************************************************************/
+typedef union {
+    _GetHostByNameIPv4AsyncResponse_t IpV4;
+    _GetHostByNameIPv6AsyncResponse_t IpV6;
+} _GetHostByNameAsyncResponse_u;
+
+typedef union {
+    _GetHostByNameCommand_t         Cmd;
+    _BasicResponse_t                Rsp;
+} _SlGetHostByNameMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_NetAppDnsGetHostByName)
+const _SlCmdCtrl_t _SlGetHostByNameCtrl = {
+    SL_OPCODE_NETAPP_DNSGETHOSTBYNAME,
+    sizeof(_GetHostByNameCommand_t),
+    sizeof(_BasicResponse_t)
+};
+
+int16_t cc3100_netapp::sl_NetAppDnsGetHostByName(unsigned char * hostname, const uint16_t usNameLen, uint32_t*  out_ip_addr, const uint8_t family)
+{
+    _SlGetHostByNameMsg_u           Msg;
+    _SlCmdExt_t                     ExtCtrl;
+    _GetHostByNameAsyncResponse_u   AsyncRsp;
+    uint8_t ObjIdx = MAX_CONCURRENT_ACTIONS;
+    
+    _driver._SlDrvResetCmdExt(&ExtCtrl);
+    ExtCtrl.TxPayloadLen = usNameLen;
+    
+    ExtCtrl.pTxPayload = (unsigned char *)hostname;
+    
+
+    Msg.Cmd.Len = usNameLen;
+    Msg.Cmd.family = family;
+
+    /*Use Obj to issue the command, if not available try later */
+    ObjIdx = (uint8_t)_driver._SlDrvWaitForPoolObj(GETHOSYBYNAME_ID,SL_MAX_SOCKETS);
+    if (MAX_CONCURRENT_ACTIONS == ObjIdx) {
+        Uart_Write((uint8_t*)"SL_POOL_IS_EMPTY \r\n");
+        return SL_POOL_IS_EMPTY;
+    }
+    
+    _driver._SlDrvProtectionObjLockWaitForever();
+    
+    g_pCB->ObjPool[ObjIdx].pRespArgs =  (uint8_t *)&AsyncRsp;
+    /*set bit to indicate IPv6 address is expected */
+    if (SL_AF_INET6 == family) {
+        g_pCB->ObjPool[ObjIdx].AdditionalData |= SL_NETAPP_FAMILY_MASK;
+    }
+
+     _driver._SlDrvProtectionObjUnLock();
+    
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlGetHostByNameCtrl, &Msg, &ExtCtrl));
+
+    if(SL_RET_CODE_OK == Msg.Rsp.status) {
+        _driver._SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj);
+        Msg.Rsp.status = AsyncRsp.IpV4.status;
+
+        if(SL_OS_RET_CODE_OK == (int16_t)Msg.Rsp.status) {
+            memcpy((int8_t *)out_ip_addr, (signed char *)&AsyncRsp.IpV4.ip0, (SL_AF_INET == family) ? SL_IPV4_ADDRESS_SIZE : SL_IPV6_ADDRESS_SIZE);
+        }
+    }
+    _driver._SlDrvReleasePoolObj(ObjIdx);
+    return Msg.Rsp.status;
+}
+#endif
+
+#ifndef SL_TINY_EXT
+void cc3100_netapp::CopyPingResultsToReport(_PingReportResponse_t *pResults,SlPingReport_t *pReport)
+{
+    pReport->PacketsSent     = pResults->numSendsPings;
+    pReport->PacketsReceived = pResults->numSuccsessPings;
+    pReport->MinRoundTime    = pResults->rttMin;
+    pReport->MaxRoundTime    = pResults->rttMax;
+    pReport->AvgRoundTime    = pResults->rttAvg;
+    pReport->TestTime        = pResults->testTime;
+}
+#endif
+/*****************************************************************************/
+/* sl_PingStart */
+/*****************************************************************************/
+typedef union {
+    _PingStartCommand_t   Cmd;
+    _PingReportResponse_t  Rsp;
+} _SlPingStartMsg_u;
+
+
+typedef enum {
+    CMD_PING_TEST_RUNNING = 0,
+    CMD_PING_TEST_STOPPED
+} _SlPingStatus_e;
+
+P_SL_DEV_PING_CALLBACK  pPingCallBackFunc;
+
+#if _SL_INCLUDE_FUNC(sl_NetAppPingStart)
+int16_t cc3100_netapp::sl_NetAppPingStart(const SlPingStartCommand_t* pPingParams, const uint8_t family, SlPingReport_t *pReport, const P_SL_DEV_PING_CALLBACK pPingCallback)
+{
+
+    _SlCmdCtrl_t                CmdCtrl = {0, sizeof(_PingStartCommand_t), sizeof(_BasicResponse_t)};
+    _SlPingStartMsg_u           Msg;
+    _PingReportResponse_t       PingRsp;
+    uint8_t ObjIdx = MAX_CONCURRENT_ACTIONS;
+
+    if( 0 == pPingParams->Ip ) 
+    { /* stop any ongoing ping */
+        return _driver._SlDrvBasicCmd(SL_OPCODE_NETAPP_PINGSTOP);
+    }
+
+    if(SL_AF_INET == family) {
+        CmdCtrl.Opcode = SL_OPCODE_NETAPP_PINGSTART;
+        memcpy(&Msg.Cmd.ip0, &pPingParams->Ip, SL_IPV4_ADDRESS_SIZE);
+    } else {
+        CmdCtrl.Opcode = SL_OPCODE_NETAPP_PINGSTART_V6;
+        memcpy(&Msg.Cmd.ip0, &pPingParams->Ip, SL_IPV6_ADDRESS_SIZE);
+    }
+
+    Msg.Cmd.pingIntervalTime        = pPingParams->PingIntervalTime;
+    Msg.Cmd.PingSize                = pPingParams->PingSize;
+    Msg.Cmd.pingRequestTimeout      = pPingParams->PingRequestTimeout;
+    Msg.Cmd.totalNumberOfAttempts   = pPingParams->TotalNumberOfAttempts;
+    Msg.Cmd.flags                   = pPingParams->Flags;
+
+    if( pPingCallback ) {
+        pPingCallBackFunc = pPingCallback;
+    } else {
+        /*Use Obj to issue the command, if not available try later */
+        ObjIdx = (uint8_t)_driver._SlDrvWaitForPoolObj(PING_ID,SL_MAX_SOCKETS);
+        if (MAX_CONCURRENT_ACTIONS == ObjIdx) {
+            return SL_POOL_IS_EMPTY;
+        }
+        OSI_RET_OK_CHECK(_nonos.sl_LockObjLock(&g_pCB->ProtectionLockObj, NON_OS_LOCK_OBJ_UNLOCK_VALUE, NON_OS_LOCK_OBJ_LOCK_VALUE, SL_OS_WAIT_FOREVER));
+        /* async response handler for non callback mode */
+        g_pCB->ObjPool[ObjIdx].pRespArgs = (uint8_t *)&PingRsp;
+        pPingCallBackFunc = NULL;
+        OSI_RET_OK_CHECK(_nonos.sl_LockObjUnlock(&g_pCB->ProtectionLockObj, NON_OS_LOCK_OBJ_UNLOCK_VALUE));
+    }
+
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp(&CmdCtrl, &Msg, NULL));
+    /*send the command*/
+    if(CMD_PING_TEST_RUNNING == (int16_t)Msg.Rsp.status || CMD_PING_TEST_STOPPED == (int16_t)Msg.Rsp.status ) {
+        /* block waiting for results if no callback function is used */
+        if( NULL == pPingCallback ) {
+            _driver._SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj);
+            if( SL_OS_RET_CODE_OK == (int16_t)PingRsp.status ) {
+                CopyPingResultsToReport(&PingRsp,pReport);
+            }
+            _driver._SlDrvReleasePoolObj(ObjIdx);
+        }
+    } else {
+        /* ping failure, no async response */
+        if( NULL == pPingCallback ) {
+            _driver._SlDrvReleasePoolObj(ObjIdx);
+        }
+    }
+
+    return Msg.Rsp.status;
+}
+#endif
+
+/*****************************************************************************/
+/* sl_NetAppSet */
+/*****************************************************************************/
+typedef union {
+    _NetAppSetGet_t    Cmd;
+    _BasicResponse_t   Rsp;
+} _SlNetAppMsgSet_u;
+
+#if _SL_INCLUDE_FUNC(sl_NetAppSet)
+const _SlCmdCtrl_t _SlNetAppSetCmdCtrl = {
+    SL_OPCODE_NETAPP_NETAPPSET,
+    sizeof(_NetAppSetGet_t),
+    sizeof(_BasicResponse_t)
+};
+
+int32_t cc3100_netapp::sl_NetAppSet(const uint8_t AppId ,const uint8_t Option, const uint8_t OptionLen, const uint8_t *pOptionValue)
+{
+
+    _SlNetAppMsgSet_u         Msg;
+    _SlCmdExt_t               CmdExt;
+    
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.TxPayloadLen = (OptionLen+3) & (~3);
+    
+    CmdExt.pTxPayload = (uint8_t *)pOptionValue;
+    
+    Msg.Cmd.AppId    = AppId;
+    Msg.Cmd.ConfigLen   = OptionLen;
+    Msg.Cmd.ConfigOpt   = Option;
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlNetAppSetCmdCtrl, &Msg, &CmdExt));
+
+    return (int16_t)Msg.Rsp.status;
+}
+#endif
+
+/*****************************************************************************/
+/* sl_NetAppSendTokenValue */
+/*****************************************************************************/
+typedef union {
+    sl_NetAppHttpServerSendToken_t    Cmd;
+    _BasicResponse_t   Rsp;
+} _SlNetAppMsgSendTokenValue_u;
+
+#if defined(sl_HttpServerCallback) || defined(EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS)
+const _SlCmdCtrl_t _SlNetAppSendTokenValueCmdCtrl = {
+    SL_OPCODE_NETAPP_HTTPSENDTOKENVALUE,
+    sizeof(sl_NetAppHttpServerSendToken_t),
+    sizeof(_BasicResponse_t)
+};
+
+uint16_t cc3100_netapp::sl_NetAppSendTokenValue(slHttpServerData_t * Token_value)
+{
+
+    _SlNetAppMsgSendTokenValue_u    Msg;
+    _SlCmdExt_t						CmdExt;
+
+    CmdExt.TxPayloadLen = (Token_value->value_len+3) & (~3);
+    CmdExt.RxPayloadLen = 0;
+    CmdExt.pTxPayload = (uint8_t *) Token_value->token_value;
+    CmdExt.pRxPayload = NULL;
+
+    Msg.Cmd.token_value_len = Token_value->value_len;
+    Msg.Cmd.token_name_len = Token_value->name_len;
+    memcpy(&Msg.Cmd.token_name[0], Token_value->token_name, Token_value->name_len);
+
+
+    VERIFY_RET_OK(_driver._SlDrvCmdSend((_SlCmdCtrl_t *)&_SlNetAppSendTokenValueCmdCtrl, &Msg, &CmdExt));
+
+    return Msg.Rsp.status;
+}
+#endif
+
+/*****************************************************************************/
+/* sl_NetAppGet */
+/*****************************************************************************/
+typedef union {
+    _NetAppSetGet_t	    Cmd;
+    _NetAppSetGet_t	    Rsp;
+} _SlNetAppMsgGet_u;
+
+#if _SL_INCLUDE_FUNC(sl_NetAppGet)
+const _SlCmdCtrl_t _SlNetAppGetCmdCtrl = {
+    SL_OPCODE_NETAPP_NETAPPGET,
+    sizeof(_NetAppSetGet_t),
+    sizeof(_NetAppSetGet_t)
+};
+
+int32_t cc3100_netapp::sl_NetAppGet(const uint8_t AppId, const uint8_t Option, uint8_t *pOptionLen, uint8_t *pOptionValue)
+{
+    _SlNetAppMsgGet_u         Msg;
+    _SlCmdExt_t               CmdExt;
+
+    if (*pOptionLen == 0) {
+        return SL_EZEROLEN;
+    }
+    
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.RxPayloadLen = *pOptionLen;
+    
+    CmdExt.pRxPayload = (uint8_t *)pOptionValue;
+
+    Msg.Cmd.AppId    = AppId;
+    Msg.Cmd.ConfigOpt   = Option;
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlNetAppGetCmdCtrl, &Msg, &CmdExt));
+
+
+    if (CmdExt.RxPayloadLen < CmdExt.ActualRxPayloadLen) {
+        *pOptionLen = (uint8_t)CmdExt.RxPayloadLen;
+        return SL_ESMALLBUF;
+    } else {
+        *pOptionLen = (uint8_t)CmdExt.ActualRxPayloadLen;
+    }
+
+    return (int16_t)Msg.Rsp.Status;
+}
+#endif
+
+cc3100_flowcont::cc3100_flowcont(cc3100_driver &driver, cc3100_nonos &nonos)
+    : _driver(driver), _nonos(nonos)
+{
+
+}
+
+cc3100_flowcont::~cc3100_flowcont()
+{
+
+}
+#if 0
+/*****************************************************************************/
+/* _SlDrvFlowContInit */
+/*****************************************************************************/
+void cc3100_flowcont::_SlDrvFlowContInit(void)
+{
+    g_pCB->FlowContCB.TxPoolCnt = FLOW_CONT_MIN;
+
+    OSI_RET_OK_CHECK(_nonos.sl_LockObjCreate(&g_pCB->FlowContCB.TxLockObj, "TxLockObj"));
+
+    OSI_RET_OK_CHECK(_nonos.sl_SyncObjCreate(&g_pCB->FlowContCB.TxSyncObj, "TxSyncObj"));
+}
+
+/*****************************************************************************/
+/* _SlDrvFlowContDeinit */
+/*****************************************************************************/
+void cc3100_flowcont::_SlDrvFlowContDeinit(void)
+{
+    g_pCB->FlowContCB.TxPoolCnt = 0;
+
+    OSI_RET_OK_CHECK(_nonos.sl_LockObjDelete(&g_pCB->FlowContCB.TxLockObj, 0));
+
+    OSI_RET_OK_CHECK(_nonos.sl_SyncObjDelete(&g_pCB->FlowContCB.TxSyncObj, 0));
+}
+#endif
+}//namespace mbed_cc3100
+
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_netapp.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_netapp.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,1126 @@
+/*
+ * netapp.h - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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 files                                                             */
+/*****************************************************************************/
+
+#include "cc3100_simplelink.h"
+
+#ifndef NETAPP_H_
+#define    NETAPP_H_
+
+#include "cc3100_protocol.h"
+#include "cc3100_nonos.h"
+
+namespace mbed_cc3100 {
+
+/*!
+
+    \addtogroup netapp
+    @{
+
+*/
+
+/*****************************************************************************/
+/* Macro declarations                                                        */
+/*****************************************************************************/
+
+/*ERROR code*/
+const int16_t SL_ERROR_NETAPP_RX_BUFFER_LENGTH_ERROR      = (-230);
+
+/*  Http Server interface */
+const uint8_t MAX_INPUT_STRING                            =  (64); /*  because of WPA */
+
+const uint8_t MAX_AUTH_NAME_LEN                           =  (20);
+const uint8_t MAX_AUTH_PASSWORD_LEN                       =  (20);
+const uint8_t MAX_AUTH_REALM_LEN                          =  (20);
+
+const uint8_t MAX_DEVICE_URN_LEN                          =  (15+1);
+const uint8_t MAX_DOMAIN_NAME_LEN                         =  (24+1);
+
+const uint8_t MAX_ACTION_LEN                              =  (30);
+/* Important: in case the max len is changed, make sure the struct sl_NetAppHttpServerSendToken_t in protocol.h is padded correctly! */
+const uint8_t MAX_TOKEN_NAME_LEN                          =  (20);
+const uint8_t MAX_TOKEN_VALUE_LEN                         =  MAX_INPUT_STRING;
+
+const int16_t NETAPP_MAX_SERVICE_TEXT_SIZE                =  (256);
+const uint8_t NETAPP_MAX_SERVICE_NAME_SIZE                =  (60);
+const uint8_t NETAPP_MAX_SERVICE_HOST_NAME_SIZE           =  (64);
+
+
+/* Server Responses */
+const uint8_t SL_NETAPP_RESPONSE_NONE                     =  (0);
+const uint8_t SL_NETAPP_HTTPSETTOKENVALUE                 =  (1);
+
+const uint8_t SL_NETAPP_FAMILY_MASK                       =  (0x80);
+
+/* mDNS types */
+const uint32_t SL_NET_APP_MASK_IPP_TYPE_OF_SERVICE        =   (0x00000001);
+const uint32_t SL_NET_APP_MASK_DEVICE_INFO_TYPE_OF_SERVICE =  (0x00000002);
+const uint32_t SL_NET_APP_MASK_HTTP_TYPE_OF_SERVICE       =   (0x00000004);
+const uint32_t SL_NET_APP_MASK_HTTPS_TYPE_OF_SERVICE      =   (0x00000008);
+const uint32_t SL_NET_APP_MASK_WORKSATION_TYPE_OF_SERVICE =   (0x00000010);
+const uint32_t SL_NET_APP_MASK_GUID_TYPE_OF_SERVICE       =   (0x00000020);
+const uint32_t SL_NET_APP_MASK_H323_TYPE_OF_SERVICE       =   (0x00000040);
+const uint32_t SL_NET_APP_MASK_NTP_TYPE_OF_SERVICE        =   (0x00000080);
+const uint32_t SL_NET_APP_MASK_OBJECITVE_TYPE_OF_SERVICE  =   (0x00000100);
+const uint32_t SL_NET_APP_MASK_RDP_TYPE_OF_SERVICE        =   (0x00000200);
+const uint32_t SL_NET_APP_MASK_REMOTE_TYPE_OF_SERVICE     =   (0x00000400);
+const uint32_t SL_NET_APP_MASK_RTSP_TYPE_OF_SERVICE       =   (0x00000800);
+const uint32_t SL_NET_APP_MASK_SIP_TYPE_OF_SERVICE        =   (0x00001000);
+const uint32_t SL_NET_APP_MASK_SMB_TYPE_OF_SERVICE        =   (0x00002000);
+const uint32_t SL_NET_APP_MASK_SOAP_TYPE_OF_SERVICE       =   (0x00004000);
+const uint32_t SL_NET_APP_MASK_SSH_TYPE_OF_SERVICE        =   (0x00008000);
+const uint32_t SL_NET_APP_MASK_TELNET_TYPE_OF_SERVICE     =   (0x00010000);
+const uint32_t SL_NET_APP_MASK_TFTP_TYPE_OF_SERVICE       =   (0x00020000);
+const uint32_t SL_NET_APP_MASK_XMPP_CLIENT_TYPE_OF_SERVICE =  (0x00040000);
+const uint32_t SL_NET_APP_MASK_RAOP_TYPE_OF_SERVICE       =   (0x00080000);
+const uint32_t SL_NET_APP_MASK_ALL_TYPE_OF_SERVICE        =   (0xFFFFFFFF);
+
+/********************************************************************************************************/
+/* sl_NetAppDnsGetHostByName error codes     */
+
+const int16_t SL_NET_APP_DNS_QUERY_NO_RESPONSE            =  (-159);  /* DNS query failed, no response                        */
+const int16_t SL_NET_APP_DNS_NO_SERVER                    =  (-161);  /* No DNS server was specified                          */
+const int16_t SL_NET_APP_DNS_PARAM_ERROR                  =  (-162);  /* mDNS parameters error                                */
+const int16_t SL_NET_APP_DNS_QUERY_FAILED                 =  (-163);  /* DNS query failed; no DNS server sent an 'answer'     */
+const int16_t SL_NET_APP_DNS_INTERNAL_1                   =  (-164);
+const int16_t SL_NET_APP_DNS_INTERNAL_2                   =  (-165);
+const int16_t SL_NET_APP_DNS_MALFORMED_PACKET             =  (-166);  /* Improperly formed or corrupted DNS packet received   */
+const int16_t SL_NET_APP_DNS_INTERNAL_3                   =  (-167);
+const int16_t SL_NET_APP_DNS_INTERNAL_4                   =  (-168);
+const int16_t SL_NET_APP_DNS_INTERNAL_5                   =  (-169);
+const int16_t SL_NET_APP_DNS_INTERNAL_6                   =  (-170);
+const int16_t SL_NET_APP_DNS_INTERNAL_7                   =  (-171);
+const int16_t SL_NET_APP_DNS_INTERNAL_8                   =  (-172);
+const int16_t SL_NET_APP_DNS_INTERNAL_9                   =  (-173);
+const int16_t SL_NET_APP_DNS_MISMATCHED_RESPONSE          =  (-174);  /* Server response type does not match the query request*/
+const int16_t SL_NET_APP_DNS_INTERNAL_10                  =  (-175);
+const int16_t SL_NET_APP_DNS_INTERNAL_11                  =  (-176);
+const int16_t SL_NET_APP_DNS_NO_ANSWER                    =  (-177);  /* No response for one-shot query */
+const int16_t SL_NET_APP_DNS_NO_KNOWN_ANSWER              =  (-178);  /* No known answer for query */
+const int16_t SL_NET_APP_DNS_NAME_MISMATCH                =  (-179);  /* Illegal service name according to the RFC            */
+const int16_t SL_NET_APP_DNS_NOT_STARTED                  =  (-180);  /* mDNS is not running                                  */
+const int16_t SL_NET_APP_DNS_HOST_NAME_ERROR              =  (-181);  /* Host name error. Host name format is not allowed according to RFC 1033,1034,1035, 6763 */
+const int16_t SL_NET_APP_DNS_NO_MORE_ENTRIES              =  (-182);  /* No more entries be found.                            */
+
+const int16_t SL_NET_APP_DNS_MAX_SERVICES_ERROR           =  (-200);  /* Maximum advertise services are already configured    */
+const int16_t SL_NET_APP_DNS_IDENTICAL_SERVICES_ERROR     =  (-201);  /* Trying to register a service that is already exists  */
+const int16_t SL_NET_APP_DNS_NOT_EXISTED_SERVICE_ERROR    =  (-203);  /* Trying to delete service that does not existed       */
+const int16_t SL_NET_APP_DNS_ERROR_SERVICE_NAME_ERROR     =  (-204);  /* Illegal service name according to the RFC            */
+const int16_t SL_NET_APP_DNS_RX_PACKET_ALLOCATION_ERROR   =  (-205);  /* Retry request                                        */
+const int16_t SL_NET_APP_DNS_BUFFER_SIZE_ERROR            =  (-206);  /* List size buffer is bigger than internally allowed in the NWP */
+const int16_t SL_NET_APP_DNS_NET_APP_SET_ERROR            =  (-207);  /* Illegal length of one of the mDNS Set functions      */
+const int16_t SL_NET_APP_DNS_GET_SERVICE_LIST_FLAG_ERROR  =  (-208);
+const int16_t SL_NET_APP_DNS_NO_CONFIGURATION_ERROR       =  (-209);
+
+/* Set Dev name error codes  (NETAPP_SET_GET_DEV_CONF_OPT_DEVICE_URN) */
+const int16_t SL_ERROR_DEVICE_NAME_LEN_ERR                =   (-117);
+const int16_t SL_ERROR_DEVICE_NAME_INVALID                =   (-118);
+/* Set domain name error codes (NETAPP_SET_GET_DEV_CONF_OPT_DOMAIN_NAME) */
+const int16_t SL_ERROR_DOMAIN_NAME_LEN_ERR                =   (-119);
+const int16_t SL_ERROR_DOMAIN_NAME_INVALID                =   (-120);
+
+/********************************************************************************************************/
+
+/* NetApp application IDs */
+const uint8_t SL_NET_APP_HTTP_SERVER_ID                   =  (1);
+const uint8_t SL_NET_APP_DHCP_SERVER_ID                   =  (2);
+const uint8_t SL_NET_APP_MDNS_ID                          =  (4);
+const uint8_t SL_NET_APP_DNS_SERVER_ID                    =  (8);
+const uint8_t SL_NET_APP_DEVICE_CONFIG_ID                 =  (16);
+/* NetApp application set/get options */
+const uint8_t NETAPP_SET_DHCP_SRV_BASIC_OPT               =  (0);
+/* HTTP server set/get options */
+const uint8_t NETAPP_SET_GET_HTTP_OPT_PORT_NUMBER         =  (0);
+const uint8_t NETAPP_SET_GET_HTTP_OPT_AUTH_CHECK          =  (1);
+const uint8_t NETAPP_SET_GET_HTTP_OPT_AUTH_NAME           =  (2);
+const uint8_t NETAPP_SET_GET_HTTP_OPT_AUTH_PASSWORD       =  (3);
+const uint8_t NETAPP_SET_GET_HTTP_OPT_AUTH_REALM          =  (4);
+const uint8_t NETAPP_SET_GET_HTTP_OPT_ROM_PAGES_ACCESS    =  (5);
+
+const uint8_t NETAPP_SET_GET_MDNS_CONT_QUERY_OPT          =  (1);
+const uint8_t NETAPP_SET_GET_MDNS_QEVETN_MASK_OPT         =  (2);
+const uint8_t NETAPP_SET_GET_MDNS_TIMING_PARAMS_OPT       =  (3);
+
+/* DNS server set/get options */
+const uint8_t NETAPP_SET_GET_DNS_OPT_DOMAIN_NAME          =  (0);
+
+/* Device Config set/get options */
+const uint8_t NETAPP_SET_GET_DEV_CONF_OPT_DEVICE_URN      =  (0);
+const uint8_t NETAPP_SET_GET_DEV_CONF_OPT_DOMAIN_NAME     =  (1);
+
+
+/*****************************************************************************/
+/* Structure/Enum declarations                                               */
+/*****************************************************************************/
+/*
+ * The below structure depict the constant parameters that are returned in the Async event answer
+ * according to command/API sl_DnsGetHostByService for IPv4 and IPv6.
+ *
+    1Status                     - The status of the response.
+    2.Address                       - Contains the IP address of the service.
+    3.Port                          - Contains the port of the service.
+    4.TextLen                       - Contains the max length of the text that the user wants to get.
+                                                it means that if the test of service is bigger that its value than
+                                                the text is cut to inout_TextLen value.
+                                        Output: Contain the length of the text that is returned. Can be full text or part
+                                                of the text (see above).
+
+*
+ */
+typedef struct {
+    uint16_t   Status;
+    uint16_t   TextLen;
+    uint32_t    Port;
+    uint32_t    Address;
+} _GetHostByServiceIPv4AsyncResponse_t;
+
+/*
+ * The below struct contains pointers to the output parameters that the user gives
+ *
+ */
+typedef struct {
+    int16_t       Status;
+    uint32_t      *out_pAddr;
+    uint32_t      *out_pPort;
+    uint16_t      *inout_TextLen; // in: max len , out: actual len
+    unsigned char *out_pText;
+} _GetHostByServiceAsyncResponse_t;
+
+typedef struct {
+    uint32_t    PacketsSent;
+    uint32_t    PacketsReceived;
+    uint16_t    MinRoundTime;
+    uint16_t    MaxRoundTime;
+    uint16_t    AvgRoundTime;
+    uint32_t    TestTime;
+} SlPingReport_t;
+
+typedef struct {
+    uint32_t    PingIntervalTime;       /* delay between pings, in milliseconds */
+    uint16_t    PingSize;               /* ping packet size in bytes           */
+    uint16_t    PingRequestTimeout;     /* timeout time for every ping in milliseconds  */
+    uint32_t    TotalNumberOfAttempts;  /* max number of ping requests. 0 - forever    */
+    uint32_t    Flags;                  /* flag - 0 report only when finished, 1 - return response for every ping, 2 - stop after 1 successful ping.  */
+    uint32_t    Ip;                     /* IPv4 address or IPv6 first 4 bytes  */
+    uint32_t    Ip1OrPaadding;
+    uint32_t    Ip2OrPaadding;
+    uint32_t    Ip3OrPaadding;
+} SlPingStartCommand_t;
+
+typedef struct _slHttpServerString_t {
+    uint8_t     len;
+    uint8_t     *data;
+} slHttpServerString_t;
+
+typedef struct _slHttpServerData_t {
+    uint8_t     value_len;
+    uint8_t     name_len;
+    uint8_t     *token_value;
+    uint8_t     *token_name;
+} slHttpServerData_t;
+
+typedef struct _slHttpServerPostData_t {
+    slHttpServerString_t action;
+    slHttpServerString_t token_name;
+    slHttpServerString_t token_value;
+} slHttpServerPostData_t;
+
+typedef union {
+    slHttpServerString_t     httpTokenName; /* SL_NETAPP_HTTPGETTOKENVALUE */
+    slHttpServerPostData_t   httpPostData;  /* SL_NETAPP_HTTPPOSTTOKENVALUE */
+} SlHttpServerEventData_u;
+
+typedef union {
+    slHttpServerString_t token_value;
+} SlHttpServerResponsedata_u;
+
+typedef struct {
+    uint32_t                Event;
+    SlHttpServerEventData_u EventData;
+} SlHttpServerEvent_t;
+
+typedef struct {
+    uint32_t                   Response;
+    SlHttpServerResponsedata_u ResponseData;
+} SlHttpServerResponse_t;
+
+
+typedef struct {
+    uint32_t   lease_time;
+    uint32_t   ipv4_addr_start;
+    uint32_t   ipv4_addr_last;
+} SlNetAppDhcpServerBasicOpt_t;
+
+/*mDNS parameters*/
+typedef enum {
+    SL_NET_APP_FULL_SERVICE_WITH_TEXT_IPV4_TYPE = 1,
+    SL_NET_APP_FULL_SERVICE_IPV4_TYPE,
+    SL_NET_APP_SHORT_SERVICE_IPV4_TYPE
+
+} SlNetAppGetServiceListType_e;
+
+typedef struct {
+    uint32_t   service_ipv4;
+    uint16_t   service_port;
+    uint16_t   Reserved;
+} SlNetAppGetShortServiceIpv4List_t;
+
+typedef struct {
+    uint32_t   service_ipv4;
+    uint16_t   service_port;
+    uint16_t   Reserved;
+    uint8_t    service_name[NETAPP_MAX_SERVICE_NAME_SIZE];
+    uint8_t    service_host[NETAPP_MAX_SERVICE_HOST_NAME_SIZE];
+} SlNetAppGetFullServiceIpv4List_t;
+
+typedef struct {
+    uint32_t    service_ipv4;
+    uint16_t    service_port;
+    uint16_t    Reserved;
+    uint8_t     service_name[NETAPP_MAX_SERVICE_NAME_SIZE];
+    uint8_t     service_host[NETAPP_MAX_SERVICE_HOST_NAME_SIZE];
+    uint8_t     service_text[NETAPP_MAX_SERVICE_TEXT_SIZE];
+} SlNetAppGetFullServiceWithTextIpv4List_t;
+
+typedef struct {
+    /*The below parameters are used to configure the advertise times and interval
+    For example:
+        If:
+        Period is set to T
+        Repetitions are set to P
+        Telescopic factor is K=2
+        The transmission shall be:
+        advertise P times
+        wait T
+        advertise P times
+        wait 4 * T
+        advertise P time
+        wait 16 * T  ... (till max time reached / configuration changed / query issued)
+    */
+    uint32_t    t;              /* Number of ticks for the initial period. Default is 100 ticks for 1 second. */
+    uint32_t    p;              /* Number of repetitions. Default value is 1                                  */
+    uint32_t    k;              /* Telescopic factor. Default value is 2.                                     */
+    uint32_t    RetransInterval;/* Announcing retransmission interval                                         */
+    uint32_t    Maxinterval;     /* Announcing max period interval                                            */
+    uint32_t    max_time;       /* Announcing max time                                                        */
+} SlNetAppServiceAdvertiseTimingParameters_t;
+
+/*****************************************************************************/
+/* Types declarations                                               */
+/*****************************************************************************/
+typedef void (*P_SL_DEV_PING_CALLBACK)(SlPingReport_t*);
+extern P_SL_DEV_PING_CALLBACK  pPingCallBackFunc;
+
+/*****************************************************************************************
+*   NETAPP structs
+******************************************************************************************/
+
+
+typedef _BasicResponse_t _NetAppStartStopResponse_t;
+
+typedef struct {
+    uint32_t  appId;
+} _NetAppStartStopCommand_t;
+
+typedef struct {
+    uint16_t  Status;
+    uint16_t  AppId;
+    uint16_t  ConfigOpt;
+    uint16_t  ConfigLen;
+} _NetAppSetGet_t;
+typedef struct {
+    uint16_t  port_number;
+} _NetAppHttpServerGetSet_port_num_t;
+
+typedef struct {
+    uint8_t  auth_enable;
+} _NetAppHttpServerGetSet_auth_enable_t;
+
+typedef struct _sl_NetAppHttpServerGetToken_t {
+    uint8_t   token_name_len;
+    uint8_t   padd1;
+    uint16_t  padd2;
+} sl_NetAppHttpServerGetToken_t;
+
+typedef struct _sl_NetAppHttpServerSendToken_t {
+    uint8_t   token_value_len;
+    uint8_t   token_name_len;
+    uint8_t   token_name[MAX_TOKEN_NAME_LEN];
+    uint16_t  padd;
+} sl_NetAppHttpServerSendToken_t;
+
+typedef struct _sl_NetAppHttpServerPostToken_t {
+    uint8_t post_action_len;
+    uint8_t token_name_len;
+    uint8_t token_value_len;
+    uint8_t padding;
+} sl_NetAppHttpServerPostToken_t;
+
+
+typedef struct {
+    uint16_t Len;
+    uint8_t  family;
+    uint8_t  padding;
+} _GetHostByNameCommand_t;
+
+typedef struct {
+    uint16_t status;
+    uint16_t padding;
+    uint32_t ip0;
+    uint32_t ip1;
+    uint32_t ip2;
+    uint32_t ip3;
+} _GetHostByNameIPv6AsyncResponse_t;
+
+typedef struct {
+    uint16_t status;
+    uint8_t  padding1;
+    uint8_t  padding2;
+    uint32_t ip0;
+} _GetHostByNameIPv4AsyncResponse_t;
+
+typedef enum {
+    CTST_BSD_UDP_TX,
+    CTST_BSD_UDP_RX,
+    CTST_BSD_TCP_TX,
+    CTST_BSD_TCP_RX,
+    CTST_BSD_TCP_SERVER_BI_DIR,
+    CTST_BSD_TCP_CLIENT_BI_DIR,
+    CTST_BSD_UDP_BI_DIR,
+    CTST_BSD_RAW_TX,
+    CTST_BSD_RAW_RX,
+    CTST_BSD_RAW_BI_DIR,
+    CTST_BSD_SECURED_TCP_TX,
+    CTST_BSD_SECURED_TCP_RX,
+    CTST_BSD_SECURED_TCP_SERVER_BI_DIR,
+    CTST_BSD_SECURED_TCP_CLIENT_BI_DIR
+} CommTest_e;
+
+typedef struct _sl_protocol_CtestStartCommand_t {
+    uint32_t Test;
+    uint16_t DestPort;
+    uint16_t SrcPort;
+    uint32_t DestAddr[4];
+    uint32_t PayloadSize;
+    uint32_t timeout;
+    uint32_t csEnabled;
+    uint32_t secure;
+    uint32_t rawProtocol;
+    uint8_t  reserved1[4];
+} _CtestStartCommand_t;
+
+typedef struct {
+    uint8_t  test;
+    uint8_t  socket;
+    int16_t  status;
+    uint32_t startTime;
+    uint32_t endTime;
+    uint16_t txKbitsSec;
+    uint16_t rxKbitsSec;
+    uint32_t outOfOrderPackets;
+    uint32_t missedPackets;
+    int16_t  token;
+} _CtestAsyncResponse_t;
+
+typedef struct {
+    uint32_t pingIntervalTime;
+    uint16_t PingSize;
+    uint16_t pingRequestTimeout;
+    uint32_t totalNumberOfAttempts;
+    uint32_t flags;
+    uint32_t ip0;
+    uint32_t ip1OrPaadding;
+    uint32_t ip2OrPaadding;
+    uint32_t ip3OrPaadding;
+} _PingStartCommand_t;
+
+typedef struct {
+    uint16_t status;
+    uint16_t rttMin;
+    uint16_t rttMax;
+    uint16_t rttAvg;
+    uint32_t numSuccsessPings;
+    uint32_t numSendsPings;
+    uint32_t testTime;
+} _PingReportResponse_t;
+
+
+typedef struct {
+    uint32_t ip;
+    uint32_t gateway;
+    uint32_t dns;
+} _IpV4AcquiredAsync_t;
+
+
+typedef enum {
+    ACQUIRED_IPV6_LOCAL = 1,
+    ACQUIRED_IPV6_GLOBAL
+} IpV6AcquiredType_e;
+
+
+typedef struct {
+    uint32_t type;
+    uint32_t ip[4];
+    uint32_t gateway[4];
+    uint32_t dns[4];
+} _IpV6AcquiredAsync_t;
+
+
+typedef union {
+    _SocketCommand_t     EventMask;
+    _sendRecvCommand_t   DeviceInit;
+} _device_commands_t;
+
+
+class cc3100_netapp
+{
+
+public:
+
+    cc3100_netapp(cc3100_driver &driver, cc3100_nonos &nonos);
+
+    ~cc3100_netapp();
+
+    /*****************************************************************************/
+    /* Functions prototypes                                                      */
+    /*****************************************************************************/
+    int16_t sl_NetAppMDNSRegisterUnregisterService(const char* pServiceName,  
+                                                   const uint8_t ServiceNameLen, 
+                                                   const char* pText, 
+                                                   const uint8_t TextLen, 
+                                                   const uint16_t Port, 
+                                                   const uint32_t TTL, 
+                                                   const uint32_t Options);
+
+    void _sl_HandleAsync_DnsGetHostByAddr(void *pVoidBuf);
+
+    void CopyPingResultsToReport(_PingReportResponse_t *pResults,SlPingReport_t *pReport);
+    
+#if defined(sl_HttpServerCallback) || defined(EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS)
+    uint16_t sl_NetAppSendTokenValue(slHttpServerData_t * Token);
+#endif
+
+//    uint16_t sl_NetAppSendTokenValue(slHttpServerData_t * Token);
+
+
+    /*****************************************************************************/
+    /* Function prototypes                                                       */
+    /*****************************************************************************/
+
+
+    /*!
+        \brief Starts a network application
+
+        Gets and starts network application for the current WLAN mode
+
+        \param[in] AppBitMap      application bitmap, could be one or combination of the following: \n
+                                  - SL_NET_APP_HTTP_SERVER_ID
+                                  - SL_NET_APP_DHCP_SERVER_ID
+                                  - SL_NET_APP_MDNS_ID
+
+        \return                   On error, negative number is returned
+
+        \sa                       Stop one or more the above started applications using sl_NetAppStop
+        \note                     This command activates the application for the current WLAN mode (AP or STA)
+        \warning
+        \par                 Example:
+        \code
+        For example: Starting internal HTTP server + DHCP server:
+        sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID | SL_NET_APP_DHCP_SERVER_ID)
+
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_NetAppStart)
+    int16_t sl_NetAppStart(const uint32_t AppBitMap);
+#endif
+    /*!
+        \brief Stops a network application
+
+        Gets and stops network application for the current WLAN mode
+
+        \param[in] AppBitMap    application id, could be one of the following: \n
+                                - SL_NET_APP_HTTP_SERVER_ID
+                                - SL_NET_APP_DHCP_SERVER_ID
+                                - SL_NET_APP_MDNS_ID
+
+        \return                 On error, negative number is returned
+
+        \sa
+        \note                This command disables the application for the current active WLAN mode (AP or STA)
+        \warning
+        \par                 Example:
+        \code
+
+        For example: Stopping internal HTTP server:
+                             sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);
+
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_NetAppStop)
+    int16_t sl_NetAppStop(const uint32_t AppBitMap);
+#endif
+
+    /*!
+        \brief Get host IP by name
+
+        Obtain the IP Address of machine on network, by machine name.
+
+        \param[in]  hostname        host name
+        \param[in]  usNameLen       name length
+        \param[out] out_ip_addr     This parameter is filled in with
+                                    host IP address. In case that host name is not
+                                    resolved, out_ip_addr is zero.
+        \param[in]  family          protocol family
+
+        \return                     On success, 0 is returned.
+                                    On error, negative is returned
+                                    SL_POOL_IS_EMPTY may be return in case there are no resources in the system
+                                    In this case try again later or increase MAX_CONCURRENT_ACTIONS
+                                    Possible DNS error codes:
+                                    - SL_NET_APP_DNS_QUERY_NO_RESPONSE
+                                    - SL_NET_APP_DNS_NO_SERVER
+                                    - SL_NET_APP_DNS_QUERY_FAILED
+                                    - SL_NET_APP_DNS_MALFORMED_PACKET
+                                    - SL_NET_APP_DNS_MISMATCHED_RESPONSE
+
+        \sa
+        \note   Only one sl_NetAppDnsGetHostByName can be handled at a time.
+                Calling this API while the same command is called from another thread, may result
+                in one of the two scenarios:
+                1. The command will wait (internal) until the previous command finish, and then be executed.
+                2. There are not enough resources and POOL_IS_EMPTY error will return.
+                In this case, MAX_CONCURRENT_ACTIONS can be increased (result in memory increase) or try
+                again later to issue the command.
+        \warning
+        In case an IP address in a string format is set as input, without any prefix (e.g. "1.2.3.4") the device will not 
+        try to access the DNS and it will return the input address on the 'out_ip_addr' field 
+        \par  Example:
+        \code
+        uint32_t DestinationIP;
+        sl_NetAppDnsGetHostByName("www.google.com", strlen("www.google.com"), &DestinationIP,SL_AF_INET);
+
+        Addr.sin_family = SL_AF_INET;
+        Addr.sin_port = sl_Htons(80);
+        Addr.sin_addr.s_addr = sl_Htonl(DestinationIP);
+        AddrSize = sizeof(SlSockAddrIn_t);
+        SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_NetAppDnsGetHostByName)
+    int16_t sl_NetAppDnsGetHostByName(unsigned char * hostname, const uint16_t usNameLen, uint32_t*  out_ip_addr, const uint8_t family );
+#endif
+
+    /*!
+            \brief Return service attributes like IP address, port and text according to service name
+            \par
+            The user sets a service name Full/Part (see example below), and should get:
+            - IP of service
+            - The port of service
+            - The text of service
+
+            Hence it can make a connection to the specific service and use it.
+            It is similar to get host by name method.
+            It is done by a single shot query with PTR type on the service name.
+                      The command that is sent is from constant parameters and variables parameters.
+
+            \param[in]     pService                   Service name can be full or partial. \n
+                                                      Example for full service name:
+                                                      1. PC1._ipp._tcp.local
+                                                      2. PC2_server._ftp._tcp.local \n
+                                                      .
+                                                      Example for partial service name:
+                                                      1. _ipp._tcp.local
+                                                      2. _ftp._tcp.local
+
+            \param[in]    ServiceLen                  The length of the service name (in_pService).
+            \param[in]    Family                      IPv4 or IPv6 (SL_AF_INET , SL_AF_INET6).
+            \param[out]    pAddr                      Contains the IP address of the service.
+            \param[out]    pPort                      Contains the port of the service.
+            \param[out]    pTextLen                   Has 2 options. One as Input field and the other one as output:
+                                                      - Input: \n
+                                                      Contains the max length of the text that the user wants to get.\n
+                                                      It means that if the text len of service is bigger that its value than
+                                                      the text is cut to inout_TextLen value.
+                                                      - Output: \n
+                                                       Contain the length of the text that is returned. Can be full text or part of the text (see above).
+
+            \param[out]   pOut_pText     Contains the text of the service full or partial
+
+            \return       On success, zero is returned
+                          SL_POOL_IS_EMPTY may be return in case there are no resources in the system
+                          In this case try again later or increase MAX_CONCURRENT_ACTIONS
+                          In case No service is found error SL_NET_APP_DNS_NO_ANSWER will be returned
+
+            \note         The returns attributes belongs to the first service found.
+                          There may be other services with the same service name that will response to the query.
+                          The results of these responses are saved in the peer cache of the Device and should be read by another API.
+
+                          Only one sl_NetAppDnsGetHostByService can be handled at a time.
+                          Calling this API while the same command is called from another thread, may result
+                          in one of the two scenarios:
+                          1. The command will wait (internal) until the previous command finish, and then be executed.
+                          2. There are not enough resources and SL_POOL_IS_EMPTY error will return.
+                          In this case, MAX_CONCURRENT_ACTIONS can be increased (result in memory increase) or try
+                          again later to issue the command.
+
+            \warning      Text length can be 120 bytes only
+    */
+#if _SL_INCLUDE_FUNC(sl_NetAppDnsGetHostByService)
+    int32_t sl_NetAppDnsGetHostByService(unsigned char  *pServiceName, /*  string containing all (or only part): name + subtype + service */
+                                         const uint8_t  ServiceLen,
+                                         const uint8_t  Family,        /*  4-IPv4 , 16-IPv6  */
+                                         uint32_t pAddr[],
+                                         uint32_t *pPort,
+                                         uint16_t *pTextLen,     /*  in: max len , out: actual len */
+                                         unsigned char  *pText
+                                        );
+
+#endif
+
+    /*!
+            \brief Get service List
+            Insert into out pBuffer a list of peer's services that are the NWP.
+            The list is in a form of service struct. The user should chose the type
+            of the service struct like:
+                - Full service parameters with text.
+                - Full service parameters.
+                - Short service parameters (port and IP only) especially for tiny hosts.
+
+            The different types of struct are made to give the
+            Possibility to save memory in the host
+
+
+            The user also chose how many max services to get and start point index
+            NWP peer cache.
+            For example:
+                1.    Get max of 3 full services from index 0.Up to 3 full services
+                from index 0 are inserted into pBuffer (services that are in indexes 0,1,2).
+                2.    Get max of 4 full services from index 3.Up to 4 full services
+                from index 3 are inserted into pBuffer (services that are in indexes 3,4,5,6).
+                3.    Get max of 2 int services from index 6.Up to 2 int services
+                from index 6 are inserted into pBuffer (services that are in indexes 6,7).
+
+            See below - command parameters.
+
+            \param[in] indexOffset - The start index in the peer cache that from it the first service is returned.
+            \param[in] MaxServiceCount - The Max services that can be returned if existed or if not exceed the max index
+                          in the peer cache
+            \param[in] Flags - an ENUM number that means which service struct to use (means which types of service to fill)
+                            - use SlNetAppGetFullServiceWithTextIpv4List_t
+                            - use SlNetAppGetFullServiceIpv4List_t
+                            - use SlNetAppGetShortServiceIpv4List_t
+
+           \param[out]  Buffer - The Services are inserted into this buffer. In the struct form according to the bit that is set in the Flags
+                          input parameter.
+
+            \return    ServiceFoundCount - The number of the services that were inserted into the buffer. zero means no service is found
+                        negative number means an error
+            \sa           sl_NetAppMDNSRegisterService
+            \note
+            \warning
+                        if the out pBuffer size is bigger than an RX packet(1480), than
+                        an error is returned because there
+                        is no place in the RX packet.
+                        The size is a multiply of MaxServiceCount and size of service struct(that is set
+                        according to flag value).
+    */
+
+#if _SL_INCLUDE_FUNC(sl_NetAppGetServiceList)
+    int16_t sl_NetAppGetServiceList(const uint8_t   IndexOffest,
+                                    const uint8_t   MaxServiceCount,
+                                    const uint8_t   Flags,
+                                    int8_t   *pBuffer,
+                                    const uint32_t  RxBufferLength
+                                   );
+
+#endif
+
+    /*!
+            \brief Unregister mDNS service
+            This function deletes the mDNS service from the mDNS package and the database.
+
+            The mDNS service that is to be unregistered is a service that the application no longer wishes to provide. \n
+            The service name should be the full service name according to RFC
+            of the DNS-SD - meaning the value in name field in the SRV answer.
+
+            Examples for service names:
+            1. PC1._ipp._tcp.local
+            2. PC2_server._ftp._tcp.local
+
+            \param[in]    pServiceName            Full service name. \n
+                                                    Example for service name:
+                                                    1. PC1._ipp._tcp.local
+                                                    2. PC2_server._ftp._tcp.local
+            \param[in]    ServiceLen              The length of the service.
+            \return    On success, zero is returned
+            \sa          sl_NetAppMDNSRegisterService
+            \note
+            \warning
+            The size of the service length should be smaller than 255.
+    */
+#if _SL_INCLUDE_FUNC(sl_NetAppMDNSUnRegisterService)
+    int16_t sl_NetAppMDNSUnRegisterService(const char *pServiceName, const uint8_t ServiceNameLen);
+#endif
+
+    /*!
+            \brief Register a new mDNS service
+            \par
+            This function registers a new mDNS service to the mDNS package and the DB.
+
+            This registered service is a service offered by the application.
+            The service name should be full service name according to RFC
+            of the DNS-SD - meaning the value in name field in the SRV answer.
+            Example for service name:
+            1. PC1._ipp._tcp.local
+            2. PC2_server._ftp._tcp.local
+
+            If the option is_unique is set, mDNS probes the service name to make sure
+            it is unique before starting to announce the service on the network.
+            Instance is the instance portion of the service name.
+
+            \param[in]  ServiceLen         The length of the service.
+            \param[in]  TextLen            The length of the service should be smaller than 64.
+            \param[in]  port               The port on this target host port.
+            \param[in]  TTL                The TTL of the service
+            \param[in]  Options            bitwise parameters: \n
+                                           - bit 0  - service is unique (means that the service needs to be unique)
+                                           - bit 31  - for internal use if the service should be added or deleted (set means ADD).
+                                           - bit 1-30 for future.
+
+            \param[in]    pServiceName              The service name.
+                                           Example for service name: \n
+                                                    1. PC1._ipp._tcp.local
+                                                    2. PC2_server._ftp._tcp.local
+
+            \param[in] pText                     The description of the service.
+                                                    should be as mentioned in the RFC
+                                                    (according to type of the service IPP,FTP...)
+
+            \return     On success, zero is returned
+                        Possible error codes:
+                        - Maximum advertise services are already configured.
+                                    Delete another existed service that is registered and then register again the new service
+                        - Trying to register a service that is already exists
+                        - Trying to delete service that does not existed
+                        - Illegal service name according to the RFC
+                        - Retry request
+                        - Illegal length of one of the mDNS Set functions
+                        - mDNS is not operational as the device has no IP.Connect the device to an AP to get an IP address.
+                        - mDNS parameters error
+                        - mDNS internal cache error
+                        - mDNS internal error
+                        - Adding a service is not allowed as it is already exist (duplicate service)
+                        - mDNS is not running
+                        - Host name error. Host name format is not allowed according to RFC 1033,1034,1035, 6763
+                        - List size buffer is bigger than internally allowed in the NWP (API get service list),
+                         change the APIs� parameters to decrease the size of the list
+
+
+            \sa              sl_NetAppMDNSUnRegisterService
+
+            \warning      1) Temporary -  there is an allocation on stack of internal buffer.
+                        Its size is NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH. \n
+                        It means that the sum of the text length and service name length cannot be bigger than
+                        NETAPP_MDNS_MAX_SERVICE_NAME_AND_TEXT_LENGTH.\n
+                        If it is - An error is returned. \n
+                        2) According to now from certain constraints the variables parameters are set in the
+                        attribute part (contain constant parameters)
+    */
+#if _SL_INCLUDE_FUNC(sl_NetAppMDNSRegisterService)
+    int16_t sl_NetAppMDNSRegisterService( const char*  pServiceName,
+                                          const uint8_t         ServiceNameLen,
+                                          const char*  pText,
+                                          const uint8_t         TextLen,
+                                          const uint16_t        Port,
+                                          const uint32_t        TTL,
+                                          uint32_t        Options);
+#endif
+
+    /*!
+        \brief send ICMP ECHO_REQUEST to network hosts
+
+        Ping uses the ICMP protocol's mandatory ECHO_REQUEST
+
+        \param[in]   pPingParams     Pointer to the ping request structure: \n
+                                     - if flags parameter is set to 0, ping will report back once all requested pings are done (as defined by TotalNumberOfAttempts). \n
+                                     - if flags parameter is set to 1, ping will report back after every ping, for TotalNumberOfAttempts.
+                                     - if flags parameter is set to 2, ping will stop after the first successful ping, and report back for the successful ping, as well as any preceding failed ones.
+                                     For stopping an ongoing ping activity, set parameters IP address to 0
+
+        \param[in]   family          SL_AF_INET or  SL_AF_INET6
+        \param[out]  pReport         Ping pReport
+        \param[out]  pCallback       Callback function upon completion.
+                                     If callback is NULL, the API is blocked until data arrives
+
+
+        \return    On success, zero is returned. On error, -1 is returned
+                   SL_POOL_IS_EMPTY may be return in case there are no resources in the system
+                   In this case try again later or increase MAX_CONCURRENT_ACTIONS
+
+        \sa       sl_NetAppPingReport
+        \note      Only one sl_NetAppPingStart can be handled at a time.
+                  Calling this API while the same command is called from another thread, may result
+                      in one of the two scenarios:
+                  1. The command will wait (internal) until the previous command finish, and then be executed.
+                  2. There are not enough resources and SL_POOL_IS_EMPTY error will return.
+                  In this case, MAX_CONCURRENT_ACTIONS can be increased (result in memory increase) or try
+                  again later to issue the command.
+        \warning
+        \par      Example:
+        \code
+
+        An example of sending 20 ping requests and reporting results to a callback routine when
+                  all requests are sent:
+
+                  // callback routine
+                  void pingRes(SlPingReport_t* pReport)
+                  {
+                   // handle ping results
+                  }
+
+                  // ping activation
+                  void PingTest()
+                  {
+                     SlPingReport_t report;
+                     SlPingStartCommand_t pingCommand;
+
+                     pingCommand.Ip = SL_IPV4_VAL(10,1,1,200);     // destination IP address is 10.1.1.200
+                     pingCommand.PingSize = 150;                   // size of ping, in bytes
+                     pingCommand.PingIntervalTime = 100;           // delay between pings, in milliseconds
+                     pingCommand.PingRequestTimeout = 1000;        // timeout for every ping in milliseconds
+                     pingCommand.TotalNumberOfAttempts = 20;       // max number of ping requests. 0 - forever
+                     pingCommand.Flags = 0;                        // report only when finished
+
+                     sl_NetAppPingStart( &pingCommand, SL_AF_INET, &report, pingRes ) ;
+                 }
+
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_NetAppPingStart)
+    int16_t sl_NetAppPingStart(const SlPingStartCommand_t* pPingParams, const uint8_t family,SlPingReport_t *pReport, const P_SL_DEV_PING_CALLBACK pPingCallback);
+#endif
+
+    /*!
+        \brief     Internal function for setting network application configurations
+
+        \return    On success, zero is returned. On error, -1 is
+                   returned
+
+        \param[in] AppId          Application id, could be one of the following: \n
+                                  - SL_NET_APP_HTTP_SERVER_ID
+                                  - SL_NET_APP_DHCP_SERVER_ID
+                                  - SL_NET_APP_MDNS_ID
+                                  - SL_NET_APP_DEVICE_CONFIG_ID
+
+        \param[in] SetOptions     set option, could be one of the following: \n
+                                  - SL_NET_APP_DHCP_SERVER_ID
+                                 - NETAPP_SET_DHCP_SRV_BASIC_OPT
+                                 - SL_NET_APP_HTTP_SERVER_ID
+                                 - NETAPP_SET_GET_HTTP_OPT_PORT_NUMBER
+                                 - NETAPP_SET_GET_HTTP_OPT_AUTH_CHECK
+                                 - NETAPP_SET_GET_HTTP_OPT_AUTH_NAME
+                                 - NETAPP_SET_GET_HTTP_OPT_AUTH_PASSWORD
+                                 - NETAPP_SET_GET_HTTP_OPT_AUTH_REALM
+                                 - NETAPP_SET_GET_HTTP_OPT_ROM_PAGES_ACCESS
+                                 - SL_NET_APP_MDNS_ID
+                                 - NETAPP_SET_GET_MDNS_CONT_QUERY_OPT
+                                 - NETAPP_SET_GET_MDNS_QEVETN_MASK_OPT
+                                 - NETAPP_SET_GET_MDNS_TIMING_PARAMS_OPT
+                                 - SL_NET_APP_DEVICE_CONFIG_ID
+                                 - NETAPP_SET_GET_DEV_CONF_OPT_DEVICE_URN
+                                 - NETAPP_SET_GET_DEV_CONF_OPT_DOMAIN_NAME
+
+
+        \param[in] OptionLen       option structure length
+
+        \param[in] pOptionValues   pointer to the option structure
+        \sa
+        \note
+        \warning
+        \par
+        \code
+            Set DHCP Server (AP mode) parameters example:
+
+            SlNetAppDhcpServerBasicOpt_t dhcpParams;
+            uint8_t outLen = sizeof(SlNetAppDhcpServerBasicOpt_t);
+            dhcpParams.lease_time      = 4096;                         // lease time (in seconds) of the IP Address
+            dhcpParams.ipv4_addr_start =  SL_IPV4_VAL(192,168,1,10);   // first IP Address for allocation. IP Address should be set as Hex number - i.e. 0A0B0C01 for (10.11.12.1)
+            dhcpParams.ipv4_addr_last  =  SL_IPV4_VAL(192,168,1,16);   // last IP Address for allocation. IP Address should be set as Hex number - i.e. 0A0B0C01 for (10.11.12.1)
+            sl_NetAppStop(SL_NET_APP_DHCP_SERVER_ID);                  // Stop DHCP server before settings
+            sl_NetAppSet(SL_NET_APP_DHCP_SERVER_ID, NETAPP_SET_DHCP_SRV_BASIC_OPT, outLen, (uint8_t* )&dhcpParams);  // set parameters
+            sl_NetAppStart(SL_NET_APP_DHCP_SERVER_ID);                 // Start DHCP server with new settings
+        \endcode
+        \code
+            Set Device URN name example:
+
+            Device name, maximum length of 33 characters
+            Device name affects URN name, own SSID name in AP mode, and WPS file "device name" in WPS I.E (STA-WPS / P2P)
+            In case no device URN name set, the default name is "mysimplelink"
+            Allowed characters in device name are: 'a - z' , 'A - Z' , '0-9' and '-'
+
+            uint8_t *my_device = "MY-SIMPLELINK-DEV";
+            sl_NetAppSet (SL_NET_APP_DEVICE_CONFIG_ID, NETAPP_SET_GET_DEV_CONF_OPT_DEVICE_URN, strlen(my_device), (uint8_t *) my_device);
+        \endcode
+
+    */
+#if _SL_INCLUDE_FUNC(sl_NetAppSet)
+    int32_t sl_NetAppSet(const uint8_t AppId, const uint8_t Option, const uint8_t OptionLen, const uint8_t *pOptionValue);
+#endif
+
+    /*!
+        \brief     Internal function for getting network applications configurations
+
+        \return    On success, zero is returned. On error, -1 is
+                   returned
+
+        \param[in] AppId          Application id, could be one of the following: \n
+                                  - SL_NET_APP_HTTP_SERVER_ID
+                                  - SL_NET_APP_DHCP_SERVER_ID
+                                  - SL_NET_APP_MDNS_ID
+                                  - SL_NET_APP_DEVICE_CONFIG_ID
+
+    \param[in] SetOptions     set option, could be one of the following: \n
+                                 - SL_NET_APP_DHCP_SERVER_ID
+                                 - NETAPP_SET_DHCP_SRV_BASIC_OPT
+                                 - SL_NET_APP_HTTP_SERVER_ID
+                                 - NETAPP_SET_GET_HTTP_OPT_PORT_NUMBER
+                                 - NETAPP_SET_GET_HTTP_OPT_AUTH_CHECK
+                                 - NETAPP_SET_GET_HTTP_OPT_AUTH_NAME
+                                 - NETAPP_SET_GET_HTTP_OPT_AUTH_PASSWORD
+                                 - NETAPP_SET_GET_HTTP_OPT_AUTH_REALM
+                                 - NETAPP_SET_GET_HTTP_OPT_ROM_PAGES_ACCESS
+                                 - SL_NET_APP_MDNS_ID
+                                 - NETAPP_SET_GET_MDNS_CONT_QUERY_OPT
+                                 - NETAPP_SET_GET_MDNS_QEVETN_MASK_OPT
+                                 - NETAPP_SET_GET_MDNS_TIMING_PARAMS_OPT
+                                 - SL_NET_APP_DEVICE_CONFIG_ID
+                                 - NETAPP_SET_GET_DEV_CONF_OPT_DEVICE_URN
+                                 - NETAPP_SET_GET_DEV_CONF_OPT_DOMAIN_NAME
+
+        \param[in] OptionLen     The length of the allocated memory as input, when the
+                                            function complete, the value of this parameter would be
+                                            the len that actually read from the device.
+                                            If the device return length that is longer from the input
+                                            value, the function will cut the end of the returned structure
+                                            and will return ESMALLBUF
+
+        \param[out] pValues      pointer to the option structure which will be filled with the response from the device
+
+        \sa
+        \note
+        \warning
+        \par
+        \code
+             Get DHCP Server parameters example:
+
+             SlNetAppDhcpServerBasicOpt_t dhcpParams;
+             uint8_t outLen = sizeof(SlNetAppDhcpServerBasicOpt_t);
+             sl_NetAppGet(SL_NET_APP_DHCP_SERVER_ID, NETAPP_SET_DHCP_SRV_BASIC_OPT, &outLen, (uint8_t* )&dhcpParams);
+
+             printf("DHCP Start IP %d.%d.%d.%d End IP %d.%d.%d.%d Lease time seconds %d\n",
+                SL_IPV4_BYTE(dhcpParams.ipv4_addr_start,3),SL_IPV4_BYTE(dhcpParams.ipv4_addr_start,2),
+                SL_IPV4_BYTE(dhcpParams.ipv4_addr_start,1),SL_IPV4_BYTE(dhcpParams.ipv4_addr_start,0),
+                SL_IPV4_BYTE(dhcpParams.ipv4_addr_last,3),SL_IPV4_BYTE(dhcpParams.ipv4_addr_last,2),
+                SL_IPV4_BYTE(dhcpParams.ipv4_addr_last,1),SL_IPV4_BYTE(dhcpParams.ipv4_addr_last,0),
+                dhcpParams.lease_time);
+        \endcode
+        \code
+             Get Device URN name example:
+             Maximum length of 33 characters of device name.
+             Device name affects URN name, own SSID name in AP mode, and WPS file "device name" in WPS I.E (STA-WPS / P2P)
+             in case no device URN name set, the default name is "mysimplelink"
+
+             uint8_t my_device_name[35];
+             sl_NetAppGet (SL_NET_APP_DEVICE_CONFIG_ID, NETAPP_SET_GET_DEV_CONF_OPT_DEVICE_URN, strlen(my_device_name), (uint8_t *)my_device_name);
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_NetAppGet)
+    int32_t sl_NetAppGet(const uint8_t AppId, const uint8_t Option,uint8_t *pOptionLen, uint8_t *pOptionValue);
+#endif
+
+private:
+
+    cc3100_driver           &_driver;
+    cc3100_nonos            &_nonos;
+
+
+};//class
+
+/*****************************************************************************/
+/* Macro declarations                                                        */
+/*****************************************************************************/
+const uint8_t FLOW_CONT_MIN = 1;
+
+
+class cc3100_flowcont
+{
+
+public:
+
+    cc3100_flowcont(cc3100_driver &driver, cc3100_nonos &nonos);
+
+
+    ~cc3100_flowcont();
+
+#if 0
+    /*****************************************************************************/
+    /* Function prototypes                                                       */
+    /*****************************************************************************/
+    void _SlDrvFlowContInit(void);
+    void _SlDrvFlowContDeinit(void);
+#endif
+
+private:
+
+    cc3100_driver &_driver;
+    cc3100_nonos  &_nonos;
+
+};//class
+}//namespace mbed_cc3100
+
+/*!
+
+ Close the Doxygen group.
+ @}
+
+ */
+
+#endif    /*  __NETAPP_H__ */
+
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_netcfg.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_netcfg.cpp	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,164 @@
+/*
+* netcfg.c - CC31xx/CC32xx Host Driver Implementation
+*
+* Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+*
+*
+*  Redistribution and use in source and binary forms, with or without
+*  modification, are permitted provided that the following conditions
+*  are met:
+*
+*    Redistributions of source code must retain the above copyright
+*    notice, this list of conditions and the following disclaimer.
+*
+*    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.
+*
+*    Neither the name of Texas Instruments Incorporated nor the names of
+*    its contributors may be used to endorse or promote products derived
+*    from this software without specific prior written permission.
+*
+*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+*  "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 COPYRIGHT
+*  OWNER OR CONTRIBUTORS 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 files                                                             */
+/*****************************************************************************/
+#include "cc3100_simplelink.h"
+#include "cc3100_protocol.h"
+#include "cc3100_driver.h"
+
+#include "cc3100_netcfg.h"
+
+namespace mbed_cc3100 {
+
+cc3100_netcfg::cc3100_netcfg(cc3100_driver &driver)
+    : _driver(driver)
+{
+
+}
+
+cc3100_netcfg::~cc3100_netcfg()
+{
+
+}
+
+/*****************************************************************************/
+/* sl_NetCfgSet */
+/*****************************************************************************/
+typedef union {
+    _NetCfgSetGet_t    Cmd;
+    _BasicResponse_t   Rsp;
+} _SlNetCfgMsgSet_u;
+
+#if _SL_INCLUDE_FUNC(sl_NetCfgSet)
+const _SlCmdCtrl_t _SlNetCfgSetCmdCtrl = {
+    SL_OPCODE_DEVICE_NETCFG_SET_COMMAND,
+    sizeof(_NetCfgSetGet_t),
+    sizeof(_BasicResponse_t)
+};
+
+int32_t cc3100_netcfg::sl_NetCfgSet(const uint8_t ConfigId, const uint8_t ConfigOpt, const uint8_t ConfigLen, const uint8_t *pValues)
+{
+    _SlNetCfgMsgSet_u         Msg;
+    _SlCmdExt_t               CmdExt;
+
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.TxPayloadLen = (ConfigLen+3) & (~3);
+    CmdExt.pTxPayload = (uint8_t *)pValues;
+
+    Msg.Cmd.ConfigId    = ConfigId;
+    Msg.Cmd.ConfigLen   = ConfigLen;
+    Msg.Cmd.ConfigOpt   = ConfigOpt;
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlNetCfgSetCmdCtrl, &Msg, &CmdExt));
+
+    return (int16_t)Msg.Rsp.status;
+}
+#endif
+
+uint32_t cc3100_netcfg::SL_IPV4_VAL(uint8_t add_3,uint8_t add_2,uint8_t add_1,uint8_t add_0){
+	
+	     return((((uint32_t)add_3 << 24) & 0xFF000000) | (((uint32_t)add_2 << 16) & 0xFF0000) | (((uint32_t)add_1 << 8) & 0xFF00) | ((uint32_t)add_0 & 0xFF) );
+}
+
+uint8_t cc3100_netcfg::SL_IPV4_BYTE(uint32_t val,uint8_t index){
+	                  
+	    return( (val >>= (index*8)) & 0xFF );
+}	                  
+
+/*****************************************************************************/
+/* sl_NetCfgGet */
+/*****************************************************************************/
+typedef union {
+    _NetCfgSetGet_t	    Cmd;
+    _NetCfgSetGet_t	    Rsp;
+} _SlNetCfgMsgGet_u;
+
+#if _SL_INCLUDE_FUNC(sl_NetCfgGet)
+const _SlCmdCtrl_t _SlNetCfgGetCmdCtrl = {
+    SL_OPCODE_DEVICE_NETCFG_GET_COMMAND,
+    sizeof(_NetCfgSetGet_t),
+    sizeof(_NetCfgSetGet_t)
+};
+
+int32_t cc3100_netcfg::sl_NetCfgGet(const uint8_t ConfigId, uint8_t *pConfigOpt,uint8_t *pConfigLen, uint8_t *pValues)
+{
+    _SlNetCfgMsgGet_u         Msg;
+    _SlCmdExt_t               CmdExt;
+
+    if (*pConfigLen == 0) {
+        return SL_EZEROLEN;
+    }
+    
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.RxPayloadLen = *pConfigLen;
+    CmdExt.pRxPayload = (uint8_t *)pValues;
+    
+    Msg.Cmd.ConfigLen    = *pConfigLen;
+    Msg.Cmd.ConfigId     = ConfigId;
+
+    if( pConfigOpt ) {
+        Msg.Cmd.ConfigOpt   = (uint16_t)*pConfigOpt;
+    }
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlNetCfgGetCmdCtrl, &Msg, &CmdExt));
+
+    if( pConfigOpt ) {
+        *pConfigOpt = (uint8_t)Msg.Rsp.ConfigOpt;
+    }
+    if (CmdExt.RxPayloadLen < CmdExt.ActualRxPayloadLen) {
+        *pConfigLen = (uint8_t)CmdExt.RxPayloadLen;
+         if( SL_MAC_ADDRESS_GET == ConfigId )
+         {
+           return SL_RET_CODE_OK;  /* sp fix */
+         }
+         else
+         {
+           return SL_ESMALLBUF;
+         }
+    } 
+    else 
+    {
+        *pConfigLen = (uint8_t)CmdExt.ActualRxPayloadLen;
+    }
+
+    return (int16_t)Msg.Rsp.Status;
+}
+#endif
+
+}//namespace mbed_cc3100
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_netcfg.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_netcfg.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,288 @@
+/*
+ * netcfg.h - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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 files                                                             */
+/*****************************************************************************/
+#include "cc3100_simplelink.h"
+
+#ifndef NETCFG_H_
+#define NETCFG_H_
+
+namespace mbed_cc3100 {
+
+/*!
+
+    \addtogroup netcfg
+    @{
+
+*/
+
+
+/*****************************************************************************/
+/* Macro declarations                                                        */
+/*****************************************************************************/
+const uint8_t SL_MAC_ADDR_LEN                       =   (6);
+const uint8_t IPCONFIG_MODE_DISABLE_IPV4            =   (0);
+const uint8_t IPCONFIG_MODE_ENABLE_IPV4             =   (1);
+
+/*****************************************************************************/
+/* Structure/Enum declarations                                               */
+/*****************************************************************************/
+typedef enum {
+    SL_MAC_ADDRESS_SET          = 1,
+    SL_MAC_ADDRESS_GET          = 2,
+    SL_IPV4_STA_P2P_CL_GET_INFO           = 3,
+    SL_IPV4_STA_P2P_CL_DHCP_ENABLE        = 4,
+    SL_IPV4_STA_P2P_CL_STATIC_ENABLE      = 5,
+    SL_IPV4_AP_P2P_GO_GET_INFO            = 6,
+    SL_IPV4_AP_P2P_GO_STATIC_ENABLE       = 7,
+    SL_SET_HOST_RX_AGGR                   = 8,
+    MAX_SETTINGS = 0xFF
+} Sl_NetCfg_e;
+
+
+typedef struct {
+    uint32_t  ipV4;
+    uint32_t  ipV4Mask;
+    uint32_t  ipV4Gateway;
+    uint32_t  ipV4DnsServer;
+} SlNetCfgIpV4Args_t;
+
+class cc3100_netcfg
+{
+
+public:
+
+    cc3100_netcfg(cc3100_driver  &driver);
+
+    ~cc3100_netcfg();
+
+
+    /*****************************************************************************/
+    /* Function prototypes                                                       */
+    /*****************************************************************************/
+
+    /*!
+        \brief     Internal function for setting network configurations
+
+        \return    On success, zero is returned. On error, -1 is
+                   returned
+
+        \param[in] ConfigId   configuration id
+        \param[in] ConfigOpt  configurations option
+        \param[in] ConfigLen  configurations len
+        \param[in] pValues    configurations values
+
+        \sa
+        \note
+        \warning
+
+        \par   Examples:
+        \code
+            SL_MAC_ADDRESS_SET:
+
+            Setting MAC address to the Device.
+            The new MAC address will override the default MAC address and it be saved in the FileSystem.
+            Requires restarting the device for updating this setting.
+
+            uint8_t MAC_Address[6];
+            MAC_Address[0] = 0x8;
+            MAC_Address[1] = 0x0;
+            MAC_Address[2] = 0x28;
+            MAC_Address[3] = 0x22;
+            MAC_Address[4] = 0x69;
+            MAC_Address[5] = 0x31;
+            sl_NetCfgSet(SL_MAC_ADDRESS_SET,1,SL_MAC_ADDR_LEN,(uint8_t *)newMacAddress);
+            sl_Stop(0);
+            sl_Start(NULL,NULL,NULL);
+        \endcode
+
+        \code
+            SL_IPV4_STA_P2P_CL_STATIC_ENABLE:
+
+            Setting a static IP address to the device working in STA mode or P2P client.
+            The IP address will be stored in the FileSystem.
+            In order to disable the static IP and get the address assigned from DHCP one should use SL_STA_P2P_CL_IPV4_DHCP_SET
+
+            SlNetCfgIpV4Args_t ipV4;
+            ipV4.ipV4          = (uint32_t)SL_IPV4_VAL(10,1,1,201);            // uint32_t IP address
+            ipV4.ipV4Mask      = (uint32_t)SL_IPV4_VAL(255,255,255,0);         // uint32_t Subnet mask for this STA/P2P
+            ipV4.ipV4Gateway   = (uint32_t)SL_IPV4_VAL(10,1,1,1);              // uint32_t Default gateway address
+            ipV4.ipV4DnsServer = (uint32_t)SL_IPV4_VAL(8,16,32,64);            // uint32_t DNS server address
+
+            sl_NetCfgSet(SL_IPV4_STA_P2P_CL_STATIC_ENABLE,IPCONFIG_MODE_ENABLE_IPV4,sizeof(SlNetCfgIpV4Args_t),(uint8_t *)&ipV4);
+            sl_Stop(0);
+            sl_Start(NULL,NULL,NULL);
+        \endcode
+
+        \code
+            SL_IPV4_STA_P2P_CL_DHCP_ENABLE:
+
+            Setting IP address by DHCP to FileSystem using WLAN sta mode or P2P client.
+                    This should be done once if using Serial Flash.
+                    This is the system's default mode for acquiring an IP address after WLAN connection.
+            uint8_t val = 1;
+            sl_NetCfgSet(SL_IPV4_STA_P2P_CL_DHCP_ENABLE,IPCONFIG_MODE_ENABLE_IPV4,1,&val);
+            sl_Stop(0);
+            sl_Start(NULL,NULL,NULL);
+        \endcode
+
+        \code
+            SL_IPV4_AP_P2P_GO_STATIC_ENABLE:
+
+            Setting a static IP address to the device working in AP mode or P2P go.
+            The IP address will be stored in the FileSystem. Requires restart.
+
+            SlNetCfgIpV4Args_t ipV4;
+            ipV4.ipV4          = (uint32_t)SL_IPV4_VAL(10,1,1,201);            // uint32_t IP address
+            ipV4.ipV4Mask      = (uint32_t)SL_IPV4_VAL(255,255,255,0);         // uint32_t Subnet mask for this AP/P2P
+            ipV4.ipV4Gateway   = (uint32_t)SL_IPV4_VAL(10,1,1,1);              // uint32_t Default gateway address
+            ipV4.ipV4DnsServer = (uint32_t)SL_IPV4_VAL(8,16,32,64);            // uint32_t DNS server address
+
+            sl_NetCfgSet(SL_IPV4_AP_P2P_GO_STATIC_ENABLE,IPCONFIG_MODE_ENABLE_IPV4,sizeof(SlNetCfgIpV4Args_t),(uint8_t *)&ipV4);
+            sl_Stop(0);
+            sl_Start(NULL,NULL,NULL);
+        \endcode
+
+
+    */
+#if _SL_INCLUDE_FUNC(sl_NetCfgSet)
+    int32_t sl_NetCfgSet(const uint8_t ConfigId, const uint8_t ConfigOpt, const uint8_t ConfigLen, const uint8_t *pValues);
+#endif
+
+
+    /*!
+        \brief     Internal function for getting network configurations
+
+        \return    On success, zero is returned. On error, -1 is
+                   returned
+
+        \param[in] ConfigId      configuration id
+
+        \param[out] pConfigOpt   Get configurations option
+
+        \param[out] pConfigLen   The length of the allocated memory as input, when the
+                                            function complete, the value of this parameter would be
+                                 the len that actually read from the device.\n
+                                            If the device return length that is longer from the input
+                                            value, the function will cut the end of the returned structure
+                                            and will return ESMALLBUF
+
+        \param[out] pValues - get configurations values
+
+        \sa
+        \note
+        \warning
+        \par   Examples:
+        \code
+           SL_MAC_ADDRESS_GET:
+
+           Get the device MAC address.
+           The returned MAC address is taken from FileSystem first. If the MAC address was not set by SL_MAC_ADDRESS_SET, the default MAC address
+           is retrieved from HW.
+
+           uint8_t macAddressVal[SL_MAC_ADDR_LEN];
+           uint8_t macAddressLen = SL_MAC_ADDR_LEN;
+           sl_NetCfgGet(SL_MAC_ADDRESS_GET,NULL,&macAddressLen,(uint8_t *)macAddressVal);
+
+        \endcode
+
+        \code
+            SL_IPV4_STA_P2P_CL_GET_INFO:
+
+            Get IP address from WLAN station or P2P client. A DHCP flag is returned to indicate if the IP address is static or from DHCP.
+
+            uint8_t len = sizeof(SlNetCfgIpV4Args_t);
+            uint8_t dhcpIsOn = 0;
+            SlNetCfgIpV4Args_t ipV4 = {0};
+            sl_NetCfgGet(SL_IPV4_STA_P2P_CL_GET_INFO,&dhcpIsOn,&len,(uint8_t *)&ipV4);
+
+            printf("DHCP is %s IP %d.%d.%d.%d MASK %d.%d.%d.%d GW %d.%d.%d.%d DNS %d.%d.%d.%d\n",
+                    (dhcpIsOn > 0) ? "ON" : "OFF",
+                    SL_IPV4_BYTE(ipV4.ipV4,3),SL_IPV4_BYTE(ipV4.ipV4,2),SL_IPV4_BYTE(ipV4.ipV4,1),SL_IPV4_BYTE(ipV4.ipV4,0),
+                    SL_IPV4_BYTE(ipV4.ipV4Mask,3),SL_IPV4_BYTE(ipV4.ipV4Mask,2),SL_IPV4_BYTE(ipV4.ipV4Mask,1),SL_IPV4_BYTE(ipV4.ipV4Mask,0),
+                    SL_IPV4_BYTE(ipV4.ipV4Gateway,3),SL_IPV4_BYTE(ipV4.ipV4Gateway,2),SL_IPV4_BYTE(ipV4.ipV4Gateway,1),SL_IPV4_BYTE(ipV4.ipV4Gateway,0),
+                    SL_IPV4_BYTE(ipV4.ipV4DnsServer,3),SL_IPV4_BYTE(ipV4.ipV4DnsServer,2),SL_IPV4_BYTE(ipV4.ipV4DnsServer,1),SL_IPV4_BYTE(ipV4.ipV4DnsServer,0));
+
+        \endcode
+
+        \code
+            SL_IPV4_AP_P2P_GO_GET_INFO:
+
+            Get static IP address for AP or P2P go.
+
+            uint8_t len = sizeof(SlNetCfgIpV4Args_t);
+            uint8_t dhcpIsOn = 0; // this flag is meaningless on AP/P2P go.
+            SlNetCfgIpV4Args_t ipV4 = {0};
+            sl_NetCfgGet(SL_IPV4_AP_P2P_GO_GET_INFO,&dhcpIsOn,&len,(uint8_t *)&ipV4);
+
+            printf("IP %d.%d.%d.%d MASK %d.%d.%d.%d GW %d.%d.%d.%d DNS %d.%d.%d.%d\n",
+                    SL_IPV4_BYTE(ipV4.ipV4,3),SL_IPV4_BYTE(ipV4.ipV4,2),SL_IPV4_BYTE(ipV4.ipV4,1),SL_IPV4_BYTE(ipV4.ipV4,0),
+                    SL_IPV4_BYTE(ipV4.ipV4Mask,3),SL_IPV4_BYTE(ipV4.ipV4Mask,2),SL_IPV4_BYTE(ipV4.ipV4Mask,1),SL_IPV4_BYTE(ipV4.ipV4Mask,0),
+                    SL_IPV4_BYTE(ipV4.ipV4Gateway,3),SL_IPV4_BYTE(ipV4.ipV4Gateway,2),SL_IPV4_BYTE(ipV4.ipV4Gateway,1),SL_IPV4_BYTE(ipV4.ipV4Gateway,0),
+                    SL_IPV4_BYTE(ipV4.ipV4DnsServer,3),SL_IPV4_BYTE(ipV4.ipV4DnsServer,2),SL_IPV4_BYTE(ipV4.ipV4DnsServer,1),SL_IPV4_BYTE(ipV4.ipV4DnsServer,0));
+
+        \endcode
+
+
+    */
+#if _SL_INCLUDE_FUNC(sl_NetCfgGet)
+    int32_t sl_NetCfgGet(const uint8_t ConfigId ,uint8_t *pConfigOpt, uint8_t *pConfigLen, uint8_t *pValues);
+#endif
+
+uint32_t SL_IPV4_VAL(uint8_t add_3,uint8_t add_2,uint8_t add_1,uint8_t add_0);
+uint8_t SL_IPV4_BYTE(uint32_t val,uint8_t index);
+
+private:
+
+    cc3100_driver  &_driver;
+    
+};//class
+
+}//namespace mbed_cc3100    
+
+    /*!
+
+     Close the Doxygen group.
+     @}
+
+     */
+
+
+#endif    /*  __NETCFG_H__ */
+
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_nonos.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_nonos.cpp	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,291 @@
+/*
+* nonos.c - CC31xx/CC32xx Host Driver Implementation
+*
+* Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+*
+*
+*  Redistribution and use in source and binary forms, with or without
+*  modification, are permitted provided that the following conditions
+*  are met:
+*
+*    Redistributions of source code must retain the above copyright
+*    notice, this list of conditions and the following disclaimer.
+*
+*    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.
+*
+*    Neither the name of Texas Instruments Incorporated nor the names of
+*    its contributors may be used to endorse or promote products derived
+*    from this software without specific prior written permission.
+*
+*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+*  "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 COPYRIGHT
+*  OWNER OR CONTRIBUTORS 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 files                                                             */
+/*****************************************************************************/
+
+#ifndef SL_PLATFORM_MULTI_THREADED
+
+#include "cc3100_simplelink.h"
+#include "cc3100_nonos.h"
+#include "fPtr_func.h"
+
+namespace mbed_cc3100 {
+		
+#ifndef SL_TINY_EXT
+#define NONOS_MAX_SPAWN_ENTRIES     5
+#else
+#define NONOS_MAX_SPAWN_ENTRIES     1
+#endif	
+
+cc3100_nonos::cc3100_nonos(cc3100_driver &driver)
+    : _driver(driver)
+{
+    
+}
+
+cc3100_nonos::~cc3100_nonos()
+{
+
+}
+
+typedef struct {
+    _SlSpawnEntryFunc_t 		pEntry;
+    void* 						pValue;
+} _SlNonOsSpawnEntry_t;
+
+typedef struct {
+    _SlNonOsSpawnEntry_t	SpawnEntries[NONOS_MAX_SPAWN_ENTRIES];
+} _SlNonOsCB_t;
+
+_SlNonOsCB_t g_SlNonOsCB;
+
+
+_SlNonOsRetVal_t cc3100_nonos::_SlNonOsSemSet(_SlNonOsSemObj_t* pSemObj , _SlNonOsSemObj_t Value)
+{
+    *pSemObj = Value;
+    return NONOS_RET_OK;
+}
+
+_SlNonOsRetVal_t cc3100_nonos::_SlNonOsSemGet(_SlNonOsSemObj_t* pSyncObj, _SlNonOsSemObj_t WaitValue, _SlNonOsSemObj_t SetValue, _SlNonOsTime_t Timeout)
+{
+#ifdef _SlSyncWaitLoopCallback
+    _SlNonOsTime_t timeOutRequest = Timeout; 
+#endif    
+    
+    while (Timeout > 0) {
+        if (WaitValue == *pSyncObj) {
+            *pSyncObj = SetValue;            
+            break;
+        }
+        if (Timeout != NONOS_WAIT_FOREVER) {
+            Timeout--;
+        }
+        _SlNonOsMainLoopTask();
+        
+#ifdef _SlSyncWaitLoopCallback
+        if( (__NON_OS_SYNC_OBJ_SIGNAL_VALUE == WaitValue) && (timeOutRequest != NONOS_NO_WAIT) ) {
+            if (WaitValue == *pSyncObj) {
+                *pSyncObj = SetValue;
+                break;
+            }
+            _SlSyncWaitLoopCallback();
+        }
+#endif
+
+    }
+
+    if (0 == Timeout) {        
+        return NONOS_RET_ERR;
+    } else {        
+        return NONOS_RET_OK;
+    }
+}
+
+
+_SlNonOsRetVal_t cc3100_nonos::_SlNonOsSpawn(_SlSpawnEntryFunc_t pEntry , void* pValue , uint32_t flags)
+{
+    int8_t i = 0;
+    
+#ifndef SL_TINY_EXT 	
+	for (i=0 ; i<NONOS_MAX_SPAWN_ENTRIES ; i++)
+#endif     
+	{
+		_SlNonOsSpawnEntry_t* pE = &g_SlNonOsCB.SpawnEntries[i];
+	
+		if (NULL == pE->pEntry)
+		{
+			pE->pValue = pValue;
+			pE->pEntry = pEntry;
+#ifndef SL_TINY_EXT 	                        
+			break;
+#endif                        
+		}
+	}
+        
+        
+        return NONOS_RET_OK;
+}
+
+_SlNonOsRetVal_t cc3100_nonos::_SlNonOsMainLoopTask(void)
+{
+    int8_t i = 0;
+      	
+#ifndef SL_TINY_EXT
+	for (i=0 ; i<NONOS_MAX_SPAWN_ENTRIES ; i++)
+#endif
+	{
+		_SlNonOsSpawnEntry_t* pE = &g_SlNonOsCB.SpawnEntries[i];
+		_SlSpawnEntryFunc_t 		pF = pE->pEntry;
+		
+		if (NULL != pF)
+		{
+            if(RxIrqCnt != (g_pCB)->RxDoneCnt) {                
+                _SlDrvMsgReadSpawnCtx(0);
+                //pF(0);/*(pValue);*//*Function pointer*/                
+        }
+            pE->pEntry = NULL;
+			pE->pValue = NULL;
+		}
+	}
+        
+        return NONOS_RET_OK;
+}
+/*
+_SlNonOsRetVal_t cc3100_nonos::sl_SyncObjCreate(_SlNonOsSemObj_t* pSemObj, _SlNonOsSemObj_t Value){//_SlNonOsSemSet(pSyncObj,NON_OS_SYNC_OBJ_CLEAR_VALUE)
+    
+    *pSemObj = Value;
+    return NONOS_RET_OK;
+
+}
+*/
+_SlNonOsRetVal_t cc3100_nonos::sl_SyncObjDelete(_SlNonOsSemObj_t* pSemObj, _SlNonOsSemObj_t Value){//_SlNonOsSemSet(pSyncObj,0)
+    
+    *pSemObj = Value;
+    return NONOS_RET_OK;
+}
+
+_SlNonOsRetVal_t cc3100_nonos::sl_SyncObjSignal(_SlNonOsSemObj_t* pSemObj, _SlNonOsSemObj_t Value){//_SlNonOsSemSet(pSyncObj,NON_OS_SYNC_OBJ_SIGNAL_VALUE)
+
+    *pSemObj = Value;
+    return NONOS_RET_OK;
+}
+    
+_SlNonOsRetVal_t cc3100_nonos::sl_SyncObjSignalFromIRQ(_SlNonOsSemObj_t* pSemObj, _SlNonOsSemObj_t Value){//_SlNonOsSemSet(pSyncObj,NON_OS_SYNC_OBJ_SIGNAL_VALUE)
+
+        *pSemObj = Value;
+        return NONOS_RET_OK;
+}
+/*    
+_SlNonOsRetVal_t cc3100_nonos::sl_LockObjCreate(_SlNonOsSemObj_t* pSemObj, _SlNonOsSemObj_t Value){//_SlNonOsSemSet(pLockObj,NON_OS_LOCK_OBJ_UNLOCK_VALUE)
+
+        *pSemObj = Value;
+        return NONOS_RET_OK;
+}        
+*/        
+_SlNonOsRetVal_t cc3100_nonos::sl_LockObjDelete(_SlNonOsSemObj_t* pSemObj, _SlNonOsSemObj_t Value){//_SlNonOsSemSet(pLockObj,0)
+
+    *pSemObj = Value;
+    return NONOS_RET_OK;
+}    
+           
+_SlNonOsRetVal_t cc3100_nonos::sl_LockObjUnlock(_SlNonOsSemObj_t* pSemObj, _SlNonOsSemObj_t Value){//_SlNonOsSemSet(pLockObj,NON_OS_LOCK_OBJ_UNLOCK_VALUE)
+
+    *pSemObj = Value;
+    return NONOS_RET_OK;
+}    
+    
+_SlNonOsRetVal_t cc3100_nonos::sl_SyncObjWait(_SlNonOsSemObj_t* pSyncObj, _SlNonOsSemObj_t WaitValue, _SlNonOsSemObj_t SetValue, _SlNonOsTime_t Timeout){//_SlNonOsSemGet(pSyncObj,NON_OS_SYNC_OBJ_SIGNAL_VALUE,NON_OS_SYNC_OBJ_CLEAR_VALUE,Timeout)
+
+#ifdef _SlSyncWaitLoopCallback
+    _SlNonOsTime_t timeOutRequest = Timeout; 
+#endif     
+    
+    while (Timeout > 0) {
+        if (WaitValue == *pSyncObj) {
+            *pSyncObj = SetValue;            
+            break;
+        }
+        if (Timeout != NONOS_WAIT_FOREVER) {
+            Timeout--;
+        }
+        _SlNonOsMainLoopTask();
+        
+#ifdef _SlSyncWaitLoopCallback
+        if( (__NON_OS_SYNC_OBJ_SIGNAL_VALUE == WaitValue) && (timeOutRequest != NONOS_NO_WAIT) ) {
+            if (WaitValue == *pSyncObj) {
+                *pSyncObj = SetValue;
+                break;
+            }
+            _SlSyncWaitLoopCallback();
+        }
+#endif
+
+    }
+
+    if (0 == Timeout) {        
+        return NONOS_RET_ERR;
+    } else {        
+        return NONOS_RET_OK;
+    }
+}
+
+_SlNonOsRetVal_t cc3100_nonos::sl_LockObjLock(_SlNonOsSemObj_t* pSyncObj, _SlNonOsSemObj_t WaitValue, _SlNonOsSemObj_t SetValue, _SlNonOsTime_t Timeout){//_SlNonOsSemGet(pLockObj,NON_OS_LOCK_OBJ_UNLOCK_VALUE,NON_OS_LOCK_OBJ_LOCK_VALUE,Timeout)
+
+#ifdef _SlSyncWaitLoopCallback
+    _SlNonOsTime_t timeOutRequest = Timeout; 
+#endif    
+    
+    while (Timeout > 0) {
+        if (WaitValue == *pSyncObj) {
+            *pSyncObj = SetValue;            
+            break;
+        }
+        if (Timeout != NONOS_WAIT_FOREVER) {
+            Timeout--;
+        }
+        _SlNonOsMainLoopTask();
+        
+#ifdef _SlSyncWaitLoopCallback
+        if( (__NON_OS_SYNC_OBJ_SIGNAL_VALUE == WaitValue) && (timeOutRequest != NONOS_NO_WAIT) ) {
+            if (WaitValue == *pSyncObj) {
+                *pSyncObj = SetValue;
+                break;
+            }
+            _SlSyncWaitLoopCallback();
+        }
+#endif
+
+    }
+
+    if (0 == Timeout) {        
+        return NONOS_RET_ERR;
+    } else {        
+        return NONOS_RET_OK;
+    }
+}
+
+}//namespace mbed_cc3100
+
+#endif /*(SL_PLATFORM != SL_PLATFORM_NON_OS)*/
+
+
+
+
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_nonos.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_nonos.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,332 @@
+/*
+ * nonos.h - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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.
+ *
+*/
+
+#ifndef NONOS_H_
+#define	NONOS_H_
+
+#include "cc3100_simplelink.h"
+	
+/*****************************************************************************/
+/* Macro declarations                                                        */
+/*****************************************************************************/
+
+#ifndef SL_PLATFORM_MULTI_THREADED
+
+namespace mbed_cc3100 {
+
+/* This function call the user defined function, if defined, from the sync wait loop  */
+/* The use case of this function is to allow nonos system to call a user function to put the device into sleep */
+/* The wake up should be activated after getting an interrupt from the device to Host */
+/* The user function must return without blocking to prevent a delay on the event handling */
+/*
+#define _SlSyncWaitLoopCallback  UserSleepFunction
+*/
+
+const uint8_t NONOS_WAIT_FOREVER   			 =	0xFF;
+const uint8_t NONOS_NO_WAIT        			 =	0x00;
+
+const uint8_t NONOS_RET_OK                   =  (0);
+const int8_t  NONOS_RET_ERR                  =  (0xFF);
+const uint8_t OSI_OK                         =  NONOS_RET_OK;
+
+const uint8_t NON_OS_SYNC_OBJ_CLEAR_VALUE	 =	0x11;
+const uint8_t NON_OS_SYNC_OBJ_SIGNAL_VALUE	 =	0x22;
+const uint8_t NON_OS_LOCK_OBJ_UNLOCK_VALUE	 =	0x33;
+const uint8_t NON_OS_LOCK_OBJ_LOCK_VALUE	 =	0x44;
+
+#define _SlTime_t               _SlNonOsTime_t
+
+#define _SlSyncObj_t            _SlNonOsSemObj_t
+
+#define _SlLockObj_t            _SlNonOsSemObj_t
+
+const uint8_t SL_OS_WAIT_FOREVER   =   NONOS_WAIT_FOREVER;
+
+const uint8_t SL_OS_RET_CODE_OK    =   NONOS_RET_OK;
+
+const uint8_t SL_OS_NO_WAIT        =   NONOS_NO_WAIT;
+
+
+    /*****************************************************************************/
+    /* Function prototypes                                                       */
+    /*****************************************************************************/
+
+    /*!
+    	\brief 	This function creates a sync object
+
+    	The sync object is used for synchronization between different thread or ISR and
+    	a thread.
+
+    	\param	pSyncObj	-	pointer to the sync object control block
+
+    	\return upon successful creation the function return 0
+    			Otherwise, a negative value indicating the error code shall be returned
+    	\note
+    	\warning
+    */
+#define _SlNonOsSyncObjCreate(pSyncObj)			_SlNonOsSemSet(pSyncObj,NON_OS_SYNC_OBJ_CLEAR_VALUE)
+
+    /*!
+    	\brief 	This function deletes a sync object
+
+    	\param	pSyncObj	-	pointer to the sync object control block
+
+    	\return upon successful deletion the function should return 0
+    			Otherwise, a negative value indicating the error code shall be returned
+    	\note
+    	\warning
+    */
+//#define _SlNonOsSyncObjDelete(pSyncObj)			_SlNonOsSemSet(pSyncObj,0)
+
+    /*!
+    	\brief 		This function generates a sync signal for the object.
+
+    	All suspended threads waiting on this sync object are resumed
+
+    	\param		pSyncObj	-	pointer to the sync object control block
+
+    	\return 	upon successful signaling the function should return 0
+    				Otherwise, a negative value indicating the error code shall be returned
+    	\note		the function could be called from ISR context
+    	\warning
+    */
+//#define _SlNonOsSyncObjSignal(pSyncObj)			_SlNonOsSemSet(pSyncObj,NON_OS_SYNC_OBJ_SIGNAL_VALUE)
+
+    /*!
+    	\brief 	This function waits for a sync signal of the specific sync object
+
+    	\param	pSyncObj	-	pointer to the sync object control block
+    	\param	Timeout		-	numeric value specifies the maximum number of mSec to
+    							stay suspended while waiting for the sync signal
+    							Currently, the simple link driver uses only two values:
+    								- NONOS_WAIT_FOREVER
+    								- NONOS_NO_WAIT
+
+    	\return upon successful reception of the signal within the timeout window return 0
+    			Otherwise, a negative value indicating the error code shall be returned
+    	\note
+    	\warning
+    */
+//#define _SlNonOsSyncObjWait(pSyncObj , Timeout)	_SlNonOsSemGet(pSyncObj,NON_OS_SYNC_OBJ_SIGNAL_VALUE,NON_OS_SYNC_OBJ_CLEAR_VALUE,Timeout)
+
+    /*!
+    	\brief 	This function clears a sync object
+
+    	\param	pSyncObj	-	pointer to the sync object control block
+
+    	\return upon successful clearing the function should return 0
+    			Otherwise, a negative value indicating the error code shall be returned
+    	\note
+    	\warning
+    */
+//#define _SlNonOsSyncObjClear(pSyncObj)			_SlNonOsSemSet(pSyncObj,NON_OS_SYNC_OBJ_CLEAR_VALUE)
+
+    /*!
+    	\brief 	This function creates a locking object.
+
+    	The locking object is used for protecting a shared resources between different
+    	threads.
+
+    	\param	pLockObj	-	pointer to the locking object control block
+
+    	\return upon successful creation the function should return 0
+    			Otherwise, a negative value indicating the error code shall be returned
+    	\note
+    	\warning
+    */
+#define _SlNonOsLockObjCreate(pLockObj)			_SlNonOsSemSet(pLockObj,NON_OS_LOCK_OBJ_UNLOCK_VALUE)
+
+    /*!
+    	\brief 	This function deletes a locking object.
+
+    	\param	pLockObj	-	pointer to the locking object control block
+
+    	\return upon successful deletion the function should return 0
+    			Otherwise, a negative value indicating the error code shall be returned
+    	\note
+    	\warning
+    */
+//#define _SlNonOsLockObjDelete(pLockObj)			_SlNonOsSemSet(pLockObj,0)
+
+    /*!
+    	\brief 	This function locks a locking object.
+
+    	All other threads that call this function before this thread calls
+    	the _SlNonOsLockObjUnlock would be suspended
+
+    	\param	pLockObj	-	pointer to the locking object control block
+    	\param	Timeout		-	numeric value specifies the maximum number of mSec to
+    							stay suspended while waiting for the locking object
+    							Currently, the simple link driver uses only two values:
+    								- NONOS_WAIT_FOREVER
+    								- NONOS_NO_WAIT
+
+
+    	\return upon successful reception of the locking object the function should return 0
+    			Otherwise, a negative value indicating the error code shall be returned
+    	\note
+    	\warning
+    */
+//#define _SlNonOsLockObjLock(pLockObj , Timeout)	_SlNonOsSemGet(pLockObj,NON_OS_LOCK_OBJ_UNLOCK_VALUE,NON_OS_LOCK_OBJ_LOCK_VALUE,Timeout)
+
+    /*!
+    	\brief 	This function unlock a locking object.
+
+    	\param	pLockObj	-	pointer to the locking object control block
+
+    	\return upon successful unlocking the function should return 0
+    			Otherwise, a negative value indicating the error code shall be returned
+    	\note
+    	\warning
+    */
+//#define _SlNonOsLockObjUnlock(pLockObj)			_SlNonOsSemSet(pLockObj,NON_OS_LOCK_OBJ_UNLOCK_VALUE)
+
+/*****************************************************************************
+
+    Overwrite SimpleLink driver OS adaptation functions
+
+
+ *****************************************************************************/
+
+#undef sl_SyncObjCreate
+#define sl_SyncObjCreate(pSyncObj,pName)           _SlNonOsSemSet(pSyncObj,NON_OS_SYNC_OBJ_CLEAR_VALUE)
+
+#undef sl_LockObjCreate
+#define sl_LockObjCreate(pLockObj,pName)            _SlNonOsSemSet(pLockObj,NON_OS_LOCK_OBJ_UNLOCK_VALUE)
+/*
+#undef sl_Spawn
+#define sl_Spawn(pEntry,pValue,flags)               _nonos._SlNonOsSpawn(pEntry,pValue,flags)
+
+#undef _SlTaskEntry
+#define _SlTaskEntry                                _nonos._SlNonOsMainLoopTask
+*/
+	
+/*!
+	\brief type definition for the return values of this adaptation layer
+*/
+typedef int8_t _SlNonOsRetVal_t;
+
+/*!
+	\brief type definition for a time value
+*/
+typedef uint8_t _SlNonOsTime_t;
+
+/*!
+	\brief 	type definition for a sync object container
+
+	Sync object is object used to synchronize between two threads or thread and interrupt handler.
+	One thread is waiting on the object and the other thread send a signal, which then
+	release the waiting thread.
+	The signal must be able to be sent from interrupt context.
+	This object is generally implemented by binary semaphore or events.
+*/
+typedef uint8_t _SlNonOsSemObj_t;	
+	
+class cc3100_driver;
+
+class cc3100_nonos
+{
+
+public:
+
+    cc3100_nonos(cc3100_driver &driver);
+
+    ~cc3100_nonos();
+
+    /*!
+    	\brief 	This function call the pEntry callback from a different context
+
+    	\param	pEntry		-	pointer to the entry callback function
+
+    	\param	pValue		- 	pointer to any type of memory structure that would be
+    							passed to pEntry callback from the execution thread.
+
+    	\param	flags		- 	execution flags - reserved for future usage
+
+    	\return upon successful registration of the spawn the function return 0
+    			(the function is not blocked till the end of the execution of the function
+    			and could be returned before the execution is actually completed)
+    			Otherwise, a negative value indicating the error code shall be returned
+    	\note
+    	\warning
+    */
+    _SlNonOsRetVal_t _SlNonOsSpawn(_SlSpawnEntryFunc_t pEntry , void* pValue , uint32_t flags);
+
+
+    /*!
+    	\brief 	This function must be called from the main loop in non-os paltforms
+
+    	\param	None
+
+    	\return 0 - No more activities
+    			1 - Activity still in progress
+    	\note
+    	\warning
+    */
+    _SlNonOsRetVal_t _SlNonOsMainLoopTask(void);
+
+    _SlNonOsRetVal_t _SlNonOsSemGet(_SlNonOsSemObj_t* pSyncObj, _SlNonOsSemObj_t WaitValue, _SlNonOsSemObj_t SetValue, _SlNonOsTime_t Timeout);
+    _SlNonOsRetVal_t _SlNonOsSemSet(_SlNonOsSemObj_t* pSemObj , _SlNonOsSemObj_t Value);
+//    _SlNonOsRetVal_t _SlNonOsSpawn(_SlSpawnEntryFunc_t pEntry , void* pValue , uint32_t flags);
+//    _SlNonOsRetVal_t sl_SyncObjCreate(_SlNonOsSemObj_t* pSemObj, _SlNonOsSemObj_t NON_OS_SYNC_OBJ_CLEAR_VALUE);
+    _SlNonOsRetVal_t sl_SyncObjDelete(_SlNonOsSemObj_t* pSemObj, _SlNonOsSemObj_t );
+    _SlNonOsRetVal_t sl_SyncObjSignal(_SlNonOsSemObj_t* pSemObj, _SlNonOsSemObj_t NON_OS_SYNC_OBJ_SIGNAL_VALUE);
+    _SlNonOsRetVal_t sl_SyncObjSignalFromIRQ(_SlNonOsSemObj_t* pSemObj, _SlNonOsSemObj_t NON_OS_SYNC_OBJ_SIGNAL_VALUE);
+//    _SlNonOsRetVal_t sl_LockObjCreate(_SlNonOsSemObj_t* pSemObj, _SlNonOsSemObj_t NON_OS_LOCK_OBJ_UNLOCK_VALUE);
+    _SlNonOsRetVal_t sl_LockObjDelete(_SlNonOsSemObj_t* pSemObj, _SlNonOsSemObj_t );
+    _SlNonOsRetVal_t sl_LockObjUnlock(_SlNonOsSemObj_t* pSemObj, _SlNonOsSemObj_t NON_OS_LOCK_OBJ_UNLOCK_VALUE);
+    _SlNonOsRetVal_t sl_SyncObjWait(_SlNonOsSemObj_t* pSyncObj, _SlNonOsSemObj_t NON_OS_SYNC_OBJ_SIGNAL_VALUE, _SlNonOsSemObj_t NON_OS_SYNC_OBJ_CLEAR_VALUE, _SlNonOsTime_t Timeout);
+    _SlNonOsRetVal_t sl_LockObjLock(_SlNonOsSemObj_t* pSyncObj, _SlNonOsSemObj_t NON_OS_LOCK_OBJ_UNLOCK_VALUE, _SlNonOsSemObj_t NON_OS_LOCK_OBJ_LOCK_VALUE, _SlNonOsTime_t Timeout);
+    
+
+#if (defined(_SlSyncWaitLoopCallback))
+    void _SlSyncWaitLoopCallback(void);
+#endif
+
+private:
+
+    cc3100_driver &_driver;
+
+};//class
+
+}//namespace mbed_cc3100
+
+#endif /* !SL_PLATFORM_MULTI_THREADED */
+
+
+
+#endif
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_objInclusion.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_objInclusion.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,314 @@
+/*
+ * objInclusion.h - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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.
+ *
+*/
+#ifndef OBJINCLUSION_H_
+#define OBJINCLUSION_H_
+
+
+#include "cc3100_simplelink.h"
+
+
+/******************************************************************************
+
+ For future use
+
+*******************************************************************************/
+
+#define __inln        	/* if inline functions requiered: #define __inln inline */
+
+#define SL_DEVICE      	/* Device silo is currently always mandatory */
+
+
+
+/******************************************************************************
+
+ Qualifiers for package customizations
+
+*******************************************************************************/
+
+#if defined (SL_DEVICE)
+#define __dev   1
+#else
+#define __dev   0
+#endif
+
+#if defined (SL_DEVICE) && defined (SL_INC_EXT_API)
+#define __dev__ext   1
+#else
+#define __dev__ext   0
+#endif
+
+
+#if (!defined (SL_PLATFORM_MULTI_THREADED)) || (!defined (SL_PLATFORM_EXTERNAL_SPAWN))
+#define __int__spwn     1
+#else
+#define __int__spwn     0
+#endif
+
+#if defined (SL_INC_NET_APP_PKG)
+#define __nap    1
+#else
+#define __nap    0
+#endif
+
+#if defined  (SL_INC_NET_APP_PKG) && defined (SL_INC_SOCK_CLIENT_SIDE_API)
+#define __nap__clt  1
+#else
+#define __nap__clt  0
+#endif
+
+#if defined  (SL_INC_NET_APP_PKG) && defined (SL_INC_EXT_API)
+#define __nap__ext   1
+#else
+#define __nap__ext   0
+#endif
+
+#if defined (SL_INC_NET_CFG_PKG)
+#define __ncg        1
+#else
+#define __ncg        0
+#endif
+
+#if defined (SL_INC_NET_CFG_PKG) && defined (SL_INC_EXT_API)
+#define __ncg__ext        1
+#else
+#define __ncg__ext        0
+#endif
+
+#if defined (SL_INC_NVMEM_PKG)
+#define __nvm       1
+#else
+#define __nvm       0
+#endif
+
+#if defined (SL_INC_SOCKET_PKG)
+#define __sck        1
+#else
+#define __sck        0
+#endif
+
+#if defined  (SL_INC_SOCKET_PKG) && defined (SL_INC_EXT_API)
+#define __sck__ext    1
+#else
+#define __sck__ext    0
+#endif
+
+#if defined  (SL_INC_SOCKET_PKG) && defined (SL_INC_SOCK_SERVER_SIDE_API)
+#define __sck__srv     1
+#else
+#define __sck__srv     0
+#endif
+
+#if defined  (SL_INC_SOCKET_PKG) && defined (SL_INC_SOCK_CLIENT_SIDE_API)
+#define __sck__clt      1
+#else
+#define __sck__clt      0
+#endif
+
+#if defined  (SL_INC_SOCKET_PKG) && defined (SL_INC_SOCK_RECV_API)
+#define __sck__rcv     1
+#else
+#define __sck__rcv     0
+#endif
+
+#if defined  (SL_INC_SOCKET_PKG) && defined (SL_INC_SOCK_SEND_API)
+#define __sck__snd      1
+#else
+#define __sck__snd      0
+#endif
+
+#if defined (SL_INC_WLAN_PKG)
+#define __wln           1
+#else
+#define __wln           0
+#endif
+
+#if defined  (SL_INC_WLAN_PKG) && defined (SL_INC_EXT_API)
+#define __wln__ext      1
+#else
+#define __wln__ext      0
+#endif
+
+/* The return 1 is the function need to be included in the output */
+#define _SL_INCLUDE_FUNC(Name)		(_SL_INC_##Name)
+
+/* Driver */
+#define _SL_INC_sl_NetAppStart          __nap__ext
+#define _SL_INC_sl_NetAppStop           __nap__ext
+
+#define _SL_INC_sl_NetAppDnsGetHostByName   __nap__clt
+
+
+#define _SL_INC_sl_NetAppDnsGetHostByService			__nap__ext
+#define _SL_INC_sl_NetAppMDNSRegisterService		    __nap__ext
+#define _SL_INC_sl_NetAppMDNSUnRegisterService		    __nap__ext
+#define _SL_INC_sl_NetAppMDNSRegisterUnregisterService	__nap__ext
+#define _SL_INC_sl_NetAppGetServiceList	                __nap__ext
+	
+
+#define _SL_INC_sl_DnsGetHostByAddr     __nap__ext
+#define _SL_INC_sl_NetAppPingStart      __nap__ext
+#define _SL_INC_sl_NetAppPingReport     __nap__ext
+#define _SL_INC_sl_NetAppSet            __nap__ext
+#define _SL_INC_sl_NetAppGet            __nap__ext
+
+/* FS */
+#define _SL_INC_sl_FsOpen               __nvm
+
+#define _SL_INC_sl_FsClose              __nvm
+
+#define _SL_INC_sl_FsRead               __nvm
+
+#define _SL_INC_sl_FsWrite              __nvm
+
+#define _SL_INC_sl_FsGetInfo            __nvm
+
+#define _SL_INC_sl_FsDel                __nvm
+
+/* netcfg */
+#define _SL_INC_sl_MacAdrrSet           __ncg
+
+#define _SL_INC_sl_MacAdrrGet           __ncg
+
+#define _SL_INC_sl_NetCfgGet            __ncg
+
+#define _SL_INC_sl_NetCfgSet            __ncg
+
+
+/* socket */
+#define _SL_INC_sl_Socket               __sck
+
+#define _SL_INC_sl_Close                __sck
+
+#define _SL_INC_sl_Accept               __sck__srv
+
+#define _SL_INC_sl_Bind                 __sck
+
+#define _SL_INC_sl_Listen               __sck__srv
+
+#define _SL_INC_sl_Connect              __sck__clt
+
+#define _SL_INC_sl_Select               __sck
+
+#define _SL_INC_sl_SetSockOpt           __sck
+
+#define _SL_INC_sl_GetSockOpt           __sck__ext
+
+#define _SL_INC_sl_Recv                 __sck__rcv
+
+#define _SL_INC_sl_RecvFrom             __sck__rcv
+
+#define _SL_INC_sl_Write                __sck__snd
+
+#define _SL_INC_sl_Send                 __sck__snd
+
+#define _SL_INC_sl_SendTo               __sck__snd
+
+#define _SL_INC_sl_Htonl                __sck
+
+#define _SL_INC_sl_Htons                __sck
+
+/* wlan */
+#define _SL_INC_sl_WlanConnect           __wln__ext
+
+#define _SL_INC_sl_WlanDisconnect        __wln__ext
+
+#define _SL_INC_sl_WlanProfileAdd        __wln__ext
+
+#define _SL_INC_sl_WlanProfileGet        __wln__ext
+
+#define _SL_INC_sl_WlanProfileDel        __wln__ext
+
+#define _SL_INC_sl_WlanPolicySet         __wln__ext
+
+#define _SL_INC_sl_WlanPolicyGet         __wln__ext
+
+#define _SL_INC_sl_WlanGetNetworkList    __wln__ext
+
+#define _SL_INC_sl_WlanRxFilterAdd       __wln__ext
+
+#define _SL_INC_sl_WlanRxFilterSet       __wln__ext
+
+#define _SL_INC_sl_WlanRxFilterGet       __wln__ext
+
+#define _SL_INC_sl_SmartConfigStart      __wln
+
+#define _SL_INC_sl_SmartConfigOptSet     __wln__ext
+
+
+#define _SL_INC_sl_WlanSmartConfigStart  __wln
+
+#define _SL_INC_sl_WlanSmartConfigStop   __wln
+
+#define _SL_INC_sl_WlanSetMode			 __wln
+
+#define _SL_INC_sl_WlanSet			     __wln
+
+#define _SL_INC_sl_WlanGet			     __wln
+
+#define _SL_INC_sl_SmartConfigOptSet     __wln__ext
+
+#define _SL_INC_sl_SmartConfigOptGet     __wln__ext
+
+#define  _SL_INC_sl_WlanRxStatStart      __wln__ext
+
+#define _SL_INC_sl_WlanRxStatStop        __wln__ext
+
+#define _SL_INC_sl_WlanRxStatGet         __wln__ext
+
+
+/* device */
+#define _SL_INC_sl_Task                  __int__spwn
+
+#define _SL_INC_sl_Start                 __dev
+
+#define _SL_INC_sl_Stop                  __dev
+
+#define _SL_INC_sl_StatusGet             __dev
+
+#ifdef SL_IF_TYPE_UART
+#define _SL_INC_sl_UartSetMode			 __dev__ext
+#endif
+
+#define _SL_INC_sl_EventMaskGet          __dev__ext
+
+#define _SL_INC_sl_EventMaskSet          __dev__ext
+
+#define _SL_INC_sl_DevGet			     __dev__ext
+
+#define _SL_INC_sl_DevSet			     __dev__ext
+
+#endif /*OBJINCLUSION_H_  */
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_protocol.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_protocol.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,855 @@
+/*
+ * protocol.h - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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.
+ *
+*/
+
+/*******************************************************************************\
+*
+*   FILE NAME:      protocol.h
+*
+*   DESCRIPTION:    Constant and data structure definitions and function
+*                   prototypes for the SL protocol module, which implements
+*                   processing of SimpleLink Commands.
+*
+*   AUTHOR:
+*
+\*******************************************************************************/
+
+#ifndef SL_PROTOCOL_TYPES_H_
+#define SL_PROTOCOL_TYPES_H_
+
+namespace mbed_cc3100 {
+
+/****************************************************************************
+**
+**  User I/F pools definitions
+**
+****************************************************************************/
+
+/****************************************************************************
+**
+**  Definitions for SimpleLink Commands
+**
+****************************************************************************/
+
+
+/* pattern for LE 8/16/32 or BE*/
+#define H2N_SYNC_PATTERN     {0xBBDDEEFF,0x4321,0x34,0x12}
+#define H2N_CNYS_PATTERN     {0xBBDDEEFF,0x8765,0x78,0x56}
+
+const uint32_t H2N_DUMMY_PATTERN         =  (uint32_t)0xFFFFFFFF;
+const uint32_t N2H_SYNC_PATTERN          =  (uint32_t)0xABCDDCBA;
+const uint32_t SYNC_PATTERN_LEN          =  (uint32_t)sizeof(uint32_t);
+const uint32_t UART_SET_MODE_MAGIC_CODE  =  (uint32_t)0xAA55AA55;
+#define SPI_16BITS_BUG(pattern)     (uint32_t)((uint32_t)pattern & (uint32_t)0xFFFF7FFF)
+#define SPI_8BITS_BUG(pattern)      (uint32_t)((uint32_t)pattern & (uint32_t)0xFFFFFF7F)
+
+
+
+typedef struct {
+    uint16_t Opcode;
+    uint16_t Len;
+} _SlGenericHeader_t;
+
+
+typedef struct {
+    uint32_t  Long;
+    uint16_t  Short;
+    uint8_t  Byte1;
+    uint8_t  Byte2;
+} _SlSyncPattern_t;
+
+typedef _SlGenericHeader_t _SlCommandHeader_t;
+
+typedef struct {
+    _SlGenericHeader_t  GenHeader;
+    uint8_t               TxPoolCnt;
+    uint8_t               DevStatus;
+    uint8_t               SocketTXFailure;
+    uint8_t               SocketNonBlocking;
+} _SlResponseHeader_t;
+
+#define _SL_RESP_SPEC_HDR_SIZE (sizeof(_SlResponseHeader_t) - sizeof(_SlGenericHeader_t))
+#define _SL_RESP_HDR_SIZE       sizeof(_SlResponseHeader_t)
+#define _SL_CMD_HDR_SIZE        sizeof(_SlCommandHeader_t)
+
+#define _SL_RESP_ARGS_START(_pMsg) (((_SlResponseHeader_t *)(_pMsg)) + 1)
+
+/* Used only in NWP! */
+typedef struct {
+    _SlCommandHeader_t  sl_hdr;
+    uint8_t   func_args_start;
+} T_SCMD;
+
+
+const uint8_t WLAN_CONN_STATUS_BIT  =  0x01;
+const uint8_t EVENTS_Q_STATUS_BIT   =  0x02;
+const uint8_t PENDING_RCV_CMD_BIT   =  0x04;
+const uint8_t FW_BUSY_PACKETS_BIT   =  0x08;
+
+const uint32_t INIT_STA_OK          =  0x11111111;
+const uint32_t INIT_STA_ERR         =  0x22222222;
+const uint32_t INIT_AP_OK           =  0x33333333;
+const uint32_t INIT_AP_ERR          =  0x44444444;
+const uint32_t INIT_P2P_OK          =  0x55555555;
+const uint32_t INIT_P2P_ERR         =  0x66666666;
+
+/****************************************************************************
+**  OPCODES
+****************************************************************************/
+const uint16_t SL_IPV4_IPV6_OFFSET                        =     ( 9 );
+const uint16_t SL_OPCODE_IPV4							  =     ( 0x0 << SL_IPV4_IPV6_OFFSET );
+const uint16_t SL_OPCODE_IPV6							  =     ( 0x1 << SL_IPV4_IPV6_OFFSET );
+
+const uint16_t SL_SYNC_ASYNC_OFFSET                       =     ( 10 );
+const uint16_t SL_OPCODE_SYNC							  =     (0x1 << SL_SYNC_ASYNC_OFFSET );
+const uint16_t SL_OPCODE_SILO_OFFSET                      =     ( 11 );
+const uint16_t SL_OPCODE_SILO_MASK                        =     ( 0xF << SL_OPCODE_SILO_OFFSET );
+const uint16_t SL_OPCODE_SILO_DEVICE                      =     ( 0x0 << SL_OPCODE_SILO_OFFSET );
+const uint16_t SL_OPCODE_SILO_WLAN                        =     ( 0x1 << SL_OPCODE_SILO_OFFSET );
+const uint16_t SL_OPCODE_SILO_SOCKET                      =     ( 0x2 << SL_OPCODE_SILO_OFFSET );
+const uint16_t SL_OPCODE_SILO_NETAPP                      =     ( 0x3 << SL_OPCODE_SILO_OFFSET );
+const uint16_t SL_OPCODE_SILO_NVMEM                       =     ( 0x4 << SL_OPCODE_SILO_OFFSET );
+const uint16_t SL_OPCODE_SILO_NETCFG                      =     ( 0x5 << SL_OPCODE_SILO_OFFSET );
+
+const uint16_t SL_FAMILY_SHIFT                            =     (0x4);
+const uint16_t SL_FLAGS_MASK                              =     (0xF);
+
+const uint16_t SL_OPCODE_DEVICE_INITCOMPLETE                         =      	0x0008;
+const uint16_t SL_OPCODE_DEVICE_ABORT			                     =          0x000C;
+const uint16_t SL_OPCODE_DEVICE_STOP_COMMAND                         =      	0x8473;
+const uint16_t SL_OPCODE_DEVICE_STOP_RESPONSE                        =      	0x0473;
+const uint16_t SL_OPCODE_DEVICE_STOP_ASYNC_RESPONSE                  =      	0x0073;
+const uint16_t SL_OPCODE_DEVICE_DEVICEASYNCDUMMY                     =      	0x0063;
+
+const uint16_t SL_OPCODE_DEVICE_VERSIONREADCOMMAND	                 =          0x8470;
+const uint16_t SL_OPCODE_DEVICE_VERSIONREADRESPONSE	                 =          0x0470;
+const uint16_t SL_OPCODE_DEVICE_DEVICEASYNCFATALERROR                =      	0x0078;
+const uint16_t SL_OPCODE_WLAN_WLANCONNECTCOMMAND                     =      	0x8C80;
+const uint16_t SL_OPCODE_WLAN_WLANCONNECTRESPONSE                    =      	0x0C80;
+const uint16_t SL_OPCODE_WLAN_WLANASYNCCONNECTEDRESPONSE             =      	0x0880;
+const uint16_t SL_OPCODE_WLAN_P2P_DEV_FOUND                          =          0x0830;
+const uint16_t SL_OPCODE_WLAN_CONNECTION_FAILED                      =          0x0831;
+const uint16_t SL_OPCODE_WLAN_P2P_NEG_REQ_RECEIVED                   =          0x0832;
+
+const uint16_t SL_OPCODE_WLAN_WLANDISCONNECTCOMMAND                  =      	0x8C81;
+const uint16_t SL_OPCODE_WLAN_WLANDISCONNECTRESPONSE                 =      	0x0C81;
+const uint16_t SL_OPCODE_WLAN_WLANASYNCDISCONNECTEDRESPONSE          =      	0x0881;
+const uint16_t SL_OPCODE_WLAN_WLANCONNECTEAPCOMMAND                  =      	0x8C82;
+const uint16_t SL_OPCODE_WLAN_WLANCONNECTEAPCRESPONSE                =      	0x0C82;
+const uint16_t SL_OPCODE_WLAN_PROFILEADDCOMMAND                      =      	0x8C83;
+const uint16_t SL_OPCODE_WLAN_PROFILEADDRESPONSE                     =      	0x0C83;
+const uint16_t SL_OPCODE_WLAN_PROFILEGETCOMMAND                      =      	0x8C84;
+const uint16_t SL_OPCODE_WLAN_PROFILEGETRESPONSE                     =      	0x0C84;
+const uint16_t SL_OPCODE_WLAN_PROFILEDELCOMMAND                      =      	0x8C85;
+const uint16_t SL_OPCODE_WLAN_PROFILEDELRESPONSE                     =      	0x0C85;
+const uint16_t SL_OPCODE_WLAN_POLICYSETCOMMAND                       =      	0x8C86;
+const uint16_t SL_OPCODE_WLAN_POLICYSETRESPONSE                      =      	0x0C86;
+const uint16_t SL_OPCODE_WLAN_POLICYGETCOMMAND                       =      	0x8C87;
+const uint16_t SL_OPCODE_WLAN_POLICYGETRESPONSE                      =      	0x0C87;
+const uint16_t SL_OPCODE_WLAN_FILTERADD                              =      	0x8C88;
+const uint16_t SL_OPCODE_WLAN_FILTERADDRESPONSE                      =      	0x0C88;
+const uint16_t SL_OPCODE_WLAN_FILTERGET                              =      	0x8C89;
+const uint16_t SL_OPCODE_WLAN_FILTERGETRESPONSE                      =      	0x0C89;
+const uint16_t SL_OPCODE_WLAN_FILTERDELETE                           =      	0x8C8A;
+const uint16_t SL_OPCODE_WLAN_FILTERDELETERESPOSNE                   =      	0x0C8A;
+const uint16_t SL_OPCODE_WLAN_WLANGETSTATUSCOMMAND                   =      	0x8C8F;
+const uint16_t SL_OPCODE_WLAN_WLANGETSTATUSRESPONSE                  =      	0x0C8F;
+const uint16_t SL_OPCODE_WLAN_STARTTXCONTINUESCOMMAND                =      	0x8CAA;
+const uint16_t SL_OPCODE_WLAN_STARTTXCONTINUESRESPONSE               =      	0x0CAA;
+const uint16_t SL_OPCODE_WLAN_STOPTXCONTINUESCOMMAND                 =      	0x8CAB;
+const uint16_t SL_OPCODE_WLAN_STOPTXCONTINUESRESPONSE                =      	0x0CAB;
+const uint16_t SL_OPCODE_WLAN_STARTRXSTATCOMMAND                     =      	0x8CAC;
+const uint16_t SL_OPCODE_WLAN_STARTRXSTATRESPONSE                    =      	0x0CAC;
+const uint16_t SL_OPCODE_WLAN_STOPRXSTATCOMMAND                      =      	0x8CAD;
+const uint16_t SL_OPCODE_WLAN_STOPRXSTATRESPONSE                     =      	0x0CAD;
+const uint16_t SL_OPCODE_WLAN_GETRXSTATCOMMAND                       =      	0x8CAF;
+const uint16_t SL_OPCODE_WLAN_GETRXSTATRESPONSE                      =      	0x0CAF;
+const uint16_t SL_OPCODE_WLAN_POLICYSETCOMMANDNEW                    =      	0x8CB0;
+const uint16_t SL_OPCODE_WLAN_POLICYSETRESPONSENEW                   =      	0x0CB0;
+const uint16_t SL_OPCODE_WLAN_POLICYGETCOMMANDNEW                    =      	0x8CB1;
+const uint16_t SL_OPCODE_WLAN_POLICYGETRESPONSENEW                   =      	0x0CB1;
+
+const uint16_t SL_OPCODE_WLAN_SMART_CONFIG_START_COMMAND             =      	0x8CB2;
+const uint16_t SL_OPCODE_WLAN_SMART_CONFIG_START_RESPONSE            =      	0x0CB2;
+const uint16_t SL_OPCODE_WLAN_SMART_CONFIG_START_ASYNC_RESPONSE      =      	0x08B2;
+const uint16_t SL_OPCODE_WLAN_SMART_CONFIG_STOP_COMMAND              =      	0x8CB3;
+const uint16_t SL_OPCODE_WLAN_SMART_CONFIG_STOP_RESPONSE             =      	0x0CB3;
+const uint16_t SL_OPCODE_WLAN_SMART_CONFIG_STOP_ASYNC_RESPONSE       =      	0x08B3;
+const uint16_t SL_OPCODE_WLAN_SET_MODE                               =          0x8CB4;
+const uint16_t SL_OPCODE_WLAN_SET_MODE_RESPONSE                      =          0x0CB4;
+const uint16_t SL_OPCODE_WLAN_CFG_SET                                =          0x8CB5;
+const uint16_t SL_OPCODE_WLAN_CFG_SET_RESPONSE                       =          0x0CB5;
+const uint16_t SL_OPCODE_WLAN_CFG_GET                                =          0x8CB6;
+const uint16_t SL_OPCODE_WLAN_CFG_GET_RESPONSE                       =          0x0CB6;
+const uint16_t SL_OPCODE_WLAN_STA_CONNECTED                          =      	0x082E;
+const uint16_t SL_OPCODE_WLAN_STA_DISCONNECTED                       =      	0x082F;
+const uint16_t SL_OPCODE_WLAN_EAP_PROFILEADDCOMMAND                  =          0x8C67;
+const uint16_t SL_OPCODE_WLAN_EAP_PROFILEADDCOMMAND_RESPONSE         =          0x0C67;
+
+const uint16_t SL_OPCODE_SOCKET_SOCKET                               =      	0x9401;
+const uint16_t SL_OPCODE_SOCKET_SOCKETRESPONSE                       =      	0x1401;
+const uint16_t SL_OPCODE_SOCKET_CLOSE                                =      	0x9402;
+const uint16_t SL_OPCODE_SOCKET_CLOSERESPONSE                        =      	0x1402;
+const uint16_t SL_OPCODE_SOCKET_ACCEPT                               =      	0x9403;
+const uint16_t SL_OPCODE_SOCKET_ACCEPTRESPONSE                       =      	0x1403;
+const uint16_t SL_OPCODE_SOCKET_ACCEPTASYNCRESPONSE                  =      	0x1003;
+const uint16_t SL_OPCODE_SOCKET_ACCEPTASYNCRESPONSE_V6               =      	0x1203;
+const uint16_t SL_OPCODE_SOCKET_BIND                                 =      	0x9404;
+const uint16_t SL_OPCODE_SOCKET_BIND_V6                              =      	0x9604;
+const uint16_t SL_OPCODE_SOCKET_BINDRESPONSE                         =      	0x1404;
+const uint16_t SL_OPCODE_SOCKET_LISTEN                               =      	0x9405;
+const uint16_t SL_OPCODE_SOCKET_LISTENRESPONSE                       =      	0x1405;
+const uint16_t SL_OPCODE_SOCKET_CONNECT                              =      	0x9406;
+const uint16_t SL_OPCODE_SOCKET_CONNECT_V6                           =      	0x9606;
+const uint16_t SL_OPCODE_SOCKET_CONNECTRESPONSE                      =      	0x1406;
+const uint16_t SL_OPCODE_SOCKET_CONNECTASYNCRESPONSE                 =      	0x1006;
+const uint16_t SL_OPCODE_SOCKET_SELECT                               =      	0x9407;
+const uint16_t SL_OPCODE_SOCKET_SELECTRESPONSE                       =      	0x1407;
+const uint16_t SL_OPCODE_SOCKET_SELECTASYNCRESPONSE                  =      	0x1007;
+const uint16_t SL_OPCODE_SOCKET_SETSOCKOPT                           =      	0x9408;
+const uint16_t SL_OPCODE_SOCKET_SETSOCKOPTRESPONSE                   =      	0x1408;
+const uint16_t SL_OPCODE_SOCKET_GETSOCKOPT                           =      	0x9409;
+const uint16_t SL_OPCODE_SOCKET_GETSOCKOPTRESPONSE                   =      	0x1409;
+const uint16_t SL_OPCODE_SOCKET_RECV                                 =      	0x940A;
+const uint16_t SL_OPCODE_SOCKET_RECVASYNCRESPONSE                    =      	0x100A;
+const uint16_t SL_OPCODE_SOCKET_RECVFROM                             =      	0x940B;
+const uint16_t SL_OPCODE_SOCKET_RECVFROMASYNCRESPONSE                =      	0x100B;
+const uint16_t SL_OPCODE_SOCKET_RECVFROMASYNCRESPONSE_V6             =      	0x120B;
+const uint16_t SL_OPCODE_SOCKET_SEND                                 =      	0x940C;
+const uint16_t SL_OPCODE_SOCKET_SENDTO                               =      	0x940D;
+const uint16_t SL_OPCODE_SOCKET_SENDTO_V6                            =      	0x960D;
+const uint16_t SL_OPCODE_SOCKET_TXFAILEDASYNCRESPONSE                =      	0x100E;
+const uint16_t SL_OPCODE_SOCKET_SOCKETASYNCEVENT                     =          0x100F;
+const uint16_t SL_OPCODE_NETAPP_START_COMMAND                        =          0x9C0A;
+const uint16_t SL_OPCODE_NETAPP_START_RESPONSE                       =         	0x1C0A;
+const uint16_t SL_OPCODE_NETAPP_NETAPPSTARTRESPONSE                  =      	0x1C0A;
+const uint16_t SL_OPCODE_NETAPP_STOP_COMMAND                         =      	0x9C61;
+const uint16_t SL_OPCODE_NETAPP_STOP_RESPONSE                        =      	0x1C61;
+const uint16_t SL_OPCODE_NETAPP_NETAPPSET                            =	        0x9C0B;
+const uint16_t SL_OPCODE_NETAPP_NETAPPSETRESPONSE                    =	        0x1C0B;
+const uint16_t SL_OPCODE_NETAPP_NETAPPGET                            =	        0x9C27;
+const uint16_t SL_OPCODE_NETAPP_NETAPPGETRESPONSE                    =	        0x1C27;
+const uint16_t SL_OPCODE_NETAPP_DNSGETHOSTBYNAME                     =      	0x9C20;
+const uint16_t SL_OPCODE_NETAPP_DNSGETHOSTBYNAMERESPONSE             =      	0x1C20;
+const uint16_t SL_OPCODE_NETAPP_DNSGETHOSTBYNAMEASYNCRESPONSE        =      	0x1820;
+const uint16_t SL_OPCODE_NETAPP_DNSGETHOSTBYNAMEASYNCRESPONSE_V6     =      	0x1A20;
+const uint16_t SL_OPCODE_NETAPP_NETAPP_MDNS_LOOKUP_SERVICE           =          0x9C71;
+const uint16_t SL_OPCODE_NETAPP_NETAPP_MDNS_LOOKUP_SERVICE_RESPONSE  =          0x1C72;
+const uint16_t SL_OPCODE_NETAPP_MDNSREGISTERSERVICE                  =          0x9C34;
+const uint16_t SL_OPCODE_NETAPP_MDNSREGISTERSERVICERESPONSE          =          0x1C34;
+const uint16_t SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICE                 =          0x9C35;
+const uint16_t SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICERESPONSE         =          0x1C35;
+const uint16_t SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICEASYNCRESPONSE    =          0x1835;
+const uint16_t SL_OPCODE_NETAPP_MDNSGETHOSTBYSERVICEASYNCRESPONSE_V6 =          0x1A35;
+const uint16_t SL_OPCODE_NETAPP_DNSGETHOSTBYADDR                     =      	0x9C26;
+const uint16_t SL_OPCODE_NETAPP_DNSGETHOSTBYADDR_V6                  =      	0x9E26;
+const uint16_t SL_OPCODE_NETAPP_DNSGETHOSTBYADDRRESPONSE             =      	0x1C26;
+const uint16_t SL_OPCODE_NETAPP_DNSGETHOSTBYADDRASYNCRESPONSE        =      	0x1826;
+const uint16_t SL_OPCODE_NETAPP_PINGSTART                            =      	0x9C21;
+const uint16_t SL_OPCODE_NETAPP_PINGSTART_V6                         =      	0x9E21;
+const uint16_t SL_OPCODE_NETAPP_PINGSTARTRESPONSE                    =      	0x1C21;
+const uint16_t SL_OPCODE_NETAPP_PINGREPORTREQUEST                    =      	0x9C22;
+const uint16_t SL_OPCODE_NETAPP_PINGREPORTREQUESTRESPONSE            =      	0x1822;
+const uint16_t SL_OPCODE_NETAPP_PINGSTOP                             =      	0x9C23;
+const uint16_t SL_OPCODE_NETAPP_PINGSTOPRESPONSE                     =      	0x1C23;
+const uint16_t SL_OPCODE_NETAPP_ARPFLUSH                             =      	0x9C24;
+const uint16_t SL_OPCODE_NETAPP_ARPFLUSHRESPONSE                     =      	0x1C24;
+const uint16_t SL_OPCODE_NETAPP_IPACQUIRED                           =      	0x1825;
+const uint16_t SL_OPCODE_NETAPP_IPV4_LOST	                         =        	0x1832;
+const uint16_t SL_OPCODE_NETAPP_DHCP_IPV4_ACQUIRE_TIMEOUT            =      	0x1833;
+const uint16_t SL_OPCODE_NETAPP_IPACQUIRED_V6                        =      	0x1A25;
+const uint16_t SL_OPCODE_NETAPP_IPERFSTARTCOMMAND                    =      	0x9C28;
+const uint16_t SL_OPCODE_NETAPP_IPERFSTARTRESPONSE                   =      	0x1C28;
+const uint16_t SL_OPCODE_NETAPP_IPERFSTOPCOMMAND                     =      	0x9C29;
+const uint16_t SL_OPCODE_NETAPP_IPERFSTOPRESPONSE                    =      	0x1C29;
+const uint16_t SL_OPCODE_NETAPP_CTESTSTARTCOMMAND                    =      	0x9C2A;
+const uint16_t SL_OPCODE_NETAPP_CTESTSTARTRESPONSE                   =      	0x1C2A;
+const uint16_t SL_OPCODE_NETAPP_CTESTASYNCRESPONSE                   =      	0x182A;
+const uint16_t SL_OPCODE_NETAPP_CTESTSTOPCOMMAND                     =      	0x9C2B;
+const uint16_t SL_OPCODE_NETAPP_CTESTSTOPRESPONSE                    =      	0x1C2B;
+const uint16_t SL_OPCODE_NETAPP_IP_LEASED                            =      	0x182C;
+const uint16_t SL_OPCODE_NETAPP_IP_RELEASED                          =      	0x182D;
+const uint16_t SL_OPCODE_NETAPP_HTTPGETTOKENVALUE                    =      	0x182E;
+const uint16_t SL_OPCODE_NETAPP_HTTPSENDTOKENVALUE                   =      	0x9C2F;
+const uint16_t SL_OPCODE_NETAPP_HTTPPOSTTOKENVALUE                   =      	0x1830;
+const uint16_t SL_OPCODE_NVMEM_FILEOPEN                              =      	0xA43C;
+const uint16_t SL_OPCODE_NVMEM_FILEOPENRESPONSE                      =       	0x243C;
+const uint16_t SL_OPCODE_NVMEM_FILECLOSE                             =       	0xA43D;
+const uint16_t SL_OPCODE_NVMEM_FILECLOSERESPONSE                     =      	0x243D;
+const uint16_t SL_OPCODE_NVMEM_FILEREADCOMMAND                       =       	0xA440;
+const uint16_t SL_OPCODE_NVMEM_FILEREADRESPONSE                      =      	0x2440;
+const uint16_t SL_OPCODE_NVMEM_FILEWRITECOMMAND                      =      	0xA441;
+const uint16_t SL_OPCODE_NVMEM_FILEWRITERESPONSE                     =      	0x2441;
+const uint16_t SL_OPCODE_NVMEM_FILEGETINFOCOMMAND                    =      	0xA442;
+const uint16_t SL_OPCODE_NVMEM_FILEGETINFORESPONSE                   =      	0x2442;
+const uint16_t SL_OPCODE_NVMEM_FILEDELCOMMAND                        =      	0xA443;
+const uint16_t SL_OPCODE_NVMEM_FILEDELRESPONSE                       =      	0x2443;
+const uint16_t SL_OPCODE_NVMEM_NVMEMFORMATCOMMAND                    =      	0xA444;
+const uint16_t SL_OPCODE_NVMEM_NVMEMFORMATRESPONSE                   =      	0x2444;
+
+const uint16_t SL_OPCODE_DEVICE_SETDEBUGLEVELCOMMAND                 =      	0x846A;
+const uint16_t SL_OPCODE_DEVICE_SETDEBUGLEVELRESPONSE                =      	0x046A;
+
+const uint16_t SL_OPCODE_DEVICE_NETCFG_SET_COMMAND                 	 =          0x8432;
+const uint16_t SL_OPCODE_DEVICE_NETCFG_SET_RESPONSE                	 =          0x0432;
+const uint16_t SL_OPCODE_DEVICE_NETCFG_GET_COMMAND                 	 =          0x8433;
+const uint16_t SL_OPCODE_DEVICE_NETCFG_GET_RESPONSE                	 =          0x0433;
+/*  */
+const uint16_t SL_OPCODE_DEVICE_SETUARTMODECOMMAND                   =      	0x846B;
+const uint16_t SL_OPCODE_DEVICE_SETUARTMODERESPONSE                  =      	0x046B;
+const uint16_t SL_OPCODE_DEVICE_SSISIZESETCOMMAND	                 =          0x846B;
+const uint16_t SL_OPCODE_DEVICE_SSISIZESETRESPONSE	                 =          0x046B;
+
+/*  */
+const uint16_t SL_OPCODE_DEVICE_EVENTMASKSET                         =      	0x8464;
+const uint16_t SL_OPCODE_DEVICE_EVENTMASKSETRESPONSE                 =      	0x0464;
+const uint16_t SL_OPCODE_DEVICE_EVENTMASKGET                         =      	0x8465;
+const uint16_t SL_OPCODE_DEVICE_EVENTMASKGETRESPONSE                 =      	0x0465;
+
+const uint16_t SL_OPCODE_DEVICE_DEVICEGET                            =      	0x8466;
+const uint16_t SL_OPCODE_DEVICE_DEVICEGETRESPONSE                    =          0x0466;
+const uint16_t SL_OPCODE_DEVICE_DEVICESET							 =			0x84B7;
+const uint16_t SL_OPCODE_DEVICE_DEVICESETRESPONSE					 =			0x04B7;
+
+const uint16_t SL_OPCODE_WLAN_SCANRESULTSGETCOMMAND                  =      	0x8C8C;
+const uint16_t SL_OPCODE_WLAN_SCANRESULTSGETRESPONSE                 =      	0x0C8C;
+const uint16_t SL_OPCODE_WLAN_SMARTCONFIGOPTSET                      =      	0x8C8D;
+const uint16_t SL_OPCODE_WLAN_SMARTCONFIGOPTSETRESPONSE              =      	0x0C8D;
+const uint16_t SL_OPCODE_WLAN_SMARTCONFIGOPTGET                      =      	0x8C8E;
+const uint16_t SL_OPCODE_WLAN_SMARTCONFIGOPTGETRESPONSE              =      	0x0C8E;
+
+
+/* Rx Filters opcodes */
+const uint16_t SL_OPCODE_WLAN_WLANRXFILTERADDCOMMAND                 =          0x8C6C;
+const uint16_t SL_OPCODE_WLAN_WLANRXFILTERADDRESPONSE                =          0x0C6C;
+const uint16_t SL_OPCODE_WLAN_WLANRXFILTERSETCOMMAND                 =          0x8C6D;
+const uint16_t SL_OPCODE_WLAN_WLANRXFILTERSETRESPONSE                =          0x0C6D;
+const uint16_t SL_OPCODE_WLAN_WLANRXFILTERGETSTATISTICSINFOCOMMAND   =          0x8C6E;
+const uint16_t SL_OPCODE_WLAN_WLANRXFILTERGETSTATISTICSINFORESPONSE  =          0x0C6E;
+const uint16_t SL_OPCODE_WLAN_WLANRXFILTERGETCOMMAND                 =          0x8C6F;
+const uint16_t SL_OPCODE_WLAN_WLANRXFILTERGETRESPONSE                =          0x0C6F;
+const uint16_t SL_OPCODE_WLAN_WLANRXFILTERGETINFO                    =          0x8C70;
+const uint16_t SL_OPCODE_WLAN_WLANRXFILTERGETINFORESPONSE            =          0x0C70;
+
+
+/******************************************************************************************/
+/*   Device structs  */
+/******************************************************************************************/
+typedef uint32_t InitStatus_t;
+
+
+typedef struct {
+    int32_t Status;
+} InitComplete_t;
+
+typedef struct {
+    int16_t status;
+    uint16_t padding;
+
+} _BasicResponse_t;
+
+typedef struct {
+    uint16_t Timeout;
+    uint16_t padding;
+} _DevStopCommand_t;
+
+typedef struct {
+    uint32_t group;
+    uint32_t mask;
+} _DevMaskEventSetCommand_t;
+
+typedef _BasicResponse_t _DevMaskEventSetResponse_t;
+
+
+typedef struct {
+    uint32_t group;
+} _DevMaskEventGetCommand_t;
+
+
+typedef struct {
+    uint32_t group;
+    uint32_t mask;
+} _DevMaskEventGetResponse_t;
+
+
+typedef struct {
+    uint32_t group;
+} _DevStatusGetCommand_t;
+
+
+typedef struct {
+    uint32_t group;
+    uint32_t status;
+} _DevStatusGetResponse_t;
+
+typedef struct {
+    uint32_t  ChipId;
+    uint32_t  FwVersion[4];
+    uint8_t   PhyVersion[4];
+} _Device_VersionReadResponsePart_t;
+
+typedef struct {
+    _Device_VersionReadResponsePart_t part;
+    uint32_t                            NwpVersion[4];
+    uint16_t                            RomVersion;
+    uint16_t                            Padding;
+} _Device_VersionReadResponseFull_t;
+
+
+typedef struct {
+    uint32_t BaudRate;
+    uint8_t  FlowControlEnable;
+} _DevUartSetModeCommand_t;
+
+typedef _BasicResponse_t _DevUartSetModeResponse_t;
+
+/******************************************************/
+
+typedef struct {
+    uint8_t SsiSizeInBytes;
+    uint8_t Padding[3];
+} _StellarisSsiSizeSet_t;
+
+/*****************************************************************************************/
+/*   WLAN structs */
+/*****************************************************************************************/
+#define MAXIMAL_PASSWORD_LENGTH					(64)
+
+typedef struct {
+    uint8_t	SecType;
+    uint8_t	SsidLen;
+    uint8_t	Bssid[6];
+    uint8_t	PasswordLen;
+} _WlanConnectCommon_t;
+
+#define SSID_STRING(pCmd)       (int8_t *)((_WlanConnectCommon_t *)(pCmd) + 1)
+#define PASSWORD_STRING(pCmd)   (SSID_STRING(pCmd) + ((_WlanConnectCommon_t *)(pCmd))->SsidLen)
+
+typedef struct {
+    _WlanConnectCommon_t            Common;
+    uint8_t							UserLen;
+    uint8_t							AnonUserLen;
+    uint8_t   						CertIndex;
+    uint32_t  						EapBitmask;
+} _WlanConnectEapCommand_t;
+
+#define EAP_SSID_STRING(pCmd)       (int8_t *)((_WlanConnectEapCommand_t *)(pCmd) + 1)
+#define EAP_PASSWORD_STRING(pCmd)   (EAP_SSID_STRING(pCmd) + ((_WlanConnectEapCommand_t *)(pCmd))->Common.SsidLen)
+#define EAP_USER_STRING(pCmd)       (EAP_PASSWORD_STRING(pCmd) + ((_WlanConnectEapCommand_t *)(pCmd))->Common.PasswordLen)
+#define EAP_ANON_USER_STRING(pCmd)  (EAP_USER_STRING(pCmd) + ((_WlanConnectEapCommand_t *)(pCmd))->UserLen)
+
+
+typedef struct {
+    uint8_t	PolicyType;
+    uint8_t       Padding;
+    uint8_t	PolicyOption;
+    uint8_t	PolicyOptionLen;
+} _WlanPoliciySetGet_t;
+
+
+typedef struct {
+    uint32_t  minDwellTime;
+    uint32_t  maxDwellTime;
+    uint32_t  numProbeResponse;
+    uint32_t  G_Channels_mask;
+    int32_t   rssiThershold;
+    int32_t   snrThershold;
+    int32_t   defaultTXPower;
+    uint16_t  intervalList[16];
+} _WlanScanParamSetCommand_t;
+
+
+typedef struct {
+    int8_t	SecType;
+    uint8_t	SsidLen;
+    uint8_t	Priority;
+    uint8_t	Bssid[6];
+    uint8_t   PasswordLen;
+    uint8_t   WepKeyId;
+} _WlanAddGetProfile_t;
+
+
+typedef struct {
+    _WlanAddGetProfile_t              Common;
+    uint8_t                             UserLen;
+    uint8_t                             AnonUserLen;
+    uint8_t                             CertIndex;
+    uint16_t                            padding;
+    uint32_t                            EapBitmask;
+} _WlanAddGetEapProfile_t;
+
+#define PROFILE_SSID_STRING(pCmd)       ((int8_t *)((_WlanAddGetProfile_t *)(pCmd) + 1))
+#define PROFILE_PASSWORD_STRING(pCmd)   (PROFILE_SSID_STRING(pCmd) + ((_WlanAddGetProfile_t *)(pCmd))->SsidLen)
+
+#define EAP_PROFILE_SSID_STRING(pCmd)       (int8_t *)((_WlanAddGetEapProfile_t *)(pCmd) + 1)
+#define EAP_PROFILE_PASSWORD_STRING(pCmd)   (EAP_PROFILE_SSID_STRING(pCmd) + ((_WlanAddGetEapProfile_t *)(pCmd))->Common.SsidLen)
+#define EAP_PROFILE_USER_STRING(pCmd)       (EAP_PROFILE_PASSWORD_STRING(pCmd) + ((_WlanAddGetEapProfile_t *)(pCmd))->Common.PasswordLen)
+#define EAP_PROFILE_ANON_USER_STRING(pCmd)  (EAP_PROFILE_USER_STRING(pCmd) + ((_WlanAddGetEapProfile_t *)(pCmd))->UserLen)
+
+typedef struct {
+    uint8_t	index;
+    uint8_t	padding[3];
+} _WlanProfileDelGetCommand_t;
+
+typedef _BasicResponse_t _WlanGetNetworkListResponse_t;
+
+typedef struct {
+    uint8_t 	index;
+    uint8_t 	count;
+    int8_t 	padding[2];
+} _WlanGetNetworkListCommand_t;
+
+
+
+
+typedef struct {
+    uint32_t  						groupIdBitmask;
+    uint8_t                           cipher;
+    uint8_t                           publicKeyLen;
+    uint8_t                           group1KeyLen;
+    uint8_t                           group2KeyLen;
+} _WlanSmartConfigStartCommand_t;
+
+#define SMART_CONFIG_START_PUBLIC_KEY_STRING(pCmd)       ((int8_t *)((_WlanSmartConfigStartCommand_t *)(pCmd) + 1))
+#define SMART_CONFIG_START_GROUP1_KEY_STRING(pCmd)       ((int8_t *) (SMART_CONFIG_START_PUBLIC_KEY_STRING(pCmd) + ((_WlanSmartConfigStartCommand_t *)(pCmd))->publicKeyLen))
+#define SMART_CONFIG_START_GROUP2_KEY_STRING(pCmd)       ((int8_t *) (SMART_CONFIG_START_GROUP1_KEY_STRING(pCmd) + ((_WlanSmartConfigStartCommand_t *)(pCmd))->group1KeyLen))
+
+typedef	struct {
+    uint8_t	mode;
+    uint8_t   padding[3];
+} _WlanSetMode_t;
+
+
+
+
+typedef struct {
+    uint16_t  Status;
+    uint16_t  ConfigId;
+    uint16_t  ConfigOpt;
+    uint16_t  ConfigLen;
+} _WlanCfgSetGet_t;
+
+
+//wlan_rx_filters moved
+
+typedef struct {
+    uint16_t status;
+    uint8_t  WlanRole;     /* 0 = station, 2 = AP */
+    uint8_t  Ipv6Enabled;
+    uint8_t  Ipv6DhcpEnabled;
+
+    uint32_t ipV6Global[4];
+    uint32_t ipV6Local[4];
+    uint32_t ipV6DnsServer[4];
+    uint8_t  Ipv6DhcpState;
+
+} _NetappIpV6configRetArgs_t;
+
+
+typedef struct {
+    uint8_t  ipV4[4];
+    uint8_t  ipV4Mask[4];
+    uint8_t  ipV4Gateway[4];
+    uint8_t  ipV4DnsServer[4];
+    uint8_t  ipV4Start[4];
+    uint8_t  ipV4End[4];
+} _NetCfgIpV4AP_Args_t;
+
+
+
+typedef struct {
+    uint16_t status;
+    uint8_t  MacAddr[6];
+} _MAC_Address_SetGet_t;
+
+
+typedef struct {
+    uint16_t  Status;
+    uint16_t	ConfigId;
+    uint16_t	ConfigOpt;
+    uint16_t	ConfigLen;
+} _NetCfgSetGet_t;
+
+typedef struct {
+    uint16_t  Status;
+    uint16_t  DeviceSetId;
+    uint16_t  Option;
+    uint16_t  ConfigLen;
+} _DeviceSetGet_t;
+
+
+
+
+/******************************************************************************************/
+/*   Socket structs  */
+/******************************************************************************************/
+
+typedef struct {
+    uint8_t Domain;
+    uint8_t Type;
+    uint8_t Protocol;
+    uint8_t Padding;
+} _SocketCommand_t;
+
+
+typedef struct {
+    int16_t statusOrLen;
+    uint8_t  sd;
+    uint8_t  padding;
+} _SocketResponse_t;
+
+typedef struct {
+    uint8_t sd;
+    uint8_t family;
+    uint8_t padding1;
+    uint8_t padding2;
+} _AcceptCommand_t;
+
+
+typedef struct {
+    int16_t statusOrLen;
+    uint8_t sd;
+    uint8_t family;
+    uint16_t port;
+    uint16_t paddingOrAddr;
+    uint32_t address;
+} _SocketAddrAsyncIPv4Response_t;
+
+typedef struct {
+    int16_t statusOrLen;
+    uint8_t sd;
+    uint8_t family;
+    uint16_t port;
+    uint8_t address[6];
+} _SocketAddrAsyncIPv6EUI48Response_t;
+typedef struct {
+    int16_t statusOrLen;
+    uint8_t sd;
+    uint8_t family;
+    uint16_t port;
+    uint16_t paddingOrAddr;
+    uint32_t address[4];
+} _SocketAddrAsyncIPv6Response_t;
+
+
+typedef struct {
+    int16_t lenOrPadding;
+    uint8_t sd;
+    uint8_t FamilyAndFlags;
+    uint16_t port;
+    uint16_t paddingOrAddr;
+    uint32_t address;
+} _SocketAddrIPv4Command_t;
+
+typedef struct {
+    int16_t lenOrPadding;
+    uint8_t sd;
+    uint8_t FamilyAndFlags;
+    uint16_t port;
+    uint8_t address[6];
+} _SocketAddrIPv6EUI48Command_t;
+typedef struct {
+    int16_t lenOrPadding;
+    uint8_t sd;
+    uint8_t FamilyAndFlags;
+    uint16_t port;
+    uint16_t paddingOrAddr;
+    uint32_t address[4];
+} _SocketAddrIPv6Command_t;
+
+typedef union {
+    _SocketAddrIPv4Command_t IpV4;
+    _SocketAddrIPv6EUI48Command_t IpV6EUI48;
+#ifdef SL_SUPPORT_IPV6
+    _SocketAddrIPv6Command_t IpV6;
+#endif
+} _SocketAddrCommand_u;
+
+typedef union {
+    _SocketAddrAsyncIPv4Response_t IpV4;
+    _SocketAddrAsyncIPv6EUI48Response_t IpV6EUI48;
+#ifdef SL_SUPPORT_IPV6
+    _SocketAddrAsyncIPv6Response_t IpV6;
+#endif
+} _SocketAddrResponse_u;
+
+typedef struct {
+    uint8_t sd;
+    uint8_t backlog;
+    uint8_t padding1;
+    uint8_t padding2;
+} _ListenCommand_t;
+
+typedef struct {
+    uint8_t sd;
+    uint8_t padding0;
+    uint8_t padding1;
+    uint8_t padding2;
+} _CloseCommand_t;
+
+
+typedef struct {
+    uint8_t nfds;
+    uint8_t readFdsCount;
+    uint8_t writeFdsCount;
+    uint8_t padding;
+    uint16_t readFds;
+    uint16_t writeFds;
+    uint16_t tv_usec;
+    uint16_t tv_sec;
+} _SelectCommand_t;
+
+
+typedef struct {
+    uint16_t status;
+    uint8_t readFdsCount;
+    uint8_t writeFdsCount;
+    uint16_t readFds;
+    uint16_t writeFds;
+} _SelectAsyncResponse_t;
+
+typedef struct {
+    uint8_t sd;
+    uint8_t level;
+    uint8_t optionName;
+    uint8_t optionLen;
+} _setSockOptCommand_t;
+
+typedef struct {
+    uint8_t sd;
+    uint8_t level;
+    uint8_t optionName;
+    uint8_t optionLen;
+} _getSockOptCommand_t;
+
+typedef struct {
+    int16_t status;
+    uint8_t sd;
+    uint8_t optionLen;
+} _getSockOptResponse_t;
+
+
+typedef struct {
+    uint16_t StatusOrLen;
+    uint8_t  sd;
+    uint8_t FamilyAndFlags;
+} _sendRecvCommand_t;
+
+//netapp structs moved
+
+/*****************************************************************************************
+*   FS structs
+******************************************************************************************/
+
+typedef struct {
+    uint32_t FileHandle;
+    uint32_t Offset;
+    uint16_t Len;
+    uint16_t Padding;
+} _FsReadCommand_t;
+
+typedef struct {
+    uint32_t Mode;
+    uint32_t Token;
+} _FsOpenCommand_t;
+
+typedef struct {
+    uint32_t FileHandle;
+    uint32_t Token;
+} _FsOpenResponse_t;
+
+
+typedef struct {
+    uint32_t FileHandle;
+    uint32_t CertificFileNameLength;
+    uint32_t SignatureLen;
+} _FsCloseCommand_t;
+
+
+typedef _BasicResponse_t _FsReadResponse_t;
+typedef _BasicResponse_t _FsDeleteResponse_t;
+typedef _BasicResponse_t _FsCloseResponse_t;
+
+typedef struct {
+    uint16_t Status;
+    uint16_t flags;
+    uint32_t FileLen;
+    uint32_t AllocatedLen;
+    uint32_t Token[4];
+} _FsGetInfoResponse_t;
+
+typedef struct {
+    uint8_t DeviceID;
+    uint8_t Padding[3];
+} _FsFormatCommand_t;
+
+typedef _BasicResponse_t _FsFormatResponse_t;
+
+typedef struct {
+    uint32_t Token;
+} _FsDeleteCommand_t;
+
+typedef   _FsDeleteCommand_t  _FsGetInfoCommand_t;
+
+typedef struct {
+    uint32_t FileHandle;
+    uint32_t Offset;
+    uint16_t Len;
+    uint16_t Padding;
+} _FsWriteCommand_t;
+
+typedef _BasicResponse_t _FsWriteResponse_t;
+
+
+/* TODO: Set MAx Async Payload length depending on flavor (Tiny, Small, etc.) */
+
+#ifdef SL_TINY_EXT
+#define SL_ASYNC_MAX_PAYLOAD_LEN        120  /* size must be aligned to 4 */
+#else
+#define SL_ASYNC_MAX_PAYLOAD_LEN        160 /* size must be aligned to 4 */
+#endif
+#define SL_ASYNC_MAX_MSG_LEN            (_SL_RESP_HDR_SIZE + SL_ASYNC_MAX_PAYLOAD_LEN)
+
+#define RECV_ARGS_SIZE                  (sizeof(_SocketResponse_t))
+#define RECVFROM_IPV4_ARGS_SIZE         (sizeof(_SocketAddrAsyncIPv4Response_t))
+#define RECVFROM_IPV6_ARGS_SIZE         (sizeof(_SocketAddrAsyncIPv6Response_t))
+
+#define SL_IPV4_ADDRESS_SIZE 			(sizeof(uint32_t))
+#define SL_IPV6_ADDRESS_SIZE 			(4 * sizeof(uint32_t))
+
+}//namespace mbed_cc3100
+
+#endif /*  _SL_PROTOCOL_TYPES_H_  */
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_simplelink.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_simplelink.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,927 @@
+/*
+ * simplelink.h - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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.
+ *
+*/
+
+
+/*!
+    \mainpage SimpleLink Driver
+
+    \section intro_sec Introduction
+
+ The SimpleLink CC31xx/CC2xx family allows to add Wi-Fi and networking capabilities
+ to low-cost embedded products without having prior Wi-Fi, RF or networking expertise.
+ The CC31xx/CC32xx is an ideal solution for microcontroller-based sensor and control
+ applications such as home appliances, home automation and smart metering.
+ The CC31xx/CC32xx has integrated a comprehensive TCP/IP network stack, Wi-Fi driver and
+ security supplicant leading to easier portability to microcontrollers, to an
+ ultra-low memory footprint, all without compromising the capabilities and robustness
+ of the final application.
+
+
+
+ \section modules_sec Module Names
+ To make it simple, TI's SimpleLink CC31xx/CC32xx platform capabilities were divided into modules by topic (Silo).
+ These capabilities range from basic device management through wireless
+ network configuration, standard BSD socket and much more.
+ Listed below are the various modules in the SimpleLink CC31xx/CC32xx driver:
+     -# \ref device - controls the behaviour of the CC31xx/CC32xx device (start/stop, events masking and obtaining specific device status)
+     -# \ref wlan - controls the use of the WiFi WLAN module including:
+       - Connection features, such as: profiles, policies, SmartConfig&trade;
+       - Advanced WLAN features, such as: scans, rx filters and rx statistics collection
+     -# \ref socket - controls standard client/server sockets programming options and capabilities
+     -# \ref netapp - activates networking applications, such as: HTTP Server, DHCP Server, Ping, DNS and mDNS.
+     -# \ref netcfg - controls the configuration of the device addresses (i.e. IP and MAC addresses)
+     -# \ref FileSystem     - provides file system capabilities to TI's CC31XX that can be used by both the CC31XX device and the user.
+
+
+ \section         proting_sec     Porting Guide
+
+ The porting of the SimpleLink driver to any new platform is based on few simple steps.
+ This guide takes you through this process step by step. Please follow the instructions
+ carefully to avoid any problems during this process and to enable efficient and proper
+ work with the device.
+ Please notice that all modifications and porting adjustments of the driver should be
+ made in the user.h header file only.
+ Keep making any of the changes only in this file will ensure smoothly transaction to
+ new versions of the driver at the future!
+
+
+ \subsection     porting_step1   Step 1 - Create your own user.h file
+
+ The first step is to create a user.h file that will include your configurations and
+ adjustments. You can use the empty template provided as part of this driver or
+ you can choose to base your file on file from one of the wide range of examples
+ applications provided by Texas Instruments
+
+
+ \subsection    porting_step2   Step 2 - Select the capabilities set required for your application
+
+ Texas Instruments made a lot of efforts to build set of predefined capability sets that would
+ fit most of the target application.
+ It is recommended to try and choose one of this predefined capabilities set before going to
+ build your own customized set. If you find compatible set you can skip the rest of this step.
+
+ The available sets are:
+     -# SL_TINY     -   Compatible to be used on platforms with very limited resources. Provides
+                        the best in class foot print in terms of Code and Data consumption.
+     -# SL_SMALL    -   Compatible to most common networking applications. Provide the most
+                        common APIs with decent balance between code size, data size, functionality
+                        and performances
+     -# SL_FULL     -   Provide access to all SimpleLink functionalities
+
+
+ \subsection    porting_step3   Step 3 - Bind the device enable/disable output line
+
+ The enable/disable line (nHib) provide mechanism to enter the device into the least current
+ consumption mode. This mode could be used when no traffic is required (tx/rx).
+ when this line is not connected to any IO of the host this define should be left empty.
+ Not connecting this line results in ability to start the driver only once.
+
+
+ \subsection    porting_step4   Step 4 - Writing your interface communication driver
+
+ The SimpleLink device support several standard communication protocol among SPI and
+ UART. Depending on your needs and your hardware design, you should choose the
+ communication channel type.
+ The interface for this communication channel should include 4 simple access functions:
+ -# open
+ -# close
+ -# read
+ -# write
+
+ The way this driver would be implemented is directly effecting the efficiency and
+ the performances of the SimpleLink device on this platform.
+ If your system has DMA you should consider to use it in order to increase the utilization
+ of the communication channel
+ If you have enough memory resources you should consider using a buffer to increase the
+ efficiency of the write operations.
+
+
+ \subsection     porting_step5   Step 5 - Choose your memory management model
+
+ The SimpleLink driver support two memory models:
+     -# Static (default)
+     -# Dynamic
+
+ If you choose to work in dynamic model you will have to provide alloc and free functions
+ to be used by the Simple Link driver otherwise nothing need to be done.
+
+
+ \subsection     porting_step6   Step 6 - OS adaptation
+
+ The SimpleLink driver could run on two kind of platforms:
+     -# Non-Os / Single Threaded (default)
+     -# Multi-Threaded
+
+ If you choose to work in multi-threaded environment under operating system you will have to
+ provide some basic adaptation routines to allow the driver to protect access to resources
+ for different threads (locking object) and to allow synchronization between threads (sync objects).
+ In additional the driver support running without dedicated thread allocated solely to the simple
+ link driver. If you choose to work in this mode, you should also supply a spawn method that
+ will enable to run function on a temporary context.
+
+
+ \subsection     porting_step7   Step 7 - Set your asynchronous event handlers routines
+
+ The SimpleLink device generate asynchronous events in several situations.
+ These asynchronous events could be masked.
+ In order to catch these events you have to provide handler routines.
+ Please notice that if you not provide a handler routine and the event is received,
+ the driver will drop this event without any indication of this drop.
+
+
+ \subsection     porting_step8   Step 8 - Run diagnostic tools to validate the correctness of your porting
+
+ The driver is delivered with some porting diagnostic tools to simplify the porting validation process
+ and to reduce issues latter. It is very important to follow carefully this process.
+
+ The diagnostic process include:
+     -# Validating Interface Communication Driver
+     -# Validating OS adaptation layer
+     -# Validating HW integrity
+     -# Validating basic work with the device
+
+
+    \section sw_license License
+
+ *
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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.
+ *
+*/
+
+
+
+#ifndef SIMPLELINK_H_
+#define SIMPLELINK_H_
+
+#include "mbed.h"
+#include "cc3100_user.h"
+
+namespace mbed_cc3100 {
+
+/*! \attention  Async event activation notes
+    Function prototypes for event callback handlers
+    Event handler function names should be defined in the user.h file
+    e.g.
+    "#define sl_WlanEvtHdlr   SLWlanEventHandler"
+    Indicates all WLAN events are handled by User func "SLWlanEventHandler"
+    Important notes:
+    1. Event handlers cannot activate another SimpleLink API from the event's context
+    2. Event's data is valid during event's context. Any application data
+       which is required for the user application should be copied or marked
+       into user's variables
+    3. It is not recommended to delay the execution of the event callback handler
+
+*/
+
+/*!
+
+    \addtogroup UserEvents
+    @{
+
+*/
+
+
+/*****************************************************************************/
+/* Macro declarations for Host Driver version                                */
+/*****************************************************************************/
+#define SL_DRIVER_VERSION   "1.0.0.10"
+#define SL_MAJOR_VERSION_NUM    1L
+#define SL_MINOR_VERSION_NUM    0L
+#define SL_VERSION_NUM          0L
+#define SL_SUB_VERSION_NUM      10L
+
+
+/*****************************************************************************/
+/* Macro declarations for predefined configurations                          */
+/*****************************************************************************/
+
+#ifdef SL_TINY
+
+#undef SL_INC_ARG_CHECK
+#undef SL_INC_EXT_API
+#undef SL_INC_SOCK_SERVER_SIDE_API
+#undef SL_INC_WLAN_PKG
+#undef SL_INC_NET_CFG_PKG
+#undef SL_INC_FS_PKG
+#undef SL_INC_SET_UART_MODE
+#undef SL_INC_NVMEM_PKG
+#define SL_INC_STD_BSD_API_NAMING
+#define SL_INC_SOCK_CLIENT_SIDE_API
+#define SL_INC_SOCK_RECV_API
+#define SL_INC_SOCK_SEND_API
+#define SL_INC_SOCKET_PKG
+#define SL_INC_NET_APP_PKG
+#endif
+
+#ifdef SL_SMALL
+#undef SL_INC_EXT_API
+#undef SL_INC_NET_APP_PKG
+#undef SL_INC_NET_CFG_PKG
+#undef SL_INC_FS_PKG
+#define SL_INC_ARG_CHECK
+#define SL_INC_WLAN_PKG
+#define SL_INC_SOCKET_PKG
+#define SL_INC_SOCK_CLIENT_SIDE_API
+#define SL_INC_SOCK_SERVER_SIDE_API
+#define SL_INC_SOCK_RECV_API
+#define SL_INC_SOCK_SEND_API
+#define SL_INC_SET_UART_MODE
+#endif
+
+#ifdef SL_FULL
+#define SL_INC_EXT_API
+#define SL_INC_NET_APP_PKG
+#define SL_INC_NET_CFG_PKG
+#define SL_INC_FS_PKG
+#define SL_INC_ARG_CHECK
+#define SL_INC_WLAN_PKG
+#define SL_INC_SOCKET_PKG
+#define SL_INC_SOCK_CLIENT_SIDE_API
+#define SL_INC_SOCK_SERVER_SIDE_API
+#define SL_INC_SOCK_RECV_API
+#define SL_INC_SOCK_SEND_API
+#define SL_INC_SET_UART_MODE
+#endif
+
+#define SL_RET_CODE_OK                          (0)
+#define SL_RET_CODE_INVALID_INPUT               (-2)
+#define SL_RET_CODE_SELF_ERROR                  (-3)
+#define SL_RET_CODE_NWP_IF_ERROR                (-4)
+#define SL_RET_CODE_MALLOC_ERROR                (-5)
+
+#define sl_SyncObjClear(pObj)     sl_SyncObjWait(pObj,NON_OS_SYNC_OBJ_SIGNAL_VALUE,NON_OS_SYNC_OBJ_CLEAR_VALUE,SL_OS_NO_WAIT)
+
+#ifndef SL_TINY_EXT
+#define SL_MAX_SOCKETS      (8)
+#else
+#define SL_MAX_SOCKETS      (2)
+#endif
+ 
+/*****************************************************************************/
+/* Types definitions                                                                                                                */
+/*****************************************************************************/  
+
+
+#ifndef NULL
+#define NULL        (0)
+#endif
+
+#ifndef FALSE
+#define FALSE       (0)
+#endif
+
+#ifndef TRUE
+#define TRUE        (!FALSE)
+#endif
+
+#ifndef OK
+#define OK          (0)
+#endif
+
+//#ifndef _SL_USER_TYPES
+//typedef unsigned char _u8;
+//typedef signed char   _i8;
+ 
+//typedef unsigned short _u16;
+//typedef signed short   _i16;
+ 
+//typedef unsigned long  _u32;
+//typedef signed long    _i32;
+//#define _volatile volatile
+//#define _const    const
+//#endif
+
+typedef uint16_t  _SlOpcode_t;
+typedef uint8_t   _SlArgSize_t;
+typedef int16_t   _SlDataSize_t;
+typedef int16_t   _SlReturnVal_t;
+
+/*
+ * This event status used to  block or continue the event propagation
+ * through all the registered external libs/user application
+ *
+ */
+
+ typedef enum {
+    EVENT_PROPAGATION_BLOCK = 0,
+    EVENT_PROPAGATION_CONTINUE
+
+ } _SlEventPropogationStatus_e;
+ 
+typedef void (*_SlSpawnEntryFunc_t)(void* pValue);
+
+}//namespace mbed_cc3100
+/*****************************************************************************/
+/* Include files                                                             */
+/*****************************************************************************/
+
+/*
+   objInclusion.h and user.h must be included before all api header files
+   objInclusion.h must be the last arrangement just before including the API header files
+   since it based on the other configurations to decide which object should be included
+*/
+#include "cc3100_objInclusion.h"
+#include "cc3100_trace.h"
+#include "cc3100_fs.h"
+#include "cc3100_socket.h"
+#include "cc3100_netapp.h"
+#include "cc3100_wlan.h"
+#include "cc3100.h"
+#include "cc3100_netcfg.h"
+#include "cc3100_wlan_rx_filters.h"
+
+ /* The general events dispatcher which is
+  * initialized to the user handler */
+#ifdef sl_GeneralEvtHdlr
+#define _SlDrvHandleGeneralEvents sl_GeneralEvtHdlr
+#endif
+
+ /* The wlan events dispatcher which is
+  * initialized to the user handler */
+#ifdef sl_WlanEvtHdlr
+#define _SlDrvHandleWlanEvents sl_WlanEvtHdlr
+#endif
+
+ /* The NetApp events dispatcher which is
+  * initialized to the user handler */
+#ifdef sl_NetAppEvtHdlr
+#define _SlDrvHandleNetAppEvents sl_NetAppEvtHdlr
+#endif
+
+ /* The http server events dispatcher which is
+  * initialized to the user handler if exists */
+#ifdef sl_HttpServerCallback
+#define _SlDrvHandleHttpServerEvents sl_HttpServerCallback
+#endif
+
+ /* The socket events dispatcher which is
+  * initialized to the user handler */
+#ifdef sl_SockEvtHdlr
+#define _SlDrvHandleSockEvents sl_SockEvtHdlr
+#endif
+
+
+
+#define __CONCAT(x,y)   x ## y
+#define __CONCAT2(x,y)  __CONCAT(x,y)
+
+
+/*
+ * The section below handles the external lib event registration
+ * according to the desired events it specified in its API header file.
+ * The external lib should be first installed by the user (see user.h)
+ */
+#ifdef SL_EXT_LIB_1
+
+    /* General Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_1, _NOTIFY_GENERAL_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_1, _GeneralEventHdl) (SlDeviceEvent_t *);
+    #define SlExtLib1GeneralEventHandler   __CONCAT2(SL_EXT_LIB_1, _GeneralEventHdl)
+
+    #undef EXT_LIB_REGISTERED_GENERAL_EVENTS
+    #define EXT_LIB_REGISTERED_GENERAL_EVENTS
+    #endif
+
+    /* Wlan Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_1, _NOTIFY_WLAN_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_1, _WlanEventHdl) (SlWlanEvent_t *);
+    #define SlExtLib1WlanEventHandler   __CONCAT2(SL_EXT_LIB_1, _WlanEventHdl)
+
+    #undef EXT_LIB_REGISTERED_WLAN_EVENTS
+    #define EXT_LIB_REGISTERED_WLAN_EVENTS
+    #endif
+
+    /* NetApp Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_1, _NOTIFY_NETAPP_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_1, _NetAppEventHdl) (SlNetAppEvent_t *);
+    #define SlExtLib1NetAppEventHandler __CONCAT2(SL_EXT_LIB_1, _NetAppEventHdl)
+
+    #undef EXT_LIB_REGISTERED_NETAPP_EVENTS
+    #define EXT_LIB_REGISTERED_NETAPP_EVENTS
+    #endif
+
+    /* Http Server Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_1, _NOTIFY_HTTP_SERVER_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_1, _HttpServerEventHdl) (SlHttpServerEvent_t* , SlHttpServerResponse_t*);
+    #define SlExtLib1HttpServerEventHandler __CONCAT2(SL_EXT_LIB_1, _HttpServerEventHdl)
+
+    #undef EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS
+    #define EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS
+    #endif
+
+    /* Socket Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_1, _NOTIFY_SOCK_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_1, _SockEventHdl) (SlSockEvent_t *);
+    #define SlExtLib1SockEventHandler __CONCAT2(SL_EXT_LIB_1, _SockEventHdl)
+
+    #undef EXT_LIB_REGISTERED_SOCK_EVENTS
+    #define EXT_LIB_REGISTERED_SOCK_EVENTS
+    #endif
+
+#endif
+
+
+#ifdef SL_EXT_LIB_2
+
+    /* General Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_2, _NOTIFY_GENERAL_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_2, _GeneralEventHdl) (SlDeviceEvent_t *);
+    #define SlExtLib2GeneralEventHandler   __CONCAT2(SL_EXT_LIB_2, _GeneralEventHdl)
+
+    #undef EXT_LIB_REGISTERED_GENERAL_EVENTS
+    #define EXT_LIB_REGISTERED_GENERAL_EVENTS
+    #endif
+
+    /* Wlan Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_2, _NOTIFY_WLAN_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_2, _WlanEventHdl) (SlWlanEvent_t *);
+    #define SlExtLib2WlanEventHandler   __CONCAT2(SL_EXT_LIB_2, _WlanEventHdl)
+
+    #undef EXT_LIB_REGISTERED_WLAN_EVENTS
+    #define EXT_LIB_REGISTERED_WLAN_EVENTS
+    #endif
+
+    /* NetApp Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_2, _NOTIFY_NETAPP_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_2, _NetAppEventHdl) (SlNetAppEvent_t *);
+    #define SlExtLib2NetAppEventHandler __CONCAT2(SL_EXT_LIB_2, _NetAppEventHdl)
+
+    #undef EXT_LIB_REGISTERED_NETAPP_EVENTS
+    #define EXT_LIB_REGISTERED_NETAPP_EVENTS
+    #endif
+
+    /* Http Server Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_2, _NOTIFY_HTTP_SERVER_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_2, _HttpServerEventHdl) (SlHttpServerEvent_t* , SlHttpServerResponse_t*);
+    #define SlExtLib2HttpServerEventHandler __CONCAT2(SL_EXT_LIB_2, _HttpServerEventHdl)
+
+    #undef EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS
+    #define EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS
+    #endif
+
+    /* Socket Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_2, _NOTIFY_SOCK_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_2, _SockEventHdl) (SlSockEvent_t *);
+    #define SlExtLib2SockEventHandler __CONCAT2(SL_EXT_LIB_2, _SockEventHdl)
+
+    #undef EXT_LIB_REGISTERED_SOCK_EVENTS
+    #define EXT_LIB_REGISTERED_SOCK_EVENTS
+    #endif
+
+#endif
+
+
+#ifdef SL_EXT_LIB_3
+
+    /* General Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_3, _NOTIFY_GENERAL_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_3, _GeneralEventHdl) (SlDeviceEvent_t *);
+    #define SlExtLib3GeneralEventHandler   __CONCAT2(SL_EXT_LIB_3, _GeneralEventHdl)
+
+    #undef EXT_LIB_REGISTERED_GENERAL_EVENTS
+    #define EXT_LIB_REGISTERED_GENERAL_EVENTS
+    #endif
+
+    /* Wlan Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_3, _NOTIFY_WLAN_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_3, _WlanEventHdl) (SlWlanEvent_t *);
+    #define SlExtLib3WlanEventHandler   __CONCAT2(SL_EXT_LIB_3, _WlanEventHdl)
+
+    #undef EXT_LIB_REGISTERED_WLAN_EVENTS
+    #define EXT_LIB_REGISTERED_WLAN_EVENTS
+    #endif
+
+    /* NetApp Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_3, _NOTIFY_NETAPP_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_3, _NetAppEventHdl) (SlNetAppEvent_t *);
+    #define SlExtLib3NetAppEventHandler __CONCAT2(SL_EXT_LIB_3, _NetAppEventHdl)
+
+    #undef EXT_LIB_REGISTERED_NETAPP_EVENTS
+    #define EXT_LIB_REGISTERED_NETAPP_EVENTS
+    #endif
+
+    /* Http Server Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_3, _NOTIFY_HTTP_SERVER_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_3, _HttpServerEventHdl) (SlHttpServerEvent_t* , SlHttpServerResponse_t*);
+    #define SlExtLib3HttpServerEventHandler __CONCAT2(SL_EXT_LIB_3, _HttpServerEventHdl)
+
+    #undef EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS
+    #define EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS
+    #endif
+
+    /* Socket Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_3, _NOTIFY_SOCK_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_3, _SockEventHdl) (SlSockEvent_t *);
+    #define SlExtLib3SockEventHandler __CONCAT2(SL_EXT_LIB_3, _SockEventHdl)
+
+    #undef EXT_LIB_REGISTERED_SOCK_EVENTS
+    #define EXT_LIB_REGISTERED_SOCK_EVENTS
+    #endif
+
+#endif
+
+
+#ifdef SL_EXT_LIB_4
+
+    /* General Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_4, _NOTIFY_GENERAL_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_4, _GeneralEventHdl) (SlDeviceEvent_t *);
+    #define SlExtLib4GeneralEventHandler   __CONCAT2(SL_EXT_LIB_4, _GeneralEventHdl)
+
+    #undef EXT_LIB_REGISTERED_GENERAL_EVENTS
+    #define EXT_LIB_REGISTERED_GENERAL_EVENTS
+    #endif
+
+    /* Wlan Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_4, _NOTIFY_WLAN_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_4, _WlanEventHdl) (SlWlanEvent_t *);
+    #define SlExtLib4WlanEventHandler   __CONCAT2(SL_EXT_LIB_4, _WlanEventHdl)
+
+    #undef EXT_LIB_REGISTERED_WLAN_EVENTS
+    #define EXT_LIB_REGISTERED_WLAN_EVENTS
+    #endif
+
+    /* NetApp Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_4, _NOTIFY_NETAPP_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_4, _NetAppEventHdl) (SlNetAppEvent_t *);
+    #define SlExtLib4NetAppEventHandler __CONCAT2(SL_EXT_LIB_4, _NetAppEventHdl)
+
+    #undef EXT_LIB_REGISTERED_NETAPP_EVENTS
+    #define EXT_LIB_REGISTERED_NETAPP_EVENTS
+    #endif
+
+    /* Http Server Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_4, _NOTIFY_HTTP_SERVER_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_4, _HttpServerEventHdl) (SlHttpServerEvent_t* , SlHttpServerResponse_t*);
+    #define SlExtLib4HttpServerEventHandler __CONCAT2(SL_EXT_LIB_4, _HttpServerEventHdl)
+
+    #undef EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS
+    #define EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS
+    #endif
+
+    /* Socket Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_4, _NOTIFY_SOCK_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_4, _SockEventHdl) (SlSockEvent_t *);
+    #define SlExtLib4SockEventHandler __CONCAT2(SL_EXT_LIB_4, _SockEventHdl)
+
+    #undef EXT_LIB_REGISTERED_SOCK_EVENTS
+    #define EXT_LIB_REGISTERED_SOCK_EVENTS
+    #endif
+
+#endif
+
+
+#ifdef SL_EXT_LIB_5
+
+    /* General Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_5, _NOTIFY_GENERAL_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_5, _GeneralEventHdl) (SlDeviceEvent_t *);
+    #define SlExtLib5GeneralEventHandler   __CONCAT2(SL_EXT_LIB_5, _GeneralEventHdl)
+
+    #undef EXT_LIB_REGISTERED_GENERAL_EVENTS
+    #define EXT_LIB_REGISTERED_GENERAL_EVENTS
+    #endif
+
+    /* Wlan Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_5, _NOTIFY_WLAN_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_5, _WlanEventHdl) (SlWlanEvent_t *);
+    #define SlExtLib5WlanEventHandler   __CONCAT2(SL_EXT_LIB_5, _WlanEventHdl)
+
+    #undef EXT_LIB_REGISTERED_WLAN_EVENTS
+    #define EXT_LIB_REGISTERED_WLAN_EVENTS
+    #endif
+
+    /* NetApp Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_5, _NOTIFY_NETAPP_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_5, _NetAppEventHdl) (SlNetAppEvent_t *);
+    #define SlExtLib5NetAppEventHandler __CONCAT2(SL_EXT_LIB_5, _NetAppEventHdl)
+
+    #undef EXT_LIB_REGISTERED_NETAPP_EVENTS
+    #define EXT_LIB_REGISTERED_NETAPP_EVENTS
+    #endif
+
+    /* Http Server Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_5, _NOTIFY_HTTP_SERVER_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_5, _HttpServerEventHdl) (SlHttpServerEvent_t* , SlHttpServerResponse_t*);
+    #define SlExtLib5HttpServerEventHandler __CONCAT2(SL_EXT_LIB_5, _HttpServerEventHdl)
+
+    #undef EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS
+    #define EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS
+    #endif
+
+    /* Socket Event Registration */
+    #if __CONCAT2(SL_EXT_LIB_5, _NOTIFY_SOCK_EVENT)
+    extern _SlEventPropogationStatus_e __CONCAT2(SL_EXT_LIB_5, _SockEventHdl) (SlSockEvent_t *);
+    #define SlExtLib5SockEventHandler __CONCAT2(SL_EXT_LIB_5, _SockEventHdl)
+
+    #undef EXT_LIB_REGISTERED_SOCK_EVENTS
+    #define EXT_LIB_REGISTERED_SOCK_EVENTS
+    #endif
+
+#endif
+
+
+
+#if defined(EXT_LIB_REGISTERED_GENERAL_EVENTS)
+void _SlDrvHandleGeneralEvents(SlDeviceEvent_t *slGeneralEvent);
+#endif
+
+#if defined(EXT_LIB_REGISTERED_WLAN_EVENTS)
+void _SlDrvHandleWlanEvents(SlWlanEvent_t *slWlanEvent);
+#endif
+
+#if defined (EXT_LIB_REGISTERED_NETAPP_EVENTS)
+void _SlDrvHandleNetAppEvents(SlNetAppEvent_t *slNetAppEvent);
+#endif
+
+#if defined(EXT_LIB_REGISTERED_HTTP_SERVER_EVENTS)
+void _SlDrvHandleHttpServerEvents(SlHttpServerEvent_t *slHttpServerEvent, SlHttpServerResponse_t *slHttpServerResponse);
+#endif
+
+
+#if defined(EXT_LIB_REGISTERED_SOCK_EVENTS)
+void _SlDrvHandleSockEvents(SlSockEvent_t *slSockEvent);
+#endif
+
+#ifdef SL_PLATFORM_MULTI_THREADED
+    #include "cc3100_spawn.h"
+#else
+    #include "cc3100_nonos.h"
+#endif
+
+namespace mbed_cc3100 {
+
+/* Async functions description*/
+
+/*!
+    \brief General async event for inspecting general events
+
+    \param[out]      pSlDeviceEvent   pointer to SlDeviceEvent_t
+
+    \par- <b>pSlDeviceEvent->Event = SL_DEVICE_FATAL_ERROR_EVENT </b>
+              - pSlDeviceEvent->EventData.deviceEvent fields:      
+                  - status: An error code indication from the device
+                  - sender: The sender originator which is based on SlErrorSender_e enum 
+
+        - <b>pSlDeviceEvent->Event = SL_DEVICE_ABORT_ERROR_EVENT </b>
+              Indicates a severe error occured and the device stopped 
+              - pSlDeviceEvent->EventData.deviceReport fields:      
+                  - AbortType: An idication of the event type
+                  - AbortData: Additional info about the data error 
+                  
+      
+    \par  Example for fatal error:
+    \code
+    printf(General Event Handler - ID=%d Sender=%d\n\n",
+           pSlDeviceEvent->EventData.deviceEvent.status,  // status of the general event
+           pSlDeviceEvent->EventData.deviceEvent.sender); // sender type
+    \endcode
+    \par Example for abort request:
+    \code
+     printf(Abort type =%d Abort Data=%d\n\n",
+           pSlDeviceEvent->EventData.deviceReport.AbortType,  
+           pSlDeviceEvent->EventData.deviceReport.AbortData); 
+
+    \endcode
+*/
+//#if (defined(sl_GeneralEvtHdlr))
+//void sl_GeneralEvtHdlr(SlDeviceEvent_t *pSlDeviceEvent);
+//#endif
+
+
+/*!
+    \brief WLAN Async event handler
+
+    \param[out]      pSlWlanEvent   pointer to SlWlanEvent_t data
+
+    \par
+             Parameters:
+
+             - <b>pSlWlanEvent->Event = SL_WLAN_CONNECT_EVENT </b>, STA or P2P client connection indication event
+                 - pSlWlanEvent->EventData.STAandP2PModeWlanConnected main fields:
+                      - ssid_name
+                      - ssid_len
+                      - bssid
+                      - go_peer_device_name
+                      - go_peer_device_name_len
+
+             - <b>pSlWlanEvent->Event = SL_WLAN_DISCONNECT_EVENT </b>, STA or P2P client disconnection event
+                 - pSlWlanEvent->EventData.STAandP2PModeDisconnected main fields:
+                      - ssid_name
+                      - ssid_len
+                      - reason_code
+
+             - <b>pSlWlanEvent->Event = SL_WLAN_STA_CONNECTED_EVENT </b>, AP/P2P(Go) connected STA/P2P(Client)
+                  - pSlWlanEvent->EventData.APModeStaConnected fields:
+                      - go_peer_device_name
+                      - mac
+                      - go_peer_device_name_len
+                      - wps_dev_password_id
+                      - own_ssid:  relevant for event sta-connected only
+                      - own_ssid_len:  relevant for event sta-connected only
+
+             - <b>pSlWlanEvent->Event = SL_WLAN_STA_DISCONNECTED_EVENT </b>, AP/P2P(Go) disconnected STA/P2P(Client)
+                  - pSlWlanEvent->EventData.APModestaDisconnected fields:
+                      - go_peer_device_name
+                      - mac
+                      - go_peer_device_name_len
+                      - wps_dev_password_id
+                      - own_ssid:  relevant for event sta-connected only
+                      - own_ssid_len:  relevant for event sta-connected only
+
+             - <b>pSlWlanEvent->Event = SL_WLAN_SMART_CONFIG_COMPLETE_EVENT </b>
+                  - pSlWlanEvent->EventData.smartConfigStartResponse fields:
+                     - status
+                     - ssid_len
+                     - ssid
+                     - private_token_len
+                     - private_token
+
+             - <b>pSlWlanEvent->Event = SL_WLAN_SMART_CONFIG_STOP_EVENT </b>
+                     - pSlWlanEvent->EventData.smartConfigStopResponse fields:
+                         - status
+
+             - <b>pSlWlanEvent->Event = SL_WLAN_P2P_DEV_FOUND_EVENT </b>
+                     - pSlWlanEvent->EventData.P2PModeDevFound fields:
+                         - go_peer_device_name
+                         - mac
+                         - go_peer_device_name_len
+                         - wps_dev_password_id
+                         - own_ssid:  relevant for event sta-connected only
+                         - own_ssid_len:  relevant for event sta-connected only
+
+             - <b>pSlWlanEvent->Event = SL_WLAN_P2P_NEG_REQ_RECEIVED_EVENT </b>
+                      - pSlWlanEvent->EventData.P2PModeNegReqReceived fields
+                          - go_peer_device_name
+                          - mac
+                          - go_peer_device_name_len
+                          - wps_dev_password_id
+                          - own_ssid:  relevant for event sta-connected only
+
+             - <b>pSlWlanEvent->Event = SL_WLAN_CONNECTION_FAILED_EVENT </b>, P2P only
+                       - pSlWlanEvent->EventData.P2PModewlanConnectionFailure fields:
+                           - status
+*/
+//#if (defined(sl_WlanEvtHdlr))
+//void sl_WlanEvtHdlr(SlWlanEvent_t *pSlWlanEvent);
+//#endif
+
+
+/*!
+    \brief NETAPP Async event handler
+
+    \param[out]      pSlNetApp   pointer to SlNetAppEvent_t data
+
+    \par
+             Parameters:
+               - <b>pSlNetApp->Event = SL_NETAPP_IPV4_IPACQUIRED_EVENT</b>, IPV4 acquired event
+                  - pSlNetApp->EventData.ipAcquiredV4 fields:
+                       - ip
+                       - gateway
+                       - dns
+
+              - <b>pSlNetApp->Event = SL_NETAPP_IP_LEASED_EVENT</b>, AP or P2P go dhcp lease event
+                  - pSlNetApp->EventData.ipLeased  fields:
+                       - ip_address
+                       - lease_time
+                       - mac
+
+              - <b>pSlNetApp->Event = SL_NETAPP_IP_RELEASED_EVENT</b>, AP or P2P go dhcp ip release event
+                   - pSlNetApp->EventData.ipReleased fields
+                       - ip_address
+                       - mac
+                       - reason
+
+*/
+//#if (defined(sl_NetAppEvtHdlr))
+//void sl_NetAppEvtHdlr(SlNetAppEvent_t *pSlNetApp);
+//#endif
+
+/*!
+    \brief Socket Async event handler
+
+    \param[out]      pSlSockEvent   pointer to SlSockEvent_t data
+
+    \par
+             Parameters:\n
+             - <b>pSlSockEvent->Event = SL_SOCKET_TX_FAILED_EVENT</b>
+                 - pSlSockEvent->SockTxFailData fields:
+                     - sd
+                     - status
+             - <b>pSlSockEvent->Event = SL_SOCKET_ASYNC_EVENT</b>
+                - pSlSockEvent->SockAsyncData fields:
+                     - sd
+                     - type: SSL_ACCEPT  or RX_FRAGMENTATION_TOO_BIG or OTHER_SIDE_CLOSE_SSL_DATA_NOT_ENCRYPTED
+                     - val
+
+*/
+//#if (defined(sl_SockEvtHdlr))
+//void sl_SockEvtHdlr(SlSockEvent_t *pSlSockEvent);
+//#endif
+
+/*!
+    \brief HTTP server async event
+
+    \param[out] pSlHttpServerEvent   pointer to SlHttpServerEvent_t
+    \param[in] pSlHttpServerResponse pointer to SlHttpServerResponse_t
+
+    \par
+          Parameters: \n
+
+          - <b>pSlHttpServerEvent->Event = SL_NETAPP_HTTPGETTOKENVALUE_EVENT</b>
+             - pSlHttpServerEvent->EventData fields:
+                 - httpTokenName
+                     - data
+                     - len
+             - pSlHttpServerResponse->ResponseData fields:
+                     - data
+                     - len
+
+          - <b>pSlHttpServerEvent->Event = SL_NETAPP_HTTPPOSTTOKENVALUE_EVENT</b>
+              - pSlHttpServerEvent->EventData.httpPostData fields:
+                     - action
+                     - token_name
+                     - token_value
+              - pSlHttpServerResponse->ResponseData fields:
+                     - data
+                     - len
+
+*/
+//#if (defined(sl_HttpServerCallback))
+//void sl_HttpServerCallback(SlHttpServerEvent_t *pSlHttpServerEvent, SlHttpServerResponse_t *pSlHttpServerResponse);
+//#endif
+/*!
+
+ Close the Doxygen group.
+ @}
+
+ */
+
+}//namespace mbed_cc3100
+
+#endif    /*  __SIMPLELINK_H__ */
+
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_sl_common.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_sl_common.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,96 @@
+/*
+ * sl_config.h - get time sample application
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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.
+ *
+ */
+
+#ifndef SL_CONFIG_H_
+#define SL_CONFIG_H_
+
+//*****************************************************************************
+//
+// If building with a C++ compiler, make all of the definitions in this header
+// have a C binding.
+//
+//*****************************************************************************
+
+/**/
+
+namespace mbed_cc3100 {
+
+#define LOOP_FOREVER() \
+            {\
+                while(1); \
+            }
+
+#define ASSERT_ON_ERROR(error_code) \
+            {\
+                /* Handling the error-codes is specific to the application */ \
+                if (error_code < 0) return error_code; \
+                /* else, continue w/ execution */ \
+            }
+
+
+/*
+ * Values for below macros shall be modified per the access-point's (AP) properties
+ * SimpleLink device will connect to following AP when the application is executed
+ */
+#define SSID_NAME         "*********"
+//#define SSID_NAME       "*"         /* Access point name to connect to. */
+#define SEC_TYPE        SL_SEC_TYPE_WPA_WPA2    /* Security type of the Access point */
+#define PASSKEY           "**********"
+//#define PASSKEY         "********"                  /* Password in case of secure AP */
+#define PASSKEY_LEN     strlen(PASSKEY)  /* Password length in case of secure AP */
+
+/* Configuration of the device when it comes up in AP mode */
+#define SSID_AP_MODE       "mysimplelink"       /* SSID of the CC3100 in AP mode */
+#define PASSWORD_AP_MODE   ""                  /* Password of CC3100 AP */
+#define SEC_TYPE_AP_MODE   SL_SEC_TYPE_OPEN    /* Can take SL_SEC_TYPE_WEP or
+* SL_SEC_TYPE_WPA as well */
+
+/*
+ * Values for below macros shall be modified based on current time
+ */
+#define DATE        26      /* Current Date */
+#define MONTH       4       /* Month */
+#define YEAR        2015    /* Current year */
+#define HOUR        17      /* Time - hours */
+#define MINUTE      06      /* Time - minutes */
+#define SECOND      0       /* Time - seconds */
+
+#define SUCCESS             0
+
+}//namespace mbed_cc3100
+
+#endif /*__SL_CONFIG_H__*/
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_socket.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_socket.cpp	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,952 @@
+/*
+ * socket.c - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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 files                                                             */
+/*****************************************************************************/
+#include "cc3100_simplelink.h"
+#include "cc3100_protocol.h"
+#include "cc3100_driver.h"
+
+#include "cc3100_socket.h"
+
+namespace mbed_cc3100 {
+	
+/*  Note: parsing of family and port in the generic way for all IPV4, IPV6 and EUI48 */
+    /*  is possible as _i32 as these parameters are in the same offset and size for these */
+    /*  three families. */
+#define SL_SOCKET_PAYLOAD_BASE (1350)
+
+const uint8_t _SlPayloadByProtocolLUT[16] = 
+{
+    (1472 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_UDP_IPV4 */
+    (1460 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_TCP_IPV4 */
+    (1452 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_UDP_IPV6 */
+    (1440 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_TCP_IPV6 */
+    (1386 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_TCP_IPV4_SECURE */
+    (1386 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_UDP_IPV4_SECURE */
+    (1396 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_UDP_IPV6_SECURE */
+    (1396 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_TCP_IPV6_SECURE */
+    (1476 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_RAW_TRANCEIVER */
+    (1514 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_RAW_PACKET */
+    (1480 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_RAW_IP4 */
+    (1480 - SL_SOCKET_PAYLOAD_BASE), /* SL_SOCKET_PAYLOAD_TYPE_RAW_IP6 */
+    (1440 - SL_SOCKET_PAYLOAD_BASE), /* Default */
+    (1440 - SL_SOCKET_PAYLOAD_BASE), /* Default */
+    (1440 - SL_SOCKET_PAYLOAD_BASE), /* Default */
+    (1440 - SL_SOCKET_PAYLOAD_BASE)  /* Default */
+};	
+
+
+cc3100_socket::cc3100_socket(cc3100_driver &driver, cc3100_nonos &nonos)
+    : _driver(driver), _nonos(nonos)
+{
+
+}
+
+cc3100_socket::~cc3100_socket()
+{
+
+}
+
+/*******************************************************************************/
+/* Functions                                                                   */
+/*******************************************************************************/
+
+/* ******************************************************************************/
+/*  _sl_BuildAddress */
+/* ******************************************************************************/
+void cc3100_socket::_sl_BuildAddress(const SlSockAddr_t *addr, _SocketAddrCommand_u *pCmd)
+{
+    /* Note: parsing of family and port in the generic way for all IPV4, IPV6 and EUI48
+           is possible as long as these parameters are in the same offset and size for these
+           three families. */
+    pCmd->IpV4.FamilyAndFlags = (addr->sa_family << 4) & 0xF0;
+    pCmd->IpV4.port = ((SlSockAddrIn_t *)addr)->sin_port;
+
+    if(SL_AF_INET == addr->sa_family) {
+        pCmd->IpV4.address  = ((SlSockAddrIn_t *)addr)->sin_addr.s_addr;
+    } else if (SL_AF_INET6_EUI_48 == addr->sa_family ) {
+        memcpy( pCmd->IpV6EUI48.address,((SlSockAddrIn6_t *)addr)->sin6_addr._S6_un._S6_u8, 6);
+    }
+#ifdef SL_SUPPORT_IPV6
+    else {
+        memcpy(pCmd->IpV6.address, ((sockaddr_in6 *)addr)->sin6_addr._S6_un._S6_u32, 16 );
+    }
+#endif
+}
+
+/* ******************************************************************************/
+/*  _sl_TruncatePayloadByProtocol */
+/* ******************************************************************************/
+uint16_t cc3100_socket::_sl_TruncatePayloadByProtocol(const int16_t sd,const uint16_t length)
+{
+
+    uint32_t maxLength;
+
+   maxLength = SL_SOCKET_PAYLOAD_BASE + _SlPayloadByProtocolLUT[((sd & SL_SOCKET_PAYLOAD_TYPE_MASK) >> 4)];
+   
+   if( length > maxLength )
+   {
+      return maxLength;
+   }
+   else
+   {
+      return length;
+   }
+
+}
+
+/*******************************************************************************/
+/*  _sl_ParseAddress */
+/*******************************************************************************/
+#ifndef SL_TINY_EXT
+void cc3100_socket::_sl_ParseAddress(_SocketAddrResponse_u    *pRsp, SlSockAddr_t *addr, SlSocklen_t *addrlen)
+{
+    /*  Note: parsing of family and port in the generic way for all IPV4, IPV6 and EUI48 */
+    /*  is possible as long as these parameters are in the same offset and size for these */
+    /*  three families. */
+    addr->sa_family                 = pRsp->IpV4.family;
+    ((SlSockAddrIn_t *)addr)->sin_port = pRsp->IpV4.port;
+
+    *addrlen = (SL_AF_INET == addr->sa_family) ? sizeof(SlSockAddrIn_t) : sizeof(SlSockAddrIn6_t);
+
+    if(SL_AF_INET == addr->sa_family) {
+        ((SlSockAddrIn_t *)addr)->sin_addr.s_addr  = pRsp->IpV4.address;
+    } else if (SL_AF_INET6_EUI_48 == addr->sa_family ) {
+        memcpy(((SlSockAddrIn6_t *)addr)->sin6_addr._S6_un._S6_u8, pRsp->IpV6EUI48.address, 6);
+    }
+#ifdef SL_SUPPORT_IPV6
+    else {
+        memcpy(((sockaddr_in6 *)addr)->sin6_addr._S6_un._S6_u32, pRsp->IpV6.address, 16);
+    }
+#endif
+}
+#endif
+
+/*******************************************************************************/
+/* sl_Socket */
+/*******************************************************************************/
+typedef union {
+    uint32_t                Dummy;
+    _SocketCommand_t 	Cmd;
+    _SocketResponse_t	Rsp;
+} _SlSockSocketMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_Socket)
+const _SlCmdCtrl_t _SlSockSocketCmdCtrl = {
+    SL_OPCODE_SOCKET_SOCKET,
+    sizeof(_SocketCommand_t),
+    sizeof(_SocketResponse_t)
+};
+
+int16_t cc3100_socket::sl_Socket(int16_t Domain, int16_t Type, int16_t Protocol)
+{
+    _SlSockSocketMsg_u  Msg;
+
+    Msg.Cmd.Domain	    = (uint8_t)Domain;
+    Msg.Cmd.Type     	= (uint8_t)Type;
+    Msg.Cmd.Protocol 	= (uint8_t)Protocol;
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlSockSocketCmdCtrl, &Msg, NULL));
+
+    if( Msg.Rsp.statusOrLen < 0 ) {
+        return( Msg.Rsp.statusOrLen );
+    } else {
+        return (int16_t)((uint8_t)Msg.Rsp.sd);
+    }
+}
+#endif
+
+/*******************************************************************************/
+/*  sl_Close  */
+/*******************************************************************************/
+typedef union {
+    _CloseCommand_t	    Cmd;
+    _SocketResponse_t	Rsp;
+} _SlSockCloseMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_Close)
+const _SlCmdCtrl_t _SlSockCloseCmdCtrl = {
+    SL_OPCODE_SOCKET_CLOSE,
+    sizeof(_CloseCommand_t),
+    sizeof(_SocketResponse_t)
+};
+
+int16_t cc3100_socket::sl_Close(int16_t sd)
+{
+    _SlSockCloseMsg_u   Msg;
+
+    Msg.Cmd.sd = (uint8_t)sd;
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlSockCloseCmdCtrl, &Msg, NULL));
+
+    return Msg.Rsp.statusOrLen;
+}
+#endif
+
+/*******************************************************************************/
+/*  sl_Bind */
+/*******************************************************************************/
+typedef union {
+    _SocketAddrCommand_u    Cmd;
+    _SocketResponse_t	    Rsp;
+} _SlSockBindMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_Bind)
+int16_t cc3100_socket::sl_Bind(int16_t sd, const SlSockAddr_t *addr, int16_t addrlen)
+{
+    _SlSockBindMsg_u    Msg;
+    _SlCmdCtrl_t         CmdCtrl = {0, 0, sizeof(_SocketResponse_t)};
+
+    switch(addr->sa_family) {
+        case SL_AF_INET :
+            CmdCtrl.Opcode = SL_OPCODE_SOCKET_BIND;
+            CmdCtrl.TxDescLen = sizeof(_SocketAddrIPv4Command_t);
+            break;
+#ifndef SL_TINY_EXT             
+        case SL_AF_INET6_EUI_48:
+            CmdCtrl.Opcode = SL_OPCODE_SOCKET_BIND_V6;
+            CmdCtrl.TxDescLen = sizeof(_SocketAddrIPv6EUI48Command_t);
+            break;
+#ifdef SL_SUPPORT_IPV6
+        case AF_INET6:
+            CmdCtrl.Opcode = SL_OPCODE_SOCKET_BIND_V6;
+            CmdCtrl.TxDescLen = sizeof(_SocketAddrIPv6Command_t);
+            break;
+#endif
+#endif
+        case SL_AF_RF   :
+        default:
+            return SL_RET_CODE_INVALID_INPUT;
+    }
+
+    Msg.Cmd.IpV4.lenOrPadding = 0;
+    Msg.Cmd.IpV4.sd = (uint8_t)sd;
+
+    _sl_BuildAddress(addr, &Msg.Cmd);
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&CmdCtrl, &Msg, NULL));
+
+    return Msg.Rsp.statusOrLen;
+}
+#endif
+
+/*******************************************************************************/
+/*  sl_Sendto */
+/*******************************************************************************/
+typedef union {
+    _SocketAddrCommand_u    Cmd;
+    /*  no response for 'sendto' commands*/
+} _SlSendtoMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_SendTo)
+int16_t cc3100_socket::sl_SendTo(int16_t sd, const void *pBuf, int16_t Len, int16_t flags, const SlSockAddr_t *to, SlSocklen_t tolen)
+{
+    _SlSendtoMsg_u   Msg;
+    _SlCmdCtrl_t     CmdCtrl = {0, 0, 0};
+    _SlCmdExt_t      CmdExt;
+    uint16_t         ChunkLen;
+    int16_t          RetVal;
+
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.TxPayloadLen = (uint16_t)Len;
+    CmdExt.pTxPayload = (uint8_t *)pBuf;
+
+    switch(to->sa_family) {
+        case SL_AF_INET:
+            CmdCtrl.Opcode = SL_OPCODE_SOCKET_SENDTO;
+            CmdCtrl.TxDescLen = sizeof(_SocketAddrIPv4Command_t);
+            break;
+#ifndef SL_TINY_EXT            
+        case SL_AF_INET6_EUI_48:
+            CmdCtrl.Opcode = SL_OPCODE_SOCKET_BIND_V6;
+            CmdCtrl.TxDescLen = sizeof(_SocketAddrIPv6EUI48Command_t);
+            break;
+#ifdef SL_SUPPORT_IPV6
+        case AF_INET6:
+            CmdCtrl.Opcode = SL_OPCODE_SOCKET_SENDTO_V6;
+            CmdCtrl.TxDescLen = sizeof(_SocketAddrIPv6Command_t);
+            break;
+#endif
+#endif
+        case SL_AF_RF:
+        default:
+            return SL_RET_CODE_INVALID_INPUT;
+    }
+
+    ChunkLen = _sl_TruncatePayloadByProtocol(sd,Len);
+    Msg.Cmd.IpV4.lenOrPadding = ChunkLen;
+    CmdExt.TxPayloadLen = ChunkLen;
+
+    Msg.Cmd.IpV4.sd = (unsigned char)sd;
+
+    _sl_BuildAddress(to, &Msg.Cmd);
+    
+    Msg.Cmd.IpV4.FamilyAndFlags |= flags & 0x0F;
+    
+    do {
+        RetVal = _driver._SlDrvDataWriteOp((_SlSd_t)sd, &CmdCtrl, &Msg, &CmdExt);
+        
+        if(SL_OS_RET_CODE_OK == RetVal) {
+            CmdExt.pTxPayload += ChunkLen;
+            ChunkLen = (uint16_t)((unsigned char *)pBuf + Len - CmdExt.pTxPayload);
+            ChunkLen = _sl_TruncatePayloadByProtocol(sd,ChunkLen);
+            CmdExt.TxPayloadLen = ChunkLen;
+            Msg.Cmd.IpV4.lenOrPadding = ChunkLen;
+        } else {
+            return RetVal;
+        }
+    } while(ChunkLen > 0);
+
+    return (int16_t)Len;
+}
+#endif
+
+/*******************************************************************************/
+/*  sl_Recvfrom */
+/*******************************************************************************/
+typedef union {
+    _sendRecvCommand_t	    Cmd;
+    _SocketAddrResponse_u	Rsp;
+} _SlRecvfromMsg_u;
+
+const _SlCmdCtrl_t _SlRecvfomCmdCtrl = {
+    SL_OPCODE_SOCKET_RECVFROM,
+    sizeof(_sendRecvCommand_t),
+    sizeof(_SocketAddrResponse_u)
+};
+
+#if _SL_INCLUDE_FUNC(sl_RecvFrom)
+int16_t cc3100_socket::sl_RecvFrom(int16_t sd, void *buf, int16_t Len, int16_t flags, SlSockAddr_t *from, SlSocklen_t *fromlen)
+{
+    _SlRecvfromMsg_u    Msg;
+    _SlCmdExt_t         CmdExt;
+    int16_t                 RetVal;
+
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.RxPayloadLen = Len;
+    CmdExt.pRxPayload = (uint8_t *)buf;
+
+    Msg.Cmd.sd = (uint8_t)sd;
+    Msg.Cmd.StatusOrLen = Len;
+    /*  no size truncation in recv path */
+    CmdExt.RxPayloadLen = Msg.Cmd.StatusOrLen;
+    
+    Msg.Cmd.FamilyAndFlags = flags & 0x0F;
+
+    if(sizeof(SlSockAddrIn_t) == *fromlen) {
+        Msg.Cmd.FamilyAndFlags |= (SL_AF_INET << 4);
+    }
+    else if (sizeof(SlSockAddrIn6_t) == *fromlen)
+    {
+        Msg.Cmd.FamilyAndFlags |= (SL_AF_INET6 << 4);
+    } 
+    else 
+    {
+        return SL_RET_CODE_INVALID_INPUT;
+    }
+
+    RetVal = _driver._SlDrvDataReadOp((_SlSd_t)sd, (_SlCmdCtrl_t *)&_SlRecvfomCmdCtrl, &Msg, &CmdExt);
+    
+    if( RetVal != SL_OS_RET_CODE_OK ) {
+        return RetVal;
+    }
+    
+    RetVal = Msg.Rsp.IpV4.statusOrLen;
+
+    if(RetVal >= 0) {
+        VERIFY_PROTOCOL(sd == Msg.Rsp.IpV4.sd);
+#if 0
+        _sl_ParseAddress(&Msg.Rsp, from, fromlen);
+#else
+        from->sa_family = Msg.Rsp.IpV4.family;
+        if(SL_AF_INET == from->sa_family) {
+            ((SlSockAddrIn_t *)from)->sin_port = Msg.Rsp.IpV4.port;
+            ((SlSockAddrIn_t *)from)->sin_addr.s_addr = Msg.Rsp.IpV4.address;
+            *fromlen = sizeof(SlSockAddrIn_t);
+        } else if (SL_AF_INET6_EUI_48 == from->sa_family ) {
+            ((SlSockAddrIn6_t *)from)->sin6_port  = Msg.Rsp.IpV6EUI48.port;
+            memcpy(((SlSockAddrIn6_t *)from)->sin6_addr._S6_un._S6_u8, Msg.Rsp.IpV6EUI48.address, 6);
+        }
+#ifdef SL_SUPPORT_IPV6
+        else if(AF_INET6 == from->sa_family) {
+            VERIFY_PROTOCOL(*fromlen >= sizeof(sockaddr_in6));
+
+            ((sockaddr_in6 *)from)->sin6_port = Msg.Rsp.IpV6.port;
+            memcpy(((sockaddr_in6 *)from)->sin6_addr._S6_un._S6_u32, Msg.Rsp.IpV6.address, 16);
+            *fromlen = sizeof(sockaddr_in6);
+        }
+#endif
+#endif
+    }
+
+    return (int16_t)RetVal;
+}
+#endif
+
+/*******************************************************************************/
+/*  sl_Connect */
+/*******************************************************************************/
+typedef union {
+    _SocketAddrCommand_u    Cmd;
+    _SocketResponse_t	    Rsp;
+} _SlSockConnectMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_Connect)
+int16_t cc3100_socket::sl_Connect(int16_t sd, const SlSockAddr_t *addr, int16_t addrlen)
+{
+    _SlSockConnectMsg_u  Msg;
+    _SlReturnVal_t       RetVal;
+    _SlCmdCtrl_t         CmdCtrl = {0, 0, sizeof(_SocketResponse_t)};
+    _SocketResponse_t    AsyncRsp;
+    uint8_t ObjIdx = MAX_CONCURRENT_ACTIONS;
+
+
+    switch(addr->sa_family) {
+        case SL_AF_INET :
+            CmdCtrl.Opcode = SL_OPCODE_SOCKET_CONNECT;
+            CmdCtrl.TxDescLen = sizeof(_SocketAddrIPv4Command_t);
+            /* Do nothing - cmd already initialized to this type */
+            break;
+        case  SL_AF_INET6_EUI_48:
+            CmdCtrl.Opcode = SL_OPCODE_SOCKET_CONNECT_V6;
+            CmdCtrl.TxDescLen = sizeof(_SocketAddrIPv6EUI48Command_t);
+            break;
+#ifdef SL_SUPPORT_IPV6
+        case AF_INET6:
+            CmdCtrl.Opcode = SL_OPCODE_SOCKET_CONNECT_V6;
+            CmdCtrl.TxDescLen = sizeof(_SocketAddrIPv6Command_t);
+            break;
+#endif
+        case SL_AF_RF   :
+        default:
+            return SL_RET_CODE_INVALID_INPUT;
+    }
+
+    Msg.Cmd.IpV4.lenOrPadding = 0;
+    Msg.Cmd.IpV4.sd = (uint8_t)sd;
+
+    _sl_BuildAddress(addr, &Msg.Cmd);
+
+
+    ObjIdx = _driver._SlDrvProtectAsyncRespSetting((uint8_t*)&AsyncRsp, CONNECT_ID, sd  & BSD_SOCKET_ID_MASK);
+
+    if (MAX_CONCURRENT_ACTIONS == ObjIdx)
+    {
+        return SL_POOL_IS_EMPTY;
+    }
+
+    /* send the command */
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&CmdCtrl, &Msg, NULL));
+    VERIFY_PROTOCOL(Msg.Rsp.sd == sd)
+
+    RetVal = Msg.Rsp.statusOrLen;
+
+    if(SL_RET_CODE_OK == RetVal) {
+        /*  wait for async and get Data Read parameters */
+        _driver._SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj);
+
+        VERIFY_PROTOCOL(AsyncRsp.sd == sd);
+
+        RetVal = AsyncRsp.statusOrLen;
+    }
+    _driver._SlDrvReleasePoolObj(ObjIdx);
+    return RetVal;
+}
+#endif
+
+/*******************************************************************************/
+/*  sl_Send */
+/*******************************************************************************/
+typedef union {
+    _sendRecvCommand_t    Cmd;
+    /*  no response for 'sendto' commands*/
+} _SlSendMsg_u;
+
+const _SlCmdCtrl_t _SlSendCmdCtrl = {
+    SL_OPCODE_SOCKET_SEND,
+    sizeof(_sendRecvCommand_t),
+    0
+};
+
+#if _SL_INCLUDE_FUNC(sl_Send)
+int16_t cc3100_socket::sl_Send(int16_t sd, const void *pBuf, int16_t Len, int16_t flags)
+{
+    _SlSendMsg_u   Msg;
+    _SlCmdExt_t    CmdExt;
+    uint16_t         ChunkLen;
+    int16_t            RetVal;
+    uint32_t         tempVal;
+    uint8_t  runSingleChunk = FALSE;
+
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.TxPayloadLen = Len;
+    CmdExt.pTxPayload = (uint8_t *)pBuf;
+
+    /* Only for RAW transceiver type socket, relay the flags parameter in the 2 bytes (4 byte aligned) before the actual payload */
+    if ((sd & SL_SOCKET_PAYLOAD_TYPE_MASK) == SL_SOCKET_PAYLOAD_TYPE_RAW_TRANCEIVER) {
+        tempVal = flags;
+        CmdExt.pRxPayload = (uint8_t *)&tempVal;
+        CmdExt.RxPayloadLen = -4; /* mark as Rx data to send */
+        runSingleChunk = TRUE;
+    } else {
+        CmdExt.pRxPayload = NULL;
+    }
+
+    ChunkLen = _sl_TruncatePayloadByProtocol(sd,Len);
+    CmdExt.TxPayloadLen = ChunkLen;
+
+    Msg.Cmd.StatusOrLen = ChunkLen;
+    Msg.Cmd.sd = (uint8_t)sd;
+    Msg.Cmd.FamilyAndFlags |= flags & 0x0F;
+
+    do {
+        RetVal = _driver._SlDrvDataWriteOp((uint8_t)sd, (_SlCmdCtrl_t *)&_SlSendCmdCtrl, &Msg, &CmdExt);
+        if(SL_OS_RET_CODE_OK == RetVal) {
+            CmdExt.pTxPayload += ChunkLen;
+            ChunkLen = (uint8_t *)pBuf + Len - CmdExt.pTxPayload;
+            ChunkLen = _sl_TruncatePayloadByProtocol(sd,ChunkLen);
+            CmdExt.TxPayloadLen = ChunkLen;
+            Msg.Cmd.StatusOrLen = ChunkLen;
+        } else {
+            return RetVal;
+        }
+    } while((ChunkLen > 0) && (runSingleChunk==FALSE));
+
+    return (int16_t)Len;
+}
+#endif
+
+/*******************************************************************************/
+/*  sl_Listen */
+/*******************************************************************************/
+typedef union {
+    _ListenCommand_t    Cmd;
+    _BasicResponse_t    Rsp;
+} _SlListenMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_Listen)
+const _SlCmdCtrl_t _SlListenCmdCtrl = {
+    SL_OPCODE_SOCKET_LISTEN,
+    sizeof(_ListenCommand_t),
+    sizeof(_BasicResponse_t),
+};
+
+int16_t cc3100_socket::sl_Listen(int16_t sd, int16_t backlog)
+{
+    _SlListenMsg_u  Msg;
+
+    Msg.Cmd.sd = (uint8_t)sd;
+    Msg.Cmd.backlog = (uint8_t)backlog;
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlListenCmdCtrl, &Msg, NULL));
+
+    return (int16_t)Msg.Rsp.status;
+}
+#endif
+
+/*******************************************************************************/
+/*  sl_Accept */
+/*******************************************************************************/
+typedef union {
+    _AcceptCommand_t    Cmd;
+    _SocketResponse_t   Rsp;
+} _SlSockAcceptMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_Accept)
+const _SlCmdCtrl_t _SlAcceptCmdCtrl = {
+    SL_OPCODE_SOCKET_ACCEPT,
+    sizeof(_AcceptCommand_t),
+    sizeof(_BasicResponse_t),
+};
+
+int16_t cc3100_socket::sl_Accept(int16_t sd, SlSockAddr_t *addr, SlSocklen_t *addrlen)
+{
+    _SlSockAcceptMsg_u      Msg;
+    _SlReturnVal_t          RetVal;
+    _SocketAddrResponse_u   AsyncRsp;
+
+    uint8_t ObjIdx = MAX_CONCURRENT_ACTIONS;
+
+
+    Msg.Cmd.sd = (uint8_t)sd;
+    Msg.Cmd.family = (sizeof(SlSockAddrIn_t) == *addrlen) ? SL_AF_INET : SL_AF_INET6;
+
+    ObjIdx = _driver._SlDrvProtectAsyncRespSetting((uint8_t*)&AsyncRsp, ACCEPT_ID, sd  & BSD_SOCKET_ID_MASK );
+
+    if (MAX_CONCURRENT_ACTIONS == ObjIdx)
+    {
+        return SL_POOL_IS_EMPTY;
+    }
+    
+    /* send the command */
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlAcceptCmdCtrl, &Msg, NULL));
+    VERIFY_PROTOCOL(Msg.Rsp.sd == sd);
+
+    RetVal = Msg.Rsp.statusOrLen;
+
+    if(SL_OS_RET_CODE_OK == RetVal) {
+        /*  wait for async and get Data Read parameters */
+        _driver._SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj);
+
+        VERIFY_PROTOCOL(AsyncRsp.IpV4.sd == sd);
+
+        RetVal = AsyncRsp.IpV4.statusOrLen;
+        if( (NULL != addr) && (NULL != addrlen) ) {
+#if 0 /*  Kept for backup */
+            _sl_ParseAddress(&AsyncRsp, addr, addrlen);
+#else
+            addr->sa_family = AsyncRsp.IpV4.family;
+
+            if(SL_AF_INET == addr->sa_family) {
+                if( *addrlen == sizeof( SlSockAddrIn_t ) ) {
+                    ((SlSockAddrIn_t *)addr)->sin_port         = AsyncRsp.IpV4.port;
+                    ((SlSockAddrIn_t *)addr)->sin_addr.s_addr  = AsyncRsp.IpV4.address;
+                } else {
+                    *addrlen = 0;
+                }
+            } else if (SL_AF_INET6_EUI_48 == addr->sa_family ) {
+                if( *addrlen == sizeof( SlSockAddrIn6_t ) ) {
+                    ((SlSockAddrIn6_t *)addr)->sin6_port                   = AsyncRsp.IpV6EUI48.port    ;
+                    /*  will be called from here and from _sl_BuildAddress*/
+                    memcpy(((SlSockAddrIn6_t *)addr)->sin6_addr._S6_un._S6_u8, AsyncRsp.IpV6EUI48.address, 6);
+                } else {
+                    *addrlen = 0;
+                }
+            }
+#ifdef SL_SUPPORT_IPV6
+            else {
+                if( *addrlen == sizeof( sockaddr_in6 ) ) {
+                    ((sockaddr_in6 *)addr)->sin6_port                   = AsyncRsp.IpV6.port    ;
+                    memcpy(((sockaddr_in6 *)addr)->sin6_addr._S6_un._S6_u32, AsyncRsp.IpV6.address, 16);
+                } else {
+                    *addrlen = 0;
+                }
+            }
+#endif
+#endif
+        }
+    }
+
+    _driver._SlDrvReleasePoolObj(ObjIdx);
+    return (int16_t)RetVal;
+}
+#endif
+
+
+/*******************************************************************************/
+/*  sl_Htonl */
+/*******************************************************************************/
+uint32_t cc3100_socket::sl_Htonl( uint32_t val )
+{
+    uint32_t i = 1;
+    int8_t *p = (int8_t *)&i;
+    if (p[0] == 1) { /* little endian */
+        p[0] = ((int8_t* )&val)[3];
+        p[1] = ((int8_t* )&val)[2];
+        p[2] = ((int8_t* )&val)[1];
+        p[3] = ((int8_t* )&val)[0];
+        return i;
+    } else { /* big endian */
+        return val;
+    }
+}
+
+/*******************************************************************************/
+/*  sl_Htonl */
+/*******************************************************************************/
+uint16_t cc3100_socket::sl_Htons( uint16_t val )
+{
+    int16_t i = 1;
+    int8_t *p = (int8_t *)&i;
+    if (p[0] == 1) { /* little endian */
+        p[0] = ((int8_t* )&val)[1];
+        p[1] = ((int8_t* )&val)[0];
+        return i;
+    } else { /* big endian */
+        return val;
+    }
+}
+
+/*******************************************************************************/
+/*  sl_Recv */
+/*******************************************************************************/
+typedef union {
+    _sendRecvCommand_t  Cmd;
+    _SocketResponse_t   Rsp;
+} _SlRecvMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_Recv)
+const _SlCmdCtrl_t _SlRecvCmdCtrl = {
+    SL_OPCODE_SOCKET_RECV,
+    sizeof(_sendRecvCommand_t),
+    sizeof(_SocketResponse_t)
+};
+
+int16_t cc3100_socket::sl_Recv(int16_t sd, void *pBuf, int16_t Len, int16_t flags)
+{
+    _SlRecvMsg_u    Msg;
+    _SlCmdExt_t     CmdExt;
+    _SlReturnVal_t status;
+
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.RxPayloadLen = Len;
+    CmdExt.pRxPayload = (uint8_t *)pBuf;
+
+    Msg.Cmd.sd = (uint8_t)sd;
+    Msg.Cmd.StatusOrLen = Len;
+
+    /*  no size truncation in recv path */
+    CmdExt.RxPayloadLen = Msg.Cmd.StatusOrLen;
+
+    Msg.Cmd.FamilyAndFlags = flags & 0x0F;
+
+    status = _driver._SlDrvDataReadOp((_SlSd_t)sd, (_SlCmdCtrl_t *)&_SlRecvCmdCtrl, &Msg, &CmdExt);
+    if( status != SL_OS_RET_CODE_OK ) {
+        return status;
+    }
+
+    /*  if the Device side sends less than expected it is not the Driver's role */
+    /*  the returned value could be smaller than the requested size */
+    return (int16_t)Msg.Rsp.statusOrLen;
+}
+#endif
+
+/*******************************************************************************/
+/*  sl_SetSockOpt */
+/*******************************************************************************/
+typedef union {
+    _setSockOptCommand_t    Cmd;
+    _SocketResponse_t       Rsp;
+} _SlSetSockOptMsg_u;
+
+const _SlCmdCtrl_t _SlSetSockOptCmdCtrl = {
+    SL_OPCODE_SOCKET_SETSOCKOPT,
+    sizeof(_setSockOptCommand_t),
+    sizeof(_SocketResponse_t)
+};
+
+#if _SL_INCLUDE_FUNC(sl_SetSockOpt)
+int16_t cc3100_socket::sl_SetSockOpt(int16_t sd, int16_t level, int16_t optname, const void *optval, SlSocklen_t optlen)
+{
+    _SlSetSockOptMsg_u    Msg;
+    _SlCmdExt_t           CmdExt;
+
+     _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.TxPayloadLen = optlen;
+    CmdExt.pTxPayload = (uint8_t *)optval;
+
+    Msg.Cmd.sd = (uint8_t)sd;
+    Msg.Cmd.level = (uint8_t)level;
+    Msg.Cmd.optionLen = (uint8_t)optlen;
+    Msg.Cmd.optionName = (uint8_t)optname;
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlSetSockOptCmdCtrl, &Msg, &CmdExt));
+
+    return (int16_t)Msg.Rsp.statusOrLen;
+}
+#endif
+
+/*******************************************************************************/
+/*  sl_GetSockOpt */
+/*******************************************************************************/
+typedef union {
+    _getSockOptCommand_t    Cmd;
+    _getSockOptResponse_t   Rsp;
+} _SlGetSockOptMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_GetSockOpt)
+const _SlCmdCtrl_t _SlGetSockOptCmdCtrl = {
+    SL_OPCODE_SOCKET_GETSOCKOPT,
+    sizeof(_getSockOptCommand_t),
+    sizeof(_getSockOptResponse_t)
+};
+
+int16_t cc3100_socket::sl_GetSockOpt(int16_t sd, int16_t level, int16_t optname, void *optval, SlSocklen_t *optlen)
+{
+    _SlGetSockOptMsg_u    Msg;
+    _SlCmdExt_t           CmdExt;
+
+    if (*optlen == 0) {
+        return SL_EZEROLEN;
+    }
+    
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.RxPayloadLen = *optlen;
+    CmdExt.pRxPayload = (uint8_t*)optval;
+
+    Msg.Cmd.sd = (uint8_t)sd;
+    Msg.Cmd.level = (uint8_t)level;
+    Msg.Cmd.optionLen = (uint8_t)(*optlen);
+    Msg.Cmd.optionName = (uint8_t)optname;
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlGetSockOptCmdCtrl, &Msg, &CmdExt));
+
+    if (CmdExt.RxPayloadLen < CmdExt.ActualRxPayloadLen) {
+        *optlen = Msg.Rsp.optionLen;
+        return SL_ESMALLBUF;
+    } else {
+        *optlen = (uint8_t)CmdExt.ActualRxPayloadLen;
+    }
+    return (int16_t)Msg.Rsp.status;
+}
+#endif
+
+/*******************************************************************************/
+/*  sl_Select */
+/* ******************************************************************************/
+typedef union {
+    _SelectCommand_t   Cmd;
+    _BasicResponse_t   Rsp;
+} _SlSelectMsg_u;
+
+#ifndef SL_TINY_EXT
+#if _SL_INCLUDE_FUNC(sl_Select)
+const _SlCmdCtrl_t _SlSelectCmdCtrl = {
+    SL_OPCODE_SOCKET_SELECT,
+    sizeof(_SelectCommand_t),
+    sizeof(_BasicResponse_t)
+};
+
+int16_t cc3100_socket::sl_Select(int16_t nfds, SlFdSet_t *readsds, SlFdSet_t *writesds, SlFdSet_t *exceptsds, SlTimeval_t *timeout)
+{
+    _SlSelectMsg_u          Msg;
+    _SelectAsyncResponse_t  AsyncRsp;
+    uint8_t ObjIdx = MAX_CONCURRENT_ACTIONS;
+
+    Msg.Cmd.nfds          = (uint8_t)nfds;
+    Msg.Cmd.readFdsCount  = 0;
+    Msg.Cmd.writeFdsCount = 0;
+
+    Msg.Cmd.readFds = 0;
+    Msg.Cmd.writeFds = 0;
+
+    if( readsds ) {
+        Msg.Cmd.readFds       = (uint16_t)readsds->fd_array[0];
+    }
+    if( writesds ) {
+        Msg.Cmd.writeFds      = (uint16_t)writesds->fd_array[0];
+    }
+    if( NULL == timeout ) {
+        Msg.Cmd.tv_sec = 0xffff;
+        Msg.Cmd.tv_usec = 0xffff;
+    } else {
+        if( 0xffff <= timeout->tv_sec ) {
+            Msg.Cmd.tv_sec = 0xffff;
+        } else {
+            Msg.Cmd.tv_sec = (uint16_t)timeout->tv_sec;
+        }
+        timeout->tv_usec = timeout->tv_usec >> 10;  /*  convert to milliseconds */
+        if( 0xffff <= timeout->tv_usec ) {
+            Msg.Cmd.tv_usec = 0xffff;
+        } else {
+            Msg.Cmd.tv_usec = (uint16_t)timeout->tv_usec;
+        }
+    }
+
+    /* Use Obj to issue the command, if not available try later */
+    ObjIdx = _driver._SlDrvProtectAsyncRespSetting((uint8_t*)&AsyncRsp, SELECT_ID, SL_MAX_SOCKETS);
+
+    if (MAX_CONCURRENT_ACTIONS == ObjIdx)
+    {
+        return SL_POOL_IS_EMPTY;
+    }
+    
+    /* send the command */
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlSelectCmdCtrl, &Msg, NULL));
+
+    if(SL_OS_RET_CODE_OK == (int16_t)Msg.Rsp.status) {
+        _driver._SlDrvSyncObjWaitForever(&g_pCB->ObjPool[ObjIdx].SyncObj);
+        Msg.Rsp.status = AsyncRsp.status;
+
+        if(  ((int16_t)Msg.Rsp.status) >= 0 ) {
+            if( readsds ) {
+                readsds->fd_array[0]  = AsyncRsp.readFds;
+            }
+            if( writesds ) {
+                writesds->fd_array[0] = AsyncRsp.writeFds;
+            }
+        }
+    }
+    
+    _driver._SlDrvReleasePoolObj(ObjIdx);
+    return (int16_t)Msg.Rsp.status;
+}
+
+/*  Select helper functions */
+/*******************************************************************************/
+/*  SL_FD_SET */
+/* ******************************************************************************/
+void cc3100_socket::SL_FD_SET(int16_t fd, SlFdSet_t *fdset)
+{
+    fdset->fd_array[0] |=  (1<< (fd & BSD_SOCKET_ID_MASK));
+}
+/*******************************************************************************/
+/*  SL_FD_CLR */
+/*******************************************************************************/
+void cc3100_socket::SL_FD_CLR(int16_t fd, SlFdSet_t *fdset)
+{
+    fdset->fd_array[0] &=  ~(1<< (fd & BSD_SOCKET_ID_MASK));
+}
+/*******************************************************************************/
+/*  SL_FD_ISSET */
+/*******************************************************************************/
+int16_t  cc3100_socket::SL_FD_ISSET(int16_t fd, SlFdSet_t *fdset)
+{
+    if( fdset->fd_array[0] & (1<< (fd & BSD_SOCKET_ID_MASK)) ) {
+        return 1;
+    }
+    return 0;
+}
+/*******************************************************************************/
+/*  SL_FD_ZERO */
+/*******************************************************************************/
+void cc3100_socket::SL_FD_ZERO(SlFdSet_t *fdset)
+{
+    fdset->fd_array[0] = 0;
+}
+
+#endif
+#endif
+
+}//namespace mbed_cc3100
+
+
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_socket.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_socket.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,1566 @@
+/*
+ * socket.h - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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 files                                                             */
+/*****************************************************************************/
+#include "cc3100_simplelink.h"
+
+#ifndef SL_SOCKET_H_
+#define SL_SOCKET_H_
+
+#include "cc3100_protocol.h"
+
+namespace mbed_cc3100  {
+
+//#include "cc3100_driver.h"
+
+/*!
+
+    \addtogroup socket
+    @{
+
+*/
+
+/*****************************************************************************/
+/* Macro declarations                                                        */
+/*****************************************************************************/
+
+const uint8_t SL_FD_SETSIZE                      =   SL_MAX_SOCKETS;         /* Number of sockets to select on - same is max sockets!               */
+const uint8_t BSD_SOCKET_ID_MASK                 =    (0x0F);                 /* Index using the LBS 4 bits for socket id 0-7 */
+/* Define some BSD protocol constants.  */
+const uint8_t SL_SOCK_STREAM                     =    (1);                       /* TCP Socket                                                          */
+const uint8_t SL_SOCK_DGRAM                      =    (2);                       /* UDP Socket                                                          */
+const uint8_t SL_SOCK_RAW                        =    (3);                       /* Raw socket                                                          */
+const uint8_t SL_IPPROTO_TCP                     =    (6);                       /* TCP Raw Socket                                                      */
+const uint8_t SL_IPPROTO_UDP                     =    (17);                      /* UDP Raw Socket                                                      */
+const uint8_t SL_IPPROTO_RAW                     =    (255);                     /* Raw Socket                                                          */
+const uint8_t SL_SEC_SOCKET                      =    (100);                     /* Secured Socket Layer (SSL,TLS)                                      */
+
+/* Address families.  */
+const uint8_t     SL_AF_INET                     =    (2);                       /* IPv4 socket (UDP, TCP, etc)                                          */
+const uint8_t     SL_AF_INET6                    =    (3);                       /* IPv6 socket (UDP, TCP, etc)                                          */
+const uint8_t     SL_AF_INET6_EUI_48             =    (9);
+const uint8_t AF_INET                            =    SL_AF_INET;
+const uint8_t AF_INET6                           =    SL_AF_INET6;
+const uint8_t     SL_AF_RF                       =    (6);                       /* data include RF parameter, All layer by user (Wifi could be disconnected) */
+const uint8_t     SL_AF_PACKET                   =    (17);
+/* Protocol families, same as address families.  */
+const uint8_t     SL_PF_INET                     =    AF_INET;
+const uint8_t     SL_PF_INET6                    =    AF_INET6;
+const uint8_t     SL_INADDR_ANY                  =    (0);                       /*  bind any address  */
+
+/* error codes */
+const int8_t SL_SOC_ERROR                       =   (-1);  /* Failure.                                                             */
+const int8_t SL_SOC_OK                          =   ( 0);  /* Success.                                                             */
+const int8_t SL_INEXE                           =   (-8);   /* socket command in execution  */
+const int8_t SL_EBADF                           =   (-9);   /* Bad file number */
+const int8_t SL_ENSOCK                          =   (-10);  /* The system limit on the total number of open socket, has been reached */
+const int8_t SL_EAGAIN                          =   (-11);  /* Try again */
+const int8_t SL_EWOULDBLOCK                     =   SL_EAGAIN;
+const int8_t SL_ENOMEM                          =   (-12);  /* Out of memory */
+const int8_t SL_EACCES                          =   (-13);  /* Permission denied */
+const int8_t SL_EFAULT                          =   (-14);  /* Bad address */
+const int8_t SL_ECLOSE                          =   (-15);  /* close socket operation failed to transmit all queued packets */
+const int8_t SL_EALREADY_ENABLED                =   (-21);  /* Transceiver - Transceiver already ON. there could be only one */
+const int8_t SL_EINVAL                          =   (-22);  /* Invalid argument */
+const int8_t SL_EAUTO_CONNECT_OR_CONNECTING     =   (-69);  /* Transceiver - During connection, connected or auto mode started */
+const int8_t SL_CONNECTION_PENDING              =   (-72);  /* Transceiver - Device is connected, disconnect first to open transceiver */
+const int8_t SL_EUNSUPPORTED_ROLE               =   (-86);  /* Transceiver - Trying to start when WLAN role is AP or P2P GO */
+const int8_t SL_EDESTADDRREQ                    =   (-89);  /* Destination address required */
+const int8_t SL_EPROTOTYPE                      =   (-91);  /* Protocol wrong type for socket */
+const int8_t SL_ENOPROTOOPT                     =   (-92);  /* Protocol not available */
+const int8_t SL_EPROTONOSUPPORT                 =   (-93);  /* Protocol not supported */
+const int8_t SL_ESOCKTNOSUPPORT                 =   (-94);  /* Socket type not supported */
+const int8_t SL_EOPNOTSUPP                      =   (-95);  /* Operation not supported on transport endpoint */
+const int8_t SL_EAFNOSUPPORT                    =   (-97);  /* Address family not supported by protocol */
+const int8_t SL_EADDRINUSE                      =   (-98);  /* Address already in use */
+const int8_t SL_EADDRNOTAVAIL                   =   (-99);  /* Cannot assign requested address */
+const int8_t SL_ENETUNREACH                     =   (-101); /* Network is unreachable */
+const int8_t SL_ENOBUFS                         =   (-105); /* No buffer space available */
+const int8_t SL_EOBUFF                          =   SL_ENOBUFS;
+const int8_t SL_EISCONN                         =   (-106); /* Transport endpoint is already connected */
+const int8_t SL_ENOTCONN                        =   (-107); /* Transport endpoint is not connected */
+const int8_t SL_ETIMEDOUT                       =   (-110); /* Connection timed out */
+const int8_t SL_ECONNREFUSED                    =   (-111); /* Connection refused */
+const int8_t SL_EALREADY                        =   (-114); /* Non blocking connect in progress, try again */
+
+const int16_t SL_ESEC_RSA_WRONG_TYPE_E          =    (-130);  /* RSA wrong block type for RSA function */
+const int16_t SL_ESEC_RSA_BUFFER_E              =    (-131);  /* RSA buffer error, output too small or */
+const int16_t SL_ESEC_BUFFER_E                  =    (-132);  /* output buffer too small or input too large */
+const int16_t SL_ESEC_ALGO_ID_E                 =    (-133);  /* setting algo id error */
+const int16_t SL_ESEC_PUBLIC_KEY_E              =    (-134);  /* setting public key error */
+const int16_t SL_ESEC_DATE_E                    =    (-135);  /* setting date validity error */
+const int16_t SL_ESEC_SUBJECT_E                 =    (-136);  /* setting subject name error */
+const int16_t SL_ESEC_ISSUER_E                  =    (-137);  /* setting issuer  name error */
+const int16_t SL_ESEC_CA_TRUE_E                 =    (-138);  /* setting CA basic constraint true error */
+const int16_t SL_ESEC_EXTENSIONS_E              =    (-139);  /* setting extensions error */
+const int16_t SL_ESEC_ASN_PARSE_E               =    (-140);  /* ASN parsing error, invalid input */
+const int16_t SL_ESEC_ASN_VERSION_E             =    (-141);  /* ASN version error, invalid number */
+const int16_t SL_ESEC_ASN_GETINT_E              =    (-142);  /* ASN get big int16_t error, invalid data */
+const int16_t SL_ESEC_ASN_RSA_KEY_E             =    (-143);  /* ASN key init error, invalid input */
+const int16_t SL_ESEC_ASN_OBJECT_ID_E           =    (-144);  /* ASN object id error, invalid id */
+const int16_t SL_ESEC_ASN_TAG_NULL_E            =    (-145);  /* ASN tag error, not null */
+const int16_t SL_ESEC_ASN_EXPECT_0_E            =    (-146);  /* ASN expect error, not zero */
+const int16_t SL_ESEC_ASN_BITSTR_E              =    (-147);  /* ASN bit string error, wrong id */
+const int16_t SL_ESEC_ASN_UNKNOWN_OID_E         =    (-148);  /* ASN oid error, unknown sum id */
+const int16_t SL_ESEC_ASN_DATE_SZ_E             =    (-149);  /* ASN date error, bad size */
+const int16_t SL_ESEC_ASN_BEFORE_DATE_E         =    (-150);  /* ASN date error, current date before */
+const int16_t SL_ESEC_ASN_AFTER_DATE_E          =    (-151);  /* ASN date error, current date after */
+const int16_t SL_ESEC_ASN_SIG_OID_E             =    (-152);  /* ASN signature error, mismatched oid */
+const int16_t SL_ESEC_ASN_TIME_E                =    (-153);  /* ASN time error, unknown time type */
+const int16_t SL_ESEC_ASN_INPUT_E               =    (-154);  /* ASN input error, not enough data */
+const int16_t SL_ESEC_ASN_SIG_CONFIRM_E         =    (-155);  /* ASN sig error, confirm failure */
+const int16_t SL_ESEC_ASN_SIG_HASH_E            =    (-156);  /* ASN sig error, unsupported hash type */
+const int16_t SL_ESEC_ASN_SIG_KEY_E             =    (-157);  /* ASN sig error, unsupported key type */
+const int16_t SL_ESEC_ASN_DH_KEY_E              =    (-158);  /* ASN key init error, invalid input */
+const int16_t SL_ESEC_ASN_NTRU_KEY_E            =    (-159);  /* ASN ntru key decode error, invalid input */
+const int16_t SL_ESEC_ECC_BAD_ARG_E             =    (-170);  /* ECC input argument of wrong type */
+const int16_t SL_ESEC_ASN_ECC_KEY_E             =    (-171);  /* ASN ECC bad input */
+const int16_t SL_ESEC_ECC_CURVE_OID_E           =    (-172);  /* Unsupported ECC OID curve type */
+const int16_t SL_ESEC_BAD_FUNC_ARG              =    (-173);  /* Bad function argument provided */
+const int16_t SL_ESEC_NOT_COMPILED_IN           =    (-174);  /* Feature not compiled in */
+const int16_t SL_ESEC_UNICODE_SIZE_E            =    (-175);  /* Unicode password too big */
+const int16_t SL_ESEC_NO_PASSWORD               =    (-176);  /* no password provided by user */
+const int16_t SL_ESEC_ALT_NAME_E                =    (-177);  /* alt name size problem, too big */
+const int16_t SL_ESEC_AES_GCM_AUTH_E            =    (-180);  /* AES-GCM Authentication check failure */
+const int16_t SL_ESEC_AES_CCM_AUTH_E            =    (-181);  /* AES-CCM Authentication check failure */
+#define SL_SOCKET_ERROR_E                     (-208)  /* Error state on socket */
+
+#define SL_ESEC_MEMORY_ERROR                  (-203)  /* out of memory            */
+#define SL_ESEC_VERIFY_FINISHED_ERROR         (-204)  /* verify problem on finished */
+#define SL_ESEC_VERIFY_MAC_ERROR              (-205)  /* verify mac problem       */
+#define SL_ESEC_UNKNOWN_HANDSHAKE_TYPE        (-207)  /* weird handshake type     */
+#define SL_ESEC_SOCKET_ERROR_E                (-208)  /* error state on socket    */
+#define SL_ESEC_SOCKET_NODATA                 (-209)  /* expected data, not there */
+#define SL_ESEC_INCOMPLETE_DATA               (-210)  /* don't have enough data to complete task            */
+#define SL_ESEC_UNKNOWN_RECORD_TYPE           (-211)  /* unknown type in record hdr */
+#define SL_ESEC_FATAL_ERROR                   (-213)  /* recvd alert fatal error  */
+#define SL_ESEC_ENCRYPT_ERROR                 (-214)  /* error during encryption  */
+#define SL_ESEC_NO_PEER_KEY                   (-216)  /* need peer's key          */
+#define SL_ESEC_NO_PRIVATE_KEY                (-217)  /* need the private key     */
+#define SL_ESEC_RSA_PRIVATE_ERROR             (-218)  /* error during rsa priv op */
+#define SL_ESEC_NO_DH_PARAMS                  (-219)  /* server missing DH params */
+#define SL_ESEC_BUILD_MSG_ERROR               (-220)  /* build message failure    */
+#define SL_ESEC_BAD_HELLO                     (-221)  /* client hello malformed   */
+#define SL_ESEC_DOMAIN_NAME_MISMATCH          (-222)  /* peer subject name mismatch */
+#define SL_ESEC_WANT_READ                     (-223)  /* want read, call again    */
+#define SL_ESEC_NOT_READY_ERROR               (-224)  /* handshake layer not ready */
+#define SL_ESEC_PMS_VERSION_ERROR             (-225)  /* pre m secret version error */
+#define SL_ESEC_VERSION_ERROR                 (-226)  /* record layer version error */
+#define SL_ESEC_WANT_WRITE                    (-227)  /* want write, call again   */
+#define SL_ESEC_BUFFER_ERROR                  (-228)  /* malformed buffer input   */
+#define SL_ESEC_VERIFY_CERT_ERROR             (-229)  /* verify cert error        */
+#define SL_ESEC_VERIFY_SIGN_ERROR             (-230)  /* verify sign error        */
+
+#define SL_ESEC_LENGTH_ERROR                  (-241)  /* record layer length error */
+#define SL_ESEC_PEER_KEY_ERROR                (-242)  /* can't decode peer key */
+#define SL_ESEC_ZERO_RETURN                   (-243)  /* peer sent close notify */
+#define SL_ESEC_SIDE_ERROR                    (-244)  /* wrong client/server type */
+#define SL_ESEC_NO_PEER_CERT                  (-245)  /* peer didn't send key */
+#define SL_ESEC_ECC_CURVETYPE_ERROR           (-250)  /* Bad ECC Curve Type */
+#define SL_ESEC_ECC_CURVE_ERROR               (-251)  /* Bad ECC Curve */
+#define SL_ESEC_ECC_PEERKEY_ERROR             (-252)  /* Bad Peer ECC Key */
+#define SL_ESEC_ECC_MAKEKEY_ERROR             (-253)  /* Bad Make ECC Key */
+#define SL_ESEC_ECC_EXPORT_ERROR              (-254)  /* Bad ECC Export Key */
+#define SL_ESEC_ECC_SHARED_ERROR              (-255)  /* Bad ECC Shared Secret */
+#define SL_ESEC_NOT_CA_ERROR                  (-257)  /* Not a CA cert error */
+#define SL_ESEC_BAD_PATH_ERROR                (-258)  /* Bad path for opendir */
+#define SL_ESEC_BAD_CERT_MANAGER_ERROR        (-259)  /* Bad Cert Manager */
+#define SL_ESEC_MAX_CHAIN_ERROR               (-268)  /* max chain depth exceeded */
+#define SL_ESEC_SUITES_ERROR                  (-271)  /* suites pointer error */
+#define SL_ESEC_SSL_NO_PEM_HEADER             (-272)  /* no PEM header found */
+#define SL_ESEC_OUT_OF_ORDER_E                (-273)  /* out of order message */
+#define SL_ESEC_SANITY_CIPHER_E               (-275)  /* sanity check on cipher error */
+#define SL_ESEC_GEN_COOKIE_E                  (-277)  /* Generate Cookie Error */
+#define SL_ESEC_NO_PEER_VERIFY                (-278)  /* Need peer cert verify Error */
+#define SL_ESEC_UNKNOWN_SNI_HOST_NAME_E       (-281)  /* Unrecognized host name Error */
+/* begin negotiation parameter errors */
+#define SL_ESEC_UNSUPPORTED_SUITE     (-290)            /* unsupported cipher suite */
+#define SL_ESEC_MATCH_SUITE_ERROR      (-291 )            /* can't match cipher suite */
+
+/* ssl tls security start with -300 offset */
+const int16_t SL_ESEC_CLOSE_NOTIFY              =    (-300); /* ssl/tls alerts */
+const int16_t SL_ESEC_UNEXPECTED_MESSAGE        =    (-310); /* ssl/tls alerts */
+const int16_t SL_ESEC_BAD_RECORD_MAC            =    (-320); /* ssl/tls alerts */
+const int16_t SL_ESEC_DECRYPTION_FAILED         =    (-321); /* ssl/tls alerts */
+const int16_t SL_ESEC_RECORD_OVERFLOW           =    (-322); /* ssl/tls alerts */
+const int16_t SL_ESEC_DECOMPRESSION_FAILURE     =    (-330); /* ssl/tls alerts */
+const int16_t SL_ESEC_HANDSHAKE_FAILURE         =    (-340); /* ssl/tls alerts */
+const int16_t SL_ESEC_NO_CERTIFICATE            =    (-341); /* ssl/tls alerts */
+const int16_t SL_ESEC_BAD_CERTIFICATE           =    (-342); /* ssl/tls alerts */
+const int16_t SL_ESEC_UNSUPPORTED_CERTIFICATE   =    (-343); /* ssl/tls alerts */
+const int16_t SL_ESEC_CERTIFICATE_REVOKED       =    (-344); /* ssl/tls alerts */
+const int16_t SL_ESEC_CERTIFICATE_EXPIRED       =    (-345); /* ssl/tls alerts */
+const int16_t SL_ESEC_CERTIFICATE_UNKNOWN       =    (-346); /* ssl/tls alerts */
+const int16_t SL_ESEC_ILLEGAL_PARAMETER         =    (-347); /* ssl/tls alerts */
+const int16_t SL_ESEC_UNKNOWN_CA                =    (-348); /* ssl/tls alerts */
+const int16_t SL_ESEC_ACCESS_DENIED             =    (-349); /* ssl/tls alerts */
+const int16_t SL_ESEC_DECODE_ERROR              =    (-350); /* ssl/tls alerts */
+const int16_t SL_ESEC_DECRYPT_ERROR             =    (-351); /* ssl/tls alerts */
+const int16_t SL_ESEC_EXPORT_RESTRICTION        =    (-360); /* ssl/tls alerts */
+const int16_t SL_ESEC_PROTOCOL_VERSION          =    (-370); /* ssl/tls alerts */
+const int16_t SL_ESEC_INSUFFICIENT_SECURITY     =    (-371); /* ssl/tls alerts */
+const int16_t SL_ESEC_INTERNAL_ERROR            =    (-380); /* ssl/tls alerts */
+const int16_t SL_ESEC_USER_CANCELLED            =    (-390); /* ssl/tls alerts */
+const int16_t SL_ESEC_NO_RENEGOTIATION          =    (-400); /* ssl/tls alerts */
+const int16_t SL_ESEC_UNSUPPORTED_EXTENSION     =    (-410); /* ssl/tls alerts */
+const int16_t SL_ESEC_CERTIFICATE_UNOBTAINABLE  =    (-411); /* ssl/tls alerts */
+const int16_t SL_ESEC_UNRECOGNIZED_NAME         =    (-412); /* ssl/tls alerts */
+const int16_t SL_ESEC_BAD_CERTIFICATE_STATUS_RESPONSE = (-413); /* ssl/tls alerts */
+const int16_t SL_ESEC_BAD_CERTIFICATE_HASH_VALUE =   (-414); /* ssl/tls alerts */
+/* propierty secure */
+const int16_t SL_ESECGENERAL                    =    (-450);  /* error secure level general error */
+const int16_t SL_ESECDECRYPT                    =    (-451);  /* error secure level, decrypt recv packet fail */
+const int16_t SL_ESECCLOSED                     =    (-452);  /* secure layrer is closed by other size , tcp is still connected  */
+const int16_t SL_ESECSNOVERIFY                  =    (-453);  /* Connected without server verification */
+const int16_t SL_ESECNOCAFILE                   =    (-454);  /* error secure level CA file not found*/
+const int16_t SL_ESECMEMORY                     =    (-455);  /* error secure level No memory  space available */
+const int16_t SL_ESECBADCAFILE                  =    (-456);  /* error secure level bad CA file */
+const int16_t SL_ESECBADCERTFILE                =    (-457);  /* error secure level bad Certificate file */
+const int16_t SL_ESECBADPRIVATEFILE             =    (-458);  /* error secure level bad private file */
+const int16_t SL_ESECBADDHFILE                  =    (-459);  /* error secure level bad DH file */
+const int16_t SL_ESECT00MANYSSLOPENED           =    (-460);  /* MAX SSL Sockets are opened */
+const int16_t SL_ESECDATEERROR                  =    (-461);  /* connected with certificate date verification error */
+const int16_t SL_ESECHANDSHAKETIMEDOUT          =    (-462);  /* connection timed out due to handshake time */
+
+/* end error codes */
+
+/* Max payload size by protocol */
+const uint8_t SL_SOCKET_PAYLOAD_TYPE_MASK       =     (0xF0);  /*4 bits type, 4 bits sockets id */
+const uint8_t SL_SOCKET_PAYLOAD_TYPE_UDP_IPV4   =     (0x00);  /* 1472 bytes */
+const uint8_t SL_SOCKET_PAYLOAD_TYPE_TCP_IPV4   =     (0x10);  /* 1460 bytes */
+const uint8_t SL_SOCKET_PAYLOAD_TYPE_UDP_IPV6   =     (0x20);  /* 1452 bytes */
+const uint8_t SL_SOCKET_PAYLOAD_TYPE_TCP_IPV6   =     (0x30);  /* 1440 bytes */
+const uint8_t SL_SOCKET_PAYLOAD_TYPE_UDP_IPV4_SECURE =(0x40);  /*            */
+const uint8_t SL_SOCKET_PAYLOAD_TYPE_TCP_IPV4_SECURE =(0x50);  /*            */
+const uint8_t SL_SOCKET_PAYLOAD_TYPE_UDP_IPV6_SECURE =(0x60);  /*            */
+const uint8_t SL_SOCKET_PAYLOAD_TYPE_TCP_IPV6_SECURE =(0x70);  /*            */
+const uint8_t SL_SOCKET_PAYLOAD_TYPE_RAW_TRANCEIVER  =(0x80);  /* 1536 bytes */
+const uint8_t SL_SOCKET_PAYLOAD_TYPE_RAW_PACKET =     (0x90);  /* 1536 bytes */
+const uint8_t SL_SOCKET_PAYLOAD_TYPE_RAW_IP4    =     (0xa0);
+const uint8_t SL_SOCKET_PAYLOAD_TYPE_RAW_IP6    =     (SL_SOCKET_PAYLOAD_TYPE_RAW_IP4 );
+
+
+
+const uint8_t SL_SOL_SOCKET        =  (1);   /* Define the socket option category. */
+const uint8_t SL_IPPROTO_IP        =  (2);   /* Define the IP option category.     */
+const uint8_t SL_SOL_PHY_OPT       =  (3);   /* Define the PHY option category.    */
+
+const uint8_t SL_SO_RCVBUF         =  (8);   /* Setting TCP receive buffer size */
+const uint8_t SL_SO_KEEPALIVE      =  (9);   /* Connections are kept alive with periodic messages */
+const uint8_t SL_SO_RCVTIMEO       =  (20);  /* Enable receive timeout */
+const uint8_t SL_SO_NONBLOCKING    =  (24);  /* Enable . disable nonblocking mode  */
+const uint8_t SL_SO_SECMETHOD      =  (25);  /* security metohd */
+const uint8_t SL_SO_SECURE_MASK    =  (26);  /* security mask */
+const uint8_t SL_SO_SECURE_FILES   =  (27);  /* security files */
+const uint8_t SL_SO_CHANGE_CHANNEL =  (28);  /* This option is available only when transceiver started */
+const uint8_t SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME =(30); /* This option used to configue secure file */
+const uint8_t SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME =(31); /* This option used to configue secure file */
+const uint8_t SL_SO_SECURE_FILES_CA_FILE_NAME      =    (32); /* This option used to configue secure file */
+const uint8_t SL_SO_SECURE_FILES_DH_KEY_FILE_NAME  =    (33); /* This option used to configue secure file */
+
+const uint8_t SL_IP_MULTICAST_IF   =  (60); /* Specify outgoing multicast interface */
+const uint8_t SL_IP_MULTICAST_TTL  =  (61); /* Specify the TTL value to use for outgoing multicast packet. */
+const uint8_t SL_IP_ADD_MEMBERSHIP =  (65); /* Join IPv4 multicast membership */
+const uint8_t SL_IP_DROP_MEMBERSHIP=  (66); /* Leave IPv4 multicast membership */
+const uint8_t SL_IP_HDRINCL        =  (67); /* Raw socket IPv4 header included. */
+const uint8_t SL_IP_RAW_RX_NO_HEADER =(68); /* Proprietary socket option that does not includeIPv4/IPv6 header (and extension headers) on received raw sockets*/
+const uint8_t SL_IP_RAW_IPV6_HDRINCL =(69); /* Transmitted buffer over IPv6 socket contains IPv6 header. */
+
+const uint8_t SL_SO_PHY_RATE           =   (100);   /* WLAN Transmit rate */
+const uint8_t SL_SO_PHY_TX_POWER       =   (101);   /* TX Power level */
+const uint8_t SL_SO_PHY_NUM_FRAMES_TO_TX = (102);   /* Number of frames to transmit */
+const uint8_t SL_SO_PHY_PREAMBLE       =   (103);   /* Preamble for transmission */
+
+const uint8_t SL_SO_SEC_METHOD_SSLV3                  =           (0);  /* security metohd SSL v3*/
+const uint8_t SL_SO_SEC_METHOD_TLSV1                  =           (1);  /* security metohd TLS v1*/
+const uint8_t SL_SO_SEC_METHOD_TLSV1_1                =           (2);  /* security metohd TLS v1_1*/
+const uint8_t SL_SO_SEC_METHOD_TLSV1_2                =           (3);  /* security metohd TLS v1_2*/
+const uint8_t SL_SO_SEC_METHOD_SSLv3_TLSV1_2          =           (4);  /* use highest possible version from SSLv3 - TLS 1.2*/
+const uint8_t SL_SO_SEC_METHOD_DLSV1                  =           (5);  /* security metohd DTL v1  */
+
+#define SL_SEC_MASK_SSL_RSA_WITH_RC4_128_SHA               (1 << 0)
+#define SL_SEC_MASK_SSL_RSA_WITH_RC4_128_MD5               (1 << 1)
+#define SL_SEC_MASK_TLS_RSA_WITH_AES_256_CBC_SHA           (1 << 2)
+#define SL_SEC_MASK_TLS_DHE_RSA_WITH_AES_256_CBC_SHA       (1 << 3)
+#define SL_SEC_MASK_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA     (1 << 4)
+#define SL_SEC_MASK_TLS_ECDHE_RSA_WITH_RC4_128_SHA         (1 << 5)
+#define SL_SEC_MASK_TLS_RSA_WITH_AES_128_CBC_SHA256              (1 << 6)
+#define SL_SEC_MASK_TLS_RSA_WITH_AES_256_CBC_SHA256              (1 << 7)
+#define SL_SEC_MASK_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256        (1 << 8)
+#define SL_SEC_MASK_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256      (1 << 9)
+
+#define SL_SEC_MASK_SECURE_DEFAULT                         ((SL_SEC_MASK_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256  <<  1)  -  1)
+
+const uint32_t SL_MSG_DONTWAIT                       =            (0x00000008);  /* Nonblocking IO */
+
+/* AP DHCP Server - IP Release reason code */
+const uint8_t SL_IP_LEASE_PEER_RELEASE  =   (0);
+const uint8_t SL_IP_LEASE_PEER_DECLINE  =   (1);
+const uint8_t SL_IP_LEASE_EXPIRED       =   (2);
+
+/* possible types when receiving SL_SOCKET_ASYNC_EVENT*/
+const uint8_t SSL_ACCEPT                               = (1); /* accept failed due to ssl issue ( tcp pass) */
+const uint8_t RX_FRAGMENTATION_TOO_BIG                 = (2); /* connection less mode, rx packet fragmentation > 16K, packet is being released */
+const uint8_t OTHER_SIDE_CLOSE_SSL_DATA_NOT_ENCRYPTED  = (3); /* remote side down from secure to unsecure */
+
+
+
+#ifdef SL_INC_STD_BSD_API_NAMING
+
+#define FD_SETSIZE                          SL_FD_SETSIZE
+
+#define SOCK_STREAM                         SL_SOCK_STREAM
+#define SOCK_DGRAM                          SL_SOCK_DGRAM
+#define SOCK_RAW                            SL_SOCK_RAW
+#define IPPROTO_TCP                         SL_IPPROTO_TCP
+#define IPPROTO_UDP                         SL_IPPROTO_UDP
+#define IPPROTO_RAW                         SL_IPPROTO_RAW
+
+#define AF_INET6_EUI_48                     SL_AF_INET6_EUI_48
+#define AF_RF                               SL_AF_RF
+#define AF_PACKET                           SL_AF_PACKET
+
+#define PF_INET                             SL_PF_INET
+#define PF_INET6                            SL_PF_INET6
+
+#define INADDR_ANY                          SL_INADDR_ANY
+#define ERROR                               SL_SOC_ERROR
+#define INEXE                               SL_INEXE
+#define EBADF                               SL_EBADF
+#define ENSOCK                              SL_ENSOCK
+#define EAGAIN                              SL_EAGAIN
+#define EWOULDBLOCK                         SL_EWOULDBLOCK
+#define ENOMEM                              SL_ENOMEM
+#define EACCES                              SL_EACCES
+#define EFAULT                              SL_EFAULT
+#define EINVAL                              SL_EINVAL
+#define EDESTADDRREQ                        SL_EDESTADDRREQ
+#define EPROTOTYPE                          SL_EPROTOTYPE
+#define ENOPROTOOPT                         SL_ENOPROTOOPT
+#define EPROTONOSUPPORT                     SL_EPROTONOSUPPORT
+#define ESOCKTNOSUPPORT                     SL_ESOCKTNOSUPPORT
+#define EOPNOTSUPP                          SL_EOPNOTSUPP
+#define EAFNOSUPPORT                        SL_EAFNOSUPPORT
+#define EADDRINUSE                          SL_EADDRINUSE
+#define EADDRNOTAVAIL                       SL_EADDRNOTAVAIL
+#define ENETUNREACH                         SL_ENETUNREACH
+#define ENOBUFS                             SL_ENOBUFS
+#define EOBUFF                              SL_EOBUFF
+#define EISCONN                             SL_EISCONN
+#define ENOTCONN                            SL_ENOTCONN
+#define ETIMEDOUT                           SL_ETIMEDOUT
+#define ECONNREFUSED                        SL_ECONNREFUSED
+
+#define SOL_SOCKET                          SL_SOL_SOCKET
+#define IPPROTO_IP                          SL_IPPROTO_IP
+#define SO_KEEPALIVE                        SL_SO_KEEPALIVE
+
+#define SO_RCVTIMEO                         SL_SO_RCVTIMEO
+#define SO_NONBLOCKING                      SL_SO_NONBLOCKING
+
+#define IP_MULTICAST_IF                     SL_IP_MULTICAST_IF
+#define IP_MULTICAST_TTL                    SL_IP_MULTICAST_TTL
+#define IP_ADD_MEMBERSHIP                   SL_IP_ADD_MEMBERSHIP
+#define IP_DROP_MEMBERSHIP                  SL_IP_DROP_MEMBERSHIP
+
+#define socklen_t                           SlSocklen_t
+#define timeval                             SlTimeval_t
+#define sockaddr                            SlSockAddr_t
+#define in6_addr                            SlIn6Addr_t
+#define sockaddr_in6                        SlSockAddrIn6_t
+#define in_addr                             SlInAddr_t
+#define sockaddr_in                         SlSockAddrIn_t
+
+#define MSG_DONTWAIT                        SL_MSG_DONTWAIT
+
+#define FD_SET                              SL_FD_SET
+#define FD_CLR                              SL_FD_CLR
+#define FD_ISSET                            SL_FD_ISSET
+#define FD_ZERO                             SL_FD_ZERO
+#define fd_set                              SlFdSet_t
+
+#define socket                              sl_Socket
+#define close                               sl_Close
+#define accept                              sl_Accept
+#define bind                                sl_Bind
+#define listen                              sl_Listen
+#define connect                             sl_Connect
+#define select                              sl_Select
+#define setsockopt                          sl_SetSockOpt
+#define getsockopt                          sl_GetSockOpt
+#define recv                                sl_Recv
+#define recvfrom                            sl_RecvFrom
+#define write_                               sl_Write
+#define send                                sl_Send
+#define sendto                              sl_SendTo
+#define gethostbyname                       sl_NetAppDnsGetHostByName
+#define htonl                               sl_Htonl
+#define ntohl                               sl_Ntohl
+#define htons                               sl_Htons
+#define ntohs                               sl_Ntohs
+#endif
+
+
+/*****************************************************************************/
+/* Structure/Enum declarations                                               */
+/*****************************************************************************/
+
+/* Internet address   */
+typedef struct SlInAddr_t {
+#ifndef s_addr
+    uint32_t           s_addr;             /* Internet address 32 bits */
+#else
+    union S_un {
+        struct {
+            uint8_t s_b1,s_b2,s_b3,s_b4;
+        } S_un_b;
+        struct {
+            uint8_t s_w1,s_w2;
+        } S_un_w;
+        uint32_t S_addr;
+    } S_un;
+#endif
+} SlInAddr_t;
+
+
+/* sockopt */
+typedef struct {
+    uint32_t KeepaliveEnabled; /* 0 = disabled;1 = enabled; default = 1*/
+} SlSockKeepalive_t;
+
+typedef struct {
+    uint32_t ReuseaddrEnabled; /* 0 = disabled; 1 = enabled; default = 1*/
+} SlSockReuseaddr_t;
+
+typedef struct {
+    uint32_t Winsize;          /* receive window size for tcp sockets  */
+} SlSockWinsize_t;
+
+typedef struct {
+    uint32_t NonblockingEnabled;/* 0 = disabled;1 = enabled;default = 1*/
+} SlSockNonblocking_t;
+
+typedef struct {
+    uint8_t   sd;
+    uint8_t   type;
+    uint16_t  val;
+    uint8_t*  pExtraInfo;
+} SlSocketAsyncEvent_t;
+
+typedef struct {
+    int16_t        status;
+    uint8_t        sd;
+    uint8_t        padding;
+} SlSockTxFailEventData_t;
+
+
+typedef union
+{
+  SlSockTxFailEventData_t   SockTxFailData;
+  SlSocketAsyncEvent_t      SockAsyncData;
+} SlSockEventData_u;
+
+
+typedef struct {
+    uint32_t                Event;
+    SlSockEventData_u       socketAsyncEvent;
+} SlSockEvent_t;
+
+
+typedef struct {
+    uint32_t    secureMask;
+} SlSockSecureMask;
+
+typedef struct {
+    uint8_t     secureMethod;
+} SlSockSecureMethod;
+
+typedef enum {
+    SL_BSD_SECURED_PRIVATE_KEY_IDX = 0,
+    SL_BSD_SECURED_CERTIFICATE_IDX,
+    SL_BSD_SECURED_CA_IDX,
+    SL_BSD_SECURED_DH_IDX
+} slBsd_secureSocketFilesIndex_e;
+
+typedef struct {
+    SlInAddr_t   imr_multiaddr;     /* The IPv4 multicast address to join */
+    SlInAddr_t   imr_interface;     /* The interface to use for this group */
+} SlSockIpMreq;
+
+
+/* sockopt */
+typedef uint32_t   SlTime_t;
+typedef uint32_t   SlSuseconds_t;
+
+typedef struct  {
+    SlTime_t          tv_sec;             /* Seconds      */
+    SlSuseconds_t     tv_usec;            /* Microseconds */
+} SlTimeval_t;
+
+typedef uint16_t SlSocklen_t;
+
+/* IpV4 socket address */
+typedef struct  {
+    uint16_t          sa_family;     /* Address family (e.g. , AF_INET)     */
+    uint8_t           sa_data[14];  /* Protocol- specific address information*/
+} SlSockAddr_t;
+
+
+/* IpV6 or Ipv6 EUI64 */
+typedef struct  {
+    union {
+        uint8_t   _S6_u8[16];
+        uint32_t  _S6_u32[4];
+    } _S6_un;
+} SlIn6Addr_t;
+
+typedef struct  {
+    uint16_t           sin6_family;                 /* AF_INET6 || AF_INET6_EUI_48*/
+    uint16_t           sin6_port;                   /* Transport layer port.  */
+    uint32_t           sin6_flowinfo;               /* IPv6 flow information. */
+    SlIn6Addr_t        sin6_addr;                   /* IPv6 address. */
+    uint32_t           sin6_scope_id;               /* set of interfaces for a scope. */
+} SlSockAddrIn6_t;
+
+/* Socket address, Internet style. */
+
+typedef struct  {
+    uint16_t              sin_family;         /* Internet Protocol (AF_INET).                    */
+    uint16_t              sin_port;           /* Address port (16 bits).                         */
+    SlInAddr_t            sin_addr;           /* Internet address (32 bits).                     */
+    int8_t                sin_zero[8];        /* Not used.                                       */
+} SlSockAddrIn_t;
+
+typedef struct {
+    uint32_t ip;
+    uint32_t gateway;
+    uint32_t dns;
+} SlIpV4AcquiredAsync_t;
+
+typedef struct {
+    uint32_t type;
+    uint32_t ip[4];
+    uint32_t gateway[4];
+    uint32_t dns[4];
+} SlIpV6AcquiredAsync_t;
+
+typedef struct {
+    uint32_t    ip_address;
+    uint32_t    lease_time;
+    uint8_t     mac[6];
+    uint16_t    padding;
+} SlIpLeasedAsync_t;
+
+typedef struct {
+    uint32_t    ip_address;
+    uint8_t     mac[6];
+    uint16_t    reason;
+} SlIpReleasedAsync_t;
+
+
+typedef union {
+    SlIpV4AcquiredAsync_t    ipAcquiredV4; /*SL_NETAPP_IPV4_IPACQUIRED_EVENT*/
+    SlIpV6AcquiredAsync_t    ipAcquiredV6; /*SL_NETAPP_IPV6_IPACQUIRED_EVENT*/
+    uint32_t                      sd;           /*SL_SOCKET_TX_FAILED_EVENT*/
+    SlIpLeasedAsync_t        ipLeased;     /* SL_NETAPP_IP_LEASED_EVENT   */
+    SlIpReleasedAsync_t      ipReleased;   /* SL_NETAPP_IP_RELEASED_EVENT */
+} SlNetAppEventData_u;
+
+typedef struct {
+    uint32_t                     Event;
+    SlNetAppEventData_u       EventData;
+} SlNetAppEvent_t;
+
+
+typedef struct sock_secureFiles {
+    uint8_t                     secureFiles[4];
+} SlSockSecureFiles_t;
+
+
+typedef struct SlFdSet_t {                  /* The select socket array manager */
+    uint32_t        fd_array[(SL_FD_SETSIZE + 31)/32]; /* Bit map of SOCKET Descriptors */
+} SlFdSet_t;
+
+typedef struct {
+    uint8_t   rate;               /* Recevied Rate  */
+    uint8_t   channel;            /* The received channel*/
+    int8_t    rssi;               /* The computed RSSI value in db of current frame */
+    uint8_t   padding;                                           /* pad to align to 32 bits */
+    uint32_t  timestamp;          /* Timestamp in microseconds,     */
+} SlTransceiverRxOverHead_t;
+
+class cc3100_nonos;
+
+class cc3100_socket
+{
+
+public:
+
+    cc3100_socket(cc3100_driver &driver, cc3100_nonos &nonos);
+
+    ~cc3100_socket();
+
+    /*******************************************************************************/
+    /* Functions prototypes                                                        */
+    /*******************************************************************************/
+    void   _sl_BuildAddress(const SlSockAddr_t *addr, _SocketAddrCommand_u *pCmd);
+    void   _sl_ParseAddress(_SocketAddrResponse_u *pRsp, SlSockAddr_t *addr, SlSocklen_t *addrlen);
+    uint16_t   _sl_TruncatePayloadByProtocol(const int16_t pSd,const uint16_t length);
+
+    /*****************************************************************************/
+    /* Function prototypes                                                       */
+    /*****************************************************************************/
+
+    /*!
+
+        \brief create an endpoint for communication
+
+        The socket function creates a new socket of a certain socket type, identified
+        by an integer number, and allocates system resources to it.
+        This function is called by the application layer to obtain a socket handle.
+
+        \param[in] domain           specifies the protocol family of the created socket.
+                                    For example:
+                                       AF_INET for network protocol IPv4
+                                       AF_RF for starting transceiver mode. Notes:
+                                       - sending and receiving any packet overriding 802.11 header
+                                       - for optimized power consumption the socket will be started in TX
+                                         only mode until receive command is activated
+                                       AF_INET6 for IPv6
+
+
+        \param[in] type              specifies the communication semantic, one of:
+                                       SOCK_STREAM (reliable stream-oriented service or Stream Sockets)
+                                       SOCK_DGRAM (datagram service or Datagram Sockets)
+                                       SOCK_RAW (raw protocols atop the network layer)
+                                       when used with AF_RF:
+                                                                         SOCK_DGRAM - L2 socket
+                                                                         SOCK_RAW - L1 socket - bypass WLAN CCA (Clear Channel Assessment)
+
+        \param[in] protocol         specifies a particular transport to be used with
+                                    the socket.
+                                    The most common are IPPROTO_TCP, IPPROTO_SCTP, IPPROTO_UDP,
+                                    IPPROTO_DCCP.
+                                    The value 0 may be used to select a default
+                                    protocol from the selected domain and type
+
+
+        \return                     On success, socket handle that is used for consequent socket operations.
+                                    A successful return code should be a positive number (int16)
+                                    On error, a negative (int16) value will be returned specifying the error code.
+                               SL_EAFNOSUPPORT  - illegal domain parameter
+                               SL_EPROTOTYPE  - illegal type parameter
+                               SL_EACCES   - permission denied
+                               SL_ENSOCK  - exceeded maximal number of socket
+                               SL_ENOMEM  - memory allocation error
+                               SL_EINVAL  - error in socket configuration
+                               SL_EPROTONOSUPPORT  - illegal protocol parameter
+                               SL_EOPNOTSUPP  - illegal combination of protocol and type parameters
+
+
+        \sa                         sl_Close
+        \note                       belongs to \ref basic_api
+        \warning
+    */
+#if _SL_INCLUDE_FUNC(sl_Socket)
+    int16_t sl_Socket(int16_t Domain, int16_t Type, int16_t Protocol);
+#endif
+
+    /*!
+        \brief gracefully close socket
+
+        This function causes the system to release resources allocated to a socket.  \n
+        In case of TCP, the connection is terminated.
+
+        \param[in] sd               socket handle (received in sl_Socket)
+
+        \return                        On success, zero is returned.
+                                    On error, a negative number is returned.
+
+        \sa                         sl_Socket
+        \note                       belongs to \ref ext_api
+        \warning
+    */
+#if _SL_INCLUDE_FUNC(sl_Close)
+    int16_t sl_Close(int16_t sd);
+#endif
+
+    /*!
+        \brief Accept a connection on a socket
+
+        This function is used with connection-based socket types (SOCK_STREAM).
+        It extracts the first connection request on the queue of pending
+        connections, creates a new connected socket, and returns a new file
+        descriptor referring to that socket.
+        The newly created socket is not in the listening state. The
+        original socket sd is unaffected by this call.
+        The argument sd is a socket that has been created with
+        sl_Socket(), bound to a local address with sl_Bind(), and is
+        listening for connections after a sl_Listen(). The argument \b
+        \e addr is a pointer to a sockaddr structure. This structure
+        is filled in with the address of the peer socket, as known to
+        the communications layer. The exact format of the address
+        returned addr is determined by the socket's address family.
+        The \b \e addrlen argument is a value-result argument: it
+        should initially contain the size of the structure pointed to
+        by addr, on return it will contain the actual length (in
+        bytes) of the address returned.
+
+        \param[in] sd               socket descriptor (handle)
+        \param[out] addr            the argument addr is a pointer
+                                    to a sockaddr structure. This
+                                    structure is filled in with the
+                                    address of the peer socket, as
+                                    known to the communications
+                                    layer. The exact format of the
+                                    address returned addr is
+                                    determined by the socket's
+                                    address\n
+                                    sockaddr:\n - code for the
+                                    address format. On this version
+                                    only AF_INET is supported.\n -
+                                    socket address, the length
+                                    depends on the code format
+        \param[out] addrlen         the addrlen argument is a value-result
+                                    argument: it should initially contain the
+                                    size of the structure pointed to by addr
+
+        \return                        On success, a socket handle.
+                                    On a non-blocking accept a possible negative value is SL_EAGAIN.
+                                    On failure, negative value.
+                                    SL_POOL_IS_EMPTY may be return in case there are no resources in the system
+                                     In this case try again later or increase MAX_CONCURRENT_ACTIONS
+
+        \sa                         sl_Socket  sl_Bind  sl_Listen
+        \note                       belongs to \ref server_side
+        \warning
+    */
+#if _SL_INCLUDE_FUNC(sl_Accept)
+    int16_t sl_Accept(int16_t sd, SlSockAddr_t *addr, SlSocklen_t *addrlen);
+#endif
+
+    /*!
+        \brief assign a name to a socket
+
+        This function gives the socket the local address addr.
+        addr is addrlen bytes long. Traditionally, this is called
+        When a socket is created with socket, it exists in a name
+        space (address family) but has no name assigned.
+        It is necessary to assign a local address before a SOCK_STREAM
+        socket may receive connections.
+
+        \param[in] sd                socket descriptor (handle)
+        \param[in] addr              specifies the destination
+                                    addrs\n sockaddr:\n - code for
+                                    the address format. On this
+                                    version only AF_INET is
+                                    supported.\n - socket address,
+                                    the length depends on the code
+                                    format
+        \param[in] addrlen          contains the size of the structure pointed to by addr
+
+        \return                        On success, zero is returned. On error, a negative error code is returned.
+
+        \sa                         sl_Socket  sl_Accept sl_Listen
+        \note                       belongs to \ref basic_api
+        \warning
+    */
+#if _SL_INCLUDE_FUNC(sl_Bind)
+    int16_t sl_Bind(int16_t sd, const SlSockAddr_t *addr, int16_t addrlen);
+#endif
+
+    /*!
+        \brief listen for connections on a socket
+
+        The willingness to accept incoming connections and a queue
+        limit for incoming connections are specified with listen(),
+        and then the connections are accepted with accept.
+        The listen() call applies only to sockets of type SOCK_STREAM
+        The backlog parameter defines the maximum length the queue of
+        pending connections may grow to.
+
+        \param[in] sd               socket descriptor (handle)
+        \param[in] backlog          specifies the listen queue depth.
+
+
+        \return                    On success, zero is returned. On error, a negative error code is returned.
+
+        \sa                         sl_Socket  sl_Accept  sl_Bind
+        \note                       belongs to \ref server_side
+        \warning
+    */
+#if _SL_INCLUDE_FUNC(sl_Listen)
+    int16_t sl_Listen(int16_t sd, int16_t backlog);
+#endif
+
+    /*!
+        \brief Initiate a connection on a socket
+
+        Function connects the socket referred to by the socket
+        descriptor sd, to the address specified by addr. The addrlen
+        argument specifies the size of addr. The format of the
+        address in addr is determined by the address space of the
+        socket. If it is of type SOCK_DGRAM, this call specifies the
+        peer with which the socket is to be associated; this address
+        is that to which datagrams are to be sent, and the only
+        address from which datagrams are to be received.  If the
+        socket is of type SOCK_STREAM, this call attempts to make a
+        connection to another socket. The other socket is specified
+        by address, which is an address in the communications space
+        of the socket.
+
+
+        \param[in] sd               socket descriptor (handle)
+        \param[in] addr             specifies the destination addr\n
+                                    sockaddr:\n - code for the
+                                    address format. On this version
+                                    only AF_INET is supported.\n -
+                                    socket address, the length
+                                    depends on the code format
+
+        \param[in] addrlen          contains the size of the structure pointed
+                                    to by addr
+
+        \return                     On success, a socket handle.
+                                    On a non-blocking connect a possible negative value is SL_EALREADY.
+                                    On failure, negative value.
+                                    SL_POOL_IS_EMPTY may be return in case there are no resources in the system
+                                      In this case try again later or increase MAX_CONCURRENT_ACTIONS
+
+        \sa                         sl_Socket
+        \note                       belongs to \ref client_side
+        \warning
+    */
+#if _SL_INCLUDE_FUNC(sl_Connect)
+    int16_t sl_Connect(int16_t sd, const SlSockAddr_t *addr, int16_t addrlen);
+#endif
+
+    /*!
+        \brief Monitor socket activity
+
+        Select allow a program to monitor multiple file descriptors,
+        waiting until one or more of the file descriptors become
+        "ready" for some class of I/O operation
+
+
+        \param[in]  nfds        the highest-numbered file descriptor in any of the
+                                three sets, plus 1.
+        \param[out] readsds     socket descriptors list for read monitoring and accept monitoring
+        \param[out] writesds    socket descriptors list for connect monitoring only, write monitoring is not supported, non blocking connect is supported
+        \param[out] exceptsds   socket descriptors list for exception monitoring, not supported.
+        \param[in]  timeout     is an upper bound on the amount of time elapsed
+                                before select() returns. Null or above 0xffff seconds means
+                                infinity timeout. The minimum timeout is 10 milliseconds,
+                                less than 10 milliseconds will be set automatically to 10 milliseconds.
+                                Max microseconds supported is 0xfffc00.
+
+        \return                    On success, select()  returns the number of
+                                file descriptors contained in the three returned
+                                descriptor sets (that is, the total number of bits that
+                                are set in readfds, writefds, exceptfds) which may be
+                                zero if the timeout expires before anything interesting
+                                happens. On error, a negative value is returned.
+                                readsds - return the sockets on which Read request will
+                                return without delay with valid data.
+                                writesds - return the sockets on which Write request
+                                will return without delay.
+                                exceptsds - return the sockets closed recently.
+                                SL_POOL_IS_EMPTY may be return in case there are no resources in the system
+                                   In this case try again later or increase MAX_CONCURRENT_ACTIONS
+
+        \sa     sl_Socket
+        \note   If the timeout value set to less than 5ms it will automatically set
+                to 5ms to prevent overload of the system
+                belongs to \ref basic_api
+
+                Only one sl_Select can be handled at a time.
+                Calling this API while the same command is called from another thread, may result
+                    in one of the two scenarios:
+                1. The command will wait (internal) until the previous command finish, and then be executed.
+                2. There are not enough resources and SL_POOL_IS_EMPTY error will return.
+                In this case, MAX_CONCURRENT_ACTIONS can be increased (result in memory increase) or try
+                again later to issue the command.
+
+        \warning
+    */
+#if _SL_INCLUDE_FUNC(sl_Select)
+    int16_t sl_Select(int16_t nfds, SlFdSet_t *readsds, SlFdSet_t *writesds, SlFdSet_t *exceptsds, SlTimeval_t *timeout);
+
+
+    /*!
+        \brief Select's SlFdSet_t SET function
+
+        Sets current socket descriptor on SlFdSet_t container
+    */
+    void SL_FD_SET(int16_t fd, SlFdSet_t *fdset);
+
+    /*!
+        \brief Select's SlFdSet_t CLR function
+
+        Clears current socket descriptor on SlFdSet_t container
+    */
+    void SL_FD_CLR(int16_t fd, SlFdSet_t *fdset);
+
+
+    /*!
+        \brief Select's SlFdSet_t ISSET function
+
+        Checks if current socket descriptor is set (TRUE/FALSE)
+
+        \return            Returns TRUE if set, FALSE if unset
+
+    */
+    int16_t  SL_FD_ISSET(int16_t fd, SlFdSet_t *fdset);
+
+    /*!
+        \brief Select's SlFdSet_t ZERO function
+
+        Clears all socket descriptors from SlFdSet_t
+    */
+    void SL_FD_ZERO(SlFdSet_t *fdset);
+
+
+
+#endif
+
+    /*!
+        \brief set socket options
+
+        This function manipulate the options associated with a socket.
+        Options may exist at multiple protocol levels; they are always
+        present at the uppermost socket level.
+
+        When manipulating socket options the level at which the option resides
+        and the name of the option must be specified.  To manipulate options at
+        the socket level, level is specified as SOL_SOCKET.  To manipulate
+        options at any other level the protocol number of the appropriate proto-
+        col controlling the option is supplied.  For example, to indicate that an
+        option is to be interpreted by the TCP protocol, level should be set to
+        the protocol number of TCP;
+
+        The parameters optval and optlen are used to access optval -
+        ues for setsockopt().  For getsockopt() they identify a
+        buffer in which the value for the requested option(s) are to
+        be returned.  For getsockopt(), optlen is a value-result
+        parameter, initially containing the size of the buffer
+        pointed to by option_value, and modified on return to
+        indicate the actual size of the value returned.  If no option
+        value is to be supplied or returned, option_value may be
+        NULL.
+
+        \param[in] sd               socket handle
+        \param[in] level            defines the protocol level for this option
+                                    - <b>SL_SOL_SOCKET</b>   Socket level configurations (L4, transport layer)
+                                    - <b>SL_IPPROTO_IP</b>   IP level configurations (L3, network layer)
+                                    - <b>SL_SOL_PHY_OPT</b>  Link level configurations (L2, link layer)
+        \param[in] optname          defines the option name to interrogate
+                                    - <b>SL_SOL_SOCKET</b>
+                                      - <b>SL_SO_KEEPALIVE</b>  \n
+                                                     Enable/Disable periodic keep alive.
+                                                     Keeps TCP connections active by enabling the periodic transmission of messages \n
+                                                     Timeout is 5 minutes.\n
+                                                     Default: Enabled \n
+                                                     This options takes SlSockKeepalive_t struct as parameter
+                                      - <b>SL_SO_RCVTIMEO</b>  \n
+                                                     Sets the timeout value that specifies the maximum amount of time an input function waits until it completes. \n
+                                                     Default: No timeout \n
+                                                     This options takes SlTimeval_t struct as parameter
+                                      - <b>SL_SO_RCVBUF</b>  \n
+                                                     Sets tcp max recv window size. \n
+                                                     This options takes SlSockWinsize_t struct as parameter
+                                      - <b>SL_SO_NONBLOCKING</b> \n
+                                                     Sets socket to non-blocking operation Impacts: connect, accept, send, sendto, recv and recvfrom. \n
+                                                     Default: Blocking.
+                                                     This options takes SlSockNonblocking_t struct as parameter
+                                      - <b>SL_SO_SECMETHOD</b> \n
+                                                     Sets method to tcp secured socket (SL_SEC_SOCKET) \n
+                                                     Default: SL_SO_SEC_METHOD_SSLv3_TLSV1_2 \n
+                                                     This options takes SlSockSecureMethod struct as parameter
+                                      - <b>SL_SO_SEC_MASK</b> \n
+                                                     Sets specific cipher to tcp secured socket (SL_SEC_SOCKET) \n
+                                                     Default: "Best" cipher suitable to method \n
+                                                     This options takes SlSockSecureMask struct as parameter
+                                      - <b>SL_SO_SECURE_FILES_CA_FILE_NAME</b> \n
+                                                     Map secured socket to CA file by name \n
+                                                     This options takes <b>uint8_t</b> buffer as parameter
+                                      - <b>SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME</b> \n
+                                                     Map secured socket to private key by name \n
+                                                     This options takes <b>uint8_t</b> buffer as parameter
+                                      - <b>SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME</b> \n
+                                                     Map secured socket to certificate file by name \n
+                                                     This options takes <b>uint8_t</b> buffer as parameter
+                                      - <b>SL_SO_SECURE_FILES_DH_KEY_FILE_NAME</b> \n
+                                                     Map secured socket to Diffie Hellman file by name \n
+                                                     This options takes <b>uint8_t</b> buffer as parameter
+                                      - <b>SL_SO_CHANGE_CHANNEL</b> \n
+                                                     Sets channel in transceiver mode.
+                                                     This options takes <b>uint32_t</b> as channel number parameter
+                                    - <b>SL_IPPROTO_IP</b>
+                                      - <b>SL_IP_MULTICAST_TTL</b> \n
+                                                     Set the time-to-live value of outgoing multicast packets for this socket. \n
+                                                     This options takes <b>uint8_t</b> as parameter
+                                      - <b>SL_IP_ADD_MEMBERSHIP</b> \n
+                                                     UDP socket, Join a multicast group. \n
+                                                     This options takes SlSockIpMreq struct as parameter
+                                      - <b>SL_IP_DROP_MEMBERSHIP</b> \n
+                                                     UDP socket, Leave a multicast group \n
+                                                     This options takes SlSockIpMreq struct as parameter
+                                      - <b>SL_IP_RAW_RX_NO_HEADER</b> \n
+                                                     Raw socket remove IP header from received data. \n
+                                                     Default: data includes ip header \n
+                                                     This options takes <b>uint32_t</b> as parameter
+                                      - <b>SL_IP_HDRINCL</b> \n
+                                                     RAW socket only, the IPv4 layer generates an IP header when sending a packet unless \n
+                                                     the IP_HDRINCL socket option is enabled on the socket.    \n
+                                                     When it is enabled, the packet must contain an IP header. \n
+                                                     Default: disabled, IPv4 header generated by Network Stack \n
+                                                     This options takes <b>uint32_t</b> as parameter
+                                      - <b>SL_IP_RAW_IPV6_HDRINCL</b> (inactive) \n
+                                                     RAW socket only, the IPv6 layer generates an IP header when sending a packet unless \n
+                                                     the IP_HDRINCL socket option is enabled on the socket. When it is enabled, the packet must contain an IP header \n
+                                                     Default: disabled, IPv4 header generated by Network Stack \n
+                                                     This options takes <b>uint32_t</b> as parameter
+                                    - <b>SL_SOL_PHY_OPT</b>
+                                      - <b>SL_SO_PHY_RATE</b> \n
+                                                     RAW socket, set WLAN PHY transmit rate \n
+                                                     The values are based on RateIndex_e    \n
+                                                     This options takes <b>uint32_t</b> as parameter
+                                      - <b>SL_SO_PHY_TX_POWER</b> \n
+                                                     RAW socket, set WLAN PHY TX power \n
+                                                     Valid rage is 1-15 \n
+                                                     This options takes <b>uint32_t</b> as parameter
+                                      - <b>SL_SO_PHY_NUM_FRAMES_TO_TX</b> \n
+                                                     RAW socket, set number of frames to transmit in transceiver mode.
+                                                     Default: 1 packet
+                                                     This options takes <b>uint32_t</b> as parameter
+                                      - <b>SL_SO_PHY_PREAMBLE</b> \n
+                                                     RAW socket, set WLAN PHY preamble for Long/Short\n
+                                                     This options takes <b>uint32_t</b> as parameter
+
+        \param[in] optval           specifies a value for the option
+        \param[in] optlen           specifies the length of the
+            option value
+
+        \return                     On success, zero is returned.
+                                    On error, a negative value is returned.
+        \sa     sl_getsockopt
+        \note   belongs to \ref basic_api
+        \warning
+        \par   Examples:
+        \par
+        <b> SL_SO_KEEPALIVE: </b>(disable Keepalive)
+        \code
+               SlSockKeepalive_t enableOption;
+               enableOption.KeepaliveEnabled = 0;
+               sl_SetSockOpt(SockID,SL_SOL_SOCKET,SL_SO_KEEPALIVE, (uint8_t *)&enableOption,sizeof(enableOption));
+        \endcode
+        \par
+        <b> SL_SO_RCVTIMEO: </b>
+        \code
+               struct SlTimeval_t timeVal;
+               timeVal.tv_sec =  1;             // Seconds
+               timeVal.tv_usec = 0;             // Microseconds. 10000 microseconds resolution
+               sl_SetSockOpt(SockID,SL_SOL_SOCKET,SL_SO_RCVTIMEO, (uint8_t *)&timeVal, sizeof(timeVal));    // Enable receive timeout
+        \endcode
+        \par
+        <b>    SL_SO_RCVBUF: </b>
+        \code
+               SlSockWinsize_t size;
+               size.Winsize = 3000;  // bytes
+               sl_SetSockOpt(SockID,SL_SOL_SOCKET,SL_SO_RCVBUF, (uint8_t *)&size, sizeof(size));
+        \endcode
+        \par
+        <b>    SL_SO_NONBLOCKING: </b>
+        \code
+               SlSockNonblocking_t enableOption;
+               enableOption.NonblockingEnabled = 1;
+               sl_SetSockOpt(SockID,SL_SOL_SOCKET,SL_SO_NONBLOCKING, (uint8_t *)&enableOption,sizeof(enableOption)); // Enable/disable nonblocking mode
+        \endcode
+        \par
+        <b>    SL_SO_SECMETHOD:</b>
+        \code
+               SlSockSecureMethod method;
+               method.secureMethod = SL_SO_SEC_METHOD_SSLV3;                                 // security method we want to use
+               SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET);
+               sl_SetSockOpt(SockID, SL_SOL_SOCKET, SL_SO_SECMETHOD, (uint8_t *)&method, sizeof(method));
+        \endcode
+        \par
+        <b>   SL_SO_SECURE_MASK:</b>
+        \code
+               SlSockSecureMask cipher;
+               cipher.secureMask = SL_SEC_MASK_SSL_RSA_WITH_RC4_128_SHA;                   // cipher type
+               SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, SL_SEC_SOCKET);
+               sl_SetSockOpt(SockID, SL_SOL_SOCKET, SL_SO_SEC_MASK,(uint8_t *)&cipher, sizeof(cipher));
+        \endcode
+        \par
+        <b>   SL_SO_SECURE_FILES_CA_FILE_NAME:</b>
+        \code
+               sl_SetSockOpt(SockID,SL_SOL_SOCKET,SL_SO_SECURE_FILES_CA_FILE_NAME,"exuifaxCaCert.der",strlen("exuifaxCaCert.der"));
+         \endcode
+
+       \par
+        <b>   SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME:</b>
+         \code
+               sl_SetSockOpt(SockID,SL_SOL_SOCKET,SL_SO_SECURE_FILES_PRIVATE_KEY_FILE_NAME,"myPrivateKey.der",strlen("myPrivateKey.der"));
+         \endcode
+
+       \par
+        <b>   SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME:</b>
+         \code
+               sl_SetSockOpt(SockID,SL_SOL_SOCKET,SL_SO_SECURE_FILES_CERTIFICATE_FILE_NAME,"myCertificate.der",strlen("myCertificate.der"));
+         \endcode
+
+       \par
+        <b>   SL_SO_SECURE_FILES_DH_KEY_FILE_NAME:</b>
+         \code
+               sl_SetSockOpt(SockID,SL_SOL_SOCKET,SL_SO_SECURE_FILES_DH_KEY_FILE_NAME,"myDHinServerMode.der",strlen("myDHinServerMode.der"));
+         \endcode
+
+       \par
+        <b>   SL_IP_MULTICAST_TTL:</b>
+         \code
+               uint8_t ttl = 20;
+               sl_SetSockOpt(SockID, SL_IPPROTO_IP, SL_IP_MULTICAST_TTL, &ttl, sizeof(ttl));
+         \endcode
+
+       \par
+        <b>   SL_IP_ADD_MEMBERSHIP:</b>
+         \code
+               SlSockIpMreq mreq;
+               sl_SetSockOpt(SockID, SL_IPPROTO_IP, SL_IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));
+        \endcode
+
+       \par
+        <b>   SL_IP_DROP_MEMBERSHIP:</b>
+        \code
+               SlSockIpMreq mreq;
+               sl_SetSockOpt(SockID, SL_IPPROTO_IP, SL_IP_DROP_MEMBERSHIP, &mreq, sizeof(mreq));
+        \endcode
+
+       \par
+        <b>   SL_SO_CHANGE_CHANNEL:</b>
+        \code
+              uint32_t newChannel = 6; // range is 1-13
+              sl_SetSockOpt(SockID, SL_SOL_SOCKET, SL_SO_CHANGE_CHANNEL, &newChannel, sizeof(newChannel));
+        \endcode
+
+        \par
+        <b>   SL_IP_RAW_RX_NO_HEADER:</b>
+        \code
+              uint32_t header = 1;  // remove ip header
+              sl_SetSockOpt(SockID, SL_IPPROTO_IP, SL_IP_RAW_RX_NO_HEADER, &header, sizeof(header));
+        \endcode
+
+       \par
+        <b>   SL_IP_HDRINCL:</b>
+        \code
+             uint32_t header = 1;
+             sl_SetSockOpt(SockID, SL_IPPROTO_IP, SL_IP_HDRINCL, &header, sizeof(header));
+        \endcode
+       \par
+        <b>   SL_IP_RAW_IPV6_HDRINCL:</b>
+        \code
+              uint32_t header = 1;
+              sl_SetSockOpt(SockID, SL_IPPROTO_IP, SL_IP_RAW_IPV6_HDRINCL, &header, sizeof(header));
+        \endcode
+
+       \par
+        <b>   SL_SO_PHY_RATE:</b>
+        \code
+              uint32_t rate = 6; // see wlan.h RateIndex_e for values
+              sl_SetSockOpt(SockID, SL_SOL_PHY_OPT, SL_SO_PHY_RATE, &rate, sizeof(rate));
+        \endcode
+
+       \par
+        <b>   SL_SO_PHY_TX_POWER:</b>
+        \code
+              uint32_t txpower = 1; // valid range is 1-15
+              sl_SetSockOpt(SockID, SL_SOL_PHY_OPT, SL_SO_PHY_TX_POWER, &txpower, sizeof(txpower));
+        \endcode
+
+       \par
+        <b>   SL_SO_PHY_NUM_FRAMES_TO_TX:</b>
+        \code
+         	  uint32_t numframes = 1;
+              sl_SetSockOpt(SockID, SL_SOL_PHY_OPT, SL_SO_PHY_NUM_FRAMES_TO_TX, &numframes, sizeof(numframes));
+        \endcode
+
+       \par
+        <b>   SL_SO_PHY_PREAMBLE:</b>
+        \code
+              uint32_t preamble = 1;
+              sl_SetSockOpt(SockID, SL_SOL_PHY_OPT, SL_SO_PHY_PREAMBLE, &preamble, sizeof(preamble));
+        \endcode
+
+    */
+#if _SL_INCLUDE_FUNC(sl_SetSockOpt)
+    int16_t sl_SetSockOpt(int16_t sd, int16_t level, int16_t optname, const void *optval, SlSocklen_t optlen);
+#endif
+
+    /*!
+        \brief Get socket options
+
+        This function manipulate the options associated with a socket.
+        Options may exist at multiple protocol levels; they are always
+        present at the uppermost socket level.
+
+        When manipulating socket options the level at which the option resides
+        and the name of the option must be specified.  To manipulate options at
+        the socket level, level is specified as SOL_SOCKET.  To manipulate
+        options at any other level the protocol number of the appropriate proto-
+        col controlling the option is supplied.  For example, to indicate that an
+        option is to be interpreted by the TCP protocol, level should be set to
+        the protocol number of TCP;
+
+        The parameters optval and optlen are used to access optval -
+        ues for setsockopt().  For getsockopt() they identify a
+        buffer in which the value for the requested option(s) are to
+        be returned.  For getsockopt(), optlen is a value-result
+        parameter, initially containing the size of the buffer
+        pointed to by option_value, and modified on return to
+        indicate the actual size of the value returned.  If no option
+        value is to be supplied or returned, option_value may be
+        NULL.
+
+
+        \param[in]  sd              socket handle
+        \param[in]  level           defines the protocol level for this option
+        \param[in]  optname         defines the option name to interrogate
+        \param[out] optval          specifies a value for the option
+        \param[out] optlen          specifies the length of the
+                                    option value
+
+        \return                        On success, zero is returned.
+                                    On error, a negative value is returned.
+        \sa     sl_SetSockOpt
+        \note   See sl_SetSockOpt
+                belongs to \ref ext_api
+        \warning
+    */
+#if _SL_INCLUDE_FUNC(sl_GetSockOpt)
+    int16_t sl_GetSockOpt(int16_t sd, int16_t level, int16_t optname, void *optval, SlSocklen_t *optlen);
+#endif
+
+    /*!
+        \brief read data from TCP socket
+
+        function receives a message from a connection-mode socket
+
+        \param[in]  sd              socket handle
+        \param[out] buf             Points to the buffer where the
+                                    message should be stored.
+        \param[in]  Len             Specifies the length in bytes of
+                                    the buffer pointed to by the buffer argument.
+                                    Range: 1-16000 bytes
+        \param[in]  flags           Specifies the type of message
+                                    reception. On this version, this parameter is not
+                                    supported.
+
+        \return                     return the number of bytes received,
+                                    or a negative value if an error occurred.
+                                    using a non-blocking recv a possible negative value is SL_EAGAIN.
+                                    SL_POOL_IS_EMPTY may be return in case there are no resources in the system
+                                     In this case try again later or increase MAX_CONCURRENT_ACTIONS
+
+        \sa     sl_RecvFrom
+        \note                       belongs to \ref recv_api
+        \warning
+        \par        Examples:
+        \code       An example of receiving data using TCP socket:
+
+                    SlSockAddrIn_t  Addr;
+                    SlSockAddrIn_t  LocalAddr;
+                    int16_t AddrSize = sizeof(SlSockAddrIn_t);
+                    int16_t SockID, newSockID;
+                    int16_t Status;
+                    int8_t Buf[RECV_BUF_LEN];
+
+                    LocalAddr.sin_family = SL_AF_INET;
+                    LocalAddr.sin_port = sl_Htons(5001);
+                    LocalAddr.sin_addr.s_addr = 0;
+
+                    Addr.sin_family = SL_AF_INET;
+                    Addr.sin_port = sl_Htons(5001);
+                    Addr.sin_addr.s_addr = sl_Htonl(SL_IPV4_VAL(10,1,1,200));
+
+                    SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
+                    Status = sl_Bind(SockID, (SlSockAddr_t *)&LocalAddr, AddrSize);
+                    Status = sl_Listen(SockID, 0);
+                    newSockID = sl_Accept(SockID, (SlSockAddr_t*)&Addr, (SlSocklen_t*) &AddrSize);
+                    Status = sl_Recv(newSockID, Buf, 1460, 0);
+        \endcode
+        \code      Example code for Rx transceiver mode using a raw socket
+                   int8_t buffer[1536];
+                   int16_t sd;
+                   uint16_t size;
+                   SlTransceiverRxOverHead_t *transHeader;
+                   sd = sl_Socket(SL_AF_RF,SL_SOCK_RAW,11); // channel 11
+                   while(1)
+                   {
+                      size = sl_Recv(sd,buffer,1536,0);
+                      transHeader = (SlTransceiverRxOverHead_t *)buffer;
+                      printf("RSSI is %d frame type is 0x%x size %d\n",transHeader->rssi,buffer[sizeof(SlTransceiverRxOverHead_t)],size);
+                   }
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_Recv)
+    int16_t sl_Recv(int16_t sd, void *buf, int16_t Len, int16_t flags);
+#endif
+
+    /*!
+        \brief read data from socket
+
+        function receives a message from a connection-mode or
+        connectionless-mode socket
+
+        \param[in]  sd              socket handle
+        \param[out] buf             Points to the buffer where the message should be stored.
+        \param[in]  Len             Specifies the length in bytes of the buffer pointed to by the buffer argument.
+                                    Range: 1-16000 bytes
+        \param[in]  flags           Specifies the type of message
+                                    reception. On this version, this parameter is not
+                                    supported.
+        \param[in]  from            pointer to an address structure
+                                    indicating the source
+                                    address.\n sockaddr:\n - code
+                                    for the address format. On this
+                                    version only AF_INET is
+                                    supported.\n - socket address,
+                                    the length depends on the code
+                                    format
+        \param[in]  fromlen         source address structure
+                                    size. This parameter MUST be set to the size of the structure pointed to by addr.
+
+
+        \return                     return the number of bytes received,
+                                    or a negative value if an error occurred.
+                                    using a non-blocking recv a possible negative value is SL_EAGAIN.
+                                    SL_RET_CODE_INVALID_INPUT (-2) will be returned if fromlen has incorrect length.
+                                    SL_POOL_IS_EMPTY may be return in case there are no resources in the system
+                                     In this case try again later or increase MAX_CONCURRENT_ACTIONS
+
+        \sa     sl_Recv
+        \note                       belongs to \ref recv_api
+        \warning
+        \par        Example:
+        \code       An example of receiving data:
+
+                    SlSockAddrIn_t  Addr;
+                    SlSockAddrIn_t  LocalAddr;
+                    int16_t AddrSize = sizeof(SlSockAddrIn_t);
+                    int16_t SockID;
+                    int16_t Status;
+                    int8_t Buf[RECV_BUF_LEN];
+
+                    LocalAddr.sin_family = SL_AF_INET;
+                    LocalAddr.sin_port = sl_Htons(5001);
+                    LocalAddr.sin_addr.s_addr = 0;
+
+                    SockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0);
+                    Status = sl_Bind(SockID, (SlSockAddr_t *)&LocalAddr, AddrSize);
+                    Status = sl_RecvFrom(SockID, Buf, 1472, 0, (SlSockAddr_t *)&Addr, (SlSocklen_t*)&AddrSize);
+
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_RecvFrom)
+    int16_t sl_RecvFrom(int16_t sd, void *buf, int16_t Len, int16_t flags, SlSockAddr_t *from, SlSocklen_t *fromlen);
+#endif
+
+    /*!
+        \brief write data to TCP socket
+
+        This function is used to transmit a message to another socket.
+        Returns immediately after sending data to device.
+        In case of TCP failure an async event SL_SOCKET_TX_FAILED_EVENT is going to
+        be received.
+        In case of a RAW socket (transceiver mode), extra 4 bytes should be reserved at the end of the
+        frame data buffer for WLAN FCS
+
+        \param[in] sd               socket handle
+        \param[in] buf              Points to a buffer containing
+                                    the message to be sent
+        \param[in] Len              message size in bytes. Range: 1-1460 bytes
+        \param[in] flags            Specifies the type of message
+                                    transmission. On this version, this parameter is not
+                                    supported for TCP.
+                                    For transceiver mode, the SL_RAW_RF_TX_PARAMS macro can be used to determine
+                                    transmission parameters (channel,rate,tx_power,preamble)
+
+
+        \return                     Return the number of bytes transmitted,
+                                    or -1 if an error occurred
+
+        \sa     sl_SendTo
+        \note                       belongs to \ref send_api
+        \warning
+        \par        Example:
+        \code       An example of sending data:
+
+                    SlSockAddrIn_t  Addr;
+                    int16_t AddrSize = sizeof(SlSockAddrIn_t);
+                    int16_t SockID;
+                    int16_t Status;
+                    int8_t Buf[SEND_BUF_LEN];
+
+                    Addr.sin_family = SL_AF_INET;
+                    Addr.sin_port = sl_Htons(5001);
+                    Addr.sin_addr.s_addr = sl_Htonl(SL_IPV4_VAL(10,1,1,200));
+
+                    SockID = sl_Socket(SL_AF_INET,SL_SOCK_STREAM, 0);
+                    Status = sl_Connect(SockID, (SlSockAddr_t *)&Addr, AddrSize);
+                    Status = sl_Send(SockID, Buf, 1460, 0 );
+
+        \endcode
+     */
+#if _SL_INCLUDE_FUNC(sl_Send )
+    int16_t sl_Send(int16_t sd, const void *buf, int16_t Len, int16_t flags);
+#endif
+
+    /*!
+        \brief write data to socket
+
+        This function is used to transmit a message to another socket
+        (connection less socket SOCK_DGRAM,  SOCK_RAW).
+        Returns immediately after sending data to device.
+        In case of transmission failure an async event SL_SOCKET_TX_FAILED_EVENT is going to
+        be received.
+
+        \param[in] sd               socket handle
+        \param[in] buf              Points to a buffer containing
+                                    the message to be sent
+        \param[in] Len              message size in bytes. Range: 1-1460 bytes
+        \param[in] flags            Specifies the type of message
+                                    transmission. On this version, this parameter is not
+                                    supported
+        \param[in] to               pointer to an address structure
+                                    indicating the destination
+                                    address.\n sockaddr:\n - code
+                                    for the address format. On this
+                                    version only AF_INET is
+                                    supported.\n - socket address,
+                                    the length depends on the code
+                                    format
+        \param[in] tolen            destination address structure size
+
+        \return                     Return the number of transmitted bytes,
+                                    or -1 if an error occurred
+
+        \sa     sl_Send
+        \note                       belongs to \ref send_api
+        \warning
+        \par        Example:
+        \code       An example of sending data:
+
+                    SlSockAddrIn_t  Addr;
+                    int16_t AddrSize = sizeof(SlSockAddrIn_t);
+                    int16_t SockID;
+                    int16_t Status;
+                    int8_t Buf[SEND_BUF_LEN];
+
+                    Addr.sin_family = SL_AF_INET;
+                    Addr.sin_port = sl_Htons(5001);
+                    Addr.sin_addr.s_addr = sl_Htonl(SL_IPV4_VAL(10,1,1,200));
+
+                    SockID = sl_Socket(SL_AF_INET,SL_SOCK_DGRAM, 0);
+                    Status = sl_SendTo(SockID, Buf, 1472, 0, (SlSockAddr_t *)&Addr, AddrSize);
+
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_SendTo)
+    int16_t sl_SendTo(int16_t sd, const void *buf, int16_t Len, int16_t flags, const SlSockAddr_t *to, SlSocklen_t tolen);
+#endif
+
+    /*!
+        \brief Reorder the bytes of a 32-bit unsigned value
+
+        This function is used to Reorder the bytes of a 32-bit unsigned value from processor order to network order.
+
+        \param[in] var              variable to reorder
+
+        \return                     Return the reorder variable,
+
+        \sa     sl_SendTo  sl_Bind  sl_Connect  sl_RecvFrom  sl_Accept
+        \note                       belongs to \ref send_api
+        \warning
+    */
+#if _SL_INCLUDE_FUNC(sl_Htonl )
+    uint32_t sl_Htonl( uint32_t val );
+
+#define sl_Ntohl sl_Htonl  /* Reorder the bytes of a 16-bit unsigned value from network order to processor orde. */
+#endif
+
+    /*!
+        \brief Reorder the bytes of a 16-bit unsigned value
+
+        This function is used to Reorder the bytes of a 16-bit unsigned value from processor order to network order.
+
+        \param[in] var              variable to reorder
+
+        \return                     Return the reorder variable,
+
+        \sa     sl_SendTo  sl_Bind    sl_Connect  sl_RecvFrom  sl_Accept
+        \note                       belongs to \ref send_api
+        \warning
+    */
+#if _SL_INCLUDE_FUNC(sl_Htons )
+    uint16_t sl_Htons( uint16_t val );
+
+#define sl_Ntohs sl_Htons   /* Reorder the bytes of a 16-bit unsigned value from network order to processor orde. */
+#endif
+
+private:
+
+    cc3100_driver   &_driver;
+    cc3100_nonos    &_nonos;
+    
+};//class
+
+
+}//namespace mbed_cc3100    
+
+    /*!
+
+     Close the Doxygen group.
+     @}
+
+     */
+
+#endif /* __SOCKET_H__ */
+
+
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_spawn.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_spawn.cpp	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,196 @@
+/*
+ * spawn.c - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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 files                                                             */
+/*****************************************************************************/
+#include "cc3100_simplelink.h"
+
+#include "cc3100_spawn.h"
+
+#if (defined (SL_PLATFORM_MULTI_THREADED)) && (!defined (SL_PLATFORM_EXTERNAL_SPAWN))
+
+namespace mbed_cc3100 {
+
+#define _SL_MAX_INTERNAL_SPAWN_ENTRIES      10
+
+
+typedef struct _SlInternalSpawnEntry_t {
+    _SlSpawnEntryFunc_t 		        pEntry;
+    void* 						        pValue;
+    struct _SlInternalSpawnEntry_t*     pNext;
+} _SlInternalSpawnEntry_t;
+
+typedef struct {
+    _SlInternalSpawnEntry_t     SpawnEntries[_SL_MAX_INTERNAL_SPAWN_ENTRIES];
+    _SlInternalSpawnEntry_t*    pFree;
+    _SlInternalSpawnEntry_t*    pWaitForExe;
+    _SlInternalSpawnEntry_t*    pLastInWaitList;
+    _SlSyncObj_t                SyncObj;
+    _SlLockObj_t                LockObj;
+} _SlInternalSpawnCB_t;
+
+_SlInternalSpawnCB_t g_SlInternalSpawnCB;
+
+cc3100_spawn::cc3100_spawn()
+{
+
+}
+
+cc3100_spawn::~cc3100_spawn()
+{
+
+}
+
+
+void cc3100_spawn::_SlInternalSpawnTaskEntry()
+{
+    int16_t                     i;
+    _SlInternalSpawnEntry_t*    pEntry;
+    uint8_t                     LastEntry;
+
+    /* create and lock the locking object. lock in order to avoid race condition
+        on the first creation */
+    sl_LockObjCreate(&g_SlInternalSpawnCB.LockObj,"SlSpawnProtect");
+    sl_LockObjLock(&g_SlInternalSpawnCB.LockObj,SL_OS_NO_WAIT);
+
+    /* create and clear the sync object */
+    sl_SyncObjCreate(&g_SlInternalSpawnCB.SyncObj,"SlSpawnSync");
+    sl_SyncObjWait(&g_SlInternalSpawnCB.SyncObj,SL_OS_NO_WAIT);
+
+    g_SlInternalSpawnCB.pFree = &g_SlInternalSpawnCB.SpawnEntries[0];
+    g_SlInternalSpawnCB.pWaitForExe = NULL;
+    g_SlInternalSpawnCB.pLastInWaitList = NULL;
+
+    /* create the link list between the entries */
+    for (i=0 ; i<_SL_MAX_INTERNAL_SPAWN_ENTRIES - 1 ; i++) {
+        g_SlInternalSpawnCB.SpawnEntries[i].pNext = &g_SlInternalSpawnCB.SpawnEntries[i+1];
+        g_SlInternalSpawnCB.SpawnEntries[i].pEntry = NULL;
+    }
+    g_SlInternalSpawnCB.SpawnEntries[i].pNext = NULL;
+
+    _SlDrvObjUnLock(&g_SlInternalSpawnCB.LockObj);
+
+
+    /* here we ready to execute entries */
+
+    while (TRUE) {
+        sl_SyncObjWait(&g_SlInternalSpawnCB.SyncObj,SL_OS_WAIT_FOREVER);
+        /* go over all entries that already waiting for execution */
+        LastEntry = FALSE;
+        do {
+            /* get entry to execute */
+            _SlDrvObjLockWaitForever(&g_SlInternalSpawnCB.LockObj);
+
+            pEntry = g_SlInternalSpawnCB.pWaitForExe;
+            if ( NULL == pEntry ) {
+                _SlDrvObjUnLock(&g_SlInternalSpawnCB.LockObj);
+                break;
+            }
+            g_SlInternalSpawnCB.pWaitForExe = pEntry->pNext;
+            if (pEntry == g_SlInternalSpawnCB.pLastInWaitList) {
+                g_SlInternalSpawnCB.pLastInWaitList = NULL;
+                LastEntry = TRUE;
+            }
+
+            _SlDrvObjUnLock(&g_SlInternalSpawnCB.LockObj);
+
+
+            /* pEntry could be null in case that the sync was already set by some
+               of the entries during execution of earlier entry */
+            if (NULL != pEntry) {
+                pEntry->pEntry(pEntry->pValue);
+                /* free the entry */
+                _SlDrvObjLockWaitForever(&g_SlInternalSpawnCB.LockObj);
+
+                pEntry->pNext = g_SlInternalSpawnCB.pFree;
+                g_SlInternalSpawnCB.pFree = pEntry;
+
+
+                if (NULL != g_SlInternalSpawnCB.pWaitForExe) {
+                    /* new entry received meanwhile */
+                    LastEntry = FALSE;
+                }
+
+                _SlDrvObjUnLock(&g_SlInternalSpawnCB.LockObj);
+
+            }
+
+        } while (!LastEntry);
+    }
+}
+
+
+int16_t cc3100_spawn::_SlInternalSpawn(_SlSpawnEntryFunc_t pEntry , void* pValue , uint32_t flags)
+{
+    int16_t                         Res = 0;
+    _SlInternalSpawnEntry_t*    pSpawnEntry;
+
+    if (NULL == pEntry) {
+        Res = -1;
+    } else {
+         _SlDrvObjLockWaitForever(&g_SlInternalSpawnCB.LockObj);
+
+        pSpawnEntry = g_SlInternalSpawnCB.pFree;
+        g_SlInternalSpawnCB.pFree = pSpawnEntry->pNext;
+
+        pSpawnEntry->pEntry = pEntry;
+        pSpawnEntry->pValue = pValue;
+        pSpawnEntry->pNext = NULL;
+
+        if (NULL == g_SlInternalSpawnCB.pWaitForExe) {
+            g_SlInternalSpawnCB.pWaitForExe = pSpawnEntry;
+            g_SlInternalSpawnCB.pLastInWaitList = pSpawnEntry;
+        } else {
+            g_SlInternalSpawnCB.pLastInWaitList->pNext = pSpawnEntry;
+            g_SlInternalSpawnCB.pLastInWaitList = pSpawnEntry;
+        }
+
+        _SlDrvObjUnLock(&g_SlInternalSpawnCB.LockObj);
+        
+        /* this sync is called after releasing the lock object to avoid unnecessary context switches */
+        _SlDrvSyncObjSignal(&g_SlInternalSpawnCB.SyncObj);
+    }
+
+    return Res;
+}
+
+}//namespace mbed_cc3100
+
+#endif//SL_PLATFORM_MULTI_THREADED
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_spawn.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_spawn.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,75 @@
+/*
+ * spawn.h - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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.
+ *
+*/
+
+#ifndef SPAWN_H_
+#define	SPAWN_H_
+
+#if (defined (SL_PLATFORM_MULTI_THREADED)) && (!defined (SL_PLATFORM_EXTERNAL_SPAWN))
+
+namespace mbed_cc3100 {
+
+class cc3100_spawn
+{
+
+public:
+
+    cc3100_spawn() {
+
+    }
+
+    ~cc3100_spawn() {
+
+    }
+    
+
+    void _SlInternalSpawnTaskEntry();
+    int16_t _SlInternalSpawn(_SlSpawnEntryFunc_t pEntry , void* pValue , uint32_t flags);
+
+#undef sl_Spawn
+#define sl_Spawn(pEntry,pValue,flags)               _SlInternalSpawn(pEntry,pValue,flags)
+
+#undef _SlTaskEntry
+#define _SlTaskEntry                                _SlInternalSpawnTaskEntry
+
+
+};//class
+
+}//namespace mbed_cc3100
+
+#endif//SL_PLATFORM_MULTI_THREADED
+
+#endif//SPAWN_H_
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_spi.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_spi.cpp	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,280 @@
+/*
+ * spi.cpp mbed
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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 "cc3100_simplelink.h"
+#include "cc3100_spi.h"
+#include "cli_uart.h"
+
+#include "osi.h"
+#include "portmacro.h"
+#include "projdefs.h"
+
+extern OsiMsgQ_t g_PBQueue; /*Message Queue*/
+
+namespace mbed_cc3100 {
+    
+P_EVENT_HANDLER   pIraEventHandler = 0;
+uint8_t           IntIsMasked;
+
+cc3100_spi::cc3100_spi(PinName button1_irq, PinName button2_irq, PinName cc3100_irq, PinName cc3100_nHIB, PinName cc3100_cs, SPI cc3100_spi, cc3100_driver &driver)
+    : _sw1_irq(button1_irq), _sw2_irq(button2_irq), _wlan_irq(cc3100_irq), _wlan_nHIB(cc3100_nHIB), _wlan_cs(cc3100_cs), _wlan_spi(cc3100_spi), _driver(driver)
+{
+
+    _wlan_spi.format(8,0);
+    _wlan_spi.frequency(16000000);
+    _wlan_irq.rise(this, &cc3100_spi::IntSpiGPIOHandler);      //_SlDrvRxIrqHandler is called from IntSpiGPIOHandler
+    _sw1_irq.rise(this, &cc3100_spi::buttonHandler_1);
+    _sw2_irq.rise(this, &cc3100_spi::buttonHandler_2);
+    _wlan_nHIB = 0;
+    _wlan_cs = 1;
+    wait_ms(200);
+    
+    
+}
+
+cc3100_spi::~cc3100_spi()
+{
+
+}
+
+int cc3100_spi::spi_Close(Fd_t fd)
+{
+    
+    // Disable WLAN Interrupt ...
+    cc3100_InterruptDisable();
+    
+    return NONOS_RET_OK;
+}
+
+void cc3100_spi::button1_InterruptDisable()
+{
+    _sw1_irq.rise(NULL);
+    wait_ms(1);
+}  
+
+void cc3100_spi::button2_InterruptDisable()
+{
+    _sw2_irq.rise(NULL);
+    wait_ms(1);
+}   
+
+void cc3100_spi::button1_InterruptEnable()
+{    
+    _sw1_irq.rise(this, &cc3100_spi::buttonHandler_1);
+}
+
+void cc3100_spi::button2_InterruptEnable()
+{    
+    _sw2_irq.rise(this, &cc3100_spi::buttonHandler_2);
+}    
+
+void cc3100_spi::cc3100_InterruptEnable()
+{
+    _wlan_irq.rise(this, &cc3100_spi::IntSpiGPIOHandler);
+}
+
+void cc3100_spi::cc3100_InterruptDisable()
+{
+    _wlan_irq.rise(NULL);
+}
+
+void cc3100_spi::CC3100_disable()
+{
+    _wlan_nHIB = 0;
+}
+
+void cc3100_spi::CC3100_enable()
+{
+    
+    _wlan_nHIB = 1;
+}
+
+Fd_t cc3100_spi::spi_Open(int8_t *ifName, uint32_t flags)
+{
+
+    // 50 ms delay
+    wait_ms(50);
+
+    // Enable WLAN interrupt
+    cc3100_InterruptEnable();
+
+    return NONOS_RET_OK;
+}
+
+int cc3100_spi::spi_Write(Fd_t fd, uint8_t *pBuff, int len)
+{
+    int len_to_return = len;
+
+    _wlan_cs = 0;
+
+    while(len) {
+        _wlan_spi.write(*pBuff++);
+        len--;
+    }
+
+    _wlan_cs = 1;
+    
+    return len_to_return;
+}
+
+int cc3100_spi::spi_Read(Fd_t fd, uint8_t *pBuff, int len)
+{
+    int i = 0;
+    _wlan_cs = 0;
+
+    for (i = 0; i < len; i++) {
+        pBuff[i] = _wlan_spi.write(0xFF);
+    }
+
+    _wlan_cs = 1;
+    return len;
+}
+
+void cc3100_spi::IntSpiGPIOHandler(void)
+{
+    
+    if(_wlan_irq){
+        _driver._SlDrvRxIrqHandler(0);
+    }        
+}
+
+/*!
+    \brief register an interrupt handler for the host IRQ
+
+    \param[in]      InterruptHdl    -    pointer to interrupt handler function
+
+    \param[in]      pValue          -    pointer to a memory strcuture that is
+                    passed to the interrupt handler.
+
+    \return         upon successful registration, the function shall return 0.
+                    Otherwise, -1 shall be returned
+
+    \sa
+    \note           If there is already registered interrupt handler, the
+                    function should overwrite the old handler with the new one
+    \warning
+*/
+int cc3100_spi::registerInterruptHandler(P_EVENT_HANDLER InterruptHdl , void* pValue)
+{
+
+    pIraEventHandler = InterruptHdl;
+    return 0;
+}
+
+/*!
+    \brief     Unmasks the Host IRQ
+
+    \param[in]      none
+
+    \return         none
+
+    \warning
+*/
+void cc3100_spi::UnMaskIntHdlr()
+{
+    IntIsMasked = FALSE;
+}
+
+/*!
+    \brief      Masks the Host IRQ
+
+    \param[in]      none
+
+    \return         none
+
+    \warning
+*/
+void cc3100_spi::MaskIntHdlr()
+{
+    IntIsMasked = TRUE;
+}
+
+/*!
+    \brief Handles the button press 1 on the MCU 
+           and updates the queue with relevant action.
+    
+    \param none
+    
+    \return none
+ */
+void cc3100_spi::buttonHandler_1(void)
+{
+    int32_t rv = 0;
+    button1_InterruptDisable();
+    osi_messages var;
+
+    g_publishCount++;
+
+    var = PUSH_BUTTON_1_PRESSED;
+    
+    rv = osi_MsgQWrite(&g_PBQueue, &var, OSI_NO_WAIT);
+    if(rv < 0){
+        Uart_Write((uint8_t*)"Messsage queue failed\r\n");
+    }
+    
+}
+
+/*!
+    \brief Handles the button press 2 on the MCU 
+           and updates the queue with relevant action.
+    
+    \param none
+    
+    \return none
+ */
+void cc3100_spi::buttonHandler_2(void)
+{
+    int32_t rv = 0;
+    button2_InterruptDisable();
+    osi_messages var;
+
+    g_publishCount++;
+
+    var = PUSH_BUTTON_2_PRESSED;
+    
+    rv = osi_MsgQWrite(&g_PBQueue, &var, OSI_NO_WAIT);
+    if(rv < 0){
+        Uart_Write((uint8_t*)"Messsage queue failed\r\n");
+    }
+    
+}
+
+}//namespace mbed_cc3100
+
+
+
+
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_spi.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_spi.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,339 @@
+/*
+ * spi.h - mbed
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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.
+ *
+*/
+
+
+#ifndef SPI_H_
+#define SPI_H_
+
+#include "mbed.h"
+
+/*!
+    \brief   type definition for the spi channel file descriptor
+
+    \note    On each porting or platform the type could be whatever is needed
+            - integer, pointer to structure etc.
+*/
+typedef unsigned int Fd_t;
+
+typedef void (*P_EVENT_HANDLER)(void* pValue);
+
+typedef enum events
+{
+    NO_ACTION = -1,
+    PUSH_BUTTON_1_PRESSED = 3,
+    PUSH_BUTTON_2_PRESSED = 4,
+    BROKER_DISCONNECTION = 2
+} osi_messages;
+
+extern uint32_t  g_publishCount; 
+
+namespace mbed_cc3100 {
+    
+class cc3100_driver;    
+    
+class cc3100_spi
+{
+public:
+
+    cc3100_spi(PinName button1_irq, PinName button2_irq, PinName cc3100_irq, PinName cc3100_nHIB, PinName cc3100_cs, SPI cc3100_spi, cc3100_driver &driver);
+
+    ~cc3100_spi();
+
+
+    /*!
+        \brief          Enables the CC3100
+
+        \param[in]      none
+
+        \return         none
+
+        \note
+
+        \warning
+    */
+    void CC3100_enable();
+
+    /*!
+        \brief          Disables the CC3100
+
+        \param[in]      none
+
+        \return         none
+
+        \note
+
+        \warning
+    */
+    void CC3100_disable();
+    
+/*!
+        \brief          Disables the button push interrupt
+
+        \param[in]      none
+
+        \return         none
+
+        \note
+
+        \warning
+    */    
+    void button1_InterruptDisable();
+    
+/*!
+        \brief          Enables the button push interrupt
+
+        \param[in]      none
+
+        \return         none
+
+        \note
+
+        \warning
+    */   
+    void button1_InterruptEnable();
+    
+/*!
+        \brief          Disables the button push interrupt
+
+        \param[in]      none
+
+        \return         none
+
+        \note
+
+        \warning
+    */    
+    void button2_InterruptDisable();
+    
+/*!
+        \brief          Enables the button push interrupt
+
+        \param[in]      none
+
+        \return         none
+
+        \note
+
+        \warning
+    */   
+    void button2_InterruptEnable();    
+
+    /*!
+        \brief          Enables the interrupt from the CC3100
+
+        \param[in]      none
+
+        \return         none
+
+        \note
+
+        \warning
+    */
+    void cc3100_InterruptEnable();
+
+    /*!
+        \brief          Disables the interrupt from the CC3100
+
+        \param[in]      none
+
+        \return         none
+
+        \note
+
+        \warning
+    */
+    void cc3100_InterruptDisable();
+
+    /*!
+        \brief open spi communication port to be used for communicating with a
+               SimpleLink device
+
+        Given an interface name and option flags, this function opens the spi
+        communication port and creates a file descriptor. This file descriptor can
+        be used afterwards to read and write data from and to this specific spi
+        channel.
+        The SPI speed, clock polarity, clock phase, chip select and all other
+        attributes are all set to hardcoded values in this function.
+
+        \param[in]      ifName    -    points to the interface name/path. The
+                        interface name is an optional attributes that the simple
+                        link driver receives on opening the device. in systems that
+                        the spi channel is not implemented as part of the os device
+                        drivers, this parameter could be NULL.
+        \param[in]      flags     -    option flags
+
+        \return         upon successful completion, the function shall open the spi
+                        channel and return a non-negative integer representing the
+                        file descriptor. Otherwise, -1 shall be returned
+
+        \sa             spi_Close , spi_Read , spi_Write
+        \note
+        \warning
+    */
+
+    Fd_t spi_Open(int8_t *ifName, uint32_t flags);
+
+    /*!
+        \brief closes an opened spi communication port
+
+        \param[in]      fd    -     file descriptor of an opened SPI channel
+
+        \return         upon successful completion, the function shall return 0.
+                        Otherwise, -1 shall be returned
+
+        \sa             spi_Open
+        \note
+        \warning
+    */
+    int spi_Close(Fd_t fd);
+
+    /*!
+        \brief attempts to read up to len bytes from SPI channel into a buffer
+               starting at pBuff.
+
+        \param[in]      fd     -    file descriptor of an opened SPI channel
+
+        \param[in]      pBuff  -    points to first location to start writing the
+                        data
+
+        \param[in]      len    -    number of bytes to read from the SPI channel
+
+        \return         upon successful completion, the function shall return 0.
+                        Otherwise, -1 shall be returned
+
+        \sa             spi_Open , spi_Write
+        \note
+        \warning
+    */
+    int spi_Read(Fd_t fd, uint8_t *pBuff, int len);
+
+    /*!
+        \brief attempts to write up to len bytes to the SPI channel
+
+        \param[in]      fd        -    file descriptor of an opened SPI channel
+
+        \param[in]      pBuff     -    points to first location to start getting the
+                        data from
+
+        \param[in]      len       -    number of bytes to write to the SPI channel
+
+        \return         upon successful completion, the function shall return 0.
+                        Otherwise, -1 shall be returned
+
+        \sa             spi_Open , spi_Read
+        \note           This function could be implemented as zero copy and return
+                        only upon successful completion of writing the whole buffer,
+                        but in cases that memory allocation is not too tight, the
+                        function could copy the data to internal buffer, return
+                        back and complete the write in parallel to other activities
+                        as long as the other SPI activities would be blocked untill
+                        the entire buffer write would be completed
+        \warning
+    */
+    int spi_Write(Fd_t fd, uint8_t *pBuff, int len);
+
+    /*!
+        \brief          The IntSpiGPIOHandler interrupt handler
+
+        \param[in]      none
+
+        \return         none
+
+        \note
+
+        \warning
+    */
+    void IntSpiGPIOHandler(void);
+
+    /*!
+        \brief register an interrupt handler for the host IRQ
+
+        \param[in]      InterruptHdl    -    pointer to interrupt handler function
+
+        \param[in]      pValue          -    pointer to a memory strcuture that is
+                        passed to the interrupt handler.
+
+        \return         upon successful registration, the function shall return 0.
+                        Otherwise, -1 shall be returned
+
+        \sa
+        \note           If there is already registered interrupt handler, the
+                        function should overwrite the old handler with the new one
+        \warning
+    */
+    int registerInterruptHandler(P_EVENT_HANDLER InterruptHdl , void* pValue);
+
+    /*!
+        \brief      Masks the Host IRQ
+
+        \param[in]      none
+
+        \return         none
+
+        \warning
+    */
+    void MaskIntHdlr();
+
+    /*!
+        \brief     Unmasks the Host IRQ
+
+        \param[in]      none
+
+        \return         none
+
+        \warning
+    */
+    void UnMaskIntHdlr();
+    
+    void buttonHandler_1(void);
+
+    void buttonHandler_2(void);
+   
+private:
+    
+    InterruptIn         _sw1_irq;
+    InterruptIn         _sw2_irq;
+    InterruptIn         _wlan_irq;
+    DigitalOut          _wlan_nHIB;
+    DigitalOut          _wlan_cs;
+    SPI                 _wlan_spi;
+    cc3100_driver       &_driver;
+
+
+};//class
+}//namespace mbed_cc3100
+#endif
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_trace.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_trace.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,193 @@
+/*
+ * trace.h - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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.
+ *
+*/
+#ifndef SIMPLELINK_TRACE_H_
+#define SIMPLELINK_TRACE_H_
+
+
+#include "cc3100_simplelink.h"
+
+/*****************************************************************************/
+/* Macro declarations                                                        */
+/*****************************************************************************/
+
+/*  This macro is for use by other macros to form a fully valid C statement. */
+#define st(x)      do { x } while (__LINE__ == -1)
+
+#define SL_SYNC_SCAN_THRESHOLD  (( uint32_t )2000)
+
+#define _SlDrvAssert(line )  { while(1); }
+
+#define _SL_ASSERT(expr)            { if(!(expr)){_SlDrvAssert(__LINE__); } }
+#define _SL_ERROR(expr, error)      { if(!(expr)){return (error); } }
+
+#define SL_HANDLING_ASSERT          2
+#define SL_HANDLING_ERROR           1
+#define SL_HANDLING_NONE            0
+
+#ifndef SL_TINY_EXT
+#define SL_SELF_COND_HANDLING       SL_HANDLING_ASSERT
+#define SL_PROTOCOL_HANDLING        SL_HANDLING_ASSERT
+#define SL_DRV_RET_CODE_HANDLING    SL_HANDLING_ASSERT
+#define SL_NWP_IF_HANDLING          SL_HANDLING_ASSERT
+#define SL_OSI_RET_OK_HANDLING      SL_HANDLING_ASSERT
+#define SL_MALLOC_OK_HANDLING       SL_HANDLING_ASSERT
+#define SL_USER_ARGS_HANDLING       SL_HANDLING_ASSERT
+#else
+#define SL_SELF_COND_HANDLING       SL_HANDLING_NONE
+#define SL_PROTOCOL_HANDLING        SL_HANDLING_NONE
+#define SL_DRV_RET_CODE_HANDLING    SL_HANDLING_NONE
+#define SL_NWP_IF_HANDLING          SL_HANDLING_NONE
+#define SL_OSI_RET_OK_HANDLING      SL_HANDLING_NONE
+#define SL_MALLOC_OK_HANDLING       SL_HANDLING_NONE
+#define SL_USER_ARGS_HANDLING       SL_HANDLING_NONE
+#endif
+
+#if (SL_DRV_RET_CODE_HANDLING == SL_HANDLING_ASSERT)
+#define VERIFY_RET_OK(Func)                     {_SlReturnVal_t _RetVal = (Func); _SL_ASSERT((_SlReturnVal_t)SL_OS_RET_CODE_OK == _RetVal)}
+#elif (SL_DRV_RET_CODE_HANDLING == SL_HANDLING_ERROR)
+#define VERIFY_RET_OK(Func)                     {_SlReturnVal_t _RetVal = (Func); if (SL_OS_RET_CODE_OK != _RetVal) return  _RetVal;}
+#else
+#define VERIFY_RET_OK(Func)                     (Func);
+#endif
+
+#if (SL_PROTOCOL_HANDLING == SL_HANDLING_ASSERT)
+#define VERIFY_PROTOCOL(expr)                   _SL_ASSERT(expr)
+#elif (SL_PROTOCOL_HANDLING == SL_HANDLING_ERROR)
+#define VERIFY_PROTOCOL(expr)                   _SL_ERROR(expr, SL_RET_CODE_PROTOCOL_ERROR)
+#else
+#define VERIFY_PROTOCOL(expr)
+#endif
+
+#if (defined(PROTECT_SOCKET_ASYNC_RESP) && (SL_SELF_COND_HANDLING == SL_HANDLING_ASSERT))
+#define VERIFY_SOCKET_CB(expr)                  _SL_ASSERT(expr)
+#elif (defined(PROTECT_SOCKET_ASYNC_RESP) && (SL_SELF_COND_HANDLING == SL_HANDLING_ERROR))
+#define VERIFY_SOCKET_CB(expr)                  _SL_ERROR(expr, SL_RET_CODE_SELF_ERROR)
+#else
+#define VERIFY_SOCKET_CB(expr)
+#endif
+
+#if (SL_NWP_IF_HANDLING == SL_HANDLING_ASSERT)
+//#define NWP_IF_WRITE_CHECK(fd,pBuff,len)       { int16_t RetSize, ExpSize = (len); RetSize = sl_IfWrite((fd),(pBuff),ExpSize); _SL_ASSERT(ExpSize == RetSize)}
+//#define NWP_IF_READ_CHECK(fd,pBuff,len)        { int16_t RetSize, ExpSize = (len); RetSize = sl_IfRead((fd),(pBuff),ExpSize);  _SL_ASSERT(ExpSize == RetSize)}
+#elif (SL_NWP_IF_HANDLING == SL_HANDLING_ERROR)
+//#define NWP_IF_WRITE_CHECK(fd,pBuff,len)       { _SL_ERROR((len == sl_IfWrite((fd),(pBuff),(len))), SL_RET_CODE_NWP_IF_ERROR);}
+//#define NWP_IF_READ_CHECK(fd,pBuff,len)        { _SL_ERROR((len == sl_IfRead((fd),(pBuff),(len))),  SL_RET_CODE_NWP_IF_ERROR);}
+#else
+//#define NWP_IF_WRITE_CHECK(fd,pBuff,len)       { sl_IfWrite((fd),(pBuff),(len));}
+//#define NWP_IF_READ_CHECK(fd,pBuff,len)        { sl_IfRead((fd),(pBuff),(len));}
+#endif
+
+#if (SL_OSI_RET_OK_HANDLING == SL_HANDLING_ASSERT)
+#define OSI_RET_OK_CHECK(Func)                  {_SlReturnVal_t _RetVal = (Func); _SL_ASSERT((_SlReturnVal_t)SL_OS_RET_CODE_OK == _RetVal)}
+#elif (SL_OSI_RET_OK_HANDLING == SL_HANDLING_ERROR)
+#define OSI_RET_OK_CHECK(Func)                  {_SlReturnVal_t _RetVal = (Func); if (SL_OS_RET_CODE_OK != _RetVal) return  _RetVal;}
+#else
+#define OSI_RET_OK_CHECK(Func)                  (Func);
+#endif
+
+#if (SL_MALLOC_OK_HANDLING == SL_HANDLING_ASSERT)
+#define MALLOC_OK_CHECK(Ptr)                    _SL_ASSERT(NULL != Ptr)
+#elif (SL_MALLOC_OK_HANDLING == SL_HANDLING_ERROR)
+#define MALLOC_OK_CHECK(Ptr)                    _SL_ERROR((NULL != Ptr), SL_RET_CODE_MALLOC_ERROR)
+#else
+#define MALLOC_OK_CHECK(Ptr)
+#endif
+
+#ifdef SL_INC_ARG_CHECK
+
+#if (SL_USER_ARGS_HANDLING == SL_HANDLING_ASSERT)
+#define ARG_CHECK_PTR(Ptr)                      _SL_ASSERT(NULL != Ptr)
+#elif (SL_USER_ARGS_HANDLING == SL_HANDLING_ERROR)
+#define ARG_CHECK_PTR(Ptr)                      _SL_ERROR((NULL != Ptr), SL_RET_CODE_INVALID_INPUT)
+#else
+#define ARG_CHECK_PTR(Ptr)
+#endif
+
+#else
+#define ARG_CHECK_PTR(Ptr)
+#endif
+
+//#define SL_DBG_TRACE_ENABLE
+#ifdef SL_DBG_TRACE_ENABLE
+#define SL_TRACE0(level,msg_id,str)                     printf(str)
+#define SL_TRACE1(level,msg_id,str,p1)                  printf(str,(p1))
+#define SL_TRACE2(level,msg_id,str,p1,p2)               printf(str,(p1),(p2))
+#define SL_TRACE3(level,msg_id,str,p1,p2,p3)            printf(str,(p1),(p2),(p3))
+#define SL_TRACE4(level,msg_id,str,p1,p2,p3,p4)         printf(str,(p1),(p2),(p3),(p4))
+#define SL_ERROR_TRACE(msg_id,str)                      printf(str)
+#define SL_ERROR_TRACE1(msg_id,str,p1)                  printf(str,(p1))
+#define SL_ERROR_TRACE2(msg_id,str,p1,p2)               printf(str,(p1),(p2))
+#define SL_ERROR_TRACE3(msg_id,str,p1,p2,p3)            printf(str,(p1),(p2),(p3))
+#define SL_ERROR_TRACE4(msg_id,str,p1,p2,p3,p4)         printf(str,(p1),(p2),(p3),(p4))
+#define SL_TRACE_FLUSH()
+#else
+#define SL_TRACE0(level,msg_id,str)
+#define SL_TRACE1(level,msg_id,str,p1)
+#define SL_TRACE2(level,msg_id,str,p1,p2)
+#define SL_TRACE3(level,msg_id,str,p1,p2,p3)
+#define SL_TRACE4(level,msg_id,str,p1,p2,p3,p4)
+#define SL_ERROR_TRACE(msg_id,str)
+#define SL_ERROR_TRACE1(msg_id,str,p1)
+#define SL_ERROR_TRACE2(msg_id,str,p1,p2)
+#define SL_ERROR_TRACE3(msg_id,str,p1,p2,p3)
+#define SL_ERROR_TRACE4(msg_id,str,p1,p2,p3,p4)
+#define SL_TRACE_FLUSH()
+#endif
+
+//#define SL_DBG_CNT_ENABLE
+#ifdef SL_DBG_CNT_ENABLE
+#define _SL_DBG_CNT_INC(Cnt)            g_DbgCnt. ## Cnt++
+#define _SL_DBG_SYNC_LOG(index,value)   {if(index < SL_DBG_SYNC_LOG_SIZE){*(uint32_t *)&g_DbgCnt.SyncLog[index] = *(uint32_t *)(value);}}
+
+#else
+#define _SL_DBG_CNT_INC(Cnt)
+#define _SL_DBG_SYNC_LOG(index,value)
+#endif
+
+#define SL_DBG_LEVEL_1                  1
+#define SL_DBG_LEVEL_2                  2
+#define SL_DBG_LEVEL_3                  4
+#define SL_DBG_LEVEL_MASK               (SL_DBG_LEVEL_2|SL_DBG_LEVEL_3)
+
+#define SL_INCLUDE_DBG_FUNC(Name)		((Name ## _DBG_LEVEL) & SL_DBG_LEVEL_MASK)
+
+#define _SlDrvPrintStat_DBG_LEVEL       SL_DBG_LEVEL_3
+#define _SlDrvOtherFunc_DBG_LEVEL       SL_DBG_LEVEL_1
+
+
+#endif /*__SIMPLELINK_TRACE_H__*/
+
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_user.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_user.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,1047 @@
+/*
+ * user.h - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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.
+*
+*/
+
+
+#ifndef USER_H_
+#define USER_H_
+
+/*!
+
+    \addtogroup Porting
+    @{
+
+*/
+
+/*!
+ ******************************************************************************
+
+    \defgroup       porting_user_include        User Include Files
+
+    This section IS NOT REQUIRED in case user provided primitives are handled
+    in makefiles or project configurations (IDE)
+
+    PORTING ACTION:
+        - Include all required header files for the definition of:
+            -# Transport layer library API (e.g. SPI, UART)
+            -# OS primitives definitions (e.g. Task spawn, Semaphores)
+            -# Memory management primitives (e.g. alloc, free)
+
+ ******************************************************************************
+ */
+
+#include <string.h>
+
+#ifndef SL_IF_TYPE_UART
+#include "cc3100_spi.h"
+#else
+#include "uart.h"
+#endif
+
+
+/*!
+ ******************************************************************************
+
+    \defgroup       porting_capabilities        Capability Set Definition
+
+    This section IS NOT REQUIRED in case one of the following pre defined
+    capabilities set is in use:
+    - SL_TINY
+    - SL_SMALL
+    - SL_FULL
+
+    PORTING ACTION:
+        - Define one of the pre-defined capabilities set or uncomment the
+          relevant definitions below to select the required capabilities
+          in order to "install" external SimpleLink library one should follow the next steps:
+	1. Include the external library API header file (i.e. #include "IOT.h")
+	2. Define each one of the desired external lib with one (out of 5) of the following:
+      #define SL_EXT_LIB_1 <Your external lib name>
+      #define SL_EXT_LIB_2 <Your external lib name>
+      #define SL_EXT_LIB_3 <Your external lib name>
+      #define SL_EXT_LIB_4 <Your external lib name>
+      #define SL_EXT_LIB_5 <Your external lib name>
+    @{
+ *******************************************************************************
+ */
+ 
+#define SL_FULL 
+
+/*!
+	\def		MAX_CONCURRENT_ACTIONS
+
+    \brief      Defines the maximum number of concurrent action in the system
+				Min:1 , Max: 32
+
+                Actions which has async events as return, can be
+
+    \sa
+
+    \note       In case there are not enough resources for the actions needed in the system,
+	        	error is received: POOL_IS_EMPTY
+			    one option is to increase MAX_CONCURRENT_ACTIONS
+				(improves performance but results in memory consumption)
+		     	Other option is to call the API later (decrease performance)
+
+    \warning    In case of setting to one, recommend to use non-blocking recv\recvfrom to allow
+				multiple socket recv
+*/
+#ifndef SL_TINY_EXT
+#define MAX_CONCURRENT_ACTIONS 10
+#else
+#define MAX_CONCURRENT_ACTIONS 1
+#endif
+
+/*!
+	\def		CPU_FREQ_IN_MHZ
+    \brief      Defines CPU frequency for Host side, for better accuracy of busy loops, if any
+    \sa
+    \note
+
+    \warning    If not set the default CPU frequency is set to 200MHz
+                This option will be deprecated in future release
+*/
+/*
+#define CPU_FREQ_IN_MHZ        25
+*/
+
+
+/*!
+	\def		SL_INC_ARG_CHECK
+
+    \brief      Defines whether the SimpleLink driver perform argument check
+                or not
+
+                When defined, the SimpleLink driver perform argument check on
+                function call. Removing this define could reduce some code
+                size and improve slightly the performances but may impact in
+                unpredictable behaviour in case of invalid arguments
+
+    \sa
+
+    \note       belongs to \ref porting_sec
+
+    \warning    Removing argument check may cause unpredictable behaviour in
+                case of invalid arguments.
+                In this case the user is responsible to argument validity
+                (for example all handlers must not be NULL)
+*/
+#define SL_INC_ARG_CHECK
+
+
+/*!
+    \def		SL_INC_STD_BSD_API_NAMING
+
+    \brief      Defines whether SimpleLink driver should expose standard BSD
+                APIs or not
+
+                When defined, the SimpleLink driver in addition to its alternative
+                BSD APIs expose also standard BSD APIs.
+                Standard BSD API includes the following functions:
+                socket , close , accept , bind , listen	, connect , select ,
+                setsockopt	, getsockopt , recv , recvfrom , write , send , sendto ,
+                gethostbyname
+
+    \sa
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+
+#define SL_INC_STD_BSD_API_NAMING
+
+
+/*!
+    \brief      Defines whether to include extended API in SimpleLink driver
+                or not
+
+                When defined, the SimpleLink driver will include also all
+                extended API of the included packages
+
+    \sa         ext_api
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+#define SL_INC_EXT_API
+
+/*!
+    \brief      Defines whether to include WLAN package in SimpleLink driver
+                or not
+
+                When defined, the SimpleLink driver will include also
+                the WLAN package
+
+    \sa
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+#define SL_INC_WLAN_PKG
+
+/*!
+    \brief      Defines whether to include SOCKET package in SimpleLink
+                driver or not
+
+                When defined, the SimpleLink driver will include also
+                the SOCKET package
+
+    \sa
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+#define SL_INC_SOCKET_PKG
+
+/*!
+    \brief      Defines whether to include NET_APP package in SimpleLink
+                driver or not
+
+                When defined, the SimpleLink driver will include also the
+                NET_APP package
+
+    \sa
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+#define SL_INC_NET_APP_PKG
+
+/*!
+    \brief      Defines whether to include NET_CFG package in SimpleLink
+                driver or not
+
+                When defined, the SimpleLink driver will include also
+                the NET_CFG package
+
+    \sa
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+#define SL_INC_NET_CFG_PKG
+
+/*!
+    \brief      Defines whether to include NVMEM package in SimpleLink
+                driver or not
+
+                When defined, the SimpleLink driver will include also the
+                NVMEM package
+
+    \sa
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+#define SL_INC_NVMEM_PKG
+
+/*!
+    \brief      Defines whether to include socket server side APIs
+                in SimpleLink driver or not
+
+                When defined, the SimpleLink driver will include also socket
+                server side APIs
+
+    \sa         server_side
+
+    \note
+
+    \warning
+*/
+#define SL_INC_SOCK_SERVER_SIDE_API
+
+/*!
+    \brief      Defines whether to include socket client side APIs in SimpleLink
+                driver or not
+
+                When defined, the SimpleLink driver will include also socket
+                client side APIs
+
+    \sa         client_side
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+#define SL_INC_SOCK_CLIENT_SIDE_API
+
+/*!
+    \brief      Defines whether to include socket receive APIs in SimpleLink
+                driver or not
+
+                When defined, the SimpleLink driver will include also socket
+                receive side APIs
+
+    \sa         recv_api
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+#define SL_INC_SOCK_RECV_API
+
+/*!
+    \brief      Defines whether to include socket send APIs in SimpleLink
+                driver or not
+
+                When defined, the SimpleLink driver will include also socket
+                send side APIs
+
+    \sa         send_api
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+#define SL_INC_SOCK_SEND_API
+
+/*!
+
+ Close the Doxygen group.
+ @}
+
+ */
+
+
+/*!
+ ******************************************************************************
+
+    \defgroup   porting_enable_device       Device Enable/Disable IO
+
+    The enable/disable API provide mechanism to enable/disable the network processor
+
+
+    PORTING ACTION:
+        - None
+    @{
+
+ ******************************************************************************
+ */
+/*!
+    \brief		Preamble to the enabling the Network Processor.
+                        Placeholder to implement any pre-process operations
+                        before enabling networking operations.
+
+    \sa			sl_DeviceEnable
+
+    \note       belongs to \ref ported_sec
+
+*/
+#define sl_DeviceEnablePreamble()
+
+/*!
+    \brief		Enable the Network Processor
+
+    \sa			sl_DeviceDisable
+
+    \note       belongs to \ref porting_sec
+
+*/
+//#define sl_DeviceEnable       _spi->CC3100_enable
+
+/*!
+    \brief		Disable the Network Processor
+
+    \sa			sl_DeviceEnable
+
+    \note       belongs to \ref porting_sec
+*/
+//#define sl_DeviceDisable      _spi->CC3100_disable
+
+/*!
+
+ Close the Doxygen group.
+ @}
+
+ */
+
+/*!
+ ******************************************************************************
+
+    \defgroup   porting_interface         Hardware Transport Interface
+
+    The simple link device can work with different transport interfaces
+    (namely,SPI or UART). Texas Instruments provides single driver
+    that can work with all these types. This section binds the
+    physical transport interface with the SimpleLink driver
+
+
+    \note       Correct and efficient implementation of this driver is critical
+                for the performances of the SimpleLink device on this platform.
+
+
+    PORTING ACTION:
+        - None
+
+    @{
+
+ ******************************************************************************
+ */
+
+#define _SlFd_t                    int32_t
+
+/*!
+    \brief      Opens an interface communication port to be used for communicating
+                with a SimpleLink device
+
+	            Given an interface name and option flags, this function opens
+                the communication port and creates a file descriptor.
+                This file descriptor is used afterwards to read and write
+                data from and to this specific communication channel.
+	            The speed, clock polarity, clock phase, chip select and all other
+                specific attributes of the channel are all should be set to hardcoded
+                in this function.
+
+	\param	 	ifName  -   points to the interface name/path. The interface name is an
+                            optional attributes that the simple link driver receives
+                            on opening the driver (sl_Start).
+                            In systems that the spi channel is not implemented as
+                            part of the OS device drivers, this parameter could be NULL.
+
+	\param      flags   -   optional flags parameters for future use
+
+	\return     upon successful completion, the function shall open the channel
+                and return a non-negative integer representing the file descriptor.
+                Otherwise, -1 shall be returned
+
+    \sa         sl_IfClose , sl_IfRead , sl_IfWrite
+
+	\note       The prototype of the function is as follow:
+                    Fd_t xxx_IfOpen(char* pIfName , unsigned long flags);
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+//#define sl_IfOpen                           _spi->spi_Open
+
+/*!
+    \brief      Closes an opened interface communication port
+
+	\param	 	fd  -   file descriptor of opened communication channel
+
+	\return		upon successful completion, the function shall return 0.
+			    Otherwise, -1 shall be returned
+
+    \sa         sl_IfOpen , sl_IfRead , sl_IfWrite
+
+	\note       The prototype of the function is as follow:
+                    int xxx_IfClose(Fd_t Fd);
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+//#define sl_IfClose                          _spi->spi_Close
+
+/*!
+    \brief      Attempts to read up to len bytes from an opened communication channel
+                into a buffer starting at pBuff.
+
+	\param	 	fd      -   file descriptor of an opened communication channel
+
+	\param		pBuff   -   pointer to the first location of a buffer that contains enough
+                            space for all expected data
+
+	\param      len     -   number of bytes to read from the communication channel
+
+	\return     upon successful completion, the function shall return the number of read bytes.
+                Otherwise, 0 shall be returned
+
+    \sa         sl_IfClose , sl_IfOpen , sl_IfWrite
+
+
+	\note       The prototype of the function is as follow:
+                    int xxx_IfRead(Fd_t Fd , char* pBuff , int Len);
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+//#define sl_IfRead                           _spi->spi_Read
+
+/*!
+    \brief attempts to write up to len bytes to the SPI channel
+
+	\param	 	fd      -   file descriptor of an opened communication channel
+
+	\param		pBuff   -   pointer to the first location of a buffer that contains
+                            the data to send over the communication channel
+
+	\param      len     -   number of bytes to write to the communication channel
+
+	\return     upon successful completion, the function shall return the number of sent bytes.
+				otherwise, 0 shall be returned
+
+    \sa         sl_IfClose , sl_IfOpen , sl_IfRead
+
+	\note       This function could be implemented as zero copy and return only upon successful completion
+                of writing the whole buffer, but in cases that memory allocation is not too tight, the
+                function could copy the data to internal buffer, return back and complete the write in
+                parallel to other activities as long as the other SPI activities would be blocked until
+                the entire buffer write would be completed
+
+               The prototype of the function is as follow:
+                    int xxx_IfWrite(Fd_t Fd , char* pBuff , int Len);
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+//#define sl_IfWrite                          _spi->spi_Write
+
+/*!
+    \brief 		register an interrupt handler routine for the host IRQ
+
+	\param	 	InterruptHdl	-	pointer to interrupt handler routine
+
+	\param 		pValue			-	pointer to a memory structure that is passed
+									to the interrupt handler.
+
+	\return		upon successful registration, the function shall return 0.
+				Otherwise, -1 shall be returned
+
+    \sa
+
+	\note		If there is already registered interrupt handler, the function
+				should overwrite the old handler with the new one
+
+	\note       If the handler is a null pointer, the function should un-register the
+	            interrupt handler, and the interrupts can be disabled.
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+//#define sl_IfRegIntHdlr(InterruptHdl , pValue) \
+//                                _spi->registerInterruptHandler(InterruptHdl , pValue)
+/*!
+    \brief 		Masks the Host IRQ
+
+    \sa		sl_IfUnMaskIntHdlr
+
+
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+
+//#define sl_IfMaskIntHdlr()
+
+/*!
+    \brief 		Unmasks the Host IRQ
+
+    \sa		sl_IfMaskIntHdlr
+
+
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+
+//#define sl_IfUnMaskIntHdlr()
+
+/*!
+    \brief 		Write Handers for statistics debug on write
+
+	\param	 	interface handler	-	pointer to interrupt handler routine
+
+
+	\return		no return value
+
+    \sa
+
+	\note		An optional hooks for monitoring before and after write info
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+/*
+#define SL_START_WRITE_STAT
+*/
+
+#ifdef SL_START_WRITE_STAT
+#define sl_IfStartWriteSequence
+#define sl_IfEndWriteSequence
+#endif
+/*!
+
+ Close the Doxygen group.
+ @}
+
+ */
+
+/*!
+ ******************************************************************************
+
+    \defgroup   porting_mem_mgm             Memory Management
+
+    This section declare in which memory management model the SimpleLink driver
+    will run:
+        -# Static
+        -# Dynamic
+
+    This section IS NOT REQUIRED in case Static model is selected.
+
+    The default memory model is Static
+
+    PORTING ACTION:
+        - If dynamic model is selected, define the alloc and free functions.
+
+    @{
+
+ *****************************************************************************
+ */
+
+/*!
+    \brief      Defines whether the SimpleLink driver is working in dynamic
+                memory model or not
+
+                When defined, the SimpleLink driver use dynamic allocations
+                if dynamic allocation is selected malloc and free functions
+                must be retrieved
+
+    \sa
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+/*
+#define SL_MEMORY_MGMT_DYNAMIC
+*/
+
+#ifdef SL_MEMORY_MGMT_DYNAMIC
+
+/*!
+    \brief
+
+    \sa
+
+    \note           belongs to \ref porting_sec
+
+    \warning
+*/
+#define sl_Malloc(Size)    malloc(Size)
+
+/*!
+    \brief
+
+    \sa
+
+    \note           belongs to \ref porting_sec
+
+    \warning
+*/
+#define sl_Free(pMem)    free(pMem)
+
+#endif
+
+/*!
+
+ Close the Doxygen group.
+ @}
+
+ */
+
+/*!
+ ******************************************************************************
+
+    \defgroup   porting_os          Operating System (OS)
+
+    The simple link driver can run on multi-threaded environment as well
+    as non-os environment (main loop)
+
+    This section IS NOT REQUIRED in case you are working on non-os environment.
+
+    If you choose to work in multi-threaded environment under any operating system
+    you will have to provide some basic adaptation routines to allow the driver
+    to protect access to resources from different threads (locking object) and
+    to allow synchronization between threads (sync objects).
+
+    PORTING ACTION:
+        -# Uncomment SL_PLATFORM_MULTI_THREADED define
+        -# Bind locking object routines
+        -# Bind synchronization object routines
+        -# Optional - Bind spawn thread routine
+
+    @{
+
+ ******************************************************************************
+ */
+
+
+//#define SL_PLATFORM_MULTI_THREADED
+
+
+#ifdef SL_PLATFORM_MULTI_THREADED
+
+/*!
+    \brief
+    \sa
+    \note           belongs to \ref porting_sec
+    \warning
+*/
+#define SL_OS_RET_CODE_OK      ((int)OSI_OK)
+
+/*!
+    \brief
+    \sa
+    \note           belongs to \ref porting_sec
+    \warning
+*/
+#define SL_OS_WAIT_FOREVER     ((OsiTime_t)OSI_WAIT_FOREVER)
+
+/*!
+    \brief
+    \sa
+    \note           belongs to \ref porting_sec
+    \warning
+*/
+#define SL_OS_NO_WAIT      ((OsiTime_t)OSI_NO_WAIT)
+
+/*!
+	\brief type definition for a time value
+
+	\note	On each porting or platform the type could be whatever is needed - integer, pointer to structure etc.
+
+    \note       belongs to \ref porting_sec
+*/
+#define _SlTime_t      OsiTime_tv
+
+/*!
+	\brief 	type definition for a sync object container
+
+	Sync object is object used to synchronize between two threads or thread and interrupt handler.
+	One thread is waiting on the object and the other thread send a signal, which then
+	release the waiting thread.
+	The signal must be able to be sent from interrupt context.
+	This object is generally implemented by binary semaphore or events.
+
+	\note	On each porting or platform the type could be whatever is needed - integer, structure etc.
+
+    \note       belongs to \ref porting_sec
+*/
+#define _SlSyncObj_t     OsiSyncObj_t
+
+
+/*!
+	\brief 	This function creates a sync object
+
+	The sync object is used for synchronization between different thread or ISR and
+	a thread.
+
+	\param	pSyncObj	-	pointer to the sync object control block
+
+	\return upon successful creation the function should return 0
+			Otherwise, a negative value indicating the error code shall be returned
+
+    \note       belongs to \ref porting_sec
+	\warning
+*/
+#define sl_SyncObjCreate(pSyncObj,pName)      osi_SyncObjCreate(pSyncObj)
+
+
+/*!
+	\brief 	This function deletes a sync object
+
+	\param	pSyncObj	-	pointer to the sync object control block
+
+	\return upon successful deletion the function should return 0
+			Otherwise, a negative value indicating the error code shall be returned
+    \note       belongs to \ref porting_sec
+	\warning
+*/
+#define sl_SyncObjDelete(pSyncObj)      osi_SyncObjDelete(pSyncObj)
+
+
+/*!
+	\brief 		This function generates a sync signal for the object.
+
+	All suspended threads waiting on this sync object are resumed
+
+	\param		pSyncObj	-	pointer to the sync object control block
+
+	\return 	upon successful signalling the function should return 0
+				Otherwise, a negative value indicating the error code shall be returned
+	\note		the function could be called from ISR context
+	\warning
+*/
+#define sl_SyncObjSignal(pSyncObj)      osi_SyncObjSignal(pSyncObj)
+
+/*!
+	\brief 		This function generates a sync signal for the object from Interrupt
+
+	This is for RTOS that should signal from IRQ using a dedicated API
+
+	\param		pSyncObj	-	pointer to the sync object control block
+
+	\return 	upon successful signalling the function should return 0
+				Otherwise, a negative value indicating the error code shall be returned
+	\note		the function could be called from ISR context
+	\warning
+*/
+#define sl_SyncObjSignalFromIRQ(pSyncObj)     osi_SyncObjSignalFromISR( pSyncObj)
+/*!
+	\brief 	This function waits for a sync signal of the specific sync object
+
+	\param	pSyncObj	-	pointer to the sync object control block
+	\param	Timeout		-	numeric value specifies the maximum number of mSec to
+							stay suspended while waiting for the sync signal
+							Currently, the simple link driver uses only two values:
+								- OSI_WAIT_FOREVER
+								- OSI_NO_WAIT
+
+	\return upon successful reception of the signal within the timeout window return 0
+			Otherwise, a negative value indicating the error code shall be returned
+    \note       belongs to \ref porting_sec
+	\warning
+*/
+#define sl_SyncObjWait(pSyncObj,Timeout)      osi_SyncObjWait( pSyncObj , Timeout)
+
+/*!
+	\brief 	type definition for a locking object container
+
+	Locking object are used to protect a resource from mutual accesses of two or more threads.
+	The locking object should support reentrant locks by a signal thread.
+	This object is generally implemented by mutex semaphore
+
+	\note	On each porting or platform the type could be whatever is needed - integer, structure etc.
+    \note       belongs to \ref porting_sec
+*/
+#define _SlLockObj_t      OsiLockObj_t
+
+/*!
+	\brief 	This function creates a locking object.
+
+	The locking object is used for protecting a shared resources between different
+	threads.
+
+	\param	pLockObj	-	pointer to the locking object control block
+
+	\return upon successful creation the function should return 0
+			Otherwise, a negative value indicating the error code shall be returned
+    \note       belongs to \ref porting_sec
+	\warning
+*/
+#define sl_LockObjCreate(pLockObj,pName)     osi_LockObjCreate(pLockObj)
+
+/*!
+	\brief 	This function deletes a locking object.
+
+	\param	pLockObj	-	pointer to the locking object control block
+
+	\return upon successful deletion the function should return 0
+			Otherwise, a negative value indicating the error code shall be returned
+    \note       belongs to \ref porting_sec
+	\warning
+*/
+#define sl_LockObjDelete(pLockObj)      osi_LockObjDelete(pLockObj)
+
+/*!
+	\brief 	This function locks a locking object.
+
+	All other threads that call this function before this thread calls
+	the osi_LockObjUnlock would be suspended
+
+	\param	pLockObj	-	pointer to the locking object control block
+	\param	Timeout		-	numeric value specifies the maximum number of mSec to
+							stay suspended while waiting for the locking object
+							Currently, the simple link driver uses only two values:
+								- OSI_WAIT_FOREVER
+								- OSI_NO_WAIT
+
+
+	\return upon successful reception of the locking object the function should return 0
+			Otherwise, a negative value indicating the error code shall be returned
+    \note       belongs to \ref porting_sec
+	\warning
+*/
+#define sl_LockObjLock(pLockObj,Timeout)     osi_LockObjLock( pLockObj , Timeout)
+
+/*!
+	\brief 	This function unlock a locking object.
+
+	\param	pLockObj	-	pointer to the locking object control block
+
+	\return upon successful unlocking the function should return 0
+			Otherwise, a negative value indicating the error code shall be returned
+    \note       belongs to \ref porting_sec
+	\warning
+*/
+#define sl_LockObjUnlock(pLockObj)      osi_LockObjUnlock( pLockObj)
+
+#endif
+/*!
+	\brief 	This function call the pEntry callback from a different context
+
+	\param	pEntry		-	pointer to the entry callback function
+
+	\param	pValue		- 	pointer to any type of memory structure that would be
+							passed to pEntry callback from the execution thread.
+
+	\param	flags		- 	execution flags - reserved for future usage
+
+	\return upon successful registration of the spawn the function should return 0
+			(the function is not blocked till the end of the execution of the function
+			and could be returned before the execution is actually completed)
+			Otherwise, a negative value indicating the error code shall be returned
+    \note       belongs to \ref porting_sec
+	\warning
+*/
+
+#define SL_PLATFORM_EXTERNAL_SPAWN
+
+
+#ifdef SL_PLATFORM_EXTERNAL_SPAWN
+#define sl_Spawn(pEntry,pValue,flags)     osi_Spawn(pEntry,pValue,flags)
+#endif
+
+/*!
+
+ Close the Doxygen group.
+ @}
+
+ */
+
+
+/*!
+ ******************************************************************************
+
+    \defgroup       porting_events      Event Handlers
+
+    This section includes the asynchronous event handlers routines
+
+    PORTING ACTION:
+        -Uncomment the required handler and define your routine as the value
+        of this handler
+
+    @{
+
+ ******************************************************************************
+ */
+
+/*!
+    \brief
+
+    \sa
+
+    \note       belongs to \ref porting_sec
+
+    \warning
+*/
+#define sl_GeneralEvtHdlr       SimpleLinkGeneralEventHandler
+
+
+/*!
+    \brief          An event handler for WLAN connection or disconnection indication
+                    This event handles async WLAN events.
+                    Possible events are:
+                    SL_WLAN_CONNECT_EVENT - indicates WLAN is connected
+                    SL_WLAN_DISCONNECT_EVENT - indicates WLAN is disconnected
+    \sa
+
+    \note           belongs to \ref porting_sec
+
+    \warning
+*/
+#define sl_WlanEvtHdlr          SimpleLinkWlanEventHandler
+
+/*!
+    \brief          An event handler for IP address asynchronous event. Usually accepted after new WLAN connection.
+                    This event handles networking events.
+                    Possible events are:
+                    SL_NETAPP_IPV4_ACQUIRED - IP address was acquired (DHCP or Static)
+
+    \sa
+
+    \note           belongs to \ref porting_sec
+
+    \warning
+*/
+
+#define sl_NetAppEvtHdlr        SimpleLinkNetAppEventHandler
+
+/*!
+    \brief          A callback for HTTP server events.
+                    Possible events are:
+                    SL_NETAPP_HTTPGETTOKENVALUE - NWP requests to get the value of a specific token
+					SL_NETAPP_HTTPPOSTTOKENVALUE - NWP post to the host a new value for a specific token
+
+	\param			pServerEvent - Contains the relevant event information (SL_NETAPP_HTTPGETTOKENVALUE or SL_NETAPP_HTTPPOSTTOKENVALUE)
+
+	\param			pServerResponse - Should be filled by the user with the relevant response information (i.e SL_NETAPP_HTTPSETTOKENVALUE as a response to SL_NETAPP_HTTPGETTOKENVALUE event)
+
+    \sa
+
+    \note           belongs to \ref porting_sec
+
+    \warning
+*/
+
+#define sl_HttpServerCallback   SimpleLinkHttpServerCallback
+
+/*!
+    \brief
+
+    \sa
+
+    \note           belongs to \ref porting_sec
+
+    \warning
+*/
+#define sl_SockEvtHdlr          SimpleLinkSockEventHandler
+
+
+
+/*!
+
+ Close the Doxygen group.
+ @}
+
+ */
+
+#endif /* __USER_H__ */
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_wlan.cpp
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_wlan.cpp	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,931 @@
+/*
+* wlan.c - CC31xx/CC32xx Host Driver Implementation
+*
+* Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+*
+*
+*  Redistribution and use in source and binary forms, with or without
+*  modification, are permitted provided that the following conditions
+*  are met:
+*
+*    Redistributions of source code must retain the above copyright
+*    notice, this list of conditions and the following disclaimer.
+*
+*    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.
+*
+*    Neither the name of Texas Instruments Incorporated nor the names of
+*    its contributors may be used to endorse or promote products derived
+*    from this software without specific prior written permission.
+*
+*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+*  "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 COPYRIGHT
+*  OWNER OR CONTRIBUTORS 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 files                                                             */
+/*****************************************************************************/
+#include "cc3100_simplelink.h"
+#include "cc3100_protocol.h"
+#include "cc3100_driver.h"
+
+#include "cc3100_wlan.h"
+#include "cc3100_wlan_rx_filters.h"
+
+/*****************************************************************************/
+/* Macro declarations                                                        */
+/*****************************************************************************/
+#define MAX_SSID_LEN           (32)
+#define MAX_KEY_LEN            (63)
+#define MAX_USER_LEN           (32)
+#define MAX_ANON_USER_LEN      (32)
+#define MAX_SMART_CONFIG_KEY   (16)
+
+namespace mbed_cc3100 {
+
+cc3100_wlan::cc3100_wlan(cc3100_driver &driver, cc3100_wlan_rx_filters  &wlan_filters)
+    : _driver(driver), _wlan_filters(wlan_filters)
+{
+
+}
+
+cc3100_wlan::~cc3100_wlan()
+{
+
+}
+
+/*****************************************************************************
+sl_WlanConnect
+*****************************************************************************/
+typedef struct {
+    _WlanConnectEapCommand_t    Args;
+    int8_t                        Strings[MAX_SSID_LEN + MAX_KEY_LEN + MAX_USER_LEN + MAX_ANON_USER_LEN];
+} _WlanConnectCmd_t;
+
+typedef union {
+    _WlanConnectCmd_t   Cmd;
+    _BasicResponse_t	Rsp;
+} _SlWlanConnectMsg_u;
+
+
+#if _SL_INCLUDE_FUNC(sl_WlanConnect)
+int16_t cc3100_wlan::sl_WlanConnect(const signed char*  pName, const int16_t NameLen, const uint8_t *pMacAddr, const SlSecParams_t* pSecParams , const SlSecParamsExt_t* pSecExtParams)
+{
+    _SlWlanConnectMsg_u    Msg = {0};
+    _SlCmdCtrl_t           CmdCtrl = {0};
+
+    CmdCtrl.TxDescLen = 0;/* init */
+    CmdCtrl.RxDescLen = sizeof(_BasicResponse_t);
+
+    /* verify SSID length */
+    VERIFY_PROTOCOL(NameLen <= MAX_SSID_LEN);
+    /* verify SSID is not NULL */
+    if( NULL == pName )
+    {
+       return SL_INVALPARAM;
+    }
+    
+    /* update SSID length */
+    Msg.Cmd.Args.Common.SsidLen = (uint8_t)NameLen;
+    /* Profile with no security */
+    /* Enterprise security profile */
+    if (NULL != pSecExtParams) {
+        /* Update command opcode */
+        CmdCtrl.Opcode = SL_OPCODE_WLAN_WLANCONNECTEAPCOMMAND;
+        CmdCtrl.TxDescLen += sizeof(_WlanConnectEapCommand_t);
+        /* copy SSID */
+        memcpy(EAP_SSID_STRING(&Msg), pName, NameLen);
+        CmdCtrl.TxDescLen += NameLen;
+        /* Copy password if supplied */
+        if ((NULL != pSecParams) && (pSecParams->KeyLen > 0)) {
+            /* update security type */
+            Msg.Cmd.Args.Common.SecType = pSecParams->Type;
+            /* verify key length */
+            if (pSecParams->KeyLen > MAX_KEY_LEN) {
+                return SL_INVALPARAM;
+            }
+            /* update key length */
+            Msg.Cmd.Args.Common.PasswordLen = pSecParams->KeyLen;
+            ARG_CHECK_PTR(pSecParams->Key);
+            /* copy key		 */
+            memcpy(EAP_PASSWORD_STRING(&Msg), pSecParams->Key, pSecParams->KeyLen);
+            CmdCtrl.TxDescLen += pSecParams->KeyLen;
+        } else {
+            Msg.Cmd.Args.Common.PasswordLen = 0;
+        }
+        ARG_CHECK_PTR(pSecExtParams);
+        /* Update Eap bitmask */
+        Msg.Cmd.Args.EapBitmask = pSecExtParams->EapMethod;
+        /* Update Certificate file ID index - currently not supported */
+        Msg.Cmd.Args.CertIndex = pSecExtParams->CertIndex;
+        /* verify user length */
+        if (pSecExtParams->UserLen > MAX_USER_LEN) {
+            return SL_INVALPARAM;
+        }
+        Msg.Cmd.Args.UserLen = pSecExtParams->UserLen;
+        /* copy user name (identity) */
+        if(pSecExtParams->UserLen > 0) {
+            memcpy(EAP_USER_STRING(&Msg), pSecExtParams->User, pSecExtParams->UserLen);
+            CmdCtrl.TxDescLen += pSecExtParams->UserLen;
+        }
+        /* verify Anonymous user length  */
+        if (pSecExtParams->AnonUserLen > MAX_ANON_USER_LEN) {
+            return SL_INVALPARAM;
+        }
+        Msg.Cmd.Args.AnonUserLen = pSecExtParams->AnonUserLen;
+        /* copy Anonymous user */
+        if(pSecExtParams->AnonUserLen > 0) {
+            memcpy(EAP_ANON_USER_STRING(&Msg), pSecExtParams->AnonUser, pSecExtParams->AnonUserLen);
+            CmdCtrl.TxDescLen += pSecExtParams->AnonUserLen;
+        }
+
+    }
+
+    /* Regular or open security profile */
+    else {
+        /* Update command opcode */
+        CmdCtrl.Opcode = SL_OPCODE_WLAN_WLANCONNECTCOMMAND;
+        CmdCtrl.TxDescLen += sizeof(_WlanConnectCommon_t);
+        /* copy SSID */
+        memcpy(SSID_STRING(&Msg), pName, NameLen);
+        CmdCtrl.TxDescLen += NameLen;
+        /* Copy password if supplied */
+        if( NULL != pSecParams ) {
+            /* update security type */
+            Msg.Cmd.Args.Common.SecType = pSecParams->Type;
+            /* verify key length is valid */
+            if (pSecParams->KeyLen > MAX_KEY_LEN) {
+                return SL_INVALPARAM;
+            }
+            /* update key length */
+            Msg.Cmd.Args.Common.PasswordLen = pSecParams->KeyLen;
+            CmdCtrl.TxDescLen += pSecParams->KeyLen;
+            /* copy key (could be no key in case of WPS pin) */
+            if( NULL != pSecParams->Key ) {
+                memcpy(PASSWORD_STRING(&Msg), pSecParams->Key, pSecParams->KeyLen);
+            }
+        }
+        /* Profile with no security */
+        else {
+            Msg.Cmd.Args.Common.PasswordLen = 0;
+            Msg.Cmd.Args.Common.SecType = SL_SEC_TYPE_OPEN;
+        }
+    }
+    /* If BSSID is not null, copy to buffer, otherwise set to 0 */
+    if(NULL != pMacAddr) {
+        memcpy(Msg.Cmd.Args.Common.Bssid, pMacAddr, sizeof(Msg.Cmd.Args.Common.Bssid));
+    } else {
+        _driver._SlDrvMemZero(Msg.Cmd.Args.Common.Bssid, sizeof(Msg.Cmd.Args.Common.Bssid));
+    }
+
+    VERIFY_RET_OK ( _driver._SlDrvCmdOp(&CmdCtrl, &Msg, NULL));
+    return (int16_t)Msg.Rsp.status;
+}
+#endif
+
+/*******************************************************************************/
+/*   sl_Disconnect  */
+/* ******************************************************************************/
+#if _SL_INCLUDE_FUNC(sl_WlanDisconnect)
+int16_t cc3100_wlan::sl_WlanDisconnect(void)
+{
+    return _driver._SlDrvBasicCmd(SL_OPCODE_WLAN_WLANDISCONNECTCOMMAND);
+}
+#endif
+
+/******************************************************************************/
+/*  sl_PolicySet  */
+/******************************************************************************/
+typedef union {
+    _WlanPoliciySetGet_t    Cmd;
+    _BasicResponse_t	    Rsp;
+} _SlPolicyMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_WlanPolicySet)
+const _SlCmdCtrl_t _SlPolicySetCmdCtrl = {
+    SL_OPCODE_WLAN_POLICYSETCOMMAND,
+    sizeof(_WlanPoliciySetGet_t),
+    sizeof(_BasicResponse_t)
+};
+
+int16_t cc3100_wlan::sl_WlanPolicySet(const uint8_t Type , const uint8_t Policy, uint8_t *pVal, const uint8_t ValLen)
+{
+
+    _SlPolicyMsg_u         Msg;
+    _SlCmdExt_t            CmdExt;
+
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.TxPayloadLen = ValLen;
+    CmdExt.pTxPayload = (uint8_t *)pVal;
+
+    Msg.Cmd.PolicyType        = Type;
+    Msg.Cmd.PolicyOption      = Policy;
+    Msg.Cmd.PolicyOptionLen   = ValLen;
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlPolicySetCmdCtrl, &Msg, &CmdExt));
+
+    return (int16_t)Msg.Rsp.status;
+}
+#endif
+
+
+/******************************************************************************/
+/*  sl_PolicyGet  */
+/******************************************************************************/
+typedef union {
+    _WlanPoliciySetGet_t	    Cmd;
+    _WlanPoliciySetGet_t	    Rsp;
+} _SlPolicyGetMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_WlanPolicyGet)
+const _SlCmdCtrl_t _SlPolicyGetCmdCtrl = {
+    SL_OPCODE_WLAN_POLICYGETCOMMAND,
+    sizeof(_WlanPoliciySetGet_t),
+    sizeof(_WlanPoliciySetGet_t)
+};
+
+int16_t cc3100_wlan::sl_WlanPolicyGet(const uint8_t Type , uint8_t Policy,uint8_t *pVal,uint8_t *pValLen)
+{
+    _SlPolicyGetMsg_u      Msg;
+    _SlCmdExt_t            CmdExt;
+
+    if (*pValLen == 0) {
+        return SL_EZEROLEN;
+    }
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.RxPayloadLen = *pValLen;
+    CmdExt.pRxPayload = pVal;
+
+    Msg.Cmd.PolicyType = Type;
+    Msg.Cmd.PolicyOption = Policy;
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlPolicyGetCmdCtrl, &Msg, &CmdExt));
+
+
+    if (CmdExt.RxPayloadLen < CmdExt.ActualRxPayloadLen) {
+        *pValLen = Msg.Rsp.PolicyOptionLen;
+        return SL_ESMALLBUF;
+    } else {
+        /*  no pointer valus, fill the results into int8_t */
+        *pValLen = (uint8_t)CmdExt.ActualRxPayloadLen;
+        if( 0 == CmdExt.ActualRxPayloadLen ) {
+            *pValLen = 1;
+            pVal[0] = Msg.Rsp.PolicyOption;
+        }
+    }
+    return (int16_t)SL_OS_RET_CODE_OK;
+}
+#endif
+
+
+/*******************************************************************************/
+/*  sl_ProfileAdd  */
+/*******************************************************************************/
+typedef struct {
+    _WlanAddGetEapProfile_t	Args;
+    int8_t                    Strings[MAX_SSID_LEN + MAX_KEY_LEN + MAX_USER_LEN + MAX_ANON_USER_LEN];
+} _SlProfileParams_t;
+
+typedef union {
+    _SlProfileParams_t	    Cmd;
+    _BasicResponse_t	    Rsp;
+} _SlProfileAddMsg_u;
+
+
+
+#if _SL_INCLUDE_FUNC(sl_WlanProfileAdd)
+int16_t cc3100_wlan::sl_WlanProfileAdd(const int8_t*  pName, 
+                                       const int16_t NameLen, 
+                                       const uint8_t *pMacAddr, 
+                                       const SlSecParams_t* pSecParams , 
+                                       const SlSecParamsExt_t* pSecExtParams, 
+                                       const uint32_t  Priority, 
+                                       const uint32_t  Options)
+{
+    _SlProfileAddMsg_u      Msg;
+    _SlCmdCtrl_t           CmdCtrl = {0};
+    CmdCtrl.TxDescLen = 0;/* init */
+    CmdCtrl.RxDescLen = sizeof(_BasicResponse_t);
+
+    /* update priority */
+    Msg.Cmd.Args.Common.Priority = (uint8_t)Priority;
+    /* verify SSID is not NULL */
+    if( NULL == pName )
+    {
+       return SL_INVALPARAM;
+    }
+    
+    /* verify SSID length */
+    VERIFY_PROTOCOL(NameLen <= MAX_SSID_LEN);
+    /* update SSID length */
+    Msg.Cmd.Args.Common.SsidLen = (uint8_t)NameLen;
+
+
+    /* Enterprise security profile */
+    if  (NULL != pSecExtParams) {
+        /* Update command opcode */
+        CmdCtrl.Opcode = SL_OPCODE_WLAN_EAP_PROFILEADDCOMMAND;
+        CmdCtrl.TxDescLen += sizeof(_WlanAddGetEapProfile_t);
+
+        /* copy SSID */
+        memcpy(EAP_PROFILE_SSID_STRING(&Msg), pName, NameLen);
+        CmdCtrl.TxDescLen += NameLen;
+
+        /* Copy password if supplied */
+        if ((NULL != pSecParams) && (pSecParams->KeyLen > 0)) {
+            /* update security type */
+            Msg.Cmd.Args.Common.SecType = pSecParams->Type;
+
+            if( SL_SEC_TYPE_WEP == Msg.Cmd.Args.Common.SecType ) {
+                Msg.Cmd.Args.Common.WepKeyId = 0;
+            }
+
+            /* verify key length */
+            if (pSecParams->KeyLen > MAX_KEY_LEN) {
+                return SL_INVALPARAM;
+            }
+            VERIFY_PROTOCOL(pSecParams->KeyLen <= MAX_KEY_LEN);
+            /* update key length */
+            Msg.Cmd.Args.Common.PasswordLen = pSecParams->KeyLen;
+            CmdCtrl.TxDescLen += pSecParams->KeyLen;
+            ARG_CHECK_PTR(pSecParams->Key);
+            /* copy key  */
+            memcpy(EAP_PROFILE_PASSWORD_STRING(&Msg), pSecParams->Key, pSecParams->KeyLen);
+        } else {
+            Msg.Cmd.Args.Common.PasswordLen = 0;
+        }
+
+        ARG_CHECK_PTR(pSecExtParams);
+        /* Update Eap bitmask */
+        Msg.Cmd.Args.EapBitmask = pSecExtParams->EapMethod;
+        /* Update Certificate file ID index - currently not supported */
+        Msg.Cmd.Args.CertIndex = pSecExtParams->CertIndex;
+        /* verify user length */
+        if (pSecExtParams->UserLen > MAX_USER_LEN) {
+            return SL_INVALPARAM;
+        }
+        Msg.Cmd.Args.UserLen = pSecExtParams->UserLen;
+        /* copy user name (identity) */
+        if(pSecExtParams->UserLen > 0) {
+            memcpy(EAP_PROFILE_USER_STRING(&Msg), pSecExtParams->User, pSecExtParams->UserLen);
+            CmdCtrl.TxDescLen += pSecExtParams->UserLen;
+        }
+
+        /* verify Anonymous user length (for tunneled) */
+        if (pSecExtParams->AnonUserLen > MAX_ANON_USER_LEN) {
+            return SL_INVALPARAM;
+        }
+        Msg.Cmd.Args.AnonUserLen = pSecExtParams->AnonUserLen;
+
+        /* copy Anonymous user */
+        if(pSecExtParams->AnonUserLen > 0) {
+            memcpy(EAP_PROFILE_ANON_USER_STRING(&Msg), pSecExtParams->AnonUser, pSecExtParams->AnonUserLen);
+            CmdCtrl.TxDescLen += pSecExtParams->AnonUserLen;
+        }
+
+    }
+    /* Regular or open security profile */
+    else {
+        /* Update command opcode */
+        CmdCtrl.Opcode = SL_OPCODE_WLAN_PROFILEADDCOMMAND;
+        /* update commnad length */
+        CmdCtrl.TxDescLen += sizeof(_WlanAddGetProfile_t);
+
+        if (NULL != pName) {
+            /* copy SSID */
+            memcpy(PROFILE_SSID_STRING(&Msg), pName, NameLen);
+            CmdCtrl.TxDescLen += NameLen;
+        }
+
+        /* Copy password if supplied */
+        if( NULL != pSecParams ) {
+            /* update security type */
+            Msg.Cmd.Args.Common.SecType = pSecParams->Type;
+
+            if( SL_SEC_TYPE_WEP == Msg.Cmd.Args.Common.SecType ) {
+                Msg.Cmd.Args.Common.WepKeyId = 0;
+            }
+
+            /* verify key length */
+            if (pSecParams->KeyLen > MAX_KEY_LEN) {
+                return SL_INVALPARAM;
+            }
+            /* update key length */
+            Msg.Cmd.Args.Common.PasswordLen = pSecParams->KeyLen;
+            CmdCtrl.TxDescLen += pSecParams->KeyLen;
+            /* copy key (could be no key in case of WPS pin) */
+            if( NULL != pSecParams->Key ) {
+                memcpy(PROFILE_PASSWORD_STRING(&Msg), pSecParams->Key, pSecParams->KeyLen);
+            }
+        } else {
+            Msg.Cmd.Args.Common.SecType = SL_SEC_TYPE_OPEN;
+            Msg.Cmd.Args.Common.PasswordLen = 0;
+        }
+
+    }
+
+
+    /* If BSSID is not null, copy to buffer, otherwise set to 0  */
+    if(NULL != pMacAddr) {
+        memcpy(Msg.Cmd.Args.Common.Bssid, pMacAddr, sizeof(Msg.Cmd.Args.Common.Bssid));
+    } else {
+        _driver._SlDrvMemZero(Msg.Cmd.Args.Common.Bssid, sizeof(Msg.Cmd.Args.Common.Bssid));
+    }
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp(&CmdCtrl, &Msg, NULL));
+
+    return (int16_t)Msg.Rsp.status;
+}
+#endif
+
+/*******************************************************************************/
+/*   sl_ProfileGet */
+/*******************************************************************************/
+typedef union {
+    _WlanProfileDelGetCommand_t Cmd;
+    _SlProfileParams_t	        Rsp;
+} _SlProfileGetMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_WlanProfileGet)
+const _SlCmdCtrl_t _SlProfileGetCmdCtrl = {
+    SL_OPCODE_WLAN_PROFILEGETCOMMAND,
+    sizeof(_WlanProfileDelGetCommand_t),
+    sizeof(_SlProfileParams_t)
+};
+
+int16_t cc3100_wlan::sl_WlanProfileGet(const int16_t Index,int8_t*  pName, int16_t *pNameLen, uint8_t *pMacAddr, SlSecParams_t* pSecParams, SlGetSecParamsExt_t* pEntParams, uint32_t *pPriority)
+{
+    _SlProfileGetMsg_u      Msg;
+    Msg.Cmd.index = (uint8_t)Index;
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlProfileGetCmdCtrl, &Msg, NULL));
+
+    pSecParams->Type = Msg.Rsp.Args.Common.SecType;
+    /* since password is not transferred in getprofile, password length should always be zero */
+    pSecParams->KeyLen = Msg.Rsp.Args.Common.PasswordLen;
+    if (NULL != pEntParams) {
+        pEntParams->UserLen = Msg.Rsp.Args.UserLen;
+        /* copy user name */
+        if (pEntParams->UserLen > 0) {
+            memcpy(pEntParams->User, EAP_PROFILE_USER_STRING(&Msg), pEntParams->UserLen);
+        }
+        pEntParams->AnonUserLen = Msg.Rsp.Args.AnonUserLen;
+        /* copy anonymous user name */
+        if (pEntParams->AnonUserLen > 0) {
+            memcpy(pEntParams->AnonUser, EAP_PROFILE_ANON_USER_STRING(&Msg), pEntParams->AnonUserLen);
+        }
+    }
+
+    *pNameLen  = Msg.Rsp.Args.Common.SsidLen;
+    *pPriority = Msg.Rsp.Args.Common.Priority;
+
+    if (NULL != Msg.Rsp.Args.Common.Bssid) {
+        memcpy(pMacAddr, Msg.Rsp.Args.Common.Bssid, sizeof(Msg.Rsp.Args.Common.Bssid));
+    }
+
+    memcpy(pName, EAP_PROFILE_SSID_STRING(&Msg), *pNameLen);
+
+    return (int16_t)Msg.Rsp.Args.Common.SecType;
+
+}
+#endif
+
+/*******************************************************************************/
+/*   sl_ProfileDel  */
+/*******************************************************************************/
+typedef union {
+    _WlanProfileDelGetCommand_t	    Cmd;
+    _BasicResponse_t	            Rsp;
+} _SlProfileDelMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_WlanProfileDel)
+const _SlCmdCtrl_t _SlProfileDelCmdCtrl = {
+    SL_OPCODE_WLAN_PROFILEDELCOMMAND,
+    sizeof(_WlanProfileDelGetCommand_t),
+    sizeof(_BasicResponse_t)
+};
+
+int16_t cc3100_wlan::sl_WlanProfileDel(const int16_t Index)
+{
+    _SlProfileDelMsg_u Msg;
+
+    Msg.Cmd.index = (uint8_t)Index;
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlProfileDelCmdCtrl, &Msg, NULL));
+
+    return (int16_t)Msg.Rsp.status;
+}
+#endif
+
+/******************************************************************************/
+/*  sl_WlanGetNetworkList  */
+/******************************************************************************/
+typedef union {
+    _WlanGetNetworkListCommand_t    Cmd;
+    _WlanGetNetworkListResponse_t   Rsp;
+} _SlWlanGetNetworkListMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_WlanGetNetworkList)
+const _SlCmdCtrl_t _SlWlanGetNetworkListCtrl = {
+    SL_OPCODE_WLAN_SCANRESULTSGETCOMMAND,
+    sizeof(_WlanGetNetworkListCommand_t),
+    sizeof(_WlanGetNetworkListResponse_t)
+};
+
+int16_t cc3100_wlan::sl_WlanGetNetworkList(const uint8_t Index, const uint8_t Count, Sl_WlanNetworkEntry_t *pEntries)
+{
+    int16_t retVal = 0;
+    _SlWlanGetNetworkListMsg_u Msg;
+    _SlCmdExt_t    CmdExt;
+
+    if (Count == 0) {
+        return SL_EZEROLEN;
+    }
+    
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.RxPayloadLen = sizeof(Sl_WlanNetworkEntry_t)*(Count);
+    CmdExt.pRxPayload = (uint8_t *)pEntries; 
+
+    Msg.Cmd.index = Index;
+    Msg.Cmd.count = Count;
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlWlanGetNetworkListCtrl, &Msg, &CmdExt));
+    retVal = Msg.Rsp.status;
+
+    return (int16_t)retVal;
+}
+#endif
+
+/*******************************************************************************/
+/*             sl_WlanRxStatStart                                              */
+/*******************************************************************************/
+#if _SL_INCLUDE_FUNC(sl_WlanRxStatStart)
+int16_t cc3100_wlan::sl_WlanRxStatStart(void)
+{
+    return _driver._SlDrvBasicCmd(SL_OPCODE_WLAN_STARTRXSTATCOMMAND);
+}
+#endif
+
+#if _SL_INCLUDE_FUNC(sl_WlanRxStatStop)
+int16_t cc3100_wlan::sl_WlanRxStatStop(void)
+{
+    return _driver._SlDrvBasicCmd(SL_OPCODE_WLAN_STOPRXSTATCOMMAND);
+}
+#endif
+
+#if _SL_INCLUDE_FUNC(sl_WlanRxStatGet)
+int16_t cc3100_wlan::sl_WlanRxStatGet(SlGetRxStatResponse_t *pRxStat, const uint32_t Flags)
+{
+    _SlCmdCtrl_t            CmdCtrl = {SL_OPCODE_WLAN_GETRXSTATCOMMAND, 0, sizeof(SlGetRxStatResponse_t)};
+    _driver._SlDrvMemZero(pRxStat, sizeof(SlGetRxStatResponse_t));
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&CmdCtrl, pRxStat, NULL));
+
+    return 0;
+}
+#endif
+
+
+
+/******************************************************************************/
+/*   sl_WlanSmartConfigStop                                                   */
+/******************************************************************************/
+#if _SL_INCLUDE_FUNC(sl_WlanSmartConfigStop)
+int16_t cc3100_wlan::sl_WlanSmartConfigStop(void)
+{
+    return _driver._SlDrvBasicCmd(SL_OPCODE_WLAN_SMART_CONFIG_STOP_COMMAND);
+}
+#endif
+
+
+/******************************************************************************/
+/*   sl_WlanSmartConfigStart                                                  */
+/******************************************************************************/
+
+
+typedef struct {
+    _WlanSmartConfigStartCommand_t	Args;
+    int8_t                            Strings[3 * MAX_SMART_CONFIG_KEY]; /* public key + groupId1 key + groupId2 key */
+} _SlSmartConfigStart_t;
+
+typedef union {
+    _SlSmartConfigStart_t	    Cmd;
+    _BasicResponse_t	        Rsp;
+} _SlSmartConfigStartMsg_u;
+
+const _SlCmdCtrl_t _SlSmartConfigStartCmdCtrl = {
+    SL_OPCODE_WLAN_SMART_CONFIG_START_COMMAND,
+    sizeof(_SlSmartConfigStart_t),
+    sizeof(_BasicResponse_t)
+};
+
+#if _SL_INCLUDE_FUNC(sl_WlanSmartConfigStart)
+int16_t cc3100_wlan::sl_WlanSmartConfigStart( const uint32_t    groupIdBitmask,
+        const uint8_t    cipher,
+        const uint8_t    publicKeyLen,
+        const uint8_t    group1KeyLen,
+        const uint8_t    group2KeyLen,
+        const uint8_t*    pPublicKey,
+        const uint8_t*    pGroup1Key,
+        const uint8_t*    pGroup2Key)
+{
+    _SlSmartConfigStartMsg_u      Msg;
+
+    Msg.Cmd.Args.groupIdBitmask = (uint8_t)groupIdBitmask;
+    Msg.Cmd.Args.cipher         = (uint8_t)cipher;
+    Msg.Cmd.Args.publicKeyLen   = (uint8_t)publicKeyLen;
+    Msg.Cmd.Args.group1KeyLen   = (uint8_t)group1KeyLen;
+    Msg.Cmd.Args.group2KeyLen   = (uint8_t)group2KeyLen;
+
+    /* copy keys (if exist) after command (one after another) */
+    memcpy(SMART_CONFIG_START_PUBLIC_KEY_STRING(&Msg), pPublicKey, publicKeyLen);
+    memcpy(SMART_CONFIG_START_GROUP1_KEY_STRING(&Msg), pGroup1Key, group1KeyLen);
+    memcpy(SMART_CONFIG_START_GROUP2_KEY_STRING(&Msg), pGroup2Key, group2KeyLen);
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlSmartConfigStartCmdCtrl , &Msg, NULL));
+
+    return (int16_t)Msg.Rsp.status;
+
+
+}
+#endif
+
+/*******************************************************************************/
+/*   sl_WlanSetMode  */
+/*******************************************************************************/
+typedef union {
+    _WlanSetMode_t		    Cmd;
+    _BasicResponse_t	    Rsp;
+} _SlwlanSetModeMsg_u;
+
+const _SlCmdCtrl_t _SlWlanSetModeCmdCtrl = {
+    SL_OPCODE_WLAN_SET_MODE,
+    sizeof(_WlanSetMode_t),
+    sizeof(_BasicResponse_t)
+};
+
+/* possible values are:
+WLAN_SET_STA_MODE   =   1
+WLAN_SET_AP_MODE    =   2
+WLAN_SET_P2P_MODE   =   3  */
+
+#if _SL_INCLUDE_FUNC(sl_WlanSetMode)
+int16_t cc3100_wlan::sl_WlanSetMode(const uint8_t mode)
+{
+    _SlwlanSetModeMsg_u      Msg;
+
+    Msg.Cmd.mode  = mode;
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlWlanSetModeCmdCtrl , &Msg, NULL));
+
+    return (int16_t)Msg.Rsp.status;
+
+}
+#endif
+
+/*******************************************************************************/
+/*   sl_WlanSet  */
+/* ******************************************************************************/
+typedef union {
+    _WlanCfgSetGet_t	    Cmd;
+    _BasicResponse_t	    Rsp;
+} _SlWlanCfgSetMsg_u;
+
+#if _SL_INCLUDE_FUNC(sl_WlanSet)
+const _SlCmdCtrl_t _SlWlanCfgSetCmdCtrl = {
+    SL_OPCODE_WLAN_CFG_SET,
+    sizeof(_WlanCfgSetGet_t),
+    sizeof(_BasicResponse_t)
+};
+
+int16_t cc3100_wlan::sl_WlanSet(const uint16_t ConfigId, const uint16_t ConfigOpt, const uint16_t ConfigLen, const uint8_t *pValues)
+{
+    _SlWlanCfgSetMsg_u         Msg;
+    _SlCmdExt_t                CmdExt;
+
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.TxPayloadLen = (ConfigLen+3) & (~3);
+    CmdExt.pTxPayload = (uint8_t *)pValues;
+
+
+    Msg.Cmd.ConfigId    = ConfigId;
+    Msg.Cmd.ConfigLen   = ConfigLen;
+    Msg.Cmd.ConfigOpt   = ConfigOpt;
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlWlanCfgSetCmdCtrl, &Msg, &CmdExt));
+
+    return (int16_t)Msg.Rsp.status;
+}
+#endif
+
+
+/******************************************************************************/
+/*  sl_WlanGet  */
+/******************************************************************************/
+typedef union {
+    _WlanCfgSetGet_t	    Cmd;
+    _WlanCfgSetGet_t	    Rsp;
+} _SlWlanCfgMsgGet_u;
+
+#if _SL_INCLUDE_FUNC(sl_WlanGet)
+const _SlCmdCtrl_t _SlWlanCfgGetCmdCtrl = {
+    SL_OPCODE_WLAN_CFG_GET,
+    sizeof(_WlanCfgSetGet_t),
+    sizeof(_WlanCfgSetGet_t)
+};
+
+int16_t cc3100_wlan::sl_WlanGet(const uint16_t ConfigId, uint16_t *pConfigOpt,uint16_t *pConfigLen, uint8_t *pValues)
+{
+    _SlWlanCfgMsgGet_u        Msg;
+    _SlCmdExt_t               CmdExt;
+
+    if (*pConfigLen == 0) {
+        return SL_EZEROLEN;
+    }
+    
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.RxPayloadLen = *pConfigLen;
+    CmdExt.pRxPayload = (uint8_t *)pValues;
+
+    Msg.Cmd.ConfigId    = ConfigId;
+    if( pConfigOpt ) {
+        Msg.Cmd.ConfigOpt   = (uint16_t)*pConfigOpt;
+    }
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlWlanCfgGetCmdCtrl, &Msg, &CmdExt));
+
+    if( pConfigOpt ) {
+        *pConfigOpt = (uint8_t)Msg.Rsp.ConfigOpt;
+    }
+    if (CmdExt.RxPayloadLen < CmdExt.ActualRxPayloadLen) {
+        *pConfigLen = (uint8_t)CmdExt.RxPayloadLen;
+        return SL_ESMALLBUF;
+    } else {
+        *pConfigLen = (uint8_t)CmdExt.ActualRxPayloadLen;
+    }
+
+
+    return (int16_t)Msg.Rsp.Status;
+}
+#endif
+
+cc3100_wlan_rx_filters::cc3100_wlan_rx_filters(cc3100_driver &driver)
+    : _driver(driver)
+{
+
+}
+
+cc3100_wlan_rx_filters::~cc3100_wlan_rx_filters()
+{
+
+}
+
+/******************************************************************************/
+/*     RX filters message command response structures  */
+/******************************************************************************/
+
+/* Set command */
+typedef union {
+    _WlanRxFilterAddCommand_t	          Cmd;
+    _WlanRxFilterAddCommandReponse_t      Rsp;
+} _SlrxFilterAddMsg_u;
+
+/* Set command */
+typedef union _SlRxFilterSetMsg_u {
+    _WlanRxFilterSetCommand_t	            Cmd;
+    _WlanRxFilterSetCommandReponse_t        Rsp;
+} _SlRxFilterSetMsg_u;
+
+/* Get command */
+typedef union _SlRxFilterGetMsg_u {
+    _WlanRxFilterGetCommand_t	            Cmd;
+    _WlanRxFilterGetCommandReponse_t        Rsp;
+} _SlRxFilterGetMsg_u;
+
+
+#if _SL_INCLUDE_FUNC(sl_WlanRxFilterAdd)
+
+const _SlCmdCtrl_t _SlRxFilterAddtCmdCtrl =
+{
+    SL_OPCODE_WLAN_WLANRXFILTERADDCOMMAND,
+    sizeof(_WlanRxFilterAddCommand_t),
+    sizeof(_WlanRxFilterAddCommandReponse_t)
+};
+
+
+/*******************************************************************************/
+/*     RX filters  */
+/*******************************************************************************/
+SlrxFilterID_t cc3100_wlan_rx_filters::sl_WlanRxFilterAdd(	SlrxFilterRuleType_t RuleType,
+        SlrxFilterFlags_t 					FilterFlags,
+        const SlrxFilterRule_t* const 		Rule,
+        const SlrxFilterTrigger_t* const 	Trigger,
+        const SlrxFilterAction_t* const 	Action,
+        SlrxFilterID_t*                     pFilterId)
+{
+
+
+    _SlrxFilterAddMsg_u Msg;
+    Msg.Cmd.RuleType = RuleType;
+    /* filterId is zero */
+    Msg.Cmd.FilterId = 0;
+    Msg.Cmd.FilterFlags = FilterFlags;
+    memcpy( &(Msg.Cmd.Rule), Rule, sizeof(SlrxFilterRule_t) );
+    memcpy( &(Msg.Cmd.Trigger), Trigger, sizeof(SlrxFilterTrigger_t) );
+    memcpy( &(Msg.Cmd.Action), Action, sizeof(SlrxFilterAction_t) );
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlRxFilterAddtCmdCtrl, &Msg, NULL) );
+    *pFilterId = Msg.Rsp.FilterId;
+    return (int16_t)Msg.Rsp.Status;
+
+}
+#endif
+
+
+
+/*******************************************************************************/
+/*     RX filters    */
+/*******************************************************************************/
+#if _SL_INCLUDE_FUNC(sl_WlanRxFilterSet)
+const _SlCmdCtrl_t _SlRxFilterSetCmdCtrl =
+{
+    SL_OPCODE_WLAN_WLANRXFILTERSETCOMMAND,
+    sizeof(_WlanRxFilterSetCommand_t),
+    sizeof(_WlanRxFilterSetCommandReponse_t)
+};
+
+int16_t cc3100_wlan_rx_filters::sl_WlanRxFilterSet(const SLrxFilterOperation_t RxFilterOperation,
+        const uint8_t*  const pInputBuffer,
+        uint16_t InputbufferLength)
+{
+    _SlRxFilterSetMsg_u   Msg;
+    _SlCmdExt_t           CmdExt;
+
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.TxPayloadLen = InputbufferLength;
+    CmdExt.pTxPayload   = (uint8_t *)pInputBuffer;
+
+    Msg.Cmd.RxFilterOperation = RxFilterOperation;
+    Msg.Cmd.InputBufferLength = InputbufferLength;
+
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlRxFilterSetCmdCtrl, &Msg, &CmdExt) );
+
+
+    return (int16_t)Msg.Rsp.Status;
+}
+#endif
+
+/******************************************************************************/
+/*     RX filters  */
+/******************************************************************************/
+#if _SL_INCLUDE_FUNC(sl_WlanRxFilterGet)
+const _SlCmdCtrl_t _SlRxFilterGetCmdCtrl =
+{
+    SL_OPCODE_WLAN_WLANRXFILTERGETCOMMAND,
+    sizeof(_WlanRxFilterGetCommand_t),
+    sizeof(_WlanRxFilterGetCommandReponse_t)
+};
+
+int16_t cc3100_wlan_rx_filters::sl_WlanRxFilterGet(const SLrxFilterOperation_t RxFilterOperation,
+        uint8_t*  pOutputBuffer,
+        uint16_t OutputbufferLength)
+{
+    _SlRxFilterGetMsg_u   Msg;
+    _SlCmdExt_t           CmdExt;
+
+    if (OutputbufferLength == 0) {
+        return SL_EZEROLEN;
+    }
+    
+    _driver._SlDrvResetCmdExt(&CmdExt);
+    CmdExt.RxPayloadLen = OutputbufferLength;
+    CmdExt.pRxPayload   = (uint8_t *)pOutputBuffer;
+
+    Msg.Cmd.RxFilterOperation = RxFilterOperation;
+    Msg.Cmd.OutputBufferLength = OutputbufferLength;
+
+
+    VERIFY_RET_OK(_driver._SlDrvCmdOp((_SlCmdCtrl_t *)&_SlRxFilterGetCmdCtrl, &Msg, &CmdExt) );
+
+    if (CmdExt.RxPayloadLen < CmdExt.ActualRxPayloadLen) {
+        return SL_ESMALLBUF;
+    }
+
+    return (int16_t)Msg.Rsp.Status;
+}
+#endif
+
+}//namespace mbed_cc3100
+
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_wlan.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_wlan.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,1308 @@
+/*
+ * wlan.h - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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 files                                                             */
+/*****************************************************************************/
+#include "cc3100_simplelink.h"
+
+#ifndef WLAN_H_
+#define    WLAN_H_
+
+namespace mbed_cc3100 {
+
+/*****************************************************************************/
+/* Macro declarations                                                        */
+/*****************************************************************************/
+
+/*!
+
+    \addtogroup wlan
+    @{
+
+*/
+
+const uint8_t SL_BSSID_LENGTH                                                                             =    (6);
+const uint8_t MAXIMAL_SSID_LENGTH                                                                         =    (32);
+
+const uint8_t NUM_OF_RATE_INDEXES                                                                         =    (20);
+const uint8_t SIZE_OF_RSSI_HISTOGRAM                                                                      =    (6);
+
+/* WLAN Disconnect Reason Codes */
+const uint8_t  SL_DISCONNECT_RESERVED_0                                                                   =    (0);
+const uint8_t  SL_DISCONNECT_UNSPECIFIED_REASON                                                           =    (1);
+const uint8_t  SL_PREVIOUS_AUTHENTICATION_NO_LONGER_VALID                                                 =    (2);
+const uint8_t  SL_DEAUTHENTICATED_BECAUSE_SENDING_STATION_IS_LEAVING                                      =    (3);
+const uint8_t  SL_DISASSOCIATED_DUE_TO_INACTIVITY                                                         =    (4);
+const uint8_t  SL_DISASSOCIATED_BECAUSE_AP_IS_UNABLE_TO_HANDLE_ALL_CURRENTLY_ASSOCIATED_STATIONS          =    (5);
+const uint8_t  SL_CLASS_2_FRAME_RECEIVED_FROM_NONAUTHENTICATED_STATION                                    =    (6);
+const uint8_t  SL_CLASS_3_FRAME_RECEIVED_FROM_NONASSOCIATED_STATION                                       =    (7);
+const uint8_t  SL_DISASSOCIATED_BECAUSE_SENDING_STATION_IS_LEAVING_BSS                                    =    (8);
+const uint8_t  SL_STATION_REQUESTING_ASSOCIATION_IS_NOT_AUTHENTICATED_WITH_RESPONDING_STATION             =    (9);
+const uint8_t  SL_DISASSOCIATED_BECAUSE_THE_INFORMATION_IN_THE_POWER_CAPABILITY_ELEMENT_IS_UNACCEPTABLE   =    (10);
+const uint8_t  SL_DISASSOCIATED_BECAUSE_THE_INFORMATION_IN_THE_SUPPORTED_CHANNELS_ELEMENT_IS_UNACCEPTABLE =    (11);
+const uint8_t  SL_DISCONNECT_RESERVED_1                                                                   =    (12);
+const uint8_t  SL_INVALID_INFORMATION_ELEMENT                                                             =    (13);
+const uint8_t  SL_MESSAGE_INTEGRITY_CODE_MIC_FAILURE                                                      =    (14);
+const uint8_t  SL_FOUR_WAY_HANDSHAKE_TIMEOUT                                                              =    (15);
+const uint8_t  SL_GROUP_KEY_HANDSHAKE_TIMEOUT                                                             =    (16);
+const uint8_t  SL_RE_ASSOCIATION_REQUEST_PROBE_RESPONSE_BEACON_FRAME                                      =    (17);
+const uint8_t  SL_INVALID_GROUP_CIPHER                                                                    =    (18);
+const uint8_t  SL_INVALID_PAIRWISE_CIPHER                                                                 =    (19);
+const uint8_t  SL_INVALID_AKMP                                                                            =    (20);
+const uint8_t  SL_UNSUPPORTED_RSN_INFORMATION_ELEMENT_VERSION                                             =    (21);
+const uint8_t  SL_INVALID_RSN_INFORMATION_ELEMENT_CAPABILITIES                                            =    (22);
+const uint8_t  SL_IEEE_802_1X_AUTHENTICATION_FAILED                                                       =    (23);
+const uint8_t  SL_CIPHER_SUITE_REJECTED_BECAUSE_OF_THE_SECURITY_POLICY                                    =    (24);
+const uint8_t  SL_DISCONNECT_RESERVED_2                                                                   =    (25);
+const uint8_t  SL_DISCONNECT_RESERVED_3                                                                   =    (26);
+const uint8_t  SL_DISCONNECT_RESERVED_4                                                                   =    (27);
+const uint8_t  SL_DISCONNECT_RESERVED_5                                                                   =    (28);
+const uint8_t  SL_DISCONNECT_RESERVED_6                                                                   =    (29);
+const uint8_t  SL_DISCONNECT_RESERVED_7                                                                   =    (30);
+const uint8_t  SL_DISCONNECT_RESERVED_8                                                                   =    (31);
+const uint8_t  SL_USER_INITIATED_DISCONNECTION                                                            =    (200);
+
+/* Wlan error codes */
+const int8_t  SL_ERROR_KEY_ERROR                                                                          =   (-3);
+const int8_t  SL_ERROR_INVALID_ROLE                                                                       =   (-71);
+const int8_t  SL_ERROR_INVALID_SECURITY_TYPE                                                              =   (-84);
+const int8_t  SL_ERROR_PASSPHRASE_TOO_LONG                                                                =   (-85);
+const int8_t  SL_ERROR_WPS_NO_PIN_OR_WRONG_PIN_LEN                                                        =   (-87);
+const int8_t  SL_ERROR_EAP_WRONG_METHOD                                                                   =   (-88);
+const int8_t  SL_ERROR_PASSWORD_ERROR                                                                     =   (-89);
+const int8_t  SL_ERROR_EAP_ANONYMOUS_LEN_ERROR                                                            =   (-90);
+const int8_t  SL_ERROR_SSID_LEN_ERROR                                                                     =   (-91);
+const int8_t  SL_ERROR_USER_ID_LEN_ERROR                                                                  =   (-92);
+const int8_t  SL_ERROR_ILLEGAL_WEP_KEY_INDEX                                                              =   (-95);
+const int8_t  SL_ERROR_INVALID_DWELL_TIME_VALUES                                                          =   (-96);
+const int8_t  SL_ERROR_INVALID_POLICY_TYPE                                                                =   (-97);
+const int8_t  SL_ERROR_PM_POLICY_INVALID_OPTION                                                           =   (-98);
+const int8_t  SL_ERROR_PM_POLICY_INVALID_PARAMS                                                           =   (-99);
+const int16_t  SL_ERROR_WIFI_ALREADY_DISCONNECTED                                                         =   (-129);
+const int8_t  SL_ERROR_WIFI_NOT_CONNECTED                                                                 =   (-59);
+
+
+
+const uint8_t SL_SEC_TYPE_OPEN                                                                            =    (0);
+const uint8_t SL_SEC_TYPE_WEP                                                                             =    (1);
+const uint8_t SL_SEC_TYPE_WPA                                                                             =    (2); /* deprecated */
+const uint8_t SL_SEC_TYPE_WPA_WPA2                                                                        =    (2);
+const uint8_t SL_SEC_TYPE_WPS_PBC                                                                         =    (3);
+const uint8_t SL_SEC_TYPE_WPS_PIN                                                                         =    (4);
+const uint8_t SL_SEC_TYPE_WPA_ENT                                                                         =    (5);
+const uint8_t SL_SEC_TYPE_P2P_PBC                                                                         =    (6);
+const uint8_t SL_SEC_TYPE_P2P_PIN_KEYPAD                                                                  =    (7);
+const uint8_t SL_SEC_TYPE_P2P_PIN_DISPLAY                                                                 =    (8);
+const uint8_t SL_SEC_TYPE_P2P_PIN_AUTO                                                                    =    (9); /* NOT Supported yet */
+
+
+
+const uint8_t SL_SCAN_SEC_TYPE_OPEN                                                                        =   (0);
+const uint8_t SL_SCAN_SEC_TYPE_WEP                                                                         =   (1);
+const uint8_t SL_SCAN_SEC_TYPE_WPA                                                                         =   (2);
+const uint8_t SL_SCAN_SEC_TYPE_WPA2                                                                        =   (3);
+
+
+
+const uint8_t TLS                           =     (0x1);
+const uint8_t MSCHAP                        =     (0x0);
+const uint8_t PSK                           =     (0x2);
+const uint8_t TTLS                          =     (0x10);
+const uint8_t PEAP0                         =     (0x20);
+const uint8_t PEAP1                         =     (0x40);
+const uint8_t FAST                          =     (0x80);
+
+const uint8_t FAST_AUTH_PROVISIONING        =     (0x02);
+const uint8_t FAST_UNAUTH_PROVISIONING      =     (0x01);
+const uint8_t FAST_NO_PROVISIONING          =     (0x00);
+
+const uint8_t EAPMETHOD_PHASE2_SHIFT        =     (8);
+const uint8_t EAPMETHOD_PAIRWISE_CIPHER_SHIFT =   (19);
+const uint8_t EAPMETHOD_GROUP_CIPHER_SHIFT  =     (27);
+
+const uint8_t WPA_CIPHER_CCMP               =     (0x1);
+const uint8_t WPA_CIPHER_TKIP               =     (0x2);
+const uint8_t CC31XX_DEFAULT_CIPHER         =     (WPA_CIPHER_CCMP | WPA_CIPHER_TKIP);
+
+#define EAPMETHOD(phase1,phase2,pairwise_cipher,group_cipher) \
+((phase1) | \
+ ((phase2) << EAPMETHOD_PHASE2_SHIFT ) |\
+ ((uint32_t)(pairwise_cipher) << EAPMETHOD_PAIRWISE_CIPHER_SHIFT ) |\
+ ((uint32_t)(group_cipher) << EAPMETHOD_GROUP_CIPHER_SHIFT ))
+
+/*                                                            phase1  phase2                     pairwise_cipher         group_cipher         */
+#define SL_ENT_EAP_METHOD_TLS                       EAPMETHOD(TLS   , 0                        , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER)
+#define SL_ENT_EAP_METHOD_TTLS_TLS                  EAPMETHOD(TTLS  , TLS                      , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER)
+#define SL_ENT_EAP_METHOD_TTLS_MSCHAPv2             EAPMETHOD(TTLS  , MSCHAP                   , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER)
+#define SL_ENT_EAP_METHOD_TTLS_PSK                  EAPMETHOD(TTLS  , PSK                      , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER)
+#define SL_ENT_EAP_METHOD_PEAP0_TLS                 EAPMETHOD(PEAP0 , TLS                      , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER)
+#define SL_ENT_EAP_METHOD_PEAP0_MSCHAPv2            EAPMETHOD(PEAP0 , MSCHAP                   , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER)
+#define SL_ENT_EAP_METHOD_PEAP0_PSK                 EAPMETHOD(PEAP0 , PSK                      , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER)
+#define SL_ENT_EAP_METHOD_PEAP1_TLS                 EAPMETHOD(PEAP1 , TLS                      , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER)
+#define SL_ENT_EAP_METHOD_PEAP1_MSCHAPv2            EAPMETHOD(PEAP1 , MSCHAP                   , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER)
+#define SL_ENT_EAP_METHOD_PEAP1_PSK                 EAPMETHOD(PEAP1 , PSK                      , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER)
+#define SL_ENT_EAP_METHOD_FAST_AUTH_PROVISIONING    EAPMETHOD(FAST  , FAST_AUTH_PROVISIONING   , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER)
+#define SL_ENT_EAP_METHOD_FAST_UNAUTH_PROVISIONING  EAPMETHOD(FAST  , FAST_UNAUTH_PROVISIONING , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER)
+#define SL_ENT_EAP_METHOD_FAST_NO_PROVISIONING      EAPMETHOD(FAST  , FAST_NO_PROVISIONING     , CC31XX_DEFAULT_CIPHER , CC31XX_DEFAULT_CIPHER)
+
+const uint8_t SL_LONG_PREAMBLE                  =  (0);
+const uint8_t SL_SHORT_PREAMBLE                 =  (1);
+
+const uint8_t SL_RAW_RF_TX_PARAMS_CHANNEL_SHIFT =  (0);
+const uint8_t SL_RAW_RF_TX_PARAMS_RATE_SHIFT    =  (6);
+const uint8_t SL_RAW_RF_TX_PARAMS_POWER_SHIFT   =  (11);
+const uint8_t SL_RAW_RF_TX_PARAMS_PREAMBLE_SHIFT = (15);
+
+#define SL_RAW_RF_TX_PARAMS(chan,rate,power,preamble) \
+    ((chan << SL_RAW_RF_TX_PARAMS_CHANNEL_SHIFT) | \
+    (rate << SL_RAW_RF_TX_PARAMS_RATE_SHIFT) | \
+    (power << SL_RAW_RF_TX_PARAMS_POWER_SHIFT) | \
+    (preamble << SL_RAW_RF_TX_PARAMS_PREAMBLE_SHIFT))
+
+
+/* wlan config application IDs */
+const uint8_t SL_WLAN_CFG_AP_ID                  =  (0);
+const uint8_t SL_WLAN_CFG_GENERAL_PARAM_ID       =  (1);
+const uint8_t SL_WLAN_CFG_P2P_PARAM_ID           =  (2);
+
+/* wlan AP Config set/get options */
+const uint8_t WLAN_AP_OPT_SSID                   =  (0);
+const uint8_t WLAN_AP_OPT_CHANNEL                =  (3);
+const uint8_t WLAN_AP_OPT_HIDDEN_SSID            =  (4);
+const uint8_t WLAN_AP_OPT_SECURITY_TYPE          =  (6);
+const uint8_t WLAN_AP_OPT_PASSWORD               =  (7);
+const uint8_t WLAN_GENERAL_PARAM_OPT_COUNTRY_CODE = (9);
+const uint8_t WLAN_GENERAL_PARAM_OPT_STA_TX_POWER = (10);
+const uint8_t WLAN_GENERAL_PARAM_OPT_AP_TX_POWER  = (11);
+
+const uint8_t WLAN_P2P_OPT_DEV_NAME              =  (12);
+const uint8_t WLAN_P2P_OPT_DEV_TYPE              =  (13);
+const uint8_t WLAN_P2P_OPT_CHANNEL_N_REGS        =  (14);
+const uint8_t WLAN_GENERAL_PARAM_OPT_INFO_ELEMENT = (16);
+const uint8_t WLAN_GENERAL_PARAM_OPT_SCAN_PARAMS  = (18);      /* change the scan channels and RSSI threshold using this configuration option */
+
+/* SmartConfig CIPHER options */
+const uint8_t SMART_CONFIG_CIPHER_SFLASH         =  (0);      /* password is not delivered by the application. The Simple Manager should */
+/* check if the keys are stored in the Flash.                              */
+const uint8_t SMART_CONFIG_CIPHER_AES            =  (1);      /* AES (other types are not supported)                                     */
+const uint8_t SMART_CONFIG_CIPHER_NONE           =  (0xFF);   /* do not check in the flash                                               */
+
+
+const uint8_t SL_POLICY_CONNECTION               =  (0x10);
+const uint8_t SL_POLICY_SCAN                     =  (0x20);
+const uint8_t SL_POLICY_PM                       =  (0x30);
+const uint8_t SL_POLICY_P2P                      =  (0x40);
+
+#define VAL_2_MASK(position,value)           ((1 & (value))<<(position))
+#define MASK_2_VAL(position,mask)            (((1 << position) & (mask)) >> (position))
+
+#define SL_CONNECTION_POLICY(Auto,Fast,Open,anyP2P,autoSmartConfig)                (VAL_2_MASK(0,Auto) | VAL_2_MASK(1,Fast) | VAL_2_MASK(2,Open) | VAL_2_MASK(3,anyP2P) | VAL_2_MASK(4,autoSmartConfig))
+#define SL_SCAN_POLICY_EN(policy)            (MASK_2_VAL(0,policy))
+#define SL_SCAN_POLICY(Enable)               (VAL_2_MASK(0,Enable))
+
+
+const uint8_t SL_NORMAL_POLICY                   = (0);
+const uint8_t SL_LOW_LATENCY_POLICY              = (1);
+const uint8_t SL_LOW_POWER_POLICY                = (2);
+const uint8_t SL_ALWAYS_ON_POLICY                = (3);
+const uint8_t SL_LONG_SLEEP_INTERVAL_POLICY      = (4);
+
+const uint8_t SL_P2P_ROLE_NEGOTIATE              = (3);
+const uint8_t SL_P2P_ROLE_GROUP_OWNER            = (15);
+const uint8_t SL_P2P_ROLE_CLIENT                 = (0);
+
+const uint8_t SL_P2P_NEG_INITIATOR_ACTIVE        = (0);
+const uint8_t SL_P2P_NEG_INITIATOR_PASSIVE       = (1);
+const uint8_t SL_P2P_NEG_INITIATOR_RAND_BACKOFF  = (2);
+
+#define POLICY_VAL_2_OPTIONS(position,mask,policy)    ((mask & policy) << position )
+
+#define SL_P2P_POLICY(p2pNegType,p2pNegInitiator)   (POLICY_VAL_2_OPTIONS(0,0xF,(p2pNegType > SL_P2P_ROLE_GROUP_OWNER ? SL_P2P_ROLE_GROUP_OWNER : p2pNegType)) | \
+                                                     POLICY_VAL_2_OPTIONS(4,0x1,(p2pNegType > SL_P2P_ROLE_GROUP_OWNER ? 1:0)) | \
+                                                     POLICY_VAL_2_OPTIONS(5,0x3, p2pNegInitiator))
+
+
+/* Info elements */
+
+const uint8_t INFO_ELEMENT_DEFAULT_ID            =  (0); /* 221 will be used */
+
+/* info element size is up to 252 bytes (+ 3 bytes of OUI). */
+const uint8_t INFO_ELEMENT_MAX_SIZE              =  (252);
+
+/* For AP - the total length of all info elements is 300 bytes (for example - 4 info elements of 75 bytes each) */
+const uint16_t INFO_ELEMENT_MAX_TOTAL_LENGTH_AP  =   (300);
+/* For P2P - the total length of all info elements is 150 bytes (for example - 4 info elements of 40 bytes each) */
+const uint8_t INFO_ELEMENT_MAX_TOTAL_LENGTH_P2P_GO (160);
+
+const uint8_t INFO_ELEMENT_AP_ROLE               =  (0);
+const uint8_t INFO_ELEMENT_P2P_GO_ROLE           =  (1);
+
+/* we support up to 4 info elements per Role. */
+const uint8_t MAX_PRIVATE_INFO_ELEMENTS_SUPPROTED = (4);
+
+const uint8_t INFO_ELEMENT_DEFAULT_OUI_0         =  (0x08);
+const uint8_t INFO_ELEMENT_DEFAULT_OUI_1         =  (0x00);
+const uint8_t INFO_ELEMENT_DEFAULT_OUI_2         =  (0x28);
+
+const uint32_t INFO_ELEMENT_DEFAULT_OUI          =   (0x000000);  /* 08, 00, 28 will be used */
+
+
+/*****************************************************************************/
+/* Structure/Enum declarations                                               */
+/*****************************************************************************/
+
+typedef enum {
+    RATE_1M         = 1,
+    RATE_2M         = 2,
+    RATE_5_5M       = 3,
+    RATE_11M        = 4,
+    RATE_6M         = 6,
+    RATE_9M         = 7,
+    RATE_12M        = 8,
+    RATE_18M        = 9,
+    RATE_24M        = 10,
+    RATE_36M        = 11,
+    RATE_48M        = 12,
+    RATE_54M        = 13,
+    RATE_MCS_0      = 14,
+    RATE_MCS_1      = 15,
+    RATE_MCS_2      = 16,
+    RATE_MCS_3      = 17,
+    RATE_MCS_4      = 18,
+    RATE_MCS_5      = 19,
+    RATE_MCS_6      = 20,
+    RATE_MCS_7      = 21,
+    MAX_NUM_RATES   = 0xFF
+} SlRateIndex_e;
+
+typedef enum {
+    DEV_PW_DEFAULT=0,
+    DEV_PW_PIN_KEYPAD=1,
+    DEV_PW_PUSH_BUTTON=4,
+    DEV_PW_PIN_DISPLAY=5
+} sl_p2p_dev_password_method;
+
+
+typedef struct {
+    uint32_t    status;
+    uint32_t    ssid_len;
+    uint8_t     ssid[32];
+    uint32_t    private_token_len;
+    uint8_t     private_token[32];
+} slSmartConfigStartAsyncResponse_t;
+
+typedef struct {
+    uint16_t    status;
+    uint16_t    padding;
+} slSmartConfigStopAsyncResponse_t;
+
+typedef struct {
+    uint16_t    status;
+    uint16_t    padding;
+} slWlanConnFailureAsyncResponse_t;
+
+typedef struct {
+    uint8_t     connection_type;/* 0-STA,3-P2P_CL */
+    uint8_t     ssid_len;
+    uint8_t     ssid_name[32];
+    uint8_t     go_peer_device_name_len;
+    uint8_t     go_peer_device_name[32];
+    uint8_t     bssid[6];
+    uint8_t     reason_code;
+    uint8_t     padding[2];
+} slWlanConnectAsyncResponse_t;
+
+typedef struct {
+    uint8_t     go_peer_device_name[32];
+    uint8_t     mac[6];
+    uint8_t     go_peer_device_name_len;
+    uint8_t     wps_dev_password_id;
+    uint8_t     own_ssid[32];/* relevant for event sta-connected only */
+    uint8_t     own_ssid_len;/* relevant for event sta-connected only */
+    uint8_t     padding[3];
+} slPeerInfoAsyncResponse_t;
+
+
+typedef union {
+    slSmartConfigStartAsyncResponse_t        smartConfigStartResponse; /*SL_WLAN_SMART_CONFIG_COMPLETE_EVENT*/
+    slSmartConfigStopAsyncResponse_t         smartConfigStopResponse;  /*SL_WLAN_SMART_CONFIG_STOP_EVENT */
+    slPeerInfoAsyncResponse_t                APModeStaConnected;       /* SL_WLAN_STA_CONNECTED_EVENT - relevant only in AP mode - holds information regarding a new STA connection */
+    slPeerInfoAsyncResponse_t                APModestaDisconnected;    /* SL_WLAN_STA_DISCONNECTED_EVENT - relevant only in AP mode - holds information regarding a STA disconnection */
+    slWlanConnectAsyncResponse_t             STAandP2PModeWlanConnected;   /* SL_WLAN_CONNECT_EVENT - relevant only in STA and P2P mode - holds information regarding a new connection */
+    slWlanConnectAsyncResponse_t             STAandP2PModeDisconnected;   /* SL_WLAN_DISCONNECT_EVENT - relevant only in STA and P2P mode - holds information regarding a disconnection */
+    slPeerInfoAsyncResponse_t                P2PModeDevFound;             /* SL_WLAN_P2P_DEV_FOUND_EVENT - relevant only in P2P mode */
+    slPeerInfoAsyncResponse_t                P2PModeNegReqReceived;       /* SL_WLAN_P2P_NEG_REQ_RECEIVED_EVENT - relevant only in P2P mode */
+    slWlanConnFailureAsyncResponse_t         P2PModewlanConnectionFailure;   /* SL_WLAN_CONNECTION_FAILED_EVENT - relevant only in P2P mode */
+
+} SlWlanEventData_u;
+
+typedef struct {
+    uint32_t     Event;
+    SlWlanEventData_u        EventData;
+} SlWlanEvent_t;
+
+
+typedef struct {
+    uint32_t  ReceivedValidPacketsNumber;                     /* sum of the packets that been received OK (include filtered) */
+    uint32_t  ReceivedFcsErrorPacketsNumber;                  /* sum of the packets that been dropped due to FCS error */
+    uint32_t  ReceivedAddressMismatchPacketsNumber;           /* sum of the packets that been received but filtered out by one of the HW filters */
+    int16_t   AvarageDataCtrlRssi;                            /* average RSSI for all valid data packets received */
+    int16_t   AvarageMgMntRssi;                               /* average RSSI for all valid management packets received */
+    uint16_t  RateHistogram[NUM_OF_RATE_INDEXES];             /* rate histogram for all valid packets received */
+    uint16_t  RssiHistogram[SIZE_OF_RSSI_HISTOGRAM];          /* RSSI histogram from -40 until -87 (all below and above\n RSSI will appear in the first and last cells */
+    uint32_t  StartTimeStamp;                                 /* the time stamp started collecting the statistics in uSec */
+    uint32_t  GetTimeStamp;                                   /* the time stamp called the get statistics command */
+} SlGetRxStatResponse_t;
+
+
+typedef struct {
+    uint8_t ssid[MAXIMAL_SSID_LENGTH];
+    uint8_t ssid_len;
+    uint8_t sec_type;
+    uint8_t bssid[SL_BSSID_LENGTH];
+    int8_t rssi;
+    int8_t reserved[3];
+} Sl_WlanNetworkEntry_t;
+
+
+typedef struct {
+    uint8_t   Type;
+    int8_t*  Key;
+    uint8_t   KeyLen;
+} SlSecParams_t;
+
+typedef struct {
+    int8_t*  User;
+    uint8_t   UserLen;
+    int8_t*  AnonUser;
+    uint8_t   AnonUserLen;
+    uint8_t   CertIndex;  /* not supported */
+    uint32_t  EapMethod;
+} SlSecParamsExt_t;
+
+typedef struct {
+    int8_t   User[32];
+    uint8_t   UserLen;
+    int8_t   AnonUser[32];
+    uint8_t   AnonUserLen;
+    uint8_t   CertIndex;  //not supported
+    uint32_t  EapMethod;
+} SlGetSecParamsExt_t;
+
+typedef enum {
+    ROLE_STA   =   0,
+    ROLE_AP    =   2,
+    ROLE_P2P     =   3,
+    ROLE_STA_ERR =  -1,         /* Failure to load MAC/PHY in STA role */
+    ROLE_AP_ERR  =  -ROLE_AP,   /* Failure to load MAC/PHY in AP role */
+    ROLE_P2P_ERR =  -ROLE_P2P   /* Failure to load MAC/PHY in P2P role */
+} SlWlanMode_t;
+
+typedef struct {
+    uint32_t   G_Channels_mask;
+    int32_t   rssiThershold;
+} slWlanScanParamCommand_t;
+
+
+typedef struct {
+    uint8_t   id;
+    uint8_t   oui[3];
+    uint16_t  length;
+    uint8_t   data[252];
+} sl_protocol_InfoElement_t;
+
+typedef struct {
+    uint8_t                       index;  /* 0 - MAX_PRIVATE_INFO_ELEMENTS_SUPPROTED */
+    uint8_t                       role;   /* bit0: AP = 0, GO = 1                    */
+    sl_protocol_InfoElement_t   ie;
+} sl_protocol_WlanSetInfoElement_t;
+
+
+class cc3100_wlan_rx_filters;
+class cc3100_wlan
+{
+
+public:
+
+    cc3100_wlan(cc3100_driver &driver, cc3100_wlan_rx_filters  &wlan_rx_filters);
+
+    ~cc3100_wlan();
+
+
+    /*****************************************************************************/
+    /* Function prototypes                                                                       */
+    /*****************************************************************************/
+
+
+    /*!
+        \brief Connect to wlan network as a station
+
+        \param[in]      pName       up to 32 bytes in case of STA the name is the SSID of the Access Point
+        \param[in]      NameLen     name length
+        \param[in]      pMacAddr    6 bytes for MAC address
+        \param[in]      pSecParams  Security parameters (use NULL key for SL_SEC_TYPE_OPEN)
+        Security types options: \n
+                                - SL_SEC_TYPE_OPEN
+                                - SL_SEC_TYPE_WEP
+                                - SL_SEC_TYPE_WPA_WPA2
+                                - SL_SEC_TYPE_WPA_ENT
+                                - SL_SEC_TYPE_WPS_PBC
+                                - SL_SEC_TYPE_WPS_PIN
+        \param[in]      pSecExtParams  Enterprise parameters (set NULL in case Enterprise parameters is not in use)
+
+        \return         On success, zero is returned. On error, negative is returned
+                        In case error number (-71) is returned, it indicates a connection was activated while the device it running in AP role
+
+        \sa             sl_WlanDisconnect
+        \note           belongs to \ref ext_api
+        \warning        In this version only single enterprise mode could be used
+                        SL_SEC_TYPE_WPA is a deprecated definition, the new definition is SL_SEC_TYPE_WPA_WPA2
+    */
+#if _SL_INCLUDE_FUNC(sl_WlanConnect)
+    int16_t sl_WlanConnect(const signed char*  pName, const int16_t NameLen, const uint8_t *pMacAddr, const SlSecParams_t* pSecParams, const SlSecParamsExt_t* pSecExtParams);
+#endif
+
+    /*!
+        \brief wlan disconnect
+
+        Disconnect connection
+
+        \return         0 disconnected done, other already disconnected
+
+        \sa             sl_WlanConnect
+        \note           belongs to \ref ext_api
+        \warning
+    */
+#if _SL_INCLUDE_FUNC(sl_WlanDisconnect)
+    int16_t sl_WlanDisconnect(void);
+#endif
+
+    /*!
+        \brief add profile
+
+        When auto start is enabled, the device connects to a
+        station from the profiles table. Up to 7 profiles are
+        supported. If several profiles configured the device chose
+        the highest priority profile, within each priority group,
+        device will chose profile based on security policy, signal
+        strength, etc parameters.
+
+
+        \param[in]      pName          up to 32 bytes in case of STA the name is the
+                                       SSID of the Access Point
+                                       in case of P2P the name is the remote device name
+        \param[in]      NameLen     name length
+        \param[in]      pMacAddr    6 bytes for MAC address
+        \param[in]      pSecParams     Security parameters - security type
+                                       (SL_SEC_TYPE_OPEN,SL_SEC_TYPE_WEP,SL_SEC_TYPE_WPA_WPA2,
+                                        SL_SEC_TYPE_P2P_PBC,SL_SEC_TYPE_P2P_PIN_KEYPAD,SL_SEC_TYPE_P2P_PIN_DISPLAY, SL_SEC_TYPE_WPA_ENT), key, and key length
+                                       in case of p2p security type pin the key refers to pin code
+        \param[in]      pSecExtParams  Enterprise parameters - identity, identity length,
+                                       Anonymous, Anonymous length, CertIndex (not supported,
+                                       certificates need to be placed in a specific file ID),
+                                       EapMethod.Use NULL in case Enterprise parameters is not in use
+
+        \param[in]      Priority    profile priority. Lowest priority: 0
+        \param[in]      Options     Not supported
+
+        \return         On success, profile stored index is returned. On error, negative value is returned
+
+        \sa             sl_WlanProfileGet , sl_WlanProfileDel
+        \note           belongs to \ref ext_api
+        \warning        Only one Enterprise profile is supported.
+                        Please Note that in case of adding an existing profile (compared by pName,pMACAddr and security type)
+                        the old profile will be deleted and the same index will be returned.
+                        SL_SEC_TYPE_WPA is a deprecated definition, the new definition is SL_SEC_TYPE_WPA_WPA2
+
+    */
+#if _SL_INCLUDE_FUNC(sl_WlanProfileAdd)
+    int16_t sl_WlanProfileAdd(const int8_t*  pName, 
+                              const int16_t NameLen, 
+                              const uint8_t *pMacAddr, 
+                              const SlSecParams_t* pSecParams , 
+                              const SlSecParamsExt_t* pSecExtParams, 
+                              const uint32_t  Priority, 
+                              const uint32_t  Options);
+#endif
+
+    /*!
+        \brief get profile
+
+        read profile from the device
+
+        \param[in]      Index          profile stored index, if index does not exists
+                                       error is return
+        \param[out]     pName          up to 32 bytes, in case of sta mode the name of the Access Point
+                                       in case of p2p mode the name of the Remote Device
+        \param[out]     pNameLen       name length
+        \param[out]     pMacAddr       6 bytes for MAC address
+        \param[out]     pSecParams     security parameters - security type
+                                       (SL_SEC_TYPE_OPEN, SL_SEC_TYPE_WEP, SL_SEC_TYPE_WPA_WPA2 or
+                                       SL_SEC_TYPE_WPS_PBC, SL_SEC_TYPE_WPS_PIN, SL_SEC_TYPE_WPA_ENT,SL_SEC_TYPE_P2P_PBC,SL_SEC_TYPE_P2P_PIN_KEYPAD or SL_SEC_TYPE_P2P_PIN_DISPLAY), 
+                                       key and key length are not                  
+                                       in case of p2p security type pin the key refers to pin code
+                                       return due to security reasons.
+        \param[out]     pSecExtParams  enterprise parameters - identity, identity
+                                       length, Anonymous, Anonymous length
+                                       CertIndex (not supported), EapMethod.
+        \param[out]     Priority       profile priority
+
+        \return         On success, Profile security type is returned (0 or positive number). On error, -1 is
+                        returned
+
+        \sa             sl_WlanProfileAdd , sl_WlanProfileDel
+        \note           belongs to \ref ext_api
+        \warning
+    */
+#if _SL_INCLUDE_FUNC(sl_WlanProfileGet)
+    int16_t sl_WlanProfileGet(const int16_t Index,int8_t*  pName, int16_t *pNameLen, uint8_t *pMacAddr, SlSecParams_t* pSecParams, SlGetSecParamsExt_t* pSecExtParams, uint32_t *pPriority);
+#endif
+
+    /*!
+        \brief Delete WLAN profile
+
+        Delete WLAN profile
+
+        \param[in]   index  number of profile to delete.Possible values are 0 to 6.
+                     Index value 255 will delete all saved profiles
+
+        \return  On success, zero is returned. On error, -1 is
+                   returned
+
+        \sa   sl_WlanProfileAdd , sl_WlanProfileGet
+        \note           belongs to \ref ext_api
+        \warning
+    */
+#if _SL_INCLUDE_FUNC(sl_WlanProfileDel)
+    int16_t sl_WlanProfileDel(const int16_t Index);
+#endif
+
+    /*!
+        \brief Set policy values
+
+        \param[in]      Type      Type of policy to be modified. The Options are:\n
+                                  - SL_POLICY_CONNECTION
+                                  - SL_POLICY_SCAN
+                                  - SL_POLICY_PM
+                                  - SL_POLICY_P2P
+        \param[in]      Policy    The option value which depends on action type
+        \param[in]      pVal      An optional value pointer
+        \param[in]      ValLen    An optional value length, in bytes
+        \return         On success, zero is returned. On error, -1 is
+                        returned
+        \sa             sl_WlanPolicyGet
+        \note           belongs to \ref ext_api
+        \warning
+        \par
+        SL_POLICY_CONNECTION type defines three options available to connect the CC31xx device to the AP: \n
+
+        -  If Auto Connect is set, the CC31xx device tries to automatically reconnect to one of its stored profiles, each time the connection fails or the device is rebooted.\n
+           To set this option, use: \n
+           <b> sl_WlanPolicySet(SL_POLICY_CONNECTION,SL_CONNECTION_POLICY(1,0,0,0,0),NULL,0) </b>
+        -  If Fast Connect is set, the CC31xx device tries to establish a fast connection to AP. \n
+           To set this option, use: \n
+           <b> sl_WlanPolicySet(SL_POLICY_CONNECTION,SL_CONNECTION_POLICY(0,1,0,0,0),NULL,0) </b>
+        -  (relevant for P2P mode only) - If Any P2P is set,  CC31xx/CC32xx device tries to automatically connect to the first P2P device available, \n
+           supporting push button only. To set this option, use: \n
+           <b> sl_WlanPolicySet(SL_POLICY_CONNECTION,SL_CONNECTION_POLICY(0,0,0,1,0),NULL,0) </b>
+        -  For auto smart config upon restart (any command from Host will end this state) use: \n
+           <b> sl_WlanPolicySet(SL_POLICY_CONNECTION,SL_CONNECTION_POLICY(0,0,0,0,1),NULL,0) </b> \n
+        The options above could be combined to a single action, if more than one action is required. \n
+        \par
+        SL_POLICY_SCAN defines system scan time interval.Default interval is 10 minutes. \n
+        After settings scan interval, an immediate scan is activated. The next scan will be based on the interval settings. \n
+                        -  For example, setting scan interval to 1 minute interval use: \n
+                           uint32_t intervalInSeconds = 60;    \n
+                           #define SL_SCAN_ENABLE  1       \n<b>
+                           sl_WlanPolicySet(SL_POLICY_SCAN,SL_SCAN_ENABLE, (uint8_t *)&intervalInSeconds,sizeof(intervalInSeconds)); </b>\n
+
+                        -  For example, disable scan:    \n
+                           #define SL_SCAN_DISABLE  0     \n<b>
+                           sl_WlanPolicySet(SL_POLICY_SCAN,SL_SCAN_DISABLE,0,0); </b>\n
+        \par
+        SL_POLICY_PM defines a power management policy for Station mode only:
+                        -  For setting normal power management (default) policy use: <b> sl_WlanPolicySet(SL_POLICY_PM , SL_NORMAL_POLICY, NULL,0) </b>
+                        -  For setting low latency power management policy use: <b> sl_WlanPolicySet(SL_POLICY_PM , SL_LOW_LATENCY_POLICY, NULL,0) </b>
+                        -  For setting low power management policy use: <b> sl_WlanPolicySet(SL_POLICY_PM , SL_LOW_POWER_POLICY, NULL,0) </b>
+                        -  For setting always on power management policy use: <b> sl_WlanPolicySet(SL_POLICY_PM , SL_ALWAYS_ON_POLICY, NULL,0) </b>
+                        -  For setting Long Sleep Interval policy use: \n
+                                uint16_t PolicyBuff[4] = {0,0,800,0}; // PolicyBuff[2] is max sleep time in mSec \n<b>
+                                sl_WlanPolicySet(SL_POLICY_PM , SL_LONG_SLEEP_INTERVAL_POLICY, (uint8_t*)PolicyBuff,sizeof(PolicyBuff));  </b>\n
+
+        SL_POLICY_P2P defines p2p negotiation policy parameters for P2P role:
+                        - To set intent negotiation value, set on of the following:
+                            SL_P2P_ROLE_NEGOTIATE   - intent 3
+                            SL_P2P_ROLE_GROUP_OWNER - intent 15
+                            SL_P2P_ROLE_CLIENT      - intent 0
+                        - To set negotiation initiator value (initiator policy of first negotiation action frame), set on of the following:
+                            SL_P2P_NEG_INITIATOR_ACTIVE
+                            SL_P2P_NEG_INITIATOR_PASSIVE
+                            SL_P2P_NEG_INITIATOR_RAND_BACKOFF
+                        For example: \n
+                        <b>sl_WlanPolicySet(SL_POLICY_P2P, SL_P2P_POLICY(SL_P2P_ROLE_NEGOTIATE,SL_P2P_NEG_INITIATOR_RAND_BACKOFF),NULL,0) </b>
+
+    */
+#if _SL_INCLUDE_FUNC(sl_WlanPolicySet)
+    int16_t sl_WlanPolicySet(const uint8_t Type , const uint8_t Policy, uint8_t *pVal,const uint8_t ValLen);
+#endif
+    /*!
+        \brief get policy values
+
+        \param[in]      Type     SL_POLICY_CONNECTION, SL_POLICY_SCAN, SL_POLICY_PM,SL_POLICY_P2P \n
+
+        \param[in]      Policy   argument may be set to any value \n
+
+        \param[out]     The returned values, depends on each policy type, will be stored in the allocated buffer pointed by pVal
+                        with a maximum buffer length set by the calling function and pointed to by argument *pValLen
+
+        \return         On success, zero is returned. On error, -1 is returned
+
+        \sa             sl_WlanPolicySet
+
+        \note           belongs to \ref ext_api
+
+        \warning        The value pointed by the argument *pValLen should be set to a value different from 0 and
+                        greater than the buffer length returned from the SL device. Otherwise, an error will be returned.
+
+    */
+#if _SL_INCLUDE_FUNC(sl_WlanPolicyGet)
+    int16_t sl_WlanPolicyGet(const uint8_t Type , uint8_t Policy,uint8_t *pVal,uint8_t *pValLen);
+#endif
+    /*!
+        \brief Gets the WLAN scan operation results
+
+        Gets scan results , gets entry from scan result table
+
+        \param[in]   Index - Starting index identifier (range 0-19) for getting scan results
+        \param[in]   Count - How many entries to fetch. Max is (20-"Index").
+        \param[out]  pEntries - pointer to an allocated Sl_WlanNetworkEntry_t.
+                                the number of array items should match "Count"
+                                sec_type: SL_SCAN_SEC_TYPE_OPEN, SL_SCAN_SEC_TYPE_WEP, SL_SCAN_SEC_TYPE_WPA or SL_SCAN_SEC_TYPE_WPA2
+
+
+        \return  Number of valid networks list items
+
+        \sa
+        \note       belongs to \ref ext_api
+        \warning    This command do not initiate any active scanning action
+        \par        Example:
+        \code       An example of fetching max 10 results:
+
+                    Sl_WlanNetworkEntry_t netEntries[10];
+                    int16_t resultsCount = sl_WlanGetNetworkList(0,10,&netEntries[0]);
+                    for(i=0; i< resultsCount; i++)
+                    {
+                          printf("%s\n",netEntries[i].ssid);
+                    }
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_WlanGetNetworkList)
+    int16_t sl_WlanGetNetworkList(const uint8_t Index, const uint8_t Count, Sl_WlanNetworkEntry_t *pEntries);
+#endif
+
+    /*!
+        \brief   Start collecting wlan RX statistics, for unlimited time.
+
+        \return  On success, zero is returned. On error, -1 is returned
+
+        \sa     sl_WlanRxStatStop      sl_WlanRxStatGet
+        \note   belongs to \ref ext_api
+        \warning  
+        \par        Example:
+        \code       Getting wlan RX statistics:
+
+        void RxStatCollectTwice()
+        {
+            SlGetRxStatResponse_t rxStat;
+            int16_t rawSocket;
+            int8_t DataFrame[200];
+            struct SlTimeval_t timeval;
+            timeval.tv_sec =  0;             // Seconds
+            timeval.tv_usec = 20000;         // Microseconds. 10000 microseconds resolution
+
+            sl_WlanRxStatStart();  // set statistics mode
+
+            rawSocket = sl_Socket(SL_AF_RF, SL_SOCK_RAW, eChannel);
+            // set timeout - in case we have no activity for the specified channel
+            sl_SetSockOpt(rawSocket,SL_SOL_SOCKET,SL_SO_RCVTIMEO, &timeval, sizeof(timeval));    // Enable receive timeout
+            status = sl_Recv(rawSocket, DataFrame, sizeof(DataFrame), 0);
+
+            Sleep(1000); // sleep for 1 sec
+            sl_WlanRxStatGet(&rxStat,0); // statistics has been cleared upon read
+            Sleep(1000); // sleep for 1 sec
+            sl_WlanRxStatGet(&rxStat,0);
+
+        }
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_WlanRxStatStart)
+    int16_t sl_WlanRxStatStart(void);
+#endif
+
+
+    /*!
+        \brief    Stop collecting wlan RX statistic, (if previous called sl_WlanRxStatStart)
+
+        \return   On success, zero is returned. On error, -1 is returned
+
+        \sa     sl_WlanRxStatStart      sl_WlanRxStatGet
+        \note           belongs to \ref ext_api
+        \warning  
+    */
+#if _SL_INCLUDE_FUNC(sl_WlanRxStatStop)
+    int16_t sl_WlanRxStatStop(void);
+#endif
+
+
+    /*!
+        \brief Get wlan RX statistics. upon calling this command, the statistics counters will be cleared.
+
+        \param[in]  Flags should be 0  ( not applicable right now, will be added the future )
+        \param[in]  pRxStat a pointer to SlGetRxStatResponse_t filled with Rx statistics results
+        \return     On success, zero is returned. On error, -1 is returned
+
+        \sa   sl_WlanRxStatStart  sl_WlanRxStatStop
+        \note           belongs to \ref ext_api
+        \warning
+    */
+#if _SL_INCLUDE_FUNC(sl_WlanRxStatGet)
+    int16_t sl_WlanRxStatGet(SlGetRxStatResponse_t *pRxStat, const uint32_t Flags);
+#endif
+
+
+    /*!
+        \brief Stop Smart Config procedure. Once Smart Config will be stopped,
+               Asynchronous event will be received - SL_OPCODE_WLAN_SMART_CONFIG_STOP_ASYNC_RESPONSE.
+
+        \param[in]  none
+        \param[out] none
+
+        \return     0 - if Stop Smart Config is about to be executed without errors.
+
+        \sa         sl_WlanSmartConfigStart
+        \note           belongs to \ref ext_api
+        \warning      
+
+    */
+#if _SL_INCLUDE_FUNC(sl_WlanSmartConfigStop)
+    int16_t sl_WlanSmartConfigStop(void);
+#endif
+
+    /*!
+        \brief  Start Smart Config procedure
+        \par
+                The target of the procedure is to let the                      \n
+                device to gain the network parameters: SSID and Password (if network is secured)             \n
+                and to connect to it once located in the network range.                                      \n
+                An external application should be used on a device connected to any mobile network.          \n
+                The external application will transmit over the air the network parameters in secured manner.\n
+                The Password may be decrypted using a Key.                                                   \n
+                The decryption method may be decided in the command or embedded in the Flash.                \n
+                The procedure can be activated for 1-3 group ID in the range of BIT_0 - BIT_15 where the default group ID id 0 (BIT_0) \n
+                Once Smart Config has ended successfully, Asynchronous event will be received -              \n
+                SL_OPCODE_WLAN_SMART_CONFIG_START_ASYNC_RESPONSE.                                            \n
+                The Event will hold the SSID and an extra field that might have been delivered as well (i.e. - device name)
+
+        \param[in]  groupIdBitmask - each bit represent a group ID that should be searched.
+                                     The Default group ID id BIT_0. 2 more group can be searched
+                                     in addition. The range is BIT_0 - BIT_15.
+        \param[in]  chiper - 0: check in flash, 1 - AES, 0xFF - do not check in flash
+        \param[in]  publicKeyLen - public key len (used for the default group ID - BIT_0)
+        \param[in]  group1KeyLen - group ID1 length
+        \param[in]  group2KeyLen - group ID2 length
+        \param[in]  publicKey    - public key (used for the default group ID - BIT_0)
+        \param[in]  group1Key    - group ID1 key
+        \param[in]  group2Key    - group ID2 key
+
+        \param[out] none
+
+        \return     0 - if Smart Config started successfully.
+
+        \sa         sl_WlanSmartConfigStop
+        \note           belongs to \ref ext_api
+        \warning
+        \par
+        \code       An example of starting smart Config on group ID's 0 + 1 + 2
+
+                    sl_WlanSmartConfigStart(7,      //group ID's (BIT_0 | BIT_1 | BIT_2)
+                                            1,      //decrypt key by AES method
+                                            16,     //decryption key length for group ID0
+                                            16,     //decryption key length for group ID1
+                                            16,     //decryption key length for group ID2
+                                            "Key0Key0Key0Key0", //decryption key for group ID0
+                                            "Key1Key1Key1Key1", //decryption key for group ID1
+                                            "Key2Key2Key2Key2"  //decryption key for group ID2
+                                            );
+        \endcode
+    */
+#if _SL_INCLUDE_FUNC(sl_WlanSmartConfigStart)
+    int16_t sl_WlanSmartConfigStart(const uint32_t    groupIdBitmask,
+                                    const uint8_t    cipher,
+                                    const uint8_t    publicKeyLen,
+                                    const uint8_t    group1KeyLen,
+                                    const uint8_t    group2KeyLen,
+                                    const uint8_t*    publicKey,
+                                    const uint8_t*    group1Key,
+                                    const uint8_t*    group2Key);
+#endif
+
+
+    /*!
+        \brief Wlan set mode
+
+        Setting WLAN mode
+
+        \param[in] mode - WLAN mode to start the CC31xx device. Possible options are:
+                        - ROLE_STA - for WLAN station mode
+                        - ROLE_AP  - for WLAN AP mode
+                        - ROLE_P2P  -for WLAN P2P mode
+        \return   0 - if mode was set correctly
+        \sa        sl_Start sl_Stop
+        \note           belongs to \ref ext_api
+        \warning   After setting the mode the system must be restarted for activating the new mode
+        \par       Example:
+        \code
+                    //Switch from any role to STA:
+                    sl_WlanSetMode(ROLE_STA);
+                    sl_Stop(0);
+                    sl_Start(NULL,NULL,NULL);
+        \endcode
+
+    */
+#if _SL_INCLUDE_FUNC(sl_WlanSetMode)
+    int16_t sl_WlanSetMode(const uint8_t mode);
+#endif
+
+
+    /*!
+        \brief     Internal function for setting WLAN configurations
+
+        \return    On success, zero is returned. On error one of the following error codes  returned:
+                   - CONF_ERROR                        (-1)
+                   - CONF_NVMEM_ACCESS_FAILED          (-2)
+                   - CONF_OLD_FILE_VERSION             (-3)
+                   - CONF_ERROR_NO_SUCH_COUNTRY_CODE   (-4)
+
+
+        \param[in] ConfigId -  configuration id
+                              - <b>SL_WLAN_CFG_AP_ID</b>
+                              - <b>SL_WLAN_CFG_GENERAL_PARAM_ID</b>
+                              - <b>SL_WLAN_CFG_P2P_PARAM_ID</b>
+
+        \param[in] ConfigOpt - configurations option
+                              - <b>SL_WLAN_CFG_AP_ID</b>
+                                  - <b>WLAN_AP_OPT_SSID</b> \n
+                                          Set SSID for AP mode. \n
+                                          This options takes <b>uint8_t</b> buffer as parameter
+                                  - <b>WLAN_AP_OPT_CHANNEL</b> \n
+                                          Set channel for AP mode. \n
+                                          The channel is dependant on the country code which is set. i.e. for "US" the channel should be in the range of [1-11] \n
+                                          This option takes <b>uint8_t</b> as a parameter
+                                  - <b>WLAN_AP_OPT_HIDDEN_SSID</b> \n
+                                          Set Hidden SSID Mode for AP mode.Hidden options: \n
+                                             0: disabled \n
+                                             1: Send empty (length=0) SSID in beacon and ignore probe request for broadcast SSID \n
+                                             2: Clear SSID (ASCII 0), but keep the original length (this may be required with some \n
+                                                clients that do not support empty SSID) and ignore probe requests for broadcast SSID \n
+                                          This option takes <b>uint8_t</b> as a parameter
+                                  - <b>WLAN_AP_OPT_SECURITY_TYPE</b> \n
+                                          Set Security type for AP mode. Security options are:
+                                          - Open security: SL_SEC_TYPE_OPEN
+                                          - WEP security:  SL_SEC_TYPE_WEP
+                                          - WPA security:  SL_SEC_TYPE_WPA_WPA2  \n
+                                          This option takes <b>uint8_t</b> pointer as a parameter
+                                  - <b>WLAN_AP_OPT_PASSWORD</b> \n
+                                          Set Password for for AP mode (for WEP or for WPA): \n
+                                          Password - for WPA: 8 - 63 characters \n
+                                          for WEP: 5 / 13 characters (ascii) \n
+                                          This options takes <b>uint8_t</b> buffer as parameter
+                              - <b>SL_WLAN_CFG_GENERAL_PARAM_ID</b>
+                              - <b> WLAN_GENERAL_PARAM_OPT_SCAN_PARAMS </b> \n
+                                      Set scan parameters.
+                                      This option uses slWlanScanParamCommand_t as parameter
+                                  - <b>WLAN_GENERAL_PARAM_OPT_COUNTRY_CODE</b> \n
+                                          Set Country Code for AP mode \n
+                                          This options takes <b>uint8_t</b> 2 bytes buffer as parameter
+                                  - <b>WLAN_GENERAL_PARAM_OPT_STA_TX_POWER</b> \n
+                                          Set STA mode Tx power level \n
+                                          Number between 0-15, as dB offset from max power (0 will set MAX power) \n
+                                          This options takes <b>uint8_t</b> as parameter
+                                  - <b>WLAN_GENERAL_PARAM_OPT_AP_TX_POWER</b>
+                                          Set AP mode Tx power level \n
+                                          Number between 0-15, as dB offset from max power (0 will set MAX power) \n
+                                          This options takes <b>uint8_t</b> as parameter
+                                  - <b>WLAN_GENERAL_PARAM_OPT_INFO_ELEMENT</b>
+                                          Set Info Element for AP mode. \n
+                                          The Application can set up to MAX_PRIVATE_INFO_ELEMENTS_SUPPROTED info elements per Role (AP / P2P GO).  \n
+                                          To delete an info element use the relevant index and length = 0. \n
+                                          The Application can set up to MAX_PRIVATE_INFO_ELEMENTS_SUPPROTED to the same role. \n
+                                          However, for AP - no more than INFO_ELEMENT_MAX_TOTAL_LENGTH_AP bytes can be stored for all info elements. \n
+                                          For P2P GO - no more than INFO_ELEMENT_MAX_TOTAL_LENGTH_P2P_GO bytes can be stored for all info elements.  \n
+                                          This option takes sl_protocol_WlanSetInfoElement_t as parameter
+                              - <b>SL_WLAN_CFG_P2P_PARAM_ID</b>
+                                  - <b>WLAN_P2P_OPT_DEV_TYPE</b> \n
+                                          Set P2P Device type.Maximum length of 17 characters. Device type is published under P2P I.E, \n
+                                          allows to make devices easier to recognize. \n
+                                          In case no device type is set, the default type is "1-0050F204-1"  \n
+                                          This options takes <b>uint8_t</b> buffer as parameter
+                                  - <b>WLAN_P2P_OPT_CHANNEL_N_REGS</b> \n
+                                         Set P2P Channels. \n
+                                         listen channel (either 1/6/11 for 2.4GHz) \n
+                                         listen regulatory class (81 for 2.4GHz)   \n
+                                         oper channel (either 1/6/11 for 2.4GHz)   \n
+                                         oper regulatory class (81 for 2.4GHz)     \n
+                                         listen channel and regulatory class will determine the device listen channel during p2p find listen phase \n
+                                         oper channel and regulatory class will determine the operating channel preferred by this device (in case it is group owner this will be the operating channel) \n
+                                         channels should be one of the social channels (1/6/11). In case no listen/oper channel selected, a random 1/6/11 will be selected.
+                                         This option takes pointer to <b>uint8_t[4]</b> as parameter
+
+        \param[in] ConfigLen - configurations len
+
+        \param[in] pValues -   configurations values
+
+        \sa
+        \note
+        \warning
+        \par   Examples:
+        \par
+              <b> WLAN_AP_OPT_SSID: </b>
+        \code
+                uint8_t  str[33];
+                memset(str, 0, 33);
+                memcpy(str, ssid, len);  // ssid string of 32 characters
+                sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_SSID, strlen(ssid), str);
+        \endcode
+       \par
+              <b> WLAN_AP_OPT_CHANNEL: </b>
+        \code
+                uint8_t  val = channel;
+                sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_CHANNEL, 1, (uint8_t *)&val);
+        \endcode
+        \par
+              <b>  WLAN_AP_OPT_HIDDEN_SSID: </b>
+         \code
+                uint8_t  val = hidden;
+                sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_HIDDEN_SSID, 1, (uint8_t *)&val);
+        \endcode
+        \par
+              <b> WLAN_AP_OPT_SECURITY_TYPE: </b>
+         \code
+               uint8_t  val = SL_SEC_TYPE_WPA_WPA2;
+               sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_SECURITY_TYPE, 1, (uint8_t *)&val);
+        \endcode
+        \par
+              <b>  WLAN_AP_OPT_PASSWORD: </b>
+         \code
+               uint8_t  str[65];
+               uint16_t  len = strlen(password);
+               memset(str, 0, 65);
+               memcpy(str, password, len);
+               sl_WlanSet(SL_WLAN_CFG_AP_ID, WLAN_AP_OPT_PASSWORD, len, (uint8_t *)str);
+        \endcode
+        \par
+             <b> WLAN_GENERAL_PARAM_OPT_STA_TX_POWER: </b>
+         \code
+             uint8_t  stapower=(uint8_t)power;
+             sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_STA_TX_POWER,1,(uint8_t *)&stapower);
+        \endcode
+        \par   
+          <b> WLAN_GENERAL_PARAM_OPT_SCAN_PARAMS: </b>
+        \code   
+          slWlanScanParamCommand_t ScanParamConfig;
+          ScanParamConfig.G_Channels_mask = 0x01;  // bit mask for channels:1 means channel 1 is enabled, 3 means channels 1 + 2 are enabled
+          ScanParamConfig.rssiThershold = -70;     // only for RSSI level which is higher than -70
+          sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID ,WLAN_GENERAL_PARAM_OPT_SCAN_PARAMS,sizeof(slWlanScanParamCommand_t),(_u8*)&ScanParamConfig);
+       \endcode
+       \par
+              <b> WLAN_GENERAL_PARAM_OPT_COUNTRY_CODE: </b>
+        \code
+                uint8_t*  str = (uint8_t *) country;  // string of 2 characters. i.e. - "US"
+                sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_COUNTRY_CODE, 2, str);
+        \endcode
+       \par
+              <b> WLAN_GENERAL_PARAM_OPT_AP_TX_POWER: </b>
+        \code
+             uint8_t  appower=(uint8_t)power;
+             sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, WLAN_GENERAL_PARAM_OPT_AP_TX_POWER,1,(uint8_t *)&appower);
+        \endcode
+       \par
+              <b> WLAN_P2P_OPT_DEV_TYPE: </b>
+        \code
+             uint8_t   str[17];
+             uint16_t  len = strlen(device_type);
+             memset(str, 0, 17);
+             memcpy(str, device_type, len);
+             sl_WlanSet(SL_WLAN_CFG_P2P_PARAM_ID, WLAN_P2P_OPT_DEV_TYPE, len, str);
+        \endcode
+        \par
+              <b> WLAN_P2P_OPT_CHANNEL_N_REGS: </b>
+        \code
+            uint8_t  str[4];
+            str[0] = (uint8_t)11;           // listen channel
+            str[1] = (uint8_t)81;            // listen regulatory class
+            str[2] = (uint8_t)6;            // oper channel
+            str[3] = (uint8_t)81;            // oper regulatory class
+            sl_WlanSet(SL_WLAN_CFG_P2P_PARAM_ID, WLAN_P2P_OPT_CHANNEL_N_REGS, 4, str);
+        \endcode
+       \par
+              <b> WLAN_GENERAL_PARAM_OPT_INFO_ELEMENT: </b>
+         \code
+            sl_protocol_WlanSetInfoElement_t    infoele;
+            infoele.index     = Index;                  // Index of the info element. range: 0 - MAX_PRIVATE_INFO_ELEMENTS_SUPPROTED
+            infoele.role      = Role;                   // INFO_ELEMENT_AP_ROLE (0) or INFO_ELEMENT_P2P_GO_ROLE (1)
+            infoele.ie.id     =  Id;                    // Info element ID. if INFO_ELEMENT_DEFAULT_ID (0) is set, ID will be set to 221.
+            // Organization unique ID. If all 3 bytes are zero - it will be replaced with 08,00,28.
+            infoele.ie.oui[0] =  Oui0;                  // Organization unique ID first Byte
+            infoele.ie.oui[1] =  Oui1;                  // Organization unique ID second Byte
+            infoele.ie.oui[2] =  Oui2;                  // Organization unique ID third Byte
+            infoele.ie.length = Len;                    // Length of the info element. must be smaller than 253 bytes
+            memset(infoele.ie.data, 0, INFO_ELEMENT_MAX_SIZE);
+            if ( Len <= INFO_ELEMENT_MAX_SIZE )
+            {
+                memcpy(infoele.ie.data, IE, Len);           // Info element. length of the info element is [0-252]
+                sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID,WLAN_GENERAL_PARAM_OPT_INFO_ELEMENT,sizeof(sl_protocol_WlanSetInfoElement_t),(uint8_t* ) &infoele);
+            }
+            sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID,WLAN_GENERAL_PARAM_OPT_INFO_ELEMENT,sizeof(sl_protocol_WlanSetInfoElement_t),(uint8_t* ) &infoele);
+        \endcode
+
+    */
+#if _SL_INCLUDE_FUNC(sl_WlanSet)
+    int16_t sl_WlanSet(const uint16_t ConfigId ,const uint16_t ConfigOpt, const uint16_t ConfigLen, const uint8_t *pValues);
+#endif
+
+    /*!
+        \brief     Internal function for getting WLAN configurations
+
+        \return    On success, zero is returned. On error, -1 is
+                   returned
+
+        \param[in] ConfigId -  configuration id
+                              - <b>SL_WLAN_CFG_AP_ID</b>
+                              - <b>SL_WLAN_CFG_GENERAL_PARAM_ID</b>
+                              - <b>SL_WLAN_CFG_P2P_PARAM_ID</b>
+
+        \param[out] pConfigOpt - get configurations option
+                              - <b>SL_WLAN_CFG_AP_ID</b>
+                                  - <b>WLAN_AP_OPT_SSID</b> \n
+                                          Get SSID for AP mode. \n
+                                          Get up to 32 characters of SSID \n
+                                          This options takes <b>uint8_t</b> as parameter
+                                  - <b>WLAN_AP_OPT_CHANNEL</b> \n
+                                          Get channel for AP mode. \n
+                                          This option takes <b>uint8_t</b> as a parameter
+                                  - <b>WLAN_AP_OPT_HIDDEN_SSID</b> \n
+                                          Get Hidden SSID Mode for AP mode.Hidden options: \n
+                                             0: disabled \n
+                                             1: Send empty (length=0) SSID in beacon and ignore probe request for broadcast SSID \n
+                                             2: Clear SSID (ASCII 0), but keep the original length (this may be required with some \n
+                                                clients that do not support empty SSID) and ignore probe requests for broadcast SSID \n
+                                          This option takes <b>uint8_t</b> as a parameter
+                                  - <b>WLAN_AP_OPT_SECURITY_TYPE</b> \n
+                                          Get Security type for AP mode. Security options are:
+                                          - Open security: SL_SEC_TYPE_OPEN
+                                          - WEP security:  SL_SEC_TYPE_WEP
+                                          - WPA security:  SL_SEC_TYPE_WPA_WPA2  \n
+                                          This option takes <b>uint8_t</b> as a parameter
+                                  - <b>WLAN_AP_OPT_PASSWORD</b> \n
+                                          Get Password for for AP mode (for WEP or for WPA): \n
+                                          Returns password - string, fills up to 64 characters. \n
+                                          This options takes <b>uint8_t</b> buffer as parameter
+                              - <b>SL_WLAN_CFG_GENERAL_PARAM_ID</b>
+                                  - <b> WLAN_GENERAL_PARAM_OPT_SCAN_PARAMS </b> \n
+                                          Get scan parameters.
+                                          This option uses slWlanScanParamCommand_t as parameter
+                                  - <b>WLAN_GENERAL_PARAM_OPT_COUNTRY_CODE</b> \n
+                                          Get Country Code for AP mode \n
+                                          This options takes <b>uint8_t</b> buffer as parameter
+                                  - <b>WLAN_GENERAL_PARAM_OPT_STA_TX_POWER</b> \n
+                                          Get STA mode Tx power level \n
+                                          Number between 0-15, as dB offset from max power (0 indicates MAX power) \n
+                                          This options takes <b>uint8_t</b> as parameter
+                                  - <b>WLAN_GENERAL_PARAM_OPT_AP_TX_POWER</b>
+                                          Get AP mode Tx power level \n
+                                          Number between 0-15, as dB offset from max power (0 indicates MAX power) \n
+                                          This options takes <b>uint8_t</b> as parameter
+                              - <b>SL_WLAN_CFG_P2P_PARAM_ID</b>
+                                  - <b>WLAN_P2P_OPT_CHANNEL_N_REGS</b> \n
+                                         Get P2P Channels. \n
+                                         listen channel (either 1/6/11 for 2.4GHz) \n
+                                         listen regulatory class (81 for 2.4GHz)   \n
+                                         oper channel (either 1/6/11 for 2.4GHz)   \n
+                                         oper regulatory class (81 for 2.4GHz)     \n
+                                         listen channel and regulatory class will determine the device listen channel during p2p find listen phase \n
+                                         oper channel and regulatory class will determine the operating channel preferred by this device (in case it is group owner this will be the operating channel) \n
+                                         channels should be one of the social channels (1/6/11). In case no listen/oper channel selected, a random 1/6/11 will be selected. \n
+                                         This option takes pointer to <b>uint8_t[4]</b> as parameter
+
+        \param[out] pConfigLen - The length of the allocated memory as input, when the
+                                            function complete, the value of this parameter would be
+                                            the len that actually read from the device.
+                                            If the device return length that is longer from the input
+                                            value, the function will cut the end of the returned structure
+                                            and will return SL_ESMALLBUF.
+
+
+        \param[out] pValues - get configurations values
+
+        \sa   sl_WlanSet
+
+        \note
+
+        \warning
+
+        \par    Examples:
+        \par
+              <b> WLAN_GENERAL_PARAM_OPT_SCAN_PARAMS: </b>
+        \code
+              slWlanScanParamCommand_t ScanParamConfig;
+              uint16_t Option = WLAN_GENERAL_PARAM_OPT_SCAN_PARAMS;
+              uint16_t OptionLen = sizeof(slWlanScanParamCommand_t);
+              sl_WlanGet(SL_WLAN_CFG_GENERAL_PARAM_ID ,&Option,&OptionLen,(uint8_t *)&ScanParamConfig);
+        \endcode
+        \par
+               <b> WLAN_GENERAL_PARAM_OPT_AP_TX_POWER: </b>
+        \code
+               _i8 TXPower = 0;
+               _u16 Option = WLAN_GENERAL_PARAM_OPT_AP_TX_POWER;
+               _u16 OptionLen = sizeof(_i8);
+           sl_WlanGet(SL_WLAN_CFG_GENERAL_PARAM_ID ,&Option,&OptionLen,(_u8 *)&TXPower);
+        \endcode
+        \par   
+           <b> WLAN_GENERAL_PARAM_OPT_STA_TX_POWER: </b>
+        \code           
+           _i8 TXPower = 0;
+           _u16 Option = WLAN_GENERAL_PARAM_OPT_STA_TX_POWER;
+           _u16 OptionLen = sizeof(_i8);
+
+               sl_WlanGet(SL_WLAN_CFG_GENERAL_PARAM_ID ,&Option,&OptionLen,(uint8_t *)&TXPower);
+        \endcode
+        \par
+               <b> WLAN_P2P_OPT_DEV_TYPE: </b>
+        \code
+               int8_t device_type[18];
+               uint16_t len = 18;
+               uint16_t config_opt = WLAN_P2P_OPT_DEV_TYPE;
+               sl_WlanGet(SL_WLAN_CFG_P2P_PARAM_ID, &config_opt , &len, (uint8_t* )device_type);
+        \endcode
+        \par
+               <b> WLAN_AP_OPT_SSID: </b>
+        \code
+               int8_t ssid[32];
+               uint16_t len = 32;
+               uint16_t  config_opt = WLAN_AP_OPT_SSID;
+               sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt , &len, (uint8_t* )ssid);
+        \endcode
+        \par
+               <b> WLAN_GENERAL_PARAM_OPT_COUNTRY_CODE: </b>
+        \code
+               int8_t country[3];
+               uint16_t len = 3;
+               uint16_t  config_opt = WLAN_GENERAL_PARAM_OPT_COUNTRY_CODE;
+               sl_WlanGet(SL_WLAN_CFG_GENERAL_PARAM_ID, &config_opt, &len, (uint8_t* )country);
+        \endcode
+        \par
+               <b> WLAN_AP_OPT_CHANNEL: </b>
+        \code
+               int8_t channel;
+               uint16_t len = 1;
+               uint16_t  config_opt = WLAN_AP_OPT_CHANNEL;
+               sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt, &len, (uint8_t* )&channel);
+        \endcode
+        \par
+               <b> WLAN_AP_OPT_HIDDEN_SSID: </b>
+        \code
+              uint8_t hidden;
+              uint16_t len = 1;
+              uint16_t  config_opt = WLAN_AP_OPT_HIDDEN_SSID;
+              sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt, &len, (uint8_t* )&hidden);
+        \endcode
+        \par
+               <b> WLAN_AP_OPT_SECURITY_TYPE: </b>
+        \code
+             uint8_t sec_type;
+             uint16_t len = 1;
+             uint16_t  config_opt = WLAN_AP_OPT_SECURITY_TYPE;
+             sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt, &len, (uint8_t* )&sec_type);
+        \endcode
+        \par
+               <b> WLAN_AP_OPT_PASSWORD: </b>
+        \code
+             uint8_t password[64];
+             uint16_t len = 64;
+             memset(password,0,64);
+             uint16_t config_opt = WLAN_AP_OPT_PASSWORD;
+             sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt, &len, (uint8_t* )password);
+
+        \endcode
+        \par
+               <b> WLAN_P2P_OPT_CHANNEL_N_REGS: </b>
+        \code
+           uint16_t listen_channel,listen_reg,oper_channel,oper_reg;
+           uint16_t len = 4;
+           uint16_t  config_opt = WLAN_P2P_OPT_CHANNEL_N_REGS;
+           uint8_t channel_n_regs[4];
+           sl_WlanGet(SL_WLAN_CFG_P2P_PARAM_ID, &config_opt, &len, (uint8_t* )channel_n_regs);
+           listen_channel = channel_n_regs[0];
+           listen_reg = channel_n_regs[1];
+           oper_channel = channel_n_regs[2];
+           oper_reg = channel_n_regs[3];
+        \endcode
+    */
+
+#if _SL_INCLUDE_FUNC(sl_WlanGet)
+    int16_t sl_WlanGet(const uint16_t ConfigId, uint16_t *pConfigOpt,uint16_t *pConfigLen, uint8_t *pValues);
+#endif
+
+private:
+
+    cc3100_driver           &_driver;
+    cc3100_wlan_rx_filters  &_wlan_filters;
+
+    /*!
+
+     Close the Doxygen group.
+     @}
+
+     */
+
+};//class
+
+}//namespace mbed_cc3100
+
+#endif    /*  __WLAN_H__ */
+
+
diff -r 241bff9fe406 -r a8c249046181 simplelink_V2/cc3100_wlan_rx_filters.h
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/simplelink_V2/cc3100_wlan_rx_filters.h	Thu Sep 03 14:02:37 2015 +0000
@@ -0,0 +1,1012 @@
+/*
+ * wlan_rx_filters.h - CC31xx/CC32xx Host Driver Implementation
+ *
+ * Copyright (C) 2014 Texas Instruments Incorporated - http://www.ti.com/
+ *
+ *
+ *  Redistribution and use in source and binary forms, with or without
+ *  modification, are permitted provided that the following conditions
+ *  are met:
+ *
+ *    Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ *
+ *    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.
+ *
+ *    Neither the name of Texas Instruments Incorporated nor the names of
+ *    its contributors may be used to endorse or promote products derived
+ *    from this software without specific prior written permission.
+ *
+ *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ *  "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 COPYRIGHT
+ *  OWNER OR CONTRIBUTORS 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 files                                                             */
+/*****************************************************************************/
+#include "cc3100_simplelink.h"
+
+#ifndef RX_FILTERS_PREPROCESSOR_CLI_IF_H_
+#define RX_FILTERS_PREPROCESSOR_CLI_IF_H_
+
+#include "cc3100_driver.h"
+
+/*****************************************************************************/
+/* Macro declarations                                                                        */
+/*****************************************************************************/
+
+/*!
+ * \def SL_RX_FILTER_MAX_FILTERS
+ *  The Max number of filters for 64 filters
+ */
+#define SL_RX_FILTER_MAX_FILTERS 64
+
+/*!
+ * \def SL_RX_FILTER_MAX_PRE_PREPARED_FILTERS_SETS
+ * The Max number of software filters
+ */
+#define SL_RX_FILTER_MAX_PRE_PREPARED_FILTERS_SETS      (32)
+/*!
+ * \def SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS
+ *
+ */
+#define SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS          (2)
+/*!
+ * \def SL_RX_FILTER_NUM_OF_FILTER_PAYLOAD_ARGS
+ *
+ */
+#define SL_RX_FILTER_NUM_OF_FILTER_PAYLOAD_ARGS         (2)
+/*!
+ * \def SL_RX_FILTER_NUM_OF_FILTER_PAYLOAD_ARGS
+ *
+ */
+#define SL_RX_FILTER_NUM_OF_COMBINATION_TYPE_ARGS       (2)
+/*!
+ * \def SL_RX_FILTER_LENGTH_OF_REGX_PATTERN_LENGTH
+ *
+ */
+#define SL_RX_FILTER_LENGTH_OF_REGX_PATTERN_LENGTH      (32)
+
+
+/*  List of possible error numbers */
+#define RXFL_OK                                                (0) /*  O.K */
+#define RXFL_OUTPUT_OR_INPUT_BUFFER_LENGTH_TOO_SMALL           (76) /* ! The output buffer length is smaller than required for that operation */
+#define RXFL_DEPENDENT_FILTER_SOFTWARE_FILTER_NOT_FIT          (75) /* Node filter can't be child of software filter and vice_versa */
+#define RXFL_DEPENDENCY_IS_NOT_PERSISTENT                      (74) /*  Dependency filter is not persistent */
+#define RXFL_SYSTEM_STATE_NOT_SUPPORTED_FOR_THIS_FILTER        (72) /*  System state is not supported */
+#define RXFL_TRIGGER_USE_REG5_TO_REG8                          (71) /*  Only counters 5 - 8 are allowed, for Tigger */
+#define RXFL_TRIGGER_USE_REG1_TO_REG4                          (70) /*  Only counters 1 - 4 are allowed, for trigger */
+#define RXFL_ACTION_USE_REG5_TO_REG8                           (69) /*  Only counters 5 - 8 are allowed, for action */
+#define RXFL_ACTION_USE_REG1_TO_REG4                           (68) /*  Only counters 1 - 4 are allowed, for action */
+#define RXFL_FIELD_SUPPORT_ONLY_EQUAL_AND_NOTEQUAL             (67) /*  Rule compare function Id is out of range */
+#define RXFL_WRONG_MULTICAST_BROADCAST_ADDRESS                 (66) /*  The address should be of type mutlicast or broadcast */
+#define RXFL_THE_FILTER_IS_NOT_OF_HEADER_TYPE                  (65) /*  The filter should be of header type */
+#define RXFL_WRONG_COMPARE_FUNC_FOR_BROADCAST_ADDRESS          (64) /*  The compare funcion is not suitable for broadcast address */
+#define RXFL_WRONG_MULTICAST_ADDRESS                           (63) /*  The address should be of muticast type */
+#define RXFL_DEPENDENT_FILTER_IS_NOT_PERSISTENT                (62) /*  The dependency filter is not persistent */
+#define RXFL_DEPENDENT_FILTER_IS_NOT_ENABLED                   (61) /*  The dependency filter is not enabled */
+#define RXFL_FILTER_HAS_CHILDS                                 (60) /*  The filter has childs and can't be removed */
+#define RXFL_CHILD_IS_ENABLED                                  (59) /*  Can't disable filter while the child is enabled */
+#define RXFL_DEPENDENCY_IS_DISABLED                            (58) /*  Can't enable filetr in case its depndency filter is disabled */
+#define RXFL_NUMBER_OF_CONNECTION_POINTS_EXCEEDED              (52) /*  Number of connection points exceeded */
+#define RXFL_DEPENDENT_FILTER_DEPENDENCY_ACTION_IS_DROP        (51) /*  The dependent filter has Drop action, thus the filter can't be created */
+#define RXFL_FILTER_DO_NOT_EXISTS                              (50) /*  The filter doesn't exists */
+#define RXFL_DEPEDENCY_NOT_ON_THE_SAME_LAYER                   (49) /*  The filter and its dependency must be on the same layer */
+#define RXFL_NUMBER_OF_ARGS_EXCEEDED                           (48) /*  Number of arguments excceded */
+#define RXFL_ACTION_NO_REG_NUMBER                              (47) /*  Action require counter number */
+#define RXFL_DEPENDENT_FILTER_LAYER_DO_NOT_FIT                 (46) /*  the filter and its dependency should be from the same layer */
+#define RXFL_DEPENDENT_FILTER_SYSTEM_STATE_DO_NOT_FIT          (45) /*  The filter and its dependency system state don't fit  */
+#define RXFL_DEPENDENT_FILTER_DO_NOT_EXIST_2                   (44) /*  The parent filter don't exist  */
+#define RXFL_DEPENDENT_FILTER_DO_NOT_EXIST_1                   (43) /*  The parent filter is null */
+#define RXFL_RULE_HEADER_ACTION_TYPE_NOT_SUPPORTED             (42) /*  The action type is not supported */
+#define RXFL_RULE_HEADER_TRIGGER_COMPARE_FUNC_OUT_OF_RANGE     (41) /*  The Trigger comparision function is out of range */
+#define RXFL_RULE_HEADER_TRIGGER_OUT_OF_RANGE                  (40) /*  The Trigger is out of range */
+#define RXFL_RULE_HEADER_COMPARE_FUNC_OUT_OF_RANGE             (39) /*  The rule compare function is out of range */
+#define RXFL_FRAME_TYPE_NOT_SUPPORTED                          (38) /*  ASCII frame type string is illegal */
+#define RXFL_RULE_FIELD_ID_NOT_SUPPORTED                       (37) /*  Rule field ID is out of range */
+#define RXFL_RULE_HEADER_FIELD_ID_ASCII_NOT_SUPPORTED          (36) /*  This ASCII field ID is not supported */
+#define RXFL_RULE_HEADER_NOT_SUPPORTED                         (35) /*  The header rule is not supported on current release */
+#define RXFL_RULE_HEADER_OUT_OF_RANGE                          (34) /*  The header rule is out of range */
+#define RXFL_RULE_HEADER_COMBINATION_OPERATOR_OUT_OF_RANGE     (33) /*  Combination function Id is out of ramge */
+#define RXFL_RULE_HEADER_FIELD_ID_OUT_OF_RANGE                 (32) /*  rule field Id is out of range */
+#define RXFL_UPDATE_NOT_SUPPORTED                              (31) /*  Update not supported */
+#define RXFL_NO_FILTERS_ARE_DEFINED                            (24) /*  No filters are defined in the system */
+#define RXFL_NUMBER_OF_FILTER_EXCEEDED                         (23) /*  Number of max filters excceded */
+
+
+/******************************************************************************/
+/* Type declarations                                                                         */
+/******************************************************************************/
+
+/*!
+
+
+ * \typedef SlrxFilterID_t
+ * Unique filter ID which is allocated by the system , negative number means error
+ */
+typedef  int8_t    SlrxFilterID_t;
+
+
+/*!
+ * \typedef SlrxFilterCompareMask_t
+ * The mask is used for the rule comparison function
+ */
+typedef uint8_t   SlrxFilterCompareMask_t;
+
+/*!
+ * \typedef SlrxFilterIdMask_t
+ *  Representation of filters Id as a bit field
+ *  The bit field is used to declare which filters are involved
+ *  in operation. Number of filter can be up to 128 filters. i.e. 128 bits are needed.
+ *  On the current release, up to 64 filters can be defined.
+ */
+typedef uint8_t   SlrxFilterIdMask_t[128/8];
+
+/*!
+ * \typedef SlrxFilterPrePreparedFilters_t
+ *  Describes the supported software filter sets,
+ */
+typedef uint8_t  SlrxFilterPrePreparedFilters_t;
+#define SL_ARP_AUTO_REPLY_PRE_PREPARED_FILTERS       (0)
+#define SL_MULTICASTSIPV4_DROP_PREPREPARED_FILTERS   (1)
+#define SL_MULTICASTSIPV6_DROP_PREPREPARED_FILTERS   (2)
+#define SL_MULTICASTSWIFI_DROP_PREPREPARED_FILTERS   (3)
+
+
+
+/*!
+ * \typedef SlrxFilterPrePreparedFiltersMask_t
+ *  Describes the supported software filter sets,
+ *  each bit represents different software filter set
+ *  The filter sets are defined at SlrxFilterPrePreparedFilters_t
+ */
+typedef uint8_t   SlrxFilterPrePreparedFiltersMask_t[SL_RX_FILTER_MAX_PRE_PREPARED_FILTERS_SETS/8];
+
+
+/*! \typedef SlrxFilterRegxPattern_t
+ * The struct contains the regular expression pattern which is used in case of payload rule.
+ * Not supported in the current release
+ */
+typedef struct SlrxFilterRegxPattern_t {
+    uint8_t x[SL_RX_FILTER_LENGTH_OF_REGX_PATTERN_LENGTH];
+} SlrxFilterRegxPattern_t;
+
+
+/*! \typedef SlrxFilterAsciiArg_t
+ * The buffer is used to provide container for ASCII argument, which may be used in case of HEADER rule.
+ * example for ASCII argument can be : IP = 256.0.67.1
+ */
+typedef uint8_t SlrxFilterAsciiArg_t;
+
+
+/*! \typedef SlrxFilterBinaryArg_t
+ * The buffer provides container for binary argument, which  may be used in case of HEADER rule
+ */
+typedef uint8_t   SlrxFilterBinaryArg_t ;
+
+
+/*! \typedef SlrxFilterActionArg_t
+ *  Provides container for the filter action argument.
+ *  for example: in case action is to send automatic response , the argument is the template to be used for the automatic response.
+ *
+ *
+ */
+typedef  uint8_t SlrxFilterActionArg_t ;
+
+
+
+/*! \typedef SlrxFilterOffset_t
+ * The offset relative to the packet payload start location.
+ * Not supported on current release
+ */
+typedef uint32_t   SlrxFilterOffset_t;
+
+
+
+/*! \typedef SlrxFilterRuleType_t
+ * Enumerates the different filter types.
+ * On the current release only HEADER and COMBINATION are supported.
+ */
+typedef uint8_t SlrxFilterRuleType_t;
+/* possible values for SlrxFilterRuleType_t */
+#define HEADER                    (0)
+#define COMBINATION               (1)
+#define EXACT_PATTERN             (2)
+#define LIKELIHOOD_PATTERN        (3)
+#define ALWAYS_TRUE               (4)
+#define NUM_OF_FILTER_TYPES       (5)
+
+
+/*! \typedef SlrxFilterFlags_t
+ * Bit field which sets the behaviour of the RX filter
+ *
+ */
+
+#define RX_FILTER_BINARY          (0x1)
+#define RX_FILTER_PERSISTENT      (0x8)
+#define RX_FILTER_ENABLE          (0x10)
+
+typedef union SlrxFilterFlags_t {
+
+    /* struct
+    { */
+    /*!
+     *  The filter argument can be set as binary argument or ASCII arguments.
+     *  When the bit is on the argument are binary.
+     */
+    /* uint8_t Binary: 1; */
+    /*!
+     *
+     */
+    /* uint8_t AutoSort : 1; */
+    /*!
+     *
+     */
+    /* uint8_t AutoFaultDetect : 1; */
+    /*!
+     *  When the bit is on it means the the node is enabled .
+    */
+    /* uint8_t Enabled : 1; */
+    /* uint8_t padding : 3; */
+    /*
+    };*/
+
+    uint8_t IntRepresentation;
+
+} SlrxFilterFlags_t;
+
+/*! \typedef SlrxFilterCompareFunction_t
+ * Used as comparison function for the header type arguments
+ *
+ */
+typedef uint8_t SlrxFilterCompareFunction_t;
+/* Possible values for SlrxFilterCompareFunction_t */
+#define COMPARE_FUNC_IN_BETWEEN                 (0)
+#define COMPARE_FUNC_EQUAL                      (1)
+#define COMPARE_FUNC_NOT_EQUAL_TO               (2)
+#define COMPARE_FUNC_NOT_IN_BETWEEN             (3)
+#define COMPARE_FUNC_NUM_OF_FILTER_COMPARE_FUNC (4)
+
+/*! \typedef SlrxFilterCompareFunction_t
+ * Used as comparison function for the header type arguments
+ *
+ */
+typedef uint8_t SlrxTriggerCompareFunction_t;
+/* Possible values for SlrxTriggerCompareFunction_t */
+#define TRIGGER_COMPARE_FUNC_EQUAL              (0)
+/*   arg1 == protocolVal ,not supported in current release */
+#define TRIGGER_COMPARE_FUNC_NOT_EQUAL_TO       (1)
+/*   arg1 == protocolVal */
+#define TRIGGER_COMPARE_FUNC_SMALLER_THAN       (2)
+/*   arg1 == protocolVal */
+#define TRIGGER_COMPARE_FUNC_BIGGER_THAN        (3)
+/* definition */
+#define TRIGGER_COMPARE_FUNC_NUM_OF_FILTER_COMPARE_FUNC (4)
+
+
+/*! \typedef SlrxFilterHdrField_t
+ * Provides list of possible header types which may be defined as part of the rule
+ *
+ */
+typedef uint8_t SlrxFilterHdrField_t;
+/* Possible values for SlrxFilterHdrField_t */
+#define NULL_FIELD_ID_TYPE           (0)
+/* 802.11 control\data\management */
+#define FRAME_TYPE_FIELD             (1)
+/*  802.11 beacon\probe\.. */
+#define FRAME_SUBTYPE_FIELD          (2)
+/*  802.11 bssid type */
+#define BSSID_FIELD                  (3)
+/* */
+#define MAC_SRC_ADDRESS_FIELD        (4)
+/* */
+#define MAC_DST_ADDRESS_FIELD        (5)
+/* */
+#define FRAME_LENGTH_FIELD           (6)
+/* */
+#define PROTOCOL_TYPE_FIELD          (7)
+/* */
+#define IP_VERSION_FIELD             (8)
+/* TCP / UDP */
+#define IP_PROTOCOL_FIELD            (9)
+/* */
+#define IPV4_SRC_ADRRESS_FIELD       (10)
+/* */
+#define IPV4_DST_ADDRESS_FIELD       (11)
+/* */
+#define IPV6_SRC_ADRRESS_FIELD       (12)
+/* */
+#define IPV6_DST_ADDRESS_FIELD       (13)
+/* */
+#define SRC_PORT_FIELD               (14)
+/* */
+#define DST_PORT_FIELD               (15)
+/* Definition */
+#define NUM_OF_FIELD_NAME_FIELD      (16)
+
+/*! \union SlrxFilterHeaderArg_t
+ * The structure holds the header ARGS which are used in case of HDR rule.
+ */
+/* -- 36 bytes */
+typedef union SlrxFilterHeaderArg_t {
+    /*----------------------------- Large size ---------------------------------*/
+    /*! buffer for binary arguments, number of argument may be up to SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS
+     * example : IPV6 16 bytes, 39 characters
+     * ipv6 Ascii address: 2001:0db8:3c4d:0015:0000:0000:abcd:ef12
+     */
+
+    SlrxFilterBinaryArg_t RxFilterDB16BytesRuleArgs[SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS][16 ]; /*  Binary Values for comparition */
+    /*! buffer for ASCII arguments, number of argument may be up to SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS
+     * example : IPV6 16 bytes, 39 characters
+     * ipv6 Ascii address: 2001:0db8:3c4d:0015:0000:0000:abcd:ef12
+     * Ascii format for ipV6 is not supported
+     */
+    /*----------------------------- Medium size ---------------------------------*/
+    /*! buffer for binary arguments, number of argument may be up to SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS
+     * MAC address: 6 bytes, 17 chars
+     */
+    SlrxFilterBinaryArg_t RxFilterDB6BytesRuleArgs[SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS][6]; /*  Binary Values for comparition */
+    /*!
+     * ! buffer for ASCII arguments, number of argument may be up to SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS
+     *  IP address: 4 bytes, 15 chars
+     *  2 bytes are added for padding
+     */
+    SlrxFilterAsciiArg_t RxFilterDB18BytesAsciiRuleArgs[SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS][18]; /* Ascii Values for comparison */
+    /*----------------------------- Small size ---------------------------------*/
+    /*! buffer for binary arguments, number of argument may be up to SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS
+     *  IP address: 4 bytes, 15 chars
+     *  Port: 2 bytes, chars: 5 chars
+     */
+    SlrxFilterBinaryArg_t RxFilterDB4BytesRuleArgs[SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS][4]; /*  Binary Values for comparison */
+    /*! buffer for ASCII arguments, number of argument may be up to SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS
+     * Port: 2 bytes, chars: 5 chars
+     */
+    SlrxFilterAsciiArg_t RxFilterDB5BytesRuleAsciiArgs[SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS][5]; /* Ascii Values for comparison */
+    /*----------------------------- 1 byte size ---------------------------------*/
+    /*! buffer for binary arguments, number of argument may be up to SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS
+     */
+    SlrxFilterBinaryArg_t RxFilterDB1BytesRuleArgs[SL_RX_FILTER_NUM_OF_FILTER_HEADER_ARGS][1]; /*  Binary Values for comparison */
+} SlrxFilterHeaderArg_t;
+
+
+
+/*! \typedef SlrxFilterRuleHeaderArgsAndMask_t
+ * Structure which defines the Header Args and mask
+ */
+/* -- 52 bytes */
+typedef struct SlrxFilterRuleHeaderArgsAndMask_t {
+    /*! Argument for the comparison function */
+    /* -- 36 byte */
+    SlrxFilterHeaderArg_t RuleHeaderArgs;
+
+    /*! the mask is used in order to enable partial comparison,
+     *  Use the 0xFFFFFFFF in case you don't want to use mask
+     */
+    /* -- 16 bytes */
+    SlrxFilterCompareMask_t RuleHeaderArgsMask[16];
+
+} SlrxFilterRuleHeaderArgsAndMask_t;
+
+/*! \typedef SlrxFilterHeaderType_t
+ * Structure which defines the Header rule
+ * The header rule defines compare function on the protocol header
+ * For example destMacAddre is between ( 12:6::78:77,  12:6::78:90 )
+ *
+ */
+/* -- 56 byte */
+typedef struct SlrxFilterHeaderType_t {
+    /*! see :: SlrxFilterRuleHeaderArgsAndMask_t */
+    /* -- 52 bytes */
+    SlrxFilterRuleHeaderArgsAndMask_t RuleHeaderArgsAndMask;
+
+    /*! Packet HDR field which will be compared to the argument */
+    /* -- 1 byte */
+    SlrxFilterHdrField_t RuleHeaderfield;
+
+    /* -- 1 byte */
+    /*! type of the comparison function
+     * see :: SlrxFilterCompareFunction_t
+     */
+    SlrxFilterCompareFunction_t RuleCompareFunc;
+
+    /*! padding */
+    /* -- 2 bytes */
+    uint8_t RulePadding[2];
+
+} SlrxFilterHeaderType_t;
+
+/*! \typedef SlrxFilterPayloadType_t
+ *  Structure which defines payload rule.
+ *  Not supported on current release.
+ */
+/* -- 40 byte  */
+typedef struct SlrxFilterPayloadType_t {
+    /*! Not supported on current release */
+    /* -- 32 byte */
+    SlrxFilterRegxPattern_t RegxPattern;
+    /*! Not supported on current release */
+    /* -- 4 byte */
+    SlrxFilterOffset_t LowerOffset;
+    /*! Not supported on current release */
+    /* -- 4 byte */
+    SlrxFilterOffset_t UpperOffset;
+} SlrxFilterPayloadType_t;
+
+/*! \typedef SlrxFilterCombinationTypeOperator_t
+ * Enumerate the optional operators for the combination type
+ * filterID1 is located in  the first arg , filterId2 is the second arg,see ::SlrxFilterCombinationType_t.CombinationFilterId
+ */
+typedef uint8_t SlrxFilterCombinationTypeOperator_t;
+/* Possible values for SlrxFilterCombinationTypeOperator_t */
+/*! !filterID1 */
+#define COMBINED_FUNC_NOT     (0)
+/*! filterID1 && filterID2 */
+#define COMBINED_FUNC_AND     (1)
+/*! filterID1 && filterID2 */
+#define COMBINED_FUNC_OR      (2)
+
+/*! \typedef SlrxFilterCombinationType_t
+ * Defines the structure which define the combination type filter
+ * The combined filter enable to make operation on one or two filter,
+ * for example !filterId1 or and(filterId2,filterId3).
+ *
+ */
+/* -- 4  byte */
+typedef struct SlrxFilterCombinationType_t {
+    /* ! combination operator */
+    /*  -- 1 byte */
+    SlrxFilterCombinationTypeOperator_t CombinationTypeOperator;
+    /* ! filterID, may be one or two depends on the combination operator type */
+    /*  -- 2  byte */
+    SlrxFilterID_t CombinationFilterId[SL_RX_FILTER_NUM_OF_COMBINATION_TYPE_ARGS];
+    /* ! Padding */
+    /*  -- 1  byte */
+    uint8_t Padding;
+} SlrxFilterCombinationType_t;
+
+
+/*! \typedef SlrxFilterRule_t
+ * Rule structure composed of behavioral flags and the filter rule definitions
+ *
+ */
+/*  -- 56  byte */
+typedef union SlrxFilterRule_t {
+    /* ! Header type rule , see explanation on the ::SlrxFilterHeaderType_t structure */
+    /*  -- 56 byte */
+    SlrxFilterHeaderType_t HeaderType;
+    /* ! Payload rule, not supported in current release */
+    /*  -- 40 byte */
+    SlrxFilterPayloadType_t PayLoadHeaderType; /* future for exact pattern or like hood pattern */
+    /* ! Combined type rule , see explanation in ::SlrxFilterCombinationType_t structure */
+    /*  -- 4  byte */
+    SlrxFilterCombinationType_t CombinationType;
+} SlrxFilterRule_t;
+
+/*! \typedef SlrxFilterTriggerRoles_t
+ * Bit field which represents the roleId possible values
+ * In the current release only Station/AP roles are supported.
+ */
+#define RX_FILTER_ROLE_AP                            (1)
+#define RX_FILTER_ROLE_STA                           (2)
+#define RX_FILTER_ROLE_PROMISCUOUS                   (4)
+#define RX_FILTER_ROLE_NULL                          (0)
+
+typedef union SlrxFilterTriggerRoles_t {
+    /*     struct                                                            */
+    /*     {                                                                 */
+    /*         uint8_t RoleAP :1;                                      */
+    /*         uint8_t RoleStation :1;                                 */
+    /* The filter is activated only in Promiscuous mode          */
+    /*         uint8_t PromiscuousMode :1;                             */
+    /*         uint8_t RoleReserved :5;                                */
+    /*     };                                                                */
+    /* ! Bit fiels of the Filter role    */
+    uint8_t IntRepresentation;
+
+} SlrxFilterTriggerRoles_t;
+
+/*! \typedef SlrxFilterTriggerConnectionStates_t
+ * Bit field representing the possible values of the When section of the rule
+ *
+ */
+#define RX_FILTER_CONNECTION_STATE_STA_CONNECTED     (1)
+#define RX_FILTER_CONNECTION_STATE_STA_NOT_CONNECTED (2)
+#define RX_FILTER_CONNECTION_STATE_STA_HAS_IP        (4)
+#define RX_FILTER_CONNECTION_STATE_STA_HAS_NO_IP     (8)
+
+typedef union SlrxFilterTriggerConnectionStates_t {
+    /*     struct */
+    /*     {      */
+    /*         uint8_t RoleStationWiFiConnected :1;  */
+    /*         uint8_t RoleStationWiFiDisconneted:1; */
+    /*         uint8_t RoleStationWiFiHasIp:1;       */
+    /*         uint8_t RoleStationWiFiHasNoIp:1;     */
+    /*         uint8_t RoleStationWiFiSocketOpened:1; */
+    /*         uint8_t RoleStationWiFiSocketclosed:1; */
+    /*     }; */
+    /*  */
+    /* ! */
+    uint8_t IntRepresentation;
+
+} SlrxFilterTriggerConnectionStates_t;
+
+/*! \typedef SlrxFilterDBTriggerArg_t
+ * Provides container for entering the filter 'when' argument.
+ * The current release support 'When rules' which has no arguments.
+ * For example :
+ *  When connect to specific AP -- the AP bssid is the argument.
+ *
+ */
+typedef uint32_t  SlrxFilterDBTriggerArg_t;
+
+
+
+/*! \typedef  SlrxFilterCounterId_t
+ * the counter ID we have 4 counters
+ */
+typedef uint8_t SlrxFilterCounterId_t;
+/* Possible values for SlrxFilterCounterId_t */
+#define NO_TRIGGER                                  (0)
+#define RX_FILTER_COUNTER1                          (1)
+#define RX_FILTER_COUNTER2                          (2)
+#define RX_FILTER_COUNTER3                          (3)
+#define RX_FILTER_COUNTER4                          (4)
+#define RX_FILTER_COUNTER5                          (5)
+#define RX_FILTER_COUNTER6                          (6)
+#define RX_FILTER_COUNTER7                          (7)
+#define RX_FILTER_COUNTER8                          (8)
+#define MAX_RX_FILTER_COUNTER                       (9)
+
+
+
+/*! \typedef SlrxFilterActionArgs_t
+ * Possible value for filter action args
+ *
+ */
+
+typedef uint8_t  SlrxFilterActionArgs_t;
+/* Possible values for SlrxFilterActionArgs_t */
+#define ACTION_ARG_REG_1_4                          (0)
+/* ! Can be use as counter */
+#define ACTION_ARG_TEMPLATE                         (1)
+/* ! Can be use as counter */
+#define ACTION_ARG_EVENT                            (2)
+
+/* ! GPIO number */
+#define ACTION_ARG_GPIO                             (4)
+/*!
+ * \def SL_RX_FILTER_NUM_OF_BYTES_FOR_ACTIONS_ARGS
+ *
+ */
+#define SL_RX_FILTER_NUM_OF_BYTES_FOR_ACTIONS_ARGS  (5)
+
+
+
+
+/*! \typedef SlrxFilterTrigger_t
+ * The filter trigger, determine when the filter is triggered,
+ * The filter is triggered in the following condition :\n
+ * 1. The filter parent is triggered\n
+ * 2. The requested connection type exists, i.e. wlan_connect\n
+ * 3. The filter role is the same as the system role\n
+ *
+ */
+/*  --  12 byte */
+typedef struct SlrxFilterTrigger_t {
+    /*! The parent filter ID, this is the way to build filter tree. */
+    /*  NULL           value means  tree root.
+    */
+    /*  --  1 byte */
+    SlrxFilterID_t ParentFilterID;
+    /* ! See ::SlrxFilterCounterId_t explanation */
+    /*  -- 1 byte */
+    SlrxFilterCounterId_t Trigger;
+    /* ! See :: SlrxFilterTriggerConnectionStates_t */
+    /*  -- 1 byte */
+    SlrxFilterTriggerConnectionStates_t TriggerArgConnectionState;
+    /* ! See ::SlrxFilterTriggerRoles_t */
+    /*  -- 1 byte */
+    SlrxFilterTriggerRoles_t TriggerArgRoleStatus;
+    /* ! The Trigger arguments are in the same order as the Trigger bit field order. */
+    /*  --  4 byte */
+    SlrxFilterDBTriggerArg_t TriggerArg;
+    /** The compare function which will be operate for each bit that is turned on in the ::SlrxFilterTrigger_t.Trigger field,
+     * for example , in case the second bit in the Trigger function is on the second function in the list will be executed.
+     *
+    */
+    /*  --  1 byte */
+    SlrxTriggerCompareFunction_t TriggerCompareFunction;
+
+    /* ! padding */
+    /*  --  3 byte */
+    uint8_t Padding[3];
+} SlrxFilterTrigger_t;
+
+/*! \typedef SlrxFilterActionType_t
+ *  The actions are executed only if the filter is matched,\n
+ *  In case of false match the packet is transfered to the HOST. \n
+ *  The action is composed of bit field structure,
+ *  up to 2 actions can be defined per filter.
+ *
+ */
+#define RX_FILTER_ACTION_NULL               (0x0)
+#define RX_FILTER_ACTION_DROP               (0x1)
+#define RX_FILTER_ACTION_GPIO               (0x2)
+#define RX_FILTER_ACTION_ON_REG_INCREASE    (0x4)
+#define RX_FILTER_ACTION_ON_REG_DECREASE    (0x8)
+#define RX_FILTER_ACTION_ON_REG_RESET       (0x10)
+#define RX_FILTER_ACTION_SEND_TEMPLATE      (0x20) /* unsupported */
+#define RX_FILTER_ACTION_EVENT_TO_HOST      (0x40) /* unsupported */
+
+typedef union SlrxFilterActionType_t {
+    /*     struct */
+    /*     { */
+    /* ! No action to execute the packet is dropped,drop is always on leaf. */
+    /* ! If not dropped ,The packet is passed to the next filter or in case it is the last filter to the host */
+    /*         uint8_t ActionDrop : 1; */
+    /* ! Not Supported in the current release */
+    /*         uint8_t ActionGpio : 1; */
+    /*! action can increase counter registers.
+     *  1 = Increase
+     *  2 = decrease
+     *  3 = reset
+     */
+    /*         uint8_t ActionOnREGIncrease : 1; */
+    /*         uint8_t ActionOnREGDecrease : 1; */
+    /*         uint8_t ActionOnREGReset : 1;    */
+
+    /* ! Not Supported in the current release */
+    /*         uint8_t ActionSendTemplate : 1; */
+    /* ! Not Supported in the current release */
+    /*         uint8_t ActionEventToHost: 1;   */
+    /*         uint8_t padding: 1;             */
+    /*     }; */
+
+    uint8_t IntRepresentation;
+
+} SlrxFilterActionType_t;
+
+/*! \typedef SlrxFilterAction_t
+ * Several actions can be defined,\n
+ * The action is executed in case the filter rule is matched.
+ */
+/*  -- 8 byte   */
+typedef struct SlrxFilterAction_t {
+    /*  -- 1 byte */
+    /* ! Determine which actions are supported */
+    SlrxFilterActionType_t ActionType;
+    /* ! Buffer for the action arguments */
+    /**
+     * <b>location 0</b> - The counter to increase
+     *     In case the action is of type "increase" the arg will contain the counter number,
+     *     The counter number values are as in  ::SlrxFilterCounterId_t.\n
+     * <b>location 1</b> - The template arg.\n
+     * <b>location 2</b> - The event arg.\n
+     *
+     */
+    /*  -- 5 byte */
+    SlrxFilterActionArg_t ActionArg[SL_RX_FILTER_NUM_OF_BYTES_FOR_ACTIONS_ARGS];
+
+    /* ! Padding */
+    /* - 2 Bytes */
+    uint8_t Padding[2];
+
+} SlrxFilterAction_t;
+
+
+/*! \struct _WlanRxFilterOperationCommandBuff_t
+ *  The structure is used for the interface HOST NWP.\n
+ *  The supported operation : \n
+ *   ::ENABLE_DISABLE_RX_FILTER,\n
+ *   ::REMOVE_RX_FILTER,\n
+ *
+ */
+/*  20 bytes */
+typedef struct _WlanRxFilterOperationCommandBuff_t {
+    /*  -- 16 bytes */
+    SlrxFilterIdMask_t FilterIdMask;
+    /*  4 bytes */
+    uint8_t Padding[4];
+} _WlanRxFilterOperationCommandBuff_t;
+
+
+
+/* -- 56 bytes */
+typedef struct _WlanRxFilterUpdateArgsCommandBuff_t {
+    /*  -- 1 bytes */
+    uint8_t  FilterId;
+
+    /*  -- 1 bytes */
+    /* ! the args representation */
+    uint8_t BinaryRepresentation;
+
+    /*  -- 52 byte */
+    SlrxFilterRuleHeaderArgsAndMask_t FilterRuleHeaderArgsAndMask;
+
+    /* -- 2 bytes */
+    uint8_t Padding[2];
+} _WlanRxFilterUpdateArgsCommandBuff_t;
+
+
+/*! \typedef _WlanRxFilterRetrieveEnableStatusCommandResponseBuff_t
+ *  The structure is used for the interface HOST NWP.\n
+ *
+ */
+/* -- 16 bytes */
+typedef struct _WlanRxFilterRetrieveEnableStatusCommandResponseBuff_t {
+
+    /* ! the filter set bit map */
+    /*  -- 16 bytes             */
+    SlrxFilterIdMask_t FilterIdMask;
+
+} _WlanRxFilterRetrieveEnableStatusCommandResponseBuff_t;
+
+
+/*! \struct _WlanRxFilterPrePreparedFiltersCommandBuff_t
+ *  The function enables to perform operations on pre-prepared filters
+ *
+ */
+typedef struct _WlanRxFilterPrePreparedFiltersCommandBuff_t {
+    /* ! the filter set bit map */
+    /*  -- 4 bytes */
+    SlrxFilterPrePreparedFiltersMask_t  FilterPrePreparedFiltersMask;
+
+} _WlanRxFilterPrePreparedFiltersCommandBuff_t;
+
+
+/*! \typedef sl_protocol_WlanRxFilterPrePreparedFiltersCommandResponseBuff_t
+ *
+ */
+/*-- 4 bytes  */
+typedef struct _WlanRxFilterPrePreparedFiltersCommandResponseBuff_t {
+    /* -- 4 bytes */
+    /* ! the filter set bit map */
+    SlrxFilterPrePreparedFiltersMask_t  FilterPrePreparedFiltersMask;
+
+} _WlanRxFilterPrePreparedFiltersCommandResponseBuff_t;
+
+
+
+typedef uint8_t SLrxFilterOperation_t;
+#define SL_ENABLE_DISABLE_RX_FILTER                         (0)
+#define SL_REMOVE_RX_FILTER                                 (1)
+#define SL_STORE_RX_FILTERS                                 (2)
+#define SL_UPDATE_RX_FILTER_ARGS                            (3)
+#define SL_FILTER_RETRIEVE_ENABLE_STATE                     (4)
+#define SL_FILTER_PRE_PREPARED_RETRIEVE_CREATE_REMOVE_STATE (5)
+#define SL_FILTER_PRE_PREPARED_SET_CREATE_REMOVE_STATE      (6)
+
+
+/*  Bit manipulation for 8 bit */
+#define ISBITSET8(x,i) ((x[i>>3] & (0x80>>(i&7)))!=0) /* < Is bit set, 8 bit unsigned numbers = x , location = i */
+#define SETBIT8(x,i) x[i>>3]|=(0x80>>(i&7)); /* < Set bit,8 bit unsigned numbers = x , location = i */
+#define CLEARBIT8(x,i) x[i>>3]&=(0x80>>(i&7))^0xFF; /* < Clear bit,8 bit unsigned numbers = x , location = i */
+
+namespace mbed_cc3100 {
+
+/* ******************************************************************************/
+/*     RX filters - Start  */
+/* ******************************************************************************/
+/*  -- 80 bytes */
+typedef struct _WlanRxFilterAddCommand_t {
+    /*  -- 1 byte */
+    SlrxFilterRuleType_t RuleType;
+    /*  -- 1 byte */
+    SlrxFilterFlags_t FilterFlags;
+    /*  --  1 byte */
+    SlrxFilterID_t FilterId;
+    /*  --  1 byte */
+    uint8_t Padding;
+    /*  -- 56 byte */
+    SlrxFilterRule_t Rule;
+    /*  --  12 byte ( 3 padding ) */
+    SlrxFilterTrigger_t Trigger;
+    /*  --  8 byte */
+    SlrxFilterAction_t Action;
+} _WlanRxFilterAddCommand_t;
+
+
+
+/* -- 4 bytes */
+typedef struct l_WlanRxFilterAddCommandReponse_t {
+    /*  -- 1 byte */
+    SlrxFilterID_t FilterId;
+    /* -- 1 Byte */
+    uint8_t          Status;
+    /*  -- 2 byte */
+    uint8_t  Padding[2];
+
+} _WlanRxFilterAddCommandReponse_t;
+
+
+
+/*
+ * \struct _WlanRxFilterSetCommand_t
+ */
+typedef struct _WlanRxFilterSetCommand_t {
+    uint16_t InputBufferLength;
+    /* 1 byte */
+    SLrxFilterOperation_t RxFilterOperation;
+    uint8_t Padding[1];
+} _WlanRxFilterSetCommand_t;
+
+/**
+ * \struct _WlanRxFilterSetCommandReponse_t
+ */
+typedef struct _WlanRxFilterSetCommandReponse_t {
+    /* 1 byte */
+    uint8_t  Status;
+    /* 3 bytes  */
+    uint8_t Padding[3];
+
+} _WlanRxFilterSetCommandReponse_t;
+
+/**
+ * \struct _WlanRxFilterGetCommand_t
+ */
+typedef struct _WlanRxFilterGetCommand_t {
+    uint16_t OutputBufferLength;
+    /* 1 byte  */
+    SLrxFilterOperation_t RxFilterOperation;
+    uint8_t Padding[1];
+} _WlanRxFilterGetCommand_t;
+
+/**
+ * \struct _WlanRxFilterGetCommandReponse_t
+ */
+typedef struct _WlanRxFilterGetCommandReponse_t {
+    /* 1 byte  */
+    uint8_t  Status;
+    /* 1 bytes  */
+    uint8_t Padding;
+    /* 2 byte  */
+    uint16_t OutputBufferLength;
+
+} _WlanRxFilterGetCommandReponse_t;
+
+
+
+/* ******************************************************************************/
+/*     RX filters -- End  */
+/* ******************************************************************************/
+
+class cc3100_driver;
+
+class cc3100_wlan_rx_filters
+{
+
+public:
+
+    cc3100_wlan_rx_filters(cc3100_driver &driver);
+
+    ~cc3100_wlan_rx_filters();
+
+
+    /*********************************************************************************************/
+    /* Function prototypes                                                                       */
+    /*********************************************************************************************/
+
+    /*!
+
+        \addtogroup wlan
+        @{
+
+    */
+
+
+    /*!
+      \brief Adds new filter rule to the system
+
+      \param[in]    RuleType     The rule type
+      \param[in]    FilterFlags  Flags which set the type of header rule Args and sets the persistent flag
+      \param[in]    pRule        Determine the filter rule logic
+      \param[in]    pTrigger     Determine when the rule is triggered also sets rule parent.
+      \param[in]    pAction      Sets the action to be executed in case the match functions pass
+      \param[out]   pFilterId    The filterId which was created
+
+      \return       On success, zero is returned. Otherwise error code is returned
+     */
+#if _SL_INCLUDE_FUNC(sl_WlanRxFilterAdd)
+    SlrxFilterID_t sl_WlanRxFilterAdd(    SlrxFilterRuleType_t                 RuleType,
+                                          SlrxFilterFlags_t                     FilterFlags,
+                                          const SlrxFilterRule_t* const         Rule,
+                                          const SlrxFilterTrigger_t* const     Trigger,
+                                          const SlrxFilterAction_t* const     Action,
+                                          SlrxFilterID_t*                     pFilterId);
+
+#endif
+
+
+
+
+
+    /*!
+      \brief   Sets parameters to Rx filters
+
+     \param[in] RxFilterOperation
+     possible operations :
+        - SL_ENABLE_DISABLE_RX_FILTER - Enables\disables filter in a filter list
+        - SL_REMOVE_RX_FILTER - Removes filter from memory ( to remove from flash call SL_STORE_RX_FILTERS after this command)
+        - SL_STORE_RX_FILTERS - Save the filters for persistent
+        - SL_UPDATE_RX_FILTER_ARGS - Update the arguments of existing filter
+        - SL_FILTER_PRE_PREPARED_SET_CREATE_REMOVE_STATE - Change the default creation of the pre-prepared filters
+
+      \param[in] pInputBuffer options:
+       The buffer input is _WlanRxFilterOperationCommandBuff_t:
+         - SL_ENABLE_DISABLE_RX_FILTER
+        - SL_REMOVE_RX_FILTER
+        - SL_STORE_RX_FILTERS
+        The buffer input is _WlanRxFilterUpdateArgsCommandBuff_t:
+         - SL_UPDATE_RX_FILTER_ARGS
+       The buffer input is _WlanRxFilterPrePreparedFiltersCommandBuff_t:
+         - SL_FILTER_PRE_PREPARED_SET_CREATE_REMOVE_STATE
+
+      \param[in] InputbufferLength The length in byte of the input buffer
+
+      \return    On success, zero is returned. Otherwise error code is returned
+     */
+
+#if _SL_INCLUDE_FUNC(sl_WlanRxFilterSet)
+    int16_t sl_WlanRxFilterSet(  const SLrxFilterOperation_t RxFilterOperation,
+                                 const uint8_t*  const pInputBuffer,
+                                 uint16_t InputbufferLength);
+#endif
+
+    /*!
+      \brief    Gets parameters of Rx filters
+
+     \param[in] RxFilterOperation
+     possible operations :
+        - SL_FILTER_RETRIEVE_ENABLE_STATE - Retrieves the enable disable status
+        - SL_FILTER_PRE_PREPARED_RETRIEVE_CREATE_REMOVE_STATE - Retrieves the pre-prepared filters creation status
+
+     \param[in] pOutputBuffer
+       The buffer input is _WlanRxFilterRetrieveEnableStatusCommandResponseBuff_t:
+         - SL_FILTER_RETRIEVE_ENABLE_STATE
+       The buffer input is _WlanRxFilterPrePreparedFiltersCommandResponseBuff_t:
+         - SL_FILTER_PRE_PREPARED_RETRIEVE_CREATE_REMOVE_STATE
+
+      \param[in] OutputbufferLength   The length in byte of the output buffer
+
+       \return   On success, zero is returned. Otherwise error code is returned
+    */
+
+#if _SL_INCLUDE_FUNC(sl_WlanRxFilterGet)
+    int16_t sl_WlanRxFilterGet(const SLrxFilterOperation_t RxFilterOperation,
+                               uint8_t*  pOutputBuffer,
+                               uint16_t  OutputbufferLength);
+#endif
+
+private:
+
+    cc3100_driver           &_driver;
+
+
+    /*!
+
+     Close the Doxygen group.
+     @}
+
+     */
+};//class
+
+}//namespace mbed_cc3100
+
+#endif /* RX_FILTERS_PREPROCESSOR_CLI_IF_H_ */
+
+
+