Sailesh Timilsena / Mbed OS Z_IOT_ResearchWork

Dependencies:   X_NUCLEO_COMMON ST_INTERFACES

Files at this revision

API Documentation at this revision

Comitter:
adustm
Date:
Fri Jul 06 11:44:19 2018 +0200
Parent:
3:9f646544d302
Child:
5:8d7b1da4f6fa
Commit message:
Update for public cloud client version

Changed in this revision

main.cpp Show annotated file Show diff for this revision Revisions of this file
mbed_app.json Show annotated file Show diff for this revision Revisions of this file
mbed_cloud_client_user_config.h Show annotated file Show diff for this revision Revisions of this file
mbed_cloud_dev_credentials.c Show annotated file Show diff for this revision Revisions of this file
update_default_resources.c Show annotated file Show diff for this revision Revisions of this file
--- a/main.cpp	Fri Jul 06 11:43:01 2018 +0200
+++ b/main.cpp	Fri Jul 06 11:44:19 2018 +0200
@@ -1,5 +1,5 @@
 // ----------------------------------------------------------------------------
-// Copyright 2016-2017 ARM Ltd.
+// Copyright 2016-2018 ARM Ltd.
 //
 // SPDX-License-Identifier: Apache-2.0
 //
@@ -17,151 +17,142 @@
 // ----------------------------------------------------------------------------
 
 #include "mbed.h"
-#include "mbed-trace/mbed_trace.h"
-#include "mbed-trace-helper.h"
 #include "simple-mbed-cloud-client.h"
-#include "key-config-manager/kcm_status.h"
-#include "key-config-manager/key_config_manager.h"
 #include "SDBlockDevice.h"
 #include "FATFileSystem.h"
 #include "ISM43362Interface.h"
 
-// Placeholder to hardware that trigger events (timer, button, etc)
-Ticker timer;
+// An event queue is a very useful structure to debounce information between contexts (e.g. ISR and normal threads)
+// This is great because things such as network operations are illegal in ISR, so updating a resource in a button's fall() function is not allowed
+EventQueue eventQueue;
 
-// Placeholder for storage
+// Storage implementation definition, currently using SDBlockDevice (SPI flash, DataFlash, and internal flash are also available)
 SDBlockDevice sd(SPI_MOSI, SPI_MISO, SPI_SCK, SPI_CS);
-FATFileSystem fs("sd");
+FATFileSystem fs("sd", &sd);
+
+// Declaring net interface as a global variable instead of local to avoid stack overflow
+ISM43362Interface net;
 
-// Pointers to the resources that will be created in main_application().
-static MbedCloudClientResource* pattern_ptr;
+// Declaring pointers for access to Mbed Cloud Client resources outside of main()
+MbedCloudClientResource *button_res;
+MbedCloudClientResource *pattern_res;
 
