Jack Hansdampf / Mbed OS WebSwitch_ENC28J60_GSOE

Dependencies:   UIPEthernet_GSOE

main.cpp

Committer:
hudakz
Date:
2017-06-30
Revision:
8:3bd85b731cca
Parent:
7:f5e11393836d
Child:
9:6f63abd61de8

File content as of revision 8:3bd85b731cca:

/*
 * In this project LED1 on the mbed board is switched on/off using a web browser.
 * However, you can easily modify the project to remotely switch on/off any external device.
 * The HTTP server is built from an mbed board and an ENC28J60 board.
 * ENC28J60 is driven by the UIPEthernet library <https://github.com/ntruchsess/arduino_uip>.
 * The example is based on the Tuxgraphics Web Switch <http://www.tuxgraphics.org/>.
 */

//#define TARGET_STM32F103C8T6  1     // uncomment this line when using STM32F103C8T6 boards!

#if defined(TARGET_STM32F103C8T6)
#include "stm32f103c8t6.h"
#define LED_PIN PC_13
const int OFF = 1;
const int ON  = 0;
#else
#define LED_PIN LED1
const int OFF = 0;
const int ON  = 1;
#endif

#include "mbed.h"
#include "UIPEthernet.h"
#include "UIPServer.h"
#include "UIPClient.h"
#include "string"

using namespace     std;

Serial  pc(USBTX, USBRX);

#define DHCP    1   // if you'd like to use static IP address comment out this line

// uIPEthernet is the name of a global instance of UIPEthernet.
// Do not change the name! It is used within the UIPEthernet library.
#if defined(TARGET_LPC1768)
UIPEthernet  uIPEthernet(p11, p12, p13, p8);         // mosi, miso, sck, cs
#elif defined(TARGET_LPC1114)
UIPEthernet  uIPEthernet(dp2, dp1, dp6, dp25);       // mosi, miso, sck, cs
#elif defined(TARGET_LPC11U68)
UIPEthernet  uIPEthernet(P0_9, P0_8, P1_29, P0_2);   // mosi, miso, sck, cs
#elif defined(TARGET_NUCLEO_F103RB) || defined(TARGET_NUCLEO_L152RE) || defined(TARGET_NUCLEO_F030R8)  \
   || defined(TARGET_NUCLEO_F401RE) || defined(TARGET_NUCLEO_F302R8) || defined(TARGET_NUCLEO_L053R8)  \
   || defined(TARGET_NUCLEO_F411RE) || defined(TARGET_NUCLEO_F334R8) || defined(TARGET_NUCLEO_F072RB)  \
   || defined(TARGET_NUCLEO_F091RC) || defined(TARGET_NUCLEO_F303RE) || defined(TARGET_NUCLEO_F070RB)
//UIPEthernet  uIPEthernet(D4, D5, D3, D2);             // mosi, miso, sck, cs
//UIPEthernet  uIPEthernet(D11, D12, D13, D10);            // mosi, miso, sck, cs
UIPEthernet  uIPEthernet(PA_7, PA_6, PA_5, PB_6);            // mosi, miso, sck, cs

// If your board/plaform is not present yet then uncomment
// the following two lines and replace TARGET_YOUR_BOARD as appropriate.

//#elif defined(TARGET_YOUR_BOARD)
//UIPEthernet  uIPEthernet(SPI_MOSI, SPI_MISO, SPI_SCK, SPI_CS);   // mosi, miso, sck, cs

#endif

// Note:
// If it happends that any of the SPI_MOSI, SPI_MISO, SPI_SCK, SPI_CS pins collide with LED1 pin
// then either use different SPI port (if available on the board) and change the pin names
// in the constructor uIPEthernet(...) accordingly or instead of using LED1 pin, select
// a free pin (not used by SPI port) and connect to it an external LED which is connected
// to a 220 Ohm resitor that is connected to the groud.
// In the second case remember to replace LED1 in sw(LED1) constructor (see below).
// MAC number must be unique within the connected network. Modify as appropriate.
const uint8_t       MY_MAC[6] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x06 };
const uint16_t      MY_PORT = 80;           // for HTTP connection
EthernetServer      myServer = EthernetServer(MY_PORT);

// In this example we are turning on/off LED1.
DigitalOut          sw(LED_PIN);        // Change LED_PIN to a pin of your choice.
//DigitalOut          sw(D9);           // Change LED_PIN to a pin of your choice.
float               roomTemp = 21.8;    // A temperature sensor output

// However, make sure that it does not collide with any of the SPI pins
// already used in the uIPEthernet(...) constructor above!
const string        PASSWORD = "secret";    // change as you like
const string        HTTP_OK = "HTTP/1.0 200 OK";
const string        MOVED_PERM = "HTTP/1.0 301 Moved Permanently\r\nLocation: ";
const string        UNAUTHORIZED = "HTTP/1.0 401 Unauthorized";
string              httpHeader;     // HTTP header
string              httpContent;    // HTTP content

/**
 * @brief   Analyses the received URL
 * @note    The string passed to this function will look like this:
 *          GET /password HTTP/1.....
 *          GET /password/ HTTP/1.....
 *          GET /password/?sw=1 HTTP/1.....
 *          GET /password/?sw=0 HTTP/1.....
 * @param   url URL string
 * @retval -1 invalid password
 *         -2 no command given but password valid
 *         -3 just refresh page
 *          0 switch off
 *          1 switch on
 */
