chipKIT® Development Platform

Inspired by Arduino™

Last edit: 2021-03-21 22:34 by Majenko

DEWFcK

DEWFcK
Quick Look
Hardware WF32, Wi-FIRE or uC32 with a WiFiShield
Include DEWFcK.h

The DEWFcK library defines the core C++ class for WiFi support.

  1. Detailed Introduction

  2. Introductory Programs

    1. WiFiScan

    2. WiFiTCPEchoServer

    3. WiFiTCPEchoServer

  3. Full library usage

    1. DEWFcK

      1. Public Functions

        1. setWF(const NWWF * pNwWF)

        2. isWFInitialized(void)

        3. isWFInitialized(IPSTATUS * pStatus)

        4. wfDisconnect(void)

        5. getScanInfo(int iNetwork, SCANINFO * pscanInfo)

        6. wfScan

          1. wfScan(WFSCAN scanType, int * pcNetworks, IPSTATUS * pStatus)

          2. wfScan(int * pcNetworks)

          3. wfScan(WFSCAN scanType, int * pcNetworks)

          4. wfScan(int * pcNetworks, IPSTATUS * pStatus)

        7. wfConnect

          1. wfConnect(const char * szSsid)

          2. wfConnect(const char * szSsid, IPSTATUS * pStatus)

          3. wfConnect(const char * szSsid, WEP40KEY& keySet, int iKey)

          4. wfConnect(const char * szSsid, WEP40KEY& keySet, int iKey, IPSTATUS * pStatus)

          5. bool wfConnect(const char * szSsid, WEP104KEY& keySet, int iKey)

          6. wfConnect(const char * szSsid, WEP104KEY& keySet, int iKey, IPSTATUS * pStatus)

          7. wfConnect(const char * szSsid, const char * szPassPhrase)

          8. wfConnect(const char * szSsid, const char * szPassPhrase)

          9. wfConnect(const char * szSsid, WPA2KEY& key)

          10. wfConnect(const char * szSsid, WPA2KEY& key, IPSTATUS * pStatus)

          11. wfConnect(SECURITY security, const char * szSsid, const char * szPassPhrase)

          12. wfConnect(SECURITY security, const char * szSsid, const char * szPassPhrase, IPSTATUS * pStatus)

          13. wfConnect(SECURITY security, const char * szSsid, const byte * rgbKey, int iKey)

          14. wfConnect(SECURITY security, const char * szSsid, const byte * rgbKey, int iKey, IPSTATUS * pStatus)

  4. External Links

Detailed Introduction

DEWFcK defines the minimal class for WiFi support. This is not the WiFi adaptor. The examples included on this page make use of other libraries such as MRF24G and DEIPcK.

Introductory Programs

WiFiScan

Scans the network for all available routers and prints their parameters to the Serial Monitor.

/************************************************************************/
/*                                                                      */
/*      WiFiScan                                                        */
/*                                                                      */
/*      Scans the network for all available routers                     */
/*      and prints their parameters to the Serial Monitor               */
/*                                                                      */
/************************************************************************/
/*    Author:     Keith Vogel                                           */
/*    Copyright 2013, Digilent Inc.                                     */
/************************************************************************/
/* 
*
* Copyright (c) 2013-2014, Digilent <www.digilentinc.com>
* Contact Digilent for the latest version.
*
* This program is free software; distributed under the terms of 
* BSD 3-clause license ("Revised BSD License", "New BSD License", or "Modified BSD License")
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1.    Redistributions of source code must retain the above copyright notice, this
*        list of conditions and the following disclaimer.
* 2.    Redistributions in binary form must reproduce the above copyright notice,
*        this list of conditions and the following disclaimer in the documentation
*        and/or other materials provided with the distribution.
* 3.    Neither the name(s) of the above-listed copyright holder(s) nor the names
*        of its contributors may be used to endorse or promote products derived
*        from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/************************************************************************/
/*  Revision History:                                                   */
/*    5/14/2014 (KeithV): Created                                       */
/************************************************************************/
/************************************************************************/
/*                       Supported hardware:                            */
/*                                                                      */
/*  uC32 with a WiFiShield                                              */
/*  WF32                                                                */
/*  WiFIRE                                                              */
/*                                                                      */
/************************************************************************/
/************************************************************************/
/*                                                                      */
/*    Network Hardware libraries                                        */
/*    INCLUDE ONLY ONE                                                  */
/*                                                                      */
/************************************************************************/
// You MUST select 1 and ONLY 1 of the following hardware libraries
// they are here so that MPIDE will put the lib path on the compiler include path.
#include <MRF24G.h>                         // This is for the MRF24WGxx on a pmodWiFi or WiFiShield
//#include <IM8720PHY.h>                      // This is for the the Internal MAC and SMSC 8720 PHY

/************************************************************************/
/*    Network libraries                                                 */
/************************************************************************/
// The base network library
// this is a required library
// Do not comment out this library
#include <DEIPcK.h>