-// Pointer to mbedClient, used for calling close function.
-static SimpleMbedCloudClient *client;
+// This function gets triggered by the timer. It's easy to replace it by an InterruptIn and fall() mode on a real button
+void fake_button_press() {
+    int v = button_res->get_value_int() + 1;
 
-static bool button_pressed = false;
+    button_res->set_value(v);
 
-void button_press() {
-    button_pressed = true;
+    printf("Simulated button clicked %d times\n", v);
 }
 
-void pattern_updated(const char *) {
-    printf("PUT received, new value: %s\n", pattern_ptr->get_value().c_str());
-    // Placeholder for PUT action
+/**
+ * PUT handler
+ * @param resource The resource that triggered the callback
+ * @param newValue Updated value for the resource
+ */
+void pattern_updated(MbedCloudClientResource *resource, m2m::String newValue) {
+    printf("PUT received, new value: %s\n", newValue.c_str());
 }
 
-void blink_callback(void *) {
-    String pattern_str = pattern_ptr->get_value();
-    const char *pattern = pattern_str.c_str();
-    printf("POST received. LED pattern = %s\n", pattern);
-    // Placeholder for POST action
-    // The pattern is something like 500:200:500, so parse that.
-}
+/**
+ * POST handler
+ * @param resource The resource that triggered the callback
+ * @param buffer If a body was passed to the POST function, this contains the data.
+ *               Note that the buffer is deallocated after leaving this function, so copy it if you need it longer.
+ * @param size Size of the body
+ */
+void blink_callback(MbedCloudClientResource *resource, const uint8_t *buffer, uint16_t size) {
+    printf("POST received. Going to blink LED pattern: %s\n", pattern_res->get_value().c_str());
+
+    static DigitalOut augmentedLed(LED1); // LED that is used for blinking the pattern
 
-void button_callback(const M2MBase& object, const NoticationDeliveryStatus status)
-{
-    printf("Button notification. Callback: (%s)\n", object.uri_path());
-    // Placeholder for GET
+    // Parse the pattern string, and toggle the LED in that pattern
+    string s = std::string(pattern_res->get_value().c_str());
+    size_t i = 0;
+    size_t pos = s.find(':');
+    while (pos != string::npos) {
+        wait_ms(atoi(s.substr(i, pos - i).c_str()));
+        augmentedLed = !augmentedLed;
+
+        i = ++pos;
+        pos = s.find(':', pos);
+
+        if (pos == string::npos) {
+            wait_ms(atoi(s.substr(i, s.length()).c_str()));
+            augmentedLed = !augmentedLed;
+        }
+    }
 }
 
-
-int main(void)
-{
-    // Requires DAPLink 245+ (https://github.com/ARMmbed/DAPLink/pull/364)
-    // Older versions: workaround to prevent possible deletion of credentials:
-    wait(2);
-
-    // Misc OS setup
-    srand(time(NULL));
+/**
+ * Notification callback handler
+ * @param resource The resource that triggered the callback
+ * @param status The delivery status of the notification
+ */
+void button_callback(MbedCloudClientResource *resource, const NoticationDeliveryStatus status) {
+    printf("Button notification, status %s (%d)\n", MbedCloudClientResource::delivery_status_to_string(status), status);
+}
 
-    // Placeholder for network
-    printf("Start Simple Mbed Cloud Client\n");
-    ISM43362Interface net(MBED_CONF_APP_WIFI_SPI_MOSI, MBED_CONF_APP_WIFI_SPI_MISO, MBED_CONF_APP_WIFI_SPI_SCLK, MBED_CONF_APP_WIFI_SPI_NSS, MBED_CONF_APP_WIFI_RESET, MBED_CONF_APP_WIFI_DATAREADY, MBED_CONF_APP_WIFI_WAKEUP, false);
-
+/**
+ * Registration callback handler
+ * @param endpoint Information about the registered endpoint such as the name (so you can find it back in portal)
+ */
+void registered(const ConnectorClientEndpointInfo *endpoint) {
+    printf("Connected to Mbed Cloud. Endpoint Name: %s\n", endpoint->internal_endpoint_name.c_str());
+}
 
-    // Initialize SD card
-    int status = sd.init();
-    if (status != BD_ERROR_OK) {
-        printf("Failed to init SD card\r\n");
+int main(void) {
+    printf("Starting Simple Mbed Cloud Client example\n");
+    printf("Connecting to the network using Wifi...\n");
+
+    // Connect to the internet (DHCP is expected to be on)
+    nsapi_error_t status = net.connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, (strlen(MBED_CONF_APP_WIFI_PASSWORD) > 1) ? NSAPI_SECURITY_WPA_WPA2 : NSAPI_SECURITY_NONE);
+
+    if (status != 0) {
+        printf("Connecting to the network failed %d!\n", status);
         return -1;
     }
 
-    // Mount the file system (reformatting on failure)
-    status = fs.mount(&sd);
-    if (status) {
-        printf("Failed to mount FAT file system, reformatting...\r\n");
-        status = fs.reformat(&sd);
-        if (status) {
-            printf("Failed to reformat FAT file system\r\n");
-            return -1;
-        } else {
-            printf("Reformat and mount complete\r\n");
-        }
-    }
-
-    printf("Connecting to the network using Wifi...\n");
+    printf("Connected to the network successfully. IP address: %s\n", net.get_ip_address());
 
-    status = net.connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, (strlen(MBED_CONF_APP_WIFI_PASSWORD) > 1) ? NSAPI_SECURITY_WPA_WPA2 : NSAPI_SECURITY_NONE);
-    if (status) {
-        printf("Connection to Network Failed %d!\n", status);
-        return -1;
-    } else {
-        const char *ip_addr  = net.get_ip_address();
-        printf("Connected successfully\n");
-        printf("IP address %s\n", ip_addr);
-    }
-
-    SimpleMbedCloudClient mbedClient(&net);
-    // Save pointer to mbedClient so that other functions can access it.
-    client = &mbedClient;
-
-    status = mbedClient.init();
-    if (status) {
-        printf("FAILED\r\n");
+    // SimpleMbedCloudClient handles registering over LwM2M to Mbed Cloud
+    SimpleMbedCloudClient client(&net, &sd, &fs);
+    int client_status = client.init();
+    if (client_status != 0) {
+        printf("Initializing Mbed Cloud Client failed (%d)\n", client_status);
         return -1;
     }
 
-    printf("Client initialized\r\n");
+    // Creating resources, which can be written or read from the cloud
+    button_res = client.create_resource("3200/0/5501", "button_count");
+    button_res->set_value(0);
+    button_res->methods(M2MMethod::GET);
+    button_res->observable(true);
+    button_res->attach_notification_callback(button_callback);
 
-    // Mbed Cloud Client resource setup
-    MbedCloudClientResource *button = mbedClient.create_resource("3200/0/5501", "button_resource");
-    button->set_value("0");
-    button->methods(M2MMethod::GET);
-    button->observable(true);
-    button->attach_notification_callback(button_callback);
+    pattern_res = client.create_resource("3201/0/5853", "blink_pattern");
+    pattern_res->set_value("500:500:500:500:500:500:500:500");
+    pattern_res->methods(M2MMethod::GET | M2MMethod::PUT);
+    pattern_res->attach_put_callback(pattern_updated);
 
-    MbedCloudClientResource *pattern = mbedClient.create_resource("3201/0/5853", "pattern_resource");
-    pattern->set_value("500:500:500:500");
-    pattern->methods(M2MMethod::GET | M2MMethod::PUT);
-    pattern->attach_put_callback(pattern_updated);
-    pattern_ptr = pattern;
+    MbedCloudClientResource *blink_res = client.create_resource("3201/0/5850", "blink_action");
+    blink_res->methods(M2MMethod::POST);
+    blink_res->attach_post_callback(blink_callback);
+
+    printf("Initialized Mbed Cloud Client. Registering...\n");
 
-    MbedCloudClientResource *blink = mbedClient.create_resource("3201/0/5850", "blink_resource");
-    blink->methods(M2MMethod::POST);
-    blink->attach_post_callback(blink_callback);
+    // Callback that fires when registering is complete
+    client.on_registered(&registered);
 
-    mbedClient.register_and_connect();
-
-    // Wait for client to finish registering
-    while (!mbedClient.is_client_registered()) {
-        wait_ms(100);
-    }
+    // Register with Mbed Cloud
+    client.register_and_connect();
 
     // Placeholder for callback to update local resource when GET comes.
-    timer.attach(&button_press, 5.0);
-
-    // Check if client is registering or registered, if true sleep and repeat.
-    while (mbedClient.is_register_called()) {
-        static int button_count = 0;
-        wait_ms(100);
+    // The timer fires on an interrupt context, but debounces it to the eventqueue, so it's safe to do network operations
+    Ticker timer;
+    timer.attach(eventQueue.event(&fake_button_press), 5.0);
 
-        if (button_pressed) {
-            button_pressed = false;
-            printf("Simulated button clicked %d times\r\n", ++button_count);
-            button->set_value(button_count);
-        }
-    }
-
-    // Client unregistered, exit program.
-    return 0;
+    // You can easily run the eventQueue in a separate thread if required
+    eventQueue.dispatch_forever();
 }
--- a/mbed_app.json	Fri Jul 06 11:43:01 2018 +0200
+++ b/mbed_app.json	Fri Jul 06 11:44:19 2018 +0200
@@ -1,20 +1,37 @@
 {
     "macros": [
         "MBEDTLS_USER_CONFIG_FILE=\"mbedTLSConfig_mbedOS.h\"",
+        "PAL_USER_DEFINED_CONFIGURATION=\"sotp_fs_config_MbedOS.h\"",
         "MBED_CLIENT_USER_CONFIG_FILE=\"mbed_cloud_client_user_config.h\"",
         "MBED_CLOUD_CLIENT_USER_CONFIG_FILE=\"mbed_cloud_client_user_config.h\"",
         "PAL_DTLS_PEER_MIN_TIMEOUT=5000",
-        "MBED_CONF_APP_MAIN_STACK_SIZE=6000",
-        "MBED_CONF_APP_THREAD_STACK_SIZE=6000"
+        "MBED_CONF_APP_MAIN_STACK_SIZE=4608",
+        "ARM_UC_USE_PAL_BLOCKDEVICE=1",
+        "MBED_CLOUD_CLIENT_UPDATE_STORAGE=ARM_UCP_FLASHIAP_BLOCKDEVICE"
     ],
     "target_overrides": {
         "*": {
             "platform.stdio-baud-rate": 115200,
             "platform.stdio-convert-newlines": true,
+            "update-client.storage-address"  : "(1024*1024*64)",
+            "update-client.storage-size"     : "(1024*1024*2)",
+            "update-client.storage-locations": "1",
             "mbed-trace.enable": null
+        },
+        "DISCO_L475VG_IOT01A": {
+            "sotp-section-1-address"           : "(0x08000000+((1024-32)*1024))",
+            "sotp-section-1-size"              : "(16*1024)",
+            "sotp-section-2-address"           : "(0x08000000+((1024-16)*1024))",
+            "sotp-section-2-size"              : "(16*1024)",
+            "sotp-num-sections"                : 2
         }
+
     },
     "config": {
+        "format-storage-layer-on-error": {
+            "help": "Whether to format the storage layer when it cannot be read - always disable for production devices!",
+            "value": 1
+        },
         "developer-mode": {
             "help": "Enable Developer mode to skip Factory enrollment",
             "value": 1
@@ -27,41 +44,30 @@
             "help": "WiFi Password",
             "value": "\"PASSWORD\""
         },
-        "wifi-tx": {
-            "help": "TX pin for serial connection to external device",
-            "value": "D1"
-        },
-        "wifi-rx": {
-            "help": "RX pin for serial connection to external device",
-            "value": "D0"
+        "sotp-section-1-address": {
+            "help": "Flash sector address for SOTP sector 1",
+            "macro_name": "PAL_INTERNAL_FLASH_SECTION_1_ADDRESS",
+            "value": null
         },
-        "wifi-spi_miso": {
-            "help": "SPI-MISO connection to external device",
-            "value": "PC_11"
-        },
-        "wifi-spi_mosi": {
-            "help": "SPI-MOSI connection to external device",
-            "value": "PC_12"
+        "sotp-section-1-size": {
+            "help": "Flash sector size for SOTP sector 1",
+            "macro_name": "PAL_INTERNAL_FLASH_SECTION_1_SIZE",
+            "value": null
         },
-        "wifi-spi_sclk": {
-            "help": "SPI-CLOCK connection to external device",
-            "value": "PC_10"
-        },
-        "wifi-spi_nss": {
-            "help": "SPI chip select of external device",
-            "value": "PE_0"
+        "sotp-section-2-address": {
+            "help": "Flash sector address for SOTP sector 2",
+            "macro_name": "PAL_INTERNAL_FLASH_SECTION_2_ADDRESS",
+            "value": null
         },
-        "wifi-reset": {
-            "help": "WIFI module reset pin",
-            "value": "PE_8"
+        "sotp-section-2-size": {
+            "help": "Flash sector size for SOTP sector 2",
+            "macro_name": "PAL_INTERNAL_FLASH_SECTION_2_SIZE",
+            "value": null
         },
-        "wifi-dataready": {
-            "help": "WIFI module data ready pin",
-            "value": "PE_1"
-        },
-        "wifi-wakeup": {
-            "help": "WIFI module wakeup pin",
-            "value": "PB_12"
+        "sotp-num-sections": {
+            "help": "Number of SOTP sections",
+            "macro_name": "PAL_INT_FLASH_NUM_SECTIONS",
+            "value": null
         }
     }
 }
--- a/mbed_cloud_client_user_config.h	Fri Jul 06 11:43:01 2018 +0200
+++ b/mbed_cloud_client_user_config.h	Fri Jul 06 11:44:19 2018 +0200
@@ -22,8 +22,11 @@
 #ifndef MBED_CLOUD_CLIENT_USER_CONFIG_H
 #define MBED_CLOUD_CLIENT_USER_CONFIG_H
 
-
+#ifdef MBED_CONF_APP_ENDPOINT_TYPE
+#define MBED_CLOUD_CLIENT_ENDPOINT_TYPE         MBED_CONF_APP_ENDPOINT_TYPE
+#else
 #define MBED_CLOUD_CLIENT_ENDPOINT_TYPE         "default"
+#endif
 
 // Enable either TCP or UDP, but no both
 #define MBED_CLOUD_CLIENT_TRANSPORT_MODE_TCP
--- a/mbed_cloud_dev_credentials.c	Fri Jul 06 11:43:01 2018 +0200
+++ b/mbed_cloud_dev_credentials.c	Fri Jul 06 11:44:19 2018 +0200
@@ -15,40 +15,39 @@
  */
 #ifndef __MBED_CLOUD_DEV_CREDENTIALS_H__
 #define __MBED_CLOUD_DEV_CREDENTIALS_H__
- 
+
 #if MBED_CONF_APP_DEVELOPER_MODE == 1
 #error "Replace mbed_cloud_dev_credentials.c with your own developer cert."
 #endif
- 
+
 #include <inttypes.h>
- 
+
 const char MBED_CLOUD_DEV_BOOTSTRAP_ENDPOINT_NAME[] = "";
 const char MBED_CLOUD_DEV_ACCOUNT_ID[] = "";
 const char MBED_CLOUD_DEV_BOOTSTRAP_SERVER_URI[] = "";
- 
+
 const uint8_t MBED_CLOUD_DEV_BOOTSTRAP_DEVICE_CERTIFICATE[] =
 { 0x0 };
- 
+
 const uint8_t MBED_CLOUD_DEV_BOOTSTRAP_SERVER_ROOT_CA_CERTIFICATE[] =
 { 0x0 };
- 
+
 const uint8_t MBED_CLOUD_DEV_BOOTSTRAP_DEVICE_PRIVATE_KEY[] =
 { 0x0 };
- 
+
 const char MBED_CLOUD_DEV_MANUFACTURER[] = "dev_manufacturer";
- 
+
 const char MBED_CLOUD_DEV_MODEL_NUMBER[] = "dev_model_num";
- 
+
 const char MBED_CLOUD_DEV_SERIAL_NUMBER[] = "0";
- 
+
 const char MBED_CLOUD_DEV_DEVICE_TYPE[] = "dev_device_type";
- 
+
 const char MBED_CLOUD_DEV_HARDWARE_VERSION[] = "dev_hardware_version";
- 
+
 const uint32_t MBED_CLOUD_DEV_MEMORY_TOTAL_KB = 0;
 const uint32_t MBED_CLOUD_DEV_BOOTSTRAP_DEVICE_CERTIFICATE_SIZE = sizeof(MBED_CLOUD_DEV_BOOTSTRAP_DEVICE_CERTIFICATE);
 const uint32_t MBED_CLOUD_DEV_BOOTSTRAP_SERVER_ROOT_CA_CERTIFICATE_SIZE = sizeof(MBED_CLOUD_DEV_BOOTSTRAP_SERVER_ROOT_CA_CERTIFICATE);
 const uint32_t MBED_CLOUD_DEV_BOOTSTRAP_DEVICE_PRIVATE_KEY_SIZE = sizeof(MBED_CLOUD_DEV_BOOTSTRAP_DEVICE_PRIVATE_KEY);
- 
+
 #endif //__MBED_CLOUD_DEV_CREDENTIALS_H__
- 
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/update_default_resources.c	Fri Jul 06 11:44:19 2018 +0200
@@ -0,0 +1,41 @@
+// ----------------------------------------------------------------------------
+// Copyright 2016-2018 ARM Ltd.
+//
+// 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.
+// ----------------------------------------------------------------------------
+
+#ifdef MBED_CLOUD_CLIENT_USER_CONFIG_FILE
+#include MBED_CLOUD_CLIENT_USER_CONFIG_FILE
+#endif
+
+#include <stdint.h>
+
+#ifdef MBED_CLOUD_DEV_UPDATE_ID
+const uint8_t arm_uc_vendor_id[16] = { "dev_manufacturer" };
+const uint16_t arm_uc_vendor_id_size = sizeof(arm_uc_vendor_id);
+
+const uint8_t arm_uc_class_id[16]  = { "dev_model_number" };
+const uint16_t arm_uc_class_id_size = sizeof(arm_uc_class_id);
+#endif
+
+#ifdef MBED_CLOUD_DEV_UPDATE_CERT
+const uint8_t arm_uc_default_fingerprint[32] = { 0 };
+const uint16_t arm_uc_default_fingerprint_size =
+    sizeof(arm_uc_default_fingerprint);
+
+const uint8_t arm_uc_default_certificate[1] = { 0 };
+const uint16_t arm_uc_default_certificate_size =
+    sizeof(arm_uc_default_certificate);
+#endif