↓ Skip to main content
  1. Blog/
  2. nRF52840 Web Server/

Bringing It All Together: Implementing the HTTP Server

Preface
#

In the previous article, I integrated FatFs and WIZnet ioLibrary with the shared SPI driver, allowing the nRF52840 to access files stored on the SD card and communicate with the W5500 Ethernet controller.

With all the necessary components in place, I will now bring them together to implement a static HTTP server capable of serving websites stored on the SD card over Ethernet.

This article concludes the core firmware implementation of the nRF52840 web server.

GitHub Repo: https://github.com/codetit4n/nrf52840-webserver

Design Goals
#

  • Static network configuration: Configure the W5500 with a fixed IP address and other required network parameters.
  • Multiple socket support: Utilize the eight hardware sockets provided by the W5500 to handle incoming connections.
  • Minimal HTTP implementation: Receive and parse HTTP GET requests and generate the corresponding HTTP responses.
  • Static file serving: Serve files stored on the SD card using FatFs, including HTML, CSS, JavaScript, and images.
  • Request validation: Validate incoming request paths and restrict file access to the designated /static root directory.
  • Chunked file transfers: Read and transmit files in chunks to avoid loading entire files into RAM.
  • Error handling and recovery: Handle request timeouts, communication failures, and storage failures, with recovery mechanisms for the W5500 and SD card.
  • Polling-based socket management: Manage socket states and incoming connections by polling the W5500 rather than using W5500 hardware interrupts.

Architecture
#

The diagram below illustrates how the HTTP server brings together the networking and storage components implemented in the previous articles. The HTTP server runs as a FreeRTOS task and uses the socket API provided by WIZnet ioLibrary to communicate with HTTP clients. It uses FatFs to access files stored on the SD card, whose contents are then transmitted to the client through the W5500 Ethernet controller.

High-level architecture of the nRF52840 web server
High-level architecture of the nRF52840 web server

NOTE: In this article, I will focus on the implementation of the HTTP server using the existing networking and storage components.

Relevant Source Code
#

Setting Up Networking
#

Now that the W5500 Ethernet controller has been integrated with the shared SPI driver, the next step is to configure the network parameters and set up a FreeRTOS task to handle incoming connections and HTTP requests.

Network Configuration
#

In this web server, I am using a static network configuration instead of dynamically obtaining the network parameters using DHCP. The configuration is defined in net.h.

#define NET_MAC {0x02, 0x00, 0x00, 0x00, 0x00, 0x50}
#define NET_IP {192, 168, 29, 70}
#define NET_SUBNET {255, 255, 255, 0}
#define NET_GATEWAY {192, 168, 29, 1}
#define NET_DNS {192, 168, 29, 1}

#define HTTP_SOCK_COUNT 8
#define HTTP_PORT 8080
  • MAC address: A locally administered unicast MAC address used to identify the device on the local Ethernet network. In this case, the MAC address is 02:00:00:00:00:50:

    • 02 indicates that it is a locally administered unicast address.

    • 00:00:00:00 represents the middle four bytes of the MAC address, which I have set to zero.

    • 50 is the last byte of the MAC address, which I have chosen to identify this device.

      NOTE: The complete MAC address must be unique within the local Layer 2 network.

  • IP address: A fixed IPv4 address assigned to the web server. In this case, the IP address is 192.168.29.70:

    • 192.168.29 identifies the network based on the configured subnet mask.
    • 70 identifies the device within this subnet.
  • Subnet mask: Determines which portion of the IP address represents the network and which represents the host. In this case, the subnet mask is 255.255.255.0:

    • The first 24 bits identify the network.
    • The remaining 8 bits identify the host.
    • 192.168.29.0 is the network address.
    • 192.168.29.255 is the broadcast address.
    • 192.168.29.1 to 192.168.29.254 are the 254 usable host addresses within the subnet.
  • Gateway: The address of the router through which the device communicates with devices outside its local subnet.

    • I have configured 192.168.29.1, which is the IP address of my local router, as the default gateway.
    • Communication with devices within the same subnet does not require going through the default gateway.
    • Traffic destined for devices outside the local subnet is forwarded through the default gateway.
  • DNS (Domain Name System): Used to resolve domain names to IP addresses.

    • I have configured my local router (192.168.29.1) as the DNS server.
    • Although configured, DNS is not used by the current HTTP server implementation.
    • Clients can access the web server directly using its IP address.
  • Socket count: The number of hardware sockets used by the HTTP server. I am using all eight sockets provided by the W5500.

  • HTTP port: The TCP port on which the HTTP server listens for incoming connections. I am using port 8080 instead of the default HTTP port 80.

