Exemple #1
0
/*******************************************************************************
  Function:
    uint16_t WF_Scan(uint8_t CpId)

  Summary:
    Commands the MRF24W to start a scan operation.  This will generate the
    WF_EVENT_SCAN_RESULTS_READY event.

  Description:
    Directs the MRF24W to initiate a scan operation utilizing the input
    Connection Profile ID.  The Host Application will be notified that the scan
    results are ready when it receives the WF_EVENT_SCAN_RESULTS_READY event.
    The eventInfo field for this event will contain the number of scan results.
    Once the scan results are ready they can be retrieved with
    WF_ScanGetResult().

    Scan results are retained on the MRF24W until:
    1.  Calling WF_Scan() again (after scan results returned from previous
        call).
    2.  MRF24W reset.

    MRF24WB0M & MRF24WG0M support up to max of 60 scan results (SSIDs).

  Precondition:
    MACInit must be called first.

  Parameters:
    CpId - Connection Profile to use.
            If the CpId is valid then the values from that Connection Profile
            will be used for filtering scan results.  If the CpId is set to
            WF_SCAN_ALL (0xFF) then a default filter will be used.

            Valid CpId
            * If CP has a defined SSID only scan results with that SSID are
               retained.
            * If CP does not have a defined SSID then all scanned SSID’s will be
               retained
            * Only scan results from Infrastructure or AdHoc networks are
               retained, depending on the value of networkType in the Connection Profile
            * The channel list that is scanned will be determined from
               channelList in the Connection Algorithm (which must be defined
               before calling this function).

            CpId is equal to WF_SCAN_ALL
            * All scan results are retained (both Infrastructure and Ad Hoc
               networks).
            * All channels within the MRF24W’s regional domain will be
               scanned.
            * No Connection Profiles need to be defined before calling this
               function.
            * The Connection Algorithm does not need to be defined before
               calling this function.

  Returns:
    Operation results. Success or Failure

  Remarks:
    Host scan is allowed only in idle or connected state.
    If MRF24W FW is in the midst of connection ( or reconnection) process, then
    host scan can hammer connection process, and furthermore it may cause
    fatal failure in MRF24W FW operation. To use host scan, we strongly
    recommend the user to disable MRF24W FW connection manager by enabling
    #define DISABLE_MODULE_FW_CONNECT_MANAGER_IN_INFRASTRUCTURE
    in drv_wifi_config.h
  *****************************************************************************/
uint16_t WF_Scan(uint8_t CpId)
{
    uint8_t   hdr[4];
#ifndef MRF24WG
    uint8_t   connectionState;
    uint8_t   dummy;
#endif

    /* WARNING !!! :
    * Host scan is allowed only in idle or connected state.
    * If module FW is in the midst of connection ( or reconenction) process, then
    * host scan can hammer connection process, and furthermore it may cause
    * fatal failure in module FW operation. To be safte to use host scan, we strongly
    * recommend you to disable module FW connection manager by uncommenting
    * #define DISABLE_MODULE_FW_CONNECT_MANAGER_IN_INFRASTRUCTURE
    * in drv_wifi_config.h
    */
    if (!WF_CMIsHostScanAllowed())
        return WF_ERROR_OPERATION_CANCELLED;

#ifndef MRF24WG
    WF_CMGetConnectionState(&connectionState, &dummy);
    if (connectionState == WF_CSTATE_NOT_CONNECTED)
        WF_CMConnect(0xff); /* 120c host scan bug workaround */
#endif

    hdr[0] = WF_MGMT_REQUEST_TYPE;
    hdr[1] = WF_SCAN_START_SUBTYPE;
    hdr[2] = CpId;                  /* Connection Profile ID */
    hdr[3] = 0;                     /* not used              */

    SendMgmtMsg(hdr,             /* header           */
                sizeof(hdr),     /* size of header   */
                NULL,            /* no data          */
                0);              /* no data          */

    /* wait for mgmt response, free it after it comes in (no data needed) */
    WaitForMgmtResponse(WF_SCAN_START_SUBTYPE, FREE_MGMT_BUFFER);

    return WF_SUCCESS;
}
Exemple #2
0
static int WFEasyConfigProcess(void)
{
    UINT8 ConnectionProfileID;
    UINT8 ConnectionState;
    
    #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 = TickGet();
        return 0;
    }
    
    /* Wait for stall time to expire */
    if (CFGCXT.cfg_state == cfg_stalled)
	{
        UINT32 time = TickGet();
        if ((time - CFGCXT.timeStart) < WF_STALL_TIME_MS)
            return 0;
    }
    
    #endif //EZ_CONFIG_STALL
  
    /* We will re-use the current profile */
    WF_CMGetConnectionState(&ConnectionState, &ConnectionProfileID);

    /* Need to disconnect */
    WF_CMDisconnect();

    /* Delete profile */
    WF_CPDelete(ConnectionProfileID);

    /* Create and prepare new profile */
    WF_CPCreate(&ConnectionProfileID);

    /* Now set the various connection profile parameters */

    /* Set SSID... */
    if (CFGCXT.ssid)
#if defined(__18CXX)
        WF_CPSetSsid(ConnectionProfileID, 
        	(ROM char *)CFGCXT.ssid, 
            strlen(CFGCXT.ssid));  
#else
        WF_CPSetSsid(ConnectionProfileID, 
            CFGCXT.ssid, 
            strlen((char*)CFGCXT.ssid));  
#endif       

    /* Now deal with security... */
    switch ((BYTE)CFGCXT.security) {
        case WF_SECURITY_OPEN: /* No security */
            WF_CPSetSecurity(ConnectionProfileID, WF_SECURITY_OPEN, 0, 0, 0);
            break; 

        case WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE:
            if (CFGCXT.key) {
                WF_CPSetSecurity(ConnectionProfileID, WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE, 0, CFGCXT.key, strlen((char *)CFGCXT.key));
            }
            break;

        case WF_SECURITY_WPA_AUTO_WITH_KEY:
            if (CFGCXT.key) {
                WF_CPSetSecurity(ConnectionProfileID, WF_SECURITY_WPA_AUTO_WITH_KEY, 0, CFGCXT.key, 32);
            }
            break;

        case WF_SECURITY_WEP_40:
            {
                BYTE  keys[20];
                int   i;

                if (CFGCXT.key) {
                    /* Clear key */
                    for (i = 0; i < 20; i++)
                        keys[i] = 0;
                    memcpy(keys, CFGCXT.key, 20);
                    WF_CPSetSecurity(ConnectionProfileID, WF_SECURITY_WEP_40, CFGCXT.defaultWepKey, keys, 20);
                }
            }
            break;

        case WF_SECURITY_WEP_104:
            {
                BYTE  keys[52];
                int   i;

                if (CFGCXT.key) {
                    /* Clear key */
                    for (i = 0; i < 52; i++)
                        keys[i] = 0;
                    memcpy(keys, CFGCXT.key, 52);
                    WF_CPSetSecurity(ConnectionProfileID, WF_SECURITY_WEP_104, CFGCXT.defaultWepKey, keys, 52);
                }
            }
            break;
    }
 
    #if defined (EZ_CONFIG_STORE)
    SaveWifiConfig();
    #endif

    /* Set wlan mode */
    WF_CPSetNetworkType(ConnectionProfileID, CFGCXT.type);

    /* Kick off connection now... */
    WF_CMConnect(ConnectionProfileID);
    /* Change state and return TRUE to show we are done! */
    CFGCXT.cfg_state = cfg_stopped;

    return 1;
}
static int WFEasyConfigProcess(void)
{
    uint8_t ConnectionProfileID;
    uint8_t ConnectionState;

    #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 = TickGet();
        return 0;
    }

    /* Wait for stall time to expire */
    if (CFGCXT.cfg_state == cfg_stalled)
    {
        uint32_t time = TickGet();
        if ((time - CFGCXT.timeStart) < WF_STALL_TIME_MS)
            return 0;
    }

    #endif //EZ_CONFIG_STALL

    /* We will re-use the current profile */
    WF_CMGetConnectionState(&ConnectionState, &ConnectionProfileID);

    /* Need to disconnect */
    WF_CMDisconnect();

    /* Delete profile */
    WF_CPDelete(ConnectionProfileID);

    /* Create and prepare new profile */
    WF_CPCreate(&ConnectionProfileID);
    AppConfig.passPhraseToKeyFlag = 0;

    /* Now set the various connection profile parameters */

    /* Set SSID... */
    if (CFGCXT.ssid)
#if defined(__XC8)
        WF_CPSetSsid(ConnectionProfileID,
            //(ROM char *)CFGCXT.ssid,   Note (VMH): fixed compile warning - not sure why this is necessary.
            CFGCXT.ssid,
            strlen(CFGCXT.ssid));
#else
        WF_CPSetSsid(ConnectionProfileID,
            CFGCXT.ssid,
            strlen((char*)CFGCXT.ssid));
#endif