//  -----  COMMENT THIS OUT IF YOU ARE NOT USING WIFI  -----
#include <DEWFcK.h>

//************************************************************************
//************************************************************************
//**************** END OF LIBRARY CONFIGURATION **************************
//************************************************************************
//************************************************************************

#define MRFVERSION

typedef enum
{
    NONE = 0,
    WIFISCAN,
    PRINTAPINFO,
    ERROR,
    STOP,
    DONE
} STATE;

STATE state = WIFISCAN;

IPSTATUS status = ipsSuccess;
int  cNetworks = 0;
int iNetwork = 0;

void setup() {

    Serial.begin(9600);

    Serial.println("Start of Sketch");
    Serial.println("WiFiScan 3.0");
    Serial.println("Digilent, Copyright 2014");
    Serial.println("");

    state = WIFISCAN;          // Scan WiFi First, verify the WiFi connection
    Serial.println("Start WiFi Scan");
    cNetworks = 0;
}

void loop() 
{
    switch(state)
    {
        case WIFISCAN:
            if(deIPcK.wfScan(&cNetworks, &status))
            {
                Serial.print("Scan Done, ");
                Serial.print(cNetworks, DEC);
                Serial.println(" Networks Found");
                state = PRINTAPINFO;
                iNetwork = 0;
            }
            else if(IsIPStatusAnError(status))
            {
                Serial.println("Scan Failed");
                Serial.println("");
                state = ERROR;
            }
            break;

        case PRINTAPINFO:
            if(iNetwork < cNetworks)
            {
                SCANINFO scanInfo;
                uint32_t j = 0;

                if(deIPcK.getScanInfo(iNetwork, &scanInfo))
                {
                    Serial.println("");
                    Serial.print("Scan info for index: ");
                    Serial.println(iNetwork, DEC);

                    Serial.print("SSID: ");
                    for(j=0; j<scanInfo.ssidLen; j++)
                    {
                        Serial.print((char) scanInfo.ssid[j]);
                    }
                    Serial.println();

                    Serial.print("BSSID / MAC: ");
                    for(j=0; j<sizeof(scanInfo.bssid); j++)
                    {
                        if(scanInfo.bssid[j] < 16)
                        {
                            Serial.print(0, HEX);
                        }
                        Serial.print(scanInfo.bssid[j], HEX);
                    }
                    Serial.println("");

                    Serial.print("Channel: ");
                    Serial.println(scanInfo.channel, DEC);

                    Serial.print("Signal Strength: ");
                    Serial.println(scanInfo.rssi, DEC);

                    if(scanInfo.bssType == DEWF_INFRASTRUCTURE)
                    {
                        Serial.println("Infrastructure Network");
                    }
                    else if(scanInfo.bssType == DEWF_ADHOC)
                    {
                        Serial.println("AdHoc Network");
                    }
                    else
                    {
                        Serial.println("Unknown Network Type");
                    }

                    Serial.print("Beacon Period: ");
                    Serial.println(scanInfo.beaconPeriod, DEC);

                    Serial.print("dtimPeriod: ");
                    Serial.println(scanInfo.dtimPeriod, DEC);

                    Serial.print("atimWindow: ");
                    Serial.println(scanInfo.atimWindow, DEC);

                    Serial.println("Secuity info: WPA2  WPA  Preamble  Privacy  Reserved  Reserved  Reserved  IE");
                      Serial.print("                ");
                      Serial.print((scanInfo.apConfig & 0b10000000) >> 7, DEC);
                                       Serial.print("    ");
                                       Serial.print((scanInfo.apConfig & 0b01000000) >> 6, DEC);
                                            Serial.print("       ");
                                            Serial.print((scanInfo.apConfig & 0b00100000) >> 5, DEC);
                                                    Serial.print("        ");
                                                    Serial.print((scanInfo.apConfig & 0b00010000) >> 4, DEC);
                                                             Serial.print("         ");
                                                             Serial.print((scanInfo.apConfig & 0b00001000) >> 3, DEC);
                                                                       Serial.print("         ");
                                                                        Serial.print((scanInfo.apConfig & 0b00000100) >> 2, DEC);
                                                                                 Serial.print("         ");
                                                                                 Serial.print((scanInfo.apConfig & 0b00000010) >> 1, DEC);
                                                                                           Serial.print("      ");
                                                                                           Serial.println((scanInfo.apConfig & 0b00000001), DEC);

                    Serial.print("Count of support bit rates: ");
                    Serial.println(scanInfo.cBasicRates, DEC);    

                    for(j=0; j<scanInfo.cBasicRates; j++)
                    {
                        uint32_t rate = (scanInfo.basicRateSet[j] & 0x7F) * 500;
                        Serial.print("\tSupported Rate: ");
                        Serial.print(rate, DEC);
                        Serial.println(" kbps");
                    }
                }
                else
                {
                    Serial.print("Unable to get scan info for iNetwork: ");
                    Serial.println(iNetwork, DEC);
                }

                iNetwork++;
            }
            else
            {            
// this is MRF24 specific code
// this will not run in all implemenations
#if defined(MRFVERSION)
                t_deviceInfo dvInfo;
                WF_DeviceInfoGet(&dvInfo);

                Serial.println("");
                Serial.println("Device Info");
                Serial.print("DeviceType: 0x");
                Serial.print((int) dvInfo.deviceType, HEX);
                Serial.print(" Rom Version: 0x");
                Serial.print((int) dvInfo.romVersion, HEX);
                Serial.print(" Patch Version: 0x");
                Serial.println((int) dvInfo.patchVersion, HEX);
#endif
                Serial.println("");
                state = STOP;
            }
            break;

        case ERROR:
            Serial.print("Status value: ");
            Serial.println(status, DEC);
            state = STOP;
            break;

        case STOP:
            Serial.println("End of Sketch");
            state = DONE;
            break;

        case DONE:
        default:
            break;

    }

    DEIPcK::periodicTasks();
}