NOTE: These network parameters are specific to my local network and may need to be changed depending on the network the device is connected to.

The net_configure() function uses the wiz_NetInfo_t structure provided by WIZnet ioLibrary to configure the network parameters.

static void net_configure(void) {
    struct wiz_NetInfo_t net = {
        .mac = NET_MAC,
        .ip = NET_IP,
        .sn = NET_SUBNET,
        .gw = NET_GATEWAY,
        .dns = NET_DNS,
        .dhcp = NETINFO_STATIC,
    };

    ctlnetwork(CN_SET_NETINFO, &net); // Set the network configuration

    // ... read back the network configuration and verify it
}

Once the network module is initialized and the sockets are listening, the web server can be accessed at http://192.168.29.70:8080 from the local network.

Network Initialization and Task
#

The network module is initialized from the startup_task() in main.c, after attempting to initialize the SD card and mount the file system. The net_init() function is responsible for three things:

  1. Initializing the W5500 using the porting layer.
  2. Applying the static network configuration.
  3. Creating the FreeRTOS network task.
int net_init(void) {
    int8_t st = w5500_init();

    if (st != 0) {
        // ... log initialization failure
        return -1;
    }

    net_configure();

    BaseType_t ok = xTaskCreate(net_task, "net_task", 2048, NULL, 2, NULL);

    if (ok != pdPASS) {
        // ... log task creation failure
        return -1;
    }

    return 0;
}

NOTE: The network task is created with a stack depth of 2048 words (8 KiB on the nRF52840) and a priority of 2, which is also the priority of the startup task.

Rather than creating a separate FreeRTOS task for each hardware socket, I use a single network task to manage all eight sockets. For this implementation, I am using a polling-based approach rather than an interrupt-driven approach for handling W5500 socket events. The network task periodically checks the state of each socket and takes the appropriate action without relying on the W5500’s interrupt pin (INTn).

The net_task() function is responsible for managing all eight hardware sockets provided by the W5500. It continuously polls the sockets and handles each socket based on its current state.

static void net_task(void* arg) {
    (void)arg;

    uint8_t last_st[HTTP_SOCK_COUNT];

    for (uint8_t i = 0; i < HTTP_SOCK_COUNT; i++) {
        last_st[i] = 0xFF;
    }

    for (;;) {
        // ... handle network recovery if requested

        for (uint8_t i = 0; i < HTTP_SOCK_COUNT; i++) {
            handle_http_sock(http_socks[i], &last_st[i]);
        }

        vTaskDelay(pdMS_TO_TICKS(5));
    }
}
  • The last_st array stores the previously observed state of each socket. Each element is initially set to 0xFF, which is not a valid W5500 socket state. This ensures that the initial observed state of each socket is logged during the first iteration, followed by subsequent observed state changes.
  • The handle_http_sock() function is called for each socket and is responsible for listening for incoming connections, receiving HTTP requests, sending responses, and closing connections. I will discuss this function in detail in the following sections.
  • After iterating through all eight sockets, the network task calls vTaskDelay(pdMS_TO_TICKS(5)) to avoid continuously polling the sockets and to give other FreeRTOS tasks an opportunity to execute.

NOTE: Although the W5500 can maintain multiple TCP connections simultaneously, the firmware handles the sockets sequentially within a single FreeRTOS task.

Managing W5500 Sockets
#

The W5500 provides eight independent hardware sockets that can be configured for network communication. Each socket has its own set of registers and dedicated TX and RX buffer space.

For the HTTP server, I have configured all eight sockets to operate in TCP server mode and listen on port 8080. This allows the W5500 to maintain multiple TCP connections without requiring the nRF52840 to implement the underlying TCP/IP stack.

