示例#1
0
/*****************************************************************************
 * FUNCTION: iwprivSetCb
 *
 * RETURNS: TRUE or FALSE
 *
 * PARAMS:  None
 *
 * NOTES:   Set the iwprivCb structure
 *****************************************************************************/
static BOOL iwprivSetCb(void)
{
	tWFCPElements cprof;
	BOOL cpIdChanged = FALSE;

	if ( !iwprivCbInitialized ) // first time call of iwprivSetCb
	{
		memset(&iwprivCb, 0, sizeof(iwprivCb));
		iwprivCbInitialized = TRUE;
	}

	if (!g_hibernate_state && !iwconfigSetCb() ) // first set iwconfigCb
		return FALSE;

    if ( iwprivCb.cpId != iwconfigCb.cpId)
    {
        iwprivCb.cpId = iwconfigCb.cpId;
        cpIdChanged = TRUE;
    }    
        
    WF_CPGetElements(iwprivCb.cpId, &cprof);
        
	// set refreshable part of iwprivCb
	{
		memcpy((void*)iwprivCb.ssid, (const void*)cprof.ssid, cprof.ssidLength);
		iwprivCb.ssid[cprof.ssidLength] = '\0';

		iwprivCb.wepDefaultKeyId = cprof.wepDefaultKeyId;
	}
	
	// set non-refreshable part of iwprivCb only when cpId has changed
	if (cpIdChanged)
	{
 		iwprivCb.securityType = cprof.securityType;
 		if (iwprivCb.securityType == WF_SECURITY_WPA_WITH_KEY || iwprivCb.securityType == WF_SECURITY_WPA2_WITH_KEY)
 		{
     		iwprivCb.securityType = WF_SECURITY_WPA_AUTO_WITH_KEY;
        }
        else if (iwprivCb.securityType == WF_SECURITY_WPA_WITH_PASS_PHRASE || iwprivCb.securityType == WF_SECURITY_WPA2_WITH_PASS_PHRASE)
        {
     		iwprivCb.securityType = WF_SECURITY_WPA_AUTO_WITH_PASS_PHRASE;
        }
              		
 		iwprivCb.securityKeyLength = 0;
    }   	

	return TRUE;
}
/*****************************************************************************
 * FUNCTION: iwprivSetCb
 *
 * RETURNS: true or false
 *
 * PARAMS: none
 *
 * NOTES: Set the iwprivCb structure
 *****************************************************************************/
static bool iwprivSetCb(void)
{
    tWFCPElements cprof;
    bool cpIdChanged = false;

    if ( !iwprivCbInitialized ) // first time call of iwprivSetCb
    {
        memset(&iwprivCb, 0, sizeof(iwprivCb));
        iwprivCbInitialized = true;
    }

    if (!WF_hibernate.state && !iwconfigSetCb() ) // first set iwconfigCb
        return false;

    if ( iwprivCb.cpId != iwconfigCb.cpId)
    {
        iwprivCb.cpId = iwconfigCb.cpId;
        cpIdChanged = true;
    }

    WF_CPGetElements(iwprivCb.cpId, &cprof);

    // set refreshable part of iwprivCb
    {
        memcpy((void*)iwprivCb.ssid, (const void*)cprof.ssid, cprof.ssidLength);
        iwprivCb.ssid[cprof.ssidLength] = '\0';

        iwprivCb.wepDefaultKeyId = cprof.wepDefaultKeyId;
    }

    // set non-refreshable part of iwprivCb only when cpId has changed
    if (cpIdChanged)
    {
        iwprivCb.securityType = cprof.securityType;
        iwprivCb.securityKeyLength = 0;
    }

    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);
    }
}
示例#4
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
        }
    }
}
示例#5
0
// ************************************************************
// 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
		}

    }
}