Hackster is hosting Hackster Holidays, Ep. 7: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Friday!Stream Hackster Holidays, Ep. 7 on Friday!

Greenhouse Monitoring with Discovery Kit IoT and Android

How to build a greenhouse monitoring system that measures environment parameters like temperature and humidity.

AdvancedFull instructions provided3,769
Greenhouse Monitoring with Discovery Kit IoT and Android

Things used in this project

Hardware components

STM32 B-L475E-IOT01A Discovery kit for IoT
×1

Software apps and online services

Mbed Studio
Arm Mbed Studio
AWS IoT
Amazon Web Services AWS IoT
Android Studio
Android Studio

Story

Read more

Code

main.cpp

C/C++
#include "mbed.h"
#include "mbed-trace/mbed_trace.h"
#include "mbedtls/debug.h"

#include "stm32l475e_iot01_tsensor.h"
#include "stm32l475e_iot01_hsensor.h"

#include "core/cloud.h"

#define AWS_IOT_UPDATE_FREQUENCY    10

DigitalOut led(LED1);

// Connect services 
int connect(){
    int result = 0;

    int cloud_status = cloud_connect();
    if(cloud_status == 1){
        result = 1;    
    }
    
    return result;
}

// Main
int main(){
    mbed_trace_init();
    
    printf("IoT device starting\r\n");
    
    // Define sensor vars 
    float temperature = 0;
    float humidity = 0;
    
    // Initalize sensors 
    BSP_TSENSOR_Init();
    BSP_HSENSOR_Init();
    
    // Initialize cloud (connect wifi) 
    cloud_init();
    
    // Connect to network 
    int connected = connect();
    while(1) {
        if(connected == 1){
            //It works
            led = 1;
            
            // Get current sensor data
            temperature = BSP_TSENSOR_ReadTemp();
            humidity = BSP_HSENSOR_ReadHumidity();
            
            // Send message to cloud
            cloud_send(temperature,humidity);
            
            // wait 
            wait(AWS_IOT_UPDATE_FREQUENCY);
        }else{
            // It doens't work  
            wait(2);  
            led=0;
        }
    }
}

MQTT_server_setting.h

C/C++
#ifndef __MQTT_SERVER_SETTING_H__
#define __MQTT_SERVER_SETTING_H__

const char MQTT_SERVER_HOST_NAME[] = "a2ljeoyca4z5yq-ats.iot.eu-central-1.amazonaws.com";
const char MQTT_CLIENT_ID[] = "STM32L475VGIOT01A";
const char MQTT_USERNAME[] = "STM32L4";
const char MQTT_PASSWORD[] = "";
const char MQTT_TOPIC_PUB[] = "pubtopic";
const char MQTT_TOPIC_SUB[] = "subtopic";


const int MQTT_SERVER_PORT = 8883;

/*
 * Root CA certificate here in PEM format.
 * "-----BEGIN CERTIFICATE-----\n"
 * ...
 * "-----END CERTIFICATE-----\n";
 */
/* Amazon Legacy Root CA */
/*const char* SSL_CA_PEM = "-----BEGIN CERTIFICATE-----\n"
"MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB\n"
"yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL\n"
"ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp\n"
"U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxW\n"
"ZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0\n"
"aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCByjEL\n"
"MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZW\n"
"ZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2ln\n"
"biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJp\n"
"U2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9y\n"
"aXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvJAgIKXo1\n"
"nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6Cq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FICATE-----\n";

/*
 * (optional) Client certificate here in PEM format.
 * Set NULL if you don't use.
 * "-----BEGIN CERTIFICATE-----\n"
 * ...
 * "-----END CERTIFICATE-----\n";
 */
const char* SSL_CLIENT_CERT_PEM = "-----BEGIN CERTIFICATE-----\n"
-
-
-
"-----END CERTIFICATE-----\n";


/*
 * (optional) Client private key here in PEM format.
 * Set NULL if you don't use.
 * "-----BEGIN RSA PRIVATE KEY-----\n"
 * ...
 * "-----END RSA PRIVATE KEY-----\n";
 */
const char* SSL_CLIENT_PRIVATE_KEY_PEM = "-----BEGIN RSA PRIVATE KEY-----\n"
-
-
-
"-----END RSA PRIVATE KEY-----\n";

#endif /* __MQTT_SERVER_SETTING_H__ */

mbed_app.json