Socket Lifecycle
#

Each socket goes through a series of states during its lifetime, from initialization and connection establishment to data transfer and connection termination.

The current state of a socket can be determined by reading its Socket Status Register (Sn_SR). The WIZnet ioLibrary provides the getSn_SR() function for reading this register.

The following table describes the relevant TCP socket states:

Socket StateValueDescription
SOCK_CLOSED0x00The socket is closed and available for use.
SOCK_INIT0x13The socket has been opened in TCP mode.
SOCK_LISTEN0x14The socket is waiting for an incoming connection.
SOCK_SYNRECV0x16A TCP connection is being established.
SOCK_ESTABLISHED0x17A TCP connection has been established.
SOCK_FIN_WAIT0x18The connection is being terminated.
SOCK_CLOSING0x1ABoth endpoints have initiated termination.
SOCK_TIME_WAIT0x1BWaiting before completing connection closure.
SOCK_CLOSE_WAIT0x1CThe remote endpoint has requested termination.
SOCK_LAST_ACK0x1DWaiting for the final acknowledgement.
Simplified TCP server socket lifecycle on the W5500
Simplified TCP server socket lifecycle on the W5500

NOTE: SOCK_ESTABLISHED is highlighted because this is the state in which the HTTP request is handled and the response is sent.

The W5500 handles the underlying TCP connection establishment, TCP acknowledgements, retransmissions, and connection termination in hardware. The firmware primarily monitors the socket states and issues the appropriate commands when required.

Handling Connections
#

The handle_http_sock() function is responsible for handling each socket based on its current state.

The function first reads the Sn_SR register and compares the returned state with the previously observed state of the socket.

static void handle_http_sock(uint8_t sock, uint8_t* last_st) {
    uint8_t st = getSn_SR(sock);

    if (st != *last_st) {
        *last_st = st;
        log_sock_st(sock, st);
    }

    // ... handle the current socket state
}

If the state has changed, the new state is stored and logged using log_sock_st(). This allows me to observe socket state transitions through the UARTE logger without repeatedly logging the same state.

The function then uses a switch statement to determine what action needs to be taken based on the current socket state.

switch (st) {

case SOCK_CLOSED: {
    int8_t r = socket(sock, Sn_MR_TCP, HTTP_PORT, 0);

    if (r != (int8_t)sock) {
        // ... log failure
        net_record_failure();
        break;
    }

    if (listen(sock) != SOCK_OK) {
        // ... log failure
        net_record_failure();
        close(sock);
        break;
    }

    net_record_success();

} break;

case SOCK_LISTEN:
    break;

case SOCK_ESTABLISHED:
    // ... receive and process the HTTP request
    break;

case SOCK_CLOSE_WAIT:
    disconnect(sock);
    break;

case SOCK_FIN_WAIT:
case SOCK_CLOSING:
case SOCK_TIME_WAIT:
case SOCK_LAST_ACK:
    break;

default:
    break;
}
  • SOCK_CLOSED: The firmware opens the socket in TCP mode using socket() and puts it into listening mode using listen().
  • SOCK_LISTEN: No action is required from the firmware. The W5500 waits for an incoming TCP connection.
  • SOCK_ESTABLISHED: The firmware receives the HTTP request, processes it, sends the response, and initiates connection termination. The request handling and response generation will be discussed in detail in the following sections.
  • SOCK_CLOSE_WAIT: The client has initiated connection termination. The firmware calls disconnect() to complete the process.
  • SOCK_FIN_WAIT, SOCK_CLOSING, SOCK_TIME_WAIT, and SOCK_LAST_ACK: No additional action is taken by the firmware in these states. The W5500 handles the remaining TCP connection termination process internally.

Once a socket returns to SOCK_CLOSED, it is opened again and put into listening mode during a subsequent iteration of the network task, making it available for another incoming connection.

When opening a socket or putting it into listening mode fails, the net_record_failure() function is called. If both operations succeed, net_record_success() is called instead.

static void net_set_recovery_requested(uint8_t requested) {
    net_recovery_requested = requested ? 1 : 0;
}

