From: Shinkyu Park Date: Fri, 30 Jun 2017 01:24:32 +0000 (+0900) Subject: Add AWS IoT device SDK X-Git-Tag: 1.1_Public_Release~468^2~2 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=3fe11a5d6f64ffee6f42ee75cfeb78a982ab9d56;p=rtos%2Ftinyara.git Add AWS IoT device SDK Add AWS IoT device SDK on external/aws --- diff --git a/external/Kconfig b/external/Kconfig index 78c72c3..1fcb639 100644 --- a/external/Kconfig +++ b/external/Kconfig @@ -170,3 +170,10 @@ config LIBTUV default n ---help--- enable libtuv + +config AWS_SDK + bool "AWS IoT SDK" + default n + ---help--- + enable AWS IoT Device SDK + diff --git a/external/Makefile b/external/Makefile index addacd5..812dfe7 100644 --- a/external/Makefile +++ b/external/Makefile @@ -70,15 +70,21 @@ include libtuv/source/unix/Make.defs include libtuv/source/Make.defs endif +ifeq ($(CONFIG_AWS_SDK),y) +include aws/Make.defs +include aws/src/Make.defs +endif + ifeq ($(CONFIG_DM),y) CFLAGS+=-I$(TOPDIR)/../framework/include/dm endif AOBJS = $(ASRCS:.S=$(OBJEXT)) COBJS = $(CSRCS:.c=$(OBJEXT)) +CXXOBJS = $(CXXSRCS:.cpp=$(OBJEXT)) -SRCS = $(ASRCS) $(CSRCS) -OBJS = $(AOBJS) $(COBJS) +SRCS = $(ASRCS) $(CSRCS) $(CXXSRCS) +OBJS = $(AOBJS) $(COBJS) $(CXXOBJS) BIN = libexternal$(LIBEXT) @@ -90,6 +96,9 @@ $(AOBJS): %$(OBJEXT): %.S $(COBJS): %$(OBJEXT): %.c $(call COMPILE, $<, $@) +$(CXXOBJS): %$(OBJEXT): %.cpp + $(call COMPILEXX, $<, $@) + iotivity_build: ifeq ($(CONFIG_ENABLE_IOTIVITY),y) touch $(IOTIVITY_BASE_DIR)/iotivity.built @@ -105,7 +114,9 @@ $(BIN): $(OBJS) iotivity_build $(call ARCHIVE, $@, $(OBJS)) .depend: Makefile $(SRCS) - $(Q) $(MKDEP) $(DEPPATH) "$(CC)" -- $(CFLAGS) -- $(SRCS) >Make.dep + $(Q) $(MKDEP) $(DEPPATH) "$(CC)" -- $(CFLAGS) -- $(ASRCS) >Make.dep + $(Q) $(MKDEP) $(DEPPATH) "$(CC)" -- $(CFLAGS) -- $(CSRCS) >Make.dep + $(Q) $(MKDEP) $(DEPPATH) "$(CXX)" -- $(CXXFLAGS) -- $(CXXSRCS) >Make.dep $(Q) touch $@ depend: .depend diff --git a/external/aws/CHANGELOG.md b/external/aws/CHANGELOG.md new file mode 100644 index 0000000..f8acdf8 --- /dev/null +++ b/external/aws/CHANGELOG.md @@ -0,0 +1,145 @@ +#Change Log +## [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/external/aws/CppUTestMakefileWorker.mk b/external/aws/CppUTestMakefileWorker.mk new file mode 100644 index 0000000..9f3c305 --- /dev/null +++ b/external/aws/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/external/aws/LICENSE.txt b/external/aws/LICENSE.txt new file mode 100644 index 0000000..1b6cbea --- /dev/null +++ b/external/aws/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/external/aws/Make.defs b/external/aws/Make.defs new file mode 100644 index 0000000..1c8c2cb --- /dev/null +++ b/external/aws/Make.defs @@ -0,0 +1,49 @@ +AWS_SAMPLE_DIR=aws/samples/TizenRT +AWS_CERT_DIR=aws/certs +AWS_PLATFORM_DIR=aws/platform/TizenRT + +CSRCS += $(AWS_SAMPLE_DIR)/subscribe_publish_sample/subscribe_publish_sample.c \ + $(AWS_SAMPLE_DIR)/subscribe_publish_library_sample/subscribe_publish_library_sample.c \ + $(AWS_SAMPLE_DIR)/shadow_sample_console_echo/shadow_console_echo.c \ + $(AWS_SAMPLE_DIR)/shadow_sample/shadow_sample.c +CSRCS += $(AWS_PLATFORM_DIR)/mbedtls/network_mbedtls_wrapper.c +CSRCS += $(AWS_PLATFORM_DIR)/common/timer.c +CSRCS += $(AWS_CERT_DIR)/certData.c +CSRCS += aws/external_libs/jsmn/jsmn.c + + +CXXSRCS += $(AWS_SAMPLE_DIR)/subscribe_publish_cpp_sample/subscribe_publish_cpp_sample.cpp + +CXXOBJS = $(CXXSRCS:.cpp=$(OBJEXT)) + +SRCS += $(CXXSRCS) + +OBJS += $(CXXOBJS) + +CFLAGS += -I$(TOPDIR)/include +CFLAGS += -Iaws/include +CFLAGS += -Iaws/external_libs/jsmn +CFLAGS += -I$(AWS_PLATFORM_DIR)/common +CFLAGS += -I$(AWS_CERT_DIR) +CFLAGS += -I$(AWS_PLATFORM_DIR)/mbedtls +CFLAGS += -I$(AWS_SAMPLE_DIR)/subscribe_publish_sample +CFLAGS += -I$(AWS_SAMPLE_DIR)/subscribe_publish_library_sample +CFLAGS += -I$(AWS_SAMPLE_DIR)/subscribe_publish_cpp_sample +CFLAGS += -I$(AWS_SAMPLE_DIR)/shadow_console_echo +CFLAGS += -I$(AWS_SAMPLE_DIR)/shadow_sample + +# Enable AWS IoT Debugging Messages +#CFLAGS += -DENABLE_IOT_TRACE +#CFLAGS += -DENABLE_IOT_DEBUG +CFLAGS += -DENABLE_IOT_INFO +CFLAGS += -DENABLE_IOT_ERROR + +CXXFLAGS += -Iaws/include +CXXFLAGS += -Iaws/external_libs/jsmn +CXXFLAGS += -I$(AWS_PLATFORM_DIR)/common +CXXFLAGS += -I$(AWS_CERT_DIR) +CXXFLAGS += -I$(AWS_PLATFORM_DIR)/mbedtls +CXXFLAGS += -I$(AWS_SAMPLE_DIR)/subscribe_publish_cpp_sample + +DEPPATH += --dep-path aws +VPATH += :aws diff --git a/external/aws/Makefile b/external/aws/Makefile new file mode 100644 index 0000000..eebdb17 --- /dev/null +++ b/external/aws/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/external/aws/NOTICE.txt b/external/aws/NOTICE.txt new file mode 100644 index 0000000..c3f856f --- /dev/null +++ b/external/aws/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/external/aws/PortingGuide.md b/external/aws/PortingGuide.md new file mode 100644 index 0000000..ab393a2 --- /dev/null +++ b/external/aws/PortingGuide.md @@ -0,0 +1,150 @@ +#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 SDK ported for linux can be downloaded from the below link: + * [mbedTLS from ARM](https://s3.amazonaws.com/aws-iot-device-sdk-embedded-c/linux_mqtt_mbedtls-2.0.0.tar) + +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, char *pDeviceCertLocation, + char *pDevicePrivateKeyLocation, 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/external/aws/README.md b/external/aws/README.md new file mode 100644 index 0000000..5c2429c --- /dev/null +++ b/external/aws/README.md @@ -0,0 +1,110 @@ +## 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) + +## 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*. The tarball can be downloaded from the below link: + +* [mbedTLS from ARM](https://s3.amazonaws.com/aws-iot-device-sdk-embedded-c/linux_mqtt_mbedtls-2.1.1.tar) + +## 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/external/aws/certs/README.txt b/external/aws/certs/README.txt new file mode 100644 index 0000000..8df3d02 --- /dev/null +++ b/external/aws/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/external/aws/certs/certData.c b/external/aws/certs/certData.c new file mode 100644 index 0000000..0dc1eb4 --- /dev/null +++ b/external/aws/certs/certData.c @@ -0,0 +1,44 @@ + +/* + * USER STEP: Copy the whole lines in the root CA certificate file + * + * Paste the lines in string format for the following array: + */ +const unsigned char root_ca_pem[] = +"-----BEGIN CERTIFICATE-----\r\n" +"MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB\r\n" +"ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp\r\n" +"..." +"..." +"hnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq\r\n" +"-----END CERTIFICATE-----\r\n"; + +const int rootCaLen = sizeof(root_ca_pem); + +/* + * USER STEP: Copy the whole lines in the cert.pem certificate file between + * + * Paste the lines in string format for the following array: + */ +const unsigned char client_cert_pem[] = +"-----BEGIN CERTIFICATE-----\r\n" +"MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB\r\n" +"..." +"..." +"mwMi4q9hN6MT9FGa0R0KwmD9y+o11yCbrNBbP0Gud/7m/y4r+09By8xr68Lz\r\n" +"-----END CERTIFICATE-----\r\n"; +const int clientCertLen = sizeof(client_cert_pem); + +/* + * USER STEP: Copy the whole lines in the privateKey.pem certificate file between + * + * Paste the lines in string format for the following array: + */ +const unsigned char client_private_key_pem[] = +"-----BEGIN RSA PRIVATE KEY-----\r\n" +"MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB\r\n" +"..." +"..." +"9bc8aGVeZ+mD3SYYJamB77XqH2kcCd5Axc2EckdL9ansf+S9v1FP\r\n" +"-----END RSA PRIVATE KEY-----\r\n"; +const int clientPrivateKeyLen = sizeof(client_private_key_pem); diff --git a/external/aws/certs/certData.h b/external/aws/certs/certData.h new file mode 100644 index 0000000..f19af85 --- /dev/null +++ b/external/aws/certs/certData.h @@ -0,0 +1,13 @@ +#ifndef __CERTDATA_H__ +#define __CERTDATA_H__ + +extern unsigned const char root_ca_pem[]; +extern const int rootCaLen; + +extern unsigned const char client_cert_pem[]; +extern const int clientCertLen; + +extern unsigned const char client_private_key_pem[]; +extern const int clientPrivateKeyLen; + +#endif /* __CERTDATA_H__ */ diff --git a/external/aws/external_libs/CppUTest/README.txt b/external/aws/external_libs/CppUTest/README.txt new file mode 100644 index 0000000..5b2e092 --- /dev/null +++ b/external/aws/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/external/aws/external_libs/jsmn/jsmn.c b/external/aws/external_libs/jsmn/jsmn.c new file mode 100644 index 0000000..ea82be3 --- /dev/null +++ b/external/aws/external_libs/jsmn/jsmn.c @@ -0,0 +1,341 @@ +/* + * 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) { + 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/external/aws/external_libs/jsmn/jsmn.h b/external/aws/external_libs/jsmn/jsmn.h new file mode 100644 index 0000000..1df808e --- /dev/null +++ b/external/aws/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. + * @param type type (object, array, string etc.) + * @param start start position in JSON data string + * @param 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/external/aws/external_libs/mbedTLS/README.txt b/external/aws/external_libs/mbedTLS/README.txt new file mode 100644 index 0000000..30e2e56 --- /dev/null +++ b/external/aws/external_libs/mbedTLS/README.txt @@ -0,0 +1,2 @@ +# Copy source code for mbedTLS into this directory +# The SDK was tested internally with mbedTLS v2.1.1 which can be found here - https://github.com/ARMmbed/mbedtls/releases/tag/mbedtls-2.1.1 \ No newline at end of file diff --git a/external/aws/filterGcov.sh b/external/aws/filterGcov.sh new file mode 100644 index 0000000..fee4a03 --- /dev/null +++ b/external/aws/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/external/aws/include/aws_iot_error.h b/external/aws/include/aws_iot_error.h new file mode 100644 index 0000000..03f297b --- /dev/null +++ b/external/aws/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/external/aws/include/aws_iot_json_utils.h b/external/aws/include/aws_iot_json_utils.h new file mode 100644 index 0000000..ceb02b3 --- /dev/null +++ b/external/aws/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/external/aws/include/aws_iot_log.h b/external/aws/include/aws_iot_log.h new file mode 100644 index 0000000..60c2608 --- /dev/null +++ b/external/aws/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/external/aws/include/aws_iot_mqtt_client.h b/external/aws/include/aws_iot_mqtt_client.h new file mode 100644 index 0000000..32e1481 --- /dev/null +++ b/external/aws/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 + 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 + char *pRootCALocation; ///< Pointer to a string defining the Root CA file (full file, not path) + char *pDeviceCertLocation; ///< Pointer to a string defining the device identity certificate file (full file, not path) + 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, 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/external/aws/include/aws_iot_mqtt_client_common_internal.h b/external/aws/include/aws_iot_mqtt_client_common_internal.h new file mode 100644 index 0000000..4ee1b2e --- /dev/null +++ b/external/aws/include/aws_iot_mqtt_client_common_internal.h @@ -0,0 +1,142 @@ +/* +* 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_log.h" +#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; + +/** + * Bitfields for the MQTT header byte. + */ +typedef union { + unsigned char byte; /**< the whole byte */ +#if defined(REVERSED) + struct { + unsigned int type : 4; /**< message type nibble */ + unsigned int dup : 1; /**< DUP flag bit */ + unsigned int qos : 2; /**< QoS value, 0, 1 or 2 */ + unsigned int retain : 1; /**< retained flag bit */ + } bits; +#else + struct { + unsigned int retain : 1; /**< retained flag bit */ + unsigned int qos : 2; /**< QoS value, 0, 1 or 2 */ + unsigned int dup : 1; /**< DUP flag bit */ + unsigned int type : 4; /**< message type nibble */ + } bits; +#endif +} 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/external/aws/include/aws_iot_mqtt_client_interface.h b/external/aws/include/aws_iot_mqtt_client_interface.h new file mode 100644 index 0000000..6e5531f --- /dev/null +++ b/external/aws/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, 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, 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/external/aws/include/aws_iot_shadow_actions.h b/external/aws/include/aws_iot_shadow_actions.h new file mode 100644 index 0000000..a5f8755 --- /dev/null +++ b/external/aws/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/external/aws/include/aws_iot_shadow_interface.h b/external/aws/include/aws_iot_shadow_interface.h new file mode 100644 index 0000000..15c9bd2 --- /dev/null +++ b/external/aws/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 + char *pRootCA; ///< Location with the Filename of the Root CA + char *pClientCRT; ///< Location of Device certs signed by AWS IoT service + 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 { + char *pMyThingName; ///< Every device has a Thing Shadow and this is the placeholder for name + 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, 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, 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/external/aws/include/aws_iot_shadow_json.h b/external/aws/include/aws_iot_shadow_json.h new file mode 100644 index 0000000..a84713e --- /dev/null +++ b/external/aws/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/external/aws/include/aws_iot_shadow_json_data.h b/external/aws/include/aws_iot_shadow_json_data.h new file mode 100644 index 0000000..deaf9a1 --- /dev/null +++ b/external/aws/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/external/aws/include/aws_iot_shadow_key.h b/external/aws/include/aws_iot_shadow_key.h new file mode 100644 index 0000000..075a726 --- /dev/null +++ b/external/aws/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/external/aws/include/aws_iot_shadow_records.h b/external/aws/include/aws_iot_shadow_records.h new file mode 100644 index 0000000..fc2de03 --- /dev/null +++ b/external/aws/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/external/aws/include/aws_iot_version.h b/external/aws/include/aws_iot_version.h new file mode 100644 index 0000000..832fcf4 --- /dev/null +++ b/external/aws/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 1 +/** + * @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/external/aws/include/network_interface.h b/external/aws/include/network_interface.h new file mode 100644 index 0000000..cf28341 --- /dev/null +++ b/external/aws/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 { + char *pRootCALocation; ///< Pointer to string containing the filename (including path) of the root CA file. + char *pDeviceCertLocation; ///< Pointer to string containing the filename (including path) of the device certificate. + char *pDevicePrivateKeyLocation; ///< Pointer to string containing the filename (including path) of the device private key file. + 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, char *pRootCALocation, char *pDeviceCertLocation, + char *pDevicePrivateKeyLocation, 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/external/aws/include/threads_interface.h b/external/aws/include/threads_interface.h new file mode 100644 index 0000000..b4bc370 --- /dev/null +++ b/external/aws/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/external/aws/include/timer_interface.h b/external/aws/include/timer_interface.h new file mode 100644 index 0000000..0bef0fc --- /dev/null +++ b/external/aws/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/external/aws/platform/TizenRT/common/timer.c b/external/aws/platform/TizenRT/common/timer.c new file mode 100644 index 0000000..379dedd --- /dev/null +++ b/external/aws/platform/TizenRT/common/timer.c @@ -0,0 +1,75 @@ +/* + * 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 +#include "timer_platform.h" + +bool has_timer_expired(Timer *timer) { + struct timeval now, res; + gettimeofday(&now, NULL); + timersub(&timer->end_time, &now, &res); + return (int)(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( (int)(res.tv_sec) >= 0 ) { + result_ms = (uint32_t) ((int)(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/external/aws/platform/TizenRT/common/timer_platform.h b/external/aws/platform/TizenRT/common/timer_platform.h new file mode 100644 index 0000000..8c9f2a9 --- /dev/null +++ b/external/aws/platform/TizenRT/common/timer_platform.h @@ -0,0 +1,70 @@ +/* + * 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; +}; + +/* Convenience macros for operations on timevals. + * NOTE: `timercmp' does not work for >= or <=. */ +#define timerisset(tvp) ((tvp)->tv_sec || (tvp)->tv_usec) +#define timerclear(tvp) ((tvp)->tv_sec = (tvp)->tv_usec = 0) +#define timercmp(a, b, CMP) \ + (((a)->tv_sec == (b)->tv_sec) ? \ + ((a)->tv_usec CMP (b)->tv_usec) : \ + ((a)->tv_sec CMP (b)->tv_sec)) +#define timeradd(a, b, result) \ + do { \ + (result)->tv_sec = (a)->tv_sec + (b)->tv_sec; \ + (result)->tv_usec = (a)->tv_usec + (b)->tv_usec; \ + if ((result)->tv_usec >= 1000000) \ + { \ + ++(result)->tv_sec; \ + (result)->tv_usec -= 1000000; \ + } \ + } while (0) + +#define timersub(a, b, result) \ + do { \ + (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ + (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ + if ((result)->tv_usec < 0) { \ + --(result)->tv_sec; \ + (result)->tv_usec += 1000000; \ + } \ + } while (0) + +#ifdef __cplusplus +} +#endif + +#endif /* SRC_PROTOCOL_MQTT_AWS_IOT_EMBEDDED_CLIENT_WRAPPER_PLATFORM_LINUX_COMMON_TIMER_PLATFORM_H_ */ diff --git a/external/aws/platform/TizenRT/mbedtls/network_mbedtls_wrapper.c b/external/aws/platform/TizenRT/mbedtls/network_mbedtls_wrapper.c new file mode 100644 index 0000000..59ad35d --- /dev/null +++ b/external/aws/platform/TizenRT/mbedtls/network_mbedtls_wrapper.c @@ -0,0 +1,373 @@ +/* + * 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" +#include "certData.h" + +/* 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 + */ + +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 IOT_DEBUG + unsigned char buf[MBEDTLS_SSL_MAX_CONTENT_LEN + 1]; +#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 ..."); +// CA root certificate +//ret = mbedtls_x509_crt_parse_file(&(tlsDataParams->cacert), pNetwork->tlsConnectParams.pRootCALocation); +//IOT_DEBUG("[rootCaLen]: %d \n", rootCaLen); + ret = mbedtls_x509_crt_parse(&(tlsDataParams->cacert), root_ca_pem, rootCaLen); + + 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..."); +// Client cert. +// ret = mbedtls_x509_crt_parse_file(&(tlsDataParams->clicert), pNetwork->tlsConnectParams.pDeviceCertLocation); + ret = mbedtls_x509_crt_parse(&(tlsDataParams->clicert), client_cert_pem, clientCertLen); + 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; + } +// PrivateKeyLoc. +// ret = mbedtls_pk_parse_keyfile(&(tlsDataParams->pkey), pNetwork->tlsConnectParams.pDevicePrivateKeyLocation, ""); + ret = mbedtls_pk_parse_key(&(tlsDataParams->pkey), client_private_key_pem, clientPrivateKeyLen, NULL, 0); + 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 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 = 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) { + 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/external/aws/platform/TizenRT/mbedtls/network_platform.h b/external/aws/platform/TizenRT/mbedtls/network_platform.h new file mode 100644 index 0000000..b6f7e4c --- /dev/null +++ b/external/aws/platform/TizenRT/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 "tls/config.h" + +#include "tls/platform.h" +#include "tls/net.h" +#include "tls/ssl.h" +#include "tls/entropy.h" +#include "tls/ctr_drbg.h" +#include "tls/certs.h" +#include "tls/x509.h" +#include "tls/error.h" +#include "tls/debug.h" +#include "tls/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/external/aws/platform/TizenRT/pthread/threads_platform.h b/external/aws/platform/TizenRT/pthread/threads_platform.h new file mode 100644 index 0000000..8a520c6 --- /dev/null +++ b/external/aws/platform/TizenRT/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/external/aws/platform/TizenRT/pthread/threads_pthread_wrapper.c b/external/aws/platform/TizenRT/pthread/threads_pthread_wrapper.c new file mode 100644 index 0000000..65a310f --- /dev/null +++ b/external/aws/platform/TizenRT/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/external/aws/samples/README.md b/external/aws/samples/README.md new file mode 100644 index 0000000..7ac0fa5 --- /dev/null +++ b/external/aws/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/external/aws/samples/TizenRT/shadow_sample/Makefile b/external/aws/samples/TizenRT/shadow_sample/Makefile new file mode 100644 index 0000000..6199b04 --- /dev/null +++ b/external/aws/samples/TizenRT/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/external/aws/samples/TizenRT/shadow_sample/aws_iot_config.h b/external/aws/samples/TizenRT/shadow_sample/aws_iot_config.h new file mode 100644 index 0000000..252c384 --- /dev/null +++ b/external/aws/samples/TizenRT/shadow_sample/aws_iot_config.h @@ -0,0 +1,56 @@ +/* + * 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 +#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. + +#endif /* SRC_SHADOW_IOT_SHADOW_CONFIG_H_ */ diff --git a/external/aws/samples/TizenRT/shadow_sample/shadow_sample.c b/external/aws/samples/TizenRT/shadow_sample/shadow_sample.c new file mode 100644 index 0000000..56a1f76 --- /dev/null +++ b/external/aws/samples/TizenRT/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)); + } +} + +static 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 aws_shadow(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/external/aws/samples/TizenRT/shadow_sample_console_echo/Makefile b/external/aws/samples/TizenRT/shadow_sample_console_echo/Makefile new file mode 100644 index 0000000..8447901 --- /dev/null +++ b/external/aws/samples/TizenRT/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/external/aws/samples/TizenRT/shadow_sample_console_echo/aws_iot_config.h b/external/aws/samples/TizenRT/shadow_sample_console_echo/aws_iot_config.h new file mode 100644 index 0000000..252c384 --- /dev/null +++ b/external/aws/samples/TizenRT/shadow_sample_console_echo/aws_iot_config.h @@ -0,0 +1,56 @@ +/* + * 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 +#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. + +#endif /* SRC_SHADOW_IOT_SHADOW_CONFIG_H_ */ diff --git a/external/aws/samples/TizenRT/shadow_sample_console_echo/shadow_console_echo.c b/external/aws/samples/TizenRT/shadow_sample_console_echo/shadow_console_echo.c new file mode 100644 index 0000000..1c096fd --- /dev/null +++ b/external/aws/samples/TizenRT/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 +static 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 aws_shadow_console_echo(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/external/aws/samples/TizenRT/subscribe_publish_cpp_sample/Makefile b/external/aws/samples/TizenRT/subscribe_publish_cpp_sample/Makefile new file mode 100644 index 0000000..9f60434 --- /dev/null +++ b/external/aws/samples/TizenRT/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/external/aws/samples/TizenRT/subscribe_publish_cpp_sample/aws_iot_config.h b/external/aws/samples/TizenRT/subscribe_publish_cpp_sample/aws_iot_config.h new file mode 100644 index 0000000..252c384 --- /dev/null +++ b/external/aws/samples/TizenRT/subscribe_publish_cpp_sample/aws_iot_config.h @@ -0,0 +1,56 @@ +/* + * 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 +#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. + +#endif /* SRC_SHADOW_IOT_SHADOW_CONFIG_H_ */ diff --git a/external/aws/samples/TizenRT/subscribe_publish_cpp_sample/subscribe_publish_cpp_sample.cpp b/external/aws/samples/TizenRT/subscribe_publish_cpp_sample/subscribe_publish_cpp_sample.cpp new file mode 100644 index 0000000..a943858 --- /dev/null +++ b/external/aws/samples/TizenRT/subscribe_publish_cpp_sample/subscribe_publish_cpp_sample.cpp @@ -0,0 +1,264 @@ +/* + * 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 + */ +static char certDirectory[PATH_MAX + 1] = "../../../certs"; + +/** + * @brief Default MQTT HOST URL is pulled from the aws_iot_config.h + */ +static char HostAddress[255] = AWS_IOT_MQTT_HOST; + +/** + * @brief Default MQTT port is pulled from the aws_iot_config.h + */ +static 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 + */ +static uint32_t publishCount = 0; + +static 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); +} + +static 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); + } + } +} + +static 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; + } + } + +} + +extern "C" int aws_subscribe_publish_cpp(int argc, char **argv); + +int aws_subscribe_publish_cpp(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 = 10; + 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/external/aws/samples/TizenRT/subscribe_publish_library_sample/Makefile b/external/aws/samples/TizenRT/subscribe_publish_library_sample/Makefile new file mode 100644 index 0000000..bad2849 --- /dev/null +++ b/external/aws/samples/TizenRT/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/external/aws/samples/TizenRT/subscribe_publish_library_sample/aws_iot_config.h b/external/aws/samples/TizenRT/subscribe_publish_library_sample/aws_iot_config.h new file mode 100644 index 0000000..252c384 --- /dev/null +++ b/external/aws/samples/TizenRT/subscribe_publish_library_sample/aws_iot_config.h @@ -0,0 +1,56 @@ +/* + * 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 +#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. + +#endif /* SRC_SHADOW_IOT_SHADOW_CONFIG_H_ */ diff --git a/external/aws/samples/TizenRT/subscribe_publish_library_sample/subscribe_publish_library_sample.c b/external/aws/samples/TizenRT/subscribe_publish_library_sample/subscribe_publish_library_sample.c new file mode 100644 index 0000000..2a7ea4c --- /dev/null +++ b/external/aws/samples/TizenRT/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 + */ +static char certDirectory[PATH_MAX + 1] = "../../../certs"; + +/** + * @brief Default MQTT HOST URL is pulled from the aws_iot_config.h + */ +static char HostAddress[255] = AWS_IOT_MQTT_HOST; + +/** + * @brief Default MQTT port is pulled from the aws_iot_config.h + */ +static 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 + */ +static uint32_t publishCount = 0; + +static 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); +} + +static 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); + } + } +} + +static 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 aws_subscribe_publish_library(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 = 10; + 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/external/aws/samples/TizenRT/subscribe_publish_sample/Makefile b/external/aws/samples/TizenRT/subscribe_publish_sample/Makefile new file mode 100644 index 0000000..4b32391 --- /dev/null +++ b/external/aws/samples/TizenRT/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/external/aws/samples/TizenRT/subscribe_publish_sample/aws_iot_config.h b/external/aws/samples/TizenRT/subscribe_publish_sample/aws_iot_config.h new file mode 100644 index 0000000..252c384 --- /dev/null +++ b/external/aws/samples/TizenRT/subscribe_publish_sample/aws_iot_config.h @@ -0,0 +1,56 @@ +/* + * 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 +#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. + +#endif /* SRC_SHADOW_IOT_SHADOW_CONFIG_H_ */ diff --git a/external/aws/samples/TizenRT/subscribe_publish_sample/subscribe_publish_sample.c b/external/aws/samples/TizenRT/subscribe_publish_sample/subscribe_publish_sample.c new file mode 100644 index 0000000..117a324 --- /dev/null +++ b/external/aws/samples/TizenRT/subscribe_publish_sample/subscribe_publish_sample.c @@ -0,0 +1,263 @@ +/* + * 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" +#include "certData.h" + +/** + * @brief Default cert location + */ +static char certDirectory[PATH_MAX + 1] = "../../../certs"; + +/** + * @brief Default MQTT HOST URL is pulled from the aws_iot_config.h + */ +static char HostAddress[255] = AWS_IOT_MQTT_HOST; + +/** + * @brief Default MQTT port is pulled from the aws_iot_config.h + */ +static 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 + */ +static uint32_t publishCount = 0; + +static 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); +} + +static 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); + } + } +} + +static 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 aws_subscribe_publish(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 = 10; + 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/external/aws/src/Make.defs b/external/aws/src/Make.defs new file mode 100644 index 0000000..a00d667 --- /dev/null +++ b/external/aws/src/Make.defs @@ -0,0 +1,17 @@ +AWS_SRC_DIR=aws/src + +CSRCS += $(AWS_SRC_DIR)/aws_iot_json_utils.c \ + $(AWS_SRC_DIR)/aws_iot_mqtt_client.c \ + $(AWS_SRC_DIR)/aws_iot_mqtt_client_common_internal.c \ + $(AWS_SRC_DIR)/aws_iot_mqtt_client_connect.c \ + $(AWS_SRC_DIR)/aws_iot_mqtt_client_publish.c \ + $(AWS_SRC_DIR)/aws_iot_mqtt_client_subscribe.c \ + $(AWS_SRC_DIR)/aws_iot_mqtt_client_unsubscribe.c \ + $(AWS_SRC_DIR)/aws_iot_mqtt_client_yield.c \ + $(AWS_SRC_DIR)/aws_iot_shadow_actions.c \ + $(AWS_SRC_DIR)/aws_iot_shadow.c \ + $(AWS_SRC_DIR)/aws_iot_shadow_json.c \ + $(AWS_SRC_DIR)/aws_iot_shadow_records.c + +ROOTDEPPATH += --dep-path aws/src/ +VPATH += :aws/src/ diff --git a/external/aws/src/aws_iot_json_utils.c b/external/aws/src/aws_iot_json_utils.c new file mode 100644 index 0000000..3a058f8 --- /dev/null +++ b/external/aws/src/aws_iot_json_utils.c @@ -0,0 +1,201 @@ +/* + * 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; + } + + if(('-' == (char) (jsonString[token->start])) || (1 != sscanf(jsonString + token->start, "%" SCNu8, i))) { + IOT_WARN("Token was not an unsigned integer."); + return JSON_PARSE_ERROR; + } + + 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; + } + + if(1 != sscanf(jsonString + token->start, "%" SCNi16, i)) { + IOT_WARN("Token was not an integer."); + return JSON_PARSE_ERROR; + } + + 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; + } + + if(1 != sscanf(jsonString + token->start, "%" SCNi8, i)) { + IOT_WARN("Token was not an integer."); + return JSON_PARSE_ERROR; + } + + 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/external/aws/src/aws_iot_mqtt_client.c b/external/aws/src/aws_iot_mqtt_client.c new file mode 100644 index 0000000..1786f76 --- /dev/null +++ b/external/aws/src/aws_iot_mqtt_client.c @@ -0,0 +1,310 @@ +/* +* 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 "aws_iot_log.h" +#include "aws_iot_mqtt_client_interface.h" + +#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, 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; + pClient->clientData.options.pUsername = pNewConnectParams->pUsername; + pClient->clientData.options.usernameLen = pNewConnectParams->usernameLen; + pClient->clientData.options.pPassword = pNewConnectParams->pUsername; + 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, 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/external/aws/src/aws_iot_mqtt_client_common_internal.c b/external/aws/src/aws_iot_mqtt_client_common_internal.c new file mode 100644 index 0000000..a7cafb7 --- /dev/null +++ b/external/aws/src/aws_iot_mqtt_client_common_internal.c @@ -0,0 +1,685 @@ +/* +* 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 +#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; + switch(message_type) { + case UNKNOWN: + /* Should never happen */ + return FAILURE; + case CONNECT: + pHeader->bits.type = 0x01; + break; + case CONNACK: + pHeader->bits.type = 0x02; + break; + case PUBLISH: + pHeader->bits.type = 0x03; + break; + case PUBACK: + pHeader->bits.type = 0x04; + break; + case PUBREC: + pHeader->bits.type = 0x05; + break; + case PUBREL: + pHeader->bits.type = 0x06; + break; + case PUBCOMP: + pHeader->bits.type = 0x07; + break; + case SUBSCRIBE: + pHeader->bits.type = 0x08; + break; + case SUBACK: + pHeader->bits.type = 0x09; + break; + case UNSUBSCRIBE: + pHeader->bits.type = 0x0A; + break; + case UNSUBACK: + pHeader->bits.type = 0x0B; + break; + case PINGREQ: + pHeader->bits.type = 0x0C; + break; + case PINGRESP: + pHeader->bits.type = 0x0D; + break; + case DISCONNECT: + pHeader->bits.type = 0x0E; + break; + default: + /* Should never happen */ + FUNC_EXIT_RC(FAILURE); + } + + pHeader->bits.dup = (1 == dup) ? 0x01 : 0x00; + switch(qos) { + case QOS0: + pHeader->bits.qos = 0x00; + break; + case QOS1: + pHeader->bits.qos = 0x01; + break; + default: + /* Using QOS0 as default */ + pHeader->bits.qos = 0x00; + break; + } + + pHeader->bits.retain = (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, 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); + + len = 0; + 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 = header.bits.type; + + 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 char _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 NULL_VALUE_ERROR; + } + + 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); + rc = 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/external/aws/src/aws_iot_mqtt_client_connect.c b/external/aws/src/aws_iot_mqtt_client_connect.c new file mode 100644 index 0000000..9c4f25e --- /dev/null +++ b/external/aws/src/aws_iot_mqtt_client_connect.c @@ -0,0 +1,621 @@ +/* +* 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 "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; + flags.bits.cleansession = (pConnectParams->isCleanSession) ? 1 : 0; + flags.bits.will = (pConnectParams->isWillMsgPresent) ? 1 : 0; + if(flags.bits.will) { + flags.bits.willQoS = pConnectParams->will.qos; + flags.bits.willRetain = (pConnectParams->will.isRetained) ? 1 : 0; + } + + if(pConnectParams->pUsername) { + flags.bits.username = 1; + } + + if(pConnectParams->pPassword) { + flags.bits.password = 1; + } + + 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(flags.bits.username) { + aws_iot_mqtt_internal_write_utf8_string(&ptr, pConnectParams->pUsername, pConnectParams->usernameLen); + } + + if(flags.bits.password) { + 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 != header.bits.type) { + 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, 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, 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)); + 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) { + rc = aws_iot_mqtt_internal_send_packet(pClient, serialized_len, &timer); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + } + } + + /* 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/external/aws/src/aws_iot_mqtt_client_publish.c b/external/aws/src/aws_iot_mqtt_client_publish.c new file mode 100644 index 0000000..6895d52 --- /dev/null +++ b/external/aws/src/aws_iot_mqtt_client_publish.c @@ -0,0 +1,429 @@ +/* +* 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 != header.bits.type) { + FUNC_EXIT_RC(FAILURE); + } + + *dup = header.bits.dup; + *qos = (QoS) header.bits.qos; + *retained = header.bits.retain; + + /* read remaining length */ + rc = aws_iot_mqtt_internal_decode_remaining_length_from_buffer(curData, &decodedLen, &readBytesLen); + if(SUCCESS != rc) { + FUNC_EXIT_RC(rc); + return 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 = header.bits.dup; + *pPacketType = header.bits.type; + + /* 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/external/aws/src/aws_iot_mqtt_client_subscribe.c b/external/aws/src/aws_iot_mqtt_client_subscribe.c new file mode 100644 index 0000000..2311f73 --- /dev/null +++ b/external/aws/src/aws_iot_mqtt_client_subscribe.c @@ -0,0 +1,437 @@ +/* +* 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 != header.bits.type) { + 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++) { + 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/external/aws/src/aws_iot_mqtt_client_unsubscribe.c b/external/aws/src/aws_iot_mqtt_client_unsubscribe.c new file mode 100644 index 0000000..fcbb97a --- /dev/null +++ b/external/aws/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/external/aws/src/aws_iot_mqtt_client_yield.c b/external/aws/src/aws_iot_mqtt_client_yield.c new file mode 100644 index 0000000..c40bcbb --- /dev/null +++ b/external/aws/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/external/aws/src/aws_iot_shadow.c b/external/aws/src/aws_iot_shadow.c new file mode 100644 index 0000000..35697ae --- /dev/null +++ b/external/aws/src/aws_iot_shadow.c @@ -0,0 +1,225 @@ +/* + * 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}; + +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, 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.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, ShadowConnectParameters_t *pParams) { + IoT_Error_t rc = SUCCESS; + char deleteAcceptedTopic[MAX_SHADOW_TOPIC_LENGTH_BYTES]; + 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 = 10; + 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) { + 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/external/aws/src/aws_iot_shadow_actions.c b/external/aws/src/aws_iot_shadow_actions.c new file mode 100644 index 0000000..ed0f0cf --- /dev/null +++ b/external/aws/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/external/aws/src/aws_iot_shadow_json.c b/external/aws/src/aws_iot_shadow_json.c new file mode 100644 index 0000000..5d5d4ab --- /dev/null +++ b/external/aws/src/aws_iot_shadow_json.c @@ -0,0 +1,471 @@ +/* + * 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, + 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, 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)); + } + + 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; + + 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; + } + + pJsonHandler = (void *) jsonTokenStruct; + *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); + } + + 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 *pJsonTokenStruct; + jsmntok_t dataToken; + + pJsonTokenStruct = (jsmntok_t *) 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; + } + } + 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/external/aws/src/aws_iot_shadow_records.c b/external/aws/src/aws_iot_shadow_records.c new file mode 100644 index 0000000..1e4c4ac --- /dev/null +++ b/external/aws/src/aws_iot_shadow_records.c @@ -0,0 +1,525 @@ +/* + * 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 isAckForMyThingName(const char *pTopicName) { + if(strstr(pTopicName, myThingName) != NULL && + ((strstr(pTopicName, "get/accepted") != NULL) || (strstr(pTopicName, "update/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(isAckForMyThingName(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_TIMEOUT; + 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; + } else 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.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/os/include/inttypes.h b/os/include/inttypes.h index 3fd4ec5..1c8b2a3 100644 --- a/os/include/inttypes.h +++ b/os/include/inttypes.h @@ -236,6 +236,27 @@ uintmax_t wcstoumax(const wchar_t *, wchar_t **, int); #endif #define PRId64 __PRI64_PREFIX "d" + +#define PRIu8 "u" +#define PRIu16 "u" +#define PRIu32 "u" +#define PRIu64 __PRI64_PREFIX "u" + + +#define PRIi8 "i" +#define PRIi16 "i" +#define PRIi32 "i" +#define PRIi64 __PRI64_PREFIX "i" + +#define SCNu8 "hhu" +#define SCNu16 "hu" +#define SCNu32 "u" +#define SCNu64 __PRI64_PREFIX "u" + +#define SCNi8 "hhi" +#define SCNi16 "hi" +#define SCNi32 "i" +#define SCNi64 __PRI64_PREFIX "i" /** * @endcond */