#if defined(DERIVE_KEY_FROM_PASSPHRASE_IN_HOST)
        if ((uint8_t)CFGCXT.security == WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE)
        {
            WF_ConvPassphrase2Key(strlen((char *)CFGCXT.key), CFGCXT.key, strlen((char*)CFGCXT.ssid), CFGCXT.ssid);
            CFGCXT.security--;
            #if MY_DEFAULT_NETWORK_TYPE == WF_ADHOC
                if (AppConfig.SecurityMode == WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE) {
        WF_ConvPassphrase2Key(AppConfig.SecurityKeyLength, AppConfig.SecurityKey,
            AppConfig.SsidLength, AppConfig.MySSID);
            AppConfig.SecurityMode--;
            AppConfig.SecurityKeyLength = 32;
                        AppConfig.passPhraseToKeyFlag = 1;
                }
            #endif /* MY_DEFAULT_NETWORK_TYPE == WF_ADHOC */
        }
#endif    /* defined(DERIVE_KEY_FROM_PASSPHRASE_IN_HOST) */

    /* Now deal with security... */
    switch ((uint8_t)CFGCXT.security) {
        case WF_SECURITY_OPEN: /* No security */
            WF_CPSetSecurity(ConnectionProfileID, WF_SECURITY_OPEN, 0, 0, 0);
            break;

        case WF_SECURITY_WEP_40:
            {
                uint8_t  keys[20];
                int   i;

                if (CFGCXT.key) {
                    /* Clear key */
                    for (i = 0; i < 20; i++)
                        keys[i] = 0;
                    memcpy(keys, (void*)CFGCXT.key, 20);
                    WF_CPSetSecurity(ConnectionProfileID, WF_SECURITY_WEP_40, CFGCXT.defaultWepKey, keys, 20);
                }
            }
            break;

        case WF_SECURITY_WEP_104:
            {
                uint8_t  keys[52];
                int   i;

                if (CFGCXT.key) {
                    /* Clear key */
                    for (i = 0; i < 52; i++)
                        keys[i] = 0;
                    memcpy(keys, (void*)CFGCXT.key, 52);
                    WF_CPSetSecurity(ConnectionProfileID, WF_SECURITY_WEP_104, CFGCXT.defaultWepKey, keys, 52);
                }
            }
            break;

        case WF_SECURITY_WPA_AUTO_WITH_KEY:
            if (CFGCXT.key) {
                WF_CPSetSecurity(ConnectionProfileID, WF_SECURITY_WPA_AUTO_WITH_KEY, 0, CFGCXT.key, 32);
            }
            break;

        case WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE:
            if (CFGCXT.key) {
                WF_CPSetSecurity(ConnectionProfileID, WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE, 0, CFGCXT.key, strlen((char *)CFGCXT.key));
            }
            break;
    }

    #if defined (EZ_CONFIG_STORE)
    SaveAppConfig(&AppConfig);
    #endif

    /* Set wlan mode */
    WF_CPSetNetworkType(ConnectionProfileID, CFGCXT.type);

    if (AppConfig.networkType == WF_INFRASTRUCTURE)
        WF_CASetListRetryCount(MY_DEFAULT_LIST_RETRY_COUNT_INFRASTRUCTURE);

#if defined(DISABLE_MODULE_FW_CONNECT_MANAGER_IN_INFRASTRUCTURE)
        WF_DisableModuleConnectionManager();
#endif

#if MY_DEFAULT_NETWORK_TYPE == WF_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.

    // Operation of hibernate mode
    //      Turned off LDO of the MRF24W module, which is turning off the power completely. Has same effect of resetting the module.
    //

    // FW flow of hibernate mode:
    // Ensure WF_USE_POWER_SAVE_FUNCTIONS is enabled.
    // In main() loop, StackTask() -> MACProcess() will be called. It will invoke CheckHibernate(), which executes/handles
    // hibernate mode based on WF_hibernate.state and  WF_hibernate.wakeup_notice.
    WF_hibernate.state = WF_HB_ENTER_SLEEP;
    WF_hibernate.wakeup_notice = false;
    //WFConsolePrintRomStr("SoftAP redirection: Put Wi-Fi module into hibernate mode.", true);

    DelayMs(50);  // SOFTAP_ZEROCONF_SUPPORT. Timing reduced from 200 to 50.

    WF_hibernate.wakeup_notice = true;
    //WFConsolePrintRomStr("Wakeup Wi-Fi module.", true);
#else
    /* Kick off connection now... */
    WF_CMConnect(ConnectionProfileID);
#endif

    /* Change state and return true to show we are done! */
    CFGCXT.cfg_state = cfg_stopped;

    return 1;
}
Exemple #4
0
/*******************************************************************************
  Function:
	  void iwconfigDisplayStatus(void)

  Summary:
	Responds to the user invoking iwconfig with no parameters

  Description:
	Responds to the user invoking iwconfig with no parameters

  Parameters:
      None.

  Returns:
	None

  Remarks:
       None.
 *****************************************************************************/
