Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
source/main.cpp
- Committer:
- morgandu
- Date:
- 2020-06-29
- Revision:
- 2:ff1a293c4df3
- Parent:
- 0:41f820ea137a
File content as of revision 2:ff1a293c4df3:
#include "mbed.h"
#include "http_server.h"
#include "http_response_builder.h"
#define USE_FIXED_IP 1 // 1 for fixed IP, 0 for DHCP
DigitalOut led(LED1);
// Requests come in here
void request_handler(ParsedHttpRequest* request, TCPSocket* socket) {
printf("Request came in: %s %s\n", http_method_str(request->get_method()), request->get_url().c_str());
if (request->get_method() == HTTP_GET && request->get_url() == "/") {
HttpResponseBuilder builder(200);
builder.set_header("Content-Type", "text/html; charset=utf-8");
char response[] = "<html><head><title>Hello from mbed</title></head>"
"<body>"
"<h1>mbed webserver</h1>"
"<button id=\"toggle\">Toggle LED</button>"
"<script>document.querySelector('#toggle').onclick = function() {"
"var x = new XMLHttpRequest(); x.open('POST', '/toggle'); x.send();"
"}</script>"
"</body></html>";
builder.send(socket, response, sizeof(response) - 1);
}
else if (request->get_method() == HTTP_POST && request->get_url() == "/toggle") {
printf("toggle LED called\n");
led = !led;
HttpResponseBuilder builder(200);
builder.send(socket, NULL, 0);
}
else {
HttpResponseBuilder builder(404);
builder.send(socket, NULL, 0);
}
}
int main() {
// Connect to the network (see mbed_app.json for the connectivity method used)
NetworkInterface *network = NetworkInterface::get_default_instance();
if (!network) {
printf("Cannot connect to the network, see serial output\n");
return 1;
}
#if USE_FIXED_IP
// This fixed IP address is convenient to test with Windows PC
SocketAddress ip_addr("169.254.108.2");
SocketAddress ip_mask("255.255.0.0");
SocketAddress ip_gwaddr("169.254.108.1");
network->set_network(ip_addr, ip_mask, ip_gwaddr);
#endif
network->connect();
HttpServer server(network);
nsapi_error_t res = server.start(80, &request_handler);
if (res == NSAPI_ERROR_OK) {
SocketAddress ip_addr;
network->get_ip_address(&ip_addr);
printf("Server is listening at http://%s\n", ip_addr.get_ip_address());
}
else {
printf("Server could not be started... %d\n", res);
}
while(1) ThisThread::sleep_for(1000000);
}