static void net_record_failure(void) {
    if (net_failure_count < UINT8_MAX) {
        net_failure_count++;
    }

    if (net_failure_count >= NET_RECOVERY_FAIL_THRESHOLD) {
        net_set_recovery_requested(1);
    }
}

static void net_record_success(void) {
    net_failure_count = 0;
}
  • net_record_failure(): Increments the network failure counter whenever a socket fails to open or enter listening mode.

    • The net_failure_count counter is shared across all eight sockets.
    • The counter is incremented only if it is less than UINT8_MAX (255) to prevent integer wraparound.
    • Once the counter reaches NET_RECOVERY_FAIL_THRESHOLD, which is set to 5, a network recovery request is raised.
  • net_set_recovery_requested(): Sets or clears the network recovery request flag.

    • Any non-zero value passed to this function sets the flag to 1.
    • Passing 0 clears the flag.
    • The flag is checked by net_task() before iterating through the sockets.
  • net_record_success(): Resets the network failure counter to zero whenever a socket is successfully opened and put into listening mode.

    • This prevents intermittent failures from accumulating over time and unnecessarily triggering network recovery.
    • Resetting the counter does not clear an already raised recovery request.

NOTE: These functions only track socket initialization failures and raise recovery requests. The actual network recovery mechanism will be discussed later in this article.

Handling HTTP Requests
#

Once a socket enters the SOCK_ESTABLISHED state, a TCP connection has been established between the client and the server. The next step is to receive the HTTP request, extract the requested path, and determine which resource the client is requesting.

Receiving and Parsing Requests
#

Before looking at the implementation, let’s consider a simple HTTP GET request:

GET /style.css HTTP/1.1
Host: 192.168.29.70:8080
Accept: text/css
Connection: close

An HTTP request consists of a request line, followed by the request headers, an empty line, and an optional message body.

The first line of the request contains:

  • Request method: GET - Indicates that the client is requesting a resource.
  • Request target: /style.css - Identifies the requested resource.
  • HTTP version: HTTP/1.1 - The HTTP protocol version used by the client.

Each line of the request line and headers is terminated by a carriage return (\r) followed by a line feed (\n), collectively referred to as CRLF. An empty line marks the end of the HTTP headers, resulting in the sequence \r\n\r\n.

Since TCP is a byte-stream protocol, there is no guarantee that the entire HTTP request will be received in a single recv() call. Therefore, I accumulate the received data in a buffer until the end of the HTTP headers is detected.

The receive buffer is defined in net.c:

static uint8_t rx_buf[SPI_MAX_XFER];

The following logic is executed inside the SOCK_ESTABLISHED case of the handle_http_sock() function:

TickType_t start_tick = xTaskGetTickCount();

size_t req_len = 0;
uint8_t req_fin = 0;

for (;;) {
    if (getSn_SR(sock) != SOCK_ESTABLISHED) {
        break;
    }

    uint16_t avail = getSn_RX_RSR(sock);

    if (avail == 0) {
        if ((xTaskGetTickCount() - start_tick) >= REQUEST_TIMEOUT_TICKS) {
            // ... log request timeout
            disconnect(sock);
            break;
        }

        vTaskDelay(1);
        continue;
    }

    if (req_len >= sizeof(rx_buf)) {
        disconnect(sock);
        break;
    }

    size_t remains = sizeof(rx_buf) - req_len;

    int32_t n = recv(sock, rx_buf + req_len, (uint16_t)remains);

    if (n <= 0) {
        break;
    }

    req_len += (size_t)n;

    if (req_len >= 4) {
        for (size_t i = 0; i <= req_len - 4; i++) {
            if (mem_cmp(&rx_buf[i],
                        (const uint8_t*)"\r\n\r\n", 4) == 0) {
                req_fin = 1;
                break;
            }
        }
    }

    if (req_fin) {
        break;
    }
}

