static bool IwconfigSetMode(SYS_CMD_DEVICE_NODE *pCmdIO, int argc, char **argv)
{
    uint8_t networkType;

    DRV_WIFI_NetworkTypeGet(&networkType);

    if ((3 <= argc) && (strcmp((char*)argv[2], "idle") == 0)) {
        if (s_IwconfigCb.isIdle) {
            SYS_CONSOLE_MESSAGE("Already in Idle mode\r\n");
        } else {
            if (networkType == DRV_WIFI_NETWORK_TYPE_SOFT_AP)
                SYS_CONSOLE_MESSAGE("MRF24W cannot disconnect in Soft AP mode\r\n");
            else
                DRV_WIFI_Disconnect();
        }
    } else if ((3 <= argc) && (strcmp((char*)argv[2], "managed") == 0)) {
        if (s_IwconfigCb.isIdle) {
            DRV_WIFI_NetworkTypeSet(DRV_WIFI_NETWORK_TYPE_INFRASTRUCTURE);
            DRV_WIFI_Connect();
        } else {
            if (networkType == DRV_WIFI_NETWORK_TYPE_INFRASTRUCTURE)
                SYS_CONSOLE_MESSAGE("Already in Managed mode\r\n");
            else
                SYS_CONSOLE_MESSAGE("This command only works in Infrastructure mode\r\n");
        }
    } else if ((3 <= argc) && (strcmp((char*)argv[2], "adhoc") == 0)) {
        if (s_IwconfigCb.isIdle)
        {
            DRV_WIFI_ADHOC_NETWORK_CONTEXT adhocContext;

            DRV_WIFI_NetworkTypeSet(DRV_WIFI_NETWORK_TYPE_ADHOC);
            adhocContext.mode = DRV_WIFI_DEFAULT_ADHOC_MODE;
            adhocContext.hiddenSsid = DRV_WIFI_DEFAULT_ADHOC_HIDDEN_SSID;
            adhocContext.beaconPeriod = DRV_WIFI_DEFAULT_ADHOC_BEACON_PERIOD;
            DRV_WIFI_AdhocContextSet(&adhocContext);
            DRV_WIFI_ReconnectModeSet(3,                              // retry N times to start or join Ad-Hoc network
                                DRV_WIFI_DO_NOT_ATTEMPT_TO_RECONNECT, // do not attempt to reconnect on deauth from station
                                40,                                   // beacon timeout is 40 beacon periods
                                DRV_WIFI_ATTEMPT_TO_RECONNECT);       // reconnect on beacon timeout
            DRV_WIFI_Connect();
        } else {
            if (networkType == DRV_WIFI_NETWORK_TYPE_ADHOC)
                SYS_CONSOLE_MESSAGE("Already in Ad-Hoc mode\r\n");
            else
                SYS_CONSOLE_MESSAGE("This command only works in Ad-Hoc mode\r\n");
        }
    } else {
        SYS_CONSOLE_MESSAGE("Unknown parameter\r\n");
        return false;
    }

    return true;
}
void AppConfig_NetworkInitialise(void)
{
    bool configDefault = false;
    bool logSettingsDefault = false;
    bool deviceServerConfig = false;

    //Unfortunately defaults to connected
    DRV_WIFI_MGMT_INDICATE_SOFT_AP_EVENT *event = DRV_WIFI_SoftApEventInfoGet();
    if (event)
    {
        event->event = -1;
    }

    ConfigStore_Initialize();
    // TODO - remove debug
//   	CreatorConsole_Printf("DeviceConfig size = %d, LogConfig size = %d\r\n", sizeof(ConfigStruct), sizeof(LoggingSettingsStruct));
//   	CreatorConsole_Printf("LOGGINGSETTINGS_PAGEOFFSET = %d\r\n", LOGGINGSETTINGS_PAGEOFFSET);
//   	CreatorConsole_Printf("DRV_NVM_PAGE_SIZE  = %d\r\n", DRV_NVM_PAGE_SIZE);

    if (!ConfigStore_Config_Read())
        CreatorConsole_Puts("ERROR: Could not read config_store memory.\r\n");

    if (!ConfigStore_Config_IsValid())
    {
        if (!ConfigStore_Config_IsMagicValid())
            CreatorConsole_Puts("\r\nWriting default device configuration for first-time use...");
        else
            CreatorConsole_Puts("\r\nDevice configuration invalid. Re-writing default configuration...");

        configDefault = true;
        if (!ConfigStore_Config_ResetToDefaults())
            CreatorConsole_Puts("ERROR: Could not reset config to defaults\r\n");

        if (!ConfigStore_Config_Write())
            CreatorConsole_Puts("ERROR: Could not write default config\r\n");

        CreatorConsole_Puts(" Done\r\n");
    }

    if (!ConfigStore_LoggingSettings_Read())
        CreatorConsole_Puts("ERROR: Could not read loggingSettings.\r\n");

    if (!ConfigStore_LoggingSettings_IsValid())
    {
        if (!ConfigStore_LoggingSettings_IsMagicValid())
            CreatorConsole_Puts("\r\nWriting default device logging-settings for first-time use...");
        else
            CreatorConsole_Puts("\r\nDevice logging-settings invalid. Re-writing defaults...");

        logSettingsDefault = true;
        if (!ConfigStore_LoggingSettings_ResetToDefaults())
            CreatorConsole_Puts("ERROR: Could not reset config to defaults\r\n");

        if (!ConfigStore_LoggingSettings_Write())
            CreatorConsole_Puts("ERROR: Could not write default config\r\n");

        CreatorConsole_Puts(" Done\r\n");
    }

    CreatorLogLevel level = ConfigStore_GetLoggingLevel();
    CreatorLog_SetLevel(level);
    Client_SetLogLevel(level);

    if (!ConfigStore_DeviceServerConfig_Read())
        CreatorConsole_Puts("ERROR: Could not read device server settings.\r\n");

    if (!ConfigStore_DeviceServerConfig_IsValid())
    {
        if (!ConfigStore_DeviceServerConfig_IsMagicValid())
            CreatorConsole_Puts("\r\nWriting default device server settings for first-time use...");
        else
            CreatorConsole_Puts("\r\nDevice server settings invalid. Re-writing defaults...");

        deviceServerConfig = true;
        if (!ConfigStore_DeviceServerConfig_ResetToDefaults())
            CreatorConsole_Puts("ERROR: Could not reset device server config to defaults\r\n");

        if (!ConfigStore_DeviceServerConfig_Write())
            CreatorConsole_Puts("ERROR: Could not write default device server config\r\n");

        CreatorConsole_Puts(" Done\r\n");
    }

    CreatorTimer_SetTicksPerSecond(1000);

    // Check date/time has valid minimum value
    // TODO - could use NTP to get time (in app mode), or mobile app could set time (in config mode)
    time_t time = Creator_GetTime(NULL);
    if (time < DATETIME_MINIMUM_VALUE)
    {
        Creator_SetTime(DATETIME_MINIMUM_VALUE);
    }
    else
    {
        Creator_SetTime(time);	// Kick start the date/time support
    }
    
    // Add initial activity log entries (Note: must be after date/time and logging settings initialised)
    if (configDefault && logSettingsDefault && deviceServerConfig)
    {
        Creator_Log(CreatorLogLevel_Warning, "Default configuration settings set for first-time use");
    }
    else
    {
        if (configDefault)
            Creator_Log(CreatorLogLevel_Error, "Creator configuration lost, default values set");
        if (logSettingsDefault)
            Creator_Log(CreatorLogLevel_Error, "Logging settings lost, default values set");
        if (deviceServerConfig)
            Creator_Log(CreatorLogLevel_Error, "Device server configuration lost, default values set");
    }

    if ((BSP_SwitchStateGet(BSP_SWITCH_1) == BSP_SWITCH_STATE_PRESSED) && (BSP_SwitchStateGet(BSP_SWITCH_2) == BSP_SWITCH_STATE_PRESSED))
        _RunningInConfigurationMode = true;

    // Only run in application mode if device has valid configuration
    if (!_RunningInConfigurationMode && (!ConfigStore_Config_IsValid() || ConfigStore_StartInConfigMode() || !AppConfig_CheckValidAppConfig(false)))
        _RunningInConfigurationMode = true;

    int numberOfNetworkInterfaces = TCPIP_STACK_NumberOfNetworksGet();
    int index;
    TCPIP_NET_HANDLE networkHandle = 0;
    do
    {
        CreatorThread_SleepMilliseconds(NULL, 500);
        for (index = 0; index < numberOfNetworkInterfaces; index++)
        {
            networkHandle = TCPIP_STACK_IndexToNet(index);
            if (TCPIP_STACK_NetIsUp(networkHandle))
            {
                break;
            }
        }
    } while (index == numberOfNetworkInterfaces);

    CreatorConsole_Puts("Done\r\n");

    TCPIP_DHCP_Disable(networkHandle);
    TCPIP_DNS_Disable(networkHandle, true);
    TCPIP_DHCPS_Disable(networkHandle);
    TCPIP_DNSS_Disable(networkHandle);

    if (!ConfigStore_SoftAPSSIDValid())
    {
        const unsigned int MAC_ADDRESS_UNIQUE_PORTION_LENGTH = 6;
        char *softAPSSID = (char *) ConfigStore_GetSoftAPSSID();
        unsigned int baseStrLen = strlen(WF_DEFAULT_SSID_NAME_PREFIX) * sizeof(char);
        memset(softAPSSID, 0, CONFIG_STORE_DEFAULT_FIELD_LENGTH);
        memcpy(softAPSSID, WF_DEFAULT_SSID_NAME_PREFIX, baseStrLen);
        char macStr[MAC_ADDRESS_LENGTH];
        memset(macStr, 0, sizeof(macStr));
        uint8_t mac[MAC_ADDRESS_LENGTH / 2];
        DRV_WIFI_MacAddressGet(mac);
        unsigned int i = 0;
        for (i = 0; i < MAC_ADDRESS_LENGTH / 2; i++)
            sprintf(macStr + (i * 2 * sizeof(char)), "%02X", mac[i]);
        // Store device MAC Address so it doesn't need to be retrieved more than once
        ConfigStore_SetMacAddress(macStr);
        // Use unique portion of mac address to build SSID (last three bytes)
        strncpy((char*) softAPSSID + baseStrLen, macStr + MAC_ADDRESS_LENGTH - MAC_ADDRESS_UNIQUE_PORTION_LENGTH, MAC_ADDRESS_UNIQUE_PORTION_LENGTH);

        // Set the device's name to the same as the SoftAP SSID if it is still the blank value
        if (strcmp(ConfigStore_GetDeviceName(), CREATOR_BLANK_DEVICE_NAME) == 0)
            ConfigStore_SetDeviceName(softAPSSID);

        // Update the Device's configuration information
        ConfigStore_Config_UpdateCheckbyte();
        if (!ConfigStore_Config_Write())
            CreatorConsole_Puts("ERROR: Could not write default config");
    }

    uint8_t networkType;
    uint8_t securityType = 0;
    uint8_t connectionState;
    DRV_WIFI_NetworkTypeGet(&networkType);

    if (networkType == DRV_WIFI_NETWORK_TYPE_ADHOC)
    {
        do
        {
            CreatorThread_SleepMilliseconds(NULL, 100);
            DRV_WIFI_ConnectionStateGet(&connectionState);
        } while ((connectionState == DRV_WIFI_CSTATE_CONNECTION_IN_PROGRESS) || (connectionState == DRV_WIFI_CSTATE_RECONNECTION_IN_PROGRESS));
    }
    else if (networkType == DRV_WIFI_NETWORK_TYPE_SOFT_AP)
    {
        do
        {
            CreatorThread_SleepMilliseconds(NULL, 100);
            DRV_WIFI_ConnectionStateGet(&connectionState);
        } while ((connectionState != DRV_WIFI_CSTATE_CONNECTION_IN_PROGRESS) && (connectionState == DRV_WIFI_CSTATE_CONNECTION_PERMANENTLY_LOST));
    }

    DRV_WIFI_ReconnectModeSet(0, DRV_WIFI_DO_NOT_ATTEMPT_TO_RECONNECT, 40, DRV_WIFI_DO_NOT_ATTEMPT_TO_RECONNECT);

    DRV_WIFI_Disconnect();

    do
    {
        CreatorThread_SleepMilliseconds(NULL, 100);
        DRV_WIFI_ConnectionStateGet(&connectionState);
    } while (connectionState != DRV_WIFI_CSTATE_NOT_CONNECTED);

    if (_AppInfo)
    {
        CreatorConsole_Puts("\r\n --- ");
        CreatorConsole_Puts(_AppInfo->ApplicationName);
        CreatorConsole_Puts(" v");
        CreatorConsole_Puts(_AppInfo->ApplicationVersion);
        CreatorConsole_Puts(" ---\r\n");
    }
    const char *networkSSID;
    const char *softAPPPassword = NULL;
    if (_RunningInConfigurationMode)
    {
        networkType = DRV_WIFI_NETWORK_TYPE_SOFT_AP;
        CreatorConsole_Puts("              [Configuration Mode]\r\n\r\n\r\n");
        networkSSID = ConfigStore_GetSoftAPSSID();
        const char *mac = ConfigStore_GetSoftAPSSID();
        int networkSSIDLength = strlen(networkSSID);
        DRV_WIFI_SsidSet((uint8_t *) networkSSID, networkSSIDLength);
        softAPPPassword = ConfigStore_GetSoftAPPassword();
        securityType = SetWEPKey(softAPPPassword);
        DRV_WIFI_NetworkTypeSet(DRV_WIFI_NETWORK_TYPE_SOFT_AP);

        while (DRV_WIFI_ContextLoad() == TCPIP_MAC_RES_PENDING)
        {
            CreatorThread_SleepMilliseconds(NULL, 50);
        }
    }
    else
    {
        networkType = DRV_WIFI_NETWORK_TYPE_INFRASTRUCTURE;
        UIControl_SetUIState(AppUIState_AppInitConnectingToNetwork);
        CreatorConsole_Puts("               [Application Mode]\r\n\r\n\r\n");

        uint8_t channelList[] = { };
        DRV_WIFI_ChannelListSet(channelList, sizeof(channelList));

        DRV_WIFI_ReconnectModeSet(DRV_WIFI_RETRY_FOREVER,         // retry forever to connect to Wi-Fi network
                DRV_WIFI_ATTEMPT_TO_RECONNECT,  // reconnect on deauth from AP
                40,                             // beacon timeout is 40 beacon periods
                DRV_WIFI_ATTEMPT_TO_RECONNECT); // reconnect on beacon timeout

        networkSSID = ConfigStore_GetNetworkSSID();
        int networkSSIDLength = strlen(networkSSID);
        DRV_WIFI_SsidSet((uint8_t *) networkSSID, networkSSIDLength);

        WiFiEncryptionType encryptionType = ConfigStore_GetEncryptionType();
        switch (encryptionType) {
            case WiFiEncryptionType_WEP:
            {
                const char *wepKey = ConfigStore_GetNetworkPassword();
                securityType = SetWEPKey(wepKey);
            }
                break;
            case WiFiEncryptionType_Open:
                DRV_WIFI_SecurityOpenSet();
                securityType = DRV_WIFI_SECURITY_OPEN;
                break;
            case WiFiEncryptionType_WPA:
            case WiFiEncryptionType_WPA2:
            default:
            {
                DRV_WIFI_WPA_CONTEXT context;
                if (encryptionType == WiFiEncryptionType_WPA)
                    context.wpaSecurityType = DRV_WIFI_SECURITY_WPA_WITH_KEY; // DRV_WIFI_SECURITY_WPA_WITH_PASS_PHRASE;
                else
                    context.wpaSecurityType = DRV_WIFI_SECURITY_WPA2_WITH_KEY; //DRV_WIFI_SECURITY_WPA2_WITH_PASS_PHRASE;
                const char *passPhrase = ConfigStore_GetNetworkPassword();
                int keyLength = strlen(passPhrase);
                memcpy(context.keyInfo.key, passPhrase, keyLength);
                context.keyInfo.keyLength = keyLength;

                while (TCPIP_MAC_RES_OK != DRV_WIFI_KeyDerive(keyLength, context.keyInfo.key, networkSSIDLength, networkSSID))
                    ;
                context.keyInfo.keyLength = 32;

                DRV_WIFI_SecurityWpaSet(&context);
                securityType = context.wpaSecurityType;
            }
                break;
        }
        DRV_WIFI_NetworkTypeSet(DRV_WIFI_NETWORK_TYPE_INFRASTRUCTURE);
    }

    CreatorConsole_Puts("==========================\r\n");
    CreatorConsole_Puts("*** WiFi Configuration ***\r\n");
    CreatorConsole_Puts("==========================\r\n");
    CreatorConsole_Puts("MAC:\t\t");
    CreatorConsole_Puts(ConfigStore_GetMacAddress());
    CreatorConsole_Puts("\r\nSSID:\t\t");
    CreatorConsole_Puts(networkSSID);
    if (softAPPPassword)
    {
        CreatorConsole_Puts("\r\nPassword:\t");
        CreatorConsole_Puts(softAPPPassword);

    }
    CreatorConsole_Puts("\r\nNetwork Type:\t");

    switch (networkType) {
        case DRV_WIFI_NETWORK_TYPE_INFRASTRUCTURE:
            CreatorConsole_Puts("Infrastructure");
            break;
        case DRV_WIFI_NETWORK_TYPE_ADHOC:
            CreatorConsole_Puts("AdHoc");
            break;
        case DRV_WIFI_NETWORK_TYPE_SOFT_AP:
            CreatorConsole_Puts("SoftAP");
            break;
    }
    CreatorConsole_Puts("\r\nSecurity:\t");

    switch (securityType) {
        case DRV_WIFI_SECURITY_OPEN:
            CreatorConsole_Puts("Open");
            break;
        case DRV_WIFI_SECURITY_WEP_40:
            CreatorConsole_Puts("WEP40");
            break;
        case DRV_WIFI_SECURITY_WEP_104:
            CreatorConsole_Puts("WEP104");
            break;
        case DRV_WIFI_SECURITY_WPA_WITH_KEY:
        case DRV_WIFI_SECURITY_WPA_WITH_PASS_PHRASE:
            CreatorConsole_Puts("WPA");
            break;
        case DRV_WIFI_SECURITY_WPA2_WITH_KEY:
        case DRV_WIFI_SECURITY_WPA2_WITH_PASS_PHRASE:
            CreatorConsole_Puts("WPA2");
            break;
        case DRV_WIFI_SECURITY_WPA_AUTO_WITH_KEY:
        case DRV_WIFI_SECURITY_WPA_AUTO_WITH_PASS_PHRASE:
            CreatorConsole_Puts("WPA AUTO");
            break;
    }

    DRV_WIFI_PsPollDisable();
    DRV_WIFI_Connect();

    CreatorConsole_Puts("\r\n\r\n");

    if (_RunningInConfigurationMode)
    {
        do
        {
            CreatorThread_SleepMilliseconds(NULL, 100);
            DRV_WIFI_ConnectionStateGet(&connectionState);
        } while ((connectionState != DRV_WIFI_CSTATE_CONNECTION_IN_PROGRESS) && (connectionState != DRV_WIFI_CSTATE_RECONNECTION_IN_PROGRESS));
        TCPIP_DHCPS_Enable(networkHandle);
        TCPIP_DNSS_Enable(networkHandle);
        UIControl_SetUIState(AppUIState_SoftApNotConnected);
        IPV4_ADDR ipAdd;
        ipAdd.Val = TCPIP_STACK_NetAddress(networkHandle);
        CreatorConsole_Puts(TCPIP_STACK_NetNameGet(networkHandle));
        CreatorConsole_Puts(" IP Address: ");
        CreatorConsole_Printf("%d.%d.%d.%d \r\n", ipAdd.v[0], ipAdd.v[1], ipAdd.v[2], ipAdd.v[3]);
    }
    else
    {
        CreatorConsole_Printf("\n\rConnecting to WiFi network...\n\r");
        bool displayedConnectionWarningToUser = false;
        do
        {
            CreatorThread_SleepMilliseconds(NULL, 100);
            DRV_WIFI_ConnectionStateGet(&connectionState);

            if (!displayedConnectionWarningToUser)
            {
                SYS_UPTIME uptime;
                AppConfig_Uptime(&uptime);
                if (uptime.Seconds >= 30 && !AppConfig_IsDeviceOnline())
                {
                    CreatorConsole_Printf("\n\r\n\r");
                    CreatorConsole_Printf("\n\r**********************************************************************");
                    CreatorConsole_Printf("\n\r* Your WiFire is taking a long time to connect to your WiFi network. *");
                    CreatorConsole_Printf("\n\r* Please check your network settings are correctly configured.       *");
                    CreatorConsole_Printf("\n\r*                                                                    *");
                    CreatorConsole_Printf("\n\r* Hold BTN1 and BTN2 whilst pressing the RESET button on your WiFire *");
                    CreatorConsole_Printf("\n\r* to restart it in Configuration mode.                               *");
                    CreatorConsole_Printf("\n\r*                                                                    *");
                    CreatorConsole_Printf("\n\r* You can then review and change your settings if required.          *");
                    CreatorConsole_Printf("\n\r**********************************************************************");
                    CreatorConsole_Printf("\n\r\n\r");
                    displayedConnectionWarningToUser = true;
                }
            }

        } while ((connectionState != DRV_WIFI_CSTATE_CONNECTED_INFRASTRUCTURE));
        TCPIP_DHCP_Enable(networkHandle);
        IPV4_ADDR ipAdd;
        ipAdd.Val = TCPIP_STACK_NetAddress(networkHandle);
        while (ipAdd.Val == 0x1901A8C0)
        {
            CreatorThread_SleepMilliseconds(NULL, 500);
            ipAdd.Val = TCPIP_STACK_NetAddress(networkHandle);
        }
        CreatorConsole_Puts(TCPIP_STACK_NetNameGet(networkHandle));
        CreatorConsole_Puts(" IP Address: ");
        CreatorConsole_Printf("%d.%d.%d.%d \r\n", ipAdd.v[0], ipAdd.v[1], ipAdd.v[2], ipAdd.v[3]);
        TCPIP_DNS_Enable(networkHandle, TCPIP_DNS_ENABLE_PREFERRED);
        UIControl_SetUIState(AppUIState_AppInitConnectedToNetwork);
    }
    CreatorConsole_Puts("\r\nConnected\r\n");

    //	IPV4_ADDR ipAdd;
    //	ipAdd.Val = TCPIP_STACK_NetAddress(networkHandle);
    //	CreatorConsole_Puts(TCPIP_STACK_NetNameGet(networkHandle));
    //	CreatorConsole_Puts(" IP Address: ");
    //	CreatorConsole_Printf("%d.%d.%d.%d \r\n", ipAdd.v[0], ipAdd.v[1], ipAdd.v[2], ipAdd.v[3]);

}
static int WFEasyConfigProcess(TCPIP_NET_IF* pNetIf)
{
#if 0  // should not be needed
    uint8_t ConnectionState;
#endif
    DRV_WIFI_SECURITY_CONTEXT securityContext;
    
    #if defined (EZ_CONFIG_STALL)
        if (CFGCXT.cfg_state == cfg_stopped)
        {
            /* State machine just started get current time stamp */
            CFGCXT.cfg_state = cfg_stalled;
            CFGCXT.timeStart = SYS_TICK_Get();
            return false;
        }

        /* Wait for stall time to expire */
        if (CFGCXT.cfg_state == cfg_stalled)
        {
            SYS_TICK time = SYS_TICK_Get();
            if ((time - CFGCXT.timeStart) < (WF_EASY_CONFIG_DELAY_TIME * SYS_TICK_TicksPerSecondGet()))
            {
                return false;
            }
        }
    #endif //EZ_CONFIG_STALL

#if 0  // should not be needed
    /* We will re-use the current profile */
    DRV_WIFI_ConnectionStateGet(&ConnectionState);
#endif

    /* Need to disconnect */
    DRV_WIFI_Disconnect();

    /* Set SSID... */
    if (CFGCXT.ssid)
    {
        DRV_WIFI_SsidSet(CFGCXT.ssid, strlen((char*)CFGCXT.ssid));
    }

    /* Now deal with security... */
    switch ((uint8_t)CFGCXT.security)
    {
        case DRV_WIFI_SECURITY_OPEN: /* No security */
            DRV_WIFI_SecurityOpenSet();
            break; 

        case DRV_WIFI_SECURITY_WPA_AUTO_WITH_PASS_PHRASE:
            if (CFGCXT.key)
            {
                securityContext.wpaContext.wpaSecurityType = DRV_WIFI_SECURITY_WPA_AUTO_WITH_PASS_PHRASE;
                securityContext.wpaContext.keyInfo.keyLength = strlen((char *)CFGCXT.key);
                memcpy(securityContext.wpaContext.keyInfo.key, CFGCXT.key, securityContext.wpaContext.keyInfo.keyLength);
                DRV_WIFI_SecurityWpaSet(&securityContext.wpaContext);
            }
            break;

        case DRV_WIFI_SECURITY_WPA_AUTO_WITH_KEY:
            if (CFGCXT.key) 
            {
                securityContext.wpaContext.wpaSecurityType = DRV_WIFI_SECURITY_WPA_AUTO_WITH_KEY;
                securityContext.wpaContext.keyInfo.keyLength = 32;
                memcpy(securityContext.wpaContext.keyInfo.key, CFGCXT.key, 32);
                DRV_WIFI_SecurityWpaSet(&securityContext.wpaContext);
            }
            break;

        case DRV_WIFI_SECURITY_WEP_40:
            if (CFGCXT.key)
            {
                securityContext.wepContext.wepSecurityType = DRV_WIFI_SECURITY_WEP_40;
                securityContext.wepContext.wepKeyLength    = DRV_WIFI_WEP40_KEY_LENGTH;
                memset(CFGCXT.key, 0x00, DRV_WIFI_WEP40_KEY_LENGTH);
                memset(securityContext.wepContext.wepKey, 0x00, DRV_WIFI_WEP40_KEY_LENGTH);
                securityContext.wepContext.wepKeyType      = DRV_WIFI_DEFAULT_WEP_KEY_TYPE;
                DRV_WIFI_SecurityWepSet(&securityContext.wepContext);
            }
            break;

        case DRV_WIFI_SECURITY_WEP_104:
            if (CFGCXT.key)
            {
                securityContext.wepContext.wepSecurityType = DRV_WIFI_SECURITY_WEP_104;
                securityContext.wepContext.wepKeyLength    = DRV_WIFI_WEP104_KEY_LENGTH;
                memset(CFGCXT.key, 0x00, DRV_WIFI_WEP104_KEY_LENGTH);
                memset(securityContext.wepContext.wepKey, 0x00, DRV_WIFI_WEP104_KEY_LENGTH);
                securityContext.wepContext.wepKeyType      = DRV_WIFI_DEFAULT_WEP_KEY_TYPE;
                DRV_WIFI_SecurityWepSet(&securityContext.wepContext);
            }
            break;
    }
 
    #if defined (EZ_CONFIG_STORE) && defined(TCPIP_STACK_USE_STORAGE)
        #if 0
            TCPIP_STORAGE_HANDLE hS;
            hS = TCPIPStorageOpen(0, 1);
            TCPIPStorageSaveIfConfig(hS, "MRF24W", true);
            TCPIPStorageClose(hS);
        #else
            DRV_WIFI_ConfigDataSave();
        #endif
    #endif // defined (EZ_CONFIG_STORE)

    /* Set wlan mode */
    DRV_WIFI_NetworkTypeSet(CFGCXT.type);

#if defined(DISABLE_MODULE_FW_CONNECT_MANAGER_IN_INFRASTRUCTURE)
    DRV_WIFI_ReconnectModeSet(0,                                     // report-only when connection lost (no reconnect)
                        DRV_WIFI_DO_NOT_ATTEMPT_TO_RECONNECT,  // report-only when deauth received (no reconnect)
                        40,                                    // set beacon timeout to 40 beacon periods
                        DRV_WIFI_DO_NOT_ATTEMPT_TO_RECONNECT); // report only when beacon timeout occurs
#endif
    //TCPIP_NET_IF* p_config= (TCPIP_NET_IF*)GetNetworkConfig();
    if (p_wifi_ConfigData->networkType == DRV_WIFI_NETWORK_TYPE_INFRASTRUCTURE)
    {
        DRV_WIFI_ReconnectModeSet(DRV_WIFI_RETRY_FOREVER,   // retry forever to connect to WiFi network
                            DRV_WIFI_ATTEMPT_TO_RECONNECT,  // reconnect on deauth from AP
                            40,                             // beacon timeout is 40 beacon periods
                            DRV_WIFI_ATTEMPT_TO_RECONNECT); // reconnect on beacon timeout
    }

#if WF_DEFAULT_NETWORK_TYPE == DRV_WIFI_NETWORK_TYPE_SOFT_AP
    // SoftAP: To allow redirection, need to hibernate before changing network type. Module
    //         FW has SoftAP flag and therefore hibernate mode is needed to clear this
    //         indication and allow proper network change. This should work for non-SoftAP,
    //         but these have not been tested yet.
    #if 0
        WF_hibernate.state = DRV_WIFI_HB_ENTER_SLEEP;
        WF_hibernate.wakeup_notice = false;
        //WFConsolePrintRomStr("SoftAP redirection: Put Wi-Fi module into hibernate mode.", true);

        DelayMs(200);

        WF_hibernate.wakeup_notice = true;
        //WFConsolePrintRomStr("Wakeup Wi-Fi module.", true);
    #else
        //extern bool SoftAP_Redirection_Enable;
        //SoftAP_Redirection_Enable = true;

        int ret_init;
        WF_InitForSoftApReDirection_enable();
        do
        {
            ret_init = WF_InitForSoftApReDirection();
        }while(ret_init == TCPIP_MAC_RES_PENDING);

    #endif
#else
    /* Kick off connection now... */
    DRV_WIFI_Connect();
#endif
    /* Change state and return true to show we are done! */
    CFGCXT.cfg_state = cfg_stopped;

    return true;
}
static void EasyConfigConnect(void)
{
    DRV_WIFI_Disconnect();    // break the connection supporting the web page

    if (g_easyConfigCtx.ssid)    // if AP has an SSID (not a hidden SSID)
    {
        DRV_WIFI_SsidSet(g_easyConfigCtx.ssid, strlen((char*)g_easyConfigCtx.ssid));
    }

    // Set security supported by designated AP
    EasyConfigSetSecurity();

    #if defined (EZ_CONFIG_STORE) 
        #if 0
            TCPIP_STORAGE_HANDLE hS;
            hS = TCPIPStorageOpen(0, 1);
            TCPIPStorageSaveIfConfig(hS, "MRF24W", true);
            TCPIPStorageClose(hS);
        #else
            DRV_WIFI_ConfigDataSave();
        #endif
    #endif // defined (EZ_CONFIG_STORE)

                /* Set wlan mode */
    DRV_WIFI_NetworkTypeSet(CFGCXT.type);

    #if defined(DISABLE_MODULE_FW_CONNECT_MANAGER_IN_INFRASTRUCTURE)
        DRV_WIFI_ReconnectModeSet(0,                               // report-only when connection lost (no reconnect)
                            DRV_WIFI_DO_NOT_ATTEMPT_TO_RECONNECT,  // report-only when deauth received (no reconnect)
                            40,                                    // set beacon timeout to 40 beacon periods
                            DRV_WIFI_DO_NOT_ATTEMPT_TO_RECONNECT); // report only when beacon timeout occurs
    #else
        //TCPIP_NET_IF* p_config= (TCPIP_NET_IF*)GetNetworkConfig();
        if (p_wifi_ConfigData->networkType == DRV_WIFI_NETWORK_TYPE_INFRASTRUCTURE)
        {
            DRV_WIFI_ReconnectModeSet(DRV_WIFI_RETRY_FOREVER,   // retry forever to connect to WiFi network
                                DRV_WIFI_ATTEMPT_TO_RECONNECT,  // reconnect on deauth from AP
                                40,                             // beacon timeout is 40 beacon periods
                                DRV_WIFI_ATTEMPT_TO_RECONNECT); // reconnect on beacon timeout
        }
    #endif

#if WF_DEFAULT_NETWORK_TYPE == DRV_WIFI_NETWORK_TYPE_SOFT_AP
    // SoftAP: To allow redirection, need to hibernate before changing network type. Module
    //         FW has SoftAP flag and therefore hibernate mode is needed to clear this
    //         indication and allow proper network change. This should work for non-SoftAP,
    //         but these have not been tested yet.
    #if 0
        WF_hibernate.state = DRV_WIFI_HB_ENTER_SLEEP;
        WF_hibernate.wakeup_notice = false;
        //WFConsolePrintRomStr("SoftAP redirection: Put Wi-Fi module into hibernate mode.", true);

        DelayMs(200);

        WF_hibernate.wakeup_notice = true;
        //WFConsolePrintRomStr("Wakeup Wi-Fi module.", true);
    #else
        //extern bool SoftAP_Redirection_Enable;
        //SoftAP_Redirection_Enable = true;
        int ret_init;
        WF_InitForSoftApReDirection_enable();
        do
        {
            ret_init = WF_InitForSoftApReDirection();
        }while(ret_init == TCPIP_MAC_RES_PENDING);
    #endif
#else
    /* Kick off connection now... */
    DRV_WIFI_Connect();
#endif

}