Simple Webserver example for wiznet W5500 (SPI Ethernet chip) mbed OS 5 - HTTP 1.1 and multi-threaded
Dependencies: W5500Interface easy-connect mbed-http
Fork of http-webserver-example by
mbed-os-example-http-server
This application demonstrates how to run an HTTP server on an mbed OS 5 device & WIZnet W5500 Ethernet components.
Request parsing is done through [nodejs/http-parser](https://github.com/nodejs/http-parser).
To build
- Open ``mbed_app.json`` and change the `network-interface` option to your connectivity method ([more info](https://github.com/ARMmbed/easy-connect)).
- Build the project in the online compiler or using mbed CLI.
- Flash the project to your development board.
- Attach a serial monitor to your board to see the debug messages.
Tested on
- NUCLEO_F411RE with W5500 Ethernet shield.
- For W5500, you need the following libraries.
Import libraryW5500Interface
W5500 driver for mbed OS 5
Import libraryeasy-connect
Modified version of easy-connect for W5500 Ethernet components
But every networking stack that supports the [mbed OS 5 NetworkInterface API](https://docs.mbed.com/docs/mbed-os-api-reference/en/latest/APIs/communication/network_sockets/) should work.
Test Result
Revision 0:41f820ea137a, committed 2017-07-31
- Comitter:
- Jan Jongboom
- Date:
- Mon Jul 31 15:41:22 2017 +0200
- Child:
- 1:fe3df398bdf5
- Commit message:
- Initial release
Changed in this revision
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.gitignore Mon Jul 31 15:41:22 2017 +0200 @@ -0,0 +1,4 @@ +.mbed +BUILD/ +mbed_settings.* +
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/.hgignore Mon Jul 31 15:41:22 2017 +0200 @@ -0,0 +1,8 @@ +syntax: glob +.mbed +BUILD/ +mbed_settings.* +mbed-os/ +easy-connect/ +mbed-http/ +.git/
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/LICENSE Mon Jul 31 15:41:22 2017 +0200 @@ -0,0 +1,191 @@ +Apache License +Version 2.0, January 2004 +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and +distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright +owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities +that control, are controlled by, or are under common control with that entity. +For the purposes of this definition, "control" means (i) the power, direct or +indirect, to cause the direction or management of such entity, whether by +contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the +outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising +permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including +but not limited to software source code, documentation source, and configuration +files. + +"Object" form shall mean any form resulting from mechanical transformation or +translation of a Source form, including but not limited to compiled object code, +generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made +available under the License, as indicated by a copyright notice that is included +in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that +is based on (or derived from) the Work and for which the editorial revisions, +annotations, elaborations, or other modifications represent, as a whole, an +original work of authorship. For the purposes of this License, Derivative Works +shall not include works that remain separable from, or merely link (or bind by +name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version +of the Work and any modifications or additions to that Work or Derivative Works +thereof, that is intentionally submitted to Licensor for inclusion in the Work +by the copyright owner or by an individual or Legal Entity authorized to submit +on behalf of the copyright owner. For the purposes of this definition, +"submitted" means any form of electronic, verbal, or written communication sent +to the Licensor or its representatives, including but not limited to +communication on electronic mailing lists, source code control systems, and +issue tracking systems that are managed by, or on behalf of, the Licensor for +the purpose of discussing and improving the Work, but excluding communication +that is conspicuously marked or otherwise designated in writing by the copyright +owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf +of whom a Contribution has been received by Licensor and subsequently +incorporated within the Work. + +2. Grant of Copyright License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable copyright license to reproduce, prepare Derivative Works of, +publicly display, publicly perform, sublicense, and distribute the Work and such +Derivative Works in Source or Object form. + +3. Grant of Patent License. + +Subject to the terms and conditions of this License, each Contributor hereby +grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, +irrevocable (except as stated in this section) patent license to make, have +made, use, offer to sell, sell, import, and otherwise transfer the Work, where +such license applies only to those patent claims licensable by such Contributor +that are necessarily infringed by their Contribution(s) alone or by combination +of their Contribution(s) with the Work to which such Contribution(s) was +submitted. If You institute patent litigation against any entity (including a +cross-claim or counterclaim in a lawsuit) alleging that the Work or a +Contribution incorporated within the Work constitutes direct or contributory +patent infringement, then any patent licenses granted to You under this License +for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. + +You may reproduce and distribute copies of the Work or Derivative Works thereof +in any medium, with or without modifications, and in Source or Object form, +provided that You meet the following conditions: + +You must give any other recipients of the Work or Derivative Works a copy of +this License; and +You must cause any modified files to carry prominent notices stating that You +changed the files; and +You must retain, in the Source form of any Derivative Works that You distribute, +all copyright, patent, trademark, and attribution notices from the Source form +of the Work, excluding those notices that do not pertain to any part of the +Derivative Works; and +If the Work includes a "NOTICE" text file as part of its distribution, then any +Derivative Works that You distribute must include a readable copy of the +attribution notices contained within such NOTICE file, excluding those notices +that do not pertain to any part of the Derivative Works, in at least one of the +following places: within a NOTICE text file distributed as part of the +Derivative Works; within the Source form or documentation, if provided along +with the Derivative Works; or, within a display generated by the Derivative +Works, if and wherever such third-party notices normally appear. The contents of +the NOTICE file are for informational purposes only and do not modify the +License. You may add Your own attribution notices within Derivative Works that +You distribute, alongside or as an addendum to the NOTICE text from the Work, +provided that such additional attribution notices cannot be construed as +modifying the License. +You may add Your own copyright statement to Your modifications and may provide +additional or different license terms and conditions for use, reproduction, or +distribution of Your modifications, or for any such Derivative Works as a whole, +provided Your use, reproduction, and distribution of the Work otherwise complies +with the conditions stated in this License. + +5. Submission of Contributions. + +Unless You explicitly state otherwise, any Contribution intentionally submitted +for inclusion in the Work by You to the Licensor shall be under the terms and +conditions of this License, without any additional terms or conditions. +Notwithstanding the above, nothing herein shall supersede or modify the terms of +any separate license agreement you may have executed with Licensor regarding +such Contributions. + +6. Trademarks. + +This License does not grant permission to use the trade names, trademarks, +service marks, or product names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. + +Unless required by applicable law or agreed to in writing, Licensor provides the +Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, +including, without limitation, any warranties or conditions of TITLE, +NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are +solely responsible for determining the appropriateness of using or +redistributing the Work and assume any risks associated with Your exercise of +permissions under this License. + +8. Limitation of Liability. + +In no event and under no legal theory, whether in tort (including negligence), +contract, or otherwise, unless required by applicable law (such as deliberate +and grossly negligent acts) or agreed to in writing, shall any Contributor be +liable to You for damages, including any direct, indirect, special, incidental, +or consequential damages of any character arising as a result of this License or +out of the use or inability to use the Work (including but not limited to +damages for loss of goodwill, work stoppage, computer failure or malfunction, or +any and all other commercial damages or losses), even if such Contributor has +been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. + +While redistributing the Work or Derivative Works thereof, You may choose to +offer, and charge a fee for, acceptance of support, warranty, indemnity, or +other liability obligations and/or rights consistent with this License. However, +in accepting such obligations, You may act only on Your own behalf and on Your +sole responsibility, not on behalf of any other Contributor, and only if You +agree to indemnify, defend, and hold each Contributor harmless for any liability +incurred by, or claims asserted against, such Contributor by reason of your +accepting any such warranty or additional liability. + +--- + +http_parser.c is based on src/http/ngx_http_parse.c from NGINX copyright +Igor Sysoev. + +Additional changes are licensed under the same terms as NGINX and +copyright Joyent, Inc. and other Node contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/README.md Mon Jul 31 15:41:22 2017 +0200 @@ -0,0 +1,20 @@ +# mbed-os-example-http-server + +This application demonstrates how to run an HTTP server on an mbed OS 5 device. + +Request parsing is done through [nodejs/http-parser](https://github.com/nodejs/http-parser). + +## To build + +1. Open ``mbed_app.json`` and change the `network-interface` option to your connectivity method ([more info](https://github.com/ARMmbed/easy-connect)). +2. Build the project in the online compiler or using mbed CLI. +3. Flash the project to your development board. +4. Attach a serial monitor to your board to see the debug messages. + +## Tested on + +* K64F with Ethernet. +* NUCLEO_F411RE with ESP8266. + * For ESP8266, you need [this patch](https://github.com/ARMmbed/esp8266-driver/pull/41). + +But every networking stack that supports the [mbed OS 5 NetworkInterface API](https://docs.mbed.com/docs/mbed-os-api-reference/en/latest/APIs/communication/network_sockets/) should work.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/easy-connect.lib Mon Jul 31 15:41:22 2017 +0200 @@ -0,0 +1,1 @@ +https://github.com/ARMmbed/easy-connect/#e7629734c9846617dd6a55e181a851d7ae7a62b9
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-http.lib Mon Jul 31 15:41:22 2017 +0200 @@ -0,0 +1,1 @@ +https://developer.mbed.org/teams/sandbox/code/mbed-http/#6e0025e01b98
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-os.lib Mon Jul 31 15:41:22 2017 +0200 @@ -0,0 +1,1 @@ +https://github.com/ARMmbed/mbed-os/#ed9d1da9dd0c43907ba40cba5ebd9f2c6da3dc07
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/mbed_app.json Mon Jul 31 15:41:22 2017 +0200
@@ -0,0 +1,50 @@
+{
+ "config": {
+ "network-interface": {
+ "help": "options are ETHERNET, WIFI_ESP8266, WIFI_ODIN, WIFI_RTW, MESH_LOWPAN_ND, MESH_THREAD",
+ "value": "WIFI_ESP8266"
+ },
+ "mesh_radio_type": {
+ "help": "options are ATMEL, MCR20, SPIRIT1, EFR32",
+ "value": "ATMEL"
+ },
+ "esp8266-tx": {
+ "help": "Pin used as TX (connects to ESP8266 RX)",
+ "value": "D1"
+ },
+ "esp8266-rx": {
+ "help": "Pin used as RX (connects to ESP8266 TX)",
+ "value": "D0"
+ },
+ "esp8266-debug": {
+ "value": true
+ },
+ "wifi-ssid": {
+ "value": "\"SSID\""
+ },
+ "wifi-password": {
+ "value": "\"Password\""
+ }
+ },
+ "target_overrides": {
+ "*": {
+ "target.features_add": ["NANOSTACK", "LOWPAN_ROUTER", "COMMON_PAL"],
+ "mbed-mesh-api.6lowpan-nd-channel-page": 0,
+ "mbed-mesh-api.6lowpan-nd-channel": 12,
+ "mbed-trace.enable": 0,
+ "mbed-http.http-buffer-size": 2048
+ },
+ "HEXIWEAR": {
+ "esp8266-tx": "PTD3",
+ "esp8266-rx": "PTD2"
+ },
+ "NUCLEO_F401RE": {
+ "esp8266-tx": "D8",
+ "esp8266-rx": "D2"
+ },
+ "NUCLEO_F411RE": {
+ "esp8266-tx": "D8",
+ "esp8266-rx": "D2"
+ }
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/profiles/debug-c++11.json Mon Jul 31 15:41:22 2017 +0200
@@ -0,0 +1,49 @@
+{
+ "GCC_ARM": {
+ "common": ["-c", "-Wall", "-Wextra",
+ "-Wno-unused-parameter", "-Wno-missing-field-initializers",
+ "-fmessage-length=0", "-fno-exceptions", "-fno-builtin",
+ "-ffunction-sections", "-fdata-sections", "-funsigned-char",
+ "-MMD", "-fno-delete-null-pointer-checks",
+ "-fomit-frame-pointer", "-O0", "-g3", "-DMBED_DEBUG",
+ "-DMBED_TRAP_ERRORS_ENABLED=1"],
+ "asm": ["-x", "assembler-with-cpp"],
+ "c": ["-std=gnu99"],
+ "cxx": ["-std=gnu++11", "-fno-rtti", "-Wvla"],
+ "ld": ["-Wl,--gc-sections", "-Wl,--wrap,main", "-Wl,--wrap,_malloc_r",
+ "-Wl,--wrap,_free_r", "-Wl,--wrap,_realloc_r", "-Wl,--wrap,_memalign_r",
+ "-Wl,--wrap,_calloc_r", "-Wl,--wrap,exit", "-Wl,--wrap,atexit",
+ "-Wl,-n"]
+ },
+ "ARM": {
+ "common": ["-c", "--gnu", "-Otime", "--split_sections",
+ "--apcs=interwork", "--brief_diagnostics", "--restrict",
+ "--multibyte_chars", "-O0", "-g", "-DMBED_DEBUG",
+ "-DMBED_TRAP_ERRORS_ENABLED=1"],
+ "asm": [],
+ "c": ["--md", "--no_depend_system_headers", "--c99", "-D__ASSERT_MSG"],
+ "cxx": ["--cpp", "--no_rtti", "--no_vla"],
+ "ld": []
+ },
+ "uARM": {
+ "common": ["-c", "--gnu", "-Otime", "--split_sections",
+ "--apcs=interwork", "--brief_diagnostics", "--restrict",
+ "--multibyte_chars", "-O0", "-D__MICROLIB", "-g",
+ "--library_type=microlib", "-DMBED_RTOS_SINGLE_THREAD", "-DMBED_DEBUG",
+ "-DMBED_TRAP_ERRORS_ENABLED=1"],
+ "asm": [],
+ "c": ["--md", "--no_depend_system_headers", "--c99", "-D__ASSERT_MSG"],
+ "cxx": ["--cpp", "--no_rtti", "--no_vla"],
+ "ld": ["--library_type=microlib"]
+ },
+ "IAR": {
+ "common": [
+ "--no_wrap_diagnostics", "-e",
+ "--diag_suppress=Pa050,Pa084,Pa093,Pa082", "-On", "-r", "-DMBED_DEBUG",
+ "-DMBED_TRAP_ERRORS_ENABLED=1"],
+ "asm": [],
+ "c": ["--vla"],
+ "cxx": ["--guard_calls", "--no_static_destruction"],
+ "ld": ["--skip_dynamic_initialization", "--threaded_lib"]
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/profiles/develop-c++11.json Mon Jul 31 15:41:22 2017 +0200
@@ -0,0 +1,45 @@
+{
+ "GCC_ARM": {
+ "common": ["-c", "-Wall", "-Wextra",
+ "-Wno-unused-parameter", "-Wno-missing-field-initializers",
+ "-fmessage-length=0", "-fno-exceptions", "-fno-builtin",
+ "-ffunction-sections", "-fdata-sections", "-funsigned-char",
+ "-MMD", "-fno-delete-null-pointer-checks",
+ "-fomit-frame-pointer", "-Os"],
+ "asm": ["-x", "assembler-with-cpp"],
+ "c": ["-std=gnu99"],
+ "cxx": ["-std=gnu++11", "-fno-rtti", "-Wvla"],
+ "ld": ["-Wl,--gc-sections", "-Wl,--wrap,main", "-Wl,--wrap,_malloc_r",
+ "-Wl,--wrap,_free_r", "-Wl,--wrap,_realloc_r", "-Wl,--wrap,_memalign_r",
+ "-Wl,--wrap,_calloc_r", "-Wl,--wrap,exit", "-Wl,--wrap,atexit",
+ "-Wl,-n"]
+ },
+ "ARM": {
+ "common": ["-c", "--gnu", "-Otime", "--split_sections",
+ "--apcs=interwork", "--brief_diagnostics", "--restrict",
+ "--multibyte_chars", "-O3"],
+ "asm": [],
+ "c": ["--md", "--no_depend_system_headers", "--c99", "-D__ASSERT_MSG"],
+ "cxx": ["--cpp", "--no_rtti", "--no_vla"],
+ "ld": []
+ },
+ "uARM": {
+ "common": ["-c", "--gnu", "-Otime", "--split_sections",
+ "--apcs=interwork", "--brief_diagnostics", "--restrict",
+ "--multibyte_chars", "-O3", "-D__MICROLIB",
+ "--library_type=microlib", "-DMBED_RTOS_SINGLE_THREAD"],
+ "asm": [],
+ "c": ["--md", "--no_depend_system_headers", "--c99", "-D__ASSERT_MSG"],
+ "cxx": ["--cpp", "--no_rtti", "--no_vla"],
+ "ld": ["--library_type=microlib"]
+ },
+ "IAR": {
+ "common": [
+ "--no_wrap_diagnostics", "-e",
+ "--diag_suppress=Pa050,Pa084,Pa093,Pa082", "-Oh"],
+ "asm": [],
+ "c": ["--vla"],
+ "cxx": ["--guard_calls", "--no_static_destruction"],
+ "ld": ["--skip_dynamic_initialization", "--threaded_lib"]
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/profiles/release-c++11.json Mon Jul 31 15:41:22 2017 +0200
@@ -0,0 +1,45 @@
+{
+ "GCC_ARM": {
+ "common": ["-c", "-Wall", "-Wextra",
+ "-Wno-unused-parameter", "-Wno-missing-field-initializers",
+ "-fmessage-length=0", "-fno-exceptions", "-fno-builtin",
+ "-ffunction-sections", "-fdata-sections", "-funsigned-char",
+ "-MMD", "-fno-delete-null-pointer-checks",
+ "-fomit-frame-pointer", "-Os", "-DNDEBUG"],
+ "asm": ["-x", "assembler-with-cpp"],
+ "c": ["-std=gnu99"],
+ "cxx": ["-std=gnu++11", "-fno-rtti", "-Wvla"],
+ "ld": ["-Wl,--gc-sections", "-Wl,--wrap,main", "-Wl,--wrap,_malloc_r",
+ "-Wl,--wrap,_free_r", "-Wl,--wrap,_realloc_r", "-Wl,--wrap,_memalign_r",
+ "-Wl,--wrap,_calloc_r", "-Wl,--wrap,exit", "-Wl,--wrap,atexit",
+ "-Wl,-n"]
+ },
+ "ARM": {
+ "common": ["-c", "--gnu", "-Ospace", "--split_sections",
+ "--apcs=interwork", "--brief_diagnostics", "--restrict",
+ "--multibyte_chars", "-O3", "-DNDEBUG"],
+ "asm": [],
+ "c": ["--md", "--no_depend_system_headers", "--c99", "-D__ASSERT_MSG"],
+ "cxx": ["--cpp", "--no_rtti", "--no_vla"],
+ "ld": []
+ },
+ "uARM": {
+ "common": ["-c", "--gnu", "-Ospace", "--split_sections",
+ "--apcs=interwork", "--brief_diagnostics", "--restrict",
+ "--multibyte_chars", "-O3", "-D__MICROLIB",
+ "--library_type=microlib", "-DMBED_RTOS_SINGLE_THREAD", "-DNDEBUG"],
+ "asm": [],
+ "c": ["--md", "--no_depend_system_headers", "--c99", "-D__ASSERT_MSG"],
+ "cxx": ["--cpp", "--no_rtti", "--no_vla"],
+ "ld": ["--library_type=microlib"]
+ },
+ "IAR": {
+ "common": [
+ "--no_wrap_diagnostics", "-e",
+ "--diag_suppress=Pa050,Pa084,Pa093,Pa082", "-Ohz", "-DNDEBUG"],
+ "asm": [],
+ "c": ["--vla"],
+ "cxx": ["--guard_calls", "--no_static_destruction"],
+ "ld": ["--skip_dynamic_initialization", "--threaded_lib"]
+ }
+}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/source/http_response_builder.h Mon Jul 31 15:41:22 2017 +0200
@@ -0,0 +1,181 @@
+/*
+ * PackageLicenseDeclared: Apache-2.0
+ * Copyright (c) 2017 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _MBED_HTTP_RESPONSE_BUILDER_
+#define _MBED_HTTP_RESPONSE_BUILDER_
+
+#include <string>
+#include <map>
+#include "http_parser.h"
+#include "http_parsed_url.h"
+
+static const char* get_http_status_string(uint16_t status_code) {
+ switch (status_code) {
+ case 100: return "Continue";
+ case 101: return "Switching Protocols";
+ case 102: return "Processing";
+ case 200: return "OK";
+ case 201: return "Created";
+ case 202: return "Accepted";
+ case 203: return "Non-Authoritative Information";
+ case 204: return "No Content";
+ case 205: return "Reset Content";
+ case 206: return "Partial Content";
+ case 207: return "Multi-Status";
+ case 208: return "Already Reported";
+ case 226: return "IM Used";
+ case 300: return "Multiple Choices";
+ case 301: return "Moved Permanently";
+ case 302: return "Found";
+ case 303: return "See Other";
+ case 304: return "Not Modified";
+ case 305: return "Use Proxy";
+ case 307: return "Temporary Redirect";
+ case 308: return "Permanent Redirect";
+ case 400: return "Bad Request";
+ case 401: return "Unauthorized";
+ case 402: return "Payment Required";
+ case 403: return "Forbidden";
+ case 404: return "Not Found";
+ case 405: return "Method Not Allowed";
+ case 406: return "Not Acceptable";
+ case 407: return "Proxy Authentication Required";
+ case 408: return "Request Timeout";
+ case 409: return "Conflict";
+ case 410: return "Gone";
+ case 411: return "Length Required";
+ case 412: return "Precondition Failed";
+ case 413: return "Payload Too Large";
+ case 414: return "URI Too Long";
+ case 415: return "Unsupported Media Type";
+ case 416: return "Range Not Satisfiable";
+ case 417: return "Expectation Failed";
+ case 421: return "Misdirected Request";
+ case 422: return "Unprocessable Entity";
+ case 423: return "Locked";
+ case 424: return "Failed Dependency";
+ case 426: return "Upgrade Required";
+ case 428: return "Precondition Required";
+ case 429: return "Too Many Requests";
+ case 431: return "Request Header Fields Too Large";
+ case 451: return "Unavailable For Legal Reasons";
+ case 500: return "Internal Server Error";
+ case 501: return "Not Implemented";
+ case 502: return "Bad Gateway";
+ case 503: return "Service Unavailable";
+ case 504: return "Gateway Timeout";
+ case 505: return "HTTP Version Not Supported";
+ case 506: return "Variant Also Negotiates";
+ case 507: return "Insufficient Storage";
+ case 508: return "Loop Detected";
+ case 510: return "Not Extended";
+ case 511: return "Network Authentication Required";
+ default : return "Unknown";
+ }
+}
+
+class HttpResponseBuilder {
+public:
+ HttpResponseBuilder(uint16_t a_status_code)
+ : status_code(a_status_code), status_message(get_http_status_string(a_status_code))
+ {
+ }
+
+ /**
+ * Set a header for the request
+ * If the key already exists, it will be overwritten...
+ */
+ void set_header(string key, string value) {
+ map<string, string>::iterator it = headers.find(key);
+
+ if (it != headers.end()) {
+ it->second = value;
+ }
+ else {
+ headers.insert(headers.end(), pair<string, string>(key, value));
+ }
+ }
+
+ char* build(const void* body, size_t body_size, size_t* size) {
+ char buffer[10];
+ snprintf(buffer, sizeof(buffer), "%d", body_size);
+ set_header("Content-Length", string(buffer));
+
+ char status_code_buffer[5];
+ snprintf(status_code_buffer, sizeof(status_code_buffer), "%d", status_code /* max 5 digits */);
+
+ *size = 0;
+
+ // first line is HTTP/1.1 200 OK\r\n
+ *size += 8 + 1 + strlen(status_code_buffer) + 1 + strlen(status_message) + 2;
+
+ // after that we'll do the headers
+ typedef map<string, string>::iterator it_type;
+ for(it_type it = headers.begin(); it != headers.end(); it++) {
+ // line is KEY: VALUE\r\n
+ *size += it->first.length() + 1 + 1 + it->second.length() + 2;
+ }
+
+ // then the body, first an extra newline
+ *size += 2;
+
+ // body
+ *size += body_size;
+
+ // Now let's print it
+ char* res = (char*)calloc(*size + 1, 1);
+ char* originalRes = res;
+
+ res += sprintf(res, "HTTP/1.1 %s %s\r\n", status_code_buffer, status_message);
+
+ typedef map<string, string>::iterator it_type;
+ for(it_type it = headers.begin(); it != headers.end(); it++) {
+ // line is KEY: VALUE\r\n
+ res += sprintf(res, "%s: %s\r\n", it->first.c_str(), it->second.c_str());
+ }
+
+ res += sprintf(res, "\r\n");
+
+ if (body_size > 0) {
+ memcpy(res, body, body_size);
+ }
+ res += body_size;
+
+ // Uncomment to debug...
+ // printf("----- BEGIN RESPONSE -----\n");
+ // printf("%s", originalRes);
+ // printf("----- END RESPONSE -----\n");
+
+ return originalRes;
+ }
+
+ nsapi_error_t send(TCPSocket* socket, const void* body, size_t body_size) {
+ if (!socket) return NSAPI_ERROR_NO_SOCKET;
+
+ size_t res_size;
+ char* response = build(body, body_size, &res_size);
+
+ return socket->send(response, res_size);
+ }
+
+private:
+ uint16_t status_code;
+ const char* status_message;
+ map<string, string> headers;
+};
+
+#endif // _MBED_HTTP_RESPONSE_BUILDER_
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/source/http_server.h Mon Jul 31 15:41:22 2017 +0200
@@ -0,0 +1,177 @@
+/*
+ * PackageLicenseDeclared: Apache-2.0
+ * Copyright (c) 2017 ARM Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef _HTTP_SERVER_
+#define _HTTP_SERVER_
+
+#include "mbed.h"
+#include "http_request_parser.h"
+#include "http_response.h"
+#include "http_response_builder.h"
+
+#define HTTP_SERVER_MAX_CONCURRENT 5
+
+typedef HttpResponse ParsedHttpRequest;
+
+/**
+ * \brief HttpServer implements the logic for setting up an HTTP server.
+ */
+class HttpServer {
+public:
+ /**
+ * HttpRequest Constructor
+ *
+ * @param[in] network The network interface
+ */
+ HttpServer(NetworkInterface* network) : server(network) {
+
+ }
+
+ ~HttpServer() {
+ for (size_t ix = 0; ix < HTTP_SERVER_MAX_CONCURRENT; ix++) {
+ if (socket_threads[ix]) {
+ delete socket_threads[ix];
+ }
+ }
+ }
+
+ /**
+ * Start listening
+ *
+ * @param[in] port The port to listen on
+ */
+ nsapi_error_t bind(uint16_t port) {
+ server.listen(HTTP_SERVER_MAX_CONCURRENT); // max. concurrent connections...
+ return server.bind(port);
+ }
+
+ /**
+ * Start running the server (it will run on it's own thread)
+ */
+ nsapi_error_t start(uint16_t port, Callback<void(ParsedHttpRequest* request, TCPSocket* socket)> a_handler) {
+ server.listen(HTTP_SERVER_MAX_CONCURRENT); // max. concurrent connections...
+
+ nsapi_error_t ret = server.bind(port);
+ if (ret != NSAPI_ERROR_OK) {
+ return ret;
+ }
+
+ handler = a_handler;
+
+ main_thread.start(callback(this, &HttpServer::main));
+
+ return NSAPI_ERROR_OK;
+ }
+
+private:
+
+ void receive_data() {
+ // UNSAFE: should Mutex around it or something
+ TCPSocket* socket = sockets.back();
+
+ // needs to keep running until the socket gets closed
+ while (1) {
+
+ ParsedHttpRequest* response = new ParsedHttpRequest();
+ HttpParser* parser = new HttpParser(response, HTTP_REQUEST);
+
+ // Set up a receive buffer (on the heap)
+ uint8_t* recv_buffer = (uint8_t*)malloc(HTTP_RECEIVE_BUFFER_SIZE);
+
+ // TCPSocket::recv is called until we don't have any data anymore
+ nsapi_size_or_error_t recv_ret;
+ while ((recv_ret = socket->recv(recv_buffer, HTTP_RECEIVE_BUFFER_SIZE)) > 0) {
+ // Pass the chunk into the http_parser
+ size_t nparsed = parser->execute((const char*)recv_buffer, recv_ret);
+ if (nparsed != recv_ret) {
+ printf("Parsing failed... parsed %d bytes, received %d bytes\n", nparsed, recv_ret);
+ recv_ret = -2101;
+ break;
+ }
+
+ if (response->is_message_complete()) {
+ break;
+ }
+ }
+ // error?
+ if (recv_ret < 0) {
+ printf("Error reading from socket %d\n", recv_ret);
+
+ // error = recv_ret;
+ delete response;
+ delete parser;
+ free(recv_buffer);
+
+ // q; should we always break out of the thread or only if NO_SOCKET ?
+ // should we delete socket here? the socket seems already gone...
+ if (recv_ret < -3000) {
+ return;
+ }
+ else {
+ continue;
+ }
+ }
+
+ // When done, call parser.finish()
+ parser->finish();
+
+ // Free the receive buffer
+ free(recv_buffer);
+
+ // Let user application handle the request, if user needs a handle to response they need to memcpy themselves
+ handler(response, socket);
+
+ // Free the response and parser
+ delete response;
+ delete parser;
+ }
+ }
+
+ void main() {
+ while (1) {
+ TCPSocket* clt_sock = new TCPSocket(); // Q: when should these be cleared? When not connected anymore?
+ SocketAddress clt_addr;
+
+ nsapi_error_t accept_res = server.accept(clt_sock, &clt_addr);
+ if (accept_res == NSAPI_ERROR_OK) {
+ sockets.push_back(clt_sock); // so we can clear our disconnected sockets
+
+ // and start listening for events there
+ Thread* t = new Thread(osPriorityNormal, 2048);
+ t->start(callback(this, &HttpServer::receive_data));
+
+ socket_threads.push_back(t);
+ }
+
+ for (size_t ix = 0; ix < socket_threads.size(); ix++) {
+ if (socket_threads[ix]->get_state() == Thread::Deleted) {
+ delete socket_threads[ix];
+ socket_threads.erase(socket_threads.begin() + ix); // what if there are two?
+ }
+ }
+
+ }
+ }
+
+ TCPServer server;
+ Thread main_thread;
+ vector<TCPSocket*> sockets;
+ vector<Thread*> socket_threads;
+ Callback<void(ParsedHttpRequest* request, TCPSocket* socket)> handler = 0;
+};
+
+#endif // _HTTP_SERVER
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/source/main.cpp Mon Jul 31 15:41:22 2017 +0200
@@ -0,0 +1,63 @@
+#include "mbed.h"
+#include "easy-connect.h"
+#include "http_server.h"
+#include "http_response_builder.h"
+
+Serial pc(USBTX, USBRX);
+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() {
+ pc.baud(115200);
+
+ // Connect to the network (see mbed_app.json for the connectivity method used)
+ NetworkInterface* network = easy_connect(true);
+ if (!network) {
+ printf("Cannot connect to the network, see serial output\n");
+ return 1;
+ }
+
+ HttpServer server(network);
+ nsapi_error_t res = server.start(8080, &request_handler);
+
+ if (res == NSAPI_ERROR_OK) {
+ printf("Server is listening at http://%s:8080\n", network->get_ip_address());
+ }
+ else {
+ printf("Server could not be started... %d\n", res);
+ }
+
+ wait(osWaitForever);
+}
Bongjun Hur