static void iwconfigDisplayStatus(void)
{
    UINT8 *p;
    UINT8 tmp;
    UINT8 connectionState;
    UINT8 cpId;
#if defined(MRF24WG)
    char buf[6];
#endif

    union
    {
        struct
        {
            UINT8 List[WF_CHANNEL_LIST_LENGTH];
            UINT8 Num;
        } Channel;

        UINT8 Domain;

        struct
        {
            UINT8 String[WF_MAX_SSID_LENGTH+1];
            UINT8 Len;
        } Ssid;

        struct
        {
            UINT8 NetworkType;
        } Mode;

        struct
        {
            UINT16 Threshold;
        } Rts;
    } ws; // workspace

    // cpId
    {
        WFConsolePrintRomStr("\tcpid:     ", FALSE);
        WFConsolePrintInteger(iwconfigCb.cpId, 'd');
        WFConsolePrintRomStr("", TRUE);
    }

    // channel
    {
        WF_CAGetChannelList(ws.Channel.List, &ws.Channel.Num);
        WFConsolePrintRomStr("\tchannel:  ", FALSE);

        p = ws.Channel.List;
        tmp = ws.Channel.Num;

        while ( --tmp > 0u )
        {
            WFConsolePrintInteger(*p, 'd');
            WFConsolePrintRomStr(",", FALSE);
            p++;
        }

        WFConsolePrintInteger(*p, 'd');
        WFConsolePrintRomStr("", TRUE);
    }

#if defined(MRF24WG)
    // domain
    {
        WF_GetRegionalDomain(&ws.Domain);

        WFConsolePrintRomStr("\tdomain:   ", FALSE);

        if ( ws.Domain == WF_DOMAIN_FCC )
        {
            WFConsolePrintRomStr("fcc", TRUE);
        }
        else if ( ws.Domain == WF_DOMAIN_ETSI )
        {
            WFConsolePrintRomStr("etsi", TRUE);
        }
        else if ( ws.Domain == WF_DOMAIN_JAPAN )
        {
            WFConsolePrintRomStr("japan", TRUE);
        }
        else if ( ws.Domain == WF_DOMAIN_OTHER )
        {
            WFConsolePrintRomStr("other", TRUE);
        }
        else
        {
            WFConsolePrintRomStr("unknown", TRUE);
        }
    }
#else
    // domain
    {
        WF_GetRegionalDomain(&ws.Domain);

        WFConsolePrintRomStr("\tdomain:   ", FALSE);

        if ( ws.Domain == WF_DOMAIN_FCC )
        {
            WFConsolePrintRomStr("fcc", TRUE);
        }
        else if ( ws.Domain == WF_DOMAIN_IC )
        {
            WFConsolePrintRomStr("ic", TRUE);
        }
        else if ( ws.Domain == WF_DOMAIN_ETSI )
        {
            WFConsolePrintRomStr("etsi", TRUE);
        }
        else if ( ws.Domain == WF_DOMAIN_SPAIN )
        {
            WFConsolePrintRomStr("spain", TRUE);
        }
        else if ( ws.Domain == WF_DOMAIN_FRANCE )
        {
            WFConsolePrintRomStr("france", TRUE);
        }
        else if ( ws.Domain == WF_DOMAIN_JAPAN_A )
        {
            WFConsolePrintRomStr("japana", TRUE);
        }
        else if ( ws.Domain == WF_DOMAIN_JAPAN_B )
        {
            WFConsolePrintRomStr("japanb", TRUE);
        }
        else
        {
            WFConsolePrintRomStr("unknown", TRUE);
        }
    }

#endif

    // rts
    {
        WF_GetRtsThreshold(&ws.Rts.Threshold);

        WFConsolePrintRomStr("\trts:      ", FALSE);
        WFConsolePrintInteger(ws.Rts.Threshold, 'd');
        WFConsolePrintRomStr("", TRUE);
    }

    // mode
    {

        WF_CMGetConnectionState(&connectionState, &cpId);
        WF_CPGetNetworkType(iwconfigCb.cpId, &ws.Mode.NetworkType);

        WFConsolePrintRomStr("\tmode:     ", FALSE);

        if (iwconfigCb.isIdle)
        {
            if (iwconfigCb.connState == WF_CSTATE_NOT_CONNECTED)
            {
                WFConsolePrintRomStr("idle", TRUE);
            }
            else if (iwconfigCb.connState == WF_CSTATE_CONNECTION_PERMANENTLY_LOST)
            {
                WFConsolePrintRomStr("idle (connection permanently lost)", TRUE);
            }
            else
            {
                WFConsolePrintRomStr("idle (?)", TRUE);
            }
        }
        else
        {
            WF_CPGetNetworkType(iwconfigCb.cpId, &ws.Mode.NetworkType);
            if (ws.Mode.NetworkType == WF_INFRASTRUCTURE)
            {
                if (iwconfigCb.connState == WF_CSTATE_CONNECTION_IN_PROGRESS)
                {
                    WFConsolePrintRomStr("managed (connection in progress)", TRUE);
                }
                else if (iwconfigCb.connState == WF_CSTATE_CONNECTED_INFRASTRUCTURE)
                {
                    WFConsolePrintRomStr("managed", TRUE);
                }
                else if (iwconfigCb.connState == WF_CSTATE_RECONNECTION_IN_PROGRESS)
                {
                    WFConsolePrintRomStr("managed (reconnection in progress)", TRUE);
                }
                else
                {
                    WFConsolePrintRomStr("managed (?)", TRUE);
                }
            }
            else if (ws.Mode.NetworkType == WF_ADHOC)
            {
                if (iwconfigCb.connState == WF_CSTATE_CONNECTION_IN_PROGRESS)
                {
                    WFConsolePrintRomStr("adhoc (connection in progress)", TRUE);
                }
                else if (iwconfigCb.connState == WF_CSTATE_CONNECTED_ADHOC)
                {
                    WFConsolePrintRomStr("adhoc", TRUE);
                }
                else if (iwconfigCb.connState == WF_CSTATE_RECONNECTION_IN_PROGRESS)
                {
                    WFConsolePrintRomStr("adhoc (reconnection in progress)", TRUE);
                }
                else
                {
                    WFConsolePrintRomStr("adhoc (?)", TRUE);
                }
            }
            else
            {
                WFConsolePrintRomStr("unknown", TRUE);
            }
        }
    }

    // ssid
    {
        WF_CPGetSsid(iwconfigCb.cpId, ws.Ssid.String, &ws.Ssid.Len);
        ws.Ssid.String[ws.Ssid.Len] = '\0';

        WFConsolePrintRomStr("\tssid:     ", FALSE);
        WFConsolePrintRamStr(ws.Ssid.String, TRUE);
    }

    // power
    {
        switch (iwconfigCb.powerSaveState)
        {
        case WF_PS_PS_POLL_DTIM_ENABLED:
            WFConsolePrintRomStr("\tpwrsave:  enabled", TRUE);
            WFConsolePrintRomStr("\tdtim rx:  enabled", TRUE);
            break;
        case WF_PS_PS_POLL_DTIM_DISABLED:
            WFConsolePrintRomStr("\tpwrsave:  enabled", TRUE);
            WFConsolePrintRomStr("\tdtim rx:  disabled", TRUE);
            break;
        case WF_PS_OFF:
            WFConsolePrintRomStr("\tpwrsave:  disabled", TRUE);
            break;
        default:
            WFConsolePrintRomStr("\tpwrsave:  unknown(", FALSE);
            WFConsolePrintInteger(iwconfigCb.powerSaveState, 'd');
            WFConsolePrintRomStr(")", TRUE);
            break;
        }
    }

#if defined(MRF24WG)
    // context
    WF_OutputConnectionContext();

    // Network Type
    putrsUART("\tNetwork:  ");
#if defined(EZ_CONFIG_STORE) && !defined(WF_CONSOLE_DEMO)   /* if EZConfig demo */

    if (AppConfig.networkType == WF_ADHOC)
    {
        putrsUART("AdHoc\r\n");
    }
    else
    {
        putrsUART("Infrastructure\r\n");
    }
#else
#if (MY_DEFAULT_NETWORK_TYPE == WF_ADHOC)
    putrsUART("AdHoc\r\n");
#elif (MY_DEFAULT_NETWORK_TYPE == WF_P2P)
    putrsUART("P2P\r\n");
#elif (MY_DEFAULT_NETWORK_TYPE == WF_INFRASTRUCTURE)
#if (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPS_PUSH_BUTTON)
    putrsUART("Infrastructure (using WPS Push Button)\r\n");
#elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPS_PIN)
    putrsUART("Infrastructure (using WPS Pin)\r\n");
#else
    putrsUART("Infrastructure\r\n");
#endif
#endif
#endif /* EZ_CONFIG_STORE  */

    // Retry Count
    putrsUART("\tRetries   ");
#if (MY_DEFAULT_NETWORK_TYPE == WF_ADHOC)
    sprintf(buf, "%d\r\n", ADHOC_RETRY_COUNT);
    putsUART(buf);
#elif (MY_DEFAULT_NETWORK_TYPE == WF_INFRASTRUCTURE)
#if (INFRASTRUCTURE_RETRY_COUNT == WF_RETRY_FOREVER)
    sprintf(buf, "Retry Forever\r\n");
    putsUART(buf);
#else
    sprintf(buf, "%d\r\n", INFRASTRUCTURE_RETRY_COUNT);
    putsUART(buf);
#endif
#endif    /* (MY_DEFAULT_NETWORK_TYPE == WF_ADHOC) */

    // Security
    putrsUART("\tSecurity: ");
#if (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_OPEN)
    putrsUART("WF_SECURITY_OPEN");
#elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WEP_40)
    putrsUART("WF_SECURITY_WEP_40");
#elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WEP_104)
    putrsUART("WF_SECURITY_WEP_104");
#elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPA_WITH_KEY)
    putrsUART("WF_SECURITY_WPA_WITH_KEY");
#elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPA_WITH_PASS_PHRASE)
    putrsUART("WF_SECURITY_WPA_WITH_PASS_PHRASE");
#elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPA2_WITH_KEY)
    putrsUART("WF_SECURITY_WPA2_WITH_KEY");
#elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPA2_WITH_PASS_PHRASE)
    putrsUART("WF_SECURITY_WPA2_WITH_PASS_PHRASE");
#elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPA_AUTO_WITH_KEY)
    putrsUART("WF_SECURITY_WPA_AUTO_WITH_KEY");
#elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE)
    putrsUART("WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE");
#elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPS_PUSH_BUTTON)
    putrsUART("WF_SECURITY_WPS_PUSH_BUTTON");
#elif (MY_DEFAULT_WIFI_SECURITY_MODE == WF_SECURITY_WPS_PIN)
    putrsUART("WF_SECURITY_WPS_PIN");
#else
    putrsUART("Unknown");
#endif
    putrsUART("\r\n");

    // scan type
    putrsUART("\tScan:     ");
#if (MY_DEFAULT_SCAN_TYPE == WF_ACTIVE_SCAN)
    putrsUART("Active Scan\r\n");
#else
    putrsUART("Passive Scan\r\n");
#endif

    // MAC address
    putrsUART("\tMAC:      ");
    OutputMacAddress();

#endif  /* MRF24WG */
}
Exemple #5
0
/*******************************************************************************
  Function:
      BOOL iwconfigSetCb(void)

  Summary:
	Set the iwconfigCb structure

  Description:
	Set the iwconfigCb structure

  Parameters:
      None.

  Returns:
      TRUE or FALSE

  Remarks:
       None.
 *****************************************************************************/
BOOL iwconfigSetCb(void)
{
    UINT8 cpId;

    if ( !iwconfigCbInitialized ) // first time call of iwconfigSetCb
    {
        memset(&iwconfigCb, 0, sizeof(iwconfigCb));
        iwconfigCbInitialized = TRUE;
    }

#if defined(WF_USE_POWER_SAVE_FUNCTIONS)
    WF_GetPowerSaveState(&iwconfigCb.powerSaveState);
#endif
    if (iwconfigCb.powerSaveState == WF_PS_HIBERNATE)
    {
        WFConsolePrintRomStr("WF device hibernated", TRUE);
        return FALSE;
    }

    WF_CMGetConnectionState(&iwconfigCb.connState, &cpId);

    if ( iwconfigCb.cpId == WF_CURRENT_CPID_NONE )
    {
        if ( cpId == WF_CURRENT_CPID_NONE )
        {
            iwconfigCb.cpId = 1;     // console demo only supports 1 CPID; don't create a new one here
        }
        else if ( cpId == WF_CURRENT_CPID_LIST )
        {
            WFConsolePrintRomStr("Connection profile list not supported", TRUE);
            return FALSE;
        }
        else
        {
            iwconfigCb.cpId = cpId; // use the application-created profile
        }
    }
    else // WF_MIN_NUM_CPID <= iwconfigCb.cpId && iwconfigCb.cpId <= WF_MAX_NUM_CPID
    {
        if ( cpId == WF_CURRENT_CPID_NONE )
        {
            // continue to use iwconfigCb.cpId
        }
        else if ( cpId == WF_CURRENT_CPID_LIST )
        {
            WFConsolePrintRomStr("Conection profile list not supported", TRUE);

            WF_CPDelete(iwconfigCb.cpId);
            iwconfigCb.cpId = WF_CURRENT_CPID_NONE;

            return FALSE;
        }
        else if ( cpId != iwconfigCb.cpId )
        {
            WF_CPDelete(iwconfigCb.cpId);
            iwconfigCb.cpId = cpId; // use the application-created profile
        }
        else // cpId == iwconfigCb.cpId
        {
            // contine to use iwconfigCb.cpId
        }
    }

    if ((iwconfigCb.connState == WF_CSTATE_NOT_CONNECTED) || (iwconfigCb.connState == WF_CSTATE_CONNECTION_PERMANENTLY_LOST))
    {
        iwconfigCb.isIdle = TRUE;
    }
    else
    {
        iwconfigCb.isIdle = FALSE;
    }

    return TRUE;
}
/*****************************************************************************
 * FUNCTION: do_ifconfig_cmd
 *
 * RETURNS: None
 *
 * PARAMS:  None
 *
 * NOTES:   Responds to the user invoking ifconfig
 *****************************************************************************/
