### Install Homebrew and CMake on Mac OS Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/Platform.md Instructions for installing the Homebrew package manager and CMake on macOS. Homebrew simplifies the installation of various development tools. ```shell $ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" brew install cmake ``` -------------------------------- ### Build AWS IoT SDK C++ on Windows Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/Platform.md Instructions for setting up the build environment on Windows for the AWS IoT Device SDK C++. Requires OpenSSL 1.1.0, CMake, and Git. Generates a Visual Studio solution. ```shell git clone https://github.com/aws/aws-iot-device-sdk-cpp.git cd aws-iot-device-sdk-cpp mkdir build cd build /bin/cmake -G "Visual Studio 14 2015 Win64" ../. ``` -------------------------------- ### Install libssl-dev on Ubuntu Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/Platform.md Procedure to install `libssl-dev` on Ubuntu 14.04, potentially by adding PPA sources for Xenial. Includes steps to fix broken libraries and clean up sources. ```shell echo "deb [arch=i386,amd64] http://archive.ubuntu.com/ubuntu xenial main restricted universe multiverse " | sudo tee -a /etc/apt/sources.list echo "deb [arch=i386,amd64] http://security.ubuntu.com/ubuntu xenial-security main restricted universe multiverse " | sudo tee -a /etc/apt/sources.list echo "deb [arch=i386,amd64] http://archive.ubuntu.com/ubuntu xenial-backports main restricted universe multiverse " | sudo tee -a /etc/apt/sources.list echo "deb [arch=arm64,armhf,powerpc] http://ports.ubuntu.com/ xenial main restricted universe multiverse " | sudo tee -a /etc/apt/sources.list echo "deb [arch=arm64,armhf,powerpc] http://ports.ubuntu.com/ xenial-security main restricted universe multiverse " | sudo tee -a /etc/apt/sources.list echo "deb [arch=arm64,armhf,powerpc] http://ports.ubuntu.com/ xenial-backports main restricted universe multiverse " | sudo tee -a /etc/apt/sources.list echo "deb-src http://archive.ubuntu.com/ubuntu xenial main restricted universe multiverse " | sudo tee -a /etc/apt/sources.list echo "deb-src http://security.ubuntu.com/ubuntu xenial-security main restricted universe multiverse " | sudo tee -a /etc/apt/sources.list echo "deb-src http://archive.ubuntu.com/ubuntu xenial-backports main restricted universe multiverse " | sudo tee -a /etc/apt/sources.list echo "deb-src http://ports.ubuntu.com/ xenial main restricted universe multiverse " | sudo tee -a /etc/apt/sources.list echo "deb-src http://ports.ubuntu.com/ xenial-security main restricted universe multiverse " | sudo tee -a /etc/apt/sources.list echo "deb-src http://ports.ubuntu.com/ xenial-backports main restricted universe multiverse " | sudo tee -a /etc/apt/sources.list sudo apt-get update sudo dpkg --configure -a --force-all sudo apt-get -f install sudo apt-get install libssl-dev # Remove xenial backports from sources.list # (Manual editing or script to remove lines added above) sudo apt-get update ``` -------------------------------- ### AWS IoT SDK C++ Basic MQTT Client Setup Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/DevGuide.md To achieve basic MQTT support, include the `mqtt/Client.hpp` header. The client requires a Network Connection instance. Additional utilities like `Utf8String.hpp`, `JsonParser.hpp`, and `ResponseCode.hpp` may also be needed depending on application requirements. ```cpp #include "mqtt/Client.hpp" #include "util/Utf8String.hpp" #include "util/JsonParser.hpp" #include "ResponseCode.hpp" #include "shadow/Shadow.hpp" ``` -------------------------------- ### AWS IoT SDK C++ Logging Setup and Macros Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/DevGuide.md Demonstrates how to initialize the ConsoleLogSystem for logging, define log tags, and use logging macros like AWS_LOG_INFO and AWS_LOG_ERROR within the AWS IoT Device SDK C++. ```APIDOC AWS IoT SDK C++ Logging System: This section details the setup and usage of the logging system provided by the AWS IoT Device SDK C++. **ConsoleLogSystem Initialization:** To enable logging, an instance of `ConsoleLogSystem` must be created and initialized. * **Create Instance:** ```cpp // Example from samples/PubSub/PubSub.cpp#L271 auto logSystem = std::make_shared(); ``` * **Initialize Instance:** ```cpp // Example from samples/PubSub/PubSub.cpp#L273 logSystem->Initialize(awsiot::iotidentity::LogConfig::INFO, "PubSub"); ``` - `Initialize` takes a log level (e.g., `INFO`) and a log tag. **Defining Log Tags:** A log tag is used to identify the source of log messages. * **Example:** ```cpp // Example from samples/PubSub/PubSub.cpp#L40 static const char* TAG = "PUB_SUB"; ``` **Logging Macros:** Use the following macros to log messages at different severity levels. * **`AWS_LOG_INFO(tag, message)`:** Logs an informational message. - **Usage Example:** ```cpp // Example from src/mqtt/Connect.cpp#L74 AWS_LOG_INFO(TAG, "Connecting to endpoint: %s", endpoint.c_str()); ``` * **`AWS_LOG_ERROR(tag, message)`:** Logs an error message. - **Usage Example:** ```cpp // Example from src/mqtt/Connect.cpp#L142 AWS_LOG_ERROR(TAG, "Failed to connect to endpoint: %s, Error: %s", endpoint.c_str(), errorMessage.c_str()); ``` **Related Concepts:** * **Json Parsing:** The SDK uses RapidJson for JSON parsing. Refer to the Json Parsing section for details on its capabilities and limitations. * **Shadow Limitations:** Understand the constraints on Shadow operations, such as the number of subscriptions per MQTT connection. ``` -------------------------------- ### Add CMake to Mac OS PATH Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/Platform.md Guides on how to add the CMake executable path to the system's PATH environment variable when using the DMG installer on macOS. ```shell sudo vim /etc/paths # Add the following line to the paths already present: /Applications/CMake.app/Contents/bin # Save and quit. Then open a new terminal window and run: echo $PATH ``` -------------------------------- ### Manage GCC/G++ Alternatives on Raspberry Pi Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/Platform.md Provides commands to manage symbolic links for different GCC and G++ versions using `update-alternatives`. This is useful for selecting specific compiler versions required by the SDK. ```shell sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-5 20 sudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-6 10 sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-5 20 sudo update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-6 10 sudo update-alternatives --install /usr/bin/cc cc /usr/bin/gcc 30 sudo update-alternatives --set cc /usr/bin/gcc sudo update-alternatives --install /usr/bin/c++ c++ /usr/bin/g++ 30 sudo update-alternatives --set c++ /usr/bin/g++ ``` -------------------------------- ### AWS IoT Device SDK C++ Job Document Formats Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/samples/README.md Defines the JSON structure for various job operations handled by the jobs-agent. This includes formats for installing files, starting, stopping, and restarting packages on a device. ```APIDOC Install Job Document: Describes the structure for installing files on a device. { "operation": "install", "packageName": "uniquePackageName", "workingDirectory": ".", "launchCommand": "program-name program-arguments", "autoStart": "true", "files": [ { "fileName": "program-name", "fileVersion": "1.0.2.10", "fileSource": { "url": "https://some-bucket.s3.amazonaws.com/program-name" }, "checksum": { "inline": { "value": "9569257356cfc5c7b2b849e5f58b5d287f183e08627743498d9bd52801a2fbe4" }, "hashAlgorithm": "SHA256" } }, { "fileName": "config.json", "fileSource": { "url": "https://some-bucket.s3.amazonaws.com/config.json" } } ] } Parameters: - operation (string): Must be "install". - packageName (string): Unique identifier for the package. Overwrites previous installs with the same name. - workingDirectory (string, optional): The directory where files will be installed. - launchCommand (string, optional): Command to execute after installation. If omitted, only files are copied. - autoStart (string, optional): If "true", the launch command is executed when the agent starts. - files (array): List of files to install. - fileName (string): The name of the file as it will be written to the file system. - fileVersion (string, optional): The version of the file. - fileSource (object): Specifies the source of the file. - url (string): The URL from which to download the file. - checksum (object, optional): Optional checksum for file integrity verification (currently ignored). - inline (object): - value (string): The checksum value. - hashAlgorithm (string): The algorithm used for the checksum (e.g., "SHA256"). Start Job Document: Initiates the startup of a specified package. { "operation": "start", "packageName": "somePackageName" } Parameters: - operation (string): Must be "start". - packageName (string): The name of the package to start. Stop Job Document: Halts the execution of a specified package. { "operation": "stop", "packageName": "somePackageName" } Parameters: - operation (string): Must be "stop". - packageName (string): The name of the package to stop. Restart Job Document: Restarts a specified package. { "operation": "restart", "packageName": "somePackageName" } Parameters: - operation (string): Must be "restart". - packageName (string): The name of the package to restart. ``` -------------------------------- ### ClientCore Initialization and Threading Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/DevGuide.md Describes the initialization of the ClientCore class, which is the foundation for all SDK clients. It automatically creates a thread for processing outbound actions and manages action execution rates and queue sizes. ```APIDOC ClientCore __init__(shared_ptr state) - Initializes the ClientCore instance. - Creates a thread for processing Outbound Actions. - Processes queued Async actions sequentially. - Uses a default sleep time for actions requiring sleep (defined in ./include/Action.hpp). - Action processing rate is a constant (defined in ./src/ClientCoreState.cpp). ClientCoreState SetMaxActionQueueSize(size_t maxSize) - Sets the maximum size for the action queue. - Default value is defined in ./include/ClientCoreState.hpp. ClientCore ~ClientCore() - Destructor automatically stops all running threads and frees associated memory. ``` -------------------------------- ### Action Registration and Custom Actions Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/DevGuide.md Explains how to register actions with ClientCore and the requirements for creating custom actions, including factory methods and action type definitions. ```APIDOC ClientCore RegisterAction(ActionType actionType, unique_ptr actionInstance) - Registers a specific action instance with the ClientCore. - Creates a single instance of the Action if it's not required to run in a separate thread. - Used for all subsequent PerformAction calls with this ActionType. Action - Base class for custom actions. - Custom Actions must derive from this class. - Required to define a Create Factory method for ClientCore instantiation. ActionType - Represents the type of an action. - Custom Actions require an Action Type to be added to this class. ClientCoreState - Can be extended by creating a derived class to add action-specific values. ``` -------------------------------- ### Project Setup and Build Directory Check Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/samples/Discovery/CMakeLists.txt Initializes the CMake project and enforces the use of an out-of-source build directory to prevent in-source builds, which is a common best practice for CMake projects. ```cmake cmake_minimum_required(VERSION 3.2 FATAL_ERROR) project(aws-iot-cpp-samples CXX) ###################################### # Section : Disable in-source builds # ###################################### if (${PROJECT_SOURCE_DIR} STREQUAL ${PROJECT_BINARY_DIR}) message(FATAL_ERROR "In-source builds not allowed. Please make a new directory (called a build directory) and run CMake from there. You may need to remove CMakeCache.txt and CMakeFiles folder.") endif () ``` -------------------------------- ### Action Execution and Thread Management Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/DevGuide.md Details how to execute registered actions using PerformAction and PerformActionAsync, and how to manage actions running in separate threads. ```APIDOC ClientCore CreateActionRunner(ActionType actionType) - Creates a thread task (ThreadTask) to run a specific Action Type. - Creates a new instance of the requested Action Type and assigns it to the ThreadTask. - Threads created this way are cleared when PerformAction returns or ClientCore goes out of scope. ClientCore PerformAction(ActionType actionType, ...) - Executes a registered action synchronously (blocking). - Only one Sync/Blocking action can be performed at a time. ClientCore PerformActionAsync(ActionType actionType, ...) - Executes a registered action asynchronously. ``` -------------------------------- ### Build Setup with Clang and Sanitizer Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/tests/README.md Steps to create a build directory, configure CMake with a specific C++ compiler (Clang) and enable a sanitizer (e.g., ThreadSanitizer). This must be done before the first CMake run in a fresh build directory. ```shell mkdir build cd build cmake .. -DCMAKE_BUILD_TYPE=debug -DSANITIZE_THREAD=On -DCMAKE_CXX_COMPILER=/usr/bin/clang++ make ``` -------------------------------- ### CMake Project and Build Setup Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/samples/Jobs/CMakeLists.txt Configures the minimum CMake version, project name, and enforces standard C++11 with no extensions. It also sets output directories for archives, libraries, and runtimes. ```cmake cmake_minimum_required(VERSION 3.2 FATAL_ERROR) project(aws-iot-cpp-samples CXX) # Disable in-source builds if (${PROJECT_SOURCE_DIR} STREQUAL ${PROJECT_BINARY_DIR}) message(FATAL_ERROR "In-source builds not allowed. Please make a new directory (called a build directory) and run CMake from there. You may need to remove CMakeCache.txt and CMakeFiles folder.") endif () # Common Build settings # Set required compiler standard to standard c++11. Disable extensions. set(CMAKE_CXX_STANDARD 11) # C++11... set(CMAKE_CXX_STANDARD_REQUIRED ON) #...is required... set(CMAKE_CXX_EXTENSIONS OFF) #...without compiler extensions like gnu++11 set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/archive) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) ``` -------------------------------- ### JobsAgent Target Setup Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/samples/JobsAgent/CMakeLists.txt Defines the 'jobs-agent' executable target, specifies its source files, includes necessary directories for headers (SDK, rapidjson, common), finds and links required libraries (Threads, CURL, SDK), and applies custom compiler flags. ```CMake ################################ # Target : Build JobsAgent sample # ################################ set(JOBS_AGENT_TARGET_NAME jobs-agent) # Add Target add_executable(${JOBS_AGENT_TARGET_NAME} "${PROJECT_SOURCE_DIR}/JobsAgent.cpp;${PROJECT_SOURCE_DIR}/JobsAgentOperations.cpp;${PROJECT_SOURCE_DIR}/../../common/ConfigCommon.cpp") # Add Target specific includes target_include_directories(${JOBS_AGENT_TARGET_NAME} PRIVATE ${PROJECT_SOURCE_DIR}/../../common) target_include_directories(${JOBS_AGENT_TARGET_NAME} PUBLIC ${PROJECT_SOURCE_DIR}) # Configure Threading library find_package(Threads REQUIRED) # Configure CURL library find_package(CURL REQUIRED) # Add SDK includes target_include_directories(${JOBS_AGENT_TARGET_NAME} PUBLIC ${CMAKE_BINARY_DIR}/${DEPENDENCY_DIR}/rapidjson/src/include) target_include_directories(${JOBS_AGENT_TARGET_NAME} PUBLIC ${PROJECT_SOURCE_DIR}/../../include) target_link_libraries(${JOBS_AGENT_TARGET_NAME} PUBLIC "Threads::Threads") target_link_libraries(${JOBS_AGENT_TARGET_NAME} PUBLIC ${CURL_LIBRARIES}) target_link_libraries(${JOBS_AGENT_TARGET_NAME} PUBLIC ${SDK_TARGET_NAME}) # Copy Json config file add_custom_command(TARGET ${JOBS_AGENT_TARGET_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_SOURCE_DIR}/../../common/SampleConfig.json $/config/SampleConfig.json) set_property(TARGET ${JOBS_AGENT_TARGET_NAME} APPEND_STRING PROPERTY COMPILE_FLAGS ${CUSTOM_COMPILER_FLAGS}) ``` -------------------------------- ### MQTT Client Initialization and Threads Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/DevGuide.md Details on creating an MQTT client instance using a factory method or constructor, and the threads automatically created for outbound processing, network reading, and keep-alive logic. It highlights that the network connection cannot be changed after instantiation. ```cpp #include "mqtt/Client.hpp" // Example of creating an MQTT client instance (using factory method) // auto mqttClient = mqtt::Client::Create(...); // The client automatically creates three threads: // 1. Outbound Processing Queue Runner // 2. Network Read Runner // 3. Keep Alive Runner // Once instantiated, the Network Connection instance cannot be changed. // Auto-reconnect configuration can be modified via specific APIs. ``` -------------------------------- ### AWS IoT Device SDK C++ Unit Test and Coverage Setup Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/tests/unit/CMakeLists.txt Configures the CMake build system to set up unit tests for the AWS IoT Device SDK C++. This includes adding Google Test and Google Mock targets, defining test sources and include directories, linking essential libraries, enabling sanitizers, and configuring a custom target for generating code coverage reports using lcov and genhtml. ```cmake add_subdirectory(${CMAKE_BINARY_DIR}/third_party/googletest/src ${CMAKE_BINARY_DIR}/third_party/googletest/build EXCLUDE_FROM_ALL) file(GLOB_RECURSE SDK_UNIT_TEST_SOURCES FOLLOW_SYMLINKS ${CMAKE_SOURCE_DIR}/tests/unit/src/*.cpp) target_sources(${UNIT_TEST_TARGET_NAME} PUBLIC ${SDK_UNIT_TEST_SOURCES}) target_include_directories(${UNIT_TEST_TARGET_NAME} PUBLIC ${CMAKE_SOURCE_DIR}/common) target_include_directories(${UNIT_TEST_TARGET_NAME} PUBLIC ${CMAKE_SOURCE_DIR}/tests/unit/include) target_link_libraries(${UNIT_TEST_TARGET_NAME} gtest gtest_main gmock gmock_main) target_link_libraries(${UNIT_TEST_TARGET_NAME} ${THREAD_LIBRARY_LINK_STRING}) target_link_libraries(${UNIT_TEST_TARGET_NAME} ${SDK_TARGET_NAME}) if(SANITIZE_THREAD OR SANITIZE_MEMORY OR SANITIZE_ADDRESS OR SANITIZE_MEMORY) add_sanitizers(${UNIT_TEST_TARGET_NAME}) endif() find_program(GCOV gcov) find_program(LCOV lcov) find_program(GENHTML genhtml) if (GCOV AND LCOV AND GENHTML) set(UNIT_TEST_COVERAGE_TARGET_NAME "${UNIT_TEST_TARGET_NAME}-coverage") target_link_libraries(${UNIT_TEST_TARGET_NAME} -fprofile-arcs) target_link_libraries(${UNIT_TEST_TARGET_NAME} -ftest-coverage) set(UNIT_TEST_OUTPUT_DIR_PATH ${CMAKE_BINARY_DIR}/unit_test_results) set(UNIT_TEST_OUTPUT_NAME unit_test) file(MAKE_DIRECTORY ${UNIT_TEST_OUTPUT_DIR_PATH}) set(CUSTOM_COMPILER_FLAGS "${CUSTOM_COMPILER_FLAGS} -g -O0 -fprofile-arcs -ftest-coverage") set(LCOV_INFO "${UNIT_TEST_OUTPUT_DIR_PATH}/${UNIT_TEST_OUTPUT_NAME}.info") set(LCOV_CLEAN "${LCOV_INFO}.clean") # Setup target add_custom_target(${UNIT_TEST_COVERAGE_TARGET_NAME} DEPENDS ${UNIT_TEST_TARGET_NAME} WORKING_DIRECTORY ${CMAKE_RUNTIME_OUTPUT_DIRECTORY} # Cleanup old lcov runs COMMAND ${LCOV} --directory ${UNIT_TEST_OUTPUT_DIR_PATH} --zerocounters --rc lcov_branch_coverage=1 # Run tests COMMAND ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${UNIT_TEST_TARGET_NAME} # Capturing lcov counters and generating report COMMAND ${LCOV} --rc lcov_branch_coverage=1 --directory ${CMAKE_BINARY_DIR} --capture --output-file ${LCOV_INFO} COMMAND ${LCOV} --rc lcov_branch_coverage=1 --remove ${LCOV_INFO} 'tests/*' 'build/*' '/usr/*' '*logging/*' --output-file ${LCOV_CLEAN} COMMAND ${GENHTML} -o ${UNIT_TEST_OUTPUT_NAME} ${LCOV_CLEAN} COMMAND ${CMAKE_COMMAND} -E remove ${LCOV_INFO} ${LCOV_CLEAN} COMMENT "Open ${CMAKE_BINARY_DIR}/${UNIT_TEST_OUTPUT_NAME}/index.html in your browser to view the coverage report." ) endif () add_custom_command(TARGET ${UNIT_TEST_TARGET_NAME} PRE_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_SOURCE_DIR}/tests/unit/src/util/TestParser.json $/TestParser.json) set_property(TARGET ${UNIT_TEST_TARGET_NAME} APPEND_STRING PROPERTY COMPILE_FLAGS ${CUSTOM_COMPILER_FLAGS}) # Enable 'make test' add_test(NAME Run-All-Tests COMMAND ${UNIT_TEST_TARGET_NAME}) ``` -------------------------------- ### Update OpenSSL to 1.1.0 on Ubuntu Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/Platform.md Steps to update OpenSSL to version 1.1.0 on Ubuntu 14.04. Involves downloading, compiling, and installing OpenSSL from source. Ensures the correct version is linked. ```shell sudo apt-get install make wget https://www.openssl.org/source/openssl-1.1.0.tar.gz tar -xzvf openssl-1.1.0g.tar.gz cd openssl-1.1.0g sudo ./config sudo make install sudo ln -sf /usr/local/ssl/bin/openssl openssl version -v ``` -------------------------------- ### Configure OpenSSL Path in CMakeLists.txt on Mac OS Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/Platform.md Details how to manually configure the OpenSSL library and include directories within the CMake build system for the AWS SDK on macOS, specifically when using a custom OpenSSL installation. ```cmake # Comment out the default OpenSSL find package line # find_package(OpenSSL REQUIRED) # Add custom paths for OpenSSL 1.1.0 or above set(OPENSSL_LIBRARIES "YOUR_OPENSSL_PATH/lib/libssl.a;YOUR_OPENSSL_PATH/lib/libcrypto.a") set(OPENSSL_INCLUDE_DIR "YOUR_OPENSSL_PATH/include") ``` -------------------------------- ### Basic Subscribe Publish Sample (C++) Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/samples/README.md This sample demonstrates basic MQTT Subscribe and Publish operations using the default MQTT Client. It requires the AWS IoT SDK to be built and configured with appropriate certificates. ```cpp // Code for this sample is located [here](./PubSub) // Target for this sample is `pub-sub-sample` ``` -------------------------------- ### Configure C++ Project with C Language Support Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/Platform.md Addresses a common issue where CMake might not recognize C files if only C++ is enabled. This snippet shows how to modify the CMake project to include C language support. ```cmake project(aws-iot-sdk-cpp C CXX) ENABLE_LANGUAGE(C) ``` -------------------------------- ### Shadow Operations API Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/DevGuide.md APIs for interacting with AWS IoT Shadows. This includes creating a Shadow instance, subscribing to shadow topics, and performing operations like Get, Update (device and server state), and Delete. It also covers methods for managing the shadow document structure. ```APIDOC Shadow::Shadow(std::shared_ptr client) - Constructor for the Shadow class, requires an active MQTT client instance. Shadow::AddShadowSubscription() - Manually subscribes to shadow action topics. Subscriptions are persistent for the lifetime of the Shadow instance. Shadow::PerformGet(std::function callback) - Retrieves the current state of the shadow from the server and updates the server shadow state document. - Parameters: - callback: Function to handle the result of the Get operation. Shadow::UpdateDeviceShadow(const std::string& shadowDocument, std::function callback) - Updates the device-side shadow state document. - The provided JSON document MUST have the same structure as the shadow JSON. - The API merges the provided JSON to the current state of the device shadow. - Parameters: - shadowDocument: The JSON string representing the device shadow state. - callback: Function to handle the result of the Update operation. Shadow::GetShadowDocument() - Retrieves the current shadow document structure, useful for updating. - Returns: A JSON document representing the current shadow state. Shadow::GetEmptyShadowDocument() - Retrieves an empty JSON document structure, useful for creating a new shadow state. - Returns: An empty JSON document. Shadow::PerformUpdate(const std::string& shadowDocument, std::function callback) - Updates the shadow state on the server by generating a diff between the current device and server state shadow documents and calling the shadow update API. - Parameters: - shadowDocument: The JSON string representing the desired device shadow state. - callback: Function to handle the result of the Update operation. Shadow::PerformDelete(std::function callback) - Deletes the shadow JSON from the server. - Parameters: - callback: Function to handle the result of the Delete operation. // Destructor of the Shadow instance will unsubscribe from all currently subscribed topics. ``` -------------------------------- ### Run Integration Tests Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/tests/README.md Executes the compiled integration tests. This involves switching to the build's bin directory, configuring the test settings in a JSON file, and then running the test executable. ```bash # Switch to the generated bin folder cd bin # Modify the configuration file with your AWS IoT endpoint and certificate names # Example: config/IntegrationTestConfig.json # { # "endpoint": "YOUR_AWS_IOT_ENDPOINT", # "certPath": "certs/YOUR_CERTIFICATE.pem", # "keyPath": "certs/YOUR_PRIVATE_KEY.pem" # } # Run the integration tests ./aws-iot-integration-tests ``` -------------------------------- ### CMake: Install SDK Components (Non-MSVC) Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/CMakeLists.txt This CMake code defines the installation rules for the AWS IoT Device SDK C++. It installs the main library target to the `lib` destination and the include directory to the `include` destination, but only for non-MSVC (non-Windows) platforms. ```cmake if(NOT MSVC) install(TARGETS aws-iot-sdk-cpp DESTINATION lib) install(DIRECTORY include/ DESTINATION include) endif() ``` -------------------------------- ### Discovery Sample Target Definition Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/samples/Discovery/CMakeLists.txt Defines the 'discovery-sample' executable target, specifies its source files, sets include directories for common headers and SDK components, and links necessary libraries like Threads and the main SDK target. ```cmake ################################ # Target : Build Discovery sample # ################################ set(DISCOVERY_SAMPLE_TARGET_NAME discovery-sample) # Add Target add_executable(${DISCOVERY_SAMPLE_TARGET_NAME} "${PROJECT_SOURCE_DIR}/Discovery.cpp;${PROJECT_SOURCE_DIR}/../../common/ConfigCommon.cpp") # Add Target specific includes target_include_directories(${DISCOVERY_SAMPLE_TARGET_NAME} PUBLIC ${PROJECT_SOURCE_DIR}/../../common) target_include_directories(${DISCOVERY_SAMPLE_TARGET_NAME} PUBLIC ${PROJECT_SOURCE_DIR}) # Configure Threading library find_package(Threads REQUIRED) # Add SDK includes target_include_directories(${DISCOVERY_SAMPLE_TARGET_NAME} PUBLIC ${CMAKE_BINARY_DIR}/${DEPENDENCY_DIR}/rapidjson/src/include) target_include_directories(${DISCOVERY_SAMPLE_TARGET_NAME} PUBLIC ${PROJECT_SOURCE_DIR}/../../include) target_link_libraries(${DISCOVERY_SAMPLE_TARGET_NAME} PUBLIC "Threads::Threads") target_link_libraries(${DISCOVERY_SAMPLE_TARGET_NAME} PUBLIC ${SDK_TARGET_NAME}) ``` -------------------------------- ### Cross-compiling Toolchain Configuration Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/README.md Example configuration snippet for the `ToolchainFile.cmake` used to specify the toolchain directory and target for cross-compiling the AWS IoT C++ SDK. ```cmake # specify toolchain directory SET(TOOLCHAIN_DIR /home/toolchain/dir/here/bin) # specify cross compilation target SET(TARGET_CROSS target-here) ``` -------------------------------- ### Include Network Libraries Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/samples/Discovery/CMakeLists.txt Includes the CMakeLists.txt.in file from the network directory, which likely contains configurations and targets related to network functionalities required by the sample. ```cmake ######################### # Add Network libraries # ######################### set(NETWORK_WRAPPER_DEST_TARGET ${DISCOVERY_SAMPLE_TARGET_NAME}) include(${PROJECT_SOURCE_DIR}/../../network/CMakeLists.txt.in) ``` -------------------------------- ### Log Message C++ Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/README.md Illustrates how to log messages using the AWS IoT Device SDK's logging macros. It shows an example of logging an error message with a custom tag and formatted output. ```cpp AWS_LOG_ERROR(LOG_TAG_APPLICATION, "Failed to perform action. %s", ResponseHelper::ToString(rc).c_str()); ``` -------------------------------- ### Custom Build Commands for Discovery Sample Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/samples/Discovery/CMakeLists.txt Adds custom commands to the build process. A POST_BUILD command copies the sample configuration file, and a PRE_BUILD command copies the certificate directory to the target output directory. ```cmake # Copy Json config file add_custom_command(TARGET ${DISCOVERY_SAMPLE_TARGET_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_SOURCE_DIR}/../../common/SampleConfig.json $/config/SampleConfig.json) set_property(TARGET ${DISCOVERY_SAMPLE_TARGET_NAME} APPEND_STRING PROPERTY COMPILE_FLAGS ${CUSTOM_COMPILER_FLAGS}) # Gather list of all .cert files in "/cert" add_custom_command(TARGET ${DISCOVERY_SAMPLE_TARGET_NAME} PRE_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory ${PROJECT_SOURCE_DIR}/../../certs $/certs) ``` -------------------------------- ### Sample Greengrass Discovery Response Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/GreengrassDiscovery.md An example JSON structure for a successful AWS IoT Greengrass discovery response, detailing one group with one core and one endpoint, including root CA certificates. ```json { "GGGroups": [ { "GGGroupId": "", "Cores": [ { "thingArn": "", "Connectivity": [ { "Id": "", "HostAddress": "", "PortNumber": , "Metadata": "" } ] } ], "CAs": [ "-----BEGIN CERTIFICATE-----\\nsLongStringHere\\n-----END CERTIFICATE-----\\n" ] } ] } ``` -------------------------------- ### Jobs Agent Sample: System Status Operation (C++) Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/samples/README.md This sample demonstrates the Jobs Agent responding to a 'systemStatus' operation job document. The agent sends system status information to the AWS IoT jobs management platform. ```cpp // Code for this sample is located [here](./JobsAgent) // Target for this sample is `jobs-agent` // Example job document for systemStatus operation: // { // "operation": "systemStatus" // } ``` -------------------------------- ### Jobs Sample (C++) Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/samples/README.md This sample demonstrates how to perform various AWS IoT Jobs API operations, including subscribing to Jobs notifications and publishing Job execution updates. It requires the SDK to be built and configured. ```cpp // Code for this sample is located [here](./Jobs) // Target for this sample is `jobs-sample` ``` -------------------------------- ### AWS Greengrass Discovery API Request Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/GreengrassDiscovery.md Defines the HTTPS GET request format used by AWS IoT Devices to discover Greengrass groups and cores. It specifies the endpoint and the required path parameter for the thing name. ```http GET /greengrass/discover/thing/ ``` -------------------------------- ### Shadow Delta Sample (C++) Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/samples/README.md This sample demonstrates various AWS IoT Shadow operations. It requires the SDK to be built and configured. A limitation exists for the shadow client token, which is set as the thing name by default and is limited to 64 bytes. ```cpp // Code for this sample is located [here](./ShadowDelta) // Target for this sample is `shadow-delta-sample` // Note: The shadow client token is set as the thing name by default in the sample. // The shadow client token is limited to 64 bytes and will return an error if a token longer than 64 bytes is used // ("code":400,"message":"invalid client token"), although receiving a 400 does not necessarily mean that it is due to the length of the client token). // Modify the code [here](../ShadowDelta/ShadowDelta.cpp#L184) if your thing name is longer than 64 bytes to prevent this error. ``` -------------------------------- ### Initialize AWS Logging C++ Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/README.md Demonstrates how to initialize the AWS IoT Device SDK's logging system. It involves creating a ConsoleLogSystem instance with a specified log level and then initializing the logging framework. ```cpp std::shared_ptr p_log_system = std::make_shared(awsiotsdk::util::Logging::LogLevel::Info); awsiotsdk::util::Logging::InitializeAWSLogging(p_log_system); ``` -------------------------------- ### PublishActionAsync: MQTT Publish Operations (C++) Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/DevGuide.md Provides support for MQTT Publish operations, allowing clients to send messages to topics. This action is a core component for message broadcasting within the MQTT protocol. ```APIDOC PublishActionAsync - Purpose: Handles MQTT Publish operations. - Usage: Sends messages to specified MQTT topics. - Related: PubackActionAsync, SubscribeActionAsync, UnsubscribeActionAsync ``` -------------------------------- ### MQTT Client Auto-Reconnect Configuration Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/DevGuide.md APIs for configuring the auto-reconnect behavior of the MQTT client. This includes enabling/disabling the feature, setting backoff timer values, and configuring callbacks for disconnect, reconnect, and resubscribe events. ```APIDOC MQTTClient::SetAutoReconnectEnabled(bool enabled) - Enables or disables the auto-reconnect flow. MQTTClient::SetMinReconnectBackoffTimeout(std::chrono::milliseconds timeout) - Sets the minimum backoff timer value for auto-reconnect. - Default: 1 second. MQTTClient::SetMaxReconnectBackoffTimeout(std::chrono::milliseconds timeout) - Sets the maximum backoff timer value for auto-reconnect. - Default: 128 seconds. MQTTClient::SetDisconnectCallback(std::function callback) - Sets a callback function to be invoked upon disconnection. - The callback must be non-blocking. MQTTClient::SetReconnectCallback(std::function callback) - Sets a callback function to be invoked when a reconnection attempt is made. - The callback must be non-blocking. MQTTClient::SetResubscribeCallback(std::function callback) - Sets a callback function to be invoked after a successful resubscription. - The callback must be non-blocking. ``` -------------------------------- ### Build SDK with Network Libraries Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/tests/README.md Configures the build system using CMake to prepare the AWS IoT Device SDK C++ for integration tests. Users can specify the network library to be used during the build process. ```bash cmake -DNETWORK_LIBRARY=OpenSSL cmake -DNETWORK_LIBRARY=MbedTLS cmake -DNETWORK_LIBRARY=WebSocket ``` -------------------------------- ### UnsubscribeActionAsync: MQTT Unsubscribe Operations (C++) Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/DevGuide.md Provides support for MQTT Unsubscribe operations, allowing clients to stop receiving messages from previously subscribed topics. A maximum of 8 topics can be unsubscribed from per message. ```APIDOC UnsubscribeActionAsync - Purpose: Handles MQTT Unsubscribe operations. - Limitations: Max 8 topics per message. - Usage: Unsubscribes from MQTT topics. - Related: SubscribeActionAsync, PublishActionAsync ``` -------------------------------- ### Shadow Delta Sample Linking and Post-Build Actions Source: https://github.com/aws/aws-iot-device-sdk-cpp/blob/master/samples/ShadowDelta/CMakeLists.txt Links the 'shadow-delta-sample' target against the Threads library and the main SDK target. It also configures post-build commands to copy the configuration file and certificate directory to the output directory. ```CMake target_link_libraries(${SHADOW_DELTA_SAMPLE_TARGET_NAME} PUBLIC "Threads::Threads") target_link_libraries(${SHADOW_DELTA_SAMPLE_TARGET_NAME} PUBLIC ${SDK_TARGET_NAME}) # Copy Json config file add_custom_command(TARGET ${SHADOW_DELTA_SAMPLE_TARGET_NAME} POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy ${PROJECT_SOURCE_DIR}/../../common/SampleConfig.json $/config/SampleConfig.json) set_property(TARGET ${SHADOW_DELTA_SAMPLE_TARGET_NAME} APPEND_STRING PROPERTY COMPILE_FLAGS ${CUSTOM_COMPILER_FLAGS}) # Gather list of all .cert files in "/cert" add_custom_command(TARGET ${SHADOW_DELTA_SAMPLE_TARGET_NAME} PRE_BUILD COMMAND ${CMAKE_COMMAND} -E copy_directory ${PROJECT_SOURCE_DIR}/../../certs $/certs) ```