Catie fork
Dependencies: SDFileSystem X_NUCLEO_IKS01A1
Fork of ATT_AWS_IoT_demo by
Diff: main.cpp
- Revision:
- 15:6f2798e45099
- Parent:
- 12:1ae41c231014
- Child:
- 16:02008a2a2569
diff -r 339320b096c5 -r 6f2798e45099 main.cpp --- a/main.cpp Fri Oct 28 13:30:20 2016 +0100 +++ b/main.cpp Thu Dec 01 18:05:38 2016 +0000 @@ -1,448 +1,382 @@ /* - * Hello world example of a TLS client: fetch an HTTPS page - * - * 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) + * AT&T IoT Starter Kit example using Amazon Web Service */ +#include "mbed.h" + +// Serial extension +#include "MODSERIAL.h" -/** \file main.cpp - * \brief An example TLS Client application - * This application sends an HTTPS request to developer.mbed.org and searches for a string in - * the result. - * - * This example is implemented as a logic class (HelloHTTPS) wrapping a TCP socket. - * The logic class handles all events, leaving the main loop to just check if the process - * has finished. - */ +// Network includes +#include "WNCInterface.h" +#include "network_interface.h" -/* Change to a number between 1 and 4 to debug the TLS connection */ -#define DEBUG_LEVEL 0 - -#include "mbed.h" -#include "NetworkStack.h" - -#include "EthernetInterface.h" -#include "TCPSocket.h" - -#include "mbedtls/platform.h" -#include "mbedtls/ssl.h" -#include "mbedtls/entropy.h" -#include "mbedtls/ctr_drbg.h" -#include "mbedtls/error.h" +// AWS includes +#include "aws_iot_log.h" +#include "aws_iot_version.h" +#include "aws_iot_shadow_interface.h" +#include "aws_iot_shadow_json_data.h" +#include "aws_iot_config.h" +#include "aws_iot_mqtt_interface.h" #if DEBUG_LEVEL > 0 #include "mbedtls/debug.h" #endif -namespace { - -const char *HTTPS_SERVER_NAME = "developer.mbed.org"; -const int HTTPS_SERVER_PORT = 443; -const int RECV_BUFFER_SIZE = 600; - -const char HTTPS_PATH[] = "/media/uploads/mbed_official/hello.txt"; -const size_t HTTPS_PATH_LEN = sizeof(HTTPS_PATH) - 1; - -/* Test related data */ -const char *HTTPS_OK_STR = "200 OK"; -const char *HTTPS_HELLO_STR = "Hello world!"; - -/* personalization string for the drbg */ -const char *DRBG_PERS = "mbed TLS helloword client"; +//===================================================================================================================== +// +// Defines +// +//===================================================================================================================== +// LED Colors +#define COLOR_OFF 0x00 +#define COLOR_RED 0x01 +#define COLOR_GREEN 0x02 +#define COLOR_BLUE 0x04 +#define COLOR_WHITE 0x07 +#define NUM_COLORS 5 -/* List of trusted root CA certificates - * currently only GlobalSign, the CA for developer.mbed.org - * - * To add more than one root, just concatenate them. - */ -const char SSL_CA_PEM[] = "-----BEGIN CERTIFICATE-----\n" - "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG\n" - "A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv\n" - "b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw\n" - "MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i\n" - "YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT\n" - "aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ\n" - "jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp\n" - "xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp\n" - "1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG\n" - "snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ\n" - "U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8\n" - "9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E\n" - "BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B\n" - "AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz\n" - "yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE\n" - "38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP\n" - "AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad\n" - "DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME\n" - "HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n" - "-----END CERTIFICATE-----\n"; - -} - -/** - * \brief HelloHTTPS implements the logic for fetching a file from a webserver - * using a TCP socket and parsing the result. - */ -class HelloHTTPS { -public: - /** - * HelloHTTPS Constructor - * Initializes the TCP socket, sets up event handlers and flags. - * - * @param[in] domain The domain name to fetch from - * @param[in] port The port of the HTTPS server - */ - HelloHTTPS(const char * domain, const uint16_t port, NetworkInterface *net_iface) : - _domain(domain), _port(port) - { - - _error = false; - _gothello = false; - _got200 = false; - _bpos = 0; - _request_sent = 0; - _tcpsocket = new TCPSocket(net_iface); +// AWS defines +#define PATH_MAX 4096 +#define MAX_LENGTH_OF_UPDATE_JSON_BUFFER 200 // NOTE: Be wary of this if your JSON doc grows +#define SHADOW_SYNC_INTERVAL 3.0 // How often we sync with AWS Shadow (in seconds) - 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); - } - /** - * HelloHTTPS Desctructor - */ - ~HelloHTTPS() { - 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); - } - /** - * Start the test. - * - * Starts by clearing test flags, then resolves the address with DNS. - * - * @param[in] path The path of the file to fetch from the HTTPS server - * @return SOCKET_ERROR_NONE on success, or an error code on failure - */ - void startTest(const char *path) { - /* Initialize the flags */ - _got200 = false; - _gothello = false; - _error = false; - _disconnected = false; - _request_sent = false; - /* Fill the request buffer */ - _bpos = snprintf(_buffer, sizeof(_buffer) - 1, "GET %s HTTP/1.1\nHost: %s\n\n", path, HTTPS_SERVER_NAME); - - /* - * Initialize TLS-related stuf. - */ - int ret; - 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); - _error = true; - return; - } - - if ((ret = mbedtls_x509_crt_parse(&_cacert, (const unsigned char *) SSL_CA_PEM, - sizeof (SSL_CA_PEM))) != 0) { - print_mbedtls_error("mbedtls_x509_crt_parse", ret); - _error = true; - return; - } - - 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); - _error = true; - return; - } - - 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); +// Comment out the following line if color is not supported on the terminal +//#define USE_COLOR +#ifdef USE_COLOR + #define BLK "\033[30m" + #define RED "\033[31m" + #define GRN "\033[32m" + #define YEL "\033[33m" + #define BLU "\033[34m" + #define MAG "\033[35m" + #define CYN "\033[36m" + #define WHT "\033[37m" + #define DEF "\033[39m" +#else + #define BLK + #define RED + #define GRN + #define YEL + #define BLU + #define MAG + #define CYN + #define WHT + #define DEF #endif - if ((ret = mbedtls_ssl_setup(&_ssl, &_ssl_conf)) != 0) { - print_mbedtls_error("mbedtls_ssl_setup", ret); - _error = true; - return; - } +//===================================================================================================================== +// +// Globals +// +//===================================================================================================================== +// Controls LED color +unsigned char ledColor = COLOR_OFF; + +// Color cycle array (used with SW3 button presses) +unsigned char colorCycle[NUM_COLORS] = {COLOR_OFF, COLOR_RED, COLOR_GREEN, COLOR_BLUE, COLOR_WHITE}; - mbedtls_ssl_set_hostname(&_ssl, HTTPS_SERVER_NAME); +// Button interrupts +bool buttonOverride = false; +InterruptIn Interrupt(SW3); + +// Default cert location +//char certDirectory[PATH_MAX + 1] = "../../../certs"; + +// Default MQTT HOST URL is pulled from the aws_iot_config.h +char HostAddress[255] = AWS_IOT_MQTT_HOST; + +// Default MQTT port is pulled from the aws_iot_config.h +uint32_t port = AWS_IOT_MQTT_PORT; - mbedtls_ssl_set_bio(&_ssl, static_cast<void *>(_tcpsocket), - ssl_send, ssl_recv, NULL ); +//===================================================================================================================== +// +// Devices +// +//===================================================================================================================== +// GPIOs for RGB LED +DigitalOut led_green(LED_GREEN); +DigitalOut led_red(LED_RED); +DigitalOut led_blue(LED_BLUE); +// USB Serial port (to PC) +MODSERIAL pc(USBTX,USBRX,256,256); - /* Connect to the server */ - mbedtls_printf("Connecting with %s\r\n", _domain); - ret = _tcpsocket->connect(_domain, _port); - if (ret != NSAPI_ERROR_OK) { - mbedtls_printf("Failed to connect\r\n"); - onError(_tcpsocket, -1); - return; - } +//===================================================================================================================== +// +// Functions +// +//===================================================================================================================== +//********************************************************************************************************************* +//* Prints the given format to the PC serial port. Exposed to all files via aws_iot_log.h +//********************************************************************************************************************* +void pc_print(const char * format, ...) +{ + va_list vl; + va_start(vl, format); + pc.vprintf(format, vl); + va_end(vl); +} - /* Start the handshake, the rest will be done in onReceive() */ - mbedtls_printf("Starting the TLS handshake...\r\n"); - ret = mbedtls_ssl_handshake(&_ssl); - if (ret < 0) { - if (ret != MBEDTLS_ERR_SSL_WANT_READ && - ret != MBEDTLS_ERR_SSL_WANT_WRITE) { - print_mbedtls_error("mbedtls_ssl_handshake", ret); - onError(_tcpsocket, -1 ); - } - return; - } +//********************************************************************************************************************* +//* Set the RGB LED's Color +//* LED Color 0=Off to 7=White. 3 bits represent BGR (bit0=Red, bit1=Green, bit2=Blue) +//********************************************************************************************************************* +void SetLedColor(unsigned char ucColor) +{ + //Note that when an LED is on, you write a 0 to it: + led_red = !(ucColor & 0x1); //bit 0 + led_green = !(ucColor & 0x2); //bit 1 + led_blue = !(ucColor & 0x4); //bit 2 +} - ret = mbedtls_ssl_write(&_ssl, (const unsigned char *) _buffer, _bpos); - if (ret < 0) { - if (ret != MBEDTLS_ERR_SSL_WANT_READ && - ret != MBEDTLS_ERR_SSL_WANT_WRITE) { - print_mbedtls_error("mbedtls_ssl_write", ret); - onError(_tcpsocket, -1 ); - } - return; - } - - /* It also means the handshake is done, time to print info */ - printf("TLS connection to %s established\r\n", HTTPS_SERVER_NAME); +//********************************************************************************************************************* +//* SW3 Button handler. Finds the current LED color and sets the button to the next color in colorCycle[] +//********************************************************************************************************************* +void sw3ButtonHandler() +{ + int i; + for(i=0; i < NUM_COLORS; i++) { + if (ledColor == colorCycle[i]) + break; + } + + // (circular-queue) + if (++i == NUM_COLORS) + i = 0; + + ledColor = colorCycle[i]; + SetLedColor(ledColor); + buttonOverride = true; +} - 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:\r\n%s\r", buf); +//===================================================================================================================== +// +// AWS Shadow Callbacks +// +//===================================================================================================================== +//********************************************************************************************************************* +//* This is the callback function that fires when an update is sent. It will print the update response status. +//********************************************************************************************************************* +void ShadowUpdateStatusCallback(const char *pThingName, ShadowActions_t action, Shadow_Ack_Status_t status, + const char *pReceivedJsonDocument, void *pContextData) { - 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:\r\n%s\r\r\n", buf); - } - else - printf("Certificate verification passed\r\n\r\n"); + INFO("Shadow Update Status Callback"); + + if (status == SHADOW_ACK_TIMEOUT) { + INFO("Update Timeout--"); + } else if (status == SHADOW_ACK_REJECTED) { + INFO("Update RejectedXX"); + } else if (status == SHADOW_ACK_ACCEPTED) { + INFO("Update Accepted!!"); // Good + } +} - - /* Read data out of the socket */ - ret = mbedtls_ssl_read(&_ssl, (unsigned char *) _buffer, sizeof(_buffer)); - if (ret < 0) { - if (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { - print_mbedtls_error("mbedtls_ssl_read", ret); - onError(_tcpsocket, -1 ); - } - delete[] buf; - return; +//********************************************************************************************************************* +//* This is the callback function that fires when AWS has sends out a shadow update. +//********************************************************************************************************************* +void ledControl_Callback(const char *pJsonString, uint32_t JsonStringDataLen, jsonStruct_t *pContext) { + + INFO("LED Callback Detected."); + + if (pContext != NULL) { + switch (*(unsigned char *)(pContext->pData)){ + case COLOR_OFF: + INFO("LED -> OFF (%d)", *(unsigned char *)(pContext->pData)); + break; + case COLOR_RED: + INFO("LED -> RED (%d)", *(unsigned char *)(pContext->pData)); + break; + case COLOR_GREEN: + INFO("LED -> GREEN (%d)", *(unsigned char *)(pContext->pData)); + break; + case COLOR_BLUE: + INFO("LED -> BLUE (%d)", *(unsigned char *)(pContext->pData)); + break; + case COLOR_WHITE: + INFO("LED -> WHITE (%d)", *(unsigned char *)(pContext->pData)); + break; } - _bpos = static_cast<size_t>(ret); - - _buffer[_bpos] = 0; - - /* Check each of the flags */ - _got200 = _got200 || strstr(_buffer, HTTPS_OK_STR) != NULL; - _gothello = _gothello || strstr(_buffer, HTTPS_HELLO_STR) != NULL; - - /* Print status messages */ - mbedtls_printf("HTTPS: Received %d chars from server\r\n", _bpos); - mbedtls_printf("HTTPS: Received 200 OK status ... %s\r\n", _got200 ? "[OK]" : "[FAIL]"); - mbedtls_printf("HTTPS: Received '%s' status ... %s\r\n", HTTPS_HELLO_STR, _gothello ? "[OK]" : "[FAIL]"); - mbedtls_printf("HTTPS: Received message:\r\n\r\n"); - mbedtls_printf("%s", _buffer); - _error = !(_got200 && _gothello); - - _tcpsocket->close(); - delete[] buf; + } + else { + INFO("pContext was detected as NULL"); } - /** - * Check if the test has completed. - * @return Returns true if done, false otherwise. - */ - bool done() { - return _error || (_got200 && _gothello); - } - /** - * Check if there was an error - * @return Returns true if there was an error, false otherwise. - */ - bool error() { - return _error; +} + +//===================================================================================================================== +// +// Main +// +//===================================================================================================================== +int main() { + + // Set baud rate for PC Serial + pc.baud(115200); + INFO("Hello World from AT&T IoT Start Kit demo!"); + + IoT_Error_t rc = NONE_ERROR; + char JsonDocumentBuffer[MAX_LENGTH_OF_UPDATE_JSON_BUFFER]; + size_t sizeOfJsonDocumentBuffer = sizeof(JsonDocumentBuffer) / sizeof(JsonDocumentBuffer[0]); + + // JSON struct for LED control + jsonStruct_t ledController; + ledController.cb = ledControl_Callback; + ledController.pData = &ledColor; + ledController.pKey = "ledColor"; + ledController.type = SHADOW_JSON_UINT8; + + // TODO Add FRDM temperature reading + /* + float temperature = 0.0; + jsonStruct_t temperatureHandler; + temperatureHandler.cb = NULL; + temperatureHandler.pKey = "temperature"; + temperatureHandler.pData = &temperature; + temperatureHandler.type = SHADOW_JSON_FLOAT; + */ + + INFO("AWS IoT SDK Version(dev) %d.%d.%d-%s", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG); + + // TODO: We could try to pull the certs from an SD card + /* + char rootCA[PATH_MAX + 1]; + char clientCRT[PATH_MAX + 1]; + char clientKey[PATH_MAX + 1]; + char CurrentWD[PATH_MAX + 1]; + char cafileName[] = AWS_IOT_ROOT_CA_FILENAME; + char clientCRTName[] = AWS_IOT_CERTIFICATE_FILENAME; + char clientKeyName[] = AWS_IOT_PRIVATE_KEY_FILENAME; + + getcwd(CurrentWD, sizeof(CurrentWD)); + sprintf(rootCA, "%s/%s/%s", CurrentWD, certDirectory, cafileName); + sprintf(clientCRT, "%s/%s/%s", CurrentWD, certDirectory, clientCRTName); + sprintf(clientKey, "%s/%s/%s", CurrentWD, certDirectory, clientKeyName); + + DEBUG("Using rootCA %s", rootCA); + DEBUG("Using clientCRT %s", clientCRT); + DEBUG("Using clientKey %s", clientKey); + */ + + // Blinks through RGB then turns off + SetLedColor(COLOR_RED); + wait(.5); + SetLedColor(COLOR_GREEN); + wait(.5); + SetLedColor(COLOR_BLUE); + wait(.5); + SetLedColor(COLOR_OFF); + + // Setup SW3 button to falling edge interrupt + Interrupt.fall(&sw3ButtonHandler); + + // Boot the Avnet Shield before any other operations + net_modem_boot(); + + INFO("Initialize the MQTT client..."); + MQTTClient_t mqttClient; + aws_iot_mqtt_init(&mqttClient); + + ShadowParameters_t sp = ShadowParametersDefault; + sp.pMyThingName = AWS_IOT_MY_THING_NAME; + sp.pMqttClientId = AWS_IOT_MQTT_CLIENT_ID; + sp.pHost = HostAddress; + sp.port = port; + //sp.pClientCRT = clientCRT; + //sp.pClientKey = clientKey; + //sp.pRootCA = rootCA; + sp.pClientCRT = AWS_IOT_CERTIFICATE_FILENAME; + sp.pClientKey = AWS_IOT_PRIVATE_KEY_FILENAME; + sp.pRootCA = AWS_IOT_ROOT_CA_FILENAME; + + INFO("Shadow Init..."); + rc = aws_iot_shadow_init(&mqttClient); + if (NONE_ERROR != rc) { + ERROR("Shadow Init Error %d", rc); + return rc; } - /** - * Closes the TCP socket - */ - void close() { - _tcpsocket->close(); - while (!_disconnected) - __WFI(); - } -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\r\n", name, -err, err, buf); + + INFO("Shadow Connect..."); + rc = aws_iot_shadow_connect(&mqttClient, &sp); + if (NONE_ERROR != rc) { + ERROR("Shadow Connection Error %d", rc); + return rc; } -#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; + // Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h + // #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL + // #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL + rc = mqttClient.setAutoReconnectStatus(true); + if (NONE_ERROR != rc) { + ERROR("Unable to set Auto Reconnect to true - %d", rc); + return rc; + } + + // Example line of how to delete a shadow (not used in this demo) + //aws_iot_shadow_delete(&mqttClient, AWS_IOT_MY_THING_NAME, ShadowUpdateStatusCallback, NULL, 8, true); - /* Extract basename from file */ - for(p = basename = file; *p != '\0'; p++) { - if(*p == '/' || *p == '\\') { - basename = p + 1; + INFO("Shadow Register Delta..."); + rc = aws_iot_shadow_register_delta(&mqttClient, &ledController); + if (NONE_ERROR != rc) { + ERROR("Shadow Register Delta Error"); + return rc; + } + + INFO("Will attempt to sync with device shadow every %f seconds.", SHADOW_SYNC_INTERVAL); + // Loop and publish changes from the FRDM board + while (NETWORK_ATTEMPTING_RECONNECT == rc || RECONNECT_SUCCESSFUL == rc || NONE_ERROR == rc) { + + // Looks for incoming socket messages + rc = aws_iot_shadow_yield(&mqttClient, 200); + if (NETWORK_ATTEMPTING_RECONNECT == rc) { + // If the client is attempting to reconnect we will skip the rest of the loop. + INFO("Attempting to reconnect..."); + wait(1); + continue; + } + + INFO("\n=======================================================================================\n"); + // Initialize JSON shadow document + rc = aws_iot_shadow_init_json_document(JsonDocumentBuffer, sizeOfJsonDocumentBuffer); + if (rc == NONE_ERROR) { + + // If there has been a SW3 button press update the 'desired' color + if (buttonOverride) { + rc = aws_iot_shadow_add_desired(JsonDocumentBuffer, sizeOfJsonDocumentBuffer, 1, &ledController); + buttonOverride = false; } - } - - mbedtls_printf("%s:%04d: |%d| %s", basename, line, level, str); + + // Updates the 'reported' color + rc = aws_iot_shadow_add_reported(JsonDocumentBuffer, sizeOfJsonDocumentBuffer, 1, &ledController); + + // TODO: format for adding temperature + //rc = aws_iot_shadow_add_reported(JsonDocumentBuffer, sizeOfJsonDocumentBuffer, 2, &ledController, &temperatureHandler); + + if (rc == NONE_ERROR) { + rc = aws_iot_finalize_json_document(JsonDocumentBuffer, sizeOfJsonDocumentBuffer); + + if (rc == NONE_ERROR) { + INFO("Update Shadow: %s", JsonDocumentBuffer); + rc = aws_iot_shadow_update(&mqttClient, AWS_IOT_MY_THING_NAME, JsonDocumentBuffer, + ShadowUpdateStatusCallback, NULL, 8, true); + } + } + } + INFO("*****************************************************************************************\n"); + + // Set LED color then wait an loop again + SetLedColor(ledColor); + wait(SHADOW_SYNC_INTERVAL); } - /** - * 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){ - 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 len; - }else if(size < 0){ - return -1; - }else{ - return size; - } + if (NONE_ERROR != rc) { + ERROR("An error occurred in the loop %d", rc); } - void onError(TCPSocket *s, int error) { - printf("MBED: Socket Error: %d\r\n", error); - s->close(); - _error = true; + INFO("Disconnecting"); + rc = aws_iot_shadow_disconnect(&mqttClient); + + if (NONE_ERROR != rc) { + ERROR("Disconnect error %d", rc); } -protected: - TCPSocket* _tcpsocket; - - const char *_domain; /**< The domain name of the HTTPS server */ - const uint16_t _port; /**< The HTTPS server port */ - char _buffer[RECV_BUFFER_SIZE]; /**< The response buffer */ - size_t _bpos; /**< The current offset in the response buffer */ - volatile bool _got200; /**< Status flag for HTTPS 200 */ - volatile bool _gothello; /**< Status flag for finding the test string */ - volatile bool _error; /**< Status flag for an error */ - volatile bool _disconnected; - volatile bool _request_sent; - - mbedtls_entropy_context _entropy; - mbedtls_ctr_drbg_context _ctr_drbg; - mbedtls_x509_crt _cacert; - mbedtls_ssl_context _ssl; - mbedtls_ssl_config _ssl_conf; -}; - -/** - * The main loop of the HTTPS Hello World test - */ -int main() { - /* The default 9600 bps is too slow to print full TLS debug info and could - * cause the other party to time out. */ - - /* Inititalise with DHCP, connect, and start up the stack */ - EthernetInterface eth_iface; - eth_iface.connect(); - mbedtls_printf("Using Ethernet LWIP\r\n"); - const char *ip_addr = eth_iface.get_ip_address(); - if (ip_addr) { - mbedtls_printf("Client IP Address is %s\r\n", ip_addr); - } else { - mbedtls_printf("No Client IP Address\r\n"); - } - - HelloHTTPS *hello = new HelloHTTPS(HTTPS_SERVER_NAME, HTTPS_SERVER_PORT, ð_iface); - hello->startTest(HTTPS_PATH); - delete hello; -} + return rc; +} \ No newline at end of file