void do_ifconfig_cmd(void)
{
     uint8_t   macAddress[6];
     uint8_t conState, cpId;
     IP_ADDR ipAddress;

    // if user only typed in ifconfig with no other parameters
    if (ARGC == 1u)
    {
        IfconfigDisplayStatus();
        return;
    }

    if (WF_hibernate.state)
    {
        WFConsolePrintRomStr("The Wi-Fi module is in hibernate mode - command failed.", true);
        return;
    }

#if defined(WF_CM_DEBUG)
    else if ( (ARGC == 2u) && !strcmp((char *) ARGV[1], "info") )
    {
        uint8_t i;
        tWFCMInfoFSMStats cm_stats;

        WF_CMInfoGetFSMStats(&cm_stats);
        for (i = 0; i < 12; i++)
        {
            sprintf( (char *) g_ConsoleContext.txBuf,
                    "[%02X]: %02X%02X %02X%02X",
                    i,
                    cm_stats.byte[i*4 + 0],
                    cm_stats.byte[i*4 + 1],
                    cm_stats.byte[i*4 + 2],
                    cm_stats.byte[i*4 + 3]
                    );
            WFConsolePrintRamStr( (char *) g_ConsoleContext.txBuf , true);
        }
    }
    else if ( (ARGC == 2u) && !strcmp((char *) ARGV[1], "scan") )
    {
        if (WF_Scan(1) != WF_SUCCESS) // scan, using CP 1
            WFConsolePrintRomStr("Scan failed", true);
    }
    else if ( (ARGC == 2u) && !strcmp((char *) ARGV[1], "scanget") ) //"scangetresult"
    {
        tWFScanResult pScanResult[1];

        WF_ScanGetResult(0, pScanResult);
    }
    else if ( (ARGC == 2u) && !strcmp((char *) ARGV[1], "cpgete") ) //"cpgetelements"
    {
        tWFCPElements pCPElements[1];

        WF_CPGetElements(1, pCPElements);
    }
#endif
    // else if 2 arguments and the second arg is IP address
    else if ( (ARGC == 2u) && (StringToIPAddress((uint8_t*)ARGV[1], &ipAddress)) )
    {
        #if defined(STACK_USE_DHCP_CLIENT)
        if (DHCPIsEnabled(0))
        {
          WFConsolePrintRomStr("Static IP address should not be set with DHCP enabled", true);
          return;
        }
        #endif

        AppConfig.MyIPAddr.v[0] = ipAddress.v[0];
        AppConfig.MyIPAddr.v[1] = ipAddress.v[1];
        AppConfig.MyIPAddr.v[2] = ipAddress.v[2];
        AppConfig.MyIPAddr.v[3] = ipAddress.v[3];

        /* Microchip DHCP client clobbers static ip on every iteration of loop, even if dhcp is turned off*/
        AppConfig.DefaultIPAddr.v[0] = ipAddress.v[0];
        AppConfig.DefaultIPAddr.v[1] = ipAddress.v[1];
        AppConfig.DefaultIPAddr.v[2] = ipAddress.v[2];
        AppConfig.DefaultIPAddr.v[3] = ipAddress.v[3];

        LCDDisplayIPValue(AppConfig.MyIPAddr);
    }
    // else if 2 args and second arg is MAC address
    else if ( (ARGC == 2u) && isMacAddress(ARGV[1], macAddress))
    {
        /* Can only set MAC address in idle state */
        WF_CMGetConnectionState(&conState, &cpId);
        if ( conState != WF_CSTATE_NOT_CONNECTED )
        {
            WFConsolePrintRomStr("HW MAC address can only be set in idle mode", true);
            return;
        }

        WF_SetMacAddress( macAddress );
        AppConfig.MyMACAddr.v[0] = macAddress[0];
        AppConfig.MyMACAddr.v[1] = macAddress[1];
        AppConfig.MyMACAddr.v[2] = macAddress[2];
        AppConfig.MyMACAddr.v[3] = macAddress[3];
        AppConfig.MyMACAddr.v[4] = macAddress[4];
        AppConfig.MyMACAddr.v[5] = macAddress[5];
    }
    else if ( (2u <= ARGC) && (strcmppgm2ram((char *)ARGV[1], (ROM FAR char *)"netmask") == 0) )
    {
        if (ARGC != 3u)
        {
            missingValue();
            return;
        }

        #if defined(STACK_USE_DHCP_CLIENT)
        if ( DHCPIsEnabled(0) )
        {
            WFConsolePrintRomStr(
                "The Netmask should not be set with DHCP enabled", true);
            return;
        }
        #endif

        if ( !StringToIPAddress((uint8_t*)ARGV[2], &ipAddress) )
        {
            WFConsolePrintRomStr("Invalid netmask value", true);
            return;
        }

        AppConfig.MyMask.v[0] = ipAddress.v[0];
        AppConfig.MyMask.v[1] = ipAddress.v[1];
        AppConfig.MyMask.v[2] = ipAddress.v[2];
        AppConfig.MyMask.v[3] = ipAddress.v[3];

        /* Microchip DHCP client clobbers static netmask on every iteration of loop, even if dhcp is turned off*/
        AppConfig.DefaultMask.v[0] = ipAddress.v[0];
        AppConfig.DefaultMask.v[1] = ipAddress.v[1];
        AppConfig.DefaultMask.v[2] = ipAddress.v[2];
        AppConfig.DefaultMask.v[3] = ipAddress.v[3];
    }
    else if ( (2u <= ARGC) && (strcmppgm2ram((char *)ARGV[1], (ROM FAR char *)"gateway") == 0) )
    {
        if (ARGC != 3u)
        {
            missingValue();
            return;
        }

        if ( !StringToIPAddress((uint8_t*)ARGV[2], &ipAddress) )
        {
            WFConsolePrintRomStr("Invalid gateway value", true);
            return;
        }

        AppConfig.MyGateway.v[0] = ipAddress.v[0];
        AppConfig.MyGateway.v[1] = ipAddress.v[1];
        AppConfig.MyGateway.v[2] = ipAddress.v[2];
        AppConfig.MyGateway.v[3] = ipAddress.v[3];
    }
    else if ( (2u <= ARGC) && (strcmppgm2ram((char*)ARGV[1], "auto-dhcp") == 0) )
    {
        if (ARGC != 3u)
        {
            missingValue();
            return;
        }

        #if defined(STACK_USE_DHCP_CLIENT)
        if (strcmppgm2ram((char*)ARGV[2], "start") == 0)
        {
            setDHCPState(true);
        }
        else if (strcmppgm2ram((char*)ARGV[2], "stop") == 0)
        {
            setDHCPState(false);
        }
        else
        #endif
        {
            WFConsolePrintRomStr("   Invalid dhcp param", true);
            return;
        }
    }
    else
    {
        notHandledParam(1);
    }
}
Exemple #7
0
int main(void)
#endif
{
    static DWORD t = 0;
    static DWORD dwLastIP = 0;

    #if defined (EZ_CONFIG_STORE)
    static DWORD ButtonPushStart = 0;
    #endif

    #if (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP)
    UINT8            channelList[] = MY_DEFAULT_CHANNEL_LIST_PRESCAN;  // WF_PRESCAN
    tWFScanResult     bssDesc;
    #endif

    // Initialize application specific hardware
    InitializeBoard();

    #if defined(USE_LCD)
    // Initialize and display the stack version on the LCD
    LCDInit();
    DelayMs(100);
    strcpypgm2ram((char*)LCDText, "TCPStack " TCPIP_STACK_VERSION "  "
        "                ");
    LCDUpdate();
    #endif

    // Initialize stack-related hardware components that may be
    // required by the UART configuration routines
    TickInit();
    #if defined(STACK_USE_MPFS2)
    MPFSInit();
    #endif

    // Initialize Stack and application related NV variables into AppConfig.
    InitAppConfig();

    // Initiates board setup process if button is depressed 
    // on startup
    if(BUTTON0_IO == 0u)
    {
        #if defined(EEPROM_CS_TRIS) || defined(SPIFLASH_CS_TRIS)
        // Invalidate the EEPROM contents if BUTTON0 is held down for more than 4 seconds
        DWORD StartTime = TickGet();
        LED_PUT(0x00);

        while(BUTTON0_IO == 0u)
        {
            if(TickGet() - StartTime > 4*TICK_SECOND)
            {
                #if defined(EEPROM_CS_TRIS)
                XEEBeginWrite(0x0000);
                XEEWrite(0xFF);
                XEEWrite(0xFF);
                XEEEndWrite();
                #elif defined(SPIFLASH_CS_TRIS)
                SPIFlashBeginWrite(0x0000);
                SPIFlashWrite(0xFF);
                SPIFlashWrite(0xFF);
                #endif

                #if defined(STACK_USE_UART)
                putrsUART("\r\n\r\nBUTTON0 held for more than 4 seconds.  Default settings restored.\r\n\r\n");
                #endif

                LED_PUT(0x0F);
                while((LONG)(TickGet() - StartTime) <= (LONG)(9*TICK_SECOND/2));
                LED_PUT(0x00);
                while(BUTTON0_IO == 0u);
                Reset();
                break;
            }
        }
        #endif

        #if defined(STACK_USE_UART)
        DoUARTConfig();
        #endif
    }

    // Initialize core stack layers (MAC, ARP, TCP, UDP) and
    // application modules (HTTP, SNMP, etc.)
    StackInit();

    #if defined ( EZ_CONFIG_SCAN )
    WFInitScan();
    #endif

    #if (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP)
    // WF_PRESCAN: Pre-scan before starting up as SoftAP mode  
    WF_CASetScanType(MY_DEFAULT_SCAN_TYPE);
    WF_CASetChannelList(channelList, sizeof(channelList));

    if (WFStartScan() == WF_SUCCESS)
    {
        SCAN_SET_DISPLAY(SCANCXT.scanState);
        SCANCXT.displayIdx = 0;
        //putsUART("main: Prescan WFStartScan() success ................. \r\n");
    }

    // Needed to trigger g_scan_done
    WFRetrieveScanResult(0, &bssDesc);
    #else

    #if defined(WF_CS_TRIS)
    WF_Connect();
    #endif // defined(WF_CS_TRIS)

    #endif // (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP)

    // Initialize any application-specific modules or functions/
    // For this demo application, this only includes the
    // UART 2 TCP Bridge
    #if defined(STACK_USE_UART2TCP_BRIDGE)
    UART2TCPBridgeInit();
    #endif

    #if defined(STACK_USE_ZEROCONF_LINK_LOCAL)
    ZeroconfLLInitialize();
    #endif

    #if defined(STACK_USE_ZEROCONF_MDNS_SD)
    mDNSInitialize(MY_DEFAULT_HOST_NAME);
	#if defined(STACK_USE_TCP_MOBILE_APP_SERVER)
		mDNSServiceRegister(
        	(const char *) "HomeControlServer",    // base name of the service
        	"_home-control._tcp.local",                // type of the service
        	27561,                                // TCP or UDP port, at which this service is available
        	((const BYTE *)"control home devices"),    // TXT info
        	1,                                    // auto rename the service when if needed
        	NULL,                                // no callback function
        	NULL                                // no application context
        	);
	#else	/* !defined(STACK_USE_TCP_MOBILE_APP_SERVER) */
    	mDNSServiceRegister(
        	(const char *) "DemoWebServer",    // base name of the service
        	"_http._tcp.local",                // type of the service
        	80,                                // TCP or UDP port, at which this service is available
        	((const BYTE *)"path=/index.htm"),    // TXT info
        	1,                                    // auto rename the service when if needed
        	NULL,                                // no callback function
        	NULL                                // no application context
        	);
	#endif	/* defined(STACK_USE_TCP_MOBILE_APP_SERVER) */
    mDNSMulticastFilterRegister();
    #endif

    #if defined(WF_CONSOLE)
    WFConsoleInit();
    #endif

    // Now that all items are initialized, begin the co-operative
    // multitasking loop.  This infinite loop will continuously
    // execute all stack-related tasks, as well as your own
    // application's functions.  Custom functions should be added
    // at the end of this loop.
    // Note that this is a "co-operative mult-tasking" mechanism
    // where every task performs its tasks (whether all in one shot
    // or part of it) and returns so that other tasks can do their
    // job.
    // If a task needs very long time to do its job, it must be broken
    // down into smaller pieces so that other tasks can have CPU time.
    while(1)
    {
        #if (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP)    
        if (g_scan_done) {
           if (g_prescan_waiting) {
               putrsUART((ROM char*)"\n SoftAP prescan results ........ \r\n\n");
               SCANCXT.displayIdx = 0;
               while (IS_SCAN_STATE_DISPLAY(SCANCXT.scanState)) {
                   WFDisplayScanMgr();
               }
               putrsUART((ROM char*)"\r\n ");

               #if defined(WF_CS_TRIS)
               WF_Connect();
               #endif
               g_scan_done = 0;
               g_prescan_waiting = 0;
           }
        }
        #endif // (MY_DEFAULT_NETWORK_TYPE == WF_SOFT_AP)   

        #if defined(WF_PRE_SCAN_IN_ADHOC)
        if(g_prescan_adhoc_done)
        {
            WFGetScanResults();
            g_prescan_adhoc_done = 0;
        }
        #endif

        #if defined (EZ_CONFIG_STORE)
        // Hold button3 for 4 seconds to reset to defaults.
        if (BUTTON3_IO == 0u) {  // Button is pressed
            if (ButtonPushStart == 0)  //Just pressed
                ButtonPushStart = TickGet();
            else
                if(TickGet() - ButtonPushStart > 4*TICK_SECOND)
                    RestoreWifiConfig();
        } 
        else 
        {
            ButtonPushStart = 0; //Button release reset the clock
        } 

        if (AppConfig.saveSecurityInfo)
        {
            // set true by WF_ProcessEvent after connecting to a new network
            // get the security info, and if required, push the PSK to EEPROM
            if ((AppConfig.SecurityMode == WF_SECURITY_WPA_WITH_PASS_PHRASE) ||
                (AppConfig.SecurityMode == WF_SECURITY_WPA2_WITH_PASS_PHRASE) ||
                (AppConfig.SecurityMode == WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE))
            {
                // only need to save when doing passphrase
                tWFCPElements profile;
                UINT8 connState;
                UINT8 connID;
                WF_CMGetConnectionState(&connState, &connID);
                WF_CPGetElements(connID, &profile);
                
                memcpy((char*)AppConfig.SecurityKey, (char*)profile.securityKey, 32);
                AppConfig.SecurityMode--; // the calc psk is exactly one below for each passphrase option
                AppConfig.SecurityKeyLength = 32;                

                SaveAppConfig(&AppConfig);
            }
            
            AppConfig.saveSecurityInfo = FALSE;
        }
        #endif // EZ_CONFIG_STORE

        #if defined (STACK_USE_EZ_CONFIG)
        // Blink LED0 twice per sec when unconfigured, once per sec after config
        if((TickGet() - t >= TICK_SECOND/(4ul - (CFGCXT.isWifiDoneConfigure*2ul))))
        #else
        // Blink LED0 (right most one) every second.
        if(TickGet() - t >= TICK_SECOND/2ul)
        #endif // STACK_USE_EZ_CONFIG
        {
            t = TickGet();
            LED0_IO ^= 1;
        }

        // This task performs normal stack task including checking
        // for incoming packet, type of packet and calling
        // appropriate stack entity to process it.
        StackTask();

        // This tasks invokes each of the core stack application tasks
        StackApplications();

        #if defined(STACK_USE_ZEROCONF_LINK_LOCAL)
        ZeroconfLLProcess();
        #endif

        #if defined(STACK_USE_ZEROCONF_MDNS_SD)
        mDNSProcess();
        // Use this function to exercise service update function
        // HTTPUpdateRecord();
        #endif

        // Process application specific tasks here.
        // For this demo app, this will include the Generic TCP
        // client and servers, and the SNMP, Ping, and SNMP Trap
        // demos.  Following that, we will process any IO from
        // the inputs on the board itself.
        // Any custom modules or processing you need to do should
        // go here.

        #if defined(WF_CONSOLE)
        WFConsoleProcess();
        WFConsoleProcessEpilogue();
        #endif

        #if defined(STACK_USE_GENERIC_TCP_CLIENT_EXAMPLE)
        GenericTCPClient();
        #endif

        #if defined(STACK_USE_GENERIC_TCP_SERVER_EXAMPLE)
        GenericTCPServer();
        #endif

		#if defined(STACK_USE_TCP_MOBILE_APP_SERVER)
		MobileTCPServer();
		#endif
		
        #if defined(STACK_USE_SMTP_CLIENT)
        SMTPDemo();
        #endif

        #if defined(STACK_USE_ICMP_CLIENT)
        PingDemo();
        PingConsole();
        #endif

        #if defined(STACK_USE_SNMP_SERVER) && !defined(SNMP_TRAP_DISABLED)
        //User should use one of the following SNMP demo
        // This routine demonstrates V1 or V2 trap formats with one variable binding.
        SNMPTrapDemo();

        #if defined(SNMP_STACK_USE_V2_TRAP) || defined(SNMP_V1_V2_TRAP_WITH_SNMPV3)
        //This routine provides V2 format notifications with multiple (3) variable bindings
        //User should modify this routine to send v2 trap format notifications with the required varbinds.
        //SNMPV2TrapDemo();
        #endif
        if(gSendTrapFlag)
            SNMPSendTrap();
        #endif

        #if defined(STACK_USE_BERKELEY_API)
        BerkeleyTCPClientDemo();
        BerkeleyTCPServerDemo();
        BerkeleyUDPClientDemo();
        #endif


        // If the local IP address has changed (ex: due to DHCP lease change)
        // write the new IP address to the LCD display, UART, and Announce 
        // service
        if(dwLastIP != AppConfig.MyIPAddr.Val)
        {
            dwLastIP = AppConfig.MyIPAddr.Val;

            #if defined(STACK_USE_UART)
                putrsUART((ROM char*)"\r\nNew IP Address: ");
            #endif

            DisplayIPValue(AppConfig.MyIPAddr);

            #if defined(STACK_USE_UART)
                putrsUART((ROM char*)"\r\n");
            #endif


            #if defined(STACK_USE_ANNOUNCE)
                AnnounceIP();
            #endif

            #if defined(STACK_USE_ZEROCONF_MDNS_SD)
                mDNSFillHostRecord();
            #endif
        }
    }
}
// ************************************************************
// Main application entry point.
// ************************************************************
int main(void)
{
    static DWORD t = 0;	
    static DWORD dwLastIP = 0;
#if defined (EZ_CONFIG_STORE)
    static DWORD ButtonPushStart = 0;
#endif
    UINT8         channelList[] = MY_DEFAULT_CHANNEL_LIST_PRESCAN;  // WF_PRESCAN
    tWFScanResult bssDesc;
#if 0	
    INT8 TxPower;   // Needed to change MRF24WG transmit power. 
#endif

    // Initialize application specific hardware
    InitializeBoard();

    // Initialize TCP/IP stack timer
    TickInit();                        //  Timer 3 interrupt for refreshing motor status inside here
    demo_TickInit();

    #if defined(STACK_USE_MPFS2)
    // Initialize the MPFS File System
	// Generate a WifiGDemoMPFSImg.c file using the MPFS utility (refer to Convert WebPages to MPFS.bat)
	// that gets compiled into source code and programmed into the flash of the uP.
    MPFSInit();
    #endif
	
    // Initialize Stack and application related NV variables into AppConfig.
    InitAppConfig();

    // Initialize core stack layers (MAC, ARP, TCP, UDP) and
    // application modules (HTTP, SNMP, etc.)
    StackInit();

    Exosite_Init("microchip","dv102412",IF_WIFI, 0);

#if 0	
    // Below is used to change MRF24WG transmit power. 
    // This has been verified to be functional (Jan 2013) 
    if (AppConfig.networkType == WF_SOFT_AP)
    {
        WF_TxPowerGetMax(&TxPower);                       
        WF_TxPowerSetMax(TxPower);       
    }
#endif

    // Run Self Test if SW0 pressed on startup
    if(SW0_IO == 1)
        SelfTest();

    #ifdef STACK_USE_TELNET_SERVER
        // Initialize Telnet and
        // Put Remote client in Remote Character Echo Mode
        TelnetInit();
        putc(0xff, stdout);     // IAC = Interpret as Command
        putc(0xfe, stdout);     // Type of Operation = DONT
        putc(0x22, stdout);     // Option = linemode
        putc(0xff, stdout);     // IAC = Interpret as Command
        putc(0xfb, stdout);     // Type of Operation = DO
        putc(0x01, stdout);     // Option = echo
    #endif


    #if defined ( EZ_CONFIG_SCAN )
    // Initialize WiFi Scan State Machine NV variables
    WFInitScan();
    #endif
	
    // WF_PRESCAN: Pre-scan before starting up as SoftAP mode  
    WF_CASetScanType(MY_DEFAULT_SCAN_TYPE);
    WF_CASetChannelList(channelList, sizeof(channelList));
		
    if (WFStartScan() == WF_SUCCESS) {
       SCAN_SET_DISPLAY(SCANCXT.scanState);
       SCANCXT.displayIdx = 0;
    }
	
    // Needed to trigger g_scan_done		
    WFRetrieveScanResult(0, &bssDesc);		
  	
    #if defined(STACK_USE_ZEROCONF_LINK_LOCAL)
    // Initialize Zeroconf Link-Local state-machine, regardless of network type.
    ZeroconfLLInitialize();
    #endif
	
    #if defined(STACK_USE_ZEROCONF_MDNS_SD)
    // Initialize DNS Host-Name from TCPIPConfig.h, regardless of network type.
    mDNSInitialize(MY_DEFAULT_HOST_NAME);
    mDNSServiceRegister(
            // (const char *) AppConfig.NetBIOSName,        // base name of the service. Ensure uniformity with CheckHibernate().
            (const char *) "DemoWebServer",          // base name of the service. Ensure uniformity with CheckHibernate().
            "_http._tcp.local",                      // type of the service
            80,	                                     // TCP or UDP port, at which this service is available
            ((const BYTE *)"path=/index.htm"),       // TXT info
            1,                                       // auto rename the service when if needed
            NULL,                                    // no callback function
            NULL                                     // no application context
            );
    mDNSMulticastFilterRegister();
    #endif
	
    #if defined(WF_CONSOLE)
    // Initialize the WiFi Console App
    WFConsoleInit();
    #endif

    // Now that all items are initialized, begin the co-operative
    // multitasking loop.  This infinite loop will continuously
    // execute all stack-related tasks, as well as your own
    // application's functions.  Custom functions should be added
    // at the end of this loop.
    // Note that this is a "co-operative mult-tasking" mechanism
    // where every task performs its tasks (whether all in one shot
    // or part of it) and returns so that other tasks can do their
    // job.
    // If a task needs very long time to do its job, it must be broken
    // down into smaller pieces so that other tasks can have CPU time.
   #ifndef PERIOD
#define PERIOD  3120        //  set 3120 for get to timer interrupt every 20ms, 40MHz PBUS, div by 256
#endif
    OpenTimer3(T3_ON | T3_SOURCE_INT | T3_PS_1_256, PERIOD);
    while(1)
    {
         if (AppConfig.networkType == WF_SOFT_AP) {
            if (g_scan_done) {
                if (g_prescan_waiting) {
                     SCANCXT.displayIdx = 0;
                     while (IS_SCAN_STATE_DISPLAY(SCANCXT.scanState)) {
                         WFDisplayScanMgr();
                     }
				
                     #if defined(WF_CS_TRIS)
                     WF_Connect();
                     #endif
                     g_scan_done = 0;
                     g_prescan_waiting = 0;
                }
            }
         }

        #if defined (EZ_CONFIG_STORE)
        // Hold SW0 for 4 seconds to reset to defaults.
        if (SW0_IO == 1u) {  // Button is pressed
            button_state = 1;
            if (ButtonPushStart == 0)  //Just pressed
                ButtonPushStart = TickGet();
            else
                if(TickGet() - ButtonPushStart > 4*TICK_SECOND)
                    RestoreWifiConfig();
        } 
        else 
        {
            ButtonPushStart = 0; //Button release reset the clock
        }
		
        if (AppConfig.saveSecurityInfo)
        {
            // set true by WF_ProcessEvent after connecting to a new network
            // get the security info, and if required, push the PSK to EEPROM
            if ((AppConfig.SecurityMode == WF_SECURITY_WPA_WITH_PASS_PHRASE) ||
                (AppConfig.SecurityMode == WF_SECURITY_WPA2_WITH_PASS_PHRASE) ||
                (AppConfig.SecurityMode == WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE))
            {
                // only need to save when doing passphrase
                tWFCPElements profile;
                UINT8 connState;
                UINT8 connID;
                WF_CMGetConnectionState(&connState, &connID);
                WF_CPGetElements(connID, &profile);
                
                memcpy((char*)AppConfig.SecurityKey, (char*)profile.securityKey, 32);
                AppConfig.SecurityMode--; // the calc psk is exactly one below for each passphrase option
                AppConfig.SecurityKeyLength = 32;                

                SaveAppConfig(&AppConfig);
            }
            
            AppConfig.saveSecurityInfo = FALSE;
        }
        #endif // EZ_CONFIG_STORE
		
        // Blink LED0 twice per sec when unconfigured, once per sec after config
        if((TickGet() - t >= TICK_SECOND/(4ul - (CFGCXT.isWifiDoneConfigure*3ul))))
        {
            t = TickGet();
            LED0_INV();
        }

        // This task performs normal stack task including checking
        // for incoming packet, type of packet and calling
        // appropriate stack entity to process it.
        StackTask();

        // This task invokes each of the core stack application tasks
        if (cloud_mode == 0)
          StackApplications();

        // Enable WF_USE_POWER_SAVE_FUNCTIONS 
        WiFiTask();

        #if defined(STACK_USE_ZEROCONF_LINK_LOCAL)
        ZeroconfLLProcess();
        #endif

        #if defined(STACK_USE_ZEROCONF_MDNS_SD)
        mDNSProcess();
        #endif

        Exosite_Demo();
        // Process application specific tasks here.
        // Any custom modules or processing you need to do should
        // go here.
        #if defined(WF_CONSOLE)
		WFConsoleProcess();
		WFConsoleProcessEpilogue();
		#endif

		// If the local IP address has changed (ex: due to DHCP lease change)
		// write the new IP address to the LCD display, UART, and Announce 
		// service
		if(dwLastIP != AppConfig.MyIPAddr.Val) 
		{
			dwLastIP = AppConfig.MyIPAddr.Val;	
			DisplayIPValue(AppConfig.MyIPAddr);			
		
			#if defined(STACK_USE_ANNOUNCE)
			AnnounceIP();
	 		#endif
		
			#if defined(STACK_USE_ZEROCONF_MDNS_SD)
			mDNSFillHostRecord();
	 		#endif
		}

    }
}
static int WFEasyConfigProcess(void)
{
    UINT8 ConnectionProfileID;
    UINT8 ConnectionState;
    
    #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 = TickGet();
        return 0;
    }
    
    /* Wait for stall time to expire */
    if (CFGCXT.cfg_state == cfg_stalled)
    {
        UINT32 time = TickGet();
        if ((time - CFGCXT.timeStart) < WF_STALL_TIME_MS)
            return 0;
    }
    
    #endif //EZ_CONFIG_STALL
  
    /* We will re-use the current profile */
    WF_CMGetConnectionState(&ConnectionState, &ConnectionProfileID);

    /* Need to disconnect */
    WF_CMDisconnect();

    /* Delete profile */
    WF_CPDelete(ConnectionProfileID);

    /* Create and prepare new profile */
    WF_CPCreate(&ConnectionProfileID);

    /* Now set the various connection profile parameters */

    /* Set SSID... */
    if (CFGCXT.ssid)
