From da660b234c1bc65f6304f9dd04c7ea0d0c230f17 Mon Sep 17 00:00:00 2001 From: Angus Gratton Date: Wed, 5 Oct 2016 16:32:09 +1100 Subject: [PATCH] AWS IoT Device SDK Support Use device cert/key embedded in firmware, or loaded from filesystem. --- .gitignore | 10 +- .gitlab-ci.yml | 1 + .gitmodules | 3 + components/aws_iot/Kconfig | 32 ++ .../aws_iot/aws-iot-device-sdk-embedded-C | 1 + components/aws_iot/component.mk | 20 + components/aws_iot/include/aws_iot_config.h | 60 +++ components/aws_iot/include/aws_iot_log.h | 44 ++ components/aws_iot/include/network_platform.h | 64 +++ components/aws_iot/include/threads_platform.h | 45 ++ components/aws_iot/include/timer_platform.h | 40 ++ .../aws_iot/port/network_mbedtls_wrapper.c | 408 ++++++++++++++++++ components/aws_iot/port/threads_freertos.c | 104 +++++ components/aws_iot/port/timer.c | 83 ++++ examples/protocols/aws_iot/README.md | 131 ++++++ .../aws_iot/subscribe_publish/Makefile | 9 + .../aws_iot/subscribe_publish/README.md | 32 ++ .../subscribe_publish/main/Kconfig.projbuild | 60 +++ .../subscribe_publish/main/certs/README.md | 3 + .../main/certs/aws-root-ca.pem | 28 ++ .../subscribe_publish/main/component.mk | 22 + .../main/subscribe_publish_sample.c | 326 ++++++++++++++ .../subscribe_publish/sdkconfig.defaults | 9 + .../protocols/aws_iot/thing_shadow/Makefile | 9 + .../protocols/aws_iot/thing_shadow/README.md | 34 ++ .../thing_shadow/main/Kconfig.projbuild | 66 +++ .../aws_iot/thing_shadow/main/certs/README.md | 3 + .../thing_shadow/main/certs/aws-root-ca.pem | 28 ++ .../aws_iot/thing_shadow/main/component.mk | 22 + .../thing_shadow/main/thing_shadow_sample.c | 368 ++++++++++++++++ .../aws_iot/thing_shadow/sdkconfig.defaults | 8 + tools/unit-test-app/sdkconfig | 7 +- 32 files changed, 2076 insertions(+), 4 deletions(-) create mode 100644 components/aws_iot/Kconfig create mode 160000 components/aws_iot/aws-iot-device-sdk-embedded-C create mode 100644 components/aws_iot/component.mk create mode 100644 components/aws_iot/include/aws_iot_config.h create mode 100644 components/aws_iot/include/aws_iot_log.h create mode 100644 components/aws_iot/include/network_platform.h create mode 100644 components/aws_iot/include/threads_platform.h create mode 100644 components/aws_iot/include/timer_platform.h create mode 100644 components/aws_iot/port/network_mbedtls_wrapper.c create mode 100644 components/aws_iot/port/threads_freertos.c create mode 100644 components/aws_iot/port/timer.c create mode 100644 examples/protocols/aws_iot/README.md create mode 100644 examples/protocols/aws_iot/subscribe_publish/Makefile create mode 100644 examples/protocols/aws_iot/subscribe_publish/README.md create mode 100644 examples/protocols/aws_iot/subscribe_publish/main/Kconfig.projbuild create mode 100644 examples/protocols/aws_iot/subscribe_publish/main/certs/README.md create mode 100644 examples/protocols/aws_iot/subscribe_publish/main/certs/aws-root-ca.pem create mode 100644 examples/protocols/aws_iot/subscribe_publish/main/component.mk create mode 100644 examples/protocols/aws_iot/subscribe_publish/main/subscribe_publish_sample.c create mode 100644 examples/protocols/aws_iot/subscribe_publish/sdkconfig.defaults create mode 100644 examples/protocols/aws_iot/thing_shadow/Makefile create mode 100644 examples/protocols/aws_iot/thing_shadow/README.md create mode 100644 examples/protocols/aws_iot/thing_shadow/main/Kconfig.projbuild create mode 100644 examples/protocols/aws_iot/thing_shadow/main/certs/README.md create mode 100644 examples/protocols/aws_iot/thing_shadow/main/certs/aws-root-ca.pem create mode 100644 examples/protocols/aws_iot/thing_shadow/main/component.mk create mode 100644 examples/protocols/aws_iot/thing_shadow/main/thing_shadow_sample.c create mode 100644 examples/protocols/aws_iot/thing_shadow/sdkconfig.defaults diff --git a/.gitignore b/.gitignore index 82f7fd3f2b..5490ebb935 100644 --- a/.gitignore +++ b/.gitignore @@ -19,9 +19,9 @@ GPATH .settings # Example project files -examples/*/*/sdkconfig -examples/*/*/sdkconfig.old -examples/*/*/build +examples/**/sdkconfig +examples/**/sdkconfig.old +examples/**/build #Doc build artifacts docs/_build/ @@ -33,3 +33,7 @@ docs/man/ tools/unit-test-app/sdkconfig tools/unit-test-app/sdkconfig.old tools/unit-test-app/build + +# AWS IoT Examples require device-specific certs/keys +examples/protocols/aws_iot/*/main/certs/*.pem.* + diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 27663db32b..1a88a2e80e 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -32,6 +32,7 @@ build_template_app: IDF_PATH: "$CI_PROJECT_DIR" GIT_STRATEGY: clone BATCH_BUILD: "1" + IDF_CI_BUILD: "1" script: - git clone https://github.com/espressif/esp-idf-template.git diff --git a/.gitmodules b/.gitmodules index 6a6af0e9d5..14a4cd85d4 100644 --- a/.gitmodules +++ b/.gitmodules @@ -13,3 +13,6 @@ [submodule "components/coap/libcoap"] path = components/coap/libcoap url = https://github.com/obgm/libcoap.git +[submodule "components/aws_iot/aws-iot-device-sdk-embedded-C"] + path = components/aws_iot/aws-iot-device-sdk-embedded-C + url = https://github.com/espressif/aws-iot-device-sdk-embedded-C.git diff --git a/components/aws_iot/Kconfig b/components/aws_iot/Kconfig new file mode 100644 index 0000000000..031def977d --- /dev/null +++ b/components/aws_iot/Kconfig @@ -0,0 +1,32 @@ +menuconfig AWS_IOT_SDK + bool "Amazon Web Services IoT Platform" + help + Select this option to enable support for the AWS IoT platform, + via the esp-idf component for the AWS IoT Device C SDK. + +config AWS_IOT_MQTT_HOST + string "AWS IoT Endpoint Hostname" + depends on AWS_IOT_SDK + default "" + help + Default endpoint host name to connect to AWS IoT MQTT/S gateway + + This is the custom endpoint hostname and is specific to an AWS + IoT account. You can find it by logging into your AWS IoT + Console and clicking the Settings button. The endpoint hostname + is shown under the "Custom Endpoint" heading on this page. + + If you need per-device hostnames for different regions or + accounts, you can override the default hostname in your app. + +config AWS_IOT_MQTT_PORT + int "AWS IoT MQTT Port" + depends on AWS_IOT_SDK + default 8883 + range 0 65535 + help + Default port number to connect to AWS IoT MQTT/S gateway + + If you need per-device port numbers for different regions, you can + override the default port number in your app. + diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C b/components/aws_iot/aws-iot-device-sdk-embedded-C new file mode 160000 index 0000000000..7132505b00 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C @@ -0,0 +1 @@ +Subproject commit 7132505b00d2dd57f48478e75efa636021919aae diff --git a/components/aws_iot/component.mk b/components/aws_iot/component.mk new file mode 100644 index 0000000000..cd1b15eeea --- /dev/null +++ b/components/aws_iot/component.mk @@ -0,0 +1,20 @@ +# +# Component Makefile +# + +ifdef CONFIG_AWS_IOT_SDK + +COMPONENT_ADD_INCLUDEDIRS := include aws-iot-device-sdk-embedded-C/include + +COMPONENT_SRCDIRS := aws-iot-device-sdk-embedded-C/src port + +# Check the submodule is initialised +COMPONENT_SUBMODULES := aws-iot-device-sdk-embedded-C + + +else +# Disable AWS IoT support +COMPONENT_ADD_INCLUDEDIRS := +COMPONENT_ADD_LDFLAGS := +COMPONENT_SRCDIRS := +endif diff --git a/components/aws_iot/include/aws_iot_config.h b/components/aws_iot/include/aws_iot_config.h new file mode 100644 index 0000000000..a19de46e08 --- /dev/null +++ b/components/aws_iot/include/aws_iot_config.h @@ -0,0 +1,60 @@ +/* + * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file 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. + */ + +/** + * @file aws_iot_config.h + * @brief AWS IoT specific configuration file + */ + +#ifndef _AWS_IOT_CONFIG_H_ +#define _AWS_IOT_CONFIG_H_ + +#include "aws_iot_log.h" + +// This configuration macro needs to be available globally to enable threading +#define _ENABLE_THREAD_SUPPORT_ + +// These values are defined in the menuconfig of the AWS IoT component. +// However, you can override these constants from your own code. +#define AWS_IOT_MQTT_HOST CONFIG_AWS_IOT_MQTT_HOST ///< Customer specific MQTT HOST. The same will be used for Thing Shadow +#define AWS_IOT_MQTT_PORT CONFIG_AWS_IOT_MQTT_PORT ///< default port for MQTT/S + +// These values are defaults and are used for ShadowConnectParametersDefault. +// You should override them from your own code. +#define AWS_IOT_MQTT_CLIENT_ID "ESP32" ///< MQTT client ID should be unique for every device +#define AWS_IOT_MY_THING_NAME "ESP32" ///< Thing Name of the Shadow this device is associated with + +// MQTT PubSub +#define AWS_IOT_MQTT_TX_BUF_LEN 512 ///< Any time a message is sent out through the MQTT layer. The message is copied into this buffer anytime a publish is done. This will also be used in the case of Thing Shadow +#define AWS_IOT_MQTT_RX_BUF_LEN 512 ///< Any message that comes into the device should be less than this buffer size. If a received message is bigger than this buffer size the message will be dropped. +#define AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS 5 ///< Maximum number of topic filters the MQTT client can handle at any given time. This should be increased appropriately when using Thing Shadow + +// Thing Shadow specific configs +#define SHADOW_MAX_SIZE_OF_RX_BUFFER (AWS_IOT_MQTT_RX_BUF_LEN + 1) ///< Maximum size of the SHADOW buffer to store the received Shadow message +#define MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES 80 ///< Maximum size of the Unique Client Id. For More info on the Client Id refer \ref response "Acknowledgments" +#define MAX_SIZE_CLIENT_ID_WITH_SEQUENCE (MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES + 10) ///< This is size of the extra sequence number that will be appended to the Unique client Id +#define MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE (MAX_SIZE_CLIENT_ID_WITH_SEQUENCE + 20) ///< This is size of the the total clientToken key and value pair in the JSON +#define MAX_ACKS_TO_COMEIN_AT_ANY_GIVEN_TIME 10 ///< At Any given time we will wait for this many responses. This will correlate to the rate at which the shadow actions are requested +#define MAX_THINGNAME_HANDLED_AT_ANY_GIVEN_TIME 10 ///< We could perform shadow action on any thing Name and this is maximum Thing Names we can act on at any given time +#define MAX_JSON_TOKEN_EXPECTED 120 ///< These are the max tokens that is expected to be in the Shadow JSON document. Include the metadata that gets published +#define MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME 60 ///< All shadow actions have to be published or subscribed to a topic which is of the formablogt $aws/things/{thingName}/shadow/update/accepted. This refers to the size of the topic without the Thing Name +#define MAX_SIZE_OF_THING_NAME 20 ///< The Thing Name should not be bigger than this value. Modify this if the Thing Name needs to be bigger +#define MAX_SHADOW_TOPIC_LENGTH_BYTES (MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME + MAX_SIZE_OF_THING_NAME) ///< This size includes the length of topic with Thing Name + +// Auto Reconnect specific config +#define AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL 1000 ///< Minimum time before the First reconnect attempt is made as part of the exponential back-off algorithm +#define AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL 128000 ///< Maximum time interval after which exponential back-off will stop attempting to reconnect. + +#endif /* _AWS_IOT_CONFIG_H_ */ diff --git a/components/aws_iot/include/aws_iot_log.h b/components/aws_iot/include/aws_iot_log.h new file mode 100644 index 0000000000..9a2043b3e2 --- /dev/null +++ b/components/aws_iot/include/aws_iot_log.h @@ -0,0 +1,44 @@ +// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD +// +// 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. +#pragma once + +/* (these two headers aren't used here, but AWS IoT SDK code relies on them + being included from here...) */ +#include +#include + +#include "esp_log.h" + +/* This is a stub replacement for the aws_iot_log.h header in the AWS IoT SDK, + which redirects their logging framework into the esp-idf logging framework. + + The current (2.1.1) upstream AWS IoT SDK doesn't allow this as some of its + headers include aws_iot_log.h, but our modified fork does. +*/ + +// redefine the AWS IoT log functions to call into the IDF log layer +#define IOT_DEBUG(format, ...) ESP_LOGD("aws_iot", format, ##__VA_ARGS__) +#define IOT_INFO(format, ...) ESP_LOGI("aws_iot", format, ##__VA_ARGS__) +#define IOT_WARN(format, ...) ESP_LOGW("aws_iot", format, ##__VA_ARGS__) +#define IOT_ERROR(format, ...) ESP_LOGE("aws_iot", format, ##__VA_ARGS__) + +/* Function tracing macros used in AWS IoT SDK, + mapped to "verbose" level output +*/ +#define FUNC_ENTRY ESP_LOGV("aws_iot", "FUNC_ENTRY: %s L#%d \n", __func__, __LINE__) +#define FUNC_EXIT_RC(x) \ + do { \ + ESP_LOGV("aws_iot", "FUNC_EXIT: %s L#%d Return Code : %d \n", __func__, __LINE__, x); \ + return x; \ + } while(0) diff --git a/components/aws_iot/include/network_platform.h b/components/aws_iot/include/network_platform.h new file mode 100644 index 0000000000..1193a409fc --- /dev/null +++ b/components/aws_iot/include/network_platform.h @@ -0,0 +1,64 @@ +/* + * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Additions Copyright 2016 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file 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. + */ + +#ifndef IOTSDKC_NETWORK_MBEDTLS_PLATFORM_H_H + +#if !defined(MBEDTLS_CONFIG_FILE) +#include "mbedtls/config.h" +#else +#include MBEDTLS_CONFIG_FILE +#endif + +#include "mbedtls/platform.h" +#include "mbedtls/net.h" +#include "mbedtls/ssl.h" +#include "mbedtls/entropy.h" +#include "mbedtls/ctr_drbg.h" +#include "mbedtls/certs.h" +#include "mbedtls/x509.h" +#include "mbedtls/error.h" +#include "mbedtls/debug.h" +#include "mbedtls/timing.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief TLS Connection Parameters + * + * Defines a type containing TLS specific parameters to be passed down to the + * TLS networking layer to create a TLS secured socket. + */ +typedef struct _TLSDataParams { + mbedtls_entropy_context entropy; + mbedtls_ctr_drbg_context ctr_drbg; + mbedtls_ssl_context ssl; + mbedtls_ssl_config conf; + uint32_t flags; + mbedtls_x509_crt cacert; + mbedtls_x509_crt clicert; + mbedtls_pk_context pkey; + mbedtls_net_context server_fd; +}TLSDataParams; + +#define IOTSDKC_NETWORK_MBEDTLS_PLATFORM_H_H + +#ifdef __cplusplus +} +#endif + +#endif //IOTSDKC_NETWORK_MBEDTLS_PLATFORM_H_H diff --git a/components/aws_iot/include/threads_platform.h b/components/aws_iot/include/threads_platform.h new file mode 100644 index 0000000000..011a1a0b23 --- /dev/null +++ b/components/aws_iot/include/threads_platform.h @@ -0,0 +1,45 @@ +/* + * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Additions Copyright 2016 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file 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. + */ + +#include "threads_interface.h" + +#ifndef AWS_IOTSDK_THREADS_PLATFORM_H +#define AWS_IOTSDK_THREADS_PLATFORM_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" + +/** + * @brief Mutex Type + * + * definition of the Mutex struct. Platform specific + * + */ +struct _IoT_Mutex_t { + SemaphoreHandle_t mutex; +}; + +#ifdef __cplusplus +} +#endif + +#endif /* AWS_IOTSDK_THREADS_PLATFORM_H */ + + diff --git a/components/aws_iot/include/timer_platform.h b/components/aws_iot/include/timer_platform.h new file mode 100644 index 0000000000..07e7385db3 --- /dev/null +++ b/components/aws_iot/include/timer_platform.h @@ -0,0 +1,40 @@ +/* + * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Additions Copyright 2016 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file 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. + */ + +#ifndef AWS_IOT_PLATFORM_H +#define AWS_IOT_PLATFORM_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "timer_interface.h" + +/** + * definition of the Timer struct. Platform specific + */ +struct Timer { + uint32_t start_ticks; + uint32_t timeout_ticks; + uint32_t last_polled_ticks; +}; + +#ifdef __cplusplus +} +#endif + +#endif /* AWS_IOT_PLATFORM_H */ diff --git a/components/aws_iot/port/network_mbedtls_wrapper.c b/components/aws_iot/port/network_mbedtls_wrapper.c new file mode 100644 index 0000000000..07e2ed4138 --- /dev/null +++ b/components/aws_iot/port/network_mbedtls_wrapper.c @@ -0,0 +1,408 @@ +/* + * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Additions Copyright 2016 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file 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. + */ +#include +#include +#include +#include +#include + +#include "aws_iot_config.h" +#include "aws_iot_error.h" +#include "network_interface.h" +#include "network_platform.h" + +#include "mbedtls/esp_debug.h" + +#include "esp_log.h" +#include "esp_vfs.h" + +static const char *TAG = "aws_iot"; + +/* This is the value used for ssl read timeout */ +#define IOT_SSL_READ_TIMEOUT 10 + +/* + * This is a function to do further verification if needed on the cert received. + * + * Currently used to print debug-level information about each cert. + */ +static int _iot_tls_verify_cert(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags) { + char buf[256]; + ((void) data); + + if (LOG_LOCAL_LEVEL >= ESP_LOG_DEBUG) { + ESP_LOGD(TAG, "Verify requested for (Depth %d):", depth); + mbedtls_x509_crt_info(buf, sizeof(buf) - 1, "", crt); + ESP_LOGD(TAG, "%s", buf); + + if((*flags) == 0) { + ESP_LOGD(TAG, " This certificate has no flags"); + } else { + ESP_LOGD(TAG, "Verify result:%s", buf); + } + } + + return 0; +} + +static void _iot_tls_set_connect_params(Network *pNetwork, const char *pRootCALocation, const char *pDeviceCertLocation, + const char *pDevicePrivateKeyLocation, const char *pDestinationURL, + uint16_t destinationPort, uint32_t timeout_ms, bool ServerVerificationFlag) { + pNetwork->tlsConnectParams.DestinationPort = destinationPort; + pNetwork->tlsConnectParams.pDestinationURL = pDestinationURL; + pNetwork->tlsConnectParams.pDeviceCertLocation = pDeviceCertLocation; + pNetwork->tlsConnectParams.pDevicePrivateKeyLocation = pDevicePrivateKeyLocation; + pNetwork->tlsConnectParams.pRootCALocation = pRootCALocation; + pNetwork->tlsConnectParams.timeout_ms = timeout_ms; + pNetwork->tlsConnectParams.ServerVerificationFlag = ServerVerificationFlag; +} + +IoT_Error_t iot_tls_init(Network *pNetwork, const char *pRootCALocation, const char *pDeviceCertLocation, + const char *pDevicePrivateKeyLocation, const char *pDestinationURL, + uint16_t destinationPort, uint32_t timeout_ms, bool ServerVerificationFlag) { + _iot_tls_set_connect_params(pNetwork, pRootCALocation, pDeviceCertLocation, pDevicePrivateKeyLocation, + pDestinationURL, destinationPort, timeout_ms, ServerVerificationFlag); + + pNetwork->connect = iot_tls_connect; + pNetwork->read = iot_tls_read; + pNetwork->write = iot_tls_write; + pNetwork->disconnect = iot_tls_disconnect; + pNetwork->isConnected = iot_tls_is_connected; + pNetwork->destroy = iot_tls_destroy; + + pNetwork->tlsDataParams.flags = 0; + + return SUCCESS; +} + +IoT_Error_t iot_tls_is_connected(Network *pNetwork) { + /* Use this to add implementation which can check for physical layer disconnect */ + return NETWORK_PHYSICAL_LAYER_CONNECTED; +} + +IoT_Error_t iot_tls_connect(Network *pNetwork, TLSConnectParams *params) { + int ret = SUCCESS; + TLSDataParams *tlsDataParams = NULL; + char portBuffer[6]; + char info_buf[256]; + + if(NULL == pNetwork) { + return NULL_VALUE_ERROR; + } + + if(NULL != params) { + _iot_tls_set_connect_params(pNetwork, params->pRootCALocation, params->pDeviceCertLocation, + params->pDevicePrivateKeyLocation, params->pDestinationURL, + params->DestinationPort, params->timeout_ms, params->ServerVerificationFlag); + } + + tlsDataParams = &(pNetwork->tlsDataParams); + + mbedtls_net_init(&(tlsDataParams->server_fd)); + mbedtls_ssl_init(&(tlsDataParams->ssl)); + mbedtls_ssl_config_init(&(tlsDataParams->conf)); + +#ifdef CONFIG_MBEDTLS_DEBUG + mbedtls_esp_enable_debug_log(&(tlsDataParams->conf), 4); +#endif + + mbedtls_ctr_drbg_init(&(tlsDataParams->ctr_drbg)); + mbedtls_x509_crt_init(&(tlsDataParams->cacert)); + mbedtls_x509_crt_init(&(tlsDataParams->clicert)); + mbedtls_pk_init(&(tlsDataParams->pkey)); + + ESP_LOGD(TAG, "Seeding the random number generator..."); + mbedtls_entropy_init(&(tlsDataParams->entropy)); + if((ret = mbedtls_ctr_drbg_seed(&(tlsDataParams->ctr_drbg), mbedtls_entropy_func, &(tlsDataParams->entropy), + (const unsigned char *) TAG, strlen(TAG))) != 0) { + ESP_LOGE(TAG, "failed! mbedtls_ctr_drbg_seed returned -0x%x", -ret); + return NETWORK_MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED; + } + + /* Load root CA... + + Certs/keys can be paths or they can be raw data. These use a + very basic heuristic: if the cert starts with '/' then it's a + path, if it's longer than this then it's raw cert data (PEM or DER, + neither of which can start with a slash. */ + if (pNetwork->tlsConnectParams.pRootCALocation[0] == '/') { + ESP_LOGD(TAG, "Loading CA root certificate from file ..."); + ret = mbedtls_x509_crt_parse_file(&(tlsDataParams->cacert), pNetwork->tlsConnectParams.pRootCALocation); + } else { + ESP_LOGD(TAG, "Loading embedded CA root certificate ..."); + ret = mbedtls_x509_crt_parse(&(tlsDataParams->cacert), (const unsigned char *)pNetwork->tlsConnectParams.pRootCALocation, + strlen(pNetwork->tlsConnectParams.pRootCALocation)+1); + } + + if(ret < 0) { + ESP_LOGE(TAG, "failed! mbedtls_x509_crt_parse returned -0x%x while parsing root cert", -ret); + return NETWORK_X509_ROOT_CRT_PARSE_ERROR; + } + ESP_LOGD(TAG, "ok (%d skipped)", ret); + + /* Load client certificate... */ + if (pNetwork->tlsConnectParams.pDeviceCertLocation[0] == '/') { + ESP_LOGD(TAG, "Loading client cert from file..."); + ret = mbedtls_x509_crt_parse_file(&(tlsDataParams->clicert), + pNetwork->tlsConnectParams.pDeviceCertLocation); + } else { + ESP_LOGD(TAG, "Loading embedded client certificate..."); + ret = mbedtls_x509_crt_parse(&(tlsDataParams->clicert), + (const unsigned char *)pNetwork->tlsConnectParams.pDeviceCertLocation, + strlen(pNetwork->tlsConnectParams.pDeviceCertLocation)+1); + } + if(ret != 0) { + ESP_LOGE(TAG, "failed! mbedtls_x509_crt_parse returned -0x%x while parsing device cert", -ret); + return NETWORK_X509_DEVICE_CRT_PARSE_ERROR; + } + + /* Parse client private key... */ + if (pNetwork->tlsConnectParams.pDevicePrivateKeyLocation[0] == '/') { + ESP_LOGD(TAG, "Loading client private key from file..."); + ret = mbedtls_pk_parse_keyfile(&(tlsDataParams->pkey), + pNetwork->tlsConnectParams.pDevicePrivateKeyLocation, + ""); + } else { + ESP_LOGD(TAG, "Loading embedded client private key..."); + ret = mbedtls_pk_parse_key(&(tlsDataParams->pkey), + (const unsigned char *)pNetwork->tlsConnectParams.pDevicePrivateKeyLocation, + strlen(pNetwork->tlsConnectParams.pDevicePrivateKeyLocation)+1, + (const unsigned char *)"", 0); + } + if(ret != 0) { + ESP_LOGE(TAG, "failed! mbedtls_pk_parse_key returned -0x%x while parsing private key", -ret); + return NETWORK_PK_PRIVATE_KEY_PARSE_ERROR; + } + + /* Done parsing certs */ + ESP_LOGD(TAG, "ok"); + snprintf(portBuffer, 6, "%d", pNetwork->tlsConnectParams.DestinationPort); + ESP_LOGD(TAG, "Connecting to %s/%s...", pNetwork->tlsConnectParams.pDestinationURL, portBuffer); + if((ret = mbedtls_net_connect(&(tlsDataParams->server_fd), pNetwork->tlsConnectParams.pDestinationURL, + portBuffer, MBEDTLS_NET_PROTO_TCP)) != 0) { + ESP_LOGE(TAG, "failed! mbedtls_net_connect returned -0x%x", -ret); + switch(ret) { + case MBEDTLS_ERR_NET_SOCKET_FAILED: + return NETWORK_ERR_NET_SOCKET_FAILED; + case MBEDTLS_ERR_NET_UNKNOWN_HOST: + return NETWORK_ERR_NET_UNKNOWN_HOST; + case MBEDTLS_ERR_NET_CONNECT_FAILED: + default: + return NETWORK_ERR_NET_CONNECT_FAILED; + }; + } + + ret = mbedtls_net_set_block(&(tlsDataParams->server_fd)); + if(ret != 0) { + ESP_LOGE(TAG, "failed! net_set_(non)block() returned -0x%x", -ret); + return SSL_CONNECTION_ERROR; + } ESP_LOGD(TAG, "ok"); + + ESP_LOGD(TAG, "Setting up the SSL/TLS structure..."); + if((ret = mbedtls_ssl_config_defaults(&(tlsDataParams->conf), MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT)) != 0) { + ESP_LOGE(TAG, "failed! mbedtls_ssl_config_defaults returned -0x%x", -ret); + return SSL_CONNECTION_ERROR; + } + + mbedtls_ssl_conf_verify(&(tlsDataParams->conf), _iot_tls_verify_cert, NULL); + + if(pNetwork->tlsConnectParams.ServerVerificationFlag == true) { + mbedtls_ssl_conf_authmode(&(tlsDataParams->conf), MBEDTLS_SSL_VERIFY_REQUIRED); + } else { + mbedtls_ssl_conf_authmode(&(tlsDataParams->conf), MBEDTLS_SSL_VERIFY_OPTIONAL); + } + mbedtls_ssl_conf_rng(&(tlsDataParams->conf), mbedtls_ctr_drbg_random, &(tlsDataParams->ctr_drbg)); + + mbedtls_ssl_conf_ca_chain(&(tlsDataParams->conf), &(tlsDataParams->cacert), NULL); + ret = mbedtls_ssl_conf_own_cert(&(tlsDataParams->conf), &(tlsDataParams->clicert), &(tlsDataParams->pkey)); + if(ret != 0) { + ESP_LOGE(TAG, "failed! mbedtls_ssl_conf_own_cert returned %d", ret); + return SSL_CONNECTION_ERROR; + } + + mbedtls_ssl_conf_read_timeout(&(tlsDataParams->conf), pNetwork->tlsConnectParams.timeout_ms); + + if((ret = mbedtls_ssl_setup(&(tlsDataParams->ssl), &(tlsDataParams->conf))) != 0) { + ESP_LOGE(TAG, "failed! mbedtls_ssl_setup returned -0x%x", -ret); + return SSL_CONNECTION_ERROR; + } + if((ret = mbedtls_ssl_set_hostname(&(tlsDataParams->ssl), pNetwork->tlsConnectParams.pDestinationURL)) != 0) { + ESP_LOGE(TAG, "failed! mbedtls_ssl_set_hostname returned %d", ret); + return SSL_CONNECTION_ERROR; + } + ESP_LOGD(TAG, "SSL state connect : %d ", tlsDataParams->ssl.state); + mbedtls_ssl_set_bio(&(tlsDataParams->ssl), &(tlsDataParams->server_fd), mbedtls_net_send, NULL, + mbedtls_net_recv_timeout); + ESP_LOGD(TAG, "ok"); + + ESP_LOGD(TAG, "SSL state connect : %d ", tlsDataParams->ssl.state); + ESP_LOGD(TAG, "Performing the SSL/TLS handshake..."); + while((ret = mbedtls_ssl_handshake(&(tlsDataParams->ssl))) != 0) { + if(ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { + ESP_LOGE(TAG, "failed! mbedtls_ssl_handshake returned -0x%x", -ret); + if(ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) { + ESP_LOGE(TAG, " Unable to verify the server's certificate. "); + } + return SSL_CONNECTION_ERROR; + } + } + + ESP_LOGD(TAG, "ok [ Protocol is %s ] [ Ciphersuite is %s ]", mbedtls_ssl_get_version(&(tlsDataParams->ssl)), + mbedtls_ssl_get_ciphersuite(&(tlsDataParams->ssl))); + if((ret = mbedtls_ssl_get_record_expansion(&(tlsDataParams->ssl))) >= 0) { + ESP_LOGD(TAG, " [ Record expansion is %d ]", ret); + } else { + ESP_LOGD(TAG, " [ Record expansion is unknown (compression) ]"); + } + + ESP_LOGD(TAG, "Verifying peer X.509 certificate..."); + + if(pNetwork->tlsConnectParams.ServerVerificationFlag == true) { + if((tlsDataParams->flags = mbedtls_ssl_get_verify_result(&(tlsDataParams->ssl))) != 0) { + ESP_LOGE(TAG, "failed"); + mbedtls_x509_crt_verify_info(info_buf, sizeof(info_buf), " ! ", tlsDataParams->flags); + ESP_LOGE(TAG, "%s", info_buf); + ret = SSL_CONNECTION_ERROR; + } else { + ESP_LOGD(TAG, "ok"); + ret = SUCCESS; + } + } else { + ESP_LOGW(TAG, " Server Verification skipped"); + ret = SUCCESS; + } + + if(LOG_LOCAL_LEVEL >= ESP_LOG_DEBUG) { + if (mbedtls_ssl_get_peer_cert(&(tlsDataParams->ssl)) != NULL) { + ESP_LOGD(TAG, "Peer certificate information:"); + mbedtls_x509_crt_info((char *) info_buf, sizeof(info_buf) - 1, " ", mbedtls_ssl_get_peer_cert(&(tlsDataParams->ssl))); + ESP_LOGD(TAG, "%s", info_buf); + } + } + + return (IoT_Error_t) ret; +} + +IoT_Error_t iot_tls_write(Network *pNetwork, unsigned char *pMsg, size_t len, Timer *timer, size_t *written_len) { + size_t written_so_far; + bool isErrorFlag = false; + int frags, ret = 0; + TLSDataParams *tlsDataParams = &(pNetwork->tlsDataParams); + + for(written_so_far = 0, frags = 0; + written_so_far < len && !has_timer_expired(timer); written_so_far += ret, frags++) { + while(!has_timer_expired(timer) && + (ret = mbedtls_ssl_write(&(tlsDataParams->ssl), pMsg + written_so_far, len - written_so_far)) <= 0) { + if(ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { + ESP_LOGE(TAG, "failed! mbedtls_ssl_write returned -0x%x", -ret); + /* All other negative return values indicate connection needs to be reset. + * Will be caught in ping request so ignored here */ + isErrorFlag = true; + break; + } + } + if(isErrorFlag) { + break; + } + } + + *written_len = written_so_far; + + if(isErrorFlag) { + return NETWORK_SSL_WRITE_ERROR; + } else if(has_timer_expired(timer) && written_so_far != len) { + return NETWORK_SSL_WRITE_TIMEOUT_ERROR; + } + + return SUCCESS; +} + +IoT_Error_t iot_tls_read(Network *pNetwork, unsigned char *pMsg, size_t len, Timer *timer, size_t *read_len) { + TLSDataParams *tlsDataParams = &(pNetwork->tlsDataParams); + mbedtls_ssl_context *ssl = &(tlsDataParams->ssl); + mbedtls_ssl_config *ssl_conf = &(tlsDataParams->conf); + uint32_t read_timeout; + size_t rxLen = 0; + int ret; + + read_timeout = ssl_conf->read_timeout; + + while (len > 0) { + + /* Make sure we never block on read for longer than timer has left, + but also that we don't block indefinitely (ie read_timeout > 0) */ + mbedtls_ssl_conf_read_timeout(ssl_conf, MAX(1, MIN(read_timeout, left_ms(timer)))); + + ret = mbedtls_ssl_read(ssl, pMsg, len); + + /* Restore the old timeout */ + mbedtls_ssl_conf_read_timeout(ssl_conf, read_timeout); + + if (ret > 0) { + rxLen += ret; + pMsg += ret; + len -= ret; + } else if (ret == 0 || (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE && ret != MBEDTLS_ERR_SSL_TIMEOUT)) { + return NETWORK_SSL_READ_ERROR; + } + + // Evaluate timeout after the read to make sure read is done at least once + if (has_timer_expired(timer)) { + break; + } + } + + if (len == 0) { + *read_len = rxLen; + return SUCCESS; + } + + if (rxLen == 0) { + return NETWORK_SSL_NOTHING_TO_READ; + } else { + return NETWORK_SSL_READ_TIMEOUT_ERROR; + } +} + +IoT_Error_t iot_tls_disconnect(Network *pNetwork) { + mbedtls_ssl_context *ssl = &(pNetwork->tlsDataParams.ssl); + int ret = 0; + do { + ret = mbedtls_ssl_close_notify(ssl); + } while(ret == MBEDTLS_ERR_SSL_WANT_WRITE); + + /* All other negative return values indicate connection needs to be reset. + * No further action required since this is disconnect call */ + + return SUCCESS; +} + +IoT_Error_t iot_tls_destroy(Network *pNetwork) { + TLSDataParams *tlsDataParams = &(pNetwork->tlsDataParams); + + mbedtls_net_free(&(tlsDataParams->server_fd)); + + mbedtls_x509_crt_free(&(tlsDataParams->clicert)); + mbedtls_x509_crt_free(&(tlsDataParams->cacert)); + mbedtls_pk_free(&(tlsDataParams->pkey)); + mbedtls_ssl_free(&(tlsDataParams->ssl)); + mbedtls_ssl_config_free(&(tlsDataParams->conf)); + mbedtls_ctr_drbg_free(&(tlsDataParams->ctr_drbg)); + mbedtls_entropy_free(&(tlsDataParams->entropy)); + + return SUCCESS; +} diff --git a/components/aws_iot/port/threads_freertos.c b/components/aws_iot/port/threads_freertos.c new file mode 100644 index 0000000000..065ead78cb --- /dev/null +++ b/components/aws_iot/port/threads_freertos.c @@ -0,0 +1,104 @@ +/* + * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Additions Copyright 2016 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file 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. + */ + + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" + +#include "threads_platform.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Initialize the provided mutex + * + * Call this function to initialize the mutex + * + * @param IoT_Mutex_t - pointer to the mutex to be initialized + * @return IoT_Error_t - error code indicating result of operation + */ +IoT_Error_t aws_iot_thread_mutex_init(IoT_Mutex_t *pMutex) { + + pMutex->mutex = xSemaphoreCreateRecursiveMutex(); + return pMutex->mutex ? SUCCESS : MUTEX_INIT_ERROR; +} + +/** + * @brief Lock the provided mutex + * + * Call this function to lock the mutex before performing a state change + * Blocking, thread will block until lock request fails + * + * @param IoT_Mutex_t - pointer to the mutex to be locked + * @return IoT_Error_t - error code indicating result of operation + */ +IoT_Error_t aws_iot_thread_mutex_lock(IoT_Mutex_t *pMutex) { + xSemaphoreTakeRecursive(pMutex->mutex, portMAX_DELAY); + return SUCCESS; +} + +/** + * @brief Try to lock the provided mutex + * + * Call this function to attempt to lock the mutex before performing a state change + * Non-Blocking, immediately returns with failure if lock attempt fails + * + * @param IoT_Mutex_t - pointer to the mutex to be locked + * @return IoT_Error_t - error code indicating result of operation + */ +IoT_Error_t aws_iot_thread_mutex_trylock(IoT_Mutex_t *pMutex) { + if (xSemaphoreTakeRecursive(pMutex->mutex, 0)) { + return SUCCESS; + } else { + return MUTEX_LOCK_ERROR; + } +} + +/** + * @brief Unlock the provided mutex + * + * Call this function to unlock the mutex before performing a state change + * + * @param IoT_Mutex_t - pointer to the mutex to be unlocked + * @return IoT_Error_t - error code indicating result of operation + */ +IoT_Error_t aws_iot_thread_mutex_unlock(IoT_Mutex_t *pMutex) { + if (xSemaphoreGiveRecursive(pMutex->mutex)) { + return SUCCESS; + } else { + return MUTEX_UNLOCK_ERROR; + } +} + +/** + * @brief Destroy the provided mutex + * + * Call this function to destroy the mutex + * + * @param IoT_Mutex_t - pointer to the mutex to be destroyed + * @return IoT_Error_t - error code indicating result of operation + */ +IoT_Error_t aws_iot_thread_mutex_destroy(IoT_Mutex_t *pMutex) { + vSemaphoreDelete(pMutex->mutex); + return SUCCESS; +} + +#ifdef __cplusplus +} +#endif + diff --git a/components/aws_iot/port/timer.c b/components/aws_iot/port/timer.c new file mode 100644 index 0000000000..ee4d8b5be1 --- /dev/null +++ b/components/aws_iot/port/timer.c @@ -0,0 +1,83 @@ +/* + * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Additions Copyright 2016 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file 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. + */ + +/** + * @file timer.c + * @brief FreeRTOS implementation of the timer interface uses ticks. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#include "timer_platform.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "esp_log.h" + +const static char *TAG = "aws_timer"; + +bool has_timer_expired(Timer *timer) { + uint32_t now = xTaskGetTickCount(); + bool expired = (now - timer->start_ticks) >= timer->timeout_ticks; + + /* AWS IoT SDK isn't very RTOS friendly because it polls for "done + timers" a lot without ever sleeping on them. So we hack in some + amount of sleeping here: if it seems like the caller is polling + an unexpired timer in a tight loop then we delay a tick to let + things progress elsewhere. + */ + if(!expired && now == timer->last_polled_ticks) { + vTaskDelay(1); + } + timer->last_polled_ticks = now; + return expired; +} + +void countdown_ms(Timer *timer, uint32_t timeout) { + timer->start_ticks = xTaskGetTickCount(); + timer->timeout_ticks = timeout / portTICK_PERIOD_MS; + timer->last_polled_ticks = 0; +} + +uint32_t left_ms(Timer *timer) { + uint32_t now = xTaskGetTickCount(); + uint32_t elapsed = now - timer->start_ticks; + if (elapsed < timer->timeout_ticks) { + return (timer->timeout_ticks - elapsed) * portTICK_PERIOD_MS; + } else { + return 0; + } +} + +void countdown_sec(Timer *timer, uint32_t timeout) { + if (timeout > UINT32_MAX / 1000) { + ESP_LOGE(TAG, "timeout is out of range: %ds", timeout); + } + countdown_ms(timer, timeout * 1000); +} + +void init_timer(Timer *timer) { + timer->start_ticks = 0; + timer->timeout_ticks = 0; + timer->last_polled_ticks = 0; +} + +#ifdef __cplusplus +} +#endif diff --git a/examples/protocols/aws_iot/README.md b/examples/protocols/aws_iot/README.md new file mode 100644 index 0000000000..e64fcc8b57 --- /dev/null +++ b/examples/protocols/aws_iot/README.md @@ -0,0 +1,131 @@ +# Amazon Web Services IoT Examples + +These examples are adaptations of some of the [AWS IoT C SDK](https://github.com/aws/aws-iot-device-sdk-embedded-C) examples. + +The provisioning/configuration steps for these examples are the same, and are given in this README. + +This README also contains some troubleshooting information for common problems found when connecting to AWS IoT. + +# Provisioning/Configuration + +There are some additional steps that need to be run before you can build this example. + +The [Getting Started section of the AWS IoT Developer Guide](http://docs.aws.amazon.com/iot/latest/developerguide/iot-gs.html) lays out the steps to get started with AWS IoT. + +To build and use this example, follow all the AWS IoT Getting Started steps from the beginning ("Sign in to the AWS Iot Console") up until "Configuring Your Device". For configuring the device, these are the steps: + +## Configuring Your Device + +### Installing Private Key & Certificate + +As part of creating a device certificate, you downloaded a Private Key (`xxx-private.pem.key`) and a Certificate file (`xxx-certificate.pem.crt`). These keys need to be loaded by the ESP32 to identify itself. + +There are currently two options for how to load the key & cert. + +* Embed the files into the app binary (default) +* Load the files from SD card + +### Option 1: Embedded Key & Cert into App Binary + +Copy the `.pem.key` and `.pem.crt` files to the `main/certs` subdirectory of the example. Rename them by removing the device-specific prefix - the new names are `private.pem.key` and `certificate.pem.crt`. + +As these files are bound to your AWS IoT account, take care not to accidentally commit them to public source control. In a commercial IoT device these files would be flashed to the device via a provisioning step, but for these examples they are compiled in. + +### Option 2: Loading Key & Cert from SD Card + +The alternative to embedding the key and certificate is to load them from a FAT filesystem on an SD card. + +Before loading data from SD, format your SD card as FAT and run the `examples/storage/sd_card` example on it to verify that it's working as expected in ESP-IDF. This helps cut down the possible causes of errors in the more complex AWS IoT examples! + +Run `make menuconfig`, navigate to "Example Configuration" and change "AWS IoT Certificate Source" to "Load from SD card". + +Three new prompts will appear for filenames for the device key, device certificate and root CA certificate path. These paths start with `/sdcard/` as this is where the example mounts the (FAT formatted) SD card. + +Copy the certificate and key files to the SD card, and make sure the file names match the names given in the example configuration (either rename the files, or change the config). For the Root CA certificate file (which is not device-specific), you can find the file in the `main/certs` directory or download it from AWS. + +*Note: By default, esp-idf's FATFS support only allows 8.3 character filenames. However, the AWS IoT examples pre-configure the sdkconfig to enable long filenames. If you're setting up your projects, you will probably want to enable these options as well (under Component Config -> FAT Filesystem Support). You can also consider configure the FAT filesystem for read-only support, if you don't need to write to the SD card.* + +## Find & Set AWS Endpoint Hostname + +Your AWS IoT account has a unique endpoint hostname to connect to. To find it, open the AWS IoT Console and click the "Settings" button on the bottom left side. The endpoint hostname is shown under the "Custom Endpoint" heading on this page. + +Run `make menuconfig` and navigate to `Component Config` -> `Amazon Web Service IoT Config` -> `AWS IoT MQTT Hostname`. Enter the host name here. + +*Note: It may seem odd that you have to configure parts of the AWS settings under Component Config and some under Example Configuration.* The IoT MQTT Hostname and Port are set as part of the component because when using the AWS IoT SDK's Thing Shadow API (in examples or in other projects) the `ShadowInitParametersDefault` structure means the Thing Shadow connection will default to that host & port. You're not forced to use these config values in your own projects, you can set the values in code via the AWS IoT SDK's init parameter structures - `ShadowInitParameters_t` for Thing Shadow API or `IoT_Client_Init_Params` for MQTT API. + +### (Optional) Set Client ID + +Run `make menuconfig`. Under `Example Configuration`, set the `AWS IoT Client ID` to a unique value. + +The Client ID is used in the MQTT protocol used to send messages to/from AWS IoT. AWS IoT requires that each connected device within a single AWS account uses a unique Client ID. Other than this restriction, the Client ID can be any value that you like. The example default should be fine if you're only connecting one ESP32 at a time. + +In a production IoT app this ID would be set dynamically, but for these examples it is compiled in via menuconfig. + +### (Optional) Locally Check The Root Certificate + +The Root CA certificate provides a root-of-trust when the ESP32 connects to AWS IoT. We have supplied the root CA certificate already (in PEM format) in the file `main/certs/aws-root-ca.pem`. + +If you want to locally verify that this Root CA certificate hasn't changed, you can run the following command against your AWS MQTT Host: + +``` +openssl s_client -showcerts -connect hostname:8883 < /dev/null +``` + +(Replace hostname with your AWS MQTT endpoint host.) The Root CA certificate is the last certificate in the list of certificates printed. You can copy-paste this in place of the existing `aws-root-ca.pem` file. + + +# Troubleshooting + +## Tips + +* Raise the ESP debug log level to Debug in order to see messages about the connection to AWS, certificate contents, etc. + +* Enable mbedTLS debugging (under Components -> mbedTLS -> mbedTLS Debug) in order to see even more low-level debug output from the mbedTLS layer. + +* To create a successful AWS IoT connection, the following factors must all be present: + - Endpoint hostname is correct for your AWS account. + - Certificate & private key are both attached to correct Thing in AWS IoT Console. + - Certificate is activated. + - Policy is attached to the Certificate in AWS IoT Console. + - Policy contains sufficient permissions to authorize AWS IoT connection. + +## TLS connection fails + +If connecting fails entirely (handshake doesn't complete), this usually indicates a problem with certification configuration. The error usually looks like this: + +``` +aws_iot: failed! mbedtls_ssl_handshake returned -0x7780 +``` + +(0x7780 is the mbedTLS error code when the server sends an alert message and closes the connection.) + +* Check your client private key and certificate file match a Certificate registered and **activated** in AWS IoT console. You can find the Certificate in IoT Console in one of two ways, via the Thing or via Certificates: + - To find the Certificate directly, click on "Registry" -> "Security Certificates". Then click on the Certificate itself to view it. + - To find the Certificate via the Thing, click on "Registry" -> "Things", then click on the particular Thing you are using. Click "Certificates" in the sidebar to view all Certificates attached to that Thing. Then click on the Certificate itself to view it. + +Verify the Certificate is activated (when viewing the Certificate, it will say "ACTIVE" or "INACTIVE" near the top under the certificate name). + +If the Certificate appears correct and activated, verify that you are connecting to the correct AWS IoT endpoint (see above.) + +## TLS connection closes immediately + +Sometimes connecting is successful (the handshake completes) but as soon as the client sends its `MQTT CONNECT` message the server sends back a TLS alert and closes the connection, without anything else happening. + +The error returned from AWS IoT is usually -28 (`MQTT_REQUEST_TIMEOUT_ERROR`). You may also see mbedtls error `-0x7780` (server alert), although if this error comes during `mbedtls_ssl_handshake` then it's usually a different problem (see above). + +In the subscribe_publish example, the error may look like this in the log: + +``` +subpub: Error(-28) connecting to (endpoint)... +``` + +In the thing_shadow example, the error may look like this in the log: + +``` +shadow: aws_iot_shadow_connect returned error -28, aborting... +``` + +This error implies the Certificate is recognised, but the Certificate is either missing the correct Thing or the correct Policy attached to it. + +* Check in the AWS IoT console that your certificate is activated and has both a **security policy** and a **Thing** attached to it. You can find this in IoT Console by clicking "Registry" -> "Security Certificates", then click the Certificate. Once viewing the Certificate, you can click the "Policies" and "Things" links in the sidebar. + diff --git a/examples/protocols/aws_iot/subscribe_publish/Makefile b/examples/protocols/aws_iot/subscribe_publish/Makefile new file mode 100644 index 0000000000..4f0d138201 --- /dev/null +++ b/examples/protocols/aws_iot/subscribe_publish/Makefile @@ -0,0 +1,9 @@ +# +# This is a project Makefile. It is assumed the directory this Makefile resides in is a +# project subdirectory. +# + +PROJECT_NAME := aws_iot_subpub + +include $(IDF_PATH)/make/project.mk + diff --git a/examples/protocols/aws_iot/subscribe_publish/README.md b/examples/protocols/aws_iot/subscribe_publish/README.md new file mode 100644 index 0000000000..9555ecf572 --- /dev/null +++ b/examples/protocols/aws_iot/subscribe_publish/README.md @@ -0,0 +1,32 @@ +# Amazon Web Services IoT MQTT Subscribe/Publish Example + +This is an adaptation of the [AWS IoT C SDK](https://github.com/aws/aws-iot-device-sdk-embedded-C) "subscribe_publish" example for ESP-IDF. + +# Configuration + +See the README.md in the parent directory for information about configuring the AWS IoT examples. + +# Monitoring MQTT Data from the device + +After flashing the example to your ESP32, it should connect to Amazon and start subscribing/publishing MQTT data. + +The example code publishes MQTT data to the topic `test_topic/esp32`. Amazon provides a web interface to subscribe to MQTT topics for testing: + +* On the AWS IoT console, click "MQTT Client" near the top-right. +* Click "Generate Client ID" to generate a random client ID. +* Click "Connect" + +One connection succeeds, you can subscribe to the data published by the ESP32: + +* Click "Subscribe to Topic" +* Enter "Subscription Topic" `test_topic/esp32` +* Click "Subscribe" + +... you should see MQTT data published from the running example. + +To publish data back to the device: + +* Click "Publish to Topic" +* Enter "Publish Topic" `test_topic/esp32` +* Enter a message in the payload field +* Click Publish diff --git a/examples/protocols/aws_iot/subscribe_publish/main/Kconfig.projbuild b/examples/protocols/aws_iot/subscribe_publish/main/Kconfig.projbuild new file mode 100644 index 0000000000..368b06b329 --- /dev/null +++ b/examples/protocols/aws_iot/subscribe_publish/main/Kconfig.projbuild @@ -0,0 +1,60 @@ +menu "Example Configuration" + +config WIFI_SSID + string "WiFi SSID" + default "myssid" + help + SSID (network name) for the example to connect to. + +config WIFI_PASSWORD + string "WiFi Password" + default "myssid" + help + WiFi password (WPA or WPA2) for the example to use. + + Can be left blank if the network has no security set. + +config AWS_EXAMPLE_CLIENT_ID + string "AWS IoT Client ID" + default "myesp32" + help + AWS IoT Client ID for the example. Should be unique for every device. + +choice EXAMPLE_CERT_SOURCE + prompt "AWS IoT Certificate Source" + default EXAMPLE_EMBEDDED_CERTS + help + AWS IoT requires loading of a device-specific certificate and private key, + and a common Root CA Certificate. These can be compiled into the example + app, or they can be loaded via the filesystem from an SD card. + +config EXAMPLE_EMBEDDED_CERTS + bool "Embed into app" +config EXAMPLE_SDCARD_CERTS + bool "Load from SD card" + select EXAMPLE_FILESYSTEM_CERTS +endchoice + +# Currently this is equivalent to EXAMPLE_SDCARD_CERTS, +# however eventually we want to support more filesystem +# sources (SPIFFS, etc.) So this hidden config item +# is selected whenever the item should load from filesystem. +config EXAMPLE_FILESYSTEM_CERTS + bool + +config EXAMPLE_CERTIFICATE_PATH + string "Device Certificate Path" + depends on EXAMPLE_FILESYSTEM_CERTS + default "/sdcard/certificate.pem.crt" + +config EXAMPLE_PRIVATE_KEY_PATH + string "Device Private Key Path" + depends on EXAMPLE_FILESYSTEM_CERTS + default "/sdcard/private.pem.key" + +config EXAMPLE_ROOT_CA_PATH + string "Root CA Certificate Path" + depends on EXAMPLE_FILESYSTEM_CERTS + default "/sdcard/aws-root-ca.pem" + +endmenu \ No newline at end of file diff --git a/examples/protocols/aws_iot/subscribe_publish/main/certs/README.md b/examples/protocols/aws_iot/subscribe_publish/main/certs/README.md new file mode 100644 index 0000000000..d445cc62ba --- /dev/null +++ b/examples/protocols/aws_iot/subscribe_publish/main/certs/README.md @@ -0,0 +1,3 @@ +Copy certificate files for AWS IoT SDK example here + +See README.md in main example directory for details. diff --git a/examples/protocols/aws_iot/subscribe_publish/main/certs/aws-root-ca.pem b/examples/protocols/aws_iot/subscribe_publish/main/certs/aws-root-ca.pem new file mode 100644 index 0000000000..a9490be3a0 --- /dev/null +++ b/examples/protocols/aws_iot/subscribe_publish/main/certs/aws-root-ca.pem @@ -0,0 +1,28 @@ +-----BEGIN CERTIFICATE----- +MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB +yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL +ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp +U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxW +ZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0 +aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCByjEL +MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZW +ZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2ln +biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJp +U2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9y +aXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvJAgIKXo1 +nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKzj/i5Vbex +t0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIz +SdhDY2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQG +BO+QueQA5N06tRn/Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+ +rCpSx4/VBEnkjWNHiDxpg8v+R70rfk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/ +NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8E +BAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEwHzAH +BgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy +aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKv +MzEzMA0GCSqGSIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzE +p6B4Eq1iDkVwZMXnl2YtmAl+X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y +5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKEKQsTb47bDN0lAtukixlE0kF6BWlK +WE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiCKm0oHw0LxOXnGiYZ +4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vEZV8N +hnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq +-----END CERTIFICATE----- \ No newline at end of file diff --git a/examples/protocols/aws_iot/subscribe_publish/main/component.mk b/examples/protocols/aws_iot/subscribe_publish/main/component.mk new file mode 100644 index 0000000000..bc11b63933 --- /dev/null +++ b/examples/protocols/aws_iot/subscribe_publish/main/component.mk @@ -0,0 +1,22 @@ +# +# Main Makefile. This is basically the same as a component makefile. +# + +ifdef CONFIG_EXAMPLE_EMBEDDED_CERTS +# Certificate files. certificate.pem.crt & private.pem.key must be downloaded +# from AWS, see README for details. +COMPONENT_EMBED_TXTFILES := certs/aws-root-ca.pem certs/certificate.pem.crt certs/private.pem.key + +ifndef IDF_CI_BUILD +# Print an error if the certificate/key files are missing +$(COMPONENT_PATH)/certs/certificate.pem.crt $(COMPONENT_PATH)/certs/private.pem.key: + @echo "Missing PEM file $@. This file identifies the ESP32 to AWS for the example, see README for details." + exit 1 +else # IDF_CI_BUILD +# this case is for the internal Continuous Integration build which +# compiles all examples. Add some dummy certs so the example can +# compile (even though it won't work) +$(COMPONENT_PATH)/certs/certificate.pem.crt $(COMPONENT_PATH)/certs/private.pem.key: + echo "Dummy certificate data for continuous integration" > $@ +endif +endif diff --git a/examples/protocols/aws_iot/subscribe_publish/main/subscribe_publish_sample.c b/examples/protocols/aws_iot/subscribe_publish/main/subscribe_publish_sample.c new file mode 100644 index 0000000000..ab9161fcb1 --- /dev/null +++ b/examples/protocols/aws_iot/subscribe_publish/main/subscribe_publish_sample.c @@ -0,0 +1,326 @@ +/* + * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Additions Copyright 2016 Espressif Systems (Shanghai) PTE LTD + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file 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. + */ +/** + * @file subscribe_publish_sample.c + * @brief simple MQTT publish and subscribe on the same topic + * + * This example takes the parameters from the build configuration and establishes a connection to the AWS IoT MQTT Platform. + * It subscribes and publishes to the same topic - "test_topic/esp32" + * + * Some setup is required. See example README for details. + * + */ +#include +#include +#include +#include +#include +#include + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/event_groups.h" +#include "esp_system.h" +#include "esp_wifi.h" +#include "esp_event_loop.h" +#include "esp_log.h" +#include "esp_vfs_fat.h" +#include "driver/sdmmc_host.h" + +#include "aws_iot_config.h" +#include "aws_iot_log.h" +#include "aws_iot_version.h" +#include "aws_iot_mqtt_client_interface.h" + +static const char *TAG = "subpub"; + +/* The examples use simple WiFi configuration that you can set via + 'make menuconfig'. + + If you'd rather not, just change the below entries to strings with + the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid" +*/ +#define EXAMPLE_WIFI_SSID CONFIG_WIFI_SSID +#define EXAMPLE_WIFI_PASS CONFIG_WIFI_PASSWORD + +/* FreeRTOS event group to signal when we are connected & ready to make a request */ +static EventGroupHandle_t wifi_event_group; + +/* The event group allows multiple bits for each event, + but we only care about one event - are we connected + to the AP with an IP? */ +const int CONNECTED_BIT = BIT0; + + +/* CA Root certificate, device ("Thing") certificate and device + * ("Thing") key. + + Example can be configured one of two ways: + + "Embedded Certs" are loaded from files in "certs/" and embedded into the app binary. + + "Filesystem Certs" are loaded from the filesystem (SD card, etc.) + + See example README for more details. +*/ +#if defined(CONFIG_EXAMPLE_EMBEDDED_CERTS) + +extern const uint8_t aws_root_ca_pem_start[] asm("_binary_aws_root_ca_pem_start"); +extern const uint8_t aws_root_ca_pem_end[] asm("_binary_aws_root_ca_pem_end"); +extern const uint8_t certificate_pem_crt_start[] asm("_binary_certificate_pem_crt_start"); +extern const uint8_t certificate_pem_crt_end[] asm("_binary_certificate_pem_crt_end"); +extern const uint8_t private_pem_key_start[] asm("_binary_private_pem_key_start"); +extern const uint8_t private_pem_key_end[] asm("_binary_private_pem_key_end"); + +#elif defined(CONFIG_EXAMPLE_FILESYSTEM_CERTS) + +static const char * DEVICE_CERTIFICATE_PATH = CONFIG_EXAMPLE_CERTIFICATE_PATH; +static const char * DEVICE_PRIVATE_KEY_PATH = CONFIG_EXAMPLE_PRIVATE_KEY_PATH; +static const char * ROOT_CA_PATH = CONFIG_EXAMPLE_ROOT_CA_PATH; + +#else +#error "Invalid method for loading certs" +#endif + +/** + * @brief Default MQTT HOST URL is pulled from the aws_iot_config.h + */ +char HostAddress[255] = AWS_IOT_MQTT_HOST; + +/** + * @brief Default MQTT port is pulled from the aws_iot_config.h + */ +uint32_t port = AWS_IOT_MQTT_PORT; + + +static esp_err_t event_handler(void *ctx, system_event_t *event) +{ + switch(event->event_id) { + case SYSTEM_EVENT_STA_START: + esp_wifi_connect(); + break; + case SYSTEM_EVENT_STA_GOT_IP: + xEventGroupSetBits(wifi_event_group, CONNECTED_BIT); + break; + case SYSTEM_EVENT_STA_DISCONNECTED: + /* This is a workaround as ESP32 WiFi libs don't currently + auto-reassociate. */ + esp_wifi_connect(); + xEventGroupClearBits(wifi_event_group, CONNECTED_BIT); + break; + default: + break; + } + return ESP_OK; +} + +void iot_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, + IoT_Publish_Message_Params *params, void *pData) { + ESP_LOGI(TAG, "Subscribe callback"); + ESP_LOGI(TAG, "%.*s\t%.*s", topicNameLen, topicName, (int) params->payloadLen, (char *)params->payload); +} + +void disconnectCallbackHandler(AWS_IoT_Client *pClient, void *data) { + ESP_LOGW(TAG, "MQTT Disconnect"); + IoT_Error_t rc = FAILURE; + + if(NULL == pClient) { + return; + } + + if(aws_iot_is_autoreconnect_enabled(pClient)) { + ESP_LOGI(TAG, "Auto Reconnect is enabled, Reconnecting attempt will start now"); + } else { + ESP_LOGW(TAG, "Auto Reconnect not enabled. Starting manual reconnect..."); + rc = aws_iot_mqtt_attempt_reconnect(pClient); + if(NETWORK_RECONNECTED == rc) { + ESP_LOGW(TAG, "Manual Reconnect Successful"); + } else { + ESP_LOGW(TAG, "Manual Reconnect Failed - %d", rc); + } + } +} + +void aws_iot_task(void *param) { + char cPayload[100]; + + int32_t i = 0; + + IoT_Error_t rc = FAILURE; + + AWS_IoT_Client client; + IoT_Client_Init_Params mqttInitParams = iotClientInitParamsDefault; + IoT_Client_Connect_Params connectParams = iotClientConnectParamsDefault; + + IoT_Publish_Message_Params paramsQOS0; + IoT_Publish_Message_Params paramsQOS1; + + ESP_LOGI(TAG, "AWS IoT SDK Version %d.%d.%d-%s", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG); + + mqttInitParams.enableAutoReconnect = false; // We enable this later below + mqttInitParams.pHostURL = HostAddress; + mqttInitParams.port = port; + +#if defined(CONFIG_EXAMPLE_EMBEDDED_CERTS) + mqttInitParams.pRootCALocation = (const char *)aws_root_ca_pem_start; + mqttInitParams.pDeviceCertLocation = (const char *)certificate_pem_crt_start; + mqttInitParams.pDevicePrivateKeyLocation = (const char *)private_pem_key_start; + +#elif defined(CONFIG_EXAMPLE_FILESYSTEM_CERTS) + mqttInitParams.pRootCALocation = ROOT_CA_PATH; + mqttInitParams.pDeviceCertLocation = DEVICE_CERTIFICATE_PATH; + mqttInitParams.pDevicePrivateKeyLocation = DEVICE_PRIVATE_KEY_PATH; +#endif + + mqttInitParams.mqttCommandTimeout_ms = 20000; + mqttInitParams.tlsHandshakeTimeout_ms = 5000; + mqttInitParams.isSSLHostnameVerify = true; + mqttInitParams.disconnectHandler = disconnectCallbackHandler; + mqttInitParams.disconnectHandlerData = NULL; + +#ifdef CONFIG_EXAMPLE_SDCARD_CERTS + ESP_LOGI(TAG, "Mounting SD card..."); + sdmmc_host_t host = SDMMC_HOST_DEFAULT(); + sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); + esp_vfs_fat_sdmmc_mount_config_t mount_config = { + .format_if_mount_failed = false, + .max_files = 3, + }; + sdmmc_card_t* card; + esp_err_t ret = esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, &card); + if (ret != ESP_OK) { + ESP_LOGE(TAG, "Failed to mount SD card VFAT filesystem."); + abort(); + } +#endif + + rc = aws_iot_mqtt_init(&client, &mqttInitParams); + if(SUCCESS != rc) { + ESP_LOGE(TAG, "aws_iot_mqtt_init returned error : %d ", rc); + abort(); + } + + /* Wait for WiFI to show as connected */ + xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, + false, true, portMAX_DELAY); + + connectParams.keepAliveIntervalInSec = 10; + connectParams.isCleanSession = true; + connectParams.MQTTVersion = MQTT_3_1_1; + /* Client ID is set in the menuconfig of the example */ + connectParams.pClientID = CONFIG_AWS_EXAMPLE_CLIENT_ID; + connectParams.clientIDLen = (uint16_t) strlen(CONFIG_AWS_EXAMPLE_CLIENT_ID); + connectParams.isWillMsgPresent = false; + + ESP_LOGI(TAG, "Connecting to AWS..."); + do { + rc = aws_iot_mqtt_connect(&client, &connectParams); + if(SUCCESS != rc) { + ESP_LOGE(TAG, "Error(%d) connecting to %s:%d", rc, mqttInitParams.pHostURL, mqttInitParams.port); + vTaskDelay(1000 / portTICK_RATE_MS); + } + } while(SUCCESS != rc); + + /* + * 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 = aws_iot_mqtt_autoreconnect_set_status(&client, true); + if(SUCCESS != rc) { + ESP_LOGE(TAG, "Unable to set Auto Reconnect to true - %d", rc); + abort(); + } + + const char *TOPIC = "test_topic/esp32"; + const int TOPIC_LEN = strlen(TOPIC); + + ESP_LOGI(TAG, "Subscribing..."); + rc = aws_iot_mqtt_subscribe(&client, TOPIC, TOPIC_LEN, QOS0, iot_subscribe_callback_handler, NULL); + if(SUCCESS != rc) { + ESP_LOGE(TAG, "Error subscribing : %d ", rc); + abort(); + } + + sprintf(cPayload, "%s : %d ", "hello from SDK", i); + + paramsQOS0.qos = QOS0; + paramsQOS0.payload = (void *) cPayload; + paramsQOS0.isRetained = 0; + + paramsQOS1.qos = QOS1; + paramsQOS1.payload = (void *) cPayload; + paramsQOS1.isRetained = 0; + + while((NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc)) { + + //Max time the yield function will wait for read messages + rc = aws_iot_mqtt_yield(&client, 100); + if(NETWORK_ATTEMPTING_RECONNECT == rc) { + // If the client is attempting to reconnect we will skip the rest of the loop. + continue; + } + + ESP_LOGI(TAG, "-->sleep"); + vTaskDelay(1000 / portTICK_RATE_MS); + sprintf(cPayload, "%s : %d ", "hello from ESP32 (QOS0)", i++); + paramsQOS0.payloadLen = strlen(cPayload); + rc = aws_iot_mqtt_publish(&client, TOPIC, TOPIC_LEN, ¶msQOS0); + + sprintf(cPayload, "%s : %d ", "hello from ESP32 (QOS1)", i++); + paramsQOS1.payloadLen = strlen(cPayload); + rc = aws_iot_mqtt_publish(&client, TOPIC, TOPIC_LEN, ¶msQOS1); + if (rc == MQTT_REQUEST_TIMEOUT_ERROR) { + ESP_LOGW(TAG, "QOS1 publish ack not received."); + rc = SUCCESS; + } + } + + ESP_LOGE(TAG, "An error occurred in the main loop."); + abort(); +} + +static void initialise_wifi(void) +{ + tcpip_adapter_init(); + wifi_event_group = xEventGroupCreate(); + ESP_ERROR_CHECK( esp_event_loop_init(event_handler, NULL) ); + wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); + ESP_ERROR_CHECK( esp_wifi_init(&cfg) ); + ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM) ); + wifi_config_t wifi_config = { + .sta = { + .ssid = EXAMPLE_WIFI_SSID, + .password = EXAMPLE_WIFI_PASS, + }, + }; + ESP_LOGI(TAG, "Setting WiFi configuration SSID %s...", wifi_config.sta.ssid); + ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA) ); + ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &wifi_config) ); + ESP_ERROR_CHECK( esp_wifi_start() ); +} + + +void app_main() +{ + initialise_wifi(); +#ifdef CONFIG_MBEDTLS_DEBUG + const size_t stack_size = 36*1024; +#else + const size_t stack_size = 36*1024; +#endif + xTaskCreatePinnedToCore(&aws_iot_task, "aws_iot_task", stack_size, NULL, 5, NULL, 1); +} diff --git a/examples/protocols/aws_iot/subscribe_publish/sdkconfig.defaults b/examples/protocols/aws_iot/subscribe_publish/sdkconfig.defaults new file mode 100644 index 0000000000..8bb40678d9 --- /dev/null +++ b/examples/protocols/aws_iot/subscribe_publish/sdkconfig.defaults @@ -0,0 +1,9 @@ +# Enable AWS IoT SDK support +CONFIG_AWS_IOT_SDK=y + +# Enable FATFS read only with long filename support +# for loading Cert/CA/etc from filesystem +# (if enabled in config) +CONFIG_FATFS_READONLY=y +CONFIG_FATFS_CODEPAGE_437=y +CONFIG_FATFS_LFN_HEAP=y diff --git a/examples/protocols/aws_iot/thing_shadow/Makefile b/examples/protocols/aws_iot/thing_shadow/Makefile new file mode 100644 index 0000000000..dac75a3194 --- /dev/null +++ b/examples/protocols/aws_iot/thing_shadow/Makefile @@ -0,0 +1,9 @@ +# +# This is a project Makefile. It is assumed the directory this Makefile resides in is a +# project subdirectory. +# + +PROJECT_NAME := aws_iot_thing_shadow + +include $(IDF_PATH)/make/project.mk + diff --git a/examples/protocols/aws_iot/thing_shadow/README.md b/examples/protocols/aws_iot/thing_shadow/README.md new file mode 100644 index 0000000000..ea9b9ae5f3 --- /dev/null +++ b/examples/protocols/aws_iot/thing_shadow/README.md @@ -0,0 +1,34 @@ +# Amazon Web Services IoT Thing Shadow Example + +This is an adaptation of the [AWS IoT C SDK](https://github.com/aws/aws-iot-device-sdk-embedded-C) "shadow_sample" example for ESP-IDF. + +# Provisioning/Configuration + +See the README.md in the parent directory for information about configuring the AWS IoT examples. + +After following those steps, there is one additional step for this exmaple: + +## Set Thing Name + +For this example, you will need to set a Thing Name under `make menuconfig` -> `Example Configuration` -> `AWS IoT Thing Name`. + +The Thing Name should match a Thing that you created while following the Getting Started guide (to check the Things you have registered, go t othe AWS IoT console web interface, click Registry and then click Things). + +# Monitoring Thing Status + +After flashing the example to your ESP32, it should connect to Amazon and start updating the example Thing's shadow. + +In the ESP32's serial output, you should see the message "Update accepted" logged every couple of seconds. + +You can monitor the Thing status from the AWS IoT console web interface: + +* On the left-hand toolbar, click Registry and then click Things. +* Click on the "Thing" you set up for the example. +* Click on the "Shadow" sidebar link. You should see the Thing Shadow updating regularly. +* Click on the "Activity" sidebar link to see all Thing Shadow updates in a list. You can examine each update individually. + +# Troubleshooting + +If you're having problems with the AWS IoT connection itself, check the Troubleshooting section of the README in the parent directory. + +* If your Thing is connecting and appears to be successfully updating, but you don't see any updates in the AWS IoT console, then check that the Thing Name in the Example Configuration under menuconfig matches exactly the thing name in AWS IoT console (including case). diff --git a/examples/protocols/aws_iot/thing_shadow/main/Kconfig.projbuild b/examples/protocols/aws_iot/thing_shadow/main/Kconfig.projbuild new file mode 100644 index 0000000000..d796a20b7e --- /dev/null +++ b/examples/protocols/aws_iot/thing_shadow/main/Kconfig.projbuild @@ -0,0 +1,66 @@ +menu "Example Configuration" + +config WIFI_SSID + string "WiFi SSID" + default "myssid" + help + SSID (network name) for the example to connect to. + +config WIFI_PASSWORD + string "WiFi Password" + default "myssid" + help + WiFi password (WPA or WPA2) for the example to use. + + Can be left blank if the network has no security set. + +config AWS_EXAMPLE_CLIENT_ID + string "AWS IoT Client ID" + default "myesp32" + help + AWS IoT Client ID for the example. Should be unique for every device. + +config AWS_EXAMPLE_THING_NAME + string "AWS IoT Thing Name" + default "myesp32" + help + AWS IoT Thing Name for the example. Should be unique for every device. + +choice EXAMPLE_CERT_SOURCE + prompt "AWS IoT Certificate Source" + default EXAMPLE_EMBEDDED_CERTS + help + AWS IoT requires loading of a device-specific certificate and private key, + and a common Root CA Certificate. These can be compiled into the example + app, or they can be loaded via the filesystem from an SD card. + +config EXAMPLE_EMBEDDED_CERTS + bool "Embed into app" +config EXAMPLE_SDCARD_CERTS + bool "Load from SD card" + select EXAMPLE_FILESYSTEM_CERTS +endchoice + +# Currently this is equivalent to EXAMPLE_SDCARD_CERTS, +# however eventually we want to support more filesystem +# sources (SPIFFS, etc.) So this hidden config item +# is selected whenever the item should load from filesystem. +config EXAMPLE_FILESYSTEM_CERTS + bool + +config EXAMPLE_CERTIFICATE_PATH + string "Device Certificate Path" + depends on EXAMPLE_FILESYSTEM_CERTS + default "/sdcard/certificate.pem.crt" + +config EXAMPLE_PRIVATE_KEY_PATH + string "Device Private Key Path" + depends on EXAMPLE_FILESYSTEM_CERTS + default "/sdcard/private.pem.key" + +config EXAMPLE_ROOT_CA_PATH + string "Root CA Certificate Path" + depends on EXAMPLE_FILESYSTEM_CERTS + default "/sdcard/aws-root-ca.pem" + +endmenu \ No newline at end of file diff --git a/examples/protocols/aws_iot/thing_shadow/main/certs/README.md b/examples/protocols/aws_iot/thing_shadow/main/certs/README.md new file mode 100644 index 0000000000..d445cc62ba --- /dev/null +++ b/examples/protocols/aws_iot/thing_shadow/main/certs/README.md @@ -0,0 +1,3 @@ +Copy certificate files for AWS IoT SDK example here + +See README.md in main example directory for details. diff --git a/examples/protocols/aws_iot/thing_shadow/main/certs/aws-root-ca.pem b/examples/protocols/aws_iot/thing_shadow/main/certs/aws-root-ca.pem new file mode 100644 index 0000000000..a9490be3a0 --- /dev/null +++ b/examples/protocols/aws_iot/thing_shadow/main/certs/aws-root-ca.pem @@ -0,0 +1,28 @@ +-----BEGIN CERTIFICATE----- +MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB +yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL +ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp +U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxW +ZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0 +aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCByjEL +MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZW +ZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2ln +biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJp +U2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9y +aXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvJAgIKXo1 +nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKzj/i5Vbex +t0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIz +SdhDY2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQG +BO+QueQA5N06tRn/Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+ +rCpSx4/VBEnkjWNHiDxpg8v+R70rfk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/ +NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8E +BAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEwHzAH +BgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy +aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKv +MzEzMA0GCSqGSIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzE +p6B4Eq1iDkVwZMXnl2YtmAl+X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y +5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKEKQsTb47bDN0lAtukixlE0kF6BWlK +WE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiCKm0oHw0LxOXnGiYZ +4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vEZV8N +hnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq +-----END CERTIFICATE----- \ No newline at end of file diff --git a/examples/protocols/aws_iot/thing_shadow/main/component.mk b/examples/protocols/aws_iot/thing_shadow/main/component.mk new file mode 100644 index 0000000000..bc11b63933 --- /dev/null +++ b/examples/protocols/aws_iot/thing_shadow/main/component.mk @@ -0,0 +1,22 @@ +# +# Main Makefile. This is basically the same as a component makefile. +# + +ifdef CONFIG_EXAMPLE_EMBEDDED_CERTS +# Certificate files. certificate.pem.crt & private.pem.key must be downloaded +# from AWS, see README for details. +COMPONENT_EMBED_TXTFILES := certs/aws-root-ca.pem certs/certificate.pem.crt certs/private.pem.key + +ifndef IDF_CI_BUILD +# Print an error if the certificate/key files are missing +$(COMPONENT_PATH)/certs/certificate.pem.crt $(COMPONENT_PATH)/certs/private.pem.key: + @echo "Missing PEM file $@. This file identifies the ESP32 to AWS for the example, see README for details." + exit 1 +else # IDF_CI_BUILD +# this case is for the internal Continuous Integration build which +# compiles all examples. Add some dummy certs so the example can +# compile (even though it won't work) +$(COMPONENT_PATH)/certs/certificate.pem.crt $(COMPONENT_PATH)/certs/private.pem.key: + echo "Dummy certificate data for continuous integration" > $@ +endif +endif diff --git a/examples/protocols/aws_iot/thing_shadow/main/thing_shadow_sample.c b/examples/protocols/aws_iot/thing_shadow/main/thing_shadow_sample.c new file mode 100644 index 0000000000..2da22472ee --- /dev/null +++ b/examples/protocols/aws_iot/thing_shadow/main/thing_shadow_sample.c @@ -0,0 +1,368 @@ +/* + * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * Additions Copyright 2016 Espressif Systems (Shanghai) PTE LTD + * + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file 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. + */ +/** + * @file thing_shadow_sample.c + * @brief A simple connected window example demonstrating the use of Thing Shadow + * + * See example README for more details. + */ +#include +#include +#include +#include +#include +#include + +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "freertos/event_groups.h" +#include "esp_system.h" +#include "esp_wifi.h" +#include "esp_event_loop.h" +#include "esp_log.h" +#include "esp_vfs_fat.h" +#include "driver/sdmmc_host.h" + +#include "aws_iot_config.h" +#include "aws_iot_log.h" +#include "aws_iot_version.h" +#include "aws_iot_mqtt_client_interface.h" +#include "aws_iot_shadow_interface.h" + +/*! + * The goal of this sample application is to demonstrate the capabilities of shadow. + * This device(say Connected Window) will open the window of a room based on temperature + * It can report to the Shadow the following parameters: + * 1. temperature of the room (double) + * 2. status of the window (open or close) + * It can act on commands from the cloud. In this case it will open or close the window based on the json object "windowOpen" data[open/close] + * + * The two variables from a device's perspective are double temperature and bool windowOpen + * The device needs to act on only on windowOpen variable, so we will create a primitiveJson_t object with callback + The Json Document in the cloud will be + { + "reported": { + "temperature": 0, + "windowOpen": false + }, + "desired": { + "windowOpen": false + } + } + */ + +static const char *TAG = "shadow"; + +#define ROOMTEMPERATURE_UPPERLIMIT 32.0f +#define ROOMTEMPERATURE_LOWERLIMIT 25.0f +#define STARTING_ROOMTEMPERATURE ROOMTEMPERATURE_LOWERLIMIT + +#define MAX_LENGTH_OF_UPDATE_JSON_BUFFER 200 + +/* The examples use simple WiFi configuration that you can set via + 'make menuconfig'. + + If you'd rather not, just change the below entries to strings with + the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid" +*/ +#define EXAMPLE_WIFI_SSID CONFIG_WIFI_SSID +#define EXAMPLE_WIFI_PASS CONFIG_WIFI_PASSWORD + + +/* FreeRTOS event group to signal when we are connected & ready to make a request */ +static EventGroupHandle_t wifi_event_group; + +/* The event group allows multiple bits for each event, + but we only care about one event - are we connected + to the AP with an IP? */ +const int CONNECTED_BIT = BIT0; + + +/* CA Root certificate, device ("Thing") certificate and device + * ("Thing") key. + + Example can be configured one of two ways: + + "Embedded Certs" are loaded from files in "certs/" and embedded into the app binary. + + "Filesystem Certs" are loaded from the filesystem (SD card, etc.) + + See example README for more details. +*/ +#if defined(CONFIG_EXAMPLE_EMBEDDED_CERTS) + +extern const uint8_t aws_root_ca_pem_start[] asm("_binary_aws_root_ca_pem_start"); +extern const uint8_t aws_root_ca_pem_end[] asm("_binary_aws_root_ca_pem_end"); +extern const uint8_t certificate_pem_crt_start[] asm("_binary_certificate_pem_crt_start"); +extern const uint8_t certificate_pem_crt_end[] asm("_binary_certificate_pem_crt_end"); +extern const uint8_t private_pem_key_start[] asm("_binary_private_pem_key_start"); +extern const uint8_t private_pem_key_end[] asm("_binary_private_pem_key_end"); + +#elif defined(CONFIG_EXAMPLE_FILESYSTEM_CERTS) + +static const char * DEVICE_CERTIFICATE_PATH = CONFIG_EXAMPLE_CERTIFICATE_PATH; +static const char * DEVICE_PRIVATE_KEY_PATH = CONFIG_EXAMPLE_PRIVATE_KEY_PATH; +static const char * ROOT_CA_PATH = CONFIG_EXAMPLE_ROOT_CA_PATH; + +#else +#error "Invalid method for loading certs" +#endif + +/** + * @brief Default MQTT HOST URL is pulled from the aws_iot_config.h which + * uses menuconfig to find a default. + */ +char HostAddress[255] = AWS_IOT_MQTT_HOST; + +/** + * @brief Default MQTT port is pulled from the aws_iot_config.h which + * uses menuconfig to find a default. + */ +uint32_t port = AWS_IOT_MQTT_PORT; + +static esp_err_t event_handler(void *ctx, system_event_t *event) +{ + switch(event->event_id) { + case SYSTEM_EVENT_STA_START: + esp_wifi_connect(); + break; + case SYSTEM_EVENT_STA_GOT_IP: + xEventGroupSetBits(wifi_event_group, CONNECTED_BIT); + break; + case SYSTEM_EVENT_STA_DISCONNECTED: + /* This is a workaround as ESP32 WiFi libs don't currently + auto-reassociate. */ + esp_wifi_connect(); + xEventGroupClearBits(wifi_event_group, CONNECTED_BIT); + break; + default: + break; + } + return ESP_OK; +} + +static void simulateRoomTemperature(float *pRoomTemperature) { + static float deltaChange; + + if(*pRoomTemperature >= ROOMTEMPERATURE_UPPERLIMIT) { + deltaChange = -0.5f; + } else if(*pRoomTemperature <= ROOMTEMPERATURE_LOWERLIMIT) { + deltaChange = 0.5f; + } + + *pRoomTemperature += deltaChange; +} + +static bool shadowUpdateInProgress; + +void ShadowUpdateStatusCallback(const char *pThingName, ShadowActions_t action, Shadow_Ack_Status_t status, + const char *pReceivedJsonDocument, void *pContextData) { + IOT_UNUSED(pThingName); + IOT_UNUSED(action); + IOT_UNUSED(pReceivedJsonDocument); + IOT_UNUSED(pContextData); + + shadowUpdateInProgress = false; + + if(SHADOW_ACK_TIMEOUT == status) { + ESP_LOGE(TAG, "Update timed out"); + } else if(SHADOW_ACK_REJECTED == status) { + ESP_LOGE(TAG, "Update rejected"); + } else if(SHADOW_ACK_ACCEPTED == status) { + ESP_LOGI(TAG, "Update accepted"); + } +} + +void windowActuate_Callback(const char *pJsonString, uint32_t JsonStringDataLen, jsonStruct_t *pContext) { + IOT_UNUSED(pJsonString); + IOT_UNUSED(JsonStringDataLen); + + if(pContext != NULL) { + ESP_LOGI(TAG, "Delta - Window state changed to %d", *(bool *) (pContext->pData)); + } +} + +void aws_iot_task(void *param) { + IoT_Error_t rc = FAILURE; + + char JsonDocumentBuffer[MAX_LENGTH_OF_UPDATE_JSON_BUFFER]; + size_t sizeOfJsonDocumentBuffer = sizeof(JsonDocumentBuffer) / sizeof(JsonDocumentBuffer[0]); + float temperature = 0.0; + + bool windowOpen = false; + jsonStruct_t windowActuator; + windowActuator.cb = windowActuate_Callback; + windowActuator.pData = &windowOpen; + windowActuator.pKey = "windowOpen"; + windowActuator.type = SHADOW_JSON_BOOL; + + jsonStruct_t temperatureHandler; + temperatureHandler.cb = NULL; + temperatureHandler.pKey = "temperature"; + temperatureHandler.pData = &temperature; + temperatureHandler.type = SHADOW_JSON_FLOAT; + + ESP_LOGI(TAG, "AWS IoT SDK Version %d.%d.%d-%s", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG); + + // initialize the mqtt client + AWS_IoT_Client mqttClient; + + ShadowInitParameters_t sp = ShadowInitParametersDefault; + sp.pHost = AWS_IOT_MQTT_HOST; + sp.port = AWS_IOT_MQTT_PORT; + +#if defined(CONFIG_EXAMPLE_EMBEDDED_CERTS) + sp.pClientCRT = (const char *)certificate_pem_crt_start; + sp.pClientKey = (const char *)private_pem_key_start; + sp.pRootCA = (const char *)aws_root_ca_pem_start; +#elif defined(CONFIG_EXAMPLE_FILESYSTEM_CERTS) + sp.pClientCRT = DEVICE_CERTIFICATE_PATH; + sp.pClientKey = DEVICE_PRIVATE_KEY_PATH; + sp.pRootCA = ROOT_CA_PATH; +#endif + sp.enableAutoReconnect = false; + sp.disconnectHandler = NULL; + +#ifdef CONFIG_EXAMPLE_SDCARD_CERTS + ESP_LOGI(TAG, "Mounting SD card..."); + sdmmc_host_t host = SDMMC_HOST_DEFAULT(); + sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); + esp_vfs_fat_sdmmc_mount_config_t mount_config = { + .format_if_mount_failed = false, + .max_files = 3, + }; + sdmmc_card_t* card; + esp_err_t ret = esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, &card); + if (ret != ESP_OK) { + ESP_LOGE(TAG, "Failed to mount SD card VFAT filesystem."); + abort(); + } +#endif + + /* Wait for WiFI to show as connected */ + xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, + false, true, portMAX_DELAY); + + ESP_LOGI(TAG, "Shadow Init"); + rc = aws_iot_shadow_init(&mqttClient, &sp); + if(SUCCESS != rc) { + ESP_LOGE(TAG, "aws_iot_shadow_init returned error %d, aborting...", rc); + abort(); + } + + ShadowConnectParameters_t scp = ShadowConnectParametersDefault; + scp.pMyThingName = CONFIG_AWS_EXAMPLE_THING_NAME; + scp.pMqttClientId = CONFIG_AWS_EXAMPLE_CLIENT_ID; + scp.mqttClientIdLen = (uint16_t) strlen(CONFIG_AWS_EXAMPLE_CLIENT_ID); + + ESP_LOGI(TAG, "Shadow Connect"); + rc = aws_iot_shadow_connect(&mqttClient, &scp); + if(SUCCESS != rc) { + ESP_LOGE(TAG, "aws_iot_shadow_connect returned error %d, aborting...", rc); + abort(); + } + + /* + * 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 = aws_iot_shadow_set_autoreconnect_status(&mqttClient, true); + if(SUCCESS != rc) { + ESP_LOGE(TAG, "Unable to set Auto Reconnect to true - %d, aborting...", rc); + abort(); + } + + rc = aws_iot_shadow_register_delta(&mqttClient, &windowActuator); + + if(SUCCESS != rc) { + ESP_LOGE(TAG, "Shadow Register Delta Error"); + } + temperature = STARTING_ROOMTEMPERATURE; + + // loop and publish a change in temperature + while(NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc) { + rc = aws_iot_shadow_yield(&mqttClient, 200); + if(NETWORK_ATTEMPTING_RECONNECT == rc || shadowUpdateInProgress) { + rc = aws_iot_shadow_yield(&mqttClient, 1000); + // If the client is attempting to reconnect, or already waiting on a shadow update, + // we will skip the rest of the loop. + continue; + } + ESP_LOGI(TAG, "======================================================================================="); + ESP_LOGI(TAG, "On Device: window state %s", windowOpen ? "true" : "false"); + simulateRoomTemperature(&temperature); + + rc = aws_iot_shadow_init_json_document(JsonDocumentBuffer, sizeOfJsonDocumentBuffer); + if(SUCCESS == rc) { + rc = aws_iot_shadow_add_reported(JsonDocumentBuffer, sizeOfJsonDocumentBuffer, 2, &temperatureHandler, + &windowActuator); + if(SUCCESS == rc) { + rc = aws_iot_finalize_json_document(JsonDocumentBuffer, sizeOfJsonDocumentBuffer); + if(SUCCESS == rc) { + ESP_LOGI(TAG, "Update Shadow: %s", JsonDocumentBuffer); + rc = aws_iot_shadow_update(&mqttClient, CONFIG_AWS_EXAMPLE_THING_NAME, JsonDocumentBuffer, + ShadowUpdateStatusCallback, NULL, 4, true); + shadowUpdateInProgress = true; + } + } + } + ESP_LOGI(TAG, "*****************************************************************************************"); + vTaskDelay(1000 / portTICK_RATE_MS); + } + + if(SUCCESS != rc) { + ESP_LOGE(TAG, "An error occurred in the loop %d", rc); + } + + ESP_LOGI(TAG, "Disconnecting"); + rc = aws_iot_shadow_disconnect(&mqttClient); + + if(SUCCESS != rc) { + ESP_LOGE(TAG, "Disconnect error %d", rc); + } + + vTaskDelete(NULL); +} + +static void initialise_wifi(void) +{ + tcpip_adapter_init(); + wifi_event_group = xEventGroupCreate(); + ESP_ERROR_CHECK( esp_event_loop_init(event_handler, NULL) ); + wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); + ESP_ERROR_CHECK( esp_wifi_init(&cfg) ); + ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM) ); + wifi_config_t wifi_config = { + .sta = { + .ssid = EXAMPLE_WIFI_SSID, + .password = EXAMPLE_WIFI_PASS, + }, + }; + ESP_LOGI(TAG, "Setting WiFi configuration SSID %s...", wifi_config.sta.ssid); + ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA) ); + ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &wifi_config) ); + ESP_ERROR_CHECK( esp_wifi_start() ); +} + + +void app_main() +{ + initialise_wifi(); + /* Temporarily pin task to core, due to FPU uncertainty */ + xTaskCreatePinnedToCore(&aws_iot_task, "aws_iot_task", 16384+1024, NULL, 5, NULL, 1); +} diff --git a/examples/protocols/aws_iot/thing_shadow/sdkconfig.defaults b/examples/protocols/aws_iot/thing_shadow/sdkconfig.defaults new file mode 100644 index 0000000000..5874f30f5c --- /dev/null +++ b/examples/protocols/aws_iot/thing_shadow/sdkconfig.defaults @@ -0,0 +1,8 @@ +# Enable AWS IoT SDK support +CONFIG_AWS_IOT_SDK=y + +# Enable FATFS read only with long filename support +# for loading Cert/CA/etc from filesystem +# (if enabled in config) +CONFIG_FATFS_CODEPAGE_437=y +CONFIG_FATFS_LFN_HEAP=y diff --git a/tools/unit-test-app/sdkconfig b/tools/unit-test-app/sdkconfig index e9ad8e6374..2c73a45cab 100644 --- a/tools/unit-test-app/sdkconfig +++ b/tools/unit-test-app/sdkconfig @@ -57,7 +57,6 @@ CONFIG_ESPTOOLPY_FLASHSIZE="4MB" CONFIG_ESPTOOLPY_FLASHSIZE_DETECT=y CONFIG_ESPTOOLPY_BEFORE_RESET=y # CONFIG_ESPTOOLPY_BEFORE_NORESET is not set -# CONFIG_ESPTOOLPY_BEFORE_ESP32R0 is not set CONFIG_ESPTOOLPY_BEFORE="default_reset" CONFIG_ESPTOOLPY_AFTER_RESET=y # CONFIG_ESPTOOLPY_AFTER_NORESET is not set @@ -89,6 +88,12 @@ CONFIG_OPTIMIZATION_LEVEL_DEBUG=y # # Component config # + +# +# Amazon Web Service IoT Config +# +CONFIG_AWS_IOT_MQTT_HOST="" +CONFIG_AWS_IOT_MQTT_PORT=8883 # CONFIG_BT_ENABLED is not set CONFIG_BT_RESERVE_DRAM=0