this is using the mbed os version 5-13-1
Revision 73:6f5021cbe752, committed 2019-02-28
- Comitter:
- ocomeni
- Date:
- Thu Feb 28 18:13:48 2019 +0000
- Parent:
- 72:b36a60f4b290
- Child:
- 74:f26e846adfe9
- Commit message:
- commit current application code
Changed in this revision
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbed-http.lib Thu Feb 28 18:13:48 2019 +0000 @@ -0,0 +1,1 @@ +https://developer.mbed.org/teams/sandbox/code/mbed-http/#fa4d71265625
--- a/mbed_app.json Fri Nov 16 16:45:32 2018 +0000
+++ b/mbed_app.json Thu Feb 28 18:13:48 2019 +0000
@@ -1,4 +1,29 @@
{
+ "config": {
+ "main-stack-size": {
+ "value": 8192
+ },
+ "network-interface":{
+ "help": "options are ETHERNET, WIFI_ESP8266, WIFI_ODIN, WIFI_IDW01M1, WIFI_RTW, MESH_LOWPAN_ND, MESH_THREAD",
+ "value": "WIFI_ODIN"
+ },
+ "wifi-ssid": {
+ "help": "WiFi SSID",
+ "value": "\"VM9109107\""
+ },
+ "wifi-password": {
+ "help": "WiFi Password",
+ "value": "\"Bonga01shop02\""
+ }
+ },
+ "macros": [
+ "MBEDTLS_MPI_MAX_SIZE=1024",
+ "MBEDTLS_MPI_WINDOW_SIZE=1",
+ "MBEDTLS_USER_CONFIG_FILE=\"mbedtls_entropy_config.h\"",
+ "MBEDTLS_TEST_NULL_ENTROPY",
+ "MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES",
+ "MBED_HEAP_STATS_ENABLED=1"
+ ],
"target_overrides": {
"K64F": {
"target.features_add": ["BLE"],
@@ -12,5 +37,5 @@
"target.features_add": ["BLE"],
"target.extra_labels_add": ["CORDIO", "CORDIO_BLUENRG"]
}
- }
+ }
}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedtls_entropy_config.h Thu Feb 28 18:13:48 2019 +0000 @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2006-2016, ARM Limited, All Rights Reserved + * SPDX-License-Identifier: Apache-2.0 + * + * 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. + * + * This file is part of mbed TLS (https://tls.mbed.org) + */ + +#include "select-demo.h" + +/* Enable entropy for devices with TRNG. This means entropy is disabled for all other targets. */ +/* Do **NOT** deploy this code in production on other targets! */ +/* See https://tls.mbed.org/kb/how-to/add-entropy-sources-to-entropy-pool */ +#if defined(DEVICE_TRNG) +#undef MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES +#undef MBEDTLS_TEST_NULL_ENTROPY +#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/simconfig.json Thu Feb 28 18:13:48 2019 +0000
@@ -0,0 +1,5 @@
+{
+ "ignore": [
+ "./mbed-http"
+ ]
+}
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/source/https_certificates.h Thu Feb 28 18:13:48 2019 +0000 @@ -0,0 +1,75 @@ +/* List of trusted root CA certificates + * currently two: GlobalSign, the CA for os.mbed.com and Let's Encrypt, the CA for httpbin.org + * + * To add more root certificates, just concatenate them. + */ + + const char SSL_CA_PEM[] = "-----BEGIN CERTIFICATE-----\n" + "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG\n" + "A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv\n" + "b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw\n" + "MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i\n" + "YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT\n" + "aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ\n" + "jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp\n" + "xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp\n" + "1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG\n" + "snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ\n" + "U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8\n" + "9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E\n" + "BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B\n" + "AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz\n" + "yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE\n" + "38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP\n" + "AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad\n" + "DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME\n" + "HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n" + "-----END CERTIFICATE-----\n" + "-----BEGIN CERTIFICATE-----\n" + "MIIEkjCCA3qgAwIBAgIQCgF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QcC\n" + "ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz\n" + "MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu\n" + "Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF\n" + "AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo\n" + "uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/\n" + "wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu\n" + "X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG\n" + "PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6\n" + "KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==\n" + "-----END CERTIFICATE-----\n" + "-----BEGIN CERTIFICATE-----\n" + "MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF\n" + "ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6\n" + "b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL\n" + "MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv\n" + "b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj\n" + "ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM\n" + "9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw\n" + "IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6\n" + "VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L\n" + "93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm\n" + "jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC\n" + "AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA\n" + "A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI\n" + "U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs\n" + "N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv\n" + "o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU\n" + "5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy\n" + "rqXRfboQnoZsG4q5WTP468SQvvG5\n" + "-----END CERTIFICATE-----\n" +;
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/source/main-http-ipv6.cpp Thu Feb 28 18:13:48 2019 +0000
@@ -0,0 +1,48 @@
+#include "select-demo.h"
+
+#if DEMO == DEMO_HTTP_IPV6
+
+#include "mbed.h"
+#include "network-helper.h"
+#include "http_request.h"
+
+void dump_response(HttpResponse* res) {
+ printf("Status: %d - %s\n", res->get_status_code(), res->get_status_message().c_str());
+
+ printf("Headers:\n");
+ for (size_t ix = 0; ix < res->get_headers_length(); ix++) {
+ printf("\t%s: %s\n", res->get_headers_fields()[ix]->c_str(), res->get_headers_values()[ix]->c_str());
+ }
+ printf("\nBody (%d bytes):\n\n%s\n", res->get_body_length(), res->get_body_as_string().c_str());
+}
+
+int main() {
+ NetworkInterface* network = connect_to_default_network_interface();
+ if (!network) {
+ printf("Cannot connect to the network, see serial output\n");
+ return 1;
+ }
+
+ // Do a GET request to icanhazip.com which returns the public IPv6 address for the device
+ // This page is only accessible over IPv6
+ {
+ // By default the body is automatically parsed and stored in a buffer, this is memory heavy.
+ // To receive chunked response, pass in a callback as last parameter to the constructor.
+ HttpRequest* get_req = new HttpRequest(network, HTTP_GET, "http://ipv6.icanhazip.com");
+
+ HttpResponse* get_res = get_req->send();
+ if (!get_res) {
+ printf("HttpRequest failed (error code %d)\n", get_req->get_error());
+ return 1;
+ }
+
+ printf("\n----- HTTP GET response -----\n");
+ dump_response(get_res);
+
+ delete get_req;
+ }
+
+ wait(osWaitForever);
+}
+
+#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/source/main-http-socket-reuse.cpp Thu Feb 28 18:13:48 2019 +0000
@@ -0,0 +1,87 @@
+#include "select-demo.h"
+
+#if DEMO == DEMO_HTTP_SOCKET_REUSE
+
+#include "mbed.h"
+#include "network-helper.h"
+#include "http_request.h"
+
+void dump_response(HttpResponse* res) {
+ printf("Status: %d - %s\n", res->get_status_code(), res->get_status_message().c_str());
+
+ printf("Headers:\n");
+ for (size_t ix = 0; ix < res->get_headers_length(); ix++) {
+ printf("\t%s: %s\n", res->get_headers_fields()[ix]->c_str(), res->get_headers_values()[ix]->c_str());
+ }
+ printf("\nBody (%d bytes):\n\n%s\n", res->get_body_length(), res->get_body_as_string().c_str());
+}
+
+int main() {
+ NetworkInterface* network = connect_to_default_network_interface();
+ if (!network) {
+ printf("Cannot connect to the network, see serial output\n");
+ return 1;
+ }
+
+ // Create a TCP socket
+ printf("\n----- Setting up TCP connection -----\n");
+
+ TCPSocket* socket = new TCPSocket();
+ nsapi_error_t open_result = socket->open(network);
+ if (open_result != 0) {
+ printf("Opening TCPSocket failed... %d\n", open_result);
+ return 1;
+ }
+
+ nsapi_error_t connect_result = socket->connect("httpbin.org", 80);
+ if (connect_result != 0) {
+ printf("Connecting over TCPSocket failed... %d\n", connect_result);
+ return 1;
+ }
+
+ printf("Connected over TCP to httpbin.org:80\n");
+
+ // Do a GET request to httpbin.org
+ {
+ HttpRequest* get_req = new HttpRequest(socket, HTTP_GET, "http://httpbin.org/status/418");
+
+ // By default the body is automatically parsed and stored in a string, this is memory heavy.
+ // To receive chunked response, pass in a callback as third parameter to 'send'.
+ HttpResponse* get_res = get_req->send();
+ if (!get_res) {
+ printf("HttpRequest failed (error code %d)\n", get_req->get_error());
+ return 1;
+ }
+
+ printf("\n----- HTTP GET response -----\n");
+ dump_response(get_res);
+
+ delete get_req;
+ }
+
+ // POST request to httpbin.org
+ {
+ HttpRequest* post_req = new HttpRequest(socket, HTTP_POST, "http://httpbin.org/post");
+ post_req->set_header("Content-Type", "application/json");
+
+ const char body[] = "{\"hello\":\"world\"}";
+
+ HttpResponse* post_res = post_req->send(body, strlen(body));
+ if (!post_res) {
+ printf("HttpRequest failed (error code %d)\n", post_req->get_error());
+ return 1;
+ }
+
+ printf("\n----- HTTP POST response -----\n");
+ dump_response(post_res);
+
+ delete post_req;
+ }
+
+ socket->close();
+ delete socket;
+
+ wait(osWaitForever);
+}
+
+#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/source/main-http.cpp Thu Feb 28 18:13:48 2019 +0000
@@ -0,0 +1,69 @@
+#include "select-demo.h"
+
+#if DEMO == DEMO_HTTP
+
+#include "mbed.h"
+#include "http_request.h"
+#include "network-helper.h"
+#include "mbed_mem_trace.h"
+
+void dump_response(HttpResponse* res) {
+ printf("Status: %d - %s\n", res->get_status_code(), res->get_status_message().c_str());
+
+ printf("Headers:\n");
+ for (size_t ix = 0; ix < res->get_headers_length(); ix++) {
+ printf("\t%s: %s\n", res->get_headers_fields()[ix]->c_str(), res->get_headers_values()[ix]->c_str());
+ }
+ printf("\nBody (%d bytes):\n\n%s\n", res->get_body_length(), res->get_body_as_string().c_str());
+}
+
+int main() {
+ // Connect to the network with the default networking interface
+ // if you use WiFi: see mbed_app.json for the credentials
+ NetworkInterface* network = connect_to_default_network_interface();
+ if (!network) {
+ printf("Cannot connect to the network, see serial output\n");
+ return 1;
+ }
+
+ // Do a GET request to httpbin.org
+ {
+ // By default the body is automatically parsed and stored in a buffer, this is memory heavy.
+ // To receive chunked response, pass in a callback as last parameter to the constructor.
+ HttpRequest* get_req = new HttpRequest(network, HTTP_GET, "http://httpbin.org/status/418");
+
+ HttpResponse* get_res = get_req->send();
+ if (!get_res) {
+ printf("HttpRequest failed (error code %d)\n", get_req->get_error());
+ return 1;
+ }
+
+ printf("\n----- HTTP GET response -----\n");
+ dump_response(get_res);
+
+ delete get_req;
+ }
+
+ // POST request to httpbin.org
+ {
+ HttpRequest* post_req = new HttpRequest(network, HTTP_POST, "http://httpbin.org/post");
+ post_req->set_header("Content-Type", "application/json");
+
+ const char body[] = "{\"hello\":\"world\"}";
+
+ HttpResponse* post_res = post_req->send(body, strlen(body));
+ if (!post_res) {
+ printf("HttpRequest failed (error code %d)\n", post_req->get_error());
+ return 1;
+ }
+
+ printf("\n----- HTTP POST response -----\n");
+ dump_response(post_res);
+
+ delete post_req;
+ }
+
+ wait(osWaitForever);
+}
+
+#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/source/main-https-chunked-request.cpp Thu Feb 28 18:13:48 2019 +0000
@@ -0,0 +1,113 @@
+/**
+ * This is an example of doing chunked requests, where you do not need to load the full request body
+ * into memory. You do this by adding a callback to the `send` function of the HTTP/HTTPS request.
+ */
+
+#include "select-demo.h"
+
+#if DEMO == DEMO_HTTPS_CHUNKED_REQUEST
+
+#include "mbed.h"
+#include "mbed_trace.h"
+#include "https_request.h"
+#include "network-helper.h"
+
+/* List of trusted root CA certificates
+ * currently one: Comodo, the CA for reqres.in
+ *
+ * To add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ump_response(HttpResponse* res) {
+ printf("Status: %d - %s\n", res->get_status_code(), res->get_status_message().c_str());
+
+ printf("Headers:\n");
+ for (size_t ix = 0; ix < res->get_headers_length(); ix++) {
+ printf("\t%s: %s\n", res->get_headers_fields()[ix]->c_str(), res->get_headers_values()[ix]->c_str());
+ }
+ printf("\nBody (%lu bytes):\n\n%s\n", res->get_body_length(), res->get_body_as_string().c_str());
+}
+
+// Spread the message out over 3 different chunks
+const char * chunks[] = {
+ "{\"message\":",
+ "\"this is an example",
+ " of chunked encoding\"}"
+};
+
+int chunk_ix = 0;
+
+// Callback function, grab the next chunk and return it
+const void * get_chunk(uint32_t* out_size) {
+ // If you don't have any data left, set out_size to 0 and return a null pointer
+ if (chunk_ix == (sizeof(chunks) / sizeof(chunks[0]))) {
+ *out_size = 0;
+ return NULL;
+ }
+ const char *chunk = chunks[chunk_ix];
+ *out_size = strlen(chunk);
+ chunk_ix++;
+
+ return chunk;
+}
+
+int main() {
+ NetworkInterface* network = connect_to_default_network_interface();
+ if (!network) {
+ printf("Cannot connect to the network, see serial output\n");
+ return 1;
+ }
+
+ mbed_trace_init();
+
+ // This example also logs the raw request, you can do this by calling 'set_request_log_buffer' on the request
+ uint8_t *request_buffer = (uint8_t*)calloc(2048, 1);
+
+ // POST request to reqres.in
+ {
+ HttpsRequest* post_req = new HttpsRequest(network, SSL_CA_PEM, HTTP_POST, "https://reqres.in/api/users");
+ post_req->set_header("Content-Type", "application/json");
+ post_req->set_request_log_buffer(request_buffer, 2048);
+
+ // If you pass a callback here, the Transfer-Encoding header is automatically set to chunked
+ HttpResponse* post_res = post_req->send(&get_chunk);
+ if (!post_res) {
+ printf("HttpsRequest failed (error code %d)\n", post_req->get_error());
+ return 1;
+ }
+
+ // Log the raw request that went over the line (if you decode the hex you can see the chunked parts)
+ // e.g. in Node.js (take the output from below):
+ // '50 4f 53 54 20'.split(' ').map(c=>parseInt(c,16)).map(c=>String.fromCharCode(c)).join('')
+ printf("\n----- Request buffer -----\n");
+ for (size_t ix = 0; ix < post_req->get_request_log_buffer_length(); ix++) {
+ printf("%02x ", request_buffer[ix]);
+ }
+ printf("\n");
+
+ printf("\n----- HTTPS POST response -----\n");
+ dump_response(post_res);
+
+ delete post_req;
+ }
+
+ wait(osWaitForever);
+}
+
+#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/source/main-https-socket-reuse.cpp Thu Feb 28 18:13:48 2019 +0000
@@ -0,0 +1,125 @@
+#include "select-demo.h"
+
+/**
+ * This demo shows how to re-use sockets, so the TLS handshake only has to happen once
+ */
+
+#if DEMO == DEMO_HTTPS_SOCKET_REUSE
+
+#include "mbed.h"
+#include "mbed_trace.h"
+#include "https_request.h"
+#include "network-helper.h"
+
+/* List of trusted root CA certificates
+ * currently one: Let's Encrypt, the CA for httpbin.org
+ *
+ * To add more root certificates, just concatenate them.
+ */
+const char SSL_CA_PEM[] = "-----BEGIN CERTIFICATE-----\n"
+ "MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/\n"
+ "MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n"
+ "DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow\n"
+ "SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT\n"
+ "GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC\n"
+ "AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF\n"
+ "q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8\n"
+ "SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0\n"
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h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6\n"
+ "KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==\n"
+ "-----END CERTIFICATE-----\n";
+
+void dump_response(HttpResponse* res) {
+ printf("Status: %d - %s\n", res->get_status_code(), res->get_status_message().c_str());
+
+ printf("Headers:\n");
+ for (size_t ix = 0; ix < res->get_headers_length(); ix++) {
+ printf("\t%s: %s\n", res->get_headers_fields()[ix]->c_str(), res->get_headers_values()[ix]->c_str());
+ }
+ printf("\nBody (%d bytes):\n\n%s\n", res->get_body_length(), res->get_body_as_string().c_str());
+}
+
+int main() {
+ NetworkInterface* network = connect_to_default_network_interface();
+ if (!network) {
+ printf("Cannot connect to the network, see serial output\n");
+ return 1;
+ }
+
+ mbed_trace_init();
+
+ // Create a TLS socket (which holds a TCPSocket)
+ printf("\n----- Setting up TLS connection -----\n");
+
+ nsapi_error_t r;
+
+ TLSSocket* socket = new TLSSocket();
+ if ((r = socket->open(network)) != NSAPI_ERROR_OK) {
+ printf("TLS socket open failed (%d)\n", r);
+ return 1;
+ }
+ if ((r = socket->set_root_ca_cert(SSL_CA_PEM)) != NSAPI_ERROR_OK) {
+ printf("TLS socket set_root_ca_cert failed (%d)\n", r);
+ return 1;
+ }
+ if ((r = socket->connect("httpbin.org", 443)) != NSAPI_ERROR_OK) {
+ printf("TLS socket connect failed (%d)\n", r);
+ return 1;
+ }
+
+ // GET request to httpbin.org
+ {
+ HttpsRequest* get_req = new HttpsRequest(socket, HTTP_GET, "https://httpbin.org/status/418");
+
+ HttpResponse* get_res = get_req->send();
+ if (!get_res) {
+ printf("HttpRequest failed (error code %d)\n", get_req->get_error());
+ return 1;
+ }
+ printf("\n----- HTTPS GET response -----\n");
+ dump_response(get_res);
+
+ delete get_req;
+ }
+
+ // POST request to httpbin.org
+ {
+ HttpsRequest* post_req = new HttpsRequest(socket, HTTP_POST, "https://httpbin.org/post");
+ post_req->set_header("Content-Type", "application/json");
+
+ const char body[] = "{\"hello\":\"world\"}";
+
+ HttpResponse* post_res = post_req->send(body, strlen(body));
+ if (!post_res) {
+ printf("HttpRequest failed (error code %d)\n", post_req->get_error());
+ return 1;
+ }
+
+ printf("\n----- HTTPS POST response -----\n");
+ dump_response(post_res);
+
+ delete post_req;
+ }
+
+ socket->close();
+ delete socket;
+
+ wait(osWaitForever);
+}
+
+#endif
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/source/main-https.cpp Thu Feb 28 18:13:48 2019 +0000
@@ -0,0 +1,617 @@
+#define MBED_CONF_MBED_TRACE_ENABLE 1
+
+#include "select-demo.h"
+
+#if DEMO == DEMO_HTTPS
+
+//#include "mbed.h"
+#include <events/mbed_events.h>
+#include <mbed.h>
+#include "ble/BLE.h"
+//#include "BLE.h"
+#include "mbed_trace.h"
+#include "https_request.h"
+#include "http_request.h"
+#include "network-helper.h"
+#include "ATCmdParser.h"
+//#include "BLEDevice.h"
+
+#include "LEDService.h"
+#include "ble/services/UARTService.h"
+
+UARTService *uart;
+
+DigitalOut alivenessLED(LED1, 0);
+DigitalOut actuatedLED(LED2, 0);
+
+#define DEFAULT_BAUD_RATE 115200
+
+RawSerial *device; // tx, rx
+UARTSerial *_serial; // tx, rx
+ATCmdParser *_parser;
+const static char DEVICE_NAME[] = "BLE-UART";
+static const uint16_t uuid16_list[] = {LEDService::LED_SERVICE_UUID};
+#define BUFFER_LEN 256
+#define TX_BUFFER_LEN 4*256
+#define RX_BUFFER_LEN 4*256
+char buffer[BUFFER_LEN];
+uint8_t TxBuffer[TX_BUFFER_LEN];
+uint8_t RxBuffer[RX_BUFFER_LEN];
+static EventQueue eventQueue(/* event count */ 20 * EVENTS_EVENT_SIZE);
+//static EventQueue eventQueue2(/* event count */ 10 * EVENTS_EVENT_SIZE);
+
+LEDService *ledServicePtr;
+
+Thread t;
+
+/* List of trusted root CA certificates
+ * currently two: GlobalSign, the CA for os.mbed.com and Let's Encrypt, the CA for httpbin.org
+ *
+ * To add more root certificates, just concatenate them.
+ */
+#include "https_certificates.h"
+
+
+
+void disconnectionCallback(const Gap::DisconnectionCallbackParams_t *params)
+{
+ (void) params;
+ BLE::Instance().gap().startAdvertising();
+}
+
+void blinkCallback(void)
+{
+ alivenessLED = !alivenessLED; /* Do blinky on LED1 to indicate system aliveness. */
+}
+
+void EchoBleUartReceived()
+{
+ uart->writeString(buffer);
+ uart->writeString("\n"); //flushes uart output buffer and sends data
+}
+
+/**
+ * This callback allows the LEDService to receive updates to the ledState Characteristic.
+ *
+ * @param[in] params
+ * Information about the characterisitc being updated.
+ */
+void onDataWrittenCallback(const GattWriteCallbackParams *params) {
+ if ((params->handle == ledServicePtr->getValueHandle()) && (params->len == 1)) {
+ actuatedLED = *(params->data);
+ }
+ else if ((uart != NULL) && (params->handle == uart->getTXCharacteristicHandle())) {
+ uint16_t bytesRead = params->len;
+
+ printf("received %u bytes\n\r ", bytesRead);
+
+ if(bytesRead >= 255){
+ printf("Overflow command %u n\r ", bytesRead);
+ bytesRead = 255;
+ }
+
+ unsigned index = 0;
+ for (; index < bytesRead; index++) {
+ buffer[index] = params->data[index];
+ }
+
+ buffer[index++] = 0;
+
+ printf("Data : %s ",buffer);
+ printf("\r\n");
+ eventQueue.call(EchoBleUartReceived);
+
+ }
+}
+
+
+/**
+ * This function is called when the ble initialization process has failled
+ */
+void onBleInitError(BLE &ble, ble_error_t error)
+{
+ printf("\n BLE Initialization failed!! \n");
+
+ /* Initialization error handling should go here */
+}
+
+void printMacAddress()
+{
+ /* Print out device MAC address to the console*/
+ Gap::AddressType_t addr_type;
+ Gap::Address_t address;
+ BLE::Instance().gap().getAddress(&addr_type, address);
+ printf("DEVICE MAC ADDRESS: ");
+ for (int i = 5; i >= 1; i--){
+ printf("%02x:", address[i]);
+ }
+ printf("%02x\r\n", address[0]);
+}
+
+/**
+ * Callback triggered when the ble initialization process has finished
+ */
+void bleInitComplete(BLE::InitializationCompleteCallbackContext *params)
+{
+ BLE& ble = params->ble;
+ ble_error_t error = params->error;
+
+ if (error != BLE_ERROR_NONE) {
+ /* In case of error, forward the error handling to onBleInitError */
+ onBleInitError(ble, error);
+ return;
+ }
+
+ /* Ensure that it is the default instance of BLE */
+ if(ble.getInstanceID() != BLE::DEFAULT_INSTANCE) {
+ return;
+ }
+
+ ble.gap().onDisconnection(disconnectionCallback);
+ ble.gattServer().onDataWritten(onDataWrittenCallback);
+
+ bool initialValueForLEDCharacteristic = false;
+ ledServicePtr = new LEDService(ble, initialValueForLEDCharacteristic);
+ /* Setup primary service */
+ uart = new UARTService(ble);
+
+ /* setup advertising */
+ ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
+ ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list));
+ ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
+ /* set up the services that can be discovered */
+ ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS,(const uint8_t *)UARTServiceUUID_reversed, sizeof(UARTServiceUUID_reversed));
+ ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
+ ble.gap().setAdvertisingInterval(1000); /* 1000ms. */
+ ble.gap().startAdvertising();
+
+ printMacAddress();
+}
+
+void scheduleBleEventsProcessing(BLE::OnEventsToProcessCallbackContext* context) {
+ BLE &ble = BLE::Instance();
+ eventQueue.call(Callback<void()>(&ble, &BLE::processEvents));
+}
+
+
+void bleInitialization()
+{
+ BLE &ble = BLE::Instance();
+ device->printf("\n --- BLE Instance Instantiated --- \n");
+ ble.onEventsToProcess(scheduleBleEventsProcessing);
+ device->printf("\n --- BLE scheduleBleEventsProcessing setup --- \n");
+ ble.init(bleInitComplete);
+}
+
+
+static int uartExpectedRcvCount = 0;
+static int uartCharRcvCount = 0;
+static bool UartBusy = false;
+int WriteUartBytes(const uint8_t * txBuffer, size_t bufSize, int txLen)
+{
+ if(txLen > bufSize)
+ {
+ txLen = bufSize;
+ }
+ //int goodTxLen;
+ //goodTxLen = _parser.write((const char *) txBuffer, txLen);
+ for(int i=0;i<txLen;i++)
+ {
+ device->putc(txBuffer[i]);
+ }
+ // return number of bytes written to UART
+ return (int) txLen;
+}
+
+void UartRxcallback_ex() {
+ if(uartCharRcvCount >= uartExpectedRcvCount)
+ {
+ int x = device->getc();
+ return;
+ }
+ if(uartCharRcvCount == 0)
+ {
+ device->printf("\nFirst Call to UART attach callback!!\n");
+ }
+ // Note: you need to actually read from the serial to clear the RX interrupt
+ RxBuffer[uartCharRcvCount] = (uint8_t) device->getc();
+ uartCharRcvCount++;
+ if(uartCharRcvCount >= uartExpectedRcvCount)
+ {
+ alivenessLED = !alivenessLED; /* Do blinky on LED1 to indicate system aliveness. */
+ device->printf("\nNumber of Received Bytes = %d\n\n", uartCharRcvCount);
+ device->printf("--- Writing back received bytes --- \n");
+ int n;
+ n = WriteUartBytes(RxBuffer, TX_BUFFER_LEN, uartCharRcvCount);
+ UartBusy = false;
+ }
+}
+
+void BackGndUartRead(uint8_t * rxBuffer, size_t bufSize, int rxLen)
+{
+ UartBusy = true;
+ device->printf("Setting up background UART read - rxLen = %d\n", rxLen);
+ uartCharRcvCount = 0;
+ if(rxLen > bufSize)
+ {
+ rxLen = bufSize;
+ }
+ uartExpectedRcvCount = rxLen;
+ device->attach(&UartRxcallback_ex);
+ device->printf("\nBackground UART read setup completed\n\n");
+ //for(int i=0;i<rxLen;i++)
+ //{
+ // rxBuffer[i] = (uint8_t) getc();
+ //}
+ // return number of bytes written to UART
+ //return rxLen;
+}
+
+int ReadUartBytes(uint8_t * rxBuffer, size_t bufSize, int rxLen, bool echo)
+{
+ UartBusy = true;
+ if(rxLen > bufSize)
+ {
+ rxLen = bufSize;
+ }
+ for(int i=0;i<rxLen;i++)
+ {
+ rxBuffer[i] = (uint8_t) device->getc();
+ if(echo)device->putc(rxBuffer[i]);
+ }
+ UartBusy = false;
+ //return number of bytes written to UART
+ return rxLen;
+}
+
+
+void checkUartReceive()
+{
+ //device->printf("Hello World!\n\r");
+ char cbuf[100];
+ int rxCnt=0;
+ while(device->readable()) {
+ //device->printf("uartCharRcvCount = %d\n\r", uartCharRcvCount++);
+ cbuf[rxCnt++] = device->getc();
+ //putc(getc() + 1); // echo input back to terminal
+ }
+ cbuf[rxCnt] = NULL;
+ if(rxCnt > 0)
+ {
+ device->printf("received %d chars\n", rxCnt);
+ device->printf("%s\n", cbuf);
+ }
+
+}
+uint64_t lastTime = 0;
+uint64_t now = 0;
+uint32_t callCount = 0;
+void HelloUart()
+{
+ //if(UartBusy)return;
+ // 64-bit time doesn't wrap for half a billion years, at least
+ lastTime = now;
+ now = Kernel::get_ms_count();
+ callCount++;
+ device->printf("\nHello : %d secs elapsed : CallCount = %d \n", uint32_t(now - lastTime), callCount);
+}
+
+
+
+
+//Serial device(USBTX, USBRX); // tx, rx
+//RawSerial device(MBED_CONF_APP_UART1_TX, MBED_CONF_APP_UART1_RX); // tx, rx
+
+
+int chunkNum;
+void dump_response(HttpResponse* res) {
+ device->printf("Status: %d - %s\n", res->get_status_code(), res->get_status_message().c_str());
+
+ device->printf("Headers:\n");
+ for (size_t ix = 0; ix < res->get_headers_length(); ix++) {
+ device->printf("\t%s: %s\n", res->get_headers_fields()[ix]->c_str(), res->get_headers_values()[ix]->c_str());
+ }
+ device->printf("\nBody (%lu bytes):\n\n%s\n", res->get_body_length(), res->get_body_as_string().c_str());
+}
+
+void completed(){
+ }
+void dump_chunked_response(const char *at, uint32_t length) {
+ device->printf("\n Chunked response: Chunk %d : Total Bytes = %d\n", chunkNum , length);
+ //device->printf("\n Try Print Header as string:\n\n ");
+ //device->printf("recv %d [%.*s]\n", length, strstr((char *)at, "\r\n")-(char *)at, (char *)at);
+ //if(false)
+ if(chunkNum < 2)
+ for(int i=0; i < length; i++){
+
+ while(device->writeable())
+ {
+ device->putc((uint8_t)at[i]);
+ }
+ //int resp = write( (const uint8_t *)at, (int) length, &completed, SERIAL_EVENT_TX_COMPLETE);
+ }
+ if(false)
+ for (size_t ix = 0; ix < length; ix++) {
+ device->printf("%02X: ", at[ix]);
+ if((ix % 32) == 0 and ix)
+ device->printf("\n");
+ }
+ device->printf("\n\n");
+ chunkNum++;
+ //device->printf("\nBody (%lu bytes):\n\n%s\n", res->get_body_length(), res->get_body_as_string().c_str());
+}
+
+
+// Wifi-demo
+void wifi_demo(NetworkInterface* network){
+ if (!network) {
+ device->printf("Cannot connect to the network, see serial output\n");
+ return 1;
+ }
+
+ mbed_trace_init();
+
+ // GET request to os.mbed.com
+ {
+ chunkNum = 0;
+ device->printf("\n----- HTTPS GET request -----\n");
+
+ HttpsRequest* get_req = new HttpsRequest(network, SSL_CA_PEM, HTTP_GET, "https://os.mbed.com/media/uploads/mbed_official/hello.txt", &dump_chunked_response);
+
+ HttpResponse* get_res = get_req->send();
+ if (!get_res) {
+ device->printf("HttpRequest failed (error code %d)\n", get_req->get_error());
+ return 1;
+ }
+ device->printf("\n----- HTTPS GET response -----\n");
+ dump_response(get_res);
+ delete get_req;
+ }
+
+
+
+ // Do a GET request to httpbin.org
+ {
+ chunkNum = 0;
+ device->printf("\n----- HTTP GET request to httpbin.org -----\n");
+
+ // By default the body is automatically parsed and stored in a buffer, this is memory heavy.
+ // To receive chunked response, pass in a callback as last parameter to the constructor.
+ HttpRequest* get_req = new HttpRequest(network, HTTP_GET, "http://httpbin.org/status/418");
+
+ HttpResponse* get_res = get_req->send();
+ if (!get_res) {
+ device->printf("HttpRequest failed (error code %d)\n", get_req->get_error());
+ return 1;
+ }
+
+ device->printf("\n----- HTTP GET response from httpbin.org -----\n");
+ dump_response(get_res);
+
+ delete get_req;
+ }
+
+
+ // Do a GET request to ovh.net
+ if(false)
+ {
+ chunkNum = 0;
+ device->printf("\n----- HTTP GET request to ovh.net -----\n");
+ Timer t;
+ // By default the body is automatically parsed and stored in a buffer, this is memory heavy.
+ // To receive chunked response, pass in a callback as last parameter to the constructor.
+ t.start();
+ HttpRequest* get_req = new HttpRequest(network, HTTP_GET, "http://www.ovh.net/files/1Mio.dat", &dump_chunked_response);
+
+ HttpResponse* get_res = get_req->send();
+ if (!get_res) {
+ device->printf("HttpRequest failed (error code %d)\n", get_req->get_error());
+ return 1;
+ }
+
+ device->printf("\n----- HTTP GET response from ovh.net -----\n");
+ dump_response(get_res);
+ t.stop();
+ device->printf("The time taken was %f seconds\n", t.read());
+
+
+ delete get_req;
+ }
+
+ {
+ device->printf("\n----- HTTPS GET request (large file!) -----\n");
+
+ HttpsRequest* get_req = new HttpsRequest(network, SSL_CA_PEM, HTTP_GET, "https://os.mbed.com/media/uploads/mbed_official/hello.txt");
+
+ HttpResponse* get_res = get_req->send();
+ if (!get_res) {
+ device->printf("HttpRequest failed (error code %d)\n", get_req->get_error());
+ return 1;
+ }
+ /*
+ while (0 < (response = socket.recv(p, remaining))) {
+ p += response;
+ rcount += response;
+ remaining -= response;
+ }
+ */
+ device->printf("\n----- HTTPS GET response -----\n");
+ dump_response(get_res);
+
+
+
+ delete get_req;
+ }
+
+ // POST request to httpbin.org
+ {
+ device->printf("\n----- HTTPS POST request -----\n");
+
+ HttpsRequest* post_req = new HttpsRequest(network, SSL_CA_PEM, HTTP_POST, "https://httpbin.org/post");
+ post_req->set_header("Content-Type", "application/json");
+
+ const char body[] = "{\"hello\":\"world\"}";
+
+ HttpResponse* post_res = post_req->send(body, strlen(body));
+ if (!post_res) {
+ device->printf("HttpRequest failed (error code %d)\n", post_req->get_error());
+ return 1;
+ }
+
+ device->printf("\n----- HTTPS POST response -----\n");
+ dump_response(post_res);
+
+ delete post_req;
+ }
+
+
+ // POST request to ws.dnanudge.io:80
+ {
+ device->printf("\n----- HTTP POST request (http://ws.dnanudge.io/nudgebox/v1) -----\n");
+
+ HttpRequest* post_req = new HttpRequest(network, HTTP_POST, "http://ws.dnanudge.io/nudgebox/v1");
+ post_req->set_header("Host", "ws.dnanudge.io");
+ post_req->set_header("Accept", "*/*");
+ post_req->set_header("Content-Type", "application/octet-stream");
+ post_req->set_header("Content-Length", "20");
+ // 00 08 6a 48 f8 2d 8e 82 01 68
+ const uint8_t body[] = {0x00, 0x08, 0x6a, 0x48, 0xf8, 0x2d, 0x8e, 0x82, 0x01, 0x68,
+ // 65 6c 6c 6f 00 00 67 c3 19 f8
+ 0x65, 0x6c, 0x6c, 0x6f, 0x00, 0x00, 0x67, 0xc3, 0x19, 0xf8};
+
+ HttpResponse* post_res = post_req->send(body, 20);
+ if (!post_res) {
+ device->printf("HttpRequest failed (error code %d)\n", post_req->get_error());
+ return 1;
+ }
+
+ device->printf("\n----- HTTPS POST response -----\n");
+ dump_response(post_res);
+
+ delete post_req;
+ }
+
+
+ // POST request to httpbin.org
+ if(false)
+ {
+ device->printf("\n----- HTTPS POST request to AWS -----\n");
+
+ HttpsRequest* post_req = new HttpsRequest(network, SSL_CA_PEM, HTTP_POST, "https://q6bc0dxw7f.execute-api.eu-west-2.amazonaws.com/test/samples/v1");
+ post_req->set_header("Content-Type", "application/json");
+
+ const char body[] =
+ "{"
+ "\"firstName\": \"Maria\", "
+ "\"lastName\": \"Huntera\", "
+ "\"dob\": \"1970-12-03\", "
+ "\"mobile\": \"07841887580\", "
+ "\"cartridgeId\": \"DN00000000RMPOE\", "
+ "\"labSampleId\": \"DYYAK\""
+ "}";
+ HttpResponse* post_res = post_req->send(body, strlen(body));
+ if (!post_res) {
+ device->printf("HttpRequest failed (error code %d)\n", post_req->get_error());
+ return 1;
+ }
+
+ device->printf("\n----- HTTPS POST response from AWS -----\n");
+ dump_response(post_res);
+
+ delete post_req;
+ }
+ }
+
+int main() {
+ //RawSerial *device(USBTX, USBRX); // tx, rx
+ device = new RawSerial(USBTX, USBRX, DEFAULT_BAUD_RATE);
+
+ device->printf("\n --- Running UART-BLE-UartService --- \n");
+ // Start the event queue
+ //t.start(callback(&eventQueue, &EventQueue::dispatch_forever));
+
+ eventQueue.call_every(500, blinkCallback);
+ eventQueue.call_every(60000, HelloUart);
+ //eventQueue.call_every(1000, checkUartReceive);
+ device->printf("\n --- EventQueues setup --- \n");
+ ////////////////////////////////////////////////////////////////////////////////
+ // BLE Initialization /////////////////////////////////////////////////////////
+ device->printf("\n --- about to instantiate BLE instance --- \n");
+ device->getc();
+ //cbMAIN_driverLock();
+ BLE &ble = BLE::Instance();
+ device->printf("\n --- BLE Instance Instantiated --- \n");
+ //ble.onEventsToProcess(scheduleBleEventsProcessing);
+ //device->printf("\n --- BLE scheduleBleEventsProcessing setup --- \n");
+ //ble.init(bleInitComplete);
+ bleInitialization();
+ //cbMAIN_driverUnlock();
+ device->printf("\n --- BLE Initialization completed --- \n");
+ device->printf("\n Press any key to start Wifi demo: ");
+ device->getc();
+ ////////////////////////////////////////////////////////////////////////////////////
+
+ //device->baud(115200);
+ NetworkInterface* network = connect_to_default_network_interface();
+ // run on separate thread;
+ t.start(wifi_demo(network));
+ network->disconnect();
+ t.join();
+
+ for(int i=0;i<255;i++)
+ {
+ device->putc(i);
+ }
+ int n;
+ //ReadUartBytes(RxBuffer, RX_BUFFER_LEN, 4);
+ device->printf("\n\n\nEnter # of expected bytes: ");
+ n = ReadUartBytes(RxBuffer, RX_BUFFER_LEN, 4, true);
+ int rxLen = (int) 100*(RxBuffer[0]-'0') + 10*(RxBuffer[1]-'0') + (RxBuffer[2]-'0');
+ device->printf("\n\nExpected # of Received Bytes = %d\n", rxLen);
+ BackGndUartRead(RxBuffer, RX_BUFFER_LEN, rxLen);
+ //device->printf("--- Writing back received data --- \n\n");
+ //n = WriteUartBytes(RxBuffer, TX_BUFFER_LEN, rxLen);
+ //write("\n\ntesting Serial Write\n", 40); //, checkUartReceive, SERIAL_EVENT_TX_COMPLETE);
+
+
+ device->printf("\nATCmdParser with ESP8266 example");
+ device->printf("\n Waiting for 2 minutes ");
+ wait(120);
+ eventQueue.dispatch_forever();
+ return 0;
+ device->printf("\n About to delete RawSerial device instance ");
+ delete device;
+ _serial = new UARTSerial(USBTX, USBRX, DEFAULT_BAUD_RATE);
+ printf("\n ATCmdParser printf being used now \n\n");
+ _parser = new ATCmdParser(_serial);
+ _parser->debug_on( 1 );
+ _parser->set_delimiter( "\r\n" );
+
+ //Now get the FW version number of ESP8266 by sending an AT command
+ printf("\nATCmdParser: Retrieving FW version");
+ _parser->send("AT+GMR");
+ int version;
+ if(_parser->recv("SDK version:%d", &version) && _parser->recv("OK")) {
+ printf("\nATCmdParser: FW version: %d", version);
+ printf("\nATCmdParser: Retrieving FW version success");
+ } else {
+ printf("\nATCmdParser: Retrieving FW version failed");
+ return -1;
+ }
+
+ printf("\nDone\n");
+
+
+ //eventQueue.dispatch_forever();
+ //t.start(callback(&eventQueue, &EventQueue::dispatch_forever));
+ //eventQueue2.dispatch_forever();
+
+ return 0;
+
+
+
+
+ //wait(osWaitForever);
+}
+
+#endif
--- a/source/main.cpp Fri Nov 16 16:45:32 2018 +0000
+++ b/source/main.cpp Thu Feb 28 18:13:48 2019 +0000
@@ -13,18 +13,26 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-
+#ifdef false
#include <events/mbed_events.h>
#include <mbed.h>
#include "ble/BLE.h"
#include "LEDService.h"
+#include "ble/services/UARTService.h"
+
+UARTService *uart;
DigitalOut alivenessLED(LED1, 0);
DigitalOut actuatedLED(LED2, 0);
-
-const static char DEVICE_NAME[] = "LED";
+RawSerial pc(USBTX, USBRX); // tx, rx
+const static char DEVICE_NAME[] = "BLE-UART";
static const uint16_t uuid16_list[] = {LEDService::LED_SERVICE_UUID};
-
+#define BUFFER_LEN 256
+#define TX_BUFFER_LEN 4*256
+#define RX_BUFFER_LEN 4*256
+char buffer[BUFFER_LEN];
+uint8_t TxBuffer[TX_BUFFER_LEN];
+uint8_t RxBuffer[RX_BUFFER_LEN];
static EventQueue eventQueue(/* event count */ 10 * EVENTS_EVENT_SIZE);
LEDService *ledServicePtr;
@@ -40,6 +48,13 @@
alivenessLED = !alivenessLED; /* Do blinky on LED1 to indicate system aliveness. */
}
+void EchoBleUartReceived()
+{
+ uart->writeString(buffer);
+ uart->writeString("\n"); //flushes uart output buffer and sends data
+}
+
+
/**
* This callback allows the LEDService to receive updates to the ledState Characteristic.
*
@@ -50,8 +65,31 @@
if ((params->handle == ledServicePtr->getValueHandle()) && (params->len == 1)) {
actuatedLED = *(params->data);
}
+ else if ((uart != NULL) && (params->handle == uart->getTXCharacteristicHandle())) {
+ uint16_t bytesRead = params->len;
+
+ pc.printf("received %u bytes\n\r ", bytesRead);
+
+ if(bytesRead >= 255){
+ pc.printf("Overflow command %u n\r ", bytesRead);
+ bytesRead = 255;
+ }
+
+ unsigned index = 0;
+ for (; index < bytesRead; index++) {
+ buffer[index] = params->data[index];
+ }
+
+ buffer[index++] = 0;
+
+ pc.printf("Data : %s ",buffer);
+ pc.printf("\r\n");
+ eventQueue.call(EchoBleUartReceived);
+
+ }
}
+
/**
* This function is called when the ble initialization process has failled
*/
@@ -66,11 +104,11 @@
Gap::AddressType_t addr_type;
Gap::Address_t address;
BLE::Instance().gap().getAddress(&addr_type, address);
- printf("DEVICE MAC ADDRESS: ");
+ pc.printf("DEVICE MAC ADDRESS: ");
for (int i = 5; i >= 1; i--){
- printf("%02x:", address[i]);
+ pc.printf("%02x:", address[i]);
}
- printf("%02x\r\n", address[0]);
+ pc.printf("%02x\r\n", address[0]);
}
/**
@@ -80,7 +118,6 @@
{
BLE& ble = params->ble;
ble_error_t error = params->error;
-
if (error != BLE_ERROR_NONE) {
/* In case of error, forward the error handling to onBleInitError */
onBleInitError(ble, error);
@@ -97,11 +134,21 @@
bool initialValueForLEDCharacteristic = false;
ledServicePtr = new LEDService(ble, initialValueForLEDCharacteristic);
+ /* Setup primary service */
+ uart = new UARTService(ble);
+ /* setup security */
+ error = ble.securityManager().init();
+ if(error != BLE_ERROR_NONE)
+ {
+ pc.printf("\nBLE Security manager initialization failed!!\n");
+ }
/* setup advertising */
ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
- ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list));
+ //ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, (uint8_t *)uuid16_list, sizeof(uuid16_list));
ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME));
+ /* set up the services that can be discovered */
+ ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS,(const uint8_t *)UARTServiceUUID_reversed, sizeof(UARTServiceUUID_reversed));
ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
ble.gap().setAdvertisingInterval(1000); /* 1000ms. */
ble.gap().startAdvertising();
@@ -114,15 +161,143 @@
eventQueue.call(Callback<void()>(&ble, &BLE::processEvents));
}
+static int uartExpectedRcvCount = 0;
+static int uartCharRcvCount = 0;
+static bool UartBusy = false;
+int WriteUartBytes(const uint8_t * txBuffer, size_t bufSize, int txLen)
+{
+ if(txLen > bufSize)
+ {
+ txLen = bufSize;
+ }
+ for(int i=0;i<txLen;i++)
+ {
+ pc.putc(txBuffer[i]);
+ }
+ // return number of bytes written to UART
+ return txLen;
+}
+
+void UartRxcallback_ex() {
+ if(uartCharRcvCount >= uartExpectedRcvCount)
+ {
+ int x = pc.getc();
+ return;
+ }
+ if(uartCharRcvCount == 0)
+ {
+ pc.printf("\nFirst Call to UART attach callback!!\n");
+ }
+ // Note: you need to actually read from the serial to clear the RX interrupt
+ RxBuffer[uartCharRcvCount] = (uint8_t) pc.getc();
+ uartCharRcvCount++;
+ if(uartCharRcvCount >= uartExpectedRcvCount)
+ {
+ alivenessLED = !alivenessLED; /* Do blinky on LED1 to indicate system aliveness. */
+ pc.printf("\nNumber of Received Bytes = %d\n\n", uartCharRcvCount);
+ pc.printf("--- Writing back received bytes --- \n");
+ int n;
+ n = WriteUartBytes(RxBuffer, TX_BUFFER_LEN, uartCharRcvCount);
+ UartBusy = false;
+ }
+}
+
+void BackGndUartRead(uint8_t * rxBuffer, size_t bufSize, int rxLen)
+{
+ UartBusy = true;
+ pc.printf("Setting up background UART read - rxLen = %d\n", rxLen);
+ uartCharRcvCount = 0;
+ if(rxLen > bufSize)
+ {
+ rxLen = bufSize;
+ }
+ uartExpectedRcvCount = rxLen;
+ pc.attach(&UartRxcallback_ex);
+ pc.printf("\nBackground UART read setup completed\n\n");
+ //for(int i=0;i<rxLen;i++)
+ //{
+ // rxBuffer[i] = (uint8_t) pc.getc();
+ //}
+ // return number of bytes written to UART
+ //return rxLen;
+}
+
+int ReadUartBytes(uint8_t * rxBuffer, size_t bufSize, int rxLen, bool echo)
+{
+ UartBusy = true;
+ if(rxLen > bufSize)
+ {
+ rxLen = bufSize;
+ }
+ for(int i=0;i<rxLen;i++)
+ {
+ rxBuffer[i] = (uint8_t) pc.getc();
+ if(echo)pc.putc(rxBuffer[i]);
+ }
+ UartBusy = false;
+ //return number of bytes written to UART
+ return rxLen;
+}
+
+
+void checkUartReceive()
+{
+ //pc.printf("Hello World!\n\r");
+ char cbuf[100];
+ int rxCnt=0;
+ while(pc.readable()) {
+ //pc.printf("uartCharRcvCount = %d\n\r", uartCharRcvCount++);
+ cbuf[rxCnt++] = pc.getc();
+ //pc.putc(pc.getc() + 1); // echo input back to terminal
+ }
+ cbuf[rxCnt] = NULL;
+ if(rxCnt > 0)
+ {
+ pc.printf("received %d chars\n", rxCnt);
+ pc.printf("%s\n", cbuf);
+ }
+
+}
+uint64_t lastTime = 0;
+uint64_t now = 0;
+uint32_t callCount = 0;
+void HelloUart()
+{
+ //if(UartBusy)return;
+ // 64-bit time doesn't wrap for half a billion years, at least
+ lastTime = now;
+ now = Kernel::get_ms_count();
+ callCount++;
+ pc.printf("\nHello : %d secs elapsed : CallCount = %d \n", uint32_t(now - lastTime), callCount);
+}
+
+Thread t;
int main()
{
+ pc.baud(115200);
eventQueue.call_every(500, blinkCallback);
+ eventQueue.call_every(60000, HelloUart);
+ //eventQueue.call_every(1000, checkUartReceive);
BLE &ble = BLE::Instance();
ble.onEventsToProcess(scheduleBleEventsProcessing);
ble.init(bleInitComplete);
-
- eventQueue.dispatch_forever();
-
+ for(int i=0;i<255;i++)
+ {
+ pc.putc(i);
+ }
+ int n;
+ //ReadUartBytes(RxBuffer, RX_BUFFER_LEN, 4);
+ pc.printf("\n\n\nEnter # of expected bytes: ");
+ n = ReadUartBytes(RxBuffer, RX_BUFFER_LEN, 4, true);
+ int rxLen = (int) 100*(RxBuffer[0]-'0') + 10*(RxBuffer[1]-'0') + (RxBuffer[0]-'0');
+ pc.printf("\n\nExpected # of Received Bytes = %d\n", rxLen);
+ BackGndUartRead(RxBuffer, RX_BUFFER_LEN, rxLen);
+ //pc.printf("--- Writing back received data --- \n\n");
+ //n = WriteUartBytes(RxBuffer, TX_BUFFER_LEN, rxLen);
+ //pc.write("\n\ntesting Serial Write\n", 40); //, checkUartReceive, SERIAL_EVENT_TX_COMPLETE);
+ //eventQueue.dispatch_forever();
+ t.start(callback(&eventQueue, &EventQueue::dispatch_forever));
return 0;
}
+#endif
\ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/source/network-helper.h Thu Feb 28 18:13:48 2019 +0000
@@ -0,0 +1,110 @@
+#ifndef _MBED_HTTP_EXAMPLE_H_
+#define _MBED_HTTP_EXAMPLE_H_
+
+#include "mbed.h"
+#ifdef TARGET_SIMULATOR
+#include "EthernetInterface.h"
+#endif
+
+
+const char * sec2str(nsapi_security_t sec)
+{
+ switch (sec) {
+ case NSAPI_SECURITY_NONE:
+ return "None";
+ case NSAPI_SECURITY_WEP:
+ return "WEP";
+ case NSAPI_SECURITY_WPA:
+ return "WPA";
+ case NSAPI_SECURITY_WPA2:
+ return "WPA2";
+ case NSAPI_SECURITY_WPA_WPA2:
+ return "WPA/WPA2";
+ case NSAPI_SECURITY_UNKNOWN:
+ default:
+ return "Unknown";
+ }
+}
+
+int scan_demo(WiFiInterface *wifi)
+{
+ WiFiAccessPoint *ap;
+
+ printf("Scan:\n");
+
+ int count = wifi->scan(NULL,0);
+
+ if (count <= 0) {
+ printf("scan() failed with return value: %d\n", count);
+ return 0;
+ }
+
+ /* Limit number of network arbitrary to 15 */
+ count = count < 15 ? count : 15;
+
+ ap = new WiFiAccessPoint[count];
+ count = wifi->scan(ap, count);
+
+ if (count <= 0) {
+ printf("scan() failed with return value: %d\n", count);
+ return 0;
+ }
+
+ for (int i = 0; i < count; i++) {
+ printf("Network: %s secured: %s BSSID: %hhX:%hhX:%hhX:%hhx:%hhx:%hhx RSSI: %hhd Ch: %hhd\n", ap[i].get_ssid(),
+ sec2str(ap[i].get_security()), ap[i].get_bssid()[0], ap[i].get_bssid()[1], ap[i].get_bssid()[2],
+ ap[i].get_bssid()[3], ap[i].get_bssid()[4], ap[i].get_bssid()[5], ap[i].get_rssi(), ap[i].get_channel());
+ }
+ printf("%d networks available.\n", count);
+
+ delete[] ap;
+ return count;
+}
+
+
+/**
+ * Connect to the network using the default networking interface,
+ * you can also swap this out with a driver for a different networking interface
+ * if you use WiFi: see mbed_app.json for the credentials
+ */
+NetworkInterface *connect_to_default_network_interface() {
+ printf("[NWKH] Connecting to network...\n");
+
+#ifdef TARGET_SIMULATOR
+ NetworkInterface* network = new EthernetInterface();
+#else
+ //NetworkInterface* network = NetworkInterface::get_default_instance();
+ WiFiInterface *network = WiFiInterface::get_default_instance();
+ if (!network) {
+ printf("ERROR: No WiFiInterface found.\n");
+ return NULL;
+ }
+ int count;
+ count = scan_demo(network);
+ if (count == 0) {
+ printf("No WIFI APNs found - can't continue further.\n");
+ return NULL;
+ }
+
+ //printf("\nConnecting to %s...\n", MBED_CONF_APP_WIFI_SSID);
+ //ret = network->connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2);
+ //if (ret != 0) {
+ // printf("\nConnection error: %d\n", ret);
+ // return -1;
+ //}
+#endif
+
+ //nsapi_error_t connect_status = network->connect();
+ nsapi_error_t connect_status = network->connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2);
+
+ if (connect_status != NSAPI_ERROR_OK) {
+ printf("[NWKH] Failed to connect to network (%d)\n", connect_status);
+ return NULL;
+ }
+
+ printf("[NWKH] Connected to the network\n");
+ printf("[NWKH] IP address: %s\n", network->get_ip_address());
+ return network;
+}
+
+#endif // _MBED_HTTP_EXAMPLE_H_
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/source/select-demo.h Thu Feb 28 18:13:48 2019 +0000 @@ -0,0 +1,13 @@ +#ifndef _SELECT_METHOD_H_ +#define _SELECT_METHOD_H_ + +#define DEMO_HTTP 1 +#define DEMO_HTTP_SOCKET_REUSE 2 +#define DEMO_HTTP_IPV6 3 +#define DEMO_HTTPS 4 +#define DEMO_HTTPS_SOCKET_REUSE 5 +#define DEMO_HTTPS_CHUNKED_REQUEST 6 + +#define DEMO DEMO_HTTPS + +#endif // _SELECT_METHOD_H_