#if defined(__18CXX)
        WF_CPSetSsid(ConnectionProfileID, 
            //(ROM char *)CFGCXT.ssid,   Note (VMH): fixed compile warning - not sure why this is necessary.
            CFGCXT.ssid, 
            strlen(CFGCXT.ssid));  
#else
        WF_CPSetSsid(ConnectionProfileID, 
            CFGCXT.ssid, 
            strlen((char*)CFGCXT.ssid));  
#endif       

#if defined(DERIVE_KEY_FROM_PASSPHRASE_IN_HOST)
        if ((BYTE)CFGCXT.security == WF_SECURITY_WPA_WITH_PASS_PHRASE
            || (BYTE)CFGCXT.security == WF_SECURITY_WPA2_WITH_PASS_PHRASE
            || (BYTE)CFGCXT.security == WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE) 
        {
            WF_ConvPassphrase2Key(strlen((char *)CFGCXT.key), CFGCXT.key, strlen((char*)CFGCXT.ssid), CFGCXT.ssid);
            CFGCXT.security--;
        }
#endif    /* defined(DERIVE_KEY_FROM_PASSPHRASE_IN_HOST) */

    /* Now deal with security... */
    switch ((BYTE)CFGCXT.security) {
        case WF_SECURITY_OPEN: /* No security */
            WF_CPSetSecurity(ConnectionProfileID, WF_SECURITY_OPEN, 0, 0, 0);
            break; 

        case WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE:
            if (CFGCXT.key) {
                WF_CPSetSecurity(ConnectionProfileID, WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE, 0, CFGCXT.key, strlen((char *)CFGCXT.key));
            }
            break;

        case WF_SECURITY_WPA_AUTO_WITH_KEY:
            if (CFGCXT.key) {
                WF_CPSetSecurity(ConnectionProfileID, WF_SECURITY_WPA_AUTO_WITH_KEY, 0, CFGCXT.key, 32);
            }
            break;

        case WF_SECURITY_WEP_40:
            {
                BYTE  keys[20];
                int   i;

                if (CFGCXT.key) {
                    /* Clear key */
                    for (i = 0; i < 20; i++)
                        keys[i] = 0;
                    memcpy(keys, (void*)CFGCXT.key, 20);
                    WF_CPSetSecurity(ConnectionProfileID, WF_SECURITY_WEP_40, CFGCXT.defaultWepKey, keys, 20);
                }
            }
            break;

        case WF_SECURITY_WEP_104:
            {
                BYTE  keys[52];
                int   i;

                if (CFGCXT.key) {
                    /* Clear key */
                    for (i = 0; i < 52; i++)
                        keys[i] = 0;
                    memcpy(keys, (void*)CFGCXT.key, 52);
                    WF_CPSetSecurity(ConnectionProfileID, WF_SECURITY_WEP_104, CFGCXT.defaultWepKey, keys, 52);
                }
            }
            break;
    }
 
    #if defined (EZ_CONFIG_STORE)
    SaveAppConfig(&AppConfig);
    #endif

    /* Set wlan mode */
    WF_CPSetNetworkType(ConnectionProfileID, CFGCXT.type);