WiFiTCPEchoServer

450px

A chipKIT DEWFcK TCP Server application to demonstrate how to use the TcpServer Class. This can be used in conjuction with the included C# TCPEchoClient located in ...\libraries\DEIPcK\examples\TCPEchoServer\PCCode. Note that it's in the DEIPFcK and not DEWFcK library example directory.

To use this example you'll first need to modify it a bit. You'll need to provide an IP Address which is not already in use on your network. You can also change the port if you desire. Provide the SSID (name of you network) so that the board knows what local network we want to connect to. Then you'll need to setup security settings. This will be the same settings you would use if connecting to your local network using a tablet or laptop. By default WPA2 is enabled. To choose another type of security key or no key at all comment out WPA2 and un-comment the appropriate setting for you network. For example if your password typically looks like 1122334455 then you are probably using WEP40. If this is the case un-comment #define USE_WEP40 and change

WEP40KEY keySet = { 0xBE, 0xC9, 0x58, 0x06, 0x97,         // Key 0
                        0x00, 0x00, 0x00, 0x00, 0x00,     // Key 1
                        0x00, 0x00, 0x00, 0x00, 0x00,     // Key 2
                        0x00, 0x00, 0x00, 0x00, 0x00 };   // Key 3 

to

 WEP40KEY keySet = { 0x11, 0x22, 0x33, 0x44, 0x55,        // Key 0
                        0x00, 0x00, 0x00, 0x00, 0x00,     // Key 1
                        0x00, 0x00, 0x00, 0x00, 0x00,     // Key 2
                        0x00, 0x00, 0x00, 0x00, 0x00 };   // Key 3
/************************************************************************/
/*                                                                      */
/*       TCPEchoServer                                                  */
/*                                                                      */
/*       A chipKIT DEWFcK TCP Server application to                     */
/*       demonstrate how to use the TcpServer Class.                    */
/*       This can be used in conjuction  with TCPEchoClient             */              
/*                                                                      */
/************************************************************************/
/*       Author:        Keith Vogel                                     */
/*       Copyright 2014, Digilent Inc.                                  */
/************************************************************************/
/* 
*
* Copyright (c) 2013-2014, Digilent <www.digilentinc.com>
* Contact Digilent for the latest version.
*
* This program is free software; distributed under the terms of 
* BSD 3-clause license ("Revised BSD License", "New BSD License", or "Modified BSD License")
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1.    Redistributions of source code must retain the above copyright notice, this
*        list of conditions and the following disclaimer.
* 2.    Redistributions in binary form must reproduce the above copyright notice,
*        this list of conditions and the following disclaimer in the documentation
*        and/or other materials provided with the distribution.
* 3.    Neither the name(s) of the above-listed copyright holder(s) nor the names
*        of its contributors may be used to endorse or promote products derived
*        from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/************************************************************************/
/*  Revision History:                                                   */
/*                                                                      */
/*       5/14/2014 (KeithV): Created                                    */
/*                                                                      */
/************************************************************************/

/************************************************************************/
/*                       Supported hardware:                            */
/*                                                                      */
/*  uC32 with a WiFiShield                                              */
/*  WF32                                                                */
/*  WiFIRE                                                              */
/*                                                                      */
/************************************************************************/

//******************************************************************************************
//******************************************************************************************
//***************************** SET YOUR CONFIGURATION *************************************
//******************************************************************************************
//******************************************************************************************

/************************************************************************/
/*                                                                      */
/*              Include ONLY 1 hardware library that matches            */
/*              the network hardware you are using                      */
/*                                                                      */
/*              Refer to the hardware library header file               */
/*              for supported boards and hardware configurations        */
/*                                                                      */
/************************************************************************/
#include <MRF24G.h>                     // This is for the MRF24WGxx on a pmodWiFi or WiFiShield

