├── clicks.png ├── LICENSE ├── module.json ├── .gitignore ├── README.md ├── apache-2.0.txt └── source ├── main.cpp └── simpleclient.h /clicks.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ARMmbed/mbed-client-quickstart/HEAD/clicks.png -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Unless specifically indicated otherwise in a file, files are licensed 2 | under the Apache 2.0 license, as can be found in: apache-2.0.txt -------------------------------------------------------------------------------- /module.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mbed-client-quickstart", 3 | "version": "1.1.0", 4 | "description": "mbed Client Example for mbed", 5 | "keywords": [ 6 | "mbed-client" 7 | ], 8 | "author": "yogesh.pande@arm.com", 9 | "license": "Apache-2.0", 10 | "extraIncludes": [], 11 | "dependencies": { 12 | "mbed-client": "^1.0.0", 13 | "mbed-trace": "^1.0.0" 14 | }, 15 | "targetDependencies": {}, 16 | "bin": "./source/" 17 | } 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Object files 2 | *.o 3 | *.ko 4 | *.obj 5 | *.elf 6 | 7 | # Precompiled Headers 8 | *.gch 9 | *.pch 10 | 11 | # Libraries 12 | *.lib 13 | *.a 14 | *.la 15 | *.lo 16 | 17 | # Shared objects (inc. Windows DLLs) 18 | *.dll 19 | *.so 20 | *.so.* 21 | *.dylib 22 | 23 | # Executables 24 | *.exe 25 | *.out 26 | *.app 27 | *.i*86 28 | *.x86_64 29 | *.hex 30 | 31 | yotta_modules/ 32 | yotta_targets/ 33 | build/ 34 | .yotta.json 35 | source/security.h 36 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **THIS EXAMPLE IS DEPRECATED AND IS SUPERCEDED BY ANOTHER EXAMPLE AVAILABLE HERE [mbed-os-example-client](https://github.com/ARMmbed/mbed-os-example-client)** 2 | 3 | # Getting started with mbed Client on mbed OS 4 | 5 | This is the mbed Client example for mbed OS (we also have one for [Linux](https://github.com/ARMmbed/mbed-client-linux-example)). It demonstrates how to register a device with mbed Device Connector, how to read and write values, and how to deregister. If you are unfamiliar with mbed Device Connector, we recommend that you read [the introduction to the data model](https://docs.mbed.com/docs/mbed-device-connector-web-interfaces/en/latest/#the-mbed-device-connector-data-model) first. 6 | 7 | The application: 8 | 9 | * Registers with mbed Device Connector. 10 | * Gives mbed Device Connector access to its resources (read and write). 11 | * Records the number of clicks on the device’s button and sends the number to mbed Device Connector. 12 | * Lets you control the blink pattern of the LED on the device (through mbed Device Connector). 13 | 14 | ## Required hardware 15 | 16 | * An [FRDM-K64F](http://developer.mbed.org/platforms/frdm-k64f/) board. 17 | * An Ethernet connection to the internet. 18 | * An Ethernet cable. 19 | * A micro-USB cable. 20 | 21 | ## Required software 22 | 23 | * An [ARM mbed account](https://developer.mbed.org/account/login/?next=/). 24 | * [yotta](http://docs.yottabuild.org/#installing) - to build the example programs. To learn how to build mbed OS applications with yotta, see [the user guide](https://docs.mbed.com/docs/getting-started-mbed-os/en/latest/Full_Guide/app_on_yotta/#building-an-application). 25 | * A [serial port monitor](https://developer.mbed.org/handbook/SerialPC#host-interface-and-terminal-applications). 26 | 27 | ## Setting up 28 | 29 | To set up the example, please: 30 | 31 | 1. [Build the example](#Building-the-example). 32 | 1. [Set up an IP address](#IP-address-setup). This step is optional. 33 | 1. [Set a socket type](#Setting-socket-type). This step is optional. 34 | 35 | ### Building the example 36 | 37 | To build the example application: 38 | 39 | 1. Clone [this](https://github.com/ARMmbed/mbed-client-examples) repository. 40 | 1. Go to [mbed Device Connector](https://connector.mbed.com) and log in with your mbed account. 41 | 1. On mbed Device Connector, go to [My Devices > Security credentials](https://connector.mbed.com/#credentials), and get new credentials for your device by clicking the **Get my device security credentials** button. 42 | 1. Store the credentials as `source/security.h` in this project's directory. 43 | 1. Open a command line tool and navigate to the project’s directory. 44 | 1. Set yotta's build target. For example, if you are targeting the FRDM-K64F board: `yotta target frdm-k64f-gcc`. 45 | 1. Build the application by using the command `yotta build`. yotta builds a binary file in the project’s directory. 46 | 1. Plug the Ethernet cable into the board. 47 | 1. Plug the micro-USB cable into the **OpenSDA** port. The board is listed as a mass-storage device. 48 | 1. Drag the binary `build/frdm-k64f-gcc/source/mbed-client-examples.bin` to the board to flash the application. 49 | 1. The board is automatically programmed with the new binary. A flashing LED on it indicates that it is still working. When the LED stops blinking, the board is ready to work. 50 | 1. Press the **RESET** button to run the program. 51 | 1. For verification, continue to the [Monitoring the application](#monitoring-the-application) chapter. 52 | 53 | ### IP address setup (optional) 54 | 55 | This example uses IPv4 to communicate with the [mbed Device Connector Server](https://api.connector.mbed.com). The example program should automatically get an IPv4 address from the router when connected over Ethernet. 56 | 57 | If your network does not have DHCP enabled, you have to manually assign a static IP address to the board. We recommend having DHCP enabled to make everything run smoothly. 58 | 59 | ### Changing socket type (binding mode - optional) 60 | 61 | Your device can connect to mbed Device Connector via one of two binding modes: UDP or TCP. The default is UDP. 62 | 63 | To change the binding mode: 64 | 65 | 1. In the `simpleclient.h` file, find the parameter `SOCKET_MODE`. 66 | 1. The default is `M2MInterface::UDP`. 67 | 1. To switch to TCP, change it to `M2MInterface::TCP`. 68 | 69 | Then re-build and flash the application. 70 | 71 | **Tip:** The instructions in this document remain the same, irrespective of the socket mode you select. 72 | 73 | ## Monitoring the application 74 | 75 | The application prints debug messages over the serial port, so you can monitor its activity with a serial port monitor. The application uses baud rate 115200. 76 | 77 | **Note:** Instructions to set this up are located [here](https://developer.mbed.org/handbook/SerialPC#host-interface-and-terminal-applications). 78 | 79 | After connecting you should see messages about connecting to mbed Device Connector: 80 | 81 | ``` 82 | In app_start() 83 | IP address 10.2.15.222 84 | Device name 6868df22-d353-4150-b90a-a878130859d9 85 | ``` 86 | 87 | **Note:** Device name is the endpoint name you will need later on [Testing the application](https://github.com/ARMmbed/mbed-client-quickstart#testing-the-application) chapter. 88 | 89 | After you click the `SW2` button on your board you should see messages about the value changes: 90 | 91 | ``` 92 | handle_button_click, new value of counter is 1 93 | ``` 94 | 95 | ## Testing the application 96 | 97 | 1. Flash the application. 98 | 1. Verify that the registration succeeded. You should see `Registered object successfully!` printed to the serial port. 99 | 1. On mbed Device Connector, go to [My devices > Connected devices](https://connector.mbed.com/#endpoints). Your device should be listed here. 100 | 1. Press the `SW2` button on the device a number of times (make a note of how many times you did that). 101 | 1. Go to [Device Connector > API Console](https://connector.mbed.com/#console). 102 | 1. Enter `https://api.connector.mbed.com/endpoints/DEVICE_NAME/3200/0/5501` in the URI field and click **TEST API**. Replace `DEVICE_NAME` with your actual endpoint name. The device name can be found in the `source/security.h` file, see variable `MBED_ENDPOINT_NAME` or it can be found from the traces [Monitoring the application](https://github.com/ARMmbed/mbed-client-quickstart#monitoring-the-application). 103 | 1. The number of times you pressed `SW2` is shown. 104 | 1. Press the `SW3` button to unregister from mbed Device Connector. You should see `Unregistered Object Successfully` printed to the serial port and LED starts blinking. 105 | This will also stop your application. Press the `RESET` button to run the program again. 106 | 107 | 108 | ![SW2 pressed five times, as shown by the API Console](clicks.png) 109 | 110 | **NOTE:** If you get an error, for example `Server Response: 410 (Gone)`, clear your browser's cache, log out, and log back in. 111 | **NOTE:** Only GET methods can be executed through [Device Connector > API Console](https://connector.mbed.com/#console). For the other methods check the [mbed Device Connector Quick Start](https://github.com/ARMmbed/mbed-connector-api-node-quickstart). 112 | 113 | ### Application resources 114 | 115 | The application exposes three [resources](https://docs.mbed.com/docs/mbed-device-connector-web-interfaces/en/latest/#the-mbed-device-connector-data-model): 116 | 117 | 1. `3200/0/5501`. Number of presses of SW2 (GET). 118 | 2. `3201/0/5850`. Blink function, blinks `LED1` when executed (POST). 119 | 3. `3201/0/5853`. Blink pattern, used by the blink function to determine how to blink. In the format of `1000:500:1000:500:1000:500` (PUT). 120 | 121 | For information on how to get notifications when resource 1 changes, or how to use resources 2 and 3, take a look at the [mbed Device Connector Quick Start](https://github.com/ARMmbed/mbed-connector-api-node-quickstart). 122 | 123 | -------------------------------------------------------------------------------- /apache-2.0.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | Apache License 4 | 5 | Version 2.0, January 2004 6 | 7 | http://www.apache.org/licenses/ 8 | 9 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 10 | 11 | 1. Definitions. 12 | 13 | "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. 14 | 15 | "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. 16 | 17 | "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. 18 | 19 | "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. 20 | 21 | "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. 22 | 23 | "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. 24 | 25 | "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). 26 | 27 | "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. 28 | 29 | "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." 30 | 31 | "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. 32 | 33 | 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. 34 | 35 | 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. 36 | 37 | 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: 38 | 39 | You must give any other recipients of the Work or Derivative Works a copy of this License; and 40 | You must cause any modified files to carry prominent notices stating that You changed the files; and 41 | 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 42 | 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. 43 | 44 | 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. 45 | 46 | 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. 47 | 48 | 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. 49 | 50 | 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. 51 | 52 | 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. 53 | 54 | 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. 55 | 56 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /source/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the License); you may 5 | * not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an AS IS BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "minar/minar.h" 18 | #include "security.h" 19 | #include "simpleclient.h" 20 | #include "lwipv4_init.h" 21 | #include 22 | #include 23 | #include 24 | #include "mbed-trace/mbed_trace.h" 25 | 26 | using namespace mbed::util; 27 | 28 | Serial &output = get_stdio_serial(); 29 | 30 | EthernetInterface eth; 31 | 32 | // These are example resource values for the Device Object 33 | struct MbedClientDevice device = { 34 | "Manufacturer_String", // Manufacturer 35 | "Type_String", // Type 36 | "ModelNumber_String", // ModelNumber 37 | "SerialNumber_String" // SerialNumber 38 | }; 39 | 40 | // Instantiate the class which implements LWM2M Client API (from simpleclient.h) 41 | MbedClient mbed_client(device); 42 | 43 | // Set up Hardware interrupt button. 44 | InterruptIn obs_button(SW2); 45 | InterruptIn unreg_button(SW3); 46 | 47 | // debug printf function 48 | void trace_printer(const char* str) { 49 | printf("%s\r\n", str); 50 | } 51 | 52 | // LED Output 53 | DigitalOut led1(LED1); 54 | 55 | /* 56 | * The Led contains one property (pattern) and a function (blink). 57 | * When the function blink is executed, the pattern is read, and the LED 58 | * will blink based on the pattern. 59 | */ 60 | class LedResource { 61 | public: 62 | LedResource() { 63 | // create ObjectID with metadata tag of '3201', which is 'digital output' 64 | led_object = M2MInterfaceFactory::create_object("3201"); 65 | M2MObjectInstance* led_inst = led_object->create_object_instance(); 66 | 67 | // 5853 = Multi-state output 68 | M2MResource* pattern_res = led_inst->create_dynamic_resource("5853", "Pattern", 69 | M2MResourceInstance::STRING, false); 70 | // read and write 71 | pattern_res->set_operation(M2MBase::GET_PUT_ALLOWED); 72 | // set initial pattern (toggle every 200ms. 7 toggles in total) 73 | pattern_res->set_value((const uint8_t*)"500:500:500:500:500:500:500", 27); 74 | 75 | // there's not really an execute LWM2M ID that matches... hmm... 76 | M2MResource* led_res = led_inst->create_dynamic_resource("5850", "Blink", 77 | M2MResourceInstance::OPAQUE, false); 78 | // we allow executing a function here... 79 | led_res->set_operation(M2MBase::POST_ALLOWED); 80 | // when a POST comes in, we want to execute the led_execute_callback 81 | led_res->set_execute_function(execute_callback(this, &LedResource::blink)); 82 | } 83 | 84 | M2MObject* get_object() { 85 | return led_object; 86 | } 87 | 88 | void blink(void *argument) { 89 | // read the value of 'Pattern' 90 | M2MObjectInstance* inst = led_object->object_instance(); 91 | M2MResource* res = inst->resource("5853"); 92 | 93 | // values in mbed Client are all buffers, and we need a vector of int's 94 | uint8_t* buffIn = NULL; 95 | uint32_t sizeIn; 96 | res->get_value(buffIn, sizeIn); 97 | 98 | // turn the buffer into a string, and initialize a vector on the heap 99 | std::string s((char*)buffIn, sizeIn); 100 | std::vector* v = new std::vector; 101 | std::stringstream ss(s); 102 | std::string item; 103 | // our pattern is something like 500:200:500, so parse that 104 | while (std::getline(ss, item, ':')) { 105 | // then convert to integer, and push to the vector 106 | v->push_back(atoi((const char*)item.c_str())); 107 | } 108 | // check if POST contains payload 109 | if (argument) { 110 | M2MResource::M2MExecuteParameter* param = (M2MResource::M2MExecuteParameter*)argument; 111 | String object_name = param->get_argument_object_name(); 112 | uint16_t object_instance_id = param->get_argument_object_instance_id(); 113 | String resource_name = param->get_argument_resource_name(); 114 | int payload_length = param->get_argument_value_length(); 115 | uint8_t* payload = param->get_argument_value(); 116 | output.printf("Resource: %s/%d/%s executed\r\n", object_name.c_str(), object_instance_id, resource_name.c_str()); 117 | output.printf("Payload: %.*s\r\n", payload_length, payload); 118 | } 119 | 120 | output.printf("led_execute_callback pattern=%s\r\n", s.c_str()); 121 | 122 | // do_blink is called with the vector, and starting at -1 123 | do_blink(v, 0); 124 | } 125 | 126 | private: 127 | M2MObject* led_object; 128 | 129 | void do_blink(std::vector* pattern, uint16_t position) { 130 | // blink the LED 131 | led1 = !led1; 132 | 133 | // up the position, if we reached the end of the vector 134 | if (position >= pattern->size()) { 135 | // free memory, and exit this function 136 | delete pattern; 137 | return; 138 | } 139 | 140 | // how long do we need to wait before the next blink? 141 | uint32_t delay_ms = pattern->at(position); 142 | 143 | // we create a FunctionPointer to this same function 144 | FunctionPointer2*, uint16_t> fp(this, &LedResource::do_blink); 145 | // and invoke it after `delay_ms` (upping position) 146 | minar::Scheduler::postCallback(fp.bind(pattern, ++position)).delay(minar::milliseconds(delay_ms)); 147 | } 148 | }; 149 | 150 | /* 151 | * The button contains one property (click count). 152 | * When `handle_button_click` is executed, the counter updates. 153 | */ 154 | class BigPayloadResource { 155 | public: 156 | BigPayloadResource() { 157 | big_payload = M2MInterfaceFactory::create_object("1000"); 158 | M2MObjectInstance* payload_inst = big_payload->create_object_instance(); 159 | M2MResource* payload_res = payload_inst->create_dynamic_resource("1", "BigData", 160 | M2MResourceInstance::STRING, true /* observable */); 161 | payload_res->set_operation(M2MBase::GET_PUT_ALLOWED); 162 | payload_res->set_value((uint8_t*)"0", 1); 163 | payload_res->set_incoming_block_message_callback( 164 | incoming_block_message_callback(this, &BigPayloadResource::block_message_received)); 165 | payload_res->set_outgoing_block_message_callback( 166 | outgoing_block_message_callback(this, &BigPayloadResource::block_message_requested)); 167 | } 168 | 169 | M2MObject* get_object() { 170 | return big_payload; 171 | } 172 | 173 | void block_message_received(M2MBlockMessage *argument) { 174 | if (argument) { 175 | if (M2MBlockMessage::ErrorNone == argument->error_code()) { 176 | if (argument->is_last_block()) { 177 | output.printf("Last block received\r\n"); 178 | } 179 | output.printf("Block number: %d\r\n", argument->block_number()); 180 | // First block received 181 | if (argument->block_number() == 0) { 182 | // Store block 183 | // More blocks coming 184 | } else { 185 | // Store blocks 186 | } 187 | } else { 188 | output.printf("Error when receiving block message! - EntityTooLarge"); 189 | } 190 | output.printf("Total message size: %d\r\n", argument->total_message_size()); 191 | } 192 | } 193 | 194 | void block_message_requested(const String& resource, uint8_t *&/*data*/, uint32_t &/*len*/) { 195 | output.printf("GET request received for resource: %s\r\n", resource.c_str()); 196 | // Copy data and length to coap response 197 | } 198 | 199 | private: 200 | M2MObject* big_payload; 201 | }; 202 | 203 | /* 204 | * The button contains one property (click count). 205 | * When `handle_button_click` is executed, the counter updates. 206 | */ 207 | class ButtonResource { 208 | public: 209 | ButtonResource() { 210 | // create ObjectID with metadata tag of '3200', which is 'digital input' 211 | btn_object = M2MInterfaceFactory::create_object("3200"); 212 | M2MObjectInstance* btn_inst = btn_object->create_object_instance(); 213 | // create resource with ID '5501', which is digital input counter 214 | M2MResource* btn_res = btn_inst->create_dynamic_resource("5501", "Button", 215 | M2MResourceInstance::INTEGER, true /* observable */); 216 | // we can read this value 217 | btn_res->set_operation(M2MBase::GET_ALLOWED); 218 | // set initial value (all values in mbed Client are buffers) 219 | // to be able to read this data easily in the Connector console, we'll use a string 220 | btn_res->set_value((uint8_t*)"0", 1); 221 | } 222 | 223 | M2MObject* get_object() { 224 | return btn_object; 225 | } 226 | 227 | /* 228 | * When you press the button, we read the current value of the click counter 229 | * from mbed Device Connector, then up the value with one. 230 | */ 231 | void handle_button_click() { 232 | M2MObjectInstance* inst = btn_object->object_instance(); 233 | M2MResource* res = inst->resource("5501"); 234 | 235 | // up counter 236 | counter++; 237 | 238 | printf("handle_button_click, new value of counter is %d\r\n", counter); 239 | 240 | // serialize the value of counter as a string, and tell connector 241 | stringstream ss; 242 | ss << counter; 243 | std::string stringified = ss.str(); 244 | res->set_value((uint8_t*)stringified.c_str(), stringified.length()); 245 | } 246 | 247 | private: 248 | M2MObject* btn_object; 249 | uint16_t counter = 0; 250 | }; 251 | 252 | void app_start(int /*argc*/, char* /*argv*/[]) { 253 | 254 | //Sets the console baud-rate 255 | output.baud(115200); 256 | output.printf("In app_start()\r\n"); 257 | 258 | // This sets up the network interface configuration which will be used 259 | // by LWM2M Client API to communicate with mbed Device server. 260 | eth.init(); //Use DHCP 261 | if (eth.connect() != 0) { 262 | output.printf("Failed to form a connection!\r\n"); 263 | } 264 | if (lwipv4_socket_init() != 0) { 265 | output.printf("Error on lwipv4_socket_init!\r\n"); 266 | } 267 | output.printf("IP address %s\r\n", eth.getIPAddress()); 268 | output.printf("Device name %s\r\n", MBED_ENDPOINT_NAME); 269 | mbed_trace_init(); 270 | mbed_trace_print_function_set(trace_printer); 271 | // we create our button and LED resources 272 | auto button_resource = new ButtonResource(); 273 | auto led_resource = new LedResource(); 274 | auto big_payload_resource = new BigPayloadResource(); 275 | 276 | // Unregister button (SW3) press will unregister endpoint from connector.mbed.com 277 | unreg_button.fall(&mbed_client, &MbedClient::test_unregister); 278 | 279 | // Observation Button (SW2) press will send update of endpoint resource values to connector 280 | obs_button.fall(button_resource, &ButtonResource::handle_button_click); 281 | 282 | // Create endpoint interface to manage register and unregister 283 | mbed_client.create_interface(); 284 | 285 | // Create Objects of varying types, see simpleclient.h for more details on implementation. 286 | M2MSecurity* register_object = mbed_client.create_register_object(); // server object specifying connector info 287 | M2MDevice* device_object = mbed_client.create_device_object(); // device resources object 288 | 289 | // Create list of Objects to register 290 | M2MObjectList object_list; 291 | 292 | // Add objects to list 293 | object_list.push_back(device_object); 294 | object_list.push_back(button_resource->get_object()); 295 | object_list.push_back(led_resource->get_object()); 296 | object_list.push_back(big_payload_resource->get_object()); 297 | 298 | // Set endpoint registration object 299 | mbed_client.set_register_object(register_object); 300 | 301 | // Issue register command. 302 | FunctionPointer2 fp(&mbed_client, &MbedClient::test_register); 303 | minar::Scheduler::postCallback(fp.bind(register_object,object_list)); 304 | minar::Scheduler::postCallback(&mbed_client,&MbedClient::test_update_register).period(minar::milliseconds(25000)); 305 | } 306 | -------------------------------------------------------------------------------- /source/simpleclient.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015 ARM Limited. All rights reserved. 3 | * SPDX-License-Identifier: Apache-2.0 4 | * Licensed under the Apache License, Version 2.0 (the License); you may 5 | * not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an AS IS BASIS, WITHOUT 12 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef __SIMPLECLIENT_H__ 18 | #define __SIMPLECLIENT_H__ 19 | 20 | #include "sockets/UDPSocket.h" 21 | #include "EthernetInterface.h" 22 | #include "mbed-drivers/test_env.h" 23 | #include "mbed-client/m2minterfacefactory.h" 24 | #include "mbed-client/m2mdevice.h" 25 | #include "mbed-client/m2minterfaceobserver.h" 26 | #include "mbed-client/m2minterface.h" 27 | #include "mbed-client/m2mobject.h" 28 | #include "mbed-client/m2mobjectinstance.h" 29 | #include "mbed-client/m2mresource.h" 30 | #include "mbed-client/m2mblockmessage.h" 31 | #include "minar/minar.h" 32 | #include "security.h" 33 | 34 | 35 | //Select binding mode: UDP or TCP 36 | M2MInterface::BindingMode SOCKET_MODE = M2MInterface::UDP; 37 | 38 | // This is address to mbed Device Connector 39 | const String &MBED_SERVER_ADDRESS = "coap://api.connector.mbed.com:5684"; 40 | 41 | // These come from the security.h file copied from connector.mbed.com 42 | const String &MBED_USER_NAME_DOMAIN = MBED_DOMAIN; 43 | const String &ENDPOINT_NAME = MBED_ENDPOINT_NAME; 44 | 45 | struct MbedClientDevice { 46 | const char* Manufacturer; 47 | const char* Type; 48 | const char* ModelNumber; 49 | const char* SerialNumber; 50 | }; 51 | 52 | /* 53 | * Wrapper for mbed client stack that handles all callbacks, error handling, and 54 | * other schenanigans to make the mbed client stack easier to use. 55 | * 56 | * The end user should only have to care about configuring the parameters at the 57 | * top of this file and making sure they add the security.h file correctly. 58 | * To add resources you can copy the _TODO__ function and add as many instances as 59 | * you want. 60 | * 61 | */ 62 | class MbedClient: public M2MInterfaceObserver { 63 | public: 64 | 65 | // constructor for MbedClient object, initialize private variables 66 | MbedClient(struct MbedClientDevice device) { 67 | _interface = NULL; 68 | _bootstrapped = false; 69 | _error = false; 70 | _registered = false; 71 | _unregistered = false; 72 | _register_security = NULL; 73 | _value = 0; 74 | _object = NULL; 75 | _device = device; 76 | } 77 | 78 | // de-constructor for MbedClient object, you can ignore this 79 | ~MbedClient() { 80 | if(_interface) { 81 | delete _interface; 82 | } 83 | if(_register_security){ 84 | delete _register_security; 85 | } 86 | } 87 | 88 | // debug printf function 89 | void trace_printer(const char* str) { 90 | printf("\r\n%s\r\n", str); 91 | } 92 | 93 | /* 94 | * Creates M2MInterface using which endpoint can 95 | * setup its name, resource type, life time, connection mode, 96 | * Currently only LwIPv4 is supported. 97 | */ 98 | void create_interface() { 99 | // Randomizing listening port for Certificate mode connectivity 100 | srand(time(NULL)); 101 | uint16_t port = rand() % 65535 + 12345; 102 | 103 | // create mDS interface object, this is the base object everything else attaches to 104 | _interface = M2MInterfaceFactory::create_interface(*this, 105 | ENDPOINT_NAME, // endpoint name string 106 | "test", // endpoint type string 107 | 100, // lifetime 108 | port, // listen port 109 | MBED_USER_NAME_DOMAIN, // domain string 110 | SOCKET_MODE, // binding mode 111 | M2MInterface::LwIP_IPv4, // network stack 112 | ""); // context address string 113 | String binding_mode; 114 | (SOCKET_MODE == M2MInterface::UDP) ? binding_mode = "UDP" : binding_mode = "TCP"; 115 | printf("\r\nSOCKET_MODE : %s\r\n", binding_mode.c_str()); 116 | printf("Connecting to %s\r\n", MBED_SERVER_ADDRESS.c_str()); 117 | } 118 | 119 | /* 120 | * check private variable to see if the registration was sucessful or not 121 | */ 122 | bool register_successful() { 123 | return _registered; 124 | } 125 | 126 | /* 127 | * check private variable to see if un-registration was sucessful or not 128 | */ 129 | bool unregister_successful() { 130 | return _unregistered; 131 | } 132 | 133 | /* 134 | * Creates register server object with mbed device server address and other parameters 135 | * required for client to connect to mbed device server. 136 | */ 137 | M2MSecurity* create_register_object() { 138 | // create security object using the interface factory. 139 | // this will generate a security ObjectID and ObjectInstance 140 | M2MSecurity *security = M2MInterfaceFactory::create_security(M2MSecurity::M2MServer); 141 | 142 | // make sure security ObjectID/ObjectInstance was created successfully 143 | if(security) { 144 | // Add ResourceID's and values to the security ObjectID/ObjectInstance 145 | security->set_resource_value(M2MSecurity::M2MServerUri, MBED_SERVER_ADDRESS); 146 | security->set_resource_value(M2MSecurity::SecurityMode, M2MSecurity::Certificate); 147 | security->set_resource_value(M2MSecurity::ServerPublicKey, SERVER_CERT, sizeof(SERVER_CERT)); 148 | security->set_resource_value(M2MSecurity::PublicKey, CERT, sizeof(CERT)); 149 | security->set_resource_value(M2MSecurity::Secretkey, KEY, sizeof(KEY)); 150 | } 151 | return security; 152 | } 153 | 154 | /* 155 | * Creates device object which contains mandatory resources linked with 156 | * device endpoint. 157 | */ 158 | M2MDevice* create_device_object() { 159 | // create device objectID/ObjectInstance 160 | M2MDevice *device = M2MInterfaceFactory::create_device(); 161 | // make sure device object was created successfully 162 | if(device) { 163 | // add resourceID's to device objectID/ObjectInstance 164 | device->create_resource(M2MDevice::Manufacturer, _device.Manufacturer); 165 | device->create_resource(M2MDevice::DeviceType, _device.Type); 166 | device->create_resource(M2MDevice::ModelNumber, _device.ModelNumber); 167 | device->create_resource(M2MDevice::SerialNumber, _device.SerialNumber); 168 | } 169 | return device; 170 | } 171 | 172 | /* 173 | * register an object 174 | */ 175 | void test_register(M2MSecurity *register_object, M2MObjectList object_list){ 176 | if(_interface) { 177 | // Register function 178 | _interface->register_object(register_object, object_list); 179 | } 180 | } 181 | 182 | /* 183 | * unregister all objects 184 | */ 185 | void test_unregister() { 186 | if(_interface) { 187 | // Unregister function 188 | _interface->unregister_object(NULL); // NULL will unregister all objects 189 | } 190 | } 191 | 192 | //Callback from mbed client stack when the bootstrap 193 | // is successful, it returns the mbed Device Server object 194 | // which will be used for registering the resources to 195 | // mbed Device server. 196 | void bootstrap_done(M2MSecurity *server_object){ 197 | if(server_object) { 198 | _bootstrapped = true; 199 | _error = false; 200 | trace_printer("Bootstrapped"); 201 | } 202 | } 203 | 204 | //Callback from mbed client stack when the registration 205 | // is successful, it returns the mbed Device Server object 206 | // to which the resources are registered and registered objects. 207 | void object_registered(M2MSecurity */*security_object*/, const M2MServer &/*server_object*/){ 208 | _registered = true; 209 | _unregistered = false; 210 | trace_printer("Registered object successfully!"); 211 | } 212 | 213 | //Callback from mbed client stack when the unregistration 214 | // is successful, it returns the mbed Device Server object 215 | // to which the resources were unregistered. 216 | void object_unregistered(M2MSecurity */*server_object*/){ 217 | trace_printer("Unregistered Object Successfully"); 218 | _unregistered = true; 219 | _registered = false; 220 | notify_completion(_unregistered); 221 | minar::Scheduler::stop(); 222 | } 223 | 224 | /* 225 | * Callback from mbed client stack when registration is updated 226 | */ 227 | void registration_updated(M2MSecurity */*security_object*/, const M2MServer & /*server_object*/){ 228 | /* The registration is updated automatically and frequently by the 229 | * mbed client stack. This print statement is turned off because it 230 | * tends to happen alot. 231 | */ 232 | //trace_printer("\r\nRegistration Updated\r\n"); 233 | } 234 | 235 | // Callback from mbed client stack if any error is encountered 236 | // during any of the LWM2M operations. Error type is passed in 237 | // the callback. 238 | void error(M2MInterface::Error error){ 239 | _error = true; 240 | switch(error){ 241 | case M2MInterface::AlreadyExists: 242 | trace_printer("[ERROR:] M2MInterface::AlreadyExist"); 243 | break; 244 | case M2MInterface::BootstrapFailed: 245 | trace_printer("[ERROR:] M2MInterface::BootstrapFailed"); 246 | break; 247 | case M2MInterface::InvalidParameters: 248 | trace_printer("[ERROR:] M2MInterface::InvalidParameters"); 249 | break; 250 | case M2MInterface::NotRegistered: 251 | trace_printer("[ERROR:] M2MInterface::NotRegistered"); 252 | break; 253 | case M2MInterface::Timeout: 254 | trace_printer("[ERROR:] M2MInterface::Timeout"); 255 | break; 256 | case M2MInterface::NetworkError: 257 | trace_printer("[ERROR:] M2MInterface::NetworkError"); 258 | break; 259 | case M2MInterface::ResponseParseFailed: 260 | trace_printer("[ERROR:] M2MInterface::ResponseParseFailed"); 261 | break; 262 | case M2MInterface::UnknownError: 263 | trace_printer("[ERROR:] M2MInterface::UnknownError"); 264 | break; 265 | case M2MInterface::MemoryFail: 266 | trace_printer("[ERROR:] M2MInterface::MemoryFail"); 267 | break; 268 | case M2MInterface::NotAllowed: 269 | trace_printer("[ERROR:] M2MInterface::NotAllowed"); 270 | break; 271 | case M2MInterface::SecureConnectionFailed: 272 | trace_printer("[ERROR:] M2MInterface::SecureConnectionFailed"); 273 | break; 274 | case M2MInterface::DnsResolvingFailed: 275 | trace_printer("[ERROR:] M2MInterface::DnsResolvingFailed"); 276 | break; 277 | default: 278 | break; 279 | } 280 | } 281 | 282 | /* Callback from mbed client stack if any value has changed 283 | * during PUT operation. Object and its type is passed in 284 | * the callback. 285 | * BaseType enum from m2mbase.h 286 | * Object = 0x0, Resource = 0x1, ObjectInstance = 0x2, ResourceInstance = 0x3 287 | */ 288 | void value_updated(M2MBase *base, M2MBase::BaseType type) { 289 | printf("\r\nPUT Request Received!"); 290 | printf("\r\nName :'%s', \r\nType : '%d' (0 for Object, 1 for Resource), \r\nType : '%s'\r\n", 291 | base->name().c_str(), 292 | type, 293 | base->resource_type().c_str() 294 | ); 295 | } 296 | 297 | /* 298 | * update the registration period 299 | */ 300 | void test_update_register() { 301 | if (_registered) { 302 | _interface->update_registration(_register_security, 100); 303 | } 304 | } 305 | 306 | /* 307 | * manually configure the security object private variable 308 | */ 309 | void set_register_object(M2MSecurity *register_object) { 310 | if (_register_security == NULL) { 311 | _register_security = register_object; 312 | } 313 | } 314 | 315 | private: 316 | 317 | /* 318 | * Private variables used in class 319 | */ 320 | M2MInterface *_interface; 321 | M2MSecurity *_register_security; 322 | M2MObject *_object; 323 | volatile bool _bootstrapped; 324 | volatile bool _error; 325 | volatile bool _registered; 326 | volatile bool _unregistered; 327 | int _value; 328 | struct MbedClientDevice _device; 329 | }; 330 | 331 | #endif // __SIMPLECLIENT_H__ 332 | --------------------------------------------------------------------------------