JSON
{
    "macros": [
        "MBEDTLS_USER_CONFIG_FILE=\"mbedtls_entropy_config.h\""
    ],
    "config": {
        "wifi-shield": {
            "help": "Options are internal, WIFI_ESP8266, WIFI_IDW0XX1",
            "value": "internal"
        },
        "wifi-ssid": {
            "help": "WiFi SSID",
            "value": "\"FASTWEB-B9614B\""
        },
        "wifi-password": {
            "help": "WiFi Password",
            "value": "\"example123\""
        },
        "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"
        },
        "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"
        },
        "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"
        },
        "wifi-reset": {
            "help": "WIFI module reset pin",
            "value": "PE_8"
        },
        "wifi-dataready": {
            "help": "WIFI module data ready pin",
            "value": "PE_1"
        },
        "wifi-wakeup": {
            "help": "WIFI module wakeup pin",
            "value": "PB_12"
        },
        "main-stack-size": {
            "value": 7000
        }
    },
    "target_overrides": {
        "*": {
            "target.network-default-interface-type": "ETHERNET",
            "nsapi.default-wifi-security": "WPA_WPA2",
            "nsapi.default-wifi-ssid": "\"\"",
            "nsapi.default-wifi-password": "\"\"",
            "mbed-trace.enable": true,
            "tls-socket.debug-level": 0,
            "platform.stdio-baud-rate": 115200,
            "platform.stdio-convert-newlines": false
        }
    }
}

cloud.cpp

C/C++
#define MQTTCLIENT_QOS1 0
#define MQTTCLIENT_QOS2 0

#include "mbed.h"
#include "ISM43362Interface.h"
#include "NTPClient.h"
#include "MQTTNetwork.h"
#include "MQTTmbed.h"
#include "MQTT_server_setting.h"
#include "MQTTClient.h"
#include "mbed-trace/mbed_trace.h"
#include "mbed_events.h"
#include "mbedtls/error.h"

/*
    Private classes for MQTT handling
*/

ISM43362Interface wifi(false);

MQTTNetwork* mqttNetwork = NULL;
MQTT::Client<MQTTNetwork, Countdown>* mqttClient = NULL;

static unsigned short mqtt_message_id = 0;

/*
    Sync clock with NTP server
*/
void cloud_sync_clock(NetworkInterface* network){
    NTPClient ntp(network);
    
    /* use PTB server in Braunschweig */
    ntp.set_server("ptbtime1.ptb.de", 123);
    
    time_t now = ntp.get_timestamp();
    set_time(now);    
}

/*
    initialise cloud enviroment
*/
void cloud_init(){
    /* connect to the wifi network */
    int w_ret = wifi.connect(MBED_CONF_APP_WIFI_SSID, MBED_CONF_APP_WIFI_PASSWORD, NSAPI_SECURITY_WPA_WPA2);
    if(w_ret == 0) {
        printf("WIFI is now connected\r\n");
    }else{
        printf("Failed to connect WIFI\r\n");
    }
    
    /* sync the clock */
    cloud_sync_clock(&wifi);    
}

/*
    Sends an MQTT message to the cloud
*/
void cloud_send(float temperature, float humidity){
    MQTT::Message message;
    message.retained = false;
    message.dup = false;
    
    const size_t buf_size = 512;
    char *buf = new char[buf_size];
    message.payload = (void*)buf;
    
    message.qos = MQTT::QOS0;
    message.id = mqtt_message_id++;
    int ret = snprintf(buf, buf_size, 
                "{\"sensor\":{\"temperature\":%.2f,\"humidity\":%.2f}}", 
                temperature, humidity);
    if(ret < 0) {
        printf("ERROR: snprintf() returns %d.", ret);
    }
    message.payloadlen = ret;
    
    int rc = mqttClient->publish("stm32/sensor", message);
    if(rc != MQTT::SUCCESS) {
        printf("ERROR: rc from MQTT publish is %d\r\n", rc);
    }
    printf("Message published: %s\r\n",buf);
    delete[] buf; 
}

/*
    Connects to cloud using TLS socket
*/
int cloud_connect(){
    int result = 0;
      
    /* create mqtt network instance */
    printf("Initialising MQTT network...");
    mqttNetwork = new MQTTNetwork(&wifi);
    int rc = mqttNetwork->connect(MQTT_SERVER_HOST_NAME, MQTT_SERVER_PORT, SSL_CA_PEM,
                SSL_CLIENT_CERT_PEM, SSL_CLIENT_PRIVATE_KEY_PEM);
    if (rc != MQTT::SUCCESS){
        printf("MQTT network not successful\r\n");
        return 0;
    }      
    
    /* create mqtt data packet */
    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
    data.MQTTVersion = 3;
    data.clientID.cstring = (char *)MQTT_CLIENT_ID;
    data.username.cstring = (char *)MQTT_USERNAME;
    data.password.cstring = (char *)MQTT_PASSWORD;

    /* execute client and send data */
    mqttClient = new MQTT::Client<MQTTNetwork, Countdown>(*mqttNetwork);
    rc = mqttClient->connect(data);
    if (rc != MQTT::SUCCESS) {
        printf("MQTT client failed\r\n");
        return 0;
    }else{
        printf("MQTT connect successful\r\n");
        result = 1;
    }
    
    return result;
}

Credits

Matteo Rizza
3 projects • 5 followers
Shend Osmanaj
3 projects • 3 followers
Shilpajoy 93
2 projects • 1 follower
alfin joji
3 projects • 3 followers

Comments