#if defined(DISABLE_MODULE_FW_CONNECT_MANAGER_IN_INFRASTRUCTURE)
    WF_DisableModuleConnectionManager();
#endif

    if (AppConfig.networkType == WF_INFRASTRUCTURE) 
        WF_CASetListRetryCount(MY_DEFAULT_LIST_RETRY_COUNT_INFRASTRUCTURE);
    
#if MY_DEFAULT_NETWORK_TYPE == WF_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.
    WF_hibernate.state = WF_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    
    /* Kick off connection now... */
    WF_CMConnect(ConnectionProfileID);
#endif

    /* Change state and return TRUE to show we are done! */
    CFGCXT.cfg_state = cfg_stopped;

    return 1;
}
/*****************************************************************************
  Function:
	static HTTP_IO_RESULT HTTPPostWifiConfig(void)

  Summary:
	Processes the wifi config data

  Description:
	Accepts wireless configuration data from the www site and saves them to a
	structure to be applied by the ZG configuration manager.

    The following configurations are possible:
         i) Mode: adhoc or infrastructure
        ii) Security:
               - None
               - WPA/WPA2 passphrase
               - WPA/WPA2 pre-calculated key
               - WEP 64-bit
               - WEP 128-bit
       iii) Key material
	
	If an error occurs, such as data is invalid they will be redirected to a page
    informing the user of such results.  

    NOTE: This code for modified originally from HTTPPostWifiConfig as distributed
          by Microchip.

  Precondition:
	None

  Parameters:
	None

  Return Values:
  	HTTP_IO_DONE - all parameters have been processed
  	HTTP_IO_NEED_DATA - data needed by this function has not yet arrived
  ***************************************************************************/
