This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

Unable to open, read or write to a file in httpserver code when device is in AP Mode.

Other Parts Discussed in Thread: CC3200SDK, CC3200-LAUNCHXL, UNIFLASH, CC3200

I have been referring to the httpserver code, wherein i have been able create my own webpage for setting the IP address, gateway etc.

I have used user-defined tokens and successfully received data in my code.

My problem is that i am unable to save this data in a file on the Serial Flash.

I want to save the data in a .txt file, but the command lRetVal = sl_FsOpen((unsigned char *)USER_FILE_NAME, FS_MODE_OPEN_CREATE(65536, \ _FS_FILE_OPEN_FLAG_COMMIT|_FS_FILE_PUBLIC_WRITE), ulToken, lFileHandle); does not execute completely, and does not return lRetVal.

I did refer to the file_operations code, and performed these open-write-read operations using sl_FsOpen, sl_FsWrite, sl_FsRead, sl_FsClose etc successfully.

But, i am unable to do the same in httpserver code when device is in AP mode.

Please shed some light on this.

P.S: #define USER_FILE_NAME "fs_demo.txt"

  • HI Abhishek,


    Please provide us following information:
    1. Device version
    2. Is it stuck in sl_FsOpen? If yes then please provide us the stack trace else tell us the error code you are getting.


    Regards,
    Aashish
  • Hi,You should be able to communicate with the file system during AP mode.
    Can you please clarify if you are getting stuck on file system API or does it return with some error code? if it is stuck, what is the call stack?
    In addition, are you able to communicate with the serial flash at all (not only in AP mode, e.g. run the file operations example code)?
    Last, please send me the version of the device and also the service pack version (you can do it by invoking sl_DevGet() with SL_DEVICE_GENERAL_VERSION option).
    Regards,Shlomi
  • Hello Aashish.

    Many thanks for replying.

    I am using the CC3200-LaunchXL Rev3.2, the CC3200SDK_1.0.0 and CC31xx_CC32xx_ServicePack_1.0.0.1.1.

    The execution is not struck anywhere, it returns to    

    //Handle Async Events

       while(1)

       {

       }

    I am attaching the stack trace screens for code execution before execution, at execution and after execution of  sl_FsOpen (in descending order).

    Please reply.

  • Hello Shlomi.
    Thank you for replying.
    I am unable to communicate with the file system in AP mode only.
    The code doesn't get stuck anywhere, it doesn't completely execute the sl_FsOpen, sl_FsWrite etc functions, and goes to handle Async events. It does not return the value of IRetVal.

    In other cases, i am completely able to communicate with the Serial Flash.
    I have run the file_operations many times to confirm. Also, i have Flashed it using UniFlash as well.

    I have mentioned the device and software versions and uploaded screens of Stack Traces above.

    Please reply.
  • Hi Abhishek,


    Still we need some more information form you as it still not clear from stack trace. Can you please put a debug point at if(RetVal < 0) and let us know what value you are getting for RetVal. If it's not coming to this debug point then please do step-by-step debugging and let us know where exactly it stuck in sl_FsOpen.
    Also let us know device version that printed on chip (HZ or JR or something else).


    Regards,
    Aashish
  • Thank you once again.

    The version name printed on the device is XCC3200HZ.

    The execution never comes to if(RetVal<0), nor does it execute the else part.
    It just goes to handle Async events.

    I am uploading screens of single step debug.

    Please refer and reply.

  • Hi Shlomi,
    You said "Hi,You should be able to communicate with the file system during AP mode. "

    Can you please provide some example or code to show how this is done.

    Regards,
    Abhishek.
  • Hi Abhishek,


    You supposed to not to call any simplelink host api (in your case sl_FsOpen) from simplelink async event handler as it will try to lock a object that already locked by host callback caller function.


    Regards,
    Aashish
  • Hi,I can see the problem.
    You are calling to driver API (in this case file system API but it could be any other command) from async event context.
    This is not allowed as the async event grabs the global lock and then the calling API waits on the same global lock causing to a dead lock.
    You can for example implement a state machine and avoid calling these APIs from event context. You should call it from your main.
    Regards,Shlomi
  • Thank you for replying.
    I would like to explain to you my code.
    I have created a html page, which sends me the IP address, Gateway, Subnet Mask, and DNS while other page sends me the SSID name, Password and Profile Priority set in the browser.

    I want to store this data in a .txt file (while the CC3200 is still in AP mode).

    Then, i want to restart my device and come up in Station mode, apply the stored IP adddress etc and connect to the AP whose SSID name and Password is stored.

    I am finding it difficult to store the data received from the browser in .txt file.
  • Whenever i stop(halt) the execution, the execution always stops in static void HTTPServerTask(void *pvParameters) function....


    As you suggest, where should i call the sl_FsOpen function from ??

    Should i call it from
    static void HTTPServerTask(void *pvParameters)
    {
    ...............
    ...............
    ...............
    //Handle Async Events
    while(1)
    {
    //CALL sl_FsOpen from here ??
    }
    }

    or should i call it from
    void main()
    {
    ................
    ................
    ................
    //
    // Start OS Scheduler
    //
    osi_start();

    while (1)
    {
    //CALL sl_FsOpen from here ??
    }

    }


    Please reply.
  • Hi Abhishek,


    You can use queue for your requirement. You can post data to a queue from async handler and read it back in another task and write to a file. For queue example please refer freertos_demo.


    Regards,
    Aashish
  • Thank you so much.
    I will implement this and get back to you.

    Regards,
    Abhishek.
  • Hello Ashish.
    I implemented the what you suggested.
    I am uploading some screens that will help you understand my implementation step by step....
  • First: In the httpserver code, i created another task for creating a .txt file (task-2)

    Second: static void Update_IPConfig_file (void *pvParameters) called the function WriteFileToDevice(&ulToken, &lFileHandle)

    Third: long WriteFileToDevice(unsigned long *ulToken, long *lFileHandle) calls the function sl_FsOpen(.....)

  • Hi Abhishek,


    Is it working or you still facing some issue?


    Regards,
    Aashish
  • Fourth: sl_FsOpen called the function RetVal = _SlDrvCmdOp((_SlCmdCtrl_t *)&_SlFsOpenCmdCtrl, &Msg, &CmdExt);

    Fifth: _SlDrvCmdOp calls the function OSI_RET_OK_CHECK(sl_LockObjLock(&g_pCB->GlobalLockObj, SL_OS_WAIT_FOREVER));

    Sixth: osi_LockObjLock calls the function  if(pdTRUE == xSemaphoreTake( *pLockObj, ( TickType_t ) (Timeout/portTICK_PERIOD_MS) ))


  • Seventh: Execution goes to xQueueGenericReceive( QueueHandle_t xQueue, void * const pvBuffer, TickType_t xTicksToWait, const BaseType_t xJus

    Eight: Execution gets stuck in void
    vAssertCalled( const char *pcFile, unsigned long ulLine )

  • Hello Aashish.
    Thank you very much for replying.
    I have sent you 8 steps and screens with stack trace.
    I am still unable to open the file using sl_FsOpen...
    Please go through the screens and reply.

    Warm regards,
    Abhishek
  • Hi Abhishek,


    Is it possible to share code with us?


    Regards,
    Aashish
  • Yes.
    Uploading the files here...
  • //*****************************************************************************
    //
    // 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.
    //
    //*****************************************************************************

    //*****************************************************************************
    //
    // Application Name - HTTP Server
    // Application Overview - This is a sample application demonstrating
    // interaction between HTTP Client(Browser) and
    // SimpleLink Device.The SimpleLink device runs an
    // HTTP Server and user can interact using web browser.
    // Application Details -
    // http://processors.wiki.ti.com/index.php/CC32xx_HTTP_Server
    // or
    // doc\examples\CC32xx_HTTP_Server.pdf
    //
    //*****************************************************************************

    //****************************************************************************
    //
    //! \addtogroup httpserver
    //! @{
    //
    //****************************************************************************

    // Standard includes
    #include <string.h>
    #include <stdlib.h>

    // Simplelink includes
    #include "simplelink.h"
    #include "netcfg.h"

    //driverlib includes
    #include "hw_ints.h"
    #include "hw_types.h"
    #include "hw_memmap.h"
    #include "interrupt.h"
    #include "utils.h"
    #include "pin.h"
    #include "uart.h"
    #include "rom.h"
    #include "rom_map.h"
    #include "prcm.h"

    //Free_rtos/ti-rtos includes
    #include "osi.h"

    // common interface includes
    #include "gpio_if.h"
    #include "uart_if.h"
    #include "common.h"

    #include "smartconfig.h"
    #include "pinmux.h"


    #define APPLICATION_NAME "HTTP Server"
    #define APPLICATION_VERSION "1.1.0"
    #define AP_SSID_LEN_MAX (33)
    #define ROLE_INVALID (-5)

    #define LED_STRING "LED"
    #define LED1_STRING "LED1_"
    #define LED2_STRING ",LED2_"
    #define LED_ON_STRING "ON"
    #define LED_OFF_STRING "OFF"

    #define OOB_TASK_PRIORITY (1)
    #define OSI_STACK_SIZE (2048)
    #define SH_GPIO_3 (3) /* P58 - Device Mode */
    #define ROLE_INVALID (-5)
    #define AUTO_CONNECTION_TIMEOUT_COUNT (50) /* 5 Sec */


    #define SL_MAX_FILE_SIZE 64L*1024L /* 64KB file */
    #define BUF_SIZE 2048
    #define USER_FILE_NAME "fs_demo.txt"


    // Application specific status/error codes
    typedef enum{
    // Choosing -0x7D0 to avoid overlap w/ host-driver's error codes
    LAN_CONNECTION_FAILED = -0x7D0,
    INTERNET_CONNECTION_FAILED = LAN_CONNECTION_FAILED - 1,
    DEVICE_NOT_IN_STATION_MODE = INTERNET_CONNECTION_FAILED - 1,

    FILE_ALREADY_EXIST = -0x7D0,
    FILE_CLOSE_ERROR = FILE_ALREADY_EXIST - 1,
    FILE_NOT_MATCHED = FILE_CLOSE_ERROR - 1,
    FILE_OPEN_READ_FAILED = FILE_NOT_MATCHED - 1,
    FILE_OPEN_WRITE_FAILED = FILE_OPEN_READ_FAILED -1,
    FILE_READ_FAILED = FILE_OPEN_WRITE_FAILED - 1,
    FILE_WRITE_FAILED = FILE_READ_FAILED - 1,

    STATUS_CODE_MAX = -0xBB8
    }e_AppStatusCodes;


    //*****************************************************************************
    // GLOBAL VARIABLES -- Start
    //*****************************************************************************
    unsigned char ptrlen ;
    unsigned long g_ulStatus = 0;//SimpleLink Status
    unsigned long g_ulPingPacketsRecv = 0; //Number of Ping Packets received
    unsigned long g_ulGatewayIP = 0; //Network Gateway IP address
    unsigned char g_ucConnectionSSID[SSID_LEN_MAX+1]; //Connection SSID
    unsigned char g_ucConnectionBSSID[BSSID_LEN_MAX]; //Connection BSSID
    unsigned char POST_token[] = "__SL_P_ULD";
    unsigned char GET_token[] = "__SL_G_ULD";
    int g_iSimplelinkRole = ROLE_INVALID;
    signed int g_uiIpAddress = 0;
    unsigned char g_ucSSID[AP_SSID_LEN_MAX];

    unsigned char gaucCmpBuf[BUF_SIZE];
    const unsigned char gaucOldMacDonald[] = "Old MacDonald had a farm,E-I-E-I-O, \
    And on his farm he had a cow, \
    E-I-E-I-O, \
    With a moo-moo here, \
    And a moo-moo there, \
    Here a moo, there a moo, \
    Everywhere a moo-moo. \
    Old MacDonald had a farm, \
    E-I-E-I-O. \
    Old MacDonald had a farm, \
    E-I-E-I-O, \
    And on his farm he had a pig, \
    E-I-E-I-O, \
    With an oink-oink here, \
    And an oink-oink there, \
    Here an oink, there an oink, \
    Everywhere an oink-oink. \
    Old MacDonald had a farm, \
    E-I-E-I-O. \
    Old MacDonald had a farm, \
    E-I-E-I-O, \
    And on his farm he had a duck, \
    E-I-E-I-O, \
    With a quack-quack here, \
    And a quack-quack there, \
    Here a quack, there a quack, \
    Everywhere a quack-quack. \
    Old MacDonald had a farm, \
    E-I-E-I-O. \
    Old MacDonald had a farm, \
    E-I-E-I-O, \
    And on his farm he had a horse, \
    E-I-E-I-O, \
    With a neigh-neigh here, \
    And a neigh-neigh there, \
    Here a neigh, there a neigh, \
    Everywhere a neigh-neigh. \
    Old MacDonald had a farm, \
    E-I-E-I-O. \
    Old MacDonald had a farm, \
    E-I-E-I-O, \
    And on his farm he had a donkey, \
    E-I-E-I-O, \
    With a hee-haw here, \
    And a hee-haw there, \
    Here a hee, there a hee, \
    Everywhere a hee-haw. \
    Old MacDonald had a farm, \
    E-I-E-I-O. \
    Old MacDonald had a farm, \
    E-I-E-I-O, \
    And on his farm he had some chickens, \
    E-I-E-I-O, \
    With a cluck-cluck here, \
    And a cluck-cluck there, \
    Here a cluck, there a cluck, \
    Everywhere a cluck-cluck. \
    Old MacDonald had a farm, \
    E-I-E-I-O.";


    long lRetVal;
    unsigned char policyVal;
    long lFileHandle;
    unsigned long ulToken;

    #if defined(ccs)
    extern void (* const g_pfnVectors[])(void);
    #endif
    #if defined(ewarm)
    extern uVectorEntry __vector_table;
    #endif
    //*****************************************************************************
    // GLOBAL VARIABLES -- End
    //*****************************************************************************


    //*****************************************************************************
    // Variable related to Connection status
    //*****************************************************************************
    volatile unsigned short g_usMCNetworkUstate = 0;

    int g_uiSimplelinkRole = ROLE_INVALID;
    unsigned int g_uiDeviceModeConfig = ROLE_STA; //default is STA mode
    unsigned char g_ucConnectTimeout =0;



    #ifdef USE_FREERTOS
    //*****************************************************************************
    // FreeRTOS User Hook Functions enabled in FreeRTOSConfig.h
    //*****************************************************************************

    //*****************************************************************************
    //
    //! \brief Application defined hook (or callback) function - assert
    //!
    //! \param[in] pcFile - Pointer to the File Name
    //! \param[in] ulLine - Line Number
    //!
    //! \return none
    //!
    //*****************************************************************************
    void
    vAssertCalled( const char *pcFile, unsigned long ulLine )
    {
    //Handle Assert here
    while(1)
    {
    }
    }

    //*****************************************************************************
    //
    //! \brief Application defined idle task hook
    //!
    //! \param none
    //!
    //! \return none
    //!
    //*****************************************************************************
    void
    vApplicationIdleHook( void)
    {
    //Handle Idle Hook for Profiling, Power Management etc
    }

    //*****************************************************************************
    //
    //! \brief Application defined malloc failed hook
    //!
    //! \param none
    //!
    //! \return none
    //!
    //*****************************************************************************
    void vApplicationMallocFailedHook()
    {
    //Handle Memory Allocation Errors
    while(1)
    {
    }
    }

    //*****************************************************************************
    //
    //! \brief Application defined stack overflow hook
    //!
    //! \param none
    //!
    //! \return none
    //!
    //*****************************************************************************
    void vApplicationStackOverflowHook( OsiTaskHandle *pxTask,
    signed char *pcTaskName)
    {
    //Handle FreeRTOS Stack Overflow
    while(1)
    {
    }
    }
    #endif //USE_FREERTOS




    //*****************************************************************************
    //
    //! This funtion includes the following steps:
    //! -open a user file for writing
    //! -write "Old MacDonalds" child song 37 times to get just below a 64KB file
    //! -close the user file
    //!
    //! /param[out] ulToken : file token
    //! /param[out] lFileHandle : file handle
    //!
    //! /return 0:Success, -ve: failure
    //
    //*****************************************************************************
    long WriteFileToDevice(unsigned long *ulToken, long *lFileHandle)
    {
    long lRetVal = -1;
    int iLoopCnt = 0;

    //
    // create a user file
    //
    lRetVal = sl_FsOpen((unsigned char *)USER_FILE_NAME,
    FS_MODE_OPEN_CREATE(65536, \
    _FS_FILE_OPEN_FLAG_COMMIT|_FS_FILE_PUBLIC_WRITE),
    ulToken,
    lFileHandle);
    if(lRetVal < 0)
    {
    //
    // File may already be created
    //
    lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
    ASSERT_ON_ERROR(lRetVal);
    }
    else
    {
    //
    // close the user file
    //
    lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
    if (SL_RET_CODE_OK != lRetVal)
    {
    ASSERT_ON_ERROR(FILE_CLOSE_ERROR);
    }
    }

    //
    // open a user file for writing
    //
    lRetVal = sl_FsOpen((unsigned char *)USER_FILE_NAME,
    FS_MODE_OPEN_WRITE,
    ulToken,
    lFileHandle);
    if(lRetVal < 0)
    {
    lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
    ASSERT_ON_ERROR(FILE_OPEN_WRITE_FAILED);
    }

    //
    // write "Old MacDonalds" child song as many times to get just below a 64KB file
    //
    for (iLoopCnt = 0;
    iLoopCnt < (SL_MAX_FILE_SIZE / sizeof(gaucOldMacDonald));
    iLoopCnt++)
    {
    lRetVal = sl_FsWrite(*lFileHandle,
    (unsigned int)(iLoopCnt * sizeof(gaucOldMacDonald)),
    (unsigned char *)gaucOldMacDonald, sizeof(gaucOldMacDonald));
    if (lRetVal < 0)
    {
    lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
    ASSERT_ON_ERROR(FILE_WRITE_FAILED);
    }
    }

    //
    // close the user file
    //
    lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
    if (SL_RET_CODE_OK != lRetVal)
    {
    ASSERT_ON_ERROR(FILE_CLOSE_ERROR);
    }

    return SUCCESS;
    }

    //*****************************************************************************
    //
    //! This funtion includes the following steps:
    //! -open the user file for reading
    //! -read the data and compare with the stored buffer
    //! -close the user file
    //!
    //! /param[in] ulToken : file token
    //! /param[in] lFileHandle : file handle
    //!
    //! /return 0: success, -ve:failure
    //
    //*****************************************************************************
    long ReadFileFromDevice(unsigned long ulToken, long lFileHandle)
    {
    long lRetVal = -1;
    int iLoopCnt = 0;

    //
    // open a user file for reading
    //
    lRetVal = sl_FsOpen((unsigned char *)USER_FILE_NAME,
    FS_MODE_OPEN_READ,
    &ulToken,
    &lFileHandle);
    if(lRetVal < 0)
    {
    lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);
    ASSERT_ON_ERROR(FILE_OPEN_READ_FAILED);
    }

    //
    // read the data and compare with the stored buffer
    //
    for (iLoopCnt = 0;
    iLoopCnt < (SL_MAX_FILE_SIZE / sizeof(gaucOldMacDonald));
    iLoopCnt++)
    {
    lRetVal = sl_FsRead(lFileHandle,
    (unsigned int)(iLoopCnt * sizeof(gaucOldMacDonald)),
    gaucCmpBuf, sizeof(gaucOldMacDonald));
    if ((lRetVal < 0) || (lRetVal != sizeof(gaucOldMacDonald)))
    {
    lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);
    ASSERT_ON_ERROR(FILE_READ_FAILED);
    }

    lRetVal = memcmp(gaucOldMacDonald,
    gaucCmpBuf,
    sizeof(gaucOldMacDonald));
    if (lRetVal != 0)
    {
    ASSERT_ON_ERROR(FILE_NOT_MATCHED);
    }
    }

    //
    // close the user file
    //
    lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);
    if (SL_RET_CODE_OK != lRetVal)
    {
    ASSERT_ON_ERROR(FILE_CLOSE_ERROR);
    }

    return SUCCESS;
    }



    //*****************************************************************************
    // Updating IP Configuration file
    //*****************************************************************************


    static void Update_IPConfig_file (void *pvParameters)
    {

    if(WriteFileToDevice(&ulToken, &lFileHandle) < 0)
    {
    GPIO_IF_LedOn(MCU_RED_LED_GPIO);
    LOOP_FOREVER();
    }

    if(ReadFileFromDevice(ulToken, lFileHandle) < 0)
    {
    GPIO_IF_LedOn(MCU_RED_LED_GPIO);
    LOOP_FOREVER();
    }
    }


    //*****************************************************************************
    // SimpleLink Asynchronous Event Handlers -- Start
    //*****************************************************************************


    //*****************************************************************************
    //
    //! \brief The Function Handles WLAN Events
    //!
    //! \param[in] pWlanEvent - Pointer to WLAN Event Info
    //!
    //! \return None
    //!
    //*****************************************************************************
    void SimpleLinkWlanEventHandler(SlWlanEvent_t *pWlanEvent)
    {
    if(!pWlanEvent)
    {
    return;
    }

    switch(pWlanEvent->Event)
    {
    case SL_WLAN_CONNECT_EVENT:
    {
    SET_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION);

    //
    // 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;
    //

    // 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);

    UART_PRINT("[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]);
    }
    break;

    case SL_WLAN_DISCONNECT_EVENT:
    {
    slWlanConnectAsyncResponse_t* pEventData = NULL;

    CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION);
    CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_AQUIRED);

    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)
    {
    UART_PRINT("[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]);
    }
    else
    {
    UART_PRINT("[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]);
    }
    memset(g_ucConnectionSSID,0,sizeof(g_ucConnectionSSID));
    memset(g_ucConnectionBSSID,0,sizeof(g_ucConnectionBSSID));
    }
    break;

    case SL_WLAN_STA_CONNECTED_EVENT:
    {
    // when device is in AP mode and any client connects to device cc3xxx
    SET_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION);
    CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION_FAILED);

    //
    // Information about the connected client (like SSID, MAC etc) will
    // be available in 'slPeerInfoAsyncResponse_t' - Applications
    // can use it if required
    //
    // slPeerInfoAsyncResponse_t *pEventData = NULL;
    // pEventData = &pSlWlanEvent->EventData.APModeStaConnected;
    //

    }
    break;

    case SL_WLAN_STA_DISCONNECTED_EVENT:
    {
    // when client disconnects from device (AP)
    CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION);
    CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_LEASED);

    //
    // Information about the connected client (like SSID, MAC etc) will
    // be available in 'slPeerInfoAsyncResponse_t' - Applications
    // can use it if required
    //
    // slPeerInfoAsyncResponse_t *pEventData = NULL;
    // pEventData = &pSlWlanEvent->EventData.APModestaDisconnected;
    //
    }
    break;

    case SL_WLAN_SMART_CONFIG_COMPLETE_EVENT:
    {
    SET_STATUS_BIT(g_ulStatus, STATUS_BIT_SMARTCONFIG_START);

    //
    // Information about the SmartConfig details (like Status, SSID,
    // Token etc) will be available in 'slSmartConfigStartAsyncResponse_t'
    // - Applications can use it if required
    //
    // slSmartConfigStartAsyncResponse_t *pEventData = NULL;
    // pEventData = &pSlWlanEvent->EventData.smartConfigStartResponse;
    //

    }
    break;

    case SL_WLAN_SMART_CONFIG_STOP_EVENT:
    {
    // SmartConfig operation finished
    CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_SMARTCONFIG_START);

    //
    // Information about the SmartConfig details (like Status, padding
    // etc) will be available in 'slSmartConfigStopAsyncResponse_t' -
    // Applications can use it if required
    //
    // slSmartConfigStopAsyncResponse_t *pEventData = NULL;
    // pEventData = &pSlWlanEvent->EventData.smartConfigStopResponse;
    //
    }
    break;

    case SL_WLAN_P2P_DEV_FOUND_EVENT:
    {
    SET_STATUS_BIT(g_ulStatus, STATUS_BIT_P2P_DEV_FOUND);

    //
    // Information about P2P config details (like Peer device name, own
    // SSID etc) will be available in 'slPeerInfoAsyncResponse_t' -
    // Applications can use it if required
    //
    // slPeerInfoAsyncResponse_t *pEventData = NULL;
    // pEventData = &pSlWlanEvent->EventData.P2PModeDevFound;
    //
    }
    break;

    case SL_WLAN_P2P_NEG_REQ_RECEIVED_EVENT:
    {
    SET_STATUS_BIT(g_ulStatus, STATUS_BIT_P2P_REQ_RECEIVED);

    //
    // Information about P2P Negotiation req details (like Peer device
    // name, own SSID etc) will be available in 'slPeerInfoAsyncResponse_t'
    // - Applications can use it if required
    //
    // slPeerInfoAsyncResponse_t *pEventData = NULL;
    // pEventData = &pSlWlanEvent->EventData.P2PModeNegReqReceived;
    //
    }
    break;

    case SL_WLAN_CONNECTION_FAILED_EVENT:
    {
    // If device gets any connection failed event
    SET_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION_FAILED);
    }
    break;

    default:
    {
    UART_PRINT("[WLAN EVENT] Unexpected event [0x%x]\n\r",
    pWlanEvent->Event);
    }
    break;
    }
    }

    //*****************************************************************************
    //
    //! \brief This function handles network events such as IP acquisition, IP
    //! leased, IP released etc.
    //!
    //! \param[in] pNetAppEvent - Pointer to NetApp Event Info
    //!
    //! \return None
    //!
    //*****************************************************************************
    void SimpleLinkNetAppEventHandler(SlNetAppEvent_t *pNetAppEvent)
    {
    if(!pNetAppEvent)
    {
    return;
    }

    switch(pNetAppEvent->Event)
    {
    case SL_NETAPP_IPV4_IPACQUIRED_EVENT:
    {
    SlIpV4AcquiredAsync_t *pEventData = NULL;

    SET_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_AQUIRED);

    //Ip Acquired Event Data
    pEventData = &pNetAppEvent->EventData.ipAcquiredV4;
    g_uiIpAddress = pEventData->ip;

    //Gateway IP address
    g_ulGatewayIP = pEventData->gateway;

    /*UART_PRINT("[NETAPP EVENT] IP Acquired: IP=%d.%d.%d.%d , "
    "Gateway=%d.%d.%d.%d\n\r",
    SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,3),
    SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,2),
    SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,1),
    SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,0),
    SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,3),
    SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,2),
    SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,1),
    SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,0));
    */
    }
    break;

    case SL_NETAPP_IP_LEASED_EVENT:
    {
    SET_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_LEASED);

    //
    // Information about the IP-Leased details(like IP-Leased,lease-time,
    // mac etc) will be available in 'SlIpLeasedAsync_t' - Applications
    // can use it if required
    //
    // SlIpLeasedAsync_t *pEventData = NULL;
    // pEventData = &pNetAppEvent->EventData.ipLeased;
    //

    }
    break;

    case SL_NETAPP_IP_RELEASED_EVENT:
    {
    CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_LEASED);

    //
    // Information about the IP-Released details (like IP-address, mac
    // etc) will be available in 'SlIpReleasedAsync_t' - Applications
    // can use it if required
    //
    // SlIpReleasedAsync_t *pEventData = NULL;
    // pEventData = &pNetAppEvent->EventData.ipReleased;
    //
    }
    break;

    default:
    {
    UART_PRINT("[NETAPP EVENT] Unexpected event [0x%x] \n\r",
    pNetAppEvent->Event);
    }
    break;
    }
    }

    //*****************************************************************************
    //
    //! This function handles socket events indication
    //!
    //! \param[in] pSock - Pointer to Socket Event Info
    //!
    //! \return None
    //!
    //*****************************************************************************
    void SimpleLinkSockEventHandler(SlSockEvent_t *pSock)
    {
    //
    // This application doesn't work w/ socket - Events are not expected
    //

    }


    //*****************************************************************************
    //
    //! This function gets triggered when HTTP Server receives Application
    //! defined GET and POST HTTP Tokens.
    //!
    //! \param pHttpServerEvent Pointer indicating http server event
    //! \param pHttpServerResponse Pointer indicating http server response
    //!
    //! \return None
    //!
    //*****************************************************************************
    void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pSlHttpServerEvent,
    SlHttpServerResponse_t *pSlHttpServerResponse)
    {
    unsigned char strLenVal = 0;

    if(!pSlHttpServerEvent || !pSlHttpServerResponse)
    {
    return;
    }

    switch (pSlHttpServerEvent->Event)
    {
    case SL_NETAPP_HTTPGETTOKENVALUE_EVENT:
    {
    unsigned char status, *ptr;

    ptr = pSlHttpServerResponse->ResponseData.token_value.data;
    pSlHttpServerResponse->ResponseData.token_value.len = 0;
    if(memcmp(pSlHttpServerEvent->EventData.httpTokenName.data, GET_token,
    strlen((const char *)GET_token)) == 0)
    {
    status = GPIO_IF_LedStatus(MCU_RED_LED_GPIO);
    strLenVal = strlen(LED1_STRING);
    memcpy(ptr, LED1_STRING, strLenVal);
    ptr += strLenVal;
    pSlHttpServerResponse->ResponseData.token_value.len += strLenVal;
    if(status & 0x01)
    {
    strLenVal = strlen(LED_ON_STRING);
    memcpy(ptr, LED_ON_STRING, strLenVal);
    ptr += strLenVal;
    pSlHttpServerResponse->ResponseData.token_value.len += strLenVal;
    }
    else
    {
    strLenVal = strlen(LED_OFF_STRING);
    memcpy(ptr, LED_OFF_STRING, strLenVal);
    ptr += strLenVal;
    pSlHttpServerResponse->ResponseData.token_value.len += strLenVal;
    }
    status = GPIO_IF_LedStatus(MCU_GREEN_LED_GPIO);
    strLenVal = strlen(LED2_STRING);
    memcpy(ptr, LED2_STRING, strLenVal);
    ptr += strLenVal;
    pSlHttpServerResponse->ResponseData.token_value.len += strLenVal;
    if(status & 0x01)
    {
    strLenVal = strlen(LED_ON_STRING);
    memcpy(ptr, LED_ON_STRING, strLenVal);
    ptr += strLenVal;
    pSlHttpServerResponse->ResponseData.token_value.len += strLenVal;
    }
    else
    {
    strLenVal = strlen(LED_OFF_STRING);
    memcpy(ptr, LED_OFF_STRING, strLenVal);
    ptr += strLenVal;
    pSlHttpServerResponse->ResponseData.token_value.len += strLenVal;
    }
    *ptr = '\0';
    }

    }
    break;

    case SL_NETAPP_HTTPPOSTTOKENVALUE_EVENT:
    {
    unsigned char led;
    unsigned char *ptr = pSlHttpServerEvent->EventData.httpPostData.token_name.data;

    if(memcmp(ptr, POST_token, strlen((const char *)POST_token)) == 0)
    {
    ptr = pSlHttpServerEvent->EventData.httpPostData.token_value.data;
    strLenVal = strlen(LED_STRING);
    if(memcmp(ptr, LED_STRING, strLenVal) != 0)
    break;
    ptr += strLenVal;
    led = *ptr;
    strLenVal = strlen(LED_ON_STRING);
    ptr += strLenVal;
    if(led == '1')
    {
    if(memcmp(ptr, LED_ON_STRING, strLenVal) == 0)
    {
    GPIO_IF_LedOn(MCU_RED_LED_GPIO);
    }
    else
    {
    GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    }
    }
    else if(led == '2')
    {
    if(memcmp(ptr, LED_ON_STRING, strLenVal) == 0)
    {
    GPIO_IF_LedOn(MCU_GREEN_LED_GPIO);
    }
    else
    {
    GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);
    }
    }

    }
    }
    break;
    default:
    break;
    }
    }

    //*****************************************************************************
    //
    //! \brief This function initializes the application variables
    //!
    //! \param None
    //!
    //! \return None
    //!
    //*****************************************************************************
    static void InitializeAppVariables()
    {
    g_ulStatus = 0;
    g_uiIpAddress = 0;
    }


    //*****************************************************************************
    //! \brief This function puts the device in its default state. It:
    //! - Set 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
    //! - Unregister mDNS services
    //! - Remove all filters
    //!
    //! \param none
    //! \return On success, zero is returned. On error, negative is returned
    //*****************************************************************************
    static long ConfigureSimpleLinkToDefaultState()
    {
    SlVersionFull ver = {0};
    _WlanRxFilterOperationCommandBuff_t RxFilterIdMask = {0};

    unsigned char ucVal = 1;
    unsigned char ucConfigOpt = 0;
    unsigned char ucConfigLen = 0;
    unsigned char ucPower = 0;

    long lRetVal = -1;
    long lMode = -1;

    lMode = sl_Start(0, 0, 0);
    ASSERT_ON_ERROR(lMode);

    // If the device is not in station-mode, try configuring it in station-mode
    if (ROLE_STA != lMode)
    {
    if (ROLE_AP == lMode)
    {
    // If the device is in AP mode, we need to wait for this event
    // before doing anything
    while(!IS_IP_ACQUIRED(g_ulStatus))
    {
    #ifndef SL_PLATFORM_MULTI_THREADED
    _SlNonOsMainLoopTask();
    #endif
    }
    }

    // Switch to STA role and restart
    lRetVal = sl_WlanSetMode(ROLE_STA);
    ASSERT_ON_ERROR(lRetVal);

    lRetVal = sl_Stop(0xFF);
    ASSERT_ON_ERROR(lRetVal);

    lRetVal = sl_Start(0, 0, 0);
    ASSERT_ON_ERROR(lRetVal);

    // Check if the device is in station again
    if (ROLE_STA != lRetVal)
    {
    // We don't want to proceed if the device is not coming up in STA-mode
    return DEVICE_NOT_IN_STATION_MODE;
    }
    }


    //abhishek

    _u8 len = sizeof(SlNetCfgIpV4Args_t);
    _u8 dhcpIsOn = 0;
    SlNetCfgIpV4Args_t ipV4 = {0};
    sl_NetCfgGet(SL_IPV4_STA_P2P_CL_GET_INFO,&dhcpIsOn,&len,(_u8 *)&ipV4);

    UART_PRINT("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));


    sl_NetCfgGet(SL_IPV4_AP_P2P_GO_GET_INFO,&dhcpIsOn,&len,(_u8 *)&ipV4);

    UART_PRINT("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));
    //abhishek


    //Update_IPConfig_file();

    // Get the device's version-information
    ucConfigOpt = SL_DEVICE_GENERAL_VERSION;
    ucConfigLen = sizeof(ver);
    lRetVal = sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION, &ucConfigOpt,
    &ucConfigLen, (unsigned char *)(&ver));
    ASSERT_ON_ERROR(lRetVal);

    UART_PRINT("Host Driver Version: %s\n\r",SL_DRIVER_VERSION);
    UART_PRINT("Build Version %d.%d.%d.%d.31.%d.%d.%d.%d.%d.%d.%d.%d\n\r",
    ver.NwpVersion[0],ver.NwpVersion[1],ver.NwpVersion[2],ver.NwpVersion[3],
    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]);

    // Set connection policy to Auto + SmartConfig
    // (Device's default connection policy)
    lRetVal = sl_WlanPolicySet(SL_POLICY_CONNECTION,
    SL_CONNECTION_POLICY(1, 0, 0, 0, 1), NULL, 0);
    ASSERT_ON_ERROR(lRetVal);

    // Remove all profiles
    lRetVal = sl_WlanProfileDel(0xFF);
    ASSERT_ON_ERROR(lRetVal);



    //
    // 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
    //
    lRetVal = sl_WlanDisconnect();
    if(0 == lRetVal)
    {
    // Wait
    while(IS_CONNECTED(g_ulStatus))
    {
    #ifndef SL_PLATFORM_MULTI_THREADED
    _SlNonOsMainLoopTask();
    #endif
    }
    }

    // Enable DHCP client
    lRetVal = sl_NetCfgSet(SL_IPV4_STA_P2P_CL_DHCP_ENABLE,1,1,&ucVal);
    ASSERT_ON_ERROR(lRetVal);

    // Disable scan
    ucConfigOpt = SL_SCAN_POLICY(0);
    lRetVal = sl_WlanPolicySet(SL_POLICY_SCAN , ucConfigOpt, NULL, 0);
    ASSERT_ON_ERROR(lRetVal);

    // Set Tx power level for station mode
    // Number between 0-15, as dB offset from max power - 0 will set max power
    ucPower = 0;
    lRetVal = sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID,
    WLAN_GENERAL_PARAM_OPT_STA_TX_POWER, 1, (unsigned char *)&ucPower);
    ASSERT_ON_ERROR(lRetVal);

    // Set PM policy to normal
    lRetVal = sl_WlanPolicySet(SL_POLICY_PM , SL_NORMAL_POLICY, NULL, 0);
    ASSERT_ON_ERROR(lRetVal);

    // Unregister mDNS services
    lRetVal = sl_NetAppMDNSUnRegisterService(0, 0);
    ASSERT_ON_ERROR(lRetVal);

    // Remove all 64 filters (8*8)
    memset(RxFilterIdMask.FilterIdMask, 0xFF, 8);
    lRetVal = sl_WlanRxFilterSet(SL_REMOVE_RX_FILTER, (_u8 *)&RxFilterIdMask,
    sizeof(_WlanRxFilterOperationCommandBuff_t));
    ASSERT_ON_ERROR(lRetVal);

    lRetVal = sl_Stop(SL_STOP_TIMEOUT);
    ASSERT_ON_ERROR(lRetVal);

    InitializeAppVariables();

    return lRetVal; // Success
    }



    //****************************************************************************
    //
    //! \brief Connects to the Network in AP or STA Mode - If ForceAP Jumper is
    //! Placed, Force it to AP mode
    //!
    //! \return 0 on success else error code
    //
    //****************************************************************************
    long ConnectToNetwork()
    {
    char ucAPSSID[32];
    unsigned short len, config_opt;
    long lRetVal = -1;

    // staring simplelink
    g_uiSimplelinkRole = sl_Start(NULL,NULL,NULL);

    // Device is not in STA mode and Force AP Jumper is not Connected
    //- Switch to STA mode
    if(g_uiSimplelinkRole != ROLE_STA && g_uiDeviceModeConfig == ROLE_STA )
    {
    //Switch to STA Mode
    lRetVal = sl_WlanSetMode(ROLE_STA);
    ASSERT_ON_ERROR(lRetVal);

    lRetVal = sl_Stop(SL_STOP_TIMEOUT);

    g_usMCNetworkUstate = 0;
    g_uiSimplelinkRole = sl_Start(NULL,NULL,NULL);
    }

    //Device is not in AP mode and Force AP Jumper is Connected -
    //Switch to AP mode
    if(g_uiSimplelinkRole != ROLE_AP && g_uiDeviceModeConfig == ROLE_AP )
    {
    //Switch to AP Mode
    lRetVal = sl_WlanSetMode(ROLE_AP);
    ASSERT_ON_ERROR(lRetVal);

    lRetVal = sl_Stop(SL_STOP_TIMEOUT);

    g_usMCNetworkUstate = 0;
    g_uiSimplelinkRole = sl_Start(NULL,NULL,NULL);
    }

    //No Mode Change Required
    if(g_uiSimplelinkRole == ROLE_AP)
    {
    //waiting for the AP to acquire IP address from Internal DHCP Server
    while(!IS_IP_ACQUIRED(g_ulStatus))
    {

    }

    //Stop Internal HTTP Server
    lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);
    ASSERT_ON_ERROR( lRetVal);

    //Start Internal HTTP Server
    lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID);
    ASSERT_ON_ERROR( lRetVal);

    char iCount=0;
    //Read the AP SSID
    memset(ucAPSSID,'\0',AP_SSID_LEN_MAX);
    len = AP_SSID_LEN_MAX;
    config_opt = WLAN_AP_OPT_SSID;
    lRetVal = sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt , &len,
    (unsigned char*) ucAPSSID);
    ASSERT_ON_ERROR(lRetVal);

    Report("\n\rDevice is in AP Mode, Please Connect to AP [%s] and"
    "type [mysimplelink.net] in the browser \n\r",ucAPSSID);

    //Blink LED 3 times to Indicate AP Mode
    for(iCount=0;iCount<3;iCount++)
    {
    //Turn RED LED On
    GPIO_IF_LedOn(MCU_RED_LED_GPIO);
    osi_Sleep(400);

    //Turn RED LED Off
    GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    osi_Sleep(400);
    }

    }
    else
    {
    //Stop Internal HTTP Server
    lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);
    ASSERT_ON_ERROR( lRetVal);

    //Start Internal HTTP Server
    lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID);
    ASSERT_ON_ERROR( lRetVal);

    //waiting for the device to Auto Connect
    while ( (!IS_IP_ACQUIRED(g_ulStatus))&&
    g_ucConnectTimeout < AUTO_CONNECTION_TIMEOUT_COUNT)
    {
    //Turn RED LED On
    GPIO_IF_LedOn(MCU_RED_LED_GPIO);
    osi_Sleep(50);

    //Turn RED LED Off
    GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    osi_Sleep(50);

    g_ucConnectTimeout++;
    }
    //Couldn't connect Using Auto Profile
    if(g_ucConnectTimeout == AUTO_CONNECTION_TIMEOUT_COUNT)
    {
    //Blink Red LED to Indicate Connection Error
    GPIO_IF_LedOn(MCU_RED_LED_GPIO);

    CLR_STATUS_BIT_ALL(g_ulStatus);

    Report("Use Smart Config Application to configure the device.\n\r");
    //Connect Using Smart Config
    lRetVal = SmartConfigConnect();
    ASSERT_ON_ERROR(lRetVal);

    //Waiting for the device to Auto Connect
    while(!IS_IP_ACQUIRED(g_ulStatus))
    {
    MAP_UtilsDelay(500);
    }

    }
    //Turn RED LED Off
    GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    UART_PRINT("\n\rDevice is in STA Mode, Connect to the AP[%s] and type"
    "IP address [%d.%d.%d.%d] in the browser \n\r",g_ucConnectionSSID,
    SL_IPV4_BYTE(g_uiIpAddress,3),SL_IPV4_BYTE(g_uiIpAddress,2),
    SL_IPV4_BYTE(g_uiIpAddress,1),SL_IPV4_BYTE(g_uiIpAddress,0));

    }
    return SUCCESS;
    }


    //****************************************************************************
    //
    //! \brief Read Force AP GPIO and Configure Mode - 1(Access Point Mode)
    //! - 0 (Station Mode)
    //!
    //! \return None
    //
    //****************************************************************************
    static void ReadDeviceConfiguration()
    {
    unsigned int uiGPIOPort;
    unsigned char pucGPIOPin;
    unsigned char ucPinValue;

    //Read GPIO
    GPIO_IF_GetPortNPin(SH_GPIO_3,&uiGPIOPort,&pucGPIOPin);
    ucPinValue = GPIO_IF_Get(SH_GPIO_3,uiGPIOPort,pucGPIOPin);

    //If Connected to VCC, Mode is AP
    if(ucPinValue == 1)
    {
    //AP Mode
    g_uiDeviceModeConfig = ROLE_AP;
    }
    else
    {
    //STA Mode
    g_uiDeviceModeConfig = ROLE_STA;
    }

    }

    //****************************************************************************
    //
    //! \brief Handles HTTP Server Task
    //!
    //! \param[in] pvParameters is the data passed to the Task
    //!
    //! \return None
    //
    //****************************************************************************
    static void HTTPServerTask(void *pvParameters)
    {
    long lRetVal = -1;
    InitializeAppVariables();

    //
    // Following function configure the device to default state by cleaning
    // the persistent settings stored in NVMEM (viz. connection profiles &
    // policies, power policy etc)
    //
    // Applications may choose to skip this step if the developer is sure
    // that the device is in its default state at start of applicaton
    //
    // Note that all profiles and persistent settings that were done on the
    // device will be lost
    //
    lRetVal = ConfigureSimpleLinkToDefaultState();
    if(lRetVal < 0)
    {
    if (DEVICE_NOT_IN_STATION_MODE == lRetVal)
    UART_PRINT("Failed to configure the device in its default state\n\r");

    LOOP_FOREVER();
    }

    UART_PRINT("Device is configured in default state \n\r");

    memset(g_ucSSID,'\0',AP_SSID_LEN_MAX);

    //Read Device Mode Configuration
    ReadDeviceConfiguration();

    //Connect to Network
    lRetVal = ConnectToNetwork();

    //Stop Internal HTTP Server
    lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);
    if(lRetVal < 0)
    {
    ERR_PRINT(lRetVal);
    LOOP_FOREVER();
    }

    //Start Internal HTTP Server
    lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID);
    if(lRetVal < 0)
    {
    ERR_PRINT(lRetVal);
    LOOP_FOREVER();
    }

    //Handle Async Events
    while(1)
    {

    }
    }
    //*****************************************************************************
    //
    //! Application startup display on UART
    //!
    //! \param none
    //!
    //! \return none
    //!
    //*****************************************************************************
    static void
    DisplayBanner(char * AppName)
    {

    Report("\n\n\n\r");
    Report("\t\t *************************************************\n\r");
    Report("\t\t CC3200 %s Application \n\r", AppName);
    Report("\t\t *************************************************\n\r");
    Report("\n\n\n\r");
    }

    //*****************************************************************************
    //
    //! Board Initialization & Configuration
    //!
    //! \param None
    //!
    //! \return None
    //
    //*****************************************************************************
    static void
    BoardInit(void)
    {
    /* In case of TI-RTOS vector table is initialize by OS itself */
    #ifndef USE_TIRTOS
    //
    // Set vector table base
    //
    #if defined(ccs)
    MAP_IntVTableBaseSet((unsigned long)&g_pfnVectors[0]);
    #endif
    #if defined(ewarm)
    MAP_IntVTableBaseSet((unsigned long)&__vector_table);
    #endif
    #endif
    //
    // Enable Processor
    //
    MAP_IntMasterEnable();
    MAP_IntEnable(FAULT_SYSTICK);

    PRCMCC3200MCUInit();
    }

    //****************************************************************************
    // MAIN FUNCTION
    //****************************************************************************

    void main()
    {
    long lRetVal = -1;

    //Board Initialization
    BoardInit();

    //Pin Configuration
    PinMuxConfig();

    //Change Pin 58 Configuration from Default to Pull Down
    MAP_PinConfigSet(PIN_58,PIN_STRENGTH_2MA|PIN_STRENGTH_4MA,PIN_TYPE_STD_PD);

    //
    // Initialize GREEN and ORANGE LED
    //
    GPIO_IF_LedConfigure(LED1|LED2|LED3);
    //Turn Off the LEDs
    GPIO_IF_LedOff(MCU_ALL_LED_IND);

    //UART Initialization
    MAP_PRCMPeripheralReset(PRCM_UARTA0);

    MAP_UARTConfigSetExpClk(CONSOLE,MAP_PRCMPeripheralClockGet(CONSOLE_PERIPH),
    UART_BAUD_RATE,(UART_CONFIG_WLEN_8 |
    UART_CONFIG_STOP_ONE | UART_CONFIG_PAR_NONE));

    //Display Application Banner on UART Terminal
    DisplayBanner(APPLICATION_NAME);

    //
    // Simplelinkspawntask
    //
    lRetVal = VStartSimpleLinkSpawnTask(SPAWN_TASK_PRIORITY);
    if(lRetVal < 0)
    {
    UART_PRINT("Unable to start simpelink spawn task\n\r");
    LOOP_FOREVER();
    }
    //
    // Create HTTP Server Task
    //
    lRetVal = osi_TaskCreate(HTTPServerTask, (signed char*)"HTTPServerTask",
    OSI_STACK_SIZE, NULL, OOB_TASK_PRIORITY, NULL );
    if(lRetVal < 0)
    {
    UART_PRINT("Unable to create task\n\r");
    LOOP_FOREVER();
    }


    //
    // Create Filesystem Task
    //
    lRetVal = osi_TaskCreate(Update_IPConfig_file, (signed char*)"Update_IPConfig_file",
    OSI_STACK_SIZE, NULL, OOB_TASK_PRIORITY, NULL );
    if(lRetVal < 0)
    {
    UART_PRINT("Unable to create task\n\r");
    LOOP_FOREVER();
    }



    //
    // Start OS Scheduler
    //
    osi_start();

    while (1)
    {

    }

    }
  • Hello Aashish,
    I am very thankful to you for replying.

    I have created the task of updating file in main(), and used the long WriteFileToDevice(unsigned long *ulToken, long *lFileHandle) and ReadFileFromDevice(unsigned long ulToken, long lFileHandle) functions and their parameters from file_operations code...

    Awaiting you reply.

    Regards,
    Abhishek.
  • Hi Abhishek,


    Update_IPConfig_file is getting schedule before the n/w processor started/initialized and trying to access file system. That causing to break the flow. Please create file or performed file operation after the n/w processor started (After the final sl_start() call).


    Regards,
    Aashish
  • Hi Aashish,

    Sending you the complete application code here.....

    Please refer to the bold part in the code...

    //*****************************************************************************
    //
    // 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.
    //
    //*****************************************************************************

    //*****************************************************************************
    //
    // Application Name     -   HTTP Server
    // Application Overview -   This is a sample application demonstrating
    //                          interaction between HTTP Client(Browser) and
    //                          SimpleLink Device.The SimpleLink device runs an
    //                          HTTP Server and user can interact using web browser.
    // Application Details  -
    // http://processors.wiki.ti.com/index.php/CC32xx_HTTP_Server
    // or
    // doc\examples\CC32xx_HTTP_Server.pdf
    //
    //*****************************************************************************

    //****************************************************************************
    //
    //! \addtogroup httpserver
    //! @{
    //
    //****************************************************************************

    // Standard includes
    #include <string.h>
    #include <stdlib.h>

    // Simplelink includes
    #include "simplelink.h"
    #include "netcfg.h"

    //driverlib includes
    #include "hw_ints.h"
    #include "hw_types.h"
    #include "hw_memmap.h"
    #include "interrupt.h"
    #include "utils.h"
    #include "pin.h"
    #include "uart.h"
    #include "rom.h"
    #include "rom_map.h"
    #include "prcm.h"

    // Driverlib includes
    #include "hw_common_reg.h"

    //Free_rtos/ti-rtos includes
    #include "osi.h"

    #include "FreeRTOS.h"
    #include "task.h"
    #include "queue.h"
    #include "semphr.h"
    #include "portmacro.h"

    // common interface includes
    #include "gpio_if.h"
    #include "uart_if.h"
    #include "common.h"

    #include "smartconfig.h"
    #include "pinmux.h"


    #define APPLICATION_NAME        "HTTP Server"
    #define APPLICATION_VERSION     "1.1.0"
    #define AP_SSID_LEN_MAX         (33)
    #define ROLE_INVALID            (-5)

    #define LED_STRING              "LED"
    #define LED1_STRING             "LED1_"
    #define LED2_STRING             ",LED2_"
    #define LED_ON_STRING           "ON"
    #define LED_OFF_STRING          "OFF"

    #define OOB_TASK_PRIORITY               (1)
    #define FILE_TASK_PRIORITY              (2)
    #define OSI_STACK_SIZE                  (2048)
    #define SH_GPIO_3                       (3)  /* P58 - Device Mode */
    #define ROLE_INVALID                    (-5)
    #define AUTO_CONNECTION_TIMEOUT_COUNT   (50)   /* 5 Sec */


    #define SL_MAX_FILE_SIZE        1024L*1024L       /* 64KB file */
    #define BUF_SIZE                2048
    #define USER_FILE_NAME          "fs_demo.txt"

    #define USER_FILE_NAME1          "www/IP_Config.txt"
    #define USER_FILE_NAME2          "www/safe/SSID_Config.txt"

    // Application specific status/error codes
    typedef enum{
        // Choosing -0x7D0 to avoid overlap w/ host-driver's error codes
        LAN_CONNECTION_FAILED = -0x7D0,
        INTERNET_CONNECTION_FAILED = LAN_CONNECTION_FAILED - 1,
        DEVICE_NOT_IN_STATION_MODE = INTERNET_CONNECTION_FAILED - 1,

        FILE_ALREADY_EXIST = -0x7D0,
        FILE_CLOSE_ERROR = FILE_ALREADY_EXIST - 1,
        FILE_NOT_MATCHED = FILE_CLOSE_ERROR - 1,
        FILE_OPEN_READ_FAILED = FILE_NOT_MATCHED - 1,
        FILE_OPEN_WRITE_FAILED = FILE_OPEN_READ_FAILED -1,
        FILE_READ_FAILED = FILE_OPEN_WRITE_FAILED - 1,
        FILE_WRITE_FAILED = FILE_READ_FAILED - 1,

        STATUS_CODE_MAX = -0xBB8
    }e_AppStatusCodes;

    SlNetCfgIpV4Args_t Machine_IP_Config;

    ProfileConfig Profile_Config;
    ServerIPConfig Server_IP_Config;


    //*****************************************************************************
    //                 GLOBAL VARIABLES -- Start
    //*****************************************************************************
    // The queue used to send strings to the task2.
    QueueHandle_t xPrintQueue;
    unsigned char ptrlen ;
    unsigned long  g_ulStatus = 0;//SimpleLink Status
    unsigned long  g_ulPingPacketsRecv = 0; //Number of Ping Packets received
    unsigned long  g_ulGatewayIP = 0; //Network Gateway IP address
    unsigned char  g_ucConnectionSSID[SSID_LEN_MAX+1]; //Connection SSID
    unsigned char  g_ucConnectionBSSID[BSSID_LEN_MAX]; //Connection BSSID
    unsigned char POST_token[] = "__SL_P_ULD";
    unsigned char GET_token[]  = "__SL_G_ULD";
    int g_iSimplelinkRole = ROLE_INVALID;
    signed int g_uiIpAddress = 0;
    unsigned char g_ucSSID[AP_SSID_LEN_MAX];

    char Temp_IP_String[16];
    unsigned char Temp_SSID_String[32];
    unsigned char Temp_Priority_String[10];
    unsigned char bytes[4];
    int iCount = 0;
    unsigned char priority_status;

    void SET_STATIC_IPADDRESS(void);
    unsigned long IP_Parsing(char* Temp_IP_String1);
    static void Update_IPConfig_file(void *pvParameters);

    unsigned char IP_Config_Set = 0;
    unsigned char Profile_Config_Set = 0;

    unsigned char POST_token_DHCP[] = "__SL_P_UDH";
    unsigned char GET_token_DHCP[]  = "__SL_G_UDH";

    unsigned char POST_token_IPaddress[] = "__SL_P_UIP";
    unsigned char GET_token_IPaddress[]  = "__SL_G_UIP";

    unsigned char POST_token_SubnetMask[] = "__SL_P_USM";
    unsigned char GET_token_SubnetMask[]  = "__SL_G_USM";

    unsigned char POST_token_DefaultGateway[] = "__SL_P_UDG";
    unsigned char GET_token_DefaultGateway[]  = "__SL_G_UDG";

    unsigned char POST_token_DNSserver[] = "__SL_P_UDS";
    unsigned char GET_token_DNSserver[]  = "__SL_G_UDS";

    unsigned char POST_token_ServerIP[] = "__SL_P_USI";
    unsigned char GET_token_ServerIP[]  = "__SL_G_USI";

    unsigned char POST_token_PortNumber[] = "__SL_P_UPN";
    unsigned char GET_token_PortNumber[]  = "__SL_G_UPN";

    unsigned char POST_token_SSID[] = "__SL_P_USN";
    unsigned char GET_token_SSID[]  = "__SL_G_USN";

    unsigned char POST_token_SecurityType[] = "__SL_P_UST";
    unsigned char GET_token_SecurityType[]  = "__SL_G_UST";

    unsigned char POST_token_SecurityKey[] = "__SL_P_USK";
    unsigned char GET_token_SecurityKey[]  = "__SL_G_USK";

    unsigned char POST_token_ProfilePriority[] = "__SL_P_UPP";
    unsigned char GET_token_ProfilePriority[]  = "__SL_G_UPP";



    unsigned char gaucCmpBuf[BUF_SIZE];
    const unsigned char gaucOldMacDonald[] = "Old MacDonald had a farm,E-I-E-I-O, \
    And on his farm he had a cow, \
    E-I-E-I-O, \
    With a moo-moo here, \
    And a moo-moo there, \
    Here a moo, there a moo, \
    Everywhere a moo-moo. \
    Old MacDonald had a farm, \
    E-I-E-I-O. \
    Old MacDonald had a farm, \
    E-I-E-I-O, \
    And on his farm he had a pig, \
    E-I-E-I-O, \
    With an oink-oink here, \
    And an oink-oink there, \
    Here an oink, there an oink, \
    Everywhere an oink-oink. \
    Old MacDonald had a farm, \
    E-I-E-I-O. \
    Old MacDonald had a farm, \
    E-I-E-I-O, \
    And on his farm he had a duck, \
    E-I-E-I-O, \
    With a quack-quack here, \
    And a quack-quack there, \
    Here a quack, there a quack, \
    Everywhere a quack-quack. \
    Old MacDonald had a farm, \
    E-I-E-I-O. \
    Old MacDonald had a farm, \
    E-I-E-I-O, \
    And on his farm he had a horse, \
    E-I-E-I-O, \
    With a neigh-neigh here, \
    And a neigh-neigh there, \
    Here a neigh, there a neigh, \
    Everywhere a neigh-neigh. \
    Old MacDonald had a farm, \
    E-I-E-I-O. \
    Old MacDonald had a farm, \
    E-I-E-I-O, \
    And on his farm he had a donkey, \
    E-I-E-I-O, \
    With a hee-haw here, \
    And a hee-haw there, \
    Here a hee, there a hee, \
    Everywhere a hee-haw. \
    Old MacDonald had a farm, \
    E-I-E-I-O. \
    Old MacDonald had a farm, \
    E-I-E-I-O, \
    And on his farm he had some chickens, \
    E-I-E-I-O, \
    With a cluck-cluck here, \
    And a cluck-cluck there, \
    Here a cluck, there a cluck, \
    Everywhere a cluck-cluck. \
    Old MacDonald had a farm, \
    E-I-E-I-O.";

    long lRetVal;
    unsigned char policyVal;
    long lFileHandle;
    unsigned long ulToken;

    #if defined(ccs)
    extern void (* const g_pfnVectors[])(void);
    #endif
    #if defined(ewarm)
    extern uVectorEntry __vector_table;
    #endif
    //*****************************************************************************
    //                 GLOBAL VARIABLES -- End
    //*****************************************************************************


    //*****************************************************************************
    // Variable related to Connection status
    //*****************************************************************************
    volatile unsigned short g_usMCNetworkUstate = 0;

    int g_uiSimplelinkRole = ROLE_INVALID;
    unsigned int g_uiDeviceModeConfig = ROLE_STA; //default is STA mode
    unsigned char g_ucConnectTimeout =0;



    #ifdef USE_FREERTOS
    //*****************************************************************************
    // FreeRTOS User Hook Functions enabled in FreeRTOSConfig.h
    //*****************************************************************************

    //*****************************************************************************
    //
    //! \brief Application defined hook (or callback) function - assert
    //!
    //! \param[in]  pcFile - Pointer to the File Name
    //! \param[in]  ulLine - Line Number
    //!
    //! \return none
    //!
    //*****************************************************************************
    void
    vAssertCalled( const char *pcFile, unsigned long ulLine )
    {
        //Handle Assert here
        while(1)
        {
        }
    }

    //*****************************************************************************
    //
    //! \brief Application defined idle task hook
    //!
    //! \param  none
    //!
    //! \return none
    //!
    //*****************************************************************************
    void
    vApplicationIdleHook( void)
    {
        //Handle Idle Hook for Profiling, Power Management etc
    }

    //*****************************************************************************
    //
    //! \brief Application defined malloc failed hook
    //!
    //! \param  none
    //!
    //! \return none
    //!
    //*****************************************************************************
    void vApplicationMallocFailedHook()
    {
        //Handle Memory Allocation Errors
        while(1)
        {
        }
    }

    //*****************************************************************************
    //
    //! \brief Application defined stack overflow hook
    //!
    //! \param  none
    //!
    //! \return none
    //!
    //*****************************************************************************
    void vApplicationStackOverflowHook( OsiTaskHandle *pxTask,
                                       signed char *pcTaskName)
    {
        //Handle FreeRTOS Stack Overflow
        while(1)
        {
        }
    }
    #endif //USE_FREERTOS




    //*****************************************************************************
    //
    //!  This funtion includes the following steps:
    //!  -open a user file for writing
    //!  -write "Old MacDonalds" child song 37 times to get just below a 64KB file
    //!  -close the user file
    //!
    //!  /param[out] ulToken : file token
    //!  /param[out] lFileHandle : file handle
    //!
    //!  /return  0:Success, -ve: failure
    //
    //*****************************************************************************
    long WriteFileToDevice(unsigned long *ulToken, long *lFileHandle)
    {
        long lRetVal = -1;
        int iLoopCnt = 0;

        //
        //  create a user file
        //
        lRetVal = sl_FsOpen((unsigned char *)USER_FILE_NAME,
                    FS_MODE_OPEN_CREATE(65536, \
                              _FS_FILE_OPEN_FLAG_COMMIT|_FS_FILE_PUBLIC_WRITE),
                            ulToken,
                            lFileHandle);
        if(lRetVal < 0)
        {
            //
            // File may already be created
            //
            lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
            ASSERT_ON_ERROR(lRetVal);
        }
        else
        {
            //
            // close the user file
            //
            lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
            if (SL_RET_CODE_OK != lRetVal)
            {
                ASSERT_ON_ERROR(FILE_CLOSE_ERROR);
            }
        }

        //
        //  open a user file for writing
        //
        lRetVal = sl_FsOpen((unsigned char *)USER_FILE_NAME,
                            FS_MODE_OPEN_WRITE,
                            ulToken,
                            lFileHandle);
        if(lRetVal < 0)
        {
            lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
            ASSERT_ON_ERROR(FILE_OPEN_WRITE_FAILED);
        }

        //
        // write "Old MacDonalds" child song as many times to get just below a 64KB file
        //
        for (iLoopCnt = 0;
                iLoopCnt < (SL_MAX_FILE_SIZE / sizeof(gaucOldMacDonald));
                iLoopCnt++)
        {
            lRetVal = sl_FsWrite(*lFileHandle,
                        (unsigned int)(iLoopCnt * sizeof(gaucOldMacDonald)),
                        (unsigned char *)gaucOldMacDonald, sizeof(gaucOldMacDonald));
            if (lRetVal < 0)
            {
                lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
                ASSERT_ON_ERROR(FILE_WRITE_FAILED);
            }
        }

        //
        // close the user file
        //
        lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
        if (SL_RET_CODE_OK != lRetVal)
        {
            ASSERT_ON_ERROR(FILE_CLOSE_ERROR);
        }

        return SUCCESS;
    }

    //*****************************************************************************
    //
    //!  This funtion includes the following steps:
    //!    -open the user file for reading
    //!    -read the data and compare with the stored buffer
    //!    -close the user file
    //!
    //!  /param[in] ulToken : file token
    //!  /param[in] lFileHandle : file handle
    //!
    //!  /return 0: success, -ve:failure
    //
    //*****************************************************************************
    long ReadFileFromDevice(unsigned long ulToken, long lFileHandle)
    {
        long lRetVal = -1;
        int iLoopCnt = 0;

        //
        // open a user file for reading
        //
        lRetVal = sl_FsOpen((unsigned char *)USER_FILE_NAME,
                            FS_MODE_OPEN_READ,
                            &ulToken,
                            &lFileHandle);
        if(lRetVal < 0)
        {
            lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);
            ASSERT_ON_ERROR(FILE_OPEN_READ_FAILED);
        }

        //
        // read the data and compare with the stored buffer
        //
        for (iLoopCnt = 0;
                iLoopCnt < (SL_MAX_FILE_SIZE / sizeof(gaucOldMacDonald));
                iLoopCnt++)
        {
            lRetVal = sl_FsRead(lFileHandle,
                        (unsigned int)(iLoopCnt * sizeof(gaucOldMacDonald)),
                         gaucCmpBuf, sizeof(gaucOldMacDonald));
            if ((lRetVal < 0) || (lRetVal != sizeof(gaucOldMacDonald)))
            {
                lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);
                ASSERT_ON_ERROR(FILE_READ_FAILED);
            }

            lRetVal = memcmp(gaucOldMacDonald,
                             gaucCmpBuf,
                             sizeof(gaucOldMacDonald));
            if (lRetVal != 0)
            {
                ASSERT_ON_ERROR(FILE_NOT_MATCHED);
            }
        }

        //
        // close the user file
        //
        lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);
        if (SL_RET_CODE_OK != lRetVal)
        {
            ASSERT_ON_ERROR(FILE_CLOSE_ERROR);
        }

        return SUCCESS;
    }



    //*****************************************************************************
    //                 SETTING THE STATIC IP ADDRESS
    //*****************************************************************************


    void SET_STATIC_IPADDRESS(void)
    {

      Machine_IP_Config.ipV4          = (_u32)SL_IPV4_VAL(192,168,100,5);            // _u32 IP address
      Machine_IP_Config.ipV4Mask      = (_u32)SL_IPV4_VAL(255,255,255,0);         // _u32 Subnet mask for this STA/P2P
      Machine_IP_Config.ipV4Gateway   = (_u32)SL_IPV4_VAL(192,168,100,50);              // _u32 Default gateway address
      Machine_IP_Config.ipV4DnsServer = (_u32)SL_IPV4_VAL(192,168,100,23);            // _u32 DNS server address
    }


    //*****************************************************************************
    //                 IP Address Parsing (AtoI)
    //*****************************************************************************


    unsigned long IP_Parsing(char* Temp_IP_String1)
    {
      long Address;

                iCount = 0;

                char* buff = malloc(ptrlen+1);
                buff = strtok(Temp_IP_String1,".");
                while (buff != NULL)
                {
                  //if you want to print its value
                  //printf("%s\n",buff);
                  //and also if you want to save each byte
                  bytes[iCount] = (unsigned char)atoi(buff);
                  buff = strtok(NULL,".");
                  iCount++;
                }
                free(buff);
                Address = (_u32)SL_IPV4_VAL(bytes[0], bytes[1], bytes[2], bytes[3]);
                return Address;
    }


    //*****************************************************************************
    //                 Updating IP Configuration file
    //*****************************************************************************


    static void Update_IPConfig_file (void *pvParameters)
    {
           /*char*           DeviceFileName = "MyFile.txt";
           unsigned long   MaxSize = 63 * 1024; //62.5K is max file size
           long            DeviceFileHandle = -1;
           long            lRetVal;        //negative retval is an error
           unsigned long   Offset = 0;
           unsigned char   InputBuffer[100];

           // Create a file and write data. The file in this example is secured, without signature and with a fail safe commit
           lRetVal = sl_FsOpen((unsigned char *)DeviceFileName,
                                            FS_MODE_OPEN_CREATE(MaxSize , _FS_FILE_OPEN_FLAG_NO_SIGNATURE_TEST | _FS_FILE_OPEN_FLAG_COMMIT ),
                                            NULL, &DeviceFileHandle);

               if(lRetVal < 0)
        {
            //
            // File may already be created
            //
            lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);
            ASSERT_ON_ERROR(lRetVal);
        }
        else
        {
            //
            // close the user file
            //
            lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);
            if (SL_RET_CODE_OK != lRetVal)
            {
                ASSERT_ON_ERROR(FILE_CLOSE_ERROR);
            }
        }*/


        if(WriteFileToDevice(&ulToken, &lFileHandle) < 0)
        {
            GPIO_IF_LedOn(MCU_RED_LED_GPIO);
            LOOP_FOREVER();
        }

        if(ReadFileFromDevice(ulToken, lFileHandle) < 0)
        {
            GPIO_IF_LedOn(MCU_RED_LED_GPIO);
             LOOP_FOREVER();
        }
    }


    //*****************************************************************************
    // SimpleLink Asynchronous Event Handlers -- Start
    //*****************************************************************************


    //*****************************************************************************
    //
    //! \brief The Function Handles WLAN Events
    //!
    //! \param[in]  pWlanEvent - Pointer to WLAN Event Info
    //!
    //! \return None
    //!
    //*****************************************************************************
    void SimpleLinkWlanEventHandler(SlWlanEvent_t *pWlanEvent)
    {
        if(!pWlanEvent)
        {
            return;
        }

        switch(pWlanEvent->Event)
        {
            case SL_WLAN_CONNECT_EVENT:
            {
                SET_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION);

                //
                // 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;
                //

                // 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);

                UART_PRINT("[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]);
            }
            break;

            case SL_WLAN_DISCONNECT_EVENT:
            {
                slWlanConnectAsyncResponse_t*  pEventData = NULL;

                CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION);
                CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_AQUIRED);

                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)
                {
                    UART_PRINT("[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]);
                }
                else
                {
                    UART_PRINT("[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]);
                }
                memset(g_ucConnectionSSID,0,sizeof(g_ucConnectionSSID));
                memset(g_ucConnectionBSSID,0,sizeof(g_ucConnectionBSSID));
            }
            break;

            case SL_WLAN_STA_CONNECTED_EVENT:
            {
                // when device is in AP mode and any client connects to device cc3xxx
                SET_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION);
                CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION_FAILED);

                //
                // Information about the connected client (like SSID, MAC etc) will
                // be available in 'slPeerInfoAsyncResponse_t' - Applications
                // can use it if required
                //
                // slPeerInfoAsyncResponse_t *pEventData = NULL;
                // pEventData = &pSlWlanEvent->EventData.APModeStaConnected;
                //

            }
            break;

            case SL_WLAN_STA_DISCONNECTED_EVENT:
            {
                // when client disconnects from device (AP)
                CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION);
                CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_LEASED);

                //
                // Information about the connected client (like SSID, MAC etc) will
                // be available in 'slPeerInfoAsyncResponse_t' - Applications
                // can use it if required
                //
                // slPeerInfoAsyncResponse_t *pEventData = NULL;
                // pEventData = &pSlWlanEvent->EventData.APModestaDisconnected;
                //
            }
            break;

            case SL_WLAN_SMART_CONFIG_COMPLETE_EVENT:
            {
                SET_STATUS_BIT(g_ulStatus, STATUS_BIT_SMARTCONFIG_START);

                //
                // Information about the SmartConfig details (like Status, SSID,
                // Token etc) will be available in 'slSmartConfigStartAsyncResponse_t'
                // - Applications can use it if required
                //
                //  slSmartConfigStartAsyncResponse_t *pEventData = NULL;
                //  pEventData = &pSlWlanEvent->EventData.smartConfigStartResponse;
                //

            }
            break;

            case SL_WLAN_SMART_CONFIG_STOP_EVENT:
            {
                // SmartConfig operation finished
                CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_SMARTCONFIG_START);

                //
                // Information about the SmartConfig details (like Status, padding
                // etc) will be available in 'slSmartConfigStopAsyncResponse_t' -
                // Applications can use it if required
                //
                // slSmartConfigStopAsyncResponse_t *pEventData = NULL;
                // pEventData = &pSlWlanEvent->EventData.smartConfigStopResponse;
                //
            }
            break;

            case SL_WLAN_P2P_DEV_FOUND_EVENT:
            {
                SET_STATUS_BIT(g_ulStatus, STATUS_BIT_P2P_DEV_FOUND);

                //
                // Information about P2P config details (like Peer device name, own
                // SSID etc) will be available in 'slPeerInfoAsyncResponse_t' -
                // Applications can use it if required
                //
                // slPeerInfoAsyncResponse_t *pEventData = NULL;
                // pEventData = &pSlWlanEvent->EventData.P2PModeDevFound;
                //
            }
            break;

            case SL_WLAN_P2P_NEG_REQ_RECEIVED_EVENT:
            {
                SET_STATUS_BIT(g_ulStatus, STATUS_BIT_P2P_REQ_RECEIVED);

                //
                // Information about P2P Negotiation req details (like Peer device
                // name, own SSID etc) will be available in 'slPeerInfoAsyncResponse_t'
                //  - Applications can use it if required
                //
                // slPeerInfoAsyncResponse_t *pEventData = NULL;
                // pEventData = &pSlWlanEvent->EventData.P2PModeNegReqReceived;
                //
            }
            break;

            case SL_WLAN_CONNECTION_FAILED_EVENT:
            {
                // If device gets any connection failed event
                SET_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION_FAILED);
            }
            break;

            default:
            {
                UART_PRINT("[WLAN EVENT] Unexpected event [0x%x]\n\r",
                           pWlanEvent->Event);
            }
            break;
        }
    }

    //*****************************************************************************
    //
    //! \brief This function handles network events such as IP acquisition, IP
    //!           leased, IP released etc.
    //!
    //! \param[in]  pNetAppEvent - Pointer to NetApp Event Info
    //!
    //! \return None
    //!
    //*****************************************************************************
    void SimpleLinkNetAppEventHandler(SlNetAppEvent_t *pNetAppEvent)
    {
        if(!pNetAppEvent)
        {
            return;
        }

        switch(pNetAppEvent->Event)
        {
            case SL_NETAPP_IPV4_IPACQUIRED_EVENT:
            {
                SlIpV4AcquiredAsync_t *pEventData = NULL;

                SET_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_AQUIRED);

                //Ip Acquired Event Data
                pEventData = &pNetAppEvent->EventData.ipAcquiredV4;
                g_uiIpAddress = pEventData->ip;

                //Gateway IP address
                g_ulGatewayIP = pEventData->gateway;

                /*UART_PRINT("[NETAPP EVENT] IP Acquired: IP=%d.%d.%d.%d , "
                "Gateway=%d.%d.%d.%d\n\r",
                SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,3),
                SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,2),
                SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,1),
                SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,0),
                SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,3),
                SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,2),
                SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,1),
                SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,0));
                */
            }
            break;

            case SL_NETAPP_IP_LEASED_EVENT:
            {
                SET_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_LEASED);

                //
                // Information about the IP-Leased details(like IP-Leased,lease-time,
                // mac etc) will be available in 'SlIpLeasedAsync_t' - Applications
                // can use it if required
                //
                // SlIpLeasedAsync_t *pEventData = NULL;
                // pEventData = &pNetAppEvent->EventData.ipLeased;
                //

            }
            break;

            case SL_NETAPP_IP_RELEASED_EVENT:
            {
                CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_LEASED);

                //
                // Information about the IP-Released details (like IP-address, mac
                // etc) will be available in 'SlIpReleasedAsync_t' - Applications
                // can use it if required
                //
                // SlIpReleasedAsync_t *pEventData = NULL;
                // pEventData = &pNetAppEvent->EventData.ipReleased;
                //
            }
            break;

            default:
            {
                UART_PRINT("[NETAPP EVENT] Unexpected event [0x%x] \n\r",
                           pNetAppEvent->Event);
            }
            break;
        }
    }

    //*****************************************************************************
    //
    //! This function handles socket events indication
    //!
    //! \param[in]      pSock - Pointer to Socket Event Info
    //!
    //! \return None
    //!
    //*****************************************************************************
    void SimpleLinkSockEventHandler(SlSockEvent_t *pSock)
    {
        //
        // This application doesn't work w/ socket - Events are not expected
        //

    }


    //*****************************************************************************
    //
    //! This function gets triggered when HTTP Server receives Application
    //! defined GET and POST HTTP Tokens.
    //!
    //! \param pHttpServerEvent Pointer indicating http server event
    //! \param pHttpServerResponse Pointer indicating http server response
    //!
    //! \return None
    //!
    //*****************************************************************************
    void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pSlHttpServerEvent,
                                   SlHttpServerResponse_t *pSlHttpServerResponse)
    {
        unsigned char strLenVal = 0;

        if(!pSlHttpServerEvent || !pSlHttpServerResponse)
        {
            return;
        }


        switch (pSlHttpServerEvent->Event)
        {
            case SL_NETAPP_HTTPGETTOKENVALUE_EVENT:
            {
              unsigned char status, *ptr;

              ptr = pSlHttpServerResponse->ResponseData.token_value.data;
              pSlHttpServerResponse->ResponseData.token_value.len = 0;
              if(memcmp(pSlHttpServerEvent->EventData.httpTokenName.data, GET_token,
                        strlen((const char *)GET_token)) == 0)
              {
                status = GPIO_IF_LedStatus(MCU_RED_LED_GPIO);
                strLenVal = strlen(LED1_STRING);
                memcpy(ptr, LED1_STRING, strLenVal);
                ptr += strLenVal;
                pSlHttpServerResponse->ResponseData.token_value.len += strLenVal;
                if(status & 0x01)
                {
                  strLenVal = strlen(LED_ON_STRING);
                  memcpy(ptr, LED_ON_STRING, strLenVal);
                  ptr += strLenVal;
                  pSlHttpServerResponse->ResponseData.token_value.len += strLenVal;
                }
                else
                {
                  strLenVal = strlen(LED_OFF_STRING);
                  memcpy(ptr, LED_OFF_STRING, strLenVal);
                  ptr += strLenVal;
                  pSlHttpServerResponse->ResponseData.token_value.len += strLenVal;
                }
                status = GPIO_IF_LedStatus(MCU_GREEN_LED_GPIO);
                strLenVal = strlen(LED2_STRING);
                memcpy(ptr, LED2_STRING, strLenVal);
                ptr += strLenVal;
                pSlHttpServerResponse->ResponseData.token_value.len += strLenVal;
                if(status & 0x01)
                {
                  strLenVal = strlen(LED_ON_STRING);
                  memcpy(ptr, LED_ON_STRING, strLenVal);
                  ptr += strLenVal;
                  pSlHttpServerResponse->ResponseData.token_value.len += strLenVal;
                }
                else
                {
                  strLenVal = strlen(LED_OFF_STRING);
                  memcpy(ptr, LED_OFF_STRING, strLenVal);
                  ptr += strLenVal;
                  pSlHttpServerResponse->ResponseData.token_value.len += strLenVal;
                }
                *ptr = '\0';
              }

            }
            break;

            case SL_NETAPP_HTTPPOSTTOKENVALUE_EVENT:
            {
              unsigned char led;
              unsigned char *ptr = pSlHttpServerEvent->EventData.httpPostData.token_name.data;

              if(memcmp(ptr, POST_token, strlen((const char *)POST_token)) == 0)
              {
                ptr = pSlHttpServerEvent->EventData.httpPostData.token_value.data;
                strLenVal = strlen(LED_STRING);
                if(memcmp(ptr, LED_STRING, strLenVal) != 0)
                  break;
                ptr += strLenVal;
                led = *ptr;
                strLenVal = strlen(LED_ON_STRING);
                ptr += strLenVal;
                if(led == '1')
                {
                  if(memcmp(ptr, LED_ON_STRING, strLenVal) == 0)
                  {
                          GPIO_IF_LedOn(MCU_RED_LED_GPIO);
                  }
                  else
                  {
                          GPIO_IF_LedOff(MCU_RED_LED_GPIO);
                  }
                }
                else if(led == '2')
                {
                  if(memcmp(ptr, LED_ON_STRING, strLenVal) == 0)
                  {
                          GPIO_IF_LedOn(MCU_GREEN_LED_GPIO);
                  }
                  else
                  {
                          GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);
                  }
                }

              }


              if(memcmp(ptr, POST_token_DHCP, strlen((const char *)POST_token_DHCP)) == 0)
              {

              }

              else if(memcmp(ptr, POST_token_IPaddress, strlen((const char *)POST_token_IPaddress)) == 0)
              {
                ptr = pSlHttpServerEvent->EventData.httpPostData.token_value.data;
                ptrlen =0;
                memset(bytes,0,4);
                memset(Temp_IP_String,0,16);
                while(ptrlen <= (pSlHttpServerEvent->EventData.httpPostData.token_value.len))
                {
                  Temp_IP_String[ptrlen] = *ptr;
                  ptr++;
                  ptrlen++;
                }

                Machine_IP_Config.ipV4 = IP_Parsing(Temp_IP_String);
              }

              else if(memcmp(ptr, POST_token_SubnetMask, strlen((const char *)POST_token_SubnetMask)) == 0)
              {
                ptr = pSlHttpServerEvent->EventData.httpPostData.token_value.data;
                ptrlen =0;
                memset(bytes,0,4);
                memset(Temp_IP_String,0,16);
                while(ptrlen <= (pSlHttpServerEvent->EventData.httpPostData.token_value.len))
                {
                  Temp_IP_String[ptrlen] = *ptr;
                  ptr++;
                  ptrlen++;
                }

                Machine_IP_Config.ipV4Mask = IP_Parsing(Temp_IP_String);
              }

              else if(memcmp(ptr, POST_token_DefaultGateway, strlen((const char *)POST_token_DefaultGateway)) == 0)
              {
                ptr = pSlHttpServerEvent->EventData.httpPostData.token_value.data;
                ptrlen =0;
                memset(bytes,0,4);
                memset(Temp_IP_String,0,16);
                while(ptrlen <= (pSlHttpServerEvent->EventData.httpPostData.token_value.len))
                {
                  Temp_IP_String[ptrlen] = *ptr;
                  ptr++;
                  ptrlen++;
                }

                Machine_IP_Config.ipV4Gateway = IP_Parsing(Temp_IP_String);
              }

              else if(memcmp(ptr, POST_token_DNSserver, strlen((const char *)POST_token_DNSserver)) == 0)
              {
                ptr = pSlHttpServerEvent->EventData.httpPostData.token_value.data;
                ptrlen =0;
                memset(bytes,0,4);
                memset(Temp_IP_String,0,16);
                while(ptrlen <= (pSlHttpServerEvent->EventData.httpPostData.token_value.len))
                {
                  Temp_IP_String[ptrlen] = *ptr;
                  ptr++;
                  ptrlen++;
                }

                Machine_IP_Config.ipV4DnsServer = IP_Parsing(Temp_IP_String);         // _u32 DNS server address
              }

              else if(memcmp(ptr, POST_token_ServerIP, strlen((const char *)POST_token_ServerIP)) == 0)
              {
                ptr = pSlHttpServerEvent->EventData.httpPostData.token_value.data;
                ptrlen =0;
                memset(bytes,0,4);
                memset(Temp_IP_String,0,16);
                while(ptrlen <= (pSlHttpServerEvent->EventData.httpPostData.token_value.len))
                {
                  Temp_IP_String[ptrlen] = *ptr;
                  ptr++;
                  ptrlen++;
                }

                Server_IP_Config.ServerIP = IP_Parsing(Temp_IP_String);         // _u32 DNS server address
              }

              else if(memcmp(ptr, POST_token_PortNumber, strlen((const char *)POST_token_PortNumber)) == 0)
              {
              ptr = pSlHttpServerEvent->EventData.httpPostData.token_value.data;
              ptrlen =0;
              memset(Temp_IP_String,0,16);
              while(ptrlen < (pSlHttpServerEvent->EventData.httpPostData.token_value.len))
              {
               Temp_IP_String[ptrlen] = *ptr;
               ptr++;
               ptrlen++;
              }

              Server_IP_Config.Server_Port = atoi(Temp_IP_String);

    This is where my complete data is received. I want to store the Machine_IP_Config and Server_IP_Config structures onto a .txt file. So i call Update_IPConfig_file function here. According to you, from exactly where should i call this function ??

              //Update_IPConfig_file();       //Updating the IP config file
              }

              else if(memcmp(ptr, POST_token_SSID, strlen((const char *)POST_token_SSID)) == 0)
              {
              ptr = pSlHttpServerEvent->EventData.httpPostData.token_value.data;
              ptrlen =0;
              memset(Temp_SSID_String,0,32);
              while(ptrlen < (pSlHttpServerEvent->EventData.httpPostData.token_value.len))
              {
               Temp_SSID_String[ptrlen] = *ptr;
               ptr++;
               ptrlen++;
              }
              for(iCount = 0; iCount < (pSlHttpServerEvent->EventData.httpPostData.token_value.len); iCount++)
              {
              Profile_Config.SSID[iCount] = Temp_SSID_String[iCount];
              }
             }

              else if(memcmp(ptr, POST_token_SecurityType, strlen((const char *)POST_token_SecurityType)) == 0)
              {
              ptr = pSlHttpServerEvent->EventData.httpPostData.token_value.data;
              priority_status = (*ptr - 0x30);

      switch(priority_status)
      {
              case 0:
              {
                Profile_Config.Security_Type = SL_SEC_TYPE_OPEN;
                break;
              }
              case 1:
              {
                Profile_Config.Security_Type = SL_SEC_TYPE_WEP;
                break;
              }
              case 2:
              {
                Profile_Config.Security_Type = SL_SEC_TYPE_WPA;
                break;
              }
              case 3:
              {
                Profile_Config.Security_Type = SL_SEC_TYPE_WPA_WPA2;
                break;
              }
          default:
          break;
      }

              }

              else if(memcmp(ptr, POST_token_SecurityKey, strlen((const char *)POST_token_SecurityKey)) == 0)
              {
              ptr = pSlHttpServerEvent->EventData.httpPostData.token_value.data;
              ptrlen =0;
              memset(Temp_SSID_String,0,32);
              while(ptrlen < (pSlHttpServerEvent->EventData.httpPostData.token_value.len))
              {
               Temp_SSID_String[ptrlen] = *ptr;
               ptr++;
               ptrlen++;
              }
              for(iCount = 0; iCount < (pSlHttpServerEvent->EventData.httpPostData.token_value.len); iCount++)
              {
              Profile_Config.Security_Key[iCount] = Temp_SSID_String[iCount];
              }
              }

              else if(memcmp(ptr, POST_token_ProfilePriority, strlen((const char *)POST_token_ProfilePriority)) == 0)
              {
              ptr = pSlHttpServerEvent->EventData.httpPostData.token_value.data;
              priority_status = (*ptr - 0x30);
              Profile_Config.Priority = priority_status;
              }

            }
              break;
            default:
              break;
        }
    }

    //*****************************************************************************
    //
    //! \brief This function initializes the application variables
    //!
    //! \param    None
    //!
    //! \return None
    //!
    //*****************************************************************************
    static void InitializeAppVariables()
    {
        g_ulStatus = 0;
        g_uiIpAddress = 0;
    }


    //*****************************************************************************
    //! \brief This function puts the device in its default state. It:
    //!           - Set 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
    //!           - Unregister mDNS services
    //!           - Remove all filters
    //!
    //! \param   none
    //! \return  On success, zero is returned. On error, negative is returned
    //*****************************************************************************
    static long ConfigureSimpleLinkToDefaultState()
    {
        SlVersionFull   ver = {0};
        _WlanRxFilterOperationCommandBuff_t  RxFilterIdMask = {0};

        unsigned char ucVal = 1;
        unsigned char ucConfigOpt = 0;
        unsigned char ucConfigLen = 0;
        unsigned char ucPower = 0;

        long lRetVal = -1;
        long lMode = -1;

        lMode = sl_Start(0, 0, 0);
        ASSERT_ON_ERROR(lMode);

        // If the device is not in station-mode, try configuring it in station-mode
        if (ROLE_STA != lMode)
        {
            if (ROLE_AP == lMode)
            {
                // If the device is in AP mode, we need to wait for this event
                // before doing anything
                while(!IS_IP_ACQUIRED(g_ulStatus))
                {
    #ifndef SL_PLATFORM_MULTI_THREADED
                  _SlNonOsMainLoopTask();
    #endif
                }
            }

            // Switch to STA role and restart
            lRetVal = sl_WlanSetMode(ROLE_STA);
            ASSERT_ON_ERROR(lRetVal);

            lRetVal = sl_Stop(0xFF);
            ASSERT_ON_ERROR(lRetVal);

            lRetVal = sl_Start(0, 0, 0);
            ASSERT_ON_ERROR(lRetVal);

            // Check if the device is in station again
            if (ROLE_STA != lRetVal)
            {
                // We don't want to proceed if the device is not coming up in STA-mode
                return DEVICE_NOT_IN_STATION_MODE;
            }
        }

        // Get the device's version-information
        ucConfigOpt = SL_DEVICE_GENERAL_VERSION;
        ucConfigLen = sizeof(ver);
        lRetVal = sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION, &ucConfigOpt,
                                    &ucConfigLen, (unsigned char *)(&ver));
        ASSERT_ON_ERROR(lRetVal);

        UART_PRINT("Host Driver Version: %s\n\r",SL_DRIVER_VERSION);
        UART_PRINT("Build Version %d.%d.%d.%d.31.%d.%d.%d.%d.%d.%d.%d.%d\n\r",
        ver.NwpVersion[0],ver.NwpVersion[1],ver.NwpVersion[2],ver.NwpVersion[3],
        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]);

        // Set connection policy to Auto + SmartConfig
        //      (Device's default connection policy)
        lRetVal = sl_WlanPolicySet(SL_POLICY_CONNECTION,
                                    SL_CONNECTION_POLICY(1, 0, 0, 0, 1), NULL, 0);
        ASSERT_ON_ERROR(lRetVal);

        // Remove all profiles
        lRetVal = sl_WlanProfileDel(0xFF);
        ASSERT_ON_ERROR(lRetVal);



        //
        // 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
        //
        lRetVal = sl_WlanDisconnect();
        if(0 == lRetVal)
        {
            // Wait
            while(IS_CONNECTED(g_ulStatus))
            {
    #ifndef SL_PLATFORM_MULTI_THREADED
                  _SlNonOsMainLoopTask();
    #endif
            }
        }

        // Enable DHCP client
        lRetVal = sl_NetCfgSet(SL_IPV4_STA_P2P_CL_DHCP_ENABLE,1,1,&ucVal);
        ASSERT_ON_ERROR(lRetVal);

        // Disable scan
        ucConfigOpt = SL_SCAN_POLICY(0);
        lRetVal = sl_WlanPolicySet(SL_POLICY_SCAN , ucConfigOpt, NULL, 0);
        ASSERT_ON_ERROR(lRetVal);

        // Set Tx power level for station mode
        // Number between 0-15, as dB offset from max power - 0 will set max power
        ucPower = 0;
        lRetVal = sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID,
                WLAN_GENERAL_PARAM_OPT_STA_TX_POWER, 1, (unsigned char *)&ucPower);
        ASSERT_ON_ERROR(lRetVal);

        // Set PM policy to normal
        lRetVal = sl_WlanPolicySet(SL_POLICY_PM , SL_NORMAL_POLICY, NULL, 0);
        ASSERT_ON_ERROR(lRetVal);

        // Unregister mDNS services
        lRetVal = sl_NetAppMDNSUnRegisterService(0, 0);
        ASSERT_ON_ERROR(lRetVal);

        // Remove  all 64 filters (8*8)
        memset(RxFilterIdMask.FilterIdMask, 0xFF, 8);
        lRetVal = sl_WlanRxFilterSet(SL_REMOVE_RX_FILTER, (_u8 *)&RxFilterIdMask,
                           sizeof(_WlanRxFilterOperationCommandBuff_t));
        ASSERT_ON_ERROR(lRetVal);

        lRetVal = sl_Stop(SL_STOP_TIMEOUT);
        ASSERT_ON_ERROR(lRetVal);

        InitializeAppVariables();

        return lRetVal; // Success
    }



    //****************************************************************************
    //
    //!    \brief Connects to the Network in AP or STA Mode - If ForceAP Jumper is
    //!                                             Placed, Force it to AP mode
    //!
    //! \return                        0 on success else error code
    //
    //****************************************************************************
    long ConnectToNetwork()
    {
        char ucAPSSID[32];
        unsigned short len, config_opt;
        long lRetVal = -1;

        // staring simplelink
        g_uiSimplelinkRole =  sl_Start(NULL,NULL,NULL);

        // Device is not in STA mode and Force AP Jumper is not Connected
        //- Switch to STA mode
        if(g_uiSimplelinkRole != ROLE_STA && g_uiDeviceModeConfig == ROLE_STA )
        {
            //Switch to STA Mode
            lRetVal = sl_WlanSetMode(ROLE_STA);
            ASSERT_ON_ERROR(lRetVal);

            lRetVal = sl_Stop(SL_STOP_TIMEOUT);

            g_usMCNetworkUstate = 0;
            g_uiSimplelinkRole =  sl_Start(NULL,NULL,NULL);
        }

        //Device is not in AP mode and Force AP Jumper is Connected -
        //Switch to AP mode
        if(g_uiSimplelinkRole != ROLE_AP && g_uiDeviceModeConfig == ROLE_AP )
        {
             //Switch to AP Mode
            lRetVal = sl_WlanSetMode(ROLE_AP);
            ASSERT_ON_ERROR(lRetVal);

            lRetVal = sl_Stop(SL_STOP_TIMEOUT);

            g_usMCNetworkUstate = 0;
            g_uiSimplelinkRole =  sl_Start(NULL,NULL,NULL);
        }

        //No Mode Change Required
        if(g_uiSimplelinkRole == ROLE_AP)
        {
           //waiting for the AP to acquire IP address from Internal DHCP Server
           while(!IS_IP_ACQUIRED(g_ulStatus))
           {

           }

           //Stop Internal HTTP Server
           lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);
           ASSERT_ON_ERROR( lRetVal);

           //Start Internal HTTP Server
           lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID);
           ASSERT_ON_ERROR( lRetVal);

           char iCount=0;
           //Read the AP SSID
           memset(ucAPSSID,'\0',AP_SSID_LEN_MAX);
           len = AP_SSID_LEN_MAX;
           config_opt = WLAN_AP_OPT_SSID;
           lRetVal = sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt , &len,
                                                  (unsigned char*) ucAPSSID);
            ASSERT_ON_ERROR(lRetVal);

           Report("\n\rDevice is in AP Mode, Please Connect to AP [%s] and"
              "type [mysimplelink.net] in the browser \n\r",ucAPSSID);

           //Blink LED 3 times to Indicate AP Mode
           for(iCount=0;iCount<3;iCount++)
           {
               //Turn RED LED On
               GPIO_IF_LedOn(MCU_RED_LED_GPIO);
               osi_Sleep(400);

               //Turn RED LED Off
               GPIO_IF_LedOff(MCU_RED_LED_GPIO);
               osi_Sleep(400);
           }

        }
        else
        {
            //Stop Internal HTTP Server
            lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);
            ASSERT_ON_ERROR( lRetVal);

            //Start Internal HTTP Server
            lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID);
            ASSERT_ON_ERROR( lRetVal);

            //waiting for the device to Auto Connect
            while ( (!IS_IP_ACQUIRED(g_ulStatus))&&
                   g_ucConnectTimeout < AUTO_CONNECTION_TIMEOUT_COUNT)
            {
                //Turn RED LED On
                GPIO_IF_LedOn(MCU_RED_LED_GPIO);
                osi_Sleep(50);

                //Turn RED LED Off
                GPIO_IF_LedOff(MCU_RED_LED_GPIO);
                osi_Sleep(50);

                g_ucConnectTimeout++;
            }
            //Couldn't connect Using Auto Profile
            if(g_ucConnectTimeout == AUTO_CONNECTION_TIMEOUT_COUNT)
            {
                //Blink Red LED to Indicate Connection Error
                GPIO_IF_LedOn(MCU_RED_LED_GPIO);

                CLR_STATUS_BIT_ALL(g_ulStatus);

                Report("Use Smart Config Application to configure the device.\n\r");
                //Connect Using Smart Config
                lRetVal = SmartConfigConnect();
                ASSERT_ON_ERROR(lRetVal);

                //Waiting for the device to Auto Connect
                while(!IS_IP_ACQUIRED(g_ulStatus))
                {
                    MAP_UtilsDelay(500);
                }

            }
        //Turn RED LED Off
        GPIO_IF_LedOff(MCU_RED_LED_GPIO);
        UART_PRINT("\n\rDevice is in STA Mode, Connect to the AP[%s] and type"
              "IP address [%d.%d.%d.%d] in the browser \n\r",g_ucConnectionSSID,
              SL_IPV4_BYTE(g_uiIpAddress,3),SL_IPV4_BYTE(g_uiIpAddress,2),
              SL_IPV4_BYTE(g_uiIpAddress,1),SL_IPV4_BYTE(g_uiIpAddress,0));

        }
        return SUCCESS;
    }


    //****************************************************************************
    //
    //!    \brief Read Force AP GPIO and Configure Mode - 1(Access Point Mode)
    //!                                                  - 0 (Station Mode)
    //!
    //! \return                        None
    //
    //****************************************************************************
    static void ReadDeviceConfiguration()
    {
        unsigned int uiGPIOPort;
        unsigned char pucGPIOPin;
        unsigned char ucPinValue;

            //Read GPIO
        GPIO_IF_GetPortNPin(SH_GPIO_3,&uiGPIOPort,&pucGPIOPin);
        ucPinValue = GPIO_IF_Get(SH_GPIO_3,uiGPIOPort,pucGPIOPin);

            //If Connected to VCC, Mode is AP
        if(ucPinValue == 1)
        {
                //AP Mode
                g_uiDeviceModeConfig = ROLE_AP;
        }
        else
        {
                //STA Mode
                g_uiDeviceModeConfig = ROLE_STA;
        }

    }

    //****************************************************************************
    //
    //!  \brief                     Handles HTTP Server Task
    //!
    //! \param[in]                  pvParameters is the data passed to the Task
    //!
    //! \return                        None
    //
    //****************************************************************************
    static void HTTPServerTask(void *pvParameters)
    {
        long lRetVal = -1;
        InitializeAppVariables();

        //
        // Following function configure the device to default state by cleaning
        // the persistent settings stored in NVMEM (viz. connection profiles &
        // policies, power policy etc)
        //
        // Applications may choose to skip this step if the developer is sure
        // that the device is in its default state at start of applicaton
        //
        // Note that all profiles and persistent settings that were done on the
        // device will be lost
        //
        lRetVal = ConfigureSimpleLinkToDefaultState();
        if(lRetVal < 0)
        {
            if (DEVICE_NOT_IN_STATION_MODE == lRetVal)
                UART_PRINT("Failed to configure the device in its default state\n\r");

            LOOP_FOREVER();
        }

        UART_PRINT("Device is configured in default state \n\r");

        memset(g_ucSSID,'\0',AP_SSID_LEN_MAX);

        //Read Device Mode Configuration
        ReadDeviceConfiguration();

        //Connect to Network
        lRetVal = ConnectToNetwork();

        //Stop Internal HTTP Server
        lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);
        if(lRetVal < 0)
        {
            ERR_PRINT(lRetVal);
            LOOP_FOREVER();
        }

        //Start Internal HTTP Server
        lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID);
        if(lRetVal < 0)
        {
            ERR_PRINT(lRetVal);
            LOOP_FOREVER();
        }

        //Handle Async Events
        while(1)
        {

        }
    }
    //*****************************************************************************
    //
    //! Application startup display on UART
    //!
    //! \param  none
    //!
    //! \return none
    //!
    //*****************************************************************************
    static void
    DisplayBanner(char * AppName)
    {

        Report("\n\n\n\r");
        Report("\t\t *************************************************\n\r");
        Report("\t\t      CC3200 %s Application       \n\r", AppName);
        Report("\t\t *************************************************\n\r");
        Report("\n\n\n\r");
    }

    //*****************************************************************************
    //
    //! Board Initialization & Configuration
    //!
    //! \param  None
    //!
    //! \return None
    //
    //*****************************************************************************
    static void
    BoardInit(void)
    {
    /* In case of TI-RTOS vector table is initialize by OS itself */
    #ifndef USE_TIRTOS
      //
      // Set vector table base
      //
    #if defined(ccs)
        MAP_IntVTableBaseSet((unsigned long)&g_pfnVectors[0]);
    #endif
    #if defined(ewarm)
        MAP_IntVTableBaseSet((unsigned long)&__vector_table);
    #endif
    #endif
        //
        // Enable Processor
        //
        MAP_IntMasterEnable();
        MAP_IntEnable(FAULT_SYSTICK);

        PRCMCC3200MCUInit();
    }

    //****************************************************************************
    //                            MAIN FUNCTION
    //****************************************************************************

    int main(void)
    {
        long lRetVal = -1;

        //Board Initialization
        BoardInit();

        //Pin Configuration
        PinMuxConfig();

        //Change Pin 58 Configuration from Default to Pull Down
        MAP_PinConfigSet(PIN_58,PIN_STRENGTH_2MA|PIN_STRENGTH_4MA,PIN_TYPE_STD_PD);

        //
        // Initialize GREEN and ORANGE LED
        //
        GPIO_IF_LedConfigure(LED1|LED2|LED3);
        //Turn Off the LEDs
        GPIO_IF_LedOff(MCU_ALL_LED_IND);

        //UART Initialization
        MAP_PRCMPeripheralReset(PRCM_UARTA0);

        MAP_UARTConfigSetExpClk(CONSOLE,MAP_PRCMPeripheralClockGet(CONSOLE_PERIPH),
                                UART_BAUD_RATE,(UART_CONFIG_WLEN_8 |
                                  UART_CONFIG_STOP_ONE | UART_CONFIG_PAR_NONE));

        //Display Application Banner on UART Terminal
        DisplayBanner(APPLICATION_NAME);

        //
        // Creating a queue for 10 elements.
        //
        xPrintQueue =xQueueCreate( 10, sizeof( unsigned portLONG ) );

        if( xPrintQueue == 0 )
        {
          // Queue was not created and must not be used.
          return 0;
        }

        //
        // Simplelinkspawntask
        //
        lRetVal = VStartSimpleLinkSpawnTask(SPAWN_TASK_PRIORITY);
        if(lRetVal < 0)
        {
            UART_PRINT("Unable to start simpelink spawn task\n\r");
            LOOP_FOREVER();
        }
        //
        // Create HTTP Server Task
        //
        lRetVal = osi_TaskCreate(HTTPServerTask, (signed char*)"HTTPServerTask",
                             OSI_STACK_SIZE, NULL, OOB_TASK_PRIORITY, NULL );
        if(lRetVal < 0)
        {
            UART_PRINT("Unable to create task\n\r");
            LOOP_FOREVER();
        }


        //
        // Create Filesystem Task
        //
        lRetVal = osi_TaskCreate(Update_IPConfig_file, (signed char*)"Update_IPConfig_file",
                             OSI_STACK_SIZE, NULL, FILE_TASK_PRIORITY, NULL );
        if(lRetVal < 0)
        {
            UART_PRINT("Unable to create task\n\r");
            LOOP_FOREVER();
        }



        //
        // Start OS Scheduler
        //
        osi_start();

        while (1)
        {

        }

    }

  • Hi Abhishek,

    Please find attached file for your reference. In SimpleLinkHttpServerCallback() I am writing dummy data to queue and in HTTPServerTask() reading from queue and writing to a file. 

    main.c
    //*****************************************************************************
    //
    // 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.
    //
    //*****************************************************************************
    
    //*****************************************************************************
    //
    // Application Name     -   HTTP Server
    // Application Overview -   This is a sample application demonstrating
    //                          interaction between HTTP Client(Browser) and 
    //                          SimpleLink Device.The SimpleLink device runs an 
    //                          HTTP Server and user can interact using web browser.
    // Application Details  -
    // http://processors.wiki.ti.com/index.php/CC32xx_HTTP_Server
    // or
    // doc\examples\CC32xx_HTTP_Server.pdf
    //
    //*****************************************************************************
    
    //****************************************************************************
    //
    //! \addtogroup httpserver
    //! @{
    //
    //****************************************************************************
    
    // Standard includes
    #include <string.h>
    #include <stdlib.h>
    
    // Simplelink includes
    #include "simplelink.h"
    #include "netcfg.h"
    
    //driverlib includes
    #include "hw_ints.h"
    #include "hw_types.h"
    #include "hw_memmap.h"
    #include "interrupt.h"
    #include "utils.h"
    #include "pin.h"
    #include "uart.h"
    #include "rom.h"
    #include "rom_map.h"
    #include "prcm.h"
    
    //Free_rtos/ti-rtos includes
    #include "FreeRTOS.h"
    #include "task.h"
    #include "queue.h"
    #include "semphr.h"
    #include "portmacro.h"
    #include "osi.h"
    
    // common interface includes
    #include "gpio_if.h"
    #include "uart_if.h"
    #include "common.h"
    
    #include "smartconfig.h"
    #include "pinmux.h"
    
    
    #define APPLICATION_NAME        "HTTP Server"
    #define APPLICATION_VERSION     "1.1.0"
    #define AP_SSID_LEN_MAX         (33)
    #define ROLE_INVALID            (-5)
    
    #define LED_STRING              "LED"
    #define LED1_STRING             "LED1_"
    #define LED2_STRING             ",LED2_"
    #define LED_ON_STRING           "ON"
    #define LED_OFF_STRING          "OFF"
    
    #define OOB_TASK_PRIORITY               (1)
    #define OSI_STACK_SIZE                  (2048)
    #define SH_GPIO_3                       (3)  /* P58 - Device Mode */
    #define ROLE_INVALID                    (-5)
    #define AUTO_CONNECTION_TIMEOUT_COUNT   (50)   /* 5 Sec */
    
    // Application specific status/error codes
    typedef enum{
        // Choosing -0x7D0 to avoid overlap w/ host-driver's error codes
        LAN_CONNECTION_FAILED = -0x7D0,       
        INTERNET_CONNECTION_FAILED = LAN_CONNECTION_FAILED - 1,
        DEVICE_NOT_IN_STATION_MODE = INTERNET_CONNECTION_FAILED - 1,
    
        STATUS_CODE_MAX = -0xBB8
    }e_AppStatusCodes;
    
    
    //*****************************************************************************
    //                 GLOBAL VARIABLES -- Start
    //*****************************************************************************
    unsigned long  g_ulStatus = 0;//SimpleLink Status
    unsigned long  g_ulPingPacketsRecv = 0; //Number of Ping Packets received 
    unsigned long  g_ulGatewayIP = 0; //Network Gateway IP address
    unsigned char  g_ucConnectionSSID[SSID_LEN_MAX+1]; //Connection SSID
    unsigned char  g_ucConnectionBSSID[BSSID_LEN_MAX]; //Connection BSSID
    unsigned char POST_token[] = "__SL_P_ULD";
    unsigned char GET_token[]  = "__SL_G_ULD";
    int g_iSimplelinkRole = ROLE_INVALID;
    signed int g_uiIpAddress = 0;
    unsigned char g_ucSSID[AP_SSID_LEN_MAX];
    
    // The queue used to send strings to the task1.
    QueueHandle_t xPrintQueue;
    
    #if defined(ccs)
    extern void (* const g_pfnVectors[])(void);
    #endif
    #if defined(ewarm)
    extern uVectorEntry __vector_table;
    #endif
    //*****************************************************************************
    //                 GLOBAL VARIABLES -- End
    //*****************************************************************************
    
    
    //*****************************************************************************
    // Variable related to Connection status
    //*****************************************************************************
    volatile unsigned short g_usMCNetworkUstate = 0;
    
    int g_uiSimplelinkRole = ROLE_INVALID;
    unsigned int g_uiDeviceModeConfig = ROLE_STA; //default is STA mode
    unsigned char g_ucConnectTimeout =0;
    
    
    
    #ifdef USE_FREERTOS
    //*****************************************************************************
    // FreeRTOS User Hook Functions enabled in FreeRTOSConfig.h
    //*****************************************************************************
    
    //*****************************************************************************
    //
    //! \brief Application defined hook (or callback) function - assert
    //!
    //! \param[in]  pcFile - Pointer to the File Name
    //! \param[in]  ulLine - Line Number
    //!
    //! \return none
    //!
    //*****************************************************************************
    void
    vAssertCalled( const char *pcFile, unsigned long ulLine )
    {
        //Handle Assert here
        while(1)
        {
        }
    }
    
    //*****************************************************************************
    //
    //! \brief Application defined idle task hook
    //!
    //! \param  none
    //!
    //! \return none
    //!
    //*****************************************************************************
    void
    vApplicationIdleHook( void)
    {
        //Handle Idle Hook for Profiling, Power Management etc
    }
    
    //*****************************************************************************
    //
    //! \brief Application defined malloc failed hook
    //!
    //! \param  none
    //!
    //! \return none
    //!
    //*****************************************************************************
    void vApplicationMallocFailedHook()
    {
        //Handle Memory Allocation Errors
        while(1)
        {
        }
    }
    
    //*****************************************************************************
    //
    //! \brief Application defined stack overflow hook
    //!
    //! \param  none
    //!
    //! \return none
    //!
    //*****************************************************************************
    void vApplicationStackOverflowHook( OsiTaskHandle *pxTask,
                                       signed char *pcTaskName)
    {
        //Handle FreeRTOS Stack Overflow
        while(1)
        {
        }
    }
    #endif //USE_FREERTOS
    
    
    
    //*****************************************************************************
    // SimpleLink Asynchronous Event Handlers -- Start
    //*****************************************************************************
    
    
    //*****************************************************************************
    //
    //! \brief The Function Handles WLAN Events
    //!
    //! \param[in]  pWlanEvent - Pointer to WLAN Event Info
    //!
    //! \return None
    //!
    //*****************************************************************************
    void SimpleLinkWlanEventHandler(SlWlanEvent_t *pWlanEvent)
    {
        if(!pWlanEvent)
        {
            return;
        }
    
        switch(pWlanEvent->Event)
        {
            case SL_WLAN_CONNECT_EVENT:
            {
                SET_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION);
                
                //
                // 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;
                //
                
                // 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);
    
                UART_PRINT("[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]);
            }
            break;
    
            case SL_WLAN_DISCONNECT_EVENT:
            {
                slWlanConnectAsyncResponse_t*  pEventData = NULL;
    
                CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION);
                CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_AQUIRED);
    
                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)
                {
                    UART_PRINT("[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]);
                }
                else
                {
                    UART_PRINT("[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]);
                }
                memset(g_ucConnectionSSID,0,sizeof(g_ucConnectionSSID));
                memset(g_ucConnectionBSSID,0,sizeof(g_ucConnectionBSSID));
            }
            break;
    
            case SL_WLAN_STA_CONNECTED_EVENT:
            {
                // when device is in AP mode and any client connects to device cc3xxx
                SET_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION);
                CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION_FAILED);
    
                //
                // Information about the connected client (like SSID, MAC etc) will
                // be available in 'slPeerInfoAsyncResponse_t' - Applications
                // can use it if required
                //
                // slPeerInfoAsyncResponse_t *pEventData = NULL;
                // pEventData = &pSlWlanEvent->EventData.APModeStaConnected;
                //
    
            }
            break;
    
            case SL_WLAN_STA_DISCONNECTED_EVENT:
            {
                // when client disconnects from device (AP)
                CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION);
                CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_LEASED);
    
                //
                // Information about the connected client (like SSID, MAC etc) will
                // be available in 'slPeerInfoAsyncResponse_t' - Applications
                // can use it if required
                //
                // slPeerInfoAsyncResponse_t *pEventData = NULL;
                // pEventData = &pSlWlanEvent->EventData.APModestaDisconnected;
                //
            }
            break;
    
            case SL_WLAN_SMART_CONFIG_COMPLETE_EVENT:
            {
                SET_STATUS_BIT(g_ulStatus, STATUS_BIT_SMARTCONFIG_START);
    
                //
                // Information about the SmartConfig details (like Status, SSID,
                // Token etc) will be available in 'slSmartConfigStartAsyncResponse_t'
                // - Applications can use it if required
                //
                //  slSmartConfigStartAsyncResponse_t *pEventData = NULL;
                //  pEventData = &pSlWlanEvent->EventData.smartConfigStartResponse;
                //
    
            }
            break;
    
            case SL_WLAN_SMART_CONFIG_STOP_EVENT:
            {
                // SmartConfig operation finished
                CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_SMARTCONFIG_START);
    
                //
                // Information about the SmartConfig details (like Status, padding
                // etc) will be available in 'slSmartConfigStopAsyncResponse_t' -
                // Applications can use it if required
                //
                // slSmartConfigStopAsyncResponse_t *pEventData = NULL;
                // pEventData = &pSlWlanEvent->EventData.smartConfigStopResponse;
                //
            }
            break;
    
            case SL_WLAN_P2P_DEV_FOUND_EVENT:
            {
                SET_STATUS_BIT(g_ulStatus, STATUS_BIT_P2P_DEV_FOUND);
    
                //
                // Information about P2P config details (like Peer device name, own
                // SSID etc) will be available in 'slPeerInfoAsyncResponse_t' -
                // Applications can use it if required
                //
                // slPeerInfoAsyncResponse_t *pEventData = NULL;
                // pEventData = &pSlWlanEvent->EventData.P2PModeDevFound;
                //
            }
            break;
    
            case SL_WLAN_P2P_NEG_REQ_RECEIVED_EVENT:
            {
                SET_STATUS_BIT(g_ulStatus, STATUS_BIT_P2P_REQ_RECEIVED);
    
                //
                // Information about P2P Negotiation req details (like Peer device
                // name, own SSID etc) will be available in 'slPeerInfoAsyncResponse_t'
                //  - Applications can use it if required
                //
                // slPeerInfoAsyncResponse_t *pEventData = NULL;
                // pEventData = &pSlWlanEvent->EventData.P2PModeNegReqReceived;
                //
            }
            break;
    
            case SL_WLAN_CONNECTION_FAILED_EVENT:
            {
                // If device gets any connection failed event
                SET_STATUS_BIT(g_ulStatus, STATUS_BIT_CONNECTION_FAILED);
            }
            break;
    
            default:
            {
                UART_PRINT("[WLAN EVENT] Unexpected event [0x%x]\n\r",
                           pWlanEvent->Event);
            }
            break;
        }
    }
    
    //*****************************************************************************
    //
    //! \brief This function handles network events such as IP acquisition, IP
    //!           leased, IP released etc.
    //!
    //! \param[in]  pNetAppEvent - Pointer to NetApp Event Info 
    //!
    //! \return None
    //!
    //*****************************************************************************
    void SimpleLinkNetAppEventHandler(SlNetAppEvent_t *pNetAppEvent)
    {
        if(!pNetAppEvent)
        {
            return;
        }
    
        switch(pNetAppEvent->Event)
        {
            case SL_NETAPP_IPV4_IPACQUIRED_EVENT:
            {
                SlIpV4AcquiredAsync_t *pEventData = NULL;
    
                SET_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_AQUIRED);
                
                //Ip Acquired Event Data
                pEventData = &pNetAppEvent->EventData.ipAcquiredV4;
                g_uiIpAddress = pEventData->ip;
    
                //Gateway IP address
                g_ulGatewayIP = pEventData->gateway;
                
                /*UART_PRINT("[NETAPP EVENT] IP Acquired: IP=%d.%d.%d.%d , "
                "Gateway=%d.%d.%d.%d\n\r", 
                SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,3),
                SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,2),
                SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,1),
                SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.ip,0),
                SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,3),
                SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,2),
                SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,1),
                SL_IPV4_BYTE(pNetAppEvent->EventData.ipAcquiredV4.gateway,0));
                */
            }
            break;
    
            case SL_NETAPP_IP_LEASED_EVENT:
            {
                SET_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_LEASED);
    
                //
                // Information about the IP-Leased details(like IP-Leased,lease-time,
                // mac etc) will be available in 'SlIpLeasedAsync_t' - Applications
                // can use it if required
                //
                // SlIpLeasedAsync_t *pEventData = NULL;
                // pEventData = &pNetAppEvent->EventData.ipLeased;
                //
    
            }
            break;
    
            case SL_NETAPP_IP_RELEASED_EVENT:
            {
                CLR_STATUS_BIT(g_ulStatus, STATUS_BIT_IP_LEASED);
    
                //
                // Information about the IP-Released details (like IP-address, mac
                // etc) will be available in 'SlIpReleasedAsync_t' - Applications
                // can use it if required
                //
                // SlIpReleasedAsync_t *pEventData = NULL;
                // pEventData = &pNetAppEvent->EventData.ipReleased;
                //
            }
    		break;
    
            default:
            {
                UART_PRINT("[NETAPP EVENT] Unexpected event [0x%x] \n\r",
                           pNetAppEvent->Event);
            }
            break;
        }
    }
    
    //*****************************************************************************
    //
    //! This function handles socket events indication
    //!
    //! \param[in]      pSock - Pointer to Socket Event Info
    //!
    //! \return None
    //!
    //*****************************************************************************
    void SimpleLinkSockEventHandler(SlSockEvent_t *pSock)
    {
        //
        // This application doesn't work w/ socket - Events are not expected
        //
     
    }
    
    
    //*****************************************************************************
    //
    //! This function gets triggered when HTTP Server receives Application
    //! defined GET and POST HTTP Tokens.
    //!
    //! \param pHttpServerEvent Pointer indicating http server event
    //! \param pHttpServerResponse Pointer indicating http server response
    //!
    //! \return None
    //!
    //*****************************************************************************
    void SimpleLinkHttpServerCallback(SlHttpServerEvent_t *pSlHttpServerEvent, 
                                   SlHttpServerResponse_t *pSlHttpServerResponse)
    {
        unsigned char strLenVal = 0;
        static unsigned int dummy = 0;
    
        if(!pSlHttpServerEvent || !pSlHttpServerResponse)
        {
            return;
        }
        
        xQueueSend( xPrintQueue, &dummy, portMAX_DELAY ); //Send data to queue for writing to a file. here writing dummy
        dummy++;
        
        switch (pSlHttpServerEvent->Event)
        {
            case SL_NETAPP_HTTPGETTOKENVALUE_EVENT:
            {
              unsigned char status, *ptr;
    
              ptr = pSlHttpServerResponse->ResponseData.token_value.data;
              pSlHttpServerResponse->ResponseData.token_value.len = 0;
              if(memcmp(pSlHttpServerEvent->EventData.httpTokenName.data, GET_token,
                        strlen((const char *)GET_token)) == 0)
              {
                status = GPIO_IF_LedStatus(MCU_RED_LED_GPIO);
                strLenVal = strlen(LED1_STRING);
                memcpy(ptr, LED1_STRING, strLenVal);
                ptr += strLenVal;
                pSlHttpServerResponse->ResponseData.token_value.len += strLenVal;
                if(status & 0x01)
                {
                  strLenVal = strlen(LED_ON_STRING);
                  memcpy(ptr, LED_ON_STRING, strLenVal);
                  ptr += strLenVal;
                  pSlHttpServerResponse->ResponseData.token_value.len += strLenVal;
                }
                else
                {
                  strLenVal = strlen(LED_OFF_STRING);
                  memcpy(ptr, LED_OFF_STRING, strLenVal);
                  ptr += strLenVal;
                  pSlHttpServerResponse->ResponseData.token_value.len += strLenVal;
                }
                status = GPIO_IF_LedStatus(MCU_GREEN_LED_GPIO);
                strLenVal = strlen(LED2_STRING);
                memcpy(ptr, LED2_STRING, strLenVal);
                ptr += strLenVal;
                pSlHttpServerResponse->ResponseData.token_value.len += strLenVal;
                if(status & 0x01)
                {
                  strLenVal = strlen(LED_ON_STRING);
                  memcpy(ptr, LED_ON_STRING, strLenVal);
                  ptr += strLenVal;
                  pSlHttpServerResponse->ResponseData.token_value.len += strLenVal;
                }
                else
                {
                  strLenVal = strlen(LED_OFF_STRING);
                  memcpy(ptr, LED_OFF_STRING, strLenVal);
                  ptr += strLenVal;
                  pSlHttpServerResponse->ResponseData.token_value.len += strLenVal;
                }
                *ptr = '\0';
              }
    
            }
            break;
    
            case SL_NETAPP_HTTPPOSTTOKENVALUE_EVENT:
            {
              unsigned char led;
              unsigned char *ptr = pSlHttpServerEvent->EventData.httpPostData.token_name.data;
    
              if(memcmp(ptr, POST_token, strlen((const char *)POST_token)) == 0)
              {
                ptr = pSlHttpServerEvent->EventData.httpPostData.token_value.data;
                strLenVal = strlen(LED_STRING);
                if(memcmp(ptr, LED_STRING, strLenVal) != 0)
                  break;
                ptr += strLenVal;
                led = *ptr;
                strLenVal = strlen(LED_ON_STRING);
                ptr += strLenVal;
                if(led == '1')
                {
                  if(memcmp(ptr, LED_ON_STRING, strLenVal) == 0)
                  {
                          GPIO_IF_LedOn(MCU_RED_LED_GPIO);
                  }
                  else
                  {
                          GPIO_IF_LedOff(MCU_RED_LED_GPIO);
                  }
                }
                else if(led == '2')
                {
                  if(memcmp(ptr, LED_ON_STRING, strLenVal) == 0)
                  {
                          GPIO_IF_LedOn(MCU_GREEN_LED_GPIO);
                  }
                  else
                  {
                          GPIO_IF_LedOff(MCU_GREEN_LED_GPIO);
                  }
                }
    
              }
            }
              break;
            default:
              break;
        }
    }
    
    //*****************************************************************************
    //
    //! \brief This function initializes the application variables
    //!
    //! \param    None
    //!
    //! \return None
    //!
    //*****************************************************************************
    static void InitializeAppVariables()
    {
        g_ulStatus = 0;
        g_uiIpAddress = 0;
    }
    
    
    //*****************************************************************************
    //! \brief This function puts the device in its default state. It:
    //!           - Set 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
    //!           - Unregister mDNS services
    //!           - Remove all filters
    //!
    //! \param   none
    //! \return  On success, zero is returned. On error, negative is returned
    //*****************************************************************************
    static long ConfigureSimpleLinkToDefaultState()
    {
        SlVersionFull   ver = {0};
        _WlanRxFilterOperationCommandBuff_t  RxFilterIdMask = {0};
    
        unsigned char ucVal = 1;
        unsigned char ucConfigOpt = 0;
        unsigned char ucConfigLen = 0;
        unsigned char ucPower = 0;
    
        long lRetVal = -1;
        long lMode = -1;
    
        lMode = sl_Start(0, 0, 0);
        ASSERT_ON_ERROR(lMode);
    
        // If the device is not in station-mode, try configuring it in station-mode 
        if (ROLE_STA != lMode)
        {
            if (ROLE_AP == lMode)
            {
                // If the device is in AP mode, we need to wait for this event 
                // before doing anything 
                while(!IS_IP_ACQUIRED(g_ulStatus))
                {
    #ifndef SL_PLATFORM_MULTI_THREADED
                  _SlNonOsMainLoopTask(); 
    #endif
                }
            }
    
            // Switch to STA role and restart 
            lRetVal = sl_WlanSetMode(ROLE_STA);
            ASSERT_ON_ERROR(lRetVal);
    
            lRetVal = sl_Stop(0xFF);
            ASSERT_ON_ERROR(lRetVal);
    
            lRetVal = sl_Start(0, 0, 0);
            ASSERT_ON_ERROR(lRetVal);
    
            // Check if the device is in station again 
            if (ROLE_STA != lRetVal)
            {
                // We don't want to proceed if the device is not coming up in STA-mode 
                return DEVICE_NOT_IN_STATION_MODE;
            }
        }
        
        // Get the device's version-information
        ucConfigOpt = SL_DEVICE_GENERAL_VERSION;
        ucConfigLen = sizeof(ver);
        lRetVal = sl_DevGet(SL_DEVICE_GENERAL_CONFIGURATION, &ucConfigOpt, 
                                    &ucConfigLen, (unsigned char *)(&ver));
        ASSERT_ON_ERROR(lRetVal);
        
        UART_PRINT("Host Driver Version: %s\n\r",SL_DRIVER_VERSION);
        UART_PRINT("Build Version %d.%d.%d.%d.31.%d.%d.%d.%d.%d.%d.%d.%d\n\r",
        ver.NwpVersion[0],ver.NwpVersion[1],ver.NwpVersion[2],ver.NwpVersion[3],
        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]);
    
        // Set connection policy to Auto + SmartConfig 
        //      (Device's default connection policy)
        lRetVal = sl_WlanPolicySet(SL_POLICY_CONNECTION, 
                                    SL_CONNECTION_POLICY(1, 0, 0, 0, 1), NULL, 0);
        ASSERT_ON_ERROR(lRetVal);
    
        // Remove all profiles
        lRetVal = sl_WlanProfileDel(0xFF);
        ASSERT_ON_ERROR(lRetVal);
    
        
    
        //
        // 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
        //
        lRetVal = sl_WlanDisconnect();
        if(0 == lRetVal)
        {
            // Wait
            while(IS_CONNECTED(g_ulStatus))
            {
    #ifndef SL_PLATFORM_MULTI_THREADED
                  _SlNonOsMainLoopTask(); 
    #endif
            }
        }
    
        // Enable DHCP client
        lRetVal = sl_NetCfgSet(SL_IPV4_STA_P2P_CL_DHCP_ENABLE,1,1,&ucVal);
        ASSERT_ON_ERROR(lRetVal);
    
        // Disable scan
        ucConfigOpt = SL_SCAN_POLICY(0);
        lRetVal = sl_WlanPolicySet(SL_POLICY_SCAN , ucConfigOpt, NULL, 0);
        ASSERT_ON_ERROR(lRetVal);
    
        // Set Tx power level for station mode
        // Number between 0-15, as dB offset from max power - 0 will set max power
        ucPower = 0;
        lRetVal = sl_WlanSet(SL_WLAN_CFG_GENERAL_PARAM_ID, 
                WLAN_GENERAL_PARAM_OPT_STA_TX_POWER, 1, (unsigned char *)&ucPower);
        ASSERT_ON_ERROR(lRetVal);
    
        // Set PM policy to normal
        lRetVal = sl_WlanPolicySet(SL_POLICY_PM , SL_NORMAL_POLICY, NULL, 0);
        ASSERT_ON_ERROR(lRetVal);
    
        // Unregister mDNS services
        lRetVal = sl_NetAppMDNSUnRegisterService(0, 0);
        ASSERT_ON_ERROR(lRetVal);
    
        // Remove  all 64 filters (8*8)
        memset(RxFilterIdMask.FilterIdMask, 0xFF, 8);
        lRetVal = sl_WlanRxFilterSet(SL_REMOVE_RX_FILTER, (_u8 *)&RxFilterIdMask,
                           sizeof(_WlanRxFilterOperationCommandBuff_t));
        ASSERT_ON_ERROR(lRetVal);
    
        lRetVal = sl_Stop(SL_STOP_TIMEOUT);
        ASSERT_ON_ERROR(lRetVal);
    
        InitializeAppVariables();
        
        return lRetVal; // Success
    }
    
    
    
    //****************************************************************************
    //
    //!    \brief Connects to the Network in AP or STA Mode - If ForceAP Jumper is
    //!                                             Placed, Force it to AP mode
    //!
    //! \return                        0 on success else error code
    //
    //****************************************************************************
    long ConnectToNetwork()
    {
        char ucAPSSID[32];
        unsigned short len, config_opt;
        long lRetVal = -1;
    
        // staring simplelink
        g_uiSimplelinkRole =  sl_Start(NULL,NULL,NULL);
    
        // Device is not in STA mode and Force AP Jumper is not Connected 
        //- Switch to STA mode
        if(g_uiSimplelinkRole != ROLE_STA && g_uiDeviceModeConfig == ROLE_STA )
        {
            //Switch to STA Mode
            lRetVal = sl_WlanSetMode(ROLE_STA);
            ASSERT_ON_ERROR(lRetVal);
            
            lRetVal = sl_Stop(SL_STOP_TIMEOUT);
            
            g_usMCNetworkUstate = 0;
            g_uiSimplelinkRole =  sl_Start(NULL,NULL,NULL);
        }
    
        //Device is not in AP mode and Force AP Jumper is Connected - 
        //Switch to AP mode
        if(g_uiSimplelinkRole != ROLE_AP && g_uiDeviceModeConfig == ROLE_AP )
        {
             //Switch to AP Mode
            lRetVal = sl_WlanSetMode(ROLE_AP);
            ASSERT_ON_ERROR(lRetVal);
            
            lRetVal = sl_Stop(SL_STOP_TIMEOUT);
            
            g_usMCNetworkUstate = 0;
            g_uiSimplelinkRole =  sl_Start(NULL,NULL,NULL);
        }
    
        //No Mode Change Required
        if(g_uiSimplelinkRole == ROLE_AP)
        {
           //waiting for the AP to acquire IP address from Internal DHCP Server
           while(!IS_IP_ACQUIRED(g_ulStatus))
           {
    
           }
    
           //Stop Internal HTTP Server
           lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);
           ASSERT_ON_ERROR( lRetVal);
    
           //Start Internal HTTP Server
           lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID);
           ASSERT_ON_ERROR( lRetVal);
    
           char iCount=0;
           //Read the AP SSID
           memset(ucAPSSID,'\0',AP_SSID_LEN_MAX);
           len = AP_SSID_LEN_MAX;
           config_opt = WLAN_AP_OPT_SSID;
           lRetVal = sl_WlanGet(SL_WLAN_CFG_AP_ID, &config_opt , &len,
                                                  (unsigned char*) ucAPSSID);
            ASSERT_ON_ERROR(lRetVal);
            
           Report("\n\rDevice is in AP Mode, Please Connect to AP [%s] and"
              "type [mysimplelink.net] in the browser \n\r",ucAPSSID);
           
           //Blink LED 3 times to Indicate AP Mode
           for(iCount=0;iCount<3;iCount++)
           {
               //Turn RED LED On
               GPIO_IF_LedOn(MCU_RED_LED_GPIO);
               osi_Sleep(400);
               
               //Turn RED LED Off
               GPIO_IF_LedOff(MCU_RED_LED_GPIO);
               osi_Sleep(400);
           }
    
        }
        else
        {
            //Stop Internal HTTP Server
            lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);
            ASSERT_ON_ERROR( lRetVal);
    
            //Start Internal HTTP Server
            lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID);
            ASSERT_ON_ERROR( lRetVal);
            
    		//waiting for the device to Auto Connect
    		while ( (!IS_IP_ACQUIRED(g_ulStatus))&&
    			   g_ucConnectTimeout < AUTO_CONNECTION_TIMEOUT_COUNT)
    		{
    			//Turn RED LED On
    			GPIO_IF_LedOn(MCU_RED_LED_GPIO);
    			osi_Sleep(50);
    
    			//Turn RED LED Off
    			GPIO_IF_LedOff(MCU_RED_LED_GPIO);
    			osi_Sleep(50);
    
    			g_ucConnectTimeout++;
    		}
    		//Couldn't connect Using Auto Profile
    		if(g_ucConnectTimeout == AUTO_CONNECTION_TIMEOUT_COUNT)
    		{
    			//Blink Red LED to Indicate Connection Error
    			GPIO_IF_LedOn(MCU_RED_LED_GPIO);
    
    			CLR_STATUS_BIT_ALL(g_ulStatus);
    
    			Report("Use Smart Config Application to configure the device.\n\r");
    			//Connect Using Smart Config
    			lRetVal = SmartConfigConnect();
    			ASSERT_ON_ERROR(lRetVal);
    
    			//Waiting for the device to Auto Connect
    			while(!IS_IP_ACQUIRED(g_ulStatus))
    			{
    				MAP_UtilsDelay(500);
    			}
    
    		}
        //Turn RED LED Off
        GPIO_IF_LedOff(MCU_RED_LED_GPIO);
        UART_PRINT("\n\rDevice is in STA Mode, Connect to the AP[%s] and type"
              "IP address [%d.%d.%d.%d] in the browser \n\r",g_ucConnectionSSID,
              SL_IPV4_BYTE(g_uiIpAddress,3),SL_IPV4_BYTE(g_uiIpAddress,2),
              SL_IPV4_BYTE(g_uiIpAddress,1),SL_IPV4_BYTE(g_uiIpAddress,0));
    
        }
        return SUCCESS;
    }
    
    
    //****************************************************************************
    //
    //!    \brief Read Force AP GPIO and Configure Mode - 1(Access Point Mode)
    //!                                                  - 0 (Station Mode)
    //!
    //! \return                        None
    //
    //****************************************************************************
    static void ReadDeviceConfiguration()
    {
        unsigned int uiGPIOPort;
        unsigned char pucGPIOPin;
        unsigned char ucPinValue;
            
            //Read GPIO
        GPIO_IF_GetPortNPin(SH_GPIO_3,&uiGPIOPort,&pucGPIOPin);
        ucPinValue = GPIO_IF_Get(SH_GPIO_3,uiGPIOPort,pucGPIOPin);
            
            //If Connected to VCC, Mode is AP
        if(ucPinValue == 1)
        {
                //AP Mode
                g_uiDeviceModeConfig = ROLE_AP;
        }
        else
        {
                //STA Mode
                g_uiDeviceModeConfig = ROLE_STA;
        }
    
    }
    
    //****************************************************************************
    //
    //!  \brief                     Handles HTTP Server Task
    //!                                              
    //! \param[in]                  pvParameters is the data passed to the Task
    //!
    //! \return                        None
    //
    //****************************************************************************
    static void HTTPServerTask(void *pvParameters)
    {
        long lRetVal = -1;
        InitializeAppVariables();
        unsigned int dummy = 0;
        unsigned int readDummy = 0;
        unsigned int offset1 = 0;
        static unsigned int offset = 0;
        long lFileHandle;
        
        //
        // Following function configure the device to default state by cleaning
        // the persistent settings stored in NVMEM (viz. connection profiles &
        // policies, power policy etc)
        //
        // Applications may choose to skip this step if the developer is sure
        // that the device is in its default state at start of applicaton
        //
        // Note that all profiles and persistent settings that were done on the
        // device will be lost
        //
        lRetVal = ConfigureSimpleLinkToDefaultState();
        if(lRetVal < 0)
        {
            if (DEVICE_NOT_IN_STATION_MODE == lRetVal)
                UART_PRINT("Failed to configure the device in its default state\n\r");
    
            LOOP_FOREVER();
        }
    
        UART_PRINT("Device is configured in default state \n\r");  
      
        memset(g_ucSSID,'\0',AP_SSID_LEN_MAX);
        
        //Read Device Mode Configuration
        ReadDeviceConfiguration();
    
        //Connect to Network
        lRetVal = ConnectToNetwork();
    
        //Stop Internal HTTP Server
        lRetVal = sl_NetAppStop(SL_NET_APP_HTTP_SERVER_ID);
        if(lRetVal < 0)
        {
            ERR_PRINT(lRetVal);
            LOOP_FOREVER();
        }
    
        //Start Internal HTTP Server
        lRetVal = sl_NetAppStart(SL_NET_APP_HTTP_SERVER_ID);
        if(lRetVal < 0)
        {
            ERR_PRINT(lRetVal);
            LOOP_FOREVER();
        }
    
        //Handle Async Events
        while(1)
        {
            xQueueReceive( xPrintQueue, &dummy, portMAX_DELAY ); // Read data from queue and write to file
            
            lRetVal = sl_FsOpen((unsigned char *)"demo.txt",
                    FS_MODE_OPEN_CREATE(65536, \
                              _FS_FILE_OPEN_FLAG_COMMIT|_FS_FILE_PUBLIC_WRITE),
                            NULL,
                            &lFileHandle);
            
            if(lRetVal < 0)
            {
                //
                // File may already be created
                //
                lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);
                LOOP_FOREVER();
            }
            else
            {
                //
                // close the user file
                //
                lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);
                if (SL_RET_CODE_OK != lRetVal)
                {
                    LOOP_FOREVER();
                }
            }
            
            //
            //  open a user file for writing
            //
            lRetVal = sl_FsOpen((unsigned char *)"demo.txt",
                                FS_MODE_OPEN_WRITE, 
                                NULL,
                                &lFileHandle);
            if(lRetVal < 0)
            {
                lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);
                LOOP_FOREVER();
            }
            
            lRetVal = sl_FsWrite(lFileHandle, offset, (unsigned char *)&dummy, sizeof(dummy));
            if (lRetVal < 0)
            {
                lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);
                LOOP_FOREVER();
            }
            offset += sizeof(dummy);
            lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);
            if (SL_RET_CODE_OK != lRetVal)
            {
              LOOP_FOREVER();
            }
             
            
            //
            // open a user file for reading
            //
            lRetVal = sl_FsOpen((unsigned char *)"demo.txt",
                            FS_MODE_OPEN_READ,
                            NULL,
                            &lFileHandle);
            if(lRetVal < 0)
            {
                lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);
                LOOP_FOREVER();
            }
            offset1 = 0;
            UART_PRINT("----\n\r");
            while(1)
            {
              lRetVal = sl_FsRead(lFileHandle, offset1, (unsigned char *)&readDummy, sizeof(readDummy));
              if(lRetVal <= 0)
              {
                break;
              }
              UART_PRINT("%d", readDummy);
              offset1 += sizeof(readDummy);
            }
            UART_PRINT("\n\r----");
            lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);
            if (SL_RET_CODE_OK != lRetVal)
            {
                LOOP_FOREVER();
            }
                
    
        }
    }
    //*****************************************************************************
    //
    //! Application startup display on UART
    //!
    //! \param  none
    //!
    //! \return none
    //!
    //*****************************************************************************
    static void
    DisplayBanner(char * AppName)
    {
    
        Report("\n\n\n\r");
        Report("\t\t *************************************************\n\r");
        Report("\t\t      CC3200 %s Application       \n\r", AppName);
        Report("\t\t *************************************************\n\r");
        Report("\n\n\n\r");
    }
    
    //*****************************************************************************
    //
    //! Board Initialization & Configuration
    //!
    //! \param  None
    //!
    //! \return None
    //
    //*****************************************************************************
    static void
    BoardInit(void)
    {
    /* In case of TI-RTOS vector table is initialize by OS itself */
    #ifndef USE_TIRTOS
      //
      // Set vector table base
      //
    #if defined(ccs)
        MAP_IntVTableBaseSet((unsigned long)&g_pfnVectors[0]);
    #endif
    #if defined(ewarm)
        MAP_IntVTableBaseSet((unsigned long)&__vector_table);
    #endif
    #endif
        //
        // Enable Processor
        //
        MAP_IntMasterEnable();
        MAP_IntEnable(FAULT_SYSTICK);
    
        PRCMCC3200MCUInit();
    }
    
    //****************************************************************************
    //                            MAIN FUNCTION
    //****************************************************************************
    void main()
    {
        long lRetVal = -1;
      
        //Board Initialization
        BoardInit();
        
        //Pin Configuration
        PinMuxConfig();
        
        //Change Pin 58 Configuration from Default to Pull Down
        MAP_PinConfigSet(PIN_58,PIN_STRENGTH_2MA|PIN_STRENGTH_4MA,PIN_TYPE_STD_PD);
        
        //
        // Initialize GREEN and ORANGE LED
        //
        GPIO_IF_LedConfigure(LED1|LED2|LED3);
        //Turn Off the LEDs
        GPIO_IF_LedOff(MCU_ALL_LED_IND);
    
        //UART Initialization
        MAP_PRCMPeripheralReset(PRCM_UARTA0);
    
        MAP_UARTConfigSetExpClk(CONSOLE,MAP_PRCMPeripheralClockGet(CONSOLE_PERIPH),
                                UART_BAUD_RATE,(UART_CONFIG_WLEN_8 | 
                                  UART_CONFIG_STOP_ONE | UART_CONFIG_PAR_NONE));
    
        //Display Application Banner on UART Terminal
        DisplayBanner(APPLICATION_NAME);
        
        
        //
        // Creating a queue for 10 elements.
        //
        xPrintQueue =xQueueCreate( 10, sizeof( unsigned portLONG ) );
            if( xPrintQueue == 0 )
        {
          // Queue was not created and must not be used.
          LOOP_FOREVER();
        }
        
        //
        // Simplelinkspawntask
        //
        lRetVal = VStartSimpleLinkSpawnTask(SPAWN_TASK_PRIORITY);    
        if(lRetVal < 0)
        {
            UART_PRINT("Unable to start simpelink spawn task\n\r");
            LOOP_FOREVER();
        }
        //
        // Create HTTP Server Task
        //
        lRetVal = osi_TaskCreate(HTTPServerTask, (signed char*)"HTTPServerTask",
                             OSI_STACK_SIZE, NULL, OOB_TASK_PRIORITY, NULL );    
        if(lRetVal < 0)
        {
            UART_PRINT("Unable to create task\n\r");
            LOOP_FOREVER();
        }
    
        //
        // Start OS Scheduler
        //
        osi_start();
    
        while (1)
        {
    
        }
    
    }
    

    Regards,

    Aashish

  • Thank you so much Aashish.
    I will implement in my code and get back to you.
  • I implemented the code.
    Everything works fine for now.

    Thank you very much Aashish for you support.
    Really appreciated.
  • Hello Aashish.

    Thank you for your support.

    The first write looks correct, but on the next write, the data read from the file looks like -1-1-1-1-2....

    Actually i want to delete the previous file and create a new file on every new write.

    I implemented this,

    ....//Handle Async Events

       while(1)

       {

         xQueueReceive( xPrintQueue, &Dummy_Machine_Config, portMAX_DELAY ); // Read data from queue and write to file

         lRetVal = sl_FsDel("demo.txt",0);                    //Deleting the previous file

         lRetVal = sl_FsOpen((unsigned char *)"demo.txt",

                   FS_MODE_OPEN_CREATE(65536, \

                             _FS_FILE_OPEN_FLAG_COMMIT|_FS_FILE_PUBLIC_WRITE),

                           NULL,

                           &lFileHandle);

           if(lRetVal < 0)

           {

               //

               // File may already be created

               //

               lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);

               LOOP_FOREVER();

           }

           else

           {

               //

               // close the user file

               //

               lRetVal = sl_FsClose(lFileHandle, 0, 0, 0);

               if (SL_RET_CODE_OK != lRetVal)

               {

                   LOOP_FOREVER();

               }

    }

    .....

    But this doesn't work.

    How do i delete the previous file and write new data to new file every-time ??

    Please help !!

  • Thank you very much Aashish for your help and co-operation.
    I implemented everything successfully.

    Regards,
    Abhishek.
  • Abhishek, in that case one solution is to create global variables in your code to store these variables you get from the HTML pages. The async HTTP handler would only store the inputs from the webpage to those variables, nothing else.
    Then your event-loop in main() can check if they are present/set. When they are, it can begin writing them to the .txt and doing the reset you want.
  • Hello Nemanja,
    Thank for replying.
    I didn't get what you are suggesting.
    Can you please send me a sample code to make things more clear.

    Regards,
    Abhishek.