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.
main.cpp
00001 #include "mbed.h" 00002 #include "easy-connect.h" 00003 #include "http_server.h" 00004 #include "http_response_builder.h" 00005 00006 00007 00008 Serial pc(USBTX,USBRX,9600); 00009 DigitalOut led(LED1); 00010 00011 // Requests come in here 00012 00013 void request_handler(ParsedHttpRequest* request, TCPSocket* socket) { 00014 00015 pc.printf("Request came in: %s %s\n", http_method_str(request->get_method()), request->get_url().c_str()); 00016 00017 if (request->get_method() == HTTP_GET && request->get_url() == "/") { 00018 HttpResponseBuilder builder(200); 00019 builder.set_header("Content-Type", "text/html; charset=utf-8"); 00020 00021 char response[] = "<html><head><title>Hello from mbed</title></head>" 00022 "<body>" 00023 "<h1>mbed webserver</h1>" 00024 "<button id=\"toggle\">Toggle LED</button>" 00025 "<script>document.querySelector('#toggle').onclick = function() {" 00026 "var x = new XMLHttpRequest(); x.open('POST', '/toggle'); x.send();" 00027 "}</script>" 00028 "</body></html>"; 00029 00030 builder.send(socket, response, sizeof(response) - 1); 00031 00032 } 00033 else if (request->get_method() == HTTP_POST && request->get_url() == "/toggle") { 00034 pc.printf("toggle LED called\n"); 00035 led = !led; 00036 00037 HttpResponseBuilder builder(200); 00038 builder.send(socket, NULL, 0); 00039 } 00040 else { 00041 HttpResponseBuilder builder(404); 00042 builder.send(socket, NULL, 0); 00043 } 00044 } 00045 00046 int main() { 00047 00048 lcd_printf("Reem"); 00049 // Connect to the network (see mbed_app.json for the connectivity method used) 00050 NetworkInterface* network = easy_connect(true); 00051 if (!network) { 00052 pc.printf("Cannot connect to the network, see serial output\n"); 00053 return 1; 00054 } 00055 00056 HttpServer server(network); 00057 nsapi_error_t res = server.start(8080, &request_handler); 00058 00059 if (res == NSAPI_ERROR_OK) { 00060 pc.printf("Server is listening at http://%s:8080\n", network->get_ip_address()); 00061 } 00062 else { 00063 pc.printf("Server could not be started... %d\n", res); 00064 } 00065 00066 00067 00068 wait(osWaitForever); 00069 00070 00071 }
Generated on Wed Jul 13 2022 01:16:06 by
