diff --git a/components/aws_iot/Kconfig b/components/aws_iot/Kconfig new file mode 100644 index 00000000..9144f166 --- /dev/null +++ b/components/aws_iot/Kconfig @@ -0,0 +1,159 @@ +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. + + +config AWS_IOT_MQTT_TX_BUF_LEN + int "MQTT TX Buffer Length" + depends on AWS_IOT_SDK + default 512 + range 32 65536 + help + Maximum MQTT transmit buffer size. This is the maximum MQTT + message length (including protocol overhead) which can be sent. + + Sending longer messages will fail. + +config AWS_IOT_MQTT_RX_BUF_LEN + int "MQTT RX Buffer Length" + depends on AWS_IOT_SDK + default 512 + range 32 65536 + help + Maximum MQTT receive buffer size. This is the maximum MQTT + message length (including protocol overhead) which can be + received. + + Longer messages are dropped. + + + +config AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS + int "Maximum MQTT Topic Filters" + depends on AWS_IOT_SDK + default 5 + range 1 100 + help + Maximum number of concurrent MQTT topic filters. + + +config AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL + int "Auto reconnect initial interval (ms)" + depends on AWS_IOT_SDK + default 1000 + range 10 3600000 + help + Initial delay before making first reconnect attempt, if the AWS IoT connection fails. + Client will perform exponential backoff, starting from this value. + +config AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL + int "Auto reconnect maximum interval (ms)" + depends on AWS_IOT_SDK + default 128000 + range 10 3600000 + help + Maximum delay between reconnection attempts. If the exponentially increased delay + interval reaches this value, the client will stop automatically attempting to reconnect. + +menu "Thing Shadow" + depends on AWS_IOT_SDK + +config AWS_IOT_OVERRIDE_THING_SHADOW_RX_BUFFER + bool "Override Shadow RX buffer size" + depends on AWS_IOT_SDK + default n + help + Allows setting a different Thing Shadow RX buffer + size. This is the maximum size of a Thing Shadow + message in bytes, plus one. + + If not overridden, the default value is the MQTT RX Buffer length plus one. If overriden, do not set higher than the default value. + +config AWS_IOT_SHADOW_MAX_SIZE_OF_RX_BUFFER + int "Maximum RX Buffer (bytes)" + depends on AWS_IOT_OVERRIDE_THING_SHADOW_RX_BUFFER + default 513 + range 32 65536 + help + Allows setting a different Thing Shadow RX buffer size. + This is the maximum size of a Thing Shadow message in bytes, + plus one. + + +config AWS_IOT_SHADOW_MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES + int "Maximum unique client ID size (bytes)" + depends on AWS_IOT_SDK + default 80 + range 4 1000 + help + Maximum size of the Unique Client Id. + +config AWS_IOT_SHADOW_MAX_SIMULTANEOUS_ACKS + int "Maximum simultaneous responses" + depends on AWS_IOT_SDK + default 10 + range 1 100 + help + At any given time we will wait for this many responses. This will correlate to the rate at which the shadow actions are requested + +config AWS_IOT_SHADOW_MAX_SIMULTANEOUS_THINGNAMES + int "Maximum simultaneous Thing Name operations" + depends on AWS_IOT_SDK + default 10 + range 1 100 + help + We could perform shadow action on any thing Name and this is maximum Thing Names we can act on at any given time + +config AWS_IOT_SHADOW_MAX_JSON_TOKEN_EXPECTED + int "Maximum expected JSON tokens" + depends on AWS_IOT_SDK + default 120 + help + These are the max tokens that is expected to be in the Shadow JSON document. Includes the metadata which is published + +config AWS_IOT_SHADOW_MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME + int "Maximum topic length (not including Thing Name)" + depends on AWS_IOT_SDK + default 60 + range 10 1000 + help + All shadow actions have to be published or subscribed to a topic which is of the format $aws/things/{thingName}/shadow/update/accepted. This refers to the size of the topic without the Thing Name + +config AWS_IOT_SHADOW_MAX_SIZE_OF_THING_NAME + int "Maximum Thing Name length" + depends on AWS_IOT_SDK + default 20 + range 4 1000 + help + Maximum length of a Thing Name. + +endmenu # Thing Shadow + diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/CHANGELOG.md b/components/aws_iot/aws-iot-device-sdk-embedded-C/CHANGELOG.md new file mode 100644 index 00000000..c2580964 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/CHANGELOG.md @@ -0,0 +1,196 @@ +# Change Log +## [2.2.1](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v2.2.1) (Dec 26, 2017) + +Bugfixes: + + - [#115](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/115) - Issue with new client metrics + +Pull requests: + + - [#112](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/112) - Initialize msqParams.isRetained to 0 in publishToShadowAction() + - [#118](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/118) - mqttInitParams.mqttPacketTimeout_ms initialized + +## [2.2.0](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v2.2.0) (Nov 22, 2017) + +New Features: + + - Added SDK metrics string into connect packet + +Bugfixes: + + - [#49](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/49) - Add support for SHADOW_JSON_STRING as supported value + - [#57](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/57) - remove unistd.h + - [#58](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/58) - Fix return type of aws_iot_mqtt_internal_is_topic_matched + - [#59](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/95) - Fix extraneous assignment + - [#62](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/62) - Clearing SubscriptionList entries in shadowActionAcks after subscription failure + - [#63](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/63) - Stack overflow when IOT_DEBUG is enabled + - [#66](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/66) - Bug in send packet function + - [#69](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/69) - Fix for broken deleteActionHandler in shadow API + - [#71](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/71) - Prevent messages on /update/accepted from incrementing shadowJsonVersionNum in delta + - [#73](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/73) - wait for all messages to be received in subscribe publish sample + - [#96](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/96) - destroy TLS instance even if disconnect send fails + - Fix for aws_iot_mqtt_resubscribe not properly resubscribing to all topics + - Update MbedTLS Network layer Readme to remove specific version link + - Fix for not Passing througheError code on aws_iot_shadow_connect failure + - Allow sending of SHADOW_JSON_OBJECT to the shadow + - Ignore delta token callback for metadata + - Fix infinite publish exiting early in subscribe publish sample + +Improvements: + + - Updated jsmn to latest commit + - Change default keepalive interval to 600 seconds + +Pull requests: + + - [#29](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/29) - three small fixes + - [#59](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/59) - Fixed MQTT header constructing and parsing + - [#88](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/88) - Fix username and password are confused + - [#78](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/78) - Fixed compilation warnings + - [#102](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/102) - Corrected markdown headers + - [#105](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/105) - Fixed warnings when compiling + +## [2.1.1](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v2.1.1) (Sep 5, 2016) + +Bugfixes/Improvements: + + - Network layer interface improvements to address reported issues + - Incorporated GitHub pull request [#41](https://github.com/aws/aws-iot-device-sdk-embedded-c/pull/41) + - Bugfixes for issues [#36](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/36) and [#33](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/33) + +## [2.1.0](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v2.1.0) (Jun 15, 2016) + +New features: + + - Added unit tests, further details can be found in the testing readme [here](https://github.com/aws/aws-iot-device-sdk-embedded-c/blob/master/tests/README.md) + - Added sample to demonstrate building the SDK as library + - Added sample to demonstrate building the SDK in C++ + +Bugfixes/Improvements: + + - Increased default value of Maximum Reconnect Wait interval to 128 secs + - Increased default value of MQTT Command Timeout in Shadow Connect to 20 secs + - Shadow null/length checks + - Client Id Length not passed correctly in shadow connect + - Add extern C to headers and source files, added sample to demonstrate usage with C++ + - Delete/Accepted not being reported, callback added for delete/accepted + - Append IOT_ to all Debug macros (eg. DEBUG is now IOT_DEBUG) + - Fixed exit on error for subscribe_publish_sample + +## [2.0.0](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v2.0.0) (April 28, 2016) + +New features: + + - Refactored API to make it instance specific. This is a breaking change in the API from 1.x releases because a Client Instance parameter had to be added to all APIs + - Added Threading library porting layer wrapper + - Added support for multiple connections from one application + - Shadows and connections de-linked, connection needs to be set up separately, can be used independently of shadow + - Added integration tests for testing SDK functionality + +Bugfixes/Improvements: + + - Yield cannot be called again while waiting for application callback to return + - Fixed issue with TLS layer handles not being cleaned up properly on connection failure reported [here](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/16) + - Renamed timer_linux.h to timer_platform.h as requested [here](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/5) + - Adds support for disconnect handler to shadow. A similar pull request can be found [here](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/9) + - New SDK folder structure, cleaned and simplified code structure + - Removed Paho Wrapper, Merge MQTT into SDK code, added specific error codes + - Refactored Network and Timer layer wrappers, added specific error codes + - Refactored samples and makefiles + +## [1.1.2](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v1.1.2) (April 22, 2016) + +Bugfixes/Improvements: + + - Signature mismatch in MQTT library file fixed + - Makefiles have a protective target on the top to prevent accidental execution + +## [1.1.1](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v1.1.1) (April 1, 2016) + +Bugfixes/Improvements: + + - Removing the Executable bit from all the files in the repository. Fixing [this](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/14) issue + - Refactoring MQTT client to remove declaration after statement warnings + - Fixing [this](https://forums.aws.amazon.com/thread.jspa?threadID=222467&tstart=0) bug + + +## [1.1.0](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v1.1.0) (February 10, 2016) +Features: + + - Auto Reconnect and Resubscribe + +Bugfixes/Improvements: + + - MQTT buffer handling incase of bigger message + - Large timeout values converted to seconds and milliseconds + - Dynamic loading of Shadow parameters. Client ID and Thing Name are not hard-coded + - MQTT Library refactored + + +## [1.0.1](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v1.0.1) (October 21, 2015) + +Bugfixes/Improvements: + + - Paho name changed to Eclipse Paho + - Renamed the Makefiles in the samples directory + - Device Shadow - Delete functionality macro fixed + - `subscribe_publish_sample` updated + +## [1.0.0](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v1.0.0) (October 8, 2015) + +Features: + + - Release to github + - SDK tarballs made available for public download + +Bugfixes/Improvements: + - Updated API documentation + +## 0.4.0 (October 5, 2015) + +Features: + + - Thing Shadow Actions - Update, Delete, Get for any Thing Name + - aws_iot_config.h file for easy configuration of parameters + - Sample app for talking with console's Interactive guide + - disconnect handler for the MQTT client library + +Bugfixes/Improvements: + + - mbedTLS read times out every 10 ms instead of hanging for ever + - mbedTLS handshake failure handled + +## 0.3.0 (September 14, 2015) + +Features: + + - Testing with mbedTLS, prepping for relase + +Bugfixes/Improvements: + + - Refactored to break out timer and network interfaces + +## 0.2.0 (September 2, 2015) + +Features: + + - Added initial Shadow implementation + example + - Added hostname verification to OpenSSL example + - Added iot_log interface + - Initial API Docs (Doxygen) + +Bugfixes/Improvements: + + - Fixed yield timeout + - Refactored APIs to pass by reference vs value + +## 0.1.0 (August 12, 2015) + +Features: + + - Initial beta release + - MQTT Publish and Subscribe + - TLS mutual auth on linux with OpenSSL + +Bugfixes/Improvements: + - N/A diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/CppUTestMakefileWorker.mk b/components/aws_iot/aws-iot-device-sdk-embedded-C/CppUTestMakefileWorker.mk new file mode 100644 index 00000000..9f3c3054 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/CppUTestMakefileWorker.mk @@ -0,0 +1,575 @@ +#--------- +# +# MakefileWorker.mk +# +# Include this helper file in your makefile +# It makes +# A static library +# A test executable +# +# See this example for parameter settings +# examples/Makefile +# +#---------- +# Inputs - these variables describe what to build +# +# INCLUDE_DIRS - Directories used to search for include files. +# This generates a -I for each directory +# SRC_DIRS - Directories containing source file to built into the library +# SRC_FILES - Specific source files to build into library. Helpful when not all code +# in a directory can be built for test (hopefully a temporary situation) +# TEST_SRC_DIRS - Directories containing unit test code build into the unit test runner +# These do not go in a library. They are explicitly included in the test runner +# TEST_SRC_FILES - Specific source files to build into the unit test runner +# These do not go in a library. They are explicitly included in the test runner +# MOCKS_SRC_DIRS - Directories containing mock source files to build into the test runner +# These do not go in a library. They are explicitly included in the test runner +#---------- +# You can adjust these variables to influence how to build the test target +# and where to put and name outputs +# See below to determine defaults +# COMPONENT_NAME - the name of the thing being built +# TEST_TARGET - name the test executable. By default it is +# $(COMPONENT_NAME)_tests +# Helpful if you want 1 > make files in the same directory with different +# executables as output. +# CPPUTEST_HOME - where CppUTest home dir found +# TARGET_PLATFORM - Influences how the outputs are generated by modifying the +# CPPUTEST_OBJS_DIR and CPPUTEST_LIB_DIR to use a sub-directory under the +# normal objs and lib directories. Also modifies where to search for the +# CPPUTEST_LIB to link against. +# CPPUTEST_OBJS_DIR - a directory where o and d files go +# CPPUTEST_LIB_DIR - a directory where libs go +# CPPUTEST_ENABLE_DEBUG - build for debug +# CPPUTEST_USE_MEM_LEAK_DETECTION - Links with overridden new and delete +# CPPUTEST_USE_STD_CPP_LIB - Set to N to keep the standard C++ library out +# of the test harness +# CPPUTEST_USE_GCOV - Turn on coverage analysis +# Clean then build with this flag set to Y, then 'make gcov' +# CPPUTEST_MAPFILE - generate a map file +# CPPUTEST_WARNINGFLAGS - overly picky by default +# OTHER_MAKEFILE_TO_INCLUDE - a hook to use this makefile to make +# other targets. Like CSlim, which is part of fitnesse +# CPPUTEST_USE_VPATH - Use Make's VPATH functionality to support user +# specification of source files and directories that aren't below +# the user's Makefile in the directory tree, like: +# SRC_DIRS += ../../lib/foo +# It defaults to N, and shouldn't be necessary except in the above case. +#---------- +# +# Other flags users can initialize to sneak in their settings +# CPPUTEST_CXXFLAGS - flags for the C++ compiler +# CPPUTEST_CPPFLAGS - flags for the C++ AND C preprocessor +# CPPUTEST_CFLAGS - flags for the C complier +# CPPUTEST_LDFLAGS - Linker flags +#---------- + +# Some behavior is weird on some platforms. Need to discover the platform. + +# Platforms +UNAME_OUTPUT = "$(shell uname -a)" +MACOSX_STR = Darwin +MINGW_STR = MINGW +CYGWIN_STR = CYGWIN +LINUX_STR = Linux +SUNOS_STR = SunOS +UNKNWOWN_OS_STR = Unknown + +# Compilers +CC_VERSION_OUTPUT ="$(shell $(CXX) -v 2>&1)" +CLANG_STR = clang +SUNSTUDIO_CXX_STR = SunStudio + +UNAME_OS = $(UNKNWOWN_OS_STR) + +ifeq ($(findstring $(MINGW_STR),$(UNAME_OUTPUT)),$(MINGW_STR)) + UNAME_OS = $(MINGW_STR) +endif + +ifeq ($(findstring $(CYGWIN_STR),$(UNAME_OUTPUT)),$(CYGWIN_STR)) + UNAME_OS = $(CYGWIN_STR) +endif + +ifeq ($(findstring $(LINUX_STR),$(UNAME_OUTPUT)),$(LINUX_STR)) + UNAME_OS = $(LINUX_STR) +endif + +ifeq ($(findstring $(MACOSX_STR),$(UNAME_OUTPUT)),$(MACOSX_STR)) + UNAME_OS = $(MACOSX_STR) +#lion has a problem with the 'v' part of -a + UNAME_OUTPUT = "$(shell uname -pmnrs)" +endif + +ifeq ($(findstring $(SUNOS_STR),$(UNAME_OUTPUT)),$(SUNOS_STR)) + UNAME_OS = $(SUNOS_STR) + + SUNSTUDIO_CXX_ERR_STR = CC -flags +ifeq ($(findstring $(SUNSTUDIO_CXX_ERR_STR),$(CC_VERSION_OUTPUT)),$(SUNSTUDIO_CXX_ERR_STR)) + CC_VERSION_OUTPUT ="$(shell $(CXX) -V 2>&1)" + COMPILER_NAME = $(SUNSTUDIO_CXX_STR) +endif +endif + +ifeq ($(findstring $(CLANG_STR),$(CC_VERSION_OUTPUT)),$(CLANG_STR)) + COMPILER_NAME = $(CLANG_STR) +endif + +#Kludge for mingw, it does not have cc.exe, but gcc.exe will do +ifeq ($(UNAME_OS),$(MINGW_STR)) + CC := gcc +endif +# RHEL5 is always going to use GCC, CC is going for the old verison +CC := gcc +#And another kludge. Exception handling in gcc 4.6.2 is broken when linking the +# Standard C++ library as a shared library. Unbelievable. +ifeq ($(UNAME_OS),$(MINGW_STR)) + CPPUTEST_LDFLAGS += -static +endif +ifeq ($(UNAME_OS),$(CYGWIN_STR)) + CPPUTEST_LDFLAGS += -static +endif + + +#Kludge for MacOsX gcc compiler on Darwin9 who can't handle pendantic +ifeq ($(UNAME_OS),$(MACOSX_STR)) +ifeq ($(findstring Version 9,$(UNAME_OUTPUT)),Version 9) + CPPUTEST_PEDANTIC_ERRORS = N +endif +endif + +ifndef COMPONENT_NAME + COMPONENT_NAME = name_this_in_the_makefile +endif + +# Debug on by default +ifndef CPPUTEST_ENABLE_DEBUG + CPPUTEST_ENABLE_DEBUG = Y +endif + +# new and delete for memory leak detection on by default +ifndef CPPUTEST_USE_MEM_LEAK_DETECTION + CPPUTEST_USE_MEM_LEAK_DETECTION = Y +endif + +# Use the standard C library +ifndef CPPUTEST_USE_STD_C_LIB + CPPUTEST_USE_STD_C_LIB = Y +endif + +# Use the standard C++ library +ifndef CPPUTEST_USE_STD_CPP_LIB + CPPUTEST_USE_STD_CPP_LIB = Y +endif + +# Use gcov, off by default +ifndef CPPUTEST_USE_GCOV + CPPUTEST_USE_GCOV = N +endif + +ifndef CPPUTEST_PEDANTIC_ERRORS + CPPUTEST_PEDANTIC_ERRORS = Y +endif + +# Default warnings +ifndef CPPUTEST_WARNINGFLAGS + CPPUTEST_WARNINGFLAGS = -Wall -Wextra -Wswitch-default -Wswitch-enum -Wconversion +ifeq ($(CPPUTEST_PEDANTIC_ERRORS), Y) + CPPUTEST_WARNINGFLAGS += -pedantic-errors +endif +ifeq ($(UNAME_OS),$(LINUX_STR)) +# CPPUTEST_WARNINGFLAGS += -Wsign-conversion +endif + CPPUTEST_CXX_WARNINGFLAGS = -Woverloaded-virtual + CPPUTEST_C_WARNINGFLAGS = -Wstrict-prototypes +endif + +#Wonderful extra compiler warnings with clang +ifeq ($(COMPILER_NAME),$(CLANG_STR)) +# -Wno-disabled-macro-expansion -> Have to disable the macro expansion warning as the operator new overload warns on that. +# -Wno-padded -> I sort-of like this warning but if there is a bool at the end of the class, it seems impossible to remove it! (except by making padding explicit) +# -Wno-global-constructors Wno-exit-time-destructors -> Great warnings, but in CppUTest it is impossible to avoid as the automatic test registration depends on the global ctor and dtor +# -Wno-weak-vtables -> The TEST_GROUP macro declares a class and will automatically inline its methods. Thats ok as they are only in one translation unit. Unfortunately, the warning can't detect that, so it must be disabled. + CPPUTEST_CXX_WARNINGFLAGS += -Weverything -Wno-disabled-macro-expansion -Wno-padded -Wno-global-constructors -Wno-exit-time-destructors -Wno-weak-vtables + CPPUTEST_C_WARNINGFLAGS += -Weverything -Wno-padded +endif + +# Uhm. Maybe put some warning flags for SunStudio here? +ifeq ($(COMPILER_NAME),$(SUNSTUDIO_CXX_STR)) + CPPUTEST_CXX_WARNINGFLAGS = + CPPUTEST_C_WARNINGFLAGS = +endif + +# Default dir for temporary files (d, o) +ifndef CPPUTEST_OBJS_DIR +ifndef TARGET_PLATFORM + CPPUTEST_OBJS_DIR = objs +else + CPPUTEST_OBJS_DIR = objs/$(TARGET_PLATFORM) +endif +endif + +# Default dir for the output library +ifndef CPPUTEST_LIB_DIR +ifndef TARGET_PLATFORM + CPPUTEST_LIB_DIR = testLibs +else + CPPUTEST_LIB_DIR = testLibs/$(TARGET_PLATFORM) +endif +endif + +# No map by default +ifndef CPPUTEST_MAP_FILE + CPPUTEST_MAP_FILE = N +endif + +# No extentions is default +ifndef CPPUTEST_USE_EXTENSIONS + CPPUTEST_USE_EXTENSIONS = N +endif + +# No VPATH is default +ifndef CPPUTEST_USE_VPATH + CPPUTEST_USE_VPATH := N +endif +# Make empty, instead of 'N', for usage in $(if ) conditionals +ifneq ($(CPPUTEST_USE_VPATH), Y) + CPPUTEST_USE_VPATH := +endif + +ifndef TARGET_PLATFORM +CPPUTEST_LIB_LINK_DIR = $(CPPUTEST_BUILD_LIB) +else +CPPUTEST_LIB_LINK_DIR = $(CPPUTEST_BUILD_LIB)/$(TARGET_PLATFORM) +endif + +# -------------------------------------- +# derived flags in the following area +# -------------------------------------- + +# Without the C library, we'll need to disable the C++ library and ... +ifeq ($(CPPUTEST_USE_STD_C_LIB), N) + CPPUTEST_USE_STD_CPP_LIB = N + CPPUTEST_USE_MEM_LEAK_DETECTION = N + CPPUTEST_CPPFLAGS += -DCPPUTEST_STD_C_LIB_DISABLED + CPPUTEST_CPPFLAGS += -nostdinc +endif + +CPPUTEST_CPPFLAGS += -DCPPUTEST_COMPILATION + +ifeq ($(CPPUTEST_USE_MEM_LEAK_DETECTION), N) + CPPUTEST_CPPFLAGS += -DCPPUTEST_MEM_LEAK_DETECTION_DISABLED +else + ifndef CPPUTEST_MEMLEAK_DETECTOR_NEW_MACRO_FILE + CPPUTEST_MEMLEAK_DETECTOR_NEW_MACRO_FILE = -include $(CPPUTEST_INCLUDE)/CppUTest/MemoryLeakDetectorNewMacros.h + endif + ifndef CPPUTEST_MEMLEAK_DETECTOR_MALLOC_MACRO_FILE + CPPUTEST_MEMLEAK_DETECTOR_MALLOC_MACRO_FILE = -include $(CPPUTEST_INCLUDE)/CppUTest/MemoryLeakDetectorMallocMacros.h + endif +endif + +ifeq ($(CPPUTEST_ENABLE_DEBUG), Y) + CPPUTEST_CXXFLAGS += -g + CPPUTEST_CFLAGS += -g + CPPUTEST_LDFLAGS += -g +endif + +ifeq ($(CPPUTEST_USE_STD_CPP_LIB), N) + CPPUTEST_CPPFLAGS += -DCPPUTEST_STD_CPP_LIB_DISABLED +ifeq ($(CPPUTEST_USE_STD_C_LIB), Y) + CPPUTEST_CXXFLAGS += -nostdinc++ +endif +endif + +ifdef $(GMOCK_HOME) + GTEST_HOME = $(GMOCK_HOME)/gtest + CPPUTEST_CPPFLAGS += -I$(GMOCK_HOME)/include + GMOCK_LIBRARY = $(GMOCK_HOME)/lib/.libs/libgmock.a + LD_LIBRARIES += $(GMOCK_LIBRARY) + CPPUTEST_CPPFLAGS += -DINCLUDE_GTEST_TESTS + CPPUTEST_WARNINGFLAGS = + CPPUTEST_CPPFLAGS += -I$(GTEST_HOME)/include -I$(GTEST_HOME) + GTEST_LIBRARY = $(GTEST_HOME)/lib/.libs/libgtest.a + LD_LIBRARIES += $(GTEST_LIBRARY) +endif + + +ifeq ($(CPPUTEST_USE_GCOV), Y) + CPPUTEST_CXXFLAGS += -fprofile-arcs -ftest-coverage + CPPUTEST_CFLAGS += -fprofile-arcs -ftest-coverage +endif + +CPPUTEST_CXXFLAGS += $(CPPUTEST_WARNINGFLAGS) $(CPPUTEST_CXX_WARNINGFLAGS) +CPPUTEST_CPPFLAGS += $(CPPUTEST_WARNINGFLAGS) +CPPUTEST_CXXFLAGS += $(CPPUTEST_MEMLEAK_DETECTOR_NEW_MACRO_FILE) +CPPUTEST_CPPFLAGS += $(CPPUTEST_MEMLEAK_DETECTOR_MALLOC_MACRO_FILE) +CPPUTEST_CFLAGS += $(CPPUTEST_C_WARNINGFLAGS) + +TARGET_MAP = $(COMPONENT_NAME).map.txt +ifeq ($(CPPUTEST_MAP_FILE), Y) + CPPUTEST_LDFLAGS += -Wl,-map,$(TARGET_MAP) +endif + +# Link with CppUTest lib +CPPUTEST_LIB = $(CPPUTEST_LIB_LINK_DIR)/libCppUTest.a + +ifeq ($(CPPUTEST_USE_EXTENSIONS), Y) +CPPUTEST_LIB += $(CPPUTEST_LIB_LINK_DIR)/libCppUTestExt.a +endif + +ifdef CPPUTEST_STATIC_REALTIME + LD_LIBRARIES += -lrt +endif + +TARGET_LIB = \ + $(CPPUTEST_LIB_DIR)/lib$(COMPONENT_NAME).a + +ifndef TEST_TARGET + ifndef TARGET_PLATFORM + TEST_TARGET = $(COMPONENT_NAME)_tests + else + TEST_TARGET = $(COMPONENT_NAME)_$(TARGET_PLATFORM)_tests + endif +endif + +#Helper Functions +get_src_from_dir = $(wildcard $1/*.cpp) $(wildcard $1/*.cc) $(wildcard $1/*.c) +get_dirs_from_dirspec = $(wildcard $1) +get_src_from_dir_list = $(foreach dir, $1, $(call get_src_from_dir,$(dir))) +__src_to = $(subst .c,$1, $(subst .cc,$1, $(subst .cpp,$1,$(if $(CPPUTEST_USE_VPATH),$(notdir $2),$2)))) +src_to = $(addprefix $(CPPUTEST_OBJS_DIR)/,$(call __src_to,$1,$2)) +src_to_o = $(call src_to,.o,$1) +src_to_d = $(call src_to,.d,$1) +src_to_gcda = $(call src_to,.gcda,$1) +src_to_gcno = $(call src_to,.gcno,$1) +time = $(shell date +%s) +delta_t = $(eval minus, $1, $2) +debug_print_list = $(foreach word,$1,echo " $(word)";) echo; + +#Derived +STUFF_TO_CLEAN += $(TEST_TARGET) $(TEST_TARGET).exe $(TARGET_LIB) $(TARGET_MAP) + +SRC += $(call get_src_from_dir_list, $(SRC_DIRS)) $(SRC_FILES) +OBJ = $(call src_to_o,$(SRC)) + +STUFF_TO_CLEAN += $(OBJ) + +TEST_SRC += $(call get_src_from_dir_list, $(TEST_SRC_DIRS)) $(TEST_SRC_FILES) +TEST_OBJS = $(call src_to_o,$(TEST_SRC)) +STUFF_TO_CLEAN += $(TEST_OBJS) + + +MOCKS_SRC += $(call get_src_from_dir_list, $(MOCKS_SRC_DIRS)) +MOCKS_OBJS = $(call src_to_o,$(MOCKS_SRC)) +STUFF_TO_CLEAN += $(MOCKS_OBJS) + +ALL_SRC = $(SRC) $(TEST_SRC) $(MOCKS_SRC) + +# If we're using VPATH +ifeq ($(CPPUTEST_USE_VPATH), Y) +# gather all the source directories and add them + VPATH += $(sort $(dir $(ALL_SRC))) +# Add the component name to the objs dir path, to differentiate between same-name objects + CPPUTEST_OBJS_DIR := $(addsuffix /$(COMPONENT_NAME),$(CPPUTEST_OBJS_DIR)) +endif + +#LCOV html generation +BUILD_OUTPUT_DIR=build_output +COVERAGE_DIR=$(BUILD_OUTPUT_DIR)/generated-coverage +LCOV_INFO_FILE=$(TEST_TARGET).info +LCOV_SUMMARY_FILE=$(TEST_TARGET)_summary.info + +#Test coverage with gcov +GCOV_OUTPUT = gcov_output.txt +GCOV_REPORT = gcov_report.txt +GCOV_ERROR = gcov_error.txt +GCOV_GCDA_FILES = $(call src_to_gcda, $(ALL_SRC)) +GCOV_GCNO_FILES = $(call src_to_gcno, $(ALL_SRC)) +TEST_OUTPUT = $(TEST_TARGET).txt +STUFF_TO_CLEAN += \ + $(GCOV_OUTPUT)\ + $(GCOV_REPORT)\ + $(GCOV_REPORT).html\ + $(GCOV_ERROR)\ + $(GCOV_GCDA_FILES)\ + $(GCOV_GCNO_FILES)\ + $(TEST_OUTPUT) + +#The gcda files for gcov need to be deleted before each run +#To avoid annoying messages. +GCOV_CLEAN = $(SILENCE)$(RM) -f $(GCOV_GCDA_FILES) $(GCOV_OUTPUT) $(GCOV_REPORT) $(GCOV_ERROR) +RUN_TEST_TARGET = $(SILENCE) $(GCOV_CLEAN) ; echo "Running $(TEST_TARGET)"; ./$(TEST_TARGET) $(CPPUTEST_EXE_FLAGS) + +ifeq ($(CPPUTEST_USE_GCOV), Y) + + ifeq ($(COMPILER_NAME),$(CLANG_STR)) + LD_LIBRARIES += --coverage + else + LD_LIBRARIES += -lgcov + endif +endif + + +INCLUDES_DIRS_EXPANDED = $(call get_dirs_from_dirspec, $(INCLUDE_DIRS)) +INCLUDES += $(foreach dir, $(INCLUDES_DIRS_EXPANDED), -I$(dir)) +MOCK_DIRS_EXPANDED = $(call get_dirs_from_dirspec, $(MOCKS_SRC_DIRS)) +INCLUDES += $(foreach dir, $(MOCK_DIRS_EXPANDED), -I$(dir)) + +CPPUTEST_CPPFLAGS += $(INCLUDES) + +DEP_FILES = $(call src_to_d, $(ALL_SRC)) +STUFF_TO_CLEAN += $(DEP_FILES) $(PRODUCTION_CODE_START) $(PRODUCTION_CODE_END) +STUFF_TO_CLEAN += $(STDLIB_CODE_START) $(MAP_FILE) cpputest_*.xml junit_run_output + +# We'll use the CPPUTEST_CFLAGS etc so that you can override AND add to the CppUTest flags +CFLAGS = $(CPPUTEST_CFLAGS) $(CPPUTEST_ADDITIONAL_CFLAGS) +CPPFLAGS = $(CPPUTEST_CPPFLAGS) $(CPPUTEST_ADDITIONAL_CPPFLAGS) +CXXFLAGS = $(CPPUTEST_CXXFLAGS) $(CPPUTEST_ADDITIONAL_CXXFLAGS) +LDFLAGS = $(CPPUTEST_LDFLAGS) $(CPPUTEST_ADDITIONAL_LDFLAGS) + +# Don't consider creating the archive a warning condition that does STDERR output +ARFLAGS := $(ARFLAGS)c + +DEP_FLAGS=-MMD -MP + +# Some macros for programs to be overridden. For some reason, these are not in Make defaults +RANLIB = ranlib + +# Targets + +ALL_TARGETS += cpputest_all +ALL_TARGETS_CLEAN += cpputest_clean +.PHONY: cpputest_all +cpputest_all: start $(TEST_TARGET) gcov + $(RUN_TEST_TARGET) + +.PHONY: start +start: $(TEST_TARGET) + $(SILENCE)START_TIME=$(call time) + +.PHONY: all_no_tests +all_no_tests: $(TEST_TARGET) + +.PHONY: flags +flags: + @echo + @echo "OS ${UNAME_OS}" + @echo "Compile C and C++ source with CPPFLAGS:" + @$(call debug_print_list,$(CPPFLAGS)) + @echo "Compile C++ source with CXXFLAGS:" + @$(call debug_print_list,$(CXXFLAGS)) + @echo "Compile C source with CFLAGS:" + @$(call debug_print_list,$(CFLAGS)) + @echo "Link with LDFLAGS:" + @$(call debug_print_list,$(LDFLAGS)) + @echo "Link with LD_LIBRARIES:" + @$(call debug_print_list,$(LD_LIBRARIES)) + @echo "Create libraries with ARFLAGS:" + @$(call debug_print_list,$(ARFLAGS)) + +TEST_DEPS = $(TEST_OBJS) $(MOCKS_OBJS) $(PRODUCTION_CODE_START) $(TARGET_LIB) $(USER_LIBS) $(PRODUCTION_CODE_END) $(CPPUTEST_LIB) $(STDLIB_CODE_START) +test-deps: $(TEST_DEPS) + +$(TEST_TARGET): $(TEST_DEPS) + @echo Linking $@ + $(SILENCE)$(CXX) -o $@ $^ $(LD_LIBRARIES) $(LDFLAGS) + +$(TARGET_LIB): $(OBJ) + @echo Building archive $@ + $(SILENCE)mkdir -p $(dir $@) + $(SILENCE)$(AR) $(ARFLAGS) $@ $^ + $(SILENCE)$(RANLIB) $@ + +test: $(TEST_TARGET) + $(RUN_TEST_TARGET) $(COMMAND_LINE_ARGUMENTS) | tee $(TEST_OUTPUT) +vtest: $(TEST_TARGET) + $(RUN_TEST_TARGET) -v | tee $(TEST_OUTPUT) + +$(CPPUTEST_OBJS_DIR)/%.o: %.cc + @echo compiling $(notdir $<) + $(SILENCE)mkdir -p $(dir $@) + $(SILENCE)$(COMPILE.cpp) $(DEP_FLAGS) $(OUTPUT_OPTION) $< + +$(CPPUTEST_OBJS_DIR)/%.o: %.cpp + @echo compiling $(notdir $<) + $(SILENCE)mkdir -p $(dir $@) + $(SILENCE)$(COMPILE.cpp) $(DEP_FLAGS) $(OUTPUT_OPTION) $< + +$(CPPUTEST_OBJS_DIR)/%.o: %.c + @echo compiling $(notdir $<) + $(SILENCE)mkdir -p $(dir $@) + $(SILENCE)$(COMPILE.c) $(DEP_FLAGS) $(OUTPUT_OPTION) $< + +ifneq "$(MAKECMDGOALS)" "clean" +-include $(DEP_FILES) +endif + +.PHONY: cpputest_clean +cpputest_clean: + @echo Making clean + $(SILENCE)$(RM) $(STUFF_TO_CLEAN) + $(SILENCE)$(RM) -rf gcov $(CPPUTEST_OBJS_DIR) + $(SILENCE)find . -name "*.gcno" | xargs $(RM) -f + $(SILENCE)find . -name "*.gcda" | xargs $(RM) -f + +#realclean gets rid of all gcov, o and d files in the directory tree +#not just the ones made by this makefile +.PHONY: realclean +realclean: clean + $(SILENCE)$(RM) -rf gcov + $(SILENCE)$(RM) -rf $(BUILD_OUTPUT_DIR) + $(SILENCE)find . -name "*.gdcno" | xargs $(RM) -f + $(SILENCE)find . -name "*.[do]" | xargs $(RM) -f + +gcov: test + $(SILENCE)mkdir -p $(BUILD_OUTPUT_DIR) +ifeq ($(CPPUTEST_USE_VPATH), Y) + $(SILENCE)gcov --object-directory $(CPPUTEST_OBJS_DIR) $(SRC) >> $(GCOV_OUTPUT) 2>> $(GCOV_ERROR) +else + $(SILENCE)for d in $(SRC_DIRS) ; do \ + FILES=`ls $$d/*.c $$d/*.cc $$d/*.cpp 2> /dev/null` ; \ + gcov --object-directory $(CPPUTEST_OBJS_DIR)/$$d $$FILES >> $(GCOV_OUTPUT) 2>>$(GCOV_ERROR) ; \ + done + $(SILENCE)for f in $(SRC_FILES) ; do \ + gcov --object-directory $(CPPUTEST_OBJS_DIR)/$$f $$f >> $(GCOV_OUTPUT) 2>>$(GCOV_ERROR) ; \ + done +endif + $(SILENCE)./filterGcov.sh $(GCOV_OUTPUT) $(GCOV_ERROR) $(GCOV_REPORT) $(TEST_OUTPUT) + $(SILENCE)mkdir -p gcov + $(SILENCE)mv *.gcov gcov + $(SILENCE)mv gcov_* gcov + $(SILENCE)mkdir -p $(COVERAGE_DIR) + $(SILENCE)lcov -d $(CPPUTEST_OBJS_DIR) -c -o $(COVERAGE_DIR)/$(LCOV_INFO_FILE) -q --rc lcov_branch_coverage=1 + $(SILENCE)lcov --remove $(COVERAGE_DIR)/$(LCOV_INFO_FILE) $(LCOV_EXCLUDE_PATTERN) -o $(COVERAGE_DIR)/$(LCOV_INFO_FILE) + $(SILENCE)lcov --remove $(COVERAGE_DIR)/$(LCOV_INFO_FILE) "*CppUTest*" -o $(COVERAGE_DIR)/$(LCOV_INFO_FILE) + $(SILENCE)lcov --summary ./$(COVERAGE_DIR)/$(LCOV_INFO_FILE) &> $(COVERAGE_DIR)/$(LCOV_SUMMARY_FILE) + $(SILENCE)echo ansic:line:`grep -E -o "([0-9]*\.[0-9]+|[0-9]+)" $(COVERAGE_DIR)/$(LCOV_SUMMARY_FILE) | head -1` >> $(COVERAGE_DIR)/coverage-data.txt + $(SILENCE)genhtml -o $(COVERAGE_DIR) $(COVERAGE_DIR)/$(LCOV_INFO_FILE) -q --rc lcov_branch_coverage=1 + @echo "See gcov directory for details" + +.PHONEY: format +format: + $(CPPUTEST_HOME)/scripts/reformat.sh $(PROJECT_HOME_DIR) + +.PHONEY: debug +debug: + @echo + @echo "Target Source files:" + @$(call debug_print_list,$(SRC)) + @echo "Target Object files:" + @$(call debug_print_list,$(OBJ)) + @echo "Test Source files:" + @$(call debug_print_list,$(TEST_SRC)) + @echo "Test Object files:" + @$(call debug_print_list,$(TEST_OBJS)) + @echo "Mock Source files:" + @$(call debug_print_list,$(MOCKS_SRC)) + @echo "Mock Object files:" + @$(call debug_print_list,$(MOCKS_OBJS)) + @echo "All Input Dependency files:" + @$(call debug_print_list,$(DEP_FILES)) + @echo Stuff to clean: + @$(call debug_print_list,$(STUFF_TO_CLEAN)) + @echo Includes: + @$(call debug_print_list,$(INCLUDES)) + +-include $(OTHER_MAKEFILE_TO_INCLUDE) diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/LICENSE.txt b/components/aws_iot/aws-iot-device-sdk-embedded-C/LICENSE.txt new file mode 100644 index 00000000..1b6cbea0 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/LICENSE.txt @@ -0,0 +1,120 @@ +############################################################################################################################# + + +Apache License +Version 2.0, January 2004 + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + 1. You must give any other recipients of the Work or Derivative Works a copy of this License; and + 2. You must cause any modified files to carry prominent notices stating that You changed the files; and + 3. You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + 4. If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. +You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + + +############################################################################################################################# + + +Components are made available under the terms of the Eclipse Public License v1.0 +and Eclipse Distribution License v1.0 which accompany this distribution. + +The Eclipse Public License is available at + http://www.eclipse.org/legal/epl-v10.html +and the Eclipse Distribution License is available at + http://www.eclipse.org/org/documents/edl-v10.php. + + +############################################################################################################################# + + +Copyright (C) 2012, iSEC Partners. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +############################################################################################################################# + + _ _ ____ _ + Project ___| | | | _ \| | + / __| | | | |_) | | + | (__| |_| | _ <| |___ + \___|\___/|_| \_\_____| + +Copyright (C) 1998 - 2011, Daniel Stenberg, , et al. + +This software is licensed as described in the file COPYING, which +you should have received as part of this distribution. The terms +are also available at http://curl.haxx.se/docs/copyright.html. + +You may opt to use, copy, modify, merge, publish, distribute and/or sell +copies of the Software, and permit persons to whom the Software is +furnished to do so, under the terms of the COPYING file. + +This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY +KIND, either express or implied. + + +############################################################################################################################# + + +Copyright (c) 2010 Serge A. Zaitsev + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +############################################################################################################################# + diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/Makefile b/components/aws_iot/aws-iot-device-sdk-embedded-C/Makefile new file mode 100644 index 00000000..eebdb171 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/Makefile @@ -0,0 +1,131 @@ +#This target is to ensure accidental execution of Makefile as a bash script will not execute commands like rm in unexpected directories and exit gracefully. +.prevent_execution: + exit 0 + +#Set this to @ to keep the makefile quiet +ifndef SILENCE + SILENCE = @ +endif + +CC = gcc +RM = rm + +DEBUG = + +#--- Inputs ----# +COMPONENT_NAME = IotSdkC + +ALL_TARGETS := build-cpputest +ALL_TARGETS_CLEAN := + +CPPUTEST_USE_EXTENSIONS = Y +CPP_PLATFORM = Gcc +CPPUTEST_CFLAGS += -std=gnu99 +CPPUTEST_LDFLAGS += -lpthread +CPPUTEST_CFLAGS += -D__USE_BSD +CPPUTEST_USE_GCOV = Y + +#IoT client directory +IOT_CLIENT_DIR = . + +APP_DIR = $(IOT_CLIENT_DIR)/tests/unit +APP_NAME = aws_iot_sdk_unit_tests +APP_SRC_FILES = $(shell find $(APP_DIR)/src -name '*.cpp') +APP_SRC_FILES = $(shell find $(APP_DIR)/src -name '*.c') +APP_INCLUDE_DIRS = -I $(APP_DIR)/include + +CPPUTEST_DIR = $(IOT_CLIENT_DIR)/external_libs/CppUTest + +# Provide paths for CppUTest to run Unit Tests otherwise build will fail +ifndef CPPUTEST_INCLUDE + CPPUTEST_INCLUDE = $(CPPUTEST_DIR)/include +endif + +ifndef CPPUTEST_BUILD_LIB + CPPUTEST_BUILD_LIB = $(CPPUTEST_DIR) +endif + +CPPUTEST_LDFLAGS += -ldl $(CPPUTEST_BUILD_LIB)/libCppUTest.a + +PLATFORM_DIR = $(IOT_CLIENT_DIR)/platform/linux + +#MbedTLS directory +TEMP_MBEDTLS_SRC_DIR = $(APP_DIR)/tls_mock +TLS_LIB_DIR = $(TEMP_MBEDTLS_SRC_DIR) +TLS_INCLUDE_DIR = -I $(TEMP_MBEDTLS_SRC_DIR) + +# Logging level control +LOG_FLAGS += -DENABLE_IOT_DEBUG +#LOG_FLAGS += -DENABLE_IOT_TRACE +LOG_FLAGS += -DENABLE_IOT_INFO +LOG_FLAGS += -DENABLE_IOT_WARN +LOG_FLAGS += -DENABLE_IOT_ERROR +COMPILER_FLAGS += $(LOG_FLAGS) + +EXTERNAL_LIBS += -L$(CPPUTEST_BUILD_LIB) + +#IoT client directory +PLATFORM_COMMON_DIR = $(PLATFORM_DIR)/common + +IOT_INCLUDE_DIRS = -I $(PLATFORM_COMMON_DIR) +IOT_INCLUDE_DIRS += -I $(IOT_CLIENT_DIR)/include +IOT_INCLUDE_DIRS += -I $(IOT_CLIENT_DIR)/external_libs/jsmn + +IOT_SRC_FILES += $(shell find $(PLATFORM_COMMON_DIR)/ -name '*.c') +IOT_SRC_FILES += $(shell find $(IOT_CLIENT_DIR)/src/ -name '*.c') +IOT_SRC_FILES += $(shell find $(IOT_CLIENT_DIR)/external_libs/jsmn/ -name '*.c') + +#Aggregate all include and src directories +INCLUDE_DIRS += $(IOT_INCLUDE_DIRS) +INCLUDE_DIRS += $(APP_INCLUDE_DIRS) +INCLUDE_DIRS += $(TLS_INCLUDE_DIR) +INCLUDE_DIRS += $(CPPUTEST_INCLUDE) + +TEST_SRC_DIRS = $(APP_DIR)/src + +SRC_FILES += $(APP_SRC_FILES) +SRC_FILES += $(IOT_SRC_FILES) + +COMPILER_FLAGS += -g +COMPILER_FLAGS += $(LOG_FLAGS) +PRE_MAKE_CMDS = cd $(CPPUTEST_DIR) && +PRE_MAKE_CMDS += cmake CMakeLists.txt && +PRE_MAKE_CMDS += make && +PRE_MAKE_CMDS += cd - && +PRE_MAKE_CMDS += pwd && +PRE_MAKE_CMDS += cp -f $(CPPUTEST_DIR)/src/CppUTest/libCppUTest.a $(CPPUTEST_DIR)/libCppUTest.a && +PRE_MAKE_CMDS += cp -f $(CPPUTEST_DIR)/src/CppUTestExt/libCppUTestExt.a $(CPPUTEST_DIR)/libCppUTestExt.a + +# Using TLS Mock for running Unit Tests +MOCKS_SRC += $(APP_DIR)/tls_mock/aws_iot_tests_unit_mock_tls_params.c +MOCKS_SRC += $(APP_DIR)/tls_mock/aws_iot_tests_unit_mock_tls.c + +ISYSTEM_HEADERS += $(IOT_ISYSTEM_HEADERS) +CPPUTEST_CPPFLAGS += $(ISYSTEM_HEADERS) +CPPUTEST_CPPFLAGS += $(LOG_FLAGS) + +LCOV_EXCLUDE_PATTERN = "tests/unit/*" +LCOV_EXCLUDE_PATTERN += "tests/integration/*" +LCOV_EXCLUDE_PATTERN += "external_libs/*" + +#use this section for running a specific group of tests, comment this to run all +#ONLY FOR TESTING PURPOSE +#COMMAND_LINE_ARGUMENTS += -g CommonTests +#COMMAND_LINE_ARGUMENTS += -v + +build-cpputest: + $(PRE_MAKE_CMDS) + +include CppUTestMakefileWorker.mk + +.PHONY: run-unit-tests +run-unit-tests: $(ALL_TARGETS) + @echo $(ALL_TARGETS) + +.PHONY: clean +clean: + $(MAKE) -C $(CPPUTEST_DIR) clean + $(RM) -rf build_output + $(RM) -rf gcov + $(RM) -rf objs + $(RM) -rf testLibs \ No newline at end of file diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/NOTICE.txt b/components/aws_iot/aws-iot-device-sdk-embedded-C/NOTICE.txt new file mode 100644 index 00000000..c3f856f1 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/NOTICE.txt @@ -0,0 +1,16 @@ +AWS C SDK for Internet of Things Service +Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +This product includes software developed by +Amazon Inc (http://www.amazon.com/). + +********************** +THIRD PARTY COMPONENTS +********************** +This software includes third party software subject to the following licensing: +- Embedded C MQTT Client - From the Eclipse Paho Project - EPL v1.0 +- mbedTLS (external library, included in tarball or downloaded separately) - Apache 2.0 +- jsmn (JSON Parsing) - MIT +- cURL (hostname verification) - MIT + +The licenses for these third party components are included in LICENSE.txt diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/PortingGuide.md b/components/aws_iot/aws-iot-device-sdk-embedded-C/PortingGuide.md new file mode 100644 index 00000000..18baaf3c --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/PortingGuide.md @@ -0,0 +1,147 @@ +# Porting Guide + +## Scope +The scope of this document is to provide instructions to modify the provided source files and functions in this SDK to run in a variety of embedded C–based environments (e.g. real-time OS, embedded Linux) and to be adjusted to use a specific TLS implementation as available with specific hardware platforms. + +## Contents of the SDK + +The C-code files of this SDK are delivered via the following directory structure (see comment behind folder name for an explanation of its content). + +Current SDK Directory Layout (mbedTLS) + +|--`certs` (Private key, device certificate and Root CA)
+|--`docs` (Developer guide & API documentation)
+|--`external_libs` (external libraries - jsmn, mbedTLS)
+|--`include` (Header files of the AWS IoT device SDK)
+|--`src` (Source files of the AWS IoT device SDK)
+|--`platform` (Platform specific files)
+|--`samples` (Samples including makefiles for building on mbedTLS)
+|--`tests` (Tests for verifying SDK is functioning as expected)
+ +All makefiles in this SDK were configured using the documented folder structure above, so moving or renaming folders will require modifications to makefiles. + +## Explanation of folders and their content + + * `certs` : This directory is initially empty and will need to contain the private key, the client certificate and the root CA. The client certificate and private key can be downloaded from the AWS IoT console or be created using the AWS CLI commands. The root CA can be downloaded from [Symantec](https://www.symantec.com/content/en/us/enterprise/verisign/roots/VeriSign-Class%203-Public-Primary-Certification-Authority-G5.pem). + + * `docs` : SDK API and file documentation. + + * `external_libs` : The mbedTLS and jsmn source files. The jsmn source files are always present. The mbedTLS source files are only included when downloading the tarball version of the SDK. + + * `include` : This directory contains the header files that an application using the SDK needs to include. + + * `src` : This directory contains the SDK source code including the MQTT library, device shadow code and utilities. + + * `platform` : Platform specific files for timer, TLS and threading layers. Includes a reference implementation for the linux using mbedTLS and pthread. + + * `samples` : This directory contains sample applications as well as their makefiles. The samples include a simple MQTT example which publishes and subscribes to the AWS IoT service as well as a device shadow example that shows example usage of the device shadow functionality. + + * `tests` : Contains tests for verifying SDK functionality. For further details please check the readme file included with the tests [here](https://github.com/aws/aws-iot-device-sdk-embedded-C/blob/master/tests/README.md/). + +## Integrating the SDK into your environment + +This section explains the API calls that need to be implemented in order for the Device SDK to run on your platform. The SDK interfaces follow the driver model where only prototypes are defined by the Device SDK itself while the implementation is delegated to the user of the SDK to adjust it to the platform in use. The following sections list the needed functionality for the device SDK to run successfully on any given platform. + +### Timer Functions + +A timer implementation is necessary to handle request timeouts (sending MQTT connect, subscribe, etc. commands) as well as connection maintenance (MQTT keep-alive pings). Timers need millisecond resolution and are polled for expiration so these can be implemented using a "milliseconds since startup" free-running counter if desired. In the synchronous sample provided with this SDK only one command will be "in flight" at one point in time plus the client's ping timer. + +Define the `Timer` Struct as in `timer_platform.h` + +`void init_timer(Timer *);` +init_timer - A timer structure is initialized to a clean state. + +`bool has_timer_expired(Timer *);` +has_timer_expired - a polling function to determine if the timer has expired. + +`void countdown_ms(Timer *, uint32_t);` +countdown_ms - set the timer to expire in x milliseconds and start the timer. + +`void countdown_sec(Timer *, uint32_t);` +countdown_sec - set the timer to expire in x seconds and start the timer. + +`uint32_t left_ms(Timer *);` +left_ms - query time in milliseconds left on the timer. + + +### Network Functions + +In order for the MQTT client stack to be able to communicate via the TCP/IP network protocol stack using a mutually authenticated TLS connection, the following API calls need to be implemented for your platform. + +For additional details about API parameters refer to the [API documentation](http://aws-iot-device-sdk-embedded-c-docs.s3-website-us-east-1.amazonaws.com/index.html). + +Define the `TLSDataParams` Struct as in `network_platform.h` +This is used for data specific to the TLS library being used. + +`IoT_Error_t iot_tls_init(Network *pNetwork, char *pRootCALocation, const char *pDeviceCertLocation, + const char *pDevicePrivateKeyLocation, const char *pDestinationURL, + uint16_t DestinationPort, uint32_t timeout_ms, bool ServerVerificationFlag);` +Initialize the network client / structure. + +`IoT_Error_t iot_tls_connect(Network *pNetwork, TLSConnectParams *TLSParams);` +Create a TLS TCP socket to the configure address using the credentials provided via the NewNetwork API call. This will include setting up certificate locations / arrays. + + +`IoT_Error_t iot_tls_write(Network*, unsigned char*, size_t, Timer *, size_t *);` +Write to the TLS network buffer. + +`IoT_Error_t iot_tls_read(Network*, unsigned char*, size_t, Timer *, size_t *);` +Read from the TLS network buffer. + +`IoT_Error_t iot_tls_disconnect(Network *pNetwork);` +Disconnect API + +`IoT_Error_t iot_tls_destroy(Network *pNetwork);` +Clean up the connection + +`IoT_Error_t iot_tls_is_connected(Network *pNetwork);` +Check if the TLS layer is still connected + +The TLS library generally provides the API for the underlying TCP socket. + + +### Threading Functions + +The MQTT client uses a state machine to control operations in multi-threaded situations. However it requires a mutex implementation to guarantee thread safety. This is not required in situations where thread safety is not important and it is disabled by default. The _ENABLE_THREAD_SUPPORT_ macro needs to be defined in aws_iot_config.h to enable this layer. You will also need to add the -lpthread linker flag for the compiler if you are using the provided reference implementation. + +For additional details about API parameters refer to the [API documentation](http://aws-iot-device-sdk-embedded-c-docs.s3-website-us-east-1.amazonaws.com/index.html). + +Define the `IoT_Mutex_t` Struct as in `threads_platform.h` +This is used for data specific to the TLS library being used. + +`IoT_Error_t aws_iot_thread_mutex_init(IoT_Mutex_t *);` +Initialize the mutex provided as argument. + +`IoT_Error_t aws_iot_thread_mutex_lock(IoT_Mutex_t *);` +Lock the mutex provided as argument + +`IoT_Error_t aws_iot_thread_mutex_unlock(IoT_Mutex_t *);` +Unlock the mutex provided as argument. + +`IoT_Error_t aws_iot_thread_mutex_destroy(IoT_Mutex_t *);` +Destroy the mutex provided as argument. + +The threading layer provides the implementation of mutexes used for thread-safe operations. + +### Sample Porting: + +Marvell has ported the SDK for their development boards. [These](https://github.com/marvell-iot/aws_starter_sdk/tree/master/sdk/external/aws_iot/platform/wmsdk) files are example implementations of the above mentioned functions. +This provides a port of the timer and network layer. The threading layer is not a part of this port. + +## Time source for certificate validation + +As part of the TLS handshake the device (client) needs to validate the server certificate which includes validation of the certificate lifetime requiring that the device is aware of the actual time. Devices should be equipped with a real time clock or should be able to obtain the current time via NTP. Bypassing validation of the lifetime of a certificate is not recommended as it exposes the device to a security vulnerability, as it will still accept server certificates even when they have already has_timer_expired. + +## Integration into operating system +### Single-Threaded implementation + +The single threaded implementation implies that the sample application code (SDK + MQTT client) is called periodically by the firmware application running on the main thread. This is done by calling the function `aws_iot_mqtt_yield` (in the simple pub-sub example) and by calling `aws_iot_shadow_yield()` (in the device shadow example). In both cases the keep-alive time is set to 10 seconds. This means that the yield functions need to be called at a minimum frequency of once every 10 seconds. Note however that the `iot_mqtt_yield()` function takes care of reading incoming MQTT messages from the IoT service as well and hence should be called more frequently depending on the timing requirements of an application. All incoming messages can only be processed at the frequency at which `yield` is called. + +### Multi-Threaded implementation + +In the simple multi-threaded case the `yield` function can be moved to a background thread. Ensure this task runs at the frequency described above. In this case, depending on the OS mechanism, a message queue or mailbox could be used to proxy incoming MQTT messages from the callback to the worker task responsible for responding to or dispatching messages. A similar mechanism could be employed to queue publish messages from threads into a publish queue that are processed by a publishing task. Ensure the threading layer is enabled as the library is not thread safe otherwise. +There is a validation test for the multi-threaded implementation that can be found with the integration tests. You can find further details in the Readme for the integration tests [here](https://github.com/aws/aws-iot-device-sdk-embedded-C/blob/master/tests/integration/README.md). We have run the validation test with 10 threads sending 500 messages each and verified to be working fine. It can be used as a reference testing application to validate whether your use case will work with multi-threading enabled. + +## Sample applications + +The sample apps in this SDK provide a working implementation for mbedTLS. They use a reference implementation for linux provided with the SDK. Threading layer is enabled in the subscribe publish sample. diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/README.md b/components/aws_iot/aws-iot-device-sdk-embedded-C/README.md new file mode 100644 index 00000000..8b762d4a --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/README.md @@ -0,0 +1,117 @@ +## ***** NOTICE ***** +This repository is moving to a new branching system. The master branch will now contain bug fixes/features that have been minimally tested to ensure nothing major is broken. The release branch will contain new releases for the SDK that have been tested thoroughly on all supported platforms. Please ensure that you are tracking the release branch for all production work. + +This change will allow us to push out bug fixes quickly and avoid having situations where issues stay open for a very long time. + +## Overview + +The AWS IoT device SDK for embedded C is a collection of C source files which can be used in embedded applications to securely connect to the [AWS IoT platform](http://docs.aws.amazon.com/iot/latest/developerguide/what-is-aws-iot.html). It includes transport clients **MQTT**, **TLS** implementations and examples for their use. It also supports AWS IoT specific features such as **Thing Shadow**. It is distributed in source form and intended to be built into customer firmware along with application code, other libraries and RTOS. For additional information about porting the Device SDK for embedded C onto additional platforms please refer to the [PortingGuide](https://github.com/aws/aws-iot-device-sdk-embedded-c/blob/master/PortingGuide.md/). + +## Features +The Device SDK simplifies access to the Pub/Sub functionality of the AWS IoT broker via MQTT and provide APIs to interact with Thing Shadows. The SDK has been tested to work with the AWS IoT platform to ensure best interoperability of a device with the AWS IoT platform. + +### MQTT Connection +The Device SDK provides functionality to create and maintain a mutually authenticated TLS connection over which it runs MQTT. This connection is used for any further publish operations and allow for subscribing to MQTT topics which will call a configurable callback function when these topics are received. + +### Thing Shadow +The Device SDK implements the specific protocol for Thing Shadows to retrieve, update and delete Thing Shadows adhering to the protocol that is implemented to ensure correct versioning and support for client tokens. It abstracts the necessary MQTT topic subscriptions by automatically subscribing to and unsubscribing from the reserved topics as needed for each API call. Inbound state change requests are automatically signalled via a configurable callback. + +## Design Goals of this SDK +The embedded C SDK was specifically designed for resource constrained devices (running on micro-controllers and RTOS). + +Primary aspects are: + * Flexibility in picking and choosing functionality (reduce memory footprint) + * Static memory only (no malloc’s) + * Configurable resource usage(JSON tokens, MQTT subscription handlers, etc…) + * Can be ported to a different RTOS, uses wrappers for OS specific functions + +For more information on the Architecture of the SDK refer [here](http://aws-iot-device-sdk-embedded-c-docs.s3-website-us-east-1.amazonaws.com/index.html) + +## Collection of Metrics +Beginning with Release v2.2.0 of the SDK, AWS collects usage metrics indicating which language and version of the SDK is being used. This allows us to prioritize our resources towards addressing issues faster in SDKs that see the most and is an important data point. However, we do understand that not all customers would want to report this data by default. In that case, the sending of usage metrics can be easily disabled by the user by setting the `DISABLE_METRICS` flag to true in the +`aws_iot_config.h` for each application. + +## How to get started ? +Ensure you understand the AWS IoT platform and create the necessary certificates and policies. For more information on the AWS IoT platform please visit the [AWS IoT developer guide](http://docs.aws.amazon.com/iot/latest/developerguide/iot-security-identity.html). + +In order to quickly get started with the AWS IoT platform, we have ported the SDK for POSIX type Operating Systems like Ubuntu, OS X and RHEL. The SDK is configured for the mbedTLS library and can be built out of the box with *GCC* using *make utility*. You'll need to download mbedTLS from the official ARMmbed repository. We recommend that you pick the latest version in order to have up-to-date security fixes. + +## Installation +This section explains the individual steps to retrieve the necessary files and be able to build your first application using the AWS IoT device SDK for embedded C. + +Steps: + + * Create a directory to hold your application e.g. (/home//aws_iot/my_app) + * Change directory to this new directory + * Download the SDK to device and place in the newly created directory + * Expand the tarball (tar -xf ). This will create the below directories: + * `certs` - TLS certificates directory + * `docs` - SDK API and file documentation. This folder is not present on GitHub. You can access the documentation [here](http://aws-iot-device-sdk-embedded-c-docs.s3-website-us-east-1.amazonaws.com/index.html) + * `external_libs` - The mbedTLS and jsmn source files + * `include` - The AWS IoT SDK header files + * `platform` - Platform specific files for timer, TLS and threading layers + * `samples` - The sample applications + * `src` - The AWS IoT SDK source files + * `tests` - Contains tests for verifying that the SDK is functioning as expected. More information can be found [here](https://github.com/aws/aws-iot-device-sdk-embedded-c/blob/master/tests/README.md) + * View further information on how to use the SDK in the Readme file for samples that can be found [here](https://github.com/aws/aws-iot-device-sdk-embedded-c/blob/master/samples/README.md) + +Also, for a guided example on getting started with the Thing Shadow, visit the AWS IoT Console's [Interactive Guide](https://console.aws.amazon.com/iot). + +## Porting to different platforms +As Embedded devices run on different Real Time Operating Systems and TCP/IP stacks, it is one of the important design goals for the Device SDK to keep it portable. Please refer to the [porting guide](https://github.com/aws/aws-iot-device-sdk-embedded-C/blob/master/PortingGuide.md) to get more information on how to make this SDK run on your devices (i.e. micro-controllers). + +## Migrating from 1.x to 2.x +The 2.x branch makes several changes to the SDK. This section provides information on what changes will be required in the client application for migrating from v1.x to 2.x. + + * The first change is in the folder structure. Client applications using the SDK now need to keep only the certs, external_libs, include, src and platform folder in their application. The folder descriptions can be found above + * All the SDK headers are in the `include` folder. These need to be added to the makefile as include directories + * The source files are in the `src` folder. These need to be added to the makefile as one of the source directories + * Similar to 1.x, the platform folder contains the platform specific headers and source files. These need to be added to the makefile as well + * The `platform/threading` folder only needs to be added if multi-threading is required, and the `_ENABLE_THREAD_SUPPORT_` macro is defined in config + * The list below provides a mapping for migrating from the major APIs used in 1.x to the new APIs: + + | Description | 1.x | 2.x | + | :---------- | :-- | :-- | + | Initializing the client | ```void aws_iot_mqtt_init(MQTTClient_t *pClient);``` | ```IoT_Error_t aws_iot_mqtt_init(AWS_IoT_Client *pClient, IoT_Client_Init_Params *pInitParams);``` | + | Connect | ```IoT_Error_t aws_iot_mqtt_connect(MQTTConnectParams *pParams);``` | ```IoT_Error_t aws_iot_mqtt_connect(AWS_IoT_Client *pClient, IoT_Client_Connect_Params *pConnectParams);``` | + | Subscribe | ```IoT_Error_t aws_iot_mqtt_subscribe(MQTTSubscribeParams *pParams);``` | ```IoT_Error_t aws_iot_mqtt_subscribe(AWS_IoT_Client *pClient, const char *pTopicName, uint16_t topicNameLen, QoS qos, pApplicationHandler_t pApplicationHandler, void *pApplicationHandlerData);``` | + | Unsubscribe | ```IoT_Error_t aws_iot_mqtt_unsubscribe(char *pTopic);``` | ```IoT_Error_t aws_iot_mqtt_unsubscribe(AWS_IoT_Client *pClient, const char *pTopicFilter, uint16_t topicFilterLen);``` | + | Yield | ```IoT_Error_t aws_iot_mqtt_yield(int timeout);``` | ```IoT_Error_t aws_iot_mqtt_yield(AWS_IoT_Client *pClient, uint32_t timeout_ms);``` | + | Publish | ```IoT_Error_t aws_iot_mqtt_publish(MQTTPublishParams *pParams);``` | ```IoT_Error_t aws_iot_mqtt_publish(AWS_IoT_Client *pClient, const char *pTopicName, uint16_t topicNameLen, IoT_Publish_Message_Params *pParams);``` | + | Disconnect | ```IoT_Error_t aws_iot_mqtt_disconnect(void);``` | ```IoT_Error_t aws_iot_mqtt_disconnect(AWS_IoT_Client *pClient);``` | + +You can find more information on how to use the new APIs in the Readme file for samples that can be found [here](https://github.com/aws/aws-iot-device-sdk-embedded-c/blob/master/samples/README.md) + +## Resources +[API Documentation](http://aws-iot-device-sdk-embedded-c-docs.s3-website-us-east-1.amazonaws.com/index.html) + +[MQTT 3.1.1 Spec](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/csprd02/mqtt-v3.1.1-csprd02.html) + +## Support +If you have any technical questions about AWS IoT Device SDK, use the [AWS IoT forum](https://forums.aws.amazon.com/forum.jspa?forumID=210). +For any other questions on AWS IoT, contact [AWS Support](https://aws.amazon.com/contact-us/). + +## Sample APIs +Connecting to the AWS IoT MQTT platform + +``` +AWS_IoT_Client client; +rc = aws_iot_mqtt_init(&client, &iotInitParams); +rc = aws_iot_mqtt_connect(&client, &iotConnectParams); +``` + + +Subscribe to a topic + +``` +AWS_IoT_Client client; +rc = aws_iot_mqtt_subscribe(&client, "sdkTest/sub", 11, QOS0, iot_subscribe_callback_handler, NULL); +``` + + +Update Thing Shadow from a device + +``` +rc = aws_iot_shadow_update(&mqttClient, AWS_IOT_MY_THING_NAME, pJsonDocumentBuffer, ShadowUpdateStatusCallback, + pCallbackContext, TIMEOUT_4SEC, persistenSubscription); +``` diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/certs/README.txt b/components/aws_iot/aws-iot-device-sdk-embedded-C/certs/README.txt new file mode 100644 index 00000000..8df3d020 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/certs/README.txt @@ -0,0 +1,4 @@ +# Copy certificates for running the samples and tests provided with the SDK into this directory +# Certificates can be created and downloaded from the AWS IoT Console +# The IoT Client takes the full path of the certificates as an input parameter while initializing +# This is the default folder for the certificates only for samples and tests. A different path can be specified if required. \ No newline at end of file diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/external_libs/CppUTest/README.txt b/components/aws_iot/aws-iot-device-sdk-embedded-C/external_libs/CppUTest/README.txt new file mode 100644 index 00000000..5b2e0925 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/external_libs/CppUTest/README.txt @@ -0,0 +1,2 @@ +# Copy source code for CppUTest into this directory +# The SDK was tested internally with CppUTest v3.6 which can be found here - https://github.com/cpputest/cpputest/releases/tag/v3.6 \ No newline at end of file diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/external_libs/jsmn/jsmn.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/external_libs/jsmn/jsmn.c new file mode 100644 index 00000000..e920e862 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/external_libs/jsmn/jsmn.c @@ -0,0 +1,344 @@ +/* + * Copyright (c) 2010 Serge A. Zaitsev + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +/** + * @file jsmn.c + * @brief Implementation of the JSMN (Jasmine) JSON parser. + * + * For more information on JSMN: + * @see http://zserge.com/jsmn.html + */ + +#include "jsmn.h" + +/** + * Allocates a fresh unused token from the token pull. + */ +static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser, + jsmntok_t *tokens, size_t num_tokens) { + jsmntok_t *tok; + if (parser->toknext >= num_tokens) { + return NULL; + } + tok = &tokens[parser->toknext++]; + tok->start = tok->end = -1; + tok->size = 0; +#ifdef JSMN_PARENT_LINKS + tok->parent = -1; +#endif + return tok; +} + +/** + * Fills token type and boundaries. + */ +static void jsmn_fill_token(jsmntok_t *token, jsmntype_t type, + int start, int end) { + token->type = type; + token->start = start; + token->end = end; + token->size = 0; +} + +/** + * Fills next available token with JSON primitive. + */ +static int jsmn_parse_primitive(jsmn_parser *parser, const char *js, + size_t len, jsmntok_t *tokens, size_t num_tokens) { + jsmntok_t *token; + int start; + + start = parser->pos; + + for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { + switch (js[parser->pos]) { +#ifndef JSMN_STRICT + /* In strict mode primitive must be followed by "," or "}" or "]" */ + case ':': +#endif + case '\t' : case '\r' : case '\n' : case ' ' : + case ',' : case ']' : case '}' : + goto found; + } + if (js[parser->pos] < 32 || js[parser->pos] >= 127) { + parser->pos = start; + return JSMN_ERROR_INVAL; + } + } +#ifdef JSMN_STRICT + /* In strict mode primitive must be followed by a comma/object/array */ + parser->pos = start; + return JSMN_ERROR_PART; +#endif + +found: + if (tokens == NULL) { + parser->pos--; + return 0; + } + token = jsmn_alloc_token(parser, tokens, num_tokens); + if (token == NULL) { + parser->pos = start; + return JSMN_ERROR_NOMEM; + } + jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos); +#ifdef JSMN_PARENT_LINKS + token->parent = parser->toksuper; +#endif + parser->pos--; + return 0; +} + +/** + * Fills next token with JSON string. + */ +static int jsmn_parse_string(jsmn_parser *parser, const char *js, + size_t len, jsmntok_t *tokens, size_t num_tokens) { + jsmntok_t *token; + + int start = parser->pos; + + parser->pos++; + + /* Skip starting quote */ + for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { + char c = js[parser->pos]; + + /* Quote: end of string */ + if (c == '\"') { + if (tokens == NULL) { + return 0; + } + token = jsmn_alloc_token(parser, tokens, num_tokens); + if (token == NULL) { + parser->pos = start; + return JSMN_ERROR_NOMEM; + } + jsmn_fill_token(token, JSMN_STRING, start+1, parser->pos); +#ifdef JSMN_PARENT_LINKS + token->parent = parser->toksuper; +#endif + return 0; + } + + /* Backslash: Quoted symbol expected */ + if (c == '\\' && parser->pos + 1 < len) { + int i; + parser->pos++; + switch (js[parser->pos]) { + /* Allowed escaped symbols */ + case '\"': case '/' : case '\\' : case 'b' : + case 'f' : case 'r' : case 'n' : case 't' : + break; + /* Allows escaped symbol \uXXXX */ + case 'u': + parser->pos++; + for(i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0'; i++) { + /* If it isn't a hex character we have an error */ + if(!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */ + (js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */ + (js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */ + parser->pos = start; + return JSMN_ERROR_INVAL; + } + parser->pos++; + } + parser->pos--; + break; + /* Unexpected symbol */ + default: + parser->pos = start; + return JSMN_ERROR_INVAL; + } + } + } + parser->pos = start; + return JSMN_ERROR_PART; +} + +/** + * Parse JSON string and fill tokens. + */ +int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, + jsmntok_t *tokens, unsigned int num_tokens) { + int r; + int i; + jsmntok_t *token; + int count = parser->toknext; + + for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { + char c; + jsmntype_t type; + + c = js[parser->pos]; + switch (c) { + case '{': case '[': + count++; + if (tokens == NULL) { + break; + } + token = jsmn_alloc_token(parser, tokens, num_tokens); + if (token == NULL) + return JSMN_ERROR_NOMEM; + if (parser->toksuper != -1) { + tokens[parser->toksuper].size++; +#ifdef JSMN_PARENT_LINKS + token->parent = parser->toksuper; +#endif + } + token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY); + token->start = parser->pos; + parser->toksuper = parser->toknext - 1; + break; + case '}': case ']': + if (tokens == NULL) + break; + type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY); +#ifdef JSMN_PARENT_LINKS + if (parser->toknext < 1) { + return JSMN_ERROR_INVAL; + } + token = &tokens[parser->toknext - 1]; + for (;;) { + if (token->start != -1 && token->end == -1) { + if (token->type != type) { + return JSMN_ERROR_INVAL; + } + token->end = parser->pos + 1; + parser->toksuper = token->parent; + break; + } + if (token->parent == -1) { + if(token->type != type || parser->toksuper == -1) { + return JSMN_ERROR_INVAL; + } + break; + } + token = &tokens[token->parent]; + } +#else + for (i = parser->toknext - 1; i >= 0; i--) { + token = &tokens[i]; + if (token->start != -1 && token->end == -1) { + if (token->type != type) { + return JSMN_ERROR_INVAL; + } + parser->toksuper = -1; + token->end = parser->pos + 1; + break; + } + } + /* Error if unmatched closing bracket */ + if (i == -1) return JSMN_ERROR_INVAL; + for (; i >= 0; i--) { + token = &tokens[i]; + if (token->start != -1 && token->end == -1) { + parser->toksuper = i; + break; + } + } +#endif + break; + case '\"': + r = jsmn_parse_string(parser, js, len, tokens, num_tokens); + if (r < 0) return r; + count++; + if (parser->toksuper != -1 && tokens != NULL) + tokens[parser->toksuper].size++; + break; + case '\t' : case '\r' : case '\n' : case ' ': + break; + case ':': + parser->toksuper = parser->toknext - 1; + break; + case ',': + if (tokens != NULL && parser->toksuper != -1 && + tokens[parser->toksuper].type != JSMN_ARRAY && + tokens[parser->toksuper].type != JSMN_OBJECT) { +#ifdef JSMN_PARENT_LINKS + parser->toksuper = tokens[parser->toksuper].parent; +#else + for (i = parser->toknext - 1; i >= 0; i--) { + if (tokens[i].type == JSMN_ARRAY || tokens[i].type == JSMN_OBJECT) { + if (tokens[i].start != -1 && tokens[i].end == -1) { + parser->toksuper = i; + break; + } + } + } +#endif + } + break; +#ifdef JSMN_STRICT + /* In strict mode primitives are: numbers and booleans */ + case '-': case '0': case '1' : case '2': case '3' : case '4': + case '5': case '6': case '7' : case '8': case '9': + case 't': case 'f': case 'n' : + /* And they must not be keys of the object */ + if (tokens != NULL && parser->toksuper != -1) { + jsmntok_t *t = &tokens[parser->toksuper]; + if (t->type == JSMN_OBJECT || + (t->type == JSMN_STRING && t->size != 0)) { + return JSMN_ERROR_INVAL; + } + } +#else + /* In non-strict mode every unquoted value is a primitive */ + default: +#endif + r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens); + if (r < 0) return r; + count++; + if (parser->toksuper != -1 && tokens != NULL) + tokens[parser->toksuper].size++; + break; + +#ifdef JSMN_STRICT + /* Unexpected char in strict mode */ + default: + return JSMN_ERROR_INVAL; +#endif + } + } + + if (tokens != NULL) { + for (i = parser->toknext - 1; i >= 0; i--) { + /* Unmatched opened object or array */ + if (tokens[i].start != -1 && tokens[i].end == -1) { + return JSMN_ERROR_PART; + } + } + } + + return count; +} + +/** + * Creates a new parser based over a given buffer with an array of tokens + * available. + */ +void jsmn_init(jsmn_parser *parser) { + parser->pos = 0; + parser->toknext = 0; + parser->toksuper = -1; +} + diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/external_libs/jsmn/jsmn.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/external_libs/jsmn/jsmn.h new file mode 100644 index 00000000..e0ffb1bc --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/external_libs/jsmn/jsmn.h @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2010 Serge A. Zaitsev + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ + +/** + * @file jsmn.h + * @brief Definition of the JSMN (Jasmine) JSON parser. + * + * For more information on JSMN: + * @see http://zserge.com/jsmn.html + */ + +#ifndef __JSMN_H_ +#define __JSMN_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * JSON type identifier. Basic types are: + * o Object + * o Array + * o String + * o Other primitive: number, boolean (true/false) or null + */ +typedef enum { + JSMN_UNDEFINED = 0, + JSMN_OBJECT = 1, + JSMN_ARRAY = 2, + JSMN_STRING = 3, + JSMN_PRIMITIVE = 4 +} jsmntype_t; + +enum jsmnerr { + /* Not enough tokens were provided */ + JSMN_ERROR_NOMEM = -1, + /* Invalid character inside JSON string */ + JSMN_ERROR_INVAL = -2, + /* The string is not a full JSON packet, more bytes expected */ + JSMN_ERROR_PART = -3 +}; + +/** + * JSON token description. + * type type (object, array, string etc.) + * start start position in JSON data string + * end end position in JSON data string + */ +typedef struct { + jsmntype_t type; + int start; + int end; + int size; +#ifdef JSMN_PARENT_LINKS + int parent; +#endif +} jsmntok_t; + +/** + * JSON parser. Contains an array of token blocks available. Also stores + * the string being parsed now and current position in that string + */ +typedef struct { + unsigned int pos; /* offset in the JSON string */ + unsigned int toknext; /* next token to allocate */ + int toksuper; /* superior token node, e.g parent object or array */ +} jsmn_parser; + +/** + * Create JSON parser over an array of tokens + */ +void jsmn_init(jsmn_parser *parser); + +/** + * Run JSON parser. It parses a JSON data string into and array of tokens, each describing + * a single JSON object. + */ +int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, + jsmntok_t *tokens, unsigned int num_tokens); + +#ifdef __cplusplus +} +#endif + +#endif /* __JSMN_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/external_libs/mbedTLS/README.txt b/components/aws_iot/aws-iot-device-sdk-embedded-C/external_libs/mbedTLS/README.txt new file mode 100644 index 00000000..a3ff466b --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/external_libs/mbedTLS/README.txt @@ -0,0 +1,5 @@ +# Copy source code for mbedTLS into this directory +# +# You'll need to download mbedTLS from the official ARMmbed repository and +# place the files here. We recommend that you pick the latest version in +# order to have up-to-date security fixes. diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/filterGcov.sh b/components/aws_iot/aws-iot-device-sdk-embedded-C/filterGcov.sh new file mode 100755 index 00000000..fee4a032 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/filterGcov.sh @@ -0,0 +1,63 @@ +#!/bin/bash +INPUT_FILE=$1 +TEMP_FILE1=${INPUT_FILE}1.tmp +TEMP_FILE2=${INPUT_FILE}2.tmp +TEMP_FILE3=${INPUT_FILE}3.tmp +ERROR_FILE=$2 +OUTPUT_FILE=$3 +HTML_OUTPUT_FILE=$3.html +TEST_RESULTS=$4 + +flattenGcovOutput() { +while read line1 +do + read line2 + echo $line2 " " $line1 + read junk + read junk +done < ${INPUT_FILE} +} + +getRidOfCruft() { +sed '-e s/^Lines.*://g' \ + '-e s/^[0-9]\./ &/g' \ + '-e s/^[0-9][0-9]\./ &/g' \ + '-e s/of.*File/ /g' \ + "-e s/'//g" \ + '-e s/^.*\/usr\/.*$//g' \ + '-e s/^.*\.$//g' +} + +flattenPaths() { +sed \ + -e 's/\/[^/][^/]*\/[^/][^/]*\/\.\.\/\.\.\//\//g' \ + -e 's/\/[^/][^/]*\/[^/][^/]*\/\.\.\/\.\.\//\//g' \ + -e 's/\/[^/][^/]*\/[^/][^/]*\/\.\.\/\.\.\//\//g' \ + -e 's/\/[^/][^/]*\/\.\.\//\//g' +} + +getFileNameRootFromErrorFile() { +sed '-e s/gc..:cannot open .* file//g' ${ERROR_FILE} +} + +writeEachNoTestCoverageFile() { +while read line +do + echo " 0.00% " ${line} +done +} + +createHtmlOutput() { + echo "" + echo "" + sed "-e s/.*% /
CoverageFile
&<\/td>/" \ + "-e s/[a-zA-Z0-9_]*\.[ch][a-z]*/&<\/a><\/td><\/tr>/" + echo "
" + sed "-e s/.*/&
/g" < ${TEST_RESULTS} +} + +flattenGcovOutput | getRidOfCruft | flattenPaths > ${TEMP_FILE1} +getFileNameRootFromErrorFile | writeEachNoTestCoverageFile | flattenPaths > ${TEMP_FILE2} +cat ${TEMP_FILE1} ${TEMP_FILE2} | sort | uniq > ${OUTPUT_FILE} +createHtmlOutput < ${OUTPUT_FILE} > ${HTML_OUTPUT_FILE} +rm -f ${TEMP_FILE1} ${TEMP_FILE2} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_error.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_error.h new file mode 100644 index 00000000..03f297b2 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_error.h @@ -0,0 +1,160 @@ +/* + * 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_error.h + * @brief Definition of error types for the SDK. + */ + +#ifndef AWS_IOT_SDK_SRC_IOT_ERROR_H_ +#define AWS_IOT_SDK_SRC_IOT_ERROR_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/* Used to avoid warnings in case of unused parameters in function pointers */ +#define IOT_UNUSED(x) (void)(x) + +/*! \public + * @brief IoT Error enum + * + * Enumeration of return values from the IoT_* functions within the SDK. + * Values less than -1 are specific error codes + * Value of -1 is a generic failure response + * Value of 0 is a generic success response + * Values greater than 0 are specific non-error return codes + */ +typedef enum { + /** Returned when the Network physical layer is connected */ + NETWORK_PHYSICAL_LAYER_CONNECTED = 6, + /** Returned when the Network is manually disconnected */ + NETWORK_MANUALLY_DISCONNECTED = 5, + /** Returned when the Network is disconnected and the reconnect attempt is in progress */ + NETWORK_ATTEMPTING_RECONNECT = 4, + /** Return value of yield function to indicate auto-reconnect was successful */ + NETWORK_RECONNECTED = 3, + /** Returned when a read attempt is made on the TLS buffer and it is empty */ + MQTT_NOTHING_TO_READ = 2, + /** Returned when a connection request is successful and packet response is connection accepted */ + MQTT_CONNACK_CONNECTION_ACCEPTED = 1, + /** Success return value - no error occurred */ + SUCCESS = 0, + /** A generic error. Not enough information for a specific error code */ + FAILURE = -1, + /** A required parameter was passed as null */ + NULL_VALUE_ERROR = -2, + /** The TCP socket could not be established */ + TCP_CONNECTION_ERROR = -3, + /** The TLS handshake failed */ + SSL_CONNECTION_ERROR = -4, + /** Error associated with setting up the parameters of a Socket */ + TCP_SETUP_ERROR = -5, + /** A timeout occurred while waiting for the TLS handshake to complete. */ + NETWORK_SSL_CONNECT_TIMEOUT_ERROR = -6, + /** A Generic write error based on the platform used */ + NETWORK_SSL_WRITE_ERROR = -7, + /** SSL initialization error at the TLS layer */ + NETWORK_SSL_INIT_ERROR = -8, + /** An error occurred when loading the certificates. The certificates could not be located or are incorrectly formatted. */ + NETWORK_SSL_CERT_ERROR = -9, + /** SSL Write times out */ + NETWORK_SSL_WRITE_TIMEOUT_ERROR = -10, + /** SSL Read times out */ + NETWORK_SSL_READ_TIMEOUT_ERROR = -11, + /** A Generic error based on the platform used */ + NETWORK_SSL_READ_ERROR = -12, + /** Returned when the Network is disconnected and reconnect is either disabled or physical layer is disconnected */ + NETWORK_DISCONNECTED_ERROR = -13, + /** Returned when the Network is disconnected and the reconnect attempt has timed out */ + NETWORK_RECONNECT_TIMED_OUT_ERROR = -14, + /** Returned when the Network is already connected and a connection attempt is made */ + NETWORK_ALREADY_CONNECTED_ERROR = -15, + /** Network layer Error Codes */ + /** Network layer Random number generator seeding failed */ + NETWORK_MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED = -16, + /** A generic error code for Network layer errors */ + NETWORK_SSL_UNKNOWN_ERROR = -17, + /** Returned when the physical layer is disconnected */ + NETWORK_PHYSICAL_LAYER_DISCONNECTED = -18, + /** Returned when the root certificate is invalid */ + NETWORK_X509_ROOT_CRT_PARSE_ERROR = -19, + /** Returned when the device certificate is invalid */ + NETWORK_X509_DEVICE_CRT_PARSE_ERROR = -20, + /** Returned when the private key failed to parse */ + NETWORK_PK_PRIVATE_KEY_PARSE_ERROR = -21, + /** Returned when the network layer failed to open a socket */ + NETWORK_ERR_NET_SOCKET_FAILED = -22, + /** Returned when the server is unknown */ + NETWORK_ERR_NET_UNKNOWN_HOST = -23, + /** Returned when connect request failed */ + NETWORK_ERR_NET_CONNECT_FAILED = -24, + /** Returned when there is nothing to read in the TLS read buffer */ + NETWORK_SSL_NOTHING_TO_READ = -25, + /** A connection could not be established. */ + MQTT_CONNECTION_ERROR = -26, + /** A timeout occurred while waiting for the TLS handshake to complete */ + MQTT_CONNECT_TIMEOUT_ERROR = -27, + /** A timeout occurred while waiting for the TLS request complete */ + MQTT_REQUEST_TIMEOUT_ERROR = -28, + /** The current client state does not match the expected value */ + MQTT_UNEXPECTED_CLIENT_STATE_ERROR = -29, + /** The client state is not idle when request is being made */ + MQTT_CLIENT_NOT_IDLE_ERROR = -30, + /** The MQTT RX buffer received corrupt or unexpected message */ + MQTT_RX_MESSAGE_PACKET_TYPE_INVALID_ERROR = -31, + /** The MQTT RX buffer received a bigger message. The message will be dropped */ + MQTT_RX_BUFFER_TOO_SHORT_ERROR = -32, + /** The MQTT TX buffer is too short for the outgoing message. Request will fail */ + MQTT_TX_BUFFER_TOO_SHORT_ERROR = -33, + /** The client is subscribed to the maximum possible number of subscriptions */ + MQTT_MAX_SUBSCRIPTIONS_REACHED_ERROR = -34, + /** Failed to decode the remaining packet length on incoming packet */ + MQTT_DECODE_REMAINING_LENGTH_ERROR = -35, + /** Connect request failed with the server returning an unknown error */ + MQTT_CONNACK_UNKNOWN_ERROR = -36, + /** Connect request failed with the server returning an unacceptable protocol version error */ + MQTT_CONNACK_UNACCEPTABLE_PROTOCOL_VERSION_ERROR = -37, + /** Connect request failed with the server returning an identifier rejected error */ + MQTT_CONNACK_IDENTIFIER_REJECTED_ERROR = -38, + /** Connect request failed with the server returning an unavailable error */ + MQTT_CONNACK_SERVER_UNAVAILABLE_ERROR = -39, + /** Connect request failed with the server returning a bad userdata error */ + MQTT_CONNACK_BAD_USERDATA_ERROR = -40, + /** Connect request failed with the server failing to authenticate the request */ + MQTT_CONNACK_NOT_AUTHORIZED_ERROR = -41, + /** An error occurred while parsing the JSON string. Usually malformed JSON. */ + JSON_PARSE_ERROR = -42, + /** Shadow: The response Ack table is currently full waiting for previously published updates */ + SHADOW_WAIT_FOR_PUBLISH = -43, + /** Any time an snprintf writes more than size value, this error will be returned */ + SHADOW_JSON_BUFFER_TRUNCATED = -44, + /** Any time an snprintf encounters an encoding error or not enough space in the given buffer */ + SHADOW_JSON_ERROR = -45, + /** Mutex initialization failed */ + MUTEX_INIT_ERROR = -46, + /** Mutex lock request failed */ + MUTEX_LOCK_ERROR = -47, + /** Mutex unlock request failed */ + MUTEX_UNLOCK_ERROR = -48, + /** Mutex destroy failed */ + MUTEX_DESTROY_ERROR = -49, +} IoT_Error_t; + +#ifdef __cplusplus +} +#endif + +#endif /* AWS_IOT_SDK_SRC_IOT_ERROR_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_json_utils.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_json_utils.h new file mode 100644 index 00000000..ceb02b31 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_json_utils.h @@ -0,0 +1,197 @@ +/* + * 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_json_utils.h + * @brief Utilities for manipulating JSON + * + * json_utils provides JSON parsing utilities for use with the IoT SDK. + * Underlying JSON parsing relies on the Jasmine JSON parser. + * + */ + +#ifndef AWS_IOT_SDK_SRC_JSON_UTILS_H_ +#define AWS_IOT_SDK_SRC_JSON_UTILS_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +#include "aws_iot_error.h" +#include "jsmn.h" + +// utility functions +/** + * @brief JSON Equality Check + * + * Given a token pointing to a particular JSON node and an + * input string, check to see if the key is equal to the string. + * + * @param json json string + * @param tok json token - pointer to key to test for equality + * @param s input string for key to test equality + * + * @return 0 if equal, 1 otherwise + */ +int8_t jsoneq(const char *json, jsmntok_t *tok, const char *s); + +/** + * @brief Parse a signed 32-bit integer value from a JSON node. + * + * Given a JSON node parse the integer value from the value. + * + * @param jsonString json string + * @param tok json token - pointer to JSON node + * @param i address of int32_t to be updated + * + * @return SUCCESS - success + * @return JSON_PARSE_ERROR - error parsing value + */ +IoT_Error_t parseInteger32Value(int32_t *i, const char *jsonString, jsmntok_t *token); + +/** + * @brief Parse a signed 16-bit integer value from a JSON node. + * + * Given a JSON node parse the integer value from the value. + * + * @param jsonString json string + * @param tok json token - pointer to JSON node + * @param i address of int16_t to be updated + * + * @return SUCCESS - success + * @return JSON_PARSE_ERROR - error parsing value + */ +IoT_Error_t parseInteger16Value(int16_t *i, const char *jsonString, jsmntok_t *token); + +/** + * @brief Parse a signed 8-bit integer value from a JSON node. + * + * Given a JSON node parse the integer value from the value. + * + * @param jsonString json string + * @param tok json token - pointer to JSON node + * @param i address of int8_t to be updated + * + * @return SUCCESS - success + * @return JSON_PARSE_ERROR - error parsing value + */ +IoT_Error_t parseInteger8Value(int8_t *i, const char *jsonString, jsmntok_t *token); + +/** + * @brief Parse an unsigned 32-bit integer value from a JSON node. + * + * Given a JSON node parse the integer value from the value. + * + * @param jsonString json string + * @param tok json token - pointer to JSON node + * @param i address of uint32_t to be updated + * + * @return SUCCESS - success + * @return JSON_PARSE_ERROR - error parsing value + */ +IoT_Error_t parseUnsignedInteger32Value(uint32_t *i, const char *jsonString, jsmntok_t *token); + +/** + * @brief Parse an unsigned 16-bit integer value from a JSON node. + * + * Given a JSON node parse the integer value from the value. + * + * @param jsonString json string + * @param tok json token - pointer to JSON node + * @param i address of uint16_t to be updated + * + * @return SUCCESS - success + * @return JSON_PARSE_ERROR - error parsing value + */ +IoT_Error_t parseUnsignedInteger16Value(uint16_t *i, const char *jsonString, jsmntok_t *token); + +/** + * @brief Parse an unsigned 8-bit integer value from a JSON node. + * + * Given a JSON node parse the integer value from the value. + * + * @param jsonString json string + * @param tok json token - pointer to JSON node + * @param i address of uint8_t to be updated + * + * @return SUCCESS - success + * @return JSON_PARSE_ERROR - error parsing value + */ +IoT_Error_t parseUnsignedInteger8Value(uint8_t *i, const char *jsonString, jsmntok_t *token); + +/** + * @brief Parse a float value from a JSON node. + * + * Given a JSON node parse the float value from the value. + * + * @param jsonString json string + * @param tok json token - pointer to JSON node + * @param f address of float to be updated + * + * @return SUCCESS - success + * @return JSON_PARSE_ERROR - error parsing value + */ +IoT_Error_t parseFloatValue(float *f, const char *jsonString, jsmntok_t *token); + +/** + * @brief Parse a double value from a JSON node. + * + * Given a JSON node parse the double value from the value. + * + * @param jsonString json string + * @param tok json token - pointer to JSON node + * @param d address of double to be updated + * + * @return SUCCESS - success + * @return JSON_PARSE_ERROR - error parsing value + */ +IoT_Error_t parseDoubleValue(double *d, const char *jsonString, jsmntok_t *token); + +/** + * @brief Parse a boolean value from a JSON node. + * + * Given a JSON node parse the boolean value from the value. + * + * @param jsonString json string + * @param tok json token - pointer to JSON node + * @param b address of boolean to be updated + * + * @return SUCCESS - success + * @return JSON_PARSE_ERROR - error parsing value + */ +IoT_Error_t parseBooleanValue(bool *b, const char *jsonString, jsmntok_t *token); + +/** + * @brief Parse a string value from a JSON node. + * + * Given a JSON node parse the string value from the value. + * + * @param jsonString json string + * @param tok json token - pointer to JSON node + * @param s address of string to be updated + * + * @return SUCCESS - success + * @return JSON_PARSE_ERROR - error parsing value + */ +IoT_Error_t parseStringValue(char *buf, const char *jsonString, jsmntok_t *token); + +#ifdef __cplusplus +} +#endif + +#endif /* AWS_IOT_SDK_SRC_JSON_UTILS_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_log.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_log.h new file mode 100644 index 00000000..60c26086 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_log.h @@ -0,0 +1,131 @@ +/* + * 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_log.h + * @brief Logging macros for the SDK. + * This file defines common logging macros with log levels to be used within the SDK. + * These macros can also be used in the IoT application code as a common way to output + * logs. The log levels can be tuned by modifying the makefile. Removing (commenting + * out) the IOT_* statement in the makefile disables that log level. + * + * It is expected that the macros below will be modified or replaced when porting to + * specific hardware platforms as printf may not be the desired behavior. + */ + +#ifndef _IOT_LOG_H +#define _IOT_LOG_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +/** + * @brief Debug level logging macro. + * + * Macro to expose function, line number as well as desired log message. + */ +#ifdef ENABLE_IOT_DEBUG +#define IOT_DEBUG(...) \ + {\ + printf("DEBUG: %s L#%d ", __func__, __LINE__); \ + printf(__VA_ARGS__); \ + printf("\n"); \ + } +#else +#define IOT_DEBUG(...) +#endif + +/** + * @brief Debug level trace logging macro. + * + * Macro to print message function entry and exit + */ +#ifdef ENABLE_IOT_TRACE +#define FUNC_ENTRY \ + {\ + printf("FUNC_ENTRY: %s L#%d \n", __func__, __LINE__); \ + } +#define FUNC_EXIT \ + {\ + printf("FUNC_EXIT: %s L#%d \n", __func__, __LINE__); \ + } +#define FUNC_EXIT_RC(x) \ + {\ + printf("FUNC_EXIT: %s L#%d Return Code : %d \n", __func__, __LINE__, x); \ + return x; \ + } +#else +#define FUNC_ENTRY + +#define FUNC_EXIT +#define FUNC_EXIT_RC(x) { return x; } +#endif + +/** + * @brief Info level logging macro. + * + * Macro to expose desired log message. Info messages do not include automatic function names and line numbers. + */ +#ifdef ENABLE_IOT_INFO +#define IOT_INFO(...) \ + {\ + printf(__VA_ARGS__); \ + printf("\n"); \ + } +#else +#define IOT_INFO(...) +#endif + +/** + * @brief Warn level logging macro. + * + * Macro to expose function, line number as well as desired log message. + */ +#ifdef ENABLE_IOT_WARN +#define IOT_WARN(...) \ + { \ + printf("WARN: %s L#%d ", __func__, __LINE__); \ + printf(__VA_ARGS__); \ + printf("\n"); \ + } +#else +#define IOT_WARN(...) +#endif + +/** + * @brief Error level logging macro. + * + * Macro to expose function, line number as well as desired log message. + */ +#ifdef ENABLE_IOT_ERROR +#define IOT_ERROR(...) \ + { \ + printf("ERROR: %s L#%d ", __func__, __LINE__); \ + printf(__VA_ARGS__); \ + printf("\n"); \ + } +#else +#define IOT_ERROR(...) +#endif + +#ifdef __cplusplus +} +#endif + +#endif // _IOT_LOG_H diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_mqtt_client.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_mqtt_client.h new file mode 100644 index 00000000..bf061894 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_mqtt_client.h @@ -0,0 +1,418 @@ +/* + * 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. + */ + +// Based on Eclipse Paho. +/******************************************************************************* + * Copyright (c) 2014 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * Contributors: + * Ian Craggs - initial API and implementation and/or initial documentation + * Xiang Rong - 442039 Add makefile to Embedded C client + *******************************************************************************/ + +/** + * @file aws_iot_mqtt_client.h + * @brief Client definition for MQTT + */ + +#ifndef AWS_IOT_SDK_SRC_IOT_MQTT_CLIENT_H +#define AWS_IOT_SDK_SRC_IOT_MQTT_CLIENT_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Library Header files */ +#include "stdio.h" +#include "stdbool.h" +#include "stdint.h" +#include "stddef.h" + +/* AWS Specific header files */ +#include "aws_iot_error.h" +#include "aws_iot_config.h" + +/* Platform specific implementation header files */ +#include "network_interface.h" +#include "timer_interface.h" + +#ifdef _ENABLE_THREAD_SUPPORT_ +#include "threads_interface.h" +#endif + +#define MAX_PACKET_ID 65535 + +typedef struct _Client AWS_IoT_Client; + +/** + * @brief Quality of Service Type + * + * Defining a QoS type. + * @note QoS 2 is \b NOT supported by the AWS IoT Service at the time of this SDK release. + * + */ +typedef enum QoS { + QOS0 = 0, + QOS1 = 1 +} QoS; + +/** + * @brief Publish Message Parameters Type + * + * Defines a type for MQTT Publish messages. Used for both incoming and out going messages + * + */ +typedef struct { + QoS qos; ///< Message Quality of Service + uint8_t isRetained; ///< Retained messages are \b NOT supported by the AWS IoT Service at the time of this SDK release. + uint8_t isDup; ///< Is this message a duplicate QoS > 0 message? Handled automatically by the MQTT client. + uint16_t id; ///< Message sequence identifier. Handled automatically by the MQTT client. + void *payload; ///< Pointer to MQTT message payload (bytes). + size_t payloadLen; ///< Length of MQTT payload. +} IoT_Publish_Message_Params; + +/** + * @brief MQTT Version Type + * + * Defining an MQTT version type. Only 3.1.1 is supported at this time + * + */ +typedef enum { + MQTT_3_1_1 = 4 ///< MQTT 3.1.1 (protocol message byte = 4) +} MQTT_Ver_t; + +/** + * @brief Last Will and Testament Definition + * + * Defining a type for the MQTT "Last Will and Testament" (LWT) parameters. + * @note Retained messages are \b NOT supported by the AWS IoT Service at the time of this SDK release. + * + */ +typedef struct { + char struct_id[4]; ///< The eyecatcher for this structure. must be MQTW + char *pTopicName; ///< The LWT topic to which the LWT message will be published + uint16_t topicNameLen; ///< The length of the LWT topic, 16 bit unsinged integer + char *pMessage; ///< Message to be delivered as LWT + uint16_t msgLen; ///< The length of the Message, 16 bit unsinged integer + bool isRetained; ///< NOT supported. The retained flag for the LWT message (see MQTTAsync_message.retained) + QoS qos; ///< QoS of LWT message +} IoT_MQTT_Will_Options; +extern const IoT_MQTT_Will_Options iotMqttWillOptionsDefault; + +#define IoT_MQTT_Will_Options_Initializer { {'M', 'Q', 'T', 'W'}, NULL, 0, NULL, 0, false, QOS0 } + +/** + * @brief MQTT Connection Parameters + * + * Defining a type for MQTT connection parameters. Passed into client when establishing a connection. + * + */ +typedef struct { + char struct_id[4]; ///< The eyecatcher for this structure. must be MQTC + MQTT_Ver_t MQTTVersion; ///< Desired MQTT version used during connection + const char *pClientID; ///< Pointer to a string defining the MQTT client ID (this needs to be unique \b per \b device across your AWS account) + uint16_t clientIDLen; ///< Client Id Length. 16 bit unsigned integer + uint16_t keepAliveIntervalInSec; ///< MQTT keep alive interval in seconds. Defines inactivity time allowed before determining the connection has been lost. + bool isCleanSession; ///< MQTT clean session. True = this session is to be treated as clean. Previous server state is cleared and no stated is retained from this connection. + bool isWillMsgPresent; ///< Is there a LWT associated with this connection? + IoT_MQTT_Will_Options will; ///< MQTT LWT parameters. + char *pUsername; ///< Not used in the AWS IoT Service, will need to be cstring if used + uint16_t usernameLen; ///< Username Length. 16 bit unsigned integer + char *pPassword; ///< Not used in the AWS IoT Service, will need to be cstring if used + uint16_t passwordLen; ///< Password Length. 16 bit unsigned integer +} IoT_Client_Connect_Params; +extern const IoT_Client_Connect_Params iotClientConnectParamsDefault; + +#define IoT_Client_Connect_Params_initializer { {'M', 'Q', 'T', 'C'}, MQTT_3_1_1, NULL, 0, 60, true, false, \ + IoT_MQTT_Will_Options_Initializer, NULL, 0, NULL, 0 } + +/** + * @brief Disconnect Callback Handler Type + * + * Defining a TYPE for definition of disconnect callback function pointers. + * + */ +typedef void (*iot_disconnect_handler)(AWS_IoT_Client *, void *); + +/** + * @brief MQTT Initialization Parameters + * + * Defining a type for MQTT initialization parameters. + * Passed into client when to initialize the client + * + */ +typedef struct { + bool enableAutoReconnect; ///< Set to true to enable auto reconnect + char *pHostURL; ///< Pointer to a string defining the endpoint for the MQTT service + uint16_t port; ///< MQTT service listening port + const char *pRootCALocation; ///< Pointer to a string defining the Root CA file (full file, not path) + const char *pDeviceCertLocation; ///< Pointer to a string defining the device identity certificate file (full file, not path) + const char *pDevicePrivateKeyLocation; ///< Pointer to a string defining the device private key file (full file, not path) + uint32_t mqttPacketTimeout_ms; ///< Timeout for reading a complete MQTT packet. In milliseconds + uint32_t mqttCommandTimeout_ms; ///< Timeout for MQTT blocking calls. In milliseconds + uint32_t tlsHandshakeTimeout_ms; ///< TLS handshake timeout. In milliseconds + bool isSSLHostnameVerify; ///< Client should perform server certificate hostname validation + iot_disconnect_handler disconnectHandler; ///< Callback to be invoked upon connection loss + void *disconnectHandlerData; ///< Data to pass as argument when disconnect handler is called +#ifdef _ENABLE_THREAD_SUPPORT_ + bool isBlockOnThreadLockEnabled; ///< Timeout for Thread blocking calls. Set to 0 to block until lock is obtained. In milliseconds +#endif +} IoT_Client_Init_Params; +extern const IoT_Client_Init_Params iotClientInitParamsDefault; + +#ifdef _ENABLE_THREAD_SUPPORT_ +#define IoT_Client_Init_Params_initializer { true, NULL, 0, NULL, NULL, NULL, 2000, 20000, 5000, true, NULL, NULL, false } +#else +#define IoT_Client_Init_Params_initializer { true, NULL, 0, NULL, NULL, NULL, 2000, 20000, 5000, true, NULL, NULL } +#endif + +/** + * @brief MQTT Client State Type + * + * Defining a type for MQTT Client State + * + */ +typedef enum _ClientState { + CLIENT_STATE_INVALID = 0, + CLIENT_STATE_INITIALIZED = 1, + CLIENT_STATE_CONNECTING = 2, + CLIENT_STATE_CONNECTED_IDLE = 3, + CLIENT_STATE_CONNECTED_YIELD_IN_PROGRESS = 4, + CLIENT_STATE_CONNECTED_PUBLISH_IN_PROGRESS = 5, + CLIENT_STATE_CONNECTED_SUBSCRIBE_IN_PROGRESS = 6, + CLIENT_STATE_CONNECTED_UNSUBSCRIBE_IN_PROGRESS = 7, + CLIENT_STATE_CONNECTED_RESUBSCRIBE_IN_PROGRESS = 8, + CLIENT_STATE_CONNECTED_WAIT_FOR_CB_RETURN = 9, + CLIENT_STATE_DISCONNECTING = 10, + CLIENT_STATE_DISCONNECTED_ERROR = 11, + CLIENT_STATE_DISCONNECTED_MANUALLY = 12, + CLIENT_STATE_PENDING_RECONNECT = 13 +} ClientState; + +/** + * @brief Application Callback Handler Type + * + * Defining a TYPE for definition of application callback function pointers. + * Used to send incoming data to the application + * + */ +typedef void (*pApplicationHandler_t)(AWS_IoT_Client *pClient, char *pTopicName, uint16_t topicNameLen, + IoT_Publish_Message_Params *pParams, void *pClientData); + +/** + * @brief MQTT Message Handler + * + * Defining a type for MQTT Message Handlers. + * Used to pass incoming data back to the application + * + */ +typedef struct _MessageHandlers { + const char *topicName; + uint16_t topicNameLen; + QoS qos; + pApplicationHandler_t pApplicationHandler; + void *pApplicationHandlerData; +} MessageHandlers; /* Message handlers are indexed by subscription topic */ + +/** + * @brief MQTT Client Status + * + * Defining a type for MQTT Client Status + * Contains information about the state of the MQTT Client + * + */ +typedef struct _ClientStatus { + ClientState clientState; + bool isPingOutstanding; + bool isAutoReconnectEnabled; +} ClientStatus; + +/** + * @brief MQTT Client Data + * + * Defining a type for MQTT Client Data + * Contains data used by the MQTT Client + * + */ +typedef struct _ClientData { + uint16_t nextPacketId; + + uint32_t packetTimeoutMs; + uint32_t commandTimeoutMs; + uint16_t keepAliveInterval; + uint32_t currentReconnectWaitInterval; + uint32_t counterNetworkDisconnected; + + /* The below values are initialized with the + * lengths of the TX/RX buffers and never modified + * afterwards */ + size_t writeBufSize; + size_t readBufSize; + + unsigned char writeBuf[AWS_IOT_MQTT_TX_BUF_LEN]; + unsigned char readBuf[AWS_IOT_MQTT_RX_BUF_LEN]; + +#ifdef _ENABLE_THREAD_SUPPORT_ + bool isBlockOnThreadLockEnabled; + IoT_Mutex_t state_change_mutex; + IoT_Mutex_t tls_read_mutex; + IoT_Mutex_t tls_write_mutex; +#endif + + IoT_Client_Connect_Params options; + + MessageHandlers messageHandlers[AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS]; + iot_disconnect_handler disconnectHandler; + + void *disconnectHandlerData; +} ClientData; + +/** + * @brief MQTT Client + * + * Defining a type for MQTT Client + * + */ +struct _Client { + Timer pingTimer; + Timer reconnectDelayTimer; + + ClientStatus clientStatus; + ClientData clientData; + Network networkStack; +}; + +/** + * @brief What is the next available packet Id + * + * Called to retrieve the next packet id to be used for outgoing packets. + * Automatically increments the last sent packet id variable + * + * @param pClient Reference to the IoT Client + * + * @return next packet id as a 16 bit unsigned integer + */ +uint16_t aws_iot_mqtt_get_next_packet_id(AWS_IoT_Client *pClient); + +/** + * @brief Set the connection parameters for the IoT Client + * + * Called to set the connection parameters for the IoT Client. + * Used to update the connection parameters provided before the last connect. + * Won't take effect until the next time connect is called + * + * @param pClient Reference to the IoT Client + * @param pNewConnectParams Reference to the new Connection Parameters structure + * + * @return IoT_Error_t Type defining successful/failed API call + */ +IoT_Error_t aws_iot_mqtt_set_connect_params(AWS_IoT_Client *pClient, const IoT_Client_Connect_Params *pNewConnectParams); + +/** + * @brief Is the MQTT client currently connected? + * + * Called to determine if the MQTT client is currently connected. Used to support logic + * in the device application around reconnecting and managing offline state. + * + * @param pClient Reference to the IoT Client + * + * @return true = connected, false = not currently connected + */ +bool aws_iot_mqtt_is_client_connected(AWS_IoT_Client *pClient); + +/** + * @brief Get the current state of the client + * + * Called to get the current state of the client + * + * @param pClient Reference to the IoT Client + * + * @return ClientState value equal to the current state of the client + */ +ClientState aws_iot_mqtt_get_client_state(AWS_IoT_Client *pClient); + +/** + * @brief Is the MQTT client set to reconnect automatically? + * + * Called to determine if the MQTT client is set to reconnect automatically. + * Used to support logic in the device application around reconnecting + * + * @param pClient Reference to the IoT Client + * + * @return true = enabled, false = disabled + */ +bool aws_iot_is_autoreconnect_enabled(AWS_IoT_Client *pClient); + +/** + * @brief Set the IoT Client disconnect handler + * + * Called to set the IoT Client disconnect handler + * The disconnect handler is called whenever the client disconnects with error + * + * @param pClient Reference to the IoT Client + * @param pConnectHandler Reference to the new Disconnect Handler + * @param pDisconnectHandlerData Reference to the data to be passed as argument when disconnect handler is called + * + * @return IoT_Error_t Type defining successful/failed API call + */ +IoT_Error_t aws_iot_mqtt_set_disconnect_handler(AWS_IoT_Client *pClient, iot_disconnect_handler pDisconnectHandler, + void *pDisconnectHandlerData); + +/** + * @brief Enable or Disable AutoReconnect on Network Disconnect + * + * Called to enable or disabled the auto reconnect features provided with the SDK + * + * @param pClient Reference to the IoT Client + * @param newStatus set to true for enabling and false for disabling + * + * @return IoT_Error_t Type defining successful/failed API call + */ +IoT_Error_t aws_iot_mqtt_autoreconnect_set_status(AWS_IoT_Client *pClient, bool newStatus); + +/** + * @brief Get count of Network Disconnects + * + * Called to get the number of times a network disconnect occurred due to errors + * + * @param pClient Reference to the IoT Client + * + * @return uint32_t the disconnect count + */ +uint32_t aws_iot_mqtt_get_network_disconnected_count(AWS_IoT_Client *pClient); + +/** + * @brief Reset Network Disconnect conter + * + * Called to reset the Network Disconnect counter to zero + * + * @param pClient Reference to the IoT Client + */ +void aws_iot_mqtt_reset_network_disconnected_count(AWS_IoT_Client *pClient); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_mqtt_client_common_internal.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_mqtt_client_common_internal.h new file mode 100644 index 00000000..43d24870 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_mqtt_client_common_internal.h @@ -0,0 +1,132 @@ +/* +* Copyright 2015-2016 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. +*/ + +// Based on Eclipse Paho. +/******************************************************************************* + * Copyright (c) 2014 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * Contributors: + * Ian Craggs - initial API and implementation and/or initial documentation + * Xiang Rong - 442039 Add makefile to Embedded C client + *******************************************************************************/ + +/** + * @file aws_iot_mqtt_client_common_internal.h + * @brief Internal MQTT functions not exposed to application + */ + +#ifndef AWS_IOT_SDK_SRC_IOT_COMMON_INTERNAL_H +#define AWS_IOT_SDK_SRC_IOT_COMMON_INTERNAL_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +#include "aws_iot_mqtt_client_interface.h" + +/* Enum order should match the packet ids array defined in MQTTFormat.c */ +typedef enum msgTypes { + UNKNOWN = -1, + CONNECT = 1, + CONNACK = 2, + PUBLISH = 3, + PUBACK = 4, + PUBREC = 5, + PUBREL = 6, + PUBCOMP = 7, + SUBSCRIBE = 8, + SUBACK = 9, + UNSUBSCRIBE = 10, + UNSUBACK = 11, + PINGREQ = 12, + PINGRESP = 13, + DISCONNECT = 14 +} MessageTypes; + +/* Macros for parsing header fields from incoming MQTT frame. */ +#define MQTT_HEADER_FIELD_TYPE(_byte) ((_byte >> 4) & 0x0F) +#define MQTT_HEADER_FIELD_DUP(_byte) ((_byte & (1 << 3)) >> 3) +#define MQTT_HEADER_FIELD_QOS(_byte) ((_byte & (3 << 1)) >> 1) +#define MQTT_HEADER_FIELD_RETAIN(_byte) ((_byte & (1 << 0)) >> 0) + +/** + * Bitfields for the MQTT header byte. + */ +typedef union { + unsigned char byte; /**< the whole byte */ +} MQTTHeader; + +IoT_Error_t aws_iot_mqtt_internal_init_header(MQTTHeader *pHeader, MessageTypes message_type, + QoS qos, uint8_t dup, uint8_t retained); + +IoT_Error_t aws_iot_mqtt_internal_serialize_ack(unsigned char *pTxBuf, size_t txBufLen, + MessageTypes msgType, uint8_t dup, uint16_t packetId, + uint32_t *pSerializedLen); +IoT_Error_t aws_iot_mqtt_internal_deserialize_ack(unsigned char *, unsigned char *, + uint16_t *, unsigned char *, size_t); + +uint32_t aws_iot_mqtt_internal_get_final_packet_length_from_remaining_length(uint32_t rem_len); + +size_t aws_iot_mqtt_internal_write_len_to_buffer(unsigned char *buf, uint32_t length); +IoT_Error_t aws_iot_mqtt_internal_decode_remaining_length_from_buffer(unsigned char *buf, uint32_t *decodedLen, + uint32_t *readBytesLen); + +uint16_t aws_iot_mqtt_internal_read_uint16_t(unsigned char **pptr); +void aws_iot_mqtt_internal_write_uint_16(unsigned char **pptr, uint16_t anInt); + +unsigned char aws_iot_mqtt_internal_read_char(unsigned char **pptr); +void aws_iot_mqtt_internal_write_char(unsigned char **pptr, unsigned char c); +void aws_iot_mqtt_internal_write_utf8_string(unsigned char **pptr, const char *string, uint16_t stringLen); + +IoT_Error_t aws_iot_mqtt_internal_send_packet(AWS_IoT_Client *pClient, size_t length, Timer *pTimer); +IoT_Error_t aws_iot_mqtt_internal_cycle_read(AWS_IoT_Client *pClient, Timer *pTimer, uint8_t *pPacketType); +IoT_Error_t aws_iot_mqtt_internal_wait_for_read(AWS_IoT_Client *pClient, uint8_t packetType, Timer *pTimer); +IoT_Error_t aws_iot_mqtt_internal_serialize_zero(unsigned char *pTxBuf, size_t txBufLen, + MessageTypes packetType, size_t *pSerializedLength); +IoT_Error_t aws_iot_mqtt_internal_deserialize_publish(uint8_t *dup, QoS *qos, + uint8_t *retained, uint16_t *pPacketId, + char **pTopicName, uint16_t *topicNameLen, + unsigned char **payload, size_t *payloadLen, + unsigned char *pRxBuf, size_t rxBufLen); + +IoT_Error_t aws_iot_mqtt_set_client_state(AWS_IoT_Client *pClient, ClientState expectedCurrentState, + ClientState newState); + +#ifdef _ENABLE_THREAD_SUPPORT_ + +IoT_Error_t aws_iot_mqtt_client_lock_mutex(AWS_IoT_Client *pClient, IoT_Mutex_t *pMutex); + +IoT_Error_t aws_iot_mqtt_client_unlock_mutex(AWS_IoT_Client *pClient, IoT_Mutex_t *pMutex); + +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* AWS_IOT_SDK_SRC_IOT_COMMON_INTERNAL_H */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_mqtt_client_interface.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_mqtt_client_interface.h new file mode 100644 index 00000000..fef12ee2 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_mqtt_client_interface.h @@ -0,0 +1,199 @@ +/* +* Copyright 2015-2016 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. +*/ + +// Based on Eclipse Paho. +/******************************************************************************* + * Copyright (c) 2014 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * Contributors: + * Ian Craggs - initial API and implementation and/or initial documentation + * Xiang Rong - 442039 Add makefile to Embedded C client + *******************************************************************************/ + +/** + * @file aws_iot_mqtt_interface.h + * @brief Interface definition for MQTT client. + */ + +#ifndef AWS_IOT_SDK_SRC_IOT_MQTT_INTERFACE_H +#define AWS_IOT_SDK_SRC_IOT_MQTT_INTERFACE_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Library Header files */ +#include "stdio.h" +#include "stdbool.h" +#include "stdint.h" +#include "stddef.h" + +/* AWS Specific header files */ +#include "aws_iot_error.h" +#include "aws_iot_config.h" +#include "aws_iot_mqtt_client.h" + +/* Platform specific implementation header files */ +#include "network_interface.h" +#include "timer_interface.h" + +/** + * @brief MQTT Client Initialization Function + * + * Called to initialize the MQTT Client + * + * @param pClient Reference to the IoT Client + * @param pInitParams Pointer to MQTT connection parameters + * + * @return IoT_Error_t Type defining successful/failed API call + */ +IoT_Error_t aws_iot_mqtt_init(AWS_IoT_Client *pClient, const IoT_Client_Init_Params *pInitParams); + +/** + * @brief MQTT Connection Function + * + * Called to establish an MQTT connection with the AWS IoT Service + * + * @param pClient Reference to the IoT Client + * @param pConnectParams Pointer to MQTT connection parameters + * + * @return An IoT Error Type defining successful/failed connection + */ +IoT_Error_t aws_iot_mqtt_connect(AWS_IoT_Client *pClient, const IoT_Client_Connect_Params *pConnectParams); + +/** + * @brief Publish an MQTT message on a topic + * + * Called to publish an MQTT message on a topic. + * @note Call is blocking. In the case of a QoS 0 message the function returns + * after the message was successfully passed to the TLS layer. In the case of QoS 1 + * the function returns after the receipt of the PUBACK control packet. + * + * @param pClient Reference to the IoT Client + * @param pTopicName Topic Name to publish to + * @param topicNameLen Length of the topic name + * @param pParams Pointer to Publish Message parameters + * + * @return An IoT Error Type defining successful/failed publish + */ +IoT_Error_t aws_iot_mqtt_publish(AWS_IoT_Client *pClient, const char *pTopicName, uint16_t topicNameLen, + IoT_Publish_Message_Params *pParams); + +/** + * @brief Subscribe to an MQTT topic. + * + * Called to send a subscribe message to the broker requesting a subscription + * to an MQTT topic. + * @note Call is blocking. The call returns after the receipt of the SUBACK control packet. + * + * @param pClient Reference to the IoT Client + * @param pTopicName Topic Name to publish to + * @param topicNameLen Length of the topic name + * @param pApplicationHandler_t Reference to the handler function for this subscription + * @param pApplicationHandlerData Data to be passed as argument to the application handler callback + * + * @return An IoT Error Type defining successful/failed subscription + */ +IoT_Error_t aws_iot_mqtt_subscribe(AWS_IoT_Client *pClient, const char *pTopicName, uint16_t topicNameLen, + QoS qos, pApplicationHandler_t pApplicationHandler, void *pApplicationHandlerData); + +/** + * @brief Subscribe to an MQTT topic. + * + * Called to resubscribe to the topics that the client has active subscriptions on. + * Internally called when autoreconnect is enabled + * + * @note Call is blocking. The call returns after the receipt of the SUBACK control packet. + * + * @param pClient Reference to the IoT Client + * + * @return An IoT Error Type defining successful/failed subscription + */ +IoT_Error_t aws_iot_mqtt_resubscribe(AWS_IoT_Client *pClient); + +/** + * @brief Unsubscribe to an MQTT topic. + * + * Called to send an unsubscribe message to the broker requesting removal of a subscription + * to an MQTT topic. + * @note Call is blocking. The call returns after the receipt of the UNSUBACK control packet. + * + * @param pClient Reference to the IoT Client + * @param pTopicName Topic Name to publish to + * @param topicNameLen Length of the topic name + * + * @return An IoT Error Type defining successful/failed unsubscribe call + */ +IoT_Error_t aws_iot_mqtt_unsubscribe(AWS_IoT_Client *pClient, const char *pTopicFilter, uint16_t topicFilterLen); + +/** + * @brief Disconnect an MQTT Connection + * + * Called to send a disconnect message to the broker. + * + * @param pClient Reference to the IoT Client + * + * @return An IoT Error Type defining successful/failed send of the disconnect control packet. + */ +IoT_Error_t aws_iot_mqtt_disconnect(AWS_IoT_Client *pClient); + +/** + * @brief Yield to the MQTT client + * + * Called to yield the current thread to the underlying MQTT client. This time is used by + * the MQTT client to manage PING requests to monitor the health of the TCP connection as + * well as periodically check the socket receive buffer for subscribe messages. Yield() + * must be called at a rate faster than the keepalive interval. It must also be called + * at a rate faster than the incoming message rate as this is the only way the client receives + * processing time to manage incoming messages. + * + * @param pClient Reference to the IoT Client + * @param timeout_ms Maximum number of milliseconds to pass thread execution to the client. + * + * @return An IoT Error Type defining successful/failed client processing. + * If this call results in an error it is likely the MQTT connection has dropped. + * iot_is_mqtt_connected can be called to confirm. + */ +IoT_Error_t aws_iot_mqtt_yield(AWS_IoT_Client *pClient, uint32_t timeout_ms); + +/** + * @brief MQTT Manual Re-Connection Function + * + * Called to establish an MQTT connection with the AWS IoT Service + * using parameters from the last time a connection was attempted + * Use after disconnect to start the reconnect process manually + * Makes only one reconnect attempt Sets the client state to + * pending reconnect in case of failure + * + * @param pClient Reference to the IoT Client + * + * @return An IoT Error Type defining successful/failed connection + */ +IoT_Error_t aws_iot_mqtt_attempt_reconnect(AWS_IoT_Client *pClient); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_actions.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_actions.h new file mode 100644 index 00000000..a5f87559 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_actions.h @@ -0,0 +1,33 @@ +/* + * 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. + */ + +#ifndef SRC_SHADOW_AWS_IOT_SHADOW_ACTIONS_H_ +#define SRC_SHADOW_AWS_IOT_SHADOW_ACTIONS_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "aws_iot_shadow_interface.h" + +IoT_Error_t aws_iot_shadow_internal_action(const char *pThingName, ShadowActions_t action, + const char *pJsonDocumentToBeSent, fpActionCallback_t callback, + void *pCallbackContext, uint32_t timeout_seconds, bool isSticky); + +#ifdef __cplusplus +} +#endif + +#endif /* SRC_SHADOW_AWS_IOT_SHADOW_ACTIONS_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_interface.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_interface.h new file mode 100644 index 00000000..818b35f0 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_interface.h @@ -0,0 +1,296 @@ +/* + * 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. + */ +#ifndef AWS_IOT_SDK_SRC_IOT_SHADOW_H_ +#define AWS_IOT_SDK_SRC_IOT_SHADOW_H_ + +#ifdef __cplusplus +extern "C" { +#endif + + +/** + * @file aws_iot_shadow_interface.h + * @brief Interface for thing shadow + * + * These are the functions and structs to manage/interact the Thing Shadow(in the cloud). + * This SDK will let you interact with your own thing shadow or any other shadow using its Thing Name. + * There are totally 3 actions a device can perform on the shadow - Get, Update and Delete. + * + * Currently the device should use MQTT/S underneath. In the future this will also support other protocols. As it supports MQTT, the shadow needs to connect and disconnect. + * It will also work on the pub/sub model. On performing any action, the acknowledgment will be received in either accepted or rejected. For Example: + * If we want to perform a GET on the thing shadow the following messages will be sent and received: + * 1. A MQTT Publish on the topic - $aws/things/{thingName}/shadow/get + * 2. Subscribe to MQTT topics - $aws/things/{thingName}/shadow/get/accepted and $aws/things/{thingName}/shadow/get/rejected. + * If the request was successful we will receive the things json document in the accepted topic. + * + * + */ +#include "aws_iot_mqtt_client_interface.h" +#include "aws_iot_shadow_json_data.h" + +/*! + * @brief Shadow Initialization parameters + * + * As the Shadow SDK uses MQTT underneath, it could be connected and disconnected on events to save some battery. + * @note Always use the \c ShadowIniTParametersDefault to initialize this struct + * + * + * + */ +typedef struct { + char *pHost; ///< This will be unique to a customer and can be retrieved from the console + uint16_t port; ///< By default the port is 8883 + const char *pRootCA; ///< Location with the Filename of the Root CA + const char *pClientCRT; ///< Location of Device certs signed by AWS IoT service + const char *pClientKey; ///< Location of Device private key + bool enableAutoReconnect; ///< Set to true to enable auto reconnect + iot_disconnect_handler disconnectHandler; ///< Callback to be invoked upon connection loss. +} ShadowInitParameters_t; + +/*! + * @brief Shadow Connect parameters + * + * As the Shadow SDK uses MQTT underneath, it could be connected and disconnected on events to save some battery. + * @note Always use the \c ShadowConnectParametersDefault to initialize this struct + * + *d + * + */ +typedef struct { + const char *pMyThingName; ///< Every device has a Thing Shadow and this is the placeholder for name + const char *pMqttClientId; ///< Currently the Shadow uses MQTT to connect and it is important to ensure we have unique client id + uint16_t mqttClientIdLen; ///< Currently the Shadow uses MQTT to connect and it is important to ensure we have unique client id + pApplicationHandler_t deleteActionHandler; ///< Callback to be invoked when Thing shadow for this device is deleted +} ShadowConnectParameters_t; + +/*! + * @brief This is set to defaults from the configuration file + * The certs are set to NULL because they need the path to the file. shadow_sample.c file demonstrates on how to get the relative path + * + * \relates ShadowInitParameters_t + */ +extern const ShadowInitParameters_t ShadowInitParametersDefault; + +/*! + * @brief This is set to defaults from the configuration file + * The length of the client id is initialized as 0. This is due to C language limitations of using constant literals + * only for creating const variables. The client id will be assigned using the value from aws_iot_config.h but the + * length needs to be assigned in code. shadow_sample.c file demonstrates this. + * + * \relates ShadowConnectParameters_t + */ +extern const ShadowConnectParameters_t ShadowConnectParametersDefault; + + +/** + * @brief Initialize the Thing Shadow before use + * + * This function takes care of initializing the internal book-keeping data structures and initializing the IoT client. + * + * @param pClient A new MQTT Client to be used as the protocol layer. Will be initialized with pParams. + * @return An IoT Error Type defining successful/failed Initialization + */ +IoT_Error_t aws_iot_shadow_init(AWS_IoT_Client *pClient, const ShadowInitParameters_t *pParams); + +/** + * @brief Connect to the AWS IoT Thing Shadow service over MQTT + * + * This function does the TLSv1.2 handshake and establishes the MQTT connection + * + * @param pClient MQTT Client used as the protocol layer + * @param pParams Shadow Conenction parameters like TLS cert location + * @return An IoT Error Type defining successful/failed Connection + */ +IoT_Error_t aws_iot_shadow_connect(AWS_IoT_Client *pClient, const ShadowConnectParameters_t *pParams); + +/** + * @brief Yield function to let the background tasks of MQTT and Shadow + * + * This function could be use in a separate thread waiting for the incoming messages, ensuring the connection is kept alive with the AWS Service. + * It also ensures the expired requests of Shadow actions are cleared and Timeout callback is executed. + * @note All callbacks ever used in the SDK will be executed in the context of this function. + * + * @param pClient MQTT Client used as the protocol layer + * @param timeout in milliseconds, This is the maximum time the yield function will wait for a message and/or read the messages from the TLS buffer + * @return An IoT Error Type defining successful/failed Yield + */ +IoT_Error_t aws_iot_shadow_yield(AWS_IoT_Client *pClient, uint32_t timeout); + +/** + * @brief Disconnect from the AWS IoT Thing Shadow service over MQTT + * + * This will close the underlying TCP connection, MQTT connection will also be closed + * + * @param pClient MQTT Client used as the protocol layer + * @return An IoT Error Type defining successful/failed disconnect status + */ +IoT_Error_t aws_iot_shadow_disconnect(AWS_IoT_Client *pClient); + +/** + * @brief Thing Shadow Acknowledgment enum + * + * This enum type is use in the callback for the action response + * + */ +typedef enum { + SHADOW_ACK_TIMEOUT, SHADOW_ACK_REJECTED, SHADOW_ACK_ACCEPTED +} Shadow_Ack_Status_t; + +/** + * @brief Thing Shadow Action type enum + * + * This enum type is use in the callback for the action response + * + */ +typedef enum { + SHADOW_GET, SHADOW_UPDATE, SHADOW_DELETE +} ShadowActions_t; + + +/** + * @brief Function Pointer typedef used as the callback for every action + * + * This function will be called from the context of \c aws_iot_shadow_yield() context + * + * @param pThingName Thing Name of the response received + * @param action The response of the action + * @param status Informs if the action was Accepted/Rejected or Timed out + * @param pReceivedJsonDocument Received JSON document + * @param pContextData the void* data passed in during the action call(update, get or delete) + * + */ +typedef void (*fpActionCallback_t)(const char *pThingName, ShadowActions_t action, Shadow_Ack_Status_t status, + const char *pReceivedJsonDocument, void *pContextData); + +/** + * @brief This function is the one used to perform an Update action to a Thing Name's Shadow. + * + * update is one of the most frequently used functionality by a device. In most cases the device may be just reporting few params to update the thing shadow in the cloud + * Update Action if no callback or if the JSON document does not have a client token then will just publish the update and not track it. + * + * @note The update has to subscribe to two topics update/accepted and update/rejected. This function waits 2 seconds to ensure the subscriptions are registered before publishing the update message. + * The following steps are performed on using this function: + * 1. Subscribe to Shadow topics - $aws/things/{thingName}/shadow/update/accepted and $aws/things/{thingName}/shadow/update/rejected + * 2. wait for 2 seconds for the subscription to take effect + * 3. Publish on the update topic - $aws/things/{thingName}/shadow/update + * 4. In the \c aws_iot_shadow_yield() function the response will be handled. In case of timeout or if the response is received, the subscription to shadow response topics are un-subscribed from. + * On the contrary if the persistent subscription is set to true then the un-subscribe will not be done. The topics will always be listened to. + * + * @param pClient MQTT Client used as the protocol layer + * @param pThingName Thing Name of the shadow that needs to be Updated + * @param pJsonString The update action expects a JSON document to send. The JSON String should be a null terminated string. This JSON document should adhere to the AWS IoT Thing Shadow specification. To help in the process of creating this document- SDK provides apis in \c aws_iot_shadow_json_data.h + * @param callback This is the callback that will be used to inform the caller of the response from the AWS IoT Shadow service.Callback could be set to NULL if response is not important + * @param pContextData This is an extra parameter that could be passed along with the callback. It should be set to NULL if not used + * @param timeout_seconds It is the time the SDK will wait for the response on either accepted/rejected before declaring timeout on the action + * @param isPersistentSubscribe As mentioned above, every time if a device updates the same shadow then this should be set to true to avoid repeated subscription and unsubscription. If the Thing Name is one off update then this should be set to false + * @return An IoT Error Type defining successful/failed update action + */ +IoT_Error_t aws_iot_shadow_update(AWS_IoT_Client *pClient, const char *pThingName, char *pJsonString, + fpActionCallback_t callback, void *pContextData, uint8_t timeout_seconds, + bool isPersistentSubscribe); + +/** + * @brief This function is the one used to perform an Get action to a Thing Name's Shadow. + * + * One use of this function is usually to get the config of a device at boot up. + * It is similar to the Update function internally except it does not take a JSON document as the input. The entire JSON document will be sent over the accepted topic + * + * @param pClient MQTT Client used as the protocol layer + * @param pThingName Thing Name of the JSON document that is needed + * @param callback This is the callback that will be used to inform the caller of the response from the AWS IoT Shadow service.Callback could be set to NULL if response is not important + * @param pContextData This is an extra parameter that could be passed along with the callback. It should be set to NULL if not used + * @param timeout_seconds It is the time the SDK will wait for the response on either accepted/rejected before declaring timeout on the action + * @param isPersistentSubscribe As mentioned above, every time if a device gets the same Sahdow (JSON document) then this should be set to true to avoid repeated subscription and un-subscription. If the Thing Name is one off get then this should be set to false + * @return An IoT Error Type defining successful/failed get action + */ +IoT_Error_t aws_iot_shadow_get(AWS_IoT_Client *pClient, const char *pThingName, fpActionCallback_t callback, + void *pContextData, uint8_t timeout_seconds, bool isPersistentSubscribe); + +/** + * @brief This function is the one used to perform an Delete action to a Thing Name's Shadow. + * + * This is not a very common use case for device. It is generally the responsibility of the accompanying app to do the delete. + * It is similar to the Update function internally except it does not take a JSON document as the input. The Thing Shadow referred by the ThingName will be deleted. + * + * @param pClient MQTT Client used as the protocol layer + * @param pThingName Thing Name of the Shadow that should be deleted + * @param callback This is the callback that will be used to inform the caller of the response from the AWS IoT Shadow service.Callback could be set to NULL if response is not important + * @param pContextData This is an extra parameter that could be passed along with the callback. It should be set to NULL if not used + * @param timeout_seconds It is the time the SDK will wait for the response on either accepted/rejected before declaring timeout on the action + * @param isPersistentSubscribe As mentioned above, every time if a device deletes the same Shadow (JSON document) then this should be set to true to avoid repeated subscription and un-subscription. If the Thing Name is one off delete then this should be set to false + * @return An IoT Error Type defining successful/failed delete action + */ +IoT_Error_t aws_iot_shadow_delete(AWS_IoT_Client *pClient, const char *pThingName, fpActionCallback_t callback, + void *pContextData, uint8_t timeout_seconds, bool isPersistentSubscriptions); + +/** + * @brief This function is used to listen on the delta topic of #AWS_IOT_MY_THING_NAME mentioned in the aws_iot_config.h file. + * + * Any time a delta is published the Json document will be delivered to the pStruct->cb. If you don't want the parsing done by the SDK then use the jsonStruct_t key set to "state". A good example of this is displayed in the sample_apps/shadow_console_echo.c + * + * @param pClient MQTT Client used as the protocol layer + * @param pStruct The struct used to parse JSON value + * @return An IoT Error Type defining successful/failed delta registering + */ +IoT_Error_t aws_iot_shadow_register_delta(AWS_IoT_Client *pClient, jsonStruct_t *pStruct); + +/** + * @brief Reset the last received version number to zero. + * This will be useful if the Thing Shadow is deleted and would like to to reset the local version + * @return no return values + * + */ +void aws_iot_shadow_reset_last_received_version(void); + +/** + * @brief Version of a document is received with every accepted/rejected and the SDK keeps track of the last received version of the JSON document of #AWS_IOT_MY_THING_NAME shadow + * + * One exception to this version tracking is that, the SDK will ignore the version from update/accepted topic. Rest of the responses will be scanned to update the version number. + * Accepting version change for update/accepted may cause version conflicts for delta message if the update message is received before the delta. + * + * @return version number of the last received response + * + */ +uint32_t aws_iot_shadow_get_last_received_version(void); + +/** + * @brief Enable the ignoring of delta messages with old version number + * + * As we use MQTT underneath, there could be more than 1 of the same message if we use QoS 0. To avoid getting called for the same message, this functionality should be enabled. All the old message will be ignored + */ +void aws_iot_shadow_enable_discard_old_delta_msgs(void); + +/** + * @brief Disable the ignoring of delta messages with old version number + */ +void aws_iot_shadow_disable_discard_old_delta_msgs(void); + +/** + * @brief This function is used to enable or disable autoreconnect + * + * Any time a disconnect happens the underlying MQTT client attempts to reconnect if this is set to true + * + * @param pClient MQTT Client used as the protocol layer + * @param newStatus The new status to set the autoreconnect option to + * + * @return An IoT Error Type defining successful/failed operation + */ +IoT_Error_t aws_iot_shadow_set_autoreconnect_status(AWS_IoT_Client *pClient, bool newStatus); + +#ifdef __cplusplus +} +#endif + +#endif //AWS_IOT_SDK_SRC_IOT_SHADOW_H_ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_json.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_json.h new file mode 100644 index 00000000..a84713ec --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_json.h @@ -0,0 +1,53 @@ +/* + * 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. + */ +#ifndef AWS_IOT_SDK_SRC_IOT_SHADOW_JSON_H_ +#define AWS_IOT_SDK_SRC_IOT_SHADOW_JSON_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include + +#include "aws_iot_error.h" +#include "aws_iot_shadow_json_data.h" + +bool isJsonValidAndParse(const char *pJsonDocument, void *pJsonHandler, int32_t *pTokenCount); + +bool isJsonKeyMatchingAndUpdateValue(const char *pJsonDocument, void *pJsonHandler, int32_t tokenCount, + jsonStruct_t *pDataStruct, uint32_t *pDataLength, int32_t *pDataPosition); + +void aws_iot_shadow_internal_get_request_json(char *pJsonDocument); + +void aws_iot_shadow_internal_delete_request_json(char *pJsonDocument); + +void resetClientTokenSequenceNum(void); + + +bool isReceivedJsonValid(const char *pJsonDocument); + +void FillWithClientToken(char *pStringToUpdateClientToken); + +bool extractClientToken(const char *pJsonDocumentToBeSent, char *pExtractedClientToken); + +bool extractVersionNumber(const char *pJsonDocument, void *pJsonHandler, int32_t tokenCount, uint32_t *pVersionNumber); + +#ifdef __cplusplus +} +#endif + +#endif // AWS_IOT_SDK_SRC_IOT_SHADOW_JSON_H_ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_json_data.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_json_data.h new file mode 100644 index 00000000..deaf9a17 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_json_data.h @@ -0,0 +1,149 @@ +/* + * 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. + */ + +#ifndef SRC_SHADOW_AWS_IOT_SHADOW_JSON_DATA_H_ +#define SRC_SHADOW_AWS_IOT_SHADOW_JSON_DATA_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file aws_iot_shadow_json_data.h + * @brief This file is the interface for all the Shadow related JSON functions. + */ + +#include + +/** + * @brief This is a static JSON object that could be used in code + * + */ +typedef struct jsonStruct jsonStruct_t; + +/** + * @brief Every JSON name value can have a callback. The callback should follow this signature + */ +typedef void (*jsonStructCallback_t)(const char *pJsonValueBuffer, uint32_t valueLength, jsonStruct_t *pJsonStruct_t); + +/** + * @brief All the JSON object types enum + * + * JSON number types need to be split into proper integer / floating point data types and sizes on embedded platforms. + */ +typedef enum { + SHADOW_JSON_INT32, + SHADOW_JSON_INT16, + SHADOW_JSON_INT8, + SHADOW_JSON_UINT32, + SHADOW_JSON_UINT16, + SHADOW_JSON_UINT8, + SHADOW_JSON_FLOAT, + SHADOW_JSON_DOUBLE, + SHADOW_JSON_BOOL, + SHADOW_JSON_STRING, + SHADOW_JSON_OBJECT +} JsonPrimitiveType; + +/** + * @brief This is the struct form of a JSON Key value pair + */ +struct jsonStruct { + const char *pKey; ///< JSON key + void *pData; ///< pointer to the data (JSON value) + JsonPrimitiveType type; ///< type of JSON + jsonStructCallback_t cb; ///< callback to be executed on receiving the Key value pair +}; + +/** + * @brief Initialize the JSON document with Shadow expected name/value + * + * This Function will fill the JSON Buffer with a null terminated string. Internally it uses snprintf + * This function should always be used First, followed by iot_shadow_add_reported and/or iot_shadow_add_desired. + * Always finish the call sequence with iot_finalize_json_document + * + * @note Ensure the size of the Buffer is enough to hold the entire JSON Document. + * + * + * @param pJsonDocument The JSON Document filled in this char buffer + * @param maxSizeOfJsonDocument maximum size of the pJsonDocument that can be used to fill the JSON document + * @return An IoT Error Type defining if the buffer was null or the entire string was not filled up + */ +IoT_Error_t aws_iot_shadow_init_json_document(char *pJsonDocument, size_t maxSizeOfJsonDocument); + +/** + * @brief Add the reported section of the JSON document of jsonStruct_t + * + * This is a variadic function and please be careful with the usage. count is the number of jsonStruct_t types that you would like to add in the reported section + * This function will add "reported":{} + * + * @note Ensure the size of the Buffer is enough to hold the reported section + the init section. Always use the same JSON document buffer used in the iot_shadow_init_json_document function. This function will accommodate the size of previous null terminated string, so pass teh max size of the buffer + * + * + * @param pJsonDocument The JSON Document filled in this char buffer + * @param maxSizeOfJsonDocument maximum size of the pJsonDocument that can be used to fill the JSON document + * @param count total number of arguments(jsonStruct_t object) passed in the arguments + * @return An IoT Error Type defining if the buffer was null or the entire string was not filled up + */ +IoT_Error_t aws_iot_shadow_add_reported(char *pJsonDocument, size_t maxSizeOfJsonDocument, uint8_t count, ...); + +/** + * @brief Add the desired section of the JSON document of jsonStruct_t + * + * This is a variadic function and please be careful with the usage. count is the number of jsonStruct_t types that you would like to add in the reported section + * This function will add "desired":{} + * + * @note Ensure the size of the Buffer is enough to hold the reported section + the init section. Always use the same JSON document buffer used in the iot_shadow_init_json_document function. This function will accommodate the size of previous null terminated string, so pass the max size of the buffer + * + * + * @param pJsonDocument The JSON Document filled in this char buffer + * @param maxSizeOfJsonDocument maximum size of the pJsonDocument that can be used to fill the JSON document + * @param count total number of arguments(jsonStruct_t object) passed in the arguments + * @return An IoT Error Type defining if the buffer was null or the entire string was not filled up + */ +IoT_Error_t aws_iot_shadow_add_desired(char *pJsonDocument, size_t maxSizeOfJsonDocument, uint8_t count, ...); + +/** + * @brief Finalize the JSON document with Shadow expected client Token. + * + * This function will automatically increment the client token every time this function is called. + * + * @note Ensure the size of the Buffer is enough to hold the entire JSON Document. If the finalized section is not invoked then the JSON doucment will not be valid + * + * + * @param pJsonDocument The JSON Document filled in this char buffer + * @param maxSizeOfJsonDocument maximum size of the pJsonDocument that can be used to fill the JSON document + * @return An IoT Error Type defining if the buffer was null or the entire string was not filled up + */ +IoT_Error_t aws_iot_finalize_json_document(char *pJsonDocument, size_t maxSizeOfJsonDocument); + +/** + * @brief Fill the given buffer with client token for tracking the Repsonse. + * + * This function will add the AWS_IOT_MQTT_CLIENT_ID with a sequence number. Every time this function is used the sequence number gets incremented + * + * + * @param pBufferToBeUpdatedWithClientToken buffer to be updated with the client token string + * @param maxSizeOfJsonDocument maximum size of the pBufferToBeUpdatedWithClientToken that can be used + * @return An IoT Error Type defining if the buffer was null or the entire string was not filled up + */ + +IoT_Error_t aws_iot_fill_with_client_token(char *pBufferToBeUpdatedWithClientToken, size_t maxSizeOfJsonDocument); + +#ifdef __cplusplus +} +#endif + +#endif /* SRC_SHADOW_AWS_IOT_SHADOW_JSON_DATA_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_key.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_key.h new file mode 100644 index 00000000..075a726d --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_key.h @@ -0,0 +1,22 @@ +/* + * 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. + */ + +#ifndef SRC_SHADOW_AWS_IOT_SHADOW_KEY_H_ +#define SRC_SHADOW_AWS_IOT_SHADOW_KEY_H_ + +#define SHADOW_CLIENT_TOKEN_STRING "clientToken" +#define SHADOW_VERSION_STRING "version" + +#endif /* SRC_SHADOW_AWS_IOT_SHADOW_KEY_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_records.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_records.h new file mode 100644 index 00000000..fc2de032 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_records.h @@ -0,0 +1,55 @@ +/* + * 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. + */ + +#ifndef SRC_SHADOW_AWS_IOT_SHADOW_RECORDS_H_ +#define SRC_SHADOW_AWS_IOT_SHADOW_RECORDS_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#include "aws_iot_shadow_interface.h" +#include "aws_iot_config.h" + + +extern uint32_t shadowJsonVersionNum; +extern bool shadowDiscardOldDeltaFlag; + +extern char myThingName[MAX_SIZE_OF_THING_NAME]; +extern uint16_t myThingNameLen; +extern char mqttClientID[MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES]; +extern uint16_t mqttClientIDLen; + +void initializeRecords(AWS_IoT_Client *pClient); +bool isSubscriptionPresent(const char *pThingName, ShadowActions_t action); +IoT_Error_t subscribeToShadowActionAcks(const char *pThingName, ShadowActions_t action, bool isSticky); +void incrementSubscriptionCnt(const char *pThingName, ShadowActions_t action, bool isSticky); + +IoT_Error_t publishToShadowAction(const char *pThingName, ShadowActions_t action, const char *pJsonDocumentToBeSent); +void addToAckWaitList(uint8_t indexAckWaitList, const char *pThingName, ShadowActions_t action, + const char *pExtractedClientToken, fpActionCallback_t callback, void *pCallbackContext, + uint32_t timeout_seconds); +bool getNextFreeIndexOfAckWaitList(uint8_t *pIndex); +void HandleExpiredResponseCallbacks(void); +void initDeltaTokens(void); +IoT_Error_t registerJsonTokenOnDelta(jsonStruct_t *pStruct); + +#ifdef __cplusplus +} +#endif + +#endif /* SRC_SHADOW_AWS_IOT_SHADOW_RECORDS_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_version.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_version.h new file mode 100644 index 00000000..1b544d75 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/aws_iot_version.h @@ -0,0 +1,48 @@ +/* + * 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_version.h + * @brief Constants defining the release version of the SDK. + * + * This file contains constants defining the release version of the SDK. + * This file is modified by AWS upon release of the SDK and should not be + * modified by the consumer of the SDK. The provided samples show example + * usage of these constants. + * + * Versioning of the SDK follows the MAJOR.MINOR.PATCH Semantic Versioning guidelines. + * @see http://semver.org/ + */ +#ifndef SRC_UTILS_AWS_IOT_VERSION_H_ +#define SRC_UTILS_AWS_IOT_VERSION_H_ + +/** + * @brief MAJOR version, incremented when incompatible API changes are made. + */ +#define VERSION_MAJOR 2 +/** + * @brief MINOR version when functionality is added in a backwards-compatible manner. + */ +#define VERSION_MINOR 2 +/** + * @brief PATCH version when backwards-compatible bug fixes are made. + */ +#define VERSION_PATCH 1 +/** + * @brief TAG is an (optional) tag appended to the version if a more descriptive verion is needed. + */ +#define VERSION_TAG "" + +#endif /* SRC_UTILS_AWS_IOT_VERSION_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/include/network_interface.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/network_interface.h new file mode 100644 index 00000000..d3d73c6d --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/network_interface.h @@ -0,0 +1,167 @@ +/* + * 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 network_interface.h + * @brief Network interface definition for MQTT client. + * + * Defines an interface to the TLS layer to be used by the MQTT client. + * Starting point for porting the SDK to the networking layer of a new platform. + */ + +#ifndef __NETWORK_INTERFACE_H_ +#define __NETWORK_INTERFACE_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include "timer_interface.h" +#include "network_platform.h" + +/** + * @brief Network Type + * + * Defines a type for the network struct. See structure definition below. + */ +typedef struct Network Network; + +/** + * @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 { + const char *pRootCALocation; ///< Pointer to string containing the filename (including path) of the root CA file. + const char *pDeviceCertLocation; ///< Pointer to string containing the filename (including path) of the device certificate. + const char *pDevicePrivateKeyLocation; ///< Pointer to string containing the filename (including path) of the device private key file. + const char *pDestinationURL; ///< Pointer to string containing the endpoint of the MQTT service. + uint16_t DestinationPort; ///< Integer defining the connection port of the MQTT service. + uint32_t timeout_ms; ///< Unsigned integer defining the TLS handshake timeout value in milliseconds. + bool ServerVerificationFlag; ///< Boolean. True = perform server certificate hostname validation. False = skip validation \b NOT recommended. +} TLSConnectParams; + +/** + * @brief Network Structure + * + * Structure for defining a network connection. + */ +struct Network { + IoT_Error_t (*connect)(Network *, TLSConnectParams *); + + IoT_Error_t (*read)(Network *, unsigned char *, size_t, Timer *, size_t *); ///< Function pointer pointing to the network function to read from the network + IoT_Error_t (*write)(Network *, unsigned char *, size_t, Timer *, size_t *); ///< Function pointer pointing to the network function to write to the network + IoT_Error_t (*disconnect)(Network *); ///< Function pointer pointing to the network function to disconnect from the network + IoT_Error_t (*isConnected)(Network *); ///< Function pointer pointing to the network function to check if TLS is connected + IoT_Error_t (*destroy)(Network *); ///< Function pointer pointing to the network function to destroy the network object + + TLSConnectParams tlsConnectParams; ///< TLSConnect params structure containing the common connection parameters + TLSDataParams tlsDataParams; ///< TLSData params structure containing the connection data parameters that are specific to the library being used +}; + +/** + * @brief Initialize the TLS implementation + * + * Perform any initialization required by the TLS layer. + * Connects the interface to implementation by setting up + * the network layer function pointers to platform implementations. + * + * @param pNetwork - Pointer to a Network struct defining the network interface. + * @param pRootCALocation - Path of the location of the Root CA + * @param pDeviceCertLocation - Path to the location of the Device Cert + * @param pDevicyPrivateKeyLocation - Path to the location of the device private key file + * @param pDestinationURL - The target endpoint to connect to + * @param DestinationPort - The port on the target to connect to + * @param timeout_ms - The value to use for timeout of operation + * @param ServerVerificationFlag - used to decide whether server verification is needed or not + * + * @return IoT_Error_t - successful initialization or TLS error + */ +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); + +/** + * @brief Create a TLS socket and open the connection + * + * Creates an open socket connection including TLS handshake. + * + * @param pNetwork - Pointer to a Network struct defining the network interface. + * @param TLSParams - TLSConnectParams defines the properties of the TLS connection. + * @return IoT_Error_t - successful connection or TLS error + */ +IoT_Error_t iot_tls_connect(Network *pNetwork, TLSConnectParams *TLSParams); + +/** + * @brief Write bytes to the network socket + * + * @param Network - Pointer to a Network struct defining the network interface. + * @param unsigned char pointer - buffer to write to socket + * @param integer - number of bytes to write + * @param Timer * - operation timer + * @return integer - number of bytes written or TLS error + * @return IoT_Error_t - successful write or TLS error code + */ +IoT_Error_t iot_tls_write(Network *, unsigned char *, size_t, Timer *, size_t *); + +/** + * @brief Read bytes from the network socket + * + * @param Network - Pointer to a Network struct defining the network interface. + * @param unsigned char pointer - pointer to buffer where read bytes should be copied + * @param size_t - number of bytes to read + * @param Timer * - operation timer + * @param size_t - pointer to store number of bytes read + * @return IoT_Error_t - successful read or TLS error code + */ +IoT_Error_t iot_tls_read(Network *, unsigned char *, size_t, Timer *, size_t *); + +/** + * @brief Disconnect from network socket + * + * @param Network - Pointer to a Network struct defining the network interface. + * @return IoT_Error_t - successful read or TLS error code + */ +IoT_Error_t iot_tls_disconnect(Network *pNetwork); + +/** + * @brief Perform any tear-down or cleanup of TLS layer + * + * Called to cleanup any resources required for the TLS layer. + * + * @param Network - Pointer to a Network struct defining the network interface + * @return IoT_Error_t - successful cleanup or TLS error code + */ +IoT_Error_t iot_tls_destroy(Network *pNetwork); + +/** + * @brief Check if TLS layer is still connected + * + * Called to check if the TLS layer is still connected or not. + * + * @param Network - Pointer to a Network struct defining the network interface + * @return IoT_Error_t - TLS error code indicating status of network physical layer connection + */ +IoT_Error_t iot_tls_is_connected(Network *pNetwork); + +#ifdef __cplusplus +} +#endif + +#endif //__NETWORK_INTERFACE_H_ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/include/threads_interface.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/threads_interface.h new file mode 100644 index 00000000..b4bc3705 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/threads_interface.h @@ -0,0 +1,108 @@ +/* +* Copyright 2015-2016 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 threads_interface.h + * @brief Thread interface definition for MQTT client. + * + * Defines an interface that can be used by system components for multithreaded situations. + * Starting point for porting the SDK to the threading hardware layer of a new platform. + */ + +#include "aws_iot_config.h" + +#ifdef _ENABLE_THREAD_SUPPORT_ +#ifndef __THREADS_INTERFACE_H_ +#define __THREADS_INTERFACE_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The platform specific timer header that defines the Timer struct + */ +#include "threads_platform.h" + +#include + +/** + * @brief Mutex Type + * + * Forward declaration of a mutex struct. The definition of this struct is + * platform dependent. When porting to a new platform add this definition + * in "threads_platform.h". + * + */ +typedef struct _IoT_Mutex_t IoT_Mutex_t; + +/** + * @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 *); + +/** + * @brief Lock the provided mutex + * + * Call this function to lock the mutex before performing a state change + * This is a blocking call. + * + * @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 *); + +/** + * @brief Lock the provided mutex + * + * Call this function to lock the mutex before performing a state change. + * This is not a blocking call. + * + * @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 *); + +/** + * @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 *); + +/** + * @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 *); + +#ifdef __cplusplus +} +#endif + +#endif /*__THREADS_INTERFACE_H_*/ +#endif /*_ENABLE_THREAD_SUPPORT_*/ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/include/timer_interface.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/timer_interface.h new file mode 100644 index 00000000..0bef0fc9 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/include/timer_interface.h @@ -0,0 +1,105 @@ +/******************************************************************************* + * Copyright (c) 2014 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * Contributors: + * Allan Stockdill-Mander - initial API and implementation and/or initial documentation + *******************************************************************************/ + +/** + * @file timer_interface.h + * @brief Timer interface definition for MQTT client. + * + * Defines an interface to timers that can be used by other system + * components. MQTT client requires timers to handle timeouts and + * MQTT keep alive. + * Starting point for porting the SDK to the timer hardware layer of a new platform. + */ + +#ifndef __TIMER_INTERFACE_H_ +#define __TIMER_INTERFACE_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * The platform specific timer header that defines the Timer struct + */ +#include "timer_platform.h" + +#include +#include + +/** + * @brief Timer Type + * + * Forward declaration of a timer struct. The definition of this struct is + * platform dependent. When porting to a new platform add this definition + * in "timer_.h" and include that file above. + * + */ +typedef struct Timer Timer; + +/** + * @brief Check if a timer is expired + * + * Call this function passing in a timer to check if that timer has expired. + * + * @param Timer - pointer to the timer to be checked for expiration + * @return bool - true = timer expired, false = timer not expired + */ +bool has_timer_expired(Timer *); + +/** + * @brief Create a timer (milliseconds) + * + * Sets the timer to expire in a specified number of milliseconds. + * + * @param Timer - pointer to the timer to be set to expire in milliseconds + * @param uint32_t - set the timer to expire in this number of milliseconds + */ +void countdown_ms(Timer *, uint32_t); + +/** + * @brief Create a timer (seconds) + * + * Sets the timer to expire in a specified number of seconds. + * + * @param Timer - pointer to the timer to be set to expire in seconds + * @param uint32_t - set the timer to expire in this number of seconds + */ +void countdown_sec(Timer *, uint32_t); + +/** + * @brief Check the time remaining on a given timer + * + * Checks the input timer and returns the number of milliseconds remaining on the timer. + * + * @param Timer - pointer to the timer to be set to checked + * @return int - milliseconds left on the countdown timer + */ +uint32_t left_ms(Timer *); + +/** + * @brief Initialize a timer + * + * Performs any initialization required to the timer passed in. + * + * @param Timer - pointer to the timer to be initialized + */ +void init_timer(Timer *); + +#ifdef __cplusplus +} +#endif + +#endif //__TIMER_INTERFACE_H_ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/platform/linux/common/timer.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/platform/linux/common/timer.c new file mode 100644 index 00000000..47a08514 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/platform/linux/common/timer.c @@ -0,0 +1,74 @@ +/* + * 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 timer.c + * @brief Linux implementation of the timer interface. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include + +#include "timer_platform.h" + +bool has_timer_expired(Timer *timer) { + struct timeval now, res; + gettimeofday(&now, NULL); + timersub(&timer->end_time, &now, &res); + return res.tv_sec < 0 || (res.tv_sec == 0 && res.tv_usec <= 0); +} + +void countdown_ms(Timer *timer, uint32_t timeout) { + struct timeval now; +#ifdef __cplusplus + struct timeval interval = {timeout / 1000, static_cast((timeout % 1000) * 1000)}; +#else + struct timeval interval = {timeout / 1000, (int)((timeout % 1000) * 1000)}; +#endif + gettimeofday(&now, NULL); + timeradd(&now, &interval, &timer->end_time); +} + +uint32_t left_ms(Timer *timer) { + struct timeval now, res; + uint32_t result_ms = 0; + gettimeofday(&now, NULL); + timersub(&timer->end_time, &now, &res); + if(res.tv_sec >= 0) { + result_ms = (uint32_t) (res.tv_sec * 1000 + res.tv_usec / 1000); + } + return result_ms; +} + +void countdown_sec(Timer *timer, uint32_t timeout) { + struct timeval now; + struct timeval interval = {timeout, 0}; + gettimeofday(&now, NULL); + timeradd(&now, &interval, &timer->end_time); +} + +void init_timer(Timer *timer) { + timer->end_time = (struct timeval) {0, 0}; +} + +#ifdef __cplusplus +} +#endif diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/platform/linux/common/timer_platform.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/platform/linux/common/timer_platform.h new file mode 100644 index 00000000..1fe5003d --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/platform/linux/common/timer_platform.h @@ -0,0 +1,41 @@ +/* + * 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. + */ + +#ifndef SRC_PROTOCOL_MQTT_AWS_IOT_EMBEDDED_CLIENT_WRAPPER_PLATFORM_LINUX_COMMON_TIMER_PLATFORM_H_ +#define SRC_PROTOCOL_MQTT_AWS_IOT_EMBEDDED_CLIENT_WRAPPER_PLATFORM_LINUX_COMMON_TIMER_PLATFORM_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @file timer_platform.h + */ +#include +#include +#include "timer_interface.h" + +/** + * definition of the Timer struct. Platform specific + */ +struct Timer { + struct timeval end_time; +}; + +#ifdef __cplusplus +} +#endif + +#endif /* SRC_PROTOCOL_MQTT_AWS_IOT_EMBEDDED_CLIENT_WRAPPER_PLATFORM_LINUX_COMMON_TIMER_PLATFORM_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/platform/linux/mbedtls/network_mbedtls_wrapper.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/platform/linux/mbedtls/network_mbedtls_wrapper.c new file mode 100644 index 00000000..1e2e8e10 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/platform/linux/mbedtls/network_mbedtls_wrapper.c @@ -0,0 +1,372 @@ +/* + * 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. + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include +#include +#include + +#include "aws_iot_error.h" +#include "aws_iot_log.h" +#include "network_interface.h" +#include "network_platform.h" + + +/* This is the value used for ssl read timeout */ +#define IOT_SSL_READ_TIMEOUT 10 + +/* This defines the value of the debug buffer that gets allocated. + * The value can be altered based on memory constraints + */ +#ifdef ENABLE_IOT_DEBUG +#define MBEDTLS_DEBUG_BUFFER_SIZE 2048 +#endif + +/* + * This is a function to do further verification if needed on the cert received + */ + +static int _iot_tls_verify_cert(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags) { + char buf[1024]; + ((void) data); + + IOT_DEBUG("\nVerify requested for (Depth %d):\n", depth); + mbedtls_x509_crt_info(buf, sizeof(buf) - 1, "", crt); + IOT_DEBUG("%s", buf); + + if((*flags) == 0) { + IOT_DEBUG(" This certificate has no flags\n"); + } else { + IOT_DEBUG(buf, sizeof(buf), " ! ", *flags); + IOT_DEBUG("%s\n", buf); + } + + return 0; +} + +void _iot_tls_set_connect_params(Network *pNetwork, char *pRootCALocation, char *pDeviceCertLocation, + char *pDevicePrivateKeyLocation, 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, char *pRootCALocation, char *pDeviceCertLocation, + char *pDevicePrivateKeyLocation, 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 = 0; + const char *pers = "aws_iot_tls_wrapper"; + TLSDataParams *tlsDataParams = NULL; + char portBuffer[6]; + char vrfy_buf[512]; + +#ifdef ENABLE_IOT_DEBUG + unsigned char buf[MBEDTLS_DEBUG_BUFFER_SIZE]; +#endif + + 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)); + mbedtls_ctr_drbg_init(&(tlsDataParams->ctr_drbg)); + mbedtls_x509_crt_init(&(tlsDataParams->cacert)); + mbedtls_x509_crt_init(&(tlsDataParams->clicert)); + mbedtls_pk_init(&(tlsDataParams->pkey)); + + IOT_DEBUG("\n . 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 *) pers, strlen(pers))) != 0) { + IOT_ERROR(" failed\n ! mbedtls_ctr_drbg_seed returned -0x%x\n", -ret); + return NETWORK_MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED; + } + + IOT_DEBUG(" . Loading the CA root certificate ..."); + ret = mbedtls_x509_crt_parse_file(&(tlsDataParams->cacert), pNetwork->tlsConnectParams.pRootCALocation); + if(ret < 0) { + IOT_ERROR(" failed\n ! mbedtls_x509_crt_parse returned -0x%x while parsing root cert\n\n", -ret); + return NETWORK_X509_ROOT_CRT_PARSE_ERROR; + } + IOT_DEBUG(" ok (%d skipped)\n", ret); + + IOT_DEBUG(" . Loading the client cert. and key..."); + ret = mbedtls_x509_crt_parse_file(&(tlsDataParams->clicert), pNetwork->tlsConnectParams.pDeviceCertLocation); + if(ret != 0) { + IOT_ERROR(" failed\n ! mbedtls_x509_crt_parse returned -0x%x while parsing device cert\n\n", -ret); + return NETWORK_X509_DEVICE_CRT_PARSE_ERROR; + } + + ret = mbedtls_pk_parse_keyfile(&(tlsDataParams->pkey), pNetwork->tlsConnectParams.pDevicePrivateKeyLocation, ""); + if(ret != 0) { + IOT_ERROR(" failed\n ! mbedtls_pk_parse_key returned -0x%x while parsing private key\n\n", -ret); + IOT_DEBUG(" path : %s ", pNetwork->tlsConnectParams.pDevicePrivateKeyLocation); + return NETWORK_PK_PRIVATE_KEY_PARSE_ERROR; + } + IOT_DEBUG(" ok\n"); + snprintf(portBuffer, 6, "%d", pNetwork->tlsConnectParams.DestinationPort); + IOT_DEBUG(" . 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) { + IOT_ERROR(" failed\n ! mbedtls_net_connect returned -0x%x\n\n", -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) { + IOT_ERROR(" failed\n ! net_set_(non)block() returned -0x%x\n\n", -ret); + return SSL_CONNECTION_ERROR; + } IOT_DEBUG(" ok\n"); + + IOT_DEBUG(" . 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) { + IOT_ERROR(" failed\n ! mbedtls_ssl_config_defaults returned -0x%x\n\n", -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); + if((ret = mbedtls_ssl_conf_own_cert(&(tlsDataParams->conf), &(tlsDataParams->clicert), &(tlsDataParams->pkey))) != + 0) { + IOT_ERROR(" failed\n ! mbedtls_ssl_conf_own_cert returned %d\n\n", 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) { + IOT_ERROR(" failed\n ! mbedtls_ssl_setup returned -0x%x\n\n", -ret); + return SSL_CONNECTION_ERROR; + } + if((ret = mbedtls_ssl_set_hostname(&(tlsDataParams->ssl), pNetwork->tlsConnectParams.pDestinationURL)) != 0) { + IOT_ERROR(" failed\n ! mbedtls_ssl_set_hostname returned %d\n\n", ret); + return SSL_CONNECTION_ERROR; + } + IOT_DEBUG("\n\nSSL state connect : %d ", tlsDataParams->ssl.state); + mbedtls_ssl_set_bio(&(tlsDataParams->ssl), &(tlsDataParams->server_fd), mbedtls_net_send, NULL, + mbedtls_net_recv_timeout); + IOT_DEBUG(" ok\n"); + + IOT_DEBUG("\n\nSSL state connect : %d ", tlsDataParams->ssl.state); + IOT_DEBUG(" . 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) { + IOT_ERROR(" failed\n ! mbedtls_ssl_handshake returned -0x%x\n", -ret); + if(ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) { + IOT_ERROR(" Unable to verify the server's certificate. " + "Either it is invalid,\n" + " or you didn't set ca_file or ca_path " + "to an appropriate value.\n" + " Alternatively, you may want to use " + "auth_mode=optional for testing purposes.\n"); + } + return SSL_CONNECTION_ERROR; + } + } + + IOT_DEBUG(" ok\n [ Protocol is %s ]\n [ Ciphersuite is %s ]\n", mbedtls_ssl_get_version(&(tlsDataParams->ssl)), + mbedtls_ssl_get_ciphersuite(&(tlsDataParams->ssl))); + if((ret = mbedtls_ssl_get_record_expansion(&(tlsDataParams->ssl))) >= 0) { + IOT_DEBUG(" [ Record expansion is %d ]\n", ret); + } else { + IOT_DEBUG(" [ Record expansion is unknown (compression) ]\n"); + } + + IOT_DEBUG(" . Verifying peer X.509 certificate..."); + + if(pNetwork->tlsConnectParams.ServerVerificationFlag == true) { + if((tlsDataParams->flags = mbedtls_ssl_get_verify_result(&(tlsDataParams->ssl))) != 0) { + IOT_ERROR(" failed\n"); + mbedtls_x509_crt_verify_info(vrfy_buf, sizeof(vrfy_buf), " ! ", tlsDataParams->flags); + IOT_ERROR("%s\n", vrfy_buf); + ret = SSL_CONNECTION_ERROR; + } else { + IOT_DEBUG(" ok\n"); + ret = SUCCESS; + } + } else { + IOT_DEBUG(" Server Verification skipped\n"); + ret = SUCCESS; + } + +#ifdef ENABLE_IOT_DEBUG + if (mbedtls_ssl_get_peer_cert(&(tlsDataParams->ssl)) != NULL) { + IOT_DEBUG(" . Peer certificate information ...\n"); + mbedtls_x509_crt_info((char *) buf, sizeof(buf) - 1, " ", mbedtls_ssl_get_peer_cert(&(tlsDataParams->ssl))); + IOT_DEBUG("%s\n", buf); + } +#endif + + mbedtls_ssl_conf_read_timeout(&(tlsDataParams->conf), IOT_SSL_READ_TIMEOUT); + + 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; + 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) { + IOT_ERROR(" failed\n ! mbedtls_ssl_write returned -0x%x\n\n", -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) { + mbedtls_ssl_context *ssl = &(pNetwork->tlsDataParams.ssl); + size_t rxLen = 0; + int ret; + + while (len > 0) { + // This read will timeout after IOT_SSL_READ_TIMEOUT if there's no data to be read + ret = mbedtls_ssl_read(ssl, pMsg, len); + 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; +} + +#ifdef __cplusplus +} +#endif diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/platform/linux/mbedtls/network_platform.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/platform/linux/mbedtls/network_platform.h new file mode 100644 index 00000000..c2810a1c --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/platform/linux/mbedtls/network_platform.h @@ -0,0 +1,59 @@ +/* + * 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. + */ + +#ifndef IOTSDKC_NETWORK_MBEDTLS_PLATFORM_H_H + +#include "mbedtls/config.h" + +#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/aws-iot-device-sdk-embedded-C/platform/linux/pthread/threads_platform.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/platform/linux/pthread/threads_platform.h new file mode 100644 index 00000000..8a520c63 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/platform/linux/pthread/threads_platform.h @@ -0,0 +1,43 @@ +/* + * 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. + */ + +#include "threads_interface.h" +#ifdef _ENABLE_THREAD_SUPPORT_ +#ifndef IOTSDKC_THREADS_PLATFORM_H_H +#define IOTSDKC_THREADS_PLATFORM_H_H + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +/** + * @brief Mutex Type + * + * definition of the Mutex struct. Platform specific + * + */ +struct _IoT_Mutex_t { + pthread_mutex_t lock; +}; + +#ifdef __cplusplus +} +#endif + +#endif /* IOTSDKC_THREADS_PLATFORM_H_H */ +#endif /* _ENABLE_THREAD_SUPPORT_ */ + diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/platform/linux/pthread/threads_pthread_wrapper.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/platform/linux/pthread/threads_pthread_wrapper.c new file mode 100644 index 00000000..65a310fb --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/platform/linux/pthread/threads_pthread_wrapper.c @@ -0,0 +1,112 @@ +/* + * 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. + */ + +#include "threads_platform.h" +#ifdef _ENABLE_THREAD_SUPPORT_ + +#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) { + if(0 != pthread_mutex_init(&(pMutex->lock), NULL)) { + return MUTEX_INIT_ERROR; + } + + return SUCCESS; +} + +/** + * @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) { +int rc = pthread_mutex_lock(&(pMutex->lock)); + if(0 != rc) { + return MUTEX_LOCK_ERROR; + } + + 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) { +int rc = pthread_mutex_trylock(&(pMutex->lock)); + if(0 != rc) { + return MUTEX_LOCK_ERROR; + } + + return SUCCESS; +} + +/** + * @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(0 != pthread_mutex_unlock(&(pMutex->lock))) { + return MUTEX_UNLOCK_ERROR; + } + + return SUCCESS; +} + +/** + * @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) { + if(0 != pthread_mutex_destroy(&(pMutex->lock))) { + return MUTEX_DESTROY_ERROR; + } + + return SUCCESS; +} + +#ifdef __cplusplus +} +#endif + +#endif /* _ENABLE_THREAD_SUPPORT_ */ + diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/README.md b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/README.md new file mode 100644 index 00000000..7ac0fa5e --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/README.md @@ -0,0 +1,42 @@ +## Overview +This folder contains several samples that demonstrate various SDK functions. The Readme file also includes a walk-through of the subscribe publish sample to explain how the SDK is used. The samples are currently provided with Makefiles for building them on linux. For each sample: + + * Explore the makefile. The makefile for each sample provides a reference on how to set up makefiles for client applications + * Explore the example. It connects to AWS IoT platform using MQTT and demonstrates few actions that can be performed by the SDK + * Download certificate authority CA file from [Symantec](https://www.symantec.com/content/en/us/enterprise/verisign/roots/VeriSign-Class%203-Public-Primary-Certification-Authority-G5.pem) and place in location referenced in the example (certs/) + * Ensure you have [created a thing](https://docs.aws.amazon.com/iot/latest/developerguide/create-thing.html) through your AWS IoT Console with name matching the definition AWS_IOT_MY_THING_NAME in the `aws_iot_config.h` file + * Place device identity cert and private key in locations referenced in the example (certs/) + * Ensure the names of the cert files are the same as in the `aws_iot_config.h` file + * Ensure the certificate has an attached policy which allows the proper permissions for AWS IoT + * Build the example using make (`make`) + * Run sample application (./subscribe_publish_sample or ./shadow_sample). The sample will print status messages to stdout + * All samples are written in C unless otherwise mentioned. The following sample applications are included: + * `subscribe_publish_sample` - a simple pub/sub MQTT example + * `subscribe_publish_cpp_sample` - a simple pub/sub MQTT example written in C++ + * `subscribe_publish_library_sample` - a simple pub/sub MQTT example which builds the SDK as a separate library + * `shadow_sample` - a simple device shadow example using a connected window example + * `shadow_sample_console_echo` - a sample to work with the AWS IoT Console interactive guide + +## Subscribe Publish Sample +This is a simple pub/sub MQTT example. It connects a single MQTT client to the server and subscribes to a test topic. Then it proceeds to publish messages on this topic and yields after each publish to ensure that the message was received. + + * The sample first creates an instance of the AWS_IoT_Client + * The next step is to initialize the client. The aws_iot_mqtt_init API is called for this purpose. The API takes the client instance and an IoT_Client_Init_Params variable to set the initial values for the client. The Init params include values like host URL, port, certificates, disconnect handler etc. + * If the call to the init API was successful, we can proceed to call connect. The API is called aws_iot_mqtt_connect. It takes the client instance and IoT_Client_Connect_Params variable as arguments. The IoT_Client_Connect_Params is optional after the first call to connect as the client retains the original values that were provided to support reconnect. The Connect params include values like Client Id, MQTT Version etc. + * If the connect API call was successful, we can proceed to subscribe and publish on this connect. The connect API call will return an error code, specific to the type of error that occurred, in case the call fails. + * It is important to remember here that there is no dynamic memory allocation in the SDK. Any values that are passed as a pointer to the APIs should not be freed unless they are not required any further. For example, if the variable that stores the certificate path is freed after the init call is made, the connect call will fail. Similarly, if it is freed after the connect API returns success, any future connect calls (including reconnects) will fail. + * The next step for this sample is to subscribe to the test topic. The API to be called for subscribe is aws_iot_mqtt_subscribe. It takes as arguments, the IoT Client instance, topic name, the length of the topic name, QoS, the subscribe callback handler and an optional pointer to some data to be returned to the subscribe handler + * The next step it to call the publish API to send a message on the test topic. The sample sends two different messages, one QoS0 and one QoS1. The + * The publish API takes the client instance, topic name to publish to, topic name length and a variable of type IoT_Publish_Message_Params. The IoT_Publish_Message_Params contains the payload, length of the payload and QoS. + * If the publish API calls are successful, the sample proceeds to call the yield API. The yield API takes the client instance and a timeout value in milliseconds as arguments. + * The yield API is called to let the SDK process any incoming messages. It also periodically sends out the PING request to prevent disconnect and, if enabled, it also performs auto-reconnect and resubscribe. + * The yield API should be called periodically to process the PING request as well as read any messages in the receive buffer. It should be called once at least every TTL/2 time periods to ensure disconnect does not happen. There can only be one yield in progress at a time. Therefore, in multi-threaded scenarios one thread can be a dedicated yield thread while other threads handle other operations. + * The sample sends out messages equal to the value set in publish count unless infinite publishing flag is set + +For further information on each API please read the API documentation. + +## Subscribe Publish Cpp Sample +This is the same sample as above but it is built using a C++ compiler. It demonstrates how the SDK can be used in a C++ program. + +## Subscribe Publish Library Sample +This is also the same code as the Subscribe Publish sample. In this case, the SDK is built as a separate library and then used in the sample program. \ No newline at end of file diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample/Makefile b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample/Makefile new file mode 100644 index 00000000..6199b048 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample/Makefile @@ -0,0 +1,71 @@ +#This target is to ensure accidental execution of Makefile as a bash script will not execute commands like rm in unexpected directories and exit gracefully. +.prevent_execution: + exit 0 + +CC = gcc + +#remove @ for no make command prints +DEBUG = @ + +APP_DIR = . +APP_INCLUDE_DIRS += -I $(APP_DIR) +APP_NAME = shadow_sample +APP_SRC_FILES = $(APP_NAME).c + +#IoT client directory +IOT_CLIENT_DIR = ../../.. + +PLATFORM_DIR = $(IOT_CLIENT_DIR)/platform/linux/mbedtls +PLATFORM_COMMON_DIR = $(IOT_CLIENT_DIR)/platform/linux/common + +IOT_INCLUDE_DIRS += -I $(IOT_CLIENT_DIR)/include +IOT_INCLUDE_DIRS += -I $(IOT_CLIENT_DIR)/external_libs/jsmn +IOT_INCLUDE_DIRS += -I $(PLATFORM_COMMON_DIR) +IOT_INCLUDE_DIRS += -I $(PLATFORM_DIR) + +IOT_SRC_FILES += $(shell find $(IOT_CLIENT_DIR)/src/ -name '*.c') +IOT_SRC_FILES += $(shell find $(IOT_CLIENT_DIR)/external_libs/jsmn -name '*.c') +IOT_SRC_FILES += $(shell find $(PLATFORM_DIR)/ -name '*.c') +IOT_SRC_FILES += $(shell find $(PLATFORM_COMMON_DIR)/ -name '*.c') + +#TLS - mbedtls +MBEDTLS_DIR = $(IOT_CLIENT_DIR)/external_libs/mbedTLS +TLS_LIB_DIR = $(MBEDTLS_DIR)/library +TLS_INCLUDE_DIR = -I $(MBEDTLS_DIR)/include +EXTERNAL_LIBS += -L$(TLS_LIB_DIR) +LD_FLAG += -Wl,-rpath,$(TLS_LIB_DIR) +LD_FLAG += -ldl $(TLS_LIB_DIR)/libmbedtls.a $(TLS_LIB_DIR)/libmbedcrypto.a $(TLS_LIB_DIR)/libmbedx509.a + + +#Aggregate all include and src directories +INCLUDE_ALL_DIRS += $(IOT_INCLUDE_DIRS) +INCLUDE_ALL_DIRS += $(TLS_INCLUDE_DIR) +INCLUDE_ALL_DIRS += $(APP_INCLUDE_DIRS) + +SRC_FILES += $(APP_SRC_FILES) +SRC_FILES += $(IOT_SRC_FILES) + +# Logging level control +LOG_FLAGS += -DENABLE_IOT_DEBUG +LOG_FLAGS += -DENABLE_IOT_INFO +LOG_FLAGS += -DENABLE_IOT_WARN +LOG_FLAGS += -DENABLE_IOT_ERROR + +COMPILER_FLAGS += -g +COMPILER_FLAGS += $(LOG_FLAGS) +#If the processor is big endian uncomment the compiler flag +#COMPILER_FLAGS += -DREVERSED + +MBED_TLS_MAKE_CMD = $(MAKE) -C $(MBEDTLS_DIR) + +PRE_MAKE_CMD = $(MBED_TLS_MAKE_CMD) +MAKE_CMD = $(CC) $(SRC_FILES) $(COMPILER_FLAGS) -o $(APP_NAME) $(LD_FLAG) $(EXTERNAL_LIBS) $(INCLUDE_ALL_DIRS) + +all: + $(PRE_MAKE_CMD) + $(DEBUG)$(MAKE_CMD) + $(POST_MAKE_CMD) + +clean: + rm -f $(APP_DIR)/$(APP_NAME) + $(MBED_TLS_MAKE_CMD) clean diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample/aws_iot_config.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample/aws_iot_config.h new file mode 100644 index 00000000..62abce4a --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample/aws_iot_config.h @@ -0,0 +1,58 @@ +/* + * 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 SRC_SHADOW_IOT_SHADOW_CONFIG_H_ +#define SRC_SHADOW_IOT_SHADOW_CONFIG_H_ + +// Get from console +// ================================================= +#define AWS_IOT_MQTT_HOST "" ///< Customer specific MQTT HOST. The same will be used for Thing Shadow +#define AWS_IOT_MQTT_PORT 8883 ///< default port for MQTT/S +#define AWS_IOT_MQTT_CLIENT_ID "c-sdk-client-id" ///< MQTT client ID should be unique for every device +#define AWS_IOT_MY_THING_NAME "AWS-IoT-C-SDK" ///< Thing Name of the Shadow this device is associated with +#define AWS_IOT_ROOT_CA_FILENAME "rootCA.crt" ///< Root CA file name +#define AWS_IOT_CERTIFICATE_FILENAME "cert.pem" ///< device signed certificate file name +#define AWS_IOT_PRIVATE_KEY_FILENAME "privkey.pem" ///< Device private key filename +// ================================================= + +// 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, including terminating NULL byte. +#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 format $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. + +#define DISABLE_METRICS false ///< Disable the collection of metrics by setting this to true + +#endif /* SRC_SHADOW_IOT_SHADOW_CONFIG_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample/shadow_sample.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample/shadow_sample.c new file mode 100644 index 00000000..9a0b270b --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample/shadow_sample.c @@ -0,0 +1,272 @@ +/* + * 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 shadow_sample.c + * @brief A simple connected window example demonstrating the use of Thing Shadow + */ + +#include +#include +#include +#include +#include +#include + +#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 + } + } + */ + +#define ROOMTEMPERATURE_UPPERLIMIT 32.0f +#define ROOMTEMPERATURE_LOWERLIMIT 25.0f +#define STARTING_ROOMTEMPERATURE ROOMTEMPERATURE_LOWERLIMIT + +#define MAX_LENGTH_OF_UPDATE_JSON_BUFFER 200 + +static char certDirectory[PATH_MAX + 1] = "../../../certs"; +static char HostAddress[255] = AWS_IOT_MQTT_HOST; +static uint32_t port = AWS_IOT_MQTT_PORT; +static uint8_t numPubs = 5; + +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; +} + +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); + + if(SHADOW_ACK_TIMEOUT == status) { + IOT_INFO("Update Timeout--"); + } else if(SHADOW_ACK_REJECTED == status) { + IOT_INFO("Update RejectedXX"); + } else if(SHADOW_ACK_ACCEPTED == status) { + IOT_INFO("Update Accepted !!"); + } +} + +void windowActuate_Callback(const char *pJsonString, uint32_t JsonStringDataLen, jsonStruct_t *pContext) { + IOT_UNUSED(pJsonString); + IOT_UNUSED(JsonStringDataLen); + + if(pContext != NULL) { + IOT_INFO("Delta - Window state changed to %d", *(bool *) (pContext->pData)); + } +} + +void parseInputArgsForConnectParams(int argc, char **argv) { + int opt; + + while(-1 != (opt = getopt(argc, argv, "h:p:c:n:"))) { + switch(opt) { + case 'h': + strcpy(HostAddress, optarg); + IOT_DEBUG("Host %s", optarg); + break; + case 'p': + port = atoi(optarg); + IOT_DEBUG("arg %s", optarg); + break; + case 'c': + strcpy(certDirectory, optarg); + IOT_DEBUG("cert root directory %s", optarg); + break; + case 'n': + numPubs = atoi(optarg); + IOT_DEBUG("num pubs %s", optarg); + break; + case '?': + if(optopt == 'c') { + IOT_ERROR("Option -%c requires an argument.", optopt); + } else if(isprint(optopt)) { + IOT_WARN("Unknown option `-%c'.", optopt); + } else { + IOT_WARN("Unknown option character `\\x%x'.", optopt); + } + break; + default: + IOT_ERROR("ERROR in command line argument parsing"); + break; + } + } + +} + +int main(int argc, char **argv) { + IoT_Error_t rc = FAILURE; + int32_t i = 0; + + char JsonDocumentBuffer[MAX_LENGTH_OF_UPDATE_JSON_BUFFER]; + size_t sizeOfJsonDocumentBuffer = sizeof(JsonDocumentBuffer) / sizeof(JsonDocumentBuffer[0]); + char *pJsonStringToUpdate; + 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; + + char rootCA[PATH_MAX + 1]; + char clientCRT[PATH_MAX + 1]; + char clientKey[PATH_MAX + 1]; + char CurrentWD[PATH_MAX + 1]; + + IOT_INFO("\nAWS IoT SDK Version %d.%d.%d-%s\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG); + + getcwd(CurrentWD, sizeof(CurrentWD)); + snprintf(rootCA, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_ROOT_CA_FILENAME); + snprintf(clientCRT, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_CERTIFICATE_FILENAME); + snprintf(clientKey, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_PRIVATE_KEY_FILENAME); + + IOT_DEBUG("rootCA %s", rootCA); + IOT_DEBUG("clientCRT %s", clientCRT); + IOT_DEBUG("clientKey %s", clientKey); + + parseInputArgsForConnectParams(argc, argv); + + // initialize the mqtt client + AWS_IoT_Client mqttClient; + + ShadowInitParameters_t sp = ShadowInitParametersDefault; + sp.pHost = AWS_IOT_MQTT_HOST; + sp.port = AWS_IOT_MQTT_PORT; + sp.pClientCRT = clientCRT; + sp.pClientKey = clientKey; + sp.pRootCA = rootCA; + sp.enableAutoReconnect = false; + sp.disconnectHandler = NULL; + + IOT_INFO("Shadow Init"); + rc = aws_iot_shadow_init(&mqttClient, &sp); + if(SUCCESS != rc) { + IOT_ERROR("Shadow Connection Error"); + return rc; + } + + ShadowConnectParameters_t scp = ShadowConnectParametersDefault; + scp.pMyThingName = AWS_IOT_MY_THING_NAME; + scp.pMqttClientId = AWS_IOT_MQTT_CLIENT_ID; + scp.mqttClientIdLen = (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID); + + IOT_INFO("Shadow Connect"); + rc = aws_iot_shadow_connect(&mqttClient, &scp); + if(SUCCESS != rc) { + IOT_ERROR("Shadow Connection Error"); + return 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_shadow_set_autoreconnect_status(&mqttClient, true); + if(SUCCESS != rc) { + IOT_ERROR("Unable to set Auto Reconnect to true - %d", rc); + return rc; + } + + rc = aws_iot_shadow_register_delta(&mqttClient, &windowActuator); + + if(SUCCESS != rc) { + IOT_ERROR("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) { + sleep(1); + // If the client is attempting to reconnect we will skip the rest of the loop. + continue; + } + IOT_INFO("\n=======================================================================================\n"); + IOT_INFO("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) { + IOT_INFO("Update Shadow: %s", JsonDocumentBuffer); + rc = aws_iot_shadow_update(&mqttClient, AWS_IOT_MY_THING_NAME, JsonDocumentBuffer, + ShadowUpdateStatusCallback, NULL, 4, true); + } + } + } + IOT_INFO("*****************************************************************************************\n"); + sleep(1); + } + + if(SUCCESS != rc) { + IOT_ERROR("An error occurred in the loop %d", rc); + } + + IOT_INFO("Disconnecting"); + rc = aws_iot_shadow_disconnect(&mqttClient); + + if(SUCCESS != rc) { + IOT_ERROR("Disconnect error %d", rc); + } + + return rc; +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample_console_echo/Makefile b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample_console_echo/Makefile new file mode 100644 index 00000000..8447901d --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample_console_echo/Makefile @@ -0,0 +1,74 @@ +#This target is to ensure accidental execution of Makefile as a bash script will not execute commands like rm in unexpected directories and exit gracefully. +.prevent_execution: + exit 0 + +CC = gcc + +#remove @ for no make command prints +DEBUG = @ + +APP_DIR = . +APP_INCLUDE_DIRS += -I $(APP_DIR) +APP_NAME = shadow_console_echo +APP_SRC_FILES = $(APP_NAME).c + +#IoT client directory +IOT_CLIENT_DIR = ../../.. + +PLATFORM_DIR = $(IOT_CLIENT_DIR)/platform/linux/mbedtls +PLATFORM_COMMON_DIR = $(IOT_CLIENT_DIR)/platform/linux/common + +IOT_INCLUDE_DIRS += -I $(IOT_CLIENT_DIR)/include +IOT_INCLUDE_DIRS += -I $(IOT_CLIENT_DIR)/external_libs/jsmn +IOT_INCLUDE_DIRS += -I $(PLATFORM_COMMON_DIR) +IOT_INCLUDE_DIRS += -I $(PLATFORM_DIR) + +IOT_SRC_FILES += $(shell find $(IOT_CLIENT_DIR)/src/ -name '*.c') +IOT_SRC_FILES += $(shell find $(IOT_CLIENT_DIR)/external_libs/jsmn -name '*.c') +IOT_SRC_FILES += $(shell find $(PLATFORM_DIR)/ -name '*.c') +IOT_SRC_FILES += $(shell find $(PLATFORM_COMMON_DIR)/ -name '*.c') + +#TLS - mbedtls +MBEDTLS_DIR = $(IOT_CLIENT_DIR)/external_libs/mbedTLS +TLS_LIB_DIR = $(MBEDTLS_DIR)/library +TLS_INCLUDE_DIR = -I $(MBEDTLS_DIR)/include +EXTERNAL_LIBS += -L$(TLS_LIB_DIR) +LD_FLAG += -Wl,-rpath,$(TLS_LIB_DIR) +LD_FLAG += -ldl $(TLS_LIB_DIR)/libmbedtls.a $(TLS_LIB_DIR)/libmbedcrypto.a $(TLS_LIB_DIR)/libmbedx509.a + + +#Aggregate all include and src directories +INCLUDE_ALL_DIRS += $(IOT_INCLUDE_DIRS) +INCLUDE_ALL_DIRS += $(MQTT_INCLUDE_DIR) +INCLUDE_ALL_DIRS += $(TLS_INCLUDE_DIR) +INCLUDE_ALL_DIRS += $(APP_INCLUDE_DIRS) + +SRC_FILES += $(MQTT_SRC_FILES) +SRC_FILES += $(APP_SRC_FILES) +SRC_FILES += $(IOT_SRC_FILES) + +# Logging level control +LOG_FLAGS += -DENABLE_IOT_DEBUG +LOG_FLAGS += -DENABLE_IOT_INFO +LOG_FLAGS += -DENABLE_IOT_WARN +LOG_FLAGS += -DENABLE_IOT_ERROR + +COMPILER_FLAGS += -g +COMPILER_FLAGS += $(LOG_FLAGS) + +#If the processor is big endian uncomment the compiler flag +#COMPILER_FLAGS += -DREVERSED + +MBED_TLS_MAKE_CMD = $(MAKE) -C $(MBEDTLS_DIR) + +PRE_MAKE_CMD = $(MBED_TLS_MAKE_CMD) +MAKE_CMD = $(CC) $(SRC_FILES) $(COMPILER_FLAGS) -o $(APP_NAME) $(LD_FLAG) $(EXTERNAL_LIBS) $(INCLUDE_ALL_DIRS) + +all: + $(PRE_MAKE_CMD) + $(DEBUG)$(MAKE_CMD) + $(POST_MAKE_CMD) + +clean: + rm -f $(APP_DIR)/$(APP_NAME) + $(MBED_TLS_MAKE_CMD) clean diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample_console_echo/aws_iot_config.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample_console_echo/aws_iot_config.h new file mode 100644 index 00000000..62abce4a --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample_console_echo/aws_iot_config.h @@ -0,0 +1,58 @@ +/* + * 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 SRC_SHADOW_IOT_SHADOW_CONFIG_H_ +#define SRC_SHADOW_IOT_SHADOW_CONFIG_H_ + +// Get from console +// ================================================= +#define AWS_IOT_MQTT_HOST "" ///< Customer specific MQTT HOST. The same will be used for Thing Shadow +#define AWS_IOT_MQTT_PORT 8883 ///< default port for MQTT/S +#define AWS_IOT_MQTT_CLIENT_ID "c-sdk-client-id" ///< MQTT client ID should be unique for every device +#define AWS_IOT_MY_THING_NAME "AWS-IoT-C-SDK" ///< Thing Name of the Shadow this device is associated with +#define AWS_IOT_ROOT_CA_FILENAME "rootCA.crt" ///< Root CA file name +#define AWS_IOT_CERTIFICATE_FILENAME "cert.pem" ///< device signed certificate file name +#define AWS_IOT_PRIVATE_KEY_FILENAME "privkey.pem" ///< Device private key filename +// ================================================= + +// 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, including terminating NULL byte. +#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 format $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. + +#define DISABLE_METRICS false ///< Disable the collection of metrics by setting this to true + +#endif /* SRC_SHADOW_IOT_SHADOW_CONFIG_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample_console_echo/shadow_console_echo.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample_console_echo/shadow_console_echo.c new file mode 100644 index 00000000..1c491fbd --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample_console_echo/shadow_console_echo.c @@ -0,0 +1,276 @@ +/* + * 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. + */ +#include +#include +#include +#include +#include +#include + +#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" + +/** + * @file shadow_console_echo.c + * @brief Echo received Delta message + * + * This application will echo the message received in delta, as reported. + * for example: + * Received Delta message + * { + * "state": { + * "switch": "on" + * } + * } + * This delta message means the desired switch position has changed to "on" + * + * This application will take this delta message and publish it back as the reported message from the device. + * { + * "state": { + * "reported": { + * "switch": "on" + * } + * } + * } + * + * This update message will remove the delta that was created. If this message was not removed then the AWS IoT Thing Shadow is going to always have a delta and keep sending delta any time an update is applied to the Shadow + * This example will not use any of the json builder/helper functions provided in the aws_iot_shadow_json_data.h. + * @note Ensure the buffer sizes in aws_iot_config.h are big enough to receive the delta message. The delta message will also contain the metadata with the timestamps + */ + +char certDirectory[PATH_MAX + 1] = "../../../certs"; +char HostAddress[255] = AWS_IOT_MQTT_HOST; +uint32_t port = AWS_IOT_MQTT_PORT; +bool messageArrivedOnDelta = false; + +/* + * @note The delta message is always sent on the "state" key in the json + * @note Any time messages are bigger than AWS_IOT_MQTT_RX_BUF_LEN the underlying MQTT library will ignore it. The maximum size of the message that can be received is limited to the AWS_IOT_MQTT_RX_BUF_LEN + */ +char stringToEchoDelta[SHADOW_MAX_SIZE_OF_RX_BUFFER]; + +// Helper functions +void parseInputArgsForConnectParams(int argc, char** argv); + +// Shadow Callback for receiving the delta +void DeltaCallback(const char *pJsonValueBuffer, uint32_t valueLength, jsonStruct_t *pJsonStruct_t); + +void UpdateStatusCallback(const char *pThingName, ShadowActions_t action, Shadow_Ack_Status_t status, + const char *pReceivedJsonDocument, void *pContextData); + +int main(int argc, char** argv) { + IoT_Error_t rc = SUCCESS; + int32_t i = 0; + + char rootCA[PATH_MAX + 1]; + char clientCRT[PATH_MAX + 1]; + char clientKey[PATH_MAX + 1]; + char CurrentWD[PATH_MAX + 1]; + + IOT_INFO("\nAWS IoT SDK Version %d.%d.%d-%s\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG); + + getcwd(CurrentWD, sizeof(CurrentWD)); + snprintf(rootCA, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_ROOT_CA_FILENAME); + snprintf(clientCRT, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_CERTIFICATE_FILENAME); + snprintf(clientKey, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_PRIVATE_KEY_FILENAME); + + IOT_DEBUG("rootCA %s", rootCA); + IOT_DEBUG("clientCRT %s", clientCRT); + IOT_DEBUG("clientKey %s", clientKey); + + parseInputArgsForConnectParams(argc, argv); + + // initialize the mqtt client + AWS_IoT_Client mqttClient; + + ShadowInitParameters_t sp = ShadowInitParametersDefault; + sp.pHost = AWS_IOT_MQTT_HOST; + sp.port = AWS_IOT_MQTT_PORT; + sp.pClientCRT = clientCRT; + sp.pClientKey = clientKey; + sp.pRootCA = rootCA; + sp.enableAutoReconnect = false; + sp.disconnectHandler = NULL; + + IOT_INFO("Shadow Init"); + rc = aws_iot_shadow_init(&mqttClient, &sp); + if (SUCCESS != rc) { + IOT_ERROR("Shadow Connection Error"); + return rc; + } + + ShadowConnectParameters_t scp = ShadowConnectParametersDefault; + scp.pMyThingName = AWS_IOT_MY_THING_NAME; + scp.pMqttClientId = AWS_IOT_MQTT_CLIENT_ID; + scp.mqttClientIdLen = (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID); + + IOT_INFO("Shadow Connect"); + rc = aws_iot_shadow_connect(&mqttClient, &scp); + if (SUCCESS != rc) { + IOT_ERROR("Shadow Connection Error"); + return 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_shadow_set_autoreconnect_status(&mqttClient, true); + if(SUCCESS != rc){ + IOT_ERROR("Unable to set Auto Reconnect to true - %d", rc); + return rc; + } + + jsonStruct_t deltaObject; + deltaObject.pData = stringToEchoDelta; + deltaObject.pKey = "state"; + deltaObject.type = SHADOW_JSON_OBJECT; + deltaObject.cb = DeltaCallback; + + /* + * Register the jsonStruct object + */ + rc = aws_iot_shadow_register_delta(&mqttClient, &deltaObject); + + // Now wait in the loop to receive any message sent from the console + while (NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc) { + /* + * Lets check for the incoming messages for 200 ms. + */ + rc = aws_iot_shadow_yield(&mqttClient, 200); + + if (NETWORK_ATTEMPTING_RECONNECT == rc) { + sleep(1); + // If the client is attempting to reconnect we will skip the rest of the loop. + continue; + } + + if (messageArrivedOnDelta) { + IOT_INFO("\nSending delta message back %s\n", stringToEchoDelta); + rc = aws_iot_shadow_update(&mqttClient, AWS_IOT_MY_THING_NAME, stringToEchoDelta, UpdateStatusCallback, NULL, 2, true); + messageArrivedOnDelta = false; + } + + // sleep for some time in seconds + sleep(1); + } + + if (SUCCESS != rc) { + IOT_ERROR("An error occurred in the loop %d", rc); + } + + IOT_INFO("Disconnecting"); + rc = aws_iot_shadow_disconnect(&mqttClient); + + if (SUCCESS != rc) { + IOT_ERROR("Disconnect error %d", rc); + } + + return rc; +} +/** + * @brief This function builds a full Shadow expected JSON document by putting the data in the reported section + * + * @param pJsonDocument Buffer to be filled up with the JSON data + * @param maxSizeOfJsonDocument maximum size of the buffer that could be used to fill + * @param pReceivedDeltaData This is the data that will be embedded in the reported section of the JSON document + * @param lengthDelta Length of the data + */ +bool buildJSONForReported(char *pJsonDocument, size_t maxSizeOfJsonDocument, const char *pReceivedDeltaData, uint32_t lengthDelta) { + int32_t ret; + + if (NULL == pJsonDocument) { + return false; + } + + char tempClientTokenBuffer[MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE]; + + if(aws_iot_fill_with_client_token(tempClientTokenBuffer, MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE) != SUCCESS){ + return false; + } + + ret = snprintf(pJsonDocument, maxSizeOfJsonDocument, "{\"state\":{\"reported\":%.*s}, \"clientToken\":\"%s\"}", lengthDelta, pReceivedDeltaData, tempClientTokenBuffer); + + if (ret >= maxSizeOfJsonDocument || ret < 0) { + return false; + } + + return true; +} + +void parseInputArgsForConnectParams(int argc, char** argv) { + int opt; + + while (-1 != (opt = getopt(argc, argv, "h:p:c:"))) { + switch (opt) { + case 'h': + strcpy(HostAddress, optarg); + IOT_DEBUG("Host %s", optarg); + break; + case 'p': + port = atoi(optarg); + IOT_DEBUG("arg %s", optarg); + break; + case 'c': + strcpy(certDirectory, optarg); + IOT_DEBUG("cert root directory %s", optarg); + break; + case '?': + if (optopt == 'c') { + IOT_ERROR("Option -%c requires an argument.", optopt); + } else if (isprint(optopt)) { + IOT_WARN("Unknown option `-%c'.", optopt); + } else { + IOT_WARN("Unknown option character `\\x%x'.", optopt); + } + break; + default: + IOT_ERROR("ERROR in command line argument parsing"); + break; + } + } + +} + + +void DeltaCallback(const char *pJsonValueBuffer, uint32_t valueLength, jsonStruct_t *pJsonStruct_t) { + IOT_UNUSED(pJsonStruct_t); + + IOT_DEBUG("Received Delta message %.*s", valueLength, pJsonValueBuffer); + + if (buildJSONForReported(stringToEchoDelta, SHADOW_MAX_SIZE_OF_RX_BUFFER, pJsonValueBuffer, valueLength)) { + messageArrivedOnDelta = true; + } +} + +void UpdateStatusCallback(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); + + if(SHADOW_ACK_TIMEOUT == status) { + IOT_INFO("Update Timeout--"); + } else if(SHADOW_ACK_REJECTED == status) { + IOT_INFO("Update RejectedXX"); + } else if(SHADOW_ACK_ACCEPTED == status) { + IOT_INFO("Update Accepted !!"); + } +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_cpp_sample/Makefile b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_cpp_sample/Makefile new file mode 100644 index 00000000..9f604348 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_cpp_sample/Makefile @@ -0,0 +1,70 @@ +#This target is to ensure accidental execution of Makefile as a bash script will not execute commands like rm in unexpected directories and exit gracefully. +.prevent_execution: + exit 0 + +CC = g++ + +#remove @ for no make command prints +DEBUG = @ + +APP_DIR = . +APP_INCLUDE_DIRS += -I $(APP_DIR) +APP_NAME = subscribe_publish_cpp_sample +APP_SRC_FILES = $(APP_NAME).cpp + +#IoT client directory +IOT_CLIENT_DIR = ../../.. + +PLATFORM_DIR = $(IOT_CLIENT_DIR)/platform/linux/mbedtls +PLATFORM_COMMON_DIR = $(IOT_CLIENT_DIR)/platform/linux/common + +IOT_INCLUDE_DIRS += -I $(IOT_CLIENT_DIR)/include +IOT_INCLUDE_DIRS += -I $(IOT_CLIENT_DIR)/external_libs/jsmn +IOT_INCLUDE_DIRS += -I $(PLATFORM_COMMON_DIR) +IOT_INCLUDE_DIRS += -I $(PLATFORM_DIR) + +IOT_SRC_FILES += $(shell find $(IOT_CLIENT_DIR)/src/ -name '*.c') +IOT_SRC_FILES += $(shell find $(IOT_CLIENT_DIR)/external_libs/jsmn -name '*.c') +IOT_SRC_FILES += $(shell find $(PLATFORM_DIR)/ -name '*.c') +IOT_SRC_FILES += $(shell find $(PLATFORM_COMMON_DIR)/ -name '*.c') + +#TLS - mbedtls +MBEDTLS_DIR = $(IOT_CLIENT_DIR)/external_libs/mbedTLS +TLS_LIB_DIR = $(MBEDTLS_DIR)/library +TLS_INCLUDE_DIR = -I $(MBEDTLS_DIR)/include +EXTERNAL_LIBS += -L$(TLS_LIB_DIR) +LD_FLAG += -Wl,-rpath,$(TLS_LIB_DIR) +LD_FLAG += -ldl $(TLS_LIB_DIR)/libmbedtls.a $(TLS_LIB_DIR)/libmbedcrypto.a $(TLS_LIB_DIR)/libmbedx509.a -lpthread + +#Aggregate all include and src directories +INCLUDE_ALL_DIRS += $(IOT_INCLUDE_DIRS) +INCLUDE_ALL_DIRS += $(TLS_INCLUDE_DIR) +INCLUDE_ALL_DIRS += $(APP_INCLUDE_DIRS) + +SRC_FILES += $(APP_SRC_FILES) +SRC_FILES += $(IOT_SRC_FILES) + +# Logging level control +LOG_FLAGS += -DENABLE_IOT_DEBUG +LOG_FLAGS += -DENABLE_IOT_INFO +LOG_FLAGS += -DENABLE_IOT_WARN +LOG_FLAGS += -DENABLE_IOT_ERROR + +COMPILER_FLAGS += $(LOG_FLAGS) +#If the processor is big endian uncomment the compiler flag +#COMPILER_FLAGS += -DREVERSED +COMPILER_FLAGS += -std=c++0x + +MBED_TLS_MAKE_CMD = $(MAKE) -C $(MBEDTLS_DIR) + +PRE_MAKE_CMD = $(MBED_TLS_MAKE_CMD) +MAKE_CMD = $(CC) $(SRC_FILES) $(COMPILER_FLAGS) -o $(APP_NAME) $(LD_FLAG) $(EXTERNAL_LIBS) $(INCLUDE_ALL_DIRS) + +all: + $(PRE_MAKE_CMD) + $(DEBUG)$(MAKE_CMD) + $(POST_MAKE_CMD) + +clean: + rm -f $(APP_DIR)/$(APP_NAME) + $(MBED_TLS_MAKE_CMD) clean diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_cpp_sample/aws_iot_config.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_cpp_sample/aws_iot_config.h new file mode 100644 index 00000000..62abce4a --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_cpp_sample/aws_iot_config.h @@ -0,0 +1,58 @@ +/* + * 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 SRC_SHADOW_IOT_SHADOW_CONFIG_H_ +#define SRC_SHADOW_IOT_SHADOW_CONFIG_H_ + +// Get from console +// ================================================= +#define AWS_IOT_MQTT_HOST "" ///< Customer specific MQTT HOST. The same will be used for Thing Shadow +#define AWS_IOT_MQTT_PORT 8883 ///< default port for MQTT/S +#define AWS_IOT_MQTT_CLIENT_ID "c-sdk-client-id" ///< MQTT client ID should be unique for every device +#define AWS_IOT_MY_THING_NAME "AWS-IoT-C-SDK" ///< Thing Name of the Shadow this device is associated with +#define AWS_IOT_ROOT_CA_FILENAME "rootCA.crt" ///< Root CA file name +#define AWS_IOT_CERTIFICATE_FILENAME "cert.pem" ///< device signed certificate file name +#define AWS_IOT_PRIVATE_KEY_FILENAME "privkey.pem" ///< Device private key filename +// ================================================= + +// 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, including terminating NULL byte. +#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 format $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. + +#define DISABLE_METRICS false ///< Disable the collection of metrics by setting this to true + +#endif /* SRC_SHADOW_IOT_SHADOW_CONFIG_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_cpp_sample/subscribe_publish_cpp_sample.cpp b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_cpp_sample/subscribe_publish_cpp_sample.cpp new file mode 100644 index 00000000..20fee197 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_cpp_sample/subscribe_publish_cpp_sample.cpp @@ -0,0 +1,262 @@ +/* + * 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 subscribe_publish_cpp_sample.cpp + * @brief simple MQTT publish and subscribe on the same topic in C++ + * + * This example takes the parameters from the aws_iot_config.h file and establishes a connection to the AWS IoT MQTT Platform. + * It subscribes and publishes to the same topic - "sdkTest/sub" + * + * If all the certs are correct, you should see the messages received by the application in a loop. + * + * The application takes in the certificate path, host name , port and the number of times the publish should happen. + * + */ +#include +#include +#include +#include +#include +#include + +#include "aws_iot_config.h" +#include "aws_iot_log.h" +#include "aws_iot_version.h" +#include "aws_iot_mqtt_client_interface.h" + +/** + * @brief Default cert location + */ +char certDirectory[PATH_MAX + 1] = "../../../certs"; + +/** + * @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; + +/** + * @brief This parameter will avoid infinite loop of publish and exit the program after certain number of publishes + */ +uint32_t publishCount = 0; + +void iot_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, + IoT_Publish_Message_Params *params, void *pData) { + IOT_UNUSED(pData); + IOT_UNUSED(pClient); + IOT_INFO("Subscribe callback"); + IOT_INFO("%.*s\t%.*s", topicNameLen, topicName, (int) params->payloadLen, params->payload); +} + +void disconnectCallbackHandler(AWS_IoT_Client *pClient, void *data) { + IOT_WARN("MQTT Disconnect"); + IoT_Error_t rc = FAILURE; + + if(NULL == pClient) { + return; + } + + IOT_UNUSED(data); + + if(aws_iot_is_autoreconnect_enabled(pClient)) { + IOT_INFO("Auto Reconnect is enabled, Reconnecting attempt will start now"); + } else { + IOT_WARN("Auto Reconnect not enabled. Starting manual reconnect..."); + rc = aws_iot_mqtt_attempt_reconnect(pClient); + if(NETWORK_RECONNECTED == rc) { + IOT_WARN("Manual Reconnect Successful"); + } else { + IOT_WARN("Manual Reconnect Failed - %d", rc); + } + } +} + +void parseInputArgsForConnectParams(int argc, char **argv) { + int opt; + + while(-1 != (opt = getopt(argc, argv, "h:p:c:x:"))) { + switch(opt) { + case 'h': + strcpy(HostAddress, optarg); + IOT_DEBUG("Host %s", optarg); + break; + case 'p': + port = atoi(optarg); + IOT_DEBUG("arg %s", optarg); + break; + case 'c': + strcpy(certDirectory, optarg); + IOT_DEBUG("cert root directory %s", optarg); + break; + case 'x': + publishCount = atoi(optarg); + IOT_DEBUG("publish %s times\n", optarg); + break; + case '?': + if(optopt == 'c') { + IOT_ERROR("Option -%c requires an argument.", optopt); + } else if(isprint(optopt)) { + IOT_WARN("Unknown option `-%c'.", optopt); + } else { + IOT_WARN("Unknown option character `\\x%x'.", optopt); + } + break; + default: + IOT_ERROR("Error in command line argument parsing"); + break; + } + } + +} + +int main(int argc, char **argv) { + bool infinitePublishFlag = true; + + char rootCA[PATH_MAX + 1]; + char clientCRT[PATH_MAX + 1]; + char clientKey[PATH_MAX + 1]; + char CurrentWD[PATH_MAX + 1]; + 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; + + parseInputArgsForConnectParams(argc, argv); + + IOT_INFO("\nAWS IoT SDK Version %d.%d.%d-%s\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG); + + getcwd(CurrentWD, sizeof(CurrentWD)); + snprintf(rootCA, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_ROOT_CA_FILENAME); + snprintf(clientCRT, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_CERTIFICATE_FILENAME); + snprintf(clientKey, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_PRIVATE_KEY_FILENAME); + + IOT_DEBUG("rootCA %s", rootCA); + IOT_DEBUG("clientCRT %s", clientCRT); + IOT_DEBUG("clientKey %s", clientKey); + mqttInitParams.enableAutoReconnect = false; // We enable this later below + mqttInitParams.pHostURL = HostAddress; + mqttInitParams.port = port; + mqttInitParams.pRootCALocation = rootCA; + mqttInitParams.pDeviceCertLocation = clientCRT; + mqttInitParams.pDevicePrivateKeyLocation = clientKey; + mqttInitParams.mqttCommandTimeout_ms = 20000; + mqttInitParams.tlsHandshakeTimeout_ms = 5000; + mqttInitParams.isSSLHostnameVerify = true; + mqttInitParams.disconnectHandler = disconnectCallbackHandler; + mqttInitParams.disconnectHandlerData = NULL; + + rc = aws_iot_mqtt_init(&client, &mqttInitParams); + if(SUCCESS != rc) { + IOT_ERROR("aws_iot_mqtt_init returned error : %d ", rc); + return rc; + } + + connectParams.keepAliveIntervalInSec = 600; + connectParams.isCleanSession = true; + connectParams.MQTTVersion = MQTT_3_1_1; + connectParams.pClientID = (char *)AWS_IOT_MQTT_CLIENT_ID; + connectParams.clientIDLen = (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID); + connectParams.isWillMsgPresent = false; + + IOT_INFO("Connecting..."); + rc = aws_iot_mqtt_connect(&client, &connectParams); + if(SUCCESS != rc) { + IOT_ERROR("Error(%d) connecting to %s:%d", rc, mqttInitParams.pHostURL, mqttInitParams.port); + return 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) { + IOT_ERROR("Unable to set Auto Reconnect to true - %d", rc); + return rc; + } + + IOT_INFO("Subscribing..."); + rc = aws_iot_mqtt_subscribe(&client, "sdkTest/sub", 11, QOS0, iot_subscribe_callback_handler, NULL); + if(SUCCESS != rc) { + IOT_ERROR("Error subscribing : %d ", rc); + return rc; + } + + 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; + + if(publishCount != 0) { + infinitePublishFlag = false; + } + + while((NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc) + && (publishCount > 0 || infinitePublishFlag)) { + + //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; + } + + IOT_INFO("-->sleep"); + sleep(1); + sprintf(cPayload, "%s : %d ", "hello from SDK QOS0", i++); + paramsQOS0.payloadLen = strlen(cPayload); + rc = aws_iot_mqtt_publish(&client, "sdkTest/sub", 11, ¶msQOS0); + if(publishCount > 0) { + publishCount--; + } + + sprintf(cPayload, "%s : %d ", "hello from SDK QOS1", i++); + paramsQOS1.payloadLen = strlen(cPayload); + rc = aws_iot_mqtt_publish(&client, "sdkTest/sub", 11, ¶msQOS1); + if (rc == MQTT_REQUEST_TIMEOUT_ERROR) { + IOT_WARN("QOS1 publish ack not received.\n"); + rc = SUCCESS; + } + if(publishCount > 0) { + publishCount--; + } + } + + if(SUCCESS != rc) { + IOT_ERROR("An error occurred in the loop.\n"); + } else { + IOT_INFO("Publish done\n"); + } + + return rc; +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_library_sample/Makefile b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_library_sample/Makefile new file mode 100644 index 00000000..bad28492 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_library_sample/Makefile @@ -0,0 +1,75 @@ +#This target is to ensure accidental execution of Makefile as a bash script will not execute commands like rm in unexpected directories and exit gracefully. +.prevent_execution: + exit 0 + +CC = gcc + +#remove @ for no make command prints +DEBUG = @ + +APP_DIR = . +APP_INCLUDE_DIRS += -I $(APP_DIR) +APP_NAME = subscribe_publish_library_sample +APP_SRC_FILES = $(APP_NAME).c + +#IoT client directory +IOT_CLIENT_DIR = ../../.. + +PLATFORM_DIR = $(IOT_CLIENT_DIR)/platform/linux/mbedtls +PLATFORM_COMMON_DIR = $(IOT_CLIENT_DIR)/platform/linux/common + +IOT_INCLUDE_DIRS += -I $(IOT_CLIENT_DIR)/include +IOT_INCLUDE_DIRS += -I $(IOT_CLIENT_DIR)/external_libs/jsmn +IOT_INCLUDE_DIRS += -I $(PLATFORM_COMMON_DIR) +IOT_INCLUDE_DIRS += -I $(PLATFORM_DIR) + +IOT_SRC_FILES += $(shell find $(IOT_CLIENT_DIR)/src/ -name '*.c') +IOT_SRC_FILES += $(shell find $(IOT_CLIENT_DIR)/external_libs/jsmn -name '*.c') +IOT_SRC_FILES += $(shell find $(PLATFORM_DIR)/ -name '*.c') +IOT_SRC_FILES += $(shell find $(PLATFORM_COMMON_DIR)/ -name '*.c') + +#TLS - mbedtls +MBEDTLS_DIR = $(IOT_CLIENT_DIR)/external_libs/mbedTLS +TLS_LIB_DIR = $(MBEDTLS_DIR)/library +TLS_INCLUDE_DIR = -I $(MBEDTLS_DIR)/include +EXTERNAL_LIBS += -L$(TLS_LIB_DIR) +LD_FLAG += -Wl,-rpath,$(TLS_LIB_DIR) +LD_FLAG += -ldl $(TLS_LIB_DIR)/libmbedtls.a $(TLS_LIB_DIR)/libmbedcrypto.a $(TLS_LIB_DIR)/libmbedx509.a -lpthread + +#Aggregate all include and src directories +INCLUDE_ALL_DIRS += $(IOT_INCLUDE_DIRS) +INCLUDE_ALL_DIRS += $(TLS_INCLUDE_DIR) +INCLUDE_ALL_DIRS += $(APP_INCLUDE_DIRS) + +SRC_FILES += $(IOT_SRC_FILES) + +# Logging level control +LOG_FLAGS += -DENABLE_IOT_DEBUG +LOG_FLAGS += -DENABLE_IOT_INFO +LOG_FLAGS += -DENABLE_IOT_WARN +LOG_FLAGS += -DENABLE_IOT_ERROR + +COMPILER_FLAGS += $(LOG_FLAGS) +#If the processor is big endian uncomment the compiler flag +#COMPILER_FLAGS += -DREVERSED + +MBED_TLS_MAKE_CMD = $(MAKE) -C $(MBEDTLS_DIR) + +PRE_MAKE_CMD = $(MBED_TLS_MAKE_CMD) +MAKE_CMD = $(CC) $(APP_NAME).c $(COMPILER_FLAGS) -o $(APP_NAME) -L. -lAwsIotSdk $(LD_FLAG) $(INCLUDE_ALL_DIRS) + +all: libAwsIotSdk.a + $(PRE_MAKE_CMD) + $(DEBUG)$(MAKE_CMD) + $(POST_MAKE_CMD) + +libAwsIotSdk.a: $(SRC_FILES:.c=.o) + ar rcs $@ $^ + +%.o : %.c + $(CC) -c $< -o $@ $(COMPILER_FLAGS) $(EXTERNAL_LIBS) $(INCLUDE_ALL_DIRS) + +clean: + rm -f $(APP_DIR)/$(APP_NAME) + rm -f $(APP_DIR)/libAwsIotSdk.a + $(MBED_TLS_MAKE_CMD) clean diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_library_sample/aws_iot_config.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_library_sample/aws_iot_config.h new file mode 100644 index 00000000..62abce4a --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_library_sample/aws_iot_config.h @@ -0,0 +1,58 @@ +/* + * 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 SRC_SHADOW_IOT_SHADOW_CONFIG_H_ +#define SRC_SHADOW_IOT_SHADOW_CONFIG_H_ + +// Get from console +// ================================================= +#define AWS_IOT_MQTT_HOST "" ///< Customer specific MQTT HOST. The same will be used for Thing Shadow +#define AWS_IOT_MQTT_PORT 8883 ///< default port for MQTT/S +#define AWS_IOT_MQTT_CLIENT_ID "c-sdk-client-id" ///< MQTT client ID should be unique for every device +#define AWS_IOT_MY_THING_NAME "AWS-IoT-C-SDK" ///< Thing Name of the Shadow this device is associated with +#define AWS_IOT_ROOT_CA_FILENAME "rootCA.crt" ///< Root CA file name +#define AWS_IOT_CERTIFICATE_FILENAME "cert.pem" ///< device signed certificate file name +#define AWS_IOT_PRIVATE_KEY_FILENAME "privkey.pem" ///< Device private key filename +// ================================================= + +// 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, including terminating NULL byte. +#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 format $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. + +#define DISABLE_METRICS false ///< Disable the collection of metrics by setting this to true + +#endif /* SRC_SHADOW_IOT_SHADOW_CONFIG_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_library_sample/subscribe_publish_library_sample.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_library_sample/subscribe_publish_library_sample.c new file mode 100644 index 00000000..b4c29293 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_library_sample/subscribe_publish_library_sample.c @@ -0,0 +1,262 @@ +/* + * 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 subscribe_publish_library_sample.c + * @brief simple MQTT publish and subscribe on the same topic using the SDK as a library + * + * This example takes the parameters from the aws_iot_config.h file and establishes a connection to the AWS IoT MQTT Platform. + * It subscribes and publishes to the same topic - "sdkTest/sub" + * + * If all the certs are correct, you should see the messages received by the application in a loop. + * + * The application takes in the certificate path, host name , port and the number of times the publish should happen. + * + */ +#include +#include +#include +#include +#include +#include + +#include "aws_iot_config.h" +#include "aws_iot_log.h" +#include "aws_iot_version.h" +#include "aws_iot_mqtt_client_interface.h" + +/** + * @brief Default cert location + */ +char certDirectory[PATH_MAX + 1] = "../../../certs"; + +/** + * @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; + +/** + * @brief This parameter will avoid infinite loop of publish and exit the program after certain number of publishes + */ +uint32_t publishCount = 0; + +void iot_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, + IoT_Publish_Message_Params *params, void *pData) { + IOT_UNUSED(pData); + IOT_UNUSED(pClient); + IOT_INFO("Subscribe callback"); + IOT_INFO("%.*s\t%.*s", topicNameLen, topicName, (int) params->payloadLen, params->payload); +} + +void disconnectCallbackHandler(AWS_IoT_Client *pClient, void *data) { + IOT_WARN("MQTT Disconnect"); + IoT_Error_t rc = FAILURE; + + if(NULL == pClient) { + return; + } + + IOT_UNUSED(data); + + if(aws_iot_is_autoreconnect_enabled(pClient)) { + IOT_INFO("Auto Reconnect is enabled, Reconnecting attempt will start now"); + } else { + IOT_WARN("Auto Reconnect not enabled. Starting manual reconnect..."); + rc = aws_iot_mqtt_attempt_reconnect(pClient); + if(NETWORK_RECONNECTED == rc) { + IOT_WARN("Manual Reconnect Successful"); + } else { + IOT_WARN("Manual Reconnect Failed - %d", rc); + } + } +} + +void parseInputArgsForConnectParams(int argc, char **argv) { + int opt; + + while(-1 != (opt = getopt(argc, argv, "h:p:c:x:"))) { + switch(opt) { + case 'h': + strcpy(HostAddress, optarg); + IOT_DEBUG("Host %s", optarg); + break; + case 'p': + port = atoi(optarg); + IOT_DEBUG("arg %s", optarg); + break; + case 'c': + strcpy(certDirectory, optarg); + IOT_DEBUG("cert root directory %s", optarg); + break; + case 'x': + publishCount = atoi(optarg); + IOT_DEBUG("publish %s times\n", optarg); + break; + case '?': + if(optopt == 'c') { + IOT_ERROR("Option -%c requires an argument.", optopt); + } else if(isprint(optopt)) { + IOT_WARN("Unknown option `-%c'.", optopt); + } else { + IOT_WARN("Unknown option character `\\x%x'.", optopt); + } + break; + default: + IOT_ERROR("Error in command line argument parsing"); + break; + } + } + +} + +int main(int argc, char **argv) { + bool infinitePublishFlag = true; + + char rootCA[PATH_MAX + 1]; + char clientCRT[PATH_MAX + 1]; + char clientKey[PATH_MAX + 1]; + char CurrentWD[PATH_MAX + 1]; + 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; + + parseInputArgsForConnectParams(argc, argv); + + IOT_INFO("\nAWS IoT SDK Version %d.%d.%d-%s\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG); + + getcwd(CurrentWD, sizeof(CurrentWD)); + snprintf(rootCA, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_ROOT_CA_FILENAME); + snprintf(clientCRT, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_CERTIFICATE_FILENAME); + snprintf(clientKey, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_PRIVATE_KEY_FILENAME); + + IOT_DEBUG("rootCA %s", rootCA); + IOT_DEBUG("clientCRT %s", clientCRT); + IOT_DEBUG("clientKey %s", clientKey); + mqttInitParams.enableAutoReconnect = false; // We enable this later below + mqttInitParams.pHostURL = HostAddress; + mqttInitParams.port = port; + mqttInitParams.pRootCALocation = rootCA; + mqttInitParams.pDeviceCertLocation = clientCRT; + mqttInitParams.pDevicePrivateKeyLocation = clientKey; + mqttInitParams.mqttCommandTimeout_ms = 20000; + mqttInitParams.tlsHandshakeTimeout_ms = 5000; + mqttInitParams.isSSLHostnameVerify = true; + mqttInitParams.disconnectHandler = disconnectCallbackHandler; + mqttInitParams.disconnectHandlerData = NULL; + + rc = aws_iot_mqtt_init(&client, &mqttInitParams); + if(SUCCESS != rc) { + IOT_ERROR("aws_iot_mqtt_init returned error : %d ", rc); + return rc; + } + + connectParams.keepAliveIntervalInSec = 600; + connectParams.isCleanSession = true; + connectParams.MQTTVersion = MQTT_3_1_1; + connectParams.pClientID = AWS_IOT_MQTT_CLIENT_ID; + connectParams.clientIDLen = (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID); + connectParams.isWillMsgPresent = false; + + IOT_INFO("Connecting..."); + rc = aws_iot_mqtt_connect(&client, &connectParams); + if(SUCCESS != rc) { + IOT_ERROR("Error(%d) connecting to %s:%d", rc, mqttInitParams.pHostURL, mqttInitParams.port); + return 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) { + IOT_ERROR("Unable to set Auto Reconnect to true - %d", rc); + return rc; + } + + IOT_INFO("Subscribing..."); + rc = aws_iot_mqtt_subscribe(&client, "sdkTest/sub", 11, QOS0, iot_subscribe_callback_handler, NULL); + if(SUCCESS != rc) { + IOT_ERROR("Error subscribing : %d ", rc); + return rc; + } + + 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; + + if(publishCount != 0) { + infinitePublishFlag = false; + } + + while((NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc) + && (publishCount > 0 || infinitePublishFlag)) { + + //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; + } + + IOT_INFO("-->sleep"); + sleep(1); + sprintf(cPayload, "%s : %d ", "hello from SDK QOS0", i++); + paramsQOS0.payloadLen = strlen(cPayload); + rc = aws_iot_mqtt_publish(&client, "sdkTest/sub", 11, ¶msQOS0); + if(publishCount > 0) { + publishCount--; + } + + sprintf(cPayload, "%s : %d ", "hello from SDK QOS1", i++); + paramsQOS1.payloadLen = strlen(cPayload); + rc = aws_iot_mqtt_publish(&client, "sdkTest/sub", 11, ¶msQOS1); + if (rc == MQTT_REQUEST_TIMEOUT_ERROR) { + IOT_WARN("QOS1 publish ack not received.\n"); + rc = SUCCESS; + } + if(publishCount > 0) { + publishCount--; + } + } + + if(SUCCESS != rc) { + IOT_ERROR("An error occurred in the loop.\n"); + } else { + IOT_INFO("Publish done\n"); + } + + return rc; +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_sample/Makefile b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_sample/Makefile new file mode 100644 index 00000000..4b323910 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_sample/Makefile @@ -0,0 +1,69 @@ +#This target is to ensure accidental execution of Makefile as a bash script will not execute commands like rm in unexpected directories and exit gracefully. +.prevent_execution: + exit 0 + +CC = gcc + +#remove @ for no make command prints +DEBUG = @ + +APP_DIR = . +APP_INCLUDE_DIRS += -I $(APP_DIR) +APP_NAME = subscribe_publish_sample +APP_SRC_FILES = $(APP_NAME).c + +#IoT client directory +IOT_CLIENT_DIR = ../../.. + +PLATFORM_DIR = $(IOT_CLIENT_DIR)/platform/linux/mbedtls +PLATFORM_COMMON_DIR = $(IOT_CLIENT_DIR)/platform/linux/common + +IOT_INCLUDE_DIRS += -I $(IOT_CLIENT_DIR)/include +IOT_INCLUDE_DIRS += -I $(IOT_CLIENT_DIR)/external_libs/jsmn +IOT_INCLUDE_DIRS += -I $(PLATFORM_COMMON_DIR) +IOT_INCLUDE_DIRS += -I $(PLATFORM_DIR) + +IOT_SRC_FILES += $(shell find $(IOT_CLIENT_DIR)/src/ -name '*.c') +IOT_SRC_FILES += $(shell find $(IOT_CLIENT_DIR)/external_libs/jsmn -name '*.c') +IOT_SRC_FILES += $(shell find $(PLATFORM_DIR)/ -name '*.c') +IOT_SRC_FILES += $(shell find $(PLATFORM_COMMON_DIR)/ -name '*.c') + +#TLS - mbedtls +MBEDTLS_DIR = $(IOT_CLIENT_DIR)/external_libs/mbedTLS +TLS_LIB_DIR = $(MBEDTLS_DIR)/library +TLS_INCLUDE_DIR = -I $(MBEDTLS_DIR)/include +EXTERNAL_LIBS += -L$(TLS_LIB_DIR) +LD_FLAG += -Wl,-rpath,$(TLS_LIB_DIR) +LD_FLAG += -ldl $(TLS_LIB_DIR)/libmbedtls.a $(TLS_LIB_DIR)/libmbedcrypto.a $(TLS_LIB_DIR)/libmbedx509.a -lpthread + +#Aggregate all include and src directories +INCLUDE_ALL_DIRS += $(IOT_INCLUDE_DIRS) +INCLUDE_ALL_DIRS += $(TLS_INCLUDE_DIR) +INCLUDE_ALL_DIRS += $(APP_INCLUDE_DIRS) + +SRC_FILES += $(APP_SRC_FILES) +SRC_FILES += $(IOT_SRC_FILES) + +# Logging level control +LOG_FLAGS += -DENABLE_IOT_DEBUG +LOG_FLAGS += -DENABLE_IOT_INFO +LOG_FLAGS += -DENABLE_IOT_WARN +LOG_FLAGS += -DENABLE_IOT_ERROR + +COMPILER_FLAGS += $(LOG_FLAGS) +#If the processor is big endian uncomment the compiler flag +#COMPILER_FLAGS += -DREVERSED + +MBED_TLS_MAKE_CMD = $(MAKE) -C $(MBEDTLS_DIR) + +PRE_MAKE_CMD = $(MBED_TLS_MAKE_CMD) +MAKE_CMD = $(CC) $(SRC_FILES) $(COMPILER_FLAGS) -o $(APP_NAME) $(LD_FLAG) $(EXTERNAL_LIBS) $(INCLUDE_ALL_DIRS) + +all: + $(PRE_MAKE_CMD) + $(DEBUG)$(MAKE_CMD) + $(POST_MAKE_CMD) + +clean: + rm -f $(APP_DIR)/$(APP_NAME) + $(MBED_TLS_MAKE_CMD) clean diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_sample/aws_iot_config.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_sample/aws_iot_config.h new file mode 100644 index 00000000..62abce4a --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_sample/aws_iot_config.h @@ -0,0 +1,58 @@ +/* + * 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 SRC_SHADOW_IOT_SHADOW_CONFIG_H_ +#define SRC_SHADOW_IOT_SHADOW_CONFIG_H_ + +// Get from console +// ================================================= +#define AWS_IOT_MQTT_HOST "" ///< Customer specific MQTT HOST. The same will be used for Thing Shadow +#define AWS_IOT_MQTT_PORT 8883 ///< default port for MQTT/S +#define AWS_IOT_MQTT_CLIENT_ID "c-sdk-client-id" ///< MQTT client ID should be unique for every device +#define AWS_IOT_MY_THING_NAME "AWS-IoT-C-SDK" ///< Thing Name of the Shadow this device is associated with +#define AWS_IOT_ROOT_CA_FILENAME "rootCA.crt" ///< Root CA file name +#define AWS_IOT_CERTIFICATE_FILENAME "cert.pem" ///< device signed certificate file name +#define AWS_IOT_PRIVATE_KEY_FILENAME "privkey.pem" ///< Device private key filename +// ================================================= + +// 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, including terminating NULL byte. +#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 format $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. + +#define DISABLE_METRICS false ///< Disable the collection of metrics by setting this to true + +#endif /* SRC_SHADOW_IOT_SHADOW_CONFIG_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_sample/subscribe_publish_sample.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_sample/subscribe_publish_sample.c new file mode 100644 index 00000000..5d4e968d --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_sample/subscribe_publish_sample.c @@ -0,0 +1,269 @@ +/* + * 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 subscribe_publish_sample.c + * @brief simple MQTT publish and subscribe on the same topic + * + * This example takes the parameters from the aws_iot_config.h file and establishes a connection to the AWS IoT MQTT Platform. + * It subscribes and publishes to the same topic - "sdkTest/sub" + * + * If all the certs are correct, you should see the messages received by the application in a loop. + * + * The application takes in the certificate path, host name , port and the number of times the publish should happen. + * + */ +#include +#include +#include +#include +#include +#include + +#include "aws_iot_config.h" +#include "aws_iot_log.h" +#include "aws_iot_version.h" +#include "aws_iot_mqtt_client_interface.h" + +/** + * @brief Default cert location + */ +char certDirectory[PATH_MAX + 1] = "../../../certs"; + +/** + * @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; + +/** + * @brief This parameter will avoid infinite loop of publish and exit the program after certain number of publishes + */ +uint32_t publishCount = 0; + +void iot_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, + IoT_Publish_Message_Params *params, void *pData) { + IOT_UNUSED(pData); + IOT_UNUSED(pClient); + IOT_INFO("Subscribe callback"); + IOT_INFO("%.*s\t%.*s", topicNameLen, topicName, (int) params->payloadLen, params->payload); +} + +void disconnectCallbackHandler(AWS_IoT_Client *pClient, void *data) { + IOT_WARN("MQTT Disconnect"); + IoT_Error_t rc = FAILURE; + + if(NULL == pClient) { + return; + } + + IOT_UNUSED(data); + + if(aws_iot_is_autoreconnect_enabled(pClient)) { + IOT_INFO("Auto Reconnect is enabled, Reconnecting attempt will start now"); + } else { + IOT_WARN("Auto Reconnect not enabled. Starting manual reconnect..."); + rc = aws_iot_mqtt_attempt_reconnect(pClient); + if(NETWORK_RECONNECTED == rc) { + IOT_WARN("Manual Reconnect Successful"); + } else { + IOT_WARN("Manual Reconnect Failed - %d", rc); + } + } +} + +void parseInputArgsForConnectParams(int argc, char **argv) { + int opt; + + while(-1 != (opt = getopt(argc, argv, "h:p:c:x:"))) { + switch(opt) { + case 'h': + strcpy(HostAddress, optarg); + IOT_DEBUG("Host %s", optarg); + break; + case 'p': + port = atoi(optarg); + IOT_DEBUG("arg %s", optarg); + break; + case 'c': + strcpy(certDirectory, optarg); + IOT_DEBUG("cert root directory %s", optarg); + break; + case 'x': + publishCount = atoi(optarg); + IOT_DEBUG("publish %s times\n", optarg); + break; + case '?': + if(optopt == 'c') { + IOT_ERROR("Option -%c requires an argument.", optopt); + } else if(isprint(optopt)) { + IOT_WARN("Unknown option `-%c'.", optopt); + } else { + IOT_WARN("Unknown option character `\\x%x'.", optopt); + } + break; + default: + IOT_ERROR("Error in command line argument parsing"); + break; + } + } + +} + +int main(int argc, char **argv) { + bool infinitePublishFlag = true; + + char rootCA[PATH_MAX + 1]; + char clientCRT[PATH_MAX + 1]; + char clientKey[PATH_MAX + 1]; + char CurrentWD[PATH_MAX + 1]; + 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; + + parseInputArgsForConnectParams(argc, argv); + + IOT_INFO("\nAWS IoT SDK Version %d.%d.%d-%s\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG); + + getcwd(CurrentWD, sizeof(CurrentWD)); + snprintf(rootCA, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_ROOT_CA_FILENAME); + snprintf(clientCRT, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_CERTIFICATE_FILENAME); + snprintf(clientKey, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_PRIVATE_KEY_FILENAME); + + IOT_DEBUG("rootCA %s", rootCA); + IOT_DEBUG("clientCRT %s", clientCRT); + IOT_DEBUG("clientKey %s", clientKey); + mqttInitParams.enableAutoReconnect = false; // We enable this later below + mqttInitParams.pHostURL = HostAddress; + mqttInitParams.port = port; + mqttInitParams.pRootCALocation = rootCA; + mqttInitParams.pDeviceCertLocation = clientCRT; + mqttInitParams.pDevicePrivateKeyLocation = clientKey; + mqttInitParams.mqttCommandTimeout_ms = 20000; + mqttInitParams.tlsHandshakeTimeout_ms = 5000; + mqttInitParams.isSSLHostnameVerify = true; + mqttInitParams.disconnectHandler = disconnectCallbackHandler; + mqttInitParams.disconnectHandlerData = NULL; + + rc = aws_iot_mqtt_init(&client, &mqttInitParams); + if(SUCCESS != rc) { + IOT_ERROR("aws_iot_mqtt_init returned error : %d ", rc); + return rc; + } + + connectParams.keepAliveIntervalInSec = 600; + connectParams.isCleanSession = true; + connectParams.MQTTVersion = MQTT_3_1_1; + connectParams.pClientID = AWS_IOT_MQTT_CLIENT_ID; + connectParams.clientIDLen = (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID); + connectParams.isWillMsgPresent = false; + + IOT_INFO("Connecting..."); + rc = aws_iot_mqtt_connect(&client, &connectParams); + if(SUCCESS != rc) { + IOT_ERROR("Error(%d) connecting to %s:%d", rc, mqttInitParams.pHostURL, mqttInitParams.port); + return 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) { + IOT_ERROR("Unable to set Auto Reconnect to true - %d", rc); + return rc; + } + + IOT_INFO("Subscribing..."); + rc = aws_iot_mqtt_subscribe(&client, "sdkTest/sub", 11, QOS0, iot_subscribe_callback_handler, NULL); + if(SUCCESS != rc) { + IOT_ERROR("Error subscribing : %d ", rc); + return rc; + } + + 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; + + if(publishCount != 0) { + infinitePublishFlag = false; + } + + while((NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc) + && (publishCount > 0 || infinitePublishFlag)) { + + //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; + } + + IOT_INFO("-->sleep"); + sleep(1); + sprintf(cPayload, "%s : %d ", "hello from SDK QOS0", i++); + paramsQOS0.payloadLen = strlen(cPayload); + rc = aws_iot_mqtt_publish(&client, "sdkTest/sub", 11, ¶msQOS0); + if(publishCount > 0) { + publishCount--; + } + + if(publishCount == 0 && !infinitePublishFlag) { + break; + } + + sprintf(cPayload, "%s : %d ", "hello from SDK QOS1", i++); + paramsQOS1.payloadLen = strlen(cPayload); + rc = aws_iot_mqtt_publish(&client, "sdkTest/sub", 11, ¶msQOS1); + if (rc == MQTT_REQUEST_TIMEOUT_ERROR) { + IOT_WARN("QOS1 publish ack not received.\n"); + rc = SUCCESS; + } + if(publishCount > 0) { + publishCount--; + } + } + + // Wait for all the messages to be received + aws_iot_mqtt_yield(&client, 100); + + if(SUCCESS != rc) { + IOT_ERROR("An error occurred in the loop.\n"); + } else { + IOT_INFO("Publish done\n"); + } + + return rc; +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_json_utils.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_json_utils.c new file mode 100644 index 00000000..1614eb26 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_json_utils.c @@ -0,0 +1,219 @@ +/* + * 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_json_utils.c + * @brief Utilities for manipulating JSON + * + * json_utils provides JSON parsing utilities for use with the IoT SDK. + * Underlying JSON parsing relies on the Jasmine JSON parser. + * + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "aws_iot_json_utils.h" + +#include +#include +#include + +#ifdef __cplusplus +#include +#else + +#include + +#endif + +#include "aws_iot_log.h" + +int8_t jsoneq(const char *json, jsmntok_t *tok, const char *s) { + if(tok->type == JSMN_STRING) { + if((int) strlen(s) == tok->end - tok->start) { + if(strncmp(json + tok->start, s, (size_t) (tok->end - tok->start)) == 0) { + return 0; + } + } + } + return -1; +} + +IoT_Error_t parseUnsignedInteger32Value(uint32_t *i, const char *jsonString, jsmntok_t *token) { + if(token->type != JSMN_PRIMITIVE) { + IOT_WARN("Token was not an integer"); + return JSON_PARSE_ERROR; + } + + if(('-' == (char) (jsonString[token->start])) || (1 != sscanf(jsonString + token->start, "%" SCNu32, i))) { + IOT_WARN("Token was not an unsigned integer."); + return JSON_PARSE_ERROR; + } + + return SUCCESS; +} + +IoT_Error_t parseUnsignedInteger16Value(uint16_t *i, const char *jsonString, jsmntok_t *token) { + if(token->type != JSMN_PRIMITIVE) { + IOT_WARN("Token was not an integer"); + return JSON_PARSE_ERROR; + } + + if(('-' == (char) (jsonString[token->start])) || (1 != sscanf(jsonString + token->start, "%" SCNu16, i))) { + IOT_WARN("Token was not an unsigned integer."); + return JSON_PARSE_ERROR; + } + + return SUCCESS; +} + +IoT_Error_t parseUnsignedInteger8Value(uint8_t *i, const char *jsonString, jsmntok_t *token) { + if(token->type != JSMN_PRIMITIVE) { + IOT_WARN("Token was not an integer"); + return JSON_PARSE_ERROR; + } + + uint32_t i_word; + if(('-' == (char) (jsonString[token->start])) || (1 != sscanf(jsonString + token->start, "%" SCNu32, &i_word))) { + IOT_WARN("Token was not an unsigned integer."); + return JSON_PARSE_ERROR; + } + if (i_word > UINT8_MAX) { + IOT_WARN("Token value %u exceeds 8 bits", i_word); + return JSON_PARSE_ERROR; + } + *i = i_word; + + return SUCCESS; +} + +IoT_Error_t parseInteger32Value(int32_t *i, const char *jsonString, jsmntok_t *token) { + if(token->type != JSMN_PRIMITIVE) { + IOT_WARN("Token was not an integer"); + return JSON_PARSE_ERROR; + } + + if(1 != sscanf(jsonString + token->start, "%" SCNi32, i)) { + IOT_WARN("Token was not an integer."); + return JSON_PARSE_ERROR; + } + + return SUCCESS; +} + +IoT_Error_t parseInteger16Value(int16_t *i, const char *jsonString, jsmntok_t *token) { + if(token->type != JSMN_PRIMITIVE) { + IOT_WARN("Token was not an integer"); + return JSON_PARSE_ERROR; + } + + int32_t i_word; + if(1 != sscanf(jsonString + token->start, "%" SCNi32, &i_word)) { + IOT_WARN("Token was not an integer."); + return JSON_PARSE_ERROR; + } + if(i_word < INT16_MIN || i_word > INT16_MAX) { + IOT_WARN("Token value %d out of range for 16-bit int", i_word); + return JSON_PARSE_ERROR; + } + *i = i_word; + + return SUCCESS; +} + +IoT_Error_t parseInteger8Value(int8_t *i, const char *jsonString, jsmntok_t *token) { + if(token->type != JSMN_PRIMITIVE) { + IOT_WARN("Token was not an integer"); + return JSON_PARSE_ERROR; + } + + int32_t i_word; + if(1 != sscanf(jsonString + token->start, "%" SCNi32, &i_word)) { + IOT_WARN("Token was not an integer."); + return JSON_PARSE_ERROR; + } + if(i_word < INT8_MIN || i_word > INT8_MAX) { + IOT_WARN("Token value %d out of range for 8-bit int", i_word); + return JSON_PARSE_ERROR; + } + *i = i_word; + + return SUCCESS; +} + +IoT_Error_t parseFloatValue(float *f, const char *jsonString, jsmntok_t *token) { + if(token->type != JSMN_PRIMITIVE) { + IOT_WARN("Token was not a float."); + return JSON_PARSE_ERROR; + } + + if(1 != sscanf(jsonString + token->start, "%f", f)) { + IOT_WARN("Token was not a float."); + return JSON_PARSE_ERROR; + } + + return SUCCESS; +} + +IoT_Error_t parseDoubleValue(double *d, const char *jsonString, jsmntok_t *token) { + if(token->type != JSMN_PRIMITIVE) { + IOT_WARN("Token was not a double."); + return JSON_PARSE_ERROR; + } + + if(1 != sscanf(jsonString + token->start, "%lf", d)) { + IOT_WARN("Token was not a double."); + return JSON_PARSE_ERROR; + } + + return SUCCESS; +} + +IoT_Error_t parseBooleanValue(bool *b, const char *jsonString, jsmntok_t *token) { + if(token->type != JSMN_PRIMITIVE) { + IOT_WARN("Token was not a primitive."); + return JSON_PARSE_ERROR; + } + if(jsonString[token->start] == 't' && jsonString[token->start + 1] == 'r' && jsonString[token->start + 2] == 'u' + && jsonString[token->start + 3] == 'e') { + *b = true; + } else if(jsonString[token->start] == 'f' && jsonString[token->start + 1] == 'a' + && jsonString[token->start + 2] == 'l' && jsonString[token->start + 3] == 's' + && jsonString[token->start + 4] == 'e') { + *b = false; + } else { + IOT_WARN("Token was not a bool."); + return JSON_PARSE_ERROR; + } + return SUCCESS; +} + +IoT_Error_t parseStringValue(char *buf, const char *jsonString, jsmntok_t *token) { + uint16_t size = 0; + if(token->type != JSMN_STRING) { + IOT_WARN("Token was not a string."); + return JSON_PARSE_ERROR; + } + size = (uint16_t) (token->end - token->start); + memcpy(buf, jsonString + token->start, size); + buf[size] = '\0'; + return SUCCESS; +} + +#ifdef __cplusplus +} +#endif diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client.c new file mode 100644 index 00000000..5ea0f75b --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client.c @@ -0,0 +1,327 @@ +/* +* Copyright 2015-2016 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. +*/ + +// Based on Eclipse Paho. +/******************************************************************************* + * Copyright (c) 2014 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * Contributors: + * Allan Stockdill-Mander/Ian Craggs - initial API and implementation and/or initial documentation + *******************************************************************************/ + +/** + * @file aws_iot_mqtt_client.c + * @brief MQTT client API definitions + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#include "aws_iot_log.h" +#include "aws_iot_mqtt_client_interface.h" +#include "aws_iot_version.h" + +#if !DISABLE_METRICS +#define SDK_METRICS_LEN 25 +#define SDK_METRICS_TEMPLATE "?SDK=C&Version=%d.%d.%d" +static char pUsernameTemp[SDK_METRICS_LEN] = {0}; +#endif + +#ifdef _ENABLE_THREAD_SUPPORT_ +#include "threads_interface.h" +#endif + +const IoT_Client_Init_Params iotClientInitParamsDefault = IoT_Client_Init_Params_initializer; +const IoT_MQTT_Will_Options iotMqttWillOptionsDefault = IoT_MQTT_Will_Options_Initializer; +const IoT_Client_Connect_Params iotClientConnectParamsDefault = IoT_Client_Connect_Params_initializer; + +ClientState aws_iot_mqtt_get_client_state(AWS_IoT_Client *pClient) { + FUNC_ENTRY; + if(NULL == pClient) { + return CLIENT_STATE_INVALID; + } + + FUNC_EXIT_RC(pClient->clientStatus.clientState); +} + +#ifdef _ENABLE_THREAD_SUPPORT_ +IoT_Error_t aws_iot_mqtt_client_lock_mutex(AWS_IoT_Client *pClient, IoT_Mutex_t *pMutex) { + FUNC_ENTRY; + IoT_Error_t threadRc = FAILURE; + + if(NULL == pClient || NULL == pMutex){ + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + if(false == pClient->clientData.isBlockOnThreadLockEnabled) { + threadRc = aws_iot_thread_mutex_trylock(pMutex); + } else { + threadRc = aws_iot_thread_mutex_lock(pMutex); + /* Should never return Error because the above request blocks until lock is obtained */ + } + + if(SUCCESS != threadRc) { + FUNC_EXIT_RC(threadRc); + } + + FUNC_EXIT_RC(SUCCESS); +} + +IoT_Error_t aws_iot_mqtt_client_unlock_mutex(AWS_IoT_Client *pClient, IoT_Mutex_t *pMutex) { + if(NULL == pClient || NULL == pMutex) { + return NULL_VALUE_ERROR; + } + IOT_UNUSED(pClient); + return aws_iot_thread_mutex_unlock(pMutex); +} +#endif + +IoT_Error_t aws_iot_mqtt_set_client_state(AWS_IoT_Client *pClient, ClientState expectedCurrentState, + ClientState newState) { + IoT_Error_t rc; +#ifdef _ENABLE_THREAD_SUPPORT_ + IoT_Error_t threadRc = FAILURE; +#endif + + FUNC_ENTRY; + if(NULL == pClient) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + +#ifdef _ENABLE_THREAD_SUPPORT_ + rc = aws_iot_mqtt_client_lock_mutex(pClient, &(pClient->clientData.state_change_mutex)); + if(SUCCESS != rc) { + return rc; + } +#endif + if(expectedCurrentState == aws_iot_mqtt_get_client_state(pClient)) { + pClient->clientStatus.clientState = newState; + rc = SUCCESS; + } else { + rc = MQTT_UNEXPECTED_CLIENT_STATE_ERROR; + } + +#ifdef _ENABLE_THREAD_SUPPORT_ + threadRc = aws_iot_mqtt_client_unlock_mutex(pClient, &(pClient->clientData.state_change_mutex)); + if(SUCCESS == rc && SUCCESS != threadRc) { + rc = threadRc; + } +#endif + + FUNC_EXIT_RC(rc); +} + +IoT_Error_t aws_iot_mqtt_set_connect_params(AWS_IoT_Client *pClient, const IoT_Client_Connect_Params *pNewConnectParams) { + FUNC_ENTRY; + if(NULL == pClient || NULL == pNewConnectParams) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + pClient->clientData.options.isWillMsgPresent = pNewConnectParams->isWillMsgPresent; + pClient->clientData.options.MQTTVersion = pNewConnectParams->MQTTVersion; + pClient->clientData.options.pClientID = pNewConnectParams->pClientID; + pClient->clientData.options.clientIDLen = pNewConnectParams->clientIDLen; +#if !DISABLE_METRICS + if (0 == strlen(pUsernameTemp)) { + snprintf(pUsernameTemp, SDK_METRICS_LEN, SDK_METRICS_TEMPLATE, VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH); + } + pClient->clientData.options.pUsername = (char*)&pUsernameTemp[0]; + pClient->clientData.options.usernameLen = strlen(pUsernameTemp); +#else + pClient->clientData.options.pUsername = pNewConnectParams->pUsername; + pClient->clientData.options.usernameLen = pNewConnectParams->usernameLen; +#endif + pClient->clientData.options.pPassword = pNewConnectParams->pPassword; + pClient->clientData.options.passwordLen = pNewConnectParams->passwordLen; + pClient->clientData.options.will.pTopicName = pNewConnectParams->will.pTopicName; + pClient->clientData.options.will.topicNameLen = pNewConnectParams->will.topicNameLen; + pClient->clientData.options.will.pMessage = pNewConnectParams->will.pMessage; + pClient->clientData.options.will.msgLen = pNewConnectParams->will.msgLen; + pClient->clientData.options.will.qos = pNewConnectParams->will.qos; + pClient->clientData.options.will.isRetained = pNewConnectParams->will.isRetained; + pClient->clientData.options.keepAliveIntervalInSec = pNewConnectParams->keepAliveIntervalInSec; + pClient->clientData.options.isCleanSession = pNewConnectParams->isCleanSession; + + FUNC_EXIT_RC(SUCCESS); +} + +IoT_Error_t aws_iot_mqtt_init(AWS_IoT_Client *pClient, const IoT_Client_Init_Params *pInitParams) { + uint32_t i; + IoT_Error_t rc; + IoT_Client_Connect_Params default_options = IoT_Client_Connect_Params_initializer; + + FUNC_ENTRY; + + if(NULL == pClient || NULL == pInitParams || NULL == pInitParams->pHostURL || 0 == pInitParams->port || + NULL == pInitParams->pRootCALocation || NULL == pInitParams->pDevicePrivateKeyLocation || + NULL == pInitParams->pDeviceCertLocation) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + for(i = 0; i < AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; ++i) { + pClient->clientData.messageHandlers[i].topicName = NULL; + pClient->clientData.messageHandlers[i].pApplicationHandler = NULL; + pClient->clientData.messageHandlers[i].pApplicationHandlerData = NULL; + pClient->clientData.messageHandlers[i].qos = QOS0; + } + + pClient->clientData.packetTimeoutMs = pInitParams->mqttPacketTimeout_ms; + pClient->clientData.commandTimeoutMs = pInitParams->mqttCommandTimeout_ms; + pClient->clientData.writeBufSize = AWS_IOT_MQTT_TX_BUF_LEN; + pClient->clientData.readBufSize = AWS_IOT_MQTT_RX_BUF_LEN; + pClient->clientData.counterNetworkDisconnected = 0; + pClient->clientData.disconnectHandler = pInitParams->disconnectHandler; + pClient->clientData.disconnectHandlerData = pInitParams->disconnectHandlerData; + pClient->clientData.nextPacketId = 1; + + /* Initialize default connection options */ + rc = aws_iot_mqtt_set_connect_params(pClient, &default_options); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + +#ifdef _ENABLE_THREAD_SUPPORT_ + pClient->clientData.isBlockOnThreadLockEnabled = pInitParams->isBlockOnThreadLockEnabled; + rc = aws_iot_thread_mutex_init(&(pClient->clientData.state_change_mutex)); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + rc = aws_iot_thread_mutex_init(&(pClient->clientData.tls_read_mutex)); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + rc = aws_iot_thread_mutex_init(&(pClient->clientData.tls_write_mutex)); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } +#endif + + pClient->clientStatus.isPingOutstanding = 0; + pClient->clientStatus.isAutoReconnectEnabled = pInitParams->enableAutoReconnect; + + rc = iot_tls_init(&(pClient->networkStack), pInitParams->pRootCALocation, pInitParams->pDeviceCertLocation, + pInitParams->pDevicePrivateKeyLocation, pInitParams->pHostURL, pInitParams->port, + pInitParams->tlsHandshakeTimeout_ms, pInitParams->isSSLHostnameVerify); + + if(SUCCESS != rc) { + pClient->clientStatus.clientState = CLIENT_STATE_INVALID; + FUNC_EXIT_RC(rc); + } + + init_timer(&(pClient->pingTimer)); + init_timer(&(pClient->reconnectDelayTimer)); + + pClient->clientStatus.clientState = CLIENT_STATE_INITIALIZED; + + FUNC_EXIT_RC(SUCCESS); +} + +uint16_t aws_iot_mqtt_get_next_packet_id(AWS_IoT_Client *pClient) { + return pClient->clientData.nextPacketId = (uint16_t) ((MAX_PACKET_ID == pClient->clientData.nextPacketId) ? 1 : ( + pClient->clientData.nextPacketId + 1)); +} + +bool aws_iot_mqtt_is_client_connected(AWS_IoT_Client *pClient) { + bool isConnected; + + FUNC_ENTRY; + + if(NULL == pClient) { + IOT_WARN(" Client is null! "); + FUNC_EXIT_RC(false); + } + + switch(pClient->clientStatus.clientState) { + case CLIENT_STATE_INVALID: + case CLIENT_STATE_INITIALIZED: + case CLIENT_STATE_CONNECTING: + isConnected = false; + break; + case CLIENT_STATE_CONNECTED_IDLE: + case CLIENT_STATE_CONNECTED_YIELD_IN_PROGRESS: + case CLIENT_STATE_CONNECTED_PUBLISH_IN_PROGRESS: + case CLIENT_STATE_CONNECTED_SUBSCRIBE_IN_PROGRESS: + case CLIENT_STATE_CONNECTED_UNSUBSCRIBE_IN_PROGRESS: + case CLIENT_STATE_CONNECTED_RESUBSCRIBE_IN_PROGRESS: + case CLIENT_STATE_CONNECTED_WAIT_FOR_CB_RETURN: + isConnected = true; + break; + case CLIENT_STATE_DISCONNECTING: + case CLIENT_STATE_DISCONNECTED_ERROR: + case CLIENT_STATE_DISCONNECTED_MANUALLY: + case CLIENT_STATE_PENDING_RECONNECT: + default: + isConnected = false; + break; + } + + FUNC_EXIT_RC(isConnected); +} + +bool aws_iot_is_autoreconnect_enabled(AWS_IoT_Client *pClient) { + FUNC_ENTRY; + if(NULL == pClient) { + IOT_WARN(" Client is null! "); + FUNC_EXIT_RC(false); + } + + FUNC_EXIT_RC(pClient->clientStatus.isAutoReconnectEnabled); +} + +IoT_Error_t aws_iot_mqtt_autoreconnect_set_status(AWS_IoT_Client *pClient, bool newStatus) { + FUNC_ENTRY; + if(NULL == pClient) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + pClient->clientStatus.isAutoReconnectEnabled = newStatus; + FUNC_EXIT_RC(SUCCESS); +} + +IoT_Error_t aws_iot_mqtt_set_disconnect_handler(AWS_IoT_Client *pClient, iot_disconnect_handler pDisconnectHandler, + void *pDisconnectHandlerData) { + FUNC_ENTRY; + if(NULL == pClient || NULL == pDisconnectHandler) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + pClient->clientData.disconnectHandler = pDisconnectHandler; + pClient->clientData.disconnectHandlerData = pDisconnectHandlerData; + FUNC_EXIT_RC(SUCCESS); +} + +uint32_t aws_iot_mqtt_get_network_disconnected_count(AWS_IoT_Client *pClient) { + return pClient->clientData.counterNetworkDisconnected; +} + +void aws_iot_mqtt_reset_network_disconnected_count(AWS_IoT_Client *pClient) { + pClient->clientData.counterNetworkDisconnected = 0; +} + +#ifdef __cplusplus +} +#endif + diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_common_internal.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_common_internal.c new file mode 100644 index 00000000..26e28655 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_common_internal.c @@ -0,0 +1,687 @@ +/* +* Copyright 2015-2016 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. +*/ + +// Based on Eclipse Paho. +/******************************************************************************* + * Copyright (c) 2014 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * Contributors: + * Ian Craggs - initial API and implementation and/or initial documentation + * Sergio R. Caprile - non-blocking packet read functions for stream transport + *******************************************************************************/ + +/** + * @file aws_iot_mqtt_client_common_internal.c + * @brief MQTT client internal API definitions + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "aws_iot_mqtt_client_common_internal.h" + +/* Max length of packet header */ +#define MAX_NO_OF_REMAINING_LENGTH_BYTES 4 + +/** + * Encodes the message length according to the MQTT algorithm + * @param buf the buffer into which the encoded data is written + * @param length the length to be encoded + * @return the number of bytes written to buffer + */ +size_t aws_iot_mqtt_internal_write_len_to_buffer(unsigned char *buf, uint32_t length) { + size_t outLen = 0; + unsigned char encodedByte; + + FUNC_ENTRY; + do { + encodedByte = (unsigned char) (length % 128); + length /= 128; + /* if there are more digits to encode, set the top bit of this digit */ + if(length > 0) { + encodedByte |= 0x80; + } + buf[outLen++] = encodedByte; + } while(length > 0); + + FUNC_EXIT_RC(outLen); +} + +/** + * Decodes the message length according to the MQTT algorithm + * @param the buffer containing the message + * @param value the decoded length returned + * @return the number of bytes read from the socket + */ +IoT_Error_t aws_iot_mqtt_internal_decode_remaining_length_from_buffer(unsigned char *buf, uint32_t *decodedLen, + uint32_t *readBytesLen) { + unsigned char encodedByte; + uint32_t multiplier, len; + FUNC_ENTRY; + + multiplier = 1; + len = 0; + *decodedLen = 0; + + do { + if(++len > MAX_NO_OF_REMAINING_LENGTH_BYTES) { + /* bad data */ + FUNC_EXIT_RC(MQTT_DECODE_REMAINING_LENGTH_ERROR); + } + encodedByte = *buf; + buf++; + *decodedLen += (encodedByte & 127) * multiplier; + multiplier *= 128; + } while((encodedByte & 128) != 0); + + *readBytesLen = len; + + FUNC_EXIT_RC(SUCCESS); +} + +uint32_t aws_iot_mqtt_internal_get_final_packet_length_from_remaining_length(uint32_t rem_len) { + rem_len += 1; /* header byte */ + /* now remaining_length field (MQTT 3.1.1 - 2.2.3)*/ + if(rem_len < 128) { + rem_len += 1; + } else if(rem_len < 16384) { + rem_len += 2; + } else if(rem_len < 2097152) { + rem_len += 3; + } else { + rem_len += 4; + } + return rem_len; +} + +/** + * Calculates uint16 packet id from two bytes read from the input buffer + * Checks Endianness at runtime + * + * @param pptr pointer to the input buffer - incremented by the number of bytes used & returned + * @return the value calculated + */ +uint16_t aws_iot_mqtt_internal_read_uint16_t(unsigned char **pptr) { + unsigned char *ptr = *pptr; + uint16_t len = 0; + uint8_t firstByte = (uint8_t) (*ptr); + uint8_t secondByte = (uint8_t) (*(ptr + 1)); + len = (uint16_t) (secondByte + (256 * firstByte)); + + *pptr += 2; + return len; +} + +/** + * Writes an integer as 2 bytes to an output buffer. + * @param pptr pointer to the output buffer - incremented by the number of bytes used & returned + * @param anInt the integer to write + */ +void aws_iot_mqtt_internal_write_uint_16(unsigned char **pptr, uint16_t anInt) { + **pptr = (unsigned char) (anInt / 256); + (*pptr)++; + **pptr = (unsigned char) (anInt % 256); + (*pptr)++; +} + +/** + * Reads one character from the input buffer. + * @param pptr pointer to the input buffer - incremented by the number of bytes used & returned + * @return the character read + */ +unsigned char aws_iot_mqtt_internal_read_char(unsigned char **pptr) { + unsigned char c = **pptr; + (*pptr)++; + return c; +} + +/** + * Writes one character to an output buffer. + * @param pptr pointer to the output buffer - incremented by the number of bytes used & returned + * @param c the character to write + */ +void aws_iot_mqtt_internal_write_char(unsigned char **pptr, unsigned char c) { + **pptr = c; + (*pptr)++; +} + +void aws_iot_mqtt_internal_write_utf8_string(unsigned char **pptr, const char *string, uint16_t stringLen) { + /* Nothing that calls this function will have a stringLen with a size larger than 2 bytes (MQTT 3.1.1 - 1.5.3) */ + aws_iot_mqtt_internal_write_uint_16(pptr, stringLen); + if(stringLen > 0) { + memcpy(*pptr, string, stringLen); + *pptr += stringLen; + } +} + +/** + * Initialize the MQTTHeader structure. Used to ensure that Header bits are + * always initialized using the proper mappings. No Endianness issues here since + * the individual fields are all less than a byte. Also generates no warnings since + * all fields are initialized using hex constants + */ +IoT_Error_t aws_iot_mqtt_internal_init_header(MQTTHeader *pHeader, MessageTypes message_type, + QoS qos, uint8_t dup, uint8_t retained) { + FUNC_ENTRY; + + if(NULL == pHeader) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + /* Set all bits to zero */ + pHeader->byte = 0; + uint8_t type = 0; + switch(message_type) { + case UNKNOWN: + /* Should never happen */ + return FAILURE; + case CONNECT: + type = 0x01; + break; + case CONNACK: + type = 0x02; + break; + case PUBLISH: + type = 0x03; + break; + case PUBACK: + type = 0x04; + break; + case PUBREC: + type = 0x05; + break; + case PUBREL: + type = 0x06; + break; + case PUBCOMP: + type = 0x07; + break; + case SUBSCRIBE: + type = 0x08; + break; + case SUBACK: + type = 0x09; + break; + case UNSUBSCRIBE: + type = 0x0A; + break; + case UNSUBACK: + type = 0x0B; + break; + case PINGREQ: + type = 0x0C; + break; + case PINGRESP: + type = 0x0D; + break; + case DISCONNECT: + type = 0x0E; + break; + default: + /* Should never happen */ + FUNC_EXIT_RC(FAILURE); + } + + pHeader->byte = type << 4; + pHeader->byte |= dup << 3; + + switch(qos) { + case QOS0: + break; + case QOS1: + pHeader->byte |= 1 << 1; + break; + default: + /* Using QOS0 as default */ + break; + } + + pHeader->byte |= (1 == retained) ? 0x01 : 0x00; + + FUNC_EXIT_RC(SUCCESS); +} + +IoT_Error_t aws_iot_mqtt_internal_send_packet(AWS_IoT_Client *pClient, size_t length, Timer *pTimer) { + + size_t sentLen, sent; + IoT_Error_t rc; + + FUNC_ENTRY; + + if(NULL == pClient || NULL == pTimer) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + if(length >= pClient->clientData.writeBufSize) { + FUNC_EXIT_RC(MQTT_TX_BUFFER_TOO_SHORT_ERROR); + } + +#ifdef _ENABLE_THREAD_SUPPORT_ + rc = aws_iot_mqtt_client_lock_mutex(pClient, &(pClient->clientData.tls_write_mutex)); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } +#endif + + sentLen = 0; + sent = 0; + + while(sent < length && !has_timer_expired(pTimer)) { + rc = pClient->networkStack.write(&(pClient->networkStack), + &pClient->clientData.writeBuf[sent], + (length - sent), + pTimer, + &sentLen); + if(SUCCESS != rc) { + /* there was an error writing the data */ + break; + } + sent += sentLen; + } + +#ifdef _ENABLE_THREAD_SUPPORT_ + rc = aws_iot_mqtt_client_unlock_mutex(pClient, &(pClient->clientData.tls_write_mutex)); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } +#endif + + if(sent == length) { + /* record the fact that we have successfully sent the packet */ + //countdown_sec(&c->pingTimer, c->clientData.keepAliveInterval); + FUNC_EXIT_RC(SUCCESS); + } + + FUNC_EXIT_RC(FAILURE); +} + +static IoT_Error_t _aws_iot_mqtt_internal_decode_packet_remaining_len(AWS_IoT_Client *pClient, + size_t *rem_len, Timer *pTimer) { + unsigned char encodedByte; + size_t multiplier, len; + IoT_Error_t rc; + + FUNC_ENTRY; + + multiplier = 1; + len = 0; + *rem_len = 0; + + do { + if(++len > MAX_NO_OF_REMAINING_LENGTH_BYTES) { + /* bad data */ + FUNC_EXIT_RC(MQTT_DECODE_REMAINING_LENGTH_ERROR); + } + + rc = pClient->networkStack.read(&(pClient->networkStack), &encodedByte, 1, pTimer, &len); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + *rem_len += ((encodedByte & 127) * multiplier); + multiplier *= 128; + } while((encodedByte & 128) != 0); + + FUNC_EXIT_RC(rc); +} + +static IoT_Error_t _aws_iot_mqtt_internal_read_packet(AWS_IoT_Client *pClient, Timer *pTimer, uint8_t *pPacketType) { + size_t len, rem_len, total_bytes_read, bytes_to_be_read, read_len; + IoT_Error_t rc; + MQTTHeader header = {0}; + Timer packetTimer; + init_timer(&packetTimer); + countdown_ms(&packetTimer, pClient->clientData.packetTimeoutMs); + + rem_len = 0; + total_bytes_read = 0; + bytes_to_be_read = 0; + read_len = 0; + + rc = pClient->networkStack.read(&(pClient->networkStack), pClient->clientData.readBuf, 1, pTimer, &read_len); + /* 1. read the header byte. This has the packet type in it */ + if(NETWORK_SSL_NOTHING_TO_READ == rc) { + return MQTT_NOTHING_TO_READ; + } else if(SUCCESS != rc) { + return rc; + } + + len = 1; + + /* Use the constant packet receive timeout, instead of the variable (remaining) pTimer time, to + * determine packet receiving timeout. This is done so we don't prematurely time out packet receiving + * if the remaining time in pTimer is too short. + */ + pTimer = &packetTimer; + + /* 2. read the remaining length. This is variable in itself */ + rc = _aws_iot_mqtt_internal_decode_packet_remaining_len(pClient, &rem_len, pTimer); + if(SUCCESS != rc) { + return rc; + } + + /* if the buffer is too short then the message will be dropped silently */ + if(rem_len >= pClient->clientData.readBufSize) { + bytes_to_be_read = pClient->clientData.readBufSize; + do { + rc = pClient->networkStack.read(&(pClient->networkStack), pClient->clientData.readBuf, bytes_to_be_read, + pTimer, &read_len); + if(SUCCESS == rc) { + total_bytes_read += read_len; + if((rem_len - total_bytes_read) >= pClient->clientData.readBufSize) { + bytes_to_be_read = pClient->clientData.readBufSize; + } else { + bytes_to_be_read = rem_len - total_bytes_read; + } + } + } while(total_bytes_read < rem_len && SUCCESS == rc); + return MQTT_RX_BUFFER_TOO_SHORT_ERROR; + } + + /* put the original remaining length into the read buffer */ + len += aws_iot_mqtt_internal_write_len_to_buffer(pClient->clientData.readBuf + 1, (uint32_t) rem_len); + + /* 3. read the rest of the buffer using a callback to supply the rest of the data */ + if(rem_len > 0) { + rc = pClient->networkStack.read(&(pClient->networkStack), pClient->clientData.readBuf + len, rem_len, pTimer, + &read_len); + if(SUCCESS != rc || read_len != rem_len) { + return FAILURE; + } + } + + header.byte = pClient->clientData.readBuf[0]; + *pPacketType = MQTT_HEADER_FIELD_TYPE(header.byte); + + FUNC_EXIT_RC(rc); +} + +// assume topic filter and name is in correct format +// # can only be at end +// + and # can only be next to separator +static bool _aws_iot_mqtt_internal_is_topic_matched(char *pTopicFilter, char *pTopicName, uint16_t topicNameLen) { + + char *curf, *curn, *curn_end; + + if(NULL == pTopicFilter || NULL == pTopicName) { + return false; + } + + curf = pTopicFilter; + curn = pTopicName; + curn_end = curn + topicNameLen; + + while(*curf && (curn < curn_end)) { + if(*curn == '/' && *curf != '/') { + break; + } + if(*curf != '+' && *curf != '#' && *curf != *curn) { + break; + } + if(*curf == '+') { + /* skip until we meet the next separator, or end of string */ + char *nextpos = curn + 1; + while(nextpos < curn_end && *nextpos != '/') + nextpos = ++curn + 1; + } else if(*curf == '#') { + /* skip until end of string */ + curn = curn_end - 1; + } + + curf++; + curn++; + }; + + return (curn == curn_end) && (*curf == '\0'); +} + +static IoT_Error_t _aws_iot_mqtt_internal_deliver_message(AWS_IoT_Client *pClient, char *pTopicName, + uint16_t topicNameLen, + IoT_Publish_Message_Params *pMessageParams) { + uint32_t itr; + IoT_Error_t rc; + ClientState clientState; + + FUNC_ENTRY; + + if(NULL == pTopicName) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + /* This function can be called from all MQTT APIs + * But while callback return is in progress, Yield should not be called. + * The state for CB_RETURN accomplishes that, as yield cannot be called while in that state */ + clientState = aws_iot_mqtt_get_client_state(pClient); + aws_iot_mqtt_set_client_state(pClient, clientState, CLIENT_STATE_CONNECTED_WAIT_FOR_CB_RETURN); + + /* Find the right message handler - indexed by topic */ + for(itr = 0; itr < AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; ++itr) { + if(NULL != pClient->clientData.messageHandlers[itr].topicName) { + if(((topicNameLen == pClient->clientData.messageHandlers[itr].topicNameLen) + && + (strncmp(pTopicName, (char *) pClient->clientData.messageHandlers[itr].topicName, topicNameLen) == 0)) + || _aws_iot_mqtt_internal_is_topic_matched((char *) pClient->clientData.messageHandlers[itr].topicName, + pTopicName, topicNameLen)) { + if(NULL != pClient->clientData.messageHandlers[itr].pApplicationHandler) { + pClient->clientData.messageHandlers[itr].pApplicationHandler(pClient, pTopicName, topicNameLen, + pMessageParams, + pClient->clientData.messageHandlers[itr].pApplicationHandlerData); + } + } + } + } + rc = aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTED_WAIT_FOR_CB_RETURN, clientState); + + FUNC_EXIT_RC(rc); +} + +static IoT_Error_t _aws_iot_mqtt_internal_handle_publish(AWS_IoT_Client *pClient, Timer *pTimer) { + char *topicName; + uint16_t topicNameLen; + uint32_t len; + IoT_Error_t rc; + IoT_Publish_Message_Params msg; + + FUNC_ENTRY; + + topicName = NULL; + topicNameLen = 0; + len = 0; + + rc = aws_iot_mqtt_internal_deserialize_publish(&msg.isDup, &msg.qos, &msg.isRetained, + &msg.id, &topicName, &topicNameLen, + (unsigned char **) &msg.payload, &msg.payloadLen, + pClient->clientData.readBuf, + pClient->clientData.readBufSize); + + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + rc = _aws_iot_mqtt_internal_deliver_message(pClient, topicName, topicNameLen, &msg); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + if(QOS0 == msg.qos) { + /* No further processing required for QoS0 */ + FUNC_EXIT_RC(SUCCESS); + } + + /* Message assumed to be QoS1 since we do not support QoS2 at this time */ + rc = aws_iot_mqtt_internal_serialize_ack(pClient->clientData.writeBuf, pClient->clientData.writeBufSize, + PUBACK, 0, msg.id, &len); + + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + rc = aws_iot_mqtt_internal_send_packet(pClient, len, pTimer); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + FUNC_EXIT_RC(SUCCESS); +} + +IoT_Error_t aws_iot_mqtt_internal_cycle_read(AWS_IoT_Client *pClient, Timer *pTimer, uint8_t *pPacketType) { + IoT_Error_t rc; + +#ifdef _ENABLE_THREAD_SUPPORT_ + IoT_Error_t threadRc; +#endif + + if(NULL == pClient || NULL == pTimer) { + return NULL_VALUE_ERROR; + } + +#ifdef _ENABLE_THREAD_SUPPORT_ + threadRc = aws_iot_mqtt_client_lock_mutex(pClient, &(pClient->clientData.tls_read_mutex)); + if(SUCCESS != threadRc) { + FUNC_EXIT_RC(threadRc); + } +#endif + + /* read the socket, see what work is due */ + rc = _aws_iot_mqtt_internal_read_packet(pClient, pTimer, pPacketType); + +#ifdef _ENABLE_THREAD_SUPPORT_ + threadRc = aws_iot_mqtt_client_unlock_mutex(pClient, &(pClient->clientData.tls_read_mutex)); + if(SUCCESS != threadRc && (MQTT_NOTHING_TO_READ == rc || SUCCESS == rc)) { + return threadRc; + } +#endif + + if(MQTT_NOTHING_TO_READ == rc) { + /* Nothing to read, not a cycle failure */ + return SUCCESS; + } else if(SUCCESS != rc) { + return rc; + } + + switch(*pPacketType) { + case CONNACK: + case PUBACK: + case SUBACK: + case UNSUBACK: + /* SDK is blocking, these responses will be forwarded to calling function to process */ + break; + case PUBLISH: { + rc = _aws_iot_mqtt_internal_handle_publish(pClient, pTimer); + break; + } + case PUBREC: + case PUBCOMP: + /* QoS2 not supported at this time */ + break; + case PINGRESP: { + pClient->clientStatus.isPingOutstanding = 0; + countdown_sec(&pClient->pingTimer, pClient->clientData.keepAliveInterval); + break; + } + default: { + /* Either unknown packet type or Failure occurred + * Should not happen */ + rc = MQTT_RX_MESSAGE_PACKET_TYPE_INVALID_ERROR; + break; + } + } + + return rc; +} + +/* only used in single-threaded mode where one command at a time is in process */ +IoT_Error_t aws_iot_mqtt_internal_wait_for_read(AWS_IoT_Client *pClient, uint8_t packetType, Timer *pTimer) { + IoT_Error_t rc; + uint8_t read_packet_type; + + FUNC_ENTRY; + if(NULL == pClient || NULL == pTimer) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + read_packet_type = 0; + do { + if(has_timer_expired(pTimer)) { + /* we timed out */ + rc = MQTT_REQUEST_TIMEOUT_ERROR; + break; + } + rc = aws_iot_mqtt_internal_cycle_read(pClient, pTimer, &read_packet_type); + } while(NETWORK_DISCONNECTED_ERROR != rc && read_packet_type != packetType); + + if(MQTT_REQUEST_TIMEOUT_ERROR != rc && NETWORK_DISCONNECTED_ERROR != rc && read_packet_type != packetType) { + FUNC_EXIT_RC(FAILURE); + } + + /* Something failed or we didn't receive the expected packet, return error code */ + FUNC_EXIT_RC(rc); +} + +/** + * Serializes a 0-length packet into the supplied buffer, ready for writing to a socket + * @param buf the buffer into which the packet will be serialized + * @param buflen the length in bytes of the supplied buffer, to avoid overruns + * @param packettype the message type + * @param serialized length + * @return IoT_Error_t indicating function execution status + */ +IoT_Error_t aws_iot_mqtt_internal_serialize_zero(unsigned char *pTxBuf, size_t txBufLen, MessageTypes packetType, + size_t *pSerializedLength) { + unsigned char *ptr; + IoT_Error_t rc; + MQTTHeader header = {0}; + + FUNC_ENTRY; + if(NULL == pTxBuf || NULL == pSerializedLength) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + /* Buffer should have at least 2 bytes for the header */ + if(4 > txBufLen) { + FUNC_EXIT_RC(MQTT_TX_BUFFER_TOO_SHORT_ERROR); + } + + ptr = pTxBuf; + + rc = aws_iot_mqtt_internal_init_header(&header, packetType, QOS0, 0, 0); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + /* write header */ + aws_iot_mqtt_internal_write_char(&ptr, header.byte); + + /* write remaining length */ + ptr += aws_iot_mqtt_internal_write_len_to_buffer(ptr, 0); + *pSerializedLength = (uint32_t) (ptr - pTxBuf); + + FUNC_EXIT_RC(SUCCESS); +} + +#ifdef __cplusplus +} +#endif diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_connect.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_connect.c new file mode 100644 index 00000000..ae6bd4b4 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_connect.c @@ -0,0 +1,627 @@ +/* +* Copyright 2015-2016 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. +*/ + +// Based on Eclipse Paho. +/******************************************************************************* + * Copyright (c) 2014 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * Contributors: + * Ian Craggs - initial API and implementation and/or initial documentation + *******************************************************************************/ + +/** + * @file aws_iot_mqtt_client_connect.c + * @brief MQTT client connect API definition and related functions + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include + +#include +#include "aws_iot_mqtt_client_interface.h" +#include "aws_iot_mqtt_client_common_internal.h" + +typedef union { + uint8_t all; /**< all connect flags */ +#if defined(REVERSED) + struct + { + unsigned int username : 1; /**< 3.1 user name */ + unsigned int password : 1; /**< 3.1 password */ + unsigned int willRetain : 1; /**< will retain setting */ + unsigned int willQoS : 2; /**< will QoS value */ + unsigned int will : 1; /**< will flag */ + unsigned int cleansession : 1; /**< clean session flag */ + unsigned int : 1; /**< unused */ + } bits; +#else + struct { + unsigned int : 1; + /**< unused */ + unsigned int cleansession : 1; + /**< cleansession flag */ + unsigned int will : 1; + /**< will flag */ + unsigned int willQoS : 2; + /**< will QoS value */ + unsigned int willRetain : 1; + /**< will retain setting */ + unsigned int password : 1; + /**< 3.1 password */ + unsigned int username : 1; /**< 3.1 user name */ + } bits; +#endif +} MQTT_Connect_Header_Flags; +/**< connect flags byte */ + +typedef union { + uint8_t all; /**< all connack flags */ +#if defined(REVERSED) + struct + { + unsigned int sessionpresent : 1; /**< session present flag */ + unsigned int : 7; /**< unused */ + } bits; +#else + struct { + unsigned int : 7; + /**< unused */ + unsigned int sessionpresent : 1; /**< session present flag */ + } bits; +#endif +} MQTT_Connack_Header_Flags; +/**< connack flags byte */ + +typedef enum { + CONNACK_CONNECTION_ACCEPTED = 0, + CONNACK_UNACCEPTABLE_PROTOCOL_VERSION_ERROR = 1, + CONNACK_IDENTIFIER_REJECTED_ERROR = 2, + CONNACK_SERVER_UNAVAILABLE_ERROR = 3, + CONNACK_BAD_USERDATA_ERROR = 4, + CONNACK_NOT_AUTHORIZED_ERROR = 5 +} MQTT_Connack_Return_Codes; /**< Connect request response codes from server */ + + +/** + * Determines the length of the MQTT connect packet that would be produced using the supplied connect options. + * @param options the options to be used to build the connect packet + * @param the length of buffer needed to contain the serialized version of the packet + * @return IoT_Error_t indicating function execution status + */ +static uint32_t _aws_iot_get_connect_packet_length(IoT_Client_Connect_Params *pConnectParams) { + uint32_t len; + /* Enable when adding further MQTT versions */ + /*size_t len = 0; + switch(pConnectParams->MQTTVersion) { + case MQTT_3_1_1: + len = 10; + break; + }*/ + FUNC_ENTRY; + + len = 10; // Len = 10 for MQTT_3_1_1 + len = len + pConnectParams->clientIDLen + 2; + + if(pConnectParams->isWillMsgPresent) { + len = len + pConnectParams->will.topicNameLen + 2 + pConnectParams->will.msgLen + 2; + } + + if(NULL != pConnectParams->pUsername) { + len = len + pConnectParams->usernameLen + 2; + } + + if(NULL != pConnectParams->pPassword) { + len = len + pConnectParams->passwordLen + 2; + } + + FUNC_EXIT_RC(len); +} + +/** + * Serializes the connect options into the buffer. + * @param buf the buffer into which the packet will be serialized + * @param len the length in bytes of the supplied buffer + * @param options the options to be used to build the connect packet + * @param serialized length + * @return IoT_Error_t indicating function execution status + */ +static IoT_Error_t _aws_iot_mqtt_serialize_connect(unsigned char *pTxBuf, size_t txBufLen, + IoT_Client_Connect_Params *pConnectParams, + size_t *pSerializedLen) { + unsigned char *ptr; + uint32_t len; + IoT_Error_t rc; + MQTTHeader header = {0}; + MQTT_Connect_Header_Flags flags = {0}; + + FUNC_ENTRY; + + if(NULL == pTxBuf || NULL == pConnectParams || NULL == pSerializedLen || + (NULL == pConnectParams->pClientID && 0 != pConnectParams->clientIDLen) || + (NULL != pConnectParams->pClientID && 0 == pConnectParams->clientIDLen)) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + /* Check needed here before we start writing to the Tx buffer */ + switch(pConnectParams->MQTTVersion) { + case MQTT_3_1_1: + break; + default: + return MQTT_CONNACK_UNACCEPTABLE_PROTOCOL_VERSION_ERROR; + } + + ptr = pTxBuf; + len = _aws_iot_get_connect_packet_length(pConnectParams); + if(aws_iot_mqtt_internal_get_final_packet_length_from_remaining_length(len) > txBufLen) { + FUNC_EXIT_RC(MQTT_TX_BUFFER_TOO_SHORT_ERROR); + } + + rc = aws_iot_mqtt_internal_init_header(&header, CONNECT, QOS0, 0, 0); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + aws_iot_mqtt_internal_write_char(&ptr, header.byte); /* write header */ + + ptr += aws_iot_mqtt_internal_write_len_to_buffer(ptr, len); /* write remaining length */ + + // Enable if adding support for more versions + //if(MQTT_3_1_1 == pConnectParams->MQTTVersion) { + aws_iot_mqtt_internal_write_utf8_string(&ptr, "MQTT", 4); + aws_iot_mqtt_internal_write_char(&ptr, (unsigned char) pConnectParams->MQTTVersion); + //} + + flags.all = 0; + if (pConnectParams->isCleanSession) + { + flags.all |= 1 << 1; + } + + if (pConnectParams->isWillMsgPresent) + { + flags.all |= 1 << 2; + flags.all |= pConnectParams->will.qos << 3; + flags.all |= pConnectParams->will.isRetained << 5; + } + + if(pConnectParams->pPassword) { + flags.all |= 1 << 6; + } + + if(pConnectParams->pUsername) { + flags.all |= 1 << 7; + } + + aws_iot_mqtt_internal_write_char(&ptr, flags.all); + aws_iot_mqtt_internal_write_uint_16(&ptr, pConnectParams->keepAliveIntervalInSec); + + /* If the code have passed the check for incorrect values above, no client id was passed as argument */ + if(NULL == pConnectParams->pClientID) { + aws_iot_mqtt_internal_write_uint_16(&ptr, 0); + } else { + aws_iot_mqtt_internal_write_utf8_string(&ptr, pConnectParams->pClientID, pConnectParams->clientIDLen); + } + + if(pConnectParams->isWillMsgPresent) { + aws_iot_mqtt_internal_write_utf8_string(&ptr, pConnectParams->will.pTopicName, + pConnectParams->will.topicNameLen); + aws_iot_mqtt_internal_write_utf8_string(&ptr, pConnectParams->will.pMessage, pConnectParams->will.msgLen); + } + + if(pConnectParams->pUsername) { + aws_iot_mqtt_internal_write_utf8_string(&ptr, pConnectParams->pUsername, pConnectParams->usernameLen); + } + + if(pConnectParams->pPassword) { + aws_iot_mqtt_internal_write_utf8_string(&ptr, pConnectParams->pPassword, pConnectParams->passwordLen); + } + + *pSerializedLen = (size_t) (ptr - pTxBuf); + + FUNC_EXIT_RC(SUCCESS); +} + +/** + * Deserializes the supplied (wire) buffer into connack data - return code + * @param sessionPresent the session present flag returned (only for MQTT 3.1.1) + * @param connack_rc returned integer value of the connack return code + * @param buf the raw buffer data, of the correct length determined by the remaining length field + * @param buflen the length in bytes of the data in the supplied buffer + * @return IoT_Error_t indicating function execution status + */ +static IoT_Error_t _aws_iot_mqtt_deserialize_connack(unsigned char *pSessionPresent, IoT_Error_t *pConnackRc, + unsigned char *pRxBuf, size_t rxBufLen) { + unsigned char *curdata, *enddata; + unsigned char connack_rc_char; + uint32_t decodedLen, readBytesLen; + IoT_Error_t rc; + MQTT_Connack_Header_Flags flags = {0}; + MQTTHeader header = {0}; + + FUNC_ENTRY; + + if(NULL == pSessionPresent || NULL == pConnackRc || NULL == pRxBuf) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + /* CONNACK header size is fixed at two bytes for fixed and 2 bytes for variable, + * using that as minimum size + * MQTT v3.1.1 Specification 3.2.1 */ + if(4 > rxBufLen) { + FUNC_EXIT_RC(MQTT_RX_BUFFER_TOO_SHORT_ERROR); + } + + curdata = pRxBuf; + enddata = NULL; + decodedLen = 0; + readBytesLen = 0; + + header.byte = aws_iot_mqtt_internal_read_char(&curdata); + if(CONNACK != MQTT_HEADER_FIELD_TYPE(header.byte)) { + FUNC_EXIT_RC(FAILURE); + } + + /* read remaining length */ + rc = aws_iot_mqtt_internal_decode_remaining_length_from_buffer(curdata, &decodedLen, &readBytesLen); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + /* CONNACK remaining length should always be 2 as per MQTT 3.1.1 spec */ + curdata += (readBytesLen); + enddata = curdata + decodedLen; + if(2 != (enddata - curdata)) { + FUNC_EXIT_RC(MQTT_DECODE_REMAINING_LENGTH_ERROR); + } + + flags.all = aws_iot_mqtt_internal_read_char(&curdata); + *pSessionPresent = flags.bits.sessionpresent; + connack_rc_char = aws_iot_mqtt_internal_read_char(&curdata); + switch(connack_rc_char) { + case CONNACK_CONNECTION_ACCEPTED: + *pConnackRc = MQTT_CONNACK_CONNECTION_ACCEPTED; + break; + case CONNACK_UNACCEPTABLE_PROTOCOL_VERSION_ERROR: + *pConnackRc = MQTT_CONNACK_UNACCEPTABLE_PROTOCOL_VERSION_ERROR; + break; + case CONNACK_IDENTIFIER_REJECTED_ERROR: + *pConnackRc = MQTT_CONNACK_IDENTIFIER_REJECTED_ERROR; + break; + case CONNACK_SERVER_UNAVAILABLE_ERROR: + *pConnackRc = MQTT_CONNACK_SERVER_UNAVAILABLE_ERROR; + break; + case CONNACK_BAD_USERDATA_ERROR: + *pConnackRc = MQTT_CONNACK_BAD_USERDATA_ERROR; + break; + case CONNACK_NOT_AUTHORIZED_ERROR: + *pConnackRc = MQTT_CONNACK_NOT_AUTHORIZED_ERROR; + break; + default: + *pConnackRc = MQTT_CONNACK_UNKNOWN_ERROR; + break; + } + + FUNC_EXIT_RC(SUCCESS); +} + +/** + * @brief Check if client state is valid for a connect request + * + * Called to check if client state is valid for a connect request + * @param pClient Reference to the IoT Client + * + * @return bool true = state is valid, false = not valid + */ +static bool _aws_iot_mqtt_is_client_state_valid_for_connect(ClientState clientState) { + bool isValid = false; + + switch(clientState) { + case CLIENT_STATE_INVALID: + isValid = false; + break; + case CLIENT_STATE_INITIALIZED: + isValid = true; + break; + case CLIENT_STATE_CONNECTING: + case CLIENT_STATE_CONNECTED_IDLE: + case CLIENT_STATE_CONNECTED_YIELD_IN_PROGRESS: + case CLIENT_STATE_CONNECTED_PUBLISH_IN_PROGRESS: + case CLIENT_STATE_CONNECTED_SUBSCRIBE_IN_PROGRESS: + case CLIENT_STATE_CONNECTED_UNSUBSCRIBE_IN_PROGRESS: + case CLIENT_STATE_CONNECTED_RESUBSCRIBE_IN_PROGRESS: + case CLIENT_STATE_CONNECTED_WAIT_FOR_CB_RETURN: + case CLIENT_STATE_DISCONNECTING: + isValid = false; + break; + case CLIENT_STATE_DISCONNECTED_ERROR: + case CLIENT_STATE_DISCONNECTED_MANUALLY: + case CLIENT_STATE_PENDING_RECONNECT: + isValid = true; + break; + default: + break; + } + + return isValid; +} + +/** + * @brief MQTT Connection Function + * + * Called to establish an MQTT connection with the AWS IoT Service + * This is the internal function which is called by the connect API to perform the operation. + * Not meant to be called directly as it doesn't do validations or client state changes + * + * @param pClient Reference to the IoT Client + * @param pConnectParams Pointer to MQTT connection parameters + * + * @return An IoT Error Type defining successful/failed connection + */ +static IoT_Error_t _aws_iot_mqtt_internal_connect(AWS_IoT_Client *pClient, const IoT_Client_Connect_Params *pConnectParams) { + Timer connect_timer; + IoT_Error_t connack_rc = FAILURE; + char sessionPresent = 0; + size_t len = 0; + IoT_Error_t rc = FAILURE; + + FUNC_ENTRY; + + if(NULL != pConnectParams) { + /* override default options if new options were supplied */ + rc = aws_iot_mqtt_set_connect_params(pClient, pConnectParams); + if(SUCCESS != rc) { + FUNC_EXIT_RC(MQTT_CONNECTION_ERROR); + } + } + + rc = pClient->networkStack.connect(&(pClient->networkStack), NULL); + if(SUCCESS != rc) { + /* TLS Connect failed, return error */ + FUNC_EXIT_RC(rc); + } + + init_timer(&connect_timer); + countdown_ms(&connect_timer, pClient->clientData.commandTimeoutMs); + + pClient->clientData.keepAliveInterval = pClient->clientData.options.keepAliveIntervalInSec; + rc = _aws_iot_mqtt_serialize_connect(pClient->clientData.writeBuf, pClient->clientData.writeBufSize, + &(pClient->clientData.options), &len); + if(SUCCESS != rc || 0 >= len) { + FUNC_EXIT_RC(rc); + } + + /* send the connect packet */ + rc = aws_iot_mqtt_internal_send_packet(pClient, len, &connect_timer); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + /* this will be a blocking call, wait for the CONNACK */ + rc = aws_iot_mqtt_internal_wait_for_read(pClient, CONNACK, &connect_timer); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + /* Received CONNACK, check the return code */ + rc = _aws_iot_mqtt_deserialize_connack((unsigned char *) &sessionPresent, &connack_rc, pClient->clientData.readBuf, + pClient->clientData.readBufSize); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + if(MQTT_CONNACK_CONNECTION_ACCEPTED != connack_rc) { + FUNC_EXIT_RC(connack_rc); + } + + pClient->clientStatus.isPingOutstanding = false; + countdown_sec(&pClient->pingTimer, pClient->clientData.keepAliveInterval); + + FUNC_EXIT_RC(SUCCESS); +} + +/** + * @brief MQTT Connection Function + * + * Called to establish an MQTT connection with the AWS IoT Service + * This is the outer function which does the validations and calls the internal connect above + * to perform the actual operation. It is also responsible for client state changes + * + * @param pClient Reference to the IoT Client + * @param pConnectParams Pointer to MQTT connection parameters + * + * @return An IoT Error Type defining successful/failed connection + */ +IoT_Error_t aws_iot_mqtt_connect(AWS_IoT_Client *pClient, const IoT_Client_Connect_Params *pConnectParams) { + IoT_Error_t rc, disconRc; + ClientState clientState; + FUNC_ENTRY; + + if(NULL == pClient) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + clientState = aws_iot_mqtt_get_client_state(pClient); + + if(false == _aws_iot_mqtt_is_client_state_valid_for_connect(clientState)) { + /* Don't send connect packet again if we are already connected + * or in the process of connecting/disconnecting */ + FUNC_EXIT_RC(NETWORK_ALREADY_CONNECTED_ERROR); + } + + aws_iot_mqtt_set_client_state(pClient, clientState, CLIENT_STATE_CONNECTING); + + rc = _aws_iot_mqtt_internal_connect(pClient, pConnectParams); + + if(SUCCESS != rc) { + pClient->networkStack.disconnect(&(pClient->networkStack)); + disconRc = pClient->networkStack.destroy(&(pClient->networkStack)); + if (SUCCESS != disconRc) { + FUNC_EXIT_RC(NETWORK_DISCONNECTED_ERROR); + } + aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTING, CLIENT_STATE_DISCONNECTED_ERROR); + } else { + aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTING, CLIENT_STATE_CONNECTED_IDLE); + } + + FUNC_EXIT_RC(rc); +} + +/** + * @brief Disconnect an MQTT Connection + * + * Called to send a disconnect message to the broker. + * This is the internal function which is called by the disconnect API to perform the operation. + * Not meant to be called directly as it doesn't do validations or client state changes + * + * @param pClient Reference to the IoT Client + * + * @return An IoT Error Type defining successful/failed send of the disconnect control packet. + */ +IoT_Error_t _aws_iot_mqtt_internal_disconnect(AWS_IoT_Client *pClient) { + /* We might wait for incomplete incoming publishes to complete */ + Timer timer; + size_t serialized_len = 0; + IoT_Error_t rc; + + FUNC_ENTRY; + + rc = aws_iot_mqtt_internal_serialize_zero(pClient->clientData.writeBuf, pClient->clientData.writeBufSize, + DISCONNECT, + &serialized_len); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + init_timer(&timer); + countdown_ms(&timer, pClient->clientData.commandTimeoutMs); + + /* send the disconnect packet */ + if(serialized_len > 0) { + aws_iot_mqtt_internal_send_packet(pClient, serialized_len, &timer); + } + + /* Clean network stack */ + pClient->networkStack.disconnect(&(pClient->networkStack)); + rc = pClient->networkStack.destroy(&(pClient->networkStack)); + if(0 != rc) { + /* TLS Destroy failed, return error */ + FUNC_EXIT_RC(FAILURE); + } + + FUNC_EXIT_RC(SUCCESS); +} + +/** + * @brief Disconnect an MQTT Connection + * + * Called to send a disconnect message to the broker. + * This is the outer function which does the validations and calls the internal disconnect above + * to perform the actual operation. It is also responsible for client state changes + * + * @param pClient Reference to the IoT Client + * + * @return An IoT Error Type defining successful/failed send of the disconnect control packet. + */ +IoT_Error_t aws_iot_mqtt_disconnect(AWS_IoT_Client *pClient) { + ClientState clientState; + IoT_Error_t rc; + + FUNC_ENTRY; + + if(NULL == pClient) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + clientState = aws_iot_mqtt_get_client_state(pClient); + if(!aws_iot_mqtt_is_client_connected(pClient)) { + /* Network is already disconnected. Do nothing */ + FUNC_EXIT_RC(NETWORK_DISCONNECTED_ERROR); + } + + rc = aws_iot_mqtt_set_client_state(pClient, clientState, CLIENT_STATE_DISCONNECTING); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + rc = _aws_iot_mqtt_internal_disconnect(pClient); + + if(SUCCESS != rc) { + pClient->clientStatus.clientState = clientState; + } else { + /* If called from Keepalive, this gets set to CLIENT_STATE_DISCONNECTED_ERROR */ + pClient->clientStatus.clientState = CLIENT_STATE_DISCONNECTED_MANUALLY; + } + + FUNC_EXIT_RC(rc); +} + +/** + * @brief MQTT Manual Re-Connection Function + * + * Called to establish an MQTT connection with the AWS IoT Service + * using parameters from the last time a connection was attempted + * Use after disconnect to start the reconnect process manually + * Makes only one reconnect attempt. Sets the client state to + * pending reconnect in case of failure + * + * @param pClient Reference to the IoT Client + * + * @return An IoT Error Type defining successful/failed connection + */ +IoT_Error_t aws_iot_mqtt_attempt_reconnect(AWS_IoT_Client *pClient) { + IoT_Error_t rc; + + FUNC_ENTRY; + + if(NULL == pClient) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + if(aws_iot_mqtt_is_client_connected(pClient)) { + FUNC_EXIT_RC(NETWORK_ALREADY_CONNECTED_ERROR); + } + + /* Ignoring return code. failures expected if network is disconnected */ + rc = aws_iot_mqtt_connect(pClient, NULL); + + /* If still disconnected handle disconnect */ + if(CLIENT_STATE_CONNECTED_IDLE != aws_iot_mqtt_get_client_state(pClient)) { + aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_DISCONNECTED_ERROR, CLIENT_STATE_PENDING_RECONNECT); + FUNC_EXIT_RC(NETWORK_ATTEMPTING_RECONNECT); + } + + rc = aws_iot_mqtt_resubscribe(pClient); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + FUNC_EXIT_RC(NETWORK_RECONNECTED); +} + +#ifdef __cplusplus +} +#endif diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_publish.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_publish.c new file mode 100644 index 00000000..081a98c2 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_publish.c @@ -0,0 +1,428 @@ +/* +* Copyright 2015-2016 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. +*/ + +// Based on Eclipse Paho. +/******************************************************************************* + * Copyright (c) 2014 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * Contributors: + * Ian Craggs - initial API and implementation and/or initial documentation + * Ian Craggs - fix for https://bugs.eclipse.org/bugs/show_bug.cgi?id=453144 + *******************************************************************************/ + +/** + * @file aws_iot_mqtt_client_publish.c + * @brief MQTT client publish API definitions + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "aws_iot_mqtt_client_common_internal.h" + +/** + * @param stringVar pointer to the String into which the data is to be read + * @param stringLen pointer to variable which has the length of the string + * @param pptr pointer to the output buffer - incremented by the number of bytes used & returned + * @param enddata pointer to the end of the data: do not read beyond + * @return SUCCESS if successful, FAILURE if not + */ +static IoT_Error_t _aws_iot_mqtt_read_string_with_len(char **stringVar, uint16_t *stringLen, + unsigned char **pptr, unsigned char *enddata) { + IoT_Error_t rc = FAILURE; + + FUNC_ENTRY; + /* the first two bytes are the length of the string */ + /* enough length to read the integer? */ + if(enddata - (*pptr) > 1) { + *stringLen = aws_iot_mqtt_internal_read_uint16_t(pptr); /* increments pptr to point past length */ + if(&(*pptr)[*stringLen] <= enddata) { + *stringVar = (char *) *pptr; + *pptr += *stringLen; + rc = SUCCESS; + } + } + + FUNC_EXIT_RC(rc); +} + +/** + * Serializes the supplied publish data into the supplied buffer, ready for sending + * @param pTxBuf the buffer into which the packet will be serialized + * @param txBufLen the length in bytes of the supplied buffer + * @param dup uint8_t - the MQTT dup flag + * @param qos QoS - the MQTT QoS value + * @param retained uint8_t - the MQTT retained flag + * @param packetId uint16_t - the MQTT packet identifier + * @param pTopicName char * - the MQTT topic in the publish + * @param topicNameLen uint16_t - the length of the Topic Name + * @param pPayload byte buffer - the MQTT publish payload + * @param payloadLen size_t - the length of the MQTT payload + * @param pSerializedLen uint32_t - pointer to the variable that stores serialized len + * + * @return An IoT Error Type defining successful/failed call + */ +static IoT_Error_t _aws_iot_mqtt_internal_serialize_publish(unsigned char *pTxBuf, size_t txBufLen, uint8_t dup, + QoS qos, uint8_t retained, uint16_t packetId, + const char *pTopicName, uint16_t topicNameLen, + const unsigned char *pPayload, size_t payloadLen, + uint32_t *pSerializedLen) { + unsigned char *ptr; + uint32_t rem_len; + IoT_Error_t rc; + MQTTHeader header = {0}; + + FUNC_ENTRY; + if(NULL == pTxBuf || NULL == pPayload || NULL == pSerializedLen) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + ptr = pTxBuf; + rem_len = 0; + + rem_len += (uint32_t) (topicNameLen + payloadLen + 2); + if(qos > 0) { + rem_len += 2; /* packetId */ + } + if(aws_iot_mqtt_internal_get_final_packet_length_from_remaining_length(rem_len) > txBufLen) { + FUNC_EXIT_RC(MQTT_TX_BUFFER_TOO_SHORT_ERROR); + } + + rc = aws_iot_mqtt_internal_init_header(&header, PUBLISH, qos, dup, retained); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + aws_iot_mqtt_internal_write_char(&ptr, header.byte); /* write header */ + + ptr += aws_iot_mqtt_internal_write_len_to_buffer(ptr, rem_len); /* write remaining length */; + + aws_iot_mqtt_internal_write_utf8_string(&ptr, pTopicName, topicNameLen); + + if(qos > 0) { + aws_iot_mqtt_internal_write_uint_16(&ptr, packetId); + } + + memcpy(ptr, pPayload, payloadLen); + ptr += payloadLen; + + *pSerializedLen = (uint32_t) (ptr - pTxBuf); + + FUNC_EXIT_RC(SUCCESS); +} + +/** + * Serializes the ack packet into the supplied buffer. + * @param pTxBuf the buffer into which the packet will be serialized + * @param txBufLen the length in bytes of the supplied buffer + * @param msgType the MQTT packet type + * @param dup the MQTT dup flag + * @param packetId the MQTT packet identifier + * @param pSerializedLen uint32_t - pointer to the variable that stores serialized len + * + * @return An IoT Error Type defining successful/failed call + */ +IoT_Error_t aws_iot_mqtt_internal_serialize_ack(unsigned char *pTxBuf, size_t txBufLen, + MessageTypes msgType, uint8_t dup, uint16_t packetId, + uint32_t *pSerializedLen) { + unsigned char *ptr; + QoS requestQoS; + IoT_Error_t rc; + MQTTHeader header = {0}; + FUNC_ENTRY; + if(NULL == pTxBuf || pSerializedLen == NULL) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + ptr = pTxBuf; + + /* Minimum byte length required by ACK headers is + * 2 for fixed and 2 for variable part */ + if(4 > txBufLen) { + FUNC_EXIT_RC(MQTT_TX_BUFFER_TOO_SHORT_ERROR); + } + + requestQoS = (PUBREL == msgType) ? QOS1 : QOS0; + rc = aws_iot_mqtt_internal_init_header(&header, msgType, requestQoS, dup, 0); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + aws_iot_mqtt_internal_write_char(&ptr, header.byte); /* write header */ + + ptr += aws_iot_mqtt_internal_write_len_to_buffer(ptr, 2); /* write remaining length */ + aws_iot_mqtt_internal_write_uint_16(&ptr, packetId); + *pSerializedLen = (uint32_t) (ptr - pTxBuf); + + FUNC_EXIT_RC(SUCCESS); +} + +/** + * @brief Publish an MQTT message on a topic + * + * Called to publish an MQTT message on a topic. + * @note Call is blocking. In the case of a QoS 0 message the function returns + * after the message was successfully passed to the TLS layer. In the case of QoS 1 + * the function returns after the receipt of the PUBACK control packet. + * This is the internal function which is called by the publish API to perform the operation. + * Not meant to be called directly as it doesn't do validations or client state changes + * + * @param pClient Reference to the IoT Client + * @param pTopicName Topic Name to publish to + * @param topicNameLen Length of the topic name + * @param pParams Pointer to Publish Message parameters + * + * @return An IoT Error Type defining successful/failed publish + */ +static IoT_Error_t _aws_iot_mqtt_internal_publish(AWS_IoT_Client *pClient, const char *pTopicName, + uint16_t topicNameLen, IoT_Publish_Message_Params *pParams) { + Timer timer; + uint32_t len = 0; + uint16_t packet_id; + unsigned char dup, type; + IoT_Error_t rc; + + FUNC_ENTRY; + + init_timer(&timer); + countdown_ms(&timer, pClient->clientData.commandTimeoutMs); + + if(QOS1 == pParams->qos) { + pParams->id = aws_iot_mqtt_get_next_packet_id(pClient); + } + + rc = _aws_iot_mqtt_internal_serialize_publish(pClient->clientData.writeBuf, pClient->clientData.writeBufSize, 0, + pParams->qos, pParams->isRetained, pParams->id, pTopicName, + topicNameLen, (unsigned char *) pParams->payload, + pParams->payloadLen, &len); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + /* send the publish packet */ + rc = aws_iot_mqtt_internal_send_packet(pClient, len, &timer); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + /* Wait for ack if QoS1 */ + if(QOS1 == pParams->qos) { + rc = aws_iot_mqtt_internal_wait_for_read(pClient, PUBACK, &timer); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + rc = aws_iot_mqtt_internal_deserialize_ack(&type, &dup, &packet_id, pClient->clientData.readBuf, + pClient->clientData.readBufSize); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + } + + FUNC_EXIT_RC(SUCCESS); +} + +/** + * @brief Publish an MQTT message on a topic + * + * Called to publish an MQTT message on a topic. + * @note Call is blocking. In the case of a QoS 0 message the function returns + * after the message was successfully passed to the TLS layer. In the case of QoS 1 + * the function returns after the receipt of the PUBACK control packet. + * This is the outer function which does the validations and calls the internal publish above + * to perform the actual operation. It is also responsible for client state changes + * + * @param pClient Reference to the IoT Client + * @param pTopicName Topic Name to publish to + * @param topicNameLen Length of the topic name + * @param pParams Pointer to Publish Message parameters + * + * @return An IoT Error Type defining successful/failed publish + */ +IoT_Error_t aws_iot_mqtt_publish(AWS_IoT_Client *pClient, const char *pTopicName, uint16_t topicNameLen, + IoT_Publish_Message_Params *pParams) { + IoT_Error_t rc, pubRc; + ClientState clientState; + + FUNC_ENTRY; + + if(NULL == pClient || NULL == pTopicName || 0 == topicNameLen || NULL == pParams) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + if(!aws_iot_mqtt_is_client_connected(pClient)) { + FUNC_EXIT_RC(NETWORK_DISCONNECTED_ERROR); + } + + clientState = aws_iot_mqtt_get_client_state(pClient); + if(CLIENT_STATE_CONNECTED_IDLE != clientState && CLIENT_STATE_CONNECTED_WAIT_FOR_CB_RETURN != clientState) { + FUNC_EXIT_RC(MQTT_CLIENT_NOT_IDLE_ERROR); + } + + rc = aws_iot_mqtt_set_client_state(pClient, clientState, CLIENT_STATE_CONNECTED_PUBLISH_IN_PROGRESS); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + pubRc = _aws_iot_mqtt_internal_publish(pClient, pTopicName, topicNameLen, pParams); + + rc = aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTED_PUBLISH_IN_PROGRESS, clientState); + if(SUCCESS == pubRc && SUCCESS != rc) { + pubRc = rc; + } + + FUNC_EXIT_RC(pubRc); +} + +/** + * Deserializes the supplied (wire) buffer into publish data + * @param dup returned uint8_t - the MQTT dup flag + * @param qos returned QoS type - the MQTT QoS value + * @param retained returned uint8_t - the MQTT retained flag + * @param pPacketId returned uint16_t - the MQTT packet identifier + * @param pTopicName returned String - the MQTT topic in the publish + * @param topicNameLen returned uint16_t - the length of the MQTT topic in the publish + * @param payload returned byte buffer - the MQTT publish payload + * @param payloadlen returned size_t - the length of the MQTT payload + * @param pRxBuf the raw buffer data, of the correct length determined by the remaining length field + * @param rxBufLen the length in bytes of the data in the supplied buffer + * + * @return An IoT Error Type defining successful/failed call + */ +IoT_Error_t aws_iot_mqtt_internal_deserialize_publish(uint8_t *dup, QoS *qos, + uint8_t *retained, uint16_t *pPacketId, + char **pTopicName, uint16_t *topicNameLen, + unsigned char **payload, size_t *payloadLen, + unsigned char *pRxBuf, size_t rxBufLen) { + unsigned char *curData = pRxBuf; + unsigned char *endData = NULL; + IoT_Error_t rc = FAILURE; + uint32_t decodedLen = 0; + uint32_t readBytesLen = 0; + MQTTHeader header = {0}; + + FUNC_ENTRY; + + if(NULL == dup || NULL == qos || NULL == retained || NULL == pPacketId) { + FUNC_EXIT_RC(FAILURE); + } + + /* Publish header size is at least four bytes. + * Fixed header is two bytes. + * Variable header size depends on QoS And Topic Name. + * QoS level 0 doesn't have a message identifier (0 - 2 bytes) + * Topic Name length fields decide size of topic name field (at least 2 bytes) + * MQTT v3.1.1 Specification 3.3.1 */ + if(4 > rxBufLen) { + FUNC_EXIT_RC(MQTT_RX_BUFFER_TOO_SHORT_ERROR); + } + + header.byte = aws_iot_mqtt_internal_read_char(&curData); + if(PUBLISH != MQTT_HEADER_FIELD_TYPE(header.byte)) { + FUNC_EXIT_RC(FAILURE); + } + + *dup = MQTT_HEADER_FIELD_DUP(header.byte); + *qos = (QoS) MQTT_HEADER_FIELD_QOS(header.byte); + *retained = MQTT_HEADER_FIELD_RETAIN(header.byte); + + /* read remaining length */ + rc = aws_iot_mqtt_internal_decode_remaining_length_from_buffer(curData, &decodedLen, &readBytesLen); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + curData += (readBytesLen); + endData = curData + decodedLen; + + /* do we have enough data to read the protocol version byte? */ + if(SUCCESS != _aws_iot_mqtt_read_string_with_len(pTopicName, topicNameLen, &curData, endData) + || (0 > (endData - curData))) { + FUNC_EXIT_RC(FAILURE); + } + + if(QOS0 != *qos) { + *pPacketId = aws_iot_mqtt_internal_read_uint16_t(&curData); + } + + *payloadLen = (size_t) (endData - curData); + *payload = curData; + + FUNC_EXIT_RC(SUCCESS); +} + +/** + * Deserializes the supplied (wire) buffer into an ack + * @param pPacketType returned integer - the MQTT packet type + * @param dup returned integer - the MQTT dup flag + * @param pPacketId returned integer - the MQTT packet identifier + * @param pRxBuf the raw buffer data, of the correct length determined by the remaining length field + * @param rxBuflen the length in bytes of the data in the supplied buffer + * + * @return An IoT Error Type defining successful/failed call + */ +IoT_Error_t aws_iot_mqtt_internal_deserialize_ack(unsigned char *pPacketType, unsigned char *dup, + uint16_t *pPacketId, unsigned char *pRxBuf, + size_t rxBuflen) { + IoT_Error_t rc = FAILURE; + unsigned char *curdata = pRxBuf; + unsigned char *enddata = NULL; + uint32_t decodedLen = 0; + uint32_t readBytesLen = 0; + MQTTHeader header = {0}; + + FUNC_ENTRY; + + if(NULL == pPacketType || NULL == dup || NULL == pPacketId || NULL == pRxBuf) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + /* PUBACK fixed header size is two bytes, variable header is 2 bytes, MQTT v3.1.1 Specification 3.4.1 */ + if(4 > rxBuflen) { + FUNC_EXIT_RC(MQTT_RX_BUFFER_TOO_SHORT_ERROR); + } + + + header.byte = aws_iot_mqtt_internal_read_char(&curdata); + *dup = MQTT_HEADER_FIELD_DUP(header.byte); + *pPacketType = MQTT_HEADER_FIELD_TYPE(header.byte); + + /* read remaining length */ + rc = aws_iot_mqtt_internal_decode_remaining_length_from_buffer(curdata, &decodedLen, &readBytesLen); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + curdata += (readBytesLen); + enddata = curdata + decodedLen; + + if(enddata - curdata < 2) { + FUNC_EXIT_RC(FAILURE); + } + + *pPacketId = aws_iot_mqtt_internal_read_uint16_t(&curdata); + + FUNC_EXIT_RC(SUCCESS); +} + +#ifdef __cplusplus +} +#endif diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_subscribe.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_subscribe.c new file mode 100644 index 00000000..c1a86320 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_subscribe.c @@ -0,0 +1,441 @@ +/* +* Copyright 2015-2016 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. +*/ + +// Based on Eclipse Paho. +/******************************************************************************* + * Copyright (c) 2014 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * Contributors: + * Ian Craggs - initial API and implementation and/or initial documentation + *******************************************************************************/ + +/** + * @file aws_iot_mqtt_client_subscribe.c + * @brief MQTT client subscribe API definitions + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "aws_iot_mqtt_client_common_internal.h" + +/** + * Serializes the supplied subscribe data into the supplied buffer, ready for sending + * @param pTxBuf the buffer into which the packet will be serialized + * @param txBufLen the length in bytes of the supplied buffer + * @param dup unsigned char - the MQTT dup flag + * @param packetId uint16_t - the MQTT packet identifier + * @param topicCount - number of members in the topicFilters and reqQos arrays + * @param pTopicNameList - array of topic filter names + * @param pTopicNameLenList - array of length of topic filter names + * @param pRequestedQoSs - array of requested QoS + * @param pSerializedLen - the length of the serialized data + * + * @return An IoT Error Type defining successful/failed operation + */ +static IoT_Error_t _aws_iot_mqtt_serialize_subscribe(unsigned char *pTxBuf, size_t txBufLen, + unsigned char dup, uint16_t packetId, uint32_t topicCount, + const char **pTopicNameList, uint16_t *pTopicNameLenList, + QoS *pRequestedQoSs, uint32_t *pSerializedLen) { + unsigned char *ptr; + uint32_t itr, rem_len; + IoT_Error_t rc; + MQTTHeader header = {0}; + + FUNC_ENTRY; + if(NULL == pTxBuf || NULL == pSerializedLen) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + ptr = pTxBuf; + rem_len = 2; /* packetId */ + + for(itr = 0; itr < topicCount; ++itr) { + rem_len += (uint32_t) (pTopicNameLenList[itr] + 2 + 1); /* topic + length + req_qos */ + } + + if(aws_iot_mqtt_internal_get_final_packet_length_from_remaining_length(rem_len) > txBufLen) { + FUNC_EXIT_RC(MQTT_TX_BUFFER_TOO_SHORT_ERROR); + } + + rc = aws_iot_mqtt_internal_init_header(&header, SUBSCRIBE, QOS1, dup, 0); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + /* write header */ + aws_iot_mqtt_internal_write_char(&ptr, header.byte); + + /* write remaining length */ + ptr += aws_iot_mqtt_internal_write_len_to_buffer(ptr, rem_len); + + aws_iot_mqtt_internal_write_uint_16(&ptr, packetId); + + for(itr = 0; itr < topicCount; ++itr) { + aws_iot_mqtt_internal_write_utf8_string(&ptr, pTopicNameList[itr], pTopicNameLenList[itr]); + aws_iot_mqtt_internal_write_char(&ptr, (unsigned char) pRequestedQoSs[itr]); + } + + *pSerializedLen = (uint32_t) (ptr - pTxBuf); + + FUNC_EXIT_RC(SUCCESS); +} + +/** + * Deserializes the supplied (wire) buffer into suback data + * @param pPacketId returned integer - the MQTT packet identifier + * @param maxExpectedQoSCount - the maximum number of members allowed in the grantedQoSs array + * @param pGrantedQoSCount returned uint32_t - number of members in the grantedQoSs array + * @param pGrantedQoSs returned array of QoS type - the granted qualities of service + * @param pRxBuf the raw buffer data, of the correct length determined by the remaining length field + * @param rxBufLen the length in bytes of the data in the supplied buffer + * + * @return An IoT Error Type defining successful/failed operation + */ +static IoT_Error_t _aws_iot_mqtt_deserialize_suback(uint16_t *pPacketId, uint32_t maxExpectedQoSCount, + uint32_t *pGrantedQoSCount, QoS *pGrantedQoSs, + unsigned char *pRxBuf, size_t rxBufLen) { + unsigned char *curData, *endData; + uint32_t decodedLen, readBytesLen; + IoT_Error_t decodeRc; + MQTTHeader header = {0}; + + FUNC_ENTRY; + if(NULL == pPacketId || NULL == pGrantedQoSCount || NULL == pGrantedQoSs) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + curData = pRxBuf; + endData = NULL; + decodeRc = FAILURE; + decodedLen = 0; + readBytesLen = 0; + + /* SUBACK header size is 4 bytes for header and at least one byte for QoS payload + * Need at least a 5 bytes buffer. MQTT3.1.1 specification 3.9 + */ + if(5 > rxBufLen) { + FUNC_EXIT_RC(MQTT_RX_BUFFER_TOO_SHORT_ERROR); + } + + header.byte = aws_iot_mqtt_internal_read_char(&curData); + if(SUBACK != MQTT_HEADER_FIELD_TYPE(header.byte)) { + FUNC_EXIT_RC(FAILURE); + } + + /* read remaining length */ + decodeRc = aws_iot_mqtt_internal_decode_remaining_length_from_buffer(curData, &decodedLen, &readBytesLen); + if(SUCCESS != decodeRc) { + FUNC_EXIT_RC(decodeRc); + } + + curData += (readBytesLen); + endData = curData + decodedLen; + if(endData - curData < 2) { + FUNC_EXIT_RC(FAILURE); + } + + *pPacketId = aws_iot_mqtt_internal_read_uint16_t(&curData); + + *pGrantedQoSCount = 0; + while(curData < endData) { + if(*pGrantedQoSCount > maxExpectedQoSCount) { + FUNC_EXIT_RC(FAILURE); + } + pGrantedQoSs[(*pGrantedQoSCount)++] = (QoS) aws_iot_mqtt_internal_read_char(&curData); + } + + FUNC_EXIT_RC(SUCCESS); +} + +/* Returns MAX_MESSAGE_HANDLERS value if no free index is available */ +static uint32_t _aws_iot_mqtt_get_free_message_handler_index(AWS_IoT_Client *pClient) { + uint32_t itr; + + FUNC_ENTRY; + + for(itr = 0; itr < AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; itr++) { + if(pClient->clientData.messageHandlers[itr].topicName == NULL) { + break; + } + } + + FUNC_EXIT_RC(itr); +} + +/** + * @brief Subscribe to an MQTT topic. + * + * Called to send a subscribe message to the broker requesting a subscription + * to an MQTT topic. This is the internal function which is called by the + * subscribe API to perform the operation. Not meant to be called directly as + * it doesn't do validations or client state changes + * @note Call is blocking. The call returns after the receipt of the SUBACK control packet. + * + * @param pClient Reference to the IoT Client + * @param pTopicName Topic Name to publish to + * @param topicNameLen Length of the topic name + * @param pApplicationHandler_t Reference to the handler function for this subscription + * + * @return An IoT Error Type defining successful/failed subscription + */ +static IoT_Error_t _aws_iot_mqtt_internal_subscribe(AWS_IoT_Client *pClient, const char *pTopicName, + uint16_t topicNameLen, QoS qos, + pApplicationHandler_t pApplicationHandler, + void *pApplicationHandlerData) { + uint16_t txPacketId, rxPacketId; + uint32_t serializedLen, indexOfFreeMessageHandler, count; + IoT_Error_t rc; + Timer timer; + QoS grantedQoS[3] = {QOS0, QOS0, QOS0}; + + FUNC_ENTRY; + init_timer(&timer); + countdown_ms(&timer, pClient->clientData.commandTimeoutMs); + + serializedLen = 0; + count = 0; + txPacketId = aws_iot_mqtt_get_next_packet_id(pClient); + rxPacketId = 0; + + rc = _aws_iot_mqtt_serialize_subscribe(pClient->clientData.writeBuf, pClient->clientData.writeBufSize, 0, + txPacketId, 1, &pTopicName, &topicNameLen, &qos, &serializedLen); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + indexOfFreeMessageHandler = _aws_iot_mqtt_get_free_message_handler_index(pClient); + if(AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS <= indexOfFreeMessageHandler) { + FUNC_EXIT_RC(MQTT_MAX_SUBSCRIPTIONS_REACHED_ERROR); + } + + /* send the subscribe packet */ + rc = aws_iot_mqtt_internal_send_packet(pClient, serializedLen, &timer); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + /* wait for suback */ + rc = aws_iot_mqtt_internal_wait_for_read(pClient, SUBACK, &timer); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + /* Granted QoS can be 0, 1 or 2 */ + rc = _aws_iot_mqtt_deserialize_suback(&rxPacketId, 1, &count, grantedQoS, pClient->clientData.readBuf, + pClient->clientData.readBufSize); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + /* TODO : Figure out how to test this before activating this check */ + //if(txPacketId != rxPacketId) { + /* Different SUBACK received than expected. Return error + * This can cause issues if the request timeout value is too small */ + // return RX_MESSAGE_INVALID_ERROR; + //} + + pClient->clientData.messageHandlers[indexOfFreeMessageHandler].topicName = + pTopicName; + pClient->clientData.messageHandlers[indexOfFreeMessageHandler].topicNameLen = + topicNameLen; + pClient->clientData.messageHandlers[indexOfFreeMessageHandler].pApplicationHandler = + pApplicationHandler; + pClient->clientData.messageHandlers[indexOfFreeMessageHandler].pApplicationHandlerData = + pApplicationHandlerData; + pClient->clientData.messageHandlers[indexOfFreeMessageHandler].qos = qos; + + FUNC_EXIT_RC(SUCCESS); +} + +/** + * @brief Subscribe to an MQTT topic. + * + * Called to send a subscribe message to the broker requesting a subscription + * to an MQTT topic. This is the outer function which does the validations and + * calls the internal subscribe above to perform the actual operation. + * It is also responsible for client state changes + * @note Call is blocking. The call returns after the receipt of the SUBACK control packet. + * + * @param pClient Reference to the IoT Client + * @param pTopicName Topic Name to publish to + * @param topicNameLen Length of the topic name + * @param pApplicationHandler_t Reference to the handler function for this subscription + * + * @return An IoT Error Type defining successful/failed subscription + */ +IoT_Error_t aws_iot_mqtt_subscribe(AWS_IoT_Client *pClient, const char *pTopicName, uint16_t topicNameLen, + QoS qos, pApplicationHandler_t pApplicationHandler, void *pApplicationHandlerData) { + ClientState clientState; + IoT_Error_t rc, subRc; + + FUNC_ENTRY; + + if(NULL == pClient || NULL == pTopicName || NULL == pApplicationHandler) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + if(!aws_iot_mqtt_is_client_connected(pClient)) { + FUNC_EXIT_RC(NETWORK_DISCONNECTED_ERROR); + } + + clientState = aws_iot_mqtt_get_client_state(pClient); + if(CLIENT_STATE_CONNECTED_IDLE != clientState && CLIENT_STATE_CONNECTED_WAIT_FOR_CB_RETURN != clientState) { + FUNC_EXIT_RC(MQTT_CLIENT_NOT_IDLE_ERROR); + } + + rc = aws_iot_mqtt_set_client_state(pClient, clientState, CLIENT_STATE_CONNECTED_SUBSCRIBE_IN_PROGRESS); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + subRc = _aws_iot_mqtt_internal_subscribe(pClient, pTopicName, topicNameLen, qos, + pApplicationHandler, pApplicationHandlerData); + + rc = aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTED_SUBSCRIBE_IN_PROGRESS, clientState); + if(SUCCESS == subRc && SUCCESS != rc) { + subRc = rc; + } + + FUNC_EXIT_RC(subRc); +} + +/** + * @brief Subscribe to an MQTT topic. + * + * Called to send a subscribe message to the broker requesting a subscription + * to an MQTT topic. + * This is the internal function which is called by the resubscribe API to perform the operation. + * Not meant to be called directly as it doesn't do validations or client state changes + * @note Call is blocking. The call returns after the receipt of the SUBACK control packet. + * + * @param pClient Reference to the IoT Client + * + * @return An IoT Error Type defining successful/failed subscription + */ +static IoT_Error_t _aws_iot_mqtt_internal_resubscribe(AWS_IoT_Client *pClient) { + uint16_t packetId; + uint32_t len, count, existingSubCount, itr; + IoT_Error_t rc; + Timer timer; + QoS grantedQoS[3] = {QOS0, QOS0, QOS0}; + + FUNC_ENTRY; + + packetId = 0; + len = 0; + count = 0; + existingSubCount = _aws_iot_mqtt_get_free_message_handler_index(pClient); + + for(itr = 0; itr < existingSubCount; itr++) { + if(pClient->clientData.messageHandlers[itr].topicName == NULL) { + continue; + } + + init_timer(&timer); + countdown_ms(&timer, pClient->clientData.commandTimeoutMs); + + rc = _aws_iot_mqtt_serialize_subscribe(pClient->clientData.writeBuf, pClient->clientData.writeBufSize, 0, + aws_iot_mqtt_get_next_packet_id(pClient), 1, + &(pClient->clientData.messageHandlers[itr].topicName), + &(pClient->clientData.messageHandlers[itr].topicNameLen), + &(pClient->clientData.messageHandlers[itr].qos), &len); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + /* send the subscribe packet */ + rc = aws_iot_mqtt_internal_send_packet(pClient, len, &timer); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + /* wait for suback */ + rc = aws_iot_mqtt_internal_wait_for_read(pClient, SUBACK, &timer); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + /* Granted QoS can be 0, 1 or 2 */ + rc = _aws_iot_mqtt_deserialize_suback(&packetId, 1, &count, grantedQoS, pClient->clientData.readBuf, + pClient->clientData.readBufSize); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + } + + FUNC_EXIT_RC(SUCCESS); +} + +/** + * @brief Subscribe to an MQTT topic. + * + * Called to send a subscribe message to the broker requesting a subscription + * to an MQTT topic. + * This is the outer function which does the validations and calls the internal resubscribe above + * to perform the actual operation. It is also responsible for client state changes + * @note Call is blocking. The call returns after the receipt of the SUBACK control packet. + * + * @param pClient Reference to the IoT Client + * + * @return An IoT Error Type defining successful/failed subscription + */ +IoT_Error_t aws_iot_mqtt_resubscribe(AWS_IoT_Client *pClient) { + IoT_Error_t rc, resubRc; + + FUNC_ENTRY; + + if(NULL == pClient) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + if(false == aws_iot_mqtt_is_client_connected(pClient)) { + FUNC_EXIT_RC(NETWORK_DISCONNECTED_ERROR); + } + + if(CLIENT_STATE_CONNECTED_IDLE != aws_iot_mqtt_get_client_state(pClient)) { + FUNC_EXIT_RC(MQTT_CLIENT_NOT_IDLE_ERROR); + } + + rc = aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTED_IDLE, + CLIENT_STATE_CONNECTED_RESUBSCRIBE_IN_PROGRESS); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + resubRc = _aws_iot_mqtt_internal_resubscribe(pClient); + + rc = aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTED_RESUBSCRIBE_IN_PROGRESS, + CLIENT_STATE_CONNECTED_IDLE); + if(SUCCESS == resubRc && SUCCESS != rc) { + resubRc = rc; + } + + FUNC_EXIT_RC(resubRc); +} + +#ifdef __cplusplus +} +#endif + diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_unsubscribe.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_unsubscribe.c new file mode 100644 index 00000000..fcbb97a9 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_unsubscribe.c @@ -0,0 +1,249 @@ +/* +* Copyright 2015-2016 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. +*/ + +// Based on Eclipse Paho. +/******************************************************************************* + * Copyright (c) 2014 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * Contributors: + * Ian Craggs - initial API and implementation and/or initial documentation + *******************************************************************************/ + +/** + * @file aws_iot_mqtt_client_unsubscribe.c + * @brief MQTT client unsubscribe API definitions + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "aws_iot_mqtt_client_common_internal.h" + +/** + * Serializes the supplied unsubscribe data into the supplied buffer, ready for sending + * @param pTxBuf the raw buffer data, of the correct length determined by the remaining length field + * @param txBufLen the length in bytes of the data in the supplied buffer + * @param dup integer - the MQTT dup flag + * @param packetId integer - the MQTT packet identifier + * @param count - number of members in the topicFilters array + * @param pTopicNameList - array of topic filter names + * @param pTopicNameLenList - array of length of topic filter names in pTopicNameList + * @param pSerializedLen - the length of the serialized data + * @return IoT_Error_t indicating function execution status + */ +static IoT_Error_t _aws_iot_mqtt_serialize_unsubscribe(unsigned char *pTxBuf, size_t txBufLen, + uint8_t dup, uint16_t packetId, + uint32_t count, const char **pTopicNameList, + uint16_t *pTopicNameLenList, uint32_t *pSerializedLen) { + unsigned char *ptr = pTxBuf; + uint32_t i = 0; + uint32_t rem_len = 2; /* packetId */ + IoT_Error_t rc; + MQTTHeader header = {0}; + + FUNC_ENTRY; + + for(i = 0; i < count; ++i) { + rem_len += (uint32_t) (pTopicNameLenList[i] + 2); /* topic + length */ + } + + if(aws_iot_mqtt_internal_get_final_packet_length_from_remaining_length(rem_len) > txBufLen) { + FUNC_EXIT_RC(MQTT_TX_BUFFER_TOO_SHORT_ERROR); + } + + rc = aws_iot_mqtt_internal_init_header(&header, UNSUBSCRIBE, QOS1, dup, 0); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + aws_iot_mqtt_internal_write_char(&ptr, header.byte); /* write header */ + + ptr += aws_iot_mqtt_internal_write_len_to_buffer(ptr, rem_len); /* write remaining length */ + + aws_iot_mqtt_internal_write_uint_16(&ptr, packetId); + + for(i = 0; i < count; ++i) { + aws_iot_mqtt_internal_write_utf8_string(&ptr, pTopicNameList[i], pTopicNameLenList[i]); + } + + *pSerializedLen = (uint32_t) (ptr - pTxBuf); + + FUNC_EXIT_RC(SUCCESS); +} + + +/** + * Deserializes the supplied (wire) buffer into unsuback data + * @param pPacketId returned integer - the MQTT packet identifier + * @param pRxBuf the raw buffer data, of the correct length determined by the remaining length field + * @param rxBufLen the length in bytes of the data in the supplied buffer + * @return IoT_Error_t indicating function execution status + */ +static IoT_Error_t _aws_iot_mqtt_deserialize_unsuback(uint16_t *pPacketId, unsigned char *pRxBuf, size_t rxBufLen) { + unsigned char type = 0; + unsigned char dup = 0; + IoT_Error_t rc; + + FUNC_ENTRY; + + rc = aws_iot_mqtt_internal_deserialize_ack(&type, &dup, pPacketId, pRxBuf, rxBufLen); + if(SUCCESS == rc && UNSUBACK != type) { + rc = FAILURE; + } + + FUNC_EXIT_RC(rc); +} + +/** + * @brief Unsubscribe to an MQTT topic. + * + * Called to send an unsubscribe message to the broker requesting removal of a subscription + * to an MQTT topic. + * @note Call is blocking. The call returns after the receipt of the UNSUBACK control packet. + * This is the internal function which is called by the unsubscribe API to perform the operation. + * Not meant to be called directly as it doesn't do validations or client state changes + * + * @param pClient Reference to the IoT Client + * @param pTopicName Topic Name to publish to + * @param topicNameLen Length of the topic name + * + * @return An IoT Error Type defining successful/failed unsubscribe call + */ +static IoT_Error_t _aws_iot_mqtt_internal_unsubscribe(AWS_IoT_Client *pClient, const char *pTopicFilter, + uint16_t topicFilterLen) { + /* No NULL checks because this is a static internal function */ + + Timer timer; + + uint16_t packet_id; + uint32_t serializedLen = 0; + uint32_t i = 0; + IoT_Error_t rc; + bool subscriptionExists = false; + + FUNC_ENTRY; + + /* Remove from message handler array */ + for(i = 0; i < AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; ++i) { + if(pClient->clientData.messageHandlers[i].topicName != NULL && + (strcmp(pClient->clientData.messageHandlers[i].topicName, pTopicFilter) == 0)) { + subscriptionExists = true; + } + } + + if(false == subscriptionExists) { + FUNC_EXIT_RC(FAILURE); + } + + init_timer(&timer); + countdown_ms(&timer, pClient->clientData.commandTimeoutMs); + + rc = _aws_iot_mqtt_serialize_unsubscribe(pClient->clientData.writeBuf, pClient->clientData.writeBufSize, 0, + aws_iot_mqtt_get_next_packet_id(pClient), 1, &pTopicFilter, + &topicFilterLen, &serializedLen); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + /* send the unsubscribe packet */ + rc = aws_iot_mqtt_internal_send_packet(pClient, serializedLen, &timer); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + rc = aws_iot_mqtt_internal_wait_for_read(pClient, UNSUBACK, &timer); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + rc = _aws_iot_mqtt_deserialize_unsuback(&packet_id, pClient->clientData.readBuf, pClient->clientData.readBufSize); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + /* Remove from message handler array */ + for(i = 0; i < AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; ++i) { + if(pClient->clientData.messageHandlers[i].topicName != NULL && + (strcmp(pClient->clientData.messageHandlers[i].topicName, pTopicFilter) == 0)) { + pClient->clientData.messageHandlers[i].topicName = NULL; + /* We don't want to break here, in case the same topic is registered + * with 2 callbacks. Unlikely scenario */ + } + } + + FUNC_EXIT_RC(SUCCESS); +} + +/** + * @brief Unsubscribe to an MQTT topic. + * + * Called to send an unsubscribe message to the broker requesting removal of a subscription + * to an MQTT topic. + * @note Call is blocking. The call returns after the receipt of the UNSUBACK control packet. + * This is the outer function which does the validations and calls the internal unsubscribe above + * to perform the actual operation. It is also responsible for client state changes + * + * @param pClient Reference to the IoT Client + * @param pTopicName Topic Name to publish to + * @param topicNameLen Length of the topic name + * + * @return An IoT Error Type defining successful/failed unsubscribe call + */ +IoT_Error_t aws_iot_mqtt_unsubscribe(AWS_IoT_Client *pClient, const char *pTopicFilter, uint16_t topicFilterLen) { + IoT_Error_t rc, unsubRc; + ClientState clientState; + + if(NULL == pClient || NULL == pTopicFilter) { + return NULL_VALUE_ERROR; + } + + if(!aws_iot_mqtt_is_client_connected(pClient)) { + return NETWORK_DISCONNECTED_ERROR; + } + + clientState = aws_iot_mqtt_get_client_state(pClient); + if(CLIENT_STATE_CONNECTED_IDLE != clientState && CLIENT_STATE_CONNECTED_WAIT_FOR_CB_RETURN != clientState) { + return MQTT_CLIENT_NOT_IDLE_ERROR; + } + + rc = aws_iot_mqtt_set_client_state(pClient, clientState, CLIENT_STATE_CONNECTED_UNSUBSCRIBE_IN_PROGRESS); + if(SUCCESS != rc) { + rc = aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTED_UNSUBSCRIBE_IN_PROGRESS, clientState); + return rc; + } + + unsubRc = _aws_iot_mqtt_internal_unsubscribe(pClient, pTopicFilter, topicFilterLen); + + rc = aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTED_UNSUBSCRIBE_IN_PROGRESS, clientState); + if(SUCCESS == unsubRc && SUCCESS != rc) { + unsubRc = rc; + } + + return unsubRc; +} + +#ifdef __cplusplus +} +#endif + diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_yield.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_yield.c new file mode 100644 index 00000000..c40bcbbb --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_yield.c @@ -0,0 +1,311 @@ +/* +* Copyright 2015-2016 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. +*/ + +// Based on Eclipse Paho. +/******************************************************************************* + * Copyright (c) 2014 IBM Corp. + * + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * and Eclipse Distribution License v1.0 which accompany this distribution. + * + * The Eclipse Public License is available at + * http://www.eclipse.org/legal/epl-v10.html + * and the Eclipse Distribution License is available at + * http://www.eclipse.org/org/documents/edl-v10.php. + * + * Contributors: + * Allan Stockdill-Mander/Ian Craggs - initial API and implementation and/or initial documentation + *******************************************************************************/ + +/** + * @file aws_iot_mqtt_client_yield.c + * @brief MQTT client yield API definitions + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "aws_iot_mqtt_client_common_internal.h" + +/** + * This is for the case when the aws_iot_mqtt_internal_send_packet Fails. + */ +static void _aws_iot_mqtt_force_client_disconnect(AWS_IoT_Client *pClient) { + pClient->clientStatus.clientState = CLIENT_STATE_DISCONNECTED_ERROR; + pClient->networkStack.disconnect(&(pClient->networkStack)); + pClient->networkStack.destroy(&(pClient->networkStack)); +} + +static IoT_Error_t _aws_iot_mqtt_handle_disconnect(AWS_IoT_Client *pClient) { + IoT_Error_t rc; + + FUNC_ENTRY; + + rc = aws_iot_mqtt_disconnect(pClient); + if(rc != SUCCESS) { + // If the aws_iot_mqtt_internal_send_packet prevents us from sending a disconnect packet then we have to clean the stack + _aws_iot_mqtt_force_client_disconnect(pClient); + } + + if(NULL != pClient->clientData.disconnectHandler) { + pClient->clientData.disconnectHandler(pClient, pClient->clientData.disconnectHandlerData); + } + + /* Reset to 0 since this was not a manual disconnect */ + pClient->clientStatus.clientState = CLIENT_STATE_DISCONNECTED_ERROR; + FUNC_EXIT_RC(NETWORK_DISCONNECTED_ERROR); +} + + +static IoT_Error_t _aws_iot_mqtt_handle_reconnect(AWS_IoT_Client *pClient) { + IoT_Error_t rc; + + FUNC_ENTRY; + + if(!has_timer_expired(&(pClient->reconnectDelayTimer))) { + /* Timer has not expired. Not time to attempt reconnect yet. + * Return attempting reconnect */ + FUNC_EXIT_RC(NETWORK_ATTEMPTING_RECONNECT); + } + + rc = NETWORK_PHYSICAL_LAYER_DISCONNECTED; + if(NULL != pClient->networkStack.isConnected) { + rc = pClient->networkStack.isConnected(&(pClient->networkStack)); + } + + if(NETWORK_PHYSICAL_LAYER_CONNECTED == rc) { + rc = aws_iot_mqtt_attempt_reconnect(pClient); + if(NETWORK_RECONNECTED == rc) { + rc = aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTED_IDLE, + CLIENT_STATE_CONNECTED_YIELD_IN_PROGRESS); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + FUNC_EXIT_RC(NETWORK_RECONNECTED); + } + } + + pClient->clientData.currentReconnectWaitInterval *= 2; + + if(AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL < pClient->clientData.currentReconnectWaitInterval) { + FUNC_EXIT_RC(NETWORK_RECONNECT_TIMED_OUT_ERROR); + } + countdown_ms(&(pClient->reconnectDelayTimer), pClient->clientData.currentReconnectWaitInterval); + FUNC_EXIT_RC(rc); +} + +static IoT_Error_t _aws_iot_mqtt_keep_alive(AWS_IoT_Client *pClient) { + IoT_Error_t rc = SUCCESS; + Timer timer; + size_t serialized_len; + + FUNC_ENTRY; + + if(NULL == pClient) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + if(0 == pClient->clientData.keepAliveInterval) { + FUNC_EXIT_RC(SUCCESS); + } + + if(!has_timer_expired(&pClient->pingTimer)) { + FUNC_EXIT_RC(SUCCESS); + } + + if(pClient->clientStatus.isPingOutstanding) { + rc = _aws_iot_mqtt_handle_disconnect(pClient); + FUNC_EXIT_RC(rc); + } + + /* there is no ping outstanding - send one */ + init_timer(&timer); + + countdown_ms(&timer, pClient->clientData.commandTimeoutMs); + serialized_len = 0; + rc = aws_iot_mqtt_internal_serialize_zero(pClient->clientData.writeBuf, pClient->clientData.writeBufSize, + PINGREQ, &serialized_len); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + /* send the ping packet */ + rc = aws_iot_mqtt_internal_send_packet(pClient, serialized_len, &timer); + if(SUCCESS != rc) { + //If sending a PING fails we can no longer determine if we are connected. In this case we decide we are disconnected and begin reconnection attempts + rc = _aws_iot_mqtt_handle_disconnect(pClient); + FUNC_EXIT_RC(rc); + } + + pClient->clientStatus.isPingOutstanding = true; + /* start a timer to wait for PINGRESP from server */ + countdown_sec(&pClient->pingTimer, pClient->clientData.keepAliveInterval); + + FUNC_EXIT_RC(SUCCESS); +} + +/** + * @brief Yield to the MQTT client + * + * Called to yield the current thread to the underlying MQTT client. This time is used by + * the MQTT client to manage PING requests to monitor the health of the TCP connection as + * well as periodically check the socket receive buffer for subscribe messages. Yield() + * must be called at a rate faster than the keepalive interval. It must also be called + * at a rate faster than the incoming message rate as this is the only way the client receives + * processing time to manage incoming messages. + * This is the internal function which is called by the yield API to perform the operation. + * Not meant to be called directly as it doesn't do validations or client state changes + * + * @param pClient Reference to the IoT Client + * @param timeout_ms Maximum number of milliseconds to pass thread execution to the client. + * + * @return An IoT Error Type defining successful/failed client processing. + * If this call results in an error it is likely the MQTT connection has dropped. + * iot_is_mqtt_connected can be called to confirm. + */ +static IoT_Error_t _aws_iot_mqtt_internal_yield(AWS_IoT_Client *pClient, uint32_t timeout_ms) { + IoT_Error_t yieldRc = SUCCESS; + + uint8_t packet_type; + ClientState clientState; + Timer timer; + init_timer(&timer); + countdown_ms(&timer, timeout_ms); + + FUNC_ENTRY; + + // evaluate timeout at the end of the loop to make sure the actual yield runs at least once + do { + clientState = aws_iot_mqtt_get_client_state(pClient); + if(CLIENT_STATE_PENDING_RECONNECT == clientState) { + if(AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL < pClient->clientData.currentReconnectWaitInterval) { + yieldRc = NETWORK_RECONNECT_TIMED_OUT_ERROR; + break; + } + yieldRc = _aws_iot_mqtt_handle_reconnect(pClient); + /* Network reconnect attempted, check if yield timer expired before + * doing anything else */ + continue; + } + + yieldRc = aws_iot_mqtt_internal_cycle_read(pClient, &timer, &packet_type); + if(SUCCESS == yieldRc) { + yieldRc = _aws_iot_mqtt_keep_alive(pClient); + } else { + // SSL read and write errors are terminal, connection must be closed and retried + if(NETWORK_SSL_READ_ERROR == yieldRc || NETWORK_SSL_READ_TIMEOUT_ERROR == yieldRc + || NETWORK_SSL_WRITE_ERROR == yieldRc || NETWORK_SSL_WRITE_TIMEOUT_ERROR == yieldRc) { + yieldRc = _aws_iot_mqtt_handle_disconnect(pClient); + } + } + + if(NETWORK_DISCONNECTED_ERROR == yieldRc) { + pClient->clientData.counterNetworkDisconnected++; + if(1 == pClient->clientStatus.isAutoReconnectEnabled) { + yieldRc = aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_DISCONNECTED_ERROR, + CLIENT_STATE_PENDING_RECONNECT); + if(SUCCESS != yieldRc) { + FUNC_EXIT_RC(yieldRc); + } + + pClient->clientData.currentReconnectWaitInterval = AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL; + countdown_ms(&(pClient->reconnectDelayTimer), pClient->clientData.currentReconnectWaitInterval); + /* Depending on timer values, it is possible that yield timer has expired + * Set to rc to attempting reconnect to inform client that autoreconnect + * attempt has started */ + yieldRc = NETWORK_ATTEMPTING_RECONNECT; + } else { + break; + } + } else if(SUCCESS != yieldRc) { + break; + } + } while(!has_timer_expired(&timer)); + + FUNC_EXIT_RC(yieldRc); +} + +/** + * @brief Yield to the MQTT client + * + * Called to yield the current thread to the underlying MQTT client. This time is used by + * the MQTT client to manage PING requests to monitor the health of the TCP connection as + * well as periodically check the socket receive buffer for subscribe messages. Yield() + * must be called at a rate faster than the keepalive interval. It must also be called + * at a rate faster than the incoming message rate as this is the only way the client receives + * processing time to manage incoming messages. + * This is the outer function which does the validations and calls the internal yield above + * to perform the actual operation. It is also responsible for client state changes + * + * @param pClient Reference to the IoT Client + * @param timeout_ms Maximum number of milliseconds to pass thread execution to the client. + * + * @return An IoT Error Type defining successful/failed client processing. + * If this call results in an error it is likely the MQTT connection has dropped. + * iot_is_mqtt_connected can be called to confirm. + */ +IoT_Error_t aws_iot_mqtt_yield(AWS_IoT_Client *pClient, uint32_t timeout_ms) { + IoT_Error_t rc, yieldRc; + ClientState clientState; + + if(NULL == pClient || 0 == timeout_ms) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + clientState = aws_iot_mqtt_get_client_state(pClient); + /* Check if network was manually disconnected */ + if(CLIENT_STATE_DISCONNECTED_MANUALLY == clientState) { + FUNC_EXIT_RC(NETWORK_MANUALLY_DISCONNECTED); + } + + /* If we are in the pending reconnect state, skip other checks. + * Pending reconnect state is only set when auto-reconnect is enabled */ + if(CLIENT_STATE_PENDING_RECONNECT != clientState) { + /* Check if network is disconnected and auto-reconnect is not enabled */ + if(!aws_iot_mqtt_is_client_connected(pClient)) { + FUNC_EXIT_RC(NETWORK_DISCONNECTED_ERROR); + } + + /* Check if client is idle, if not another operation is in progress and we should return */ + if(CLIENT_STATE_CONNECTED_IDLE != clientState) { + FUNC_EXIT_RC(MQTT_CLIENT_NOT_IDLE_ERROR); + } + + rc = aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTED_IDLE, + CLIENT_STATE_CONNECTED_YIELD_IN_PROGRESS); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + } + + yieldRc = _aws_iot_mqtt_internal_yield(pClient, timeout_ms); + + if(NETWORK_DISCONNECTED_ERROR != yieldRc && NETWORK_ATTEMPTING_RECONNECT != yieldRc) { + rc = aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTED_YIELD_IN_PROGRESS, + CLIENT_STATE_CONNECTED_IDLE); + if(SUCCESS == yieldRc && SUCCESS != rc) { + yieldRc = rc; + } + } + + FUNC_EXIT_RC(yieldRc); +} + +#ifdef __cplusplus +} +#endif + diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow.c new file mode 100644 index 00000000..6f29cafd --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow.c @@ -0,0 +1,229 @@ +/* + * 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_shadow.c + * @brief Shadow client API definitions + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "aws_iot_mqtt_client_interface.h" +#include "aws_iot_shadow_interface.h" +#include "aws_iot_error.h" +#include "aws_iot_log.h" +#include "aws_iot_shadow_actions.h" +#include "aws_iot_shadow_json.h" +#include "aws_iot_shadow_key.h" +#include "aws_iot_shadow_records.h" + +const ShadowInitParameters_t ShadowInitParametersDefault = {(char *) AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, NULL, NULL, + NULL, false, NULL}; + +const ShadowConnectParameters_t ShadowConnectParametersDefault = {(char *) AWS_IOT_MY_THING_NAME, + (char *) AWS_IOT_MQTT_CLIENT_ID, 0, NULL}; + +static char deleteAcceptedTopic[MAX_SHADOW_TOPIC_LENGTH_BYTES]; + +void aws_iot_shadow_reset_last_received_version(void) { + shadowJsonVersionNum = 0; +} + +uint32_t aws_iot_shadow_get_last_received_version(void) { + return shadowJsonVersionNum; +} + +void aws_iot_shadow_enable_discard_old_delta_msgs(void) { + shadowDiscardOldDeltaFlag = true; +} + +void aws_iot_shadow_disable_discard_old_delta_msgs(void) { + shadowDiscardOldDeltaFlag = false; +} + +IoT_Error_t aws_iot_shadow_init(AWS_IoT_Client *pClient, const ShadowInitParameters_t *pParams) { + IoT_Client_Init_Params mqttInitParams; + IoT_Error_t rc; + + FUNC_ENTRY; + + if(NULL == pClient || NULL == pParams) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + mqttInitParams.enableAutoReconnect = pParams->enableAutoReconnect; + mqttInitParams.pHostURL = pParams->pHost; + mqttInitParams.port = pParams->port; + mqttInitParams.pRootCALocation = pParams->pRootCA; + mqttInitParams.pDeviceCertLocation = pParams->pClientCRT; + mqttInitParams.pDevicePrivateKeyLocation = pParams->pClientKey; + mqttInitParams.mqttPacketTimeout_ms = 5000; + mqttInitParams.mqttCommandTimeout_ms = 20000; + mqttInitParams.tlsHandshakeTimeout_ms = 5000; + mqttInitParams.isSSLHostnameVerify = true; + mqttInitParams.disconnectHandler = pParams->disconnectHandler; + + rc = aws_iot_mqtt_init(pClient, &mqttInitParams); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + resetClientTokenSequenceNum(); + aws_iot_shadow_reset_last_received_version(); + initDeltaTokens(); + + FUNC_EXIT_RC(SUCCESS); +} + +IoT_Error_t aws_iot_shadow_connect(AWS_IoT_Client *pClient, const ShadowConnectParameters_t *pParams) { + IoT_Error_t rc = SUCCESS; + uint16_t deleteAcceptedTopicLen; + IoT_Client_Connect_Params ConnectParams = iotClientConnectParamsDefault; + + FUNC_ENTRY; + + if(NULL == pClient || NULL == pParams || NULL == pParams->pMqttClientId) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + snprintf(myThingName, MAX_SIZE_OF_THING_NAME, "%s", pParams->pMyThingName); + snprintf(mqttClientID, MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES, "%s", pParams->pMqttClientId); + + ConnectParams.keepAliveIntervalInSec = 600; // NOTE: Temporary fix + ConnectParams.MQTTVersion = MQTT_3_1_1; + ConnectParams.isCleanSession = true; + ConnectParams.isWillMsgPresent = false; + ConnectParams.pClientID = pParams->pMqttClientId; + ConnectParams.clientIDLen = pParams->mqttClientIdLen; + ConnectParams.pPassword = NULL; + ConnectParams.pUsername = NULL; + + rc = aws_iot_mqtt_connect(pClient, &ConnectParams); + + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + + initializeRecords(pClient); + + if(NULL != pParams->deleteActionHandler) { + snprintf(deleteAcceptedTopic, MAX_SHADOW_TOPIC_LENGTH_BYTES, + "$aws/things/%s/shadow/delete/accepted", myThingName); + deleteAcceptedTopicLen = (uint16_t) strlen(deleteAcceptedTopic); + rc = aws_iot_mqtt_subscribe(pClient, deleteAcceptedTopic, deleteAcceptedTopicLen, QOS1, + pParams->deleteActionHandler, (void *) myThingName); + } + + FUNC_EXIT_RC(rc); +} + +IoT_Error_t aws_iot_shadow_register_delta(AWS_IoT_Client *pMqttClient, jsonStruct_t *pStruct) { + if(NULL == pMqttClient || NULL == pStruct) { + return NULL_VALUE_ERROR; + } + + if(!aws_iot_mqtt_is_client_connected(pMqttClient)) { + return MQTT_CONNECTION_ERROR; + } + + return registerJsonTokenOnDelta(pStruct); +} + +IoT_Error_t aws_iot_shadow_yield(AWS_IoT_Client *pClient, uint32_t timeout) { + if(NULL == pClient) { + return NULL_VALUE_ERROR; + } + + HandleExpiredResponseCallbacks(); + return aws_iot_mqtt_yield(pClient, timeout); +} + +IoT_Error_t aws_iot_shadow_disconnect(AWS_IoT_Client *pClient) { + return aws_iot_mqtt_disconnect(pClient); +} + +IoT_Error_t aws_iot_shadow_update(AWS_IoT_Client *pClient, const char *pThingName, char *pJsonString, + fpActionCallback_t callback, void *pContextData, uint8_t timeout_seconds, + bool isPersistentSubscribe) { + IoT_Error_t rc; + + if(NULL == pClient) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + if(!aws_iot_mqtt_is_client_connected(pClient)) { + FUNC_EXIT_RC(MQTT_CONNECTION_ERROR); + } + + rc = aws_iot_shadow_internal_action(pThingName, SHADOW_UPDATE, pJsonString, callback, pContextData, + timeout_seconds, isPersistentSubscribe); + + FUNC_EXIT_RC(rc); +} + +IoT_Error_t aws_iot_shadow_delete(AWS_IoT_Client *pClient, const char *pThingName, fpActionCallback_t callback, + void *pContextData, uint8_t timeout_seconds, bool isPersistentSubscribe) { + char deleteRequestJsonBuf[MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE]; + IoT_Error_t rc; + + FUNC_ENTRY; + + if(NULL == pClient) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + if(!aws_iot_mqtt_is_client_connected(pClient)) { + FUNC_EXIT_RC(MQTT_CONNECTION_ERROR); + } + + aws_iot_shadow_internal_delete_request_json(deleteRequestJsonBuf); + rc = aws_iot_shadow_internal_action(pThingName, SHADOW_DELETE, deleteRequestJsonBuf, callback, pContextData, + timeout_seconds, isPersistentSubscribe); + + FUNC_EXIT_RC(rc); +} + +IoT_Error_t aws_iot_shadow_get(AWS_IoT_Client *pClient, const char *pThingName, fpActionCallback_t callback, + void *pContextData, uint8_t timeout_seconds, bool isPersistentSubscribe) { + char getRequestJsonBuf[MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE]; + IoT_Error_t rc; + + FUNC_ENTRY; + + if(NULL == pClient) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + if(!aws_iot_mqtt_is_client_connected(pClient)) { + FUNC_EXIT_RC(MQTT_CONNECTION_ERROR); + } + + aws_iot_shadow_internal_get_request_json(getRequestJsonBuf); + rc = aws_iot_shadow_internal_action(pThingName, SHADOW_GET, getRequestJsonBuf, callback, pContextData, + timeout_seconds, isPersistentSubscribe); + FUNC_EXIT_RC(rc); +} + +IoT_Error_t aws_iot_shadow_set_autoreconnect_status(AWS_IoT_Client *pClient, bool newStatus) { + return aws_iot_mqtt_autoreconnect_set_status(pClient, newStatus); +} + +#ifdef __cplusplus +} +#endif + diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow_actions.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow_actions.c new file mode 100644 index 00000000..ed0f0cf8 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow_actions.c @@ -0,0 +1,80 @@ +/* + * 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_shadow_actions.c + * @brief Shadow client Action API definitions + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "aws_iot_shadow_actions.h" + +#include "aws_iot_log.h" +#include "aws_iot_shadow_json.h" +#include "aws_iot_shadow_records.h" +#include "aws_iot_config.h" + +IoT_Error_t aws_iot_shadow_internal_action(const char *pThingName, ShadowActions_t action, + const char *pJsonDocumentToBeSent, fpActionCallback_t callback, + void *pCallbackContext, uint32_t timeout_seconds, bool isSticky) { + IoT_Error_t ret_val = SUCCESS; + bool isClientTokenPresent = false; + bool isAckWaitListFree = false; + uint8_t indexAckWaitList; + char extractedClientToken[MAX_SIZE_CLIENT_ID_WITH_SEQUENCE]; + + FUNC_ENTRY; + + if(NULL == pThingName || NULL == pJsonDocumentToBeSent) { + FUNC_EXIT_RC(NULL_VALUE_ERROR); + } + + isClientTokenPresent = extractClientToken(pJsonDocumentToBeSent, extractedClientToken); + + if(isClientTokenPresent && (NULL != callback)) { + if(getNextFreeIndexOfAckWaitList(&indexAckWaitList)) { + isAckWaitListFree = true; + } + + if(isAckWaitListFree) { + if(!isSubscriptionPresent(pThingName, action)) { + ret_val = subscribeToShadowActionAcks(pThingName, action, isSticky); + } else { + incrementSubscriptionCnt(pThingName, action, isSticky); + } + } + else { + ret_val = FAILURE; + } + } + + if(SUCCESS == ret_val) { + ret_val = publishToShadowAction(pThingName, action, pJsonDocumentToBeSent); + } + + if(isClientTokenPresent && (NULL != callback) && (SUCCESS == ret_val) && isAckWaitListFree) { + addToAckWaitList(indexAckWaitList, pThingName, action, extractedClientToken, callback, pCallbackContext, + timeout_seconds); + } + + FUNC_EXIT_RC(ret_val); +} + +#ifdef __cplusplus +} +#endif diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow_json.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow_json.c new file mode 100644 index 00000000..2ac49e2c --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow_json.c @@ -0,0 +1,479 @@ +/* + * 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_shadow_json.c + * @brief Shadow client JSON parsing API definitions + */ + +#ifdef __cplusplus +extern "C" { +#include +#else + +#include + +#endif + +#include "aws_iot_shadow_json.h" + +#include +#include + +#include "aws_iot_json_utils.h" +#include "aws_iot_log.h" +#include "aws_iot_shadow_key.h" +#include "aws_iot_config.h" + +extern char mqttClientID[MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES]; + +static uint32_t clientTokenNum = 0; + +//helper functions +static IoT_Error_t convertDataToString(char *pStringBuffer, size_t maxSizoStringBuffer, JsonPrimitiveType type, + void *pData); + +void resetClientTokenSequenceNum(void) { + clientTokenNum = 0; +} + +static void emptyJsonWithClientToken(char *pJsonDocument) { + sprintf(pJsonDocument, "{\"clientToken\":\""); + FillWithClientToken(pJsonDocument + strlen(pJsonDocument)); + sprintf(pJsonDocument + strlen(pJsonDocument), "\"}"); +} + +void aws_iot_shadow_internal_get_request_json(char *pJsonDocument) { + emptyJsonWithClientToken(pJsonDocument); +} + +void aws_iot_shadow_internal_delete_request_json(char *pJsonDocument) { + emptyJsonWithClientToken(pJsonDocument); +} + +static inline IoT_Error_t checkReturnValueOfSnPrintf(int32_t snPrintfReturn, size_t maxSizeOfJsonDocument) { + if(snPrintfReturn < 0) { + return SHADOW_JSON_ERROR; + } else if((size_t) snPrintfReturn >= maxSizeOfJsonDocument) { + return SHADOW_JSON_BUFFER_TRUNCATED; + } + return SUCCESS; +} + +IoT_Error_t aws_iot_shadow_init_json_document(char *pJsonDocument, size_t maxSizeOfJsonDocument) { + + IoT_Error_t ret_val = SUCCESS; + int32_t snPrintfReturn = 0; + + if(pJsonDocument == NULL) { + return NULL_VALUE_ERROR; + } + snPrintfReturn = snprintf(pJsonDocument, maxSizeOfJsonDocument, "{\"state\":{"); + + ret_val = checkReturnValueOfSnPrintf(snPrintfReturn, maxSizeOfJsonDocument); + + return ret_val; + +} + +IoT_Error_t aws_iot_shadow_add_desired(char *pJsonDocument, size_t maxSizeOfJsonDocument, uint8_t count, ...) { + IoT_Error_t ret_val = SUCCESS; + size_t tempSize = 0; + int8_t i; + size_t remSizeOfJsonBuffer = maxSizeOfJsonDocument; + int32_t snPrintfReturn = 0; + va_list pArgs; + jsonStruct_t *pTemporary = NULL; + va_start(pArgs, count); + + if(pJsonDocument == NULL) { + return NULL_VALUE_ERROR; + } + + tempSize = maxSizeOfJsonDocument - strlen(pJsonDocument); + if(tempSize <= 1) { + return SHADOW_JSON_ERROR; + } + remSizeOfJsonBuffer = tempSize; + + snPrintfReturn = snprintf(pJsonDocument + strlen(pJsonDocument), remSizeOfJsonBuffer, "\"desired\":{"); + ret_val = checkReturnValueOfSnPrintf(snPrintfReturn, remSizeOfJsonBuffer); + + if(ret_val != SUCCESS) { + return ret_val; + } + + for(i = 0; i < count; i++) { + tempSize = maxSizeOfJsonDocument - strlen(pJsonDocument); + if(tempSize <= 1) { + return SHADOW_JSON_ERROR; + } + remSizeOfJsonBuffer = tempSize; + pTemporary = va_arg (pArgs, jsonStruct_t *); + if(pTemporary != NULL) { + snPrintfReturn = snprintf(pJsonDocument + strlen(pJsonDocument), remSizeOfJsonBuffer, "\"%s\":", + pTemporary->pKey); + ret_val = checkReturnValueOfSnPrintf(snPrintfReturn, remSizeOfJsonBuffer); + if(ret_val != SUCCESS) { + return ret_val; + } + if(pTemporary->pKey != NULL && pTemporary->pData != NULL) { + ret_val = convertDataToString(pJsonDocument + strlen(pJsonDocument), remSizeOfJsonBuffer, + pTemporary->type, pTemporary->pData); + } else { + return NULL_VALUE_ERROR; + } + if(ret_val != SUCCESS) { + return ret_val; + } + } else { + return NULL_VALUE_ERROR; + } + } + + va_end(pArgs); + snPrintfReturn = snprintf(pJsonDocument + strlen(pJsonDocument) - 1, remSizeOfJsonBuffer, "},"); + ret_val = checkReturnValueOfSnPrintf(snPrintfReturn, remSizeOfJsonBuffer); + return ret_val; +} + +IoT_Error_t aws_iot_shadow_add_reported(char *pJsonDocument, size_t maxSizeOfJsonDocument, uint8_t count, ...) { + IoT_Error_t ret_val = SUCCESS; + + int8_t i; + size_t remSizeOfJsonBuffer = maxSizeOfJsonDocument; + int32_t snPrintfReturn = 0; + size_t tempSize = 0; + jsonStruct_t *pTemporary; + va_list pArgs; + va_start(pArgs, count); + + if(pJsonDocument == NULL) { + return NULL_VALUE_ERROR; + } + + + tempSize = maxSizeOfJsonDocument - strlen(pJsonDocument); + if(tempSize <= 1) { + return SHADOW_JSON_ERROR; + } + remSizeOfJsonBuffer = tempSize; + + snPrintfReturn = snprintf(pJsonDocument + strlen(pJsonDocument), remSizeOfJsonBuffer, "\"reported\":{"); + ret_val = checkReturnValueOfSnPrintf(snPrintfReturn, remSizeOfJsonBuffer); + + if(ret_val != SUCCESS) { + return ret_val; + } + + for(i = 0; i < count; i++) { + tempSize = maxSizeOfJsonDocument - strlen(pJsonDocument); + if(tempSize <= 1) { + return SHADOW_JSON_ERROR; + } + remSizeOfJsonBuffer = tempSize; + + pTemporary = va_arg (pArgs, jsonStruct_t *); + if(pTemporary != NULL) { + snPrintfReturn = snprintf(pJsonDocument + strlen(pJsonDocument), remSizeOfJsonBuffer, "\"%s\":", + pTemporary->pKey); + ret_val = checkReturnValueOfSnPrintf(snPrintfReturn, remSizeOfJsonBuffer); + if(ret_val != SUCCESS) { + return ret_val; + } + if(pTemporary->pKey != NULL && pTemporary->pData != NULL) { + ret_val = convertDataToString(pJsonDocument + strlen(pJsonDocument), remSizeOfJsonBuffer, + pTemporary->type, pTemporary->pData); + } else { + return NULL_VALUE_ERROR; + } + if(ret_val != SUCCESS) { + return ret_val; + } + } else { + return NULL_VALUE_ERROR; + } + } + + va_end(pArgs); + snPrintfReturn = snprintf(pJsonDocument + strlen(pJsonDocument) - 1, remSizeOfJsonBuffer, "},"); + ret_val = checkReturnValueOfSnPrintf(snPrintfReturn, remSizeOfJsonBuffer); + return ret_val; +} + + +int32_t FillWithClientTokenSize(char *pBufferToBeUpdatedWithClientToken, size_t maxSizeOfJsonDocument) { + int32_t snPrintfReturn; + snPrintfReturn = snprintf(pBufferToBeUpdatedWithClientToken, maxSizeOfJsonDocument, "%s-%d", mqttClientID, + (int) clientTokenNum++); + + return snPrintfReturn; +} + +IoT_Error_t aws_iot_fill_with_client_token(char *pBufferToBeUpdatedWithClientToken, size_t maxSizeOfJsonDocument) { + + int32_t snPrintfRet = 0; + snPrintfRet = FillWithClientTokenSize(pBufferToBeUpdatedWithClientToken, maxSizeOfJsonDocument); + return checkReturnValueOfSnPrintf(snPrintfRet, maxSizeOfJsonDocument); + +} + +IoT_Error_t aws_iot_finalize_json_document(char *pJsonDocument, size_t maxSizeOfJsonDocument) { + size_t remSizeOfJsonBuffer = maxSizeOfJsonDocument; + int32_t snPrintfReturn = 0; + size_t tempSize = 0; + IoT_Error_t ret_val = SUCCESS; + + if(pJsonDocument == NULL) { + return NULL_VALUE_ERROR; + } + + tempSize = maxSizeOfJsonDocument - strlen(pJsonDocument); + if(tempSize <= 1) { + return SHADOW_JSON_ERROR; + } + remSizeOfJsonBuffer = tempSize; + + // strlen(ShadowTxBuffer) - 1 is to ensure we remove the last ,(comma) that was added + snPrintfReturn = snprintf(pJsonDocument + strlen(pJsonDocument) - 1, remSizeOfJsonBuffer, "}, \"%s\":\"", + SHADOW_CLIENT_TOKEN_STRING); + ret_val = checkReturnValueOfSnPrintf(snPrintfReturn, remSizeOfJsonBuffer); + + if(ret_val != SUCCESS) { + return ret_val; + } + // refactor this XXX repeated code + tempSize = maxSizeOfJsonDocument - strlen(pJsonDocument); + if(tempSize <= 1) { + return SHADOW_JSON_ERROR; + } + remSizeOfJsonBuffer = tempSize; + + + snPrintfReturn = FillWithClientTokenSize(pJsonDocument + strlen(pJsonDocument), remSizeOfJsonBuffer); + ret_val = checkReturnValueOfSnPrintf(snPrintfReturn, remSizeOfJsonBuffer); + + if(ret_val != SUCCESS) { + return ret_val; + } + tempSize = maxSizeOfJsonDocument - strlen(pJsonDocument); + if(tempSize <= 1) { + return SHADOW_JSON_ERROR; + } + remSizeOfJsonBuffer = tempSize; + + + snPrintfReturn = snprintf(pJsonDocument + strlen(pJsonDocument), remSizeOfJsonBuffer, "\"}"); + ret_val = checkReturnValueOfSnPrintf(snPrintfReturn, remSizeOfJsonBuffer); + + return ret_val; +} + +void FillWithClientToken(char *pBufferToBeUpdatedWithClientToken) { + sprintf(pBufferToBeUpdatedWithClientToken, "%s-%d", mqttClientID, (int) clientTokenNum++); +} + +static IoT_Error_t convertDataToString(char *pStringBuffer, size_t maxSizoStringBuffer, JsonPrimitiveType type, + void *pData) { + int32_t snPrintfReturn = 0; + IoT_Error_t ret_val = SUCCESS; + + if(maxSizoStringBuffer == 0) { + return SHADOW_JSON_ERROR; + } + + if(type == SHADOW_JSON_INT32) { + snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%" PRIi32",", *(int32_t *) (pData)); + } else if(type == SHADOW_JSON_INT16) { + snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%" PRIi16",", *(int16_t *) (pData)); + } else if(type == SHADOW_JSON_INT8) { + snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%" PRIi8",", *(int8_t *) (pData)); + } else if(type == SHADOW_JSON_UINT32) { + snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%" PRIu32",", *(uint32_t *) (pData)); + } else if(type == SHADOW_JSON_UINT16) { + snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%" PRIu16",", *(uint16_t *) (pData)); + } else if(type == SHADOW_JSON_UINT8) { + snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%" PRIu8",", *(uint8_t *) (pData)); + } else if(type == SHADOW_JSON_DOUBLE) { + snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%f,", *(double *) (pData)); + } else if(type == SHADOW_JSON_FLOAT) { + snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%f,", *(float *) (pData)); + } else if(type == SHADOW_JSON_BOOL) { + snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%s,", *(bool *) (pData) ? "true" : "false"); + } else if(type == SHADOW_JSON_STRING) { + snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "\"%s\",", (char *) (pData)); + } else if(type == SHADOW_JSON_OBJECT) { + snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%s,", (char *) (pData)); + } + + + ret_val = checkReturnValueOfSnPrintf(snPrintfReturn, maxSizoStringBuffer); + + return ret_val; +} + +static jsmn_parser shadowJsonParser; +static jsmntok_t jsonTokenStruct[MAX_JSON_TOKEN_EXPECTED]; + +bool isJsonValidAndParse(const char *pJsonDocument, void *pJsonHandler, int32_t *pTokenCount) { + int32_t tokenCount; + + IOT_UNUSED(pJsonHandler); + + jsmn_init(&shadowJsonParser); + + tokenCount = jsmn_parse(&shadowJsonParser, pJsonDocument, strlen(pJsonDocument), jsonTokenStruct, + sizeof(jsonTokenStruct) / sizeof(jsonTokenStruct[0])); + + if(tokenCount < 0) { + IOT_WARN("Failed to parse JSON: %d\n", tokenCount); + return false; + } + + /* Assume the top-level element is an object */ + if(tokenCount < 1 || jsonTokenStruct[0].type != JSMN_OBJECT) { + IOT_WARN("Top Level is not an object\n"); + return false; + } + + *pTokenCount = tokenCount; + + return true; +} + +static IoT_Error_t UpdateValueIfNoObject(const char *pJsonString, jsonStruct_t *pDataStruct, jsmntok_t token) { + IoT_Error_t ret_val = SUCCESS; + if(pDataStruct->type == SHADOW_JSON_BOOL) { + ret_val = parseBooleanValue((bool *) pDataStruct->pData, pJsonString, &token); + } else if(pDataStruct->type == SHADOW_JSON_INT32) { + ret_val = parseInteger32Value((int32_t *) pDataStruct->pData, pJsonString, &token); + } else if(pDataStruct->type == SHADOW_JSON_INT16) { + ret_val = parseInteger16Value((int16_t *) pDataStruct->pData, pJsonString, &token); + } else if(pDataStruct->type == SHADOW_JSON_INT8) { + ret_val = parseInteger8Value((int8_t *) pDataStruct->pData, pJsonString, &token); + } else if(pDataStruct->type == SHADOW_JSON_UINT32) { + ret_val = parseUnsignedInteger32Value((uint32_t *) pDataStruct->pData, pJsonString, &token); + } else if(pDataStruct->type == SHADOW_JSON_UINT16) { + ret_val = parseUnsignedInteger16Value((uint16_t *) pDataStruct->pData, pJsonString, &token); + } else if(pDataStruct->type == SHADOW_JSON_UINT8) { + ret_val = parseUnsignedInteger8Value((uint8_t *) pDataStruct->pData, pJsonString, &token); + } else if(pDataStruct->type == SHADOW_JSON_FLOAT) { + ret_val = parseFloatValue((float *) pDataStruct->pData, pJsonString, &token); + } else if(pDataStruct->type == SHADOW_JSON_DOUBLE) { + ret_val = parseDoubleValue((double *) pDataStruct->pData, pJsonString, &token); + } else if(pDataStruct->type == SHADOW_JSON_STRING) { + ret_val = parseStringValue((char *) pDataStruct->pData, pJsonString, &token); + } + + return ret_val; +} + +bool isJsonKeyMatchingAndUpdateValue(const char *pJsonDocument, void *pJsonHandler, int32_t tokenCount, + jsonStruct_t *pDataStruct, uint32_t *pDataLength, int32_t *pDataPosition) { + int32_t i; + uint32_t dataLength; + jsmntok_t dataToken; + + IOT_UNUSED(pJsonHandler); + + for(i = 1; i < tokenCount; i++) { + if(jsoneq(pJsonDocument, &(jsonTokenStruct[i]), pDataStruct->pKey) == 0) { + dataToken = jsonTokenStruct[i + 1]; + dataLength = (uint32_t) (dataToken.end - dataToken.start); + UpdateValueIfNoObject(pJsonDocument, pDataStruct, dataToken); + *pDataPosition = dataToken.start; + *pDataLength = dataLength; + return true; + } else if(jsoneq(pJsonDocument, &(jsonTokenStruct[i]), "metadata") == 0) { + return false; + } + } + return false; +} + +bool isReceivedJsonValid(const char *pJsonDocument) { + int32_t tokenCount; + + jsmn_init(&shadowJsonParser); + + tokenCount = jsmn_parse(&shadowJsonParser, pJsonDocument, strlen(pJsonDocument), jsonTokenStruct, + sizeof(jsonTokenStruct) / sizeof(jsonTokenStruct[0])); + + if(tokenCount < 0) { + IOT_WARN("Failed to parse JSON: %d\n", tokenCount); + return false; + } + + /* Assume the top-level element is an object */ + if(tokenCount < 1 || jsonTokenStruct[0].type != JSMN_OBJECT) { + return false; + } + + return true; +} + +bool extractClientToken(const char *pJsonDocument, char *pExtractedClientToken) { + int32_t tokenCount, i; + uint8_t length; + jsmntok_t ClientJsonToken; + jsmn_init(&shadowJsonParser); + + tokenCount = jsmn_parse(&shadowJsonParser, pJsonDocument, strlen(pJsonDocument), jsonTokenStruct, + sizeof(jsonTokenStruct) / sizeof(jsonTokenStruct[0])); + + if(tokenCount < 0) { + IOT_WARN("Failed to parse JSON: %d\n", tokenCount); + return false; + } + + /* Assume the top-level element is an object */ + if(tokenCount < 1 || jsonTokenStruct[0].type != JSMN_OBJECT) { + return false; + } + + for(i = 1; i < tokenCount; i++) { + if(jsoneq(pJsonDocument, &jsonTokenStruct[i], SHADOW_CLIENT_TOKEN_STRING) == 0) { + ClientJsonToken = jsonTokenStruct[i + 1]; + length = (uint8_t) (ClientJsonToken.end - ClientJsonToken.start); + strncpy(pExtractedClientToken, pJsonDocument + ClientJsonToken.start, length); + pExtractedClientToken[length] = '\0'; + return true; + } + } + + return false; +} + +bool extractVersionNumber(const char *pJsonDocument, void *pJsonHandler, int32_t tokenCount, uint32_t *pVersionNumber) { + int32_t i; + IoT_Error_t ret_val = SUCCESS; + + IOT_UNUSED(pJsonHandler); + + for(i = 1; i < tokenCount; i++) { + if(jsoneq(pJsonDocument, &(jsonTokenStruct[i]), SHADOW_VERSION_STRING) == 0) { + ret_val = parseUnsignedInteger32Value(pVersionNumber, pJsonDocument, &jsonTokenStruct[i + 1]); + if(ret_val == SUCCESS) { + return true; + } + } + } + return false; +} + +#ifdef __cplusplus +} +#endif + diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow_records.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow_records.c new file mode 100644 index 00000000..03486679 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow_records.c @@ -0,0 +1,527 @@ +/* + * 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_mqtt_client_subscribe.c + * @brief MQTT client subscribe API definitions + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include "aws_iot_shadow_records.h" + +#include +#include + +#include "timer_interface.h" +#include "aws_iot_json_utils.h" +#include "aws_iot_log.h" +#include "aws_iot_shadow_json.h" +#include "aws_iot_config.h" + +typedef struct { + char clientTokenID[MAX_SIZE_CLIENT_ID_WITH_SEQUENCE]; + char thingName[MAX_SIZE_OF_THING_NAME]; + ShadowActions_t action; + fpActionCallback_t callback; + void *pCallbackContext; + bool isFree; + Timer timer; +} ToBeReceivedAckRecord_t; + +typedef struct { + const char *pKey; + void *pStruct; + jsonStructCallback_t callback; + bool isFree; +} JsonTokenTable_t; + +typedef struct { + char Topic[MAX_SHADOW_TOPIC_LENGTH_BYTES]; + uint8_t count; + bool isFree; + bool isSticky; +} SubscriptionRecord_t; + +typedef enum { + SHADOW_ACCEPTED, SHADOW_REJECTED, SHADOW_ACTION +} ShadowAckTopicTypes_t; + +ToBeReceivedAckRecord_t AckWaitList[MAX_ACKS_TO_COMEIN_AT_ANY_GIVEN_TIME]; + +AWS_IoT_Client *pMqttClient; + +char myThingName[MAX_SIZE_OF_THING_NAME]; +char mqttClientID[MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES]; + +char shadowDeltaTopic[MAX_SHADOW_TOPIC_LENGTH_BYTES]; + +#define MAX_TOPICS_AT_ANY_GIVEN_TIME 2*MAX_THINGNAME_HANDLED_AT_ANY_GIVEN_TIME +SubscriptionRecord_t SubscriptionList[MAX_TOPICS_AT_ANY_GIVEN_TIME]; + +#define SUBSCRIBE_SETTLING_TIME 2 +char shadowRxBuf[SHADOW_MAX_SIZE_OF_RX_BUFFER]; + +static JsonTokenTable_t tokenTable[MAX_JSON_TOKEN_EXPECTED]; +static uint32_t tokenTableIndex = 0; +static bool deltaTopicSubscribedFlag = false; +uint32_t shadowJsonVersionNum = 0; +bool shadowDiscardOldDeltaFlag = true; + +// local helper functions +static void AckStatusCallback(AWS_IoT_Client *pClient, char *topicName, + uint16_t topicNameLen, IoT_Publish_Message_Params *params, void *pData); + +static void shadow_delta_callback(AWS_IoT_Client *pClient, char *topicName, + uint16_t topicNameLen, IoT_Publish_Message_Params *params, void *pData); + +static void topicNameFromThingAndAction(char *pTopic, const char *pThingName, ShadowActions_t action, + ShadowAckTopicTypes_t ackType); + +static int16_t getNextFreeIndexOfSubscriptionList(void); + +static void unsubscribeFromAcceptedAndRejected(uint8_t index); + +void initDeltaTokens(void) { + uint32_t i; + for(i = 0; i < MAX_JSON_TOKEN_EXPECTED; i++) { + tokenTable[i].isFree = true; + } + tokenTableIndex = 0; + deltaTopicSubscribedFlag = false; +} + +IoT_Error_t registerJsonTokenOnDelta(jsonStruct_t *pStruct) { + + IoT_Error_t rc = SUCCESS; + + if(!deltaTopicSubscribedFlag) { + snprintf(shadowDeltaTopic, MAX_SHADOW_TOPIC_LENGTH_BYTES, "$aws/things/%s/shadow/update/delta", myThingName); + rc = aws_iot_mqtt_subscribe(pMqttClient, shadowDeltaTopic, (uint16_t) strlen(shadowDeltaTopic), QOS0, + shadow_delta_callback, NULL); + deltaTopicSubscribedFlag = true; + } + + if(tokenTableIndex >= MAX_JSON_TOKEN_EXPECTED) { + return FAILURE; + } + + tokenTable[tokenTableIndex].pKey = pStruct->pKey; + tokenTable[tokenTableIndex].callback = pStruct->cb; + tokenTable[tokenTableIndex].pStruct = pStruct; + tokenTable[tokenTableIndex].isFree = false; + tokenTableIndex++; + + return rc; +} + +static int16_t getNextFreeIndexOfSubscriptionList(void) { + uint8_t i; + for(i = 0; i < MAX_TOPICS_AT_ANY_GIVEN_TIME; i++) { + if(SubscriptionList[i].isFree) { + SubscriptionList[i].isFree = false; + return i; + } + } + return -1; +} + +static void topicNameFromThingAndAction(char *pTopic, const char *pThingName, ShadowActions_t action, + ShadowAckTopicTypes_t ackType) { + + char actionBuf[10]; + char ackTypeBuf[10]; + + if(SHADOW_GET == action) { + strncpy(actionBuf, "get", 10); + } else if(SHADOW_UPDATE == action) { + strncpy(actionBuf, "update", 10); + } else if(SHADOW_DELETE == action) { + strncpy(actionBuf, "delete", 10); + } + + if(SHADOW_ACCEPTED == ackType) { + strncpy(ackTypeBuf, "accepted", 10); + } else if(SHADOW_REJECTED == ackType) { + strncpy(ackTypeBuf, "rejected", 10); + } + + if(SHADOW_ACTION == ackType) { + snprintf(pTopic, MAX_SHADOW_TOPIC_LENGTH_BYTES, "$aws/things/%s/shadow/%s", pThingName, actionBuf); + } else { + snprintf(pTopic, MAX_SHADOW_TOPIC_LENGTH_BYTES, "$aws/things/%s/shadow/%s/%s", pThingName, actionBuf, + ackTypeBuf); + } +} + +static bool isValidShadowVersionUpdate(const char *pTopicName) { + if(strstr(pTopicName, myThingName) != NULL && + ((strstr(pTopicName, "get/accepted") != NULL) || + (strstr(pTopicName, "delta") != NULL))) { + return true; + } + return false; +} + +static void AckStatusCallback(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, + IoT_Publish_Message_Params *params, void *pData) { + int32_t tokenCount; + uint8_t i; + void *pJsonHandler = NULL; + char temporaryClientToken[MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE]; + + IOT_UNUSED(pClient); + IOT_UNUSED(topicNameLen); + IOT_UNUSED(pData); + + if(params->payloadLen >= SHADOW_MAX_SIZE_OF_RX_BUFFER) { + IOT_WARN("Payload larger than RX Buffer"); + return; + } + + memcpy(shadowRxBuf, params->payload, params->payloadLen); + shadowRxBuf[params->payloadLen] = '\0'; // jsmn_parse relies on a string + + if(!isJsonValidAndParse(shadowRxBuf, pJsonHandler, &tokenCount)) { + IOT_WARN("Received JSON is not valid"); + return; + } + + if(isValidShadowVersionUpdate(topicName)) { + uint32_t tempVersionNumber = 0; + if(extractVersionNumber(shadowRxBuf, pJsonHandler, tokenCount, &tempVersionNumber)) { + if(tempVersionNumber > shadowJsonVersionNum) { + shadowJsonVersionNum = tempVersionNumber; + } + } + } + + if(extractClientToken(shadowRxBuf, temporaryClientToken)) { + for(i = 0; i < MAX_ACKS_TO_COMEIN_AT_ANY_GIVEN_TIME; i++) { + if(!AckWaitList[i].isFree) { + if(strcmp(AckWaitList[i].clientTokenID, temporaryClientToken) == 0) { + Shadow_Ack_Status_t status = SHADOW_ACK_REJECTED; + if(strstr(topicName, "accepted") != NULL) { + status = SHADOW_ACK_ACCEPTED; + } else if(strstr(topicName, "rejected") != NULL) { + status = SHADOW_ACK_REJECTED; + } + if(status == SHADOW_ACK_ACCEPTED || status == SHADOW_ACK_REJECTED) { + if(AckWaitList[i].callback != NULL) { + AckWaitList[i].callback(AckWaitList[i].thingName, AckWaitList[i].action, status, + shadowRxBuf, AckWaitList[i].pCallbackContext); + } + unsubscribeFromAcceptedAndRejected(i); + AckWaitList[i].isFree = true; + return; + } + } + } + } + } +} + +static int16_t findIndexOfSubscriptionList(const char *pTopic) { + uint8_t i; + for(i = 0; i < MAX_TOPICS_AT_ANY_GIVEN_TIME; i++) { + if(!SubscriptionList[i].isFree) { + if((strcmp(pTopic, SubscriptionList[i].Topic) == 0)) { + return i; + } + } + } + return -1; +} + +static void unsubscribeFromAcceptedAndRejected(uint8_t index) { + + char TemporaryTopicNameAccepted[MAX_SHADOW_TOPIC_LENGTH_BYTES]; + char TemporaryTopicNameRejected[MAX_SHADOW_TOPIC_LENGTH_BYTES]; + IoT_Error_t ret_val = SUCCESS; + + int16_t indexSubList; + + topicNameFromThingAndAction(TemporaryTopicNameAccepted, AckWaitList[index].thingName, AckWaitList[index].action, + SHADOW_ACCEPTED); + topicNameFromThingAndAction(TemporaryTopicNameRejected, AckWaitList[index].thingName, AckWaitList[index].action, + SHADOW_REJECTED); + + indexSubList = findIndexOfSubscriptionList(TemporaryTopicNameAccepted); + if((indexSubList >= 0)) { + if(!SubscriptionList[indexSubList].isSticky && (SubscriptionList[indexSubList].count == 1)) { + ret_val = aws_iot_mqtt_unsubscribe(pMqttClient, TemporaryTopicNameAccepted, + (uint16_t) strlen(TemporaryTopicNameAccepted)); + if(ret_val == SUCCESS) { + SubscriptionList[indexSubList].isFree = true; + } + } else if(SubscriptionList[indexSubList].count > 1) { + SubscriptionList[indexSubList].count--; + } + } + + indexSubList = findIndexOfSubscriptionList(TemporaryTopicNameRejected); + if((indexSubList >= 0)) { + if(!SubscriptionList[indexSubList].isSticky && (SubscriptionList[indexSubList].count == 1)) { + ret_val = aws_iot_mqtt_unsubscribe(pMqttClient, TemporaryTopicNameRejected, + (uint16_t) strlen(TemporaryTopicNameRejected)); + if(ret_val == SUCCESS) { + SubscriptionList[indexSubList].isFree = true; + } + } else if(SubscriptionList[indexSubList].count > 1) { + SubscriptionList[indexSubList].count--; + } + } +} + +void initializeRecords(AWS_IoT_Client *pClient) { + uint8_t i; + for(i = 0; i < MAX_ACKS_TO_COMEIN_AT_ANY_GIVEN_TIME; i++) { + AckWaitList[i].isFree = true; + } + for(i = 0; i < MAX_TOPICS_AT_ANY_GIVEN_TIME; i++) { + SubscriptionList[i].isFree = true; + SubscriptionList[i].count = 0; + SubscriptionList[i].isSticky = false; + } + + pMqttClient = pClient; +} + +bool isSubscriptionPresent(const char *pThingName, ShadowActions_t action) { + + uint8_t i = 0; + bool isAcceptedPresent = false; + bool isRejectedPresent = false; + char TemporaryTopicNameAccepted[MAX_SHADOW_TOPIC_LENGTH_BYTES]; + char TemporaryTopicNameRejected[MAX_SHADOW_TOPIC_LENGTH_BYTES]; + + topicNameFromThingAndAction(TemporaryTopicNameAccepted, pThingName, action, SHADOW_ACCEPTED); + topicNameFromThingAndAction(TemporaryTopicNameRejected, pThingName, action, SHADOW_REJECTED); + + for(i = 0; i < MAX_TOPICS_AT_ANY_GIVEN_TIME; i++) { + if(!SubscriptionList[i].isFree) { + if((strcmp(TemporaryTopicNameAccepted, SubscriptionList[i].Topic) == 0)) { + isAcceptedPresent = true; + } else if((strcmp(TemporaryTopicNameRejected, SubscriptionList[i].Topic) == 0)) { + isRejectedPresent = true; + } + } + } + + if(isRejectedPresent && isAcceptedPresent) { + return true; + } + + return false; +} + +IoT_Error_t subscribeToShadowActionAcks(const char *pThingName, ShadowActions_t action, bool isSticky) { + IoT_Error_t ret_val = SUCCESS; + + bool clearBothEntriesFromList = true; + int16_t indexAcceptedSubList = 0; + int16_t indexRejectedSubList = 0; + Timer subSettlingtimer; + indexAcceptedSubList = getNextFreeIndexOfSubscriptionList(); + indexRejectedSubList = getNextFreeIndexOfSubscriptionList(); + + if(indexAcceptedSubList >= 0 && indexRejectedSubList >= 0) { + topicNameFromThingAndAction(SubscriptionList[indexAcceptedSubList].Topic, pThingName, action, SHADOW_ACCEPTED); + ret_val = aws_iot_mqtt_subscribe(pMqttClient, SubscriptionList[indexAcceptedSubList].Topic, + (uint16_t) strlen(SubscriptionList[indexAcceptedSubList].Topic), QOS0, + AckStatusCallback, NULL); + if(ret_val == SUCCESS) { + SubscriptionList[indexAcceptedSubList].count = 1; + SubscriptionList[indexAcceptedSubList].isSticky = isSticky; + topicNameFromThingAndAction(SubscriptionList[indexRejectedSubList].Topic, pThingName, action, + SHADOW_REJECTED); + ret_val = aws_iot_mqtt_subscribe(pMqttClient, SubscriptionList[indexRejectedSubList].Topic, + (uint16_t) strlen(SubscriptionList[indexRejectedSubList].Topic), QOS0, + AckStatusCallback, NULL); + if(ret_val == SUCCESS) { + SubscriptionList[indexRejectedSubList].count = 1; + SubscriptionList[indexRejectedSubList].isSticky = isSticky; + clearBothEntriesFromList = false; + + // wait for SUBSCRIBE_SETTLING_TIME seconds to let the subscription take effect + init_timer(&subSettlingtimer); + countdown_sec(&subSettlingtimer, SUBSCRIBE_SETTLING_TIME); + while(!has_timer_expired(&subSettlingtimer)); + + } + } + } + + if(clearBothEntriesFromList) { + if(indexAcceptedSubList >= 0) { + SubscriptionList[indexAcceptedSubList].isFree = true; + } + if(indexRejectedSubList >= 0) { + SubscriptionList[indexRejectedSubList].isFree = true; + } + if(SubscriptionList[indexAcceptedSubList].count == 1) { + aws_iot_mqtt_unsubscribe(pMqttClient, SubscriptionList[indexAcceptedSubList].Topic, + (uint16_t) strlen(SubscriptionList[indexAcceptedSubList].Topic)); + } + } + + return ret_val; +} + +void incrementSubscriptionCnt(const char *pThingName, ShadowActions_t action, bool isSticky) { + char TemporaryTopicNameAccepted[MAX_SHADOW_TOPIC_LENGTH_BYTES]; + char TemporaryTopicNameRejected[MAX_SHADOW_TOPIC_LENGTH_BYTES]; + uint8_t i; + topicNameFromThingAndAction(TemporaryTopicNameAccepted, pThingName, action, SHADOW_ACCEPTED); + topicNameFromThingAndAction(TemporaryTopicNameRejected, pThingName, action, SHADOW_REJECTED); + + for(i = 0; i < MAX_TOPICS_AT_ANY_GIVEN_TIME; i++) { + if(!SubscriptionList[i].isFree) { + if((strcmp(TemporaryTopicNameAccepted, SubscriptionList[i].Topic) == 0) + || (strcmp(TemporaryTopicNameRejected, SubscriptionList[i].Topic) == 0)) { + SubscriptionList[i].count++; + SubscriptionList[i].isSticky = isSticky; + } + } + } +} + +IoT_Error_t publishToShadowAction(const char *pThingName, ShadowActions_t action, const char *pJsonDocumentToBeSent) { + IoT_Error_t ret_val = SUCCESS; + char TemporaryTopicName[MAX_SHADOW_TOPIC_LENGTH_BYTES]; + IoT_Publish_Message_Params msgParams; + + if(NULL == pThingName || NULL == pJsonDocumentToBeSent) { + return NULL_VALUE_ERROR; + } + + topicNameFromThingAndAction(TemporaryTopicName, pThingName, action, SHADOW_ACTION); + + msgParams.qos = QOS0; + msgParams.isRetained = 0; + msgParams.payloadLen = strlen(pJsonDocumentToBeSent); + msgParams.payload = (char *) pJsonDocumentToBeSent; + ret_val = aws_iot_mqtt_publish(pMqttClient, TemporaryTopicName, (uint16_t) strlen(TemporaryTopicName), &msgParams); + + return ret_val; +} + +bool getNextFreeIndexOfAckWaitList(uint8_t *pIndex) { + uint8_t i; + bool rc = false; + + if(NULL == pIndex) { + return false; + } + + for(i = 0; i < MAX_ACKS_TO_COMEIN_AT_ANY_GIVEN_TIME; i++) { + if(AckWaitList[i].isFree) { + *pIndex = i; + rc = true; + break; + } + } + + return rc; +} + +void addToAckWaitList(uint8_t indexAckWaitList, const char *pThingName, ShadowActions_t action, + const char *pExtractedClientToken, fpActionCallback_t callback, void *pCallbackContext, + uint32_t timeout_seconds) { + AckWaitList[indexAckWaitList].callback = callback; + strncpy(AckWaitList[indexAckWaitList].clientTokenID, pExtractedClientToken, MAX_SIZE_CLIENT_ID_WITH_SEQUENCE); + strncpy(AckWaitList[indexAckWaitList].thingName, pThingName, MAX_SIZE_OF_THING_NAME); + AckWaitList[indexAckWaitList].pCallbackContext = pCallbackContext; + AckWaitList[indexAckWaitList].action = action; + init_timer(&(AckWaitList[indexAckWaitList].timer)); + countdown_sec(&(AckWaitList[indexAckWaitList].timer), timeout_seconds); + AckWaitList[indexAckWaitList].isFree = false; +} + +void HandleExpiredResponseCallbacks(void) { + uint8_t i; + for(i = 0; i < MAX_ACKS_TO_COMEIN_AT_ANY_GIVEN_TIME; i++) { + if(!AckWaitList[i].isFree) { + if(has_timer_expired(&(AckWaitList[i].timer))) { + if(AckWaitList[i].callback != NULL) { + AckWaitList[i].callback(AckWaitList[i].thingName, AckWaitList[i].action, SHADOW_ACK_TIMEOUT, + shadowRxBuf, AckWaitList[i].pCallbackContext); + } + AckWaitList[i].isFree = true; + unsubscribeFromAcceptedAndRejected(i); + } + } + } +} + +static void shadow_delta_callback(AWS_IoT_Client *pClient, char *topicName, + uint16_t topicNameLen, IoT_Publish_Message_Params *params, void *pData) { + int32_t tokenCount; + uint32_t i = 0; + void *pJsonHandler = NULL; + int32_t DataPosition; + uint32_t dataLength; + uint32_t tempVersionNumber = 0; + + FUNC_ENTRY; + + IOT_UNUSED(pClient); + IOT_UNUSED(topicName); + IOT_UNUSED(topicNameLen); + IOT_UNUSED(pData); + + if(params->payloadLen >= SHADOW_MAX_SIZE_OF_RX_BUFFER) { + IOT_WARN("Payload larger than RX Buffer"); + return; + } + + memcpy(shadowRxBuf, params->payload, params->payloadLen); + shadowRxBuf[params->payloadLen] = '\0'; // jsmn_parse relies on a string + + if(!isJsonValidAndParse(shadowRxBuf, pJsonHandler, &tokenCount)) { + IOT_WARN("Received JSON is not valid"); + return; + } + + if(shadowDiscardOldDeltaFlag) { + if(extractVersionNumber(shadowRxBuf, pJsonHandler, tokenCount, &tempVersionNumber)) { + if(tempVersionNumber > shadowJsonVersionNum) { + shadowJsonVersionNum = tempVersionNumber; + } else { + IOT_WARN("Old Delta Message received - Ignoring rx: %d local: %d", tempVersionNumber, + shadowJsonVersionNum); + return; + } + } + } + + for(i = 0; i < tokenTableIndex; i++) { + if(!tokenTable[i].isFree) { + if(isJsonKeyMatchingAndUpdateValue(shadowRxBuf, pJsonHandler, tokenCount, + (jsonStruct_t *) tokenTable[i].pStruct, &dataLength, &DataPosition)) { + if(tokenTable[i].callback != NULL) { + tokenTable[i].callback(shadowRxBuf + DataPosition, dataLength, + (jsonStruct_t *) tokenTable[i].pStruct); + } + } + } + } +} + +#ifdef __cplusplus +} +#endif diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/README.md b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/README.md new file mode 100644 index 00000000..3625bae6 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/README.md @@ -0,0 +1,9 @@ +# Tests +This folder contains tests to verify SDK functionality. These have been tested to work with Linux but haven't been ported to any specific platform. For additional information about porting the Device SDK for embedded C onto additional platforms please refer to the [PortingGuide](https://github.com/aws/aws-iot-device-sdk-embedded-c/blob/master/PortingGuide.md/). +A description for each folder is given below + +## integration +This folder contains integration tests that run directly against the server. For further information on how to run these tests check out the [Integration Test README](https://github.com/aws/aws-iot-device-sdk-embedded-c/blob/master/tests/integration/README.md/). + +## unit +This folder contains unit tests that test SDK functionality against a Mock TLS layer. They are built using the CppUTest testing framework. For further information on how to run these tests check out the [Unit Test README](https://github.com/aws/aws-iot-device-sdk-embedded-c/blob/master/tests/unit/README.md/). \ No newline at end of file diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/Makefile b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/Makefile new file mode 100644 index 00000000..e8353a64 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/Makefile @@ -0,0 +1,97 @@ +#This target is to ensure accidental execution of Makefile as a bash script will not execute commands like rm in unexpected directories and exit gracefully. +.prevent_execution: + exit 0 + +CC = gcc +RM = rm + +DEBUG = + +#IoT client directory +IOT_CLIENT_DIR = ../.. + +APP_DIR = $(IOT_CLIENT_DIR)/tests/integration +APP_NAME = integration_tests_mbedtls +MT_APP_NAME = integration_tests_mbedtls_mt +APP_SRC_FILES = $(shell find $(APP_DIR)/src/ -name '*.c') +MT_APP_SRC_FILES = $(shell find $(APP_DIR)/multithreadingTest/ -name '*.c') +APP_INCLUDE_DIRS = -I $(APP_DIR)/include + +PLATFORM_DIR = $(IOT_CLIENT_DIR)/platform/linux + +#MbedTLS directory +TEMP_MBEDTLS_SRC_DIR = $(IOT_CLIENT_DIR)/external_libs/mbedTLS +TLS_LIB_DIR = $(TEMP_MBEDTLS_SRC_DIR)/library +TLS_INCLUDE_DIR = -I $(TEMP_MBEDTLS_SRC_DIR)/include + +EXTERNAL_LIBS += -L$(TLS_LIB_DIR) +LD_FLAG += -Wl,-rpath,$(TLS_LIB_DIR) +LD_FLAG += -ldl $(TLS_LIB_DIR)/libmbedtls.a $(TLS_LIB_DIR)/libmbedcrypto.a $(TLS_LIB_DIR)/libmbedx509.a -lpthread + +# Logging level control +#LOG_FLAGS += -DENABLE_IOT_DEBUG +#LOG_FLAGS += -DENABLE_IOT_TRACE +LOG_FLAGS += -DENABLE_IOT_INFO +LOG_FLAGS += -DENABLE_IOT_WARN +LOG_FLAGS += -DENABLE_IOT_ERROR +COMPILER_FLAGS += $(LOG_FLAGS) + +#IoT client directory +PLATFORM_COMMON_DIR = $(PLATFORM_DIR)/common +PLATFORM_THREAD_DIR = $(PLATFORM_DIR)/pthread +PLATFORM_NETWORK_DIR = $(PLATFORM_DIR)/mbedtls + +IOT_INCLUDE_DIRS = -I $(PLATFORM_COMMON_DIR) +IOT_INCLUDE_DIRS += -I $(PLATFORM_THREAD_DIR) +IOT_INCLUDE_DIRS += -I $(PLATFORM_NETWORK_DIR) +IOT_INCLUDE_DIRS += -I $(IOT_CLIENT_DIR)/include +IOT_INCLUDE_DIRS += -I $(IOT_CLIENT_DIR)/external_libs/jsmn + +IOT_SRC_FILES += $(shell find $(IOT_CLIENT_DIR)/src/ -name '*.c') +IOT_SRC_FILES += $(shell find $(IOT_CLIENT_DIR)/external_libs/jsmn/ -name '*.c') +IOT_SRC_FILES += $(shell find $(PLATFORM_NETWORK_DIR)/ -name '*.c') +IOT_SRC_FILES += $(shell find $(PLATFORM_COMMON_DIR)/ -name '*.c') +IOT_SRC_FILES += $(shell find $(PLATFORM_THREAD_DIR)/ -name '*.c') + +#Aggregate all include and src directories +INCLUDE_ALL_DIRS += $(IOT_INCLUDE_DIRS) +INCLUDE_ALL_DIRS += $(APP_INCLUDE_DIRS) +INCLUDE_ALL_DIRS += $(TLS_INCLUDE_DIR) + +SRC_FILES += $(APP_SRC_FILES) +SRC_FILES += $(IOT_SRC_FILES) + +MT_SRC_FILES += $(MT_APP_SRC_FILES) +MT_SRC_FILES += $(IOT_SRC_FILES) + +COMPILER_FLAGS += -g +COMPILER_FLAGS += $(LOG_FLAGS) +PRE_MAKE_CMDS += cd $(TEMP_MBEDTLS_SRC_DIR) && make + +MAKE_CMD = $(CC) $(SRC_FILES) $(COMPILER_FLAGS) -g3 -o $(APP_DIR)/$(APP_NAME) $(EXTERNAL_LIBS) $(LD_FLAG) $(INCLUDE_ALL_DIRS); +MAKE_MT_CMD = $(CC) $(MT_SRC_FILES) $(COMPILER_FLAGS) -g3 -D_ENABLE_THREAD_SUPPORT_ -o $(APP_DIR)/$(MT_APP_NAME) $(EXTERNAL_LIBS) $(LD_FLAG) $(INCLUDE_ALL_DIRS); + +ifeq ($(CODE_SIZE_ENABLE),Y) +POST_MAKE_CMDS += $(CC) -c $(SRC_FILES) $(INCLUDE_ALL_DIRS) -fstack-usage; +POST_MAKE_CMDS += (size --format=Berkeley *.o > $(APP_NAME)_size_info.txt); +POST_MAKE_CMDS += (cat *.su >> $(APP_NAME)_stack_usage.txt); +POST_MAKE_CMDS += ($(RM) *.o); +POST_MAKE_CMDS += ($(RM) *.su); +CLEAN_CMD += ($(RM) -f $(APP_NAME)_size_info.txt); +CLEAN_CMD += ($(RM) -f $(APP_NAME)_stack_usage.txt); +endif + +all: + $(PRE_MAKE_CMDS) + $(DEBUG)$(MAKE_CMD) + $(DEBUG)$(MAKE_MT_CMD) + ./$(APP_NAME) + ./$(MT_APP_NAME) + $(POST_MAKE_CMDS) + +clean: + $(RM) -f $(APP_DIR)/$(APP_NAME) + $(RM) -f $(APP_DIR)/$(MT_APP_NAME) + $(CLEAN_CMD) + +ALL_TARGETS_CLEAN += test-integration-assert-clean \ No newline at end of file diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/README.md b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/README.md new file mode 100644 index 00000000..b3ea04b2 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/README.md @@ -0,0 +1,44 @@ +## Integration Tests +This folder contains integration tests to verify Embedded C SDK functionality. These have been tested to work with Linux but haven't been ported to any specific platform. For additional information about porting the Device SDK for embedded C onto additional platforms please refer to the [PortingGuide](https://github.com/aws/aws-iot-device-sdk-embedded-c/blob/master/PortingGuide.md/). +To run these tests, follow the below steps: + + * Place device identity cert and private key in locations referenced in the `certs` folder + * Download certificate authority CA file from [Symantec](https://www.symantec.com/content/en/us/enterprise/verisign/roots/VeriSign-Class%203-Public-Primary-Certification-Authority-G5.pem) and place in `certs` folder + * Ensure the names of the cert files are the same as in the `aws_iot_config.h` file + * Ensure the certificate has an attached policy which allows the proper permissions for AWS IoT + * Update the Host endpoint in the `aws_iot_config.h` file + * Build the example using make. (''make''). The tests will run automatically as a part of the build process + * For more detailed Debug output, enable the IOT_DEBUG flag in `Logging level control` section of the Makefile. IOT_TRACE can be enabled as well for very detailed information on what functions are being executed + * More information on the each test is below + +### Integration test configuration +For all the tests below, there is additional configuration in the `integ_tests_config.h`. The configuration options are explained below: + + * PUBLISH_COUNT - Number of messages to publish in each publish thread + * MAX_PUB_THREAD_COUNT - Maximum number of threads to create for the multi-threading test + * RX_RECEIVE_PERCENTAGE - Minimum percentage of messages that must be received back by the yield thread. This is here ONLY because sometimes the yield thread doesn't get scheduled before the publish thread when it is created. In every other case, 100% messages should be received + * CONNECT_MAX_ATTEMPT_COUNT - Max number of initial connect retries + * THREAD_SLEEP_INTERVAL_USEC - Interval that each thread sleeps for + * INTEGRATION_TEST_TOPIC - Test topic to publish on + * INTEGRATION_TEST_CLIENT_ID - Client ID to be used for single client tests + * INTEGRATION_TEST_CLIENT_ID_PUB, INTEGRATION_TEST_CLIENT_ID_SUB - Client IDs to be used for multiple client tests + +### Test 1 - Basic Connectivity Test +This test verifies basic connectivity with the server. It creates one client instance and connects to the server. It subscribes to the Integration Test topic. Then it creates two threads, one publish thread and one yield thread. The publish thread publishes `PUBLISH_COUNT` messages on the test topic and the yield thread receives them. Once all the messages are published, the program waits for 1 sec to ensure all the messages have sufficient time to be received. +The test ends with the program verifying that all the messages were received and no other errors occurred. + +### Test 2 - Multiple Client Connectivity Test +This test verifies usage of multiple clients in the same application. It creates two client instances and both connect to the server. One client instance subscribes to the Integration Test topic. The other client instance publishes `PUBLISH_COUNT` messages on the test topic and the yield instance receives them. Once all the messages are published, the program waits for 1 sec to ensure all the messages have sufficient time to be received. +The test ends with the program verifying that all the messages were received and no other errors occurred. + +### Test 3 - Auto Reconnect Test +This test verifies Auto-reconnect functionality. It creates one client instance. Then it performs 3 separate tests + + * Tests the disconnect handler by causing a TLS layer disconnect. + * Tests manual reconnect API by causing a TLS layer disconnect with auto-reconnect disabled + * Lastly, it tests the Auto-reconnect API by enabling auto-reconnect. It renames the rootCA file to a different name to prevent immediate reconnect, verifies the error codes are returned properly and that the reconnect algorithm is running. Once that check is satisfied, it renames the rootCA file back to the original names and verifies the client was able to reconnect. + +### Test 4 - Multi-threading Validation Test +This test is used to validate thread-safe operations. This creates on client instance, one yield thread, one thread to test subscribe/unsubscribe behavior and MAX_PUB_THREAD_COUNT number of publish threads. Then it proceeds to publish PUBLISH_COUNT messages on the test topic from each publish thread. The subscribe/unsubscribe thread runs in the background constantly subscribing and unsubscribing to a second test topic. The yield threads records which messages were received. + +The test verifies whether all the messages that were published were received or not. It also checks for errors that could occur in multi-threaded scenarios. The test has been run with 10 threads sending 500 messages each and verified to be working fine. It can be used as a reference testing application to validate whether your use case will work with multi-threading enabled. diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/include/aws_iot_config.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/include/aws_iot_config.h new file mode 100644 index 00000000..5a3889cd --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/include/aws_iot_config.h @@ -0,0 +1,53 @@ +/* + * 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. + */ + +#ifndef SRC_SHADOW_IOT_SHADOW_CONFIG_H_ +#define SRC_SHADOW_IOT_SHADOW_CONFIG_H_ + +// Get from console +// ================================================= +#define AWS_IOT_MQTT_HOST "" ///< Customer specific MQTT HOST. The same will be used for Thing Shadow +#define AWS_IOT_MQTT_PORT 8883 ///< default port for MQTT/S +#define AWS_IOT_MQTT_CLIENT_ID "c-sdk-client-id" ///< MQTT client ID should be unique for every device +#define AWS_IOT_MY_THING_NAME "AWS-IoT-C-SDK" ///< Thing Name of the Shadow this device is associated with +#define AWS_IOT_ROOT_CA_FILENAME "rootCA.crt" ///< Root CA file name +#define AWS_IOT_CERTIFICATE_FILENAME "cert.pem" ///< device signed certificate file name +#define AWS_IOT_PRIVATE_KEY_FILENAME "privkey.pem" ///< Device private key filename +// ================================================= + +// 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, including terminating NULL byte. +#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 format $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. + +#define DISABLE_METRICS false ///< Disable the collection of metrics by setting this to true + +#endif /* SRC_SHADOW_IOT_SHADOW_CONFIG_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/include/aws_iot_integ_tests_config.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/include/aws_iot_integ_tests_config.h new file mode 100644 index 00000000..a1093380 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/include/aws_iot_integ_tests_config.h @@ -0,0 +1,46 @@ +/* + * 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. + */ + +#ifndef TESTS_INTEGRATION_INTEG_TESTS_CONFIG_H_ +#define TESTS_INTEGRATION_INTEG_TESTS_CONFIG_H_ + +/* Number of messages to publish in each publish thread */ +#define PUBLISH_COUNT 100 + +/* Maximum number of threads to create for the multi-threading test */ +#define MAX_PUB_THREAD_COUNT 3 + +/* Minimum percentage of messages that must be received back by the yield thread. + * This is here ONLY because sometimes the yield thread doesn't get scheduled before the publish + * thread when it is created. In every other case, 100% messages should be received. */ +#define RX_RECEIVE_PERCENTAGE 99.0f + +/* Max number of initial connect retries */ +#define CONNECT_MAX_ATTEMPT_COUNT 3 + +/* Interval that each thread sleeps for */ +#define THREAD_SLEEP_INTERVAL_USEC 500000 + +/* Test topic to publish on */ +#define INTEGRATION_TEST_TOPIC "Tests/Integration/EmbeddedC" + +/* Client ID to be used for single client tests */ +#define INTEGRATION_TEST_CLIENT_ID "EMB_C_SDK_INTEG_TESTER" + +/* Client IDs to be used for multiple client tests */ +#define INTEGRATION_TEST_CLIENT_ID_PUB "EMB_C_SDK_INTEG_TESTER_PUB" +#define INTEGRATION_TEST_CLIENT_ID_SUB "EMB_C_SDK_INTEG_TESTER_SUB" + +#endif /* TESTS_INTEGRATION_INTEG_TESTS_CONFIG_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/include/aws_iot_test_integration_common.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/include/aws_iot_test_integration_common.h new file mode 100644 index 00000000..39da671c --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/include/aws_iot_test_integration_common.h @@ -0,0 +1,43 @@ + +/* +* Copyright 2015-2016 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_test_integration_common.h + * @brief Integration Test common header + */ + +#ifndef TESTS_INTEGRATION_H_ +#define TESTS_INTEGRATION_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "aws_iot_mqtt_client_interface.h" +#include "aws_iot_log.h" +#include "aws_iot_integ_tests_config.h" +#include "aws_iot_config.h" + +int aws_iot_mqtt_tests_basic_connectivity(); +int aws_iot_mqtt_tests_multiple_clients(); +int aws_iot_mqtt_tests_auto_reconnect(); + +#endif /* TESTS_INTEGRATION_COMMON_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/multithreadingTest/aws_iot_test_multithreading_validation.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/multithreadingTest/aws_iot_test_multithreading_validation.c new file mode 100644 index 00000000..cee6ad20 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/multithreadingTest/aws_iot_test_multithreading_validation.c @@ -0,0 +1,348 @@ +/* + * multithreadedTest.c + * + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "aws_iot_mqtt_client_interface.h" +#include "aws_iot_log.h" + +#include "aws_iot_integ_tests_config.h" +#include "aws_iot_config.h" + +static bool terminate_yield_thread; +static bool terminate_subUnsub_thread; + +static unsigned int countArray[MAX_PUB_THREAD_COUNT][PUBLISH_COUNT]; +static unsigned int rxMsgBufferTooBigCounter; +static unsigned int rxUnexpectedNumberCounter; +static unsigned int rePublishCount; +static unsigned int wrongYieldCount; +static unsigned int threadStatus[MAX_PUB_THREAD_COUNT]; + +typedef struct ThreadData { + int threadId; + AWS_IoT_Client *client; +} ThreadData; + +static void aws_iot_mqtt_tests_message_aggregator(AWS_IoT_Client *pClient, char *topicName, + uint16_t topicNameLen, IoT_Publish_Message_Params *params, void *pData) { + char tempBuf[30]; + char *temp = NULL; + unsigned int tempRow = 0, tempCol = 0; + IoT_Error_t rc; + + IOT_UNUSED(pClient); + IOT_UNUSED(topicName); + IOT_UNUSED(topicNameLen); + IOT_UNUSED(pData); + + if(30 >= params->payloadLen) { + snprintf(tempBuf, params->payloadLen, params->payload); + printf("\n Message received : %s", tempBuf); + temp = strtok(tempBuf, " ,:"); + temp = strtok(NULL, " ,:"); + if(NULL == temp) { + return; + } + tempRow = atoi(temp); + temp = strtok(NULL, " ,:"); + temp = strtok(NULL, " ,:"); + tempCol = atoi(temp); + if(NULL == temp) { + return; + } + if(((tempRow - 1) < MAX_PUB_THREAD_COUNT) && (tempCol < PUBLISH_COUNT)) { + countArray[tempRow - 1][tempCol]++; + } else { + IOT_WARN(" \nUnexpected Thread : %d, Message : %d ", tempRow, tempCol); + rxUnexpectedNumberCounter++; + } + rc = aws_iot_mqtt_yield(pClient, 10); + if(MQTT_CLIENT_NOT_IDLE_ERROR != rc) { + IOT_ERROR("\n Yield succeeded in callback!!! Client state : %d Rc : %d\n", + aws_iot_mqtt_get_client_state(pClient), rc); + wrongYieldCount++; + } + } else { + rxMsgBufferTooBigCounter++; + } +} + +static void aws_iot_mqtt_tests_disconnect_callback_handler(AWS_IoT_Client *pClient, void *param) { + IOT_UNUSED(pClient); + IOT_UNUSED(param); +} + +static IoT_Error_t aws_iot_mqtt_tests_subscribe_to_test_topic(AWS_IoT_Client *pClient, QoS qos, struct timeval *pSubscribeTime) { + IoT_Error_t rc = SUCCESS; + struct timeval start, end; + + gettimeofday(&start, NULL); + rc = aws_iot_mqtt_subscribe(pClient, INTEGRATION_TEST_TOPIC, strlen(INTEGRATION_TEST_TOPIC), qos, + aws_iot_mqtt_tests_message_aggregator, NULL); + IOT_DEBUG(" Sub response : %d\n", rc); + gettimeofday(&end, NULL); + + timersub(&end, &start, pSubscribeTime); + + return rc; +} + +static void *aws_iot_mqtt_tests_yield_thread_runner(void *ptr) { + IoT_Error_t rc = SUCCESS; + AWS_IoT_Client *pClient = (AWS_IoT_Client *) ptr; + while(SUCCESS == rc && false == terminate_yield_thread) { + do { + usleep(THREAD_SLEEP_INTERVAL_USEC); + //DEBUG("\n Yielding \n"); + rc = aws_iot_mqtt_yield(pClient, 100); + } while(MQTT_CLIENT_NOT_IDLE_ERROR == rc); + + if(SUCCESS != rc) { + IOT_ERROR("\nYield Returned : %d ", rc); + } + } +} + +static void *aws_iot_mqtt_tests_publish_thread_runner(void *ptr) { + int itr = 0; + char cPayload[30]; + IoT_Publish_Message_Params params; + IoT_Error_t rc = SUCCESS; + ThreadData *threadData = (ThreadData *) ptr; + AWS_IoT_Client *pClient = threadData->client; + int threadId = threadData->threadId; + + for(itr = 0; itr < PUBLISH_COUNT; itr++) { + snprintf(cPayload, 30, "Thread : %d, Msg : %d", threadId, itr); + printf("\nMsg being published: %s \n", cPayload); + params.payload = (void *) cPayload; + params.payloadLen = strlen(cPayload) + 1; + params.qos = QOS1; + params.isRetained = 0; + + do { + rc = aws_iot_mqtt_publish(pClient, INTEGRATION_TEST_TOPIC, strlen(INTEGRATION_TEST_TOPIC), ¶ms); + usleep(THREAD_SLEEP_INTERVAL_USEC); + } while(MUTEX_LOCK_ERROR == rc || MQTT_CLIENT_NOT_IDLE_ERROR == rc); + if(SUCCESS != rc) { + IOT_WARN("\nFailed attempt 1 Publishing Thread : %d, Msg : %d, cs : %d --> %d\n ", threadId, itr, rc, + aws_iot_mqtt_get_client_state(pClient)); + do { + rc = aws_iot_mqtt_publish(pClient, INTEGRATION_TEST_TOPIC, strlen(INTEGRATION_TEST_TOPIC), ¶ms); + usleep(THREAD_SLEEP_INTERVAL_USEC); + } while(MUTEX_LOCK_ERROR == rc || MQTT_CLIENT_NOT_IDLE_ERROR == rc); + rePublishCount++; + if(SUCCESS != rc) { + IOT_ERROR("\nFailed attempt 2 Publishing Thread : %d, Msg : %d, cs : %d --> %d Second Attempt \n", threadId, + itr, rc, aws_iot_mqtt_get_client_state(pClient)); + } + } + } + threadStatus[threadId - 1] = 1; + return 0; + +} + +static void *aws_iot_mqtt_tests_sub_unsub_thread_runner(void *ptr) { + IoT_Error_t rc = SUCCESS; + AWS_IoT_Client *pClient = (AWS_IoT_Client *) ptr; + char testTopic[50]; + snprintf(testTopic, 50, "%s_temp", INTEGRATION_TEST_TOPIC); + while(SUCCESS == rc && false == terminate_subUnsub_thread) { + do { + usleep(THREAD_SLEEP_INTERVAL_USEC); + rc = aws_iot_mqtt_subscribe(pClient, testTopic, strlen(testTopic), QOS1, + aws_iot_mqtt_tests_message_aggregator, NULL); + } while(MQTT_CLIENT_NOT_IDLE_ERROR == rc); + + if(SUCCESS != rc) { + IOT_ERROR("Subscribe Returned : %d ", rc); + } + + do { + usleep(THREAD_SLEEP_INTERVAL_USEC); + rc = aws_iot_mqtt_unsubscribe(pClient, testTopic, strlen(testTopic)); + } while(MQTT_CLIENT_NOT_IDLE_ERROR == rc); + + if(SUCCESS != rc) { + IOT_ERROR("Unsubscribe Returned : %d ", rc); + } + } +} + +int aws_iot_mqtt_tests_multi_threading_validation() { + pthread_t publish_thread[MAX_PUB_THREAD_COUNT], yield_thread, sub_unsub_thread; + char certDirectory[15] = "../../certs"; + char clientCRT[PATH_MAX + 1]; + char clientKey[PATH_MAX + 1]; + char CurrentWD[PATH_MAX + 1]; + char root_CA[PATH_MAX + 1]; + + char clientId[50]; + IoT_Client_Init_Params initParams; + IoT_Client_Connect_Params connectParams; + int threadId[MAX_PUB_THREAD_COUNT]; + int pubThreadReturn[MAX_PUB_THREAD_COUNT]; + int yieldThreadReturn = 0, subUnsubThreadReturn = 0; + float percentOfRxMsg = 0.0; + int finishedThreadCount = 0; + IoT_Error_t rc = SUCCESS; + int i, rxMsgCount = 0, j = 0; + struct timeval connectTime, subscribeTopic; + unsigned int connectCounter = 0; + int test_result = 0; + ThreadData threadData[MAX_PUB_THREAD_COUNT]; + AWS_IoT_Client client; + terminate_yield_thread = false; + rxMsgBufferTooBigCounter = 0; + rxUnexpectedNumberCounter = 0; + rePublishCount = 0; + wrongYieldCount = 0; + for(j = 0; j < MAX_PUB_THREAD_COUNT; j++) { + threadId[j] = j + 1; + threadStatus[j] = 0; + for(i = 0; i < PUBLISH_COUNT; i++) { + countArray[j][i] = 0; + } + } + + printf("\nConnecting Client "); + do { + getcwd(CurrentWD, sizeof(CurrentWD)); + snprintf(root_CA, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_ROOT_CA_FILENAME); + snprintf(clientCRT, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_CERTIFICATE_FILENAME); + snprintf(clientKey, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_PRIVATE_KEY_FILENAME); + srand((unsigned int)time(NULL)); + snprintf(clientId, 50, "%s_%d", INTEGRATION_TEST_CLIENT_ID, rand() % 10000); + + IOT_DEBUG(" Root CA Path : %s\n clientCRT : %s\n clientKey : %s\n", root_CA, clientCRT, clientKey); + initParams.pHostURL = AWS_IOT_MQTT_HOST; + initParams.port = 8883; + initParams.pRootCALocation = root_CA; + initParams.pDeviceCertLocation = clientCRT; + initParams.pDevicePrivateKeyLocation = clientKey; + initParams.mqttCommandTimeout_ms = 10000; + initParams.tlsHandshakeTimeout_ms = 10000; + initParams.disconnectHandler = aws_iot_mqtt_tests_disconnect_callback_handler; + initParams.enableAutoReconnect = false; + initParams.isBlockOnThreadLockEnabled = true; + aws_iot_mqtt_init(&client, &initParams); + + connectParams.keepAliveIntervalInSec = 10; + connectParams.isCleanSession = true; + connectParams.MQTTVersion = MQTT_3_1_1; + connectParams.pClientID = (char *)&clientId; + connectParams.clientIDLen = strlen(clientId); + connectParams.isWillMsgPresent = false; + connectParams.pUsername = NULL; + connectParams.usernameLen = 0; + connectParams.pPassword = NULL; + connectParams.passwordLen = 0; + + rc = aws_iot_mqtt_connect(&client, &connectParams); + if(SUCCESS != rc) { + IOT_ERROR("ERROR Connecting %d\n", rc); + return -1; + } + + connectCounter++; + } while(SUCCESS != rc && connectCounter < CONNECT_MAX_ATTEMPT_COUNT); + + if(SUCCESS == rc) { + printf("\n## Connect Success. Time sec: %d, usec: %d\n", connectTime.tv_sec, connectTime.tv_usec); + } else { + IOT_ERROR("## Connect Failed. error code %d\n", rc); + return -1; + } + + aws_iot_mqtt_tests_subscribe_to_test_topic(&client, QOS1, &subscribeTopic); + + printf("\nRunning Test! "); + + yieldThreadReturn = pthread_create(&yield_thread, NULL, aws_iot_mqtt_tests_yield_thread_runner, &client); + subUnsubThreadReturn = pthread_create(&sub_unsub_thread, NULL, aws_iot_mqtt_tests_sub_unsub_thread_runner, &client); + + for(i = 0; i < MAX_PUB_THREAD_COUNT; i++) { + threadData[i].client = &client; + threadData[i].threadId = threadId[i]; + pubThreadReturn[i] = pthread_create(&publish_thread[i], NULL, aws_iot_mqtt_tests_publish_thread_runner, + &threadData[i]); + } + + /* Wait until all publish threads have finished */ + do { + finishedThreadCount = 0; + for(i = 0; i < MAX_PUB_THREAD_COUNT; i++) { finishedThreadCount += threadStatus[i]; } + printf("\nFinished thread count : %d \n", finishedThreadCount); + sleep(1); + } while(finishedThreadCount < MAX_PUB_THREAD_COUNT); + + printf("\nFinished publishing!!"); + + terminate_yield_thread = true; + terminate_subUnsub_thread = true; + + /* Allow time for yield_thread and sub_sunsub thread to exit */ + sleep(1); + + /* Not using pthread_join because all threads should have terminated gracefully at this point. If they haven't, + * which should not be possible, something below will fail. */ + + printf("\n\nCalculating Results!! \n\n"); + for(i = 0; i < PUBLISH_COUNT; i++) { + for(j = 0; j < MAX_PUB_THREAD_COUNT; j++) { + if(countArray[j][i] > 0) { + rxMsgCount++; + } + } + } + + printf("\n\nResult : \n"); + percentOfRxMsg = (float) rxMsgCount * 100 / (PUBLISH_COUNT * MAX_PUB_THREAD_COUNT); + if(RX_RECEIVE_PERCENTAGE <= percentOfRxMsg && 0 == rxMsgBufferTooBigCounter && 0 == rxUnexpectedNumberCounter && + 0 == wrongYieldCount) { + printf("\nSuccess: %f \%\n", percentOfRxMsg); + printf("Published Messages: %d , Received Messages: %d \n", PUBLISH_COUNT * MAX_PUB_THREAD_COUNT, rxMsgCount); + printf("QoS 1 re publish count %d\n", rePublishCount); + printf("Connection Attempts %d\n", connectCounter); + printf("Yield count without error during callback %d\n", wrongYieldCount); + test_result = 0; + } else { + printf("\nFailure: %f\n", percentOfRxMsg); + printf("\"Received message was too big than anything sent\" count: %d\n", rxMsgBufferTooBigCounter); + printf("\"The number received is out of the range\" count: %d\n", rxUnexpectedNumberCounter); + printf("Yield count without error during callback %d\n", wrongYieldCount); + test_result = -2; + } + aws_iot_mqtt_disconnect(&client); + return test_result; +} + +int main() { + printf("\n\n"); + printf("******************************************************************\n"); + printf("* Starting MQTT Version 3.1.1 Multithreading Validation Test *\n"); + printf("******************************************************************\n"); + int rc = aws_iot_mqtt_tests_multi_threading_validation(); + if(0 != rc) { + printf("\n*******************************************************************\n"); + printf("*MQTT Version 3.1.1 Multithreading Validation Test FAILED! RC : %d \n", rc); + printf("*******************************************************************\n"); + return 1; + } + + printf("******************************************************************\n"); + printf("* MQTT Version 3.1.1 Multithreading Validation Test SUCCESS!! *\n"); + printf("******************************************************************\n"); + + return 0; +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_auto_reconnect.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_auto_reconnect.c new file mode 100644 index 00000000..140af676 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_auto_reconnect.c @@ -0,0 +1,236 @@ +/* +* Copyright 2015-2016 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_test_auto_reconnect.c + * @brief Integration Test for automatic reconnect + */ + +#include "aws_iot_test_integration_common.h" + +static char ModifiedPathBuffer[PATH_MAX + 1]; +char root_CA[PATH_MAX + 1]; + +bool terminate_yield_with_rc_thread = false; +IoT_Error_t yieldRC; +bool captureYieldReturnCode = false; + +/** + * This function renames the rootCA.crt file to a temporary name to cause connect failure + */ +int aws_iot_mqtt_tests_block_tls_connect() { + char replaceFileName[] = {"rootCATemp.crt"}; + char *pFileNamePosition = NULL; + + char mvCommand[2 * PATH_MAX + 10]; + strcpy(ModifiedPathBuffer, root_CA); + pFileNamePosition = strstr(ModifiedPathBuffer, AWS_IOT_ROOT_CA_FILENAME); + strncpy(pFileNamePosition, replaceFileName, strlen(replaceFileName)); + snprintf(mvCommand, 2 * PATH_MAX + 10, "mv %s %s", root_CA, ModifiedPathBuffer); + return system(mvCommand); +} + +/** + * Always ensure this function is called after block_tls_connect + */ +int aws_iot_mqtt_tests_unblock_tls_connect() { + char mvCommand[2 * PATH_MAX + 10]; + snprintf(mvCommand, 2 * PATH_MAX + 10, "mv %s %s", ModifiedPathBuffer, root_CA); + return system(mvCommand); +} + +void *aws_iot_mqtt_tests_yield_with_rc(void *ptr) { + IoT_Error_t rc = SUCCESS; + + struct timeval start, end, result; + static int cntr = 0; + AWS_IoT_Client *pClient = (AWS_IoT_Client *) ptr; + + while(terminate_yield_with_rc_thread == false + && (NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc)) { + usleep(500000); + printf(" Client state : %d ", aws_iot_mqtt_get_client_state(pClient)); + rc = aws_iot_mqtt_yield(pClient, 100); + printf("yield rc %d\n", rc); + if(captureYieldReturnCode && SUCCESS != rc) { + printf("yield rc capture %d\n", rc); + captureYieldReturnCode = false; + yieldRC = rc; + } + } +} + +unsigned int disconnectedCounter = 0; + +void aws_iot_mqtt_tests_disconnect_callback_handler(AWS_IoT_Client *pClient, void *param) { + disconnectedCounter++; +} + +int aws_iot_mqtt_tests_auto_reconnect() { + pthread_t reconnectTester_thread, yield_thread; + int yieldThreadReturn = 0; + int test_result = 0; + + char certDirectory[15] = "../../certs"; + char CurrentWD[PATH_MAX + 1]; + char clientCRT[PATH_MAX + 1]; + char clientKey[PATH_MAX + 1]; + char clientId[50]; + AWS_IoT_Client client; + + IoT_Error_t rc = SUCCESS; + getcwd(CurrentWD, sizeof(CurrentWD)); + snprintf(root_CA, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_ROOT_CA_FILENAME); + snprintf(clientCRT, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_CERTIFICATE_FILENAME); + snprintf(clientKey, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_PRIVATE_KEY_FILENAME); + srand((unsigned int) time(NULL)); + snprintf(clientId, 50, "%s_%d", INTEGRATION_TEST_CLIENT_ID, rand() % 10000); + + printf(" Root CA Path : %s\n clientCRT : %s\n clientKey : %s\n", root_CA, clientCRT, clientKey); + IoT_Client_Init_Params initParams; + initParams.pHostURL = AWS_IOT_MQTT_HOST; + initParams.port = 8883; + initParams.pRootCALocation = root_CA; + initParams.pDeviceCertLocation = clientCRT; + initParams.pDevicePrivateKeyLocation = clientKey; + initParams.mqttCommandTimeout_ms = 20000; + initParams.tlsHandshakeTimeout_ms = 5000; + initParams.disconnectHandler = aws_iot_mqtt_tests_disconnect_callback_handler; + initParams.enableAutoReconnect = false; + aws_iot_mqtt_init(&client, &initParams); + + IoT_Client_Connect_Params connectParams; + connectParams.keepAliveIntervalInSec = 5; + connectParams.isCleanSession = true; + connectParams.MQTTVersion = MQTT_3_1_1; + connectParams.pClientID = (char *) &clientId; + connectParams.clientIDLen = strlen(clientId); + connectParams.isWillMsgPresent = 0; + connectParams.pUsername = NULL; + connectParams.usernameLen = 0; + connectParams.pPassword = NULL; + connectParams.passwordLen = 0; + + rc = aws_iot_mqtt_connect(&client, &connectParams); + if(rc != SUCCESS) { + printf("ERROR Connecting %d\n", rc); + return -1; + } + + yieldThreadReturn = pthread_create(&yield_thread, NULL, aws_iot_mqtt_tests_yield_with_rc, &client); + + /* + * Test disconnect handler + */ + printf("1. Test Disconnect Handler\n"); + aws_iot_mqtt_tests_block_tls_connect(); + iot_tls_disconnect(&(client.networkStack)); + sleep(connectParams.keepAliveIntervalInSec + 1); + if(disconnectedCounter == 1) { + printf("Success invoking Disconnect Handler\n"); + } else { + aws_iot_mqtt_tests_unblock_tls_connect(); + printf("Failure to invoke Disconnect Handler\n"); + return -1; + } + aws_iot_mqtt_tests_unblock_tls_connect(); + terminate_yield_with_rc_thread = true; + pthread_join(yield_thread, NULL); + + /* + * Manual Reconnect Test + */ + printf("2. Test Manual Reconnect, Current Client state : %d \n", aws_iot_mqtt_get_client_state(&client)); + rc = aws_iot_mqtt_attempt_reconnect(&client); + if(rc != NETWORK_RECONNECTED) { + printf("ERROR reconnecting manually %d\n", rc); + return -4; + } + terminate_yield_with_rc_thread = false; + yieldThreadReturn = pthread_create(&yield_thread, NULL, aws_iot_mqtt_tests_yield_with_rc, &client); + + yieldRC = FAILURE; + captureYieldReturnCode = true; + + // ensure atleast 1 cycle of yield is executed to get the yield status to SUCCESS + sleep(1); + if(!captureYieldReturnCode) { + if(yieldRC == NETWORK_ATTEMPTING_RECONNECT) { + printf("Success reconnecting manually\n"); + } else { + printf("Failure to reconnect manually\n"); + return -3; + } + } + terminate_yield_with_rc_thread = true; + + /* + * Auto Reconnect Test + */ + + printf("3. Test Auto_reconnect \n"); + + rc = aws_iot_mqtt_autoreconnect_set_status(&client, true); + if(rc != SUCCESS) { + printf("Error: Failed to enable auto-reconnect %d \n", rc); + } + + yieldRC = FAILURE; + captureYieldReturnCode = true; + + // Disconnect + aws_iot_mqtt_tests_block_tls_connect(); + iot_tls_disconnect(&(client.networkStack)); + + terminate_yield_with_rc_thread = false; + yieldThreadReturn = pthread_create(&yield_thread, NULL, aws_iot_mqtt_tests_yield_with_rc, &client); + + sleep(connectParams.keepAliveIntervalInSec + 1); + if(!captureYieldReturnCode) { + if(yieldRC == NETWORK_ATTEMPTING_RECONNECT) { + printf("Success attempting reconnect\n"); + } else { + printf("Failure to attempt to reconnect\n"); + return -6; + } + } + if(disconnectedCounter == 2) { + printf("Success: disconnect handler invoked on enabling auto-reconnect\n"); + } else { + printf("Failure: disconnect handler not invoked on enabling auto-reconnect : %d\n", disconnectedCounter); + return -7; + } + aws_iot_mqtt_tests_unblock_tls_connect(); + sleep(connectParams.keepAliveIntervalInSec + 1); + captureYieldReturnCode = true; + sleep(connectParams.keepAliveIntervalInSec + 1); + if(!captureYieldReturnCode) { + if(yieldRC == SUCCESS) { + printf("Success attempting reconnect\n"); + } else { + printf("Failure to attempt to reconnect\n"); + return -6; + } + } + if(true == aws_iot_mqtt_is_client_connected(&client)) { + printf("Success: is Mqtt connected api\n"); + } else { + printf("Failure: is Mqtt Connected api\n"); + return -7; + } + + rc = aws_iot_mqtt_disconnect(&client); + return rc; +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_basic_connectivity.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_basic_connectivity.c new file mode 100644 index 00000000..217e06d8 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_basic_connectivity.c @@ -0,0 +1,276 @@ +/* +* Copyright 2015-2016 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_test_basic_connectivity.c + * @brief Integration Test for basic client connectivity + */ + +#include "aws_iot_test_integration_common.h" + +static bool terminate_yield_thread; +static bool isPubThreadFinished; + +static unsigned int countArray[PUBLISH_COUNT]; +static unsigned int rxMsgBufferTooBigCounter; +static unsigned int rxUnexpectedNumberCounter; +static unsigned int rePublishCount; +static unsigned int wrongYieldCount; + +typedef struct ThreadData { + AWS_IoT_Client *client; + int threadId; +} ThreadData; + +static void aws_iot_mqtt_tests_message_aggregator(AWS_IoT_Client *pClient, char *topicName, + uint16_t topicNameLen, IoT_Publish_Message_Params *params, void *pData) { + char tempBuf[30]; + char *temp = NULL; + unsigned int tempRow = 0, tempCol = 0; + IoT_Error_t rc; + + if(params->payloadLen <= 30) { + snprintf(tempBuf, params->payloadLen, params->payload); + printf("\nMsg received : %s", tempBuf); + temp = strtok(tempBuf, " ,:"); + temp = strtok(NULL, " ,:"); + if(NULL == temp) { + return; + } + tempRow = atoi(temp); + temp = strtok(NULL, " ,:"); + temp = strtok(NULL, " ,:"); + tempCol = atoi(temp); + if(NULL == temp) { + return; + } + if(tempCol > 0 && tempCol <= PUBLISH_COUNT) { + countArray[tempCol - 1]++; + } else { + IOT_WARN(" \n Thread : %d, Msg : %d ", tempRow, tempCol); + rxUnexpectedNumberCounter++; + } + rc = aws_iot_mqtt_yield(pClient, 10); + if(MQTT_CLIENT_NOT_IDLE_ERROR != rc) { + IOT_ERROR("\n Yield succeeded in callback!!! Client state : %d Rc : %d\n", + aws_iot_mqtt_get_client_state(pClient), rc); + wrongYieldCount++; + } + } else { + rxMsgBufferTooBigCounter++; + } +} + +static void aws_iot_mqtt_tests_disconnect_callback_handler(AWS_IoT_Client *pClient, void *param) { +} + +static IoT_Error_t aws_iot_mqtt_tests_subscribe_to_test_topic(AWS_IoT_Client *pClient, QoS qos, + struct timeval *pSubscribeTime) { + IoT_Error_t rc = SUCCESS; + struct timeval start, end; + + gettimeofday(&start, NULL); + rc = aws_iot_mqtt_subscribe(pClient, INTEGRATION_TEST_TOPIC, strlen(INTEGRATION_TEST_TOPIC), qos, + aws_iot_mqtt_tests_message_aggregator, NULL); + IOT_DEBUG("Sub response : %d\n", rc); + gettimeofday(&end, NULL); + + timersub(&end, &start, pSubscribeTime); + + return rc; +} + +static void *aws_iot_mqtt_tests_yield_thread_runner(void *ptr) { + IoT_Error_t rc = SUCCESS; + AWS_IoT_Client *pClient = (AWS_IoT_Client *) ptr; + while(SUCCESS == rc && terminate_yield_thread == false) { + do { + usleep(THREAD_SLEEP_INTERVAL_USEC); + rc = aws_iot_mqtt_yield(pClient, 100); + } while(MQTT_CLIENT_NOT_IDLE_ERROR == rc); // Client is busy, wait to get lock + + if(SUCCESS != rc) { + IOT_DEBUG("\nYield Returned : %d ", rc); + } + } +} + +static void *aws_iot_mqtt_tests_publish_thread_runner(void *ptr) { + int i = 0; + char cPayload[100]; + IoT_Publish_Message_Params params; + IoT_Error_t rc = SUCCESS; + ThreadData *threadData = (ThreadData *) ptr; + AWS_IoT_Client *pClient = threadData->client; + int threadId = threadData->threadId; + + for(i = 0; i < PUBLISH_COUNT; i++) { + snprintf(cPayload, 100, "Thread : %d, Msg : %d", threadId, i + 1); + printf("\nMsg being published: %s \n", cPayload); + params.payload = (void *) cPayload; + params.payloadLen = strlen(cPayload) + 1; + params.qos = QOS1; + params.isRetained = 0; + + do { + rc = aws_iot_mqtt_publish(pClient, INTEGRATION_TEST_TOPIC, strlen(INTEGRATION_TEST_TOPIC), ¶ms); + usleep(THREAD_SLEEP_INTERVAL_USEC); + } while(MUTEX_LOCK_ERROR == rc || MQTT_CLIENT_NOT_IDLE_ERROR == rc); + if(rc != SUCCESS) { + IOT_WARN("Error Publishing #%d --> %d\n ", i, rc); + do { + rc = aws_iot_mqtt_publish(pClient, INTEGRATION_TEST_TOPIC, strlen(INTEGRATION_TEST_TOPIC), ¶ms); + usleep(THREAD_SLEEP_INTERVAL_USEC); + } while(MUTEX_LOCK_ERROR == rc || MQTT_CLIENT_NOT_IDLE_ERROR == rc); + rePublishCount++; + if(rc != SUCCESS) { + IOT_ERROR("Error Publishing #%d --> %d Second Attempt \n", i, rc); + } + } + } + isPubThreadFinished = true; + return 0; +} + +int aws_iot_mqtt_tests_basic_connectivity() { + pthread_t publish_thread, yield_thread; + char certDirectory[15] = "../../certs"; + char clientCRT[PATH_MAX + 1]; + char root_CA[PATH_MAX + 1]; + char clientKey[PATH_MAX + 1]; + char CurrentWD[PATH_MAX + 1]; + char clientId[50]; + IoT_Client_Init_Params initParams; + IoT_Client_Connect_Params connectParams; + int pubThreadReturn; + int yieldThreadReturn = 0; + float percentOfRxMsg = 0.0; + IoT_Error_t rc = SUCCESS; + int i, rxMsgCount = 0, j = 0; + struct timeval connectTime, subscribeTopic; + struct timeval start, end; + unsigned int connectCounter = 0; + int test_result = 0; + ThreadData threadData; + AWS_IoT_Client client; + + terminate_yield_thread = false; + isPubThreadFinished = false; + + rxMsgBufferTooBigCounter = 0; + rxUnexpectedNumberCounter = 0; + rePublishCount = 0; + wrongYieldCount = 0; + for(i = 0; i < PUBLISH_COUNT; i++) { + countArray[i] = 0; + } + + IOT_DEBUG("\nConnecting Client "); + do { + getcwd(CurrentWD, sizeof(CurrentWD)); + snprintf(root_CA, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_ROOT_CA_FILENAME); + snprintf(clientCRT, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_CERTIFICATE_FILENAME); + snprintf(clientKey, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_PRIVATE_KEY_FILENAME); + srand((unsigned int)time(NULL)); + snprintf(clientId, 50, "%s_%d", INTEGRATION_TEST_CLIENT_ID, rand() % 10000); + + printf("\n\nClient ID : %s \n", clientId); + + IOT_DEBUG("Root CA Path : %s\n clientCRT : %s\n clientKey : %s\n", root_CA, clientCRT, clientKey); + initParams.pHostURL = AWS_IOT_MQTT_HOST; + initParams.port = 8883; + initParams.pRootCALocation = root_CA; + initParams.pDeviceCertLocation = clientCRT; + initParams.pDevicePrivateKeyLocation = clientKey; + initParams.mqttCommandTimeout_ms = 10000; + initParams.tlsHandshakeTimeout_ms = 10000; + initParams.disconnectHandler = aws_iot_mqtt_tests_disconnect_callback_handler; + initParams.enableAutoReconnect = false; + aws_iot_mqtt_init(&client, &initParams); + + connectParams.keepAliveIntervalInSec = 10; + connectParams.isCleanSession = true; + connectParams.MQTTVersion = MQTT_3_1_1; + connectParams.pClientID = (char *)&clientId; + connectParams.clientIDLen = strlen(clientId); + connectParams.isWillMsgPresent = false; + connectParams.pUsername = NULL; + connectParams.usernameLen = 0; + connectParams.pPassword = NULL; + connectParams.passwordLen = 0; + + gettimeofday(&connectTime, NULL); + rc = aws_iot_mqtt_connect(&client, &connectParams); + gettimeofday(&end, NULL); + timersub(&end, &start, &connectTime); + + connectCounter++; + } while(rc != SUCCESS && connectCounter < CONNECT_MAX_ATTEMPT_COUNT); + + if(SUCCESS == rc) { + IOT_DEBUG("## Connect Success. Time sec: %d, usec: %d\n", connectTime.tv_sec, connectTime.tv_usec); + } else { + IOT_ERROR("## Connect Failed. error code %d\n", rc); + return -1; + } + + aws_iot_mqtt_tests_subscribe_to_test_topic(&client, QOS1, &subscribeTopic); + + yieldThreadReturn = pthread_create(&yield_thread, NULL, aws_iot_mqtt_tests_yield_thread_runner, &client); + sleep(1); + + threadData.client = &client; + threadData.threadId = 1; + pubThreadReturn = pthread_create(&publish_thread, NULL, aws_iot_mqtt_tests_publish_thread_runner, &threadData); + + do { + sleep(1); //Let all threads run + } while(!isPubThreadFinished); + + // This sleep is to ensure that the last publish message has enough time to be received by us + sleep(1); + + terminate_yield_thread = true; + sleep(1); + + /* Not using pthread_join because all threads should have terminated gracefully at this point. If they haven't, + * which should not be possible, something below will fail. */ + + for(i = 0; i < PUBLISH_COUNT; i++) { + if(countArray[i] > 0) { + rxMsgCount++; + } + } + + IOT_DEBUG("\n\nResult : \n"); + percentOfRxMsg = (float) rxMsgCount * 100 / PUBLISH_COUNT; + if(percentOfRxMsg >= RX_RECEIVE_PERCENTAGE && rxMsgBufferTooBigCounter == 0 && rxUnexpectedNumberCounter == 0 && + wrongYieldCount == 0) { + IOT_DEBUG("\n\nSuccess: %f \%\n", percentOfRxMsg); + IOT_DEBUG("Published Messages: %d , Received Messages: %d \n", PUBLISH_COUNT, rxMsgCount); + IOT_DEBUG("QoS 1 re publish count %d\n", rePublishCount); + IOT_DEBUG("Connection Attempts %d\n", connectCounter); + IOT_DEBUG("Yield count without error during callback %d\n", wrongYieldCount); + test_result = 0; + } else { + IOT_ERROR("\n\nFailure: %f\n", percentOfRxMsg); + IOT_ERROR("\"Received message was too big than anything sent\" count: %d\n", rxMsgBufferTooBigCounter); + IOT_ERROR("\"The number received is out of the range\" count: %d\n", rxUnexpectedNumberCounter); + IOT_ERROR("Yield count without error during callback %d\n", wrongYieldCount); + test_result = -2; + } + aws_iot_mqtt_disconnect(&client); + return test_result; +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_integration_runner.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_integration_runner.c new file mode 100644 index 00000000..5ce5bd02 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_integration_runner.c @@ -0,0 +1,71 @@ +/* +* Copyright 2015-2016 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_test_integration_runner.c + * @brief Integration Test runner + */ + +#include "aws_iot_test_integration_common.h" + +int main() { + int rc = 0; + printf("\n\n"); + printf("*************************************************************************************************\n"); + printf("* Starting TEST 1 MQTT Version 3.1.1 Basic Subscribe QoS 1 Publish QoS 1 with Single Client *\n"); + printf("*************************************************************************************************\n"); + rc = aws_iot_mqtt_tests_basic_connectivity(); + if(0 != rc) { + printf("\n********************************************************************************************************\n"); + printf("* TEST 1 MQTT Version 3.1.1 Basic Subscribe QoS 1 Publish QoS 1 with Single Client FAILED! RC : %4d *\n", rc); + printf("********************************************************************************************************\n"); + return 1; + } + printf("\n*************************************************************************************************\n"); + printf("* Test 1 MQTT Version 3.1.1 Basic Subscribe QoS 1 Publish QoS 1 with Single Client SUCCESS!! *\n"); + printf("*************************************************************************************************\n"); + + printf("\n\n"); + printf("************************************************************************************************************\n"); + printf("* Starting TEST 2 MQTT Version 3.1.1 Multithreaded Subscribe QoS 1 Publish QoS 1 with Multiple Clients *\n"); + printf("************************************************************************************************************\n"); + rc = aws_iot_mqtt_tests_multiple_clients(); + if(0 != rc) { + printf("\n*******************************************************************************************************************\n"); + printf("* TEST 2 MQTT Version 3.1.1 Multithreaded Subscribe QoS 1 Publish QoS 1 with Multiple Clients FAILED! RC : %4d *\n", rc); + printf("*******************************************************************************************************************\n"); + return 1; + } + printf("\n*************************************************************************************************************\n"); + printf("* TEST 2 MQTT Version 3.1.1 Multithreaded Subscribe QoS 1 Publish QoS 1 with Multiple Clients SUCCESS!! *\n"); + printf("*************************************************************************************************************\n"); + + printf("\n\n"); + printf("*********************************************************\n"); + printf("* Starting TEST 3 MQTT Version 3.1.1 Auto Reconnect *\n"); + printf("*********************************************************\n"); + rc = aws_iot_mqtt_tests_auto_reconnect(); + if(0 != rc) { + printf("\n***************************************************************\n"); + printf("* TEST 3 MQTT Version 3.1.1 Auto Reconnect FAILED! RC : %4d *\n", rc); + printf("***************************************************************\n"); + return 1; + } + printf("\n**********************************************************\n"); + printf("* TEST 3 MQTT Version 3.1.1 Auto Reconnect SUCCESS!! *\n"); + printf("**********************************************************\n"); + + return 0; +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_multiple_clients.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_multiple_clients.c new file mode 100644 index 00000000..d017e4fb --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_multiple_clients.c @@ -0,0 +1,274 @@ +/* +* Copyright 2015-2016 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_test_multiple_clients.c + * @brief Integration Test for multiple clients from the same application + */ + +#include "aws_iot_test_integration_common.h" + +static bool terminate_yield_thread; +static bool isPubThreadFinished; + +static unsigned int countArray[PUBLISH_COUNT]; +static unsigned int rxMsgBufferTooBigCounter; +static unsigned int rxUnexpectedNumberCounter; +static unsigned int rePublishCount; + +static void aws_iot_mqtt_tests_message_aggregator(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, + IoT_Publish_Message_Params *params, void *pData) { + char tempBuf[10]; + unsigned int tempInt = 0; + + IOT_UNUSED(pClient); + IOT_UNUSED(topicName); + IOT_UNUSED(topicNameLen); + IOT_UNUSED(pData); + + if(10 >= params->payloadLen) { + snprintf(tempBuf, params->payloadLen, params->payload); + printf("\nMsg received : %s", tempBuf); + tempInt = atoi(tempBuf); + if(0 < tempInt && PUBLISH_COUNT >= tempInt) { + countArray[tempInt - 1]++; + } else { + rxUnexpectedNumberCounter++; + } + } else { + rxMsgBufferTooBigCounter++; + } +} + +static void aws_iot_mqtt_tests_disconnect_callback_handler(AWS_IoT_Client *pClient, void *param) { + IOT_UNUSED(pClient); + IOT_UNUSED(param); +} + +static IoT_Error_t aws_iot_mqtt_tests_connect_client_to_service(AWS_IoT_Client *pClient, struct timeval *pConnectTime, + char *clientId, char *rootCA, char *clientCRT, + char *clientKey) { + IoT_Client_Init_Params initParams; + IoT_Client_Connect_Params connectParams; + IoT_Error_t rc; + struct timeval start, end; + + initParams.pHostURL = AWS_IOT_MQTT_HOST; + initParams.port = 8883; + initParams.pRootCALocation = rootCA; + initParams.pDeviceCertLocation = clientCRT; + initParams.pDevicePrivateKeyLocation = clientKey; + initParams.mqttCommandTimeout_ms = 5000; + initParams.tlsHandshakeTimeout_ms = 2000; + initParams.disconnectHandler = aws_iot_mqtt_tests_disconnect_callback_handler; + initParams.enableAutoReconnect = false; + rc = aws_iot_mqtt_init(pClient, &initParams); + printf("\n Init response : %d", rc); + + printf("\nRoot CA Path : %s\nClientCRT : %s\nClientKey : %s \nClient ID : %s", rootCA, clientCRT, + clientKey, clientId); + connectParams.keepAliveIntervalInSec = 5; + connectParams.isCleanSession = true; + connectParams.MQTTVersion = MQTT_3_1_1; + connectParams.pClientID = clientId; + connectParams.clientIDLen = strlen(clientId); + connectParams.isWillMsgPresent = 0; + connectParams.pUsername = NULL; + connectParams.usernameLen = 0; + connectParams.pPassword = NULL; + connectParams.passwordLen = 0; + + gettimeofday(&start, NULL); + rc = aws_iot_mqtt_connect(pClient, &connectParams); + printf("\nConnect response : %d ", rc); + gettimeofday(&end, NULL); + timersub(&end, &start, pConnectTime); + + return rc; +} + +static IoT_Error_t aws_iot_mqtt_tests_subscribe_to_test_topic(AWS_IoT_Client *pClient, QoS qos, struct timeval *pSubscribeTime) { + IoT_Error_t rc = SUCCESS; + struct timeval start, end; + + gettimeofday(&start, NULL); + rc = aws_iot_mqtt_subscribe(pClient, INTEGRATION_TEST_TOPIC, strlen(INTEGRATION_TEST_TOPIC), qos, + aws_iot_mqtt_tests_message_aggregator, NULL); + printf("\nSub response : %d\n", rc); + gettimeofday(&end, NULL); + + timersub(&end, &start, pSubscribeTime); + + return rc; +} + +static void *aws_iot_mqtt_tests_yield_thread_runner(void *ptr) { + IoT_Error_t rc = SUCCESS; + AWS_IoT_Client *pClient = (AWS_IoT_Client *) ptr; + while(SUCCESS == rc && false == terminate_yield_thread) { + do { + usleep(THREAD_SLEEP_INTERVAL_USEC); + rc = aws_iot_mqtt_yield(pClient, 100); + } while(MQTT_CLIENT_NOT_IDLE_ERROR == rc); + + if(SUCCESS != rc) { + IOT_ERROR("\nYield Returned : %d ", rc); + } + } +} + +static void *aws_iot_mqtt_tests_publish_thread_runner(void *ptr) { + int itr = 0; + char cPayload[10]; + IoT_Publish_Message_Params params; + IoT_Error_t rc = SUCCESS; + AWS_IoT_Client *pClient = (AWS_IoT_Client *) ptr; + + for(itr = 0; itr < PUBLISH_COUNT; itr++) { + sprintf(cPayload, "%d", itr + 1); + params.payload = (void *) cPayload; + params.payloadLen = strlen(cPayload) + 1; + params.qos = QOS1; + params.isRetained = 0; + rc = aws_iot_mqtt_publish(pClient, INTEGRATION_TEST_TOPIC, strlen(INTEGRATION_TEST_TOPIC), ¶ms); + printf("\n Publishing %s", cPayload); + if(SUCCESS != rc) { + printf("Error Publishing #%d --> %d\n ", itr, rc); + usleep(300000); + rc = aws_iot_mqtt_publish(pClient, INTEGRATION_TEST_TOPIC, strlen(INTEGRATION_TEST_TOPIC), ¶ms); + rePublishCount++; + if(SUCCESS != rc) { + printf("Error Publishing #%d --> %d Second Attempt \n", itr, rc); + } + } + usleep(300000); + } + isPubThreadFinished = true; +} + + +int aws_iot_mqtt_tests_multiple_clients() { + char certDirectory[15] = "../../certs"; + char CurrentWD[PATH_MAX + 1]; + char rootCA[PATH_MAX + 1]; + char clientCRT[PATH_MAX + 1]; + char clientKey[PATH_MAX + 1]; + + char subClientId[50]; + char pubClientId[50]; + + int itr = 0; + int rxMsgCount = 0; + int test_result = 0; + int pubThreadReturn = 0; + int yieldThreadReturn = 0; + unsigned int connectCounter = 0; + float percentOfRxMsg = 0.0; + + IoT_Error_t rc = SUCCESS; + pthread_t yield_thread; + pthread_t publish_thread; + struct timeval connectTime; + struct timeval subscribeTopic; + + AWS_IoT_Client pubClient; + AWS_IoT_Client subClient; + + terminate_yield_thread = false; + isPubThreadFinished = false; + rxMsgBufferTooBigCounter = 0; + rxUnexpectedNumberCounter = 0; + rePublishCount = 0; + + srand((unsigned int)time(NULL)); + snprintf(subClientId, 50, "%s_%d", INTEGRATION_TEST_CLIENT_ID_SUB, rand() % 10000); + snprintf(pubClientId, 50, "%s_%d", INTEGRATION_TEST_CLIENT_ID_PUB, rand() % 10000); + + getcwd(CurrentWD, sizeof(CurrentWD)); + + snprintf(rootCA, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_ROOT_CA_FILENAME); + snprintf(clientCRT, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_CERTIFICATE_FILENAME); + snprintf(clientKey, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_PRIVATE_KEY_FILENAME); + + for(itr = 0; itr < PUBLISH_COUNT; itr++) { + countArray[itr] = 0; + } + + printf(" \n Connecting Pub Client "); + do { + rc = aws_iot_mqtt_tests_connect_client_to_service(&pubClient, &connectTime, pubClientId, rootCA, + clientCRT, clientKey); + connectCounter++; + } while(SUCCESS != rc && CONNECT_MAX_ATTEMPT_COUNT > connectCounter); + + if(SUCCESS == rc) { + printf("\n## Connect Success. Time sec: %d, usec: %d\n", connectTime.tv_sec, connectTime.tv_usec); + } else { + printf("\n## Connect Failed. error code %d\n", rc); + return -1; + } + + printf("\n Connecting Sub Client "); + do { + rc = aws_iot_mqtt_tests_connect_client_to_service(&subClient, &connectTime, subClientId, rootCA, + clientCRT, clientKey); + connectCounter++; + } while(SUCCESS != rc && connectCounter < CONNECT_MAX_ATTEMPT_COUNT); + + if(SUCCESS == rc) { + printf("## Connect Success. Time sec: %d, usec: %d\n", connectTime.tv_sec, connectTime.tv_usec); + } else { + printf("## Connect Failed. error code %d\n", rc); + return -1; + } + + aws_iot_mqtt_tests_subscribe_to_test_topic(&subClient, QOS1, &subscribeTopic); + + yieldThreadReturn = pthread_create(&yield_thread, NULL, aws_iot_mqtt_tests_yield_thread_runner, &subClient); + pubThreadReturn = pthread_create(&publish_thread, NULL, aws_iot_mqtt_tests_publish_thread_runner, &pubClient); + + /* This sleep is to ensure that the last publish message has enough time to be received by us */ + do { + sleep(1); + } while(!isPubThreadFinished); + + /* Kill yield thread */ + terminate_yield_thread = true; + sleep(1); + + aws_iot_mqtt_disconnect(&pubClient); + aws_iot_mqtt_disconnect(&subClient); + + for(itr = 0; itr < PUBLISH_COUNT; itr++) { + if(countArray[itr] > 0) { + rxMsgCount++; + } + } + + percentOfRxMsg = (float) rxMsgCount * 100 / PUBLISH_COUNT; + if(percentOfRxMsg >= RX_RECEIVE_PERCENTAGE && rxMsgBufferTooBigCounter == 0 && rxUnexpectedNumberCounter == 0) { + printf("\nSuccess: %f \%\n", percentOfRxMsg); + printf("Published Messages: %d , Received Messages: %d \n", PUBLISH_COUNT, rxMsgCount); + printf("QoS 1 re publish count %d\n", rePublishCount); + printf("Connection Attempts %d\n", connectCounter); + test_result = 0; + } else { + printf("\nFailure: %f\n", percentOfRxMsg); + printf("\"Received message was too big than anything sent\" count: %d\n", rxMsgBufferTooBigCounter); + printf("\"The number received is out of the range\" count: %d\n", rxUnexpectedNumberCounter); + test_result = -2; + } + return test_result; +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/README.md b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/README.md new file mode 100644 index 00000000..a58e2e47 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/README.md @@ -0,0 +1,12 @@ +## Unit Tests +This folder contains unit tests to verify Embedded C SDK functionality. These have been tested to work with Linux using CppUTest as the testing framework. +CppUTest is not provided along with this code. It needs to be separately downloaded. These tests have been verified to work with CppUTest v3.6, which can be found [here](https://github.com/cpputest/cpputest/tree/v3.6). +Each test contains a comment describing what is being tested. The Tests can be run using the Makefile provided in the root folder for the SDK. There are a total of 187 tests. + +To run these tests, follow the below steps: + + * Copy the code for CppUTest v3.6 from github to external_libs/CppUTest + * Navigate to SDK Root folder + * run `make run-unit-tests` + +This will run all unit tests and generate coverage report in the build_output folder. The report can be viewed by opening /build_output/generated-coverage/index.html in a browser. \ No newline at end of file diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/include/aws_iot_config.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/include/aws_iot_config.h new file mode 100644 index 00000000..e22db062 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/include/aws_iot_config.h @@ -0,0 +1,57 @@ +/* +* Copyright 2015-2016 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 IoT Client Unit Testing - IoT Config + */ + +#ifndef IOT_TESTS_UNIT_CONFIG_H_ +#define IOT_TESTS_UNIT_CONFIG_H_ + +// Get from console +// ================================================= +#define AWS_IOT_MQTT_HOST "localhost" +#define AWS_IOT_MQTT_PORT 8883 +#define AWS_IOT_MQTT_CLIENT_ID "C-SDK_UnitTestClient" +#define AWS_IOT_MY_THING_NAME "C-SDK_UnitTestThing" +#define AWS_IOT_ROOT_CA_FILENAME "rootCA.crt" +#define AWS_IOT_CERTIFICATE_FILENAME "cert.crt" +#define AWS_IOT_PRIVATE_KEY_FILENAME "privkey.pem" +// ================================================= + +// MQTT PubSub +#define AWS_IOT_MQTT_TX_BUF_LEN 512 +#define AWS_IOT_MQTT_RX_BUF_LEN 512 +#define AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS 5 + +// Thing Shadow specific configs +#define SHADOW_MAX_SIZE_OF_RX_BUFFER 512 +#define MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES 80 /** {"clientToken": ">>uniqueClientID<<+sequenceNumber"}*/ +#define MAX_SIZE_CLIENT_ID_WITH_SEQUENCE MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES + 10 /** {"clientToken": ">>uniqueClientID+sequenceNumber<<"}*/ +#define MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE MAX_SIZE_CLIENT_ID_WITH_SEQUENCE + 20 /** >>{"clientToken": "uniqueClientID+sequenceNumber"}<<*/ +#define MAX_SIZE_OF_THINGNAME 30 +#define MAX_ACKS_TO_COMEIN_AT_ANY_GIVEN_TIME 10 +#define MAX_THINGNAME_HANDLED_AT_ANY_GIVEN_TIME 10 +#define MAX_JSON_TOKEN_EXPECTED 120 +#define MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME 60 +#define MAX_SIZE_OF_THING_NAME 20 +#define MAX_SHADOW_TOPIC_LENGTH_BYTES MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME + MAX_SIZE_OF_THING_NAME + +// Auto Reconnect specific config +#define AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL 1000 +#define AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL 128000 + +#endif /* IOT_TESTS_UNIT_CONFIG_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/include/aws_iot_tests_unit_helper_functions.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/include/aws_iot_tests_unit_helper_functions.h new file mode 100644 index 00000000..d8a18068 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/include/aws_iot_tests_unit_helper_functions.h @@ -0,0 +1,95 @@ +/* +* Copyright 2015-2016 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_tests_unit_helper_functions.h + * @brief IoT Client Unit Testing - Helper Functions + */ + +#ifndef IOT_TESTS_UNIT_HELPER_FUNCTIONS_H_ +#define IOT_TESTS_UNIT_HELPER_FUNCTIONS_H_ + +#include +#include "aws_iot_mqtt_client_interface.h" + +typedef struct { + unsigned char PacketType; + unsigned int RemainingLength; + unsigned int ProtocolLength; + unsigned char ProtocolName[4]; + unsigned int ProtocolLevel; + unsigned char ConnectFlag; + unsigned int KeepAlive; +} ConnectBufferProofread; + +void ResetInvalidParameters(void); + +void InitMQTTParamsSetup(IoT_Client_Init_Params *params, char *pHost, uint16_t port, bool enableAutoReconnect, + iot_disconnect_handler disconnectHandler); + +void ConnectMQTTParamsSetup(IoT_Client_Connect_Params *params, char *pClientID, uint16_t clientIDLen); + +void ConnectMQTTParamsSetup_Detailed(IoT_Client_Connect_Params *params, char *pClientID, uint16_t clientIDLen, + QoS qos, bool isCleanSession, bool isWillMsgPresent, char *pWillTopicName, + uint16_t willTopicNameLen, char *pWillMessage, uint16_t willMsgLen, + char *pUsername, uint16_t userNameLen, char *pPassword, + uint16_t passwordLen); + +void printBuffer(unsigned char *buffer, size_t len); + +void setTLSRxBufferForConnack(IoT_Client_Connect_Params *params, unsigned char sessionPresent, + unsigned char connackResponseCode); + +void setTLSRxBufferForPuback(void); + +void setTLSRxBufferForSuback(char *topicName, size_t topicNameLen, QoS qos, IoT_Publish_Message_Params params); + +void setTLSRxBufferForDoubleSuback(char *topicName, size_t topicNameLen, QoS qos, IoT_Publish_Message_Params params); + +void setTLSRxBufferForSubFail(void); + +void setTLSRxBufferWithMsgOnSubscribedTopic(char *topicName, size_t topicNameLen, QoS qos, + IoT_Publish_Message_Params params, char *pMsg); + +void setTLSRxBufferForUnsuback(void); + +void setTLSRxBufferForPingresp(void); + +void setTLSRxBufferForConnackAndSuback(IoT_Client_Connect_Params *conParams, unsigned char sessionPresent, + char *topicName, size_t topicNameLen, QoS qos); + +unsigned char isLastTLSTxMessagePuback(void); + +unsigned char isLastTLSTxMessagePingreq(void); + +unsigned char isLastTLSTxMessageDisconnect(void); + +void setTLSRxBufferDelay(int seconds, int microseconds); + +void ResetTLSBuffer(void); + +unsigned char generateMultipleSubTopics(char *des, int boundary); + +void encodeRemainingLength(unsigned char *buf, size_t *st, size_t length); + +unsigned char *connectTxBufferHeaderParser(ConnectBufferProofread *params, unsigned char *buf); + +bool isConnectTxBufFlagCorrect(IoT_Client_Connect_Params *settings, ConnectBufferProofread *readRes); + +bool isConnectTxBufPayloadCorrect(IoT_Client_Connect_Params *settings, unsigned char *payloadBuf); + +void printPrfrdParams(ConnectBufferProofread *params); + +#endif /* IOT_TESTS_UNIT_HELPER_FUNCTIONS_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/include/aws_iot_tests_unit_shadow_helper.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/include/aws_iot_tests_unit_shadow_helper.h new file mode 100644 index 00000000..455a387b --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/include/aws_iot_tests_unit_shadow_helper.h @@ -0,0 +1,43 @@ +/* +* Copyright 2015-2016 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_tests_unit_shadow_helper.h + * @brief IoT Client Unit Testing - Shadow Helper functions + */ + +#ifndef IOT_TESTS_UNIT_SHADOW_HELPER_FUNCTIONS_H_ +#define IOT_TESTS_UNIT_SHADOW_HELPER_FUNCTIONS_H_ + +#define AWS_THINGS_TOPIC "$aws/things/" +#define SHADOW_TOPIC "/shadow/" +#define ACCEPTED_TOPIC "/accepted" +#define REJECTED_TOPIC "/rejected" +#define UPDATE_TOPIC "update" +#define GET_TOPIC "get" +#define DELETE_TOPIC "delete" + + +#define GET_ACCEPTED_TOPIC AWS_THINGS_TOPIC AWS_IOT_MY_THING_NAME SHADOW_TOPIC GET_TOPIC ACCEPTED_TOPIC +#define GET_REJECTED_TOPIC AWS_THINGS_TOPIC AWS_IOT_MY_THING_NAME SHADOW_TOPIC GET_TOPIC REJECTED_TOPIC +#define GET_PUB_TOPIC AWS_THINGS_TOPIC AWS_IOT_MY_THING_NAME SHADOW_TOPIC GET_TOPIC + +#define DELETE_ACCEPTED_TOPIC AWS_THINGS_TOPIC AWS_IOT_MY_THING_NAME SHADOW_TOPIC DELETE_TOPIC ACCEPTED_TOPIC +#define DELETE_REJECTED_TOPIC AWS_THINGS_TOPIC AWS_IOT_MY_THING_NAME SHADOW_TOPIC DELETE_TOPIC REJECTED_TOPIC + +#define UPDATE_ACCEPTED_TOPIC AWS_THINGS_TOPIC AWS_IOT_MY_THING_NAME SHADOW_TOPIC UPDATE_TOPIC ACCEPTED_TOPIC +#define UPDATE_REJECTED_TOPIC AWS_THINGS_TOPIC AWS_IOT_MY_THING_NAME SHADOW_TOPIC UPDATE_TOPIC REJECTED_TOPIC + +#endif /* IOT_TESTS_UNIT_SHADOW_HELPER_FUNCTIONS_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_common_tests.cpp b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_common_tests.cpp new file mode 100644 index 00000000..449647ec --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_common_tests.cpp @@ -0,0 +1,34 @@ +/* +* Copyright 2015-2016 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_tests_unit_common_tests.cpp + * @brief IoT Client Unit Testing - Common Tests + */ + +#include +#include + +TEST_GROUP_C(CommonTests){ + TEST_GROUP_C_SETUP_WRAPPER(CommonTests) + TEST_GROUP_C_TEARDOWN_WRAPPER(CommonTests) +}; + +TEST_GROUP_C_WRAPPER(CommonTests, NullClientGetState) +TEST_GROUP_C_WRAPPER(CommonTests, NullClientSetAutoreconnect) + +TEST_GROUP_C_WRAPPER(CommonTests, UnexpectedAckFiltering) +TEST_GROUP_C_WRAPPER(CommonTests, BigMQTTRxMessageIgnore) +TEST_GROUP_C_WRAPPER(CommonTests, BigMQTTRxMessageReadNextMessage) diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_common_tests_helper.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_common_tests_helper.c new file mode 100644 index 00000000..e7a852e2 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_common_tests_helper.c @@ -0,0 +1,186 @@ +/* +* Copyright 2015-2016 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_tests_unit_common_tests_helper.h + * @brief IoT Client Unit Testing - Common Tests Helper + */ + +#include +#include +#include + +#include "aws_iot_mqtt_client_interface.h" +#include "aws_iot_log.h" +#include "aws_iot_tests_unit_helper_functions.h" + +static IoT_Client_Init_Params initParams; +static IoT_Client_Connect_Params connectParams; +static IoT_Publish_Message_Params testPubMsgParams; +static AWS_IoT_Client iotClient; + +static char subTopic[10] = "sdk/Test"; +static uint16_t subTopicLen = 8; +char cPayload[100]; + +char cbBuffer[AWS_IOT_MQTT_TX_BUF_LEN + 2]; + +static void iot_tests_unit_common_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, IoT_Publish_Message_Params *params, + void *pData) { + char *tmp = params->payload; + unsigned int i; + + IOT_UNUSED(pClient); + IOT_UNUSED(topicName); + IOT_UNUSED(topicNameLen); + IOT_UNUSED(pData); + + for(i = 0; i < params->payloadLen; i++) { + cbBuffer[i] = tmp[i]; + } +} + +TEST_GROUP_C_SETUP(CommonTests) { + ResetTLSBuffer(); + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + initParams.mqttCommandTimeout_ms = 2000; + IoT_Error_t rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + IOT_DEBUG("\n\nMQTT Status State : %d, RC : %d\n\n", aws_iot_mqtt_get_client_state(&iotClient), rc); + + testPubMsgParams.qos = QOS1; + testPubMsgParams.isRetained = 0; + snprintf(cPayload, 100, "%s : %d ", "hello from SDK", 0); + testPubMsgParams.payload = (void *) cPayload; + testPubMsgParams.payloadLen = strlen(cPayload); + + ResetTLSBuffer(); +} + +TEST_GROUP_C_TEARDOWN(CommonTests) { + /* Clean up. Not checking return code here because this is common to all tests. + * A test might have already caused a disconnect by this point. + */ + IoT_Error_t rc = aws_iot_mqtt_disconnect(&iotClient); + IOT_UNUSED(rc); +} + +TEST_C(CommonTests, NullClientGetState) { + ClientState cs = aws_iot_mqtt_get_client_state(NULL); + CHECK_EQUAL_C_INT(CLIENT_STATE_INVALID, cs); +} + +TEST_C(CommonTests, NullClientSetAutoreconnect) { + IoT_Error_t rc = aws_iot_mqtt_autoreconnect_set_status(NULL, true); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +// Unexpected Ack section +TEST_C(CommonTests, UnexpectedAckFiltering) { + IoT_Error_t rc = FAILURE; + + IOT_DEBUG("\n-->Running CommonTests - Unexpected Ack Filtering\n"); + // Assume we are connected and have not done anything yet + // Connack + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ResetTLSBuffer(); + // Puback + setTLSRxBufferForPuback(); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ResetTLSBuffer(); + // Suback: OoS1 + setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ResetTLSBuffer(); + // Suback: QoS0 + setTLSRxBufferForSuback(subTopic, subTopicLen, QOS0, testPubMsgParams); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ResetTLSBuffer(); + // Unsuback + setTLSRxBufferForUnsuback(); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); +} + +TEST_C(CommonTests, BigMQTTRxMessageIgnore) { + uint32_t i = 0; + IoT_Error_t rc = FAILURE; + char expectedCallbackString[AWS_IOT_MQTT_TX_BUF_LEN + 2]; + + IOT_DEBUG("\n-->Running CommonTests - Ignore Large Incoming Message \n"); + + setTLSRxBufferForSuback("limitTest/topic1", 16, QOS0, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "limitTest/topic1", 16, QOS0, iot_tests_unit_common_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + for(i = 0; i < AWS_IOT_MQTT_TX_BUF_LEN; i++) { + expectedCallbackString[i] = 'X'; + } + expectedCallbackString[i + 1] = '\0'; + + setTLSRxBufferWithMsgOnSubscribedTopic("limitTest/topic1", 16, QOS0, testPubMsgParams, expectedCallbackString); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(MQTT_RX_BUFFER_TOO_SHORT_ERROR, rc); +} + +/** + * + * On receiving a big message into the TLS buffer the MQTT client should flush it out, otherwise it can cause undefined behavior. + */ +TEST_C(CommonTests, BigMQTTRxMessageReadNextMessage) { + uint32_t i = 0; + IoT_Error_t rc = FAILURE; + char expectedCallbackString[AWS_IOT_MQTT_TX_BUF_LEN + 2]; + + IOT_DEBUG("\n-->Running CommonTests - Clear Buffer when large message received and continue reading \n"); + + setTLSRxBufferForSuback("limitTest/topic1", 16, QOS0, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "limitTest/topic1", 16, QOS0, iot_tests_unit_common_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + for(i = 0; i < AWS_IOT_MQTT_TX_BUF_LEN; i++) { + expectedCallbackString[i] = 'X'; + } + expectedCallbackString[i + 1] = '\0'; + + setTLSRxBufferWithMsgOnSubscribedTopic("limitTest/topic1", 16, QOS0, testPubMsgParams, expectedCallbackString); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(MQTT_RX_BUFFER_TOO_SHORT_ERROR, rc); + + ResetTLSBuffer(); + + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + expectedCallbackString[3] = '\0'; + setTLSRxBufferWithMsgOnSubscribedTopic("limitTest/topic1", 16, QOS1, testPubMsgParams, expectedCallbackString); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(rc, SUCCESS); + CHECK_EQUAL_C_STRING("XXX", cbBuffer); +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_connect.cpp b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_connect.cpp new file mode 100644 index 00000000..bfb3823b --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_connect.cpp @@ -0,0 +1,84 @@ +/* +* Copyright 2015-2016 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_tests_unit_connect.cpp + * @brief IoT Client Unit Testing - Connect API Tests + */ + +#include +#include + +TEST_GROUP_C(ConnectTests){ + TEST_GROUP_C_SETUP_WRAPPER(ConnectTests) + TEST_GROUP_C_TEARDOWN_WRAPPER(ConnectTests) +}; + +/* B:1 - Init with Null/empty client instance */ +TEST_GROUP_C_WRAPPER(ConnectTests, NullClientInit) +/* B:2 - Connect with Null/empty client instance */ +TEST_GROUP_C_WRAPPER(ConnectTests, NullClientConnect) +/* B:3 - Connect with Null/Empty endpoint */ +TEST_GROUP_C_WRAPPER(ConnectTests, NullHost) +/* B:4 - Connect with Null/Empty port */ +TEST_GROUP_C_WRAPPER(ConnectTests, NullPort) +/* B:5 - Connect with Null/Empty root CA path */ +TEST_GROUP_C_WRAPPER(ConnectTests, NullRootCAPath) +/* B:6 - Connect with Null/Empty Client certificate path */ +TEST_GROUP_C_WRAPPER(ConnectTests, NullClientCertificate) +/* B:7 - Connect with Null/Empty private key Path */ +TEST_GROUP_C_WRAPPER(ConnectTests, NullPrivateKeyPath) +/* B:8 - Connect with Null/Empty client ID */ +TEST_GROUP_C_WRAPPER(ConnectTests, NullClientID) +/* B:9 - Connect with invalid Endpoint */ +TEST_GROUP_C_WRAPPER(ConnectTests, InvalidEndpoint) +/* B:10 - Connect with invalid correct endpoint but invalid port */ +TEST_GROUP_C_WRAPPER(ConnectTests, InvalidPort) +/* B:11 - Connect with invalid Root CA path */ +TEST_GROUP_C_WRAPPER(ConnectTests, InvalidRootCAPath) +/* B:12 - Connect with invalid Client certificate path */ +TEST_GROUP_C_WRAPPER(ConnectTests, InvalidClientCertPath) +/* B:13 - Connect with invalid private key path */ +TEST_GROUP_C_WRAPPER(ConnectTests, InvalidPrivateKeyPath) +/* B:14 - Connect, no response timeout */ +TEST_GROUP_C_WRAPPER(ConnectTests, NoResponseTimeout) +/* B:15 - Connect, connack malformed, too large */ +TEST_GROUP_C_WRAPPER(ConnectTests, ConnackTooLarge) +/* B:16 - Connect, connack malformed, fixed header corrupted */ +TEST_GROUP_C_WRAPPER(ConnectTests, FixedHeaderCorrupted) +/* B:17 - Connect, connack malformed, invalid remaining length */ +TEST_GROUP_C_WRAPPER(ConnectTests, InvalidRemainingLength) +/* B:18 - Connect, connack returned error, unacceptable protocol version */ +TEST_GROUP_C_WRAPPER(ConnectTests, UnacceptableProtocolVersion) +/* B:19 - Connect, connack returned error, identifier rejected */ +TEST_GROUP_C_WRAPPER(ConnectTests, IndentifierRejected) +/* B:20 - Connect, connack returned error, Server unavailable */ +TEST_GROUP_C_WRAPPER(ConnectTests, ServerUnavailable) +/* B:21 - Connect, connack returned error, bad user name or password */ +TEST_GROUP_C_WRAPPER(ConnectTests, BadUserNameOrPassword) +/* B:22 - Connect, connack returned error, not authorized */ +TEST_GROUP_C_WRAPPER(ConnectTests, NotAuthorized) +/* B:23 - Connect, connack return after half command timeout delay, success */ +TEST_GROUP_C_WRAPPER(ConnectTests, SuccessAfterDelayedConnack) +/* B:24 - Connect, connack returned success */ +TEST_GROUP_C_WRAPPER(ConnectTests, ConnectSuccess) +/* B:25 - Connect, flag settings and parameters are recorded in buffer */ +TEST_GROUP_C_WRAPPER(ConnectTests, FlagSettingsAndParamsAreRecordedIntoBuf) +/* B:26 - Connect attempt, Disconnect, Manually reconnect */ +TEST_GROUP_C_WRAPPER(ConnectTests, ConnectDisconnectConnect) +/* B:27 - Connect attempt, Clean session, Subscribe */ +TEST_GROUP_C_WRAPPER(ConnectTests, cleanSessionInitSubscribers) +/* B:28 - Connect attempt, power cycle with clean session false */ +TEST_GROUP_C_WRAPPER(ConnectTests, PowerCycleWithCleanSessionFalse) diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_connect_helper.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_connect_helper.c new file mode 100644 index 00000000..0aea77ce --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_connect_helper.c @@ -0,0 +1,720 @@ +/* +* Copyright 2015-2016 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_tests_unit_connect_helper.c + * @brief IoT Client Unit Testing - Connect API Tests Helper + */ + +#include +#include +#include +#include +#include + +#include "aws_iot_tests_unit_mock_tls_params.h" +#include "aws_iot_tests_unit_helper_functions.h" + +#include "aws_iot_log.h" + +static bool unitTestIsMqttConnected = false; + +static IoT_Client_Init_Params initParams; +static IoT_Client_Connect_Params connectParams; +static AWS_IoT_Client iotClient; + +static IoT_Publish_Message_Params testPubMsgParams; +static ConnectBufferProofread prfrdParams; + +static char subTopic1[12] = "sdk/Topic1"; +static char subTopic2[12] = "sdk/Topic2"; + +#define NO_MSG_XXXX "XXXX" +static char CallbackMsgStringclean[100] = NO_MSG_XXXX; + +static void iot_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, + IoT_Publish_Message_Params *params, void *pData) { + char *tmp = params->payload; + unsigned int i; + + if(NULL == pClient || NULL == topicName || 0 == topicNameLen) { + return; + } + + IOT_UNUSED(pData); + + for(i = 0; i < (params->payloadLen); i++) { + CallbackMsgStringclean[i] = tmp[i]; + } +} + +TEST_GROUP_C_SETUP(ConnectTests) { + IoT_Error_t rc = SUCCESS; + unitTestIsMqttConnected = false; + rc = aws_iot_mqtt_disconnect(&iotClient); + ResetTLSBuffer(); + ResetInvalidParameters(); +} + +TEST_GROUP_C_TEARDOWN(ConnectTests) { + /* Clean up. Not checking return code here because this is common to all tests. + * A test might have already caused a disconnect by this point. + */ + IoT_Error_t rc = aws_iot_mqtt_disconnect(&iotClient); + IOT_UNUSED(rc); +} + +/* B:1 - Init with Null/empty client instance */ +TEST_C(ConnectTests, NullClientInit) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:1 - Init with Null/empty client instance \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + rc = aws_iot_mqtt_init(NULL, &initParams); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); + + IOT_DEBUG("-->Success - B:1 - Init with Null/empty client instance \n"); +} + +/* B:2 - Connect with Null/empty client instance */ +TEST_C(ConnectTests, NullClientConnect) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:2 - Connect with Null/empty client instance \n"); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_connect(NULL, &connectParams); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); + + IOT_DEBUG("-->Success - B:2 - Connect with Null/empty client instance \n"); +} + +/* B:3 - Connect with Null/Empty endpoint */ +TEST_C(ConnectTests, NullHost) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:3 - Connect with Null/Empty endpoint \n"); + + InitMQTTParamsSetup(&initParams, NULL, AWS_IOT_MQTT_PORT, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_C(SUCCESS != rc); + + IOT_DEBUG("-->Success - B:3 - Connect with Null/Empty endpoint \n"); +} + +/* B:4 - Connect with Null/Empty port */ +TEST_C(ConnectTests, NullPort) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:4 - Connect with Null/Empty port \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, 0, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_C(SUCCESS != rc); + + IOT_DEBUG("-->Success - B:4 - Connect with Null/Empty port \n"); +} + +/* B:5 - Connect with Null/Empty root CA path */ +TEST_C(ConnectTests, NullRootCAPath) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:6 - Connect with Null/Empty root CA path \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + initParams.pRootCALocation = NULL; + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); + + IOT_DEBUG("-->Success - B:6 - Connect with Null/Empty root CA path \n"); +} + +/* B:6 - Connect with Null/Empty Client certificate path */ +TEST_C(ConnectTests, NullClientCertificate) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:7 - Connect with Null/Empty Client certificate path \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + initParams.pDeviceCertLocation = NULL; + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); + + IOT_DEBUG("-->Success - B:7 - Connect with Null/Empty Client certificate path \n"); +} + +/* B:7 - Connect with Null/Empty private key Path */ +TEST_C(ConnectTests, NullPrivateKeyPath) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:8 - Connect with Null/Empty private key Path \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + initParams.pDevicePrivateKeyLocation = NULL; + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); + + IOT_DEBUG("-->Success - B:8 - Connect with Null/Empty private key Path \n"); +} + +/* B:8 - Connect with Null/Empty client ID */ +TEST_C(ConnectTests, NullClientID) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:8 - Connect with Null/Empty client ID \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + setTLSRxBufferForConnack(&connectParams, 0, 0); + + /* If no client id is passed but a length was passed, return error */ + ConnectMQTTParamsSetup(&connectParams, NULL, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); + + /* If client id is passed but 0 length was passed, return error */ + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); + + /* If client id is NULL and length is 0 then request succeeds */ + ConnectMQTTParamsSetup(&connectParams, NULL, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + IOT_DEBUG("-->Success - B:8 - Connect with Null/Empty client ID \n"); +} + +/* B:9 - Connect with invalid Endpoint */ +TEST_C(ConnectTests, InvalidEndpoint) { + IoT_Error_t rc = SUCCESS; + char invalidEndPoint[20]; + snprintf(invalidEndPoint, 20, "invalid"); + + IOT_DEBUG("-->Running Connect Tests - B:9 - Connect with invalid Endpoint \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + invalidEndpointFilter = invalidEndPoint; + initParams.pHostURL = invalidEndpointFilter; + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_C(SUCCESS != rc); + + IOT_DEBUG("-->Success - B:9 - Connect with invalid Endpoint \n"); +} + +/* B:10 - Connect with invalid correct endpoint but invalid port */ +TEST_C(ConnectTests, InvalidPort) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:10 - Connect with invalid correct endpoint but invalid port \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + invalidPortFilter = 1234; + initParams.port = invalidPortFilter; + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_C(SUCCESS != rc); + + IOT_DEBUG("-->Success - B:10 - Connect with invalid correct endpoint but invalid port \n"); +} + +/* B:11 - Connect with invalid Root CA path */ +TEST_C(ConnectTests, InvalidRootCAPath) { + IoT_Error_t rc = SUCCESS; + char invalidRootCAPath[20]; + snprintf(invalidRootCAPath, 20, "invalid"); + + IOT_DEBUG("-->Running Connect Tests - B:11 - Connect with invalid Root CA path \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + invalidRootCAPathFilter = invalidRootCAPath; + initParams.pRootCALocation = invalidRootCAPathFilter; + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_C(SUCCESS != rc); + + IOT_DEBUG("-->Success - B:11 - Connect with invalid Root CA path \n"); +} + +/* B:12 - Connect with invalid Client certificate path */ +TEST_C(ConnectTests, InvalidClientCertPath) { + IoT_Error_t rc = SUCCESS; + char invalidCertPath[20]; + snprintf(invalidCertPath, 20, "invalid"); + + IOT_DEBUG("-->Running Connect Tests - B:12 - Connect with invalid Client certificate path \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + invalidCertPathFilter = invalidCertPath; + initParams.pDeviceCertLocation = invalidCertPathFilter; + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_C(SUCCESS != rc); + + IOT_DEBUG("-->Success - B:12 - Connect with invalid Client certificate path \n"); +} + +/* B:13 - Connect with invalid private key path */ +TEST_C(ConnectTests, InvalidPrivateKeyPath) { + IoT_Error_t rc = SUCCESS; + char invalidPrivKeyPath[20]; + snprintf(invalidPrivKeyPath, 20, "invalid"); + + IOT_DEBUG("-->Running Connect Tests - B:13 - Connect with invalid private key path \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + invalidPrivKeyPathFilter = invalidPrivKeyPath; + initParams.pDevicePrivateKeyLocation = invalidPrivKeyPathFilter; + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_C(SUCCESS != rc); + + IOT_DEBUG("-->Success - B:13 - Connect with invalid private key path \n"); +} + +/* B:14 - Connect, no response timeout */ +TEST_C(ConnectTests, NoResponseTimeout) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:14 - Connect, no response timeout \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ResetTLSBuffer(); + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, rc); + + IOT_DEBUG("-->Success - B:14 - Connect, no response timeout \n"); +} + +/* B:15 - Connect, connack malformed, too large */ +TEST_C(ConnectTests, ConnackTooLarge) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:15 - Connect, connack malformed, too large \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + RxBuffer.pBuffer[1] = (char) (0x15); /* Set remaining length to a larger than expected value */ + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_C(SUCCESS != rc); + + IOT_DEBUG("-->Success - B:15 - Connect, connack malformed, too large \n"); +} + +/* B:16 - Connect, connack malformed, fixed header corrupted */ +TEST_C(ConnectTests, FixedHeaderCorrupted) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:16 - Connect, connack malformed, fixed header corrupted \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + RxBuffer.pBuffer[0] = (char) (0x00); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_C(SUCCESS != rc); + + IOT_DEBUG("-->Success - B:16 - Connect, connack malformed, fixed header corrupted \n"); +} + +/* B:17 - Connect, connack malformed, invalid remaining length */ +TEST_C(ConnectTests, InvalidRemainingLength) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:17 - Connect, connack malformed, invalid remaining length \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + RxBuffer.pBuffer[1] = (char) (0x00); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(MQTT_DECODE_REMAINING_LENGTH_ERROR, rc); + + IOT_DEBUG("-->Success - B:17 - Connect, connack malformed, invalid remaining length \n"); +} + +/* B:18 - Connect, connack returned error, unacceptable protocol version */ +TEST_C(ConnectTests, UnacceptableProtocolVersion) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:18 - Connect, connack returned error, unacceptable protocol version \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + connectParams.MQTTVersion = 7; + setTLSRxBufferForConnack(&connectParams, 0, 1); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(MQTT_CONNACK_UNACCEPTABLE_PROTOCOL_VERSION_ERROR, rc); + + IOT_DEBUG("-->Success - B:18 - Connect, connack returned error, unacceptable protocol version \n"); +} + +/* B:19 - Connect, connack returned error, identifier rejected */ +TEST_C(ConnectTests, IndentifierRejected) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:19 - Connect, connack returned error, identifier rejected \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 2); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(MQTT_CONNACK_IDENTIFIER_REJECTED_ERROR, rc); + + IOT_DEBUG("-->Success - B:19 - Connect, connack returned error, identifier rejected \n"); +} + +/* B:20 - Connect, connack returned error, Server unavailable */ +TEST_C(ConnectTests, ServerUnavailable) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:20 - Connect, connack returned error, Server unavailable \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 3); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(MQTT_CONNACK_SERVER_UNAVAILABLE_ERROR, rc); + + IOT_DEBUG("-->Success - B:20 - Connect, connack returned error, Server unavailable \n"); +} + +/* B:21 - Connect, connack returned error, bad user name or password */ +TEST_C(ConnectTests, BadUserNameOrPassword) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:21 - Connect, connack returned error, bad user name or password \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 4); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(MQTT_CONNACK_BAD_USERDATA_ERROR, rc); + + IOT_DEBUG("-->Success - B:21 - Connect, connack returned error, bad user name or password \n"); +} + +/* B:22 - Connect, connack returned error, not authorized */ +TEST_C(ConnectTests, NotAuthorized) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("\n-->Running Connect Tests - B:22 - Connect, connack returned error, not authorized \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 5); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(MQTT_CONNACK_NOT_AUTHORIZED_ERROR, rc); + + IOT_DEBUG("\n-->Success - B:22 - Connect, connack returned error, not authorized \n"); +} + +/* B:23 - Connect, connack return after half command timeout delay, success */ +TEST_C(ConnectTests, SuccessAfterDelayedConnack) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:23 - Connect, connack return after half command timeout delay, success \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + setTLSRxBufferDelay(0, (int) initParams.mqttCommandTimeout_ms/2); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + IOT_DEBUG("-->Success - B:23 - Connect, connack return after half command timeout delay, success \n"); +} + +/* B:24 - Connect, connack returned success */ +TEST_C(ConnectTests, ConnectSuccess) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:24 - Connect, connack returned success \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + IOT_DEBUG("-->Success - B:24 - Connect, connack returned success \n"); +} + +/* B:25 - Connect, flag settings and parameters are recorded in buffer */ +TEST_C(ConnectTests, FlagSettingsAndParamsAreRecordedIntoBuf) { + IoT_Error_t rc = SUCCESS; + unsigned char *currPayload = NULL; + + IOT_DEBUG("-->Running Connect Tests - B:25 - Connect, flag settings and parameters are recorded in buffer \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ResetTLSBuffer(); + ConnectMQTTParamsSetup_Detailed(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID), + QOS1, false, true, "willTopicName", (uint16_t) strlen("willTopicName"), "willMsg", + (uint16_t) strlen("willMsg"), NULL, 0, NULL, 0); + connectParams.keepAliveIntervalInSec = (1 << 16) - 1; + setTLSRxBufferForConnack(&connectParams, 0, 0); + + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + currPayload = connectTxBufferHeaderParser(&prfrdParams, TxBuffer.pBuffer); + CHECK_C(true == isConnectTxBufFlagCorrect(&connectParams, &prfrdParams)); + CHECK_C(true == isConnectTxBufPayloadCorrect(&connectParams, currPayload)); + + IOT_DEBUG("-->Success - B:25 - Connect, flag settings and parameters are recorded in buffer \n"); +} + +/* B:26 - Connect attempt, Disconnect, Manually reconnect */ +TEST_C(ConnectTests, ConnectDisconnectConnect) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Connect Tests - B:26 - Connect attempt, Disconnect, Manually reconnect \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + + // connect + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + // check the is_connected call + unitTestIsMqttConnected = aws_iot_mqtt_is_client_connected(&iotClient); + CHECK_EQUAL_C_INT(true, unitTestIsMqttConnected); + + // disconnect + rc = aws_iot_mqtt_disconnect(&iotClient); + CHECK_EQUAL_C_INT(SUCCESS, rc); + // check the is_connected call + unitTestIsMqttConnected = aws_iot_mqtt_is_client_connected(&iotClient); + CHECK_EQUAL_C_INT(false, unitTestIsMqttConnected); + + ResetTLSBuffer(); + setTLSRxBufferForConnack(&connectParams, 0, 0); + + // connect + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + // check the is_connected call + unitTestIsMqttConnected = aws_iot_mqtt_is_client_connected(&iotClient); + CHECK_EQUAL_C_INT(true, unitTestIsMqttConnected); + + IOT_DEBUG("-->Success - B:26 - Connect attempt, Disconnect, Manually reconnect \n"); +} + +/* B:27 - Connect attempt, Clean session, Subscribe + * connect with clean session true and subscribe to a topic1, set msg to topic1 and ensure it is received + * connect cs false, set msg to topic1 and nothing should come in, Sub to topic2 and check if msg is received + * connect cs false and send msg to topic2 and should be received + * cs true and everything should be clean again + */ +TEST_C(ConnectTests, cleanSessionInitSubscribers) { + IoT_Error_t rc = SUCCESS; + char expectedCallbackString[] = "msg topic"; + + IOT_DEBUG("-->Running Connect Tests - B:27 - Connect attempt, Clean session, Subscribe \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + ResetTLSBuffer(); + + //1. connect with clean session true and + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + connectParams.isCleanSession = true; + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + //1. subscribe to a topic1 and + testPubMsgParams.payload = expectedCallbackString; + testPubMsgParams.payloadLen = (uint16_t) strlen(expectedCallbackString); + setTLSRxBufferForSuback(subTopic1, strlen(subTopic1), QOS0, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, subTopic1, (uint16_t) strlen(subTopic1), QOS0, iot_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ResetTLSBuffer(); + //1. receive message + setTLSRxBufferWithMsgOnSubscribedTopic(subTopic1, strlen(subTopic1), QOS0, testPubMsgParams, + expectedCallbackString); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgStringclean); + + ResetTLSBuffer(); + rc = aws_iot_mqtt_disconnect(&iotClient); + + //2. connect cs false and + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + connectParams.isCleanSession = false; + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ResetTLSBuffer(); + //3. set msg to topic1 and should receive the topic1 message + snprintf(CallbackMsgStringclean, 100, NO_MSG_XXXX); + setTLSRxBufferWithMsgOnSubscribedTopic(subTopic1, strlen(subTopic1), QOS0, testPubMsgParams, + expectedCallbackString); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgStringclean); + + ResetTLSBuffer(); + //4. ,sub to topic2 + snprintf(CallbackMsgStringclean, 100, NO_MSG_XXXX); + setTLSRxBufferForSuback(subTopic1, strlen(subTopic1), QOS0, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, subTopic2, (uint16_t) strlen(subTopic2), QOS0, iot_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ResetTLSBuffer(); + //5. and check if topic 2 msg is received + setTLSRxBufferWithMsgOnSubscribedTopic(subTopic2, strlen(subTopic2), QOS0, testPubMsgParams, + expectedCallbackString); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgStringclean); + + rc = aws_iot_mqtt_disconnect(&iotClient); + + //6. connect cs false and + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + connectParams.isCleanSession = false; + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + //7. set msg to topic2 and + snprintf(CallbackMsgStringclean, 100, NO_MSG_XXXX); + setTLSRxBufferWithMsgOnSubscribedTopic(subTopic2, strlen(subTopic2), QOS0, testPubMsgParams, + expectedCallbackString); + //8. should be received + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgStringclean); + + IOT_DEBUG("-->Success - B:27 - Connect attempt, Clean session, Subscribe \n"); + +} + +/* B:28 - Connect attempt, power cycle with clean session false + * This test is to ensure we can initialize the subscribe table in mqtt even when connecting with CS = false + * currently the AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS is set to 5 + */ +TEST_C(ConnectTests, PowerCycleWithCleanSessionFalse) { + IoT_Error_t rc = SUCCESS; + int itr = 0; + char subTestTopic[12]; + uint16_t subTestTopicLen = 0; + + IOT_DEBUG("-->Running Connect Tests - B:28 - Connect attempt, power cycle with clean session false \n"); + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + ResetTLSBuffer(); + + //1. connect with clean session false and + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + connectParams.isCleanSession = true; + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + //2. subscribe to max number of topics + for(itr = 0; itr < AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; itr++) { + snprintf(subTestTopic, 12, "sdk/topic%d", itr + 1); + subTestTopicLen = (uint16_t) strlen(subTestTopic); + setTLSRxBufferForSuback(subTestTopic, subTestTopicLen, QOS0, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, subTestTopic, subTestTopicLen, QOS0, iot_subscribe_callback_handler, + NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + } + + //3. Subscribe to one more topic. Should return error + snprintf(subTestTopic, 12, "sdk/topic%d", itr + 1); + subTestTopicLen = (uint16_t) strlen(subTestTopic); + setTLSRxBufferForSuback(subTestTopic, subTestTopicLen, QOS0, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, subTestTopic, subTestTopicLen, QOS0, iot_subscribe_callback_handler, + NULL); + CHECK_EQUAL_C_INT(MQTT_MAX_SUBSCRIPTIONS_REACHED_ERROR, rc); + + IOT_DEBUG("-->Success - B:28 - Connect attempt, power cycle with clean session false \n"); +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_disconnect.cpp b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_disconnect.cpp new file mode 100644 index 00000000..09edca39 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_disconnect.cpp @@ -0,0 +1,42 @@ +/* +* Copyright 2015-2016 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_tests_unit_disconnect.cpp + * @brief IoT Client Unit Testing - Disconnect API Tests + */ + +#include +#include + +TEST_GROUP_C(DisconnectTests){ + TEST_GROUP_C_SETUP_WRAPPER(DisconnectTests) + TEST_GROUP_C_TEARDOWN_WRAPPER(DisconnectTests) +}; + +/* F:1 - Disconnect with Null/empty client instance */ +TEST_GROUP_C_WRAPPER(DisconnectTests, NullClientDisconnect) +/* F:2 - Set Disconnect Handler with Null/empty Client */ +TEST_GROUP_C_WRAPPER(DisconnectTests, NullClientSetDisconnectHandler) +/* F:3 - Call Set Disconnect handler with Null handler */ +TEST_GROUP_C_WRAPPER(DisconnectTests, SetDisconnectHandlerNullHandler) +/* F:4 - Disconnect attempt, not connected */ +TEST_GROUP_C_WRAPPER(DisconnectTests, disconnectNotConnected) +/* F:5 - Disconnect success */ +TEST_GROUP_C_WRAPPER(DisconnectTests, disconnectNoAckSuccess) +/* F:6 - Disconnect, Handler invoked on disconnect */ +TEST_GROUP_C_WRAPPER(DisconnectTests, HandlerInvokedOnDisconnect) +/* F:7 - Disconnect, with set handler and invoked on disconnect */ +TEST_GROUP_C_WRAPPER(DisconnectTests, SetHandlerAndInvokedOnDisconnect) diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_disconnect_helper.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_disconnect_helper.c new file mode 100644 index 00000000..161a1e47 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_disconnect_helper.c @@ -0,0 +1,244 @@ +/* +* Copyright 2015-2016 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_tests_unit_disconnect_helper.c + * @brief IoT Client Unit Testing - Disconnect Tests helper + */ + +#include +#include +#include + +#include "aws_iot_tests_unit_helper_functions.h" +#include "aws_iot_log.h" + +static IoT_Client_Init_Params initParams; +static IoT_Client_Connect_Params connectParams; +static AWS_IoT_Client iotClient; + +static bool handlerInvoked = false; + +void disconnectTestHandler(AWS_IoT_Client *pClient, void *disconHandlerParam) { + IOT_UNUSED(pClient); + IOT_UNUSED(disconHandlerParam); + + handlerInvoked = true; +} + +TEST_GROUP_C_SETUP(DisconnectTests) { + IoT_Error_t rc; + ResetTLSBuffer(); + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, true, disconnectTestHandler); + initParams.mqttCommandTimeout_ms = 2000; + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + connectParams.keepAliveIntervalInSec = 5; + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + IOT_DEBUG("MQTT Status State : %d, RC : %d\n\n", aws_iot_mqtt_get_client_state(&iotClient), rc); + + ResetTLSBuffer(); +} + +TEST_GROUP_C_TEARDOWN(DisconnectTests) { } + + +/* F:1 - Disconnect with Null/empty client instance */ +TEST_C(DisconnectTests, NullClientDisconnect) { + IoT_Error_t rc = aws_iot_mqtt_disconnect(NULL); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +/* F:2 - Set Disconnect Handler with Null/empty Client */ +TEST_C(DisconnectTests, NullClientSetDisconnectHandler) { + IoT_Error_t rc = aws_iot_mqtt_set_disconnect_handler(NULL, disconnectTestHandler, NULL); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +/* F:3 - Call Set Disconnect handler with Null handler */ +TEST_C(DisconnectTests, SetDisconnectHandlerNullHandler) { + IoT_Error_t rc = aws_iot_mqtt_set_disconnect_handler(&iotClient, NULL, NULL); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +/* F:4 - Disconnect attempt, not connected */ +TEST_C(DisconnectTests, disconnectNotConnected) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Disconnect Tests - F:4 - Disconnect attempt, not connected \n"); + + /* First make sure client is disconnected */ + rc = aws_iot_mqtt_disconnect(&iotClient); + + /* Check client is disconnected */ + CHECK_EQUAL_C_INT(false, aws_iot_mqtt_is_client_connected(&iotClient)); + + /* Now call disconnect again */ + rc = aws_iot_mqtt_disconnect(&iotClient); + CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc); + + IOT_DEBUG("-->Success - F:4 - Disconnect attempt, not connected \n"); +} + +/* F:5 - Disconnect success */ +TEST_C(DisconnectTests, disconnectNoAckSuccess) { + IoT_Error_t rc = SUCCESS; + rc = aws_iot_mqtt_disconnect(&iotClient); + CHECK_EQUAL_C_INT(SUCCESS, rc); +} + +/* F:6 - Disconnect, Handler invoked on disconnect */ +TEST_C(DisconnectTests, HandlerInvokedOnDisconnect) { + bool connected = false; + bool currentAutoReconnectStatus = false; + int i; + int j; + int attempt = 3; + uint32_t dcCount = 0; + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Disconnect Tests - F:6 - Disconnect, Handler invoked on disconnect \n"); + + handlerInvoked = false; + + IOT_DEBUG("Current Keep Alive Interval is set to %d sec.\n", connectParams.keepAliveIntervalInSec); + currentAutoReconnectStatus = aws_iot_is_autoreconnect_enabled(&iotClient); + + connected = aws_iot_mqtt_is_client_connected(&iotClient); + CHECK_EQUAL_C_INT(1, connected); + + aws_iot_mqtt_autoreconnect_set_status(&iotClient, false); + + // 3 cycles of half keep alive time expiring + // verify a ping request is sent and give a ping response + for(i = 0; i < attempt; i++) { + /* Set TLS buffer for ping response */ + ResetTLSBuffer(); + setTLSRxBufferForPingresp(); + for(j = 0; j <= connectParams.keepAliveIntervalInSec; j++) { + sleep(1); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(SUCCESS, rc); + } + CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePingreq()); + } + + // keepalive() waits for 1/2 of keepalive time after sending ping request + // to receive a pingresponse before determining the connection is not alive + // wait for keepalive time and then yield() + sleep(connectParams.keepAliveIntervalInSec); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc); + CHECK_EQUAL_C_INT(1, isLastTLSTxMessageDisconnect()); + + connected = aws_iot_mqtt_is_client_connected(&iotClient); + CHECK_EQUAL_C_INT(0, connected); + + CHECK_EQUAL_C_INT(true, handlerInvoked); + + dcCount = aws_iot_mqtt_get_network_disconnected_count(&iotClient); + CHECK_C(1 == dcCount); + + aws_iot_mqtt_reset_network_disconnected_count(&iotClient); + + dcCount = aws_iot_mqtt_get_network_disconnected_count(&iotClient); + CHECK_C(0 == dcCount); + + ResetTLSBuffer(); + aws_iot_mqtt_autoreconnect_set_status(&iotClient, currentAutoReconnectStatus); + + IOT_DEBUG("-->Success - F:6 - Disconnect, Handler invoked on disconnect \n"); +} + + +/* F:7 - Disconnect, with set handler and invoked on disconnect */ +TEST_C(DisconnectTests, SetHandlerAndInvokedOnDisconnect) { + bool connected = false; + bool currentAutoReconnectStatus = false; + int i; + int j; + int attempt = 3; + uint32_t dcCount = 0; + IoT_Error_t rc = SUCCESS; + IOT_DEBUG("-->Running Disconnect Tests - F:7 - Disconnect, with set handler and invoked on disconnect \n"); + + handlerInvoked = false; + InitMQTTParamsSetup(&initParams, "localhost", 8883, false, NULL); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + connectParams.keepAliveIntervalInSec = 5; + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + aws_iot_mqtt_set_disconnect_handler(&iotClient, disconnectTestHandler, NULL); + aws_iot_mqtt_autoreconnect_set_status(&iotClient, true); + + IOT_DEBUG("Current Keep Alive Interval is set to %d sec.\n", connectParams.keepAliveIntervalInSec); + currentAutoReconnectStatus = aws_iot_is_autoreconnect_enabled(&iotClient); + + connected = aws_iot_mqtt_is_client_connected(&iotClient); + CHECK_EQUAL_C_INT(1, connected); + + aws_iot_mqtt_autoreconnect_set_status(&iotClient, false); + + // 3 cycles of keep alive time expiring + // verify a ping request is sent and give a ping response + for(i = 0; i < attempt; i++) { + /* Set TLS buffer for ping response */ + ResetTLSBuffer(); + setTLSRxBufferForPingresp(); + for(j = 0; j <= connectParams.keepAliveIntervalInSec; j++) { + sleep(1); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(SUCCESS, rc); + } + CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePingreq()); + } + ResetTLSBuffer(); + + // keepalive() waits for 1/2 of keepalive time after sending ping request + // to receive a pingresponse before determining the connection is not alive + // wait for keepalive time and then yield() + sleep(connectParams.keepAliveIntervalInSec); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc); + CHECK_EQUAL_C_INT(1, isLastTLSTxMessageDisconnect()); + + connected = aws_iot_mqtt_is_client_connected(&iotClient); + CHECK_EQUAL_C_INT(0, connected); + + CHECK_EQUAL_C_INT(true, handlerInvoked); + + dcCount = aws_iot_mqtt_get_network_disconnected_count(&iotClient); + CHECK_C(1 == dcCount); + + aws_iot_mqtt_reset_network_disconnected_count(&iotClient); + + dcCount = aws_iot_mqtt_get_network_disconnected_count(&iotClient); + CHECK_C(0 == dcCount); + + ResetTLSBuffer(); + aws_iot_mqtt_autoreconnect_set_status(&iotClient, currentAutoReconnectStatus); + + IOT_DEBUG("-->Success - F:7 - Disconnect, with set handler and invoked on disconnect \n"); +} + diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_helper_functions.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_helper_functions.c new file mode 100644 index 00000000..afa676dc --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_helper_functions.c @@ -0,0 +1,538 @@ +/* +* Copyright 2015-2016 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_tests_unit_helper_functions.c + * @brief IoT Client Unit Testing - Helper Functions + */ + +#include +#include +#include "aws_iot_mqtt_client.h" +#include "aws_iot_tests_unit_mock_tls_params.h" +#include "aws_iot_tests_unit_helper_functions.h" +#include "aws_iot_version.h" + +#if !DISABLE_METRICS +#define SDK_METRICS_LEN 25 +#define SDK_METRICS_TEMPLATE "?SDK=C&Version=%d.%d.%d" +static char pUsernameTemp[SDK_METRICS_LEN] = {0}; +#endif + +#define CONNACK_SUBACK_PACKET_SIZE 9 +#define PUBACK_PACKET_SIZE 4 +#define SUBACK_PACKET_SIZE 5 +#define UNSUBACK_PACKET_SIZE 4 +#define PINGRESP_PACKET_SIZE 2 + +void ResetInvalidParameters(void) { + invalidEndpointFilter = NULL; + invalidRootCAPathFilter = NULL; + invalidCertPathFilter = NULL; + invalidPrivKeyPathFilter = NULL; + invalidPortFilter = 0; +} + +void InitMQTTParamsSetup(IoT_Client_Init_Params *params, char *pHost, uint16_t port, bool enableAutoReconnect, + iot_disconnect_handler disconnectHandler) { + params->pHostURL = pHost; + params->port = port; + params->mqttCommandTimeout_ms = 5000; + params->tlsHandshakeTimeout_ms = 5000; + params->enableAutoReconnect = enableAutoReconnect; + params->disconnectHandler = disconnectHandler; + params->disconnectHandlerData = NULL; + params->isSSLHostnameVerify = true; + params->pDeviceCertLocation = AWS_IOT_ROOT_CA_FILENAME; + params->pDevicePrivateKeyLocation = AWS_IOT_CERTIFICATE_FILENAME; + params->pRootCALocation = AWS_IOT_PRIVATE_KEY_FILENAME; +} + +void ConnectMQTTParamsSetup(IoT_Client_Connect_Params *params, char *pClientID, uint16_t clientIDLen) { + params->keepAliveIntervalInSec = 10; + params->isCleanSession = 1; + params->MQTTVersion = MQTT_3_1_1; + params->pClientID = pClientID; + params->clientIDLen = clientIDLen; + params->isWillMsgPresent = false; + params->pUsername = NULL; + params->usernameLen = 0; + params->pPassword = NULL; + params->passwordLen = 0; +} + +void ConnectMQTTParamsSetup_Detailed(IoT_Client_Connect_Params *params, char *pClientID, uint16_t clientIDLen, QoS qos, + bool isCleanSession, bool isWillMsgPresent, char *pWillTopicName, + uint16_t willTopicNameLen, char *pWillMessage, uint16_t willMsgLen, + char *pUsername, uint16_t userNameLen, char *pPassword, uint16_t passwordLen) { + params->keepAliveIntervalInSec = 10; + params->isCleanSession = isCleanSession; + params->MQTTVersion = MQTT_3_1_1; + params->pClientID = pClientID; + params->clientIDLen = clientIDLen; + params->pUsername = pUsername; + params->usernameLen = userNameLen; + params->pPassword = pPassword; + params->passwordLen = passwordLen; + params->isWillMsgPresent = isWillMsgPresent; + params->will.pMessage = pWillMessage; + params->will.msgLen = willMsgLen; + params->will.pTopicName = pWillTopicName; + params->will.topicNameLen = willTopicNameLen; + params->will.qos = qos; + params->will.isRetained = false; +} + +void printBuffer(unsigned char *buffer, size_t len) { + size_t i; + printf("\n--\n"); + for(i = 0; i < len; i++) { + printf("%d: %c, %d\n", (uint32_t)i, buffer[i], buffer[i]); + } + printf("\n--\n"); +} + +#define CONNACK_PACKET_SIZE 4 + +void setTLSRxBufferForConnack(IoT_Client_Connect_Params *params, unsigned char sessionPresent, + unsigned char connackResponseCode) { + RxBuffer.NoMsgFlag = false; + + if(params->isCleanSession) { + sessionPresent = 0; + } + + RxBuffer.pBuffer[0] = (unsigned char) (0x20); + RxBuffer.pBuffer[1] = (unsigned char) (0x02); + RxBuffer.pBuffer[2] = sessionPresent; + RxBuffer.pBuffer[3] = connackResponseCode; + + RxBuffer.len = CONNACK_PACKET_SIZE; + RxIndex = 0; +} + +void setTLSRxBufferForConnackAndSuback(IoT_Client_Connect_Params *conParams, unsigned char sessionPresent, + char *topicName, size_t topicNameLen, QoS qos) { + IOT_UNUSED(topicName); + IOT_UNUSED(topicNameLen); + + RxBuffer.NoMsgFlag = false; + + if(conParams->isCleanSession) { + sessionPresent = 0; + } + + RxBuffer.pBuffer[0] = (unsigned char) (0x20); + RxBuffer.pBuffer[1] = (unsigned char) (0x02); + RxBuffer.pBuffer[2] = sessionPresent; + RxBuffer.pBuffer[3] = (unsigned char) (0x0); + + RxBuffer.pBuffer[4] = (unsigned char) (0x90); + RxBuffer.pBuffer[5] = (unsigned char) (0x2 + 1); + // Variable header - packet identifier + RxBuffer.pBuffer[6] = (unsigned char) (2); + RxBuffer.pBuffer[7] = (unsigned char) (0); + // payload + RxBuffer.pBuffer[8] = (unsigned char) (qos); + + RxBuffer.len = CONNACK_SUBACK_PACKET_SIZE; + RxIndex = 0; +} + +void setTLSRxBufferForPuback(void) { + size_t i; + + RxBuffer.NoMsgFlag = true; + RxBuffer.len = PUBACK_PACKET_SIZE; + RxIndex = 0; + + for(i = 0; i < RxBuffer.BufMaxSize; i++) { + RxBuffer.pBuffer[i] = 0; + } + + RxBuffer.pBuffer[0] = (unsigned char) (0x40); + RxBuffer.pBuffer[1] = (unsigned char) (0x02); + RxBuffer.pBuffer[2] = (unsigned char) (0x02); + RxBuffer.pBuffer[3] = (unsigned char) (0x00); + RxBuffer.NoMsgFlag = false; +} + +void setTLSRxBufferForSubFail(void) { + RxBuffer.NoMsgFlag = false; + RxBuffer.pBuffer[0] = (unsigned char) (0x90); + RxBuffer.pBuffer[1] = (unsigned char) (0x2 + 1); + // Variable header - packet identifier + RxBuffer.pBuffer[2] = (unsigned char) (2); + RxBuffer.pBuffer[3] = (unsigned char) (0); + // payload + RxBuffer.pBuffer[4] = (unsigned char) (128); + + RxBuffer.len = SUBACK_PACKET_SIZE; + RxIndex = 0; +} + +void setTLSRxBufferForDoubleSuback(char *topicName, size_t topicNameLen, QoS qos, IoT_Publish_Message_Params params) { + IOT_UNUSED(topicName); + IOT_UNUSED(topicNameLen); + IOT_UNUSED(params); + + RxBuffer.NoMsgFlag = false; + RxBuffer.pBuffer[0] = (unsigned char) (0x90); + RxBuffer.pBuffer[1] = (unsigned char) (0x2 + 1); + // Variable header - packet identifier + RxBuffer.pBuffer[2] = (unsigned char) (2); + RxBuffer.pBuffer[3] = (unsigned char) (0); + // payload + RxBuffer.pBuffer[4] = (unsigned char) (qos); + + RxBuffer.pBuffer[5] = (unsigned char) (0x90); + RxBuffer.pBuffer[6] = (unsigned char) (0x2 + 1); + // Variable header - packet identifier + RxBuffer.pBuffer[7] = (unsigned char) (2); + RxBuffer.pBuffer[8] = (unsigned char) (0); + // payload + RxBuffer.pBuffer[9] = (unsigned char) (qos); + + RxBuffer.len = SUBACK_PACKET_SIZE * 2; + RxIndex = 0; +} + +void setTLSRxBufferForSuback(char *topicName, size_t topicNameLen, QoS qos, IoT_Publish_Message_Params params) { + IOT_UNUSED(topicName); + IOT_UNUSED(topicNameLen); + IOT_UNUSED(params); + + RxBuffer.NoMsgFlag = false; + RxBuffer.pBuffer[0] = (unsigned char) (0x90); + RxBuffer.pBuffer[1] = (unsigned char) (0x2 + 1); + // Variable header - packet identifier + RxBuffer.pBuffer[2] = (unsigned char) (2); + RxBuffer.pBuffer[3] = (unsigned char) (0); + // payload + RxBuffer.pBuffer[4] = (unsigned char) (qos); + + RxBuffer.len = SUBACK_PACKET_SIZE; + RxIndex = 0; +} + +void setTLSRxBufferForUnsuback(void) { + RxBuffer.NoMsgFlag = false; + RxBuffer.pBuffer[0] = (unsigned char) (0xB0); + RxBuffer.pBuffer[1] = (unsigned char) (0x02); + // Variable header - packet identifier + RxBuffer.pBuffer[2] = (unsigned char) (2); + RxBuffer.pBuffer[3] = (unsigned char) (0); + // No payload + RxBuffer.len = UNSUBACK_PACKET_SIZE; + RxIndex = 0; +} + +void setTLSRxBufferForPingresp(void) { + RxBuffer.NoMsgFlag = false; + RxBuffer.pBuffer[0] = (unsigned char) (0xD0); + RxBuffer.pBuffer[1] = (unsigned char) (0x00); + RxBuffer.len = PINGRESP_PACKET_SIZE; + RxIndex = 0; +} + +void ResetTLSBuffer(void) { + size_t i; + RxBuffer.len = 0; + RxBuffer.NoMsgFlag = true; + + for(i = 0; i < RxBuffer.BufMaxSize; i++) { + RxBuffer.pBuffer[i] = 0; + } + + RxIndex = 0; + RxBuffer.expiry_time.tv_sec = 0; + RxBuffer.expiry_time.tv_usec = 0; + TxBuffer.len = 0; + for(i = 0; i < TxBuffer.BufMaxSize; i++) { + TxBuffer.pBuffer[i] = 0; + } +} + +void setTLSRxBufferDelay(int seconds, int microseconds) { + struct timeval now, duration, result; + duration.tv_sec = seconds; + duration.tv_usec = microseconds; + + gettimeofday(&now, NULL); + timeradd(&now, &duration, &result); + RxBuffer.expiry_time.tv_sec = result.tv_sec; + RxBuffer.expiry_time.tv_usec = result.tv_usec; +} + +void setTLSRxBufferWithMsgOnSubscribedTopic(char *topicName, size_t topicNameLen, QoS qos, + IoT_Publish_Message_Params params, char *pMsg) { + size_t VariableLen = topicNameLen + 2 + 2; + size_t i = 0, cursor = 0, packetIdStartLoc = 0, payloadStartLoc = 0, VarHeaderStartLoc = 0; + size_t PayloadLen = strlen(pMsg) + 1; + + RxBuffer.NoMsgFlag = false; + RxBuffer.pBuffer[0] = (unsigned char) (0x30 | ((params.qos << 1) & 0xF));// QoS1 + cursor++; // Move the cursor + + // Remaining Length + // Translate the Remaining Length into packet bytes + encodeRemainingLength(RxBuffer.pBuffer, &cursor, VariableLen + PayloadLen); + + VarHeaderStartLoc = cursor - 1; + // Variable header + RxBuffer.pBuffer[VarHeaderStartLoc + 1] = (unsigned char) ((topicNameLen & 0xFF00) >> 8); + RxBuffer.pBuffer[VarHeaderStartLoc + 2] = (unsigned char) (topicNameLen & 0xFF); + for(i = 0; i < topicNameLen; i++) { + RxBuffer.pBuffer[VarHeaderStartLoc + 3 + i] = (unsigned char) topicName[i]; + } + + packetIdStartLoc = VarHeaderStartLoc + topicNameLen + 2; + payloadStartLoc = (packetIdStartLoc + 1); + + if(QOS0 != qos) { + // packet id only for QoS 1 or 2 + RxBuffer.pBuffer[packetIdStartLoc + 1] = 2; + RxBuffer.pBuffer[packetIdStartLoc + 2] = 3; + payloadStartLoc = packetIdStartLoc + 3; + } + + // payload + for(i = 0; i < PayloadLen; i++) { + RxBuffer.pBuffer[payloadStartLoc + i] = (unsigned char) pMsg[i]; + } + + RxBuffer.len = VariableLen + PayloadLen + 2; // 2 for fixed header + RxIndex = 0; + //printBuffer(RxBuffer.pBuffer, RxBuffer.len); +} + +unsigned char isLastTLSTxMessagePuback() { + return (unsigned char) (TxBuffer.pBuffer[0] == 0x40 ? 1 : 0); +} + +unsigned char isLastTLSTxMessagePingreq() { + return (unsigned char) (TxBuffer.pBuffer[0] == 0xC0 ? 1 : 0); +} + +unsigned char isLastTLSTxMessageDisconnect() { + return (unsigned char) (TxBuffer.pBuffer[0] == 0xE0 ? 1 : 0); +} + +unsigned char generateMultipleSubTopics(char *des, int boundary) { + int i; + int currLen = 0; + char *op1 = des; + unsigned char ret = (unsigned char) (des == NULL ? 0 : 1); + while(*op1 != '\0') { + currLen++; + op1++; + } + // Save 1 byte for terminator '\0' + for(i = 0; i < boundary - currLen - 1; i++) { + //printf("%d\n", i); + strcat(des, "a"); + } + return ret; +} + +void encodeRemainingLength(unsigned char *buf, size_t *st, size_t length) { + unsigned char c; + // watch out for the type of length, could be over flow. Limits = 256MB + // No boundary check for 256MB!! + do { + c = (unsigned char) (length % 128); + length /= 128; + if(length > 0) c |= (unsigned char) (0x80); // If there is still another byte following + buf[(*st)++] = c; + } while(length > 0); + // At this point, *st should be the next position for a new part of data in the packet +} + +unsigned char *connectTxBufferHeaderParser(ConnectBufferProofread *params, unsigned char *buf) { + unsigned char *op = buf; + // Get packet type + unsigned char *ele1 = op; + unsigned int multiplier = 1; + int cnt = 0; + unsigned char *ele2; + unsigned int x; + unsigned char *op2; + params->PacketType = *ele1; + op++; + // Get remaining length (length bytes more than 4 bytes are ignored) + params->RemainingLength = 0; + do { + ele2 = op; + params->RemainingLength += ((unsigned int) (*ele2 & (0x7F)) * multiplier); + multiplier *= 128; + cnt++; + op++; + } while((*ele2 & (0x80)) != 0 && cnt < 4); + // At this point, op should be updated to the start address of the next chunk of information + // Get protocol length + params->ProtocolLength = 0; + params->ProtocolLength += (256 * (unsigned int) (*op++)); + params->ProtocolLength += (unsigned int) (*op++); + // Get protocol name + for(x = 0; x < params->ProtocolLength; x++) { + params->ProtocolName[x] = *op; + op++; + } + // Get protocol level + params->ProtocolLevel = (unsigned int) (*op++); + // Get connect flags + params->ConnectFlag = (*op++); + // Get keepalive + op2 = op; + params->KeepAlive = 0; + params->KeepAlive += (256 * (unsigned int) (*op2++)); // get rid of the sign bit + op++; + params->KeepAlive += (unsigned int) (*op2++); + op++; + + return op; +} + +bool isConnectTxBufFlagCorrect(IoT_Client_Connect_Params *settings, ConnectBufferProofread *readRes) { + bool ret = true; + int i; + unsigned char myByte[8]; // Construct our own connect flag byte according to the settings +#if !DISABLE_METRICS + myByte[0] = (unsigned char) (1); // User Name Flag +#else + myByte[0] = (unsigned char) (settings->pUsername == NULL ? 0 : 1); // User Name Flag +#endif + myByte[1] = (unsigned char) (settings->pPassword == NULL ? 0 : 1); // Password Flag + myByte[2] = 0; // Will Retain + // QoS + if(QOS1 == settings->will.qos) { + myByte[3] = 0; + myByte[4] = 1; + } else { // default QoS is QOS0 + myByte[3] = 0; + myByte[4] = 0; + } + // + myByte[5] = (unsigned char) settings->isWillMsgPresent; // Will Flag + myByte[6] = (unsigned char) settings->isCleanSession; // Clean Session + myByte[7] = 0; // Retained + // + for(i = 0; i < 8; i++) { + if(myByte[i] != (unsigned char) (((readRes->ConnectFlag) >> (7 - i)) & 0x01)) { + printf("ex %x ac %x\n", (unsigned char) (((readRes->ConnectFlag) >> (7 - i)) & 0x01) + '0', myByte[i]); + ret = false; + break; + } + } + return ret; +} + +bool isConnectTxBufPayloadCorrect(IoT_Client_Connect_Params *settings, unsigned char *payloadBuf) { + // Construct our own payload according to the settings to see if the real one matches with it + unsigned int ClientIDLen = (unsigned int) strlen(settings->pClientID); + unsigned int WillTopicLen = (unsigned int) strlen(settings->will.pTopicName); + unsigned int WillMsgLen = (unsigned int) strlen(settings->will.pMessage); +#if !DISABLE_METRICS + if (0 == strlen(pUsernameTemp)) { + snprintf(pUsernameTemp, SDK_METRICS_LEN, SDK_METRICS_TEMPLATE, + VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH); + } + unsigned int UsernameLen = (unsigned int)strlen(pUsernameTemp); +#else + unsigned int UsernameLen = (unsigned int) settings->usernameLen; +#endif + unsigned int PasswordLen = (unsigned int) settings->passwordLen; + unsigned int myPayloadLen = ClientIDLen + 2 + WillTopicLen + 2 + WillMsgLen + UsernameLen + 2 + PasswordLen; + char *myPayload = (char *) malloc(sizeof(char) * (myPayloadLen + 1)); // reserve 1 byte for '\0' + // Construction starts... + unsigned int i; + bool ret = false; + char *op = myPayload; + *op = (char) (ClientIDLen & 0x0FF00); // MSB There is a writeInt inside paho... MQTTString.lenstring.len != 0 + op++; + *op = (char) (ClientIDLen & 0x00FF); // LSB + op++; + // ClientID + for(i = 0; i < ClientIDLen; i++) { + *op = settings->pClientID[i]; + op++; + } + if(true == settings->isWillMsgPresent) { + // WillTopic + for(i = 0; i < WillTopicLen; i++) { + *op = settings->will.pTopicName[i]; + op++; + } + // WillMsg Len + *op = (char) (WillMsgLen & 0x0FF00); // MSB + op++; + *op = (char) (WillMsgLen & 0x00FF); // LSB + op++; + // WillMsg + for(i = 0; i < WillMsgLen; i++) { + *op = settings->will.pMessage[i]; + op++; + } + } + // Username +#if !DISABLE_METRICS + for(i = 0; i < strlen(pUsernameTemp); i++) + { + *op = pUsernameTemp[i]; + op++; + } +#else + if(NULL != settings->pUsername) { + for(i = 0; i < UsernameLen; i++) { + *op = settings->pUsername[i]; + op++; + } + } +#endif + // PasswordLen + Password + if(NULL != settings->pPassword) { + *op = (char) (PasswordLen & 0x0FF00); // MSB + op++; + *op = (char) (PasswordLen & 0x00FF); // LSB + op++; + // + for(i = 0; i < PasswordLen; i++) { + *op = settings->pPassword[i]; + op++; + } + } + // + *op = '\0'; + ret = strcmp(myPayload, (const char *)payloadBuf) == 0 ? true : false; + free(myPayload); + return ret; +} + +void printPrfrdParams(ConnectBufferProofread *params) { + unsigned int i; + printf("\n----------------\n"); + printf("PacketType: %x\n", params->PacketType); + printf("RemainingLength: %u\n", params->RemainingLength); + printf("ProtocolLength: %u\n", params->ProtocolLength); + printf("ProtocolName: "); + for(i = 0; i < params->ProtocolLength; i++) { + printf("%c", params->ProtocolName[i]); + } + printf("\n"); + printf("ProtocolLevel: %u\n", params->ProtocolLevel); + printf("ConnectFlag: %x\n", params->ConnectFlag); + printf("KeepAliveInterval: %u\n", params->KeepAlive); + printf("----------------\n"); +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_json_utils.cpp b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_json_utils.cpp new file mode 100644 index 00000000..68c10921 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_json_utils.cpp @@ -0,0 +1,90 @@ +/* +* Copyright 2015-2016 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_tests_unit_json_utils.cpp + * @brief IoT Client Unit Testing - JSON Utility Tests + */ + +#include +#include + +TEST_GROUP_C(JsonUtils) { + TEST_GROUP_C_SETUP_WRAPPER(JsonUtils) + TEST_GROUP_C_TEARDOWN_WRAPPER(JsonUtils) +}; + +TEST_GROUP_C_WRAPPER(JsonUtils, ParseStringBasic) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseStringLongerStringIsValid) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseStringEmptyStringIsValid) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseStringErrorOnInteger) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseStringErrorOnBoolean) + +TEST_GROUP_C_WRAPPER(JsonUtils, ParseBooleanTrue) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseBooleanFalse) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseBooleanErrorOnString) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseBooleanErrorOnInvalidJson) + +TEST_GROUP_C_WRAPPER(JsonUtils, ParseDoubleBasic) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseDoubleNumberWithNoDecimal) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseDoubleSmallDouble) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseDoubleErrorOnString) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseDoubleErrorOnBoolean) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseDoubleErrorOnJsonObject) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseDoubleNegativeNumber) + +TEST_GROUP_C_WRAPPER(JsonUtils, ParseFloatBasic) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseFloatNumberWithNoDecimal) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseFloatSmallFloat) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseFloatErrorOnString) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseFloatErrorOnBoolean) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseFloatErrorOnJsonObject) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseFloatNegativeNumber) + +TEST_GROUP_C_WRAPPER(JsonUtils, ParseIntegerBasic) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseIntegerLargeInteger) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseIntegerNegativeInteger) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseIntegerErrorOnBoolean) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseIntegerErrorOnString) + +TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger16bitBasic) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger16bitLargeInteger) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger16bitNegativeInteger) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger16bitErrorOnBoolean) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger16bitErrorOnString) + +TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger8bitBasic) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger8bitLargeInteger) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger8bitNegativeInteger) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger8bitErrorOnBoolean) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger8bitErrorOnString) + +TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedIntegerBasic) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedIntegerLargeInteger) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedIntegerErrorOnNegativeInteger) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedIntegerErrorOnBoolean) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedIntegerErrorOnString) + +TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger16bitBasic) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger16bitLargeInteger) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger16bitErrorOnNegativeInteger) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger16bitErrorOnBoolean) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger16bitErrorOnString) + +TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger8bitBasic) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger8bitLargeInteger) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger8bitErrorOnNegativeInteger) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger8bitErrorOnBoolean) +TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger8bitErrorOnString) diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_json_utils_helper.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_json_utils_helper.c new file mode 100644 index 00000000..c32c9579 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_json_utils_helper.c @@ -0,0 +1,810 @@ +/* +* Copyright 2015-2016 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_tests_unit_json_utils_helper.c + * @brief IoT Client Unit Testing - JSON Utility Tests helper + */ + +#include +#include +#include +#include + +#include "aws_iot_json_utils.h" +#include "aws_iot_tests_unit_helper_functions.h" +#include "aws_iot_log.h" + +static IoT_Error_t rc = SUCCESS; + +static jsmn_parser test_parser; +static jsmntok_t t[128]; + +TEST_GROUP_C_SETUP(JsonUtils) { + jsmn_init(&test_parser); +} + +TEST_GROUP_C_TEARDOWN(JsonUtils) { + +} + +TEST_C(JsonUtils, ParseStringBasic) { + int r; + const char *json = "{\"x\":\"test1\"}"; + char parsedString[50]; + + IOT_DEBUG("\n-->Running Json Utils Tests - Basic String Parsing \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseStringValue(parsedString, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING("test1", parsedString); +} + +TEST_C(JsonUtils, ParseStringLongerStringIsValid) { + int r; + const char *json = "{\"x\":\"this is a longer string for test 2\"}"; + char parsedString[50]; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse long string \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseStringValue(parsedString, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING("this is a longer string for test 2", parsedString); +} + +TEST_C(JsonUtils, ParseStringEmptyStringIsValid) { int r; + const char *json = "{\"x\":\"\"}"; + char parsedString[50]; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse empty string \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseStringValue(parsedString, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING("", parsedString); +} + +TEST_C(JsonUtils, ParseStringErrorOnInteger) { + int r; + const char *json = "{\"x\":3}"; + char parsedString[50]; + + IOT_DEBUG("\n-->Running Json Utils Tests - parse integer as string returns error \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseStringValue(parsedString, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseStringErrorOnBoolean) { + int r; + const char *json = "{\"x\":true}"; + char parsedString[50]; + + IOT_DEBUG("\n-->Running Json Utils Tests - parse boolean as string returns error \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseStringValue(parsedString, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseBooleanTrue) { + int r; + const char *json = "{\"x\":true}"; + bool parsedBool; + + IOT_DEBUG("\n-->Running Json Utils Tests - parse boolean with true value \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseBooleanValue(&parsedBool, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(1, (int) parsedBool); +} + +TEST_C(JsonUtils, ParseBooleanFalse) { + int r; + const char *json = "{\"x\":false}"; + bool parsedBool; + + IOT_DEBUG("\n-->Running Json Utils Tests - parse boolean with false value \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseBooleanValue(&parsedBool, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(0, (int) parsedBool); +} + +TEST_C(JsonUtils, ParseBooleanErrorOnString) { + int r; + const char *json = "{\"x\":\"not a bool\"}"; + bool parsedBool; + + IOT_DEBUG("\n-->Running Json Utils Tests - parse string as boolean returns error \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseBooleanValue(&parsedBool, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseBooleanErrorOnInvalidJson) { + int r; + const char *json = "{\"x\":frue}"; // Invalid + bool parsedBool; + + IOT_DEBUG("\n-->Running Json Utils Tests - parse boolean returns error with invalid json \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseBooleanValue(&parsedBool, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseDoubleBasic) { + int r; + const char *json = "{\"x\":20.5}"; + double parsedDouble; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse double test \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseDoubleValue(&parsedDouble, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_REAL(20.5, parsedDouble, 0.0); +} + +TEST_C(JsonUtils, ParseDoubleNumberWithNoDecimal) { + int r; + const char *json = "{\"x\":100}"; + double parsedDouble; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse double number with no decimal \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseDoubleValue(&parsedDouble, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_REAL(100, parsedDouble, 0.0); +} + +TEST_C(JsonUtils, ParseDoubleSmallDouble) { + int r; + const char *json = "{\"x\":0.000004}"; + double parsedDouble; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse small double value \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseDoubleValue(&parsedDouble, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_REAL(0.000004, parsedDouble, 0.0); +} + +TEST_C(JsonUtils, ParseDoubleErrorOnString) { + int r; + const char *json = "{\"x\":\"20.5\"}"; + double parsedDouble; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse string as double returns error \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseDoubleValue(&parsedDouble, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseDoubleErrorOnBoolean) { + int r; + const char *json = "{\"x\":true}"; + double parsedDouble; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse boolean as double returns error \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseDoubleValue(&parsedDouble, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseDoubleErrorOnJsonObject) { + int r; + const char *json = "{\"x\":{}}"; + double parsedDouble; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse json object as double returns error \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseDoubleValue(&parsedDouble, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseDoubleNegativeNumber) { + int r; + const char *json = "{\"x\":-56.78}"; + double parsedDouble; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse negative double value \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseDoubleValue(&parsedDouble, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_REAL(-56.78, parsedDouble, 0.0); +} + +TEST_C(JsonUtils, ParseFloatBasic) { + int r; + const char *json = "{\"x\":20.5}"; + float parsedFloat; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse float test \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseFloatValue(&parsedFloat, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_REAL(20.5, parsedFloat, 0.0); +} + +TEST_C(JsonUtils, ParseFloatNumberWithNoDecimal) { + int r; + const char *json = "{\"x\":100}"; + float parsedFloat; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse float number with no decimal \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseFloatValue(&parsedFloat, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_REAL(100, parsedFloat, 0.0); +} + +TEST_C(JsonUtils, ParseFloatSmallFloat) { + int r; + const char *json = "{\"x\":0.0004}"; + float parsedFloat; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse small float value \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseFloatValue(&parsedFloat, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_C(0.0004f == parsedFloat); +} + +TEST_C(JsonUtils, ParseFloatErrorOnString) { + int r; + const char *json = "{\"x\":\"20.5\"}"; + float parsedFloat; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse string as float returns error \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseFloatValue(&parsedFloat, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseFloatErrorOnBoolean) { + int r; + const char *json = "{\"x\":true}"; + float parsedFloat; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse boolean as float returns error \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseFloatValue(&parsedFloat, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseFloatErrorOnJsonObject) { + int r; + const char *json = "{\"x\":{}}"; + float parsedDouble; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse json object as float returns error \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseFloatValue(&parsedDouble, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseFloatNegativeNumber) { + int r; + const char *json = "{\"x\":-56.78}"; + float parsedFloat; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse negative float value \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseFloatValue(&parsedFloat, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_C(-56.78f == parsedFloat); +} + +TEST_C(JsonUtils, ParseIntegerBasic) { + int r; + const char *json = "{\"x\":1}"; + int32_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse 32 bit integer \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseInteger32Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(1, parsedInteger); +} + +TEST_C(JsonUtils, ParseIntegerLargeInteger) { + int r; + const char *json = "{\"x\":2147483647}"; + int32_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse large 32 bit integer \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseInteger32Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(2147483647, parsedInteger); +} + +TEST_C(JsonUtils, ParseIntegerNegativeInteger) { + int r; + const char *json = "{\"x\":-308}"; + int32_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse negative 32 bit integer \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseInteger32Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(-308, parsedInteger); +} + +TEST_C(JsonUtils, ParseIntegerErrorOnBoolean) { + int r; + const char *json = "{\"x\":true}"; + int32_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse 32 bit integer returns error with boolean \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseInteger32Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseIntegerErrorOnString) { + int r; + const char *json = "{\"x\":\"45\"}"; + int32_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse 32 bit integer returns error on string \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseInteger32Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseInteger16bitBasic) { + int r; + const char *json = "{\"x\":1}"; + int16_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse 16 bit integer \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseInteger16Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(1, parsedInteger); +} + +TEST_C(JsonUtils, ParseInteger16bitLargeInteger) { + int r; + const char *json = "{\"x\":32767}"; + int16_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse large 16 bit integer \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseInteger16Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(32767, parsedInteger); +} + +TEST_C(JsonUtils, ParseInteger16bitNegativeInteger) { + int r; + const char *json = "{\"x\":-308}"; + int16_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse negative 16 bit integer \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseInteger16Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(-308, parsedInteger); +} + +TEST_C(JsonUtils, ParseInteger16bitErrorOnBoolean) { + int r; + const char *json = "{\"x\":true}"; + int16_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse 16 bit integer returns error with boolean \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseInteger16Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseInteger16bitErrorOnString) { + int r; + const char *json = "{\"x\":\"45\"}"; + int16_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse 16 bit integer returns error on string \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseInteger16Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseInteger8bitBasic) { + int r; + const char *json = "{\"x\":1}"; + int8_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse 8 bit integer \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseInteger8Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(1, parsedInteger); +} + +TEST_C(JsonUtils, ParseInteger8bitLargeInteger) { + int r; + const char *json = "{\"x\":127}"; + int8_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse large 8 bit integer \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseInteger8Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(127, parsedInteger); +} + +TEST_C(JsonUtils, ParseInteger8bitNegativeInteger) { + int r; + const char *json = "{\"x\":-30}"; + int8_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse negative 8 bit integer \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseInteger8Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(-30, parsedInteger); +} + +TEST_C(JsonUtils, ParseInteger8bitErrorOnBoolean) { + int r; + const char *json = "{\"x\":true}"; + int8_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse 8 bit integer returns error with boolean \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseInteger8Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseInteger8bitErrorOnString) { + int r; + const char *json = "{\"x\":\"45\"}"; + int8_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse 8 bit integer returns error on string \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseInteger8Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseUnsignedIntegerBasic) { + int r; + const char *json = "{\"x\":1}"; + uint32_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 32 bit integer \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseUnsignedInteger32Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_C(1 == parsedInteger); +} + +TEST_C(JsonUtils, ParseUnsignedIntegerLargeInteger) { + int r; + const char *json = "{\"x\":2147483647}"; + uint32_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse large unsigned 32 bit integer \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseUnsignedInteger32Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_C(2147483647 == parsedInteger); +} + +TEST_C(JsonUtils, ParseUnsignedIntegerErrorOnNegativeInteger) { + int r; + const char *json = "{\"x\":-308}"; + uint32_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 32 bit integer returns error with negative value \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseUnsignedInteger32Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseUnsignedIntegerErrorOnBoolean) { + int r; + const char *json = "{\"x\":true}"; + uint32_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 32 bit integer returns error with boolean \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseUnsignedInteger32Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseUnsignedIntegerErrorOnString) { + int r; + const char *json = "{\"x\":\"45\"}"; + uint32_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 32 bit integer returns error on string \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseUnsignedInteger32Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseUnsignedInteger16bitBasic) { + int r; + const char *json = "{\"x\":1}"; + uint16_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 16 bit integer \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseUnsignedInteger16Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(1, parsedInteger); +} + +TEST_C(JsonUtils, ParseUnsignedInteger16bitLargeInteger) { + int r; + const char *json = "{\"x\":65535}"; + uint16_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse large unsigned 16 bit integer \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseUnsignedInteger16Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(65535, parsedInteger); +} + +TEST_C(JsonUtils, ParseUnsignedInteger16bitErrorOnNegativeInteger) { + int r; + const char *json = "{\"x\":-308}"; + uint16_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 16 bit integer returns error on negative value \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseUnsignedInteger16Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseUnsignedInteger16bitErrorOnBoolean) { + int r; + const char *json = "{\"x\":true}"; + uint16_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 16 bit integer returns error with boolean \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseUnsignedInteger16Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseUnsignedInteger16bitErrorOnString) { + int r; + const char *json = "{\"x\":\"45\"}"; + uint16_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 16 bit integer returns error on string \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseUnsignedInteger16Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseUnsignedInteger8bitBasic) { + int r; + const char *json = "{\"x\":1}"; + uint8_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 8 bit integer \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseUnsignedInteger8Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(1, parsedInteger); +} + +TEST_C(JsonUtils, ParseUnsignedInteger8bitLargeInteger) { + int r; + const char *json = "{\"x\":255}"; + uint8_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse large unsigned 8 bit integer \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseUnsignedInteger8Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(255, parsedInteger); +} + +TEST_C(JsonUtils, ParseUnsignedInteger8bitErrorOnNegativeInteger) { + int r; + const char *json = "{\"x\":-30}"; + uint8_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 8 bit integer returns error on negative value \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseUnsignedInteger8Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseUnsignedInteger8bitErrorOnBoolean) { + int r; + const char *json = "{\"x\":true}"; + uint8_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 8 bit integer returns error with boolean \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseUnsignedInteger8Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} + +TEST_C(JsonUtils, ParseUnsignedInteger8bitErrorOnString) { + int r; + const char *json = "{\"x\":\"45\"}"; + uint8_t parsedInteger; + + IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 8 bit integer returns error on string \n"); + + r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); + rc = parseUnsignedInteger8Value(&parsedInteger, json, t + 2); + + CHECK_EQUAL_C_INT(3, r); + CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_publish.cpp b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_publish.cpp new file mode 100644 index 00000000..da188e0f --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_publish.cpp @@ -0,0 +1,48 @@ +/* +* Copyright 2015-2016 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_tests_unit_publish.cpp + * @brief IoT Client Unit Testing - Publish API Tests + */ + +#include +#include + +TEST_GROUP_C(PublishTests) { + TEST_GROUP_C_SETUP_WRAPPER(PublishTests) + TEST_GROUP_C_TEARDOWN_WRAPPER(PublishTests) +}; + +/* E:1 - Publish with Null/empty client instance */ +TEST_GROUP_C_WRAPPER(PublishTests, PublishNullClient) +/* E:2 - Publish with Null/empty Topic Name */ +TEST_GROUP_C_WRAPPER(PublishTests, PublishNullTopic) +/* E:3 - Publish with Null/empty payload */ +TEST_GROUP_C_WRAPPER(PublishTests, PublishNullParams) +/* E:4 - Publish with network disconnected */ +TEST_GROUP_C_WRAPPER(PublishTests, PublishNetworkDisconnected) +/* E:5 - Publish with QoS2 */ +/* Not required here, enum value doesn't exist for QoS2 */ +/* E:6 - Publish with QoS1 send success, Puback not received */ +TEST_GROUP_C_WRAPPER(PublishTests, publishQoS1FailureToReceivePuback) +/* E:7 - Publish with QoS1 send success, Delayed Puback received after command timeout */ +TEST_GROUP_C_WRAPPER(PublishTests, publishQoS1FailureDelayedPuback) +/* E:8 - Publish with send success, Delayed Puback received before command timeout */ +TEST_GROUP_C_WRAPPER(PublishTests, publishQoS1Success10msDelayedPuback) +/* E:9 - Publish QoS0 success */ +TEST_GROUP_C_WRAPPER(PublishTests, publishQoS0NoPubackSuccess) +/* E:10 - Publish with QoS1 send success, Puback received */ +TEST_GROUP_C_WRAPPER(PublishTests, publishQoS1Success) diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_publish_helper.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_publish_helper.c new file mode 100644 index 00000000..2f2c6406 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_publish_helper.c @@ -0,0 +1,205 @@ +/* +* Copyright 2015-2016 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_tests_unit_publish_helper.c + * @brief IoT Client Unit Testing - Publish API Tests Helper + */ + +#include +#include +#include + +#include "aws_iot_mqtt_client_interface.h" +#include "aws_iot_tests_unit_helper_functions.h" +#include "aws_iot_log.h" + +static IoT_Client_Init_Params initParams; +static IoT_Client_Connect_Params connectParams; +static IoT_Publish_Message_Params testPubMsgParams; +static char subTopic[10] = "sdk/Test"; +static uint16_t subTopicLen = 8; + +static AWS_IoT_Client iotClient; +char cPayload[100]; + +TEST_GROUP_C_SETUP(PublishTests) { + IoT_Error_t rc = SUCCESS; + ResetTLSBuffer(); + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + initParams.mqttCommandTimeout_ms = 2000; + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + IOT_DEBUG("MQTT Status State : %d, RC : %d\n\n", aws_iot_mqtt_get_client_state(&iotClient), rc); + + testPubMsgParams.qos = QOS1; + testPubMsgParams.isRetained = 0; + sprintf(cPayload, "%s : %d ", "hello from SDK", 0); + testPubMsgParams.payload = (void *) cPayload; + testPubMsgParams.payloadLen = strlen(cPayload); + + ResetTLSBuffer(); +} + +TEST_GROUP_C_TEARDOWN(PublishTests) { } + +/* E:1 - Publish with Null/empty client instance */ +TEST_C(PublishTests, PublishNullClient) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Publish Tests - E:1 - Publish with Null/empty client instance \n"); + + testPubMsgParams.qos = QOS1; + testPubMsgParams.isRetained = 0; + testPubMsgParams.payload = "Message"; + testPubMsgParams.payloadLen = 7; + + rc = aws_iot_mqtt_publish(NULL, "sdkTest/Sub", 11, &testPubMsgParams); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); + + IOT_DEBUG("-->Success - E:1 - Publish with Null/empty client instance \n"); +} + +/* E:2 - Publish with Null/empty Topic Name */ +TEST_C(PublishTests, PublishNullTopic) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Publish Tests - E:2 - Publish with Null/empty Topic Name \n"); + + testPubMsgParams.qos = QOS1; + testPubMsgParams.isRetained = 0; + testPubMsgParams.payload = "Message"; + testPubMsgParams.payloadLen = 7; + + rc = aws_iot_mqtt_publish(&iotClient, NULL, 11, &testPubMsgParams); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); + + rc = aws_iot_mqtt_publish(&iotClient, "sdkTest/Sub", 0, &testPubMsgParams); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); + + IOT_DEBUG("-->Success - E:2 - Publish with Null/empty Topic Name \n"); +} + +/* E:3 - Publish with Null/empty payload */ +TEST_C(PublishTests, PublishNullParams) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Publish Tests - E:3 - Publish with Null/empty payload \n"); + + rc = aws_iot_mqtt_publish(&iotClient, "sdkTest/Sub", 11, NULL); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); + + testPubMsgParams.qos = QOS1; + testPubMsgParams.isRetained = 0; + testPubMsgParams.payload = NULL; + testPubMsgParams.payloadLen = 0; + + rc = aws_iot_mqtt_publish(&iotClient, "sdkTest/Sub", 11, &testPubMsgParams); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); + + IOT_DEBUG("-->Success - E:3 - Publish with Null/empty payload \n"); +} + +/* E:4 - Publish with network disconnected */ +TEST_C(PublishTests, PublishNetworkDisconnected) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Publish Tests - E:4 - Publish with network disconnected \n"); + + /* Ensure network is disconnected */ + rc = aws_iot_mqtt_disconnect(&iotClient); + + testPubMsgParams.qos = QOS1; + testPubMsgParams.isRetained = 0; + testPubMsgParams.payload = NULL; + testPubMsgParams.payloadLen = 0; + + rc = aws_iot_mqtt_publish(&iotClient, "sdkTest/Sub", 11, &testPubMsgParams); + CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc); + + IOT_DEBUG("-->Success - E:4 - Publish with network disconnected \n"); +} + +/* E:6 - Publish with QoS1 send success, Puback not received */ +TEST_C(PublishTests, publishQoS1FailureToReceivePuback) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Publish Tests - E:6 - Publish with QoS1 send success, Puback not received \n"); + + rc = aws_iot_mqtt_publish(&iotClient, subTopic, subTopicLen, &testPubMsgParams); + CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, rc); + + IOT_DEBUG("-->Success - E:6 - Publish with QoS1 send success, Puback not received \n"); +} + +/* E:7 - Publish with QoS1 send success, Delayed Puback received after command timeout */ +TEST_C(PublishTests, publishQoS1FailureDelayedPuback) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Publish Tests - E:7 - Publish with QoS1 send success, Delayed Puback received after command timeout \n"); + + setTLSRxBufferDelay(10, 0); + setTLSRxBufferForPuback(); + rc = aws_iot_mqtt_publish(&iotClient, subTopic, subTopicLen, &testPubMsgParams); + CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, rc); + + IOT_DEBUG("-->Success - E:7 - Publish with QoS1 send success, Delayed Puback received after command timeout \n"); +} + +/* E:8 - Publish with send success, Delayed Puback received before command timeout */ +TEST_C(PublishTests, publishQoS1Success10msDelayedPuback) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Publish Tests - E:8 - Publish with send success, Delayed Puback received before command timeout \n"); + + ResetTLSBuffer(); + setTLSRxBufferDelay(0, (int) iotClient.clientData.commandTimeoutMs/2); + setTLSRxBufferForPuback(); + rc = aws_iot_mqtt_publish(&iotClient, subTopic, subTopicLen, &testPubMsgParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + IOT_DEBUG("-->Success - E:8 - Publish with send success, Delayed Puback received before command timeout \n"); +} + +/* E:9 - Publish QoS0 success */ +TEST_C(PublishTests, publishQoS0NoPubackSuccess) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Publish Tests - E:9 - Publish QoS0 success \n"); + + testPubMsgParams.qos = QOS0; // switch to a Qos0 PUB + rc = aws_iot_mqtt_publish(&iotClient, subTopic, subTopicLen, &testPubMsgParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + IOT_DEBUG("-->Success - E:9 - Publish QoS0 success \n"); +} + +/* E:10 - Publish with QoS1 send success, Puback received */ +TEST_C(PublishTests, publishQoS1Success) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Publish Tests - E:10 - Publish with QoS1 send success, Puback received \n"); + + setTLSRxBufferForPuback(); + rc = aws_iot_mqtt_publish(&iotClient, subTopic, subTopicLen, &testPubMsgParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + IOT_DEBUG("-->Success - E:10 - Publish with QoS1 send success, Puback received \n"); +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_runner.cpp b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_runner.cpp new file mode 100644 index 00000000..ba1f5cb4 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_runner.cpp @@ -0,0 +1,25 @@ +/* +* Copyright 2015-2016 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_tests_unit_runner.cpp + * @brief IoT Client Unit Testing - Runner + */ + +#include + +int main(int ac, char **argv) { + return CommandLineTestRunner::RunAllTests(ac, argv); +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_action.cpp b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_action.cpp new file mode 100644 index 00000000..991e2a6a --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_action.cpp @@ -0,0 +1,48 @@ +/* +* Copyright 2015-2016 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_tests_unit_shadow_action.cpp + * @brief IoT Client Unit Testing - Shadow Action Tests + */ + +#include +#include + +TEST_GROUP_C(ShadowActionTests) { + TEST_GROUP_C_SETUP_WRAPPER(ShadowActionTests) + TEST_GROUP_C_TEARDOWN_WRAPPER(ShadowActionTests) +}; + +TEST_GROUP_C_WRAPPER(ShadowActionTests, GetTheFullJSONDocument) +TEST_GROUP_C_WRAPPER(ShadowActionTests, DeleteTheJSONDocument) +TEST_GROUP_C_WRAPPER(ShadowActionTests, UpdateTheJSONDocument) +TEST_GROUP_C_WRAPPER(ShadowActionTests, GetTheFullJSONDocumentTimeout) +TEST_GROUP_C_WRAPPER(ShadowActionTests, SubscribeToAcceptedRejectedOnGet) +TEST_GROUP_C_WRAPPER(ShadowActionTests, UnSubscribeToAcceptedRejectedOnGetResponse) +TEST_GROUP_C_WRAPPER(ShadowActionTests, UnSubscribeToAcceptedRejectedOnGetTimeout) +TEST_GROUP_C_WRAPPER(ShadowActionTests, UnSubscribeToAcceptedRejectedOnGetTimeoutWithSticky) +TEST_GROUP_C_WRAPPER(ShadowActionTests, WrongTokenInGetResponse) +TEST_GROUP_C_WRAPPER(ShadowActionTests, NoTokenInGetResponse) +TEST_GROUP_C_WRAPPER(ShadowActionTests, InvalidInboundJSONInGetResponse) +TEST_GROUP_C_WRAPPER(ShadowActionTests, AcceptedSubFailsGetRequest) +TEST_GROUP_C_WRAPPER(ShadowActionTests, RejectedSubFailsGetRequest) +TEST_GROUP_C_WRAPPER(ShadowActionTests, PublishFailsGetRequest) +TEST_GROUP_C_WRAPPER(ShadowActionTests, GetVersionFromAckStatus) +TEST_GROUP_C_WRAPPER(ShadowActionTests, StickyNonStickyNeverConflict) +TEST_GROUP_C_WRAPPER(ShadowActionTests, ACKWaitingMoreThanAllowed) +TEST_GROUP_C_WRAPPER(ShadowActionTests, InboundDataTooBigForBuffer) +TEST_GROUP_C_WRAPPER(ShadowActionTests, NoClientTokenForShadowAction) +TEST_GROUP_C_WRAPPER(ShadowActionTests, NoCallbackForShadowAction) diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_action_helper.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_action_helper.c new file mode 100644 index 00000000..59bb3c84 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_action_helper.c @@ -0,0 +1,870 @@ +/* +* Copyright 2015-2016 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_tests_unit_shadow_action_helper.c + * @brief IoT Client Unit Testing - Shadow Action API Tests Helper + */ + +#include +#include +#include +#include +#include + +#include "aws_iot_tests_unit_mock_tls_params.h" +#include "aws_iot_tests_unit_helper_functions.h" +#include "aws_iot_tests_unit_shadow_helper.h" + +#include "aws_iot_shadow_interface.h" +#include "aws_iot_shadow_actions.h" +#include "aws_iot_shadow_json.h" +#include "aws_iot_log.h" + +#define SIZE_OF_UPDATE_DOCUMENT 200 +#define TEST_JSON_RESPONSE_FULL_DOCUMENT "{\"state\":{\"reported\":{\"sensor1\":98}}, \"clientToken\":\"" AWS_IOT_MQTT_CLIENT_ID "-0\"}" +#define TEST_JSON_RESPONSE_DELETE_DOCUMENT "{\"version\":2,\"timestamp\":1443473857,\"clientToken\":\"" AWS_IOT_MQTT_CLIENT_ID "-0\"}" +#define TEST_JSON_RESPONSE_UPDATE_DOCUMENT "{\"state\":{\"reported\":{\"doubleData\":4.090800,\"floatData\":3.445000}}, \"clientToken\":\"" AWS_IOT_MQTT_CLIENT_ID "-0\"}" + +static AWS_IoT_Client client; +static IoT_Client_Connect_Params connectParams; +static IoT_Publish_Message_Params testPubMsgParams; +static ShadowInitParameters_t shadowInitParams; +static ShadowConnectParameters_t shadowConnectParams; + +static Shadow_Ack_Status_t ackStatusRx; +static char jsonFullDocument[200]; +static ShadowActions_t actionRx; + +static void topicNameFromThingAndAction(char *pTopic, const char *pThingName, ShadowActions_t action) { + char actionBuf[10]; + + if(SHADOW_GET == action) { + strcpy(actionBuf, "get"); + } else if(SHADOW_UPDATE == action) { + strcpy(actionBuf, "update"); + } else if(SHADOW_DELETE == action) { + strcpy(actionBuf, "delete"); + } + + snprintf(pTopic, 100, "$aws/things/%s/shadow/%s", pThingName, actionBuf); +} + +TEST_GROUP_C_SETUP(ShadowActionTests) { + IoT_Error_t ret_val = SUCCESS; + char cPayload[100]; + char topic[120]; + + shadowInitParams.pHost = AWS_IOT_MQTT_HOST; + shadowInitParams.port = AWS_IOT_MQTT_PORT; + shadowInitParams.pClientCRT = AWS_IOT_CERTIFICATE_FILENAME; + shadowInitParams.pRootCA = AWS_IOT_ROOT_CA_FILENAME; + shadowInitParams.pClientKey = AWS_IOT_PRIVATE_KEY_FILENAME; + shadowInitParams.disconnectHandler = NULL; + shadowInitParams.enableAutoReconnect = false; + ret_val = aws_iot_shadow_init(&client, &shadowInitParams); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + shadowConnectParams.pMyThingName = AWS_IOT_MY_THING_NAME; + shadowConnectParams.pMqttClientId = AWS_IOT_MQTT_CLIENT_ID; + shadowConnectParams.mqttClientIdLen = (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID); + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + ret_val = aws_iot_shadow_connect(&client, &shadowConnectParams); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + setTLSRxBufferForPuback(); + testPubMsgParams.qos = QOS1; + testPubMsgParams.isRetained = 0; + snprintf(cPayload, 100, "%s : %d ", "hello from SDK", 0); + testPubMsgParams.payload = (void *) cPayload; + testPubMsgParams.payloadLen = strlen(cPayload) + 1; + topicNameFromThingAndAction(topic, AWS_IOT_MY_THING_NAME, SHADOW_GET); + setTLSRxBufferForDoubleSuback(topic, strlen(topic), QOS1, testPubMsgParams); +} + +TEST_GROUP_C_TEARDOWN(ShadowActionTests) { + /* Clean up. Not checking return code here because this is common to all tests. + * A test might have already caused a disconnect by this point. + */ + IoT_Error_t rc = aws_iot_shadow_disconnect(&client); + IOT_UNUSED(rc); +} + +static void actionCallback(const char *pThingName, ShadowActions_t action, Shadow_Ack_Status_t status, + const char *pReceivedJsonDocument, void *pContextData) { + IOT_UNUSED(pThingName); + IOT_UNUSED(pContextData); + IOT_DEBUG("%s", pReceivedJsonDocument); + actionRx = action; + ackStatusRx = status; + if(SHADOW_ACK_TIMEOUT != status) { + strcpy(jsonFullDocument, pReceivedJsonDocument); + } +} + +// Happy path for Get, Update, Delete +TEST_C(ShadowActionTests, GetTheFullJSONDocument) { + IoT_Error_t ret_val = SUCCESS; + char getRequestJson[120]; + IoT_Publish_Message_Params params; + + IOT_DEBUG("-->Running Shadow Action Tests - Get full json document \n"); + + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, 4, + false); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + ResetTLSBuffer(); + params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); + params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; + params.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + CHECK_EQUAL_C_STRING(TEST_JSON_RESPONSE_FULL_DOCUMENT, jsonFullDocument); + CHECK_EQUAL_C_INT(SHADOW_GET, actionRx); + CHECK_EQUAL_C_INT(SHADOW_ACK_ACCEPTED, ackStatusRx); + + IOT_DEBUG("-->Success - Get full json document \n"); +} + +TEST_C(ShadowActionTests, DeleteTheJSONDocument) { + IoT_Error_t ret_val = SUCCESS; + IoT_Publish_Message_Params params; + char deleteRequestJson[120]; + + IOT_DEBUG("-->Running Shadow Action Tests - Delete json document \n"); + + aws_iot_shadow_internal_delete_request_json(deleteRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_DELETE, deleteRequestJson, actionCallback, + NULL, 4, false); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + params.payloadLen = strlen(TEST_JSON_RESPONSE_DELETE_DOCUMENT); + params.payload = TEST_JSON_RESPONSE_DELETE_DOCUMENT; + params.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(DELETE_ACCEPTED_TOPIC, strlen(DELETE_ACCEPTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + CHECK_EQUAL_C_STRING(TEST_JSON_RESPONSE_DELETE_DOCUMENT, jsonFullDocument); + CHECK_EQUAL_C_INT(SHADOW_DELETE, actionRx); + CHECK_EQUAL_C_INT(SHADOW_ACK_ACCEPTED, ackStatusRx); + + IOT_DEBUG("-->Success - Delete json document \n"); +} + +TEST_C(ShadowActionTests, UpdateTheJSONDocument) { + IoT_Error_t ret_val = SUCCESS; + char updateRequestJson[SIZE_OF_UPDATE_DOCUMENT]; + char expectedUpdateRequestJson[SIZE_OF_UPDATE_DOCUMENT]; + double doubleData = 4.0908f; + float floatData = 3.445f; + bool boolData = true; + jsonStruct_t dataFloatHandler; + jsonStruct_t dataDoubleHandler; + jsonStruct_t dataBoolHandler; + IoT_Publish_Message_Params params; + + IOT_DEBUG("-->Running Shadow Action Tests - Update json document \n"); + + dataFloatHandler.cb = NULL; + dataFloatHandler.pData = &floatData; + dataFloatHandler.pKey = "floatData"; + dataFloatHandler.type = SHADOW_JSON_FLOAT; + + dataDoubleHandler.cb = NULL; + dataDoubleHandler.pData = &doubleData; + dataDoubleHandler.pKey = "doubleData"; + dataDoubleHandler.type = SHADOW_JSON_DOUBLE; + + dataBoolHandler.cb = NULL; + dataBoolHandler.pData = &boolData; + dataBoolHandler.pKey = "boolData"; + dataBoolHandler.type = SHADOW_JSON_BOOL; + + ret_val = aws_iot_shadow_init_json_document(updateRequestJson, SIZE_OF_UPDATE_DOCUMENT); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + ret_val = aws_iot_shadow_add_reported(updateRequestJson, SIZE_OF_UPDATE_DOCUMENT, 2, &dataDoubleHandler, + &dataFloatHandler); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + ret_val = aws_iot_shadow_add_desired(updateRequestJson, SIZE_OF_UPDATE_DOCUMENT, 1, &dataBoolHandler); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + ret_val = aws_iot_finalize_json_document(updateRequestJson, SIZE_OF_UPDATE_DOCUMENT); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + snprintf(expectedUpdateRequestJson, SIZE_OF_UPDATE_DOCUMENT, + "{\"state\":{\"reported\":{\"doubleData\":4.090800,\"floatData\":3.445000},\"desired\":{\"boolData\":true}}, \"clientToken\":\"%s-0\"}", + AWS_IOT_MQTT_CLIENT_ID); + CHECK_EQUAL_C_STRING(expectedUpdateRequestJson, updateRequestJson); + + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_UPDATE, updateRequestJson, actionCallback, + NULL, 4, false); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + ResetTLSBuffer(); + snprintf(jsonFullDocument, 200, "%s", ""); + params.payloadLen = strlen(TEST_JSON_RESPONSE_UPDATE_DOCUMENT); + params.payload = TEST_JSON_RESPONSE_UPDATE_DOCUMENT; + params.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(UPDATE_ACCEPTED_TOPIC, strlen(UPDATE_ACCEPTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + CHECK_EQUAL_C_STRING(TEST_JSON_RESPONSE_UPDATE_DOCUMENT, jsonFullDocument); + CHECK_EQUAL_C_INT(SHADOW_UPDATE, actionRx); + CHECK_EQUAL_C_INT(SHADOW_ACK_ACCEPTED, ackStatusRx); + + IOT_DEBUG("-->Success - Update json document \n"); +} + +TEST_C(ShadowActionTests, GetTheFullJSONDocumentTimeout) { + IoT_Error_t ret_val = SUCCESS; + char getRequestJson[120]; + IoT_Publish_Message_Params params; + + IOT_DEBUG("-->Running Shadow Action Tests - Get full json document timeout \n"); + + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, 4, + false); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + sleep(4 + 1); + + params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); + params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; + params.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + CHECK_EQUAL_C_STRING(TEST_JSON_RESPONSE_FULL_DOCUMENT, jsonFullDocument); + CHECK_EQUAL_C_INT(SHADOW_GET, actionRx); + CHECK_EQUAL_C_INT(SHADOW_ACK_TIMEOUT, ackStatusRx); + + IOT_DEBUG("-->Success - Get full json document timeout \n"); +} + +// Subscribe and UnSubscribe on reception of thing names. Will perform the test with Get operation +TEST_C(ShadowActionTests, SubscribeToAcceptedRejectedOnGet) { + IoT_Error_t ret_val = SUCCESS; + char getRequestJson[120]; + + uint8_t firstByte, secondByte; + uint16_t topicNameLen; + char topicName[128] = "test"; + + IOT_DEBUG("-->Running Shadow Action Tests - Subscribe to get/accepted and get/rejected \n"); + + lastSubscribeMsgLen = 11; + snprintf(LastSubscribeMessage, lastSubscribeMsgLen, "No Message"); + secondLastSubscribeMsgLen = 11; + snprintf(SecondLastSubscribeMessage, secondLastSubscribeMsgLen, "No Message"); + + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, 4, + false); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + CHECK_EQUAL_C_STRING(GET_REJECTED_TOPIC, LastSubscribeMessage); + CHECK_EQUAL_C_STRING(GET_ACCEPTED_TOPIC, SecondLastSubscribeMessage); + + firstByte = (uint8_t)(TxBuffer.pBuffer[2]); + secondByte = (uint8_t)(TxBuffer.pBuffer[3]); + topicNameLen = (uint16_t) (secondByte + (256 * firstByte)); + + snprintf(topicName, topicNameLen + 1u, "%s", &(TxBuffer.pBuffer[4])); // Added one for null character + + // Verify publish happens + CHECK_EQUAL_C_STRING(GET_PUB_TOPIC, topicName); + + IOT_DEBUG("-->Success - Subscribe to get/accepted and get/rejected \n"); +} + +TEST_C(ShadowActionTests, UnSubscribeToAcceptedRejectedOnGetResponse) { + IoT_Error_t ret_val = SUCCESS; + char getRequestJson[120]; + IoT_Publish_Message_Params params; + + IOT_DEBUG("-->Running Shadow Action Tests - unsubscribe to get/accepted and get/rejected on response \n"); + + lastSubscribeMsgLen = 11; + snprintf(LastSubscribeMessage, lastSubscribeMsgLen, "No Message"); + secondLastSubscribeMsgLen = 11; + snprintf(SecondLastSubscribeMessage, secondLastSubscribeMsgLen, "No Message"); + + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, 4, + false); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); + params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; + params.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + CHECK_EQUAL_C_STRING(GET_REJECTED_TOPIC, LastSubscribeMessage); + CHECK_EQUAL_C_STRING(GET_ACCEPTED_TOPIC, SecondLastSubscribeMessage); + + IOT_DEBUG("-->Success - unsubscribe to get/accepted and get/rejected on response \n"); +} + +TEST_C(ShadowActionTests, UnSubscribeToAcceptedRejectedOnGetTimeout) { + IoT_Error_t ret_val = SUCCESS; + char getRequestJson[120]; + IoT_Publish_Message_Params params; + + IOT_DEBUG("-->Running Shadow Action Tests - Unsubscribe to get/accepted and get/rejected on get timeout \n"); + + snprintf(jsonFullDocument, 200, "aa"); + lastSubscribeMsgLen = 11; + snprintf(LastSubscribeMessage, lastSubscribeMsgLen, "No Message"); + secondLastSubscribeMsgLen = 11; + snprintf(SecondLastSubscribeMessage, secondLastSubscribeMsgLen, "No Message"); + + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, 4, + false); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + sleep(4 + 1); + + params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); + params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; + params.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + CHECK_EQUAL_C_STRING("aa", jsonFullDocument); + + CHECK_EQUAL_C_STRING(GET_REJECTED_TOPIC, LastSubscribeMessage); + CHECK_EQUAL_C_STRING(GET_ACCEPTED_TOPIC, SecondLastSubscribeMessage); + + IOT_DEBUG("-->Success - Unsubscribe to get/accepted and get/rejected on get timeout \n"); +} + + +TEST_C(ShadowActionTests, UnSubscribeToAcceptedRejectedOnGetTimeoutWithSticky) { + IoT_Error_t ret_val = SUCCESS; + char getRequestJson[120]; + IoT_Publish_Message_Params params; + + IOT_DEBUG("-->Running Shadow Action Tests - No unsubscribe to get/accepted and get/rejected on get timeout with a sticky subscription \n"); + + snprintf(jsonFullDocument, 200, "timeout"); + lastSubscribeMsgLen = 11; + snprintf(LastSubscribeMessage, lastSubscribeMsgLen, "No Message"); + secondLastSubscribeMsgLen = 11; + snprintf(SecondLastSubscribeMessage, secondLastSubscribeMsgLen, "No Message"); + + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, 4, + true); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + sleep(4 + 1); + + ResetTLSBuffer(); + params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); + params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; + params.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + CHECK_EQUAL_C_STRING("timeout", jsonFullDocument); + + CHECK_EQUAL_C_STRING(GET_REJECTED_TOPIC, LastSubscribeMessage); + CHECK_EQUAL_C_STRING(GET_ACCEPTED_TOPIC, SecondLastSubscribeMessage); + + IOT_DEBUG("-->Success - No unsubscribe to get/accepted and get/rejected on get timeout with a sticky subscription \n"); +} + +#define TEST_JSON_RESPONSE_FULL_DOCUMENT_WITH_VERSION(num) "{\"state\":{\"reported\":{\"sensor1\":98}}, \"clientToken\":\"" AWS_IOT_MQTT_CLIENT_ID "-0\",\"version\":" #num "}" + +TEST_C(ShadowActionTests, GetVersionFromAckStatus) { + IoT_Error_t ret_val = SUCCESS; + char getRequestJson[120]; + IoT_Publish_Message_Params params; + IoT_Publish_Message_Params params2; + + IOT_DEBUG("-->Running Shadow Action Tests - Get version from Ack status \n"); + + snprintf(jsonFullDocument, 200, "timeout"); + + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, 4, + true); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + ResetTLSBuffer(); + params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT_WITH_VERSION(1); + params.payloadLen = strlen(params.payload); + params.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + CHECK_C(1u == aws_iot_shadow_get_last_received_version()); + + ResetTLSBuffer(); + params2.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT_WITH_VERSION(132387); + params2.payloadLen = strlen(params2.payload); + params2.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params2, + params2.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + CHECK_C(132387u == aws_iot_shadow_get_last_received_version()); + + IOT_DEBUG("-->Success - Get version from Ack status \n"); +} + +#define TEST_JSON_RESPONSE_FULL_DOCUMENT_ALWAYS_WRONG_TOKEN "{\"state\":{\"reported\":{\"sensor1\":98}}, \"clientToken\":\"TroubleToken1234\"}" + +TEST_C(ShadowActionTests, WrongTokenInGetResponse) { + IoT_Error_t ret_val = SUCCESS; + char getRequestJson[120]; + IoT_Publish_Message_Params params; + + IOT_DEBUG("-->Running Shadow Action Tests - Wrong token in get response \n"); + + snprintf(jsonFullDocument, 200, "timeout"); + + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, 4, + false); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + sleep(4 + 1); + + params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT_ALWAYS_WRONG_TOKEN); + params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT_ALWAYS_WRONG_TOKEN; + params.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + CHECK_EQUAL_C_STRING("timeout", jsonFullDocument); + CHECK_EQUAL_C_INT(SHADOW_GET, actionRx); + CHECK_EQUAL_C_INT(SHADOW_ACK_TIMEOUT, ackStatusRx); + + IOT_DEBUG("-->Success - Wrong token in get response \n"); +} + +#define TEST_JSON_RESPONSE_FULL_DOCUMENT_NO_TOKEN "{\"state\":{\"reported\":{\"sensor1\":98}}}" + +TEST_C(ShadowActionTests, NoTokenInGetResponse) { + IoT_Error_t ret_val = SUCCESS; + char getRequestJson[120]; + IoT_Publish_Message_Params params; + + IOT_DEBUG("-->Running Shadow Action Tests - No token in get response \n"); + + snprintf(jsonFullDocument, 200, "timeout"); + + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, 4, + false); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + sleep(4 + 1); + + params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT_NO_TOKEN); + params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT_NO_TOKEN; + params.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + CHECK_EQUAL_C_STRING("timeout", jsonFullDocument); + CHECK_EQUAL_C_INT(SHADOW_GET, actionRx); + CHECK_EQUAL_C_INT(SHADOW_ACK_TIMEOUT, ackStatusRx); + + IOT_DEBUG("-->Success - No token in get response \n"); +} + +TEST_C(ShadowActionTests, InvalidInboundJSONInGetResponse) { + IoT_Error_t ret_val = SUCCESS; + char getRequestJson[120]; + IoT_Publish_Message_Params params; + + IOT_DEBUG("-->Running Shadow Action Tests - Invalid inbound json in get response \n"); + + snprintf(jsonFullDocument, 200, "NOT_VISITED"); + + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, 4, + false); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + params.payloadLen = strlen("{\"state\":{{"); + params.payload = "{\"state\":{{"; + params.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + CHECK_EQUAL_C_STRING("NOT_VISITED", jsonFullDocument); + + IOT_DEBUG("-->Success - Invalid inbound json in get response \n"); +} + +TEST_C(ShadowActionTests, AcceptedSubFailsGetRequest) { + IoT_Error_t ret_val = SUCCESS; + char getRequestJson[120]; + IoT_Publish_Message_Params params; + + IOT_DEBUG("-->Running Shadow Action Tests - Accepted sub fails get request \n"); + + snprintf(jsonFullDocument, 200, "NOT_SENT"); + + ResetTLSBuffer(); + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, 4, + false); + CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, ret_val); // Should never subscribe and publish + + ResetTLSBuffer(); + params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); + params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; + params.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + CHECK_EQUAL_C_STRING("NOT_SENT", jsonFullDocument); // Never called callback + + IOT_DEBUG("-->Success - Accepted sub fails get request \n"); +} + +TEST_C(ShadowActionTests, RejectedSubFailsGetRequest) { + IoT_Error_t ret_val = SUCCESS; + char getRequestJson[120]; + IoT_Publish_Message_Params params; + + IOT_DEBUG("-->Running Shadow Action Tests - Rejected sub fails get request \n"); + + snprintf(jsonFullDocument, 200, "NOT_SENT"); + + params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); + params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; + params.qos = QOS0; + + ResetTLSBuffer(); + setTLSRxBufferForSuback(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params); + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, 4, + false); + CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, ret_val); // Should never subscribe and publish + + ResetTLSBuffer(); + setTLSRxBufferWithMsgOnSubscribedTopic(GET_REJECTED_TOPIC, strlen(GET_REJECTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + CHECK_EQUAL_C_STRING("NOT_SENT", jsonFullDocument); // Never called callback + + IOT_DEBUG("-->Success - Rejected sub fails get request \n"); +} + +TEST_C(ShadowActionTests, PublishFailsGetRequest) { + IoT_Error_t ret_val = SUCCESS; + char getRequestJson[120]; + IoT_Publish_Message_Params params; + + IOT_DEBUG("-->Running Shadow Action Tests - publish fails on get request \n"); + + snprintf(jsonFullDocument, 200, "NOT_SENT"); + + ResetTLSBuffer(); + + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, 4, + false); + CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, ret_val); // Should never subscribe and publish + + ResetTLSBuffer(); + params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); + params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; + params.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + CHECK_EQUAL_C_STRING("NOT_SENT", jsonFullDocument); // Never called callback + + IOT_DEBUG("-->Success - publish fails on get request \n"); +} + +TEST_C(ShadowActionTests, StickyNonStickyNeverConflict) { + IoT_Error_t ret_val = SUCCESS; + char getRequestJson[120]; + IoT_Publish_Message_Params params; + + IOT_DEBUG("-->Running Shadow Action Tests - Sticky and non-sticky subscriptions do not conflict \n"); + + lastSubscribeMsgLen = 11; + snprintf(LastSubscribeMessage, lastSubscribeMsgLen, "No Message"); + secondLastSubscribeMsgLen = 11; + snprintf(SecondLastSubscribeMessage, secondLastSubscribeMsgLen, "No Message"); + + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, 4, + true); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); + params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; + params.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + CHECK_EQUAL_C_STRING(TEST_JSON_RESPONSE_FULL_DOCUMENT, jsonFullDocument); + CHECK_EQUAL_C_INT(SHADOW_GET, actionRx); + CHECK_EQUAL_C_INT(SHADOW_ACK_ACCEPTED, ackStatusRx); + + lastSubscribeMsgLen = 11; + snprintf(LastSubscribeMessage, lastSubscribeMsgLen, "No Message"); + secondLastSubscribeMsgLen = 11; + snprintf(SecondLastSubscribeMessage, secondLastSubscribeMsgLen, "No Message"); + + // Non-sticky shadow get, same thing name. Should never unsub since they are sticky + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, 4, + false); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + ResetTLSBuffer(); + + params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); + params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; + params.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + CHECK_EQUAL_C_STRING(TEST_JSON_RESPONSE_FULL_DOCUMENT, jsonFullDocument); + CHECK_EQUAL_C_INT(SHADOW_GET, actionRx); + CHECK_EQUAL_C_INT(SHADOW_ACK_ACCEPTED, ackStatusRx); + + CHECK_EQUAL_C_STRING("No Message", LastSubscribeMessage); + CHECK_EQUAL_C_STRING("No Message", SecondLastSubscribeMessage); + + IOT_DEBUG("-->Success - Sticky and non-sticky subscriptions do not conflict \n"); + +} + +TEST_C(ShadowActionTests, ACKWaitingMoreThanAllowed) { + IoT_Error_t ret_val = SUCCESS; + char getRequestJson[120]; + + IOT_DEBUG("-->Running Shadow Action Tests - Ack waiting more than allowed wait time \n"); + + // 1st + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, + 100, false); // 100 sec to timeout + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + // 2nd + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, + 100, false); // 100 sec to timeout + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + // 3rd + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, + 100, false); // 100 sec to timeout + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + // 4th + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, + 100, false); // 100 sec to timeout + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + // 5th + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, + 100, false); // 100 sec to timeout + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + // 6th + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, + 100, false); // 100 sec to timeout + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + // 7th + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, + 100, false); // 100 sec to timeout + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + // 8th + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, + 100, false); // 100 sec to timeout + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + // 9th + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, + 100, false); // 100 sec to timeout + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + // 10th + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, + 100, false); // 100 sec to timeout + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + // 11th + // Should return some error code, since we are running out of ACK space + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, + 100, false); // 100 sec to timeout + CHECK_EQUAL_C_INT(FAILURE, ret_val); + + IOT_DEBUG("-->Success - Ack waiting more than allowed wait time \n"); +} + +#define JSON_SIZE_OVERFLOW "{\"state\":{\"reported\":{\"file\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}}, \"clientToken\":\"" AWS_IOT_MQTT_CLIENT_ID "-0\"}" + +TEST_C(ShadowActionTests, InboundDataTooBigForBuffer) { + IoT_Error_t ret_val = SUCCESS; + char getRequestJson[120]; + IoT_Publish_Message_Params params; + + IOT_DEBUG("-->Running Shadow Action Tests - Inbound data too big for buffer \n"); + + snprintf(jsonFullDocument, 200, "NOT_VISITED"); + + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, 4, + false); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + params.payloadLen = strlen(JSON_SIZE_OVERFLOW); + params.payload = JSON_SIZE_OVERFLOW; + params.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + CHECK_EQUAL_C_INT(MQTT_RX_BUFFER_TOO_SHORT_ERROR, ret_val); + CHECK_EQUAL_C_STRING("NOT_VISITED", jsonFullDocument); + + IOT_DEBUG("-->Success - Inbound data too big for buffer \n"); +} + +#define TEST_JSON_RESPONSE_NO_TOKEN "{\"state\":{\"reported\":{\"sensor1\":98}}}" + +TEST_C(ShadowActionTests, NoClientTokenForShadowAction) { + IoT_Error_t ret_val = SUCCESS; + char getRequestJson[120]; + IoT_Publish_Message_Params params; + + uint8_t firstByte, secondByte; + uint16_t topicNameLen; + char topicName[128] = "test"; + + IOT_DEBUG("-->Running Shadow Action Tests - No client token for shadow action \n"); + + snprintf(getRequestJson, 120, "{}"); + snprintf(jsonFullDocument, 200, "NOT_VISITED"); + + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, actionCallback, NULL, 4, + false); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + params.payloadLen = strlen(TEST_JSON_RESPONSE_NO_TOKEN); + params.payload = TEST_JSON_RESPONSE_NO_TOKEN; + params.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + // Should never subscribe to accepted/rejected topics since we have no token to track the response + CHECK_EQUAL_C_STRING("NOT_VISITED", jsonFullDocument); + + firstByte = (uint8_t)(TxBuffer.pBuffer[2]); + secondByte = (uint8_t)(TxBuffer.pBuffer[3]); + topicNameLen = (uint16_t) (secondByte + (256 * firstByte)); + + snprintf(topicName, topicNameLen + 1u, "%s", &(TxBuffer.pBuffer[4])); // Added one for null character + + // Verify publish happens + CHECK_EQUAL_C_STRING(GET_PUB_TOPIC, topicName); + + IOT_DEBUG("-->Success - No client token for shadow action \n"); +} + +TEST_C(ShadowActionTests, NoCallbackForShadowAction) { + IoT_Error_t ret_val = SUCCESS; + char getRequestJson[120]; + IoT_Publish_Message_Params params; + + uint8_t firstByte, secondByte; + uint16_t topicNameLen; + char topicName[128] = "test"; + + IOT_DEBUG("-->Running Shadow Action Tests - No callback for shadow action \n"); + + snprintf(jsonFullDocument, 200, "NOT_VISITED"); + + aws_iot_shadow_internal_get_request_json(getRequestJson); + ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, NULL, NULL, 4, false); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); + params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; + setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, + params.payload); + ret_val = aws_iot_shadow_yield(&client, 200); + + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + // Should never subscribe to accepted/rejected topics since we have no callback to track the response + CHECK_EQUAL_C_STRING("NOT_VISITED", jsonFullDocument); + + firstByte = (uint8_t)(TxBuffer.pBuffer[2]); + secondByte = (uint8_t)(TxBuffer.pBuffer[3]); + topicNameLen = (uint16_t) (secondByte + (256 * firstByte)); + + snprintf(topicName, topicNameLen + 1u, "%s", &(TxBuffer.pBuffer[4])); // Added one for null character + + // Verify publish happens + CHECK_EQUAL_C_STRING(GET_PUB_TOPIC, topicName); + + IOT_DEBUG("-->Success - No callback for shadow action"); +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_delta.cpp b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_delta.cpp new file mode 100644 index 00000000..db9c0b25 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_delta.cpp @@ -0,0 +1,33 @@ +/* +* Copyright 2015-2016 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_tests_unit_shadow_delta.cpp + * @brief IoT Client Unit Testing - Shadow Delta Tests + */ + +#include +#include + +TEST_GROUP_C(ShadowDeltaTest){ + TEST_GROUP_C_SETUP_WRAPPER(ShadowDeltaTest) + TEST_GROUP_C_TEARDOWN_WRAPPER(ShadowDeltaTest) +}; + +TEST_GROUP_C_WRAPPER(ShadowDeltaTest, registerDeltaSuccess) +TEST_GROUP_C_WRAPPER(ShadowDeltaTest, registerDeltaInt) +TEST_GROUP_C_WRAPPER(ShadowDeltaTest, registerDeltaIntNoCallback) +TEST_GROUP_C_WRAPPER(ShadowDeltaTest, DeltaNestedObject) +TEST_GROUP_C_WRAPPER(ShadowDeltaTest, DeltaVersionIgnoreOldVersion) diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_delta_helper.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_delta_helper.c new file mode 100644 index 00000000..0ec18c0a --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_delta_helper.c @@ -0,0 +1,319 @@ +/* +* Copyright 2015-2016 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_tests_unit_shadow_delta_helper.c + * @brief IoT Client Unit Testing - Shadow Delta Tests Helper + */ + +#include +#include +#include + +#include "aws_iot_shadow_interface.h" +#include "aws_iot_tests_unit_helper_functions.h" +#include "aws_iot_log.h" + +static AWS_IoT_Client client; +static IoT_Client_Connect_Params connectParams; +static ShadowInitParameters_t shadowInitParams; +static ShadowConnectParameters_t shadowConnectParams; + +static char receivedNestedObject[100] = ""; +static char sentNestedObjectData[100] = "{\"sensor1\":23}"; +static char shadowDeltaTopic[MAX_SHADOW_TOPIC_LENGTH_BYTES]; + +#define SHADOW_DELTA_UPDATE "$aws/things/%s/shadow/update/delta" + +#undef AWS_IOT_MY_THING_NAME +#define AWS_IOT_MY_THING_NAME "AWS-IoT-C-SDK" + +void genericCallback(const char *pJsonStringData, uint32_t JsonStringDataLen, jsonStruct_t *pContext) { + printf("\nkey[%s]==Data[%.*s]\n", pContext->pKey, JsonStringDataLen, pJsonStringData); +} + +void nestedObjectCallback(const char *pJsonStringData, uint32_t JsonStringDataLen, jsonStruct_t *pContext) { + printf("\nkey[%s]==Data[%.*s]\n", pContext->pKey, JsonStringDataLen, pJsonStringData); + snprintf(receivedNestedObject, 100, "%.*s", JsonStringDataLen, pJsonStringData); +} + +TEST_GROUP_C_SETUP(ShadowDeltaTest) { + IoT_Error_t ret_val = SUCCESS; + + shadowInitParams.pHost = AWS_IOT_MQTT_HOST; + shadowInitParams.port = AWS_IOT_MQTT_PORT; + shadowInitParams.pClientCRT = AWS_IOT_CERTIFICATE_FILENAME; + shadowInitParams.pRootCA = AWS_IOT_ROOT_CA_FILENAME; + shadowInitParams.pClientKey = AWS_IOT_PRIVATE_KEY_FILENAME; + shadowInitParams.disconnectHandler = NULL; + shadowInitParams.enableAutoReconnect = false; + ret_val = aws_iot_shadow_init(&client, &shadowInitParams); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + shadowConnectParams.pMyThingName = AWS_IOT_MY_THING_NAME; + shadowConnectParams.pMqttClientId = AWS_IOT_MQTT_CLIENT_ID; + shadowConnectParams.mqttClientIdLen = (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID); + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + ret_val = aws_iot_shadow_connect(&client, &shadowConnectParams); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + snprintf(shadowDeltaTopic, MAX_SHADOW_TOPIC_LENGTH_BYTES, SHADOW_DELTA_UPDATE, AWS_IOT_MY_THING_NAME); +} + +TEST_GROUP_C_TEARDOWN(ShadowDeltaTest) { + +} + +TEST_C(ShadowDeltaTest, registerDeltaSuccess) { + jsonStruct_t windowHandler; + char deltaJSONString[] = "{\"state\":{\"delta\":{\"window\":true}},\"version\":1}"; + bool windowOpenData = false; + IoT_Publish_Message_Params params; + IoT_Error_t ret_val = SUCCESS; + + IOT_DEBUG("\n-->Running Shadow Delta Tests - Register delta success \n"); + + windowHandler.cb = genericCallback; + windowHandler.pKey = "window"; + windowHandler.type = SHADOW_JSON_BOOL; + windowHandler.pData = &windowOpenData; + + params.payloadLen = strlen(deltaJSONString); + params.payload = deltaJSONString; + params.qos = QOS0; + + ResetTLSBuffer(); + setTLSRxBufferForSuback(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params); + + ret_val = aws_iot_shadow_register_delta(&client, &windowHandler); + + ResetTLSBuffer(); + setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); + + ret_val = aws_iot_shadow_yield(&client, 3000); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + CHECK_EQUAL_C_INT(true, windowOpenData); +} + + +TEST_C(ShadowDeltaTest, registerDeltaInt) { + IoT_Error_t ret_val = SUCCESS; + jsonStruct_t intHandler; + int intData = 0; + char deltaJSONString[] = "{\"state\":{\"delta\":{\"length\":23}},\"version\":1}"; + IoT_Publish_Message_Params params; + + IOT_DEBUG("\n-->Running Shadow Delta Tests - Register delta integer \n"); + + intHandler.cb = genericCallback; + intHandler.pKey = "length"; + intHandler.type = SHADOW_JSON_INT32; + intHandler.pData = &intData; + + params.payloadLen = strlen(deltaJSONString); + params.payload = deltaJSONString; + params.qos = QOS0; + + ResetTLSBuffer(); + setTLSRxBufferForSuback(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params); + + ret_val = aws_iot_shadow_register_delta(&client, &intHandler); + + ResetTLSBuffer(); + setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); + + aws_iot_shadow_yield(&client, 3000); + CHECK_EQUAL_C_INT(23, intData); +} + +TEST_C(ShadowDeltaTest, registerDeltaIntNoCallback) { + IoT_Error_t ret_val = SUCCESS; + jsonStruct_t intHandler; + int intData = 0; + char deltaJSONString[] = "{\"state\":{\"delta\":{\"length_nocb\":23}},\"version\":1}"; + IoT_Publish_Message_Params params; + + IOT_DEBUG("\n-->Running Shadow Delta Tests - Register delta integer with no callback \n"); + + intHandler.cb = NULL; + intHandler.pKey = "length_nocb"; + intHandler.type = SHADOW_JSON_INT32; + intHandler.pData = &intData; + + params.payloadLen = strlen(deltaJSONString); + params.payload = deltaJSONString; + params.qos = QOS0; + + ResetTLSBuffer(); + setTLSRxBufferForSuback(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params); + + ret_val = aws_iot_shadow_register_delta(&client, &intHandler); + + ResetTLSBuffer(); + setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); + + aws_iot_shadow_yield(&client, 3000); + CHECK_EQUAL_C_INT(23, intData); +} + +TEST_C(ShadowDeltaTest, DeltaNestedObject) { + IoT_Error_t ret_val = SUCCESS; + IoT_Publish_Message_Params params; + jsonStruct_t nestedObjectHandler; + char nestedObject[100]; + char deltaJSONString[100]; + + printf("\n-->Running Shadow Delta Tests - Delta received with nested object \n"); + + nestedObjectHandler.cb = nestedObjectCallback; + nestedObjectHandler.pKey = "sensors"; + nestedObjectHandler.type = SHADOW_JSON_OBJECT; + nestedObjectHandler.pData = &nestedObject; + + snprintf(deltaJSONString, 100, "{\"state\":{\"delta\":{\"%s\":%s}},\"version\":1}", nestedObjectHandler.pKey, + sentNestedObjectData); + params.payloadLen = strlen(deltaJSONString); + params.payload = deltaJSONString; + params.qos = QOS0; + + ResetTLSBuffer(); + setTLSRxBufferForSuback(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params); + + ret_val = aws_iot_shadow_register_delta(&client, &nestedObjectHandler); + + ResetTLSBuffer(); + setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); + + aws_iot_shadow_yield(&client, 3000); + CHECK_EQUAL_C_STRING(sentNestedObjectData, receivedNestedObject); +} + + +// Send back to back version and ensure a wrong version is ignored with old message enabled +TEST_C(ShadowDeltaTest, DeltaVersionIgnoreOldVersion) { + IoT_Error_t ret_val = SUCCESS; + char deltaJSONString[100]; + jsonStruct_t nestedObjectHandler; + char nestedObject[100]; + IoT_Publish_Message_Params params; + + printf("\n-->Running Shadow Delta Tests - delta received, old version ignored \n"); + + nestedObjectHandler.cb = nestedObjectCallback; + nestedObjectHandler.pKey = "sensors"; + nestedObjectHandler.type = SHADOW_JSON_OBJECT; + nestedObjectHandler.pData = &nestedObject; + + snprintf(deltaJSONString, 100, "{\"state\":{\"delta\":{\"%s\":%s}},\"version\":1}", nestedObjectHandler.pKey, + sentNestedObjectData); + params.payloadLen = strlen(deltaJSONString); + params.payload = deltaJSONString; + params.qos = QOS0; + + ResetTLSBuffer(); + setTLSRxBufferForSuback(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params); + + ret_val = aws_iot_shadow_register_delta(&client, &nestedObjectHandler); + + ResetTLSBuffer(); + setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); + + aws_iot_shadow_yield(&client, 100); + CHECK_EQUAL_C_STRING(sentNestedObjectData, receivedNestedObject); + + snprintf(receivedNestedObject, 100, " "); + snprintf(deltaJSONString, 100, "{\"state\":{\"delta\":{\"%s\":%s}},\"version\":2}", nestedObjectHandler.pKey, + sentNestedObjectData); + params.payloadLen = strlen(deltaJSONString); + params.payload = deltaJSONString; + params.qos = QOS0; + + ResetTLSBuffer(); + setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); + + aws_iot_shadow_yield(&client, 100); + CHECK_EQUAL_C_STRING(sentNestedObjectData, receivedNestedObject); + + snprintf(receivedNestedObject, 100, " "); + snprintf(deltaJSONString, 100, "{\"state\":{\"delta\":{\"%s\":%s}},\"version\":2}", nestedObjectHandler.pKey, + sentNestedObjectData); + params.payloadLen = strlen(deltaJSONString); + params.payload = deltaJSONString; + params.qos = QOS0; + + ResetTLSBuffer(); + setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); + + aws_iot_shadow_yield(&client, 100); + CHECK_EQUAL_C_STRING(" ", receivedNestedObject); + + snprintf(receivedNestedObject, 100, " "); + snprintf(deltaJSONString, 100, "{\"state\":{\"delta\":{\"%s\":%s}},\"version\":3}", nestedObjectHandler.pKey, + sentNestedObjectData); + params.payloadLen = strlen(deltaJSONString); + params.payload = deltaJSONString; + params.qos = QOS0; + + ResetTLSBuffer(); + setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); + + aws_iot_shadow_yield(&client, 100); + CHECK_EQUAL_C_STRING(sentNestedObjectData, receivedNestedObject); + + aws_iot_shadow_reset_last_received_version(); + + snprintf(receivedNestedObject, 100, " "); + snprintf(deltaJSONString, 100, "{\"state\":{\"delta\":{\"%s\":%s}},\"version\":3}", nestedObjectHandler.pKey, + sentNestedObjectData); + params.payloadLen = strlen(deltaJSONString); + params.payload = deltaJSONString; + params.qos = QOS0; + + ResetTLSBuffer(); + setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); + + aws_iot_shadow_yield(&client, 100); + CHECK_EQUAL_C_STRING(sentNestedObjectData, receivedNestedObject); + + snprintf(receivedNestedObject, 100, " "); + snprintf(deltaJSONString, 100, "{\"state\":{\"delta\":{\"%s\":%s}},\"version\":3}", nestedObjectHandler.pKey, + sentNestedObjectData); + params.payloadLen = strlen(deltaJSONString); + params.payload = deltaJSONString; + params.qos = QOS0; + + ResetTLSBuffer(); + setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); + + aws_iot_shadow_yield(&client, 100); + CHECK_EQUAL_C_STRING(" ", receivedNestedObject); + + aws_iot_shadow_disable_discard_old_delta_msgs(); + + snprintf(receivedNestedObject, 100, " "); + snprintf(deltaJSONString, 100, "{\"state\":{\"delta\":{\"%s\":%s}},\"version\":3}", nestedObjectHandler.pKey, + sentNestedObjectData); + params.payloadLen = strlen(deltaJSONString); + params.payload = deltaJSONString; + params.qos = QOS0; + + ResetTLSBuffer(); + setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); + + aws_iot_shadow_yield(&client, 100); + CHECK_EQUAL_C_STRING(sentNestedObjectData, receivedNestedObject); +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_json_builder.cpp b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_json_builder.cpp new file mode 100644 index 00000000..8feb144e --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_json_builder.cpp @@ -0,0 +1,31 @@ +/* +* Copyright 2015-2016 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_tests_unit_shadow_json_builder.cpp + * @brief IoT Client Unit Testing - Shadow JSON Builder Tests + */ + +#include +#include + +TEST_GROUP_C(ShadowJsonBuilderTests){ + TEST_GROUP_C_SETUP_WRAPPER(ShadowJsonBuilderTests) + TEST_GROUP_C_TEARDOWN_WRAPPER(ShadowJsonBuilderTests) +}; + +TEST_GROUP_C_WRAPPER(ShadowJsonBuilderTests, UpdateTheJSONDocumentBuilder) +TEST_GROUP_C_WRAPPER(ShadowJsonBuilderTests, PassingNullValue) +TEST_GROUP_C_WRAPPER(ShadowJsonBuilderTests, SmallBuffer) diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_json_builder_helper.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_json_builder_helper.c new file mode 100644 index 00000000..8cd9fc9a --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_json_builder_helper.c @@ -0,0 +1,129 @@ +/* +* Copyright 2015-2016 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_tests_unit_shadow_json_builder_helper.c + * @brief IoT Client Unit Testing - Shadow JSON Builder Tests Helper + */ + +#include +#include +#include + +#include "aws_iot_shadow_actions.h" +#include "aws_iot_log.h" +#include "aws_iot_tests_unit_helper_functions.h" + +static jsonStruct_t dataFloatHandler; +static jsonStruct_t dataDoubleHandler; +static double doubleData = 4.0908f; +static float floatData = 3.445f; +static AWS_IoT_Client iotClient; +static IoT_Client_Connect_Params connectParams; +static ShadowInitParameters_t shadowInitParams; +static ShadowConnectParameters_t shadowConnectParams; + +TEST_GROUP_C_SETUP(ShadowJsonBuilderTests) { + IoT_Error_t ret_val; + + shadowInitParams.pHost = AWS_IOT_MQTT_HOST; + shadowInitParams.port = AWS_IOT_MQTT_PORT; + shadowInitParams.pClientCRT = AWS_IOT_CERTIFICATE_FILENAME; + shadowInitParams.pRootCA = AWS_IOT_ROOT_CA_FILENAME; + shadowInitParams.pClientKey = AWS_IOT_PRIVATE_KEY_FILENAME; + shadowInitParams.disconnectHandler = NULL; + shadowInitParams.enableAutoReconnect = false; + ret_val = aws_iot_shadow_init(&iotClient, &shadowInitParams); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + shadowConnectParams.pMyThingName = AWS_IOT_MY_THING_NAME; + shadowConnectParams.pMqttClientId = AWS_IOT_MQTT_CLIENT_ID; + shadowConnectParams.mqttClientIdLen = (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID); + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + ret_val = aws_iot_shadow_connect(&iotClient, &shadowConnectParams); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + dataFloatHandler.cb = NULL; + dataFloatHandler.pData = &floatData; + dataFloatHandler.pKey = "floatData"; + dataFloatHandler.type = SHADOW_JSON_FLOAT; + + dataDoubleHandler.cb = NULL; + dataDoubleHandler.pData = &doubleData; + dataDoubleHandler.pKey = "doubleData"; + dataDoubleHandler.type = SHADOW_JSON_DOUBLE; +} + +TEST_GROUP_C_TEARDOWN(ShadowJsonBuilderTests) { + /* Clean up. Not checking return code here because this is common to all tests. + * A test might have already caused a disconnect by this point. + */ + IoT_Error_t rc = aws_iot_mqtt_disconnect(&iotClient); + IOT_UNUSED(rc); +} + +#define TEST_JSON_RESPONSE_UPDATE_DOCUMENT "{\"state\":{\"reported\":{\"doubleData\":4.090800,\"floatData\":3.445000}}, \"clientToken\":\"" AWS_IOT_MQTT_CLIENT_ID "-0\"}" + +#define SIZE_OF_UPFATE_BUF 200 + +TEST_C(ShadowJsonBuilderTests, UpdateTheJSONDocumentBuilder) { + IoT_Error_t ret_val; + char updateRequestJson[SIZE_OF_UPFATE_BUF]; + size_t jsonBufSize = sizeof(updateRequestJson) / sizeof(updateRequestJson[0]); + + IOT_DEBUG("\n-->Running Shadow Json Builder Tests - Update the Json document builder \n"); + + ret_val = aws_iot_shadow_init_json_document(updateRequestJson, jsonBufSize); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + ret_val = aws_iot_shadow_add_reported(updateRequestJson, jsonBufSize, 2, &dataDoubleHandler, &dataFloatHandler); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + ret_val = aws_iot_finalize_json_document(updateRequestJson, jsonBufSize); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + + CHECK_EQUAL_C_STRING(TEST_JSON_RESPONSE_UPDATE_DOCUMENT, updateRequestJson); +} + +TEST_C(ShadowJsonBuilderTests, PassingNullValue) { + IoT_Error_t ret_val; + + IOT_DEBUG("\n-->Running Shadow Json Builder Tests - Passing Null value to Shadow json builder \n"); + + ret_val = aws_iot_shadow_init_json_document(NULL, SIZE_OF_UPFATE_BUF); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, ret_val); + ret_val = aws_iot_shadow_add_reported(NULL, SIZE_OF_UPFATE_BUF, 2, &dataDoubleHandler, &dataFloatHandler); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, ret_val); + ret_val = aws_iot_shadow_add_desired(NULL, SIZE_OF_UPFATE_BUF, 2, &dataDoubleHandler, &dataFloatHandler); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, ret_val); + ret_val = aws_iot_finalize_json_document(NULL, SIZE_OF_UPFATE_BUF); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, ret_val); +} + +TEST_C(ShadowJsonBuilderTests, SmallBuffer) { + IoT_Error_t ret_val; + char updateRequestJson[14]; + size_t jsonBufSize = sizeof(updateRequestJson) / sizeof(updateRequestJson[0]); + + IOT_DEBUG("\n-->Running Shadow Json Builder Tests - Json Buffer is too small \n"); + + ret_val = aws_iot_shadow_init_json_document(updateRequestJson, jsonBufSize); + CHECK_EQUAL_C_INT(SUCCESS, ret_val); + ret_val = aws_iot_shadow_add_reported(updateRequestJson, jsonBufSize, 2, &dataDoubleHandler, &dataFloatHandler); + CHECK_EQUAL_C_INT(SHADOW_JSON_BUFFER_TRUNCATED, ret_val); + ret_val = aws_iot_shadow_add_desired(updateRequestJson, jsonBufSize, 2, &dataDoubleHandler, &dataFloatHandler); + CHECK_EQUAL_C_INT(SHADOW_JSON_ERROR, ret_val); + ret_val = aws_iot_finalize_json_document(updateRequestJson, jsonBufSize); + CHECK_EQUAL_C_INT(SHADOW_JSON_ERROR, ret_val); +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_null_fields.cpp b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_null_fields.cpp new file mode 100644 index 00000000..dd4d02a6 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_null_fields.cpp @@ -0,0 +1,40 @@ +/* +* Copyright 2015-2016 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_tests_unit_shadow_null_fields.cpp + * @brief IoT Client Unit Testing - Shadow APIs NULL field Tests + */ + +#include +#include + +TEST_GROUP_C(ShadowNullFields){ + TEST_GROUP_C_SETUP_WRAPPER(ShadowNullFields) + TEST_GROUP_C_TEARDOWN_WRAPPER(ShadowNullFields) +}; + +TEST_GROUP_C_WRAPPER(ShadowNullFields, NullClientInit) +TEST_GROUP_C_WRAPPER(ShadowNullFields, NullClientConnect) +TEST_GROUP_C_WRAPPER(ShadowNullFields, NullHost) +TEST_GROUP_C_WRAPPER(ShadowNullFields, NullPort) +TEST_GROUP_C_WRAPPER(ShadowNullFields, NullClientID) +TEST_GROUP_C_WRAPPER(ShadowNullFields, NullUpdateDocument) +TEST_GROUP_C_WRAPPER(ShadowNullFields, NullClientYield) +TEST_GROUP_C_WRAPPER(ShadowNullFields, NullClientDisconnect) +TEST_GROUP_C_WRAPPER(ShadowNullFields, NullClientShadowGet) +TEST_GROUP_C_WRAPPER(ShadowNullFields, NullClientShadowUpdate) +TEST_GROUP_C_WRAPPER(ShadowNullFields, NullClientShadowDelete) +TEST_GROUP_C_WRAPPER(ShadowNullFields, NullClientSetAutoreconnect) diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_null_fields_helper.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_null_fields_helper.c new file mode 100644 index 00000000..462b730e --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_null_fields_helper.c @@ -0,0 +1,148 @@ +/* +* Copyright 2015-2016 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_tests_unit_shadow_null_fields_helper.c + * @brief IoT Client Unit Testing - Shadow APIs NULL field Tests helper + */ + +#include +#include +#include +#include + +#include "aws_iot_tests_unit_helper_functions.h" +#include "aws_iot_shadow_interface.h" +#include "aws_iot_shadow_actions.h" +#include "aws_iot_log.h" + +static AWS_IoT_Client client; +static ShadowInitParameters_t shadowInitParams; +static ShadowConnectParameters_t shadowConnectParams; + +static Shadow_Ack_Status_t ackStatusRx; +static ShadowActions_t actionRx; +static char jsonFullDocument[200]; + +void actionCallbackNullTest(const char *pThingName, ShadowActions_t action, Shadow_Ack_Status_t status, + const char *pReceivedJsonDocument, void *pContextData) { + IOT_UNUSED(pThingName); + IOT_UNUSED(pContextData); + IOT_DEBUG("%s", pReceivedJsonDocument); + actionRx = action; + ackStatusRx = status; + if(status != SHADOW_ACK_TIMEOUT) { + strcpy(jsonFullDocument, pReceivedJsonDocument); + } +} + +TEST_GROUP_C_SETUP(ShadowNullFields) { + ResetTLSBuffer(); +} + +TEST_GROUP_C_TEARDOWN(ShadowNullFields) { } + +TEST_C(ShadowNullFields, NullHost) { + shadowInitParams.pHost = NULL; + shadowInitParams.port = AWS_IOT_MQTT_PORT; + IoT_Error_t rc = aws_iot_shadow_init(&client, &shadowInitParams); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +TEST_C(ShadowNullFields, NullPort) { + shadowInitParams.pHost = AWS_IOT_MQTT_HOST; + shadowInitParams.port = 0; + IoT_Error_t rc = aws_iot_shadow_init(&client, &shadowInitParams); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +TEST_C(ShadowNullFields, NullClientID) { + shadowInitParams.pHost = AWS_IOT_MQTT_HOST; + shadowInitParams.port = AWS_IOT_MQTT_PORT; + shadowInitParams.pClientCRT = AWS_IOT_CERTIFICATE_FILENAME; + shadowInitParams.pRootCA = AWS_IOT_ROOT_CA_FILENAME; + shadowInitParams.pClientKey = AWS_IOT_PRIVATE_KEY_FILENAME; + shadowInitParams.disconnectHandler = NULL; + shadowInitParams.enableAutoReconnect = false; + IoT_Error_t rc = aws_iot_shadow_init(&client, &shadowInitParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + shadowConnectParams.pMyThingName = AWS_IOT_MY_THING_NAME; + shadowConnectParams.pMqttClientId = NULL; + rc = aws_iot_shadow_connect(&client, &shadowConnectParams); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +TEST_C(ShadowNullFields, NullClientInit) { + shadowInitParams.pHost = AWS_IOT_MQTT_HOST; + shadowInitParams.port = AWS_IOT_MQTT_PORT; + IoT_Error_t rc = aws_iot_shadow_init(NULL, &shadowInitParams); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +TEST_C(ShadowNullFields, NullClientConnect) { + shadowInitParams.pHost = AWS_IOT_MQTT_HOST; + shadowInitParams.port = AWS_IOT_MQTT_PORT; + shadowInitParams.pClientCRT = AWS_IOT_CERTIFICATE_FILENAME; + shadowInitParams.pRootCA = AWS_IOT_ROOT_CA_FILENAME; + shadowInitParams.pClientKey = AWS_IOT_PRIVATE_KEY_FILENAME; + shadowInitParams.disconnectHandler = NULL; + shadowInitParams.enableAutoReconnect = false; + IoT_Error_t rc = aws_iot_shadow_init(&client, &shadowInitParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + shadowConnectParams.pMyThingName = AWS_IOT_MY_THING_NAME; + shadowConnectParams.pMqttClientId = AWS_IOT_MQTT_CLIENT_ID; + shadowConnectParams.mqttClientIdLen = (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID); + rc = aws_iot_shadow_connect(NULL, &shadowConnectParams); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +TEST_C(ShadowNullFields, NullUpdateDocument) { + IoT_Error_t rc = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_UPDATE, NULL, actionCallbackNullTest, + NULL, 4, false); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +TEST_C(ShadowNullFields, NullClientYield) { + IoT_Error_t rc = aws_iot_shadow_yield(NULL, 1000); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +TEST_C(ShadowNullFields, NullClientDisconnect) { + IoT_Error_t rc = aws_iot_shadow_disconnect(NULL); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +TEST_C(ShadowNullFields, NullClientShadowGet) { + IoT_Error_t rc = aws_iot_shadow_get(NULL, AWS_IOT_MY_THING_NAME, actionCallbackNullTest, NULL, 100, true); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +TEST_C(ShadowNullFields, NullClientShadowUpdate) { + IoT_Error_t rc = aws_iot_shadow_update(NULL, AWS_IOT_MY_THING_NAME, jsonFullDocument, + actionCallbackNullTest, NULL, 100, true); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +TEST_C(ShadowNullFields, NullClientShadowDelete) { + IoT_Error_t rc = aws_iot_shadow_delete(NULL, AWS_IOT_MY_THING_NAME, actionCallbackNullTest, NULL, 100, true); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +TEST_C(ShadowNullFields, NullClientSetAutoreconnect) { + IoT_Error_t rc = aws_iot_shadow_set_autoreconnect_status(NULL, true); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_subscribe.cpp b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_subscribe.cpp new file mode 100644 index 00000000..205cc076 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_subscribe.cpp @@ -0,0 +1,79 @@ +/* +* Copyright 2015-2016 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_tests_unit_subscribe.cpp + * @brief IoT Client Unit Testing - Subscribe API Tests + */ + +#include +#include + +TEST_GROUP_C(SubscribeTests){ + TEST_GROUP_C_SETUP_WRAPPER(SubscribeTests) + TEST_GROUP_C_TEARDOWN_WRAPPER(SubscribeTests) +}; + +/* C:1 - Subscribe with Null/empty Client Instance */ +TEST_GROUP_C_WRAPPER(SubscribeTests, SubscribeNullClient) +/* C:2 - Subscribe with Null/empty Topic Name */ +TEST_GROUP_C_WRAPPER(SubscribeTests, SubscribeNullTopic) +/* C:3 - Subscribe with Null client callback */ +TEST_GROUP_C_WRAPPER(SubscribeTests, SubscribeNullSubscribeHandler) +/* C:4 - Subscribe with Null client callback data */ +TEST_GROUP_C_WRAPPER(SubscribeTests, SubscribeNullSubscribeHandlerData) +/* C:5 - Subscribe with no connection */ +TEST_GROUP_C_WRAPPER(SubscribeTests, SubscribeNoConnection) +/* C:6 - Subscribe QoS2, error */ +/* Not required, QoS enum doesn't have value for QoS2 */ + +/* C:7 - Subscribe attempt, QoS0, no response timeout */ +TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeQoS0FailureOnNoSuback) +/* C:8 - Subscribe attempt, QoS1, no response timeout */ +TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeQoS1FailureOnNoSuback) + +/* C:9 - Subscribe QoS0 success, suback received */ +TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeQoS0Success) +/* C:10 - Subscribe QoS1 success, suback received */ +TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeQoS1Success) + +/* C:11 - Subscribe, QoS0, delayed suback, success */ +TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeQoS0WithDelayedSubackSuccess) +/* C:12 - Subscribe, QoS1, delayed suback, success */ +TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeQoS1WithDelayedSubackSuccess) + +/* C:13 - Subscribe QoS0 success, no puback sent on message */ +TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeQoS0MsgReceivedAndNoPubackSent) +/* C:14 - Subscribe QoS1 success, puback sent on message */ +TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeQoS1MsgReceivedAndSendPuback) + +/* C:15 - Subscribe, malformed response */ +TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeMalformedResponse) + +/* C:16 - Subscribe, multiple topics, messages on each topic */ +TEST_GROUP_C_WRAPPER(SubscribeTests, SubscribeToMultipleTopicsSuccess) +/* C:17 - Subscribe, max topics, messages on each topic */ +TEST_GROUP_C_WRAPPER(SubscribeTests, SubcribeToMaxAllowedTopicsSuccess) +/* C:18 - Subscribe, max topics, another subscribe */ +TEST_GROUP_C_WRAPPER(SubscribeTests, SubcribeToMaxPlusOneAllowedTopicsFailure) + +/* C:19 - Subscribe, '#' not last character in topic name, Failure */ +TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeTopicWithHashkeyAllSubTopicSuccess) +/* C:20 - Subscribe with '#', subscribed to all subtopics */ +TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeTopicHashkeyMustBeTheLastFail) +/* C:21 - Subscribe with '+' as wildcard success */ +TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeTopicWithPluskeySuccess) +/* C:22 - Subscribe with '+' as last character in topic name, Success */ +TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeTopicPluskeyComesLastSuccess) diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_subscribe_helper.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_subscribe_helper.c new file mode 100644 index 00000000..d710f41d --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_subscribe_helper.c @@ -0,0 +1,606 @@ +/* +* Copyright 2015-2016 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_tests_unit_subscribe_helper.c + * @brief IoT Client Unit Testing - Subscribe API Tests Helper + */ + +#include +#include +#include + +#include "aws_iot_tests_unit_helper_functions.h" +#include "aws_iot_log.h" + +static IoT_Client_Init_Params initParams; +static IoT_Client_Connect_Params connectParams; +static IoT_Publish_Message_Params testPubMsgParams; +static char subTopic[10] = "sdk/Test"; +static uint16_t subTopicLen = 8; + +static AWS_IoT_Client iotClient; +static char CallbackMsgString[100]; +char cPayload[100]; + +static char CallbackMsgString1[100] = {"XXXX"}; +static char CallbackMsgString2[100] = {"XXXX"}; +static char CallbackMsgString3[100] = {"XXXX"}; +static char CallbackMsgString4[100] = {"XXXX"}; +static char CallbackMsgString5[100] = {"XXXX"}; +static char CallbackMsgString6[100] = {"XXXX"}; + +static void iot_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, + uint16_t topicNameLen, IoT_Publish_Message_Params *params, void *pData) { + if(NULL == pClient || NULL == topicName || 0 == topicNameLen) { + return; + } + + IOT_UNUSED(pData); + + char *tmp = params->payload; + unsigned int i; + + for(i = 0; i < (params->payloadLen); i++) { + CallbackMsgString[i] = tmp[i]; + } +} + +static void iot_subscribe_callback_handler1(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, + IoT_Publish_Message_Params *params, void *pData) { + if(NULL == pClient || NULL == topicName || 0 == topicNameLen) { + return; + } + + IOT_UNUSED(pData); + + char *tmp = params->payload; + unsigned int i; + + printf("callback topic %s\n", topicName); + for(i = 0; i < (params->payloadLen); i++) { + CallbackMsgString1[i] = tmp[i]; + } +} + +static void iot_subscribe_callback_handler2(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, + IoT_Publish_Message_Params *params, void *pData) { + if(NULL == pClient || NULL == topicName || 0 == topicNameLen) { + return; + } + + IOT_UNUSED(pData); + + char *tmp = params->payload; + unsigned int i; + + for(i = 0; i < (params->payloadLen); i++) { + CallbackMsgString2[i] = tmp[i]; + } +} + +static void iot_subscribe_callback_handler3(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, + IoT_Publish_Message_Params *params, void *pData) { + if(NULL == pClient || NULL == topicName || 0 == topicNameLen) { + return; + } + + IOT_UNUSED(pData); + + char *tmp = params->payload; + unsigned int i; + + for(i = 0; i < (params->payloadLen); i++) { + CallbackMsgString3[i] = tmp[i]; + } +} + +static void iot_subscribe_callback_handler4(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, + IoT_Publish_Message_Params *params, void *pData) { + if(NULL == pClient || NULL == topicName || 0 == topicNameLen) { + return; + } + + IOT_UNUSED(pData); + + char *tmp = params->payload; + unsigned int i; + + for(i = 0; i < (params->payloadLen); i++) { + CallbackMsgString4[i] = tmp[i]; + } +} + +static void iot_subscribe_callback_handler5(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, + IoT_Publish_Message_Params *params, void *pData) { + if(NULL == pClient || NULL == topicName || 0 == topicNameLen) { + return; + } + + IOT_UNUSED(pData); + + char *tmp = params->payload; + unsigned int i; + + for(i = 0; i < (params->payloadLen); i++) { + CallbackMsgString5[i] = tmp[i]; + } +} + +static void iot_subscribe_callback_handler6(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, + IoT_Publish_Message_Params *params, void *pData) { + if(NULL == pClient || NULL == topicName || 0 == topicNameLen) { + return; + } + + IOT_UNUSED(pData); + + char *tmp = params->payload; + unsigned int i; + + for(i = 0; i < (params->payloadLen); i++) { + CallbackMsgString6[i] = tmp[i]; + } +} + +TEST_GROUP_C_SETUP(SubscribeTests) { + IoT_Error_t rc; + ResetTLSBuffer(); + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + initParams.mqttCommandTimeout_ms = 2000; + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + IOT_DEBUG("MQTT Status State : %d, RC : %d\n\n", aws_iot_mqtt_get_client_state(&iotClient), rc); + + testPubMsgParams.qos = QOS1; + testPubMsgParams.isRetained = 0; + snprintf(cPayload, 100, "%s : %d ", "hello from SDK", 0); + testPubMsgParams.payload = (void *) cPayload; + testPubMsgParams.payloadLen = strlen(cPayload); + + ResetTLSBuffer(); +} + +TEST_GROUP_C_TEARDOWN(SubscribeTests) { } + + + +/* C:1 - Subscribe with Null/empty Client Instance */ +TEST_C(SubscribeTests, SubscribeNullClient) { + IoT_Error_t rc = aws_iot_mqtt_subscribe(NULL, "sdkTest/Sub", 11, QOS1, iot_subscribe_callback_handler, &iotClient); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +/* C:2 - Subscribe with Null/empty Topic Name */ +TEST_C(SubscribeTests, SubscribeNullTopic) { + IoT_Error_t rc = aws_iot_mqtt_subscribe(&iotClient, NULL, 11, QOS1, iot_subscribe_callback_handler, &iotClient); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +/* C:3 - Subscribe with Null client callback */ +TEST_C(SubscribeTests, SubscribeNullSubscribeHandler) { + IoT_Error_t rc = aws_iot_mqtt_subscribe(&iotClient, "sdkTest/Sub", 11, QOS1, NULL, &iotClient); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} +/* C:4 - Subscribe with Null client callback data */ +TEST_C(SubscribeTests, SubscribeNullSubscribeHandlerData) { + setTLSRxBufferForSuback(subTopic, subTopicLen, QOS0, testPubMsgParams); + IoT_Error_t rc = aws_iot_mqtt_subscribe(&iotClient, "sdkTest/Sub", 11, QOS1, iot_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); +} +/* C:5 - Subscribe with no connection */ +TEST_C(SubscribeTests, SubscribeNoConnection) { + /* Disconnect first */ + IoT_Error_t rc = aws_iot_mqtt_disconnect(&iotClient); + + rc = aws_iot_mqtt_subscribe(&iotClient, "sdkTest/Sub", 11, QOS1, iot_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc); +} +/* C:6 - Subscribe QoS2, error */ +/* Not required, QoS enum doesn't have value for QoS2 */ + +/* C:7 - Subscribe attempt, QoS0, no response timeout */ +TEST_C(SubscribeTests, subscribeQoS0FailureOnNoSuback) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Subscribe Tests - C:7 - Subscribe attempt, QoS0, no response timeout \n"); + + rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS0, iot_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, rc); + + IOT_DEBUG("-->Success - C:7 - Subscribe attempt, QoS0, no response timeout \n"); +} +/* C:8 - Subscribe attempt, QoS1, no response timeout */ +TEST_C(SubscribeTests, subscribeQoS1FailureOnNoSuback) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Subscribe Tests - C:8 - Subscribe attempt, QoS1, no response timeout \n"); + + rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS1, iot_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, rc); + + IOT_DEBUG("-->Success - C:8 - Subscribe attempt, QoS1, no response timeout \n"); +} + +/* C:9 - Subscribe QoS0 success, suback received */ +TEST_C(SubscribeTests, subscribeQoS0Success) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Subscribe Tests - C:9 - Subscribe QoS0 success, suback received \n"); + + setTLSRxBufferForSuback(subTopic, subTopicLen, QOS0, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS0, iot_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + IOT_DEBUG("-->Success - C:9 - Subscribe QoS0 success, suback received \n"); +} + +/* C:10 - Subscribe QoS1 success, suback received */ +TEST_C(SubscribeTests, subscribeQoS1Success) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Subscribe Tests - C:10 - Subscribe QoS1 success, suback received \n"); + + setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS1, iot_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + IOT_DEBUG("-->Success - C:10 - Subscribe QoS1 success, suback received \n"); +} + +/* C:11 - Subscribe, QoS0, delayed suback, success */ +TEST_C(SubscribeTests, subscribeQoS0WithDelayedSubackSuccess) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Subscribe Tests - C:11 - Subscribe, QoS0, delayed suback, success \n"); + + setTLSRxBufferForSuback(subTopic, subTopicLen, QOS0, testPubMsgParams); + setTLSRxBufferDelay(0, (int) iotClient.clientData.commandTimeoutMs/2); + rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS0, iot_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + IOT_DEBUG("-->Success - C:11 - Subscribe, QoS0, delayed suback, success \n"); +} + +/* C:12 - Subscribe, QoS1, delayed suback, success */ +TEST_C(SubscribeTests, subscribeQoS1WithDelayedSubackSuccess) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Subscribe Tests - C:12 - Subscribe, QoS1, delayed suback, success \n"); + + setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams); + setTLSRxBufferDelay(0, (int) iotClient.clientData.commandTimeoutMs/2); + rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS1, iot_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + IOT_DEBUG("-->Success - C:12 - Subscribe, QoS1, delayed suback, success \n"); +} + +/* C:13 - Subscribe QoS0 success, no puback sent on message */ +TEST_C(SubscribeTests, subscribeQoS0MsgReceivedAndNoPubackSent) { + IoT_Error_t rc = SUCCESS; + char expectedCallbackString[100] = "Test msg - unit test"; + + IOT_DEBUG("-->Running Subscribe Tests - C:13 - Subscribe QoS0 success, no puback sent on message \n"); + + ResetTLSBuffer(); + setTLSRxBufferForSuback(subTopic, subTopicLen, QOS0, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS0, iot_subscribe_callback_handler, NULL); + if(SUCCESS == rc) { + testPubMsgParams.qos = QOS0; + setTLSRxBufferWithMsgOnSubscribedTopic(subTopic, subTopicLen, QOS0, testPubMsgParams, expectedCallbackString); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + if(SUCCESS == rc) { + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); + } + } + CHECK_EQUAL_C_INT(0, isLastTLSTxMessagePuback()); + + IOT_DEBUG("-->Success - C:13 - Subscribe QoS0 success, no puback sent on message \n"); +} + +/* C:14 - Subscribe QoS1 success, puback sent on message */ +TEST_C(SubscribeTests, subscribeQoS1MsgReceivedAndSendPuback) { + IoT_Error_t rc = SUCCESS; + char expectedCallbackString[] = "0xA5A5A3"; + + IOT_DEBUG("-->Running Subscribe Tests - C:14 - Subscribe QoS1 success, puback sent on message \n"); + + setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS1, iot_subscribe_callback_handler, NULL); + if(SUCCESS == rc) { + setTLSRxBufferWithMsgOnSubscribedTopic(subTopic, subTopicLen, QOS1, testPubMsgParams, expectedCallbackString); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + if(SUCCESS == rc) { + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); + } + CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePuback()); + } + + IOT_DEBUG("-->Success - C:14 - Subscribe QoS1 success, puback sent on message \n"); +} + +/* C:15 - Subscribe, malformed response */ +TEST_C(SubscribeTests, subscribeMalformedResponse) {} + +/* C:16 - Subscribe, multiple topics, messages on each topic */ +TEST_C(SubscribeTests, SubscribeToMultipleTopicsSuccess) { + IoT_Error_t rc = SUCCESS; + char expectedCallbackString[] = "0xA5A5A3"; + + IOT_DEBUG("-->Running Subscribe Tests - C:16 - Subscribe, multiple topics, messages on each topic \n"); + + setTLSRxBufferForSuback("sdk/Test1", 9, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test1", 9, QOS1, iot_subscribe_callback_handler1, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + setTLSRxBufferForSuback("sdk/Test2", 9, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test2", 9, QOS1, iot_subscribe_callback_handler2, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test1", 9, QOS1, testPubMsgParams, expectedCallbackString); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString1); + + IOT_DEBUG("-->Success - C:16 - Subscribe, multiple topics, messages on each topic \n"); +} +/* C:17 - Subscribe, max topics, messages on each topic */ +TEST_C(SubscribeTests, SubcribeToMaxAllowedTopicsSuccess) { + IoT_Error_t rc = SUCCESS; + char expectedCallbackString[] = "topics sdk/Test1"; + char expectedCallbackString2[] = "topics sdk/Test2"; + char expectedCallbackString3[] = "topics sdk/Test3"; + char expectedCallbackString4[] = "topics sdk/Test4"; + char expectedCallbackString5[] = "topics sdk/Test5"; + + IOT_DEBUG("-->Running Subscribe Tests - C:17 - Subscribe, max topics, messages on each topic \n"); + + setTLSRxBufferForSuback("sdk/Test1", 9, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test1", 9, QOS1, iot_subscribe_callback_handler1, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + setTLSRxBufferForSuback("sdk/Test2", 9, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test2", 9, QOS1, iot_subscribe_callback_handler2, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + setTLSRxBufferForSuback("sdk/Test3", 9, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test3", 9, QOS1, iot_subscribe_callback_handler3, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + setTLSRxBufferForSuback("sdk/Test4", 9, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test4", 9, QOS1, iot_subscribe_callback_handler4, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + setTLSRxBufferForSuback("sdk/Test5", 9, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test5", 9, QOS1, iot_subscribe_callback_handler5, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test1", 9, QOS1, testPubMsgParams, expectedCallbackString); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test2", 9, QOS1, testPubMsgParams, expectedCallbackString2); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test3", 9, QOS1, testPubMsgParams, expectedCallbackString3); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test4", 9, QOS1, testPubMsgParams, expectedCallbackString4); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test5", 9, QOS1, testPubMsgParams, expectedCallbackString5); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString1); + CHECK_EQUAL_C_STRING(expectedCallbackString2, CallbackMsgString2); + CHECK_EQUAL_C_STRING(expectedCallbackString3, CallbackMsgString3); + CHECK_EQUAL_C_STRING(expectedCallbackString4, CallbackMsgString4); + CHECK_EQUAL_C_STRING(expectedCallbackString5, CallbackMsgString5); + + IOT_DEBUG("-->Success - C:17 - Subscribe, max topics, messages on each topic \n"); +} +/* C:18 - Subscribe, max topics, another subscribe */ +TEST_C(SubscribeTests, SubcribeToMaxPlusOneAllowedTopicsFailure) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Subscribe Tests - C:18 - Subscribe, max topics, another subscribe \n"); + + setTLSRxBufferForSuback("sdk/Test1", 9, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test1", 9, QOS1, iot_subscribe_callback_handler1, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + setTLSRxBufferForSuback("sdk/Test2", 9, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test2", 9, QOS1, iot_subscribe_callback_handler2, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + setTLSRxBufferForSuback("sdk/Test3", 9, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test3", 9, QOS1, iot_subscribe_callback_handler3, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + setTLSRxBufferForSuback("sdk/Test4", 9, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test4", 9, QOS1, iot_subscribe_callback_handler4, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + setTLSRxBufferForSuback("sdk/Test5", 9, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test5", 9, QOS1, iot_subscribe_callback_handler5, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + setTLSRxBufferForSuback("sdk/Test6", 9, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test6", 9, QOS1, iot_subscribe_callback_handler6, NULL); + CHECK_EQUAL_C_INT(MQTT_MAX_SUBSCRIPTIONS_REACHED_ERROR, rc); + + IOT_DEBUG("-->Success - C:18 - Subscribe, max topics, another subscribe \n"); +} + +/* C:19 - Subscribe, '#' not last character in topic name, Failure */ +TEST_C(SubscribeTests, subscribeTopicWithHashkeyAllSubTopicSuccess) { + IoT_Error_t rc = SUCCESS; + char expectedCallbackString[100] = "New message: sub/sub, Hashkey"; + + IOT_DEBUG("-->Running Subscribe Tests - C:19 - Subscribe, '#' not last character in topic name, Failure \n"); + + // Set up the subscribed topic, including '#' + setTLSRxBufferForSuback("sdk/Test/#", strlen("sdk/Test/#"), QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test/#", strlen("sdk/Test/#"), QOS1, + iot_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + // Now provide a published message from a sub topic + IOT_DEBUG("[Matching '#'] Checking first sub topic message, with '#' be the last..\n"); + setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test/sub/sub", strlen("sdk/Test/sub/sub"), QOS1, testPubMsgParams, + expectedCallbackString); + snprintf(CallbackMsgString, 100, "NOT_VISITED"); + + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); + CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePuback()); + + // Re-initialize Rx Tx Buffer + ResetTLSBuffer(); + + // Now provide another message from a different sub topic + IOT_DEBUG("[Matching '#'] Checking second sub topic message, with '#' be the last...\n"); + snprintf(expectedCallbackString, 100, "New message: sub2, Hashkey"); + setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test/sub2", strlen("sdk/Test/sub2"), QOS1, testPubMsgParams, + expectedCallbackString); + snprintf(CallbackMsgString, 100, "NOT_VISITED"); + + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); + CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePuback()); + + IOT_DEBUG("-->Success - C:19 - Subscribe, '#' not last character in topic name, Failure \n"); +} +/* C:20 - Subscribe with '#', subscribed to all subtopics */ +TEST_C(SubscribeTests, subscribeTopicHashkeyMustBeTheLastFail) { + IoT_Error_t rc = SUCCESS; + char expectedCallbackString[100] = "New message: foo1/sub, Hashkey"; + + IOT_DEBUG("-->Running Subscribe Tests - C:20 - Subscribe with '#', subscribed to all subtopics \n"); + + // Set up the subscribed topic, with '#' in the middle + // Topic directory not permitted, should fail + setTLSRxBufferForSuback("sdk/#/sub", strlen("sdk/#/sub"), QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/#/sub", strlen("sdk/#/sub"), QOS1, + iot_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ResetTLSBuffer(); + // Now provide a published message from a sub directoy with this sub topic + IOT_DEBUG("[Matching '#'] Checking sub topic message, with '#' in the middle...\n"); + setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test/foo1/sub", strlen("sdk/Test/foo1/sub"), QOS1, testPubMsgParams, + expectedCallbackString); + snprintf(CallbackMsgString, 100, "NOT_VISITED"); + + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING("NOT_VISITED", CallbackMsgString); + + IOT_DEBUG("-->Success - C:20 - Subscribe with '#', subscribed to all subtopics \n"); +} +/* C:21 - Subscribe with '+' as wildcard success */ +TEST_C(SubscribeTests, subscribeTopicWithPluskeySuccess) { + IoT_Error_t rc = SUCCESS; + char expectedCallbackString[100] = "New message: 1/sub, Pluskey"; + + IOT_DEBUG("-->Running Subscribe Tests - C:21 - Subscribe with '+' as wildcard success \n"); + + // Set up the subscribed topic, including '+' + setTLSRxBufferForSuback("sdk/Test/+/sub", strlen("sdk/Test/+/sub"), QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test/+/sub", strlen("sdk/Test/+/sub"), QOS1, + iot_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + // Now provide a published message from a sub topic + IOT_DEBUG("[Matching '+'] Checking first sub topic message, with '+' in the middle...\n"); + setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test/1/sub", strlen("sdk/Test/1/sub"), QOS1, testPubMsgParams, + expectedCallbackString); + snprintf(CallbackMsgString, 100, "NOT_VISITED"); + + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); + CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePuback()); + + // Re-initialize Rx Tx Buffer + ResetTLSBuffer(); + + // Now provide another message from a different sub topic + IOT_DEBUG("[Matching '+'] Checking second sub topic message, with '+' in the middle...\n"); + snprintf(expectedCallbackString, 100, "New message: 2/sub, Pluskey"); + setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test/2/sub", strlen("sdk/Test/2/sub"), QOS1, testPubMsgParams, + expectedCallbackString); + snprintf(CallbackMsgString, 100, "NOT_VISITED"); + + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); + CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePuback()); + + IOT_DEBUG("-->Success - C:21 - Subscribe with '+' as wildcard success \n"); +} +/* C:22 - Subscribe with '+' as last character in topic name, Success */ +TEST_C(SubscribeTests, subscribeTopicPluskeyComesLastSuccess) { + IoT_Error_t rc = SUCCESS; + char expectedCallbackString[100] = "New message: foo1, Pluskey"; + + IOT_DEBUG("-->Running Subscribe Tests - C:22 - Subscribe with '+' as last character in topic name, Success \n"); + + // Set up the subscribed topic, with '+' comes the last + setTLSRxBufferForSuback("sdk/Test/+", strlen("sdk/Test/+"), QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test/+", strlen("sdk/Test/+"), QOS1, + iot_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + // Now provide a published message from a single layer of sub directroy + IOT_DEBUG("[Matching '+'] Checking first sub topic message, with '+' be the last...\n"); + setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test/foo1", strlen("sdk/Test/foo1"), QOS1, testPubMsgParams, + expectedCallbackString); + snprintf(CallbackMsgString, 100, "NOT_VISITED"); + + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); + CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePuback()); + + // Re-initialize Rx Tx Buffer + ResetTLSBuffer(); + + // Now provide a published message from another single layer of sub directroy + IOT_DEBUG("[Matching '+'] Checking second sub topic message, with '+' be the last...\n"); + snprintf(expectedCallbackString, 100, "New message: foo2, Pluskey"); + setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test/foo2", strlen("sdk/Test/foo2"), QOS1, testPubMsgParams, + expectedCallbackString); + snprintf(CallbackMsgString, 100, "NOT_VISITED"); + + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); + CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePuback()); + + IOT_DEBUG("-->Success - C:22 - Subscribe with '+' as last character in topic name, Success \n"); +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_unsubscribe.cpp b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_unsubscribe.cpp new file mode 100644 index 00000000..bedea1f3 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_unsubscribe.cpp @@ -0,0 +1,55 @@ +/* +* Copyright 2015-2016 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_tests_unit_unsubscribe.cpp + * @brief IoT Client Unit Testing - Unsubscribe API Tests + */ + +#include +#include + +TEST_GROUP_C(UnsubscribeTests){ + TEST_GROUP_C_SETUP_WRAPPER(UnsubscribeTests) + TEST_GROUP_C_TEARDOWN_WRAPPER(UnsubscribeTests) +}; + +/* D:1 - Unsubscribe with Null/empty client instance */ +TEST_GROUP_C_WRAPPER(UnsubscribeTests, UnsubscribeNullClient) +/* D:2 - Unsubscribe with Null/empty topic name */ +TEST_GROUP_C_WRAPPER(UnsubscribeTests, UnsubscribeNullTopic) +/* D:3 - Unsubscribe, Not subscribed to topic */ +TEST_GROUP_C_WRAPPER(UnsubscribeTests, UnsubscribeNotSubscribed) + +/* D:4 - Unsubscribe, QoS0, No response, timeout */ +TEST_GROUP_C_WRAPPER(UnsubscribeTests, unsubscribeQoS0FailureOnNoUnsuback) +/* D:5 - Unsubscribe, QoS1, No response, timeout */ +TEST_GROUP_C_WRAPPER(UnsubscribeTests, unsubscribeQoS1FailureOnNoUnsuback) + +/* D:6 - Unsubscribe, QoS0, success */ +TEST_GROUP_C_WRAPPER(UnsubscribeTests, unsubscribeQoS0WithUnsubackSuccess) +/* D:7 - Unsubscribe, QoS0, half command timeout delayed unsuback, success */ +TEST_GROUP_C_WRAPPER(UnsubscribeTests, unsubscribeQoS0WithDelayedUnsubackSuccess) +/* D:8 - Unsubscribe, QoS1, success */ +TEST_GROUP_C_WRAPPER(UnsubscribeTests, unsubscribeQoS1WithUnsubackSuccess) +/* D:9 - Unsubscribe, QoS1, half command timeout delayed unsuback, success */ +TEST_GROUP_C_WRAPPER(UnsubscribeTests, unsubscribeQoS1WithDelayedUnsubackSuccess) + +/* D:10 - Unsubscribe, success, message on topic ignored */ +TEST_GROUP_C_WRAPPER(UnsubscribeTests, MsgAfterUnsubscribe) +/* D:11 - Unsubscribe after max topics reached */ +TEST_GROUP_C_WRAPPER(UnsubscribeTests, MaxTopicsSubscription) +/* D:12 - Repeated Subscribe and Unsubscribe */ +TEST_GROUP_C_WRAPPER(UnsubscribeTests, RepeatedSubUnSub) diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_unsubscribe_helper.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_unsubscribe_helper.c new file mode 100644 index 00000000..a4d24537 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_unsubscribe_helper.c @@ -0,0 +1,343 @@ +/* +* Copyright 2015-2016 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_tests_unit_unsubscribe_helper.c + * @brief IoT Client Unit Testing - Unsubscribe API Tests Helper + */ + +#include +#include +#include + +#include "aws_iot_mqtt_client_interface.h" +#include "aws_iot_tests_unit_helper_functions.h" +#include "aws_iot_log.h" + +static IoT_Client_Init_Params initParams; +static IoT_Client_Connect_Params connectParams; +static IoT_Publish_Message_Params testPubMsgParams; +static char subTopic[10] = "sdk/Test"; +static uint16_t subTopicLen = 8; + +static AWS_IoT_Client iotClient; +static char CallbackMsgString[100]; +char cPayload[100]; + +static void iot_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, + IoT_Publish_Message_Params *params, void *pData) { + if(NULL == pClient || NULL == topicName || 0 == topicNameLen) { + return; + } + + IOT_UNUSED(pData); + + char *tmp = params->payload; + unsigned int i; + + for(i = 0; i < (params->payloadLen); i++) { + CallbackMsgString[i] = tmp[i]; + } +} + +TEST_GROUP_C_SETUP(UnsubscribeTests) { + IoT_Error_t rc = SUCCESS; + ResetTLSBuffer(); + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); + initParams.mqttCommandTimeout_ms = 2000; + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + IOT_DEBUG("MQTT Status State : %d, RC : %d\n\n", aws_iot_mqtt_get_client_state(&iotClient), rc); + + testPubMsgParams.qos = QOS1; + testPubMsgParams.isRetained = 0; + snprintf(cPayload, 100, "%s : %d ", "hello from SDK", 0); + testPubMsgParams.payload = (void *) cPayload; + testPubMsgParams.payloadLen = strlen(cPayload); + + ResetTLSBuffer(); +} + +TEST_GROUP_C_TEARDOWN(UnsubscribeTests) { } + +/* D:1 - Unsubscribe with Null/empty client instance */ +TEST_C(UnsubscribeTests, UnsubscribeNullClient) { + IoT_Error_t rc = aws_iot_mqtt_unsubscribe(NULL, "sdkTest/Sub", 11); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +/* D:2 - Unsubscribe with Null/empty topic name */ +TEST_C(UnsubscribeTests, UnsubscribeNullTopic) { + IoT_Error_t rc = aws_iot_mqtt_unsubscribe(&iotClient, NULL, 11); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +/* D:3 - Unsubscribe, Not subscribed to topic */ +TEST_C(UnsubscribeTests, UnsubscribeNotSubscribed) { + IoT_Error_t rc = aws_iot_mqtt_unsubscribe(&iotClient, "sdkTest/Sub", 11); + CHECK_EQUAL_C_INT(FAILURE, rc); +} + +/* D:4 - Unsubscribe, QoS0, No response, timeout */ +TEST_C(UnsubscribeTests, unsubscribeQoS0FailureOnNoUnsuback) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Unsubscribe Tests - D:4 - Unsubscribe, QoS0, No response, timeout \n"); + + // First, subscribe to a topic + setTLSRxBufferForSuback(subTopic, subTopicLen, QOS0, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS0, iot_subscribe_callback_handler, + NULL); + if(SUCCESS == rc) { + // Then, unsubscribe + rc = aws_iot_mqtt_unsubscribe(&iotClient, subTopic, (uint16_t) strlen(subTopic)); + CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, rc); + } + + IOT_DEBUG("-->Success - D:4 - Unsubscribe, QoS0, No response, timeout \n"); +} + +/* D:5 - Unsubscribe, QoS1, No response, timeout */ +TEST_C(UnsubscribeTests, unsubscribeQoS1FailureOnNoUnsuback) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Unsubscribe Tests - D:5 - Unsubscribe, QoS1, No response, timeout \n"); + + // First, subscribe to a topic + setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS1, iot_subscribe_callback_handler, + NULL); + if(SUCCESS == rc) { + // Then, unsubscribe + rc = aws_iot_mqtt_unsubscribe(&iotClient, subTopic, (uint16_t) strlen(subTopic)); + CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, rc); + } + + IOT_DEBUG("-->Success - D:5 - Unsubscribe, QoS1, No response, timeout \n"); +} + +/* D:6 - Unsubscribe, QoS0, success */ +TEST_C(UnsubscribeTests, unsubscribeQoS0WithUnsubackSuccess) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Unsubscribe Tests - D:6 - Unsubscribe, QoS0, success \n"); + + // First, subscribe to a topic + setTLSRxBufferForSuback(subTopic, subTopicLen, QOS0, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS0, iot_subscribe_callback_handler, + NULL); + if(SUCCESS == rc) { + // Then, unsubscribe + setTLSRxBufferForUnsuback(); + rc = aws_iot_mqtt_unsubscribe(&iotClient, subTopic, (uint16_t) strlen(subTopic)); + CHECK_EQUAL_C_INT(SUCCESS, rc); + } + + IOT_DEBUG("-->Success - D:6 - Unsubscribe, QoS0, success \n"); +} + +/* D:7 - Unsubscribe, QoS0, half command timeout delayed unsuback, success */ +TEST_C(UnsubscribeTests, unsubscribeQoS0WithDelayedUnsubackSuccess) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Unsubscribe Tests - D:7 - Unsubscribe, QoS0, half command timeout delayed unsuback, success \n"); + + // First, subscribe to a topic + setTLSRxBufferForSuback(subTopic, subTopicLen, QOS0, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS0, iot_subscribe_callback_handler, + NULL); + if(SUCCESS == rc) { + // Then, unsubscribe + setTLSRxBufferForUnsuback(); + setTLSRxBufferDelay(0, (int) iotClient.clientData.commandTimeoutMs/2); + rc = aws_iot_mqtt_unsubscribe(&iotClient, subTopic, (uint16_t) strlen(subTopic)); + CHECK_EQUAL_C_INT(SUCCESS, rc); + } + + IOT_DEBUG("-->Success - D:7 - Unsubscribe, QoS0, half command timeout delayed unsuback, success \n"); +} + +/* D:8 - Unsubscribe, QoS1, success */ +TEST_C(UnsubscribeTests, unsubscribeQoS1WithUnsubackSuccess) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Unsubscribe Tests - D:8 - Unsubscribe, QoS1, success \n"); + + // First, subscribe to a topic + setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS1, iot_subscribe_callback_handler, + NULL); + if(SUCCESS == rc) { + // Then, unsubscribe + setTLSRxBufferForUnsuback(); + rc = aws_iot_mqtt_unsubscribe(&iotClient, subTopic, (uint16_t) strlen(subTopic)); + CHECK_EQUAL_C_INT(SUCCESS, rc); + } + + IOT_DEBUG("-->Success - D:8 - Unsubscribe, QoS1, success \n"); +} + +/* D:9 - Unsubscribe, QoS1, half command timeout delayed unsuback, success */ +TEST_C(UnsubscribeTests, unsubscribeQoS1WithDelayedUnsubackSuccess) { + IoT_Error_t rc = SUCCESS; + + IOT_DEBUG("-->Running Unsubscribe Tests - D:9 - Unsubscribe, QoS1, half command timeout delayed unsuback, success \n"); + + // First, subscribe to a topic + setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS1, iot_subscribe_callback_handler, + NULL); + if(SUCCESS == rc) { + // Then, unsubscribe + setTLSRxBufferForUnsuback(); + setTLSRxBufferDelay(0, (int) iotClient.clientData.commandTimeoutMs/2); + rc = aws_iot_mqtt_unsubscribe(&iotClient, subTopic, (uint16_t) strlen(subTopic)); + CHECK_EQUAL_C_INT(SUCCESS, rc); + } + + IOT_DEBUG("-->Success - D:9 - Unsubscribe, QoS1, half command timeout delayed unsuback, success \n"); +} + +/* D:10 - Unsubscribe, success, message on topic ignored + * 1. Subscribe to topic 1 + * 2. Send message and receive it + * 3. Unsubscribe to topic 1 + * 4. Should not receive message + */ +TEST_C(UnsubscribeTests, MsgAfterUnsubscribe) { + IoT_Error_t rc = SUCCESS; + char expectedCallbackString[100]; + + IOT_DEBUG("-->Running Unsubscribe Tests - D:10 - Unsubscribe, success, message on topic ignored \n"); + + // 1. + setTLSRxBufferForSuback("topic1", 6, QOS0, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, "topic1", 6, QOS0, iot_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + // 2. + snprintf(expectedCallbackString, 100, "Message for topic1"); + setTLSRxBufferWithMsgOnSubscribedTopic("topic1", 6, QOS1, testPubMsgParams, expectedCallbackString); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); + + //3. + setTLSRxBufferForUnsuback(); + rc = aws_iot_mqtt_unsubscribe(&iotClient, "topic1", 6); + CHECK_EQUAL_C_INT(SUCCESS, rc); + //reset the string + snprintf(CallbackMsgString, 100, " "); + + // 4. + // Have a new message published to that topic coming in + snprintf(expectedCallbackString, 100, "Message after unsubscribe"); + setTLSRxBufferWithMsgOnSubscribedTopic("topic1", 6, QOS0, testPubMsgParams, expectedCallbackString); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(SUCCESS, rc); + // No new msg was received + CHECK_EQUAL_C_STRING(" ", CallbackMsgString); + + IOT_DEBUG("-->Success - D:10 - Unsubscribe, success, message on topic ignored \n"); +} + +/* D:11 - Unsubscribe after max topics reached + * 1. Subscribe to max topics + 1 fail for last subscription + * 2. Unsubscribe from one topic + * 3. Subscribe again and should have no error + * 4. Receive msg test - last subscribed topic + */ +TEST_C(UnsubscribeTests, MaxTopicsSubscription) { + IoT_Error_t rc = SUCCESS; + int i = 0; + char topics[AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS + 1][10]; + char expectedCallbackString[] = "Message after subscribe - topic[i]"; + + IOT_DEBUG("-->Running Unsubscribe Tests - D:11 - Unsubscribe after max topics reached \n"); + + // 1. + for(i = 0; i < AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; i++) { + snprintf(topics[i], 10, "topic-%d", i); + setTLSRxBufferForSuback(topics[i], strlen(topics[i]), QOS0, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, topics[i], (uint16_t) strlen(topics[i]), QOS0, iot_subscribe_callback_handler, + NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + } + snprintf(topics[i], 10, "topic-%d", i); + setTLSRxBufferForSuback(topics[i], strlen(topics[i]), QOS0, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, topics[i], (uint16_t) strlen(topics[i]), QOS0, iot_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(MQTT_MAX_SUBSCRIPTIONS_REACHED_ERROR, rc); + + // 2. + setTLSRxBufferForUnsuback(); + rc = aws_iot_mqtt_unsubscribe(&iotClient, topics[i - 1], (uint16_t) strlen(topics[i - 1])); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + //3. + setTLSRxBufferForSuback(topics[i], strlen(topics[i]), QOS0, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, topics[i], (uint16_t) strlen(topics[i]), QOS0, iot_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + //4. + setTLSRxBufferWithMsgOnSubscribedTopic(topics[i], strlen(topics[i]), QOS1, testPubMsgParams, + expectedCallbackString); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); + + IOT_DEBUG("-->Success - D:11 - Unsubscribe after max topics reached \n"); +} + +/* D:12 - Repeated Subscribe and Unsubscribe + * 1. subscribe and unsubscribe for more than the max subscribed topic + * 2. ensure every time the subscribed topic msg is received + */ +TEST_C(UnsubscribeTests, RepeatedSubUnSub) { + IoT_Error_t rc = SUCCESS; + int i = 0; + char expectedCallbackString[100]; + char topics[3 * AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS][10]; + + IOT_DEBUG("-->Running Unsubscribe Tests - D:12 - Repeated Subscribe and Unsubscribe \n"); + + + for(i = 0; i < 3 * AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; i++) { + //1. + snprintf(topics[i], 10, "topic-%d", i); + setTLSRxBufferForSuback(topics[i], 10, QOS0, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, topics[i], 10, QOS0, iot_subscribe_callback_handler, NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + snprintf(expectedCallbackString, 10, "message##%d", i); + testPubMsgParams.payload = (void *) expectedCallbackString; + testPubMsgParams.payloadLen = strlen(expectedCallbackString); + setTLSRxBufferWithMsgOnSubscribedTopic(topics[i], strlen(topics[i]), QOS1, testPubMsgParams, + expectedCallbackString); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); + + //2. + setTLSRxBufferForUnsuback(); + rc = aws_iot_mqtt_unsubscribe(&iotClient, topics[i], (uint16_t) strlen(topics[i])); + CHECK_EQUAL_C_INT(SUCCESS, rc); + } + + IOT_DEBUG("-->Success - D:12 - Repeated Subscribe and Unsubscribe \n"); +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_yield.cpp b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_yield.cpp new file mode 100644 index 00000000..8eeb203f --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_yield.cpp @@ -0,0 +1,54 @@ +/* +* Copyright 2015-2016 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_tests_unit_yield.cpp + * @brief IoT Client Unit Testing - Yield API Tests + */ + +#include +#include + +TEST_GROUP_C(YieldTests){ + TEST_GROUP_C_SETUP_WRAPPER(YieldTests) + TEST_GROUP_C_TEARDOWN_WRAPPER(YieldTests) +}; + +/* G:1 - Yield with Null/empty Client Instance */ +TEST_GROUP_C_WRAPPER(YieldTests, NullClientYield) +/* G:2 - Yield with zero yield timeout */ +TEST_GROUP_C_WRAPPER(YieldTests, ZeroTimeoutYield) +/* G:3 - Yield, network disconnected, never connected */ +TEST_GROUP_C_WRAPPER(YieldTests, YieldNetworkDisconnectedNeverConnected) +/* G:4 - Yield, network disconnected, disconnected manually */ +TEST_GROUP_C_WRAPPER(YieldTests, YieldNetworkDisconnectedDisconnectedManually) +/* G:5 - Yield, network connected, yield called while in subscribe application callback */ +TEST_GROUP_C_WRAPPER(YieldTests, YieldInSubscribeCallback) +/* G:6 - Yield, network disconnected, ping timeout, auto-reconnect disabled */ +TEST_GROUP_C_WRAPPER(YieldTests, disconnectNoAutoReconnect) + +/* G:7 - Yield, network connected, no incoming messages */ +TEST_GROUP_C_WRAPPER(YieldTests, YieldSuccessNoMessages) +/* G:8 - Yield, network connected, ping request/response */ +TEST_GROUP_C_WRAPPER(YieldTests, PingRequestPingResponse) + +/* G:9 - Yield, disconnected, Auto-reconnect timed-out */ +TEST_GROUP_C_WRAPPER(YieldTests, disconnectAutoReconnectTimeout) +/* G:10 - Yield, disconnected, Auto-reconnect successful */ +TEST_GROUP_C_WRAPPER(YieldTests, disconnectAutoReconnectSuccess) +/* G:11 - Yield, disconnected, Manual reconnect */ +TEST_GROUP_C_WRAPPER(YieldTests, disconnectManualAutoReconnect) +/* G:12 - Yield, resubscribe to all topics on reconnect */ +TEST_GROUP_C_WRAPPER(YieldTests, resubscribeSuccessfulReconnect) diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_yield_helper.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_yield_helper.c new file mode 100644 index 00000000..ca0ea339 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_yield_helper.c @@ -0,0 +1,452 @@ +/* +* Copyright 2015-2016 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_tests_unit_yield_helper.c + * @brief IoT Client Unit Testing - Yield API Tests Helper + */ + +#include +#include +#include + +#include "aws_iot_tests_unit_helper_functions.h" +#include "aws_iot_tests_unit_mock_tls_params.h" +#include "aws_iot_log.h" + +static IoT_Client_Init_Params initParams; +static IoT_Client_Connect_Params connectParams; +static AWS_IoT_Client iotClient; +static IoT_Publish_Message_Params testPubMsgParams; + +static ConnectBufferProofread prfrdParams; +static char CallbackMsgString[100]; +static char subTopic[10] = "sdk/Test"; +static uint16_t subTopicLen = 8; + +static bool dcHandlerInvoked = false; + +static void iot_tests_unit_acr_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, + uint16_t topicNameLen, + IoT_Publish_Message_Params *params, void *pData) { + char *tmp = params->payload; + unsigned int i; + + IOT_UNUSED(pClient); + IOT_UNUSED(topicName); + IOT_UNUSED(topicNameLen); + IOT_UNUSED(pData); + + for(i = 0; i < params->payloadLen; i++) { + CallbackMsgString[i] = tmp[i]; + } +} + +static void iot_tests_unit_yield_test_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, + uint16_t topicNameLen, + IoT_Publish_Message_Params *params, void *pData) { + char *tmp = params->payload; + unsigned int i; + IoT_Error_t rc = SUCCESS; + + IOT_UNUSED(pClient); + IOT_UNUSED(topicName); + IOT_UNUSED(topicNameLen); + IOT_UNUSED(pData); + + rc = aws_iot_mqtt_yield(pClient, 1000); + CHECK_EQUAL_C_INT(MQTT_CLIENT_NOT_IDLE_ERROR, rc); + + for(i = 0; i < params->payloadLen; i++) { + CallbackMsgString[i] = tmp[i]; + } +} + +void iot_tests_unit_disconnect_handler(AWS_IoT_Client *pClient, void *disconParam) { + IOT_UNUSED(pClient); + IOT_UNUSED(disconParam); + dcHandlerInvoked = true; +} + + +TEST_GROUP_C_SETUP(YieldTests) { + IoT_Error_t rc = SUCCESS; + dcHandlerInvoked = false; + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, iot_tests_unit_disconnect_handler); + rc = aws_iot_mqtt_init(&iotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + + ConnectMQTTParamsSetup_Detailed(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID), + QOS1, false, true, "willTopicName", (uint16_t) strlen("willTopicName"), "willMsg", + (uint16_t) strlen("willMsg"), NULL, 0, NULL, 0); + connectParams.keepAliveIntervalInSec = 5; + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_connect(&iotClient, &connectParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + rc = aws_iot_mqtt_autoreconnect_set_status(&iotClient, false); + CHECK_EQUAL_C_INT(SUCCESS, rc); + ResetTLSBuffer(); +} + +TEST_GROUP_C_TEARDOWN(YieldTests) { + /* Clean up. Not checking return code here because this is common to all tests. + * A test might have already caused a disconnect by this point. + */ + IoT_Error_t rc = aws_iot_mqtt_disconnect(&iotClient); + IOT_UNUSED(rc); +} + +/* G:1 - Yield with Null/empty Client Instance */ +TEST_C(YieldTests, NullClientYield) { + IoT_Error_t rc = aws_iot_mqtt_yield(NULL, 1000); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} + +/* G:2 - Yield with zero yield timeout */ + +TEST_C(YieldTests, ZeroTimeoutYield) { + IoT_Error_t rc = aws_iot_mqtt_yield(&iotClient, 0); + CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); +} +/* G:3 - Yield, network disconnected, never connected */ + +TEST_C(YieldTests, YieldNetworkDisconnectedNeverConnected) { + AWS_IoT_Client tempIotClient; + IoT_Error_t rc; + + InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, iot_tests_unit_disconnect_handler); + rc = aws_iot_mqtt_init(&tempIotClient, &initParams); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + rc = aws_iot_mqtt_yield(&tempIotClient, 1000); + CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc); +} + +/* G:4 - Yield, network disconnected, disconnected manually */ +TEST_C(YieldTests, YieldNetworkDisconnectedDisconnectedManually) { + IoT_Error_t rc = aws_iot_mqtt_disconnect(&iotClient); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + rc = aws_iot_mqtt_yield(&iotClient, 1000); + CHECK_EQUAL_C_INT(NETWORK_MANUALLY_DISCONNECTED, rc); +} + +/* G:5 - Yield, network connected, yield called while in subscribe application callback */ +TEST_C(YieldTests, YieldInSubscribeCallback) { + IoT_Error_t rc = SUCCESS; + char expectedCallbackString[] = "0xA5A5A3"; + + IOT_DEBUG("-->Running Yield Tests - G:5 - Yield, network connected, yield called while in subscribe application callback \n"); + + setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS1, + iot_tests_unit_yield_test_subscribe_callback_handler, NULL); + if(SUCCESS == rc) { + setTLSRxBufferWithMsgOnSubscribedTopic(subTopic, subTopicLen, QOS1, testPubMsgParams, expectedCallbackString); + rc = aws_iot_mqtt_yield(&iotClient, 1000); + if(SUCCESS == rc) { + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); + } + CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePuback()); + } + + IOT_DEBUG("-->Success - G:5 - Yield, network connected, yield called while in subscribe application callback \n"); +} + +/* G:6 - Yield, network disconnected, ping timeout, auto-reconnect disabled */ +TEST_C(YieldTests, disconnectNoAutoReconnect) { + IoT_Error_t rc = FAILURE; + + IOT_DEBUG("-->Running Yield Tests - G:6 - Yield, network disconnected, ping timeout, auto-reconnect disabled \n"); + + rc = aws_iot_mqtt_autoreconnect_set_status(&iotClient, true); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + CHECK_EQUAL_C_INT(true, aws_iot_mqtt_is_client_connected(&iotClient)); + CHECK_EQUAL_C_INT(true, aws_iot_is_autoreconnect_enabled(&iotClient)); + + /* Disable Autoreconnect, then let ping request time out and call yield */ + aws_iot_mqtt_autoreconnect_set_status(&iotClient, false); + sleep((uint16_t)(iotClient.clientData.keepAliveInterval)); + + ResetTLSBuffer(); + + /* Sleep for keep alive interval to allow the first ping to be sent out */ + sleep(iotClient.clientData.keepAliveInterval); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(true, isLastTLSTxMessagePingreq()); + + /* Let ping request time out and call yield */ + sleep(iotClient.clientData.keepAliveInterval + 1); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc); + CHECK_EQUAL_C_INT(1, isLastTLSTxMessageDisconnect()); + CHECK_EQUAL_C_INT(0, aws_iot_mqtt_is_client_connected(&iotClient)); + CHECK_EQUAL_C_INT(true, dcHandlerInvoked); + + IOT_DEBUG("-->Success - G:6 - Yield, network disconnected, ping timeout, auto-reconnect disabled \n"); +} + +/* G:7 - Yield, network connected, no incoming messages */ +TEST_C(YieldTests, YieldSuccessNoMessages) { + IoT_Error_t rc; + int i; + + IOT_DEBUG("-->Running Yield Tests - G:7 - Yield, network connected, no incoming messages \n"); + + for(i = 0; i < 100; i++) { + CallbackMsgString[i] = 'x'; + } + + rc = aws_iot_mqtt_yield(&iotClient, 1000); + if(SUCCESS == rc) { + /* Check no messages were received */ + for(i = 0; i < 100; i++) { + if('x' != CallbackMsgString[i]) { + rc = FAILURE; + } + } + } + + CHECK_EQUAL_C_INT(SUCCESS, rc); + + IOT_DEBUG("-->Success - G:7 - Yield, network connected, no incoming messages \n"); +} + +/* G:8 - Yield, network connected, ping request/response */ +TEST_C(YieldTests, PingRequestPingResponse) { + IoT_Error_t rc = SUCCESS; + int i = 0; + int j = 0; + int attempt = 3; + + IOT_DEBUG("-->Running Yield Tests - G:8 - Yield, network connected, ping request/response \n"); + IOT_DEBUG("Current Keep Alive Interval is set to %d sec.\n", iotClient.clientData.keepAliveInterval); + + for(i = 0; i < attempt; i++) { + IOT_DEBUG("[Round_%d/Total_%d] Waiting for %d sec...\n", i + 1, attempt, iotClient.clientData.keepAliveInterval); + /* Set TLS buffer for ping response */ + ResetTLSBuffer(); + setTLSRxBufferForPingresp(); + + for(j = 0; j <= iotClient.clientData.keepAliveInterval; j++) { + sleep(1); + IOT_DEBUG("[Waited %d secs]", j + 1); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(SUCCESS, rc); + } + + /* Check whether ping was processed correctly and new Ping request was generated */ + CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePingreq()); + } + + IOT_DEBUG("-->Success - G:8 - Yield, network connected, ping request/response \n"); +} + +/* G:9 - Yield, disconnected, Auto-reconnect timed-out */ +TEST_C(YieldTests, disconnectAutoReconnectTimeout) { + IoT_Error_t rc = FAILURE; + + IOT_DEBUG("-->Running Yield Tests - G:9 - Yield, disconnected, Auto-reconnect timed-out \n"); + + rc = aws_iot_mqtt_autoreconnect_set_status(&iotClient, true); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + CHECK_EQUAL_C_INT(true, aws_iot_mqtt_is_client_connected(&iotClient)); + CHECK_EQUAL_C_INT(true, aws_iot_is_autoreconnect_enabled(&iotClient)); + + ResetTLSBuffer(); + + /* Sleep for keep alive interval to allow the first ping to be sent out */ + sleep(iotClient.clientData.keepAliveInterval); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(true, isLastTLSTxMessagePingreq()); + + /* Let ping request time out and call yield */ + sleep(iotClient.clientData.keepAliveInterval + 1); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(NETWORK_ATTEMPTING_RECONNECT, rc); + CHECK_EQUAL_C_INT(0, aws_iot_mqtt_is_client_connected(&iotClient)); + CHECK_EQUAL_C_INT(true, dcHandlerInvoked); + + IOT_DEBUG("-->Success - G:9 - Yield, disconnected, Auto-reconnect timed-out \n"); +} + +/* G:10 - Yield, disconnected, Auto-reconnect successful */ +TEST_C(YieldTests, disconnectAutoReconnectSuccess) { + IoT_Error_t rc = FAILURE; + unsigned char *currPayload = NULL; + + IOT_DEBUG("-->Running Yield Tests - G:10 - Yield, disconnected, Auto-reconnect successful \n"); + + rc = aws_iot_mqtt_autoreconnect_set_status(&iotClient, true); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + CHECK_EQUAL_C_INT(true, aws_iot_mqtt_is_client_connected(&iotClient)); + CHECK_EQUAL_C_INT(true, aws_iot_is_autoreconnect_enabled(&iotClient)); + + /* Sleep for keep alive interval to allow the first ping to be sent out */ + sleep(iotClient.clientData.keepAliveInterval); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(true, isLastTLSTxMessagePingreq()); + + /* Let ping request time out and call yield */ + sleep(iotClient.clientData.keepAliveInterval + 1); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(NETWORK_ATTEMPTING_RECONNECT, rc); + + sleep(2); /* Default min reconnect delay is 1 sec */ + printf("\nWakeup"); + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + currPayload = connectTxBufferHeaderParser(&prfrdParams, TxBuffer.pBuffer); + CHECK_C(true == isConnectTxBufFlagCorrect(&connectParams, &prfrdParams)); + CHECK_C(true == isConnectTxBufPayloadCorrect(&connectParams, currPayload)); + CHECK_EQUAL_C_INT(true, aws_iot_mqtt_is_client_connected(&iotClient)); + CHECK_EQUAL_C_INT(true, dcHandlerInvoked); + + IOT_DEBUG("-->Success - G:10 - Yield, disconnected, Auto-reconnect successful \n"); +} + +/* G:11 - Yield, disconnected, Manual reconnect */ +TEST_C(YieldTests, disconnectManualAutoReconnect) { + IoT_Error_t rc = FAILURE; + unsigned char *currPayload = NULL; + + IOT_DEBUG("-->Running Yield Tests - G:11 - Yield, disconnected, Manual reconnect \n"); + + CHECK_C(aws_iot_mqtt_is_client_connected(&iotClient)); + + /* Disable Autoreconnect, then let ping request time out and call yield */ + aws_iot_mqtt_autoreconnect_set_status(&iotClient, false); + CHECK_C(!aws_iot_is_autoreconnect_enabled(&iotClient)); + + /* Sleep for keep alive interval to allow the first ping to be sent out */ + sleep(iotClient.clientData.keepAliveInterval); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(true, isLastTLSTxMessagePingreq()); + + /* Let ping request time out and call yield */ + sleep(iotClient.clientData.keepAliveInterval + 1); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc); + CHECK_EQUAL_C_INT(1, isLastTLSTxMessageDisconnect()); + CHECK_C(!aws_iot_mqtt_is_client_connected(&iotClient)); + CHECK_EQUAL_C_INT(true, dcHandlerInvoked); + + dcHandlerInvoked = false; + setTLSRxBufferForConnack(&connectParams, 0, 0); + rc = aws_iot_mqtt_attempt_reconnect(&iotClient); + CHECK_EQUAL_C_INT(NETWORK_RECONNECTED, rc); + + currPayload = connectTxBufferHeaderParser(&prfrdParams, TxBuffer.pBuffer); + CHECK_C(true == isConnectTxBufFlagCorrect(&connectParams, &prfrdParams)); + CHECK_C(true == isConnectTxBufPayloadCorrect(&connectParams, currPayload)); + CHECK_C(aws_iot_mqtt_is_client_connected(&iotClient)); + CHECK_EQUAL_C_INT(false, dcHandlerInvoked); + + IOT_DEBUG("-->Success - G:11 - Yield, disconnected, Manual reconnect \n"); +} + +/* G:12 - Yield, resubscribe to all topics on reconnect */ +TEST_C(YieldTests, resubscribeSuccessfulReconnect) { + IoT_Error_t rc = FAILURE; + char cPayload[100]; + bool connected = false; + bool autoReconnectEnabled = false; + char expectedCallbackString[100]; + + IOT_DEBUG("-->Running Yield Tests - G:12 - Yield, resubscribe to all topics on reconnect \n"); + + rc = aws_iot_mqtt_autoreconnect_set_status(&iotClient, true); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + snprintf(CallbackMsgString, 100, "NOT_VISITED"); + + testPubMsgParams.qos = QOS1; + testPubMsgParams.isRetained = 0; + snprintf(cPayload, 100, "%s : %d ", "hello from SDK", 0); + testPubMsgParams.payload = (void *) cPayload; + testPubMsgParams.payloadLen = strlen(cPayload); + + connected = aws_iot_mqtt_is_client_connected(&iotClient); + CHECK_EQUAL_C_INT(1, connected); + + ResetTLSBuffer(); + + /* Subscribe to a topic */ + setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams); + rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS0, iot_tests_unit_acr_subscribe_callback_handler, + NULL); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + ResetTLSBuffer(); + + /* Check subscribe */ + snprintf(expectedCallbackString, 100, "Message for %s", subTopic); + setTLSRxBufferWithMsgOnSubscribedTopic(subTopic, subTopicLen, QOS1, testPubMsgParams, expectedCallbackString); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); + + ResetTLSBuffer(); + + autoReconnectEnabled = aws_iot_is_autoreconnect_enabled(&iotClient); + CHECK_EQUAL_C_INT(1, autoReconnectEnabled); + + /* Sleep for keep alive interval to allow the first ping to be sent out */ + sleep(iotClient.clientData.keepAliveInterval); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_INT(true, isLastTLSTxMessagePingreq()); + + /* Let ping request time out and call yield */ + sleep(iotClient.clientData.keepAliveInterval + 1); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(NETWORK_ATTEMPTING_RECONNECT, rc); + + sleep(2); /* Default min reconnect delay is 1 sec */ + + ResetTLSBuffer(); + setTLSRxBufferForConnackAndSuback(&connectParams, 0, subTopic, subTopicLen, QOS1); + + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(SUCCESS, rc); + + /* Test if reconnect worked */ + connected = aws_iot_mqtt_is_client_connected(&iotClient); + CHECK_EQUAL_C_INT(true, connected); + + ResetTLSBuffer(); + + /* Check subscribe */ + snprintf(expectedCallbackString, 100, "Message for %s after resub", subTopic); + setTLSRxBufferWithMsgOnSubscribedTopic(subTopic, subTopicLen, QOS1, testPubMsgParams, expectedCallbackString); + rc = aws_iot_mqtt_yield(&iotClient, 100); + CHECK_EQUAL_C_INT(SUCCESS, rc); + CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); + CHECK_EQUAL_C_INT(true, dcHandlerInvoked); + + IOT_DEBUG("-->Success - G:12 - Yield, resubscribe to all topics on reconnect \n"); +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/aws_iot_tests_unit_mock_tls.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/aws_iot_tests_unit_mock_tls.c new file mode 100644 index 00000000..f9a6cc71 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/aws_iot_tests_unit_mock_tls.c @@ -0,0 +1,149 @@ +#include +#include +#include + +#include "network_interface.h" +#include "aws_iot_tests_unit_mock_tls_params.h" + + +void _iot_tls_set_connect_params(Network *pNetwork, char *pRootCALocation, char *pDeviceCertLocation, + char *pDevicePrivateKeyLocation, 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, char *pRootCALocation, char *pDeviceCertLocation, + char *pDevicePrivateKeyLocation, 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; + + return SUCCESS; +} + +IoT_Error_t iot_tls_connect(Network *pNetwork, TLSConnectParams *params) { + IOT_UNUSED(pNetwork); + + if(NULL != params) { + _iot_tls_set_connect_params(pNetwork, params->pRootCALocation, params->pDeviceCertLocation, + params->pDevicePrivateKeyLocation, params->pDestinationURL, params->DestinationPort, + params->timeout_ms, params->ServerVerificationFlag); + } + + if(NULL != invalidEndpointFilter && 0 == strcmp(invalidEndpointFilter, pNetwork->tlsConnectParams.pDestinationURL)) { + return NETWORK_ERR_NET_UNKNOWN_HOST; + } + + if(invalidPortFilter == pNetwork->tlsConnectParams.DestinationPort) { + return NETWORK_ERR_NET_CONNECT_FAILED; + } + + if(NULL != invalidRootCAPathFilter && 0 == strcmp(invalidRootCAPathFilter, pNetwork->tlsConnectParams.pRootCALocation)) { + return NETWORK_ERR_NET_CONNECT_FAILED; + } + + if(NULL != invalidCertPathFilter && 0 == strcmp(invalidCertPathFilter, pNetwork->tlsConnectParams.pDeviceCertLocation)) { + return NETWORK_ERR_NET_CONNECT_FAILED; + } + + if(NULL != invalidPrivKeyPathFilter && 0 == strcmp(invalidPrivKeyPathFilter, pNetwork->tlsConnectParams.pDevicePrivateKeyLocation)) { + return NETWORK_ERR_NET_CONNECT_FAILED; + } + return SUCCESS; +} + +IoT_Error_t iot_tls_is_connected(Network *pNetwork) { + IOT_UNUSED(pNetwork); + + /* Use this to add implementation which can check for physical layer disconnect */ + return NETWORK_PHYSICAL_LAYER_CONNECTED; +} + +IoT_Error_t iot_tls_write(Network *pNetwork, unsigned char *pMsg, size_t len, Timer *timer, size_t *written_len) { + size_t i = 0; + uint8_t firstByte, secondByte; + uint16_t topicNameLen; + IOT_UNUSED(pNetwork); + IOT_UNUSED(timer); + + for(i = 0; (i < len) && left_ms(timer) > 0; i++) { + TxBuffer.pBuffer[i] = pMsg[i]; + } + TxBuffer.len = len; + *written_len = len; + + /* Save last two subscribed topics */ + if((TxBuffer.pBuffer[0] == 0x82 ? true : false)) { + snprintf(SecondLastSubscribeMessage, lastSubscribeMsgLen, "%s", LastSubscribeMessage); + secondLastSubscribeMsgLen = lastSubscribeMsgLen; + + firstByte = (uint8_t)(TxBuffer.pBuffer[4]); + secondByte = (uint8_t)(TxBuffer.pBuffer[5]); + topicNameLen = (uint16_t) (secondByte + (256 * firstByte)); + + snprintf(LastSubscribeMessage, topicNameLen + 1u, "%s", &(TxBuffer.pBuffer[6])); // Added one for null character + lastSubscribeMsgLen = topicNameLen + 1u; + } + + return SUCCESS; +} + +static unsigned char isTimerExpired(struct timeval target_time) { + unsigned char ret_val = 0; + struct timeval now, result; + + if(target_time.tv_sec != 0 || target_time.tv_usec != 0) { + gettimeofday(&now, NULL); + timersub(&(target_time), &now, &result); + if(result.tv_sec < 0 || (result.tv_sec == 0 && result.tv_usec <= 0)) { + ret_val = 1; + } + } else { + ret_val = 1; + } + return ret_val; +} + +IoT_Error_t iot_tls_read(Network *pNetwork, unsigned char *pMsg, size_t len, Timer *pTimer, size_t *read_len) { + IOT_UNUSED(pNetwork); + IOT_UNUSED(pTimer); + + if(RxIndex > TLSMaxBufferSize - 1) { + RxIndex = TLSMaxBufferSize - 1; + } + + if(RxBuffer.len <= RxIndex || !isTimerExpired(RxBuffer.expiry_time)) { + return NETWORK_SSL_NOTHING_TO_READ; + } + + if((false == RxBuffer.NoMsgFlag) && (RxIndex < RxBuffer.len)) { + memcpy(pMsg, &(RxBuffer.pBuffer[RxIndex]), len); + RxIndex += len; + *read_len = len; + } + + return SUCCESS; +} + +IoT_Error_t iot_tls_disconnect(Network *pNetwork) { + IOT_UNUSED(pNetwork); + return SUCCESS; +} + +IoT_Error_t iot_tls_destroy(Network *pNetwork) { + IOT_UNUSED(pNetwork); + return SUCCESS; +} diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/aws_iot_tests_unit_mock_tls_params.c b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/aws_iot_tests_unit_mock_tls_params.c new file mode 100644 index 00000000..efe85506 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/aws_iot_tests_unit_mock_tls_params.c @@ -0,0 +1,39 @@ +/* +* Copyright 2015-2016 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_tests_unit_mock_tls_params.c + * @brief IoT Client Unit Testing Mock TLS Params + */ + +#include "aws_iot_tests_unit_mock_tls_params.h" + +unsigned char RxBuf[TLSMaxBufferSize]; +unsigned char TxBuf[TLSMaxBufferSize]; +char LastSubscribeMessage[TLSMaxBufferSize]; +size_t lastSubscribeMsgLen; +char SecondLastSubscribeMessage[TLSMaxBufferSize]; +size_t secondLastSubscribeMsgLen; + +TlsBuffer RxBuffer = {.pBuffer = RxBuf,.len = 512, .NoMsgFlag=1, .expiry_time = {0, 0}, .BufMaxSize = TLSMaxBufferSize}; +TlsBuffer TxBuffer = {.pBuffer = TxBuf,.len = 512, .NoMsgFlag=1, .expiry_time = {0, 0}, .BufMaxSize = TLSMaxBufferSize}; + +size_t RxIndex = 0; + +char *invalidEndpointFilter; +char *invalidRootCAPathFilter; +char *invalidCertPathFilter; +char *invalidPrivKeyPathFilter; +uint16_t invalidPortFilter; diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/aws_iot_tests_unit_mock_tls_params.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/aws_iot_tests_unit_mock_tls_params.h new file mode 100644 index 00000000..22a9ead5 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/aws_iot_tests_unit_mock_tls_params.h @@ -0,0 +1,62 @@ +/* +* Copyright 2015-2016 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_tests_unit_mock_tls_params.h + * @brief IoT Client Unit Testing Mock TLS Params + */ + +#ifndef UNITTESTS_MOCKS_TLS_PARAMS_H_ +#define UNITTESTS_MOCKS_TLS_PARAMS_H_ + +#include +#include +#include +#include + +#define TLSMaxBufferSize 1024 +#define NO_MSG_LENGTH_MENTIONED -1 + +typedef struct { + unsigned char *pBuffer; + size_t len; + bool NoMsgFlag; + struct timeval expiry_time; + size_t BufMaxSize; +} TlsBuffer; + + +extern TlsBuffer RxBuffer; +extern TlsBuffer TxBuffer; + +extern size_t RxIndex; +extern unsigned char RxBuf[TLSMaxBufferSize]; +extern unsigned char TxBuf[TLSMaxBufferSize]; +extern char LastSubscribeMessage[TLSMaxBufferSize]; +extern size_t lastSubscribeMsgLen; +extern char SecondLastSubscribeMessage[TLSMaxBufferSize]; +extern size_t secondLastSubscribeMsgLen; + +extern char hostAddress[512]; +extern uint16_t port; +extern uint32_t handshakeTimeout_ms; + +extern char *invalidEndpointFilter; +extern char *invalidRootCAPathFilter; +extern char *invalidCertPathFilter; +extern char *invalidPrivKeyPathFilter; +extern uint16_t invalidPortFilter; + +#endif /* UNITTESTS_MOCKS_TLS_PARAMS_H_ */ diff --git a/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/network_platform.h b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/network_platform.h new file mode 100644 index 00000000..1bbec842 --- /dev/null +++ b/components/aws_iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/network_platform.h @@ -0,0 +1,19 @@ +// +// Created by chaurah on 3/22/16. +// + +#ifndef IOTSDKC_NETWORK_MBEDTLS_PLATFORM_H_H + +/** + * @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 { + uint32_t flags; +}TLSDataParams; + +#define IOTSDKC_NETWORK_MBEDTLS_PLATFORM_H_H + +#endif //IOTSDKC_NETWORK_MBEDTLS_PLATFORM_H_H diff --git a/components/aws_iot/component.mk b/components/aws_iot/component.mk new file mode 100644 index 00000000..cd1b15ee --- /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 00000000..c98f7dea --- /dev/null +++ b/components/aws_iot/include/aws_iot_config.h @@ -0,0 +1,65 @@ +/* + * 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 CONFIG_AWS_IOT_MQTT_TX_BUF_LEN ///< 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 CONFIG_AWS_IOT_MQTT_RX_BUF_LEN ///< 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 CONFIG_AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS ///< 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 +#ifdef CONFIG_AWS_IOT_OVERRIDE_THING_SHADOW_RX_BUFFER +#define SHADOW_MAX_SIZE_OF_RX_BUFFER CONFIG_AWS_IOT_SHADOW_MAX_SIZE_OF_RX_BUFFER ///< Maximum size of the SHADOW buffer to store the received Shadow message, including NULL terminating byte +#else +#define SHADOW_MAX_SIZE_OF_RX_BUFFER (AWS_IOT_MQTT_RX_BUF_LEN + 1) +#endif + +#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 CONFIG_AWS_IOT_SHADOW_MAX_SIMULTANEOUS_ACKS ///< 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 CONFIG_AWS_IOT_SHADOW_MAX_SIMULTANEOUS_THINGNAMES ///< 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 CONFIG_AWS_IOT_SHADOW_MAX_JSON_TOKEN_EXPECTED ///< 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 CONFIG_AWS_IOT_SHADOW_MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME ///< 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 CONFIG_AWS_IOT_SHADOW_MAX_SIZE_OF_THING_NAME ///< 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 CONFIG_AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL ///< 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 CONFIG_AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL ///< 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 00000000..9a2043b3 --- /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 00000000..a5e87d71 --- /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_sockets.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 00000000..011a1a0b --- /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 00000000..07e7385d --- /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 00000000..6da6d5da --- /dev/null +++ b/components/aws_iot/port/network_mbedtls_wrapper.c @@ -0,0 +1,417 @@ +/* + * 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); + + /* Use the AWS IoT ALPN extension for MQTT, if port 443 is requested */ + if (pNetwork->tlsConnectParams.DestinationPort == 443) { + const char *alpnProtocols[] = { "x-amzn-mqtt-ca", NULL }; + if ((ret = mbedtls_ssl_conf_alpn_protocols(&(tlsDataParams->conf), alpnProtocols)) != 0) { + ESP_LOGE(TAG, "failed! mbedtls_ssl_conf_alpn_protocols returned -0x%x", -ret); + return SSL_CONNECTION_ERROR; + } + } + + 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 00000000..065ead78 --- /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 00000000..ee4d8b5b --- /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