NOTE: The mem_cmp() function is a simple byte-wise comparison function that returns 0 if the two buffers are equal.

  • Checking the socket state: Before attempting to receive data, the firmware checks whether the socket is still in the SOCK_ESTABLISHED state.
  • Checking for incoming data: The getSn_RX_RSR() function reads the Socket RX Received Size Register (Sn_RX_RSR), which indicates the number of bytes available in the socket’s RX buffer.
    • If no data is available and the timeout has not been reached, the task waits for one FreeRTOS tick before checking again.
    • If no data is available and the elapsed time since entering the receive loop reaches REQUEST_TIMEOUT_TICKS (1000 ms converted to FreeRTOS ticks), the connection is terminated.
  • Receiving data: The recv() function transfers data from the W5500’s socket RX buffer into rx_buf in the nRF52840’s RAM.
    • req_len keeps track of the total number of bytes received so far.
    • Newly received data is appended to the existing data in the buffer.
    • The number of bytes requested from recv() is limited by the remaining space in rx_buf to prevent buffer overflow.
  • Detecting the end of HTTP headers: After receiving data, the firmware searches the accumulated data for the \r\n\r\n (two consecutive CRLFs) sequence.
    • Once detected, req_fin is set to 1, and the receive loop is exited.
    • Searching the accumulated data also allows the sequence to be detected when it is split across multiple recv() calls.

After exiting the receive loop, the firmware checks whether the socket is still connected and whether the complete HTTP headers have been received.

if (getSn_SR(sock) != SOCK_ESTABLISHED) {
    break;
}

if (!req_fin) {
    disconnect(sock);
    break;
}

NOTE: The receive buffer is shared across all eight sockets since the network task handles requests sequentially.

Extracting the request path

For this version of the web server, I am only supporting HTTP GET requests. The firmware checks whether the received request begins with GET / before attempting to extract the requested path.

if (req_len >= 6 && mem_cmp(rx_buf, (const uint8_t*)"GET /", 5) == 0) {

    uint8_t f_name[req_len + 1];

    int f_len = extract_request_path(rx_buf, f_name, 4, req_len);

    f_name[f_len] = '\0';

    // ... validate the path and serve the requested file
}

The extract_request_path() function extracts the path from the request line.

static int extract_request_path(uint8_t inp[], uint8_t out[],
                                int ptr, int lim) {
    int i = ptr;

    while (i < lim && inp[i] != ' ' && inp[i] != '?' &&
           inp[i] != '\r' && inp[i] != '\n' && inp[i] != '\0') {

        out[i - ptr] = inp[i];
        i++;
    }

    return i - ptr;
}
  • The extraction starts at index 4, immediately after GET in the request line.
  • Characters are copied into the output buffer until a space, question mark, carriage return, line feed, null character, or the input buffer limit is encountered.
  • The function returns the number of characters extracted.
  • The caller appends a null character to terminate the extracted path.

Some examples of request lines and their extracted paths:

Request lineExtracted path
GET / HTTP/1.1/
GET /style.css HTTP/1.1/style.css
GET /images/logo.png HTTP/1.1/images/logo.png
GET /docs/ HTTP/1.1/docs/
GET /style.css?v=1 HTTP/1.1/style.css

Since the extraction stops at the ? character, any query parameters included in the request are ignored.

Request Path Validation
#

Before using the extracted path to access a file on the SD card, it is important to validate it. The client should not be able to request files outside the designated directory used for serving static files.

For this implementation, the static root directory is defined as:

static const uint8_t STATIC_ROOT[] = "0:/static";

The validate_http_path() function performs a series of checks on the extracted path.

static uint8_t validate_http_path(const uint8_t path[], int len) {
    if (path == NULL || len <= 0) {
        return 0;
    }

    // 0:/static + URL path + '\0'
    if ((sizeof(STATIC_ROOT) - 1) + (size_t)len + 1 > MAX_PATH_LEN) {
        return 0;
    }

    // Path must begin with /
    if (path[0] != '/') {
        return 0;
    }

    for (int i = 0; i < len; i++) {
        uint8_t c = path[i];

        // Reject control characters and non-printable ASCII
        if (c < 0x20 || c > 0x7E) {
            return 0;
        }

        // Reject Windows-style separators
        if (c == '\\') {
            return 0;
        }

        // Reject :
        if (c == ':') {
            return 0;
        }

        // Reject ..
        if (c == '.' && (i + 1) < len && path[i + 1] == '.') {
            return 0;
        }
    }

    return 1;
}