/************************************************************************/
/*                    Required libraries, Do NOT comment out            */
/************************************************************************/
#include <DEIPcK.h>
#include <DEWFcK.h>

/************************************************************************/
/*                                                                      */
/*              SET THESE VALUES FOR YOUR NETWORK                       */
/*                                                                      */
/************************************************************************/

IPv4 ipServer = {192,168,1,190};
unsigned short portServer = DEIPcK::iPersonalPorts44 + 300;     // port 44300

// Specify the SSID
const char * szSsid = "chipKIT";

// select 1 for the security you want, or none for no security
#define USE_WPA2_PASSPHRASE
//#define USE_WPA2_KEY
//#define USE_WEP40
//#define USE_WEP104
//#define USE_WF_CONFIG_H

// modify the security key to what you have.
#if defined(USE_WPA2_PASSPHRASE)

    const char * szPassPhrase = "Digilent";
    #define WiFiConnectMacro() deIPcK.wfConnect(szSsid, szPassPhrase, &status)

#elif defined(USE_WPA2_KEY)

    WPA2KEY key = { 0x27, 0x2C, 0x89, 0xCC, 0xE9, 0x56, 0x31, 0x1E,
                    0x3B, 0xAD, 0x79, 0xF7, 0x1D, 0xC4, 0xB9, 0x05,
                    0x7A, 0x34, 0x4C, 0x3E, 0xB5, 0xFA, 0x38, 0xC2,
                    0x0F, 0x0A, 0xB0, 0x90, 0xDC, 0x62, 0xAD, 0x58 };
    #define WiFiConnectMacro() deIPcK.wfConnect(szSsid, key, &status)

#elif defined(USE_WEP40)

    const int iWEPKey = 0;
    WEP40KEY keySet = { 0xBE, 0xC9, 0x58, 0x06, 0x97,     // Key 0
                        0x00, 0x00, 0x00, 0x00, 0x00,     // Key 1
                        0x00, 0x00, 0x00, 0x00, 0x00,     // Key 2
                        0x00, 0x00, 0x00, 0x00, 0x00 };   // Key 3
    #define WiFiConnectMacro() deIPcK.wfConnect(szSsid, keySet, iWEPKey, &status)

