void AppConfig_SoftwareReset(bool resetToConfigurationMode)
{
    // Change boot-flag setting if required
    if (resetToConfigurationMode)
    {
        SYS_ASSERT(ConfigStore_Config_Read(), "ERROR: Could not read config_store memory.");

        if (ConfigStore_Config_IsValid())
        {
            // Push new setting to NVM - TODO clean up - use std routine
            ConfigStore_SetResetToConfigurationMode(true);

            if (ConfigStore_Config_UpdateCheckbyte() && ConfigStore_Config_IsValid())
                ConfigStore_Config_Write();
        }
    }
    SYS_RESET_SoftwareReset();

}
bool AppConfig_CheckValidAppConfig(bool readConfigFirst)
{
    bool result = false;
    // TODO - need ConfigStore_DeviceServerConfig_Read()? - acceptable overheads if cert = 16KB?

    if (!readConfigFirst || (ConfigStore_Config_Read() && ConfigStore_Config_IsValid() &&
        ConfigStore_DeviceServerConfig_Read() && ConfigStore_DeviceServerConfig_IsValid()))
    {
        char* bootUrl = (char*) ConfigStore_GetBootstrapURL();
        char* wifiSsid = (char *) ConfigStore_GetNetworkSSID();
        char* wifiPassword = (char *) ConfigStore_GetNetworkPassword();

        // TODO - check extra params for valid device server config
        if ((bootUrl && strlen(bootUrl) > 0) && (wifiSsid && strlen(wifiSsid) > 0) && (wifiPassword && strlen(wifiPassword) > 0))
        {
            result = true;
        }
    }
    return result;
}
static bool CommandBoardDetails(int argc, char** argv)
{
    bool result = false;
    if (ConfigStore_Config_Read() && ConfigStore_Config_IsValid() && ConfigStore_Config_IsMagicValid())
    {
        StringBuilder response = StringBuilder_New(256);

        // DeviceType
        response = StringBuilder_Append(response, ConfigStore_GetDeviceType());
        response = StringBuilder_Append(response, LINE_TERM);

        // MAC address
        response = StringBuilder_Append(response, ConfigStore_GetMacAddress());
        response = StringBuilder_Append(response, LINE_TERM);

        // Serial number
        char snString[17];
        memset((void*) snString, 0, 17);
        if (DeviceSerial_GetCpuSerialNumberHexString(snString, 17))
            response = StringBuilder_Append(response, snString);
        else
            response = StringBuilder_Append(response, " ");
        response = StringBuilder_Append(response, LINE_TERM);
        // WiFi SoftAP SSID
        response = StringBuilder_Append(response, ConfigStore_GetSoftAPSSID());
        response = StringBuilder_Append(response, LINE_TERM);

        // WiFi SoftAP password
        response = StringBuilder_Append(response, ConfigStore_GetSoftAPPassword());
        response = StringBuilder_Append(response, LINE_TERM);
        char CB[2] =
        { 0, 0 };
        int32_t byteCount = StringBuilder_GetLength(response);
        int32_t byteIndex = 0;
        for (byteIndex = 0; byteIndex < byteCount; byteIndex++)
        {
            CB[0] += (StringBuilder_GetCString(response))[byteIndex];
        }
        // Compute checkbyte - 2's compliment of MOD-256 sum
        CB[0] ^= 0xFF;
        CB[0]++;
        response = StringBuilder_Append(response, CB);
        response = StringBuilder_Append(response, LINE_TERM);
        CreatorConsole_Puts(response);

        // Output entire response  // TODO - delete?
//		byteCount = StringBuilder_GetLength(response);
//		uint8_t* _response = (uint8_t*) StringBuilder_GetCString(response);
//		for (byteIndex = 0; byteIndex < byteCount; byteIndex++)
//		{
//			if (((char *) _response)[byteIndex] == '\n')
//				CreatorConsole_Puts(LINE_TERM);
//			else
//				CreatorConsole_Putc(((char *) _response)[byteIndex]);
//		}
        //CreatorConsole_Puts(LINE_TERM);

        StringBuilder_Free(&response);
        result = true;
    }
    return result;
}
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]);

}