The following checks are performed:

  • Invalid or empty paths: Reject paths if the supplied pointer is NULL or the path length is less than or equal to zero.

  • Path length: Ensure that the complete file system path, including the static root directory and the terminating null character, fits within MAX_PATH_LEN (256 bytes).

  • Leading forward slash: Ensure that the requested path begins with /, since it will be appended to the static root directory.

  • Printable ASCII characters: Only allow characters within the ASCII range 0x20 to 0x7E. This rejects control characters and other non-printable characters.

  • Backslashes (\): Reject alternative directory separators that could otherwise be interpreted by FatFs.

  • Colons (:): Prevent the client from including a FatFs drive specifier in the requested path.

  • Consecutive dots (..): Reject paths containing two consecutive dots to prevent directory traversal attempts. For example, without this check, a request for /../config.txt could produce the following file system path:

    0:/static/../config.txt

    This could allow access to a file outside the static root directory.

The function returns 1 if the path passes all the checks and 0 otherwise.

If the path is invalid, the firmware sends an HTTP 400 Bad Request response and terminates the connection.

if (!validate_http_path(f_name, f_len)) {
    // ... log invalid path

    int32_t sr = net_send_all(sock, HTTP_400, sizeof(HTTP_400) - 1);

    if (sr <= 0) {
        close(sock);
        break;
    }

    disconnect(sock);
    break;
}

The HTTP_400 response is defined in net.c:

static const uint8_t HTTP_400[] = "HTTP/1.1 400 Bad Request\r\n"
                                 "Content-Type: text/html\r\n"
                                 "Connection: close\r\n"
                                 "\r\n"
                                 "<html><body><h1>400 Bad Request</h1></body></html>";

NOTE: This is a minimal HTTP request parser. It does not perform URL decoding or full HTTP header validation.

Once the request path has been extracted and validated, the next step is to map it to a file system path and serve the corresponding file using FatFs.

Serving Static Files
#

Once the requested path has been extracted and validated, the HTTP server maps it to a file system path, opens the corresponding file using FatFs, and transmits its contents to the client through the W5500.

Path Mapping and File Access
#

All the files served by the HTTP server are stored under the 0:/static directory on the SD card.

static const uint8_t STATIC_ROOT[] = "0:/static";
static const uint8_t STATIC_INDEX[] = "0:/static/INDEX.HTML";

The requested path is mapped to a file system path using the following rules:

  • If the requested path is /, it is mapped directly to STATIC_INDEX.
  • Otherwise, the requested path is appended to STATIC_ROOT.
  • If the requested path is not / but ends with /, index.html is appended to the resulting path.
  • The resulting path must fit within MAX_PATH_LEN (256 bytes), including the terminating null character.

Some examples of this path mapping:

Requested PathFile System Path
/0:/static/INDEX.HTML
/style.css0:/static/style.css
/images/logo.png0:/static/images/logo.png
/blog/0:/static/blog/index.html
/blog/post/0:/static/blog/post/index.html

NOTE: Mapping paths ending with / to index.html allows the server to serve directory-based static websites, such as those generated by Hugo.

Once the file system path has been constructed, the firmware attempts to open the file in read-only mode using the FatFs API.

FIL file = {0};

FRESULT fr = f_open(&file, (const char*)f_name_appended, FA_READ);

Depending on the value returned by f_open():

  • FR_OK: The file was successfully opened, and the firmware proceeds with HTTP response generation.
  • FR_NO_FILE or FR_NO_PATH: The requested resource does not exist, and an HTTP 404 Not Found response is sent to the client.
  • Any other error: The firmware marks the SD card as unavailable, raises an SD card recovery request, and terminates the connection.

The SD card recovery mechanism will be discussed later in this article.

HTTP Response Generation
#

Before transmitting the contents of the file, the firmware needs to generate the HTTP response headers and inform the client about the type of content being served.

The get_file_extension() function extracts the extension from the file path, which is then passed to the get_mime_type() function to determine the MIME type.

The following MIME types are supported by the HTTP server:

File ExtensionMIME Type
.html, .htmtext/html
.csstext/css
.jsapplication/javascript
.pngimage/png
.jpg, .jpegimage/jpeg
.svgimage/svg+xml
.icoimage/x-icon
.txttext/plain
Othersapplication/octet-stream