#elif defined(USE_WEP104)

    const int iWEPKey = 0;
    WEP104KEY keySet = { 0x3E, 0xCD, 0x30, 0xB2, 0x55, 0x2D, 0x3C, 0x50, 0x52, 0x71, 0xE8, 0x83, 0x91,   // Key 0
                         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,   // Key 1
                         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,   // Key 2
                         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // Key 3
    #define WiFiConnectMacro() deIPcK.wfConnect(szSsid, keySet, iWEPKey, &status)

#elif defined(USE_WF_CONFIG_H)

    #define WiFiConnectMacro() deIPcK.wfConnect(0, &status)

#else   // no security - OPEN

    #define WiFiConnectMacro() deIPcK.wfConnect(szSsid, &status)

#endif

//******************************************************************************************
//******************************************************************************************
//***************************** END OF CONFIGURATION ***************************************
//******************************************************************************************
//******************************************************************************************

typedef enum
{
    NONE = 0,
    CONNECT,
    LISTEN,
    ISLISTENING,
    WAITISLISTENING,
    AVAILABLECLIENT,
    ACCEPTCLIENT,
    READ,
    WRITE,
    CLOSE,
    EXIT,
    DONE
} STATE;

STATE state = CONNECT;

unsigned tStart = 0;
unsigned tWait = 5000;

TCPServer tcpServer;
#define cTcpClients 2
TCPSocket rgTcpClient[cTcpClients];

TCPSocket * ptcpClient = NULL;

byte rgbRead[1024];
int cbRead = 0;
int count = 0;

IPSTATUS status;

/***       void setup()
 *
 *       Parameters:
 *          None
 *              
 *       Return Values:
 *          None
 *
 *       Description: 
 *       
 *      Arduino setup function.
 *      
 *      Initialize the Serial Monitor, and initializes the
 *      the IP stack for a static IP of ipServer
 *      No other network addresses are supplied so 
 *      DNS will fail as any name lookup and time servers
 *      will all fail. But since we are only listening, who cares.
 *      
 * ------------------------------------------------------------ */
void setup() {
    Serial.begin(9600);
    Serial.println("WiFiTCPEchoServer 3.0");
    Serial.println("Digilent, Copyright 2014");
    Serial.println("");
}

/***       void loop()
 *
 *       Parameters:
 *          None
 *              
 *       Return Values:
 *          None
 *
 *       Description: 
 *       
 *      Arduino loop function.
 *      
 *      We are using the default timeout values for the DNETck and TcpServer class
 *      which usually is enough time for the Tcp functions to complete on their first call.
 *
 *      This code listens for a connection, then echos any strings that come in
 *      After about 5 seconds of inactivity, it will drop the connection.
 *
 *      This is a simple sketch to illistrate a simple TCP Server. 
 *      
 * ------------------------------------------------------------ */
void loop() {

    switch(state)
    {

        case CONNECT:
            if(WiFiConnectMacro())
            {
                Serial.println("Connection Created");
                deIPcK.begin(ipServer);
                state = LISTEN;
            }
            else if(IsIPStatusAnError(status))
            {
                Serial.print("Unable to connection, status: ");
                Serial.println(status, DEC);
                state = CLOSE;
            }
            break;

    // say to listen on the port
    case LISTEN:
        if(deIPcK.tcpStartListening(portServer, tcpServer))
        {
            for(int i = 0; i < cTcpClients; i++)
            {
                tcpServer.addSocket(rgTcpClient[i]);
            }
        }
        state = ISLISTENING;
        break;

    case ISLISTENING:
        count = tcpServer.isListening();
        Serial.print(count, DEC);
        Serial.print(" sockets listening on port: ");
        Serial.println(portServer, DEC);

        if(count > 0)
        {
            state = AVAILABLECLIENT;
        }
        else
        {
            state = WAITISLISTENING;
        }
        break;

    case WAITISLISTENING:
        if(tcpServer.isListening() > 0)
        {
            state = ISLISTENING;
        }
        break;

    // wait for a connection
    case AVAILABLECLIENT:
        if((count = tcpServer.availableClients()) > 0)
        {
            Serial.print("Got ");
            Serial.print(count, DEC);
            Serial.println(" clients pending");
            state = ACCEPTCLIENT;
        }
        break;

    // accept the connection
    case ACCEPTCLIENT:
        
        // accept the client
        if((ptcpClient = tcpServer.acceptClient()) != NULL && ptcpClient->isConnected())
        {
            Serial.println("Got a Connection");
            state = READ;
            tStart = (unsigned) millis();
        }

        // this probably won't happen unless the connection is dropped
        // if it is, just release our socket and go back to listening
        else
        {
            state = CLOSE;
        }
        break;

    // wait fot the read, but if too much time elapses (5 seconds)
    // we will just close the tcpClient and go back to listening
    case READ:

        // see if we got anything to read
        if((cbRead = ptcpClient->available()) > 0)
        {
            cbRead = cbRead < (int) sizeof(rgbRead) ? cbRead : sizeof(rgbRead);
            cbRead = ptcpClient->readStream(rgbRead, cbRead);

            Serial.print("Got ");
            Serial.print(cbRead, DEC);
            Serial.println(" bytes");
           
            state = WRITE;
        }

        // If too much time elapsed between reads, close the connection
        else if( (((unsigned) millis()) - tStart) > tWait )
        {
            state = CLOSE;
        }
        break;

    // echo back the string
    case WRITE:
        if(ptcpClient->isConnected())
        {               
            Serial.println("Writing: ");  
            for(int i=0; i < cbRead; i++) 
            {
                Serial.print((char) rgbRead[i]);
            }
            Serial.println("");  

            ptcpClient->writeStream(rgbRead, cbRead);
            state = READ;
            tStart = (unsigned) millis();
        }

        // the connection was closed on us, go back to listening
        else
        {
            Serial.println("Unable to write back.");  
            state = CLOSE;
        }
        break;
        
    // close our tcpClient and go back to listening
    case CLOSE:
        ptcpClient->close();
        tcpServer.addSocket(*ptcpClient);
        Serial.println("");
        state = ISLISTENING;
        break;

    // something bad happen, just exit out of the program
    case EXIT:
        tcpServer.close();
        Serial.println("Something went wrong, sketch is done.");  
        state = DONE;
        break;

    // do nothing in the loop
    case DONE:
    default:
        break;
    }

    // every pass through loop(), keep the stack alive
    DEIPcK::periodicTasks();
}

WiFiTCPEchoServer

A chipKIT DEIPcK TCP Client application to demonstrate how to use the TcpClient Class. This can be used in conjuction with TCPEchoServer.

/************************************************************************/
/*                                                                      */
/*        TCPEchoClient                                                 */
/*                                                                      */
/*        A chipKIT DEIPcK TCP Client application to                    */
/*        demonstrate how to use the TcpClient Class.                   */
/*        This can be used in conjuction  with TCPEchoServer            */                
/*                                                                      */
/************************************************************************/
/*        Author:         Keith Vogel                                   */
/*        Copyright 2014, Digilent Inc.                                 */
/************************************************************************/
/* 
*
* Copyright (c) 2013-2014, Digilent <www.digilentinc.com>
* Contact Digilent for the latest version.
*
* This program is free software; distributed under the terms of 
* BSD 3-clause license ("Revised BSD License", "New BSD License", or "Modified BSD License")
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1.    Redistributions of source code must retain the above copyright notice, this
*        list of conditions and the following disclaimer.
* 2.    Redistributions in binary form must reproduce the above copyright notice,
*        this list of conditions and the following disclaimer in the documentation
*        and/or other materials provided with the distribution.
* 3.    Neither the name(s) of the above-listed copyright holder(s) nor the names
*        of its contributors may be used to endorse or promote products derived
*        from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/************************************************************************/
/*                                                                      */
/*                                                                      */
/************************************************************************/
/*  Revision History:                                                   */
/*                                                                      */
/*    5/14/2014(KeithV): Created                                       */
/*                                                                      */
/************************************************************************/

/************************************************************************/
/*                       Supported hardware:                            */
/*                                                                      */
/*  uC32 with a WiFiShield                                              */
/*  WF32                                                                */
/*  WiFIRE                                                              */
/*                                                                      */
/************************************************************************/

//******************************************************************************************
//******************************************************************************************
//***************************** SET YOUR CONFIGURATION *************************************
//******************************************************************************************
//******************************************************************************************

/************************************************************************/
/*                                                                      */
/*              Include ONLY 1 hardware library that matches            */
/*              the network hardware you are using                      */
/*                                                                      */
/*              Refer to the hardware library header file               */
/*              for supported boards and hardware configurations        */
/*                                                                      */
/************************************************************************/
#include <MRF24G.h>                     // This is for the MRF24WGxx on a pmodWiFi or WiFiShield

/************************************************************************/
/*                    Required libraries, Do NOT comment out            */
/************************************************************************/
#include <DEIPcK.h>
#include <DEWFcK.h>

/************************************************************************/
/*                                                                      */
/*              SET THESE VALUES FOR YOUR NETWORK                       */
/*                                                                      */
/************************************************************************/

const char * szIPServer = "192.168.1.180";    // server to connect to
uint16_t portServer = DEIPcK::iPersonalPorts44 + 300;     // port 44300

// Specify the SSID
const char * szSsid = "chipKIT";

// select 1 for the security you want, or none for no security
#define USE_WPA2_PASSPHRASE
//#define USE_WPA2_KEY
//#define USE_WEP40
//#define USE_WEP104
//#define USE_WF_CONFIG_H

// modify the security key to what you have.
#if defined(USE_WPA2_PASSPHRASE)

    const char * szPassPhrase = "Digilent";
    #define WiFiConnectMacro() deIPcK.wfConnect(szSsid, szPassPhrase, &status)

#elif defined(USE_WPA2_KEY)

    WPA2KEY key = { 0x27, 0x2C, 0x89, 0xCC, 0xE9, 0x56, 0x31, 0x1E, 
                    0x3B, 0xAD, 0x79, 0xF7, 0x1D, 0xC4, 0xB9, 0x05, 
                    0x7A, 0x34, 0x4C, 0x3E, 0xB5, 0xFA, 0x38, 0xC2, 
                    0x0F, 0x0A, 0xB0, 0x90, 0xDC, 0x62, 0xAD, 0x58 };
    #define WiFiConnectMacro() deIPcK.wfConnect(szSsid, key, &status)

#elif defined(USE_WEP40)

    const int iWEPKey = 0;
    WEP40KEY keySet = { 0xBE, 0xC9, 0x58, 0x06, 0x97,     // Key 0
                        0x00, 0x00, 0x00, 0x00, 0x00,     // Key 1
                        0x00, 0x00, 0x00, 0x00, 0x00,     // Key 2
                        0x00, 0x00, 0x00, 0x00, 0x00 };   // Key 3
    #define WiFiConnectMacro() deIPcK.wfConnect(szSsid, keySet, iWEPKey, &status)

#elif defined(USE_WEP104)

    const int iWEPKey = 0;
    WEP104KEY keySet = { 0x3E, 0xCD, 0x30, 0xB2, 0x55, 0x2D, 0x3C, 0x50, 0x52, 0x71, 0xE8, 0x83, 0x91,   // Key 0
                         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,   // Key 1
                         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,   // Key 2
                         0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; // Key 3
    #define WiFiConnectMacro() deIPcK.wfConnect(szSsid, keySet, iWEPKey, &status)

#elif defined(USE_WF_CONFIG_H)

    #define WiFiConnectMacro() deIPcK.wfConnect(0, &status)

#else   // no security - OPEN

    #define WiFiConnectMacro() deIPcK.wfConnect(szSsid, &status)

#endif
   
//******************************************************************************************
//******************************************************************************************
//***************************** END OF CONFIGURATION ***************************************
//******************************************************************************************
//******************************************************************************************

typedef enum
{
    NONE = 0,
    CONNECT,
    TCPCONNECT,
    WRITE,
    READ,
    CLOSE,
    DONE,
} STATE;

STATE state = CONNECT;

unsigned tStart = 0;
unsigned tWait = 5000;

TCPSocket tcpSocket;
byte rgbRead[1024];

// this is for Print.write to print
byte rgbWrite[] = {'*','W','r','o','t','e',' ','f','r','o','m',' ','p','r','i','n','t','.','w','r','i','t','e','*','\n'};
int cbWrite = sizeof(rgbWrite);

// this is for tcpSocket.writeStream to print
byte rgbWriteStream[] = {'*','W','r','o','t','e',' ','f','r','o','m',' ','t','c','p','C','l','i','e','n','t','.','w','r','i','t','e','S','t','r','e','a','m','*','\n'};
int cbWriteStream = sizeof(rgbWriteStream);

/***        void setup()
 *
 *        Parameters:
 *          None
 *              
 *        Return Values:
 *          None
 *
 *        Description: 
 *        
 *      Arduino setup function.
 *      
 *      Initialize the Serial Monitor, and initializes the
 *      connection to the TCPEchoServer
 *      Use DHCP to get the IP, mask, and gateway
 *      by default we connect to port 44300
 *      
 * ------------------------------------------------------------ */
void setup()
{
    Serial.begin(9600);
    Serial.println("WiFiTCPEchoClient 3.0");
    Serial.println("Digilent, Copyright 2014");
    Serial.println("");
}

/***        void loop()
 *
 *        Parameters:
 *          None
 *              
 *        Return Values:
 *          None
 *
 *        Description: 
 *        
 *      Arduino loop function.
 *      
 *      We are using the default timeout values for the DEIPcK and TcpClient class
 *      which usually is enough time for the Tcp functions to complete on their first call.
 *
 *      This code will write  some stings to the server and have the server echo it back
 *      
 * ------------------------------------------------------------ */
void loop() {
    IPSTATUS status;
    int cbRead = 0;

    switch(state)
    {

        case CONNECT:
            if(WiFiConnectMacro())
            {
                Serial.println("WiFi connected");
                deIPcK.begin();
                state = TCPCONNECT;
            }
            else if(IsIPStatusAnError(status))
            {
                Serial.print("Unable to connection, status: ");
                Serial.println(status, DEC);
                state = CLOSE;
            }
            break;

        case TCPCONNECT:
            if(deIPcK.tcpConnect(szIPServer, portServer, tcpSocket))
            {
                Serial.println("Connected to server.");
                state = WRITE;
            }
        break;

        // write out the strings
        case WRITE:
            if(tcpSocket.isEstablished())
                {     
                tcpSocket.writeStream(rgbWriteStream, cbWriteStream);
 
                Serial.println("Bytes Read Back:");
                state = READ;
                tStart = (unsigned) millis();
                }
            break;

            // look for the echo back
            case READ:

                // see if we got anything to read
                if((cbRead = tcpSocket.available()) > 0)
                {
                    cbRead = cbRead < (int) sizeof(rgbRead) ? cbRead : sizeof(rgbRead);
                    cbRead = tcpSocket.readStream(rgbRead, cbRead);

                    for(int i=0; i < cbRead; i++)
                    {
                        Serial.print((char) rgbRead[i]);
                    }
                }

                // give us some time to get everything echo'ed back
                else if( (((unsigned) millis()) - tStart) > tWait )
                {
                    Serial.println("");
                    state = CLOSE;
                }
                break;

        // done, so close up the tcpSocket
        case CLOSE:
            tcpSocket.close();
            Serial.println("Closing TcpClient, Done with sketch.");
            state = DONE;
            break;

        case DONE:
        default:
            break;
    }

    // keep the stack alive each pass through the loop()
    DEIPcK::periodicTasks();
}

Full library usage

DEWFcK

Public Functions


setWF(const NWWF * pNwWF)

bool  setWF(const NWWF * pNwWF);

isWFInitialized(void)

bool isWFInitialized(void);

isWFInitialized(IPSTATUS * pStatus)

bool isWFInitialized(IPSTATUS * pStatus);

wfDisconnect(void)

void wfDisconnect(void);

Drops the connection to the AP.

getScanInfo(int iNetwork, SCANINFO * pscanInfo)

bool getScanInfo(int iNetwork, SCANINFO * pscanInfo);

Returns the the AP (router) info for the specifed network scanned. iNetwork is a zero based index that is less than the number of networks returned by isScanDone. pscanInfo is a point to a SCANINFO to return the AP (router) information. Returns True if the AP information is returned, false if there is no information or the scan is not done. This may be called at any time after isScanDone succeeds.

wfScan


The following parameters apply to all overloaded methods of wfScan. These functions scan for a WiFi SSID based on profile or connection ID. Returns True if the the scan got started, false if not.. usually becasue an invalid connectionID was given. We have to wait for a scan to finish before we can do any other hardware stuff, so this is a harsh call in that once connected this can cause problems or the connection can cause problem for this That is why once we are conneced, this call will fail, we can't run it.

Name Description
connectionID The connection ID or Profile already stored on the MRF24WB0M to use. If 0 is specified the default parameters as in WF_Config.h are used.
connectionID Scan for the network defined by the specifed profile, or all networks if 0/WF_SCAN_ALL is specified or omitted
scanType WF_ACTIVE_SCAN or WF_PASSIVE_SCAN or WF_PASSIVE_SCAN if omitted.
pStatus A point to a DEIPcK::STATUS to return the status of the connect process.
wfScan(WFSCAN scanType, int * pcNetworks, IPSTATUS * pStatus)
bool wfScan(WFSCAN scanType, int * pcNetworks, IPSTATUS * pStatus);
wfScan(int * pcNetworks)
bool wfScan(int * pcNetworks)
wfScan(WFSCAN scanType, int * pcNetworks)
bool wfScan(WFSCAN scanType, int * pcNetworks)
wfScan(int * pcNetworks, IPSTATUS * pStatus)
bool wfScan(int * pcNetworks, IPSTATUS * pStatus)

wfConnect


The following parameters apply to all overloaded methods of wfConnect. These functions setup a connection to the WiFi AP. Returns the connection/Profile ID that is in use. If 0 is returned the connection process failed. This method returns immediately and the connection process is started. Some form of isConnected should be called to determine if the connection is made. If the WPA(2) key must be calculated, this process will start and will typically take 30 seconds to complete.

Name Description
connectionID The connection ID or Profile already stored on the MRF24WB0M to use. If 0 is specified the default parameters as in WF_Config.h are used.
security One of the security key types as defined in the DEWFcK::SECURITY enum type.
szSsid A zero terminate string of the WiFi SSID to connect to.
rgbKey An array of bytes that contains the key information. This may have characters or a string if appropriate for the sercurity type used.
cbKey The number of bytes in rgbKey.
keySet The 4 WEP keysets, if WEP40 or WEP104 is used.
iKey 0 based index into the WEP key set to specify the key to use.
key The WPA(2) key (32 bytes).
szPassPhrase The WPA(2) passphrase if a key is not used.
pStatus A point to a DEIPcK::STATUS to return the status of the connect process.
wfConnect(const char * szSsid)
bool wfConnect(const char * szSsid); 

No security

wfConnect(const char * szSsid, IPSTATUS * pStatus)
bool wfConnect(const char * szSsid, IPSTATUS * pStatus);

No security

wfConnect(const char * szSsid, WEP40KEY& keySet, int iKey)
bool wfConnect(const char * szSsid, WEP40KEY& keySet, int iKey);     

WEP 40

wfConnect(const char * szSsid, WEP40KEY& keySet, int iKey, IPSTATUS * pStatus)
bool wfConnect(const char * szSsid, WEP40KEY& keySet, int iKey, IPSTATUS * pStatus);   

WEP 40

bool wfConnect(const char * szSsid, WEP104KEY& keySet, int iKey)

bool wfConnect(const char * szSsid, WEP104KEY& keySet, int iKey);

WEP 104
wfConnect(const char * szSsid, WEP104KEY& keySet, int iKey, IPSTATUS * pStatus)
bool wfConnect(const char * szSsid, WEP104KEY& keySet, int iKey, IPSTATUS * pStatus);                       

WEP 104

wfConnect(const char * szSsid, const char * szPassPhrase)
bool wfConnect(const char * szSsid, const char * szPassPhrase);                                              

WPA2

wfConnect(const char * szSsid, const char * szPassPhrase)
bool wfConnect(const char * szSsid, const char * szPassPhrase, IPSTATUS * pStatus);                          

WPA2

wfConnect(const char * szSsid, WPA2KEY& key)
bool wfConnect(const char * szSsid, WPA2KEY& key);                                                           

WPA2

wfConnect(const char * szSsid, WPA2KEY& key, IPSTATUS * pStatus)
bool wfConnect(const char * szSsid, WPA2KEY& key, IPSTATUS * pStatus);                                       

WPA2

wfConnect(SECURITY security, const char * szSsid, const char * szPassPhrase)
v bool wfConnect(SECURITY security, const char * szSsid, const char * szPassPhrase); Explicit
wfConnect(SECURITY security, const char * szSsid, const char * szPassPhrase, IPSTATUS * pStatus)
bool wfConnect(SECURITY security, const char * szSsid, const char * szPassPhrase, IPSTATUS * pStatus);       

Explicit

wfConnect(SECURITY security, const char * szSsid, const byte * rgbKey, int iKey)
bool wfConnect(SECURITY security, const char * szSsid, const byte * rgbKey, int iKey);                       

Explicit

wfConnect(SECURITY security, const char * szSsid, const byte * rgbKey, int iKey, IPSTATUS * pStatus)
bool wfConnect(SECURITY security, const char * szSsid, const byte * rgbKey, int iKey, IPSTATUS * pStatus);  

Explicit

External Links