int8_t analyseURL(string& url) {
    if(url.substr(5, PASSWORD.size()) != PASSWORD)
        return(-1);

    uint8_t pos = 5 + PASSWORD.size();

    if(url.substr(pos, 1) == " ")
        return(-2);

    if(url.substr(pos++, 1) != "/")
        return(-1);

    string  cmd(url.substr(pos, 5));

    if(cmd == "?sw=0")
        return(OFF);

    if(cmd == "?sw=1")
        return(ON);

    return(-3);
}

/**
 * @brief
 * @note
 * @param
 * @retval
 */
string& movedPermanently(uint8_t flag)
{
    if(flag == 1)
        httpContent = "/" + PASSWORD + "/";
    else
        httpContent = "";

    httpContent += "<h1>301 Moved Permanently</h1>\r\n";

    return(httpContent);
}

/**
 * @brief
 * @note
 * @param
 * @retval
 */
string& showWebPage(uint8_t status) {
    char roomTempStr[5];

    //roomTemp = ds1820.read();
    sprintf(roomTempStr, "%3.1f", roomTemp);

    httpContent = "<h2><a href=\".\" title=\"Click to refresh the page\">Smart Home</a></h2>";
    httpContent += "<pre>Temperature:\t" + string(roomTempStr) + "&deg;C\r\n</pre>";

    if(status == ON) {
        httpContent += "<pre>\r\nHeating:\t<font color=#FF0000>On </font>";
        httpContent += " <a href=\"./?sw=0\"><button>Turn off</button></a>\r\n";
    }
    else {
        httpContent += "<pre>\r\nHeating:\t<font color=#999999>Off</font>";
        httpContent += " <a href=\"./?sw=1\"><button>Turn on</button></a>\r\n";
    }

    httpContent += "</pre>\r\n";
    httpContent += "<hr>\r\n";
    httpContent += "<pre>2017 ARMmbed</pre>";
    return httpContent;
}

/**
 * @brief
 * @note
 * @param
 * @retval
 */
void sendHTTP(EthernetClient& client, string& header, string& content)
{
    char    content_length[5] = { };

    header += "\r\nContent-Type: text/html\r\n";
    header += "Content-Length: ";
    sprintf(content_length, "%d", content.length());
    header += string(content_length) + "\r\n";
    header += "Pragma: no-cache\r\n";
    header += "Connection: About to close\r\n";
    header += "\r\n";

    string  webpage = header + content;
    client.write((uint8_t*)webpage.c_str(), webpage.length());
}

/**
 * @brief
 * @note
 * @param
 * @retval
 */
int main(void)
{
#if defined(TARGET_STM32F103C8T6)
    confSysClock();     //Configure system clock (72MHz HSE clock, 48MHz USB clock)
#endif
#if defined(DHCP)
    pc.printf("Searching for DHCP server..\r\n");
    if(uIPEthernet.begin(MY_MAC) != 1) {
        pc.printf("No DHCP server found.\r\n");
        pc.printf("Exiting application.\r\n");
        return 0;
    }
    pc.printf("DHCP server found.\r\n");
#else
    // IP address must be unique and compatible with your network.
    const IPAddress MY_IP(192, 168, 1, 181);    //  Change as appropriate.
    uIPEthernet.begin(MY_MAC, MY_IP);
#endif
    IPAddress   localIP = uIPEthernet.localIP();
    pc.printf("Type %s secret/ into your web browser and hit ENTER\r\n", localIP.toString());
myServer.begin();
    while(1) {
        EthernetClient  client = myServer.available();
        if(client) {
            size_t  size = client.available();
            if(size > 0) {
                uint8_t*    buf = (uint8_t*)malloc(size);
                size = client.read(buf, size);
                string  received((char*)buf);
                free(buf);

                if(received.substr(0, 3) != "GET") {
                    httpHeader = HTTP_OK;
                    httpContent = "<h1>200 OK</h1>";
                    sendHTTP(client, httpHeader, httpContent);
                    continue;
                }

                if(received.substr(0, 6) == "GET / ") {
                    httpHeader = HTTP_OK;
                    httpContent = "<p>Usage: http://host_or_ip/password</p>\r\n";
                    sendHTTP(client, httpHeader, httpContent);
                    continue;
                }

                int cmd = analyseURL(received);

                if(cmd == -2) {
                    // redirect to the right base url
                    httpHeader = MOVED_PERM;
                    sendHTTP(client, httpHeader, movedPermanently(1));
                    continue;
                }

                if(cmd == -1) {
                    httpHeader = UNAUTHORIZED;
                    httpContent = "<h1>401 Unauthorized</h1>";
                    sendHTTP(client, httpHeader, httpContent);
                    continue;
                }

                if(cmd == ON) {
                    sw = ON;    // turn the switch on
                }

                if(cmd == OFF) {
                    sw = OFF;   // turn the switch off
                }

                httpHeader = HTTP_OK;
                sendHTTP(client, httpHeader, showWebPage(sw));
            }
        }
    }
}