Mbed OS and Pelion Device Management example for FRDM-K64F and FRDM-K66F boards

Dependencies:   FXAS21002 FXOS8700Q

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 // ----------------------------------------------------------------------------
00002 // Copyright 2016-2018 ARM Ltd.
00003 //
00004 // SPDX-License-Identifier: Apache-2.0
00005 //
00006 // Licensed under the Apache License, Version 2.0 (the "License");
00007 // you may not use this file except in compliance with the License.
00008 // You may obtain a copy of the License at
00009 //
00010 //     http://www.apache.org/licenses/LICENSE-2.0
00011 //
00012 // Unless required by applicable law or agreed to in writing, software
00013 // distributed under the License is distributed on an "AS IS" BASIS,
00014 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00015 // See the License for the specific language governing permissions and
00016 // limitations under the License.
00017 // ----------------------------------------------------------------------------
00018 #ifndef MBED_TEST_MODE
00019 
00020 #include "mbed.h"
00021 #include "simple-mbed-cloud-client.h"
00022 #include "FATFileSystem.h"
00023 #include "LittleFileSystem.h"
00024 
00025 // Default network interface object. Don't forget to change the WiFi SSID/password in mbed_app.json if you're using WiFi.
00026 NetworkInterface *net = NetworkInterface::get_default_instance();
00027 
00028 // Default block device available on the target board
00029 BlockDevice *bd = BlockDevice::get_default_instance();
00030 
00031 #if COMPONENT_SD || COMPONENT_NUSD
00032 // Use FATFileSystem for SD card type blockdevices
00033 FATFileSystem fs("fs");
00034 #else
00035 // Use LittleFileSystem for non-SD block devices to enable wear leveling and other functions
00036 LittleFileSystem fs("fs");
00037 #endif
00038 
00039 // Default User button for GET example and for resetting the storage
00040 InterruptIn button(BUTTON1);
00041 // Default LED to use for PUT/POST example
00042 DigitalOut led(LED1, 0);
00043 
00044 // How often to fetch sensor data (in seconds)
00045 #define SENSORS_POLL_INTERVAL 3.0
00046 
00047 // Send all sensor data or just limited (useful for when running out of memory)
00048 //#define SEND_ALL_SENSORS
00049 
00050 // Sensors related includes and initialization
00051 #include "FXOS8700Q.h"
00052 #include "FXAS21002.h"
00053 
00054 #ifdef TARGET_K66F
00055 I2C sens_i2c(PTD9, PTD8);
00056 #else
00057 I2C sens_i2c(PTE25, PTE24);
00058 #endif /* TARGET_K66F */
00059 
00060 FXOS8700QAccelerometer sens_acc(sens_i2c, FXOS8700CQ_SLAVE_ADDR1);    // Configured for the FRDM-K64F with onboard sensors
00061 FXOS8700QMagnetometer sens_mag(sens_i2c, FXOS8700CQ_SLAVE_ADDR1);
00062 #ifdef TARGET_K66F
00063 FXAS21002 sens_gyro(PTD9, PTD8, 0x20);
00064 #endif /* TARGET_K66F */
00065 
00066 // Declaring pointers for access to Pelion Device Management Client resources outside of main()
00067 MbedCloudClientResource *res_button;
00068 MbedCloudClientResource *res_led;
00069 MbedCloudClientResource *res_post;
00070 
00071 // Additional resources for sensor readings
00072 #ifdef SEND_ALL_SENSORS
00073 MbedCloudClientResource *res_magnometer_x;
00074 MbedCloudClientResource *res_magnometer_y;
00075 MbedCloudClientResource *res_magnometer_z;
00076 MbedCloudClientResource *res_accelerometer_x;
00077 MbedCloudClientResource *res_accelerometer_y;
00078 MbedCloudClientResource *res_accelerometer_z;
00079 #ifdef TARGET_K66F
00080 MbedCloudClientResource *res_gyroscope_x;
00081 MbedCloudClientResource *res_gyroscope_y;
00082 MbedCloudClientResource *res_gyroscope_z;
00083 #endif /* TARGET_K66F */
00084 #endif /* SEND_ALL_SENSORS */
00085 
00086 // An event queue is a very useful structure to debounce information between contexts (e.g. ISR and normal threads)
00087 // 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
00088 EventQueue eventQueue;
00089 
00090 // When the device is registered, this variable will be used to access various useful information, like device ID etc.
00091 static const ConnectorClientEndpointInfo* endpointInfo;
00092 
00093 /**
00094  * PUT handler - sets the value of the built-in LED
00095  * @param resource The resource that triggered the callback
00096  * @param newValue Updated value for the resource
00097  */
00098 void put_callback(MbedCloudClientResource *resource, m2m::String newValue) {
00099     printf("*** PUT received, new value: %s                             \n", newValue.c_str());
00100     led = atoi(newValue.c_str());
00101 }
00102 
00103 /**
00104  * POST handler - prints the content of the payload
00105  * @param resource The resource that triggered the callback
00106  * @param buffer If a body was passed to the POST function, this contains the data.
00107  *               Note that the buffer is deallocated after leaving this function, so copy it if you need it longer.
00108  * @param size Size of the body
00109  */
00110 void post_callback(MbedCloudClientResource *resource, const uint8_t *buffer, uint16_t size) {
00111     printf("*** POST received (length %u). Payload: ", size);
00112     for (size_t ix = 0; ix < size; ix++) {
00113         printf("%02x ", buffer[ix]);
00114     }
00115     printf("\n");
00116 }
00117 
00118 /**
00119  * Button handler
00120  * This function will be triggered either by a physical button press or by a ticker every 5 seconds (see below)
00121  */
00122 void button_press() {
00123     int v = res_button->get_value_int() + 1;
00124     res_button->set_value(v);
00125     printf("*** Button clicked %d times                                 \n", v);
00126 }
00127 
00128 /**
00129  * Notification callback handler
00130  * @param resource The resource that triggered the callback
00131  * @param status The delivery status of the notification
00132  */
00133 void button_callback(MbedCloudClientResource *resource, const NoticationDeliveryStatus status) {
00134     printf("*** Button notification, status %s (%d)                     \n", MbedCloudClientResource::delivery_status_to_string(status), status);
00135 }
00136 
00137 /**
00138  * Registration callback handler
00139  * @param endpoint Information about the registered endpoint such as the name (so you can find it back in portal)
00140  */
00141 void registered(const ConnectorClientEndpointInfo *endpoint) {
00142     printf("Registered to Pelion Device Management. Endpoint Name: %s\n", endpoint->internal_endpoint_name.c_str());
00143     endpointInfo = endpoint;
00144 }
00145 
00146 /**
00147  * Initialize sensors
00148  */
00149 void sensors_init() {
00150     printf ("\nSensors configuration:\n");
00151 
00152     sens_acc.enable();
00153     sens_mag.enable();
00154 #ifdef TARGET_K66F
00155     sens_gyro.activate(true);
00156 #endif /* TARGET_K66F */
00157 
00158     printf("FXOS8700Q accelerometer = 0x%X\n", sens_acc.whoAmI());
00159     printf("FXOS8700Q magnetometer  = 0x%X\n", sens_mag.whoAmI());
00160 #ifdef TARGET_K66F
00161     printf("FXAS21002 gyroscope     = 0x%X\n", sens_gyro.getStatus());
00162 #endif /* TARGET_K66F */
00163 
00164     printf("\n"); ;
00165 }
00166 
00167 /**
00168  * Update sensors and report their values.
00169  * This function is called periodically.
00170  */
00171 void sensors_update() {
00172     motion_data_counts_t acc_raw, mag_raw;
00173 
00174     sens_acc.getAxis(acc_raw);
00175     sens_mag.getAxis(mag_raw);
00176 
00177     float mag_x = (double)mag_raw.x / 1000.0, mag_y = (double)mag_raw.y / 1000.0, mag_z = (double)mag_raw.z / 1000.0;
00178     float acc_x = (double)acc_raw.x / 1000.0, acc_y = (double)acc_raw.y / 1000.0, acc_z = (double)acc_raw.z / 1000.0;
00179 #ifdef TARGET_K66F
00180     float gyro_x = (double)sens_gyro.getX() / 1000.0, gyro_y = (double)sens_gyro.getY() / 1000.0, gyro_z = (double)sens_gyro.getZ() / 1000.0;
00181 #endif /* TARGET_K66F */
00182 
00183     printf("                                                             \n");
00184     printf("FXOS8700Q mag:  %7.3f x, %7.3f y, %7.3f z [gauss]        \n", mag_x, mag_y, mag_z);
00185     printf("FXOS8700Q acc:  %7.3f x, %7.3f y, %7.3f z [g]            \n", acc_x, acc_y, acc_z);
00186 #ifdef TARGET_K66F
00187     printf("FXAS21002 gryo: %7.3f x, %7.3f y, %7.3f z [dps]          \n", gyro_x, gyro_y, gyro_z);
00188     printf("\r\033[4A");
00189 #else
00190     printf("\r\033[3A");
00191 #endif /* TARGET_K66F */
00192 
00193     if (endpointInfo) {
00194 #ifdef SEND_ALL_SENSORS
00195         res_accelerometer_x->set_value(acc_x);
00196         res_accelerometer_y->set_value(acc_y);
00197         res_accelerometer_z->set_value(acc_z);
00198         res_magnometer_x->set_value(mag_x);
00199         res_magnometer_y->set_value(mag_y);
00200         res_magnometer_z->set_value(mag_z);
00201 #ifdef TARGET_K66F
00202         res_gyroscope_x->set_value(gyro_x);
00203         res_gyroscope_y->set_value(gyro_y);
00204         res_gyroscope_z->set_value(gyro_z);
00205 #endif /* TARGET_K66F */
00206 #endif /* SEND_ALL_SENSORS */
00207     }
00208 }
00209 
00210 int main(void) {
00211     printf("\nStarting Simple Pelion Device Management Client example\n");
00212 
00213     int storage_status = fs.mount(bd);
00214     if (storage_status != 0) {
00215         printf("Storage mounting failed.\n");
00216     }
00217 #if USE_BUTTON == 1
00218     // If the User button is pressed ons start, then format storage.
00219     bool btn_pressed = (button.read() == MBED_CONF_APP_BUTTON_PRESSED_STATE);
00220     if (btn_pressed) {
00221         printf("User button is pushed on start...\n");
00222     }
00223 #else
00224     bool btn_pressed = FALSE;
00225 #endif /* USE_BUTTON */
00226 
00227     if (storage_status || btn_pressed) {
00228         printf("Formatting the storage...\n");
00229         int storage_status = StorageHelper::format(&fs, bd);
00230         if (storage_status != 0) {
00231             printf("ERROR: Failed to reformat the storage (%d).\n", storage_status);
00232         }
00233     } else {
00234         printf("You can hold the user button during boot to format the storage and change the device identity.\n");
00235     }
00236 
00237     sensors_init();
00238 
00239     // Connect to the Internet (DHCP is expected to be on)
00240     printf("Connecting to the network using the default network interface...\n");
00241     net = NetworkInterface::get_default_instance();
00242 
00243     nsapi_error_t net_status = NSAPI_ERROR_NO_CONNECTION;
00244     while ((net_status = net->connect()) != NSAPI_ERROR_OK) {
00245         printf("Unable to connect to network (%d). Retrying...\n", net_status);
00246     }
00247 
00248     printf("Connected to the network successfully. IP address: %s\n", net->get_ip_address());
00249 
00250     printf("Initializing Pelion Device Management Client...\n");
00251 
00252     // SimpleMbedCloudClient handles registering over LwM2M to Pelion Device Management
00253     SimpleMbedCloudClient client(net, bd, &fs);
00254     int client_status = client.init();
00255     if (client_status != 0) {
00256         printf("Pelion Client initialization failed (%d)\n", client_status);
00257         return -1;
00258     }
00259 
00260     // Creating resources, which can be written or read from the cloud
00261     res_button = client.create_resource("3200/0/5501", "button_count");
00262     res_button->set_value(0);
00263     res_button->methods(M2MMethod::GET);
00264     res_button->observable(true);
00265     res_button->attach_notification_callback(button_callback);
00266 
00267     res_led = client.create_resource("3201/0/5853", "led_state");
00268     res_led->set_value(led.read());
00269     res_led->methods(M2MMethod::GET | M2MMethod::PUT);
00270     res_led->attach_put_callback(put_callback);
00271 
00272     res_post = client.create_resource("3300/0/5605", "execute_function");
00273     res_post->methods(M2MMethod::POST);
00274     res_post->attach_post_callback(post_callback);
00275 
00276 #ifdef SEND_ALL_SENSORS
00277     res_accelerometer_x = client.create_resource("3313/0/5702", "Accelerometer X");
00278     res_accelerometer_x->set_value(0);
00279     res_accelerometer_x->methods(M2MMethod::GET);
00280     res_accelerometer_x->observable(true);
00281 
00282     res_accelerometer_y = client.create_resource("3313/0/5703", "Accelerometer Y");
00283     res_accelerometer_y->set_value(0);
00284     res_accelerometer_y->methods(M2MMethod::GET);
00285     res_accelerometer_y->observable(true);
00286 
00287     res_accelerometer_z = client.create_resource("3313/0/5704", "Accelerometer Z");
00288     res_accelerometer_z->set_value(0);
00289     res_accelerometer_z->methods(M2MMethod::GET);
00290     res_accelerometer_z->observable(true);
00291 
00292     res_magnometer_x = client.create_resource("3314/0/5702", "Magnometer X");
00293     res_magnometer_x->set_value(0);
00294     res_magnometer_x->methods(M2MMethod::GET);
00295     res_magnometer_x->observable(true);
00296 
00297     res_magnometer_y = client.create_resource("3314/0/5703", "Magnometer Y");
00298     res_magnometer_y->set_value(0);
00299     res_magnometer_y->methods(M2MMethod::GET);
00300     res_magnometer_y->observable(true);
00301 
00302     res_magnometer_z = client.create_resource("3314/0/5704", "Magnometer Z");
00303     res_magnometer_z->set_value(0);
00304     res_magnometer_z->methods(M2MMethod::GET);
00305     res_magnometer_z->observable(true);
00306 
00307 #ifdef TARGET_K66F
00308     res_gyroscope_x = client.create_resource("3334/0/5702", "Gyroscope X");
00309     res_gyroscope_x->set_value(0);
00310     res_gyroscope_x->methods(M2MMethod::GET);
00311     res_gyroscope_x->observable(true);
00312 
00313     res_gyroscope_y = client.create_resource("3334/0/5703", "Gyroscope Y");
00314     res_gyroscope_y->set_value(0);
00315     res_gyroscope_y->methods(M2MMethod::GET);
00316     res_gyroscope_y->observable(true);
00317 
00318     res_gyroscope_z = client.create_resource("3334/0/5704", "Gyroscope Z");
00319     res_gyroscope_z->set_value(0);
00320     res_gyroscope_z->methods(M2MMethod::GET);
00321     res_gyroscope_z->observable(true);
00322 #endif /* TARGET_K66F */
00323 #endif /* SEND_ALL_SENSORS */
00324 
00325     printf("Initialized Pelion Device Management Client. Registering...\n");
00326 
00327     // Callback that fires when registering is complete
00328     client.on_registered(&registered);
00329 
00330     // Register with Pelion DM
00331     client.register_and_connect();
00332 
00333     // The button fires on an interrupt context, but debounces it to the eventqueue, so it's safe to do network operations
00334     button.fall(eventQueue.event(&button_press));
00335     printf("Press the user button to increment the LwM2M resource value...\n");
00336 
00337     // The timer fires on an interrupt context, but debounces it to the eventqueue, so it's safe to do network operations
00338     Ticker timer;
00339     timer.attach(eventQueue.event(&sensors_update), SENSORS_POLL_INTERVAL);
00340 
00341     // You can easily run the eventQueue in a separate thread if required
00342     eventQueue.dispatch_forever();
00343 }
00344 
00345 #endif /* MBED_TEST_MODE */