Friday, December 2, 2011

My own web server

This is adapted to some extent from the web server and SD code examples. As with the web server example, this is currently interpreting any HTTP request as GET / HTTP/1.1 - the twist is that it is reading index.htm from the SD card, and serving that. If it can't open and read index.htm, it sends a 404 response. I've also written a function which reads in the request headers one line at a time, and the server then prints them to the serial console (a little like the error log on a full-sized server, and I'm intending to try to use that information later on).



#include <SPI.h>
#include <SD.h>
#include <Ethernet.h>

Server server(80);
const int chipSelect = 4;

void setup()
{
    byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0x7F, 0xB6 };
    byte ip[] = { 143,210,109,74 };
    Serial.begin(9600);
    Serial.print("Initialising SD card... ");
    // Initialise SD card
    pinMode(chipSelect, OUTPUT);
    if (!SD.begin(chipSelect)) 
    {
        Serial.println("FAILED.");
        return;
    }
    Serial.println("SUCCESS.");

    Ethernet.begin(mac, ip);
    server.begin();
}

void loop()
{
    String s;
    
    Client client = server.available();
    if (client)
    {
        while (client.connected())
        {
            if (client.available())
            {
                while (s = get_line(client), s.length() != 0)
                {
                    Serial.println(s);
                }
                File infile = SD.open("index.htm");
                if (infile)
                {
                    client.println("HTTP/1.1 200 OK");
                    client.println("Content-Type: text/html");
                    client.println();                    
                    while (infile.available())
                    {
                        client.write(infile.read());
                    }
                    infile.close();
                }
                else
                {
                    client.println("HTTP/1.1 404 Not Found");
                    client.println("Content-Type: text/html");
                    client.println();
                    client.println("<h1>Server Problem</h1>");
                }
                break;
            }
        } 
        client.stop();
    }
}

String get_line(Client client)
{
    String s = "";
    char   c;
    while (c = client.read(), c != '\n')
    {
        if (c != '\r')
        {
            s = s + c;
        }
    }
    return s;
}

No comments:

Post a Comment