ST / Mbed OS pelion-example-disco-iot01

Dependencies:   X_NUCLEO_COMMON ST_INTERFACES

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 "LittleFileSystem.h"
00023 
00024 // Default network interface object. Don't forget to change the WiFi SSID/password in mbed_app.json if you're using WiFi.
00025 // NetworkInterface *net;
00026 static WiFiInterface *net = NULL;
00027  
00028 
00029 #define WIFI_SSID "<your ssid>"
00030 #define WIFI_PASSWORD "<your pwd>"
00031 
00032 // Default block device available on the target board
00033 BlockDevice* bd = BlockDevice::get_default_instance();
00034 SlicingBlockDevice sd(bd, 0, 2*1024*1024);
00035 
00036 #if COMPONENT_SD || COMPONENT_NUSD
00037 // Use FATFileSystem for SD card type blockdevices
00038 FATFileSystem fs("fs");
00039 #else
00040 // Use LittleFileSystem for non-SD block devices to enable wear leveling and other functions
00041 LittleFileSystem fs("fs");
00042 #endif
00043 
00044 // Default User button for GET example and for resetting the storage
00045 InterruptIn button(BUTTON1);
00046 // Default LED to use for PUT/POST example
00047 DigitalOut led(LED1, 1);
00048 
00049 // How often to fetch sensor data (in seconds)
00050 #define SENSORS_POLL_INTERVAL 3.0
00051 
00052 // Send all sensor data or just limited (useful for when running out of memory)
00053 #define SEND_ALL_SENSORS
00054 
00055 // Sensors related includes and initialization
00056 #include "HTS221Sensor.h"
00057 #include "LPS22HBSensor.h"
00058 #include "LSM6DSLSensor.h"
00059 #include "lis3mdl_class.h"
00060 #include "VL53L0X.h"
00061 
00062 static DevI2C devI2c(PB_11,PB_10);
00063 static HTS221Sensor sen_hum_temp(&devI2c);
00064 static LPS22HBSensor sen_press_temp(&devI2c);
00065 static LSM6DSLSensor sen_acc_gyro(&devI2c,LSM6DSL_ACC_GYRO_I2C_ADDRESS_LOW,PD_11); // low address
00066 static LIS3MDL sen_mag(&devI2c);
00067 static DigitalOut shutdown_pin(PC_6);
00068 static VL53L0X sen_distance(&devI2c, &shutdown_pin, PC_7);
00069 // Temperature reading from microcontroller
00070 AnalogIn adc_temp(ADC_TEMP);
00071 // Voltage reference reading from microcontroller
00072 AnalogIn adc_vref(ADC_VREF);
00073 
00074 // Declaring pointers for access to Pelion Client resources outside of main()
00075 MbedCloudClientResource *res_button;
00076 MbedCloudClientResource *res_led;
00077 
00078 // Additional resources for sensor readings
00079 #ifdef SEND_ALL_SENSORS
00080 MbedCloudClientResource *res_humidity;
00081 MbedCloudClientResource *res_temperature;
00082 MbedCloudClientResource *res_pressure;
00083 MbedCloudClientResource *res_temperature2;
00084 MbedCloudClientResource *res_magnometer_x;
00085 MbedCloudClientResource *res_magnometer_y;
00086 MbedCloudClientResource *res_magnometer_z;
00087 MbedCloudClientResource *res_accelerometer_x;
00088 MbedCloudClientResource *res_accelerometer_y;
00089 MbedCloudClientResource *res_accelerometer_z;
00090 MbedCloudClientResource *res_gyroscope_x;
00091 MbedCloudClientResource *res_gyroscope_y;
00092 MbedCloudClientResource *res_gyroscope_z;
00093 MbedCloudClientResource *res_distance;
00094 MbedCloudClientResource *res_adc_temp;
00095 MbedCloudClientResource *res_adc_voltage;
00096 #endif /* SEND_ALL_SENSORS */
00097 
00098 // An event queue is a very useful structure to debounce information between contexts (e.g. ISR and normal threads)
00099 // 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
00100 EventQueue eventQueue;
00101 
00102 // When the device is registered, this variable will be used to access various useful information, like device ID etc.
00103 static const ConnectorClientEndpointInfo* endpointInfo;
00104 
00105 /**
00106  * PUT handler
00107  * @param resource The resource that triggered the callback
00108  * @param newValue Updated value for the resource
00109  */
00110 void put_callback(MbedCloudClientResource *resource, m2m::String newValue) {
00111     printf("*** PUT received, new value: %s                             \n", newValue.c_str());
00112     led = atoi(newValue.c_str());
00113 }
00114 
00115 /**
00116  * POST handler
00117  * @param resource The resource that triggered the callback
00118  * @param buffer If a body was passed to the POST function, this contains the data.
00119  *               Note that the buffer is deallocated after leaving this function, so copy it if you need it longer.
00120  * @param size Size of the body
00121  */
00122 void post_callback(MbedCloudClientResource *resource, const uint8_t *buffer, uint16_t size) {
00123     printf("*** POST received (length %u). Payload: ", size);
00124     for (size_t ix = 0; ix < size; ix++) {
00125         printf("%02x ", buffer[ix]);
00126     }
00127     printf("\n");
00128 }
00129 
00130 /**
00131  * Button function triggered by the physical button press.
00132  */
00133 void button_press() {
00134     int v = res_button->get_value_int() + 1;
00135     res_button->set_value(v);
00136     printf("*** Button clicked %d times                                 \n", v);
00137 }
00138 
00139 /**
00140  * Notification callback handler
00141  * @param resource The resource that triggered the callback
00142  * @param status The delivery status of the notification
00143  */
00144 void button_callback(MbedCloudClientResource *resource, const NoticationDeliveryStatus status) {
00145     printf("*** Button notification, status %s (%d)                     \n", MbedCloudClientResource::delivery_status_to_string(status), status);
00146 }
00147 
00148 /**
00149  * Registration callback handler
00150  * @param endpoint Information about the registered endpoint such as the name (so you can find it back in portal)
00151  */
00152 void registered(const ConnectorClientEndpointInfo *endpoint) {
00153     printf("Registered to Pelion Device Management. Endpoint Name: %s\n", endpoint->internal_endpoint_name.c_str());
00154     endpointInfo = endpoint;
00155 }
00156 
00157 /**
00158  * Initialize sensors
00159  */
00160 void sensors_init() {
00161     uint8_t id1, id2, id3, id4;
00162 
00163     printf ("\nSensors configuration:\n");
00164     // Initialize sensors
00165     sen_hum_temp.init(NULL);
00166     sen_press_temp.init(NULL);
00167     sen_acc_gyro.init(NULL);
00168     sen_mag.init(NULL);
00169     sen_distance.init_sensor(VL53L0X_DEFAULT_ADDRESS);
00170 
00171     /// Call sensors enable routines
00172     sen_hum_temp.enable();
00173     sen_press_temp.enable();
00174     sen_acc_gyro.enable_x();
00175     sen_acc_gyro.enable_g();
00176 
00177     sen_hum_temp.read_id(&id1);
00178     sen_press_temp.read_id(&id2);
00179     sen_mag.read_id(&id3);
00180     sen_acc_gyro.read_id(&id4);
00181 
00182     printf("HTS221  humidity & temperature    = 0x%X\n", id1);
00183     printf("LPS22HB pressure & temperature    = 0x%X\n", id2);
00184     printf("LIS3MDL magnetometer              = 0x%X\n", id3);
00185     printf("LSM6DSL accelerometer & gyroscope = 0x%X\n", id4);
00186 
00187     printf("\n"); ;
00188 }
00189 
00190 /**
00191  * Update sensors and report their values.
00192  * This function is called periodically.
00193  */
00194 void sensors_update() {
00195     float temp1_value, temp2_value, temp3_value, humid_value, pressure_value, volt_value = 0.0;
00196     int32_t m_axes[3], a_axes[3], g_axes[3];
00197     uint32_t distance_value, distance_reading;
00198 
00199     sen_hum_temp.get_humidity(&humid_value);
00200     sen_hum_temp.get_temperature(&temp1_value);
00201     sen_press_temp.get_pressure(&pressure_value);
00202     sen_press_temp.get_temperature(&temp2_value);
00203     sen_mag.get_m_axes(m_axes);
00204     sen_acc_gyro.get_x_axes(a_axes);
00205     sen_acc_gyro.get_g_axes(g_axes);
00206     distance_reading = sen_distance.get_distance(&distance_value);
00207     temp3_value = adc_temp.read()*100;
00208     volt_value = adc_vref.read();
00209 
00210     float mag_x =  (double)m_axes[0] / 1000.0, mag_y  = (double)m_axes[1] / 1000.0, mag_z  = (double)m_axes[2] / 1000.0;
00211     float acc_x =  (double)a_axes[0] / 1000.0, acc_y  = (double)a_axes[1] / 1000.0, acc_z  = (double)a_axes[2] / 1000.0;
00212     float gyro_x = (double)g_axes[0] / 1000.0, gyro_y = (double)g_axes[1] / 1000.0, gyro_z = (double)g_axes[2] / 1000.0;
00213 
00214     printf("                                                             \n");
00215     printf("ADC temp:     %5.4f C,  vref:      %5.4f V         \n", temp3_value, volt_value);
00216     printf("HTS221 temp:  %7.3f C,  humidity: %7.2f %%         \n", temp1_value, humid_value);
00217     printf("LPS22HB temp: %7.3f C,  pressure: %7.2f mbar       \n", temp2_value, pressure_value);
00218     printf("LIS3MDL mag:  %7.3f x, %7.3f y, %7.3f z [gauss]      \n", mag_x, mag_y, mag_z);
00219     printf("LSM6DSL acc:  %7.3f x, %7.3f y, %7.3f z [g]          \n", acc_x, acc_y, acc_z);
00220     printf("LSM6DSL gyro: %7.3f x, %7.3f y, %7.3f z [dps]        \n", gyro_x, gyro_y, gyro_z);
00221     if (distance_reading == VL53L0X_ERROR_NONE) {
00222         printf("VL53L0X dist: %7ld mm\n", distance_value);
00223     } else {
00224         printf("VL53L0X dist:        --       \n");
00225         distance_value = 999;
00226     }
00227 
00228     printf("\r\033[8A");
00229 
00230     if (endpointInfo) {
00231 #ifdef SEND_ALL_SENSORS
00232         res_humidity->set_value(humid_value);
00233         res_temperature->set_value(temp1_value);
00234         res_pressure->set_value(pressure_value);
00235         res_temperature2->set_value(temp2_value);
00236         res_magnometer_x->set_value(mag_x);
00237         res_magnometer_y->set_value(mag_y);
00238         res_magnometer_z->set_value(mag_z);
00239         res_accelerometer_x->set_value(acc_x);
00240         res_accelerometer_y->set_value(acc_y);
00241         res_accelerometer_z->set_value(acc_z);
00242         res_gyroscope_x->set_value(gyro_x);
00243         res_gyroscope_y->set_value(gyro_y);
00244         res_gyroscope_z->set_value(gyro_z);
00245         res_distance->set_value((int)distance_value);
00246         res_adc_temp->set_value(temp3_value);
00247         res_adc_voltage->set_value(volt_value);
00248 #endif /* SEND_ALL_SENSORS */
00249     }
00250 }
00251 
00252 
00253 int main(void) {
00254     printf("\nStarting Simple Pelion Device Management Client example\n");
00255     printf("\nSSID : %s, PWD : %s\n",WIFI_SSID, WIFI_PASSWORD);
00256 
00257     int storage_status = fs.mount(&sd);
00258     if (storage_status != 0) {
00259         printf("Storage mounting failed.\n");
00260     }
00261     // If the User button is pressed ons start, then format storage.
00262     bool btn_pressed = (button.read() == MBED_CONF_APP_BUTTON_PRESSED_STATE);
00263     if (btn_pressed) {
00264         printf("User button is pushed on start...\n");
00265     }
00266 
00267     if (storage_status || btn_pressed) {
00268         printf("Formatting the storage...\n");
00269         int storage_status = StorageHelper::format(&fs, &sd);
00270         if (storage_status != 0) {
00271             printf("ERROR: Failed to reformat the storage (%d).\n", storage_status);
00272         }
00273     } else {
00274         printf("You can hold the user button during boot to format the storage and change the device identity.\n");
00275     }
00276 
00277     sensors_init();
00278 
00279     // Connect to the internet (DHCP is expected to be on)
00280     printf("Connecting to the network using Wifi...\n");
00281     // net = NetworkInterface::get_default_instance();
00282     net = WiFiInterface::get_default_instance();
00283 
00284     nsapi_error_t net_status = -1;
00285 
00286     for (int tries = 0; tries < 3; tries++) {
00287         
00288         //net_status = net->connect();
00289         net_status = net->connect(WIFI_SSID, WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2);
00290         
00291         if (net_status == NSAPI_ERROR_OK) {
00292             break;
00293         } else {
00294             printf("Unable to connect to network. Retrying...\n");
00295         }
00296     }
00297 
00298     if (net_status != NSAPI_ERROR_OK) {
00299         printf("ERROR: Connecting to the network failed (%d)!\n", net_status);
00300         return -1;
00301     }
00302 
00303     printf("Connected to the network successfully. IP address: %s\n", net->get_ip_address());
00304 
00305     printf("Initializing Pelion Device Management Client...\n");
00306 
00307     // SimpleMbedCloudClient handles registering over LwM2M to Pelion DM
00308     SimpleMbedCloudClient client(net, bd, &fs);
00309     int client_status = client.init();
00310     if (client_status != 0) {
00311         printf("ERROR: Pelion Client initialization failed (%d)\n", client_status);
00312         return -1;
00313     }
00314 
00315     // Creating resources, which can be written or read from the cloud
00316     res_button = client.create_resource("3200/0/5501", "Button Count");
00317     res_button->set_value(0);
00318     res_button->methods(M2MMethod::GET);
00319     res_button->observable(true);
00320     res_button->attach_notification_callback(button_callback);
00321 
00322     res_led = client.create_resource("3201/0/5853", "LED State");
00323     res_led->set_value(1);
00324     res_led->methods(M2MMethod::GET | M2MMethod::PUT);
00325     res_led->attach_put_callback(put_callback);
00326 
00327 #ifdef SEND_ALL_SENSORS
00328     // Sensor resources
00329     res_temperature = client.create_resource("3303/0/5700", "Temperature HTS221 (C)");
00330     res_temperature->set_value(0);
00331     res_temperature->methods(M2MMethod::GET);
00332     res_temperature->observable(true);
00333 
00334     res_humidity = client.create_resource("3304/0/5700", "Humidity");
00335     res_humidity->set_value(0);
00336     res_humidity->methods(M2MMethod::GET);
00337     res_humidity->observable(true);
00338 
00339     res_temperature2 = client.create_resource("3303/1/5700", "Temperature LPS22HB (C)");
00340     res_temperature2->set_value(0);
00341     res_temperature2->methods(M2MMethod::GET);
00342     res_temperature2->observable(true);
00343 
00344     res_adc_temp = client.create_resource("3303/2/5700", "Temperature ADC (C)");
00345     res_adc_temp->set_value(0);
00346     res_adc_temp->methods(M2MMethod::GET);
00347     res_adc_temp->observable(true);
00348 
00349     res_accelerometer_x = client.create_resource("3313/0/5702", "Accelerometer X");
00350     res_accelerometer_x->set_value(0);
00351     res_accelerometer_x->methods(M2MMethod::GET);
00352     res_accelerometer_x->observable(true);
00353 
00354     res_accelerometer_y = client.create_resource("3313/0/5703", "Accelerometer Y");
00355     res_accelerometer_y->set_value(0);
00356     res_accelerometer_y->methods(M2MMethod::GET);
00357     res_accelerometer_y->observable(true);
00358 
00359     res_accelerometer_z = client.create_resource("3313/0/5704", "Accelerometer Z");
00360     res_accelerometer_z->set_value(0);
00361     res_accelerometer_z->methods(M2MMethod::GET);
00362     res_accelerometer_z->observable(true);
00363 
00364     res_magnometer_x = client.create_resource("3314/0/5702", "Magnometer X");
00365     res_magnometer_x->set_value(0);
00366     res_magnometer_x->methods(M2MMethod::GET);
00367     res_magnometer_x->observable(true);
00368 
00369     res_magnometer_y = client.create_resource("3314/0/5703", "Magnometer Y");
00370     res_magnometer_y->set_value(0);
00371     res_magnometer_y->methods(M2MMethod::GET);
00372     res_magnometer_y->observable(true);
00373 
00374     res_magnometer_z = client.create_resource("3314/0/5704", "Magnometer Z");
00375     res_magnometer_z->set_value(0);
00376     res_magnometer_z->methods(M2MMethod::GET);
00377     res_magnometer_z->observable(true);
00378 
00379     res_gyroscope_x = client.create_resource("3334/0/5702", "Gyroscope X");
00380     res_gyroscope_x->set_value(0);
00381     res_gyroscope_x->methods(M2MMethod::GET);
00382     res_gyroscope_x->observable(true);
00383 
00384     res_gyroscope_y = client.create_resource("3334/0/5703", "Gyroscope Y");
00385     res_gyroscope_y->set_value(0);
00386     res_gyroscope_y->methods(M2MMethod::GET);
00387     res_gyroscope_y->observable(true);
00388 
00389     res_gyroscope_z = client.create_resource("3334/0/5704", "Gyroscope Z");
00390     res_gyroscope_z->set_value(0);
00391     res_gyroscope_z->methods(M2MMethod::GET);
00392     res_gyroscope_z->observable(true);
00393 
00394     res_adc_voltage = client.create_resource("3316/0/5700", "Voltage");
00395     res_adc_voltage->set_value(0);
00396     res_adc_voltage->methods(M2MMethod::GET);
00397     res_adc_voltage->observable(true);
00398 
00399     res_pressure = client.create_resource("3323/0/5700", "Pressure");
00400     res_pressure->set_value(0);
00401     res_pressure->methods(M2MMethod::GET);
00402     res_pressure->observable(true);
00403 
00404     res_distance = client.create_resource("3330/0/5700", "Distance");
00405     res_distance->set_value((float)999.9);
00406     res_distance->methods(M2MMethod::GET);
00407     res_distance->observable(true);
00408 #endif /* SEND_ALL_SENSORS */
00409 
00410     printf("Initialized Pelion Client. Registering...\n");
00411 
00412     // Callback that fires when registering is complete
00413     client.on_registered(&registered);
00414 
00415     // Register with Pelion DM
00416     client.register_and_connect();
00417 
00418     int i = 600; // wait up 60 seconds before attaching sensors and button events
00419     while (i-- > 0 && !client.is_client_registered()) {
00420         wait_ms(100);
00421     }
00422 
00423     button.fall(eventQueue.event(&button_press));
00424 
00425     // The timer fires on an interrupt context, but debounces it to the eventqueue, so it's safe to do network operations
00426     Ticker timer;
00427     timer.attach(eventQueue.event(&sensors_update), SENSORS_POLL_INTERVAL);
00428 
00429     // You can easily run the eventQueue in a separate thread if required
00430     eventQueue.dispatch_forever();
00431 }
00432 
00433 #endif