Both lowercase and uppercase variants of these extensions are supported, but mixed-case variants are not explicitly matched.

The build_http_headers() function constructs the response headers using the determined MIME type.

For example, when serving an HTML file, the response headers would look like:

HTTP/1.1 200 OK
Content-Type: text/html
Connection: close

The status line and each header line are terminated by \r\n, with an additional \r\n marking the end of the headers.

NOTE: The current implementation does not include a Content-Length header. The end of the response body is indicated by closing the TCP connection.

The generated response headers are stored in a 96-byte buffer and transmitted to the client before transmitting the file contents.

Chunked File Transfers
#

Loading an entire file into RAM before transmitting it would limit the size of the files that the HTTP server could serve. Instead, I read and transmit the file in smaller chunks using a fixed-size buffer.

uint8_t filedata[SPI_MAX_XFER] = {0};
UINT br = 0;

The firmware repeatedly reads data from the file using f_read() and transmits the received bytes using net_send_all().

for (;;) {
    // ... check processing timeout and SD card availability

    fr = f_read(&file, filedata, sizeof(filedata), &br);

    // ... handle file read errors

    if (br == 0) {
        break;
    }

    sr = net_send_all(sock, filedata, br);

    // ... handle transmission errors
}

f_close(&file);
  • f_read() reads up to sizeof(filedata) bytes from the file.
  • br contains the actual number of bytes read.
  • net_send_all() transmits those bytes to the client.
  • The same buffer is reused for each iteration.
  • A successful read returning zero bytes indicates that the end of the file has been reached.

The net_send_all() function handles cases where send() transmits fewer bytes than requested.

static int32_t net_send_all(uint8_t sock, const uint8_t* buf, size_t len) {
    size_t sent = 0;

    while (sent < len) {
        int32_t sr = send(sock, (uint8_t*)(buf + sent),
                          (uint16_t)(len - sent));

        if (sr <= 0) {
            return sr;
        }

        sent += (size_t)sr;
    }

    return (int32_t)sent;
}

The function continues calling send() until all the requested bytes have been transmitted or send() returns a non-positive value.

This approach allows the HTTP server to serve files larger than the available RAM without allocating memory proportional to the file size, subject to the request processing timeout.

Once the entire file has been successfully transmitted, the file is closed using f_close() and the TCP connection is terminated using disconnect().

NOTE: Reading and transmitting files in chunks should not be confused with HTTP chunked transfer encoding, which is not implemented in this version.

Error Handling and Recovery
#

Since the HTTP server relies on two external peripherals, the SD card and the W5500, failures in either of these peripherals can affect the operation of the server. I have implemented basic error handling and recovery mechanisms to allow the firmware to recover from certain failures without requiring a manual reset of the nRF52840.

Errors and Timeouts
#

The following timeout values are defined in net.h:

#define REQUEST_TIMEOUT_TICKS         pdMS_TO_TICKS(1000)
#define REQUEST_PROCESS_TIMEOUT_TICKS pdMS_TO_TICKS(5000)
  • Request timeout (1 second): If no RX data is available and the elapsed time since entering the request reception loop reaches the configured timeout, the firmware initiates connection termination.
  • Request processing timeout (5 seconds): The elapsed time since the beginning of request processing is checked during each iteration of the file transfer loop. If the timeout is reached, the transfer is aborted, the file is closed, and the socket is closed.

Apart from these timeouts, the firmware also handles the following errors:

ErrorAction
Invalid request pathSend 400 Bad Request
File or path not foundSend 404 Not Found
Unsupported HTTP requestSend 404 Not Found
HTTP response transmission failureClose the socket
SD card unavailableRequest SD card recovery
File open failure (other than a missing file or path) or any file read failureMark SD card as unavailable and request recovery
Repeated socket initialization failuresRequest network recovery

NOTE: The processing timeout is checked between file transfer iterations. It does not interrupt an ongoing blocking operation.

SD Card Recovery
#

The SD card recovery mechanism is implemented in main.c and is handled by the startup_task().

During startup, the firmware attempts to initialize the SD card multiple times, with a delay of one second between failed attempts. Once the SD card has been successfully initialized, the firmware attempts to mount the file system using FatFs.

