Publisher for IBM Quickstart and Watson IoT cloud.
Dependencies: MQTT NDefLib X_NUCLEO_IKS01A2 X_NUCLEO_NFC01A1
Fork of Cloud_IBM_MbedOS by
To start the demo the following expansion boards are required
X_NUCLEO_IDW01M1v2, X_NUCLEO_IKS01A2, X_NUCLEO_NFC01A1
and as MCU board the NUCLEO-L476RG as it include a True Random Number Generator needed for TLS.
After having mounted the board stack on the Nucleo board the below steps should be followed:
- In case the X-NUCLEO-NFC-01A1 is on the board stack the WiFi SSID and password can be passed through the NFC tag by means of: 1) enabling the NFC support defining the X_NUCLEO_NFC01A1_PRESENT and recompiling, 2) when prompted on hyperterminal, programming the SSID and password to NFC using the Android app "NFCtools"
- In case the NFC is not present, you local WiFi SSID and password can be programmed to mbed_app.json file and compiling and flashing the binary. Make sure the Wifi network has visible SSID.
- Reset the Nucleo board and after few seconds the Nucleo green led will be on (it means the Nucleo is connected to the local Wifi and to the IBM cloud server)
- Read the NFC tag with an Android device and the browser will be automatically opened and directed to the specific IBM quickstart demo page where the environmental values are displayed in form of a x-y graph. The values are updated every few seconds. On the Hyperterminal is possible to see the values sent to the IBM cloud server and the board mac address to be entered on the IBM quickstart web page if a manual connection is needed (eg. to connect from a PC browser).
In case of registered connection ( internetofthings.ibmcloud.com ) is needed ( no TLS ) comment the #define ORG_QUICKSTART than check in the mbed_app.json the following fields and change them according to your IBM MQTT broker account, MQTT_ORG_ID, MQTT_DEVICE_PASSWORD, MQTT_DEVICE_ID, MQTT_DEVICE_TYPE.
In case of registered connection ( internetofthings.ibmcloud.com ) with TLS encryption is needed, uncomment the #define TLS_EN and make sure the certificate (SSL_CA_PEM) is still valid.
In the default case the application connect to quickstart.internetofthings.ibmcloud.com without any encryption not authentication.
Revision 5:efa13fc5d99a, committed 2018-01-24
- Comitter:
- mapellil
- Date:
- Wed Jan 24 10:42:08 2018 +0100
- Parent:
- 4:df4138621205
- Child:
- 6:0fafb8229e58
- Commit message:
- Added TLS secured connection
Changed in this revision
--- a/MQTT.lib Fri Jan 05 14:53:46 2018 +0100 +++ b/MQTT.lib Wed Jan 24 10:42:08 2018 +0100 @@ -1,1 +1,1 @@ -https://os.mbed.com/users/mapellil/code/MQTT/#0534b5d3c941 +https://os.mbed.com/users/mapellil/code/MQTT/#688f195846f1
--- a/MQTTNetwork.h Fri Jan 05 14:53:46 2018 +0100
+++ b/MQTTNetwork.h Wed Jan 24 10:42:08 2018 +0100
@@ -2,39 +2,348 @@
#define _MQTTNETWORK_H_
#include "NetworkInterface.h"
-
+#include "mbedtls/platform.h"
+#include "mbedtls/ssl.h"
+#include "mbedtls/entropy.h"
+#include "mbedtls/ctr_drbg.h"
+#include "mbedtls/error.h"
+
+/* Change to a number between 1 and 4 to debug the TLS connection */
+#define DEBUG_LEVEL 0
+
+#if DEBUG_LEVEL > 0
+#include "mbedtls/debug.h"
+#endif
+
+#define TLS_OFF 0
+#define TLS_ON 1
+
+/* personalization string for the drbg */
+const char *DRBG_PERS = "mbed TLS Publisher for IBM Watson IoT";
+
+/* List of trusted root CA certificates
+ * currently only GlobalSign, the CA for os.mbed.com
+ *
+ * To add more than one root, just concatenate them.
+ */
+ mbedtls_entropy_context _entropy;
+ mbedtls_ctr_drbg_context _ctr_drbg;
+ mbedtls_x509_crt _cacert;
+ mbedtls_ssl_context _ssl;
+ mbedtls_ssl_config _ssl_conf;
+
class MQTTNetwork {
public:
- MQTTNetwork(NetworkInterface* aNetwork) : network(aNetwork) {
- socket = new TCPSocket();
+ MQTTNetwork(NetworkInterface *net_iface) : _network(net_iface) {
+ _tcpsocket = new TCPSocket();
+ _tcpsocket->set_blocking(false);
+ _is_tcpsocket_connected = 0;
}
~MQTTNetwork() {
- delete socket;
+ if (_is_tcpsocket_connected && _tls) {
+ mbedtls_ssl_session_reset( &_ssl );
+ mbedtls_entropy_free(&_entropy);
+ mbedtls_ctr_drbg_free(&_ctr_drbg);
+ mbedtls_x509_crt_free(&_cacert);
+ mbedtls_ssl_free(&_ssl);
+ mbedtls_ssl_config_free(&_ssl_conf);
+ }
+ _tcpsocket->close();
+ delete _tcpsocket;
}
-
+
int read(unsigned char* buffer, int len, int timeout) {
- socket->set_timeout(timeout);
- return socket->recv(buffer, len);
+ size_t _bpos = 0; int offset = 0; int ret = 0;
+ if (_tls) {
+//_tcpsocket->set_timeout(timeout);
+ /* Read data out of the socket */
+ offset = 0;
+ Countdown timer;
+ timer.countdown_ms(timeout);
+
+ do {
+ ret = mbedtls_ssl_read(&_ssl, buffer + offset,
+ len - offset );
+ if (ret > 0) offset += ret;
+ if (offset == len) return offset;
+ if (timer.expired()) return 0;
+ } while (ret == MBEDTLS_ERR_SSL_WANT_READ ||
+ ret == MBEDTLS_ERR_SSL_WANT_WRITE || ret == 0 );
+ if (ret == MBEDTLS_ERR_SSL_CLIENT_RECONNECT) {
+ print_mbedtls_error("MBEDTLS_ERR_SSL_CLIENT_RECONNECT\n\r", ret);
+ // int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl );
+ _tcpsocket->close();
+ _is_tcpsocket_connected = 0;
+ return ret;
+ }
+
+ if (ret < 0) {
+ print_mbedtls_error("mbedtls_ssl_read", ret);
+ _tcpsocket->close();
+ _is_tcpsocket_connected = 0;
+ return ret;
+ }
+ return ret;
+ } else {
+ _tcpsocket->set_blocking(true);
+ _tcpsocket->set_timeout(timeout);
+ return _tcpsocket->recv(buffer, len);
+ }
+ }
+
+
+ int write(unsigned char* buffer, int len, int timeout) {
+
+ size_t _bpos = len;
+ int offset = 0; int ret = 0;
+ if (_tls) {
+ do {
+ ret = mbedtls_ssl_write(&_ssl,
+ (const unsigned char *) buffer + offset,
+ _bpos - offset);
+ if (ret > 0)
+ offset += ret;
+ } while (offset < _bpos && (ret > 0 || ret == MBEDTLS_ERR_SSL_WANT_READ ||
+ ret == MBEDTLS_ERR_SSL_WANT_WRITE));
+ if (ret < 0) {
+ print_mbedtls_error("mbedtls_ssl_write", ret);
+ _tcpsocket->close();
+ _is_tcpsocket_connected = 0;
+ return ret;
+ }
+ return ret;
+ } else {
+ _tcpsocket->set_blocking(true);
+ _tcpsocket->set_timeout(timeout);
+ return _tcpsocket->send(buffer, len);
+ }
}
- int write(unsigned char* buffer, int len, int timeout) {
- socket->set_timeout(timeout);
- return socket->send(buffer, len);
- }
-
- int connect(const char* hostname, int port) {
- socket->open(network);
- return socket->connect(hostname, port);
+ int connect(const char* hostname, int port, unsigned int tls=TLS_OFF, const char * cert=NULL, unsigned int sizeof_cert=0) {
+ _tls = tls;
+ if (tls == TLS_ON) { printf ("--->TLS is ON\n\r"); assert (cert); };
+ if (tls == TLS_ON) {
+ mbedtls_entropy_init(&_entropy);
+ mbedtls_ctr_drbg_init(&_ctr_drbg);
+ mbedtls_x509_crt_init(&_cacert);
+ mbedtls_ssl_init(&_ssl);
+ mbedtls_ssl_config_init(&_ssl_conf);
+ /*
+ * Initialize TLS-related stuf.
+ */
+ int ret = 0;
+ if ((ret = mbedtls_ctr_drbg_seed(&_ctr_drbg, mbedtls_entropy_func, &_entropy,
+ (const unsigned char *) DRBG_PERS,
+ sizeof (DRBG_PERS))) != 0) {
+ print_mbedtls_error("mbedtls_crt_drbg_init", ret);
+ return ret;
+ }
+ if ((ret = mbedtls_x509_crt_parse(&_cacert, (const unsigned char *) cert,
+ sizeof_cert)) != 0) {
+ print_mbedtls_error("mbedtls_x509_crt_parse", ret);
+ return ret;
+ }
+ if ((ret = mbedtls_ssl_config_defaults(&_ssl_conf,
+ MBEDTLS_SSL_IS_CLIENT,
+ MBEDTLS_SSL_TRANSPORT_STREAM,
+ MBEDTLS_SSL_PRESET_DEFAULT)) != 0) {
+ print_mbedtls_error("mbedtls_ssl_config_defaults", ret);
+ return ret;
+ }
+ mbedtls_ssl_conf_ca_chain(&_ssl_conf, &_cacert, NULL);
+ mbedtls_ssl_conf_rng(&_ssl_conf, mbedtls_ctr_drbg_random, &_ctr_drbg);
+ /* It is possible to disable authentication by passing
+ * MBEDTLS_SSL_VERIFY_NONE in the call to mbedtls_ssl_conf_authmode()
+ */
+ mbedtls_ssl_conf_authmode(&_ssl_conf, MBEDTLS_SSL_VERIFY_REQUIRED);
+#if DEBUG_LEVEL > 0
+ mbedtls_ssl_conf_verify(&_ssl_conf, my_verify, NULL);
+ mbedtls_ssl_conf_dbg(&_ssl_conf, my_debug, NULL);
+ mbedtls_debug_set_threshold(DEBUG_LEVEL);
+#endif
+ if ((ret = mbedtls_ssl_setup(&_ssl, &_ssl_conf)) != 0) {
+ print_mbedtls_error("mbedtls_ssl_setup", ret);
+ return ret;
+ }
+ mbedtls_ssl_set_hostname(&_ssl, hostname);
+
+ mbedtls_ssl_set_bio(&_ssl, static_cast<void *>(_tcpsocket), ssl_send, ssl_recv, NULL );
+ /* Connect to the server */
+ _tcpsocket->open(_network);
+ mbedtls_printf("Connecting with %s port: %d\n", hostname, port);
+ ret = _tcpsocket->connect(hostname, port);
+ if (ret != NSAPI_ERROR_OK) {
+ mbedtls_printf("Failed to connect\n");
+ printf("MBED: Socket Error: %d\n", ret);
+ _tcpsocket->close();
+ return ret;
+ }
+ printf ("--->TCP Connected\n\r");
+ _is_tcpsocket_connected = 1;
+
+ /* Start the handshake, the rest will be done in onReceive() */
+ mbedtls_printf("Starting the TLS handshake...\n");
+ do {
+ ret = mbedtls_ssl_handshake(&_ssl);
+ } while (ret != 0 && (ret == MBEDTLS_ERR_SSL_WANT_READ ||
+ ret == MBEDTLS_ERR_SSL_WANT_WRITE));
+ if (ret < 0) {
+ print_mbedtls_error("mbedtls_ssl_handshake", ret);
+ _tcpsocket->close();
+ return ret;
+ }
+/* const uint32_t buf_size = 1024;
+ char *buf = new char[buf_size];
+ mbedtls_x509_crt_info(buf, buf_size, "\r ",
+ mbedtls_ssl_get_peer_cert(&_ssl));
+ mbedtls_printf("Server certificate:\n%s", buf);
+
+ uint32_t flags = mbedtls_ssl_get_verify_result(&_ssl);
+ if( flags != 0 )
+ {
+ mbedtls_x509_crt_verify_info(buf, buf_size, "\r ! ", flags);
+ printf("Certificate verification failed:\n%s\n", buf);
+ }
+ else
+ printf("Certificate verification passed\n\n");
+*/
+ _is_tcpsocket_connected = 1;
+ return ret;
+
+ } else { // tls off
+ printf ("--->TLS is OFF\n\r");
+ _tcpsocket->open(_network);
+ int ret = _tcpsocket->connect(hostname, port);
+ if (ret != NSAPI_ERROR_OK) {
+ mbedtls_printf("Failed to connect\n");
+ printf("MBED: Socket Error: %d\n", ret);
+ _tcpsocket->close();
+ return ret;
+ }
+ printf ("--->TCP Connected\n\r");
+ _is_tcpsocket_connected = 1;
+ return ret;
+ }
}
int disconnect() {
- return socket->close();
+ if (_is_tcpsocket_connected && _tls == TLS_ON) {
+ mbedtls_ssl_session_reset( &_ssl );
+ mbedtls_entropy_free(&_entropy);
+ mbedtls_ctr_drbg_free(&_ctr_drbg);
+ mbedtls_x509_crt_free(&_cacert);
+ mbedtls_ssl_free(&_ssl);
+ mbedtls_ssl_config_free(&_ssl_conf);
+ }
+ _is_tcpsocket_connected = 0;
+ return _tcpsocket->close();
}
+ bool isConnected () { return _is_tcpsocket_connected; }
+
private:
- NetworkInterface* network;
- TCPSocket* socket;
+ NetworkInterface* _network;
+ unsigned int _is_tcpsocket_connected;
+
+protected:
+ /**
+ * Helper for pretty-printing mbed TLS error codes
+ */
+ static void print_mbedtls_error(const char *name, int err) {
+ char buf[128];
+ mbedtls_strerror(err, buf, sizeof (buf));
+ mbedtls_printf("%s() failed: -0x%04x (%d): %s\n", name, -err, err, buf);
+ }
+
+#if DEBUG_LEVEL > 0
+ /**
+ * Debug callback for Mbed TLS
+ * Just prints on the USB serial port
+ */
+ static void my_debug(void *ctx, int level, const char *file, int line,
+ const char *str)
+ {
+ const char *p, *basename;
+ (void) ctx;
+
+ /* Extract basename from file */
+ for(p = basename = file; *p != '\0'; p++) {
+ if(*p == '/' || *p == '\\') {
+ basename = p + 1;
+ }
+ }
+
+ mbedtls_printf("%s:%04d: |%d| %s", basename, line, level, str);
+ }
+
+ /**
+ * Certificate verification callback for Mbed TLS
+ * Here we only use it to display information on each cert in the chain
+ */
+ static int my_verify(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags)
+ {
+ const uint32_t buf_size = 1024;
+ char *buf = new char[buf_size];
+ (void) data;
+
+ mbedtls_printf("\nVerifying certificate at depth %d:\n", depth);
+ mbedtls_x509_crt_info(buf, buf_size - 1, " ", crt);
+ mbedtls_printf("%s", buf);
+
+ if (*flags == 0)
+ mbedtls_printf("No verification issue for this certificate\n");
+ else
+ {
+ mbedtls_x509_crt_verify_info(buf, buf_size, " ! ", *flags);
+ mbedtls_printf("%s\n", buf);
+ }
+
+ delete[] buf;
+ return 0;
+ }
+#endif
+
+ /**
+ * Receive callback for Mbed TLS
+ */
+ static int ssl_recv(void *ctx, unsigned char *buf, size_t len) {
+ int recv = -1;
+ TCPSocket *socket = static_cast<TCPSocket *>(ctx);
+ recv = socket->recv(buf, len);
+
+ if(NSAPI_ERROR_WOULD_BLOCK == recv){
+ return MBEDTLS_ERR_SSL_WANT_READ;
+ }else if(recv < 0){
+ mbedtls_printf("Socket recv error %d\n", recv);
+ return -1;
+ }else{
+ return recv;
+ }
+ }
+
+ /**
+ * Send callback for Mbed TLS
+ */
+ static int ssl_send(void *ctx, const unsigned char *buf, size_t len) {
+ int size = -1;
+ TCPSocket *socket = static_cast<TCPSocket *>(ctx);
+ size = socket->send(buf, len);
+
+ if(NSAPI_ERROR_WOULD_BLOCK == size){
+ return MBEDTLS_ERR_SSL_WANT_WRITE;
+ }else if(size < 0){
+ mbedtls_printf("Socket send error %d\n", size);
+ return -1;
+ }else{
+ return size;
+ }
+ }
+
+ TCPSocket* _tcpsocket;
+ volatile bool _disconnected;
+ unsigned int _tls;
};
+
#endif // _MQTTNETWORK_H_
--- a/main.cpp Fri Jan 05 14:53:46 2018 +0100
+++ b/main.cpp Wed Jan 24 10:42:08 2018 +0100
@@ -15,6 +15,7 @@
*/
#include "mbed.h"
+#include <string.h>
#include "easy-connect.h"
#include "MQTTClient.h"
#include "XNucleoIKS01A2.h"
@@ -22,9 +23,41 @@
#include "NDefNfcTag.h"
#include "NDefLib/RecordType/RecordURI.h"
#include "RecordWifiConf.h"
+#include "MQTTmbed.h"
#include "MQTTNetwork.h"
-#include "MQTTmbed.h"
+
+/**** System configuration define ****/
+#define ORG_QUICKSTART // comment to connect to play.internetofthings.ibmcloud.com
+//#define SUBSCRIBE // uncomment to subscribe to broker msgs (not to be used with IBM broker)
+#define X_NUCLEO_NFC01A1_PRESENT // uncomment to add NFC support
+#ifndef ORG_QUICKSTART
+//#define TLS_EN // uncomment to add TLS to NON quickstart connections
+#endif
+#ifdef TLS_EN // Digicert Root Certificate in PEM format (from IBM website)
+const char SSL_CA_PEM[] ="-----BEGIN CERTIFICATE-----\n"
+"MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n"
+"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n"
+"d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n"
+"QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n"
+"MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n"
+"b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n"
+"9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n"
+"CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n"
+"nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n"
+"43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n"
+"T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n"
+"gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n"
+"BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n"
+"TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n"
+"DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n"
+"hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n"
+"06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n"
+"PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n"
+"YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n"
+"CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n"
+"-----END CERTIFICATE-----\n";
+#endif
//------------------------------------
// Hyperterminal configuration
@@ -34,10 +67,6 @@
static DigitalOut myled(LED1);
static bool quickstartMode = true; // set to false to connect with authentication tocken
static bool BlueButtonToggle = false;
-
-#define ORG_QUICKSTART // comment to connect to play.internetofthings.ibmcloud.com
-//#define SUBSCRIBE // uncomment to subscribe to broker msgs (not to be used with IBM broker)
-#define X_NUCLEO_NFC01A1_PRESENT // uncomment to add NFC support
#define MQTT_MAX_PACKET_SIZE 400
#define MQTT_MAX_PAYLOAD_SIZE 300
@@ -49,15 +78,21 @@
#define AUTH_TOKEN ""
//#define DEFAULT_TYPE_NAME "iotsample-mbed-Nucleo"
#define DEFAULT_TYPE_NAME "sensor"
+#define DEFAULT_PORT MQTT_PORT
#else // not def ORG_QUICKSTART
#define ORG MQTT_ORG_ID // connect to ORG.internetofthings.ibmcloud.com/ For a registered connection, replace with your org
#define ID MQTT_DEVICE_ID // For a registered connection is your device id
#define AUTH_TOKEN MQTT_DEVICE_PASSWORD // For a registered connection is a device auth-token
#define DEFAULT_TYPE_NAME MQTT_DEVICE_TYPE // For a registered connection is device type
+#ifdef TLS_EN
+#define DEFAULT_PORT MQTT_TLS_PORT
+#else
+#define DEFAULT_PORT MQTT_PORT
+#endif
#endif
#define TYPE DEFAULT_TYPE_NAME // For a registered connection, replace with your type
-#define IBM_IOT_PORT MQTT_PORT
+#define IBM_IOT_PORT DEFAULT_PORT
#define MAXLEN_MBED_CONF_APP_WIFI_SSID 32 // same as WIFI_SSID_MAX_LEN in easy_connect
#define MAXLEN_MBED_CONF_APP_WIFI_PASSWORD 64 // same as WIFI_PASSWORD_MAX_LEN
@@ -101,13 +136,13 @@
NDefLib::Record *r = readMsg[i];
// printf ("N record %d\n\r", readMsg.get_N_records());
if (r != NULL) {
- printf ("Record RecordType_t: %d\n\r", r->get_type());
+// printf ("Record RecordType_t: %d\n\r", r->get_type());
if (r->get_type() == NDefLib::Record::TYPE_WIFI_CONF) {
NDefLib::RecordWifiConf * temp = (NDefLib::RecordWifiConf*)r;
sprintf (ssid, "%s", temp->get_network_ssid().c_str());
sprintf (seckey, "%s", temp->get_network_key().c_str());
printf ("Read SSID: %s Passw: %s\n\r", ssid, seckey);
- ReadSSIDPassw =1;
+ ReadSSIDPassw =1;
}
else if (r->get_type() == NDefLib::Record::TYPE_UNKNOWN) { printf ("NFC RECORD TYPE_UNKNOWN\n\r"); }
}
@@ -200,31 +235,46 @@
LOG("Subscription URL: %s\n\r", subscription_url);
LOG("=====================================\n\r");
netConnecting = true;
- int rc = mqttNetwork->connect(hostname, IBM_IOT_PORT);
+
+#ifdef ORG_QUICKSTART
+int tls = TLS_OFF;
+const char * cert = NULL;
+unsigned int sizeof_cert = 0;
+#else // if !QUICKSTART possible to connect with TLS or not
+#ifdef TLS_EN
+int tls = TLS_ON;
+const char * cert = SSL_CA_PEM;
+unsigned int sizeof_cert = sizeof(SSL_CA_PEM);
+#else
+int tls = TLS_OFF;
+const char * cert = 0;
+unsigned int sizeof_cert = 0;
+#endif
+#endif
+
+ int rc = mqttNetwork->connect(hostname, IBM_IOT_PORT, tls, cert, sizeof_cert);
if (rc != 0)
{
printf("rc from TCP connect is %d\r\n", rc);
return rc;
}
-
- printf ("--->TCP Connected\n\r");
netConnected = true;
netConnecting = false;
-
+
// MQTT Connect
mqttConnecting = true;
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.MQTTVersion = 4;
data.struct_version=0;
data.clientID.cstring = clientId;
- data.keepAliveInterval = MQTT_KEEPALIVE; // in Sec
+ data.keepAliveInterval = 0; //MQTT_KEEPALIVE; // in Sec
if (!quickstartMode)
{
data.username.cstring = "use-token-auth";
data.password.cstring = auth_token;
printf ("AutToken: %s\n\r", auth_token);
}
- if ((rc = client->connect(data)) != 0) {
+ if ((rc = client->connect(data)) != MQTT::SUCCESS) {
printf("rc from MQTT connect is %d\r\n", rc);
connack_rc = rc;
return rc;
@@ -256,7 +306,7 @@
while (connect(client, mqttNetwork, network) != MQTT_CONNECTION_ACCEPTED)
{
if (connack_rc == MQTT_NOT_AUTHORIZED || connack_rc == MQTT_BAD_USERNAME_OR_PASSWORD) {
- printf ("File: %s, Line: %d Error: %d\n\r",__FILE__,__LINE__, connack_rc);
+ printf ("Error MQTT_BAD_USERNAME_OR_PASSWORDFile: %s, Line: %d Error: %d \n\r",__FILE__,__LINE__, connack_rc);
return; // don't reattempt to connect if credentials are wrong
}
int timeout = getConnTimeout(++retryAttempt);
@@ -299,14 +349,15 @@
LOG("Publishing %s\n\r", buf);
return client->publish(pubTopic, message);
}
+
int main()
{
myled=0;
DevI2C *i2c = new DevI2C(I2C_SDA, I2C_SCL);
i2c->frequency(400000);
-
- XNucleoIKS01A2 *mems_expansion_board = XNucleoIKS01A2::instance(i2c);
+
+ XNucleoIKS01A2 *mems_expansion_board = XNucleoIKS01A2::instance(i2c);
pressure_sensor = mems_expansion_board->pt_sensor;
temp_sensor1 = mems_expansion_board->ht_sensor;
humidity_sensor = mems_expansion_board->ht_sensor;
@@ -321,6 +372,11 @@
#endif
pc.printf("\r\nCloud_IBM_MbedOS Application\r\n");
+#if defined(MBED_MAJOR_VERSION)
+ printf("Using Mbed OS %d.%d.%d\n", MBED_MAJOR_VERSION, MBED_MINOR_VERSION, MBED_PATCH_VERSION);
+#else
+ printf("Using Mbed OS from master.\n");
+#endif
pc.printf("\r\nconnecting to AP\r\n");
quickstartMode=false;
@@ -340,7 +396,24 @@
if (!network) {
printf ("Error easy_connect\n\r");
return -1;
- }
+ }
+//================= TODO Set System Time ideally from NTP srv or from shell
+#if 0
+ time_t ctTime;
+ ctTime = time(NULL);
+ printf ("Start Secure Socket connection with one way server autentication test\n\r");
+ printf("Initial System Time is: %s\r\n", ctime(&ctTime));
+ printf("Need to adjust time? if yes enter time in seconds elapsed since Epoch (cmd: date +'%%s'), otherwise enter 0 ");
+ int t=0;
+ scanf("%d",&t);
+ printf ("entered time is: %d \n\r", t);
+ if (t != 0) { time_t txTm = t; set_time(txTm); } // set Nucleo system time
+ ctTime = time(NULL);
+ printf ("The current system time is: %s", ctime (&ctTime)); // set WiFi module systm time
+ WiFiInterface* wifi = easy_get_wifi(0);
+ if (!((SpwfSAInterface*)wifi)->set_time(ctTime)) printf ("ERROR set_time\n\r");
+#endif
+//=================
MQTTNetwork mqttNetwork(network);
MQTT::Client<MQTTNetwork, Countdown, MQTT_MAX_PACKET_SIZE> client(mqttNetwork);
@@ -374,31 +447,34 @@
{
if (BlueButtonToggle == false && connected == true) {
if (++count == 6)
- { // Publish a message every 3 second
+ {
+ // Publish a message every 3 second
if (publish(&client) != MQTT::SUCCESS) {
myled=0;
- count=0;
- client.disconnect();
- mqttNetwork.disconnect();
+ count=0;
+ client.disconnect();
+ mqttNetwork.disconnect();
attemptConnect(&client, &mqttNetwork, network); // if we have lost the connection
} else {
- myled=1;
+ myled=1;
count=0;
}
}
- client.yield(500); // allow the MQTT client to receive subscribe messages and manage keep alive
+ if (client.isConnected()) client.yield(500); // allow the MQTT client to receive subscribe messages and manage keep alive
} else if (BlueButtonToggle == true && connected == true){ // disconnect MQTT
printf ("--->> MQTT Disconnect\n\r");
- connected = false;
+ connected = false;
+ myled=0;
count = 0;
BlueButtonToggle = false;
#ifdef SUBSCRIBE
- // unsubscribe(const char* topicFilter); // unsubscribe if subscribed
+// unsubscribe(const char* topicFilter); // unsubscribe if subscribed
#endif
client.disconnect();
- printf ("--->> TCP Disconnect\n\r");
+ printf ("--->> TCP Disconnect\n\r");
mqttNetwork.disconnect();
} else if (BlueButtonToggle == true && connected == false) {
+ attemptConnect(&client, &mqttNetwork, network);
connected = true;
BlueButtonToggle = false;
} else wait (0.5);
--- a/mbed-os.lib Fri Jan 05 14:53:46 2018 +0100 +++ b/mbed-os.lib Wed Jan 24 10:42:08 2018 +0100 @@ -1,1 +1,1 @@ -https://github.com/ARMmbed/mbed-os/#ca661f9d28526ca8f874b05432493a489c9671ea \ No newline at end of file +https://github.com/ARMmbed/mbed-os/#eca67ca7dafab4ef70c21e2463b541132d0dd691
--- a/mbed_app.json Fri Jan 05 14:53:46 2018 +0100
+++ b/mbed_app.json Wed Jan 24 10:42:08 2018 +0100
@@ -5,10 +5,10 @@
"value": "WIFI_IDW0XX1"
},
"wifi-ssid": {
- "value": "\"SSID\""
+ "value": "\"crespan\""
},
"wifi-password": {
- "value": "\"passw\""
+ "value": "\"password\""
},
"wifi-tx": {
"help": "TX pin for serial connection to external device",
@@ -23,13 +23,16 @@
"MQTT_CLIENT_ID=\"g:pvko17:<your DEVICE_ID_TYPE>:<your DEVICE_ID>\"",
"MQTT_ORG_ID=\"93ygbc\"",
"MQTT_USERNAME=\"use-token-auth\"",
- "MQTT_DEVICE_PASSWORD=\"devpassw\"",
+ "MQTT_DEVICE_PASSWORD=\"Sonmi123\"",
"MQTT_TOPIC=\"iot-2/evt/status/fmt/json\"",
"MQTT_DEVICE_ID=\"licio\"",
"MQTT_DEVICE_TYPE=\"envsens\"",
"MQTT_KEEPALIVE 10",
"MQTT_PORT 1883",
- "MQTT_TLS_PORT 8883"],
+ "MQTT_TLS_PORT 8883",
+ "MBED_CONF_APP_MAIN_STACK_SIZE=5120",
+ "MBEDTLS_USER_CONFIG_FILE=\"mbedtls_entropy_config.h\""
+ ],
"target_overrides": {
"*": {
"target.features_add": ["NANOSTACK", "LOWPAN_ROUTER", "COMMON_PAL"],
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/mbedtls_entropy_config.h Wed Jan 24 10:42:08 2018 +0100 @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2006-2016, Arm Limited, All Rights Reserved + * 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. + * + * This file is part of Mbed TLS (https://tls.mbed.org) + */ + +#if !defined(MBEDTLS_ENTROPY_HARDWARE_ALT) && \ + !defined(MBEDTLS_ENTROPY_NV_SEED) && !defined(MBEDTLS_TEST_NULL_ENTROPY) +#error "This hardware does not have an entropy source." +#endif /* !MBEDTLS_ENTROPY_HARDWARE_ALT && !MBEDTLS_ENTROPY_NV_SEED && + * !MBEDTLS_TEST_NULL_ENTROPY */ + +#if !defined(MBEDTLS_SHA1_C) +#define MBEDTLS_SHA1_C +#endif /* !MBEDTLS_SHA1_C */ + +/* + * This value is sufficient for handling 2048 bit RSA keys. + * + * Set this value higher to enable handling larger keys, but be aware that this + * will increase the stack usage. + */ +#define MBEDTLS_MPI_MAX_SIZE 256 + +#define MBEDTLS_MPI_WINDOW_SIZE 1 + +#if defined(TARGET_STM32F439xI) && defined(MBEDTLS_CONFIG_HW_SUPPORT) +#undef MBEDTLS_AES_ALT +#endif /* TARGET_STM32F439xI && MBEDTLS_CONFIG_HW_SUPPORT */