static HTTP_IO_RESULT HTTPPostWifiConfig(void)
{
	// Check to see if the browser is attempting to submit more data than we 
	// can parse at once.  This function needs to receive all updated 
	// parameters and validate them all before committing them to memory so that
	// orphaned configuration parameters do not get written (for example, if a 
	// static IP address is given, but the subnet mask fails parsing, we 
	// should not use the static IP address).  Everything needs to be processed 
	// in a single transaction.  If this is impossible, fail and notify the user.
	// As a web devloper, if you add parameters to AppConfig and run into this 
	// problem, you could fix this by to splitting your update web page into two 
	// seperate web pages (causing two transactional writes).  Alternatively, 
	// you could fix it by storing a static shadow copy of AppConfig someplace 
	// in memory and using it instead of newAppConfig.  Lastly, you could 
	// increase the TCP RX FIFO size for the HTTP server.  This will allow more 
	// data to be POSTed by the web browser before hitting this limit.

    UINT8 ConnectionProfileID;
    UINT8 ConnectionState;
    UINT8 ssidLen;

    WF_CMGetConnectionState(&ConnectionState, &ConnectionProfileID);

	if(curHTTP.byteCount > TCPIsGetReady(sktHTTP) + TCPGetRxFIFOFree(sktHTTP))
		goto ConfigFailure;
	
	// Ensure that all data is waiting to be parsed.  If not, keep waiting for 
	// all of it to arrive.
	if(TCPIsGetReady(sktHTTP) < curHTTP.byteCount)
		return HTTP_IO_NEED_DATA;
	
	// Read all browser POST data
	while(curHTTP.byteCount)
	{
		// Read a form field name
		if(HTTPReadPostName(curHTTP.data, 6) != HTTP_READ_OK)
			goto ConfigFailure;
			
		// Read a form field value
		if(HTTPReadPostValue(curHTTP.data + 6, sizeof(curHTTP.data)-6-2) != HTTP_READ_OK)
			goto ConfigFailure;
			
		// Parse the value that was read
        // Read security type
		if(!strcmppgm2ram((char*)curHTTP.data, "sec"))
		{
            char   security_type[7];

            if (strlen((char*)(curHTTP.data+6)) > 6) /* Sanity check */
                goto ConfigFailure;

            memcpy(security_type, (void*)(curHTTP.data+6), strlen((char*)(curHTTP.data+6)));
            security_type[strlen((char*)(curHTTP.data+6))] = 0; /* Terminate string */
            
            printf("\r\nSecurity Mode: ");
		    if (!strcmppgm2ram((char*)security_type, "no"))
            {
                CFGCXT.security = WF_SECURITY_OPEN;
                printf("OPEN");
            }
		    else if(!strcmppgm2ram((char*)security_type, "wpa")) 
            {
                CFGCXT.security = WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE;
                printf("WPA w/PASSPHRASE");
            }
		    else if(!strcmppgm2ram((char*)security_type, "calc")) 
            {   /* Pre-calculated key */
                CFGCXT.security = WF_SECURITY_WPA_AUTO_WITH_KEY;
                printf("WPA w/AUTO Key");
            }
		    else if(!strcmppgm2ram((char*)security_type, "wep40"))
            {
                CFGCXT.security = WF_SECURITY_WEP_40;
                printf("WEP 64-bit");
            }
		    else if(!strcmppgm2ram((char*)security_type, "wep104"))
            {
                CFGCXT.security = WF_SECURITY_WEP_104;
                printf("WEP 128-bit");
            }
		    else 
            {   //Security type no good  :-(
                printf("\r\nUnknown key type!");
                goto ConfigFailure;
            }				
		}
        // Read new Security Key
		/*
		else if(!strcmppgm2ram((char*)curHTTP.data, "key"))
		{
            BYTE key_size = 0, ascii_key = 0;

            switch ((BYTE)CFGCXT.security)
            {
                case WF_SECURITY_OPEN:   //keep compiler happy, nothing to do here!
                    break;

                case WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE:  //wpa passphrase
                    printf("\r\nPassphrase type of key! ");
                    ascii_key = 1;
                    key_size = strlen((char *)(curHTTP.data+6));
                    //between 8-63 characters, passphrase
                    if ((key_size < 8 ) || (key_size > 63))
                          goto ConfigFailure;
                    break;

                case WF_SECURITY_WPA_AUTO_WITH_KEY: //wpa pre-calculated key!!!
                    key_size = 64;
                    break;

                case WF_SECURITY_WEP_40:
                    key_size = 10; // Assume hex size
                    if (strlen((char *)(curHTTP.data+6)) == 5) {
                        key_size = 5;  // ASCII key support
                        ascii_key = 1;
                     } 
                    CFGCXT.defaultWepKey = 0; // Example uses only key idx 0 (sometimes called 1)
                    break;

                case WF_SECURITY_WEP_104:
                    key_size = 26; // Assume hex size
                    if (strlen((char *)(curHTTP.data+6)) == 13) {
                        key_size = 13;  // ASCII key support
                        ascii_key = 1;
                    } 
                    CFGCXT.defaultWepKey = 0; // Example uses only key idx 0 (sometimes called 1)
                    break;

                default:
                    break;
			}

			if (strlen((char *)(curHTTP.data + 6)) != key_size)
			{
				printf("\r\nIncomplete key received! ");
				goto ConfigFailure;
			}
			memcpy(CFGCXT.key, (void*)(curHTTP.data+6), key_size);
			CFGCXT.key[key_size] = 0; // terminate string
			if (!ascii_key)
			{
				//if ((cfg.security == sec_wep64) || (cfg.security == sec_wep128))
				key_size /= 2;
				if (!convertAsciiToHexInPlace((INT8 *)&CFGCXT.key[0], key_size))
				{
					printf("\r\nFailed to convert ASCII to hex! ");
					goto ConfigFailure;
				}
			}
		}
		*/
        // Get new ssid and make sure it is valid
		else if(!strcmppgm2ram((char*)curHTTP.data, "ssid"))
		{
			if(strlen((char*)(curHTTP.data+6)) < 33u)
			{
                memcpy(CFGCXT.ssid, (void*)(curHTTP.data+6), strlen((char*)(curHTTP.data+6)));
                CFGCXT.ssid[strlen((char*)(curHTTP.data+6))] = 0; /* Terminate string */

                /* save current profile SSID for displaying later */
                WF_CPGetSsid(ConnectionProfileID, (UINT8*)&CFGCXT.prevSSID, &ssidLen);
                CFGCXT.prevSSID[ssidLen] = 0;
                printf("\r\nSSID: %s",CFGCXT.ssid);
			}
			else
			{   //Invalid SSID... fail :-(
                printf("\r\nInvalid SSID...! ");
				goto ConfigFailure;
			}
		}
        // Get the wlan mode: adhoc or infrastructure
		else if(!strcmppgm2ram((char*)curHTTP.data, (ROM char*)"wlan"))
		{
            char mode[6];

            if (strlen((char*)(curHTTP.data+6)) > 5) /* Sanity check */
                goto ConfigFailure;

            memcpy(mode, (void*)(curHTTP.data+6), strlen((char*)(curHTTP.data+6)));
            mode[strlen((char*)(curHTTP.data+6))] = 0; /* Terminate string */
		    if(!strcmppgm2ram((char*)mode, (ROM char*)"infra"))
            {
                printf("\r\nSetting mode to infrastructure! ");
                CFGCXT.type = WF_INFRASTRUCTURE;
            }
		    else if(!strcmppgm2ram((char*)mode, "adhoc")) 
            {
                printf("\r\nSetting mode to adhoc! ");
                CFGCXT.type = WF_ADHOC;

                // Always setup adhoc to attempt to connect first, then start
                WF_CPSetAdHocBehavior(ConnectionProfileID, WF_ADHOC_CONNECT_THEN_START);
            }
		    else 
            {   //Mode type no good  :-(
                printf("\r\nConfig WLAN Mode Failure! ");
                goto ConfigFailure;
            }

            // save old WLAN mode
            WF_CPGetNetworkType(ConnectionProfileID, &CFGCXT.prevWLAN);				
		}
	}

    /* Check if WPA hasn't been selected with adhoc, if it has we choke! */
    if ((CFGCXT.type == WF_ADHOC) &&
      ((CFGCXT.security == WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE) || (CFGCXT.security == WF_SECURITY_WPA_AUTO_WITH_KEY)))
        goto ConfigFailure;

	/* 
     * All parsing complete!  If we have got to here all data has been validated and
     * we can handle what is necessary to start the reconfigure process of the WiFi device
     */
    // Copy wifi cfg data to be committed
    memcpy(CPElements.ssid, CFGCXT.ssid, strlen((char*)(CFGCXT.ssid)));
    CPElements.ssidLength = strlen((char*)(CFGCXT.ssid));
    /* Going to set security type */
    CPElements.securityType = CFGCXT.security;
    /* Going to save the key, if required */
    if (CFGCXT.security != WF_SECURITY_OPEN)
    {
        BYTE  key_size =0;

        switch ((BYTE)CFGCXT.security)
        {
            case WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE:  //wpa passphrase
                key_size = strlen((char*)(CFGCXT.key)); //ascii so use strlen
                break;
            case WF_SECURITY_WPA_AUTO_WITH_KEY: //wpa pre-calculated key!!!
                key_size = 32;
                break;
            case WF_SECURITY_WEP_40:
                key_size = 5;
                break;
            case WF_SECURITY_WEP_104:
                key_size = 13;
                break;

        }
        memcpy(CPElements.securityKey, CFGCXT.key, key_size);
        CPElements.securityKey[strlen((char*)(CFGCXT.key))] = 0;
    }
    /* Going to save the network type */
    CPElements.networkType = CFGCXT.type;

	// Set the board to reboot and display reconnecting information
	strcpypgm2ram((char*)curHTTP.data, "/reconnect.htm");
	curHTTP.httpStatus = HTTP_REDIRECT;	

    /*
     * Set state here to inform that the Wifi device has config data and it is ready
     * to be acted upon.
     */
    printf("\r\nFlagging to start config change!\r\n");

	WF_START_EASY_CONFIG();

	return HTTP_IO_DONE;

ConfigFailure:
	//!lastFailure = TRUE;
	strcpypgm2ram((char*)curHTTP.data, "/error.htm");
	curHTTP.httpStatus = HTTP_REDIRECT;		

	return HTTP_IO_DONE;
}