Even if SD card initialization or file system mounting fails, the firmware continues with network initialization.

During normal operation, if a file access operation fails (other than a missing file or path when opening a file), the network task can mark the SD card as unavailable and raise a recovery request.

sd_set_available(0);
sd_set_recovery_requested(1);

The startup_task() checks for SD card recovery requests and calls sd_recover() when one is raised.

static int sd_recover(void) {
    sd_set_available(0);

    // Forget old FatFs mount state.
    f_mount(NULL, "0:", 0);

    // ... log recovery started

    sd_status_t status = sd_init();

    if (status != SD_OK) {
        // ... log initialization failure
        return -1;
    }

    FRESULT fr = f_mount(&fs, "0:", 1);

    if (fr != FR_OK) {
        // ... log mount failure
        return -1;
    }

    sd_set_available(1);

    // ... log recovery completed

    return 0;
}

The recovery process consists of the following steps:

  1. Mark the SD card as unavailable.
  2. Unregister the existing FatFs file system object.
  3. Reinitialize the SD card.
  4. Mount the file system again.
  5. Mark the SD card as available if both initialization and mounting succeed.

If recovery fails, the startup task retries after a delay of one second, for a total of up to the number of attempts defined by SD_INIT_RECOVERY_MAX_ATTEMPTS (10).

Once these attempts are exhausted, the firmware stops the current recovery attempt. A subsequent HTTP request can raise another recovery request if the SD card is still unavailable.

Network Recovery
#

As discussed earlier in the socket management section, repeated failures while opening sockets or putting them into listening mode cause a network recovery request to be raised.

Unlike SD card recovery, network recovery is handled within the network task itself.

The net_recover() function reinitializes the W5500 and reapplies the static network configuration.

static int net_recover(void) {
    // ... log recovery started

    if (w5500_init() != 0) {
        // ... log initialization failure
        return -1;
    }

    net_configure();

    // ... log recovery completed

    return 0;
}

Before iterating through the sockets, net_task() checks whether a network recovery request has been raised.

if (net_is_recovery_requested()) {
    net_set_recovery_requested(0);

    // ... log recovery started

    if (net_recover() == 0) {
        net_failure_count = 0;

        for (uint8_t i = 0; i < HTTP_SOCK_COUNT; i++) {
            last_st[i] = 0xFF;
        }
    } else {
        // ... log recovery failure
    }
}
  • The recovery request flag is cleared before attempting recovery.
  • If recovery succeeds, the network failure counter is reset to zero.
  • The previously recorded socket states are reset to 0xFF, allowing the initial states of the reinitialized sockets to be logged again.
  • If recovery fails, the failure is logged.

The network task then resumes normal socket management. Closed sockets are opened again and put into listening mode.

NOTE: Network recovery is currently triggered by socket creation and listening failures, not by every network communication failure.

Limitations
#

The current implementation (v1.0.0) has the following limitations:

  • Static content only: The server serves files stored on the SD card.
  • GET requests only: Other HTTP request methods are not supported.
  • Plain HTTP: HTTPS and TLS are not implemented.
  • Static network configuration: DHCP is not implemented.
  • Sequential request handling: Although the W5500 provides eight hardware sockets, requests are processed sequentially within a single FreeRTOS task.
  • No persistent HTTP connections: The TCP connection is closed after serving each request.
  • Minimal HTTP parsing: Full HTTP header validation and URL decoding are not implemented.

Conclusion
#

With the implementation of the HTTP server, all the individual components developed throughout this series have now been brought together into a working web server.

The nRF52840 can now serve static websites stored on an SD card over Ethernet using the W5500, with both peripherals sharing a single SPI bus managed using a FreeRTOS mutex.

While this is by no means a full-featured web server, it provides a solid foundation for future versions of this project, if I decide to continue working on it.

More importantly, this project has been a valuable learning experience for me. It has helped me gain a better understanding of bare-metal programming, peripheral driver development, EasyDMA, real-time operating systems, shared resource management, SD card communication, file systems, networking, and the HTTP protocol. It has also helped me understand how these individual components can be integrated to build a functional embedded system with limited hardware resources.