diff --git a/.github/workflows/examples.yml b/.github/workflows/examples.yml index d8f296965..1e5c12efb 100644 --- a/.github/workflows/examples.yml +++ b/.github/workflows/examples.yml @@ -15,7 +15,6 @@ jobs: - "examples/arduino-wifiscan" - "examples/espidf-arduino-blink" - "examples/espidf-arduino-wifiscan" - - "examples/espidf-aws-iot" - "examples/espidf-ble-eddystone" - "examples/espidf-coap-server" - "examples/espidf-exceptions" diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index a93ede2d1..446f8849c 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -8,7 +8,7 @@ jobs: fail-fast: false matrix: os: [ubuntu-latest, windows-latest, macos-latest] - python-version: [3.7] + python-version: [3.9] example: - "examples/espidf-hello-world" runs-on: ${{ matrix.os }} diff --git a/boards/esp32s3_powerfeather.json b/boards/esp32s3_powerfeather.json new file mode 100644 index 000000000..1076778cb --- /dev/null +++ b/boards/esp32s3_powerfeather.json @@ -0,0 +1,48 @@ +{ + "build": { + "arduino":{ + "partitions": "default_8MB.csv" + }, + "core": "esp32", + "extra_flags": [ + "-DARDUINO_ESP32S3_POWERFEATHER", + "-DARDUINO_USB_CDC_ON_BOOT=1", + "-DARDUINO_RUNNING_CORE=1", + "-DARDUINO_EVENT_RUNNING_CORE=1" + ], + "f_cpu": "240000000L", + "f_flash": "80000000L", + "flash_mode": "qio", + "hwids": [ + [ + "0X303A", + "0x81BB" + ] + ], + "mcu": "esp32s3", + "variant": "esp32s3_powerfeather" + }, + "connectivity": [ + "bluetooth", + "wifi" + ], + "debug": { + "openocd_target": "esp32s3.cfg" + }, + "frameworks": [ + "arduino", + "espidf" + ], + "name": "ESP32-S3 PowerFeather", + "upload": { + "flash_size": "8MB", + "maximum_ram_size": 327680, + "maximum_size": 8388608, + "wait_for_upload_port": true, + "require_upload_port": true, + "speed": 460800 + }, + "url": "https://powerfeather.dev/", + "vendor": "PowerFeather" +} + diff --git a/boards/motorgo_mini_1.json b/boards/motorgo_mini_1.json new file mode 100644 index 000000000..536d7e4ba --- /dev/null +++ b/boards/motorgo_mini_1.json @@ -0,0 +1,43 @@ +{ + "build": { + "core": "esp32", + "extra_flags": [ + "-DARDUINO_MOTORGO_MINI_1", + "-DARDUINO_USB_CDC_ON_BOOT=1", + "-DARDUINO_RUNNING_CORE=1", + "-DARDUINO_EVENT_RUNNING_CORE=1" + ], + "f_cpu": "240000000L", + "f_flash": "80000000L", + "flash_mode": "qio", + "hwids": [ + [ + "0X303A", + "0x1001" + ] + ], + "mcu": "esp32s3", + "variant": "motorgo_mini_1" + }, + "connectivity": [ + "bluetooth", + "wifi" + ], + "debug": { + "openocd_target": "esp32s3.cfg" + }, + "frameworks": [ + "arduino", + "espidf" + ], + "name": "MotorGo Mini 1 (ESP32-S3)", + "upload": { + "flash_size": "4MB", + "maximum_ram_size": 327680, + "maximum_size": 4194304, + "require_upload_port": true, + "speed": 460800 + }, + "url": "https://motorgo.net/shop/ols/products/motorgo-mini-v1-dot-2-starter-kit-plus-motors", + "vendor": "MotorGo" +} diff --git a/boards/sensebox_mcu_esp32s2.json b/boards/sensebox_mcu_esp32s2.json new file mode 100644 index 000000000..dc9e6db07 --- /dev/null +++ b/boards/sensebox_mcu_esp32s2.json @@ -0,0 +1,65 @@ +{ + "build": { + "arduino": { + "ldscript": "esp32s2_out.ld", + "partitions": "partitions-4MB-tinyuf2.csv", + "memory_type": "qio_qspi" + }, + "core": "esp32", + "extra_flags": [ + "-DARDUINO_SENSEBOX_MCU_ESP32S2", + "-DBOARD_HAS_PSRAM", + "-DARDUINO_USB_CDC_ON_BOOT=1", + "-DARDUINO_USB_MSC_ON_BOOT=1" + ], + "f_cpu": "240000000L", + "f_flash": "80000000L", + "flash_mode": "qio", + "hwids": [ + [ + "0x303A", + "0x81B8" + ], + [ + "0x303A", + "0x81B9" + ], + [ + "0x303A", + "0x81BA" + ] + ], + "mcu": "esp32s2", + "variant": "sensebox_mcu_esp32s2" + }, + "connectivity": [ + "wifi" + ], + "debug": { + "openocd_target": "esp32s2.cfg" + }, + "frameworks": [ + "arduino", + "espidf" + ], + "name": "senseBox MCU-S2 ESP32-S2", + "upload": { + "arduino": { + "flash_extra_images": [ + [ + "0x2d0000", + "variants/sensebox_mcu_esp32s2/tinyuf2.bin" + ] + ] + }, + "flash_size": "4MB", + "maximum_ram_size": 327680, + "maximum_size": 4194304, + "use_1200bps_touch": true, + "wait_for_upload_port": true, + "require_upload_port": true, + "speed": 460800 + }, + "url": "https://sensebox.de/en/products-home", + "vendor": "senseBox" +} diff --git a/builder/frameworks/espidf.py b/builder/frameworks/espidf.py index 7c20e9aa1..1fe5873a3 100644 --- a/builder/frameworks/espidf.py +++ b/builder/frameworks/espidf.py @@ -26,6 +26,7 @@ import sys import shutil import os +import re import platform as sys_platform import click @@ -58,11 +59,23 @@ idf_variant = mcu.lower() # Required until Arduino switches to v5 -IDF5 = platform.get_package_version("framework-espidf").split(".")[1].startswith("5") +IDF5 = ( + platform.get_package_version("framework-espidf") + .split(".")[1] + .startswith("5") +) IDF_ENV_VERSION = "1.0.0" FRAMEWORK_DIR = platform.get_package_dir("framework-espidf") TOOLCHAIN_DIR = platform.get_package_dir( - "toolchain-%s" % ("riscv32-esp" if mcu in ("esp32c3", "esp32c6") else ("xtensa-%s" % mcu)) + "toolchain-riscv32-esp" + if mcu in ("esp32c3", "esp32c6") + else ( + ( + "toolchain-xtensa-esp-elf" + if "arduino" not in env.subst("$PIOFRAMEWORK") + else "toolchain-xtensa-%s" % mcu + ) + ) ) @@ -482,7 +495,7 @@ def _scan_components_from_framework(): return components or _scan_components_from_framework() -def extract_linker_script_fragments(framework_components_dir, sdk_config): +def extract_linker_script_fragments_backup(framework_components_dir, sdk_config): # Hardware-specific components are excluded from search and added manually below project_components = load_component_paths( framework_components_dir, ignored_component_prefixes=("esp32", "riscv") @@ -530,6 +543,52 @@ def extract_linker_script_fragments(framework_components_dir, sdk_config): return result +def extract_linker_script_fragments( + ninja_buildfile, framework_components_dir, sdk_config +): + def _normalize_fragment_path(base_dir, fragment_path): + if not os.path.isabs(fragment_path): + fragment_path = os.path.abspath( + os.path.join(base_dir, fragment_path) + ) + if not os.path.isfile(fragment_path): + print("Warning! The `%s` fragment is not found!" % fragment_path) + + return fragment_path + + assert os.path.isfile( + ninja_buildfile + ), "Cannot extract linker fragments! Ninja build file is missing!" + + result = [] + with open(ninja_buildfile, encoding="utf8") as fp: + for line in fp.readlines(): + if "sections.ld: CUSTOM_COMMAND" not in line: + continue + for fragment_match in re.finditer(r"(\S+\.lf\b)+", line): + result.append(_normalize_fragment_path( + BUILD_DIR, fragment_match.group(0).replace("$:", ":") + )) + + break + + # Fall back option if the new algorithm didn't work + if not result: + result = extract_linker_script_fragments_backup( + framework_components_dir, sdk_config + ) + + if board.get("build.esp-idf.extra_lf_files", ""): + for fragment_path in board.get( + "build.esp-idf.extra_lf_files" + ).splitlines(): + if not fragment_path.strip(): + continue + result.append(_normalize_fragment_path(PROJECT_DIR, fragment_path)) + + return result + + def create_custom_libraries_list(ldgen_libraries_file, ignore_targets): if not os.path.isfile(ldgen_libraries_file): sys.stderr.write("Error: Couldn't find the list of framework libraries\n") @@ -558,11 +617,13 @@ def create_custom_libraries_list(ldgen_libraries_file, ignore_targets): def generate_project_ld_script(sdk_config, ignore_targets=None): ignore_targets = ignore_targets or [] linker_script_fragments = extract_linker_script_fragments( - os.path.join(FRAMEWORK_DIR, "components"), sdk_config + os.path.join(BUILD_DIR, "build.ninja"), + os.path.join(FRAMEWORK_DIR, "components"), + sdk_config ) - # Create a new file to avoid automatically generated library entry as files from - # this library are built internally by PlatformIO + # Create a new file to avoid automatically generated library entry as files + # from this library are built internally by PlatformIO libraries_list = create_custom_libraries_list( os.path.join(BUILD_DIR, "ldgen_libraries"), ignore_targets ) @@ -691,7 +752,7 @@ def compile_source_files( obj_path = os.path.join(obj_path, os.path.basename(src_path)) preserve_source_file_extension = board.get( - "build.esp-idf.preserve_source_file_extension", False + "build.esp-idf.preserve_source_file_extension", True ) objects.append( diff --git a/builder/frameworks/ulp.py b/builder/frameworks/ulp.py index 8cc922179..1a66c2bc9 100644 --- a/builder/frameworks/ulp.py +++ b/builder/frameworks/ulp.py @@ -34,11 +34,14 @@ def prepare_ulp_env_vars(env): ulp_env.PrependENVPath("IDF_PATH", FRAMEWORK_DIR) + toolchain_path = platform.get_package_dir( + "toolchain-xtensa-esp-elf" + if "arduino" not in env.subst("$PIOFRAMEWORK") + else "toolchain-xtensa-%s" % idf_variant + ) + additional_packages = [ - os.path.join( - platform.get_package_dir("toolchain-xtensa-%s" % idf_variant), - "bin", - ), + toolchain_path, os.path.join( platform.get_package_dir("toolchain-esp32ulp"), "bin", diff --git a/examples/espidf-aws-iot/.gitignore b/examples/espidf-aws-iot/.gitignore deleted file mode 100644 index 03f4a3c19..000000000 --- a/examples/espidf-aws-iot/.gitignore +++ /dev/null @@ -1 +0,0 @@ -.pio diff --git a/examples/espidf-aws-iot/.travis.yml b/examples/espidf-aws-iot/.travis.yml deleted file mode 100644 index 7c486f183..000000000 --- a/examples/espidf-aws-iot/.travis.yml +++ /dev/null @@ -1,67 +0,0 @@ -# Continuous Integration (CI) is the practice, in software -# engineering, of merging all developer working copies with a shared mainline -# several times a day < https://docs.platformio.org/page/ci/index.html > -# -# Documentation: -# -# * Travis CI Embedded Builds with PlatformIO -# < https://docs.travis-ci.com/user/integration/platformio/ > -# -# * PlatformIO integration with Travis CI -# < https://docs.platformio.org/page/ci/travis.html > -# -# * User Guide for `platformio ci` command -# < https://docs.platformio.org/page/userguide/cmd_ci.html > -# -# -# Please choose one of the following templates (proposed below) and uncomment -# it (remove "# " before each line) or use own configuration according to the -# Travis CI documentation (see above). -# - - -# -# Template #1: General project. Test it using existing `platformio.ini`. -# - -# language: python -# python: -# - "2.7" -# -# sudo: false -# cache: -# directories: -# - "~/.platformio" -# -# install: -# - pip install -U platformio -# - platformio update -# -# script: -# - platformio run - - -# -# Template #2: The project is intended to be used as a library with examples. -# - -# language: python -# python: -# - "2.7" -# -# sudo: false -# cache: -# directories: -# - "~/.platformio" -# -# env: -# - PLATFORMIO_CI_SRC=path/to/test/file.c -# - PLATFORMIO_CI_SRC=examples/file.ino -# - PLATFORMIO_CI_SRC=path/to/test/directory -# -# install: -# - pip install -U platformio -# - platformio update -# -# script: -# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N diff --git a/examples/espidf-aws-iot/CMakeLists.txt b/examples/espidf-aws-iot/CMakeLists.txt deleted file mode 100644 index 61f45be84..000000000 --- a/examples/espidf-aws-iot/CMakeLists.txt +++ /dev/null @@ -1,6 +0,0 @@ -# The following lines of boilerplate have to be in your project's CMakeLists -# in this exact order for cmake to work correctly -cmake_minimum_required(VERSION 3.5) - -include($ENV{IDF_PATH}/tools/cmake/project.cmake) -project(subscribe_publish) diff --git a/examples/espidf-aws-iot/README.md b/examples/espidf-aws-iot/README.md deleted file mode 100644 index da21cb256..000000000 --- a/examples/espidf-aws-iot/README.md +++ /dev/null @@ -1,22 +0,0 @@ -How to build PlatformIO based project -===================================== - -1. [Install PlatformIO Core](https://docs.platformio.org/page/core.html) -2. Download [development platform with examples](https://github.com/platformio/platform-espressif32/archive/develop.zip) -3. Extract ZIP archive -4. Run these commands: - -```shell - -# Change directory to example -$ cd platform-espressif32/examples/espidf-aws-iot - -# Build project -$ pio run - -# Upload firmware -$ pio run --target upload - -# Clean build files -$ pio run --target clean -``` \ No newline at end of file diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/.gitignore b/examples/espidf-aws-iot/components/esp-aws-iot/.gitignore deleted file mode 100644 index bf8e14f7e..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -*.o - -# Example project files -examples/**/sdkconfig -examples/**/sdkconfig.old -examples/**/build - -# AWS IoT Examples require device-specific certs/keys -examples/*/main/certs/*.pem.* diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/.gitlab-ci.yml b/examples/espidf-aws-iot/components/esp-aws-iot/.gitlab-ci.yml deleted file mode 100644 index 5536211db..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/.gitlab-ci.yml +++ /dev/null @@ -1,42 +0,0 @@ -stages: - - build - -variables: - BATCH_BUILD: "1" - V: "0" - MAKEFLAGS: "-j5 --no-keep-going" - IDF_PATH: "$CI_PROJECT_DIR/esp-idf" - -build_demo: - stage: build - image: $CI_DOCKER_REGISTRY/esp32-ci-env - tags: - - build - script: - # add gitlab ssh key - - export PATH="$IDF_PATH/tools:$PATH" - - mkdir -p ~/.ssh - - chmod 700 ~/.ssh - - echo -n $GITLAB_KEY > ~/.ssh/id_rsa_base64 - - base64 --decode --ignore-garbage ~/.ssh/id_rsa_base64 > ~/.ssh/id_rsa - - chmod 600 ~/.ssh/id_rsa - - echo -e "Host gitlab.espressif.cn\n\tStrictHostKeyChecking no\n" >> ~/.ssh/config - - git --version - - git submodule update --init --recursive - - git clone --recursive --depth 1 $GITLAB_SSH_SERVER/idf/esp-idf.git - - export PATH="$IDF_PATH/tools:$PATH" - - cd esp-idf - - ./install.sh - - . export.sh - - cd .. - - cd examples/thing_shadow - - cat sdkconfig.ci >> sdkconfig.defaults - - make defconfig && make -j4 - - make clean && rm -rf build - - idf.py build - - cd ../.. - - cd examples/subscribe_publish - - cat sdkconfig.ci >> sdkconfig.defaults - - make defconfig && make -j4 - - make clean && rm -rf build - - idf.py build diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/.gitmodules b/examples/espidf-aws-iot/components/esp-aws-iot/.gitmodules deleted file mode 100644 index f75792f69..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "aws-iot-device-sdk-embedded-C"] - path = aws-iot-device-sdk-embedded-C - url = https://github.com/espressif/aws-iot-device-sdk-embedded-C.git diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/CMakeLists.txt b/examples/espidf-aws-iot/components/esp-aws-iot/CMakeLists.txt deleted file mode 100644 index 653fd191b..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/CMakeLists.txt +++ /dev/null @@ -1,26 +0,0 @@ -set(COMPONENT_ADD_INCLUDEDIRS "port/include aws-iot-device-sdk-embedded-C/include") -set(aws_sdk_dir aws-iot-device-sdk-embedded-C/src) -set(COMPONENT_SRCS "${aws_sdk_dir}/aws_iot_jobs_interface.c" - "${aws_sdk_dir}/aws_iot_jobs_json.c" - "${aws_sdk_dir}/aws_iot_jobs_topics.c" - "${aws_sdk_dir}/aws_iot_jobs_types.c" - "${aws_sdk_dir}/aws_iot_json_utils.c" - "${aws_sdk_dir}/aws_iot_mqtt_client.c" - "${aws_sdk_dir}/aws_iot_mqtt_client_common_internal.c" - "${aws_sdk_dir}/aws_iot_mqtt_client_connect.c" - "${aws_sdk_dir}/aws_iot_mqtt_client_publish.c" - "${aws_sdk_dir}/aws_iot_mqtt_client_subscribe.c" - "${aws_sdk_dir}/aws_iot_mqtt_client_unsubscribe.c" - "${aws_sdk_dir}/aws_iot_mqtt_client_yield.c" - "${aws_sdk_dir}/aws_iot_shadow.c" - "${aws_sdk_dir}/aws_iot_shadow_actions.c" - "${aws_sdk_dir}/aws_iot_shadow_json.c" - "${aws_sdk_dir}/aws_iot_shadow_records.c" - "port/network_mbedtls_wrapper.c" - "port/threads_freertos.c" - "port/timer.c") - -set(COMPONENT_REQUIRES "mbedtls") -set(COMPONENT_PRIV_REQUIRES "jsmn") - -register_component() diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/Kconfig b/examples/espidf-aws-iot/components/esp-aws-iot/Kconfig deleted file mode 100644 index 0e41d9689..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/Kconfig +++ /dev/null @@ -1,146 +0,0 @@ -menu "Amazon Web Services IoT Platform" - -config AWS_IOT_MQTT_HOST - string "AWS IoT Endpoint Hostname" - default "" - help - Default endpoint host name to connect to AWS IoT MQTT/S gateway - - This is the custom endpoint hostname and is specific to an AWS - IoT account. You can find it by logging into your AWS IoT - Console and clicking the Settings button. The endpoint hostname - is shown under the "Custom Endpoint" heading on this page. - - If you need per-device hostnames for different regions or - accounts, you can override the default hostname in your app. - -config AWS_IOT_MQTT_PORT - int "AWS IoT MQTT Port" - default 8883 - range 0 65535 - help - Default port number to connect to AWS IoT MQTT/S gateway - - If you need per-device port numbers for different regions, you can - override the default port number in your app. - - -config AWS_IOT_MQTT_TX_BUF_LEN - int "MQTT TX Buffer Length" - default 512 - range 32 131072 - help - Maximum MQTT transmit buffer size. This is the maximum MQTT - message length (including protocol overhead) which can be sent. - - Sending longer messages will fail. - -config AWS_IOT_MQTT_RX_BUF_LEN - int "MQTT RX Buffer Length" - default 512 - range 32 131072 - help - Maximum MQTT receive buffer size. This is the maximum MQTT - message length (including protocol overhead) which can be - received. - - Longer messages are dropped. - - - -config AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS - int "Maximum MQTT Topic Filters" - default 5 - range 1 100 - help - Maximum number of concurrent MQTT topic filters. - - -config AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL - int "Auto reconnect initial interval (ms)" - default 1000 - range 10 3600000 - help - Initial delay before making first reconnect attempt, if the AWS IoT connection fails. - Client will perform exponential backoff, starting from this value. - -config AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL - int "Auto reconnect maximum interval (ms)" - default 128000 - range 10 3600000 - help - Maximum delay between reconnection attempts. If the exponentially increased delay - interval reaches this value, the client will stop automatically attempting to reconnect. - -menu "Thing Shadow" - - config AWS_IOT_OVERRIDE_THING_SHADOW_RX_BUFFER - bool "Override Shadow RX buffer size" - default n - help - Allows setting a different Thing Shadow RX buffer - size. This is the maximum size of a Thing Shadow - message in bytes, plus one. - - If not overridden, the default value is the MQTT RX Buffer length plus one. If overriden, do not set - higher than the default value. - - config AWS_IOT_SHADOW_MAX_SIZE_OF_RX_BUFFER - int "Maximum RX Buffer (bytes)" - depends on AWS_IOT_OVERRIDE_THING_SHADOW_RX_BUFFER - default 513 - range 32 65536 - help - Allows setting a different Thing Shadow RX buffer size. - This is the maximum size of a Thing Shadow message in bytes, - plus one. - - - config AWS_IOT_SHADOW_MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES - int "Maximum unique client ID size (bytes)" - default 80 - range 4 1000 - help - Maximum size of the Unique Client Id. - - config AWS_IOT_SHADOW_MAX_SIMULTANEOUS_ACKS - int "Maximum simultaneous responses" - default 10 - range 1 100 - help - At any given time we will wait for this many responses. This will correlate to the rate at which the - shadow actions are requested - - config AWS_IOT_SHADOW_MAX_SIMULTANEOUS_THINGNAMES - int "Maximum simultaneous Thing Name operations" - default 10 - range 1 100 - help - We could perform shadow action on any thing Name and this is maximum Thing Names we can act on at any - given time - - config AWS_IOT_SHADOW_MAX_JSON_TOKEN_EXPECTED - int "Maximum expected JSON tokens" - default 120 - help - These are the max tokens that is expected to be in the Shadow JSON document. Includes the metadata which - is published - - config AWS_IOT_SHADOW_MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME - int "Maximum topic length (not including Thing Name)" - default 60 - range 10 1000 - help - All shadow actions have to be published or subscribed to a topic which is of the format - $aws/things/{thingName}/shadow/update/accepted. This refers to the size of the topic without the Thing - Name - - config AWS_IOT_SHADOW_MAX_SIZE_OF_THING_NAME - int "Maximum Thing Name length" - default 20 - range 4 1000 - help - Maximum length of a Thing Name. - -endmenu # Thing Shadow -endmenu # AWS IoT diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/LICENSE b/examples/espidf-aws-iot/components/esp-aws-iot/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - 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: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) 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 - - (d) 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 - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/README.md b/examples/espidf-aws-iot/components/esp-aws-iot/README.md deleted file mode 100644 index 57b5b1619..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# ESP-AWS-IoT - -This framework enables AWS IoT cloud connectivity with ESP32 based platforms using [AWS IoT Device Embedded SDK](https://github.com/aws/aws-iot-device-sdk-embedded-C). - -## Getting Started - -- Please clone this repository using, - ``` - git clone --recursive https://github.com/espressif/esp-aws-iot - ``` -- Please refer to https://docs.espressif.com/projects/esp-idf/en/latest/get-started/index.html for setting ESP-IDF - - ESP-IDF can be downloaded from https://github.com/espressif/esp-idf/ - - ESP-IDF v3.1 and above is recommended version -- Please refer to [example README](examples/README.md) for more information on setting up examples diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/.gitignore b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/.gitignore deleted file mode 100644 index 32361d47b..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/.gitignore +++ /dev/null @@ -1,22 +0,0 @@ -# Ignore executables -*.o -IotSdkC_tests -samples/linux/jobs_sample/jobs_sample -samples/linux/shadow_sample/shadow_sample -samples/linux/shadow_sample_console_echo/shadow_console_echo -samples/linux/subscribe_publish_library_sample/libAwsIotSdk.a -samples/linux/subscribe_publish_library_sample/subscribe_publish_library_sample -samples/linux/subscribe_publish_sample/subscribe_publish_sample -tests/integration/integration_tests_mbedtls -tests/integration/integration_tests_mbedtls_mt - -# Ignore test artifacts -objs/* -testLibs/* - -# Ignore CppUTest and mbed TLS -external_libs/CppUTest/* -external_libs/mbedTLS/* - -# Ignore credentials -certs/* diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/.travis.yml b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/.travis.yml deleted file mode 100644 index 509ccf78e..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/.travis.yml +++ /dev/null @@ -1,44 +0,0 @@ -language: c - -install: - # Remove placeholders. - - rm external_libs/CppUTest/* - - rm external_libs/mbedTLS/* - - # Get mbedtls. - - wget -qO- https://github.com/ARMmbed/mbedtls/archive/mbedtls-2.16.5.tar.gz | tar xvz -C external_libs/mbedTLS --strip-components=1 - - # Get CppUTest. - - wget -qO- https://github.com/cpputest/cpputest/archive/v3.6.tar.gz | tar xvz -C external_libs/CppUTest --strip-components=1 - -script: - # Verify that the samples build. - - cd samples/linux/jobs_sample - - make -j2 - - cd ../shadow_sample - - make -j2 - - cd ../shadow_sample_console_echo - - make -j2 - - cd ../subscribe_publish_library_sample - - make -j2 - - cd ../subscribe_publish_sample - - make -j2 - - # Build and run unit tests. - - cd ../../../ - - make build-cpputest -j2 - - make all_no_tests -j2 - - ./IotSdkC_tests -v - - # Set up integration tests if not a pull request. - - if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then cd tests/integration; fi - - if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then sed -i 's/^.*#define AWS_IOT_MQTT_HOST.*$/#define AWS_IOT_MQTT_HOST "'"$AWS_IOT_ENDPOINT"'"/' include/aws_iot_config.h; fi - - if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then make app -j2; fi - - # Import credentials for integration tests. - - if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then wget https://www.amazontrust.com/repository/AmazonRootCA1.pem -O ../../certs/rootCA.crt; fi - - if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then echo -e $AWS_IOT_CLIENT_CERT > ../../certs/cert.pem; fi - - if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then echo -e $AWS_IOT_PRIVATE_KEY > ../../certs/privkey.pem; fi - - # Run integration tests. - - if [ "$TRAVIS_PULL_REQUEST" = "false" ]; then ./integration_tests_mbedtls; fi diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/CHANGELOG.md b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/CHANGELOG.md deleted file mode 100644 index 497128753..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/CHANGELOG.md +++ /dev/null @@ -1,233 +0,0 @@ -# Change Log - -## [3.0.1](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v3.0.1) (May 10, 2018) - -Bugfixes: - - - [#167](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/167), [#168](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/168) Fixed issues reported by Coverity Scan. - - [#177](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/177) Fixes a memory corruption bug and handling of timeouts. - -Other: - - - Add .travis.yml for Travis CI. - - Removed C++ sample. - - Removed includes of `inttypes.h`, which doesn't exist on some systems. - - [#175](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/175) Added comments on static allocation of MQTT topics. - -## [3.0.0](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v3.0.0) (Apr 17, 2018) - -Bugfixes: - - - [#152](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/152) Fixes potential buffer overflows in `parseStringValue` by requiring a size parameter in `jsonStruct_t`. - - [#155](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/155) Fixes other memory corruption bugs; also improves stability. - -The two bug fixes above are not backwards compatible with v2.3.0. Please see [README.md](README.md#migrating-from-2x-to-3x) for details on migrating to v3.0.0. - -## [2.3.0](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v2.3.0) (Mar 21, 2018) - -New Features: - - - Add [AWS IoT Jobs](https://docs.aws.amazon.com/iot/latest/developerguide/iot-jobs.html) support. - - Use AWS IoT Core support for MQTT over port 443. MQTT connection now defaults to port 443. - -Pull requests: - - - [#124](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/124) - Thing Shadow: Fix potential shadow buffer overflow - - [#135](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/135) - mbedtls_wrap: Fix unintialized variable usage - - Fix bugs in long-running integration tests. - -## [2.2.1](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v2.2.1) (Dec 26, 2017) - -Bugfixes: - - - [#115](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/115) - Issue with new client metrics - -Pull requests: - - - [#112](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/112) - Initialize msqParams.isRetained to 0 in publishToShadowAction() - - [#118](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/118) - mqttInitParams.mqttPacketTimeout_ms initialized - -## [2.2.0](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v2.2.0) (Nov 22, 2017) - -New Features: - - - Added SDK metrics string into connect packet - -Bugfixes: - - - [#49](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/49) - Add support for SHADOW_JSON_STRING as supported value - - [#57](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/57) - remove unistd.h - - [#58](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/58) - Fix return type of aws_iot_mqtt_internal_is_topic_matched - - [#59](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/95) - Fix extraneous assignment - - [#62](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/62) - Clearing SubscriptionList entries in shadowActionAcks after subscription failure - - [#63](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/63) - Stack overflow when IOT_DEBUG is enabled - - [#66](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/66) - Bug in send packet function - - [#69](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/69) - Fix for broken deleteActionHandler in shadow API - - [#71](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/71) - Prevent messages on /update/accepted from incrementing shadowJsonVersionNum in delta - - [#73](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/73) - wait for all messages to be received in subscribe publish sample - - [#96](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/96) - destroy TLS instance even if disconnect send fails - - Fix for aws_iot_mqtt_resubscribe not properly resubscribing to all topics - - Update MbedTLS Network layer Readme to remove specific version link - - Fix for not Passing througheError code on aws_iot_shadow_connect failure - - Allow sending of SHADOW_JSON_OBJECT to the shadow - - Ignore delta token callback for metadata - - Fix infinite publish exiting early in subscribe publish sample - -Improvements: - - - Updated jsmn to latest commit - - Change default keepalive interval to 600 seconds - -Pull requests: - - - [#29](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/29) - three small fixes - - [#59](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/59) - Fixed MQTT header constructing and parsing - - [#88](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/88) - Fix username and password are confused - - [#78](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/78) - Fixed compilation warnings - - [#102](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/102) - Corrected markdown headers - - [#105](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/105) - Fixed warnings when compiling - -## [2.1.1](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v2.1.1) (Sep 5, 2016) - -Bugfixes/Improvements: - - - Network layer interface improvements to address reported issues - - Incorporated GitHub pull request [#41](https://github.com/aws/aws-iot-device-sdk-embedded-c/pull/41) - - Bugfixes for issues [#36](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/36) and [#33](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/33) - -## [2.1.0](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v2.1.0) (Jun 15, 2016) - -New features: - - - Added unit tests, further details can be found in the testing readme [here](https://github.com/aws/aws-iot-device-sdk-embedded-c/blob/master/tests/README.md/) - - Added sample to demonstrate building the SDK as library - - Added sample to demonstrate building the SDK in C++ - -Bugfixes/Improvements: - - - Increased default value of Maximum Reconnect Wait interval to 128 secs - - Increased default value of MQTT Command Timeout in Shadow Connect to 20 secs - - Shadow null/length checks - - Client Id Length not passed correctly in shadow connect - - Add extern C to headers and source files, added sample to demonstrate usage with C++ - - Delete/Accepted not being reported, callback added for delete/accepted - - Append IOT_ to all Debug macros (eg. DEBUG is now IOT_DEBUG) - - Fixed exit on error for subscribe_publish_sample - -## [2.0.0](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v2.0.0) (April 28, 2016) - -New features: - - - Refactored API to make it instance specific. This is a breaking change in the API from 1.x releases because a Client Instance parameter had to be added to all APIs - - Added Threading library porting layer wrapper - - Added support for multiple connections from one application - - Shadows and connections de-linked, connection needs to be set up separately, can be used independently of shadow - - Added integration tests for testing SDK functionality - -Bugfixes/Improvements: - - - Yield cannot be called again while waiting for application callback to return - - Fixed issue with TLS layer handles not being cleaned up properly on connection failure reported [here](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/16) - - Renamed timer_linux.h to timer_platform.h as requested [here](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/5) - - Adds support for disconnect handler to shadow. A similar pull request can be found [here](https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/9) - - New SDK folder structure, cleaned and simplified code structure - - Removed Paho Wrapper, Merge MQTT into SDK code, added specific error codes - - Refactored Network and Timer layer wrappers, added specific error codes - - Refactored samples and makefiles - -## [1.1.2](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v1.1.2) (April 22, 2016) - -Bugfixes/Improvements: - - - Signature mismatch in MQTT library file fixed - - Makefiles have a protective target on the top to prevent accidental execution - -## [1.1.1](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v1.1.1) (April 1, 2016) - -Bugfixes/Improvements: - - - Removing the Executable bit from all the files in the repository. Fixing [this](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/14) issue - - Refactoring MQTT client to remove declaration after statement warnings - - Fixing [this](https://forums.aws.amazon.com/thread.jspa?threadID=222467&tstart=0) bug - - -## [1.1.0](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v1.1.0) (February 10, 2016) -Features: - - - Auto Reconnect and Resubscribe - -Bugfixes/Improvements: - - - MQTT buffer handling incase of bigger message - - Large timeout values converted to seconds and milliseconds - - Dynamic loading of Shadow parameters. Client ID and Thing Name are not hard-coded - - MQTT Library refactored - - -## [1.0.1](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v1.0.1) (October 21, 2015) - -Bugfixes/Improvements: - - - Paho name changed to Eclipse Paho - - Renamed the Makefiles in the samples directory - - Device Shadow - Delete functionality macro fixed - - `subscribe_publish_sample` updated - -## [1.0.0](https://github.com/aws/aws-iot-device-sdk-embedded-C/releases/tag/v1.0.0) (October 8, 2015) - -Features: - - - Release to github - - SDK tarballs made available for public download - -Bugfixes/Improvements: - - Updated API documentation - -## 0.4.0 (October 5, 2015) - -Features: - - - Thing Shadow Actions - Update, Delete, Get for any Thing Name - - aws_iot_config.h file for easy configuration of parameters - - Sample app for talking with console's Interactive guide - - disconnect handler for the MQTT client library - -Bugfixes/Improvements: - - - mbedTLS read times out every 10 ms instead of hanging for ever - - mbedTLS handshake failure handled - -## 0.3.0 (September 14, 2015) - -Features: - - - Testing with mbedTLS, prepping for relase - -Bugfixes/Improvements: - - - Refactored to break out timer and network interfaces - -## 0.2.0 (September 2, 2015) - -Features: - - - Added initial Shadow implementation + example - - Added hostname verification to OpenSSL example - - Added iot_log interface - - Initial API Docs (Doxygen) - -Bugfixes/Improvements: - - - Fixed yield timeout - - Refactored APIs to pass by reference vs value - -## 0.1.0 (August 12, 2015) - -Features: - - - Initial beta release - - MQTT Publish and Subscribe - - TLS mutual auth on linux with OpenSSL - -Bugfixes/Improvements: - - N/A diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/CODE_OF_CONDUCT.md b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/CODE_OF_CONDUCT.md deleted file mode 100644 index 3b6446687..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/CODE_OF_CONDUCT.md +++ /dev/null @@ -1,4 +0,0 @@ -## Code of Conduct -This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). -For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact -opensource-codeofconduct@amazon.com with any additional questions or comments. diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/CONTRIBUTING.md b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/CONTRIBUTING.md deleted file mode 100644 index eb63eaed2..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/CONTRIBUTING.md +++ /dev/null @@ -1,61 +0,0 @@ -# Contributing Guidelines - -Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional -documentation, we greatly value feedback and contributions from our community. - -Please read through this document before submitting any issues or pull requests to ensure we have all the necessary -information to effectively respond to your bug report or contribution. - - -## Reporting Bugs/Feature Requests - -We welcome you to use the GitHub issue tracker to report bugs or suggest features. - -When filing an issue, please check [existing open](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues), or [recently closed](https://github.com/aws/aws-iot-device-sdk-embedded-C/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aclosed%20), issues to make sure somebody else hasn't already -reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: - -* A reproducible test case or series of steps -* The version of our code being used -* Any modifications you've made relevant to the bug -* Anything unusual about your environment or deployment - - -## Contributing via Pull Requests -Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: - -1. You are working against the latest source on the *master* branch. -2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. -3. You open an issue to discuss any significant work - we would hate for your time to be wasted. - -To send us a pull request, please: - -1. Fork the repository. -2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. -3. Ensure local tests pass. -4. Commit to your fork using clear commit messages. -5. Send us a pull request, answering any default questions in the pull request interface. -6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. - -GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and -[creating a pull request](https://help.github.com/articles/creating-a-pull-request/). - - -## Finding contributions to work on -Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels ((enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any ['help wanted'](https://github.com/aws/aws-iot-device-sdk-embedded-C/labels/help%20wanted) issues is a great place to start. - - -## Code of Conduct -This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). -For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact -opensource-codeofconduct@amazon.com with any additional questions or comments. - - -## Security issue notifications -If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. - - -## Licensing - -See the [LICENSE](https://github.com/aws/aws-iot-device-sdk-embedded-C/blob/master/LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. - -We may ask you to sign a [Contributor License Agreement (CLA)](http://en.wikipedia.org/wiki/Contributor_License_Agreement) for larger changes. diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/CppUTestMakefileWorker.mk b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/CppUTestMakefileWorker.mk deleted file mode 100644 index 9f3c3054f..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/CppUTestMakefileWorker.mk +++ /dev/null @@ -1,575 +0,0 @@ -#--------- -# -# 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/LICENSE.txt b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/LICENSE.txt deleted file mode 100644 index 1b6cbea0c..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/LICENSE.txt +++ /dev/null @@ -1,120 +0,0 @@ -############################################################################################################################# - - -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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/Makefile b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/Makefile deleted file mode 100644 index 4f37f9219..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/Makefile +++ /dev/null @@ -1,131 +0,0 @@ -#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 diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/NOTICE.txt b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/NOTICE.txt deleted file mode 100644 index c3f856f11..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/NOTICE.txt +++ /dev/null @@ -1,16 +0,0 @@ -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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/PortingGuide.md b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/PortingGuide.md deleted file mode 100644 index 2ca5f8d8c..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/PortingGuide.md +++ /dev/null @@ -1,145 +0,0 @@ -# Porting Guide - -## Scope -The scope of this document is to provide instructions to modify the provided source files and functions in this SDK to run in a variety of embedded C–based environments (e.g. real-time OS, embedded Linux) and to be adjusted to use a specific TLS implementation as available with specific hardware platforms. - -## Contents of the SDK - -The C-code files of this SDK are delivered via the following directory structure (see comment behind folder name for an explanation of its content). - -Current SDK Directory Layout (mbedTLS) - -|--`certs` (Private key, device certificate and Root CA)
-|--`docs` (Developer guide & API documentation)
-|--`external_libs` (external libraries - jsmn, mbedTLS)
-|--`include` (Header files of the AWS IoT device SDK)
-|--`src` (Source files of the AWS IoT device SDK)
-|--`platform` (Platform specific files)
-|--`samples` (Samples including makefiles for building on mbedTLS)
-|--`tests` (Tests for verifying SDK is functioning as expected)
- -All makefiles in this SDK were configured using the documented folder structure above, so moving or renaming folders will require modifications to makefiles. - -## Explanation of folders and their content - - * `certs` : This directory is initially empty and will need to contain the private key, the client certificate and the root CA. The client certificate and private key can be downloaded from the AWS IoT console or be created using the AWS CLI commands. The root CA can be downloaded from [Symantec](https://www.symantec.com/content/en/us/enterprise/verisign/roots/VeriSign-Class%203-Public-Primary-Certification-Authority-G5.pem). - - * `docs` : SDK API and file documentation. - - * `external_libs` : The mbedTLS and jsmn source files. The jsmn source files are always present. The mbedTLS source files are only included when downloading the tarball version of the SDK. - - * `include` : This directory contains the header files that an application using the SDK needs to include. - - * `src` : This directory contains the SDK source code including the MQTT library, device shadow code and utilities. - - * `platform` : Platform specific files for timer, TLS and threading layers. Includes a reference implementation for the linux using mbedTLS and pthread. - - * `samples` : This directory contains sample applications as well as their makefiles. The samples include a simple MQTT example which publishes and subscribes to the AWS IoT service as well as a device shadow example that shows example usage of the device shadow functionality. - - * `tests` : Contains tests for verifying SDK functionality. For further details please check the readme file included with the tests [here](https://github.com/aws/aws-iot-device-sdk-embedded-C/blob/master/tests/README.md/). - -## Integrating the SDK into your environment - -This section explains the API calls that need to be implemented in order for the Device SDK to run on your platform. The SDK interfaces follow the driver model where only prototypes are defined by the Device SDK itself while the implementation is delegated to the user of the SDK to adjust it to the platform in use. The following sections list the needed functionality for the device SDK to run successfully on any given platform. - -### Timer Functions - -A timer implementation is necessary to handle request timeouts (sending MQTT connect, subscribe, etc. commands) as well as connection maintenance (MQTT keep-alive pings). Timers need millisecond resolution and are polled for expiration so these can be implemented using a "milliseconds since startup" free-running counter if desired. In the synchronous sample provided with this SDK only one command will be "in flight" at one point in time plus the client's ping timer. - -Define the `Timer` Struct as in `timer_platform.h` - -`void init_timer(Timer *);` -init_timer - A timer structure is initialized to a clean state. - -`bool has_timer_expired(Timer *);` -has_timer_expired - a polling function to determine if the timer has expired. - -`void countdown_ms(Timer *, uint32_t);` -countdown_ms - set the timer to expire in x milliseconds and start the timer. - -`void countdown_sec(Timer *, uint32_t);` -countdown_sec - set the timer to expire in x seconds and start the timer. - -`uint32_t left_ms(Timer *);` -left_ms - query time in milliseconds left on the timer. - -`void delay(unsigned milliseconds)` -delay - sleep for the specified number of milliseconds. - - -### 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. - -## 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/README.md b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/README.md deleted file mode 100644 index 2686ad6a9..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/README.md +++ /dev/null @@ -1,270 +0,0 @@ -# AWS IoT Device SDK for Embedded C - -This tag [3.1.5](https://github.com/aws/aws-iot-device-sdk-embedded-C/tree/v3.1.5) contains the v3 version of AWS IoT Device SDK for Embedded C. No new features will be added to this tag; instead, only bug fixes will be made and minimally tested. - - -## 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](./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. - -### Jobs -The Device SDK implements features to facilitate use of the AWS Jobs service. The Jobs service can be used for device management tasks such as updating program files, rotating device certificates, or running other maintenance tasks such are restoring device settings or restarting devices. - -## Design Goals of this SDK -The embedded C SDK was specifically designed for resource constrained devices (running on micro-controllers and RTOS). - -Primary aspects are: - * Flexibility in picking and choosing functionality (reduce memory footprint) - * Static memory only (no malloc’s) - * Configurable resource usage(JSON tokens, MQTT subscription handlers, etc…) - * Can be ported to a different RTOS, uses wrappers for OS specific functions - -For more information on the Architecture of the SDK refer [here](http://aws-iot-device-sdk-embedded-c-docs.s3-website-us-east-1.amazonaws.com/index.html) - -## Collection of Metrics -Beginning with Release v2.2.0 of the SDK, AWS collects usage metrics indicating which language and version of the SDK is being used. This allows us to prioritize our resources towards addressing issues faster in SDKs that see the most and is an important data point. However, we do understand that not all customers would want to report this data by default. In that case, the sending of usage metrics can be easily disabled by the user by setting the `DISABLE_METRICS` flag to true in the -`aws_iot_config.h` for each application. - -## How to get started ? -Ensure you understand the AWS IoT platform and create the necessary certificates and policies. For more information on the AWS IoT platform please visit the [AWS IoT developer guide](http://docs.aws.amazon.com/iot/latest/developerguide/iot-security-identity.html). - -In order to quickly get started with the AWS IoT platform, we have ported the SDK for POSIX type Operating Systems like Ubuntu, OS X and RHEL. The SDK is configured for the mbedTLS library and can be built out of the box with *GCC* using *make utility*. You'll need to download mbedTLS from the official ARMmbed repository. We recommend that you pick the latest version of 2.16 LTS release in order to have up-to-date security fixes. - -## Installation -This section explains the individual steps to retrieve the necessary files and be able to build your first application using the AWS IoT device SDK for embedded C. - -Steps: - - * Create a directory to hold your application e.g. (/home/*user*/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. microcontrollers). - -## 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/) - -## Migrating from 2.x to 3.x -AWS IoT Device SDK for Embedded C v3.0.0 fixes two bugs (see #152 and #155) that create a potential buffer overflows. This version is not backward compatible with previous versions, so users will need to recompile their applications with the new version. - -Users of AWS IoT Device Shadows or Json utility functions such as `extractClientToken`, `emptyJsonWithClientToken`, `isJsonValidAndParse` and `isReceivedJsonValid` are encouraged to upgrade to version v3.0.0. For users who cannot upgrade, review all parts of your solution where user input can be sent to the device, and ensure sufficient authorization of these operations is enforced. - -Details of the required changes to public functions and data structures are shown below: - -### Changes in the `jsonStruct` data structure: -The member `dataLength` has been added to struct `jsonStruct`, which is declared in [include/aws_iot_shadow_json_data.h](include/aws_iot_shadow_json_data.h#L60). - -```c -struct jsonStruct { - const char * pKey; - void * pData; - size_t dataLength; - JsonPrimitiveType type; - JsonStructCallback_t cb; -}; -``` - -The size of the buffer `pData` must now be specified by `dataLength`. **Failure to do so may result in undefined behavior**. Below are examples of the code changes required to use the new jsonStruct. - -With a primitive data type, such as `int32_t`: - -```c -… -jsonStruct_t exampleJsonStruct; -int32_t value = 0L; - -/* Set the members of exampleJsonStruct. */ -exampleJsonStruct.pKey = “exampleKey”; -exampleJsonStruct.pData = &value; -exampleJsonStruct.type = SHADOW_JSON_INT32; -exampleJsonStruct.cb = exampleCallback; - -/* Register a delta callback using example JsonStruct. */ -aws_iot_shadow_register_delta(&mqttClient, &exampleJsonStruct); -… -``` - -Version 3.0.0 will require the following code: - -```c -… -jsonStruct_t exampleJsonStruct; -int32_t value = 0L; - -/* Set the members of exampleJsonStruct. */ -exampleJsonStruct.pKey = “exampleKey”; -exampleJsonStruct.pData = &value; -exampleJsonStruct.dataLength = sizeof(int32_t); /* sizeof(value) also OK.*/ -exampleJsonStruct.type = SHADOW_JSON_INT32; -exampleJsonStruct.cb = exampleCallback; - -/* Register a delta callback using example JsonStruct. */ -aws_iot_shadow_register_delta(&mqttClient, &exampleJsonStruct); -… -``` - -With a string, versions up to v2.3.0 would require the following code: - -```c -… -jsonStruct_t exampleJsonStruct; -char stringBuffer[SIZE_OF_BUFFER]; -/* Set the members of exampleJsonStruct. */ -exampleJsonStruct.pKey = “exampleKey”; -exampleJsonStruct.pData = stringBuffer; -exampleJsonStruct.type = SHADOW_JSON_STRING; -exampleJsonStruct.cb = exampleCallback; -/* Register a delta callback using example JsonStruct. */ -aws_iot_shadow_register_delta(&mqttClient, &exampleJsonStruct); -… -``` - -Version 3.0.0 will require the following code: - -```c -… -jsonStruct_t exampleJsonStruct; -char stringBuffer[SIZE_OF_BUFFER]; -/* Set the members of exampleJsonStruct. */ -exampleJsonStruct.pKey = “exampleKey”; -exampleJsonStruct.pData = stringBuffer; -exampleJsonStruct.dataLength = SIZE_OF_BUFFER; -exampleJsonStruct.type = SHADOW_JSON_STRING; -exampleJsonStruct.cb = exampleCallback; -/* Register a delta callback using example JsonStruct. */ -aws_iot_shadow_register_delta(&mqttClient, &exampleJsonStruct); -… -``` - -### Changes in parseStringValue: -The function `parseStringValue`, declared in [include/aws_iot_json_utils.h](include/aws_iot_json_utils.h#L179) and implemented in [src/aws_iot_json_utils.c](src/aws_iot_json_utils.c#L184), now requires the inclusion of a buffer length. Its new function signature is: - -```c -IoT_Error_t parseStringValue(char *buf, size_t bufLen, const char *jsonString, jsmntok_t *token); -``` - -Below is an example of code changes required to use the new parseStringValue. - -With up to version v2.3.0: - -```c -… -char* jsonString = “…”; -jsmntok_t jsmnTokens[NUMBER_OF_JSMN_TOKENS]; -char stringBuffer[SIZE_OF_BUFFER]; -parseStringValue(stringBuffer, jsonString, jsmnTokens); -… -``` - -Version 3.0.0 will require the following code: - -```c -… -char* jsonString = “…”; -jsmntok_t jsmnTokens[NUMBER_OF_JSMN_TOKENS]; -char stringBuffer[SIZE_OF_BUFFER]; -parseStringValue(stringBuffer, SIZE_OF_BUFFER, jsonString, jsmnTokens); -… -``` - -### Changes to functions intended for internal usage: -Version 3.0.0 changes the signature of four functions intended for internal usage. The new signatures explicitly carry the information for the size of the buffer or JSON document passed as a parameter to the functions. Users of the SDK may need to change their code and recompile to ingest the changes. We report the old and new signatures below. - -#### Old signatures: - -```c -bool extractClientToken(const char *pJsonDocument, char *pExtractedClientToken); - -static void emptyJsonWithClientToken(char *pBuffer); - -bool isJsonValidAndParse(const char *pJsonDocument, void *pJsonHandler, int32_t *pTokenCount); - -bool isReceivedJsonValid(const char *pJsonDocument); -``` - -#### New signatures: - -```c -bool extractClientToken(const char *pJsonDocument, size_t jsonSize, char *pExtractedClientToken, size_t clientTokenSize); - -static void emptyJsonWithClientToken(char *pBuffer, size_t bufferSize); - -bool isJsonValidAndParse(const char *pJsonDocument, size_t jsonSize, void *pJsonHandler, int32_t *pTokenCount); - -bool isReceivedJsonValid(const char *pJsonDocument, size_t jsonSize); -``` - -## 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/certs/README.txt b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/certs/README.txt deleted file mode 100644 index 8df3d0208..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/certs/README.txt +++ /dev/null @@ -1,4 +0,0 @@ -# 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/architecture.png b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/architecture.png deleted file mode 100644 index d010a47e3..000000000 Binary files a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/architecture.png and /dev/null differ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/architecture.txt b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/architecture.txt deleted file mode 100644 index 77218ea51..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/architecture.txt +++ /dev/null @@ -1,32 +0,0 @@ -/** -@page architecture SDK Architecture and Design -@brief This page documents the architecture and design goals of this SDK. - -The Embedded C SDK has a layered architecture. It is currently based on the MQTT protocol, but may support protocols like HTTP in the future. - -This SDK is primarily targeted for resource-constrained devices. - -@section architecture_considerations Considerations during design -- Low memory footprint (around 6k of code size without TLS library for the MQTT layer) -- Flexibility in picking and choosing functionality -- Static memory only (no malloc) -- Configurable resource usage (JSON tokens, MQTT subscription handlers, etc.) -- Portability across RTOSes - -@section architecture_diagram Layered architecture -@brief There are primarily 3 layers in the SDK as shown in the diagram below. - -@image html architecture.png - -@subsection architecture_tls TLS layer - -This SDK uses TLS sockets to talk to the server. We provide wrappers around mbed TLS (ARM) that allow the libraries to connect with AWS IoT Platform. - -@subsection architecture_mqtt AWS IoT MQTT client - -The MQTT library included in this SDK is a modification of the [Paho C MQTT client](https://www.eclipse.org/paho/clients/c/). MQTT is a standardized publish subscribe protocol popular on embedded devices. AWS IoT supports the MQTT protocol for communication with devices. This MQTT library can be used standalone or with other AWS IoT services such as Thing Shadows or Jobs. - -@subsection architecture_shadow Thing Shadow - -This SDK provides a client implementation for [AWS IoT Thing Shadows](https://docs.aws.amazon.com/iot/latest/developerguide/iot-device-shadows.html). A device's Shadow is a JSON document that is used to store and retrieve its current state information in the cloud regardless of whether it is connected to the Internet. -*/ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/common b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/common deleted file mode 100644 index 67181c419..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/common +++ /dev/null @@ -1,95 +0,0 @@ -# SDK version. -PROJECT_NUMBER = "3" - -# Doxygen layout file for libraries. -LAYOUT_FILE = doc/config/layout_library.xml - -# Documentation output directory. -OUTPUT_DIRECTORY = doc/output/ - -# Don't generate LaTeX documentation -GENERATE_LATEX = NO - -# Don't rearrange members in the input files. -SORT_MEMBER_DOCS = NO - -# Silence output (warnings only). -QUIET = YES - -# Configure Doxygen for C. -OPTIMIZE_OUTPUT_FOR_C = YES -TYPEDEF_HIDES_STRUCT = YES - -# Disable the tab bar and use treeview instead. -DISABLE_INDEX = YES -GENERATE_TREEVIEW = YES - -# All files should have unique names, so showing the full path is unnecessary. -FULL_PATH_NAMES = NO - -# Disable the default Doxygen diagrams. -HAVE_DOT = NO - -# Disable the default Doxygen search engine (for now). -SEARCHENGINE = NO - -# Use custom header file, footer file, and stylesheet. -HTML_HEADER = doc/config/html/header.html -HTML_FOOTER = doc/config/html/footer.html -HTML_EXTRA_STYLESHEET = doc/config/html/style.css - -# Don't show external pages or groups. -EXTERNAL_GROUPS = NO -EXTERNAL_PAGES = NO - -# Preprocessor defines. -PREDEFINED = _ENABLE_THREAD_SUPPORT_ - -# Alias for starting a dependencies section. -ALIASES += dependencies{2}="@section \1_dependencies Dependencies^^@brief Dependencies of the \2.^^^^" - -# Alias for starting a configuration settings page. -ALIASES += describeconfig="Configuration settings are C pre-processor constants. They can be set with a @c #`define` in the config file (`iot_config.h`) or by using a compiler option such as `-D` in gcc. If a configuration setting is not defined, the library will use a \"sensible\" default value (unless otherwise noted). Because they are compile-time constants, a library must be rebuilt if a configuration setting is changed." -ALIASES += configpage{2}="@page \1_config Configuration^^@brief Configuration settings of the \2.^^^^@describeconfig^^@par configpagemarker" -ALIASES += configpage{4}="@page \1_config \3 Configuration^^@brief Configuration settings of the \2.^^^^@describeconfig^^^^The settings on this page only affect the [\2](@ref \1). In addition to the settings on this page, them \2 will also be affected by [settings that affect all \4](@ref global_\4_config).^^@par configpagemarker" -ALIASES += globalconfigpage{3}="@page global_\1_config Global \2 Configuration^^^^@describeconfig^^@brief Configuration settings that affect all \3.^^@par configpagemarker" - -# Aliases for "Possible values", "Recommended values", and "Default values" -# used in configuration setting pages. -ALIASES += configpossible="Possible values: " -ALIASES += configrecommended="Recommended values: " -ALIASES += configdefault="Default value (if undefined): " - -# Alias for starting a constants page. -ALIASES += constantspage{2}="@page \1_constants Constants^^@brief Defined constants of the \2.^^^^Libraries may @c #`define` constants in their headers with special meanings. This page describes the meanings and uses of any constants defined by the \2. Related constants are shown in a single section on this page.^^" - -# Alias for starting a functions page. -ALIASES += functionspage{2}="@page \1_functions Functions^^@brief Functions of the \2.^^^^The \2 consists of the following functions." -ALIASES += functionspage{3}="@page \1_functions \3^^@brief Functions of the \2.^^^^The \2 consists of the following functions." - -# Alias for listing a single function on a functions page. -ALIASES += functionname{1}="@subpage \1
^^ @copybrief \1^^" - -# Alias for creating a page for a single function. -ALIASES += functionpage{3}="@page \2_function_\3 \1^^^^@snippet this declare_\2_\3^^@copydoc \1" - -# Alias for starting a handles group. -ALIASES += handles{2}="@defgroup \1_datatypes_handles Handles^^@brief Opaque handles of the \2." - -# Alias for starting an enum group. -ALIASES += enums{2}="@defgroup \1_datatypes_enums Enumerated types^^@brief Enumerated types of the \2." - -# Alias for starting a function pointers group. -ALIASES += functionpointers{2}="@defgroup \1_datatypes_functionpointers Function pointers types^^@brief Function pointers types of the \2." - -# Alias for starting a structs group. -ALIASES += structs{2}="@defgroup \1_datatypes_structs Structured types^^@brief Structured types of the \2." - -# Alias for starting a parameter structures group. -ALIASES += paramstructs{2}="@defgroup \1_datatypes_paramstructs Parameter structures^^@brief Structures passed as parameters to [\2 functions](@ref \1_functions)^^^^These structures are passed as parameters to library functions. Documentation for these structures will state the functions associated with each parameter structure and the purpose of each member." - -# Alias for "Parameter for". -ALIASES += paramfor="Parameter for: " - -# Alias for parameter structure initializers. -ALIASES += initializer{2}="All instances of #\1 should be initialized with #\2.^^" diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/html/footer.html b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/html/footer.html deleted file mode 100644 index 18c84eb78..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/html/footer.html +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - - - - - - - - diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/html/header.html b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/html/header.html deleted file mode 100644 index a60bb68d3..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/html/header.html +++ /dev/null @@ -1,88 +0,0 @@ - - - - - - - - - - - - - - $projectname: $title - - - - - $title - - - - - - $search - $mathjax - - $extrastylesheet - - - -
- - -
- - - - - - - - - - - - - - - - - - - - - - - - -
-
- AWS IoT Device SDK C: - $projectname -
- -
- $projectbrief -
- -
-
- $projectbrief -
-
- $searchbox -
- Return to main page ↑ -
-
- -$treeview - - - diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/html/style.css b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/html/style.css deleted file mode 100644 index 433d4cd4b..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/html/style.css +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Stylesheet for Doxygen HTML output. - * - * This file defines styles for custom elements in the header/footer and - * overrides some of the default Doxygen styles. - * - * Styles in this file do not affect the treeview sidebar. - */ - -/* Set the margins to place a small amount of whitespace on the left and right - * side of the page. */ -div.contents { - margin-left:4em; - margin-right:4em; -} - -/* Justify text in paragraphs. */ -p { - text-align: justify; -} - -/* Style of section headings. */ -h1 { - border-bottom: 1px solid #879ECB; - color: #354C7B; - font-size: 160%; - font-weight: normal; - padding-bottom: 4px; - padding-top: 8px; -} - -/* Style of subsection headings. */ -h2:not(.memtitle):not(.groupheader) { - font-size: 125%; - margin-bottom: 0px; - margin-top: 16px; - padding: 0px; -} - -/* Style of paragraphs immediately after subsection headings. */ -h2 + p { - margin: 0px; - padding: 0px; -} - -/* Style of subsubsection headings. */ -h3 { - font-size: 100%; - margin-bottom: 0px; -} - -/* Style of paragraphs immediately after subsubsection headings. */ -h3 + p { - margin-top: 0px; -} - -/* Style of the prefix "AWS IoT Device SDK C" that appears in the header. */ -#csdkprefix { - color: #757575; -} - -/* Style of the "Return to main page" link that appears in the header. */ -#returntomain { - padding: 0.5em; -} - -/* Style of the dividers on Configuration Settings pages. */ -div.configpagedivider { - margin-left: 0px !important; - margin-right: 0px !important; - margin-top: 20px !important; -} - -/* Style of configuration setting names. */ -dl.section.user ~ h1 { - border-bottom: none; - color: #000000; - font-family: monospace, fixed; - font-size: 16px; - margin-bottom: 0px; - margin-left: 2em; - margin-top: 1.5em; -} - -/* Style of paragraphs on a configuration settings page. */ -dl.section.user ~ * { - margin-bottom: 10px; - margin-left: 4em; - margin-right: 4em; - margin-top: 0px; -} - -/* Hide the configuration setting marker. */ -dl.section.user { - display: none; -} - -/* Overrides for code fragments and lines. */ -div.fragment { - background: #ffffff; - border: none; - padding: 5px; -} - -div.line { - color: #3a3a3a; -} - -/* Overrides for code syntax highlighting colors. */ -span.comment { - color: #008000; -} - -span.keyword, span.keywordtype, span.keywordflow { - color: #0000ff; -} - -span.preprocessor { - color: #50015a; -} - -span.stringliteral, span.charliteral { - color: #800c0c; -} - -a.code, a.code:visited, a.line, a.line:visited { - color: #496194; -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/layout_library.xml b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/layout_library.xml deleted file mode 100644 index 7aebbfee9..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/layout_library.xml +++ /dev/null @@ -1,197 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/layout_main.xml b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/layout_main.xml deleted file mode 100644 index 7d9fc5e16..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/layout_main.xml +++ /dev/null @@ -1,200 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/main b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/main deleted file mode 100644 index 8ef18d1ef..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/main +++ /dev/null @@ -1,30 +0,0 @@ -# Include common configuration options. -@INCLUDE_PATH = doc/config -@INCLUDE = common - -# Basic project information. -PROJECT_NAME = "Main" - -# Library documentation output directory. -HTML_OUTPUT = main - -# Generate Doxygen tag file for this library. -GENERATE_TAGFILE = doc/tag/main.tag - -# Files to show on the main page. -INPUT = README.md \ - CHANGELOG.md \ - PortingGuide.md \ - doc/architecture.txt - -# Path to architecture image. -IMAGE_PATH += doc/ - -# Use repository README as main page. -USE_MDFILE_AS_MAINPAGE = README.md - -# Don't automatically link to library symbols. -AUTOLINK_SUPPORT = NO - -# Use the Main page layout file -LAYOUT_FILE = doc/config/layout_main.xml diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/mqtt b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/mqtt deleted file mode 100644 index 38da6f2f0..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/config/mqtt +++ /dev/null @@ -1,21 +0,0 @@ -# Include common configuration options. -@INCLUDE_PATH = doc/config -@INCLUDE = common - -# Basic project information. -PROJECT_NAME = "MQTT" -PROJECT_BRIEF = "MQTT v3.1.1 client library" - -# Library documentation output directory. -HTML_OUTPUT = mqtt - -# Generate Doxygen tag file for this library. -GENERATE_TAGFILE = doc/tag/mqtt.tag - -# Directories containing library source code. -INPUT = doc/lib \ - include/ \ - src/ - -# Library file names. -FILE_PATTERNS = *mqtt*.c *mqtt*.h *mqtt*.txt diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/lib/mqtt.txt b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/lib/mqtt.txt deleted file mode 100644 index 03a77d30f..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/doc/lib/mqtt.txt +++ /dev/null @@ -1,61 +0,0 @@ -/** -@mainpage -@anchor mqtt -@brief MQTT v3.1.1 client library. - -MQTT is a standardized publish subscribe protocol popular on embedded devices. The MQTT library provided with this SDK implements a subset of the MQTT v3.1.1 protocol. The sample application for Linux `subscribe_publish_sample.c` is provided as a starting point for using this library. - -The interface for communication over MQTT is provided in the file `aws_iot_mqtt_interface.h`. -- MQTT client context management: @ref mqtt_function_init and @ref mqtt_function_free -- Connection management: @ref mqtt_function_connect and @ref mqtt_function_disconnect -- Publishing messages to the server: @ref mqtt_function_publish -- Managing subscriptions: @ref mqtt_function_subscribe and @ref mqtt_function_unsubscribe -- Process incoming messages, reconnections, and keep-alive: @ref mqtt_function_yield - -@note In a multithreaded environment, always ensure that calls to this library's functions are serialized, such as with a lock or a queue. This library is not thread safe. - -@note This library does not support QoS 2 or retained messages. - -@section mqtt_configuration Configuration -@brief The following configuration settings are associated with this MQTT library. -- `AWS_IOT_MQTT_TX_BUF_LEN`
-Size of buffer for outgoing messages. -- `AWS_IOT_MQTT_RX_BUF_LEN`
-Size of buffer for incoming messages. Messages longer than this will be dropped. -- `AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS`
-Number of subscriptions that may be registered simultaneously. -- `AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL`
-The initial wait time before the first reconnect attempt. See @ref mqtt_autoreconnect. -- `AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL`
-The maximum wait time between reconnect attempts. See @ref mqtt_autoreconnect. -*/ - -/** -@page mqtt_autoreconnect Auto-reconnect -@brief This page describes the auto-reconnect mechanism of the MQTT library. - -The auto-reconnect mechanism can be enabled through the following methods: -- Set #IoT_Client_Init_Params.enableAutoReconnect to `true` when calling @ref mqtt_function_init. -- Call @ref mqtt_function_autoreconnect_set_status with `newStatus` set to `true`. @ref mqtt_function_autoreconnect_set_status must only be called after @ref mqtt_function_connect. - -Once enabled, this feature will attempt to reconnect to the server if the library detects a disconnection. The reconnections are handled through @ref mqtt_function_yield. In addition to re-establishing the network connection and MQTT session, all the previous subscriptions will be re-established. This restores the client-side subscriptions for both clean and persistent MQTT sessions. - -The following events are considered disconnects: -- Fatal errors returned from the TLS layer. -- Failure to send a ping request. -- Failure to receive a timely ping response. - -On all disconnect events, the #iot_disconnect_handler for an MQTT client will be called. - -Reconnect attempts are made with an exponential backoff strategy. -- `AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL`
-The initial wait time before the first reconnect attempt. -- `AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL`
-The maximum wait time between reconnect attempts. - -If a reconnect attempt after `AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL` fails, @ref mqtt_function_yield will return `NETWORK_RECONNECT_TIMED_OUT`. There will be no more reconnect attempts. If an application still wants to re-connect, it should call @ref mqtt_function_attempt_reconnect. - -Calling @ref mqtt_function_attempt_reconnect performs a single reconnect and resubscribe attempt. It is equivalent to a manual reconnect attempt. - -@note Since reconnects are handled by @ref mqtt_function_yield and a new TLS handshake for reconnection may take a significant amount of time, calls to @ref mqtt_function_yield that handle reconnections may block for longer than usual. -*/ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/external_libs/CppUTest/README.txt b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/external_libs/CppUTest/README.txt deleted file mode 100644 index 5b2e09255..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/external_libs/CppUTest/README.txt +++ /dev/null @@ -1,2 +0,0 @@ -# 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/external_libs/jsmn/jsmn.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/external_libs/jsmn/jsmn.c deleted file mode 100644 index e920e8620..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/external_libs/jsmn/jsmn.c +++ /dev/null @@ -1,344 +0,0 @@ -/* - * Copyright (c) 2010 Serge A. Zaitsev - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/** - * @file jsmn.c - * @brief Implementation of the JSMN (Jasmine) JSON parser. - * - * For more information on JSMN: - * @see http://zserge.com/jsmn.html - */ - -#include "jsmn.h" - -/** - * Allocates a fresh unused token from the token pull. - */ -static jsmntok_t *jsmn_alloc_token(jsmn_parser *parser, - jsmntok_t *tokens, size_t num_tokens) { - jsmntok_t *tok; - if (parser->toknext >= num_tokens) { - return NULL; - } - tok = &tokens[parser->toknext++]; - tok->start = tok->end = -1; - tok->size = 0; -#ifdef JSMN_PARENT_LINKS - tok->parent = -1; -#endif - return tok; -} - -/** - * Fills token type and boundaries. - */ -static void jsmn_fill_token(jsmntok_t *token, jsmntype_t type, - int start, int end) { - token->type = type; - token->start = start; - token->end = end; - token->size = 0; -} - -/** - * Fills next available token with JSON primitive. - */ -static int jsmn_parse_primitive(jsmn_parser *parser, const char *js, - size_t len, jsmntok_t *tokens, size_t num_tokens) { - jsmntok_t *token; - int start; - - start = parser->pos; - - for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { - switch (js[parser->pos]) { -#ifndef JSMN_STRICT - /* In strict mode primitive must be followed by "," or "}" or "]" */ - case ':': -#endif - case '\t' : case '\r' : case '\n' : case ' ' : - case ',' : case ']' : case '}' : - goto found; - } - if (js[parser->pos] < 32 || js[parser->pos] >= 127) { - parser->pos = start; - return JSMN_ERROR_INVAL; - } - } -#ifdef JSMN_STRICT - /* In strict mode primitive must be followed by a comma/object/array */ - parser->pos = start; - return JSMN_ERROR_PART; -#endif - -found: - if (tokens == NULL) { - parser->pos--; - return 0; - } - token = jsmn_alloc_token(parser, tokens, num_tokens); - if (token == NULL) { - parser->pos = start; - return JSMN_ERROR_NOMEM; - } - jsmn_fill_token(token, JSMN_PRIMITIVE, start, parser->pos); -#ifdef JSMN_PARENT_LINKS - token->parent = parser->toksuper; -#endif - parser->pos--; - return 0; -} - -/** - * Fills next token with JSON string. - */ -static int jsmn_parse_string(jsmn_parser *parser, const char *js, - size_t len, jsmntok_t *tokens, size_t num_tokens) { - jsmntok_t *token; - - int start = parser->pos; - - parser->pos++; - - /* Skip starting quote */ - for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { - char c = js[parser->pos]; - - /* Quote: end of string */ - if (c == '\"') { - if (tokens == NULL) { - return 0; - } - token = jsmn_alloc_token(parser, tokens, num_tokens); - if (token == NULL) { - parser->pos = start; - return JSMN_ERROR_NOMEM; - } - jsmn_fill_token(token, JSMN_STRING, start+1, parser->pos); -#ifdef JSMN_PARENT_LINKS - token->parent = parser->toksuper; -#endif - return 0; - } - - /* Backslash: Quoted symbol expected */ - if (c == '\\' && parser->pos + 1 < len) { - int i; - parser->pos++; - switch (js[parser->pos]) { - /* Allowed escaped symbols */ - case '\"': case '/' : case '\\' : case 'b' : - case 'f' : case 'r' : case 'n' : case 't' : - break; - /* Allows escaped symbol \uXXXX */ - case 'u': - parser->pos++; - for(i = 0; i < 4 && parser->pos < len && js[parser->pos] != '\0'; i++) { - /* If it isn't a hex character we have an error */ - if(!((js[parser->pos] >= 48 && js[parser->pos] <= 57) || /* 0-9 */ - (js[parser->pos] >= 65 && js[parser->pos] <= 70) || /* A-F */ - (js[parser->pos] >= 97 && js[parser->pos] <= 102))) { /* a-f */ - parser->pos = start; - return JSMN_ERROR_INVAL; - } - parser->pos++; - } - parser->pos--; - break; - /* Unexpected symbol */ - default: - parser->pos = start; - return JSMN_ERROR_INVAL; - } - } - } - parser->pos = start; - return JSMN_ERROR_PART; -} - -/** - * Parse JSON string and fill tokens. - */ -int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, - jsmntok_t *tokens, unsigned int num_tokens) { - int r; - int i; - jsmntok_t *token; - int count = parser->toknext; - - for (; parser->pos < len && js[parser->pos] != '\0'; parser->pos++) { - char c; - jsmntype_t type; - - c = js[parser->pos]; - switch (c) { - case '{': case '[': - count++; - if (tokens == NULL) { - break; - } - token = jsmn_alloc_token(parser, tokens, num_tokens); - if (token == NULL) - return JSMN_ERROR_NOMEM; - if (parser->toksuper != -1) { - tokens[parser->toksuper].size++; -#ifdef JSMN_PARENT_LINKS - token->parent = parser->toksuper; -#endif - } - token->type = (c == '{' ? JSMN_OBJECT : JSMN_ARRAY); - token->start = parser->pos; - parser->toksuper = parser->toknext - 1; - break; - case '}': case ']': - if (tokens == NULL) - break; - type = (c == '}' ? JSMN_OBJECT : JSMN_ARRAY); -#ifdef JSMN_PARENT_LINKS - if (parser->toknext < 1) { - return JSMN_ERROR_INVAL; - } - token = &tokens[parser->toknext - 1]; - for (;;) { - if (token->start != -1 && token->end == -1) { - if (token->type != type) { - return JSMN_ERROR_INVAL; - } - token->end = parser->pos + 1; - parser->toksuper = token->parent; - break; - } - if (token->parent == -1) { - if(token->type != type || parser->toksuper == -1) { - return JSMN_ERROR_INVAL; - } - break; - } - token = &tokens[token->parent]; - } -#else - for (i = parser->toknext - 1; i >= 0; i--) { - token = &tokens[i]; - if (token->start != -1 && token->end == -1) { - if (token->type != type) { - return JSMN_ERROR_INVAL; - } - parser->toksuper = -1; - token->end = parser->pos + 1; - break; - } - } - /* Error if unmatched closing bracket */ - if (i == -1) return JSMN_ERROR_INVAL; - for (; i >= 0; i--) { - token = &tokens[i]; - if (token->start != -1 && token->end == -1) { - parser->toksuper = i; - break; - } - } -#endif - break; - case '\"': - r = jsmn_parse_string(parser, js, len, tokens, num_tokens); - if (r < 0) return r; - count++; - if (parser->toksuper != -1 && tokens != NULL) - tokens[parser->toksuper].size++; - break; - case '\t' : case '\r' : case '\n' : case ' ': - break; - case ':': - parser->toksuper = parser->toknext - 1; - break; - case ',': - if (tokens != NULL && parser->toksuper != -1 && - tokens[parser->toksuper].type != JSMN_ARRAY && - tokens[parser->toksuper].type != JSMN_OBJECT) { -#ifdef JSMN_PARENT_LINKS - parser->toksuper = tokens[parser->toksuper].parent; -#else - for (i = parser->toknext - 1; i >= 0; i--) { - if (tokens[i].type == JSMN_ARRAY || tokens[i].type == JSMN_OBJECT) { - if (tokens[i].start != -1 && tokens[i].end == -1) { - parser->toksuper = i; - break; - } - } - } -#endif - } - break; -#ifdef JSMN_STRICT - /* In strict mode primitives are: numbers and booleans */ - case '-': case '0': case '1' : case '2': case '3' : case '4': - case '5': case '6': case '7' : case '8': case '9': - case 't': case 'f': case 'n' : - /* And they must not be keys of the object */ - if (tokens != NULL && parser->toksuper != -1) { - jsmntok_t *t = &tokens[parser->toksuper]; - if (t->type == JSMN_OBJECT || - (t->type == JSMN_STRING && t->size != 0)) { - return JSMN_ERROR_INVAL; - } - } -#else - /* In non-strict mode every unquoted value is a primitive */ - default: -#endif - r = jsmn_parse_primitive(parser, js, len, tokens, num_tokens); - if (r < 0) return r; - count++; - if (parser->toksuper != -1 && tokens != NULL) - tokens[parser->toksuper].size++; - break; - -#ifdef JSMN_STRICT - /* Unexpected char in strict mode */ - default: - return JSMN_ERROR_INVAL; -#endif - } - } - - if (tokens != NULL) { - for (i = parser->toknext - 1; i >= 0; i--) { - /* Unmatched opened object or array */ - if (tokens[i].start != -1 && tokens[i].end == -1) { - return JSMN_ERROR_PART; - } - } - } - - return count; -} - -/** - * Creates a new parser based over a given buffer with an array of tokens - * available. - */ -void jsmn_init(jsmn_parser *parser) { - parser->pos = 0; - parser->toknext = 0; - parser->toksuper = -1; -} - diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/external_libs/jsmn/jsmn.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/external_libs/jsmn/jsmn.h deleted file mode 100644 index e0ffb1bc4..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/external_libs/jsmn/jsmn.h +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2010 Serge A. Zaitsev - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -/** - * @file jsmn.h - * @brief Definition of the JSMN (Jasmine) JSON parser. - * - * For more information on JSMN: - * @see http://zserge.com/jsmn.html - */ - -#ifndef __JSMN_H_ -#define __JSMN_H_ - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * JSON type identifier. Basic types are: - * o Object - * o Array - * o String - * o Other primitive: number, boolean (true/false) or null - */ -typedef enum { - JSMN_UNDEFINED = 0, - JSMN_OBJECT = 1, - JSMN_ARRAY = 2, - JSMN_STRING = 3, - JSMN_PRIMITIVE = 4 -} jsmntype_t; - -enum jsmnerr { - /* Not enough tokens were provided */ - JSMN_ERROR_NOMEM = -1, - /* Invalid character inside JSON string */ - JSMN_ERROR_INVAL = -2, - /* The string is not a full JSON packet, more bytes expected */ - JSMN_ERROR_PART = -3 -}; - -/** - * JSON token description. - * type type (object, array, string etc.) - * start start position in JSON data string - * end end position in JSON data string - */ -typedef struct { - jsmntype_t type; - int start; - int end; - int size; -#ifdef JSMN_PARENT_LINKS - int parent; -#endif -} jsmntok_t; - -/** - * JSON parser. Contains an array of token blocks available. Also stores - * the string being parsed now and current position in that string - */ -typedef struct { - unsigned int pos; /* offset in the JSON string */ - unsigned int toknext; /* next token to allocate */ - int toksuper; /* superior token node, e.g parent object or array */ -} jsmn_parser; - -/** - * Create JSON parser over an array of tokens - */ -void jsmn_init(jsmn_parser *parser); - -/** - * Run JSON parser. It parses a JSON data string into and array of tokens, each describing - * a single JSON object. - */ -int jsmn_parse(jsmn_parser *parser, const char *js, size_t len, - jsmntok_t *tokens, unsigned int num_tokens); - -#ifdef __cplusplus -} -#endif - -#endif /* __JSMN_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/external_libs/mbedTLS/README.txt b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/external_libs/mbedTLS/README.txt deleted file mode 100644 index b6b428d36..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/external_libs/mbedTLS/README.txt +++ /dev/null @@ -1,10 +0,0 @@ -# Copy source code for mbedTLS into this directory -# -# You'll need to download mbedTLS from the official ARMmbed repository and -# place the files here. We recommend that you pick the latest version of 2.16 -# LTS release in order to have up-to-date security fixes. - -# Note that this SDK will not negotiate the TLS Maximum Fragment Length even if -# it is enabled in mbedTLS' configuration. Therefore, you should ensure content -# buffers used by mbedTLS are at least 16384 bytes in length to use the largest -# maximum record length supported by TLS. diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/filterGcov.sh b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/filterGcov.sh deleted file mode 100755 index fee4a0327..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/filterGcov.sh +++ /dev/null @@ -1,63 +0,0 @@ -#!/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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_error.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_error.h deleted file mode 100644 index f0ccc3963..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_error.h +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Copyright 2010-2018 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, - /** Input argument exceeded the allowed maximum size */ - MAX_SIZE_ERROR = -50, - /** Some limit has been exceeded, e.g. the maximum number of subscriptions has been reached */ - LIMIT_EXCEEDED_ERROR = -51, - /** Invalid input topic type */ - INVALID_TOPIC_TYPE_ERROR = -52 -} IoT_Error_t; - -#ifdef __cplusplus -} -#endif - -#endif /* AWS_IOT_SDK_SRC_IOT_ERROR_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_jobs_interface.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_jobs_interface.h deleted file mode 100644 index 4f033d9d6..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_jobs_interface.h +++ /dev/null @@ -1,267 +0,0 @@ -/* - * Copyright 2015-2018 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_jobs_interface.h - * @brief An interface for interacting with the AWS IoT Jobs system. - * - * This file defines utility functions for interacting with the AWS IoT jobs - * APIs over MQTT. It provides functions for managing subscriptions to job - * related topics and for sending queries and updates requests for jobs. - * Callers are responsible for managing the subscriptions and associating - * responses with the queries and update messages. - */ -#ifndef AWS_IOT_JOBS_INTERFACE_H_ -#define AWS_IOT_JOBS_INTERFACE_H_ - -#ifdef DISABLE_IOT_JOBS -#error "Jobs API is disabled" -#endif - -/** - * @file aws_iot_jobs_interface.h - * @brief Functions for interacting with the AWS IoT Jobs system. - */ -#include "aws_iot_mqtt_client_interface.h" -#include "aws_iot_jobs_topics.h" -#include "aws_iot_jobs_types.h" -#include "aws_iot_error.h" -#include "aws_iot_json_utils.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @brief Subscribe to jobs messages for the given thing and/or jobs. - * - * The function can be used to subscribe to all job related messages. To subscribe - * to messages not related to a job the jobId passed should be null. The jobId - * can also be "+" to subscribe to messages related to any job, or "$next" to - * indicate the next pending job. - * - * See also #aws_iot_jobs_subscribe_to_all_job_messages to subscribe to all possible - * messages in one operation. - * - * \note Subscribing with the same thing, job and topic type more than - * once is undefined. - * - * \param pClient the client to use - * \param qos the qos to use - * \param thingName the name of the thing to subscribe to - * \param jobId the job id to subscribe to. To subscribe to messages not related to - * a job the jobId passed should be null. The jobId can also be "+" to subscribe to - * messages related to any job, or "$next" to indicate the next pending job. - * \param topicType the topic type to subscribe to - * \param replyType the reply topic type to subscribe to - * \param pApplicationHandler the callback handler - * \param pApplicationHandlerData the callback context data. This must remain valid at least until - * aws_iot_jobs_unsubscribe_from_job_messages is called. - * \param topicBuffer. A buffer to use to hold the topic name for the subscription. This buffer - * must remain valid at least until aws_iot_jobs_unsubscribe_from_job_messages is called. - * \param topicBufferSize the size of the topic buffer. The function will fail - * with LIMIT_EXCEEDED_ERROR if this is too small. - * \return the result of subscribing to the topic (see aws_iot_mqtt_subscribe) - */ -IoT_Error_t aws_iot_jobs_subscribe_to_job_messages( - AWS_IoT_Client *pClient, QoS qos, - const char *thingName, - const char *jobId, - AwsIotJobExecutionTopicType topicType, - AwsIotJobExecutionTopicReplyType replyType, - pApplicationHandler_t pApplicationHandler, - void *pApplicationHandlerData, - char *topicBuffer, - uint16_t topicBufferSize); - -/** - * @brief Subscribe to all job messages. - * - * Subscribe to all job messages for the given thing. - * - * \note Subscribing with the same thing more than once is undefined. - * - * \param pClient the client to use - * \param qos the qos to use - * \param thingName the name of the thing to subscribe to - * \param pApplicationHandler the callback handler - * \param pApplicationHandlerData the callback context data. This must remain valid at least until - * aws_iot_jobs_unsubscribe_from_job_messages is called. - * \param topicBuffer. A buffer to use to hold the topic name for the subscription. This buffer - * must remain valid at least until aws_iot_jobs_unsubscribe_from_job_messages is called. - * \param topicBufferSize the size of the topic buffer. The function will fail - * with LIMIT_EXCEEDED_ERROR if this is too small. - * \return the result of subscribing to the topic (see aws_iot_mqtt_subscribe) - */ -IoT_Error_t aws_iot_jobs_subscribe_to_all_job_messages( - AWS_IoT_Client *pClient, QoS qos, - const char *thingName, - pApplicationHandler_t pApplicationHandler, - void *pApplicationHandlerData, - char *topicBuffer, - uint16_t topicBufferSize); - -/** - * @brief Unsubscribe from a job subscription - * - * Remove the subscription created using #aws_iot_jobs_subscribe_to_job_messages or - * #aws_iot_jobs_subscribe_to_all_job_messages. - * - * \param pClient the client to use - * \param topicBuffer the topic buffer passed to #aws_iot_jobs_subscribe_to_job_messages or - * #aws_iot_jobs_subscribe_to_all_job_messages when the subscription was created. - * \return #SUCCESS or the first error encountered. - */ -IoT_Error_t aws_iot_jobs_unsubscribe_from_job_messages( - AWS_IoT_Client *pClient, - char *topicBuffer); - -/** - * @brief Send a query to one of the job query APIs. - * - * Send a query to one of the job query APIs. If jobId is null this - * requests a list of pending jobs for the thing. If jobId is - * not null then it sends a query for the details of that job. - * If jobId is $next then it sends a query for the details for - * the next pending job. - * - * \param pClient the client to use - * \param qos the qos to use - * \param thingName the thing name to query for - * \param jobId the id of the job to query for. If null a list - * of all pending jobs for the thing is requested. - * \param clientToken the client token to use for the query. - * If null no clientToken is sent resulting in an empty message. - * \param topicBuffer the topic buffer to use. This may be discarded - * as soon as this function returns - * \param topicBufferSize the size of topicBuffer - * \param messageBuffer the message buffer to use. May be NULL - * if clientToken is NULL - * \param messageBufferSize the size of messageBuffer - * \param topicType the topic type to publish query to - * \return LIMIT_EXCEEDED_ERROR if the topic buffer or - * message buffer is too small, NULL_VALUE_ERROR if the any of - * the required inputs are NULL, otherwise the result - * of the mqtt publish - */ -IoT_Error_t aws_iot_jobs_send_query( - AWS_IoT_Client *pClient, QoS qos, - const char *thingName, - const char *jobId, - const char *clientToken, - char *topicBuffer, - uint16_t topicBufferSize, - char *messageBuffer, - size_t messageBufferSize, - AwsIotJobExecutionTopicType topicType); - -/** - * @brief Send a start next command to the job start-next API. - * - * Send a start next command to the job start-next API. - * - * \param pClient the client to use - * \param qos the qos to use - * \param thingName the thing name to query for - * \param startNextRequest the start-next request to send - * \param topicBuffer the topic buffer to use. This may be discarded - * as soon as this function returns - * \param topicBufferSize the size of topicBuffer - * \param messageBuffer the message buffer to use. May be NULL - * if clientToken is NULL - * \param messageBufferSize the size of messageBuffer - * \return LIMIT_EXCEEDED_ERROR if the topic buffer or - * message buffer is too small, NULL_VALUE_ERROR if the any of - * the required inputs are NULL, otherwise the result - * of the mqtt publish - */ -IoT_Error_t aws_iot_jobs_start_next( - AWS_IoT_Client *pClient, QoS qos, - const char *thingName, - const AwsIotStartNextPendingJobExecutionRequest *startNextRequest, - char *topicBuffer, - uint16_t topicBufferSize, - char *messageBuffer, - size_t messageBufferSize); - -/** - * @brief Send a describe job query to the job query API. - * - * Send a describe job query to the job query API. If jobId is null this - * requests a list of pending jobs for the thing. If jobId is - * not null then it sends a query for the details of that job. - * - * \param pClient the client to use - * \param qos the qos to use - * \param thingName the thing name to query for - * \param jobId the id of the job to query for. If null a list - * of all pending jobs for the thing is requested. - * \param describeRequest the describe request to send - * \param topicBuffer the topic buffer to use. This may be discarded - * as soon as this function returns - * \param topicBufferSize the size of topicBuffer - * \param messageBuffer the message buffer to use. May be NULL - * if clientToken is NULL - * \param messageBufferSize the size of messageBuffer - * \return LIMIT_EXCEEDED_ERROR if the topic buffer or - * message buffer is too small, NULL_VALUE_ERROR if the any of - * the required inputs are NULL, otherwise the result - * of the mqtt publish - */ -IoT_Error_t aws_iot_jobs_describe( - AWS_IoT_Client *pClient, QoS qos, - const char *thingName, - const char *jobId, - const AwsIotDescribeJobExecutionRequest *describeRequest, - char *topicBuffer, - uint16_t topicBufferSize, - char *messageBuffer, - size_t messageBufferSize); - -/** - * @brief Send an update about a job execution. - * - * Send an update about a job execution. - * - * \param pClient the client to use - * \param qos the qos to use - * \param thingName the thing name to send the update for - * \param jobId the id of the job to send the update for - * \param updateRequest the update request to send - * \param topicBuffer the topic buffer to use. This may be discarded - * as soon as this function returns - * \param topicBufferSize the size of topicBuffer - * \param messageBuffer the message buffer to use. - * \param messageBufferSize the size of messageBuffer - * \return LIMIT_EXCEEDED_ERROR if the topic buffer or - * message buffer is too small, NULL_VALUE_ERROR if the any of - * the required inputs are NULL, otherwise the result - * of the mqtt publish - */ -IoT_Error_t aws_iot_jobs_send_update( - AWS_IoT_Client *pClient, QoS qos, - const char *thingName, - const char *jobId, - const AwsIotJobExecutionUpdateRequest *updateRequest, - char *topicBuffer, - uint16_t topicBufferSize, - char *messageBuffer, - size_t messageBufferSize); - -#ifdef __cplusplus -} -#endif - -#endif /* AWS_IOT_JOBS_INTERFACE_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_jobs_json.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_jobs_json.h deleted file mode 100644 index 55e45142b..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_jobs_json.h +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2015-2018 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_jobs_json.h - * @brief Functions for mapping between json and the AWS Iot Job data structures. - */ - -#ifdef DISABLE_IOT_JOBS -#error "Jobs API is disabled" -#endif - -#ifndef AWS_IOT_JOBS_JSON_H_ -#define AWS_IOT_JOBS_JSON_H_ - -#include -#include "jsmn.h" -#include "aws_iot_jobs_types.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * Serialize a job execution update request into a json string. - * - * \param requestBuffer buffer to contain the serialized request. If null - * this function will return the size of the buffer required - * \param bufferSize the size of the buffer. If this is smaller than the required - * length the string will be truncated to fit. - * \request the request to serialize. - * \return The size of the json string to store the serialized request or -1 - * if the request is invalid. Note that the return value should be checked against - * the size of the buffer and if its larger handle the fact that the string has - * been truncated. - */ -int aws_iot_jobs_json_serialize_update_job_execution_request( - char *requestBuffer, size_t bufferSize, - const AwsIotJobExecutionUpdateRequest *request); - -/** - * Serialize a job API request that contains only a client token. - * - * \param requestBuffer buffer to contain the serialized request. If null - * this function will return the size of the buffer required - * \param bufferSize the size of the buffer. If this is smaller than the required - * length the string will be truncated to fit. - * \param clientToken the client token to use for the request. - * \return The size of the json string to store the serialized request or -1 - * if the request is invalid. Note that the return value should be checked against - * the size of the buffer and if its larger handle the fact that the string has - * been truncated. - */ -int aws_iot_jobs_json_serialize_client_token_only_request( - char *requestBuffer, size_t bufferSize, - const char *clientToken); - -/** - * Serialize describe job execution request into json string. - * - * \param requestBuffer buffer to contain the serialized request. If null - * this function will return the size of the buffer required - * \param bufferSize the size of the buffer. If this is smaller than the required - * length the string will be truncated to fit. - * \param request the request to serialize. - * \return The size of the json string to store the serialized request or -1 - * if the request is invalid. Note that the return value should be checked against - * the size of the buffer and if its larger handle the fact that the string has - * been truncated. - */ -int aws_iot_jobs_json_serialize_describe_job_execution_request( - char *requestBuffer, size_t bufferSize, - const AwsIotDescribeJobExecutionRequest *request); - -/** - * Serialize start next job execution request into json string. - * - * \param requestBuffer buffer to contain the serialized request. If null - * this function will return the size of the buffer required - * \param bufferSize the size of the buffer. If this is smaller than the required - * length the string will be truncated to fit. - * \param request the start-next request to serialize. - * \return The size of the json string to store the serialized request or -1 - * if the request is invalid. Note that the return value should be checked against - * the size of the buffer and if its larger handle the fact that the string has - * been truncated. - */ -int aws_iot_jobs_json_serialize_start_next_job_execution_request( - char *requestBuffer, size_t bufferSize, - const AwsIotStartNextPendingJobExecutionRequest *request); - -#ifdef __cplusplus -} -#endif - -#endif /* AWS_IOT_JOBS_JSON_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_jobs_topics.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_jobs_topics.h deleted file mode 100644 index 3e291878b..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_jobs_topics.h +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright 2015-2018 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_job_topics.h - * @brief Functions for parsing and creating MQTT topics used by the AWS IoT Jobs system. - */ - -#ifdef DISABLE_IOT_JOBS -#error "Jobs API is disabled" -#endif - -#ifndef AWS_IOT_JOBS_TOPICS_H_ -#define AWS_IOT_JOBS_TOPICS_H_ - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define JOB_ID_NEXT "$next" -#define JOB_ID_WILDCARD "+" - -/** - * The type of job topic. - */ -typedef enum { - JOB_UNRECOGNIZED_TOPIC = 0, - JOB_GET_PENDING_TOPIC, - JOB_START_NEXT_TOPIC, - JOB_DESCRIBE_TOPIC, - JOB_UPDATE_TOPIC, - JOB_NOTIFY_TOPIC, - JOB_NOTIFY_NEXT_TOPIC, - JOB_WILDCARD_TOPIC -} AwsIotJobExecutionTopicType; - -/** - * The type of reply topic, or #JOB_REQUEST_TYPE for - * topics that are not replies. - */ -typedef enum { - JOB_UNRECOGNIZED_TOPIC_TYPE = 0, - JOB_REQUEST_TYPE, - JOB_ACCEPTED_REPLY_TYPE, - JOB_REJECTED_REPLY_TYPE, - JOB_WILDCARD_REPLY_TYPE -} AwsIotJobExecutionTopicReplyType; - -/** - * @brief Get the topic matching the provided details and put into the provided buffer. - * - * If the buffer is not large enough to store the full topic the topic will be truncated - * to fit, with the last character always being a null terminator. - * - * \param buffer the buffer to put the results into - * \param bufferSize the size of the buffer - * \param topicType the type of the topic - * \param replyType the reply type of the topic - * \param thingName the name of the thing in the topic - * \param jobId the name of the job id in the topic - * \return the number of characters in the topic excluding the null terminator. A return - * value of bufferSize or more means that the topic string was truncated. - */ -int aws_iot_jobs_get_api_topic(char *buffer, size_t bufferSize, - AwsIotJobExecutionTopicType topicType, AwsIotJobExecutionTopicReplyType replyType, - const char* thingName, const char* jobId); - -#ifdef __cplusplus -} -#endif - -#endif /* AWS_IOT_JOBS_TOPICS_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_jobs_types.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_jobs_types.h deleted file mode 100644 index b96ac02b7..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_jobs_types.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2015-2018 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_jobs_types.h - * @brief Structures defining the interface with the AWS IoT Jobs system - * - * This file defines the structures returned by and sent to the AWS IoT Jobs system. - * - */ - -#ifdef DISABLE_IOT_JOBS -#error "Jobs API is disabled" -#endif - -#ifndef AWS_IOT_JOBS_TYPES_H_ -#define AWS_IOT_JOBS_TYPES_H_ - -#include -#include -#include "jsmn.h" -#include "timer_interface.h" - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum { - JOB_EXECUTION_STATUS_NOT_SET = 0, - JOB_EXECUTION_QUEUED, - JOB_EXECUTION_IN_PROGRESS, - JOB_EXECUTION_FAILED, - JOB_EXECUTION_SUCCEEDED, - JOB_EXECUTION_CANCELED, - JOB_EXECUTION_REJECTED, - /*** - * Used for any status not in the supported list of statuses - */ - JOB_EXECUTION_UNKNOWN_STATUS = 99 -} JobExecutionStatus; - -extern const char *JOB_EXECUTION_QUEUED_STR; -extern const char *JOB_EXECUTION_IN_PROGRESS_STR; -extern const char *JOB_EXECUTION_FAILED_STR; -extern const char *JOB_EXECUTION_SUCCEEDED_STR; -extern const char *JOB_EXECUTION_CANCELED_STR; -extern const char *JOB_EXECUTION_REJECTED_STR; - -/** - * Convert a string to its matching status. - * - * \return the matching status, or JOB_EXECUTION_UNKNOWN_STATUS if the string was not recognized. - */ -JobExecutionStatus aws_iot_jobs_map_string_to_job_status(const char *str); - -/** - * Convert a status to its string. - * - * \return a string representing the status, or null if the status is not recognized. - */ -const char *aws_iot_jobs_map_status_to_string(JobExecutionStatus status); - -/** - * A request to update the status of a job execution. - */ -typedef struct { - int64_t expectedVersion; // set to 0 to ignore - int64_t executionNumber; // set to 0 to ignore - JobExecutionStatus status; - const char *statusDetails; - bool includeJobExecutionState; - bool includeJobDocument; - const char *clientToken; -} AwsIotJobExecutionUpdateRequest; - -/** - * A request to get the status of a job execution. - */ -typedef struct { - int64_t executionNumber; // set to 0 to ignore - bool includeJobDocument; - const char *clientToken; -} AwsIotDescribeJobExecutionRequest; - -/** - * A request to get and start the next pending (not in a terminal state) job execution for a Thing. - */ -typedef struct { - const char *statusDetails; - const char *clientToken; -} AwsIotStartNextPendingJobExecutionRequest; - -#ifdef __cplusplus -} -#endif - -#endif /* AWS_IOT_JOBS_TYPES_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_json_utils.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_json_utils.h deleted file mode 100644 index af762d8a9..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_json_utils.h +++ /dev/null @@ -1,212 +0,0 @@ -/* - * Copyright 2010-2018 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 buf address of string to be updated - * @param bufLen length of buf in bytes - * @param jsonString json string - * @param token json token - pointer to JSON node - * - * @return SUCCESS - success - * @return JSON_PARSE_ERROR - error parsing value - */ -IoT_Error_t parseStringValue(char *buf, size_t bufLen, const char *jsonString, jsmntok_t *token); - -/** - * @brief Find the JSON node associated with the given key in the given object. - * - * Given a JSON node parse the string value from the value. - * - * @param key json key - * @param token json token - pointer to JSON node - * @param jsonString json string - * - * @return pointer to found property value - * @return NULL - not found - */ -jsmntok_t *findToken(const char *key, const char *jsonString, jsmntok_t *token); - -#ifdef __cplusplus -} -#endif - -#endif /* AWS_IOT_SDK_SRC_JSON_UTILS_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_log.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_log.h deleted file mode 100644 index 2eeac5954..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_log.h +++ /dev/null @@ -1,138 +0,0 @@ -/* - * 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 -#undef IOT_DEBUG -#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 -#undef FUNC_ENTRY -#define FUNC_ENTRY - -#undef FUNC_EXIT -#define FUNC_EXIT -#undef FUNC_EXIT_RC -#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 -#undef IOT_INFO -#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 -#undef IOT_WARN -#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 -#undef IOT_ERROR -#define IOT_ERROR(...) -#endif - -#ifdef __cplusplus -} -#endif - -#endif // _IOT_LOG_H diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_mqtt_client.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_mqtt_client.h deleted file mode 100644 index 9ba98c8ba..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_mqtt_client.h +++ /dev/null @@ -1,491 +0,0 @@ -/* - * 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 - -/** Greatest packet identifier, per MQTT spec */ -#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; -/** Default initializer for will */ -extern const IoT_MQTT_Will_Options iotMqttWillOptionsDefault; - -/** Default initializer for will */ -#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; -/** Default initializer for connect */ -extern const IoT_Client_Connect_Params iotClientConnectParamsDefault; - -/** Default initializer for connect */ -#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; -/** Default initializer for client */ -extern const IoT_Client_Init_Params iotClientInitParamsDefault; - -/** Default initializer for client */ -#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; ///< Topic name of subscription - uint16_t topicNameLen; ///< Length of topic name - char resubscribed; ///< Whether this handler was successfully resubscribed in the reconnect workflow - QoS qos; ///< QoS of subscription - pApplicationHandler_t pApplicationHandler; ///< Application function to invoke - void *pApplicationHandlerData; ///< Context to pass to application handler -} 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; ///< The current state of the client's state machine - bool isPingOutstanding; ///< Whether this client is waiting for a ping response - bool isAutoReconnectEnabled; ///< Whether auto-reconnect is enabled for this client -} 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; ///< Packet ID to use for the next generated packet - - /* Packet timeout is unused. See https://github.com/aws/aws-iot-device-sdk-embedded-C/pull/1475 */ - uint32_t packetTimeoutMs; ///< Timeout for reading incoming packets from the network - uint32_t commandTimeoutMs; ///< Timeout for processing outgoing MQTT packets - uint16_t keepAliveInterval; ///< Maximum interval between control packets - uint32_t currentReconnectWaitInterval; ///< Current backoff period for reconnect - uint32_t counterNetworkDisconnected; ///< How many times this client detected a disconnection - - /* The below values are initialized with the - * lengths of the TX/RX buffers and never modified - * afterwards */ - size_t writeBufSize; ///< Size of this client's outgoing data buffer - size_t readBufSize; ///< Size of this client's incoming data buffer - size_t readBufIndex; ///< Current offset into the incoming data buffer - unsigned char writeBuf[AWS_IOT_MQTT_TX_BUF_LEN]; ///< Buffer for outgoing data - unsigned char readBuf[AWS_IOT_MQTT_RX_BUF_LEN]; ///< Buffer for incoming data - -#ifdef _ENABLE_THREAD_SUPPORT_ - bool isBlockOnThreadLockEnabled; ///< Whether to use nonblocking or blocking mutex APIs - IoT_Mutex_t state_change_mutex; ///< Mutex protecting the client's state machine - IoT_Mutex_t tls_read_mutex; ///< Mutex protecting incoming data - IoT_Mutex_t tls_write_mutex; ///< Mutex protecting outgoing data -#endif - - IoT_Client_Connect_Params options; ///< Options passed when the client was initialized - - MessageHandlers messageHandlers[AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS]; ///< Callbacks for incoming messages - iot_disconnect_handler disconnectHandler; ///< Callback when a disconnection is detected - void *disconnectHandlerData; ///< Context for disconnect handler -} ClientData; - -/** - * @brief MQTT Client - * - * Defining a type for MQTT Client - * - */ -struct _Client { - Timer pingReqTimer; ///< Timer to keep track of when to send next PINGREQ - Timer pingRespTimer; ///< Timer to ensure that PINGRESP is received timely - Timer reconnectDelayTimer; ///< Timer for backoff on reconnect - - ClientStatus clientStatus; ///< Client state information - ClientData clientData; ///< Client context - Network networkStack; ///< Table of network function pointers -}; - -/** - * @functionpage{aws_iot_mqtt_get_next_packet_id,mqtt,get_next_packet_id} - * @functionpage{aws_iot_mqtt_set_connect_params,mqtt,set_connect_params} - * @functionpage{aws_iot_mqtt_is_client_connected,mqtt,is_client_connected} - * @functionpage{aws_iot_mqtt_get_client_state,mqtt,get_client_state} - * @functionpage{aws_iot_is_autoreconnect_enabled,mqtt,is_autoreconnect_enabled} - * @functionpage{aws_iot_mqtt_set_disconnect_handler,mqtt,set_disconnect_handler} - * @functionpage{aws_iot_mqtt_autoreconnect_set_status,mqtt,autoreconnect_set_status} - * @functionpage{aws_iot_mqtt_get_network_disconnected_count,mqtt,get_network_disconnected_count} - * @functionpage{aws_iot_mqtt_reset_network_disconnected_count,mqtt,reset_network_disconnected_count} - */ - -/** - * @brief Retrieve and increment the next packet identifier for an MQTT client context. - * - * This function generates a two-byte packet identifier for an outgoing MQTT packet and - * modifies the internal state of the MQTT client context so that the next call generates - * a different packet identifier. Per the MQTT specification, MQTT packet identifiers are - * nonzero, two-byte integers that identify certain MQTT packets. MQTT packet identifiers - * must be unique at any given time: no two concurrent packets may use the same identifier, - * but packet identifiers from previously processed packets may be reused. - * - * @param[in] pClient MQTT client context - * - * @return A two-byte MQTT packet identifier that will be unique for the given MQTT client - * context. - * - * @warning This function is not thread safe. Do not call it concurrently from different - * threads. - */ -/* @[declare_mqtt_get_next_packet_id] */ -uint16_t aws_iot_mqtt_get_next_packet_id(AWS_IoT_Client *pClient); -/* @[declare_mqtt_get_next_packet_id] */ - -/** - * @brief Reset the connection parameters of an initialized MQTT client context. - * - * This function replaces the current connection parameters of an MQTT client - * context with a new set of parameters. Its primary use is to modify the connection - * parameters for the next reconnect attempt if the existing parameters are no longer - * valid. Therefore, it should be called just before a reconnect attempt, i.e. just - * before @ref mqtt_function_attempt_reconnect or @ref mqtt_function_yield. - * - * The new connection parameters take effect at the next connection attempt. - * - * @param[in] pClient MQTT client context - * @param[in] pNewConnectParams The new connection parameters - * - * @return Returns NULL_VALUE_ERROR if provided a bad parameter; otherwise, always - * returns SUCCESS. - * - * @warning Do not call this function if a connection attempt is in progress. Connection - * attempts happen in the context of @ref mqtt_function_connect, @ref mqtt_function_attempt_reconnect, - * or @ref mqtt_function_yield. - */ -/* @[declare_mqtt_set_connect_params] */ -IoT_Error_t aws_iot_mqtt_set_connect_params(AWS_IoT_Client *pClient, IoT_Client_Connect_Params *pNewConnectParams); -/* @[declare_mqtt_set_connect_params] */ - -/** - * @brief Determine if the MQTT client context currently connected to a server. - * - * This function checks the internal state of the MQTT client context to determine - * if it is currently connected to the server. - * - * @param[in] pClient MQTT client context - * - * @return true if connected; false otherwise. - * - * @warning Application code should not rely on this function's return value. - * The returned value only represents the internal state of the client and - * does not check the network connection status. - */ -/* @[declare_mqtt_is_client_connected] */ -bool aws_iot_mqtt_is_client_connected(AWS_IoT_Client *pClient); -/* @[declare_mqtt_is_client_connected] */ - -/** - * @brief Get the current state of the MQTT client context. - * - * @param[in] pClient MQTT client context - * - * @return The state of the MQTT client context at the time of the function call. - * - * @note The client's state is internal and generally not useful to application code. - * Applications should not make assumptions about the status of the client based on - * its state. - */ -/* @[declare_mqtt_get_client_state] */ -ClientState aws_iot_mqtt_get_client_state(AWS_IoT_Client *pClient); -/* @[declare_mqtt_get_client_state] */ - -/** - * @brief Determine if auto-reconnect is enabled for an MQTT client context. - * - * @param[in] pClient MQTT client context - * - * @return true if auto-reconnect is enabled; false otherwise. - */ -/* @[declare_mqtt_is_autoreconnect_enabled] */ -bool aws_iot_is_autoreconnect_enabled(AWS_IoT_Client *pClient); -/* @[declare_mqtt_is_autoreconnect_enabled] */ - -/** - * @brief Reset the disconnect handler of an initialized MQTT client context. - * - * This function replaces the current disconnect handler of an MQTT client - * context with a new disconnect handler. - * - * The new disconnect handler will be invoked when the next disconnect is detected. - * - * @param[in] pClient MQTT client context - * @param[in] pDisconnectHandler New disconnect handler - * @param[in] pDisconnectHandlerData Context to be passed to new disconnect handler - * - * @return Returns NULL_VALUE_ERROR if provided a bad parameter; otherwise, always - * returns SUCCESS. - * - * @warning Do not call this function if @ref mqtt_function_yield is in progress. - */ -/* @[declare_mqtt_set_disconnect_handler] */ -IoT_Error_t aws_iot_mqtt_set_disconnect_handler(AWS_IoT_Client *pClient, iot_disconnect_handler pDisconnectHandler, - void *pDisconnectHandlerData); -/* @[declare_mqtt_set_disconnect_handler] */ - -/** - * @brief Enable or disable auto-reconnect for an initialized MQTT client context. - * - * This function replaces the current auto-reconnect setting with the provided setting. - * - * @note This function should only be called after @ref mqtt_function_connect has been - * called for the provided client. - * - * @param[in] pClient MQTT client context - * @param[in] newStatus New setting for auto-reconnect - * - * @return Returns NULL_VALUE_ERROR if provided a bad parameter; otherwise, always - * returns SUCCESS. - * - * @warning Do not call this function if a connection attempt is in progress. Connection - * attempts happen in the context of @ref mqtt_function_connect, @ref mqtt_function_attempt_reconnect, - * or @ref mqtt_function_yield. - */ -/* @[declare_mqtt_autoreconnect_set_status] */ -IoT_Error_t aws_iot_mqtt_autoreconnect_set_status(AWS_IoT_Client *pClient, bool newStatus); -/* @[declare_mqtt_autoreconnect_set_status] */ - -/** - * @brief Get the current number of disconnects detected by an MQTT client context. - * - * @param[in] pClient MQTT client context - * - * @return The number of disconnects detected since the client was created - * (or since the last call to @ref mqtt_function_reset_network_disconnected_count). - * - * @warning Do not call this function if @ref mqtt_function_yield is in progress. - */ -/* @[declare_mqtt_get_network_disconnected_count] */ -uint32_t aws_iot_mqtt_get_network_disconnected_count(AWS_IoT_Client *pClient); -/* @[declare_mqtt_get_network_disconnected_count] */ - -/** - * @brief Reset the number of disconnects detected by an MQTT client context to zero. - * - * @param[in] pClient MQTT client context - * - * @warning Do not call this function if @ref mqtt_function_yield is in progress. - */ -/* @[declare_mqtt_reset_network_disconnected_count] */ -void aws_iot_mqtt_reset_network_disconnected_count(AWS_IoT_Client *pClient); -/* @[declare_mqtt_reset_network_disconnected_count] */ - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_mqtt_client_common_internal.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_mqtt_client_common_internal.h deleted file mode 100644 index ee8ca023e..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_mqtt_client_common_internal.h +++ /dev/null @@ -1,134 +0,0 @@ -/* -* 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" - -/** Types of MQTT messages */ -typedef enum msgTypes { - UNKNOWN = -1, - CONNECT = 1, - CONNACK = 2, - PUBLISH = 3, - PUBACK = 4, - PUBREC = 5, - PUBREL = 6, - PUBCOMP = 7, - SUBSCRIBE = 8, - SUBACK = 9, - UNSUBSCRIBE = 10, - UNSUBACK = 11, - PINGREQ = 12, - PINGRESP = 13, - DISCONNECT = 14 -} MessageTypes; - -/* Macros for parsing header fields from incoming MQTT frame. */ -#define MQTT_HEADER_FIELD_TYPE(_byte) ((_byte >> 4) & 0x0F) /**< Message type */ -#define MQTT_HEADER_FIELD_DUP(_byte) ((_byte & (1 << 3)) >> 3) /**< DUP flag */ -#define MQTT_HEADER_FIELD_QOS(_byte) ((_byte & (3 << 1)) >> 1) /**< QoS */ -#define MQTT_HEADER_FIELD_RETAIN(_byte) ((_byte & (1 << 0)) >> 0) /**< Retain flag */ - -/** - * Bitfields for the MQTT header byte. - */ -typedef union { - unsigned char byte; /**< the whole byte */ -} MQTTHeader; - -IoT_Error_t aws_iot_mqtt_internal_init_header(MQTTHeader *pHeader, MessageTypes message_type, - QoS qos, uint8_t dup, uint8_t retained); - -IoT_Error_t aws_iot_mqtt_internal_serialize_ack(unsigned char *pTxBuf, size_t txBufLen, - MessageTypes msgType, uint8_t dup, uint16_t packetId, - uint32_t *pSerializedLen); -IoT_Error_t aws_iot_mqtt_internal_deserialize_ack(unsigned char *, unsigned char *, - uint16_t *, unsigned char *, size_t); - -uint32_t aws_iot_mqtt_internal_get_final_packet_length_from_remaining_length(uint32_t rem_len); - -size_t aws_iot_mqtt_internal_write_len_to_buffer(unsigned char *buf, uint32_t length); -IoT_Error_t aws_iot_mqtt_internal_decode_remaining_length_from_buffer(unsigned char *buf, uint32_t *decodedLen, - uint32_t *readBytesLen); - -uint16_t aws_iot_mqtt_internal_read_uint16_t(unsigned char **pptr); -void aws_iot_mqtt_internal_write_uint_16(unsigned char **pptr, uint16_t anInt); - -unsigned char aws_iot_mqtt_internal_read_char(unsigned char **pptr); -void aws_iot_mqtt_internal_write_char(unsigned char **pptr, unsigned char c); -void aws_iot_mqtt_internal_write_utf8_string(unsigned char **pptr, const char *string, uint16_t stringLen); - -IoT_Error_t aws_iot_mqtt_internal_flushBuffers( AWS_IoT_Client *pClient ); -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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_mqtt_client_interface.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_mqtt_client_interface.h deleted file mode 100644 index 65e101951..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_mqtt_client_interface.h +++ /dev/null @@ -1,305 +0,0 @@ -/* -* 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_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" - -/** - * @functionspage{mqtt,MQTT library} - * - * API functions - * - @functionname{mqtt_function_init} - * - @functionname{mqtt_function_free} - * - @functionname{mqtt_function_connect} - * - @functionname{mqtt_function_publish} - * - @functionname{mqtt_function_subscribe} - * - @functionname{mqtt_function_resubscribe} - * - @functionname{mqtt_function_unsubscribe} - * - @functionname{mqtt_function_disconnect} - * - @functionname{mqtt_function_yield} - * - @functionname{mqtt_function_attempt_reconnect} - * - @functionname{mqtt_function_get_next_packet_id} - * - @functionname{mqtt_function_set_connect_params} - * - @functionname{mqtt_function_is_client_connected} - * - @functionname{mqtt_function_get_client_state} - * - @functionname{mqtt_function_is_autoreconnect_enabled} - * - @functionname{mqtt_function_set_disconnect_handler} - * - @functionname{mqtt_function_autoreconnect_set_status} - * - @functionname{mqtt_function_get_network_disconnected_count} - * - @functionname{mqtt_function_reset_network_disconnected_count} - */ - -/** - * @functionpage{aws_iot_mqtt_init,mqtt,init} - * @functionpage{aws_iot_mqtt_free,mqtt,free} - * @functionpage{aws_iot_mqtt_connect,mqtt,connect} - * @functionpage{aws_iot_mqtt_publish,mqtt,publish} - * @functionpage{aws_iot_mqtt_subscribe,mqtt,subscribe} - * @functionpage{aws_iot_mqtt_resubscribe,mqtt,resubscribe} - * @functionpage{aws_iot_mqtt_unsubscribe,mqtt,unsubscribe} - * @functionpage{aws_iot_mqtt_disconnect,mqtt,disconnect} - * @functionpage{aws_iot_mqtt_yield,mqtt,yield} - * @functionpage{aws_iot_mqtt_attempt_reconnect,mqtt,attempt_reconnect} - */ - -/** - * @brief Initialize a new MQTT client context. - * - * This function should be called before any other MQTT function to initialize - * a new MQTT client context. Once the client context is no longer needed, - * @ref mqtt_function_free should be called. - * - * @param[in] pClient MQTT client context to initialize - * @param[in] pInitParams The MQTT connection parameters - * - * @return `IoT_Error_t`: See `aws_iot_error.h` - */ -/* @[declare_mqtt_init] */ -IoT_Error_t aws_iot_mqtt_init(AWS_IoT_Client *pClient, IoT_Client_Init_Params *pInitParams); -/* @[declare_mqtt_init] */ - -/** - * @brief Clean up an MQTT client context that is no longer needed. - * - * This function will free up resources used by an MQTT client context. It should - * only be called when that context is no longer needed. - * - * @param[in] pClient MQTT client context that was previously initialized by - * @ref mqtt_function_init - * - * @return `IoT_Error_t`: See `aws_iot_error.h` - */ -/* @[declare_mqtt_free] */ -IoT_Error_t aws_iot_mqtt_free( AWS_IoT_Client *pClient ); -/* @[declare_mqtt_free] */ - -/** - * @brief Establish a connection with an MQTT server. - * - * This function should be called once and after @ref mqtt_function_init. It sends - * the MQTT CONNECT packet to the server, which establishes an MQTT session. Once - * the session is no longer needed, it can be closed with @ref mqtt_function_disconnect. - * - * @param[in] pClient MQTT client context - * @param[in] pConnectParams MQTT connection parameters - * - * @return `IoT_Error_t`: See `aws_iot_error.h` - */ -/* @[declare_mqtt_connect] */ -IoT_Error_t aws_iot_mqtt_connect(AWS_IoT_Client *pClient, IoT_Client_Connect_Params *pConnectParams); -/* @[declare_mqtt_connect] */ - -/** - * @brief Publish an MQTT message to a topic. - * - * This function sends an MQTT message to the server. The server will then - * forward this message to any clients with subscriptions to topic filters - * that match the message's topic. - * - * For a QoS 0 message, this function returns after the message is successfully - * passed to the TLS layer. For a QoS 1 message, this function returns after the - * receipt of the PUBACK for the transmitted message. - * - * @param pClient MQTT client context - * @param pTopicName Topic name to publish to - * @param topicNameLen Length of the topic name - * @param pParams Publish message parameters - * - * @return `IoT_Error_t`: See `aws_iot_error.h` - */ -/* @[declare_mqtt_publish] */ -IoT_Error_t aws_iot_mqtt_publish(AWS_IoT_Client *pClient, const char *pTopicName, uint16_t topicNameLen, - IoT_Publish_Message_Params *pParams); -/* @[declare_mqtt_publish] */ - -/** - * @brief Subscribe to an MQTT topic. - * - * This function sends an MQTT subscribe packet to the server. It registers - * a subscription that will cause the provided callback function to be invoked - * when the server sends a message on a matching topic to the client. - * - * @note Incoming messages are handled by @ref mqtt_function_yield. Therefore, - * @ref mqtt_function_yield must always be called regularly if any subscriptions - * are active. - * - * @param[in] pClient MQTT client context - * @param[in] pTopicName Topic for subscription - * @param[in] topicNameLen Length of topic - * @param[in] qos Quality of service for subscription - * @param[in] pApplicationHandler Callback function for incoming messages that arrive - * on this subscription - * @param[in] pApplicationHandlerData Data passed to the callback - * - * @return `IoT_Error_t`: See `aws_iot_error.h` - * - * @attention The `pTopicName` parameter is not copied. It must remain valid for the duration - * of the subscription (until @ref mqtt_function_unsubscribe) is called. - */ -/* @[declare_mqtt_subscribe] */ -IoT_Error_t aws_iot_mqtt_subscribe(AWS_IoT_Client *pClient, const char *pTopicName, uint16_t topicNameLen, - QoS qos, pApplicationHandler_t pApplicationHandler, void *pApplicationHandlerData); -/* @[declare_mqtt_subscribe] */ - -/** - * @brief Resubscribe to topic filter subscriptions in a previous MQTT session. - * - * This function restores subscriptions that were previously present in an - * MQTT session. Its primary use is to restore subscriptions after a session - * is manually disconnected and reopened. - * - * @note This function does not need to be called after @ref mqtt_function_attempt_reconnect - * or if auto-reconnect is enabled. - * - * @param[in] pClient MQTT client context - * - * @return `IoT_Error_t`: See `aws_iot_error.h` - */ -/* @[declare_mqtt_resubscribe] */ -IoT_Error_t aws_iot_mqtt_resubscribe(AWS_IoT_Client *pClient); -/* @[declare_mqtt_resubscribe] */ - -/** - * @brief Unsubscribe from an MQTT topic filter. - * - * This function removes an MQTT subscription previously set by @ref mqtt_function_subscribe. - * It sends an MQTT UNSUBSCRIBE packet to the server and removes the topic's message - * handler stored by the client. - * - * @param[in] pClient MQTT client context - * @param[in] pTopicFilter Topic filter of the subscription to remove - * @param[in] topicFilterLen Length of topic filter to remove - * - * @return `IoT_Error_t`: See `aws_iot_error.h` - */ -/* @[declare_mqtt_unsubscribe] */ -IoT_Error_t aws_iot_mqtt_unsubscribe(AWS_IoT_Client *pClient, const char *pTopicFilter, uint16_t topicFilterLen); -/* @[declare_mqtt_unsubscribe] */ - -/** - * @brief Disconnect an MQTT session. - * - * This function sends the MQTT DISCONNECT packet, which closes the MQTT session - * between the client and server. After this function returns, the MQTT client - * context should be either freed with @ref mqtt_function_free or reopened with - * @ref mqtt_function_connect. - * - * @param[in] pClient MQTT client context - * - * @return `IoT_Error_t`: See `aws_iot_error.h` - */ -/* @[declare_mqtt_disconnect] */ -IoT_Error_t aws_iot_mqtt_disconnect(AWS_IoT_Client *pClient); -/* @[declare_mqtt_disconnect] */ - -/** - * @brief Provide time for the MQTT client to process events. - * - * This function processes the following events: - * - Incoming messages from the server
- * Whenever a client publishes a message on a topic, the server sends that - * message to all the clients whose subscriptions match the message's - * topic. The messages sent by the server are received by this function, - * which in turn calls the corresponding message handler. This function - * must be called at a rate faster than the incoming messages, as it is the - * only way the client receives processing time to manage incoming messages. - * - MQTT keep-alive (sending ping requests and processing ping responses)
- * The MQTT keep-alive mechanism involves sending pings to the server if the connection - * is idle. Therefore, in the absence of any other messages, this function must be called - * at least once every keep-alive period to send the ping request. - * - @ref mqtt_autoreconnect (if enabled)
- * If the client detects a disconnect, the reconnection will be performed in this function. - * - * @param[in] pClient MQTT client context - * @param[in] timeout_ms Amount of time to yield. This function will return to the caller - * after AT LEAST this amount of thime has passed. - * - * @return `IoT_Error_t`: See `aws_iot_error.h` - * @return If this call results a negative value, assume the MQTT connection has dropped. - * @ref mqtt_function_is_client_connected can be called to confirm. If a reconnection is - * needed, @ref mqtt_function_attempt_reconnect should be called. - */ -/* @[declare_mqtt_yield] */ -IoT_Error_t aws_iot_mqtt_yield(AWS_IoT_Client *pClient, uint32_t timeout_ms); -/* @[declare_mqtt_yield] */ - -/** - * @brief Attempt to reconnect with the MQTT server. - * - * This function makes a single reconnect attempt with the server. If the - * reconnection is successful, subscriptions from the client's previous - * session are restored as well. - * - * If this function fails, the client's state is set to `CLIENT_STATE_PENDING_RECONNECT`. - * - * @param[in] pClient MQTT client context - * - * @return `IoT_Error_t`: See `aws_iot_error.h` - * - * @note Generally, it is not necessary to call this function if @ref mqtt_autoreconnect - * is enabled. This function may still be called to initiate a reconnect attempt when - * auto-reconnect has exhausted all attempts. - */ -/* @[declare_mqtt_attempt_reconnect] */ -IoT_Error_t aws_iot_mqtt_attempt_reconnect(AWS_IoT_Client *pClient); -/* @[declare_mqtt_attempt_reconnect] */ - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_actions.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_actions.h deleted file mode 100644 index 279c0cbec..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_actions.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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, size_t jsonSize, 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_interface.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_interface.h deleted file mode 100644 index 241edba70..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_interface.h +++ /dev/null @@ -1,305 +0,0 @@ -/* - * 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; ///< Network port for TCP/IP socket - 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 Clean shadow client from all dynamic memory allocate -* -* This function will free up memory that was dynamically allocated for the client. -* -* @param pClient MQTT Client that was previously created by calling aws_iot_shadow_init -* @return An IoT Error Type defining successful/failed freeing -*/ -IoT_Error_t aws_iot_shadow_free(AWS_IoT_Client *pClient); - -/** - * @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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_json.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_json.h deleted file mode 100644 index 748ff0884..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_json.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * 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, size_t jsonSize, void *pJsonHandler, int32_t *pTokenCount); - -bool isJsonKeyMatchingAndUpdateValue(const char *pJsonDocument, void *pJsonHandler, int32_t tokenCount, - jsonStruct_t *pDataStruct, uint32_t *pDataLength, int32_t *pDataPosition); - -IoT_Error_t aws_iot_shadow_internal_get_request_json(char *pBuffer, size_t bufferSize); - -IoT_Error_t aws_iot_shadow_internal_delete_request_json(char *pBuffer, size_t bufferSize); - -void resetClientTokenSequenceNum(void); - - -bool isReceivedJsonValid(const char *pJsonDocument, size_t jsonSize); - -bool extractClientToken(const char *pJsonDocument, size_t jsonSize, char *pExtractedClientToken, size_t clientTokenSize); - -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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_json_data.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_json_data.h deleted file mode 100644 index e2c61ac51..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_json_data.h +++ /dev/null @@ -1,150 +0,0 @@ -/* - * 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) - size_t dataLength; ///< Length (in bytes) of pData - 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_key.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_key.h deleted file mode 100644 index 075a726da..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_key.h +++ /dev/null @@ -1,22 +0,0 @@ -/* - * 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_records.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_records.h deleted file mode 100644 index fc2de0322..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_shadow_records.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_version.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_version.h deleted file mode 100644 index 873949b07..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/aws_iot_version.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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 3 -/** - * @brief MINOR version when functionality is added in a backwards-compatible manner. - */ -#define VERSION_MINOR 0 -/** - * @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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/network_interface.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/network_interface.h deleted file mode 100644 index cf2834106..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/network_interface.h +++ /dev/null @@ -1,167 +0,0 @@ -/* - * 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/threads_interface.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/threads_interface.h deleted file mode 100644 index b4bc3705d..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/threads_interface.h +++ /dev/null @@ -1,108 +0,0 @@ -/* -* 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/timer_interface.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/timer_interface.h deleted file mode 100644 index 0bef0fc94..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/include/timer_interface.h +++ /dev/null @@ -1,105 +0,0 @@ -/******************************************************************************* - * 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/platform/linux/common/timer.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/platform/linux/common/timer.c deleted file mode 100644 index d7cc204bd..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/platform/linux/common/timer.c +++ /dev/null @@ -1,82 +0,0 @@ -/* - * 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 res.tv_sec < 0 || (res.tv_sec == 0 && res.tv_usec <= 0); -} - -void countdown_ms(Timer *timer, uint32_t timeout) { - struct timeval now; -#ifdef __cplusplus - struct timeval interval = {timeout / 1000, static_cast((timeout % 1000) * 1000)}; -#else - struct timeval interval = {timeout / 1000, (int)((timeout % 1000) * 1000)}; -#endif - gettimeofday(&now, NULL); - timeradd(&now, &interval, &timer->end_time); -} - -uint32_t left_ms(Timer *timer) { - struct timeval now, res; - uint32_t result_ms = 0; - gettimeofday(&now, NULL); - timersub(&timer->end_time, &now, &res); - if(res.tv_sec >= 0) { - result_ms = (uint32_t) (res.tv_sec * 1000 + res.tv_usec / 1000); - } - return result_ms; -} - -void countdown_sec(Timer *timer, uint32_t timeout) { - struct timeval now; - struct timeval interval = {timeout, 0}; - gettimeofday(&now, NULL); - timeradd(&now, &interval, &timer->end_time); -} - -void init_timer(Timer *timer) { - timer->end_time = (struct timeval) {0, 0}; -} - -void delay(unsigned milliseconds) -{ - useconds_t sleepTime = (useconds_t)(milliseconds * 1000); - - usleep(sleepTime); -} - -#ifdef __cplusplus -} -#endif diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/platform/linux/common/timer_platform.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/platform/linux/common/timer_platform.h deleted file mode 100644 index d381447e0..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/platform/linux/common/timer_platform.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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; -}; - -/** - * @brief Delay (sleep) for the specified number of milliseconds. - * - * @param milliseconds The number of milliseconds to sleep. - */ -void delay(unsigned milliseconds); - -#ifdef __cplusplus -} -#endif - -#endif /* SRC_PROTOCOL_MQTT_AWS_IOT_EMBEDDED_CLIENT_WRAPPER_PLATFORM_LINUX_COMMON_TIMER_PLATFORM_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/platform/linux/mbedtls/network_mbedtls_wrapper.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/platform/linux/mbedtls/network_mbedtls_wrapper.c deleted file mode 100644 index a91d4aa61..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/platform/linux/mbedtls/network_mbedtls_wrapper.c +++ /dev/null @@ -1,440 +0,0 @@ -/* - * 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 "aws_iot_config.h" - -#include -#include - -#include "aws_iot_error.h" -#include "aws_iot_log.h" -#include "network_interface.h" -#include "network_platform.h" - - -/* This is the value used for ssl read timeout */ -#ifndef IOT_SSL_READ_TIMEOUT_MS - #define IOT_SSL_READ_TIMEOUT_MS 3 -#endif - -/* When this much time has elapsed after receiving MBEDTLS_ERR_SSL_WANT_READ - * or MBEDTLS_ERR_SSL_WANT_WRITE, then iot_tls_write will return - * NETWORK_SSL_WRITE_TIMEOUT_ERROR. */ -#ifndef IOT_SSL_WRITE_RETRY_TIMEOUT_MS - #define IOT_SSL_WRITE_RETRY_TIMEOUT_MS 10 -#endif - -/* When this much time has elapsed after receiving MBEDTLS_ERR_SSL_WANT_READ, - * MBEDTLS_ERR_SSL_WANT_WRITE, or MBEDTLS_ERR_SSL_TIMEOUT, then iot_tls_read - * will return NETWORK_SSL_READ_TIMEOUT_ERROR. */ -#ifndef IOT_SSL_READ_RETRY_TIMEOUT_MS - #define IOT_SSL_READ_RETRY_TIMEOUT_MS 10 -#endif - -/* This defines the value of the debug buffer that gets allocated. - * The value can be altered based on memory constraints - */ -#ifdef ENABLE_IOT_DEBUG -#define MBEDTLS_DEBUG_BUFFER_SIZE 2048 -#endif - -/* - * This is a function to do further verification if needed on the cert received - */ - -static int _iot_tls_verify_cert(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags) { - char buf[1024]; - ((void) data); - - IOT_DEBUG("\nVerify requested for (Depth %d):\n", depth); - mbedtls_x509_crt_info(buf, sizeof(buf) - 1, "", crt); - IOT_DEBUG("%s", buf); - - if((*flags) == 0) { - IOT_DEBUG(" This certificate has no flags\n"); - } else { - IOT_DEBUG(buf, sizeof(buf), " ! ", *flags); - IOT_DEBUG("%s\n", buf); - } - - return 0; -} - -void _iot_tls_set_connect_params(Network *pNetwork, char *pRootCALocation, char *pDeviceCertLocation, - char *pDevicePrivateKeyLocation, char *pDestinationURL, - uint16_t destinationPort, uint32_t timeout_ms, bool ServerVerificationFlag) { - pNetwork->tlsConnectParams.DestinationPort = destinationPort; - pNetwork->tlsConnectParams.pDestinationURL = pDestinationURL; - pNetwork->tlsConnectParams.pDeviceCertLocation = pDeviceCertLocation; - pNetwork->tlsConnectParams.pDevicePrivateKeyLocation = pDevicePrivateKeyLocation; - pNetwork->tlsConnectParams.pRootCALocation = pRootCALocation; - pNetwork->tlsConnectParams.timeout_ms = timeout_ms; - pNetwork->tlsConnectParams.ServerVerificationFlag = ServerVerificationFlag; -} - -IoT_Error_t iot_tls_init(Network *pNetwork, char *pRootCALocation, char *pDeviceCertLocation, - char *pDevicePrivateKeyLocation, char *pDestinationURL, - uint16_t destinationPort, uint32_t timeout_ms, bool ServerVerificationFlag) { - _iot_tls_set_connect_params(pNetwork, pRootCALocation, pDeviceCertLocation, pDevicePrivateKeyLocation, - pDestinationURL, destinationPort, timeout_ms, ServerVerificationFlag); - - pNetwork->connect = iot_tls_connect; - pNetwork->read = iot_tls_read; - pNetwork->write = iot_tls_write; - pNetwork->disconnect = iot_tls_disconnect; - pNetwork->isConnected = iot_tls_is_connected; - pNetwork->destroy = iot_tls_destroy; - - pNetwork->tlsDataParams.flags = 0; - - return SUCCESS; -} - -IoT_Error_t iot_tls_is_connected(Network *pNetwork) { - /* Use this to add implementation which can check for physical layer disconnect */ - return NETWORK_PHYSICAL_LAYER_CONNECTED; -} - -IoT_Error_t iot_tls_connect(Network *pNetwork, TLSConnectParams *params) { - int ret = 0; - const char *pers = "aws_iot_tls_wrapper"; - TLSDataParams *tlsDataParams = NULL; - char portBuffer[6]; - char vrfy_buf[512]; - const char *alpnProtocols[] = { "x-amzn-mqtt-ca", NULL }; - -#ifdef ENABLE_IOT_DEBUG - unsigned char buf[MBEDTLS_DEBUG_BUFFER_SIZE]; -#endif - - if(NULL == pNetwork) { - return NULL_VALUE_ERROR; - } - - if(NULL != params) { - _iot_tls_set_connect_params(pNetwork, params->pRootCALocation, params->pDeviceCertLocation, - params->pDevicePrivateKeyLocation, params->pDestinationURL, - params->DestinationPort, params->timeout_ms, params->ServerVerificationFlag); - } - - tlsDataParams = &(pNetwork->tlsDataParams); - - mbedtls_net_init(&(tlsDataParams->server_fd)); - mbedtls_ssl_init(&(tlsDataParams->ssl)); - mbedtls_ssl_config_init(&(tlsDataParams->conf)); - mbedtls_ctr_drbg_init(&(tlsDataParams->ctr_drbg)); - mbedtls_x509_crt_init(&(tlsDataParams->cacert)); - mbedtls_x509_crt_init(&(tlsDataParams->clicert)); - mbedtls_pk_init(&(tlsDataParams->pkey)); - - IOT_DEBUG("\n . Seeding the random number generator..."); - mbedtls_entropy_init(&(tlsDataParams->entropy)); - if((ret = mbedtls_ctr_drbg_seed(&(tlsDataParams->ctr_drbg), mbedtls_entropy_func, &(tlsDataParams->entropy), - (const unsigned char *) pers, strlen(pers))) != 0) { - IOT_ERROR(" failed\n ! mbedtls_ctr_drbg_seed returned -0x%x\n", -ret); - return NETWORK_MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED; - } - - IOT_DEBUG(" . Loading the CA root certificate ..."); - ret = mbedtls_x509_crt_parse_file(&(tlsDataParams->cacert), pNetwork->tlsConnectParams.pRootCALocation); - if(ret < 0) { - IOT_ERROR(" failed\n ! mbedtls_x509_crt_parse returned -0x%x while parsing root cert\n\n", -ret); - return NETWORK_X509_ROOT_CRT_PARSE_ERROR; - } - IOT_DEBUG(" ok (%d skipped)\n", ret); - - IOT_DEBUG(" . Loading the client cert. and key..."); - ret = mbedtls_x509_crt_parse_file(&(tlsDataParams->clicert), pNetwork->tlsConnectParams.pDeviceCertLocation); - if(ret != 0) { - IOT_ERROR(" failed\n ! mbedtls_x509_crt_parse returned -0x%x while parsing device cert\n\n", -ret); - return NETWORK_X509_DEVICE_CRT_PARSE_ERROR; - } - - ret = mbedtls_pk_parse_keyfile(&(tlsDataParams->pkey), pNetwork->tlsConnectParams.pDevicePrivateKeyLocation, ""); - if(ret != 0) { - IOT_ERROR(" failed\n ! mbedtls_pk_parse_key returned -0x%x while parsing private key\n\n", -ret); - IOT_DEBUG(" path : %s ", pNetwork->tlsConnectParams.pDevicePrivateKeyLocation); - return NETWORK_PK_PRIVATE_KEY_PARSE_ERROR; - } - IOT_DEBUG(" ok\n"); - snprintf(portBuffer, 6, "%d", pNetwork->tlsConnectParams.DestinationPort); - IOT_DEBUG(" . Connecting to %s/%s...", pNetwork->tlsConnectParams.pDestinationURL, portBuffer); - if((ret = mbedtls_net_connect(&(tlsDataParams->server_fd), pNetwork->tlsConnectParams.pDestinationURL, - portBuffer, MBEDTLS_NET_PROTO_TCP)) != 0) { - IOT_ERROR(" failed\n ! mbedtls_net_connect returned -0x%x\n\n", -ret); - switch(ret) { - case MBEDTLS_ERR_NET_SOCKET_FAILED: - return NETWORK_ERR_NET_SOCKET_FAILED; - case MBEDTLS_ERR_NET_UNKNOWN_HOST: - return NETWORK_ERR_NET_UNKNOWN_HOST; - case MBEDTLS_ERR_NET_CONNECT_FAILED: - default: - return NETWORK_ERR_NET_CONNECT_FAILED; - }; - } - - ret = mbedtls_net_set_block(&(tlsDataParams->server_fd)); - if(ret != 0) { - IOT_ERROR(" failed\n ! net_set_(non)block() returned -0x%x\n\n", -ret); - return SSL_CONNECTION_ERROR; - } IOT_DEBUG(" ok\n"); - - IOT_DEBUG(" . Setting up the SSL/TLS structure..."); - if((ret = mbedtls_ssl_config_defaults(&(tlsDataParams->conf), MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, - MBEDTLS_SSL_PRESET_DEFAULT)) != 0) { - IOT_ERROR(" failed\n ! mbedtls_ssl_config_defaults returned -0x%x\n\n", -ret); - return SSL_CONNECTION_ERROR; - } - - mbedtls_ssl_conf_verify(&(tlsDataParams->conf), _iot_tls_verify_cert, NULL); - if(pNetwork->tlsConnectParams.ServerVerificationFlag == true) { - mbedtls_ssl_conf_authmode(&(tlsDataParams->conf), MBEDTLS_SSL_VERIFY_REQUIRED); - } else { - mbedtls_ssl_conf_authmode(&(tlsDataParams->conf), MBEDTLS_SSL_VERIFY_OPTIONAL); - } - mbedtls_ssl_conf_rng(&(tlsDataParams->conf), mbedtls_ctr_drbg_random, &(tlsDataParams->ctr_drbg)); - - mbedtls_ssl_conf_ca_chain(&(tlsDataParams->conf), &(tlsDataParams->cacert), NULL); - if((ret = mbedtls_ssl_conf_own_cert(&(tlsDataParams->conf), &(tlsDataParams->clicert), &(tlsDataParams->pkey))) != - 0) { - IOT_ERROR(" failed\n ! mbedtls_ssl_conf_own_cert returned %d\n\n", ret); - return SSL_CONNECTION_ERROR; - } - - mbedtls_ssl_conf_read_timeout(&(tlsDataParams->conf), pNetwork->tlsConnectParams.timeout_ms); - - /* Use the AWS IoT ALPN extension for MQTT if port 443 is requested. */ - if(443 == pNetwork->tlsConnectParams.DestinationPort) { - if((ret = mbedtls_ssl_conf_alpn_protocols(&(tlsDataParams->conf), alpnProtocols)) != 0) { - IOT_ERROR(" failed\n ! mbedtls_ssl_conf_alpn_protocols returned -0x%x\n\n", -ret); - return SSL_CONNECTION_ERROR; - } - } - - /* Assign the resulting configuration to the SSL context. */ - if((ret = mbedtls_ssl_setup(&(tlsDataParams->ssl), &(tlsDataParams->conf))) != 0) { - IOT_ERROR(" failed\n ! mbedtls_ssl_setup returned -0x%x\n\n", -ret); - return SSL_CONNECTION_ERROR; - } - if((ret = mbedtls_ssl_set_hostname(&(tlsDataParams->ssl), pNetwork->tlsConnectParams.pDestinationURL)) != 0) { - IOT_ERROR(" failed\n ! mbedtls_ssl_set_hostname returned %d\n\n", ret); - return SSL_CONNECTION_ERROR; - } - IOT_DEBUG("\n\nSSL state connect : %d ", tlsDataParams->ssl.state); - mbedtls_ssl_set_bio(&(tlsDataParams->ssl), &(tlsDataParams->server_fd), mbedtls_net_send, NULL, - mbedtls_net_recv_timeout); - IOT_DEBUG(" ok\n"); - - IOT_DEBUG("\n\nSSL state connect : %d ", tlsDataParams->ssl.state); - IOT_DEBUG(" . Performing the SSL/TLS handshake..."); - while((ret = mbedtls_ssl_handshake(&(tlsDataParams->ssl))) != 0) { - if(ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { - IOT_ERROR(" failed\n ! mbedtls_ssl_handshake returned -0x%x\n", -ret); - if(ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) { - IOT_ERROR(" Unable to verify the server's certificate. " - "Either it is invalid,\n" - " or you didn't set ca_file or ca_path " - "to an appropriate value.\n" - " Alternatively, you may want to use " - "auth_mode=optional for testing purposes.\n"); - } - return SSL_CONNECTION_ERROR; - } - } - - IOT_DEBUG(" ok\n [ Protocol is %s ]\n [ Ciphersuite is %s ]\n", mbedtls_ssl_get_version(&(tlsDataParams->ssl)), - mbedtls_ssl_get_ciphersuite(&(tlsDataParams->ssl))); - if((ret = mbedtls_ssl_get_record_expansion(&(tlsDataParams->ssl))) >= 0) { - IOT_DEBUG(" [ Record expansion is %d ]\n", ret); - } else { - IOT_DEBUG(" [ Record expansion is unknown (compression) ]\n"); - } - - IOT_DEBUG(" . Verifying peer X.509 certificate..."); - - if(pNetwork->tlsConnectParams.ServerVerificationFlag == true) { - if((tlsDataParams->flags = mbedtls_ssl_get_verify_result(&(tlsDataParams->ssl))) != 0) { - IOT_ERROR(" failed\n"); - mbedtls_x509_crt_verify_info(vrfy_buf, sizeof(vrfy_buf), " ! ", tlsDataParams->flags); - IOT_ERROR("%s\n", vrfy_buf); - ret = SSL_CONNECTION_ERROR; - } else { - IOT_DEBUG(" ok\n"); - ret = SUCCESS; - } - } else { - IOT_DEBUG(" Server Verification skipped\n"); - ret = SUCCESS; - } - -#ifdef ENABLE_IOT_DEBUG - if(mbedtls_ssl_get_peer_cert(&(tlsDataParams->ssl)) != NULL) { - IOT_DEBUG(" . Peer certificate information ...\n"); - mbedtls_x509_crt_info((char *) buf, sizeof(buf) - 1, " ", mbedtls_ssl_get_peer_cert(&(tlsDataParams->ssl))); - IOT_DEBUG("%s\n", buf); - } -#endif - - mbedtls_ssl_conf_read_timeout(&(tlsDataParams->conf), IOT_SSL_READ_TIMEOUT_MS); - -#ifdef IOT_SSL_SOCKET_NON_BLOCKING - mbedtls_net_set_nonblock(&(tlsDataParams->server_fd)); -#endif - - 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) { - mbedtls_ssl_context *pSsl = &(pNetwork->tlsDataParams.ssl); - size_t txLen = 0U; - int ret = 0; - /* This timer checks for a timeout whenever MBEDTLS_ERR_SSL_WANT_READ - * or MBEDTLS_ERR_SSL_WANT_WRITE are returned by mbedtls_ssl_write. - * Timeout is specified by IOT_SSL_WRITE_RETRY_TIMEOUT_MS. */ - Timer writeTimer; - - /* This variable is unused */ - (void) timer; - - /* The timer must be started in case no bytes are written on the first try */ - init_timer(&writeTimer); - countdown_ms(&writeTimer, IOT_SSL_WRITE_RETRY_TIMEOUT_MS); - - while(len > 0U) { - ret = mbedtls_ssl_write(pSsl, pMsg, len); - - if(ret > 0) { - if((size_t) ret > len) { - IOT_ERROR("More bytes written than requested\n\n"); - return NETWORK_SSL_WRITE_ERROR; - } - - /* Successfully sent data, so reset the timeout */ - init_timer(&writeTimer); - countdown_ms(&writeTimer, IOT_SSL_WRITE_RETRY_TIMEOUT_MS); - - txLen += ret; - pMsg += ret; - len -= ret; - } else if(ret == MBEDTLS_ERR_SSL_WANT_READ || - ret == MBEDTLS_ERR_SSL_WANT_WRITE) { - if(has_timer_expired(&writeTimer)) { - *written_len = txLen; - return NETWORK_SSL_WRITE_TIMEOUT_ERROR; - } - } else { - IOT_ERROR(" failed\n ! mbedtls_ssl_write returned -0x%x\n\n", (unsigned int) -ret); - /* All other negative return values indicate connection needs to be reset. - * Will be caught in ping request so ignored here */ - return NETWORK_SSL_WRITE_ERROR; - } - } - - *written_len = txLen; - 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 *pSsl = &(pNetwork->tlsDataParams.ssl); - size_t rxLen = 0U; - int ret; - /* This timer checks for a timeout whenever MBEDTLS_ERR_SSL_WANT_READ, - * MBEDTLS_ERR_SSL_WANT_WRITE, or MBEDTLS_ERR_SSL_TIMEOUT are returned by - * mbedtls_ssl_read. Timeout is specified by IOT_SSL_READ_RETRY_TIMEOUT_MS. */ - Timer readTimer; - - /* This variable is unused */ - (void) timer; - - /* The timer must be started in case no bytes are read on the first try */ - init_timer(&readTimer); - countdown_ms(&readTimer, IOT_SSL_READ_RETRY_TIMEOUT_MS); - - while(len > 0U) { - /* This read will timeout after IOT_SSL_READ_TIMEOUT_MS if there's no data to be read */ - ret = mbedtls_ssl_read(pSsl, pMsg, len); - - if(ret > 0) { - if((size_t) ret > len) { - IOT_ERROR("More bytes read than requested\n\n"); - return NETWORK_SSL_WRITE_ERROR; - } - - /* Successfully received data, so reset the timeout */ - init_timer(&readTimer); - countdown_ms(&readTimer, IOT_SSL_READ_RETRY_TIMEOUT_MS); - - rxLen += ret; - pMsg += ret; - len -= ret; - } else if(ret == MBEDTLS_ERR_SSL_WANT_READ || - ret == MBEDTLS_ERR_SSL_WANT_WRITE || - ret == MBEDTLS_ERR_SSL_TIMEOUT) { - if(has_timer_expired(&readTimer)) { - *read_len = rxLen; - if(rxLen == 0U) { - return NETWORK_SSL_NOTHING_TO_READ; - } else { - return NETWORK_SSL_READ_TIMEOUT_ERROR; - } - } - } else { - IOT_ERROR("Failed\n ! mbedtls_ssl_read returned -0x%x\n\n", (unsigned int) -ret); - return NETWORK_SSL_READ_ERROR; - } - } - - *read_len = rxLen; - return SUCCESS; -} - -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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/platform/linux/mbedtls/network_platform.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/platform/linux/mbedtls/network_platform.h deleted file mode 100644 index c2810a1c8..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/platform/linux/mbedtls/network_platform.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://aws.amazon.com/apache2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -#ifndef IOTSDKC_NETWORK_MBEDTLS_PLATFORM_H_H - -#include "mbedtls/config.h" - -#include "mbedtls/platform.h" -#include "mbedtls/net.h" -#include "mbedtls/ssl.h" -#include "mbedtls/entropy.h" -#include "mbedtls/ctr_drbg.h" -#include "mbedtls/certs.h" -#include "mbedtls/x509.h" -#include "mbedtls/error.h" -#include "mbedtls/debug.h" -#include "mbedtls/timing.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @brief TLS Connection Parameters - * - * Defines a type containing TLS specific parameters to be passed down to the - * TLS networking layer to create a TLS secured socket. - */ -typedef struct _TLSDataParams { - mbedtls_entropy_context entropy; - mbedtls_ctr_drbg_context ctr_drbg; - mbedtls_ssl_context ssl; - mbedtls_ssl_config conf; - uint32_t flags; - mbedtls_x509_crt cacert; - mbedtls_x509_crt clicert; - mbedtls_pk_context pkey; - mbedtls_net_context server_fd; -}TLSDataParams; - -#define IOTSDKC_NETWORK_MBEDTLS_PLATFORM_H_H - -#ifdef __cplusplus -} -#endif - -#endif //IOTSDKC_NETWORK_MBEDTLS_PLATFORM_H_H diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/platform/linux/pthread/threads_platform.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/platform/linux/pthread/threads_platform.h deleted file mode 100644 index 8a520c637..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/platform/linux/pthread/threads_platform.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/platform/linux/pthread/threads_pthread_wrapper.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/platform/linux/pthread/threads_pthread_wrapper.c deleted file mode 100644 index 65a310fb0..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/platform/linux/pthread/threads_pthread_wrapper.c +++ /dev/null @@ -1,112 +0,0 @@ -/* - * 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/README.md b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/README.md deleted file mode 100644 index a0017f08a..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# Sample apps for the AWS IoT Device SDK for Embedded C - -All samples are written in C unless otherwise mentioned. The these sample apps are included in the SDK and described below. - * [`subscribe_publish_sample`](#subscribe-publish-sample) - demonstrates how to publish and subscribe to MQTT messages. - * [`subscribe_publish_library_sample`](#subscribe-publish-library-sample) - demonstrates how to create a library that provides support to publish and subscribe to MQTT messages. - - These sample apps are also provided in this SDK. - * [`shadow_sample`](https://github.com/aws/aws-iot-device-sdk-embedded-C/tree/master/samples/linux/shadow_sample) - demonstrates how to use a simple device shadow in a connected window example. - * [`shadow_sample_console_echo`](https://github.com/aws/aws-iot-device-sdk-embedded-C/tree/master/samples/linux/shadow_sample_console_echo) - demonstrates how to work with the AWS IoT Console interactive guide. - * [`jobs_sample`](https://github.com/aws/aws-iot-device-sdk-embedded-C/tree/master/samples/linux/jobs_sample) - demonstrates how to connect to the AWS IoT MQTT platform and perform several operations that use the basic capabilities of the AWS IoT Jobs platform. - -## 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 - -## 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 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. diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/jobs_sample/Makefile b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/jobs_sample/Makefile deleted file mode 100644 index 4f74593b8..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/jobs_sample/Makefile +++ /dev/null @@ -1,71 +0,0 @@ -#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 = jobs_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)/sdk_config -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 -CRYPTO_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 $(CRYPTO_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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/jobs_sample/aws_iot_config.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/jobs_sample/aws_iot_config.h deleted file mode 100644 index 7bff6c89e..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/jobs_sample/aws_iot_config.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2010-2018 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_JOBS_IOT_JOB_CONFIG_H_ -#define SRC_JOBS_IOT_JOB_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 443 ///< 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 -#ifndef DISABLE_IOT_JOBS -#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. -#else -#define AWS_IOT_MQTT_RX_BUF_LEN 2048 -#endif -#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_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 - -// Shadow and Job common configs -#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_SIZE_OF_THING_NAME 30 ///< The Thing Name should not be bigger than this value. Modify this if the Thing Name needs to be bigger - -// Thing Shadow specific configs -#define SHADOW_MAX_SIZE_OF_RX_BUFFER 512 ///< Maximum size of the SHADOW buffer to store the received Shadow message -#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_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 - -// Job specific configs -#ifndef DISABLE_IOT_JOBS -#define MAX_SIZE_OF_JOB_ID 64 -#define MAX_JOB_JSON_TOKEN_EXPECTED 120 -#define MAX_SIZE_OF_JOB_REQUEST AWS_IOT_MQTT_TX_BUF_LEN - -#define MAX_JOB_TOPIC_LENGTH_WITHOUT_JOB_ID_OR_THING_NAME 40 -#define MAX_JOB_TOPIC_LENGTH_BYTES MAX_JOB_TOPIC_LENGTH_WITHOUT_JOB_ID_OR_THING_NAME + MAX_SIZE_OF_THING_NAME + MAX_SIZE_OF_JOB_ID + 2 -#endif - -// Auto Reconnect specific config -#define AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL 1000 ///< Minimum time before the First reconnect attempt is made as part of the exponential back-off algorithm -#define AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL 128000 ///< Maximum time interval after which exponential back-off will stop attempting to reconnect. - -#define DISABLE_METRICS false ///< Disable the collection of metrics by setting this to true - -// TLS configs -#define IOT_SSL_READ_TIMEOUT_MS 3 ///< Timeout associated with underlying socket of TLS connection (set by mbedtls_ssl_conf_read_timeout) -#define IOT_SSL_READ_RETRY_TIMEOUT_MS 10 ///< Minimum elapsed time before returning from iot_tls_read when pending data has not yet been received -#define IOT_SSL_WRITE_RETRY_TIMEOUT_MS 10 ///< Minimum elapsed time before returning from iot_tls_write when pending data has not yet been written - -#endif /* SRC_JOBS_IOT_JOB_CONFIG_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/jobs_sample/jobs_sample.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/jobs_sample/jobs_sample.c deleted file mode 100644 index e79f25f7e..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/jobs_sample/jobs_sample.c +++ /dev/null @@ -1,374 +0,0 @@ -/* - * Copyright 2010-2018 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. - */ - -/** - * - * This example takes the parameters from the aws_iot_config.h file and establishes - * a connection to the AWS IoT MQTT Platform. It performs several operations to - * demonstrate the basic capabilities of the AWS IoT Jobs platform. - * - * If all the certs are correct, you should see the list of pending Job Executions - * printed out by the iot_get_pending_callback_handler. If there are any existing pending - * job executions each will be processed one at a time in the iot_next_job_callback_handler. - * After all of the pending jobs have been processed the program will wait for - * notifications for new pending jobs and process them one at a time as they come in. - * - * In the main body you can see how each callback is registered for each corresponding - * Jobs topic. - * - */ -#include -#include -#include -#include -#include -#include - -#include "aws_iot_config.h" -#include "aws_iot_json_utils.h" -#include "aws_iot_log.h" -#include "aws_iot_version.h" -#include "aws_iot_mqtt_client_interface.h" -#include "aws_iot_jobs_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; - -static jsmn_parser jsonParser; -static jsmntok_t jsonTokenStruct[MAX_JSON_TOKEN_EXPECTED]; -static int32_t tokenCount; - -static void iot_get_pending_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("\nJOB_GET_PENDING_TOPIC callback"); - IOT_INFO("topic: %.*s", topicNameLen, topicName); - IOT_INFO("payload: %.*s", (int) params->payloadLen, (char *)params->payload); - - jsmn_init(&jsonParser); - - tokenCount = jsmn_parse(&jsonParser, params->payload, (int) params->payloadLen, jsonTokenStruct, MAX_JSON_TOKEN_EXPECTED); - - if(tokenCount < 0) { - IOT_WARN("Failed to parse JSON: %d", tokenCount); - return; - } - - /* Assume the top-level element is an object */ - if(tokenCount < 1 || jsonTokenStruct[0].type != JSMN_OBJECT) { - IOT_WARN("Top Level is not an object"); - return; - } - - jsmntok_t *jobs; - - jobs = findToken("inProgressJobs", params->payload, jsonTokenStruct); - - if (jobs) { - IOT_INFO("inProgressJobs: %.*s", jobs->end - jobs->start, (char *)params->payload + jobs->start); - } - - jobs = findToken("queuedJobs", params->payload, jsonTokenStruct); - - if (jobs) { - IOT_INFO("queuedJobs: %.*s", jobs->end - jobs->start, (char *)params->payload + jobs->start); - } -} - -static void iot_next_job_callback_handler(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, - IoT_Publish_Message_Params *params, void *pData) { - char topicToPublishUpdate[MAX_JOB_TOPIC_LENGTH_BYTES]; - char messageBuffer[200]; - - IOT_UNUSED(pData); - IOT_UNUSED(pClient); - IOT_INFO("\nJOB_NOTIFY_NEXT_TOPIC / JOB_DESCRIBE_TOPIC($next) callback"); - IOT_INFO("topic: %.*s", topicNameLen, topicName); - IOT_INFO("payload: %.*s", (int) params->payloadLen, (char *)params->payload); - - jsmn_init(&jsonParser); - - tokenCount = jsmn_parse(&jsonParser, params->payload, (int) params->payloadLen, jsonTokenStruct, MAX_JSON_TOKEN_EXPECTED); - - if(tokenCount < 0) { - IOT_WARN("Failed to parse JSON: %d", tokenCount); - return; - } - - /* Assume the top-level element is an object */ - if(tokenCount < 1 || jsonTokenStruct[0].type != JSMN_OBJECT) { - IOT_WARN("Top Level is not an object"); - return; - } - - jsmntok_t *tokExecution; - - tokExecution = findToken("execution", params->payload, jsonTokenStruct); - - if (tokExecution) { - IOT_INFO("execution: %.*s", tokExecution->end - tokExecution->start, (char *)params->payload + tokExecution->start); - - jsmntok_t *tok; - - tok = findToken("jobId", params->payload, tokExecution); - - if (tok) { - IoT_Error_t rc; - char jobId[MAX_SIZE_OF_JOB_ID + 1]; - AwsIotJobExecutionUpdateRequest updateRequest; - - rc = parseStringValue(jobId, MAX_SIZE_OF_JOB_ID + 1, params->payload, tok); - if(SUCCESS != rc) { - IOT_ERROR("parseStringValue returned error : %d ", rc); - return; - } - - IOT_INFO("jobId: %s", jobId); - - tok = findToken("jobDocument", params->payload, tokExecution); - - /* - * Do your job processing here. - */ - - if (tok) { - IOT_INFO("jobDocument: %.*s", tok->end - tok->start, (char *)params->payload + tok->start); - /* Alternatively if the job still has more steps the status can be set to JOB_EXECUTION_IN_PROGRESS instead */ - updateRequest.status = JOB_EXECUTION_SUCCEEDED; - updateRequest.statusDetails = "{\"exampleDetail\":\"a value appropriate for your successful job\"}"; - } else { - updateRequest.status = JOB_EXECUTION_FAILED; - updateRequest.statusDetails = "{\"failureDetail\":\"Unable to process job document\"}"; - } - - updateRequest.expectedVersion = 0; - updateRequest.executionNumber = 0; - updateRequest.includeJobExecutionState = false; - updateRequest.includeJobDocument = false; - updateRequest.clientToken = NULL; - - rc = aws_iot_jobs_send_update(pClient, QOS0, AWS_IOT_MY_THING_NAME, jobId, &updateRequest, - topicToPublishUpdate, sizeof(topicToPublishUpdate), messageBuffer, sizeof(messageBuffer)); - if(SUCCESS != rc) { - IOT_ERROR("aws_iot_jobs_send_update returned error : %d ", rc); - return; - } - } - } else { - IOT_INFO("execution property not found, nothing to do"); - } -} - -static void iot_update_accepted_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("\nJOB_UPDATE_TOPIC / accepted callback"); - IOT_INFO("topic: %.*s", topicNameLen, topicName); - IOT_INFO("payload: %.*s", (int) params->payloadLen, (char *)params->payload); -} - -static void iot_update_rejected_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("\nJOB_UPDATE_TOPIC / rejected callback"); - IOT_INFO("topic: %.*s", topicNameLen, topicName); - IOT_INFO("payload: %.*s", (int) params->payloadLen, (char *)params->payload); - - /* Do error handling here for when the update was rejected */ -} - -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); - } - } -} - -int main(int argc, char **argv) { - char rootCA[PATH_MAX + 1]; - char clientCRT[PATH_MAX + 1]; - char clientKey[PATH_MAX + 1]; - char CurrentWD[PATH_MAX + 1]; - char cPayload[100]; - - 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; - - getcwd(CurrentWD, sizeof(CurrentWD)); - snprintf(rootCA, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_ROOT_CA_FILENAME); - snprintf(clientCRT, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_CERTIFICATE_FILENAME); - snprintf(clientKey, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_PRIVATE_KEY_FILENAME); - - IOT_DEBUG("rootCA %s", rootCA); - IOT_DEBUG("clientCRT %s", clientCRT); - IOT_DEBUG("clientKey %s", clientKey); - - mqttInitParams.enableAutoReconnect = false; // We enable this later below - mqttInitParams.pHostURL = HostAddress; - mqttInitParams.port = port; - mqttInitParams.pRootCALocation = rootCA; - mqttInitParams.pDeviceCertLocation = clientCRT; - mqttInitParams.pDevicePrivateKeyLocation = clientKey; - mqttInitParams.mqttCommandTimeout_ms = 20000; - mqttInitParams.tlsHandshakeTimeout_ms = 5000; - mqttInitParams.isSSLHostnameVerify = true; - mqttInitParams.disconnectHandler = disconnectCallbackHandler; - mqttInitParams.disconnectHandlerData = NULL; - - rc = aws_iot_mqtt_init(&client, &mqttInitParams); - if(SUCCESS != rc) { - IOT_ERROR("aws_iot_mqtt_init returned error : %d ", rc); - return rc; - } - - connectParams.keepAliveIntervalInSec = 600; - connectParams.isCleanSession = true; - connectParams.MQTTVersion = MQTT_3_1_1; - connectParams.pClientID = AWS_IOT_MQTT_CLIENT_ID; - connectParams.clientIDLen = (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID); - connectParams.isWillMsgPresent = false; - - IOT_INFO("Connecting..."); - rc = aws_iot_mqtt_connect(&client, &connectParams); - if(SUCCESS != rc) { - IOT_ERROR("Error(%d) connecting to %s:%d", rc, mqttInitParams.pHostURL, mqttInitParams.port); - return rc; - } - /* - * Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h - * #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL - * #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL - */ - rc = aws_iot_mqtt_autoreconnect_set_status(&client, true); - if(SUCCESS != rc) { - IOT_ERROR("Unable to set Auto Reconnect to true - %d", rc); - return rc; - } - - char topicToSubscribeGetPending[MAX_JOB_TOPIC_LENGTH_BYTES]; - char topicToSubscribeNotifyNext[MAX_JOB_TOPIC_LENGTH_BYTES]; - char topicToSubscribeGetNext[MAX_JOB_TOPIC_LENGTH_BYTES]; - char topicToSubscribeUpdateAccepted[MAX_JOB_TOPIC_LENGTH_BYTES]; - char topicToSubscribeUpdateRejected[MAX_JOB_TOPIC_LENGTH_BYTES]; - - char topicToPublishGetPending[MAX_JOB_TOPIC_LENGTH_BYTES]; - char topicToPublishGetNext[MAX_JOB_TOPIC_LENGTH_BYTES]; - - rc = aws_iot_jobs_subscribe_to_job_messages( - &client, QOS0, AWS_IOT_MY_THING_NAME, NULL, JOB_GET_PENDING_TOPIC, JOB_WILDCARD_REPLY_TYPE, - iot_get_pending_callback_handler, NULL, topicToSubscribeGetPending, sizeof(topicToSubscribeGetPending)); - - if(SUCCESS != rc) { - IOT_ERROR("Error subscribing JOB_GET_PENDING_TOPIC: %d ", rc); - return rc; - } - - rc = aws_iot_jobs_subscribe_to_job_messages( - &client, QOS0, AWS_IOT_MY_THING_NAME, NULL, JOB_NOTIFY_NEXT_TOPIC, JOB_REQUEST_TYPE, - iot_next_job_callback_handler, NULL, topicToSubscribeNotifyNext, sizeof(topicToSubscribeNotifyNext)); - - if(SUCCESS != rc) { - IOT_ERROR("Error subscribing JOB_NOTIFY_NEXT_TOPIC: %d ", rc); - return rc; - } - - rc = aws_iot_jobs_subscribe_to_job_messages( - &client, QOS0, AWS_IOT_MY_THING_NAME, JOB_ID_NEXT, JOB_DESCRIBE_TOPIC, JOB_WILDCARD_REPLY_TYPE, - iot_next_job_callback_handler, NULL, topicToSubscribeGetNext, sizeof(topicToSubscribeGetNext)); - - if(SUCCESS != rc) { - IOT_ERROR("Error subscribing JOB_DESCRIBE_TOPIC ($next): %d ", rc); - return rc; - } - - rc = aws_iot_jobs_subscribe_to_job_messages( - &client, QOS0, AWS_IOT_MY_THING_NAME, JOB_ID_WILDCARD, JOB_UPDATE_TOPIC, JOB_ACCEPTED_REPLY_TYPE, - iot_update_accepted_callback_handler, NULL, topicToSubscribeUpdateAccepted, sizeof(topicToSubscribeUpdateAccepted)); - - if(SUCCESS != rc) { - IOT_ERROR("Error subscribing JOB_UPDATE_TOPIC/accepted: %d ", rc); - return rc; - } - - rc = aws_iot_jobs_subscribe_to_job_messages( - &client, QOS0, AWS_IOT_MY_THING_NAME, JOB_ID_WILDCARD, JOB_UPDATE_TOPIC, JOB_REJECTED_REPLY_TYPE, - iot_update_rejected_callback_handler, NULL, topicToSubscribeUpdateRejected, sizeof(topicToSubscribeUpdateRejected)); - - if(SUCCESS != rc) { - IOT_ERROR("Error subscribing JOB_UPDATE_TOPIC/rejected: %d ", rc); - return rc; - } - - paramsQOS0.qos = QOS0; - paramsQOS0.payload = (void *) cPayload; - paramsQOS0.isRetained = 0; - paramsQOS0.payloadLen = strlen(cPayload); - - rc = aws_iot_jobs_send_query(&client, QOS0, AWS_IOT_MY_THING_NAME, NULL, NULL, topicToPublishGetPending, sizeof(topicToPublishGetPending), NULL, 0, JOB_GET_PENDING_TOPIC); - if(SUCCESS != rc) { - IOT_ERROR("Error calling aws_iot_jobs_send_query: %d ", rc); - return rc; - } - - AwsIotDescribeJobExecutionRequest describeRequest; - describeRequest.executionNumber = 0; - describeRequest.includeJobDocument = true; - describeRequest.clientToken = NULL; - - rc = aws_iot_jobs_describe(&client, QOS0, AWS_IOT_MY_THING_NAME, JOB_ID_NEXT, &describeRequest, topicToPublishGetNext, sizeof(topicToPublishGetNext), NULL, 0); - - while(SUCCESS == rc) { - //Max time the yield function will wait for read messages - rc = aws_iot_mqtt_yield(&client, 50000); - } - - return rc; -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample/Makefile b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample/Makefile deleted file mode 100644 index 9483299fc..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample/Makefile +++ /dev/null @@ -1,72 +0,0 @@ -#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 -CRYPTO_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 $(CRYPTO_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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample/aws_iot_config.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample/aws_iot_config.h deleted file mode 100644 index 81f9e39e8..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample/aws_iot_config.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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 443 ///< default port for MQTT/S -#define AWS_IOT_MQTT_CLIENT_ID "c-sdk-client-id" ///< MQTT client ID should be unique for every device -#define AWS_IOT_MY_THING_NAME "AWS-IoT-C-SDK" ///< Thing Name of the Shadow this device is associated with -#define AWS_IOT_ROOT_CA_FILENAME "rootCA.crt" ///< Root CA file name -#define AWS_IOT_CERTIFICATE_FILENAME "cert.pem" ///< device signed certificate file name -#define AWS_IOT_PRIVATE_KEY_FILENAME "privkey.pem" ///< Device private key filename -// ================================================= - -// MQTT PubSub -#define AWS_IOT_MQTT_TX_BUF_LEN 512 ///< Any time a message is sent out through the MQTT layer. The message is copied into this buffer anytime a publish is done. This will also be used in the case of Thing Shadow -#define AWS_IOT_MQTT_RX_BUF_LEN 512 ///< Any message that comes into the device should be less than this buffer size. If a received message is bigger than this buffer size the message will be dropped. -#define AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS 5 ///< Maximum number of topic filters the MQTT client can handle at any given time. This should be increased appropriately when using Thing Shadow - -// Thing Shadow specific configs -#define SHADOW_MAX_SIZE_OF_RX_BUFFER (AWS_IOT_MQTT_RX_BUF_LEN+1) ///< Maximum size of the SHADOW buffer to store the received Shadow message, including terminating NULL byte. -#define MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES 80 ///< Maximum size of the Unique Client Id. For More info on the Client Id refer \ref response "Acknowledgments" -#define MAX_SIZE_CLIENT_ID_WITH_SEQUENCE MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES + 10 ///< This is size of the extra sequence number that will be appended to the Unique client Id -#define MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE MAX_SIZE_CLIENT_ID_WITH_SEQUENCE + 20 ///< This is size of the the total clientToken key and value pair in the JSON -#define MAX_ACKS_TO_COMEIN_AT_ANY_GIVEN_TIME 10 ///< At Any given time we will wait for this many responses. This will correlate to the rate at which the shadow actions are requested -#define MAX_THINGNAME_HANDLED_AT_ANY_GIVEN_TIME 10 ///< We could perform shadow action on any thing Name and this is maximum Thing Names we can act on at any given time -#define MAX_JSON_TOKEN_EXPECTED 120 ///< These are the max tokens that is expected to be in the Shadow JSON document. Include the metadata that gets published -#define MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME 60 ///< All shadow actions have to be published or subscribed to a topic which is of the format $aws/things/{thingName}/shadow/update/accepted. This refers to the size of the topic without the Thing Name -#define MAX_SIZE_OF_THING_NAME 20 ///< The Thing Name should not be bigger than this value. Modify this if the Thing Name needs to be bigger -#define MAX_SHADOW_TOPIC_LENGTH_BYTES MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME + MAX_SIZE_OF_THING_NAME ///< This size includes the length of topic with Thing Name - -// Auto Reconnect specific config -#define AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL 1000 ///< Minimum time before the First reconnect attempt is made as part of the exponential back-off algorithm -#define AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL 128000 ///< Maximum time interval after which exponential back-off will stop attempting to reconnect. - -#define DISABLE_METRICS false ///< Disable the collection of metrics by setting this to true - -// TLS configs -#define IOT_SSL_READ_TIMEOUT_MS 3 ///< Timeout associated with underlying socket of TLS connection (set by mbedtls_ssl_conf_read_timeout) -#define IOT_SSL_READ_RETRY_TIMEOUT_MS 10 ///< Minimum elapsed time before returning from iot_tls_read when pending data has not yet been received -#define IOT_SSL_WRITE_RETRY_TIMEOUT_MS 10 ///< Minimum elapsed time before returning from iot_tls_write when pending data has not yet been written - -#endif /* SRC_SHADOW_IOT_SHADOW_CONFIG_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample/shadow_sample.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample/shadow_sample.c deleted file mode 100644 index 2a692c70c..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample/shadow_sample.c +++ /dev/null @@ -1,274 +0,0 @@ -/* - * 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"; -#define HOST_ADDRESS_SIZE 255 -static char HostAddress[HOST_ADDRESS_SIZE] = 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; -} - -static 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 !!"); - } -} - -static 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': - strncpy(HostAddress, optarg, HOST_ADDRESS_SIZE); - IOT_DEBUG("Host %s", optarg); - break; - case 'p': - port = atoi(optarg); - IOT_DEBUG("port %s", optarg); - break; - case 'c': - strncpy(certDirectory, optarg, PATH_MAX + 1); - IOT_DEBUG("cert root directory %s", optarg); - break; - case 'n': - numPubs = atoi(optarg); - IOT_DEBUG("num pubs %s", optarg); - break; - case '?': - if(optopt == 'c') { - IOT_ERROR("Option -%c requires an argument.", optopt); - } else if(isprint(optopt)) { - IOT_WARN("Unknown option `-%c'.", optopt); - } else { - IOT_WARN("Unknown option character `\\x%x'.", optopt); - } - break; - default: - IOT_ERROR("ERROR in command line argument parsing"); - break; - } - } - -} - -int main(int argc, char **argv) { - IoT_Error_t rc = FAILURE; - - char JsonDocumentBuffer[MAX_LENGTH_OF_UPDATE_JSON_BUFFER]; - size_t sizeOfJsonDocumentBuffer = sizeof(JsonDocumentBuffer) / sizeof(JsonDocumentBuffer[0]); - float temperature = 0.0; - - bool windowOpen = false; - jsonStruct_t windowActuator; - windowActuator.cb = windowActuate_Callback; - windowActuator.pData = &windowOpen; - windowActuator.dataLength = sizeof(bool); - windowActuator.pKey = "windowOpen"; - windowActuator.type = SHADOW_JSON_BOOL; - - jsonStruct_t temperatureHandler; - temperatureHandler.cb = NULL; - temperatureHandler.pKey = "temperature"; - temperatureHandler.pData = &temperature; - temperatureHandler.dataLength = sizeof(float); - 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); - - IOT_DEBUG("rootCA %s", rootCA); - IOT_DEBUG("clientCRT %s", clientCRT); - IOT_DEBUG("clientKey %s", clientKey); - - parseInputArgsForConnectParams(argc, argv); - - // generate the paths of the credentials - 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); - - // initialize the mqtt client - AWS_IoT_Client mqttClient; - - ShadowInitParameters_t sp = ShadowInitParametersDefault; - sp.pHost = HostAddress; - sp.port = 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample_console_echo/Makefile b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample_console_echo/Makefile deleted file mode 100644 index ebb173636..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample_console_echo/Makefile +++ /dev/null @@ -1,75 +0,0 @@ -#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 -CRYPTO_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 $(CRYPTO_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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample_console_echo/aws_iot_config.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample_console_echo/aws_iot_config.h deleted file mode 100644 index 81f9e39e8..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample_console_echo/aws_iot_config.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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 443 ///< default port for MQTT/S -#define AWS_IOT_MQTT_CLIENT_ID "c-sdk-client-id" ///< MQTT client ID should be unique for every device -#define AWS_IOT_MY_THING_NAME "AWS-IoT-C-SDK" ///< Thing Name of the Shadow this device is associated with -#define AWS_IOT_ROOT_CA_FILENAME "rootCA.crt" ///< Root CA file name -#define AWS_IOT_CERTIFICATE_FILENAME "cert.pem" ///< device signed certificate file name -#define AWS_IOT_PRIVATE_KEY_FILENAME "privkey.pem" ///< Device private key filename -// ================================================= - -// MQTT PubSub -#define AWS_IOT_MQTT_TX_BUF_LEN 512 ///< Any time a message is sent out through the MQTT layer. The message is copied into this buffer anytime a publish is done. This will also be used in the case of Thing Shadow -#define AWS_IOT_MQTT_RX_BUF_LEN 512 ///< Any message that comes into the device should be less than this buffer size. If a received message is bigger than this buffer size the message will be dropped. -#define AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS 5 ///< Maximum number of topic filters the MQTT client can handle at any given time. This should be increased appropriately when using Thing Shadow - -// Thing Shadow specific configs -#define SHADOW_MAX_SIZE_OF_RX_BUFFER (AWS_IOT_MQTT_RX_BUF_LEN+1) ///< Maximum size of the SHADOW buffer to store the received Shadow message, including terminating NULL byte. -#define MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES 80 ///< Maximum size of the Unique Client Id. For More info on the Client Id refer \ref response "Acknowledgments" -#define MAX_SIZE_CLIENT_ID_WITH_SEQUENCE MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES + 10 ///< This is size of the extra sequence number that will be appended to the Unique client Id -#define MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE MAX_SIZE_CLIENT_ID_WITH_SEQUENCE + 20 ///< This is size of the the total clientToken key and value pair in the JSON -#define MAX_ACKS_TO_COMEIN_AT_ANY_GIVEN_TIME 10 ///< At Any given time we will wait for this many responses. This will correlate to the rate at which the shadow actions are requested -#define MAX_THINGNAME_HANDLED_AT_ANY_GIVEN_TIME 10 ///< We could perform shadow action on any thing Name and this is maximum Thing Names we can act on at any given time -#define MAX_JSON_TOKEN_EXPECTED 120 ///< These are the max tokens that is expected to be in the Shadow JSON document. Include the metadata that gets published -#define MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME 60 ///< All shadow actions have to be published or subscribed to a topic which is of the format $aws/things/{thingName}/shadow/update/accepted. This refers to the size of the topic without the Thing Name -#define MAX_SIZE_OF_THING_NAME 20 ///< The Thing Name should not be bigger than this value. Modify this if the Thing Name needs to be bigger -#define MAX_SHADOW_TOPIC_LENGTH_BYTES MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME + MAX_SIZE_OF_THING_NAME ///< This size includes the length of topic with Thing Name - -// Auto Reconnect specific config -#define AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL 1000 ///< Minimum time before the First reconnect attempt is made as part of the exponential back-off algorithm -#define AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL 128000 ///< Maximum time interval after which exponential back-off will stop attempting to reconnect. - -#define DISABLE_METRICS false ///< Disable the collection of metrics by setting this to true - -// TLS configs -#define IOT_SSL_READ_TIMEOUT_MS 3 ///< Timeout associated with underlying socket of TLS connection (set by mbedtls_ssl_conf_read_timeout) -#define IOT_SSL_READ_RETRY_TIMEOUT_MS 10 ///< Minimum elapsed time before returning from iot_tls_read when pending data has not yet been received -#define IOT_SSL_WRITE_RETRY_TIMEOUT_MS 10 ///< Minimum elapsed time before returning from iot_tls_write when pending data has not yet been written - -#endif /* SRC_SHADOW_IOT_SHADOW_CONFIG_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample_console_echo/shadow_console_echo.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample_console_echo/shadow_console_echo.c deleted file mode 100644 index 181c8d77a..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/shadow_sample_console_echo/shadow_console_echo.c +++ /dev/null @@ -1,271 +0,0 @@ -/* - * 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 - */ - -static char certDirectory[PATH_MAX + 1] = "../../../certs"; -#define HOST_ADDRESS_SIZE 255 -static char HostAddress[HOST_ADDRESS_SIZE] = AWS_IOT_MQTT_HOST; -static uint32_t port = AWS_IOT_MQTT_PORT; -static 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 - */ -static char stringToEchoDelta[SHADOW_MAX_SIZE_OF_RX_BUFFER]; - - -/** - * @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 - */ -static 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; -} - -// Helper functions -static void parseInputArgsForConnectParams(int argc, char** argv) { - int opt; - - while (-1 != (opt = getopt(argc, argv, "h:p:c:"))) { - switch (opt) { - case 'h': - strncpy(HostAddress, optarg, HOST_ADDRESS_SIZE); - IOT_DEBUG("Host %s", optarg); - break; - case 'p': - port = atoi(optarg); - IOT_DEBUG("arg %s", optarg); - break; - case 'c': - strncpy(certDirectory, optarg, PATH_MAX + 1); - 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; - } - } - -} - -// Shadow Callback for receiving the delta -static 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; - } -} - -static 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 !!"); - } -} - -int main(int argc, char** argv) { - IoT_Error_t rc = SUCCESS; - - 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.dataLength = SHADOW_MAX_SIZE_OF_RX_BUFFER; - 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; -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_library_sample/Makefile b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_library_sample/Makefile deleted file mode 100644 index 232260464..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_library_sample/Makefile +++ /dev/null @@ -1,76 +0,0 @@ -#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 -CRYPTO_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 $(CRYPTO_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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_library_sample/aws_iot_config.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_library_sample/aws_iot_config.h deleted file mode 100644 index 81f9e39e8..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_library_sample/aws_iot_config.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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 443 ///< default port for MQTT/S -#define AWS_IOT_MQTT_CLIENT_ID "c-sdk-client-id" ///< MQTT client ID should be unique for every device -#define AWS_IOT_MY_THING_NAME "AWS-IoT-C-SDK" ///< Thing Name of the Shadow this device is associated with -#define AWS_IOT_ROOT_CA_FILENAME "rootCA.crt" ///< Root CA file name -#define AWS_IOT_CERTIFICATE_FILENAME "cert.pem" ///< device signed certificate file name -#define AWS_IOT_PRIVATE_KEY_FILENAME "privkey.pem" ///< Device private key filename -// ================================================= - -// MQTT PubSub -#define AWS_IOT_MQTT_TX_BUF_LEN 512 ///< Any time a message is sent out through the MQTT layer. The message is copied into this buffer anytime a publish is done. This will also be used in the case of Thing Shadow -#define AWS_IOT_MQTT_RX_BUF_LEN 512 ///< Any message that comes into the device should be less than this buffer size. If a received message is bigger than this buffer size the message will be dropped. -#define AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS 5 ///< Maximum number of topic filters the MQTT client can handle at any given time. This should be increased appropriately when using Thing Shadow - -// Thing Shadow specific configs -#define SHADOW_MAX_SIZE_OF_RX_BUFFER (AWS_IOT_MQTT_RX_BUF_LEN+1) ///< Maximum size of the SHADOW buffer to store the received Shadow message, including terminating NULL byte. -#define MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES 80 ///< Maximum size of the Unique Client Id. For More info on the Client Id refer \ref response "Acknowledgments" -#define MAX_SIZE_CLIENT_ID_WITH_SEQUENCE MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES + 10 ///< This is size of the extra sequence number that will be appended to the Unique client Id -#define MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE MAX_SIZE_CLIENT_ID_WITH_SEQUENCE + 20 ///< This is size of the the total clientToken key and value pair in the JSON -#define MAX_ACKS_TO_COMEIN_AT_ANY_GIVEN_TIME 10 ///< At Any given time we will wait for this many responses. This will correlate to the rate at which the shadow actions are requested -#define MAX_THINGNAME_HANDLED_AT_ANY_GIVEN_TIME 10 ///< We could perform shadow action on any thing Name and this is maximum Thing Names we can act on at any given time -#define MAX_JSON_TOKEN_EXPECTED 120 ///< These are the max tokens that is expected to be in the Shadow JSON document. Include the metadata that gets published -#define MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME 60 ///< All shadow actions have to be published or subscribed to a topic which is of the format $aws/things/{thingName}/shadow/update/accepted. This refers to the size of the topic without the Thing Name -#define MAX_SIZE_OF_THING_NAME 20 ///< The Thing Name should not be bigger than this value. Modify this if the Thing Name needs to be bigger -#define MAX_SHADOW_TOPIC_LENGTH_BYTES MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME + MAX_SIZE_OF_THING_NAME ///< This size includes the length of topic with Thing Name - -// Auto Reconnect specific config -#define AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL 1000 ///< Minimum time before the First reconnect attempt is made as part of the exponential back-off algorithm -#define AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL 128000 ///< Maximum time interval after which exponential back-off will stop attempting to reconnect. - -#define DISABLE_METRICS false ///< Disable the collection of metrics by setting this to true - -// TLS configs -#define IOT_SSL_READ_TIMEOUT_MS 3 ///< Timeout associated with underlying socket of TLS connection (set by mbedtls_ssl_conf_read_timeout) -#define IOT_SSL_READ_RETRY_TIMEOUT_MS 10 ///< Minimum elapsed time before returning from iot_tls_read when pending data has not yet been received -#define IOT_SSL_WRITE_RETRY_TIMEOUT_MS 10 ///< Minimum elapsed time before returning from iot_tls_write when pending data has not yet been written - -#endif /* SRC_SHADOW_IOT_SHADOW_CONFIG_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_library_sample/subscribe_publish_library_sample.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_library_sample/subscribe_publish_library_sample.c deleted file mode 100644 index 0c3e775e9..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_library_sample/subscribe_publish_library_sample.c +++ /dev/null @@ -1,264 +0,0 @@ -/* - * 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" - -#define HOST_ADDRESS_SIZE 255 - -/** - * @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[HOST_ADDRESS_SIZE] = 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 - */ -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, (char *) 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': - strncpy(HostAddress, optarg, HOST_ADDRESS_SIZE); - IOT_DEBUG("Host %s", optarg); - break; - case 'p': - port = atoi(optarg); - IOT_DEBUG("arg %s", optarg); - break; - case 'c': - strncpy(certDirectory, optarg, PATH_MAX + 1); - IOT_DEBUG("cert root directory %s", optarg); - break; - case 'x': - publishCount = atoi(optarg); - IOT_DEBUG("publish %s times\n", optarg); - break; - case '?': - if(optopt == 'c') { - IOT_ERROR("Option -%c requires an argument.", optopt); - } else if(isprint(optopt)) { - IOT_WARN("Unknown option `-%c'.", optopt); - } else { - IOT_WARN("Unknown option character `\\x%x'.", optopt); - } - break; - default: - IOT_ERROR("Error in command line argument parsing"); - break; - } - } - -} - -int main(int argc, char **argv) { - bool infinitePublishFlag = true; - - char rootCA[PATH_MAX + 1]; - char clientCRT[PATH_MAX + 1]; - char clientKey[PATH_MAX + 1]; - char CurrentWD[PATH_MAX + 1]; - char cPayload[100]; - - int32_t i = 0; - - IoT_Error_t rc = FAILURE; - - AWS_IoT_Client client; - IoT_Client_Init_Params mqttInitParams = iotClientInitParamsDefault; - IoT_Client_Connect_Params connectParams = iotClientConnectParamsDefault; - - IoT_Publish_Message_Params paramsQOS0; - IoT_Publish_Message_Params paramsQOS1; - - parseInputArgsForConnectParams(argc, argv); - - IOT_INFO("\nAWS IoT SDK Version %d.%d.%d-%s\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG); - - getcwd(CurrentWD, sizeof(CurrentWD)); - snprintf(rootCA, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_ROOT_CA_FILENAME); - snprintf(clientCRT, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_CERTIFICATE_FILENAME); - snprintf(clientKey, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_PRIVATE_KEY_FILENAME); - - IOT_DEBUG("rootCA %s", rootCA); - IOT_DEBUG("clientCRT %s", clientCRT); - IOT_DEBUG("clientKey %s", clientKey); - mqttInitParams.enableAutoReconnect = false; // We enable this later below - mqttInitParams.pHostURL = HostAddress; - mqttInitParams.port = port; - mqttInitParams.pRootCALocation = rootCA; - mqttInitParams.pDeviceCertLocation = clientCRT; - mqttInitParams.pDevicePrivateKeyLocation = clientKey; - mqttInitParams.mqttCommandTimeout_ms = 20000; - mqttInitParams.tlsHandshakeTimeout_ms = 5000; - mqttInitParams.isSSLHostnameVerify = true; - mqttInitParams.disconnectHandler = disconnectCallbackHandler; - mqttInitParams.disconnectHandlerData = NULL; - - rc = aws_iot_mqtt_init(&client, &mqttInitParams); - if(SUCCESS != rc) { - IOT_ERROR("aws_iot_mqtt_init returned error : %d ", rc); - return rc; - } - - connectParams.keepAliveIntervalInSec = 600; - connectParams.isCleanSession = true; - connectParams.MQTTVersion = MQTT_3_1_1; - connectParams.pClientID = AWS_IOT_MQTT_CLIENT_ID; - connectParams.clientIDLen = (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID); - connectParams.isWillMsgPresent = false; - - IOT_INFO("Connecting..."); - rc = aws_iot_mqtt_connect(&client, &connectParams); - if(SUCCESS != rc) { - IOT_ERROR("Error(%d) connecting to %s:%d", rc, mqttInitParams.pHostURL, mqttInitParams.port); - return rc; - } - /* - * Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h - * #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL - * #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL - */ - rc = aws_iot_mqtt_autoreconnect_set_status(&client, true); - if(SUCCESS != rc) { - IOT_ERROR("Unable to set Auto Reconnect to true - %d", rc); - return rc; - } - - IOT_INFO("Subscribing..."); - rc = aws_iot_mqtt_subscribe(&client, "sdkTest/sub", 11, QOS0, iot_subscribe_callback_handler, NULL); - if(SUCCESS != rc) { - IOT_ERROR("Error subscribing : %d ", rc); - return rc; - } - - sprintf(cPayload, "%s : %d ", "hello from SDK", i); - - paramsQOS0.qos = QOS0; - paramsQOS0.payload = (void *) cPayload; - paramsQOS0.isRetained = 0; - - paramsQOS1.qos = QOS1; - paramsQOS1.payload = (void *) cPayload; - paramsQOS1.isRetained = 0; - - if(publishCount != 0) { - infinitePublishFlag = false; - } - - while((NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc) - && (publishCount > 0 || infinitePublishFlag)) { - - //Max time the yield function will wait for read messages - rc = aws_iot_mqtt_yield(&client, 100); - if(NETWORK_ATTEMPTING_RECONNECT == rc) { - // If the client is attempting to reconnect we will skip the rest of the loop. - continue; - } - - IOT_INFO("-->sleep"); - sleep(1); - sprintf(cPayload, "%s : %d ", "hello from SDK QOS0", i++); - paramsQOS0.payloadLen = strlen(cPayload); - rc = aws_iot_mqtt_publish(&client, "sdkTest/sub", 11, ¶msQOS0); - if(publishCount > 0) { - publishCount--; - } - - sprintf(cPayload, "%s : %d ", "hello from SDK QOS1", i++); - paramsQOS1.payloadLen = strlen(cPayload); - rc = aws_iot_mqtt_publish(&client, "sdkTest/sub", 11, ¶msQOS1); - if (rc == MQTT_REQUEST_TIMEOUT_ERROR) { - IOT_WARN("QOS1 publish ack not received.\n"); - rc = SUCCESS; - } - if(publishCount > 0) { - publishCount--; - } - } - - if(SUCCESS != rc) { - IOT_ERROR("An error occurred in the loop.\n"); - } else { - IOT_INFO("Publish done\n"); - } - - return rc; -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_sample/Makefile b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_sample/Makefile deleted file mode 100644 index 1a665a3ae..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_sample/Makefile +++ /dev/null @@ -1,70 +0,0 @@ -#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 -CRYPTO_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 $(CRYPTO_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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_sample/aws_iot_config.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_sample/aws_iot_config.h deleted file mode 100644 index 81f9e39e8..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_sample/aws_iot_config.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * 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 443 ///< default port for MQTT/S -#define AWS_IOT_MQTT_CLIENT_ID "c-sdk-client-id" ///< MQTT client ID should be unique for every device -#define AWS_IOT_MY_THING_NAME "AWS-IoT-C-SDK" ///< Thing Name of the Shadow this device is associated with -#define AWS_IOT_ROOT_CA_FILENAME "rootCA.crt" ///< Root CA file name -#define AWS_IOT_CERTIFICATE_FILENAME "cert.pem" ///< device signed certificate file name -#define AWS_IOT_PRIVATE_KEY_FILENAME "privkey.pem" ///< Device private key filename -// ================================================= - -// MQTT PubSub -#define AWS_IOT_MQTT_TX_BUF_LEN 512 ///< Any time a message is sent out through the MQTT layer. The message is copied into this buffer anytime a publish is done. This will also be used in the case of Thing Shadow -#define AWS_IOT_MQTT_RX_BUF_LEN 512 ///< Any message that comes into the device should be less than this buffer size. If a received message is bigger than this buffer size the message will be dropped. -#define AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS 5 ///< Maximum number of topic filters the MQTT client can handle at any given time. This should be increased appropriately when using Thing Shadow - -// Thing Shadow specific configs -#define SHADOW_MAX_SIZE_OF_RX_BUFFER (AWS_IOT_MQTT_RX_BUF_LEN+1) ///< Maximum size of the SHADOW buffer to store the received Shadow message, including terminating NULL byte. -#define MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES 80 ///< Maximum size of the Unique Client Id. For More info on the Client Id refer \ref response "Acknowledgments" -#define MAX_SIZE_CLIENT_ID_WITH_SEQUENCE MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES + 10 ///< This is size of the extra sequence number that will be appended to the Unique client Id -#define MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE MAX_SIZE_CLIENT_ID_WITH_SEQUENCE + 20 ///< This is size of the the total clientToken key and value pair in the JSON -#define MAX_ACKS_TO_COMEIN_AT_ANY_GIVEN_TIME 10 ///< At Any given time we will wait for this many responses. This will correlate to the rate at which the shadow actions are requested -#define MAX_THINGNAME_HANDLED_AT_ANY_GIVEN_TIME 10 ///< We could perform shadow action on any thing Name and this is maximum Thing Names we can act on at any given time -#define MAX_JSON_TOKEN_EXPECTED 120 ///< These are the max tokens that is expected to be in the Shadow JSON document. Include the metadata that gets published -#define MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME 60 ///< All shadow actions have to be published or subscribed to a topic which is of the format $aws/things/{thingName}/shadow/update/accepted. This refers to the size of the topic without the Thing Name -#define MAX_SIZE_OF_THING_NAME 20 ///< The Thing Name should not be bigger than this value. Modify this if the Thing Name needs to be bigger -#define MAX_SHADOW_TOPIC_LENGTH_BYTES MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME + MAX_SIZE_OF_THING_NAME ///< This size includes the length of topic with Thing Name - -// Auto Reconnect specific config -#define AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL 1000 ///< Minimum time before the First reconnect attempt is made as part of the exponential back-off algorithm -#define AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL 128000 ///< Maximum time interval after which exponential back-off will stop attempting to reconnect. - -#define DISABLE_METRICS false ///< Disable the collection of metrics by setting this to true - -// TLS configs -#define IOT_SSL_READ_TIMEOUT_MS 3 ///< Timeout associated with underlying socket of TLS connection (set by mbedtls_ssl_conf_read_timeout) -#define IOT_SSL_READ_RETRY_TIMEOUT_MS 10 ///< Minimum elapsed time before returning from iot_tls_read when pending data has not yet been received -#define IOT_SSL_WRITE_RETRY_TIMEOUT_MS 10 ///< Minimum elapsed time before returning from iot_tls_write when pending data has not yet been written - -#endif /* SRC_SHADOW_IOT_SHADOW_CONFIG_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_sample/subscribe_publish_sample.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_sample/subscribe_publish_sample.c deleted file mode 100644 index ce7a28f9c..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/samples/linux/subscribe_publish_sample/subscribe_publish_sample.c +++ /dev/null @@ -1,270 +0,0 @@ -/* - * 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" - -#define HOST_ADDRESS_SIZE 255 -/** - * @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[HOST_ADDRESS_SIZE] = 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, (char *) 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': - strncpy(HostAddress, optarg, HOST_ADDRESS_SIZE); - IOT_DEBUG("Host %s", optarg); - break; - case 'p': - port = atoi(optarg); - IOT_DEBUG("arg %s", optarg); - break; - case 'c': - strncpy(certDirectory, optarg, PATH_MAX + 1); - IOT_DEBUG("cert root directory %s", optarg); - break; - case 'x': - publishCount = atoi(optarg); - IOT_DEBUG("publish %s times\n", optarg); - break; - case '?': - if(optopt == 'c') { - IOT_ERROR("Option -%c requires an argument.", optopt); - } else if(isprint(optopt)) { - IOT_WARN("Unknown option `-%c'.", optopt); - } else { - IOT_WARN("Unknown option character `\\x%x'.", optopt); - } - break; - default: - IOT_ERROR("Error in command line argument parsing"); - break; - } - } - -} - -int main(int argc, char **argv) { - bool infinitePublishFlag = true; - - char rootCA[PATH_MAX + 1]; - char clientCRT[PATH_MAX + 1]; - char clientKey[PATH_MAX + 1]; - char CurrentWD[PATH_MAX + 1]; - char cPayload[100]; - - int32_t i = 0; - - IoT_Error_t rc = FAILURE; - - AWS_IoT_Client client; - IoT_Client_Init_Params mqttInitParams = iotClientInitParamsDefault; - IoT_Client_Connect_Params connectParams = iotClientConnectParamsDefault; - - IoT_Publish_Message_Params paramsQOS0; - IoT_Publish_Message_Params paramsQOS1; - - parseInputArgsForConnectParams(argc, argv); - - IOT_INFO("\nAWS IoT SDK Version %d.%d.%d-%s\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG); - - getcwd(CurrentWD, sizeof(CurrentWD)); - snprintf(rootCA, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_ROOT_CA_FILENAME); - snprintf(clientCRT, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_CERTIFICATE_FILENAME); - snprintf(clientKey, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_PRIVATE_KEY_FILENAME); - - IOT_DEBUG("rootCA %s", rootCA); - IOT_DEBUG("clientCRT %s", clientCRT); - IOT_DEBUG("clientKey %s", clientKey); - mqttInitParams.enableAutoReconnect = false; // We enable this later below - mqttInitParams.pHostURL = HostAddress; - mqttInitParams.port = port; - mqttInitParams.pRootCALocation = rootCA; - mqttInitParams.pDeviceCertLocation = clientCRT; - mqttInitParams.pDevicePrivateKeyLocation = clientKey; - mqttInitParams.mqttCommandTimeout_ms = 20000; - mqttInitParams.tlsHandshakeTimeout_ms = 5000; - mqttInitParams.isSSLHostnameVerify = true; - mqttInitParams.disconnectHandler = disconnectCallbackHandler; - mqttInitParams.disconnectHandlerData = NULL; - - rc = aws_iot_mqtt_init(&client, &mqttInitParams); - if(SUCCESS != rc) { - IOT_ERROR("aws_iot_mqtt_init returned error : %d ", rc); - return rc; - } - - connectParams.keepAliveIntervalInSec = 600; - connectParams.isCleanSession = true; - connectParams.MQTTVersion = MQTT_3_1_1; - connectParams.pClientID = AWS_IOT_MQTT_CLIENT_ID; - connectParams.clientIDLen = (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID); - connectParams.isWillMsgPresent = false; - - IOT_INFO("Connecting..."); - rc = aws_iot_mqtt_connect(&client, &connectParams); - if(SUCCESS != rc) { - IOT_ERROR("Error(%d) connecting to %s:%d", rc, mqttInitParams.pHostURL, mqttInitParams.port); - return rc; - } - /* - * Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h - * #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL - * #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL - */ - rc = aws_iot_mqtt_autoreconnect_set_status(&client, true); - if(SUCCESS != rc) { - IOT_ERROR("Unable to set Auto Reconnect to true - %d", rc); - return rc; - } - - IOT_INFO("Subscribing..."); - rc = aws_iot_mqtt_subscribe(&client, "sdkTest/sub", 11, QOS0, iot_subscribe_callback_handler, NULL); - if(SUCCESS != rc) { - IOT_ERROR("Error subscribing : %d ", rc); - return rc; - } - - sprintf(cPayload, "%s : %d ", "hello from SDK", i); - - paramsQOS0.qos = QOS0; - paramsQOS0.payload = (void *) cPayload; - paramsQOS0.isRetained = 0; - - paramsQOS1.qos = QOS1; - paramsQOS1.payload = (void *) cPayload; - paramsQOS1.isRetained = 0; - - if(publishCount != 0) { - infinitePublishFlag = false; - } - - while((NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc) - && (publishCount > 0 || infinitePublishFlag)) { - - //Max time the yield function will wait for read messages - rc = aws_iot_mqtt_yield(&client, 100); - if(NETWORK_ATTEMPTING_RECONNECT == rc) { - // If the client is attempting to reconnect we will skip the rest of the loop. - continue; - } - - IOT_INFO("-->sleep"); - sleep(1); - sprintf(cPayload, "%s : %d ", "hello from SDK QOS0", i++); - paramsQOS0.payloadLen = strlen(cPayload); - rc = aws_iot_mqtt_publish(&client, "sdkTest/sub", 11, ¶msQOS0); - if(publishCount > 0) { - publishCount--; - } - - if(publishCount == 0 && !infinitePublishFlag) { - break; - } - - sprintf(cPayload, "%s : %d ", "hello from SDK QOS1", i++); - paramsQOS1.payloadLen = strlen(cPayload); - rc = aws_iot_mqtt_publish(&client, "sdkTest/sub", 11, ¶msQOS1); - if (rc == MQTT_REQUEST_TIMEOUT_ERROR) { - IOT_WARN("QOS1 publish ack not received.\n"); - rc = SUCCESS; - } - if(publishCount > 0) { - publishCount--; - } - } - - // Wait for all the messages to be received - aws_iot_mqtt_yield(&client, 100); - - if(SUCCESS != rc) { - IOT_ERROR("An error occurred in the loop.\n"); - } else { - IOT_INFO("Publish done\n"); - } - - return rc; -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_jobs_interface.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_jobs_interface.c deleted file mode 100644 index 0452d6786..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_jobs_interface.c +++ /dev/null @@ -1,215 +0,0 @@ -/* -* Copyright 2015-2018 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 "aws_iot_jobs_interface.h" -#include "aws_iot_log.h" -#include "aws_iot_jobs_json.h" -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define CHECK_GENERATE_STRING_RESULT(result, bufferSize) \ - if (result < 0) { \ - return FAILURE; \ - } else if ((unsigned) result >= bufferSize) { \ - return LIMIT_EXCEEDED_ERROR; \ - } - - -IoT_Error_t aws_iot_jobs_subscribe_to_job_messages( - AWS_IoT_Client *pClient, QoS qos, - const char *thingName, - const char *jobId, - AwsIotJobExecutionTopicType topicType, - AwsIotJobExecutionTopicReplyType replyType, - pApplicationHandler_t pApplicationHandler, - void *pApplicationHandlerData, - char *topicBuffer, - uint16_t topicBufferSize) -{ - int requiredSize = aws_iot_jobs_get_api_topic(topicBuffer, topicBufferSize, topicType, replyType, thingName, jobId); - CHECK_GENERATE_STRING_RESULT(requiredSize, topicBufferSize); - - return aws_iot_mqtt_subscribe(pClient, topicBuffer, (uint16_t)strlen(topicBuffer), qos, pApplicationHandler, pApplicationHandlerData); -} - -IoT_Error_t aws_iot_jobs_subscribe_to_all_job_messages( - AWS_IoT_Client *pClient, QoS qos, - const char *thingName, - pApplicationHandler_t pApplicationHandler, - void *pApplicationHandlerData, - char *topicBuffer, - uint16_t topicBufferSize) -{ - return aws_iot_jobs_subscribe_to_job_messages(pClient, qos, thingName, NULL, JOB_WILDCARD_TOPIC, JOB_WILDCARD_REPLY_TYPE, - pApplicationHandler, pApplicationHandlerData, topicBuffer, topicBufferSize); -} - -IoT_Error_t aws_iot_jobs_unsubscribe_from_job_messages( - AWS_IoT_Client *pClient, - char *topicBuffer) -{ - return aws_iot_mqtt_unsubscribe(pClient, topicBuffer, (uint16_t)strlen(topicBuffer)); -} - -IoT_Error_t aws_iot_jobs_send_query( - AWS_IoT_Client *pClient, QoS qos, - const char *thingName, - const char *jobId, - const char *clientToken, - char *topicBuffer, - uint16_t topicBufferSize, - char *messageBuffer, - size_t messageBufferSize, - AwsIotJobExecutionTopicType topicType) -{ - if (thingName == NULL || topicBuffer == NULL || (clientToken != NULL && messageBuffer == NULL)) { - return NULL_VALUE_ERROR; - } - - int neededSize = aws_iot_jobs_get_api_topic(topicBuffer, topicBufferSize, topicType, JOB_REQUEST_TYPE, thingName, jobId); - CHECK_GENERATE_STRING_RESULT(neededSize, topicBufferSize); - uint16_t topicSize = (uint16_t) neededSize; - - char emptyBuffer[1]; - size_t messageLength; - if (clientToken == NULL) { - messageLength = 0; - messageBuffer = emptyBuffer; - } else { - int serializeResult = aws_iot_jobs_json_serialize_client_token_only_request(messageBuffer, messageBufferSize, clientToken); - CHECK_GENERATE_STRING_RESULT(serializeResult, messageBufferSize); - messageLength = (size_t)serializeResult; - } - - IoT_Publish_Message_Params publishParams; - publishParams.qos = qos; - publishParams.isRetained = 0; - publishParams.isDup = 0; - publishParams.id = 0; - publishParams.payload = messageBuffer; - publishParams.payloadLen = messageLength; - - return aws_iot_mqtt_publish(pClient, topicBuffer, topicSize, &publishParams); -} - -IoT_Error_t aws_iot_jobs_start_next( - AWS_IoT_Client *pClient, QoS qos, - const char *thingName, - const AwsIotStartNextPendingJobExecutionRequest *startNextRequest, - char *topicBuffer, - uint16_t topicBufferSize, - char *messageBuffer, - size_t messageBufferSize) -{ - if (thingName == NULL || topicBuffer == NULL || startNextRequest == NULL) { - return NULL_VALUE_ERROR; - } - - int neededSize = aws_iot_jobs_get_api_topic(topicBuffer, topicBufferSize, JOB_START_NEXT_TOPIC, JOB_REQUEST_TYPE, thingName, NULL); - CHECK_GENERATE_STRING_RESULT(neededSize, topicBufferSize); - uint16_t topicSize = (uint16_t) neededSize; - - int serializeResult = aws_iot_jobs_json_serialize_start_next_job_execution_request(messageBuffer, messageBufferSize, startNextRequest); - CHECK_GENERATE_STRING_RESULT(serializeResult, messageBufferSize); - - IoT_Publish_Message_Params publishParams; - publishParams.qos = qos; - publishParams.isRetained = 0; - publishParams.isDup = 0; - publishParams.id = 0; - publishParams.payload = messageBuffer; - publishParams.payloadLen = (size_t) serializeResult; - - return aws_iot_mqtt_publish(pClient, topicBuffer, topicSize, &publishParams); -} - -IoT_Error_t aws_iot_jobs_describe( - AWS_IoT_Client *pClient, QoS qos, - const char *thingName, - const char *jobId, - const AwsIotDescribeJobExecutionRequest *describeRequest, - char *topicBuffer, - uint16_t topicBufferSize, - char *messageBuffer, - size_t messageBufferSize) -{ - if (thingName == NULL || topicBuffer == NULL || describeRequest == NULL) { - return NULL_VALUE_ERROR; - } - - int neededSize = aws_iot_jobs_get_api_topic(topicBuffer, topicBufferSize, JOB_DESCRIBE_TOPIC, JOB_REQUEST_TYPE, thingName, jobId); - CHECK_GENERATE_STRING_RESULT(neededSize, topicBufferSize); - uint16_t topicSize = (uint16_t) neededSize; - - char emptyBuffer[1]; - size_t messageLength; - if (messageBuffer == NULL) { - messageLength = 0; - messageBuffer = emptyBuffer; - } else { - int serializeResult = aws_iot_jobs_json_serialize_describe_job_execution_request(messageBuffer, messageBufferSize, describeRequest); - CHECK_GENERATE_STRING_RESULT(serializeResult, messageBufferSize); - messageLength = (size_t) serializeResult; - } - - IoT_Publish_Message_Params publishParams; - publishParams.qos = qos; - publishParams.isRetained = 0; - publishParams.isDup = 0; - publishParams.id = 0; - publishParams.payload = messageBuffer; - publishParams.payloadLen = messageLength; - - return aws_iot_mqtt_publish(pClient, topicBuffer, topicSize, &publishParams); -} - -IoT_Error_t aws_iot_jobs_send_update( - AWS_IoT_Client *pClient, QoS qos, - const char *thingName, - const char *jobId, - const AwsIotJobExecutionUpdateRequest *updateRequest, - char *topicBuffer, - uint16_t topicBufferSize, - char *messageBuffer, - size_t messageBufferSize) -{ - if (thingName == NULL || topicBuffer == NULL || jobId == NULL || updateRequest == NULL) { - return NULL_VALUE_ERROR; - } - - int neededSize = aws_iot_jobs_get_api_topic(topicBuffer, topicBufferSize, JOB_UPDATE_TOPIC, JOB_REQUEST_TYPE, thingName, jobId); - CHECK_GENERATE_STRING_RESULT(neededSize, topicBufferSize); - uint16_t topicSize = (uint16_t) neededSize; - - int serializeResult = aws_iot_jobs_json_serialize_update_job_execution_request(messageBuffer, messageBufferSize, updateRequest); - CHECK_GENERATE_STRING_RESULT(serializeResult, messageBufferSize); - - IoT_Publish_Message_Params publishParams; - publishParams.qos = qos; - publishParams.isRetained = 0; - publishParams.isDup = 0; - publishParams.id = 0; - publishParams.payload = messageBuffer; - publishParams.payloadLen = (size_t) serializeResult; - - return aws_iot_mqtt_publish(pClient, topicBuffer, topicSize, &publishParams); -} - -#ifdef __cplusplus -} -#endif diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_jobs_json.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_jobs_json.c deleted file mode 100644 index 2213ddd7b..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_jobs_json.c +++ /dev/null @@ -1,197 +0,0 @@ -/* -* Copyright 2015-2018 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 - -#define __STDC_FORMAT_MACROS -#include -#include -#include -#include -#include -#include - -#include "jsmn.h" -#include "aws_iot_jobs_json.h" - -struct _SerializeState { - int totalSize; - char *nextPtr; - size_t remaingSize; -}; - -static void _printToBuffer(struct _SerializeState *state, const char *fmt, ...) { - if (state->totalSize == -1) return; - - va_list vl; - va_start(vl, fmt); - int len = vsnprintf(state->nextPtr, state->remaingSize, fmt, vl); - if (len < 0) { - state->totalSize = -1; - } else { - state->totalSize += len; - if (state->nextPtr != NULL) { - if (state->remaingSize > (size_t) len) { - state->remaingSize -= (size_t) len; - state->nextPtr += len; - } else { - state->remaingSize = 0; - state->nextPtr = NULL; - } - } - } - va_end(vl); -} - -static void _printKey(struct _SerializeState *state, bool first, const char *key) { - if (first) { - _printToBuffer(state, "{\"%s\":", key); - } else { - _printToBuffer(state, ",\"%s\":", key); - } -} - -static void _printStringValue(struct _SerializeState *state, const char *value) { - if (value == NULL) { - _printToBuffer(state, "null"); - } else { - _printToBuffer(state, "\"%s\"", value); - } -} - -static void _printLongValue(struct _SerializeState *state, int64_t value) { - _printToBuffer(state, "%lld", value); -} - -static void _printBooleanValue(struct _SerializeState *state, bool value) { - if(value) { - _printToBuffer(state, "true"); - } else { - _printToBuffer(state, "false"); - } -} - -int aws_iot_jobs_json_serialize_update_job_execution_request( - char *requestBuffer, size_t bufferSize, - const AwsIotJobExecutionUpdateRequest *request) -{ - const char *statusStr = aws_iot_jobs_map_status_to_string(request->status); - if (statusStr == NULL) return -1; - if (requestBuffer == NULL) bufferSize = 0; - - struct _SerializeState state = { 0, requestBuffer, bufferSize }; - _printKey(&state, true, "status"); - _printStringValue(&state, statusStr); - if (request->statusDetails != NULL) { - _printKey(&state, false, "statusDetails"); - _printToBuffer(&state, "%s", request->statusDetails); - } - if (request->executionNumber != 0) { - _printKey(&state, false, "executionNumber"); - _printLongValue(&state, request->executionNumber); - } - if (request->expectedVersion != 0) { - _printKey(&state, false, "expectedVersion"); - _printLongValue(&state, request->expectedVersion); - } - if (request->includeJobExecutionState) { - _printKey(&state, false, "includeJobExecutionState"); - _printBooleanValue(&state, request->includeJobExecutionState); - } - if (request->includeJobDocument) { - _printKey(&state, false, "includeJobDocument"); - _printBooleanValue(&state, request->includeJobDocument); - } - if (request->clientToken != NULL) { - _printKey(&state, false, "clientToken"); - _printStringValue(&state, request->clientToken); - } - - _printToBuffer(&state, "}"); - - return state.totalSize; -} - -int aws_iot_jobs_json_serialize_client_token_only_request( - char *requestBuffer, size_t bufferSize, - const char *clientToken) -{ - struct _SerializeState state = { 0, requestBuffer, bufferSize }; - _printKey(&state, true, "clientToken"); - _printStringValue(&state, clientToken); - _printToBuffer(&state, "}"); - - return state.totalSize; -} - -int aws_iot_jobs_json_serialize_describe_job_execution_request( - char *requestBuffer, size_t bufferSize, - const AwsIotDescribeJobExecutionRequest *request) -{ - bool first = true; - - if (requestBuffer == NULL) return 0; - - struct _SerializeState state = { 0, requestBuffer, bufferSize }; - if (request->clientToken != NULL) { - _printKey(&state, first, "clientToken"); - _printStringValue(&state, request->clientToken); - first = false; - } - if (request->executionNumber != 0) { - _printKey(&state, first, "executionNumber"); - _printLongValue(&state, request->executionNumber); - first = false; - } - if (request->includeJobDocument) { - _printKey(&state, first, "includeJobDocument"); - _printBooleanValue(&state, request->includeJobDocument); - } - - _printToBuffer(&state, "}"); - - return state.totalSize; -} - -int aws_iot_jobs_json_serialize_start_next_job_execution_request( - char *requestBuffer, size_t bufferSize, - const AwsIotStartNextPendingJobExecutionRequest *request) -{ - if (requestBuffer == NULL) bufferSize = 0; - struct _SerializeState state = { 0, requestBuffer, bufferSize }; - if (request->statusDetails != NULL) { - _printKey(&state, true, "statusDetails"); - _printToBuffer(&state, "%s", request->statusDetails); - } - if (request->clientToken != NULL) { - if(request->statusDetails != NULL) { - _printKey(&state, false, "clientToken"); - } else { - _printKey(&state, true, "clientToken"); - } - _printStringValue(&state, request->clientToken); - } - if (request->clientToken == NULL && request->statusDetails == NULL) { - _printToBuffer(&state, "{"); - } - _printToBuffer(&state, "}"); - return state.totalSize; -} - -#ifdef __cplusplus -} -#endif diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_jobs_topics.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_jobs_topics.c deleted file mode 100644 index 39c5cba28..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_jobs_topics.c +++ /dev/null @@ -1,129 +0,0 @@ -/* -* Copyright 2015-2018 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 "aws_iot_jobs_topics.h" -#include -#include -#include - -#define BASE_THINGS_TOPIC "$aws/things/" - -#define NOTIFY_OPERATION "notify" -#define NOTIFY_NEXT_OPERATION "notify-next" -#define GET_OPERATION "get" -#define START_NEXT_OPERATION "start-next" -#define WILDCARD_OPERATION "+" -#define UPDATE_OPERATION "update" -#define ACCEPTED_REPLY "accepted" -#define REJECTED_REPLY "rejected" -#define WILDCARD_REPLY "+" - -static const char *_get_operation_for_base_topic(AwsIotJobExecutionTopicType topicType) { - switch (topicType) { - case JOB_UPDATE_TOPIC: - return UPDATE_OPERATION; - case JOB_NOTIFY_TOPIC: - return NOTIFY_OPERATION; - case JOB_NOTIFY_NEXT_TOPIC: - return NOTIFY_NEXT_OPERATION; - case JOB_GET_PENDING_TOPIC: - case JOB_DESCRIBE_TOPIC: - return GET_OPERATION; - case JOB_START_NEXT_TOPIC: - return START_NEXT_OPERATION; - case JOB_WILDCARD_TOPIC: - return WILDCARD_OPERATION; - case JOB_UNRECOGNIZED_TOPIC: - default: - return NULL; - } -} - -static bool _base_topic_requires_job_id(AwsIotJobExecutionTopicType topicType) { - switch (topicType) { - case JOB_UPDATE_TOPIC: - case JOB_DESCRIBE_TOPIC: - return true; - case JOB_NOTIFY_TOPIC: - case JOB_NOTIFY_NEXT_TOPIC: - case JOB_START_NEXT_TOPIC: - case JOB_GET_PENDING_TOPIC: - case JOB_WILDCARD_TOPIC: - case JOB_UNRECOGNIZED_TOPIC: - default: - return false; - } -} - -static const char *_get_suffix_for_topic_type(AwsIotJobExecutionTopicReplyType replyType) { - switch (replyType) { - case JOB_REQUEST_TYPE: - return ""; - break; - case JOB_ACCEPTED_REPLY_TYPE: - return "/" ACCEPTED_REPLY; - break; - case JOB_REJECTED_REPLY_TYPE: - return "/" REJECTED_REPLY; - break; - case JOB_WILDCARD_REPLY_TYPE: - return "/" WILDCARD_REPLY; - break; - case JOB_UNRECOGNIZED_TOPIC_TYPE: - default: - return NULL; - } -} - -int aws_iot_jobs_get_api_topic(char *buffer, size_t bufferSize, - AwsIotJobExecutionTopicType topicType, AwsIotJobExecutionTopicReplyType replyType, - const char* thingName, const char* jobId) -{ - if (thingName == NULL) { - return -1; - } - - if ((topicType == JOB_NOTIFY_TOPIC || topicType == JOB_NOTIFY_NEXT_TOPIC) && replyType != JOB_REQUEST_TYPE) { - return -1; - } - - bool requireJobId = _base_topic_requires_job_id(topicType); - if (jobId == NULL && requireJobId) { - return -1; - } - - const char *operation = _get_operation_for_base_topic(topicType); - if (operation == NULL) { - return -1; - } - - const char *suffix = _get_suffix_for_topic_type(replyType); - - if (requireJobId || (topicType == JOB_WILDCARD_TOPIC && jobId != NULL)) { - return snprintf(buffer, bufferSize, BASE_THINGS_TOPIC "%s/jobs/%s/%s%s", thingName, jobId, operation, suffix); - } else if (topicType == JOB_WILDCARD_TOPIC) { - return snprintf(buffer, bufferSize, BASE_THINGS_TOPIC "%s/jobs/#", thingName); - } else { - return snprintf(buffer, bufferSize, BASE_THINGS_TOPIC "%s/jobs/%s%s", thingName, operation, suffix); - } -} - -#ifdef __cplusplus -} -#endif diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_jobs_types.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_jobs_types.c deleted file mode 100644 index 9dcbf5081..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_jobs_types.c +++ /dev/null @@ -1,73 +0,0 @@ -/* -* Copyright 2015-2018 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 "aws_iot_jobs_types.h" - -const char *JOB_EXECUTION_QUEUED_STR = "QUEUED"; -const char *JOB_EXECUTION_IN_PROGRESS_STR = "IN_PROGRESS"; -const char *JOB_EXECUTION_FAILED_STR = "FAILED"; -const char *JOB_EXECUTION_SUCCEEDED_STR = "SUCCEEDED"; -const char *JOB_EXECUTION_CANCELED_STR = "CANCELED"; -const char *JOB_EXECUTION_REJECTED_STR = "REJECTED"; - -JobExecutionStatus aws_iot_jobs_map_string_to_job_status(const char *str) { - if (str == NULL || str[0] == '\0') { - return JOB_EXECUTION_STATUS_NOT_SET; - } else if (strcmp(str, JOB_EXECUTION_QUEUED_STR) == 0) { - return JOB_EXECUTION_QUEUED; - } else if(strcmp(str, JOB_EXECUTION_IN_PROGRESS_STR) == 0) { - return JOB_EXECUTION_IN_PROGRESS; - } else if(strcmp(str, JOB_EXECUTION_FAILED_STR) == 0) { - return JOB_EXECUTION_FAILED; - } else if(strcmp(str, JOB_EXECUTION_SUCCEEDED_STR) == 0) { - return JOB_EXECUTION_SUCCEEDED; - } else if(strcmp(str, JOB_EXECUTION_CANCELED_STR) == 0) { - return JOB_EXECUTION_CANCELED; - } else if(strcmp(str, JOB_EXECUTION_REJECTED_STR) == 0) { - return JOB_EXECUTION_REJECTED; - } else { - return JOB_EXECUTION_UNKNOWN_STATUS; - } -} - -const char *aws_iot_jobs_map_status_to_string(JobExecutionStatus status) { - switch(status) { - case JOB_EXECUTION_QUEUED: - return JOB_EXECUTION_QUEUED_STR; - case JOB_EXECUTION_IN_PROGRESS: - return JOB_EXECUTION_IN_PROGRESS_STR; - case JOB_EXECUTION_FAILED: - return JOB_EXECUTION_FAILED_STR; - case JOB_EXECUTION_SUCCEEDED: - return JOB_EXECUTION_SUCCEEDED_STR; - case JOB_EXECUTION_CANCELED: - return JOB_EXECUTION_CANCELED_STR; - case JOB_EXECUTION_REJECTED: - return JOB_EXECUTION_REJECTED_STR; - case JOB_EXECUTION_STATUS_NOT_SET: - case JOB_EXECUTION_UNKNOWN_STATUS: - default: - return NULL; - } -} - -#ifdef __cplusplus -} -#endif diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_json_utils.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_json_utils.c deleted file mode 100644 index f8485695f..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_json_utils.c +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Copyright 2010-2018 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 - -#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, "%u", 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, "%hu", 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, "%hhu", 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, "%i", 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, "%hi", 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, "%hhi", 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(strncmp(jsonString + token->start, "true", 4) == 0) { - *b = true; - } else if(strncmp(jsonString + token->start, "false", 5) == 0) { - *b = false; - } else { - IOT_WARN("Token was not a bool."); - return JSON_PARSE_ERROR; - } - return SUCCESS; -} - -IoT_Error_t parseStringValue(char *buf, size_t bufLen, const char *jsonString, jsmntok_t *token) { - /* This length does not include a null-terminator. */ - size_t stringLength = (size_t)(token->end - token->start); - - if(token->type != JSMN_STRING) { - IOT_WARN("Token was not a string."); - return JSON_PARSE_ERROR; - } - - if (stringLength+1 > bufLen) { - IOT_WARN("Buffer too small to hold string value."); - return SHADOW_JSON_ERROR; - } - - strncpy(buf, jsonString + token->start, stringLength); - buf[stringLength] = '\0'; - - return SUCCESS; -} - -jsmntok_t *findToken(const char *key, const char *jsonString, jsmntok_t *token) { - jsmntok_t *result = token; - int i; - - if(token->type != JSMN_OBJECT) { - IOT_WARN("Token was not an object."); - return NULL; - } - - if(token->size == 0) { - return NULL; - } - - result = token + 1; - - for (i = 0; i < token->size; i++) { - if (0 == jsoneq(jsonString, result, key)) { - return result + 1; - } - - int propertyEnd = (result + 1)->end; - result += 2; - while (result->start < propertyEnd) - result++; - } - - return NULL; -} - -#ifdef __cplusplus -} -#endif diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client.c deleted file mode 100644 index 21400faf5..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client.c +++ /dev/null @@ -1,397 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -// Based on Eclipse Paho. -/******************************************************************************* - * Copyright (c) 2014 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Allan Stockdill-Mander/Ian Craggs - initial API and implementation and/or initial documentation - *******************************************************************************/ - -/** - * @file aws_iot_mqtt_client.c - * @brief MQTT client API definitions - */ - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -#include "aws_iot_log.h" -#include "aws_iot_mqtt_client_interface.h" -#include "aws_iot_mqtt_client_common_internal.h" -#include "aws_iot_version.h" - -#if !DISABLE_METRICS -/** Length of metrics username */ -#define SDK_METRICS_LEN 25 -/** Metrics username for AWS IoT */ -#define SDK_METRICS_TEMPLATE "?SDK=C&Version=%d.%d.%d" -/** Buffer for metrics username */ -static char pUsernameTemp[SDK_METRICS_LEN] = {0}; -#endif - -#ifdef _ENABLE_THREAD_SUPPORT_ -#include "threads_interface.h" -#endif - -const IoT_Client_Init_Params iotClientInitParamsDefault = IoT_Client_Init_Params_initializer; -const IoT_MQTT_Will_Options iotMqttWillOptionsDefault = IoT_MQTT_Will_Options_Initializer; -const IoT_Client_Connect_Params iotClientConnectParamsDefault = IoT_Client_Connect_Params_initializer; - -ClientState aws_iot_mqtt_get_client_state(AWS_IoT_Client *pClient) { - FUNC_ENTRY; - if(NULL == pClient) { - return CLIENT_STATE_INVALID; - } - - FUNC_EXIT_RC(pClient->clientStatus.clientState); -} - -#ifdef _ENABLE_THREAD_SUPPORT_ -/** - * @brief Lock a mutex in the MQTT client - * - * @param pClient MQTT client - * @param pMutex Mutex to lock - * - * @return IoT_Error_t of mutex operation - */ -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); -} - -/** - * @brief Unlock a mutex in the MQTT client - * - * @param pClient MQTT client - * @param pMutex Mutex to unlock - * - * @return IoT_Error_t of mutex operation - */ -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 - -/** - * @brief Change the state in an MQTT client - * - * @param pClient MQTT client - * @param expectedCurrentState What the current state of the client should be - * @param newState What the new state of the client should be - * - * @return IoT_Error_t of state change - */ -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_ - threadRc = aws_iot_mqtt_client_lock_mutex(pClient, &(pClient->clientData.state_change_mutex)); - if(SUCCESS != threadRc) { - return threadRc; - } -#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; -#if !DISABLE_METRICS - if (0 == strlen(pUsernameTemp)) { - snprintf(pUsernameTemp, SDK_METRICS_LEN, SDK_METRICS_TEMPLATE, VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH); - } - pClient->clientData.options.pUsername = (char*)&pUsernameTemp[0]; - pClient->clientData.options.usernameLen = strlen(pUsernameTemp); -#else - pClient->clientData.options.pUsername = pNewConnectParams->pUsername; - pClient->clientData.options.usernameLen = pNewConnectParams->usernameLen; -#endif - pClient->clientData.options.pPassword = pNewConnectParams->pPassword; - pClient->clientData.options.passwordLen = pNewConnectParams->passwordLen; - pClient->clientData.options.will.pTopicName = pNewConnectParams->will.pTopicName; - pClient->clientData.options.will.topicNameLen = pNewConnectParams->will.topicNameLen; - pClient->clientData.options.will.pMessage = pNewConnectParams->will.pMessage; - pClient->clientData.options.will.msgLen = pNewConnectParams->will.msgLen; - pClient->clientData.options.will.qos = pNewConnectParams->will.qos; - pClient->clientData.options.will.isRetained = pNewConnectParams->will.isRetained; - pClient->clientData.options.keepAliveIntervalInSec = pNewConnectParams->keepAliveIntervalInSec; - pClient->clientData.options.isCleanSession = pNewConnectParams->isCleanSession; - - FUNC_EXIT_RC(SUCCESS); -} - -IoT_Error_t aws_iot_mqtt_free(AWS_IoT_Client *pClient) -{ - IoT_Error_t rc = SUCCESS; - - if (NULL == pClient) { - rc = NULL_VALUE_ERROR; - }else - { - #ifdef _ENABLE_THREAD_SUPPORT_ - if (rc == SUCCESS) - { - rc = aws_iot_thread_mutex_destroy(&(pClient->clientData.state_change_mutex)); - } - - if (rc == SUCCESS) - { - rc = aws_iot_thread_mutex_destroy(&(pClient->clientData.tls_read_mutex)); - }else{ - (void)aws_iot_thread_mutex_destroy(&(pClient->clientData.tls_read_mutex)); - } - - if (rc == SUCCESS) - { - rc = aws_iot_thread_mutex_destroy(&(pClient->clientData.tls_write_mutex)); - }else{ - (void)aws_iot_thread_mutex_destroy(&(pClient->clientData.tls_write_mutex)); - } - #endif - } - - FUNC_EXIT_RC(rc); -} - -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) { - (void)aws_iot_thread_mutex_destroy(&(pClient->clientData.state_change_mutex)); - FUNC_EXIT_RC(rc); - } - rc = aws_iot_thread_mutex_init(&(pClient->clientData.tls_write_mutex)); - if(SUCCESS != rc) { - (void)aws_iot_thread_mutex_destroy(&(pClient->clientData.tls_read_mutex)); - (void)aws_iot_thread_mutex_destroy(&(pClient->clientData.state_change_mutex)); - 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) { - #ifdef _ENABLE_THREAD_SUPPORT_ - (void)aws_iot_thread_mutex_destroy(&(pClient->clientData.tls_read_mutex)); - (void)aws_iot_thread_mutex_destroy(&(pClient->clientData.state_change_mutex)); - (void)aws_iot_thread_mutex_destroy(&(pClient->clientData.tls_write_mutex)); - #endif - pClient->clientStatus.clientState = CLIENT_STATE_INVALID; - FUNC_EXIT_RC(rc); - } - - init_timer(&(pClient->pingReqTimer)); - init_timer(&(pClient->pingRespTimer)); - 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_common_internal.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_common_internal.c deleted file mode 100644 index 8aaf4a321..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_common_internal.c +++ /dev/null @@ -1,793 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -// Based on Eclipse Paho. -/******************************************************************************* - * Copyright (c) 2014 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Ian Craggs - initial API and implementation and/or initial documentation - * Sergio R. Caprile - non-blocking packet read functions for stream transport - *******************************************************************************/ - -/** - * @file aws_iot_mqtt_client_common_internal.c - * @brief MQTT client internal API definitions - */ - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include "aws_iot_mqtt_client_common_internal.h" - -/** Max length of packet header */ -#define MAX_NO_OF_REMAINING_LENGTH_BYTES 4 - -/** - * @brief 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); -} - -/** - * @brief Decodes the message length according to the MQTT algorithm - * - * @param buf the buffer containing the message - * @param decodedLen value the decoded length returned - * @param readBytesLen output parameter for the number of bytes read from the socket - * - * @return IoT_Error_t indicating decode status - */ -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); -} - -/** - * @brief Calculates the length of the "remaining length" encoding - * - * @param rem_len "remaining length" to encode - * - * @return length of the remaining length encoding - */ -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; -} - -/** - * @brief 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; -} - -/** - * @brief 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)++; -} - -/** - * @brief 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; -} - -/** - * @brief 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)++; -} - -/** - * @brief Writes a UTF-8 string into an MQTT packet - * - * @param pptr Where the string should be written - * @param string The string to write - * @param stringLen Length to write - */ -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; - } -} - -/** - * @brief 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. - * - * @param pHeader Header to initialize - * @param message_type MQTT packet type - * @param qos Quality of service for packet - * @param dup DUP flag of a publish - * @param retained RETAIN flag of a publish - * - * @return Returns SUCCESS unless an invalid packet type is given. - */ -IoT_Error_t aws_iot_mqtt_internal_init_header(MQTTHeader *pHeader, MessageTypes message_type, - QoS qos, uint8_t dup, uint8_t retained) { - FUNC_ENTRY; - - if(NULL == pHeader) { - FUNC_EXIT_RC(NULL_VALUE_ERROR); - } - - /* Set all bits to zero */ - pHeader->byte = 0; - uint8_t type = 0; - switch(message_type) { - case UNKNOWN: - /* Should never happen */ - return FAILURE; - case CONNECT: - type = 0x01; - break; - case CONNACK: - type = 0x02; - break; - case PUBLISH: - type = 0x03; - break; - case PUBACK: - type = 0x04; - break; - case PUBREC: - type = 0x05; - break; - case PUBREL: - type = 0x06; - break; - case PUBCOMP: - type = 0x07; - break; - case SUBSCRIBE: - type = 0x08; - break; - case SUBACK: - type = 0x09; - break; - case UNSUBSCRIBE: - type = 0x0A; - break; - case UNSUBACK: - type = 0x0B; - break; - case PINGREQ: - type = 0x0C; - break; - case PINGRESP: - type = 0x0D; - break; - case DISCONNECT: - type = 0x0E; - break; - default: - /* Should never happen */ - FUNC_EXIT_RC(FAILURE); - } - - pHeader->byte = type << 4; - pHeader->byte |= dup << 3; - - switch(qos) { - case QOS0: - break; - case QOS1: - pHeader->byte |= 1 << 1; - break; - default: - /* Using QOS0 as default */ - break; - } - - pHeader->byte |= (1 == retained) ? 0x01 : 0x00; - - FUNC_EXIT_RC(SUCCESS); -} - -/** - * @brief Send an MQTT packet on the network - * - * @param pClient MQTT client which holds packet - * @param length Length of packet to send - * @param pTimer Amount of time allowed to send packet - * - * @return IoT_Error_t of send status - */ -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 = FAILURE; - -#ifdef _ENABLE_THREAD_SUPPORT_ - IoT_Error_t threadRc; -#endif - - 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_ - threadRc = aws_iot_mqtt_client_lock_mutex(pClient, &(pClient->clientData.tls_write_mutex)); - if(SUCCESS != threadRc) { - FUNC_EXIT_RC(threadRc); - } -#endif - - sentLen = 0; - sent = 0; - - while(sent < length && !has_timer_expired(pTimer)) { - rc = pClient->networkStack.write(&(pClient->networkStack), - &pClient->clientData.writeBuf[sent], - (length - sent), - pTimer, - &sentLen); - if(SUCCESS != rc) { - /* there was an error writing the data */ - break; - } - sent += sentLen; - } - -#ifdef _ENABLE_THREAD_SUPPORT_ - threadRc = aws_iot_mqtt_client_unlock_mutex(pClient, &(pClient->clientData.tls_write_mutex)); - if((SUCCESS != threadRc) && ( SUCCESS == rc )) { - FUNC_EXIT_RC(threadRc); - } -#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(rc) -} - -static IoT_Error_t _aws_iot_mqtt_internal_readWrapper( AWS_IoT_Client *pClient, size_t offset, size_t size, Timer *pTimer, size_t * read_len ) { - IoT_Error_t rc; - int byteToRead; - size_t byteRead = 0; - - byteToRead = ( offset + size ) - pClient->clientData.readBufIndex; - - if ( byteToRead > 0 ) - { - rc = pClient->networkStack.read( &( pClient->networkStack ), - pClient->clientData.readBuf + pClient->clientData.readBufIndex, - (size_t)byteToRead, - pTimer, - &byteRead ); - pClient->clientData.readBufIndex += byteRead; - - /* refresh byte to read */ - byteToRead = ( offset + size ) - ((int)pClient->clientData.readBufIndex); - *read_len = size - (size_t)byteToRead; - } - else - { - *read_len = size; - rc = SUCCESS; - } - - - - return rc; -} -static IoT_Error_t _aws_iot_mqtt_internal_decode_packet_remaining_len(AWS_IoT_Client *pClient, size_t * offset, - size_t *rem_len, Timer *pTimer) { - size_t multiplier, len; - IoT_Error_t rc; - size_t read_len; - - 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 = _aws_iot_mqtt_internal_readWrapper( pClient, len, 1, pTimer, &read_len ); - - if(SUCCESS != rc) { - FUNC_EXIT_RC(rc); - } - - *rem_len += (( pClient->clientData.readBuf[len] & 127) * multiplier); - multiplier *= 128; - } while(( pClient->clientData.readBuf[len] & 128) != 0); - *offset = len + 1; - 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 rem_len, total_bytes_read, bytes_to_be_read, read_len; - IoT_Error_t rc; - size_t offset = 0; - MQTTHeader header = {0}; - - rem_len = 0; - total_bytes_read = 0; - bytes_to_be_read = 0; - read_len = 0; - - rc = _aws_iot_mqtt_internal_readWrapper( pClient, offset, 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; - } - - /* 2. read the remaining length. This is variable in itself */ - rc = _aws_iot_mqtt_internal_decode_packet_remaining_len(pClient, &offset, &rem_len, pTimer); - if(SUCCESS != rc) { - return rc; - } - - /* if the buffer is too short then the message will be dropped silently */ - if((rem_len + offset) >= 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); - - /* Check buffer was correctly emptied, otherwise, return error message. */ - if ( total_bytes_read == rem_len ) - { - aws_iot_mqtt_internal_flushBuffers( pClient ); - return MQTT_RX_BUFFER_TOO_SHORT_ERROR; - } - else - { - return rc; - } - } - - /* 3. read the rest of the buffer using a callback to supply the rest of the data */ - if(rem_len > 0) { - rc = _aws_iot_mqtt_internal_readWrapper( pClient, offset, rem_len, pTimer, &read_len ); - if(SUCCESS != rc || read_len != rem_len) { - return FAILURE; - } - } - - /* Pack has been received, we can flush the buffers for next call. */ - aws_iot_mqtt_internal_flushBuffers( pClient ); - header.byte = pClient->clientData.readBuf[0]; - *pPacketType = MQTT_HEADER_FIELD_TYPE(header.byte); - - FUNC_EXIT_RC(rc); -} - -// assume topic filter and name is in correct format -// # can only be at end -// + and # can only be next to separator -static bool _aws_iot_mqtt_internal_is_topic_matched(char *pTopicFilter, char *pTopicName, uint16_t topicNameLen) { - - char *curf, *curn, *curn_end; - - if(NULL == pTopicFilter || NULL == pTopicName) { - return false; - } - - curf = pTopicFilter; - curn = pTopicName; - curn_end = curn + topicNameLen; - - while(*curf && (curn < curn_end)) { - if(*curn == '/' && *curf != '/') { - break; - } - if(*curf != '+' && *curf != '#' && *curf != *curn) { - break; - } - if(*curf == '+') { - /* skip until we meet the next separator, or end of string */ - char *nextpos = curn + 1; - while(nextpos < curn_end && *nextpos != '/') - nextpos = ++curn + 1; - } else if(*curf == '#') { - /* skip until end of string */ - curn = curn_end - 1; - } - - curf++; - curn++; - }; - - return (curn == curn_end) && (*curf == '\0'); -} - -static IoT_Error_t _aws_iot_mqtt_internal_deliver_message(AWS_IoT_Client *pClient, char *pTopicName, - uint16_t topicNameLen, - IoT_Publish_Message_Params *pMessageParams) { - uint32_t itr; - IoT_Error_t rc; - ClientState clientState; - - FUNC_ENTRY; - - if(NULL == pTopicName) { - FUNC_EXIT_RC(NULL_VALUE_ERROR); - } - - /* This function can be called from all MQTT APIs - * But while callback return is in progress, Yield should not be called. - * The state for CB_RETURN accomplishes that, as yield cannot be called while in that state */ - clientState = aws_iot_mqtt_get_client_state(pClient); - aws_iot_mqtt_set_client_state(pClient, clientState, CLIENT_STATE_CONNECTED_WAIT_FOR_CB_RETURN); - - /* Find the right message handler - indexed by topic */ - for(itr = 0; itr < AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; ++itr) { - if(NULL != pClient->clientData.messageHandlers[itr].topicName) { - if(((topicNameLen == pClient->clientData.messageHandlers[itr].topicNameLen) - && - (strncmp(pTopicName, (char *) pClient->clientData.messageHandlers[itr].topicName, topicNameLen) == 0)) - || _aws_iot_mqtt_internal_is_topic_matched((char *) pClient->clientData.messageHandlers[itr].topicName, - pTopicName, topicNameLen)) { - if(NULL != pClient->clientData.messageHandlers[itr].pApplicationHandler) { - pClient->clientData.messageHandlers[itr].pApplicationHandler(pClient, pTopicName, topicNameLen, - pMessageParams, - pClient->clientData.messageHandlers[itr].pApplicationHandlerData); - } - } - } - } - rc = aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTED_WAIT_FOR_CB_RETURN, clientState); - - FUNC_EXIT_RC(rc); -} - -static IoT_Error_t _aws_iot_mqtt_internal_handle_publish(AWS_IoT_Client *pClient) { - char *topicName; - uint16_t topicNameLen; - uint32_t len; - IoT_Error_t rc; - IoT_Publish_Message_Params msg; - Timer sendTimer; - - 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); - } - - /* Send acknowledgement of QoS 1 message. */ - if(QOS1 == msg.qos) { - /* Initialize timer for sending PUBACK. */ - init_timer(&sendTimer); - countdown_ms(&sendTimer, pClient->clientData.commandTimeoutMs); - - /* Generate and send a PUBACK. Warn if the PUBACK isn't sent; the server - will send the PUBLISH again in that case. */ - rc = aws_iot_mqtt_internal_serialize_ack(pClient->clientData.writeBuf, - pClient->clientData.writeBufSize, PUBACK, 0, msg.id, &len); - - if(SUCCESS == rc) { - rc = aws_iot_mqtt_internal_send_packet(pClient, len, &sendTimer); - - if(SUCCESS != rc) { - IOT_WARN("Failed to send PUBACK"); - } - } else { - IOT_WARN("Failed to generate PUBACK"); - } - } - - rc = _aws_iot_mqtt_internal_deliver_message(pClient, topicName, topicNameLen, &msg); - if(SUCCESS != rc) { - FUNC_EXIT_RC(rc); - } - - FUNC_EXIT_RC(SUCCESS); -} - -/** - * @brief Read an MQTT packet from the network - * - * @param pClient MQTT client - * @param pTimer Amount of time allowed to read packet - * @param pPacketType Output parameter for packet read from network - * - * @return IoT_Error_t of read status - */ -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); - break; - } - case PUBREC: - case PUBCOMP: - /* QoS2 not supported at this time */ - break; - case PINGRESP: { - /* There is no outstanding ping request anymore. */ - pClient->clientStatus.isPingOutstanding = false; - break; - } - default: { - /* Either unknown packet type or Failure occurred - * Should not happen */ - rc = MQTT_RX_MESSAGE_PACKET_TYPE_INVALID_ERROR; - break; - } - } - - return rc; -} - -/** - * @brief Flush incoming data from the MQTT client - * - * @param pClient Client with data to flush - * - * @return Always returns SUCCESS - */ -IoT_Error_t aws_iot_mqtt_internal_flushBuffers( AWS_IoT_Client *pClient ) { - pClient->clientData.readBufIndex = 0; - return SUCCESS; -} - -/** - * @brief Wait until a packet is read from the network - * - * Only used in single-threaded mode where one command at a time is in process - * - * @param pClient MQTT client - * @param packetType MQTT packet to read - * @param pTimer Amount of time allowed to read packet - * - * @return IoT_Error_t of read status - */ -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(((SUCCESS == rc) || (MQTT_NOTHING_TO_READ == rc)) && (read_packet_type != packetType)); - - /* If rc is SUCCESS, we have received the expected - * MQTT packet. Otherwise rc tells the error. */ - FUNC_EXIT_RC(rc); -} - -/** - * Serializes a 0-length packet into the supplied buffer, ready for writing to a socket - * @param pTxBuf the buffer into which the packet will be serialized - * @param txBufLen the length in bytes of the supplied buffer, to avoid overruns - * @param packetType the message type - * @param pSerializedLength 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_connect.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_connect.c deleted file mode 100644 index fbbfbec41..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_connect.c +++ /dev/null @@ -1,560 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -// Based on Eclipse Paho. -/******************************************************************************* - * Copyright (c) 2014 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Ian Craggs - initial API and implementation and/or initial documentation - *******************************************************************************/ - -/** - * @file aws_iot_mqtt_client_connect.c - * @brief MQTT client connect API definition and related functions - */ - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -#include -#include "aws_iot_mqtt_client_interface.h" -#include "aws_iot_mqtt_client_common_internal.h" - -/** @brief Connect request response codes from server */ -typedef enum { - CONNACK_CONNECTION_ACCEPTED = 0, /**< Connection accepted */ - CONNACK_UNACCEPTABLE_PROTOCOL_VERSION_ERROR = 1, /**< Unacceptable protocol version */ - CONNACK_IDENTIFIER_REJECTED_ERROR = 2, /**< Client identifier rejected */ - CONNACK_SERVER_UNAVAILABLE_ERROR = 3, /**< Server unavailable */ - CONNACK_BAD_USERDATA_ERROR = 4, /**< Bad username */ - CONNACK_NOT_AUTHORIZED_ERROR = 5 /**< Not authorized */ -} MQTT_Connack_Return_Codes; - -/** - * 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}; - uint8_t flags = 0u; - - 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 = 0; - if (pConnectParams->isCleanSession) - { - flags |= 1 << 1; - } - - if (pConnectParams->isWillMsgPresent) - { - flags |= 1 << 2; - flags |= (uint8_t) (pConnectParams->will.qos << 3); - flags |= (uint8_t) (pConnectParams->will.isRetained << 5); - } - - if(pConnectParams->pPassword) { - flags |= 1 << 6; - } - - if(pConnectParams->pUsername) { - flags |= 1 << 7; - } - - aws_iot_mqtt_internal_write_char(&ptr, flags); - aws_iot_mqtt_internal_write_uint_16(&ptr, pConnectParams->keepAliveIntervalInSec); - - /* If the code have passed the check for incorrect values above, no client id was passed as argument */ - if(NULL == pConnectParams->pClientID) { - aws_iot_mqtt_internal_write_uint_16(&ptr, 0); - } else { - aws_iot_mqtt_internal_write_utf8_string(&ptr, pConnectParams->pClientID, pConnectParams->clientIDLen); - } - - if(pConnectParams->isWillMsgPresent) { - aws_iot_mqtt_internal_write_utf8_string(&ptr, pConnectParams->will.pTopicName, - pConnectParams->will.topicNameLen); - aws_iot_mqtt_internal_write_utf8_string(&ptr, pConnectParams->will.pMessage, pConnectParams->will.msgLen); - } - - if(pConnectParams->pUsername) { - aws_iot_mqtt_internal_write_utf8_string(&ptr, pConnectParams->pUsername, pConnectParams->usernameLen); - } - - if(pConnectParams->pPassword) { - aws_iot_mqtt_internal_write_utf8_string(&ptr, pConnectParams->pPassword, pConnectParams->passwordLen); - } - - *pSerializedLen = (size_t) (ptr - pTxBuf); - - FUNC_EXIT_RC(SUCCESS); -} - -/** - * Deserializes the supplied (wire) buffer into connack data - return code - * @param sessionPresent the session present flag returned (only for MQTT 3.1.1) - * @param connack_rc returned integer value of the connack return code - * @param buf the raw buffer data, of the correct length determined by the remaining length field - * @param buflen the length in bytes of the data in the supplied buffer - * @return IoT_Error_t indicating function execution status - */ -static IoT_Error_t _aws_iot_mqtt_deserialize_connack(unsigned char *pSessionPresent, IoT_Error_t *pConnackRc, - unsigned char *pRxBuf, size_t rxBufLen) { - unsigned char *curdata, *enddata; - unsigned char connack_rc_char; - uint32_t decodedLen, readBytesLen; - IoT_Error_t rc; - uint8_t flags = 0u; - MQTTHeader header = {0}; - - FUNC_ENTRY; - - if(NULL == pSessionPresent || NULL == pConnackRc || NULL == pRxBuf) { - FUNC_EXIT_RC(NULL_VALUE_ERROR); - } - - /* CONNACK header size is fixed at two bytes for fixed and 2 bytes for variable, - * using that as minimum size - * MQTT v3.1.1 Specification 3.2.1 */ - if(4 > rxBufLen) { - FUNC_EXIT_RC(MQTT_RX_BUFFER_TOO_SHORT_ERROR); - } - - curdata = pRxBuf; - enddata = NULL; - decodedLen = 0; - readBytesLen = 0; - - header.byte = aws_iot_mqtt_internal_read_char(&curdata); - if(CONNACK != MQTT_HEADER_FIELD_TYPE(header.byte)) { - FUNC_EXIT_RC(FAILURE); - } - - /* read remaining length */ - rc = aws_iot_mqtt_internal_decode_remaining_length_from_buffer(curdata, &decodedLen, &readBytesLen); - if(SUCCESS != rc) { - FUNC_EXIT_RC(rc); - } - - /* CONNACK remaining length should always be 2 as per MQTT 3.1.1 spec */ - curdata += (readBytesLen); - enddata = curdata + decodedLen; - if(2 != (enddata - curdata)) { - FUNC_EXIT_RC(MQTT_DECODE_REMAINING_LENGTH_ERROR); - } - - flags = aws_iot_mqtt_internal_read_char(&curdata); - /* Session present is in the LSb. */ - *pSessionPresent = (flags & 0x01); - 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); - } - - /* Ensure that a ping request is sent after keepAliveInterval. */ - pClient->clientStatus.isPingOutstanding = false; - countdown_sec(&pClient->pingReqTimer, 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); - } - aws_iot_mqtt_internal_flushBuffers( pClient ); - clientState = aws_iot_mqtt_get_client_state(pClient); - - if(false == _aws_iot_mqtt_is_client_state_valid_for_connect(clientState)) { - /* Don't send connect packet again if we are already connected - * or in the process of connecting/disconnecting */ - FUNC_EXIT_RC(NETWORK_ALREADY_CONNECTED_ERROR); - } - - aws_iot_mqtt_set_client_state(pClient, clientState, CLIENT_STATE_CONNECTING); - - rc = _aws_iot_mqtt_internal_connect(pClient, pConnectParams); - - if(SUCCESS != rc) { - pClient->networkStack.disconnect(&(pClient->networkStack)); - disconRc = pClient->networkStack.destroy(&(pClient->networkStack)); - if (SUCCESS != disconRc) { - FUNC_EXIT_RC(NETWORK_DISCONNECTED_ERROR); - } - aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTING, CLIENT_STATE_DISCONNECTED_ERROR); - } else { - aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTING, CLIENT_STATE_CONNECTED_IDLE); - } - - FUNC_EXIT_RC(rc); -} - -/** - * @brief Disconnect an MQTT Connection - * - * Called to send a disconnect message to the broker. - * This is the internal function which is called by the disconnect API to perform the operation. - * Not meant to be called directly as it doesn't do validations or client state changes - * - * @param pClient Reference to the IoT Client - * - * @return An IoT Error Type defining successful/failed send of the disconnect control packet. - */ -static 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) { - (void)aws_iot_mqtt_internal_send_packet(pClient, serialized_len, &timer); - } - - /* Clean network stack */ - pClient->networkStack.disconnect(&(pClient->networkStack)); - rc = pClient->networkStack.destroy(&(pClient->networkStack)); - if(SUCCESS != rc) { - /* TLS Destroy failed, return error */ - FUNC_EXIT_RC(FAILURE); - } - - FUNC_EXIT_RC(SUCCESS); -} - -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); -} - -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); - } - - /* Only attempt a connect if not already connected. */ - if(!aws_iot_mqtt_is_client_connected(pClient)) { - /* Ignoring return code. failures expected if network is disconnected */ - 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); - } - } - else { - /* If already connected and no subscribe operation pending, then return - already connected error. */ - if(CLIENT_STATE_CONNECTED_RESUBSCRIBE_IN_PROGRESS != aws_iot_mqtt_get_client_state(pClient)) { - FUNC_EXIT_RC(NETWORK_ALREADY_CONNECTED_ERROR); - } - } - - rc = aws_iot_mqtt_resubscribe(pClient); - if(SUCCESS != rc) { - FUNC_EXIT_RC(NETWORK_ATTEMPTING_RECONNECT); - } - - FUNC_EXIT_RC(NETWORK_RECONNECTED); -} - -#ifdef __cplusplus -} -#endif diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_publish.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_publish.c deleted file mode 100644 index 61822ad4a..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_publish.c +++ /dev/null @@ -1,411 +0,0 @@ -/* -* 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); -} - -IoT_Error_t aws_iot_mqtt_publish(AWS_IoT_Client *pClient, const char *pTopicName, uint16_t topicNameLen, - IoT_Publish_Message_Params *pParams) { - IoT_Error_t rc, pubRc; - ClientState clientState; - - FUNC_ENTRY; - - if(NULL == pClient || NULL == pTopicName || 0 == topicNameLen || NULL == pParams) { - FUNC_EXIT_RC(NULL_VALUE_ERROR); - } - - if(!aws_iot_mqtt_is_client_connected(pClient)) { - FUNC_EXIT_RC(NETWORK_DISCONNECTED_ERROR); - } - - clientState = aws_iot_mqtt_get_client_state(pClient); - if(CLIENT_STATE_CONNECTED_IDLE != clientState && CLIENT_STATE_CONNECTED_WAIT_FOR_CB_RETURN != clientState) { - FUNC_EXIT_RC(MQTT_CLIENT_NOT_IDLE_ERROR); - } - - rc = aws_iot_mqtt_set_client_state(pClient, clientState, CLIENT_STATE_CONNECTED_PUBLISH_IN_PROGRESS); - if(SUCCESS != rc) { - FUNC_EXIT_RC(rc); - } - - pubRc = _aws_iot_mqtt_internal_publish(pClient, pTopicName, topicNameLen, pParams); - - rc = aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTED_PUBLISH_IN_PROGRESS, clientState); - if(SUCCESS == pubRc && SUCCESS != rc) { - pubRc = rc; - } - - FUNC_EXIT_RC(pubRc); -} - -/** - * Deserializes the supplied (wire) buffer into publish data - * @param dup returned uint8_t - the MQTT dup flag - * @param qos returned QoS type - the MQTT QoS value - * @param retained returned uint8_t - the MQTT retained flag - * @param pPacketId returned uint16_t - the MQTT packet identifier - * @param pTopicName returned String - the MQTT topic in the publish - * @param topicNameLen returned uint16_t - the length of the MQTT topic in the publish - * @param payload returned byte buffer - the MQTT publish payload - * @param payloadLen returned size_t - the length of the MQTT payload - * @param pRxBuf the raw buffer data, of the correct length determined by the remaining length field - * @param rxBufLen the length in bytes of the data in the supplied buffer - * - * @return An IoT Error Type defining successful/failed call - */ -IoT_Error_t aws_iot_mqtt_internal_deserialize_publish(uint8_t *dup, QoS *qos, - uint8_t *retained, uint16_t *pPacketId, - char **pTopicName, uint16_t *topicNameLen, - unsigned char **payload, size_t *payloadLen, - unsigned char *pRxBuf, size_t rxBufLen) { - unsigned char *curData = pRxBuf; - unsigned char *endData = NULL; - IoT_Error_t rc = FAILURE; - uint32_t decodedLen = 0; - uint32_t readBytesLen = 0; - MQTTHeader header = {0}; - - FUNC_ENTRY; - - if(NULL == dup || NULL == qos || NULL == retained || NULL == pPacketId) { - FUNC_EXIT_RC(FAILURE); - } - - /* Publish header size is at least four bytes. - * Fixed header is two bytes. - * Variable header size depends on QoS And Topic Name. - * QoS level 0 doesn't have a message identifier (0 - 2 bytes) - * Topic Name length fields decide size of topic name field (at least 2 bytes) - * MQTT v3.1.1 Specification 3.3.1 */ - if(4 > rxBufLen) { - FUNC_EXIT_RC(MQTT_RX_BUFFER_TOO_SHORT_ERROR); - } - - header.byte = aws_iot_mqtt_internal_read_char(&curData); - if(PUBLISH != MQTT_HEADER_FIELD_TYPE(header.byte)) { - FUNC_EXIT_RC(FAILURE); - } - - *dup = MQTT_HEADER_FIELD_DUP(header.byte); - *qos = (QoS) MQTT_HEADER_FIELD_QOS(header.byte); - *retained = MQTT_HEADER_FIELD_RETAIN(header.byte); - - /* read remaining length */ - rc = aws_iot_mqtt_internal_decode_remaining_length_from_buffer(curData, &decodedLen, &readBytesLen); - if(SUCCESS != rc) { - FUNC_EXIT_RC(rc); - } - curData += (readBytesLen); - endData = curData + decodedLen; - - /* do we have enough data to read the protocol version byte? */ - if(SUCCESS != _aws_iot_mqtt_read_string_with_len(pTopicName, topicNameLen, &curData, endData) - || (0 > (endData - curData))) { - FUNC_EXIT_RC(FAILURE); - } - - if(QOS0 != *qos) { - *pPacketId = aws_iot_mqtt_internal_read_uint16_t(&curData); - } - - *payloadLen = (size_t) (endData - curData); - *payload = curData; - - FUNC_EXIT_RC(SUCCESS); -} - -/** - * Deserializes the supplied (wire) buffer into an ack - * @param pPacketType returned integer - the MQTT packet type - * @param dup returned integer - the MQTT dup flag - * @param pPacketId returned integer - the MQTT packet identifier - * @param pRxBuf the raw buffer data, of the correct length determined by the remaining length field - * @param rxBuflen the length in bytes of the data in the supplied buffer - * - * @return An IoT Error Type defining successful/failed call - */ -IoT_Error_t aws_iot_mqtt_internal_deserialize_ack(unsigned char *pPacketType, unsigned char *dup, - uint16_t *pPacketId, unsigned char *pRxBuf, - size_t rxBuflen) { - IoT_Error_t rc = FAILURE; - unsigned char *curdata = pRxBuf; - unsigned char *enddata = NULL; - uint32_t decodedLen = 0; - uint32_t readBytesLen = 0; - MQTTHeader header = {0}; - - FUNC_ENTRY; - - if(NULL == pPacketType || NULL == dup || NULL == pPacketId || NULL == pRxBuf) { - FUNC_EXIT_RC(NULL_VALUE_ERROR); - } - - /* PUBACK fixed header size is two bytes, variable header is 2 bytes, MQTT v3.1.1 Specification 3.4.1 */ - if(4 > rxBuflen) { - FUNC_EXIT_RC(MQTT_RX_BUFFER_TOO_SHORT_ERROR); - } - - - header.byte = aws_iot_mqtt_internal_read_char(&curdata); - *dup = MQTT_HEADER_FIELD_DUP(header.byte); - *pPacketType = MQTT_HEADER_FIELD_TYPE(header.byte); - - /* read remaining length */ - rc = aws_iot_mqtt_internal_decode_remaining_length_from_buffer(curdata, &decodedLen, &readBytesLen); - if(SUCCESS != rc) { - FUNC_EXIT_RC(rc); - } - curdata += (readBytesLen); - enddata = curdata + decodedLen; - - if(enddata - curdata < 2) { - FUNC_EXIT_RC(FAILURE); - } - - *pPacketId = aws_iot_mqtt_internal_read_uint16_t(&curdata); - - FUNC_EXIT_RC(SUCCESS); -} - -#ifdef __cplusplus -} -#endif diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_subscribe.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_subscribe.c deleted file mode 100644 index 00e091709..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_subscribe.c +++ /dev/null @@ -1,435 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -// Based on Eclipse Paho. -/******************************************************************************* - * Copyright (c) 2014 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - * Contributors: - * Ian Craggs - initial API and implementation and/or initial documentation - *******************************************************************************/ - -/** - * @file aws_iot_mqtt_client_subscribe.c - * @brief MQTT client subscribe API definitions - */ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "aws_iot_mqtt_client_common_internal.h" - -/** - * Serializes the supplied subscribe data into the supplied buffer, ready for sending - * @param pTxBuf the buffer into which the packet will be serialized - * @param txBufLen the length in bytes of the supplied buffer - * @param dup unsigned char - the MQTT dup flag - * @param packetId uint16_t - the MQTT packet identifier - * @param topicCount - number of members in the topicFilters and reqQos arrays - * @param pTopicNameList - array of topic filter names - * @param pTopicNameLenList - array of length of topic filter names - * @param pRequestedQoSs - array of requested QoS - * @param pSerializedLen - the length of the serialized data - * - * @return An IoT Error Type defining successful/failed operation - */ -static IoT_Error_t _aws_iot_mqtt_serialize_subscribe(unsigned char *pTxBuf, size_t txBufLen, - unsigned char dup, uint16_t packetId, uint32_t topicCount, - const char **pTopicNameList, uint16_t *pTopicNameLenList, - QoS *pRequestedQoSs, uint32_t *pSerializedLen) { - unsigned char *ptr; - uint32_t itr, rem_len; - IoT_Error_t rc; - MQTTHeader header = {0}; - - FUNC_ENTRY; - if(NULL == pTxBuf || NULL == pSerializedLen) { - FUNC_EXIT_RC(NULL_VALUE_ERROR); - } - - ptr = pTxBuf; - rem_len = 2; /* packetId */ - - for(itr = 0; itr < topicCount; ++itr) { - rem_len += (uint32_t) (pTopicNameLenList[itr] + 2 + 1); /* topic + length + req_qos */ - } - - if(aws_iot_mqtt_internal_get_final_packet_length_from_remaining_length(rem_len) > txBufLen) { - FUNC_EXIT_RC(MQTT_TX_BUFFER_TOO_SHORT_ERROR); - } - - rc = aws_iot_mqtt_internal_init_header(&header, SUBSCRIBE, QOS1, dup, 0); - if(SUCCESS != rc) { - FUNC_EXIT_RC(rc); - } - /* write header */ - aws_iot_mqtt_internal_write_char(&ptr, header.byte); - - /* write remaining length */ - ptr += aws_iot_mqtt_internal_write_len_to_buffer(ptr, rem_len); - - aws_iot_mqtt_internal_write_uint_16(&ptr, packetId); - - for(itr = 0; itr < topicCount; ++itr) { - aws_iot_mqtt_internal_write_utf8_string(&ptr, pTopicNameList[itr], pTopicNameLenList[itr]); - aws_iot_mqtt_internal_write_char(&ptr, (unsigned char) pRequestedQoSs[itr]); - } - - *pSerializedLen = (uint32_t) (ptr - pTxBuf); - - FUNC_EXIT_RC(SUCCESS); -} - -/** - * Deserializes the supplied (wire) buffer into suback data - * @param pPacketId returned integer - the MQTT packet identifier - * @param maxExpectedQoSCount - the maximum number of members allowed in the grantedQoSs array - * @param pGrantedQoSCount returned uint32_t - number of members in the grantedQoSs array - * @param pGrantedQoSs returned array of QoS type - the granted qualities of service - * @param pRxBuf the raw buffer data, of the correct length determined by the remaining length field - * @param rxBufLen the length in bytes of the data in the supplied buffer - * - * @return An IoT Error Type defining successful/failed operation - */ -static IoT_Error_t _aws_iot_mqtt_deserialize_suback(uint16_t *pPacketId, uint32_t maxExpectedQoSCount, - uint32_t *pGrantedQoSCount, QoS *pGrantedQoSs, - unsigned char *pRxBuf, size_t rxBufLen) { - unsigned char *curData, *endData; - uint32_t decodedLen, readBytesLen; - IoT_Error_t decodeRc; - MQTTHeader header = {0}; - - FUNC_ENTRY; - if(NULL == pPacketId || NULL == pGrantedQoSCount || NULL == pGrantedQoSs) { - FUNC_EXIT_RC(NULL_VALUE_ERROR); - } - - curData = pRxBuf; - endData = NULL; - decodeRc = FAILURE; - decodedLen = 0; - readBytesLen = 0; - - /* SUBACK header size is 4 bytes for header and at least one byte for QoS payload - * Need at least a 5 bytes buffer. MQTT3.1.1 specification 3.9 - */ - if(5 > rxBufLen) { - FUNC_EXIT_RC(MQTT_RX_BUFFER_TOO_SHORT_ERROR); - } - - header.byte = aws_iot_mqtt_internal_read_char(&curData); - if(SUBACK != MQTT_HEADER_FIELD_TYPE(header.byte)) { - FUNC_EXIT_RC(FAILURE); - } - - /* read remaining length */ - decodeRc = aws_iot_mqtt_internal_decode_remaining_length_from_buffer(curData, &decodedLen, &readBytesLen); - if(SUCCESS != decodeRc) { - FUNC_EXIT_RC(decodeRc); - } - - curData += (readBytesLen); - endData = curData + decodedLen; - if(endData - curData < 2) { - FUNC_EXIT_RC(FAILURE); - } - - *pPacketId = aws_iot_mqtt_internal_read_uint16_t(&curData); - - *pGrantedQoSCount = 0; - while(curData < endData) { - if(*pGrantedQoSCount > maxExpectedQoSCount) { - FUNC_EXIT_RC(FAILURE); - } - pGrantedQoSs[(*pGrantedQoSCount)++] = (QoS) aws_iot_mqtt_internal_read_char(&curData); - } - - FUNC_EXIT_RC(SUCCESS); -} - -/* Returns MAX_MESSAGE_HANDLERS value if no free index is available */ -static uint32_t _aws_iot_mqtt_get_free_message_handler_index(AWS_IoT_Client *pClient) { - uint32_t itr; - - FUNC_ENTRY; - - for(itr = 0; itr < AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; itr++) { - if(pClient->clientData.messageHandlers[itr].topicName == NULL) { - break; - } - } - - FUNC_EXIT_RC(itr); -} - -/** - * @brief Subscribe to an MQTT topic. - * - * Called to send a subscribe message to the broker requesting a subscription - * to an MQTT topic. This is the internal function which is called by the - * subscribe API to perform the operation. Not meant to be called directly as - * it doesn't do validations or client state changes - * @note Call is blocking. The call returns after the receipt of the SUBACK control packet. - * @warning pTopicName and pApplicationHandlerData need to be static in memory. - * - * @param pClient Reference to the IoT Client - * @param pTopicName Topic Name to publish to. pTopicName needs to be static in memory since - * no malloc are performed by the SDK - * @param topicNameLen Length of the topic name - * @param pApplicationHandler_t Reference to the handler function for this subscription - * @param pApplicationHandlerData Point to data passed to the callback. - * pApplicationHandlerData also needs to be static in memory since no malloc are performed by the SDK - * - * @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); -} - -IoT_Error_t aws_iot_mqtt_subscribe(AWS_IoT_Client *pClient, const char *pTopicName, uint16_t topicNameLen, - QoS qos, pApplicationHandler_t pApplicationHandler, void *pApplicationHandlerData) { - ClientState clientState; - IoT_Error_t rc, subRc; - - FUNC_ENTRY; - - if(NULL == pClient || NULL == pTopicName || NULL == pApplicationHandler) { - FUNC_EXIT_RC(NULL_VALUE_ERROR); - } - - if(!aws_iot_mqtt_is_client_connected(pClient)) { - FUNC_EXIT_RC(NETWORK_DISCONNECTED_ERROR); - } - - clientState = aws_iot_mqtt_get_client_state(pClient); - if(CLIENT_STATE_CONNECTED_IDLE != clientState && CLIENT_STATE_CONNECTED_WAIT_FOR_CB_RETURN != clientState) { - FUNC_EXIT_RC(MQTT_CLIENT_NOT_IDLE_ERROR); - } - - rc = aws_iot_mqtt_set_client_state(pClient, clientState, CLIENT_STATE_CONNECTED_SUBSCRIBE_IN_PROGRESS); - if(SUCCESS != rc) { - FUNC_EXIT_RC(rc); - } - - subRc = _aws_iot_mqtt_internal_subscribe(pClient, pTopicName, topicNameLen, qos, - pApplicationHandler, pApplicationHandlerData); - - rc = aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTED_SUBSCRIBE_IN_PROGRESS, clientState); - if(SUCCESS == subRc && SUCCESS != rc) { - subRc = rc; - } - - FUNC_EXIT_RC(subRc); -} - -/** - * @brief Subscribe to an MQTT topic. - * - * Called to send a subscribe message to the broker requesting a subscription - * to an MQTT topic. - * This is the internal function which is called by the resubscribe API to perform the operation. - * Not meant to be called directly as it doesn't do validations or client state changes - * @note Call is blocking. The call returns after the receipt of the SUBACK control packet. - * - * @param pClient Reference to the IoT Client - * - * @return An IoT Error Type defining successful/failed subscription - */ -static IoT_Error_t _aws_iot_mqtt_internal_resubscribe(AWS_IoT_Client *pClient) { - uint16_t packetId; - uint32_t len, count, existingSubCount, itr; - IoT_Error_t rc; - Timer timer; - QoS grantedQoS[3] = {QOS0, QOS0, QOS0}; - - FUNC_ENTRY; - - packetId = 0; - len = 0; - count = 0; - existingSubCount = _aws_iot_mqtt_get_free_message_handler_index(pClient); - - for(itr = 0; itr < existingSubCount; itr++) { - if(pClient->clientData.messageHandlers[itr].topicName == NULL) { - continue; - } - - /* Do not attempt to subscribe to topics which have already been subscribed - to in the previous re-subscribe attempts. */ - if(pClient->clientData.messageHandlers[itr].resubscribed == 1) { - continue; - } - - init_timer(&timer); - countdown_ms(&timer, pClient->clientData.commandTimeoutMs); - - rc = _aws_iot_mqtt_serialize_subscribe(pClient->clientData.writeBuf, pClient->clientData.writeBufSize, 0, - aws_iot_mqtt_get_next_packet_id(pClient), 1, - &(pClient->clientData.messageHandlers[itr].topicName), - &(pClient->clientData.messageHandlers[itr].topicNameLen), - &(pClient->clientData.messageHandlers[itr].qos), &len); - if(SUCCESS != rc) { - FUNC_EXIT_RC(rc); - } - - /* send the subscribe packet */ - rc = aws_iot_mqtt_internal_send_packet(pClient, len, &timer); - if(SUCCESS != rc) { - FUNC_EXIT_RC(rc); - } - - /* wait for suback */ - rc = aws_iot_mqtt_internal_wait_for_read(pClient, SUBACK, &timer); - if(SUCCESS != rc) { - FUNC_EXIT_RC(rc); - } - - /* Granted QoS can be 0, 1 or 2 */ - rc = _aws_iot_mqtt_deserialize_suback(&packetId, 1, &count, grantedQoS, pClient->clientData.readBuf, - pClient->clientData.readBufSize); - if(SUCCESS != rc) { - FUNC_EXIT_RC(rc); - } - - /* Record that this topic has been subscribed to, so that we do not - * attempt to subscribe again to the same topic. */ - pClient->clientData.messageHandlers[itr].resubscribed = 1; - } - - FUNC_EXIT_RC(SUCCESS); -} - -IoT_Error_t aws_iot_mqtt_resubscribe(AWS_IoT_Client *pClient) { - IoT_Error_t rc, resubRc; - ClientState currentState = aws_iot_mqtt_get_client_state(pClient); - - 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); - } - - /* At this point, the client state should be either CLIENT_STATE_CONNECTED_IDLE - or CLIENT_STATE_CONNECTED_RESUBSCRIBE_IN_PROGRESS. The former means that it - is the first re-subscribe attempt while the latter means that it is second - or subsequent re-subscribe attempt. */ - if((CLIENT_STATE_CONNECTED_IDLE != currentState) && (CLIENT_STATE_CONNECTED_RESUBSCRIBE_IN_PROGRESS != currentState)) { - FUNC_EXIT_RC(MQTT_UNEXPECTED_CLIENT_STATE_ERROR); - } - - /* If it is the first re-subscribe attempt (i.e. client state is CLIENT_STATE_CONNECTED_IDLE), - set the client state to CLIENT_STATE_CONNECTED_RESUBSCRIBE_IN_PROGRESS. */ - if(CLIENT_STATE_CONNECTED_IDLE == currentState) { - 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); - - /* It is possible that the subscribe operation fails, do not change the state - in that case so that the subscribe is attempted again in the next iteration - of yield. */ - if(SUCCESS == resubRc) { - resubRc = aws_iot_mqtt_set_client_state(pClient, CLIENT_STATE_CONNECTED_RESUBSCRIBE_IN_PROGRESS, CLIENT_STATE_CONNECTED_IDLE); - } - - FUNC_EXIT_RC(resubRc); -} - -#ifdef __cplusplus -} -#endif diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_unsubscribe.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_unsubscribe.c deleted file mode 100644 index 1d78a7477..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_unsubscribe.c +++ /dev/null @@ -1,234 +0,0 @@ -/* -* 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; - break; - } - } - - 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); -} - -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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_yield.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_yield.c deleted file mode 100644 index 25a46cbfe..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_mqtt_client_yield.c +++ /dev/null @@ -1,325 +0,0 @@ -/* -* 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); - } - - pClient->clientStatus.clientState = CLIENT_STATE_DISCONNECTED_ERROR; - - if(NULL != pClient->clientData.disconnectHandler) { - pClient->clientData.disconnectHandler(pClient, pClient->clientData.disconnectHandlerData); - } - - if (pClient->clientStatus.clientState == CLIENT_STATE_CONNECTED_IDLE) { - FUNC_EXIT_RC(SUCCESS); - } - - 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(pClient->clientStatus.isPingOutstanding) { - /* We are waiting for a PINGRESP from the broker. If the pingRespTimer, - * has expired, it indicates that the transport layer connection is - * lost and therefore, we initiate MQTT disconnect (which will triggger) - * the re-connect workflow, if enabled. If the pingRespTimer is not - * expired, there is nothing to do and we continue waiting for PINGRESP. */ - if(has_timer_expired(&pClient->pingRespTimer)) { - rc = _aws_iot_mqtt_handle_disconnect(pClient); - FUNC_EXIT_RC(rc); - } else { - FUNC_EXIT_RC(SUCCESS); - } - } else { - /* We are not waiting for a PINGRESP from the broker. If the - * pingReqTimer has expired, we send a PINGREQ. Otherwise, there is - * nothing to do. */ - if(!has_timer_expired(&pClient->pingReqTimer)) { - FUNC_EXIT_RC(SUCCESS); - } - } - - - /* 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->pingRespTimer, pClient->clientData.keepAliveInterval); - /* Start a timer to keep track of when to send the next PINGREQ. */ - countdown_sec(&pClient->pingReqTimer, 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; - int itr = 0; - - 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 the client state is pending reconnect or resubscribe in progress, - we keep retrying _aws_iot_mqtt_handle_reconnect. This function only - attempts to connect if not already connected thereby ensuring that the - subsequent invocations only attempt remaining subscribes. */ - if((CLIENT_STATE_PENDING_RECONNECT == clientState) || - (CLIENT_STATE_CONNECTED_RESUBSCRIBE_IN_PROGRESS == 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_WRITE_ERROR == yieldRc || NETWORK_SSL_WRITE_TIMEOUT_ERROR == yieldRc) { - yieldRc = _aws_iot_mqtt_handle_disconnect(pClient); - } - } - - if(NETWORK_DISCONNECTED_ERROR == yieldRc) { - pClient->clientData.counterNetworkDisconnected++; - /* Always clear resubscribe flags. */ - for(itr = 0; itr < AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; itr++) { - pClient->clientData.messageHandlers[itr].resubscribed = 0; - } - - 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); -} - -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 or resubscribe in progress state, skip other checks. - * Pending reconnect or resubscribe in progress state is only set when auto-reconnect - * is enabled */ - if((CLIENT_STATE_PENDING_RECONNECT != clientState) && - (CLIENT_STATE_CONNECTED_RESUBSCRIBE_IN_PROGRESS != 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow.c deleted file mode 100644 index 5c69edb05..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow.c +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://aws.amazon.com/apache2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -/** - * @file aws_iot_shadow.c - * @brief Shadow client API definitions - */ - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include "aws_iot_mqtt_client_interface.h" -#include "aws_iot_shadow_interface.h" -#include "aws_iot_error.h" -#include "aws_iot_log.h" -#include "aws_iot_shadow_actions.h" -#include "aws_iot_shadow_json.h" -#include "aws_iot_shadow_key.h" -#include "aws_iot_shadow_records.h" - -const ShadowInitParameters_t ShadowInitParametersDefault = {(char *) AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, NULL, NULL, - NULL, false, NULL}; - -const ShadowConnectParameters_t ShadowConnectParametersDefault = {(char *) AWS_IOT_MY_THING_NAME, - (char *) AWS_IOT_MQTT_CLIENT_ID, 0, NULL}; - -static char deleteAcceptedTopic[MAX_SHADOW_TOPIC_LENGTH_BYTES]; - -void aws_iot_shadow_reset_last_received_version(void) { - shadowJsonVersionNum = 0; -} - -uint32_t aws_iot_shadow_get_last_received_version(void) { - return shadowJsonVersionNum; -} - -void aws_iot_shadow_enable_discard_old_delta_msgs(void) { - shadowDiscardOldDeltaFlag = true; -} - -void aws_iot_shadow_disable_discard_old_delta_msgs(void) { - shadowDiscardOldDeltaFlag = false; -} - -IoT_Error_t aws_iot_shadow_free(AWS_IoT_Client *pClient) -{ - IoT_Error_t rc; - - if (NULL == pClient) { - FUNC_EXIT_RC(NULL_VALUE_ERROR); - } - - rc = aws_iot_mqtt_free(pClient); - - FUNC_EXIT_RC(rc); -} - -IoT_Error_t aws_iot_shadow_init(AWS_IoT_Client *pClient, ShadowInitParameters_t *pParams) { - IoT_Client_Init_Params mqttInitParams = IoT_Client_Init_Params_initializer; - IoT_Error_t rc; - - FUNC_ENTRY; - - if(NULL == pClient || NULL == pParams) { - FUNC_EXIT_RC(NULL_VALUE_ERROR); - } - - mqttInitParams.enableAutoReconnect = pParams->enableAutoReconnect; - mqttInitParams.pHostURL = pParams->pHost; - mqttInitParams.port = pParams->port; - mqttInitParams.pRootCALocation = pParams->pRootCA; - mqttInitParams.pDeviceCertLocation = pParams->pClientCRT; - mqttInitParams.pDevicePrivateKeyLocation = pParams->pClientKey; - mqttInitParams.mqttPacketTimeout_ms = 5000; - mqttInitParams.mqttCommandTimeout_ms = 20000; - mqttInitParams.tlsHandshakeTimeout_ms = 5000; - mqttInitParams.isSSLHostnameVerify = true; - mqttInitParams.disconnectHandler = pParams->disconnectHandler; - - rc = aws_iot_mqtt_init(pClient, &mqttInitParams); - if(SUCCESS != rc) { - FUNC_EXIT_RC(rc); - } - - resetClientTokenSequenceNum(); - aws_iot_shadow_reset_last_received_version(); - initDeltaTokens(); - - FUNC_EXIT_RC(SUCCESS); -} - -IoT_Error_t aws_iot_shadow_connect(AWS_IoT_Client *pClient, ShadowConnectParameters_t *pParams) { - IoT_Error_t rc = SUCCESS; - uint16_t deleteAcceptedTopicLen; - IoT_Client_Connect_Params ConnectParams = iotClientConnectParamsDefault; - - FUNC_ENTRY; - - if(NULL == pClient || NULL == pParams || NULL == pParams->pMqttClientId) { - FUNC_EXIT_RC(NULL_VALUE_ERROR); - } - - snprintf(myThingName, MAX_SIZE_OF_THING_NAME, "%s", pParams->pMyThingName); - snprintf(mqttClientID, MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES, "%s", pParams->pMqttClientId); - - ConnectParams.keepAliveIntervalInSec = 600; // NOTE: Temporary fix - ConnectParams.MQTTVersion = MQTT_3_1_1; - ConnectParams.isCleanSession = true; - ConnectParams.isWillMsgPresent = false; - ConnectParams.pClientID = pParams->pMqttClientId; - ConnectParams.clientIDLen = pParams->mqttClientIdLen; - ConnectParams.pPassword = NULL; - ConnectParams.pUsername = NULL; - - rc = aws_iot_mqtt_connect(pClient, &ConnectParams); - - if(SUCCESS != rc) { - FUNC_EXIT_RC(rc); - } - - initializeRecords(pClient); - - if(NULL != pParams->deleteActionHandler) { - snprintf(deleteAcceptedTopic, MAX_SHADOW_TOPIC_LENGTH_BYTES, - "$aws/things/%s/shadow/delete/accepted", myThingName); - deleteAcceptedTopicLen = (uint16_t) strlen(deleteAcceptedTopic); - rc = aws_iot_mqtt_subscribe(pClient, deleteAcceptedTopic, deleteAcceptedTopicLen, QOS1, - pParams->deleteActionHandler, (void *) myThingName); - } - - FUNC_EXIT_RC(rc); -} - -IoT_Error_t aws_iot_shadow_register_delta(AWS_IoT_Client *pMqttClient, jsonStruct_t *pStruct) { - if(NULL == pMqttClient || NULL == pStruct) { - return NULL_VALUE_ERROR; - } - - if(!aws_iot_mqtt_is_client_connected(pMqttClient)) { - return MQTT_CONNECTION_ERROR; - } - - return registerJsonTokenOnDelta(pStruct); -} - -IoT_Error_t aws_iot_shadow_yield(AWS_IoT_Client *pClient, uint32_t timeout) { - if(NULL == pClient) { - return NULL_VALUE_ERROR; - } - - HandleExpiredResponseCallbacks(); - return aws_iot_mqtt_yield(pClient, timeout); -} - -IoT_Error_t aws_iot_shadow_disconnect(AWS_IoT_Client *pClient) { - return aws_iot_mqtt_disconnect(pClient); -} - -IoT_Error_t aws_iot_shadow_update(AWS_IoT_Client *pClient, const char *pThingName, char *pJsonString, - fpActionCallback_t callback, void *pContextData, uint8_t timeout_seconds, - bool isPersistentSubscribe) { - IoT_Error_t rc; - - if(NULL == pClient) { - FUNC_EXIT_RC(NULL_VALUE_ERROR); - } - - if(!aws_iot_mqtt_is_client_connected(pClient)) { - FUNC_EXIT_RC(MQTT_CONNECTION_ERROR); - } - - rc = aws_iot_shadow_internal_action(pThingName, SHADOW_UPDATE, pJsonString, strlen(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); - } - - rc = aws_iot_shadow_internal_delete_request_json(deleteRequestJsonBuf, MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE ); - if ( SUCCESS != rc ) { - FUNC_EXIT_RC( rc ); - } - - rc = aws_iot_shadow_internal_action(pThingName, SHADOW_DELETE, deleteRequestJsonBuf, MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE, 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); - } - - rc = aws_iot_shadow_internal_get_request_json(getRequestJsonBuf, MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE ); - if (SUCCESS != rc) { - FUNC_EXIT_RC(rc); - } - - rc = aws_iot_shadow_internal_action(pThingName, SHADOW_GET, getRequestJsonBuf, MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE, 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow_actions.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow_actions.c deleted file mode 100644 index 95b81c56f..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow_actions.c +++ /dev/null @@ -1,80 +0,0 @@ -/* - * 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, size_t jsonSize, 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, jsonSize, extractedClientToken, MAX_SIZE_CLIENT_ID_WITH_SEQUENCE ); - - 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow_json.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow_json.c deleted file mode 100644 index b1d777836..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow_json.c +++ /dev/null @@ -1,559 +0,0 @@ -/* - * 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" { -#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]; -#define AWS_IOT_SHADOW_CLIENT_TOKEN_KEY "{\"clientToken\":\"" -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 IoT_Error_t emptyJsonWithClientToken(char *pBuffer, size_t bufferSize) { - - IoT_Error_t rc = SUCCESS; - size_t dataLenInBuffer = 0; - - if(pBuffer != NULL) - { - dataLenInBuffer = (size_t)snprintf(pBuffer, bufferSize, AWS_IOT_SHADOW_CLIENT_TOKEN_KEY); - }else - { - IOT_ERROR("NULL buffer in emptyJsonWithClientToken\n"); - rc = FAILURE; - } - - if(rc == SUCCESS) - { - if ( dataLenInBuffer < bufferSize ) - { - dataLenInBuffer += (size_t)snprintf(pBuffer + dataLenInBuffer, bufferSize - dataLenInBuffer, "%s-%d", mqttClientID, ( int )clientTokenNum++); - } - else - { - rc = FAILURE; - IOT_ERROR("Supplied buffer too small to create JSON file\n"); - } - } - - if(rc == SUCCESS) - { - if ( dataLenInBuffer < bufferSize ) - { - dataLenInBuffer += (size_t)snprintf( pBuffer + dataLenInBuffer, bufferSize - dataLenInBuffer, "\"}" ); - if ( dataLenInBuffer > bufferSize ) - { - rc = FAILURE; - IOT_ERROR( "Supplied buffer too small to create JSON file\n" ); - } - } - else - { - rc = FAILURE; - IOT_ERROR( "Supplied buffer too small to create JSON file\n" ); - } - } - - FUNC_EXIT_RC(rc); -} - -IoT_Error_t aws_iot_shadow_internal_get_request_json(char *pBuffer, size_t bufferSize) { - return emptyJsonWithClientToken( pBuffer, bufferSize); -} - -IoT_Error_t aws_iot_shadow_internal_delete_request_json(char *pBuffer, size_t bufferSize ) { - return emptyJsonWithClientToken( pBuffer, bufferSize); -} - -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) { - va_end(pArgs); - return NULL_VALUE_ERROR; - } - - tempSize = maxSizeOfJsonDocument - strlen(pJsonDocument); - if(tempSize <= 1) { - va_end(pArgs); - return SHADOW_JSON_ERROR; - } - remSizeOfJsonBuffer = tempSize; - - snPrintfReturn = snprintf(pJsonDocument + strlen(pJsonDocument), remSizeOfJsonBuffer, "\"desired\":{"); - ret_val = checkReturnValueOfSnPrintf(snPrintfReturn, remSizeOfJsonBuffer); - - if(ret_val != SUCCESS) { - va_end(pArgs); - return ret_val; - } - - for(i = 0; i < count; i++) { - tempSize = maxSizeOfJsonDocument - strlen(pJsonDocument); - if(tempSize <= 1) { - va_end(pArgs); - 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) { - va_end(pArgs); - return ret_val; - } - if(pTemporary->pKey != NULL && pTemporary->pData != NULL) { - ret_val = convertDataToString(pJsonDocument + strlen(pJsonDocument), remSizeOfJsonBuffer, - pTemporary->type, pTemporary->pData); - } else { - va_end(pArgs); - return NULL_VALUE_ERROR; - } - if(ret_val != SUCCESS) { - va_end(pArgs); - return ret_val; - } - } else { - va_end(pArgs); - 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) { - va_end(pArgs); - return NULL_VALUE_ERROR; - } - - - tempSize = maxSizeOfJsonDocument - strlen(pJsonDocument); - if(tempSize <= 1) { - va_end(pArgs); - return SHADOW_JSON_ERROR; - } - remSizeOfJsonBuffer = tempSize; - - snPrintfReturn = snprintf(pJsonDocument + strlen(pJsonDocument), remSizeOfJsonBuffer, "\"reported\":{"); - ret_val = checkReturnValueOfSnPrintf(snPrintfReturn, remSizeOfJsonBuffer); - - if(ret_val != SUCCESS) { - va_end(pArgs); - return ret_val; - } - - for(i = 0; i < count; i++) { - tempSize = maxSizeOfJsonDocument - strlen(pJsonDocument); - if(tempSize <= 1) { - va_end(pArgs); - 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) { - va_end(pArgs); - return ret_val; - } - if(pTemporary->pKey != NULL && pTemporary->pData != NULL) { - ret_val = convertDataToString(pJsonDocument + strlen(pJsonDocument), remSizeOfJsonBuffer, - pTemporary->type, pTemporary->pData); - } else { - va_end(pArgs); - return NULL_VALUE_ERROR; - } - if(ret_val != SUCCESS) { - va_end(pArgs); - return ret_val; - } - } else { - va_end(pArgs); - return NULL_VALUE_ERROR; - } - } - - va_end(pArgs); - snPrintfReturn = snprintf(pJsonDocument + strlen(pJsonDocument) - 1, remSizeOfJsonBuffer, "},"); - ret_val = checkReturnValueOfSnPrintf(snPrintfReturn, remSizeOfJsonBuffer); - return ret_val; -} - - -int32_t FillWithClientTokenSize(char *pBufferToBeUpdatedWithClientToken, size_t maxSizeOfJsonDocument) { - int32_t snPrintfReturn; - snPrintfReturn = snprintf(pBufferToBeUpdatedWithClientToken, maxSizeOfJsonDocument, "%s-%d", mqttClientID, - (int) clientTokenNum++); - - return snPrintfReturn; -} - -IoT_Error_t aws_iot_fill_with_client_token(char *pBufferToBeUpdatedWithClientToken, size_t maxSizeOfJsonDocument) { - - int32_t snPrintfRet = 0; - snPrintfRet = FillWithClientTokenSize(pBufferToBeUpdatedWithClientToken, maxSizeOfJsonDocument); - return checkReturnValueOfSnPrintf(snPrintfRet, maxSizeOfJsonDocument); - -} - -IoT_Error_t aws_iot_finalize_json_document(char *pJsonDocument, size_t maxSizeOfJsonDocument) { - size_t remSizeOfJsonBuffer = maxSizeOfJsonDocument; - int32_t snPrintfReturn = 0; - size_t tempSize = 0; - IoT_Error_t ret_val = SUCCESS; - - if(pJsonDocument == NULL) { - return NULL_VALUE_ERROR; - } - - tempSize = maxSizeOfJsonDocument - strlen(pJsonDocument); - if(tempSize <= 1) { - return SHADOW_JSON_ERROR; - } - remSizeOfJsonBuffer = tempSize; - - // strlen(ShadowTxBuffer) - 1 is to ensure we remove the last ,(comma) that was added - snPrintfReturn = snprintf(pJsonDocument + strlen(pJsonDocument) - 1, remSizeOfJsonBuffer, "}, \"%s\":\"", - SHADOW_CLIENT_TOKEN_STRING); - ret_val = checkReturnValueOfSnPrintf(snPrintfReturn, remSizeOfJsonBuffer); - - if(ret_val != SUCCESS) { - return ret_val; - } - // refactor this XXX repeated code - tempSize = maxSizeOfJsonDocument - strlen(pJsonDocument); - if(tempSize <= 1) { - return SHADOW_JSON_ERROR; - } - remSizeOfJsonBuffer = tempSize; - - - snPrintfReturn = FillWithClientTokenSize(pJsonDocument + strlen(pJsonDocument), remSizeOfJsonBuffer); - ret_val = checkReturnValueOfSnPrintf(snPrintfReturn, remSizeOfJsonBuffer); - - if(ret_val != SUCCESS) { - return ret_val; - } - tempSize = maxSizeOfJsonDocument - strlen(pJsonDocument); - if(tempSize <= 1) { - return SHADOW_JSON_ERROR; - } - remSizeOfJsonBuffer = tempSize; - - - snPrintfReturn = snprintf(pJsonDocument + strlen(pJsonDocument), remSizeOfJsonBuffer, "\"}"); - ret_val = checkReturnValueOfSnPrintf(snPrintfReturn, remSizeOfJsonBuffer); - - return ret_val; -} - -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, "%i,", *(int32_t *) (pData)); - } else if(type == SHADOW_JSON_INT16) { - snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%hi,", *(int16_t *) (pData)); - } else if(type == SHADOW_JSON_INT8) { - snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%hhi,", *(int8_t *) (pData)); - } else if(type == SHADOW_JSON_UINT32) { - snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%u,", *(uint32_t *) (pData)); - } else if(type == SHADOW_JSON_UINT16) { - snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%hu,", *(uint16_t *) (pData)); - } else if(type == SHADOW_JSON_UINT8) { - snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%hhu,", *(uint8_t *) (pData)); - } else if(type == SHADOW_JSON_DOUBLE) { - snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%f,", *(double *) (pData)); - } else if(type == SHADOW_JSON_FLOAT) { - snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%f,", *(float *) (pData)); - } else if(type == SHADOW_JSON_BOOL) { - snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%s,", *(bool *) (pData) ? "true" : "false"); - } else if(type == SHADOW_JSON_STRING) { - snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "\"%s\",", (char *) (pData)); - } else if(type == SHADOW_JSON_OBJECT) { - snPrintfReturn = snprintf(pStringBuffer, maxSizoStringBuffer, "%s,", (char *) (pData)); - } - - - ret_val = checkReturnValueOfSnPrintf(snPrintfReturn, maxSizoStringBuffer); - - return ret_val; -} - -static jsmn_parser shadowJsonParser; -static jsmntok_t jsonTokenStruct[MAX_JSON_TOKEN_EXPECTED]; - -bool isJsonValidAndParse(const char *pJsonDocument, size_t jsonSize, void *pJsonHandler, int32_t *pTokenCount) { - int32_t tokenCount; - - IOT_UNUSED(pJsonHandler); - - jsmn_init(&shadowJsonParser); - - tokenCount = jsmn_parse(&shadowJsonParser, pJsonDocument, jsonSize, jsonTokenStruct, - sizeof(jsonTokenStruct) / sizeof(jsonTokenStruct[0])); - - if(tokenCount < 0) { - IOT_WARN("Failed to parse JSON: %d\n", tokenCount); - return false; - } - - /* Assume the top-level element is an object */ - if(tokenCount < 1 || jsonTokenStruct[0].type != JSMN_OBJECT) { - IOT_WARN("Top Level is not an object\n"); - return false; - } - - *pTokenCount = tokenCount; - - return true; -} - -static IoT_Error_t UpdateValueIfNoObject(const char *pJsonString, jsonStruct_t *pDataStruct, jsmntok_t token) { - IoT_Error_t ret_val = SHADOW_JSON_ERROR; - if(pDataStruct->type == SHADOW_JSON_BOOL && pDataStruct->dataLength >= sizeof(bool)) { - ret_val = parseBooleanValue((bool *) pDataStruct->pData, pJsonString, &token); - } else if(pDataStruct->type == SHADOW_JSON_INT32 && pDataStruct->dataLength >= sizeof(int32_t)) { - ret_val = parseInteger32Value((int32_t *) pDataStruct->pData, pJsonString, &token); - } else if(pDataStruct->type == SHADOW_JSON_INT16 && pDataStruct->dataLength >= sizeof(int16_t)) { - ret_val = parseInteger16Value((int16_t *) pDataStruct->pData, pJsonString, &token); - } else if(pDataStruct->type == SHADOW_JSON_INT8 && pDataStruct->dataLength >= sizeof(int8_t)) { - ret_val = parseInteger8Value((int8_t *) pDataStruct->pData, pJsonString, &token); - } else if(pDataStruct->type == SHADOW_JSON_UINT32 && pDataStruct->dataLength >= sizeof(uint32_t)) { - ret_val = parseUnsignedInteger32Value((uint32_t *) pDataStruct->pData, pJsonString, &token); - } else if(pDataStruct->type == SHADOW_JSON_UINT16 && pDataStruct->dataLength >= sizeof(uint16_t)) { - ret_val = parseUnsignedInteger16Value((uint16_t *) pDataStruct->pData, pJsonString, &token); - } else if(pDataStruct->type == SHADOW_JSON_UINT8 && pDataStruct->dataLength >= sizeof(uint8_t)) { - ret_val = parseUnsignedInteger8Value((uint8_t *) pDataStruct->pData, pJsonString, &token); - } else if(pDataStruct->type == SHADOW_JSON_FLOAT && pDataStruct->dataLength >= sizeof(float)) { - ret_val = parseFloatValue((float *) pDataStruct->pData, pJsonString, &token); - } else if(pDataStruct->type == SHADOW_JSON_DOUBLE && pDataStruct->dataLength >= sizeof(double)) { - ret_val = parseDoubleValue((double *) pDataStruct->pData, pJsonString, &token); - } else if(pDataStruct->type == SHADOW_JSON_STRING) { - ret_val = parseStringValue((char *) pDataStruct->pData, pDataStruct->dataLength, 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, metadataEnd; - uint32_t dataLength; - jsmntok_t dataToken; - - IOT_UNUSED(pJsonHandler); - - for(i = 1; i < tokenCount; ) { - if(jsoneq(pJsonDocument, &(jsonTokenStruct[i]), pDataStruct->pKey) == 0) { - dataToken = jsonTokenStruct[i + 1]; - dataLength = (uint32_t) (dataToken.end - dataToken.start); - UpdateValueIfNoObject(pJsonDocument, pDataStruct, dataToken); - *pDataPosition = dataToken.start; - *pDataLength = dataLength; - return true; - } else if(jsoneq(pJsonDocument, &(jsonTokenStruct[i]), "metadata") == 0) { - /* Sanity check: must not be at the last key in the json object. */ - if(i >= tokenCount-2) - { - return false; - } - - /* Record where the metadata object ends. */ - metadataEnd = jsonTokenStruct[i+1].end; - - /* Skip past the "metadata" key and jsmn object element. */ - i+= 2; - - /* Skip past every key inside "metadata". Keys inside "metadata" have - * have an end character before the end of the metadata object. - */ - while(jsonTokenStruct[i].end < metadataEnd) - { - i++; - } - } - else - { - /* Only increment the loop counter if the current object doesn't - * match AND isn't "metadata". - */ - i++; - } - } - return false; -} - -bool isReceivedJsonValid(const char *pJsonDocument, size_t jsonSize ) { - int32_t tokenCount; - - jsmn_init(&shadowJsonParser); - - tokenCount = jsmn_parse(&shadowJsonParser, pJsonDocument, jsonSize, 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, size_t jsonSize, char *pExtractedClientToken, size_t clientTokenSize) { - int32_t tokenCount, i; - size_t length; - jsmntok_t ClientJsonToken; - jsmn_init(&shadowJsonParser); - - tokenCount = jsmn_parse(&shadowJsonParser, pJsonDocument, jsonSize, 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 = (size_t) (ClientJsonToken.end - ClientJsonToken.start); - if (clientTokenSize >= length + 1) - { - strncpy( pExtractedClientToken, pJsonDocument + ClientJsonToken.start, length); - pExtractedClientToken[length] = '\0'; - return true; - }else{ - IOT_WARN( "Token size %zu too small for string %zu \n", clientTokenSize, length); - return false; - } - } - } - - 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow_records.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow_records.c deleted file mode 100644 index d3a2c7720..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/src/aws_iot_shadow_records.c +++ /dev/null @@ -1,529 +0,0 @@ -/* - * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://aws.amazon.com/apache2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -/** - * @file aws_iot_mqtt_client_subscribe.c - * @brief MQTT client subscribe API definitions - */ - -#ifdef __cplusplus -extern "C" { -#endif - -#include "aws_iot_shadow_records.h" - -#include -#include - -#include "timer_interface.h" -#include "aws_iot_json_utils.h" -#include "aws_iot_log.h" -#include "aws_iot_shadow_json.h" -#include "aws_iot_config.h" - -typedef struct { - char clientTokenID[MAX_SIZE_CLIENT_ID_WITH_SEQUENCE]; - char thingName[MAX_SIZE_OF_THING_NAME]; - ShadowActions_t action; - fpActionCallback_t callback; - void *pCallbackContext; - bool isFree; - Timer timer; -} ToBeReceivedAckRecord_t; - -typedef struct { - const char *pKey; - void *pStruct; - jsonStructCallback_t callback; - bool isFree; -} JsonTokenTable_t; - -typedef struct { - char Topic[MAX_SHADOW_TOPIC_LENGTH_BYTES]; - uint8_t count; - bool isFree; - bool isSticky; -} SubscriptionRecord_t; - -typedef enum { - SHADOW_ACCEPTED, SHADOW_REJECTED, SHADOW_ACTION -} ShadowAckTopicTypes_t; - -ToBeReceivedAckRecord_t AckWaitList[MAX_ACKS_TO_COMEIN_AT_ANY_GIVEN_TIME]; - -AWS_IoT_Client *pMqttClient; - -char myThingName[MAX_SIZE_OF_THING_NAME]; -char mqttClientID[MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES]; - -char shadowDeltaTopic[MAX_SHADOW_TOPIC_LENGTH_BYTES]; - -#define MAX_TOPICS_AT_ANY_GIVEN_TIME 2*MAX_THINGNAME_HANDLED_AT_ANY_GIVEN_TIME -SubscriptionRecord_t SubscriptionList[MAX_TOPICS_AT_ANY_GIVEN_TIME]; - -#define SUBSCRIBE_SETTLING_TIME 2 -char shadowRxBuf[SHADOW_MAX_SIZE_OF_RX_BUFFER]; - -static JsonTokenTable_t tokenTable[MAX_JSON_TOKEN_EXPECTED]; -static uint32_t tokenTableIndex = 0; -static bool deltaTopicSubscribedFlag = false; -uint32_t shadowJsonVersionNum = 0; -bool shadowDiscardOldDeltaFlag = true; - -// local helper functions -static void AckStatusCallback(AWS_IoT_Client *pClient, char *topicName, - uint16_t topicNameLen, IoT_Publish_Message_Params *params, void *pData); - -static void shadow_delta_callback(AWS_IoT_Client *pClient, char *topicName, - uint16_t topicNameLen, IoT_Publish_Message_Params *params, void *pData); - -static void topicNameFromThingAndAction(char *pTopic, const char *pThingName, ShadowActions_t action, - ShadowAckTopicTypes_t ackType); - -static int16_t getNextFreeIndexOfSubscriptionList(void); - -static void unsubscribeFromAcceptedAndRejected(uint8_t index); - -void initDeltaTokens(void) { - uint32_t i; - for(i = 0; i < MAX_JSON_TOKEN_EXPECTED; i++) { - tokenTable[i].isFree = true; - } - tokenTableIndex = 0; - deltaTopicSubscribedFlag = false; -} - -IoT_Error_t registerJsonTokenOnDelta(jsonStruct_t *pStruct) { - - IoT_Error_t rc = SUCCESS; - - if(!deltaTopicSubscribedFlag) { - snprintf(shadowDeltaTopic, MAX_SHADOW_TOPIC_LENGTH_BYTES, "$aws/things/%s/shadow/update/delta", myThingName); - rc = aws_iot_mqtt_subscribe(pMqttClient, shadowDeltaTopic, (uint16_t) strlen(shadowDeltaTopic), QOS0, - shadow_delta_callback, NULL); - deltaTopicSubscribedFlag = true; - } - - if(tokenTableIndex >= MAX_JSON_TOKEN_EXPECTED) { - return FAILURE; - } - - tokenTable[tokenTableIndex].pKey = pStruct->pKey; - tokenTable[tokenTableIndex].callback = pStruct->cb; - tokenTable[tokenTableIndex].pStruct = pStruct; - tokenTable[tokenTableIndex].isFree = false; - tokenTableIndex++; - - return rc; -} - -static int16_t getNextFreeIndexOfSubscriptionList(void) { - uint8_t i; - for(i = 0; i < MAX_TOPICS_AT_ANY_GIVEN_TIME; i++) { - if(SubscriptionList[i].isFree) { - SubscriptionList[i].isFree = false; - return i; - } - } - return -1; -} - -static void topicNameFromThingAndAction(char *pTopic, const char *pThingName, ShadowActions_t action, - ShadowAckTopicTypes_t ackType) { - - char actionBuf[10]; - char ackTypeBuf[10]; - - if(SHADOW_GET == action) { - strncpy(actionBuf, "get", 10); - } else if(SHADOW_UPDATE == action) { - strncpy(actionBuf, "update", 10); - } else if(SHADOW_DELETE == action) { - strncpy(actionBuf, "delete", 10); - } - - if(SHADOW_ACCEPTED == ackType) { - strncpy(ackTypeBuf, "accepted", 10); - } else if(SHADOW_REJECTED == ackType) { - strncpy(ackTypeBuf, "rejected", 10); - } - - if(SHADOW_ACTION == ackType) { - snprintf(pTopic, MAX_SHADOW_TOPIC_LENGTH_BYTES, "$aws/things/%s/shadow/%s", pThingName, actionBuf); - } else { - snprintf(pTopic, MAX_SHADOW_TOPIC_LENGTH_BYTES, "$aws/things/%s/shadow/%s/%s", pThingName, actionBuf, - ackTypeBuf); - } -} - -static bool isValidShadowVersionUpdate(const char *pTopicName) { - if(strstr(pTopicName, myThingName) != NULL && - ((strstr(pTopicName, "get/accepted") != NULL) || - (strstr(pTopicName, "delta") != NULL))) { - return true; - } - return false; -} - -static void AckStatusCallback(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, - IoT_Publish_Message_Params *params, void *pData) { - int32_t tokenCount; - uint8_t i; - void *pJsonHandler = NULL; - char temporaryClientToken[MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE]; - - IOT_UNUSED(pClient); - IOT_UNUSED(topicNameLen); - IOT_UNUSED(pData); - - if(params->payloadLen >= SHADOW_MAX_SIZE_OF_RX_BUFFER) { - IOT_WARN("Payload larger than RX Buffer"); - return; - } - - memcpy(shadowRxBuf, params->payload, params->payloadLen); - shadowRxBuf[params->payloadLen] = '\0'; // jsmn_parse relies on a string - - if(!isJsonValidAndParse(shadowRxBuf, SHADOW_MAX_SIZE_OF_RX_BUFFER, pJsonHandler, &tokenCount)) { - IOT_WARN("Received JSON is not valid"); - return; - } - - if(isValidShadowVersionUpdate(topicName)) { - uint32_t tempVersionNumber = 0; - if(extractVersionNumber(shadowRxBuf, pJsonHandler, tokenCount, &tempVersionNumber)) { - if(tempVersionNumber > shadowJsonVersionNum) { - shadowJsonVersionNum = tempVersionNumber; - } - } - } - - if(extractClientToken(shadowRxBuf, SHADOW_MAX_SIZE_OF_RX_BUFFER, temporaryClientToken, MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE)) { - for(i = 0; i < MAX_ACKS_TO_COMEIN_AT_ANY_GIVEN_TIME; i++) { - if(!AckWaitList[i].isFree) { - if(strcmp(AckWaitList[i].clientTokenID, temporaryClientToken) == 0) { - Shadow_Ack_Status_t status = SHADOW_ACK_REJECTED; - if(strstr(topicName, "accepted") != NULL) { - status = SHADOW_ACK_ACCEPTED; - } else if(strstr(topicName, "rejected") != NULL) { - status = SHADOW_ACK_REJECTED; - } - if(status == SHADOW_ACK_ACCEPTED || status == SHADOW_ACK_REJECTED) { - if(AckWaitList[i].callback != NULL) { - AckWaitList[i].callback(AckWaitList[i].thingName, AckWaitList[i].action, status, - shadowRxBuf, AckWaitList[i].pCallbackContext); - } - unsubscribeFromAcceptedAndRejected(i); - AckWaitList[i].isFree = true; - return; - } - } - } - } - } -} - -static int16_t findIndexOfSubscriptionList(const char *pTopic) { - uint8_t i; - for(i = 0; i < MAX_TOPICS_AT_ANY_GIVEN_TIME; i++) { - if(!SubscriptionList[i].isFree) { - if((strcmp(pTopic, SubscriptionList[i].Topic) == 0)) { - return i; - } - } - } - return -1; -} - -static void unsubscribeFromAcceptedAndRejected(uint8_t index) { - - char TemporaryTopicNameAccepted[MAX_SHADOW_TOPIC_LENGTH_BYTES]; - char TemporaryTopicNameRejected[MAX_SHADOW_TOPIC_LENGTH_BYTES]; - IoT_Error_t ret_val = SUCCESS; - - int16_t indexSubList; - - topicNameFromThingAndAction(TemporaryTopicNameAccepted, AckWaitList[index].thingName, AckWaitList[index].action, - SHADOW_ACCEPTED); - topicNameFromThingAndAction(TemporaryTopicNameRejected, AckWaitList[index].thingName, AckWaitList[index].action, - SHADOW_REJECTED); - - indexSubList = findIndexOfSubscriptionList(TemporaryTopicNameAccepted); - if((indexSubList >= 0)) { - if(!SubscriptionList[indexSubList].isSticky && (SubscriptionList[indexSubList].count == 1)) { - ret_val = aws_iot_mqtt_unsubscribe(pMqttClient, TemporaryTopicNameAccepted, - (uint16_t) strlen(TemporaryTopicNameAccepted)); - if(ret_val == SUCCESS) { - SubscriptionList[indexSubList].isFree = true; - } - } else if(SubscriptionList[indexSubList].count > 1) { - SubscriptionList[indexSubList].count--; - } - } - - indexSubList = findIndexOfSubscriptionList(TemporaryTopicNameRejected); - if((indexSubList >= 0)) { - if(!SubscriptionList[indexSubList].isSticky && (SubscriptionList[indexSubList].count == 1)) { - ret_val = aws_iot_mqtt_unsubscribe(pMqttClient, TemporaryTopicNameRejected, - (uint16_t) strlen(TemporaryTopicNameRejected)); - if(ret_val == SUCCESS) { - SubscriptionList[indexSubList].isFree = true; - } - } else if(SubscriptionList[indexSubList].count > 1) { - SubscriptionList[indexSubList].count--; - } - } -} - -void initializeRecords(AWS_IoT_Client *pClient) { - uint8_t i; - for(i = 0; i < MAX_ACKS_TO_COMEIN_AT_ANY_GIVEN_TIME; i++) { - AckWaitList[i].isFree = true; - } - for(i = 0; i < MAX_TOPICS_AT_ANY_GIVEN_TIME; i++) { - SubscriptionList[i].isFree = true; - SubscriptionList[i].count = 0; - SubscriptionList[i].isSticky = false; - } - - pMqttClient = pClient; -} - -bool isSubscriptionPresent(const char *pThingName, ShadowActions_t action) { - - uint8_t i = 0; - bool isAcceptedPresent = false; - bool isRejectedPresent = false; - char TemporaryTopicNameAccepted[MAX_SHADOW_TOPIC_LENGTH_BYTES]; - char TemporaryTopicNameRejected[MAX_SHADOW_TOPIC_LENGTH_BYTES]; - - topicNameFromThingAndAction(TemporaryTopicNameAccepted, pThingName, action, SHADOW_ACCEPTED); - topicNameFromThingAndAction(TemporaryTopicNameRejected, pThingName, action, SHADOW_REJECTED); - - for(i = 0; i < MAX_TOPICS_AT_ANY_GIVEN_TIME; i++) { - if(!SubscriptionList[i].isFree) { - if((strcmp(TemporaryTopicNameAccepted, SubscriptionList[i].Topic) == 0)) { - isAcceptedPresent = true; - } else if((strcmp(TemporaryTopicNameRejected, SubscriptionList[i].Topic) == 0)) { - isRejectedPresent = true; - } - } - } - - if(isRejectedPresent && isAcceptedPresent) { - return true; - } - - return false; -} - -IoT_Error_t subscribeToShadowActionAcks(const char *pThingName, ShadowActions_t action, bool isSticky) { - IoT_Error_t ret_val = SUCCESS; - - bool clearBothEntriesFromList = true; - int16_t indexAcceptedSubList = 0; - int16_t indexRejectedSubList = 0; - Timer subSettlingtimer; - indexAcceptedSubList = getNextFreeIndexOfSubscriptionList(); - indexRejectedSubList = getNextFreeIndexOfSubscriptionList(); - - if(indexAcceptedSubList >= 0 && indexRejectedSubList >= 0) { - topicNameFromThingAndAction(SubscriptionList[indexAcceptedSubList].Topic, pThingName, action, SHADOW_ACCEPTED); - ret_val = aws_iot_mqtt_subscribe(pMqttClient, SubscriptionList[indexAcceptedSubList].Topic, - (uint16_t) strlen(SubscriptionList[indexAcceptedSubList].Topic), QOS0, - AckStatusCallback, NULL); - if(ret_val == SUCCESS) { - SubscriptionList[indexAcceptedSubList].count = 1; - SubscriptionList[indexAcceptedSubList].isSticky = isSticky; - topicNameFromThingAndAction(SubscriptionList[indexRejectedSubList].Topic, pThingName, action, - SHADOW_REJECTED); - ret_val = aws_iot_mqtt_subscribe(pMqttClient, SubscriptionList[indexRejectedSubList].Topic, - (uint16_t) strlen(SubscriptionList[indexRejectedSubList].Topic), QOS0, - AckStatusCallback, NULL); - if(ret_val == SUCCESS) { - SubscriptionList[indexRejectedSubList].count = 1; - SubscriptionList[indexRejectedSubList].isSticky = isSticky; - clearBothEntriesFromList = false; - - // wait for SUBSCRIBE_SETTLING_TIME seconds to let the subscription take effect - init_timer(&subSettlingtimer); - countdown_sec(&subSettlingtimer, SUBSCRIBE_SETTLING_TIME); - while(!has_timer_expired(&subSettlingtimer)); - - } - } - } - - if(clearBothEntriesFromList) { - if(indexAcceptedSubList >= 0) { - SubscriptionList[indexAcceptedSubList].isFree = true; - - if(SubscriptionList[indexAcceptedSubList].count == 1) { - aws_iot_mqtt_unsubscribe(pMqttClient, SubscriptionList[indexAcceptedSubList].Topic, - (uint16_t) strlen(SubscriptionList[indexAcceptedSubList].Topic)); - } - } - if(indexRejectedSubList >= 0) { - SubscriptionList[indexRejectedSubList].isFree = true; - } - - } - - return ret_val; -} - -void incrementSubscriptionCnt(const char *pThingName, ShadowActions_t action, bool isSticky) { - char TemporaryTopicNameAccepted[MAX_SHADOW_TOPIC_LENGTH_BYTES]; - char TemporaryTopicNameRejected[MAX_SHADOW_TOPIC_LENGTH_BYTES]; - uint8_t i; - topicNameFromThingAndAction(TemporaryTopicNameAccepted, pThingName, action, SHADOW_ACCEPTED); - topicNameFromThingAndAction(TemporaryTopicNameRejected, pThingName, action, SHADOW_REJECTED); - - for(i = 0; i < MAX_TOPICS_AT_ANY_GIVEN_TIME; i++) { - if(!SubscriptionList[i].isFree) { - if((strcmp(TemporaryTopicNameAccepted, SubscriptionList[i].Topic) == 0) - || (strcmp(TemporaryTopicNameRejected, SubscriptionList[i].Topic) == 0)) { - SubscriptionList[i].count++; - SubscriptionList[i].isSticky = isSticky; - } - } - } -} - -IoT_Error_t publishToShadowAction(const char *pThingName, ShadowActions_t action, const char *pJsonDocumentToBeSent) { - IoT_Error_t ret_val = SUCCESS; - char TemporaryTopicName[MAX_SHADOW_TOPIC_LENGTH_BYTES]; - IoT_Publish_Message_Params msgParams; - - if(NULL == pThingName || NULL == pJsonDocumentToBeSent) { - return NULL_VALUE_ERROR; - } - - topicNameFromThingAndAction(TemporaryTopicName, pThingName, action, SHADOW_ACTION); - - msgParams.qos = QOS0; - msgParams.isRetained = 0; - msgParams.payloadLen = strlen(pJsonDocumentToBeSent); - msgParams.payload = (char *) pJsonDocumentToBeSent; - ret_val = aws_iot_mqtt_publish(pMqttClient, TemporaryTopicName, (uint16_t) strlen(TemporaryTopicName), &msgParams); - - return ret_val; -} - -bool getNextFreeIndexOfAckWaitList(uint8_t *pIndex) { - uint8_t i; - bool rc = false; - - if(NULL == pIndex) { - return false; - } - - for(i = 0; i < MAX_ACKS_TO_COMEIN_AT_ANY_GIVEN_TIME; i++) { - if(AckWaitList[i].isFree) { - *pIndex = i; - rc = true; - break; - } - } - - return rc; -} - -void addToAckWaitList(uint8_t indexAckWaitList, const char *pThingName, ShadowActions_t action, - const char *pExtractedClientToken, fpActionCallback_t callback, void *pCallbackContext, - uint32_t timeout_seconds) { - AckWaitList[indexAckWaitList].callback = callback; - memcpy(AckWaitList[indexAckWaitList].clientTokenID, pExtractedClientToken, MAX_SIZE_CLIENT_ID_WITH_SEQUENCE); - memcpy(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, SHADOW_MAX_SIZE_OF_RX_BUFFER, 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/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/README.md b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/README.md deleted file mode 100644 index 3625bae68..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/README.md +++ /dev/null @@ -1,9 +0,0 @@ -# Tests -This folder contains tests to verify SDK functionality. These have been tested to work with Linux but haven't been ported to any specific platform. For additional information about porting the Device SDK for embedded C onto additional platforms please refer to the [PortingGuide](https://github.com/aws/aws-iot-device-sdk-embedded-c/blob/master/PortingGuide.md/). -A description for each folder is given below - -## integration -This folder contains integration tests that run directly against the server. For further information on how to run these tests check out the [Integration Test README](https://github.com/aws/aws-iot-device-sdk-embedded-c/blob/master/tests/integration/README.md/). - -## unit -This folder contains unit tests that test SDK functionality against a Mock TLS layer. They are built using the CppUTest testing framework. For further information on how to run these tests check out the [Unit Test README](https://github.com/aws/aws-iot-device-sdk-embedded-c/blob/master/tests/unit/README.md/). \ No newline at end of file diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/Makefile b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/Makefile deleted file mode 100644 index e18648941..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/Makefile +++ /dev/null @@ -1,108 +0,0 @@ -#This target is to ensure accidental execution of Makefile as a bash script will not execute commands like rm in unexpected directories and exit gracefully. -.prevent_execution: - exit 0 - -CC = gcc -RM = rm - -DEBUG = - -#IoT client directory -IOT_CLIENT_DIR = ../.. - -APP_DIR = $(IOT_CLIENT_DIR)/tests/integration -APP_NAME = integration_tests_mbedtls -MT_APP_NAME = integration_tests_mbedtls_mt -APP_SRC_FILES = $(shell find $(APP_DIR)/src/ -name '*.c') -MT_APP_SRC_FILES = $(shell find $(APP_DIR)/multithreadingTest/ -name '*.c') -APP_INCLUDE_DIRS = -I $(APP_DIR)/include - -PLATFORM_DIR = $(IOT_CLIENT_DIR)/platform/linux - -#MbedTLS directory -TEMP_MBEDTLS_SRC_DIR = $(IOT_CLIENT_DIR)/external_libs/mbedTLS -TLS_LIB_DIR = $(TEMP_MBEDTLS_SRC_DIR)/library -CRYPTO_LIB_DIR = $(TEMP_MBEDTLS_SRC_DIR)/library -TLS_INCLUDE_DIR = -I $(TEMP_MBEDTLS_SRC_DIR)/include - -EXTERNAL_LIBS += -L$(TLS_LIB_DIR) -LD_FLAG += -Wl,-rpath,$(TLS_LIB_DIR) -LD_FLAG += -ldl $(TLS_LIB_DIR)/libmbedtls.a $(CRYPTO_LIB_DIR)/libmbedcrypto.a $(TLS_LIB_DIR)/libmbedx509.a -lpthread - -# Logging level control -#LOG_FLAGS += -DENABLE_IOT_DEBUG -#LOG_FLAGS += -DENABLE_IOT_TRACE -#LOG_FLAGS += -DENABLE_IOT_INFO -LOG_FLAGS += -DENABLE_IOT_WARN -LOG_FLAGS += -DENABLE_IOT_ERROR -COMPILER_FLAGS += $(LOG_FLAGS) - -#IoT client directory -PLATFORM_COMMON_DIR = $(PLATFORM_DIR)/common -PLATFORM_THREAD_DIR = $(PLATFORM_DIR)/pthread -PLATFORM_NETWORK_DIR = $(PLATFORM_DIR)/mbedtls - -IOT_INCLUDE_DIRS = -I $(PLATFORM_COMMON_DIR) -IOT_INCLUDE_DIRS += -I $(PLATFORM_THREAD_DIR) -IOT_INCLUDE_DIRS += -I $(PLATFORM_NETWORK_DIR) -IOT_INCLUDE_DIRS += -I $(IOT_CLIENT_DIR)/include -IOT_INCLUDE_DIRS += -I $(IOT_CLIENT_DIR)/external_libs/jsmn - -IOT_SRC_FILES += $(shell find $(IOT_CLIENT_DIR)/src/ -name '*.c') -IOT_SRC_FILES += $(shell find $(IOT_CLIENT_DIR)/external_libs/jsmn/ -name '*.c') -IOT_SRC_FILES += $(shell find $(PLATFORM_NETWORK_DIR)/ -name '*.c') -IOT_SRC_FILES += $(shell find $(PLATFORM_COMMON_DIR)/ -name '*.c') -IOT_SRC_FILES += $(shell find $(PLATFORM_THREAD_DIR)/ -name '*.c') - -#Aggregate all include and src directories -INCLUDE_ALL_DIRS += $(IOT_INCLUDE_DIRS) -INCLUDE_ALL_DIRS += $(APP_INCLUDE_DIRS) -INCLUDE_ALL_DIRS += $(TLS_INCLUDE_DIR) - -SRC_FILES += $(APP_SRC_FILES) -SRC_FILES += $(IOT_SRC_FILES) - -MT_SRC_FILES += $(MT_APP_SRC_FILES) -MT_SRC_FILES += $(IOT_SRC_FILES) - -COMPILER_FLAGS += -g -COMPILER_FLAGS += $(LOG_FLAGS) -PRE_MAKE_CMDS += cd $(TEMP_MBEDTLS_SRC_DIR) && make - -MAKE_CMD = $(CC) $(SRC_FILES) $(COMPILER_FLAGS) -g3 -D_ENABLE_THREAD_SUPPORT_ -o $(APP_DIR)/$(APP_NAME) $(EXTERNAL_LIBS) $(LD_FLAG) $(INCLUDE_ALL_DIRS); -MAKE_MT_CMD = $(CC) $(MT_SRC_FILES) $(COMPILER_FLAGS) -g3 -D_ENABLE_THREAD_SUPPORT_ -o $(APP_DIR)/$(MT_APP_NAME) $(EXTERNAL_LIBS) $(LD_FLAG) $(INCLUDE_ALL_DIRS); - -ifeq ($(CODE_SIZE_ENABLE),Y) -POST_MAKE_CMDS += $(CC) -c $(SRC_FILES) $(INCLUDE_ALL_DIRS) -fstack-usage; -POST_MAKE_CMDS += (size --format=Berkeley *.o > $(APP_NAME)_size_info.txt); -POST_MAKE_CMDS += (cat *.su >> $(APP_NAME)_stack_usage.txt); -POST_MAKE_CMDS += ($(RM) *.o); -POST_MAKE_CMDS += ($(RM) *.su); -CLEAN_CMD += ($(RM) -f $(APP_NAME)_size_info.txt); -CLEAN_CMD += ($(RM) -f $(APP_NAME)_stack_usage.txt); -endif - -all: - $(PRE_MAKE_CMDS) - $(DEBUG)$(MAKE_CMD) - $(DEBUG)$(MAKE_MT_CMD) - ./$(APP_NAME) - ./$(MT_APP_NAME) - $(POST_MAKE_CMDS) - -app: - $(PRE_MAKE_CMDS) - $(DEBUG)$(MAKE_CMD) - $(DEBUG)$(MAKE_MT_CMD) - -tests: - ./$(APP_NAME) - ./$(MT_APP_NAME) - $(POST_MAKE_CMDS) - -clean: - $(RM) -f $(APP_DIR)/$(APP_NAME) - $(RM) -f $(APP_DIR)/$(MT_APP_NAME) - $(CLEAN_CMD) - -ALL_TARGETS_CLEAN += test-integration-assert-clean diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/README.md b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/README.md deleted file mode 100644 index b3ea04b25..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/README.md +++ /dev/null @@ -1,44 +0,0 @@ -## Integration Tests -This folder contains integration tests to verify Embedded C SDK functionality. These have been tested to work with Linux but haven't been ported to any specific platform. For additional information about porting the Device SDK for embedded C onto additional platforms please refer to the [PortingGuide](https://github.com/aws/aws-iot-device-sdk-embedded-c/blob/master/PortingGuide.md/). -To run these tests, follow the below steps: - - * Place device identity cert and private key in locations referenced in the `certs` folder - * Download certificate authority CA file from [Symantec](https://www.symantec.com/content/en/us/enterprise/verisign/roots/VeriSign-Class%203-Public-Primary-Certification-Authority-G5.pem) and place in `certs` folder - * Ensure the names of the cert files are the same as in the `aws_iot_config.h` file - * Ensure the certificate has an attached policy which allows the proper permissions for AWS IoT - * Update the Host endpoint in the `aws_iot_config.h` file - * Build the example using make. (''make''). The tests will run automatically as a part of the build process - * For more detailed Debug output, enable the IOT_DEBUG flag in `Logging level control` section of the Makefile. IOT_TRACE can be enabled as well for very detailed information on what functions are being executed - * More information on the each test is below - -### Integration test configuration -For all the tests below, there is additional configuration in the `integ_tests_config.h`. The configuration options are explained below: - - * PUBLISH_COUNT - Number of messages to publish in each publish thread - * MAX_PUB_THREAD_COUNT - Maximum number of threads to create for the multi-threading test - * RX_RECEIVE_PERCENTAGE - Minimum percentage of messages that must be received back by the yield thread. This is here ONLY because sometimes the yield thread doesn't get scheduled before the publish thread when it is created. In every other case, 100% messages should be received - * CONNECT_MAX_ATTEMPT_COUNT - Max number of initial connect retries - * THREAD_SLEEP_INTERVAL_USEC - Interval that each thread sleeps for - * INTEGRATION_TEST_TOPIC - Test topic to publish on - * INTEGRATION_TEST_CLIENT_ID - Client ID to be used for single client tests - * INTEGRATION_TEST_CLIENT_ID_PUB, INTEGRATION_TEST_CLIENT_ID_SUB - Client IDs to be used for multiple client tests - -### Test 1 - Basic Connectivity Test -This test verifies basic connectivity with the server. It creates one client instance and connects to the server. It subscribes to the Integration Test topic. Then it creates two threads, one publish thread and one yield thread. The publish thread publishes `PUBLISH_COUNT` messages on the test topic and the yield thread receives them. Once all the messages are published, the program waits for 1 sec to ensure all the messages have sufficient time to be received. -The test ends with the program verifying that all the messages were received and no other errors occurred. - -### Test 2 - Multiple Client Connectivity Test -This test verifies usage of multiple clients in the same application. It creates two client instances and both connect to the server. One client instance subscribes to the Integration Test topic. The other client instance publishes `PUBLISH_COUNT` messages on the test topic and the yield instance receives them. Once all the messages are published, the program waits for 1 sec to ensure all the messages have sufficient time to be received. -The test ends with the program verifying that all the messages were received and no other errors occurred. - -### Test 3 - Auto Reconnect Test -This test verifies Auto-reconnect functionality. It creates one client instance. Then it performs 3 separate tests - - * Tests the disconnect handler by causing a TLS layer disconnect. - * Tests manual reconnect API by causing a TLS layer disconnect with auto-reconnect disabled - * Lastly, it tests the Auto-reconnect API by enabling auto-reconnect. It renames the rootCA file to a different name to prevent immediate reconnect, verifies the error codes are returned properly and that the reconnect algorithm is running. Once that check is satisfied, it renames the rootCA file back to the original names and verifies the client was able to reconnect. - -### Test 4 - Multi-threading Validation Test -This test is used to validate thread-safe operations. This creates on client instance, one yield thread, one thread to test subscribe/unsubscribe behavior and MAX_PUB_THREAD_COUNT number of publish threads. Then it proceeds to publish PUBLISH_COUNT messages on the test topic from each publish thread. The subscribe/unsubscribe thread runs in the background constantly subscribing and unsubscribing to a second test topic. The yield threads records which messages were received. - -The test verifies whether all the messages that were published were received or not. It also checks for errors that could occur in multi-threaded scenarios. The test has been run with 10 threads sending 500 messages each and verified to be working fine. It can be used as a reference testing application to validate whether your use case will work with multi-threading enabled. diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/include/aws_iot_config.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/include/aws_iot_config.h deleted file mode 100644 index 5d249bfef..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/include/aws_iot_config.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://aws.amazon.com/apache2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -#ifndef SRC_SHADOW_IOT_SHADOW_CONFIG_H_ -#define SRC_SHADOW_IOT_SHADOW_CONFIG_H_ - -// Get from console -// ================================================= -#define AWS_IOT_MQTT_HOST "" ///< Customer specific MQTT HOST. The same will be used for Thing Shadow -#define AWS_IOT_MQTT_PORT 443 ///< 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 -#ifndef DISABLE_IOT_JOBS -#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. -#else -#define AWS_IOT_MQTT_RX_BUF_LEN 2048 -#endif -#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_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 - -// Shadow and Job common configs -#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_SIZE_OF_THING_NAME 30 ///< The Thing Name should not be bigger than this value. Modify this if the Thing Name needs to be bigger - -// Thing Shadow specific configs -#define SHADOW_MAX_SIZE_OF_RX_BUFFER 512 ///< Maximum size of the SHADOW buffer to store the received Shadow message -#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_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 - -// Job specific configs -#ifndef DISABLE_IOT_JOBS -#define MAX_SIZE_OF_JOB_ID 64 -#define MAX_JOB_JSON_TOKEN_EXPECTED 120 -#define MAX_SIZE_OF_JOB_REQUEST AWS_IOT_MQTT_TX_BUF_LEN - -#define MAX_JOB_TOPIC_LENGTH_WITHOUT_JOB_ID_OR_THING_NAME 40 -#define MAX_JOB_TOPIC_LENGTH_BYTES MAX_JOB_TOPIC_LENGTH_WITHOUT_JOB_ID_OR_THING_NAME + MAX_SIZE_OF_THING_NAME + MAX_SIZE_OF_JOB_ID + 2 -#endif - -// Auto Reconnect specific config -#define AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL 1000 ///< Minimum time before the First reconnect attempt is made as part of the exponential back-off algorithm -#define AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL 128000 ///< Maximum time interval after which exponential back-off will stop attempting to reconnect. - -#define DISABLE_METRICS false ///< Disable the collection of metrics by setting this to true - -// TLS configs -#define IOT_SSL_READ_TIMEOUT_MS 3 ///< Timeout associated with underlying socket of TLS connection (set by mbedtls_ssl_conf_read_timeout) -#define IOT_SSL_READ_RETRY_TIMEOUT_MS 10 ///< Minimum elapsed time before returning from iot_tls_read when pending data has not yet been received -#define IOT_SSL_WRITE_RETRY_TIMEOUT_MS 10 ///< Minimum elapsed time before returning from iot_tls_write when pending data has not yet been written - -#endif /* SRC_SHADOW_IOT_SHADOW_CONFIG_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/include/aws_iot_integ_tests_config.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/include/aws_iot_integ_tests_config.h deleted file mode 100644 index a10933806..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/include/aws_iot_integ_tests_config.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://aws.amazon.com/apache2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -#ifndef TESTS_INTEGRATION_INTEG_TESTS_CONFIG_H_ -#define TESTS_INTEGRATION_INTEG_TESTS_CONFIG_H_ - -/* Number of messages to publish in each publish thread */ -#define PUBLISH_COUNT 100 - -/* Maximum number of threads to create for the multi-threading test */ -#define MAX_PUB_THREAD_COUNT 3 - -/* Minimum percentage of messages that must be received back by the yield thread. - * This is here ONLY because sometimes the yield thread doesn't get scheduled before the publish - * thread when it is created. In every other case, 100% messages should be received. */ -#define RX_RECEIVE_PERCENTAGE 99.0f - -/* Max number of initial connect retries */ -#define CONNECT_MAX_ATTEMPT_COUNT 3 - -/* Interval that each thread sleeps for */ -#define THREAD_SLEEP_INTERVAL_USEC 500000 - -/* Test topic to publish on */ -#define INTEGRATION_TEST_TOPIC "Tests/Integration/EmbeddedC" - -/* Client ID to be used for single client tests */ -#define INTEGRATION_TEST_CLIENT_ID "EMB_C_SDK_INTEG_TESTER" - -/* Client IDs to be used for multiple client tests */ -#define INTEGRATION_TEST_CLIENT_ID_PUB "EMB_C_SDK_INTEG_TESTER_PUB" -#define INTEGRATION_TEST_CLIENT_ID_SUB "EMB_C_SDK_INTEG_TESTER_SUB" - -#endif /* TESTS_INTEGRATION_INTEG_TESTS_CONFIG_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/include/aws_iot_test_integration_common.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/include/aws_iot_test_integration_common.h deleted file mode 100644 index 39da671ce..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/include/aws_iot_test_integration_common.h +++ /dev/null @@ -1,43 +0,0 @@ - -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_test_integration_common.h - * @brief Integration Test common header - */ - -#ifndef TESTS_INTEGRATION_H_ -#define TESTS_INTEGRATION_H_ - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "aws_iot_mqtt_client_interface.h" -#include "aws_iot_log.h" -#include "aws_iot_integ_tests_config.h" -#include "aws_iot_config.h" - -int aws_iot_mqtt_tests_basic_connectivity(); -int aws_iot_mqtt_tests_multiple_clients(); -int aws_iot_mqtt_tests_auto_reconnect(); - -#endif /* TESTS_INTEGRATION_COMMON_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/multithreadingTest/aws_iot_test_multithreading_validation.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/multithreadingTest/aws_iot_test_multithreading_validation.c deleted file mode 100644 index 032661d4f..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/multithreadingTest/aws_iot_test_multithreading_validation.c +++ /dev/null @@ -1,362 +0,0 @@ -/* - * multithreadedTest.c - * - */ - -#include -#include -#include -#include -#include -#include -#include -#include -#include "aws_iot_mqtt_client_interface.h" -#include "aws_iot_log.h" - -#include "aws_iot_integ_tests_config.h" -#include "aws_iot_config.h" - -#define BUFFER_SIZE 100 - -static bool terminate_yield_thread; -static bool terminate_subUnsub_thread; - -static unsigned int countArray[MAX_PUB_THREAD_COUNT][PUBLISH_COUNT]; -static unsigned int rxMsgBufferTooBigCounter; -static unsigned int rxUnexpectedNumberCounter; -static unsigned int rePublishCount; -static unsigned int wrongYieldCount; -static unsigned int threadStatus[MAX_PUB_THREAD_COUNT]; - -typedef struct ThreadData { - int threadId; - AWS_IoT_Client *client; -} ThreadData; - -static void aws_iot_mqtt_tests_message_aggregator(AWS_IoT_Client *pClient, char *topicName, - uint16_t topicNameLen, IoT_Publish_Message_Params *params, void *pData) { - char tempBuf[BUFFER_SIZE]; - char *temp = NULL; - char *next_token; - unsigned int tempRow = 0, tempCol = 0; - - IoT_Error_t rc; - - IOT_UNUSED(pClient); - IOT_UNUSED(topicName); - IOT_UNUSED(topicNameLen); - IOT_UNUSED(pData); - - if(BUFFER_SIZE >= params->payloadLen) { - snprintf(tempBuf, params->payloadLen, params->payload); - printf("\n Message received : %s", tempBuf); - temp = strtok_r(tempBuf, " ,:", &next_token); - temp = strtok_r(NULL, " ,:", &next_token); - if(NULL == temp) { - return; - } - tempRow = atoi(temp); - temp = strtok_r(NULL, " ,:", &next_token); - temp = strtok_r(NULL, " ,:", &next_token); - - if(NULL == temp) { - return; - } - - tempCol = atoi(temp); - - if(((tempRow - 1) < MAX_PUB_THREAD_COUNT) && (tempCol < PUBLISH_COUNT)) { - countArray[tempRow - 1][tempCol]++; - } else { - IOT_ERROR(" \nUnexpected Thread : %d, Message : %d ", tempRow, tempCol); - rxUnexpectedNumberCounter++; - } - rc = aws_iot_mqtt_yield(pClient, 10); - if(MQTT_CLIENT_NOT_IDLE_ERROR != rc) { - IOT_ERROR("\n Yield succeeded in callback!!! Client state : %d Rc : %d\n", - aws_iot_mqtt_get_client_state(pClient), rc); - wrongYieldCount++; - } - } else { - rxMsgBufferTooBigCounter++; - } -} - -static void aws_iot_mqtt_tests_disconnect_callback_handler(AWS_IoT_Client *pClient, void *param) { - IOT_UNUSED(pClient); - IOT_UNUSED(param); -} - -static IoT_Error_t aws_iot_mqtt_tests_subscribe_to_test_topic(AWS_IoT_Client *pClient, QoS qos, struct timeval *pSubscribeTime) { - IoT_Error_t rc = SUCCESS; - struct timeval start, end; - - gettimeofday(&start, NULL); - rc = aws_iot_mqtt_subscribe(pClient, INTEGRATION_TEST_TOPIC, strlen(INTEGRATION_TEST_TOPIC), qos, - aws_iot_mqtt_tests_message_aggregator, NULL); - IOT_DEBUG(" Sub response : %d\n", rc); - gettimeofday(&end, NULL); - - timersub(&end, &start, pSubscribeTime); - - return rc; -} - -static void *aws_iot_mqtt_tests_yield_thread_runner(void *ptr) { - IoT_Error_t rc = SUCCESS; - AWS_IoT_Client *pClient = (AWS_IoT_Client *) ptr; - while(SUCCESS == rc && false == terminate_yield_thread) { - do { - usleep(THREAD_SLEEP_INTERVAL_USEC); - //DEBUG("\n Yielding \n"); - rc = aws_iot_mqtt_yield(pClient, 100); - } while(MQTT_CLIENT_NOT_IDLE_ERROR == rc); - - if(SUCCESS != rc) { - IOT_ERROR("\nYield Returned : %d ", rc); - } - } - - return NULL; -} - -static void *aws_iot_mqtt_tests_publish_thread_runner(void *ptr) { - int itr = 0; - char cPayload[100]; - IoT_Publish_Message_Params params; - IoT_Error_t rc = SUCCESS; - ThreadData *threadData = (ThreadData *) ptr; - AWS_IoT_Client *pClient = threadData->client; - int threadId = threadData->threadId; - - for(itr = 0; itr < PUBLISH_COUNT; itr++) { - snprintf(cPayload, 100, "%s_Thread : %d, Msg : %d", AWS_IOT_MY_THING_NAME, threadId, itr); - printf("\nMsg being published: %s \n", cPayload); - params.payload = (void *) cPayload; - params.payloadLen = strlen(cPayload) + 1; - params.qos = QOS1; - params.isRetained = 0; - - do { - rc = aws_iot_mqtt_publish(pClient, INTEGRATION_TEST_TOPIC, strlen(INTEGRATION_TEST_TOPIC), ¶ms); - usleep(THREAD_SLEEP_INTERVAL_USEC); - } while(MUTEX_LOCK_ERROR == rc || MQTT_CLIENT_NOT_IDLE_ERROR == rc); - if(SUCCESS != rc) { - IOT_WARN("\nFailed attempt 1 Publishing Thread : %d, Msg : %d, cs : %d --> %d\n ", threadId, itr, rc, - aws_iot_mqtt_get_client_state(pClient)); - do { - rc = aws_iot_mqtt_publish(pClient, INTEGRATION_TEST_TOPIC, strlen(INTEGRATION_TEST_TOPIC), ¶ms); - usleep(THREAD_SLEEP_INTERVAL_USEC); - } while(MUTEX_LOCK_ERROR == rc || MQTT_CLIENT_NOT_IDLE_ERROR == rc); - rePublishCount++; - if(SUCCESS != rc) { - IOT_ERROR("\nFailed attempt 2 Publishing Thread : %d, Msg : %d, cs : %d --> %d Second Attempt \n", threadId, - itr, rc, aws_iot_mqtt_get_client_state(pClient)); - } - } - } - threadStatus[threadId - 1] = 1; - return 0; - -} - -static void *aws_iot_mqtt_tests_sub_unsub_thread_runner(void *ptr) { - IoT_Error_t rc = SUCCESS; - AWS_IoT_Client *pClient = (AWS_IoT_Client *) ptr; - char testTopic[50]; - snprintf(testTopic, 50, "%s_temp", INTEGRATION_TEST_TOPIC); - while(SUCCESS == rc && false == terminate_subUnsub_thread) { - do { - usleep(THREAD_SLEEP_INTERVAL_USEC); - rc = aws_iot_mqtt_subscribe(pClient, testTopic, strlen(testTopic), QOS1, - aws_iot_mqtt_tests_message_aggregator, NULL); - } while(MQTT_CLIENT_NOT_IDLE_ERROR == rc); - - if(SUCCESS != rc) { - IOT_ERROR("Subscribe Returned : %d ", rc); - } - - do { - usleep(THREAD_SLEEP_INTERVAL_USEC); - rc = aws_iot_mqtt_unsubscribe(pClient, testTopic, strlen(testTopic)); - } while(MQTT_CLIENT_NOT_IDLE_ERROR == rc); - - if(SUCCESS != rc) { - IOT_ERROR("Unsubscribe Returned : %d ", rc); - } - } - - return NULL; -} - -int aws_iot_mqtt_tests_multi_threading_validation() { - pthread_t publish_thread[MAX_PUB_THREAD_COUNT], yield_thread, sub_unsub_thread; - char certDirectory[15] = "../../certs"; - char clientCRT[PATH_MAX + 1]; - char clientKey[PATH_MAX + 1]; - char CurrentWD[PATH_MAX + 1]; - char root_CA[PATH_MAX + 1]; - - char clientId[50]; - IoT_Client_Init_Params initParams = IoT_Client_Init_Params_initializer; - IoT_Client_Connect_Params connectParams; - int threadId[MAX_PUB_THREAD_COUNT]; - int pubThreadReturn[MAX_PUB_THREAD_COUNT]; - int yieldThreadReturn = 0, subUnsubThreadReturn = 0; - float percentOfRxMsg = 0.0; - int finishedThreadCount = 0; - IoT_Error_t rc = SUCCESS; - int i, rxMsgCount = 0, j = 0; - struct timeval subscribeTopic; - unsigned int connectCounter = 0; - int test_result = 0; - ThreadData threadData[MAX_PUB_THREAD_COUNT]; - AWS_IoT_Client client; - terminate_yield_thread = false; - rxMsgBufferTooBigCounter = 0; - rxUnexpectedNumberCounter = 0; - rePublishCount = 0; - wrongYieldCount = 0; - for(j = 0; j < MAX_PUB_THREAD_COUNT; j++) { - threadId[j] = j + 1; - threadStatus[j] = 0; - for(i = 0; i < PUBLISH_COUNT; i++) { - countArray[j][i] = 0; - } - } - - printf("\nConnecting Client "); - do { - getcwd(CurrentWD, sizeof(CurrentWD)); - snprintf(root_CA, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_ROOT_CA_FILENAME); - snprintf(clientCRT, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_CERTIFICATE_FILENAME); - snprintf(clientKey, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_PRIVATE_KEY_FILENAME); - srand((unsigned int)time(NULL)); - snprintf(clientId, 50, "%s_%d", INTEGRATION_TEST_CLIENT_ID, rand() % 10000); - - IOT_DEBUG(" Root CA Path : %s\n clientCRT : %s\n clientKey : %s\n", root_CA, clientCRT, clientKey); - initParams.pHostURL = AWS_IOT_MQTT_HOST; - initParams.port = AWS_IOT_MQTT_PORT; - initParams.pRootCALocation = root_CA; - initParams.pDeviceCertLocation = clientCRT; - initParams.pDevicePrivateKeyLocation = clientKey; - initParams.mqttCommandTimeout_ms = 10000; - initParams.tlsHandshakeTimeout_ms = 10000; - initParams.disconnectHandler = aws_iot_mqtt_tests_disconnect_callback_handler; - initParams.enableAutoReconnect = false; - initParams.isBlockOnThreadLockEnabled = true; - aws_iot_mqtt_init(&client, &initParams); - - connectParams.keepAliveIntervalInSec = 10; - connectParams.isCleanSession = true; - connectParams.MQTTVersion = MQTT_3_1_1; - connectParams.pClientID = (char *)&clientId; - connectParams.clientIDLen = strlen(clientId); - connectParams.isWillMsgPresent = false; - connectParams.pUsername = NULL; - connectParams.usernameLen = 0; - connectParams.pPassword = NULL; - connectParams.passwordLen = 0; - - rc = aws_iot_mqtt_connect(&client, &connectParams); - if(SUCCESS != rc) { - IOT_ERROR("ERROR Connecting %d\n", rc); - return -1; - } - - connectCounter++; - } while(SUCCESS != rc && connectCounter < CONNECT_MAX_ATTEMPT_COUNT); - - if(SUCCESS == rc) { - printf("\n## Connect Success.\n"); - } else { - IOT_ERROR("## Connect Failed. error code %d\n", rc); - return -1; - } - - aws_iot_mqtt_tests_subscribe_to_test_topic(&client, QOS1, &subscribeTopic); - - printf("\nRunning Test! "); - - yieldThreadReturn = pthread_create(&yield_thread, NULL, aws_iot_mqtt_tests_yield_thread_runner, &client); - subUnsubThreadReturn = pthread_create(&sub_unsub_thread, NULL, aws_iot_mqtt_tests_sub_unsub_thread_runner, &client); - - for(i = 0; i < MAX_PUB_THREAD_COUNT; i++) { - threadData[i].client = &client; - threadData[i].threadId = threadId[i]; - pubThreadReturn[i] = pthread_create(&publish_thread[i], NULL, aws_iot_mqtt_tests_publish_thread_runner, - &threadData[i]); - } - - /* Wait until all publish threads have finished */ - do { - finishedThreadCount = 0; - for(i = 0; i < MAX_PUB_THREAD_COUNT; i++) { finishedThreadCount += threadStatus[i]; } - printf("\nFinished thread count : %d \n", finishedThreadCount); - sleep(1); - } while(finishedThreadCount < MAX_PUB_THREAD_COUNT); - - printf("\nFinished publishing!!"); - - terminate_yield_thread = true; - terminate_subUnsub_thread = true; - pthread_join(yield_thread, NULL); - pthread_join(sub_unsub_thread, NULL); - - for(i = 0; i < MAX_PUB_THREAD_COUNT; i++) { - pthread_join(publish_thread[i], NULL); - } - - /* Not using pthread_join because all threads should have terminated gracefully at this point. If they haven't, - * which should not be possible, something below will fail. */ - - printf("\n\nCalculating Results!! \n\n"); - for(i = 0; i < PUBLISH_COUNT; i++) { - for(j = 0; j < MAX_PUB_THREAD_COUNT; j++) { - if(countArray[j][i] > 0) { - rxMsgCount++; - } - } - } - - printf("\n\nResult : \n"); - percentOfRxMsg = (float) rxMsgCount * 100 / (PUBLISH_COUNT * MAX_PUB_THREAD_COUNT); - if(RX_RECEIVE_PERCENTAGE <= percentOfRxMsg && 0 == rxMsgBufferTooBigCounter && 0 == rxUnexpectedNumberCounter && - 0 == wrongYieldCount) { - printf("\nSuccess: %f \%\n", percentOfRxMsg); - printf("Published Messages: %d , Received Messages: %d \n", PUBLISH_COUNT * MAX_PUB_THREAD_COUNT, rxMsgCount); - printf("QoS 1 re publish count %d\n", rePublishCount); - printf("Connection Attempts %d\n", connectCounter); - printf("Yield count without error during callback %d\n", wrongYieldCount); - test_result = 0; - } else { - printf("\nFailure: %f\n", percentOfRxMsg); - printf("\"Received message was too big than anything sent\" count: %d\n", rxMsgBufferTooBigCounter); - printf("\"The number received is out of the range\" count: %d\n", rxUnexpectedNumberCounter); - printf("Yield count without error during callback %d\n", wrongYieldCount); - test_result = -2; - } - aws_iot_mqtt_disconnect(&client); - return test_result; -} - -int main() { - printf("\n\n"); - printf("******************************************************************\n"); - printf("* Starting MQTT Version 3.1.1 Multithreading Validation Test *\n"); - printf("******************************************************************\n"); - int rc = aws_iot_mqtt_tests_multi_threading_validation(); - if(0 != rc) { - printf("\n*******************************************************************\n"); - printf("*MQTT Version 3.1.1 Multithreading Validation Test FAILED! RC : %d \n", rc); - printf("*******************************************************************\n"); - return 1; - } - - printf("******************************************************************\n"); - printf("* MQTT Version 3.1.1 Multithreading Validation Test SUCCESS!! *\n"); - printf("******************************************************************\n"); - - return 0; -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_auto_reconnect.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_auto_reconnect.c deleted file mode 100644 index 267d9dc05..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_auto_reconnect.c +++ /dev/null @@ -1,236 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_test_auto_reconnect.c - * @brief Integration Test for automatic reconnect - */ - -#include "aws_iot_test_integration_common.h" - -static char ModifiedPathBuffer[PATH_MAX + 1]; -char root_CA[PATH_MAX + 1]; - -bool terminate_yield_with_rc_thread = false; -IoT_Error_t yieldRC; -bool captureYieldReturnCode = false; -char * dummyLocation = "dummyLocation"; -char * savedLocation; -/** - * This function renames the rootCA.crt file to a temporary name to cause connect failure - */ -void aws_iot_mqtt_tests_block_tls_connect(AWS_IoT_Client *pClient) { - savedLocation = pClient->networkStack.tlsConnectParams.pRootCALocation; - pClient->networkStack.tlsConnectParams.pRootCALocation = dummyLocation; -} - -/** - * Always ensure this function is called after block_tls_connect - */ -void aws_iot_mqtt_tests_unblock_tls_connect(AWS_IoT_Client *pClient) { - pClient->networkStack.tlsConnectParams.pRootCALocation = savedLocation; -} - -void *aws_iot_mqtt_tests_yield_with_rc(void *ptr) { - IoT_Error_t rc = SUCCESS; - - struct timeval start, end, result; - static int cntr = 0; - AWS_IoT_Client *pClient = (AWS_IoT_Client *) ptr; - - while(terminate_yield_with_rc_thread == false - && (NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc)) { - usleep(500000); - printf(" Client state : %d ", aws_iot_mqtt_get_client_state(pClient)); - rc = aws_iot_mqtt_yield(pClient, 100); - printf("yield rc %d\n", rc); - if(captureYieldReturnCode && SUCCESS != rc) { - printf("yield rc capture %d\n", rc); - captureYieldReturnCode = false; - yieldRC = rc; - } - } - - return NULL; -} - -unsigned int disconnectedCounter = 0; - -void aws_iot_mqtt_tests_disconnect_callback_handler(AWS_IoT_Client *pClient, void *param) { - disconnectedCounter++; -} - -int aws_iot_mqtt_tests_auto_reconnect() { - pthread_t reconnectTester_thread, yield_thread; - int yieldThreadReturn = 0; - int test_result = 0; - - char certDirectory[15] = "../../certs"; - char CurrentWD[PATH_MAX + 1]; - char clientCRT[PATH_MAX + 1]; - char clientKey[PATH_MAX + 1]; - char clientId[50]; - AWS_IoT_Client client; - - IoT_Error_t rc = SUCCESS; - getcwd(CurrentWD, sizeof(CurrentWD)); - snprintf(root_CA, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_ROOT_CA_FILENAME); - snprintf(clientCRT, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_CERTIFICATE_FILENAME); - snprintf(clientKey, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_PRIVATE_KEY_FILENAME); - srand((unsigned int) time(NULL)); - snprintf(clientId, 50, "%s_%d", INTEGRATION_TEST_CLIENT_ID, rand() % 10000); - - printf(" Root CA Path : %s\n clientCRT : %s\n clientKey : %s\n", root_CA, clientCRT, clientKey); - IoT_Client_Init_Params initParams = IoT_Client_Init_Params_initializer; - initParams.pHostURL = AWS_IOT_MQTT_HOST; - initParams.port = AWS_IOT_MQTT_PORT; - initParams.pRootCALocation = root_CA; - initParams.pDeviceCertLocation = clientCRT; - initParams.pDevicePrivateKeyLocation = clientKey; - initParams.mqttCommandTimeout_ms = 20000; - initParams.tlsHandshakeTimeout_ms = 5000; - initParams.disconnectHandler = aws_iot_mqtt_tests_disconnect_callback_handler; - initParams.enableAutoReconnect = false; - aws_iot_mqtt_init(&client, &initParams); - - IoT_Client_Connect_Params connectParams; - connectParams.keepAliveIntervalInSec = 5; - connectParams.isCleanSession = true; - connectParams.MQTTVersion = MQTT_3_1_1; - connectParams.pClientID = (char *) &clientId; - connectParams.clientIDLen = strlen(clientId); - connectParams.isWillMsgPresent = 0; - connectParams.pUsername = NULL; - connectParams.usernameLen = 0; - connectParams.pPassword = NULL; - connectParams.passwordLen = 0; - - rc = aws_iot_mqtt_connect(&client, &connectParams); - if(rc != SUCCESS) { - printf("ERROR Connecting %d\n", rc); - return -1; - } - - yieldThreadReturn = pthread_create(&yield_thread, NULL, aws_iot_mqtt_tests_yield_with_rc, &client); - - /* - * Test disconnect handler - */ - printf("1. Test Disconnect Handler\n"); - aws_iot_mqtt_tests_block_tls_connect(&client); - iot_tls_disconnect(&(client.networkStack)); - sleep(connectParams.keepAliveIntervalInSec + 1); - if(disconnectedCounter == 1) { - printf("Success invoking Disconnect Handler\n"); - } else { - aws_iot_mqtt_tests_unblock_tls_connect(&client); - printf("Failure to invoke Disconnect Handler\n"); - return -1; - } - - terminate_yield_with_rc_thread = true; - pthread_join(yield_thread, NULL); - aws_iot_mqtt_tests_unblock_tls_connect(&client); - - /* - * Manual Reconnect Test - */ - printf("2. Test Manual Reconnect, Current Client state : %d \n", aws_iot_mqtt_get_client_state(&client)); - rc = aws_iot_mqtt_attempt_reconnect(&client); - if(rc != NETWORK_RECONNECTED) { - printf("ERROR reconnecting manually %d\n", rc); - return -4; - } - terminate_yield_with_rc_thread = false; - yieldThreadReturn = pthread_create(&yield_thread, NULL, aws_iot_mqtt_tests_yield_with_rc, &client); - - yieldRC = FAILURE; - captureYieldReturnCode = true; - - // ensure atleast 1 cycle of yield is executed to get the yield status to SUCCESS - sleep(1); - if(!captureYieldReturnCode) { - if(yieldRC == NETWORK_ATTEMPTING_RECONNECT) { - printf("Success reconnecting manually\n"); - } else { - printf("Failure to reconnect manually\n"); - return -3; - } - } - terminate_yield_with_rc_thread = true; - pthread_join(yield_thread, NULL); - - /* - * Auto Reconnect Test - */ - - printf("3. Test Auto_reconnect \n"); - - rc = aws_iot_mqtt_autoreconnect_set_status(&client, true); - if(rc != SUCCESS) { - printf("Error: Failed to enable auto-reconnect %d \n", rc); - } - - yieldRC = FAILURE; - captureYieldReturnCode = true; - - // Disconnect - aws_iot_mqtt_tests_block_tls_connect(&client); - iot_tls_disconnect(&(client.networkStack)); - - terminate_yield_with_rc_thread = false; - yieldThreadReturn = pthread_create(&yield_thread, NULL, aws_iot_mqtt_tests_yield_with_rc, &client); - - sleep(connectParams.keepAliveIntervalInSec + 1); - if(!captureYieldReturnCode) { - if(yieldRC == NETWORK_ATTEMPTING_RECONNECT) { - printf("Success attempting reconnect\n"); - } else { - printf("Failure to attempt to reconnect\n"); - return -6; - } - } - if(disconnectedCounter == 2) { - printf("Success: disconnect handler invoked on enabling auto-reconnect\n"); - } else { - printf("Failure: disconnect handler not invoked on enabling auto-reconnect : %d\n", disconnectedCounter); - return -7; - } - aws_iot_mqtt_tests_unblock_tls_connect(&client); - sleep(connectParams.keepAliveIntervalInSec + 1); - captureYieldReturnCode = true; - sleep(connectParams.keepAliveIntervalInSec + 1); - if(!captureYieldReturnCode) { - if(yieldRC == SUCCESS) { - printf("Success attempting reconnect\n"); - } else { - printf("Failure to attempt to reconnect\n"); - return -6; - } - } - - terminate_yield_with_rc_thread = true; - pthread_join(yield_thread, NULL); - - if(true == aws_iot_mqtt_is_client_connected(&client)) { - printf("Success: is Mqtt connected api\n"); - } else { - printf("Failure: is Mqtt Connected api\n"); - return -7; - } - - rc = aws_iot_mqtt_disconnect(&client); - return rc; -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_basic_connectivity.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_basic_connectivity.c deleted file mode 100644 index 8d08980ee..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_basic_connectivity.c +++ /dev/null @@ -1,281 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_test_basic_connectivity.c - * @brief Integration Test for basic client connectivity - */ - -#include "aws_iot_test_integration_common.h" - -#define BUFFER_SIZE 100 - -static bool terminate_yield_thread; - -static unsigned int countArray[PUBLISH_COUNT]; -static unsigned int rxMsgBufferTooBigCounter; -static unsigned int rxUnexpectedNumberCounter; -static unsigned int rePublishCount; -static unsigned int wrongYieldCount; - -typedef struct ThreadData { - AWS_IoT_Client *client; - int threadId; -} ThreadData; - -static void aws_iot_mqtt_tests_message_aggregator(AWS_IoT_Client *pClient, char *topicName, - uint16_t topicNameLen, IoT_Publish_Message_Params *params, void *pData) { - char tempBuf[BUFFER_SIZE]; - char *next_token; - char *temp = NULL; - unsigned int tempRow = 0, tempCol = 0; - IoT_Error_t rc; - - if(params->payloadLen <= BUFFER_SIZE) { - snprintf(tempBuf, params->payloadLen, params->payload); - printf("\nMsg received : %s", tempBuf); - temp = strtok_r(tempBuf, " ,:", &next_token); - temp = strtok_r(NULL, " ,:", &next_token); - if(NULL == temp) { - return; - } - tempRow = atoi(temp); - temp = strtok_r(NULL, " ,:", &next_token); - temp = strtok_r(NULL, " ,:", &next_token); - if(NULL == temp) { - return; - } - - tempCol = atoi(temp); - - if(tempCol > 0 && tempCol <= PUBLISH_COUNT) { - countArray[tempCol - 1]++; - } else { - IOT_WARN(" \n Thread : %d, Msg : %d ", tempRow, tempCol); - rxUnexpectedNumberCounter++; - } - rc = aws_iot_mqtt_yield(pClient, 10); - if(MQTT_CLIENT_NOT_IDLE_ERROR != rc) { - IOT_ERROR("\n Yield succeeded in callback!!! Client state : %d Rc : %d\n", - aws_iot_mqtt_get_client_state(pClient), rc); - wrongYieldCount++; - } - } else { - rxMsgBufferTooBigCounter++; - } -} - -static void aws_iot_mqtt_tests_disconnect_callback_handler(AWS_IoT_Client *pClient, void *param) { -} - -static IoT_Error_t aws_iot_mqtt_tests_subscribe_to_test_topic(AWS_IoT_Client *pClient, QoS qos, - struct timeval *pSubscribeTime) { - IoT_Error_t rc = SUCCESS; - struct timeval start, end; - - gettimeofday(&start, NULL); - rc = aws_iot_mqtt_subscribe(pClient, INTEGRATION_TEST_TOPIC, strlen(INTEGRATION_TEST_TOPIC), qos, - aws_iot_mqtt_tests_message_aggregator, NULL); - IOT_DEBUG("Sub response : %d\n", rc); - gettimeofday(&end, NULL); - - timersub(&end, &start, pSubscribeTime); - - return rc; -} - -static void *aws_iot_mqtt_tests_yield_thread_runner(void *ptr) { - IoT_Error_t rc = SUCCESS; - AWS_IoT_Client *pClient = (AWS_IoT_Client *) ptr; - while(SUCCESS == rc && terminate_yield_thread == false) { - do { - usleep(THREAD_SLEEP_INTERVAL_USEC); - rc = aws_iot_mqtt_yield(pClient, 100); - } while(MQTT_CLIENT_NOT_IDLE_ERROR == rc); // Client is busy, wait to get lock - - if(SUCCESS != rc) { - IOT_DEBUG("\nYield Returned : %d ", rc); - } - } - - return NULL; -} - -static void *aws_iot_mqtt_tests_publish_thread_runner(void *ptr) { - int i = 0; - char cPayload[100]; - IoT_Publish_Message_Params params; - IoT_Error_t rc = SUCCESS; - ThreadData *threadData = (ThreadData *) ptr; - AWS_IoT_Client *pClient = threadData->client; - int threadId = threadData->threadId; - - for(i = 0; i < PUBLISH_COUNT; i++) { - snprintf(cPayload, 100, "%s_Thread : %d, Msg : %d", AWS_IOT_MY_THING_NAME, threadId, i + 1); - printf("\nMsg being published: %s \n", cPayload); - params.payload = (void *) cPayload; - params.payloadLen = strlen(cPayload) + 1; - params.qos = QOS1; - params.isRetained = 0; - - do { - rc = aws_iot_mqtt_publish(pClient, INTEGRATION_TEST_TOPIC, strlen(INTEGRATION_TEST_TOPIC), ¶ms); - usleep(THREAD_SLEEP_INTERVAL_USEC); - } while(MUTEX_LOCK_ERROR == rc || MQTT_CLIENT_NOT_IDLE_ERROR == rc); - if(rc != SUCCESS) { - IOT_WARN("Error Publishing #%d --> %d\n ", i, rc); - do { - rc = aws_iot_mqtt_publish(pClient, INTEGRATION_TEST_TOPIC, strlen(INTEGRATION_TEST_TOPIC), ¶ms); - usleep(THREAD_SLEEP_INTERVAL_USEC); - } while(MUTEX_LOCK_ERROR == rc || MQTT_CLIENT_NOT_IDLE_ERROR == rc); - rePublishCount++; - if(rc != SUCCESS) { - IOT_ERROR("Error Publishing #%d --> %d Second Attempt \n", i, rc); - } - } - } - return 0; -} - -int aws_iot_mqtt_tests_basic_connectivity() { - pthread_t publish_thread, yield_thread; - char certDirectory[15] = "../../certs"; - char clientCRT[PATH_MAX + 1]; - char root_CA[PATH_MAX + 1]; - char clientKey[PATH_MAX + 1]; - char CurrentWD[PATH_MAX + 1]; - char clientId[50]; - IoT_Client_Init_Params initParams; - IoT_Client_Connect_Params connectParams; - int pubThreadReturn; - int yieldThreadReturn = 0; - float percentOfRxMsg = 0.0; - IoT_Error_t rc = SUCCESS; - int i, rxMsgCount = 0, j = 0; - struct timeval connectTime, subscribeTopic; - struct timeval start, end; - unsigned int connectCounter = 0; - int test_result = 0; - ThreadData threadData; - AWS_IoT_Client client; - - terminate_yield_thread = false; - - rxMsgBufferTooBigCounter = 0; - rxUnexpectedNumberCounter = 0; - rePublishCount = 0; - wrongYieldCount = 0; - for(i = 0; i < PUBLISH_COUNT; i++) { - countArray[i] = 0; - } - - IOT_DEBUG("\nConnecting Client "); - do { - getcwd(CurrentWD, sizeof(CurrentWD)); - snprintf(root_CA, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_ROOT_CA_FILENAME); - snprintf(clientCRT, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_CERTIFICATE_FILENAME); - snprintf(clientKey, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_PRIVATE_KEY_FILENAME); - srand((unsigned int)time(NULL)); - snprintf(clientId, 50, "%s_%d", INTEGRATION_TEST_CLIENT_ID, rand() % 10000); - - printf("\n\nClient ID : %s \n", clientId); - - IOT_DEBUG("Root CA Path : %s\n clientCRT : %s\n clientKey : %s\n", root_CA, clientCRT, clientKey); - initParams.pHostURL = AWS_IOT_MQTT_HOST; - initParams.port = AWS_IOT_MQTT_PORT; - initParams.pRootCALocation = root_CA; - initParams.pDeviceCertLocation = clientCRT; - initParams.pDevicePrivateKeyLocation = clientKey; - initParams.mqttCommandTimeout_ms = 10000; - initParams.tlsHandshakeTimeout_ms = 10000; - initParams.mqttPacketTimeout_ms = 5000; - initParams.isSSLHostnameVerify = true; - initParams.disconnectHandlerData = NULL; - initParams.isBlockOnThreadLockEnabled = true; - initParams.disconnectHandler = aws_iot_mqtt_tests_disconnect_callback_handler; - initParams.enableAutoReconnect = false; - aws_iot_mqtt_init(&client, &initParams); - - connectParams.keepAliveIntervalInSec = 10; - connectParams.isCleanSession = true; - connectParams.MQTTVersion = MQTT_3_1_1; - connectParams.pClientID = (char *)&clientId; - connectParams.clientIDLen = strlen(clientId); - connectParams.isWillMsgPresent = false; - connectParams.pUsername = NULL; - connectParams.usernameLen = 0; - connectParams.pPassword = NULL; - connectParams.passwordLen = 0; - - gettimeofday(&start, NULL); - rc = aws_iot_mqtt_connect(&client, &connectParams); - gettimeofday(&end, NULL); - timersub(&end, &start, &connectTime); - - connectCounter++; - } while(rc != SUCCESS && connectCounter < CONNECT_MAX_ATTEMPT_COUNT); - - if(SUCCESS == rc) { - IOT_DEBUG("## Connect Success. Time sec: %d, usec: %d\n", connectTime.tv_sec, connectTime.tv_usec); - } else { - IOT_ERROR("## Connect Failed. error code %d\n", rc); - return -1; - } - - aws_iot_mqtt_tests_subscribe_to_test_topic(&client, QOS1, &subscribeTopic); - - yieldThreadReturn = pthread_create(&yield_thread, NULL, aws_iot_mqtt_tests_yield_thread_runner, &client); - sleep(1); - - threadData.client = &client; - threadData.threadId = 1; - pubThreadReturn = pthread_create(&publish_thread, NULL, aws_iot_mqtt_tests_publish_thread_runner, &threadData); - - pthread_join(publish_thread, NULL); - // This sleep is to ensure that the last publish message has enough time to be received by us - sleep(1); - - terminate_yield_thread = true; - pthread_join(yield_thread, NULL); - - /* Not using pthread_join because all threads should have terminated gracefully at this point. If they haven't, - * which should not be possible, something below will fail. */ - - for(i = 0; i < PUBLISH_COUNT; i++) { - if(countArray[i] > 0) { - rxMsgCount++; - } - } - - IOT_DEBUG("\n\nResult : \n"); - percentOfRxMsg = (float) rxMsgCount * 100 / PUBLISH_COUNT; - if(percentOfRxMsg >= RX_RECEIVE_PERCENTAGE && rxMsgBufferTooBigCounter == 0 && rxUnexpectedNumberCounter == 0 && - wrongYieldCount == 0) { - IOT_DEBUG("\n\nSuccess: %f \%\n", percentOfRxMsg); - IOT_DEBUG("Published Messages: %d , Received Messages: %d \n", PUBLISH_COUNT, rxMsgCount); - IOT_DEBUG("QoS 1 re publish count %d\n", rePublishCount); - IOT_DEBUG("Connection Attempts %d\n", connectCounter); - IOT_DEBUG("Yield count without error during callback %d\n", wrongYieldCount); - test_result = 0; - } else { - IOT_ERROR("\n\nFailure: %f\n", percentOfRxMsg); - IOT_ERROR("\"Received message was too big than anything sent\" count: %d\n", rxMsgBufferTooBigCounter); - IOT_ERROR("\"The number received is out of the range\" count: %d\n", rxUnexpectedNumberCounter); - IOT_ERROR("Yield count without error during callback %d\n", wrongYieldCount); - test_result = -2; - } - aws_iot_mqtt_disconnect(&client); - return test_result; -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_integration_runner.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_integration_runner.c deleted file mode 100644 index 61ec00fab..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_integration_runner.c +++ /dev/null @@ -1,91 +0,0 @@ -/* -* Copyright 2015-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_test_integration_runner.c - * @brief Integration Test runner - */ - -#include "aws_iot_test_integration_common.h" - -int main() { - int rc = 0; - - printf("\n\n"); - printf("*************************************************************************************************\n"); - printf("* Starting TEST 1 MQTT Version 3.1.1 Basic Subscribe QoS 1 Publish QoS 1 with Single Client *\n"); - printf("*************************************************************************************************\n"); - rc = aws_iot_mqtt_tests_basic_connectivity(); - if(0 != rc) { - printf("\n********************************************************************************************************\n"); - printf("* TEST 1 MQTT Version 3.1.1 Basic Subscribe QoS 1 Publish QoS 1 with Single Client FAILED! RC : %4d *\n", rc); - printf("********************************************************************************************************\n"); - return 1; - } - printf("\n*************************************************************************************************\n"); - printf("* TEST 1 MQTT Version 3.1.1 Basic Subscribe QoS 1 Publish QoS 1 with Single Client SUCCESS!! *\n"); - printf("*************************************************************************************************\n"); - - printf("\n\n"); - printf("************************************************************************************************************\n"); - printf("* Starting TEST 2 MQTT Version 3.1.1 Multithreaded Subscribe QoS 1 Publish QoS 1 with Multiple Clients *\n"); - printf("************************************************************************************************************\n"); - rc = aws_iot_mqtt_tests_multiple_clients(); - if(0 != rc) { - printf("\n*******************************************************************************************************************\n"); - printf("* TEST 2 MQTT Version 3.1.1 Multithreaded Subscribe QoS 1 Publish QoS 1 with Multiple Clients FAILED! RC : %4d *\n", rc); - printf("*******************************************************************************************************************\n"); - return 1; - } - printf("\n*************************************************************************************************************\n"); - printf("* TEST 2 MQTT Version 3.1.1 Multithreaded Subscribe QoS 1 Publish QoS 1 with Multiple Clients SUCCESS!! *\n"); - printf("*************************************************************************************************************\n"); - - printf("\n\n"); - printf("*********************************************************\n"); - printf("* Starting TEST 3 MQTT Version 3.1.1 Auto Reconnect *\n"); - printf("*********************************************************\n"); - rc = aws_iot_mqtt_tests_auto_reconnect(); - if(0 != rc) { - printf("\n***************************************************************\n"); - printf("* TEST 3 MQTT Version 3.1.1 Auto Reconnect FAILED! RC : %4d *\n", rc); - printf("***************************************************************\n"); - return 1; - } - printf("\n**********************************************************\n"); - printf("* TEST 3 MQTT Version 3.1.1 Auto Reconnect SUCCESS!! *\n"); - printf("**********************************************************\n"); - -#ifndef DISABLE_IOT_JOBS -#ifndef DISABLE_IOT_JOBS_INTERFACE - printf("\n\n"); - printf("*************************************************************************************************\n"); - printf("* Starting TEST 4 Jobs API Test *\n"); - printf("*************************************************************************************************\n"); - rc = aws_iot_jobs_basic_test(); - if(0 != rc) { - printf("\n********************************************************************************************************\n"); - printf("* TEST 4 Jobs API Test FAILED! RC : %4d *\n", rc); - printf("********************************************************************************************************\n"); - return 1; - } - printf("\n*************************************************************************************************\n"); - printf("* TEST 4 Jobs API Test SUCCESS!! *\n"); - printf("*************************************************************************************************\n"); -#endif -#endif - - return 0; -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_jobs_api.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_jobs_api.c deleted file mode 100644 index 4974eb857..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_jobs_api.c +++ /dev/null @@ -1,284 +0,0 @@ -/* -* Copyright 2015-2018 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 DISABLE_IOT_JOBS -#ifndef DISABLE_IOT_JOBS_INTERFACE - -#include "aws_iot_test_integration_common.h" -#include -#include -#include -#include -#include - -static AWS_IoT_Client client; - -static jsmn_parser jsonParser; -static jsmntok_t jsonTokenStruct[MAX_JSON_TOKEN_EXPECTED]; -static int32_t tokenCount; - -static void aws_iot_mqtt_tests_disconnect_callback_handler(AWS_IoT_Client *pClient, void *param) { -} - -void iot_get_pending_callback_handler(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, - IoT_Publish_Message_Params *params, void *pData) { - IoT_Error_t rc = SUCCESS; - char topicToPublishGetNext[MAX_JOB_TOPIC_LENGTH_BYTES]; - - IOT_UNUSED(pData); - IOT_UNUSED(pClient); - IOT_INFO("\nJOB_GET_PENDING_TOPIC callback"); - IOT_INFO("topic: %.*s", topicNameLen, topicName); - IOT_INFO("payload: %.*s", (int) params->payloadLen, (char *)params->payload); - - jsmn_init(&jsonParser); - - tokenCount = jsmn_parse(&jsonParser, params->payload, (int) params->payloadLen, jsonTokenStruct, MAX_JSON_TOKEN_EXPECTED); - - if(tokenCount < 0) { - IOT_WARN("Failed to parse JSON: %d", tokenCount); - return; - } - - /* Assume the top-level element is an object */ - if(tokenCount < 1 || jsonTokenStruct[0].type != JSMN_OBJECT) { - IOT_WARN("Top Level is not an object"); - return; - } - - jsmntok_t *jobs; - - jobs = findToken("inProgressJobs", params->payload, jsonTokenStruct); - - if (jobs) { - IOT_INFO("inProgressJobs: %.*s", jobs->end - jobs->start, (char *)params->payload + jobs->start); - } - - jobs = findToken("queuedJobs", params->payload, jsonTokenStruct); - - if (jobs) { - IOT_INFO("queuedJobs: %.*s", jobs->end - jobs->start, (char *)params->payload + jobs->start); - } - - AwsIotDescribeJobExecutionRequest describeRequest; - describeRequest.executionNumber = 0; - describeRequest.includeJobDocument = true; - describeRequest.clientToken = NULL; - - rc = aws_iot_jobs_describe(&client, QOS0, AWS_IOT_MY_THING_NAME, JOB_ID_NEXT, &describeRequest, topicToPublishGetNext, sizeof(topicToPublishGetNext), NULL, 0); -} - -void iot_next_job_callback_handler(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, - IoT_Publish_Message_Params *params, void *pData) { - char topicToPublishUpdate[MAX_JOB_TOPIC_LENGTH_BYTES]; - char messageBuffer[200]; - - IOT_UNUSED(pClient); - IOT_INFO("\nJOB_NOTIFY_NEXT_TOPIC / JOB_DESCRIBE_TOPIC($next) callback"); - IOT_INFO("topic: %.*s", topicNameLen, topicName); - IOT_INFO("payload: %.*s", (int) params->payloadLen, (char *)params->payload); - - jsmn_init(&jsonParser); - - tokenCount = jsmn_parse(&jsonParser, params->payload, (int) params->payloadLen, jsonTokenStruct, MAX_JSON_TOKEN_EXPECTED); - - if(tokenCount < 0) { - IOT_WARN("Failed to parse JSON: %d", tokenCount); - return; - } - - /* Assume the top-level element is an object */ - if(tokenCount < 1 || jsonTokenStruct[0].type != JSMN_OBJECT) { - IOT_WARN("Top Level is not an object"); - return; - } - - jsmntok_t *tokExecution; - - tokExecution = findToken("execution", params->payload, jsonTokenStruct); - - if (tokExecution) { - IOT_INFO("execution: %.*s", tokExecution->end - tokExecution->start, (char *)params->payload + tokExecution->start); - - jsmntok_t *tok; - - tok = findToken("jobId", params->payload, tokExecution); - - if (tok) { - IoT_Error_t rc; - char jobId[MAX_SIZE_OF_JOB_ID + 1]; - AwsIotJobExecutionUpdateRequest updateRequest; - - rc = parseStringValue(jobId, MAX_SIZE_OF_JOB_ID + 1, params->payload, tok); - if(SUCCESS != rc) { - IOT_ERROR("parseStringValue returned error : %d ", rc); - return; - } - - IOT_INFO("jobId: %s", jobId); - - tok = findToken("jobDocument", params->payload, tokExecution); - - /* - * Do your job processing here. - */ - - if (tok) { - IOT_INFO("jobDocument: %.*s", tok->end - tok->start, (char *)params->payload + tok->start); - /* Alternatively if the job still has more steps the status can be set to JOB_EXECUTION_IN_PROGRESS instead */ - updateRequest.status = JOB_EXECUTION_SUCCEEDED; - updateRequest.statusDetails = "{\"exampleDetail\":\"a value appropriate for your successful job\"}"; - } else { - updateRequest.status = JOB_EXECUTION_FAILED; - updateRequest.statusDetails = "{\"failureDetail\":\"Unable to process job document\"}"; - } - - updateRequest.expectedVersion = 0; - updateRequest.executionNumber = 0; - updateRequest.includeJobExecutionState = false; - updateRequest.includeJobDocument = false; - updateRequest.clientToken = NULL; - - rc = aws_iot_jobs_send_update(pClient, QOS0, AWS_IOT_MY_THING_NAME, jobId, &updateRequest, - topicToPublishUpdate, sizeof(topicToPublishUpdate), messageBuffer, sizeof(messageBuffer)); - } - } else { - IOT_INFO("execution property not found, nothing to do, jobs integration test complete"); - - bool *callbackDone = (bool *) pData; - *callbackDone = true; - } -} - -int aws_iot_jobs_basic_test() { - char certDirectory[15] = "../../certs"; - char clientCRT[PATH_MAX + 1]; - char root_CA[PATH_MAX + 1]; - char clientKey[PATH_MAX + 1]; - char CurrentWD[PATH_MAX + 1]; - char clientId[50]; - char cPayload[100]; - IoT_Client_Init_Params initParams = IoT_Client_Init_Params_initializer; - IoT_Client_Connect_Params connectParams; - IoT_Publish_Message_Params paramsQOS0; - IoT_Error_t rc = SUCCESS; - struct timeval connectTime, waitCallBackTime; - struct timeval start, end; - unsigned int connectCounter = 0; - - IOT_DEBUG("\nConnecting Client "); - do { - getcwd(CurrentWD, sizeof(CurrentWD)); - snprintf(root_CA, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_ROOT_CA_FILENAME); - snprintf(clientCRT, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_CERTIFICATE_FILENAME); - snprintf(clientKey, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_PRIVATE_KEY_FILENAME); - srand((unsigned int)time(NULL)); - snprintf(clientId, 50, "%s_%d", INTEGRATION_TEST_CLIENT_ID, rand() % 10000); - - printf("\n\nClient ID : %s \n", clientId); - - IOT_DEBUG("Root CA Path : %s\n clientCRT : %s\n clientKey : %s\n", root_CA, clientCRT, clientKey); - initParams.pHostURL = AWS_IOT_MQTT_HOST; - initParams.port = AWS_IOT_MQTT_PORT; - initParams.pRootCALocation = root_CA; - initParams.pDeviceCertLocation = clientCRT; - initParams.pDevicePrivateKeyLocation = clientKey; - initParams.mqttCommandTimeout_ms = 10000; - initParams.tlsHandshakeTimeout_ms = 10000; - initParams.disconnectHandler = aws_iot_mqtt_tests_disconnect_callback_handler; - initParams.enableAutoReconnect = false; - aws_iot_mqtt_init(&client, &initParams); - - connectParams.keepAliveIntervalInSec = 10; - connectParams.isCleanSession = true; - connectParams.MQTTVersion = MQTT_3_1_1; - connectParams.pClientID = (char *)&clientId; - connectParams.clientIDLen = strlen(clientId); - connectParams.isWillMsgPresent = false; - connectParams.pUsername = NULL; - connectParams.usernameLen = 0; - connectParams.pPassword = NULL; - connectParams.passwordLen = 0; - - gettimeofday(&start, NULL); - rc = aws_iot_mqtt_connect(&client, &connectParams); - gettimeofday(&end, NULL); - timersub(&end, &start, &connectTime); - - connectCounter++; - } while(rc != SUCCESS && connectCounter < CONNECT_MAX_ATTEMPT_COUNT); - - if(SUCCESS == rc) { - IOT_DEBUG("## Connect Success. Time sec: %ld, usec: %ld\n", (long int)connectTime.tv_sec, (long int)connectTime.tv_usec); - } else { - IOT_ERROR("## Connect Failed. error code %d\n", rc); - return -1; - } - - bool callbackDone = false; - char topicToSubscribeGetPending[MAX_JOB_TOPIC_LENGTH_BYTES]; - char topicToSubscribeNotifyNext[MAX_JOB_TOPIC_LENGTH_BYTES]; - char topicToSubscribeGetNext[MAX_JOB_TOPIC_LENGTH_BYTES]; - - char topicToPublishGetPending[MAX_JOB_TOPIC_LENGTH_BYTES]; - - rc = aws_iot_jobs_subscribe_to_job_messages( - &client, QOS0, AWS_IOT_MY_THING_NAME, NULL, JOB_GET_PENDING_TOPIC, JOB_WILDCARD_REPLY_TYPE, - iot_get_pending_callback_handler, &callbackDone, topicToSubscribeGetPending, sizeof(topicToSubscribeGetPending)); - - if(SUCCESS != rc) { - IOT_ERROR("Error subscribing JOB_GET_PENDING_TOPIC: %d ", rc); - return rc; - } - - rc = aws_iot_jobs_subscribe_to_job_messages( - &client, QOS0, AWS_IOT_MY_THING_NAME, NULL, JOB_NOTIFY_NEXT_TOPIC, JOB_REQUEST_TYPE, - iot_next_job_callback_handler, &callbackDone, topicToSubscribeNotifyNext, sizeof(topicToSubscribeNotifyNext)); - - if(SUCCESS != rc) { - IOT_ERROR("Error subscribing JOB_NOTIFY_NEXT_TOPIC: %d ", rc); - return rc; - } - - rc = aws_iot_jobs_subscribe_to_job_messages( - &client, QOS0, AWS_IOT_MY_THING_NAME, JOB_ID_NEXT, JOB_DESCRIBE_TOPIC, JOB_WILDCARD_REPLY_TYPE, - iot_next_job_callback_handler, &callbackDone, topicToSubscribeGetNext, sizeof(topicToSubscribeGetNext)); - - if(SUCCESS != rc) { - IOT_ERROR("Error subscribing JOB_DESCRIBE_TOPIC ($next): %d ", rc); - return rc; - } - - paramsQOS0.qos = QOS0; - paramsQOS0.payload = (void *) cPayload; - paramsQOS0.isRetained = 0; - paramsQOS0.payloadLen = strlen(cPayload); - - rc = aws_iot_jobs_send_query(&client, QOS0, AWS_IOT_MY_THING_NAME, NULL, NULL, topicToPublishGetPending, sizeof(topicToPublishGetPending), NULL, 0, JOB_GET_PENDING_TOPIC); - gettimeofday(&start, NULL); - while (!callbackDone) { - aws_iot_mqtt_yield(&client, 5000); - - gettimeofday(&end, NULL); - timersub(&end, &start, &waitCallBackTime); - - if(waitCallBackTime.tv_sec > 10) break; - } - - return 0; -} - -#endif -#endif diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_multiple_clients.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_multiple_clients.c deleted file mode 100644 index 3ea85aae4..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/integration/src/aws_iot_test_multiple_clients.c +++ /dev/null @@ -1,286 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_test_multiple_clients.c - * @brief Integration Test for multiple clients from the same application - */ - -#include "aws_iot_test_integration_common.h" - - -#define MAX_ERROR_DISPLAY 50 -static bool terminate_yield_thread; - -static unsigned int countArray[PUBLISH_COUNT]; -static unsigned int rxMsgBufferTooBigCounter; -static unsigned int rxUnexpectedNumberCounter; -static unsigned int rePublishCount; - -static void aws_iot_mqtt_tests_message_aggregator(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, - IoT_Publish_Message_Params *params, void *pData) { - char tempBuf[10]; - unsigned int tempInt = 0; - - IOT_UNUSED(pClient); - IOT_UNUSED(topicName); - IOT_UNUSED(topicNameLen); - IOT_UNUSED(pData); - - if(10 >= params->payloadLen) { - snprintf(tempBuf, params->payloadLen, params->payload); - printf("\nMsg received : %s", tempBuf); - tempInt = atoi(tempBuf); - if(0 < tempInt && PUBLISH_COUNT >= tempInt) { - countArray[tempInt - 1]++; - } else { - rxUnexpectedNumberCounter++; - } - } else { - if( params->payloadLen > MAX_ERROR_DISPLAY) - { - ((char *)params->payload)[MAX_ERROR_DISPLAY-1] = '\0'; - IOT_ERROR("\nWrong Msg received : %s", (char *)params->payload); - }else - { - IOT_ERROR("\nWrong Msg received : %s", (char *)params->payload); - } - rxMsgBufferTooBigCounter++; - } -} - -static void aws_iot_mqtt_tests_disconnect_callback_handler(AWS_IoT_Client *pClient, void *param) { - IOT_UNUSED(pClient); - IOT_UNUSED(param); -} - -static IoT_Error_t aws_iot_mqtt_tests_connect_client_to_service(AWS_IoT_Client *pClient, struct timeval *pConnectTime, - char *clientId, char *rootCA, char *clientCRT, - char *clientKey) { - IoT_Client_Init_Params initParams; - IoT_Client_Connect_Params connectParams; - IoT_Error_t rc; - struct timeval start, end; - - initParams.pHostURL = AWS_IOT_MQTT_HOST; - initParams.port = AWS_IOT_MQTT_PORT; - initParams.pRootCALocation = rootCA; - initParams.pDeviceCertLocation = clientCRT; - initParams.pDevicePrivateKeyLocation = clientKey; - initParams.mqttCommandTimeout_ms = 5000; - initParams.tlsHandshakeTimeout_ms = 2000; - initParams.mqttPacketTimeout_ms = 5000; - initParams.isSSLHostnameVerify = true; - initParams.disconnectHandlerData = NULL; - initParams.isBlockOnThreadLockEnabled = true; - initParams.disconnectHandler = aws_iot_mqtt_tests_disconnect_callback_handler; - initParams.enableAutoReconnect = false; - rc = aws_iot_mqtt_init(pClient, &initParams); - printf("\n Init response : %d", rc); - - printf("\nRoot CA Path : %s\nClientCRT : %s\nClientKey : %s \nClient ID : %s", rootCA, clientCRT, - clientKey, clientId); - connectParams.keepAliveIntervalInSec = 5; - connectParams.isCleanSession = true; - connectParams.MQTTVersion = MQTT_3_1_1; - connectParams.pClientID = clientId; - connectParams.clientIDLen = strlen(clientId); - connectParams.isWillMsgPresent = 0; - connectParams.pUsername = NULL; - connectParams.usernameLen = 0; - connectParams.pPassword = NULL; - connectParams.passwordLen = 0; - - gettimeofday(&start, NULL); - rc = aws_iot_mqtt_connect(pClient, &connectParams); - printf("\nConnect response : %d ", rc); - gettimeofday(&end, NULL); - timersub(&end, &start, pConnectTime); - - return rc; -} - -static IoT_Error_t aws_iot_mqtt_tests_subscribe_to_test_topic(AWS_IoT_Client *pClient, QoS qos, struct timeval *pSubscribeTime) { - IoT_Error_t rc = SUCCESS; - struct timeval start, end; - - gettimeofday(&start, NULL); - rc = aws_iot_mqtt_subscribe(pClient, INTEGRATION_TEST_TOPIC, strlen(INTEGRATION_TEST_TOPIC), qos, - aws_iot_mqtt_tests_message_aggregator, NULL); - printf("\nSub response : %d\n", rc); - gettimeofday(&end, NULL); - - timersub(&end, &start, pSubscribeTime); - - return rc; -} - -static void *aws_iot_mqtt_tests_yield_thread_runner(void *ptr) { - IoT_Error_t rc = SUCCESS; - AWS_IoT_Client *pClient = (AWS_IoT_Client *) ptr; - while(SUCCESS == rc && false == terminate_yield_thread) { - do { - usleep(THREAD_SLEEP_INTERVAL_USEC); - rc = aws_iot_mqtt_yield(pClient, 100); - } while(MQTT_CLIENT_NOT_IDLE_ERROR == rc); - - if(SUCCESS != rc) { - IOT_ERROR("\nYield Returned : %d ", rc); - } - } - - return NULL; -} - -static void *aws_iot_mqtt_tests_publish_thread_runner(void *ptr) { - int itr = 0; - char cPayload[10]; - IoT_Publish_Message_Params params; - IoT_Error_t rc = SUCCESS; - AWS_IoT_Client *pClient = (AWS_IoT_Client *) ptr; - - for(itr = 0; itr < PUBLISH_COUNT; itr++) { - sprintf(cPayload, "%d", itr + 1); - params.payload = (void *) cPayload; - params.payloadLen = strlen(cPayload) + 1; - params.qos = QOS1; - params.isRetained = 0; - rc = aws_iot_mqtt_publish(pClient, INTEGRATION_TEST_TOPIC, strlen(INTEGRATION_TEST_TOPIC), ¶ms); - printf("\n Publishing %s", cPayload); - if(SUCCESS != rc) { - printf("Error Publishing #%d --> %d\n ", itr, rc); - usleep(300000); - rc = aws_iot_mqtt_publish(pClient, INTEGRATION_TEST_TOPIC, strlen(INTEGRATION_TEST_TOPIC), ¶ms); - rePublishCount++; - if(SUCCESS != rc) { - printf("Error Publishing #%d --> %d Second Attempt \n", itr, rc); - } - } - usleep(300000); - } - - return NULL; -} - - -int aws_iot_mqtt_tests_multiple_clients() { - char certDirectory[15] = "../../certs"; - char CurrentWD[PATH_MAX + 1]; - char rootCA[PATH_MAX + 1]; - char clientCRT[PATH_MAX + 1]; - char clientKey[PATH_MAX + 1]; - - char subClientId[50]; - char pubClientId[50]; - - int itr = 0; - int rxMsgCount = 0; - int test_result = 0; - int pubThreadReturn = 0; - int yieldThreadReturn = 0; - unsigned int connectCounter = 0; - float percentOfRxMsg = 0.0; - - IoT_Error_t rc = SUCCESS; - pthread_t yield_thread; - pthread_t publish_thread; - struct timeval connectTime; - struct timeval subscribeTopic; - - AWS_IoT_Client pubClient; - AWS_IoT_Client subClient; - - terminate_yield_thread = false; - rxMsgBufferTooBigCounter = 0; - rxUnexpectedNumberCounter = 0; - rePublishCount = 0; - - srand((unsigned int)time(NULL)); - snprintf(subClientId, 50, "%s_%d", INTEGRATION_TEST_CLIENT_ID_SUB, rand() % 10000); - snprintf(pubClientId, 50, "%s_%d", INTEGRATION_TEST_CLIENT_ID_PUB, rand() % 10000); - - getcwd(CurrentWD, sizeof(CurrentWD)); - - snprintf(rootCA, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_ROOT_CA_FILENAME); - snprintf(clientCRT, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_CERTIFICATE_FILENAME); - snprintf(clientKey, PATH_MAX + 1, "%s/%s/%s", CurrentWD, certDirectory, AWS_IOT_PRIVATE_KEY_FILENAME); - - for(itr = 0; itr < PUBLISH_COUNT; itr++) { - countArray[itr] = 0; - } - - printf(" \n Connecting Pub Client "); - do { - rc = aws_iot_mqtt_tests_connect_client_to_service(&pubClient, &connectTime, pubClientId, rootCA, - clientCRT, clientKey); - connectCounter++; - } while(SUCCESS != rc && CONNECT_MAX_ATTEMPT_COUNT > connectCounter); - - if(SUCCESS == rc) { - printf("\n## Connect Success. Time sec: %ld, usec: %ld\n", (long int)connectTime.tv_sec, (long int)connectTime.tv_usec); - } else { - printf("\n## Connect Failed. error code %d\n", rc); - return -1; - } - - printf("\n Connecting Sub Client "); - do { - rc = aws_iot_mqtt_tests_connect_client_to_service(&subClient, &connectTime, subClientId, rootCA, - clientCRT, clientKey); - connectCounter++; - } while(SUCCESS != rc && connectCounter < CONNECT_MAX_ATTEMPT_COUNT); - - if(SUCCESS == rc) { - printf("## Connect Success. Time sec: %ld, usec: %ld\n", (long int)connectTime.tv_sec, (long int)connectTime.tv_usec); - } else { - printf("## Connect Failed. error code %d\n", rc); - return -1; - } - - aws_iot_mqtt_tests_subscribe_to_test_topic(&subClient, QOS1, &subscribeTopic); - - yieldThreadReturn = pthread_create(&yield_thread, NULL, aws_iot_mqtt_tests_yield_thread_runner, &subClient); - pubThreadReturn = pthread_create(&publish_thread, NULL, aws_iot_mqtt_tests_publish_thread_runner, &pubClient); - - pthread_join(publish_thread, NULL); - - /* Kill yield thread */ - terminate_yield_thread = true; - pthread_join(yield_thread, NULL); - - aws_iot_mqtt_disconnect(&pubClient); - aws_iot_mqtt_disconnect(&subClient); - - for(itr = 0; itr < PUBLISH_COUNT; itr++) { - if(countArray[itr] > 0) { - rxMsgCount++; - } - } - - percentOfRxMsg = (float) rxMsgCount * 100 / PUBLISH_COUNT; - if(percentOfRxMsg >= RX_RECEIVE_PERCENTAGE && rxMsgBufferTooBigCounter == 0 && rxUnexpectedNumberCounter == 0) { - printf("\nSuccess: %f \%\n", percentOfRxMsg); - printf("Published Messages: %d , Received Messages: %d \n", PUBLISH_COUNT, rxMsgCount); - printf("QoS 1 re publish count %d\n", rePublishCount); - printf("Connection Attempts %d\n", connectCounter); - test_result = 0; - } else { - printf("\nFailure: %f\n", percentOfRxMsg); - printf("\"Received message was too big than anything sent\" count: %d\n", rxMsgBufferTooBigCounter); - printf("\"The number received is out of the range\" count: %d\n", rxUnexpectedNumberCounter); - test_result = -2; - } - return test_result; -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/README.md b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/README.md deleted file mode 100644 index a58e2e475..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/README.md +++ /dev/null @@ -1,12 +0,0 @@ -## Unit Tests -This folder contains unit tests to verify Embedded C SDK functionality. These have been tested to work with Linux using CppUTest as the testing framework. -CppUTest is not provided along with this code. It needs to be separately downloaded. These tests have been verified to work with CppUTest v3.6, which can be found [here](https://github.com/cpputest/cpputest/tree/v3.6). -Each test contains a comment describing what is being tested. The Tests can be run using the Makefile provided in the root folder for the SDK. There are a total of 187 tests. - -To run these tests, follow the below steps: - - * Copy the code for CppUTest v3.6 from github to external_libs/CppUTest - * Navigate to SDK Root folder - * run `make run-unit-tests` - -This will run all unit tests and generate coverage report in the build_output folder. The report can be viewed by opening /build_output/generated-coverage/index.html in a browser. \ No newline at end of file diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/include/aws_iot_config.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/include/aws_iot_config.h deleted file mode 100644 index b75d6e3b4..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/include/aws_iot_config.h +++ /dev/null @@ -1,73 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_config.h - * @brief IoT Client Unit Testing - IoT Config - */ - -#ifndef IOT_TESTS_UNIT_CONFIG_H_ -#define IOT_TESTS_UNIT_CONFIG_H_ - -// Get from console -// ================================================= -#define AWS_IOT_MQTT_HOST "localhost" -#define AWS_IOT_MQTT_PORT 443 -#define AWS_IOT_MQTT_CLIENT_ID "C-SDK_UnitTestClient" -#define AWS_IOT_MY_THING_NAME "C-SDK_UnitTestThing" -#define AWS_IOT_ROOT_CA_FILENAME "rootCA.crt" -#define AWS_IOT_CERTIFICATE_FILENAME "cert.crt" -#define AWS_IOT_PRIVATE_KEY_FILENAME "privkey.pem" -// ================================================= - - -// MQTT PubSub -#ifndef DISABLE_IOT_JOBS -#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. -#else -#define AWS_IOT_MQTT_RX_BUF_LEN 2048 -#endif -#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_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 - -// Shadow and Job common configs -#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_SIZE_OF_THING_NAME 30 ///< The Thing Name should not be bigger than this value. Modify this if the Thing Name needs to be bigger - -// Thing Shadow specific configs -#define SHADOW_MAX_SIZE_OF_RX_BUFFER 512 ///< Maximum size of the SHADOW buffer to store the received Shadow message -#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_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 - -// Job specific configs -#ifndef DISABLE_IOT_JOBS -#define MAX_SIZE_OF_JOB_ID 64 -#define MAX_JOB_JSON_TOKEN_EXPECTED 120 -#define MAX_SIZE_OF_JOB_REQUEST AWS_IOT_MQTT_TX_BUF_LEN - -#define MAX_JOB_TOPIC_LENGTH_WITHOUT_JOB_ID_OR_THING_NAME 40 -#define MAX_JOB_TOPIC_LENGTH_BYTES MAX_JOB_TOPIC_LENGTH_WITHOUT_JOB_ID_OR_THING_NAME + MAX_SIZE_OF_THING_NAME + MAX_SIZE_OF_JOB_ID + 2 -#endif - -// 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 /* IOT_TESTS_UNIT_CONFIG_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/include/aws_iot_tests_unit_helper_functions.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/include/aws_iot_tests_unit_helper_functions.h deleted file mode 100644 index 337353af4..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/include/aws_iot_tests_unit_helper_functions.h +++ /dev/null @@ -1,104 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_helper_functions.h - * @brief IoT Client Unit Testing - Helper Functions - */ - -#ifndef IOT_TESTS_UNIT_HELPER_FUNCTIONS_H_ -#define IOT_TESTS_UNIT_HELPER_FUNCTIONS_H_ - -#include -#include "aws_iot_mqtt_client_interface.h" -#include "aws_iot_jobs_topics.h" - -typedef struct { - unsigned char PacketType; - unsigned int RemainingLength; - unsigned int ProtocolLength; - unsigned char ProtocolName[4]; - unsigned int ProtocolLevel; - unsigned char ConnectFlag; - unsigned int KeepAlive; -} ConnectBufferProofread; - -void ResetInvalidParameters(void); - -void InitMQTTParamsSetup(IoT_Client_Init_Params *params, char *pHost, uint16_t port, bool enableAutoReconnect, - iot_disconnect_handler disconnectHandler); - -void ConnectMQTTParamsSetup(IoT_Client_Connect_Params *params, char *pClientID, uint16_t clientIDLen); - -void ConnectMQTTParamsSetup_Detailed(IoT_Client_Connect_Params *params, char *pClientID, uint16_t clientIDLen, - QoS qos, bool isCleanSession, bool isWillMsgPresent, char *pWillTopicName, - uint16_t willTopicNameLen, char *pWillMessage, uint16_t willMsgLen, - char *pUsername, uint16_t userNameLen, char *pPassword, - uint16_t passwordLen); - -void printBuffer(unsigned char *buffer, size_t len); - -void setTLSRxBufferForConnack(IoT_Client_Connect_Params *params, unsigned char sessionPresent, - unsigned char connackResponseCode); - -void setTLSRxBufferForPuback(void); - -void setTLSRxBufferForSuback(char *topicName, size_t topicNameLen, QoS qos, IoT_Publish_Message_Params params); - -void setTLSRxBufferForDoubleSuback(char *topicName, size_t topicNameLen, QoS qos, IoT_Publish_Message_Params params); - -void setTLSRxBufferForSubFail(void); - -void setTLSRxBufferWithMsgOnSubscribedTopic(char *topicName, size_t topicNameLen, QoS qos, - IoT_Publish_Message_Params params, char *pMsg); - -void setTLSRxBufferForUnsuback(void); - -void setTLSRxBufferForPingresp(void); - -void setTLSRxBufferForError(IoT_Error_t error); - -void setTLSTxBufferForError(IoT_Error_t error); - -void setTLSRxBufferForConnackAndSuback(IoT_Client_Connect_Params *conParams, unsigned char sessionPresent, - char *topicName, size_t topicNameLen, QoS qos); - -unsigned char isLastTLSTxMessagePuback(void); - -unsigned char isLastTLSTxMessagePingreq(void); - -unsigned char isLastTLSTxMessageDisconnect(void); - -void setTLSRxBufferDelay(int seconds, int microseconds); - -void ResetTLSBuffer(void); - -unsigned char generateMultipleSubTopics(char *des, int boundary); - -void encodeRemainingLength(unsigned char *buf, size_t *st, size_t length); - -unsigned char *connectTxBufferHeaderParser(ConnectBufferProofread *params, unsigned char *buf); - -bool isConnectTxBufFlagCorrect(IoT_Client_Connect_Params *settings, ConnectBufferProofread *readRes); - -bool isConnectTxBufPayloadCorrect(IoT_Client_Connect_Params *settings, unsigned char *payloadBuf); - -void printPrfrdParams(ConnectBufferProofread *params); - -const char *getJobTopicTypeName(AwsIotJobExecutionTopicType topicType); - -const char *getJobReplyTypeName(AwsIotJobExecutionTopicReplyType replyType); - -#endif /* IOT_TESTS_UNIT_HELPER_FUNCTIONS_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/include/aws_iot_tests_unit_shadow_helper.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/include/aws_iot_tests_unit_shadow_helper.h deleted file mode 100644 index 455a387b3..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/include/aws_iot_tests_unit_shadow_helper.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_shadow_helper.h - * @brief IoT Client Unit Testing - Shadow Helper functions - */ - -#ifndef IOT_TESTS_UNIT_SHADOW_HELPER_FUNCTIONS_H_ -#define IOT_TESTS_UNIT_SHADOW_HELPER_FUNCTIONS_H_ - -#define AWS_THINGS_TOPIC "$aws/things/" -#define SHADOW_TOPIC "/shadow/" -#define ACCEPTED_TOPIC "/accepted" -#define REJECTED_TOPIC "/rejected" -#define UPDATE_TOPIC "update" -#define GET_TOPIC "get" -#define DELETE_TOPIC "delete" - - -#define GET_ACCEPTED_TOPIC AWS_THINGS_TOPIC AWS_IOT_MY_THING_NAME SHADOW_TOPIC GET_TOPIC ACCEPTED_TOPIC -#define GET_REJECTED_TOPIC AWS_THINGS_TOPIC AWS_IOT_MY_THING_NAME SHADOW_TOPIC GET_TOPIC REJECTED_TOPIC -#define GET_PUB_TOPIC AWS_THINGS_TOPIC AWS_IOT_MY_THING_NAME SHADOW_TOPIC GET_TOPIC - -#define DELETE_ACCEPTED_TOPIC AWS_THINGS_TOPIC AWS_IOT_MY_THING_NAME SHADOW_TOPIC DELETE_TOPIC ACCEPTED_TOPIC -#define DELETE_REJECTED_TOPIC AWS_THINGS_TOPIC AWS_IOT_MY_THING_NAME SHADOW_TOPIC DELETE_TOPIC REJECTED_TOPIC - -#define UPDATE_ACCEPTED_TOPIC AWS_THINGS_TOPIC AWS_IOT_MY_THING_NAME SHADOW_TOPIC UPDATE_TOPIC ACCEPTED_TOPIC -#define UPDATE_REJECTED_TOPIC AWS_THINGS_TOPIC AWS_IOT_MY_THING_NAME SHADOW_TOPIC UPDATE_TOPIC REJECTED_TOPIC - -#endif /* IOT_TESTS_UNIT_SHADOW_HELPER_FUNCTIONS_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_common_tests.cpp b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_common_tests.cpp deleted file mode 100644 index 449647ecc..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_common_tests.cpp +++ /dev/null @@ -1,34 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_common_tests.cpp - * @brief IoT Client Unit Testing - Common Tests - */ - -#include -#include - -TEST_GROUP_C(CommonTests){ - TEST_GROUP_C_SETUP_WRAPPER(CommonTests) - TEST_GROUP_C_TEARDOWN_WRAPPER(CommonTests) -}; - -TEST_GROUP_C_WRAPPER(CommonTests, NullClientGetState) -TEST_GROUP_C_WRAPPER(CommonTests, NullClientSetAutoreconnect) - -TEST_GROUP_C_WRAPPER(CommonTests, UnexpectedAckFiltering) -TEST_GROUP_C_WRAPPER(CommonTests, BigMQTTRxMessageIgnore) -TEST_GROUP_C_WRAPPER(CommonTests, BigMQTTRxMessageReadNextMessage) diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_common_tests_helper.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_common_tests_helper.c deleted file mode 100644 index 9d1604211..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_common_tests_helper.c +++ /dev/null @@ -1,186 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_common_tests_helper.h - * @brief IoT Client Unit Testing - Common Tests Helper - */ - -#include -#include -#include - -#include "aws_iot_mqtt_client_interface.h" -#include "aws_iot_log.h" -#include "aws_iot_tests_unit_helper_functions.h" - -static IoT_Client_Init_Params initParams; -static IoT_Client_Connect_Params connectParams; -static IoT_Publish_Message_Params testPubMsgParams; -static AWS_IoT_Client iotClient; - -static char subTopic[10] = "sdk/Test"; -static uint16_t subTopicLen = 8; -char cPayload[100]; - -char cbBuffer[AWS_IOT_MQTT_TX_BUF_LEN + 2]; - -static void iot_tests_unit_common_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, IoT_Publish_Message_Params *params, - void *pData) { - char *tmp = params->payload; - unsigned int i; - - IOT_UNUSED(pClient); - IOT_UNUSED(topicName); - IOT_UNUSED(topicNameLen); - IOT_UNUSED(pData); - - for(i = 0; i < params->payloadLen; i++) { - cbBuffer[i] = tmp[i]; - } -} - -TEST_GROUP_C_SETUP(CommonTests) { - ResetTLSBuffer(); - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - initParams.mqttCommandTimeout_ms = 2000; - IoT_Error_t rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - IOT_DEBUG("\n\nMQTT Status State : %d, RC : %d\n\n", aws_iot_mqtt_get_client_state(&iotClient), rc); - - testPubMsgParams.qos = QOS1; - testPubMsgParams.isRetained = 0; - snprintf(cPayload, 100, "%s : %d ", "hello from SDK", 0); - testPubMsgParams.payload = (void *) cPayload; - testPubMsgParams.payloadLen = strlen(cPayload); - - ResetTLSBuffer(); -} - -TEST_GROUP_C_TEARDOWN(CommonTests) { - /* Clean up. Not checking return code here because this is common to all tests. - * A test might have already caused a disconnect by this point. - */ - IoT_Error_t rc = aws_iot_mqtt_disconnect(&iotClient); - IOT_UNUSED(rc); -} - -TEST_C(CommonTests, NullClientGetState) { - ClientState cs = aws_iot_mqtt_get_client_state(NULL); - CHECK_EQUAL_C_INT(CLIENT_STATE_INVALID, cs); -} - -TEST_C(CommonTests, NullClientSetAutoreconnect) { - IoT_Error_t rc = aws_iot_mqtt_autoreconnect_set_status(NULL, true); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -// Unexpected Ack section -TEST_C(CommonTests, UnexpectedAckFiltering) { - IoT_Error_t rc = FAILURE; - - IOT_DEBUG("\n-->Running CommonTests - Unexpected Ack Filtering\n"); - // Assume we are connected and have not done anything yet - // Connack - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ResetTLSBuffer(); - // Puback - setTLSRxBufferForPuback(); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ResetTLSBuffer(); - // Suback: OoS1 - setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ResetTLSBuffer(); - // Suback: QoS0 - setTLSRxBufferForSuback(subTopic, subTopicLen, QOS0, testPubMsgParams); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ResetTLSBuffer(); - // Unsuback - setTLSRxBufferForUnsuback(); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); -} - -TEST_C(CommonTests, BigMQTTRxMessageIgnore) { - uint32_t i = 0; - IoT_Error_t rc = FAILURE; - char expectedCallbackString[AWS_IOT_MQTT_RX_BUF_LEN + 2]; - - IOT_DEBUG("\n-->Running CommonTests - Ignore Large Incoming Message \n"); - - setTLSRxBufferForSuback("limitTest/topic1", 16, QOS0, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "limitTest/topic1", 16, QOS0, iot_tests_unit_common_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - for(i = 0; i < AWS_IOT_MQTT_RX_BUF_LEN; i++) { - expectedCallbackString[i] = 'X'; - } - expectedCallbackString[i + 1] = '\0'; - - setTLSRxBufferWithMsgOnSubscribedTopic("limitTest/topic1", 16, QOS0, testPubMsgParams, expectedCallbackString); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(MQTT_RX_BUFFER_TOO_SHORT_ERROR, rc); -} - -/** - * - * On receiving a big message into the TLS buffer the MQTT client should flush it out, otherwise it can cause undefined behavior. - */ -TEST_C(CommonTests, BigMQTTRxMessageReadNextMessage) { - uint32_t i = 0; - IoT_Error_t rc = FAILURE; - char expectedCallbackString[AWS_IOT_MQTT_RX_BUF_LEN + 2]; - - IOT_DEBUG("\n-->Running CommonTests - Clear Buffer when large message received and continue reading \n"); - - setTLSRxBufferForSuback("limitTest/topic1", 16, QOS0, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "limitTest/topic1", 16, QOS0, iot_tests_unit_common_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - for(i = 0; i < AWS_IOT_MQTT_RX_BUF_LEN; i++) { - expectedCallbackString[i] = 'X'; - } - expectedCallbackString[i + 1] = '\0'; - - setTLSRxBufferWithMsgOnSubscribedTopic("limitTest/topic1", 16, QOS0, testPubMsgParams, expectedCallbackString); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(MQTT_RX_BUFFER_TOO_SHORT_ERROR, rc); - - ResetTLSBuffer(); - - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - expectedCallbackString[3] = '\0'; - setTLSRxBufferWithMsgOnSubscribedTopic("limitTest/topic1", 16, QOS1, testPubMsgParams, expectedCallbackString); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(rc, SUCCESS); - CHECK_EQUAL_C_STRING("XXX", cbBuffer); -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_connect.cpp b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_connect.cpp deleted file mode 100644 index 5b7ae0897..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_connect.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_connect.cpp - * @brief IoT Client Unit Testing - Connect API Tests - */ - -#include -#include - -TEST_GROUP_C(ConnectTests){ - TEST_GROUP_C_SETUP_WRAPPER(ConnectTests) - TEST_GROUP_C_TEARDOWN_WRAPPER(ConnectTests) -}; - -/* B:1 - Init with Null/empty client instance */ -TEST_GROUP_C_WRAPPER(ConnectTests, NullClientInit) -/* B:2 - Connect with Null/empty client instance */ -TEST_GROUP_C_WRAPPER(ConnectTests, NullClientConnect) -/* B:3 - Connect with Null/Empty endpoint */ -TEST_GROUP_C_WRAPPER(ConnectTests, NullHost) -/* B:4 - Connect with Null/Empty port */ -TEST_GROUP_C_WRAPPER(ConnectTests, NullPort) -/* B:5 - Connect with Null/Empty root CA path */ -TEST_GROUP_C_WRAPPER(ConnectTests, NullRootCAPath) -/* B:6 - Connect with Null/Empty Client certificate path */ -TEST_GROUP_C_WRAPPER(ConnectTests, NullClientCertificate) -/* B:7 - Connect with Null/Empty private key Path */ -TEST_GROUP_C_WRAPPER(ConnectTests, NullPrivateKeyPath) -/* B:8 - Connect with Null/Empty client ID */ -TEST_GROUP_C_WRAPPER(ConnectTests, NullClientID) -/* B:9 - Connect with invalid Endpoint */ -TEST_GROUP_C_WRAPPER(ConnectTests, InvalidEndpoint) -/* B:10 - Connect with invalid correct endpoint but invalid port */ -TEST_GROUP_C_WRAPPER(ConnectTests, InvalidPort) -/* B:11 - Connect with invalid Root CA path */ -TEST_GROUP_C_WRAPPER(ConnectTests, InvalidRootCAPath) -/* B:12 - Connect with invalid Client certificate path */ -TEST_GROUP_C_WRAPPER(ConnectTests, InvalidClientCertPath) -/* B:13 - Connect with invalid private key path */ -TEST_GROUP_C_WRAPPER(ConnectTests, InvalidPrivateKeyPath) -/* B:14 - Connect, no response timeout */ -TEST_GROUP_C_WRAPPER(ConnectTests, NoResponseTimeout) -/* B:15 - Connect, connack malformed, too large */ -TEST_GROUP_C_WRAPPER(ConnectTests, ConnackTooLarge) -/* B:16 - Connect, connack malformed, fixed header corrupted */ -TEST_GROUP_C_WRAPPER(ConnectTests, FixedHeaderCorrupted) -/* B:17 - Connect, connack malformed, invalid remaining length */ -TEST_GROUP_C_WRAPPER(ConnectTests, InvalidRemainingLength) -/* B:18 - Connect, connack returned error, unacceptable protocol version */ -TEST_GROUP_C_WRAPPER(ConnectTests, UnacceptableProtocolVersion) -/* B:19 - Connect, connack returned error, identifier rejected */ -TEST_GROUP_C_WRAPPER(ConnectTests, IndentifierRejected) -/* B:20 - Connect, connack returned error, Server unavailable */ -TEST_GROUP_C_WRAPPER(ConnectTests, ServerUnavailable) -/* B:21 - Connect, connack returned error, bad user name or password */ -TEST_GROUP_C_WRAPPER(ConnectTests, BadUserNameOrPassword) -/* B:22 - Connect, connack returned error, not authorized */ -TEST_GROUP_C_WRAPPER(ConnectTests, NotAuthorized) -/* B:23 - Connect, connack return after half command timeout delay, success */ -TEST_GROUP_C_WRAPPER(ConnectTests, SuccessAfterDelayedConnack) -/* B:24 - Connect, connack returned success */ -TEST_GROUP_C_WRAPPER(ConnectTests, ConnectSuccess) -/* B:25 - Connect, flag settings and parameters are recorded in buffer */ -TEST_GROUP_C_WRAPPER(ConnectTests, FlagSettingsAndParamsAreRecordedIntoBuf) -/* B:26 - Connect attempt, Disconnect, Manually reconnect */ -TEST_GROUP_C_WRAPPER(ConnectTests, ConnectDisconnectConnect) -/* B:27 - Connect attempt, Clean session, Subscribe */ -TEST_GROUP_C_WRAPPER(ConnectTests, cleanSessionInitSubscribers) -/* B:28 - Connect attempt, power cycle with clean session false */ -TEST_GROUP_C_WRAPPER(ConnectTests, PowerCycleWithCleanSessionFalse) -/* B:29 - Reconnect attempt succeeds, but resubscribes fail */ -TEST_GROUP_C_WRAPPER(ConnectTests, ReconnectAndResubscribe) diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_connect_helper.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_connect_helper.c deleted file mode 100644 index 40a0298cc..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_connect_helper.c +++ /dev/null @@ -1,792 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_connect_helper.c - * @brief IoT Client Unit Testing - Connect API Tests Helper - */ - -#include -#include -#include -#include -#include - -#include "aws_iot_tests_unit_mock_tls_params.h" -#include "aws_iot_tests_unit_helper_functions.h" - -#include "aws_iot_log.h" - -#include "aws_iot_mqtt_client_common_internal.h" - -static bool unitTestIsMqttConnected = false; - -static IoT_Client_Init_Params initParams; -static IoT_Client_Connect_Params connectParams; -static AWS_IoT_Client iotClient; - -static IoT_Publish_Message_Params testPubMsgParams; -static ConnectBufferProofread prfrdParams; - -static char subTopic1[12] = "sdk/Topic1"; -static char subTopic2[12] = "sdk/Topic2"; - -#define NO_MSG_XXXX "XXXX" -static char CallbackMsgStringclean[100] = NO_MSG_XXXX; - -static void iot_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, - IoT_Publish_Message_Params *params, void *pData) { - char *tmp = params->payload; - unsigned int i; - - if(NULL == pClient || NULL == topicName || 0 == topicNameLen) { - return; - } - - IOT_UNUSED(pData); - - for(i = 0; i < (params->payloadLen); i++) { - CallbackMsgStringclean[i] = tmp[i]; - } -} - -TEST_GROUP_C_SETUP(ConnectTests) { - unitTestIsMqttConnected = false; - ( void ) aws_iot_mqtt_disconnect(&iotClient); - ResetTLSBuffer(); - ResetInvalidParameters(); -} - -TEST_GROUP_C_TEARDOWN(ConnectTests) { - /* Clean up. Not checking return code here because this is common to all tests. - * A test might have already caused a disconnect by this point. - */ - IoT_Error_t rc = aws_iot_mqtt_disconnect(&iotClient); - IOT_UNUSED(rc); -} - -/* B:1 - Init with Null/empty client instance */ -TEST_C(ConnectTests, NullClientInit) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:1 - Init with Null/empty client instance \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(NULL, &initParams); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); - - IOT_DEBUG("-->Success - B:1 - Init with Null/empty client instance \n"); -} - -/* B:2 - Connect with Null/empty client instance */ -TEST_C(ConnectTests, NullClientConnect) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:2 - Connect with Null/empty client instance \n"); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(NULL, &connectParams); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); - - IOT_DEBUG("-->Success - B:2 - Connect with Null/empty client instance \n"); -} - -/* B:3 - Connect with Null/Empty endpoint */ -TEST_C(ConnectTests, NullHost) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:3 - Connect with Null/Empty endpoint \n"); - - InitMQTTParamsSetup(&initParams, NULL, AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_C(SUCCESS != rc); - - IOT_DEBUG("-->Success - B:3 - Connect with Null/Empty endpoint \n"); -} - -/* B:4 - Connect with Null/Empty port */ -TEST_C(ConnectTests, NullPort) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:4 - Connect with Null/Empty port \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, 0, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_C(SUCCESS != rc); - - IOT_DEBUG("-->Success - B:4 - Connect with Null/Empty port \n"); -} - -/* B:5 - Connect with Null/Empty root CA path */ -TEST_C(ConnectTests, NullRootCAPath) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:6 - Connect with Null/Empty root CA path \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - initParams.pRootCALocation = NULL; - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); - - IOT_DEBUG("-->Success - B:6 - Connect with Null/Empty root CA path \n"); -} - -/* B:6 - Connect with Null/Empty Client certificate path */ -TEST_C(ConnectTests, NullClientCertificate) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:7 - Connect with Null/Empty Client certificate path \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - initParams.pDeviceCertLocation = NULL; - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); - - IOT_DEBUG("-->Success - B:7 - Connect with Null/Empty Client certificate path \n"); -} - -/* B:7 - Connect with Null/Empty private key Path */ -TEST_C(ConnectTests, NullPrivateKeyPath) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:8 - Connect with Null/Empty private key Path \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - initParams.pDevicePrivateKeyLocation = NULL; - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); - - IOT_DEBUG("-->Success - B:8 - Connect with Null/Empty private key Path \n"); -} - -/* B:8 - Connect with Null/Empty client ID */ -TEST_C(ConnectTests, NullClientID) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:8 - Connect with Null/Empty client ID \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - setTLSRxBufferForConnack(&connectParams, 0, 0); - - /* If no client id is passed but a length was passed, return error */ - ConnectMQTTParamsSetup(&connectParams, NULL, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); - - /* If client id is passed but 0 length was passed, return error */ - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); - - /* If client id is NULL and length is 0 then request succeeds */ - ConnectMQTTParamsSetup(&connectParams, NULL, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - IOT_DEBUG("-->Success - B:8 - Connect with Null/Empty client ID \n"); -} - -/* B:9 - Connect with invalid Endpoint */ -TEST_C(ConnectTests, InvalidEndpoint) { - IoT_Error_t rc = SUCCESS; - char invalidEndPoint[20]; - snprintf(invalidEndPoint, 20, "invalid"); - - IOT_DEBUG("-->Running Connect Tests - B:9 - Connect with invalid Endpoint \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - invalidEndpointFilter = invalidEndPoint; - initParams.pHostURL = invalidEndpointFilter; - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_C(SUCCESS != rc); - - IOT_DEBUG("-->Success - B:9 - Connect with invalid Endpoint \n"); -} - -/* B:10 - Connect with invalid correct endpoint but invalid port */ -TEST_C(ConnectTests, InvalidPort) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:10 - Connect with invalid correct endpoint but invalid port \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - invalidPortFilter = 1234; - initParams.port = invalidPortFilter; - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_C(SUCCESS != rc); - - IOT_DEBUG("-->Success - B:10 - Connect with invalid correct endpoint but invalid port \n"); -} - -/* B:11 - Connect with invalid Root CA path */ -TEST_C(ConnectTests, InvalidRootCAPath) { - IoT_Error_t rc = SUCCESS; - char invalidRootCAPath[20]; - snprintf(invalidRootCAPath, 20, "invalid"); - - IOT_DEBUG("-->Running Connect Tests - B:11 - Connect with invalid Root CA path \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - invalidRootCAPathFilter = invalidRootCAPath; - initParams.pRootCALocation = invalidRootCAPathFilter; - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_C(SUCCESS != rc); - - IOT_DEBUG("-->Success - B:11 - Connect with invalid Root CA path \n"); -} - -/* B:12 - Connect with invalid Client certificate path */ -TEST_C(ConnectTests, InvalidClientCertPath) { - IoT_Error_t rc = SUCCESS; - char invalidCertPath[20]; - snprintf(invalidCertPath, 20, "invalid"); - - IOT_DEBUG("-->Running Connect Tests - B:12 - Connect with invalid Client certificate path \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - invalidCertPathFilter = invalidCertPath; - initParams.pDeviceCertLocation = invalidCertPathFilter; - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_C(SUCCESS != rc); - - IOT_DEBUG("-->Success - B:12 - Connect with invalid Client certificate path \n"); -} - -/* B:13 - Connect with invalid private key path */ -TEST_C(ConnectTests, InvalidPrivateKeyPath) { - IoT_Error_t rc = SUCCESS; - char invalidPrivKeyPath[20]; - snprintf(invalidPrivKeyPath, 20, "invalid"); - - IOT_DEBUG("-->Running Connect Tests - B:13 - Connect with invalid private key path \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - invalidPrivKeyPathFilter = invalidPrivKeyPath; - initParams.pDevicePrivateKeyLocation = invalidPrivKeyPathFilter; - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_C(SUCCESS != rc); - - IOT_DEBUG("-->Success - B:13 - Connect with invalid private key path \n"); -} - -/* B:14 - Connect, no response timeout */ -TEST_C(ConnectTests, NoResponseTimeout) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:14 - Connect, no response timeout \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ResetTLSBuffer(); - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, rc); - - IOT_DEBUG("-->Success - B:14 - Connect, no response timeout \n"); -} - -/* B:15 - Connect, connack malformed, too large */ -TEST_C(ConnectTests, ConnackTooLarge) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:15 - Connect, connack malformed, too large \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - RxBuffer.pBuffer[1] = (char) (0x15); /* Set remaining length to a larger than expected value */ - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_C(SUCCESS != rc); - - IOT_DEBUG("-->Success - B:15 - Connect, connack malformed, too large \n"); -} - -/* B:16 - Connect, connack malformed, fixed header corrupted */ -TEST_C(ConnectTests, FixedHeaderCorrupted) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:16 - Connect, connack malformed, fixed header corrupted \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - RxBuffer.pBuffer[0] = (char) (0x00); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_C(SUCCESS != rc); - - IOT_DEBUG("-->Success - B:16 - Connect, connack malformed, fixed header corrupted \n"); -} - -/* B:17 - Connect, connack malformed, invalid remaining length */ -TEST_C(ConnectTests, InvalidRemainingLength) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:17 - Connect, connack malformed, invalid remaining length \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - RxBuffer.pBuffer[1] = (char) (0x00); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(MQTT_DECODE_REMAINING_LENGTH_ERROR, rc); - - IOT_DEBUG("-->Success - B:17 - Connect, connack malformed, invalid remaining length \n"); -} - -/* B:18 - Connect, connack returned error, unacceptable protocol version */ -TEST_C(ConnectTests, UnacceptableProtocolVersion) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:18 - Connect, connack returned error, unacceptable protocol version \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - connectParams.MQTTVersion = 7; - setTLSRxBufferForConnack(&connectParams, 0, 1); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(MQTT_CONNACK_UNACCEPTABLE_PROTOCOL_VERSION_ERROR, rc); - - IOT_DEBUG("-->Success - B:18 - Connect, connack returned error, unacceptable protocol version \n"); -} - -/* B:19 - Connect, connack returned error, identifier rejected */ -TEST_C(ConnectTests, IndentifierRejected) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:19 - Connect, connack returned error, identifier rejected \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 2); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(MQTT_CONNACK_IDENTIFIER_REJECTED_ERROR, rc); - - IOT_DEBUG("-->Success - B:19 - Connect, connack returned error, identifier rejected \n"); -} - -/* B:20 - Connect, connack returned error, Server unavailable */ -TEST_C(ConnectTests, ServerUnavailable) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:20 - Connect, connack returned error, Server unavailable \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 3); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(MQTT_CONNACK_SERVER_UNAVAILABLE_ERROR, rc); - - IOT_DEBUG("-->Success - B:20 - Connect, connack returned error, Server unavailable \n"); -} - -/* B:21 - Connect, connack returned error, bad user name or password */ -TEST_C(ConnectTests, BadUserNameOrPassword) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:21 - Connect, connack returned error, bad user name or password \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 4); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(MQTT_CONNACK_BAD_USERDATA_ERROR, rc); - - IOT_DEBUG("-->Success - B:21 - Connect, connack returned error, bad user name or password \n"); -} - -/* B:22 - Connect, connack returned error, not authorized */ -TEST_C(ConnectTests, NotAuthorized) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("\n-->Running Connect Tests - B:22 - Connect, connack returned error, not authorized \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 5); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(MQTT_CONNACK_NOT_AUTHORIZED_ERROR, rc); - - IOT_DEBUG("\n-->Success - B:22 - Connect, connack returned error, not authorized \n"); -} - -/* B:23 - Connect, connack return after half command timeout delay, success */ -TEST_C(ConnectTests, SuccessAfterDelayedConnack) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:23 - Connect, connack return after half command timeout delay, success \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - setTLSRxBufferDelay(0, (int) initParams.mqttCommandTimeout_ms/2); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - IOT_DEBUG("-->Success - B:23 - Connect, connack return after half command timeout delay, success \n"); -} - -/* B:24 - Connect, connack returned success */ -TEST_C(ConnectTests, ConnectSuccess) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:24 - Connect, connack returned success \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - IOT_DEBUG("-->Success - B:24 - Connect, connack returned success \n"); -} - -/* B:25 - Connect, flag settings and parameters are recorded in buffer */ -TEST_C(ConnectTests, FlagSettingsAndParamsAreRecordedIntoBuf) { - IoT_Error_t rc = SUCCESS; - unsigned char *currPayload = NULL; - - IOT_DEBUG("-->Running Connect Tests - B:25 - Connect, flag settings and parameters are recorded in buffer \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ResetTLSBuffer(); - ConnectMQTTParamsSetup_Detailed(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID), - QOS1, false, true, "willTopicName", (uint16_t) strlen("willTopicName"), "willMsg", - (uint16_t) strlen("willMsg"), NULL, 0, NULL, 0); - connectParams.keepAliveIntervalInSec = (1 << 16) - 1; - setTLSRxBufferForConnack(&connectParams, 0, 0); - - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - currPayload = connectTxBufferHeaderParser(&prfrdParams, TxBuffer.pBuffer); - CHECK_C(true == isConnectTxBufFlagCorrect(&connectParams, &prfrdParams)); - CHECK_C(true == isConnectTxBufPayloadCorrect(&connectParams, currPayload)); - - IOT_DEBUG("-->Success - B:25 - Connect, flag settings and parameters are recorded in buffer \n"); -} - -/* B:26 - Connect attempt, Disconnect, Manually reconnect */ -TEST_C(ConnectTests, ConnectDisconnectConnect) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Connect Tests - B:26 - Connect attempt, Disconnect, Manually reconnect \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - - // connect - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - // check the is_connected call - unitTestIsMqttConnected = aws_iot_mqtt_is_client_connected(&iotClient); - CHECK_EQUAL_C_INT(true, unitTestIsMqttConnected); - - // disconnect - rc = aws_iot_mqtt_disconnect(&iotClient); - CHECK_EQUAL_C_INT(SUCCESS, rc); - // check the is_connected call - unitTestIsMqttConnected = aws_iot_mqtt_is_client_connected(&iotClient); - CHECK_EQUAL_C_INT(false, unitTestIsMqttConnected); - - ResetTLSBuffer(); - setTLSRxBufferForConnack(&connectParams, 0, 0); - - // connect - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - // check the is_connected call - unitTestIsMqttConnected = aws_iot_mqtt_is_client_connected(&iotClient); - CHECK_EQUAL_C_INT(true, unitTestIsMqttConnected); - - IOT_DEBUG("-->Success - B:26 - Connect attempt, Disconnect, Manually reconnect \n"); -} - -/* B:27 - Connect attempt, Clean session, Subscribe - * connect with clean session true and subscribe to a topic1, set msg to topic1 and ensure it is received - * connect cs false, set msg to topic1 and nothing should come in, Sub to topic2 and check if msg is received - * connect cs false and send msg to topic2 and should be received - * cs true and everything should be clean again - */ -TEST_C(ConnectTests, cleanSessionInitSubscribers) { - IoT_Error_t rc = SUCCESS; - char expectedCallbackString[] = "msg topic"; - - IOT_DEBUG("-->Running Connect Tests - B:27 - Connect attempt, Clean session, Subscribe \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - ResetTLSBuffer(); - - //1. connect with clean session true and - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - connectParams.isCleanSession = true; - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - //1. subscribe to a topic1 and - testPubMsgParams.payload = expectedCallbackString; - testPubMsgParams.payloadLen = (uint16_t) strlen(expectedCallbackString); - setTLSRxBufferForSuback(subTopic1, strlen(subTopic1), QOS0, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, subTopic1, (uint16_t) strlen(subTopic1), QOS0, iot_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ResetTLSBuffer(); - //1. receive message - setTLSRxBufferWithMsgOnSubscribedTopic(subTopic1, strlen(subTopic1), QOS0, testPubMsgParams, - expectedCallbackString); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgStringclean); - - ResetTLSBuffer(); - rc = aws_iot_mqtt_disconnect(&iotClient); - - //2. connect cs false and - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - connectParams.isCleanSession = false; - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ResetTLSBuffer(); - //3. set msg to topic1 and should receive the topic1 message - snprintf(CallbackMsgStringclean, 100, NO_MSG_XXXX); - setTLSRxBufferWithMsgOnSubscribedTopic(subTopic1, strlen(subTopic1), QOS0, testPubMsgParams, - expectedCallbackString); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgStringclean); - - ResetTLSBuffer(); - //4. ,sub to topic2 - snprintf(CallbackMsgStringclean, 100, NO_MSG_XXXX); - setTLSRxBufferForSuback(subTopic1, strlen(subTopic1), QOS0, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, subTopic2, (uint16_t) strlen(subTopic2), QOS0, iot_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ResetTLSBuffer(); - //5. and check if topic 2 msg is received - setTLSRxBufferWithMsgOnSubscribedTopic(subTopic2, strlen(subTopic2), QOS0, testPubMsgParams, - expectedCallbackString); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgStringclean); - - rc = aws_iot_mqtt_disconnect(&iotClient); - - //6. connect cs false and - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - connectParams.isCleanSession = false; - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - //7. set msg to topic2 and - snprintf(CallbackMsgStringclean, 100, NO_MSG_XXXX); - setTLSRxBufferWithMsgOnSubscribedTopic(subTopic2, strlen(subTopic2), QOS0, testPubMsgParams, - expectedCallbackString); - //8. should be received - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgStringclean); - - IOT_DEBUG("-->Success - B:27 - Connect attempt, Clean session, Subscribe \n"); - -} - -/* B:28 - Connect attempt, power cycle with clean session false - * This test is to ensure we can initialize the subscribe table in mqtt even when connecting with CS = false - * currently the AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS is set to 5 - */ -TEST_C(ConnectTests, PowerCycleWithCleanSessionFalse) { - IoT_Error_t rc = SUCCESS; - int itr = 0; - char subTestTopic[12]; - uint16_t subTestTopicLen = 0; - - IOT_DEBUG("-->Running Connect Tests - B:28 - Connect attempt, power cycle with clean session false \n"); - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - ResetTLSBuffer(); - - //1. connect with clean session false and - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - connectParams.isCleanSession = true; - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - //2. subscribe to max number of topics - for(itr = 0; itr < AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; itr++) { - snprintf(subTestTopic, 12, "sdk/topic%d", itr + 1); - subTestTopicLen = (uint16_t) strlen(subTestTopic); - setTLSRxBufferForSuback(subTestTopic, subTestTopicLen, QOS0, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, subTestTopic, subTestTopicLen, QOS0, iot_subscribe_callback_handler, - NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - } - - //3. Subscribe to one more topic. Should return error - snprintf(subTestTopic, 12, "sdk/topic%d", itr + 1); - subTestTopicLen = (uint16_t) strlen(subTestTopic); - setTLSRxBufferForSuback(subTestTopic, subTestTopicLen, QOS0, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, subTestTopic, subTestTopicLen, QOS0, iot_subscribe_callback_handler, - NULL); - CHECK_EQUAL_C_INT(MQTT_MAX_SUBSCRIPTIONS_REACHED_ERROR, rc); - - IOT_DEBUG("-->Success - B:28 - Connect attempt, power cycle with clean session false \n"); -} - -/* B:29 - Reconnect attempt succeeds, but resubscribes fail. - * This test verifies the behaviour that if a subscribe operation fails after - * connect during the auto-reconnect sequence, the client must not disconnect - * and must only re-attempt the subscribe operation. */ -TEST_C(ConnectTests, ReconnectAndResubscribe) { - IoT_Error_t rc = SUCCESS; - int itr = 0; - char subTestTopic[12] = { 0 }; - uint16_t subTestTopicLen = 0; - IoT_Publish_Message_Params publish = { 0 }; - - IOT_DEBUG("-->Running Connect Tests - B:29 - Reconnect attempt succeeds, but resubscribes fail \n"); - - #if AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS < 3 - #error "ReconnectAndResubscribe needs at least 3 subscription handlers to run" - #endif - - // 1. Initialize client - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, true, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - ResetTLSBuffer(); - - // 2. Establish connection - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - connectParams.isCleanSession = true; - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - // 3. Add 3 subscriptions - for(itr = 0; itr < 3; itr++) - { - snprintf(subTestTopic, 12, "sdk/topic%d", itr + 1); - subTestTopicLen = (uint16_t) strlen(subTestTopic); - setTLSRxBufferForSuback(subTestTopic, subTestTopicLen, QOS0, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, subTestTopic, subTestTopicLen, QOS0, iot_subscribe_callback_handler, - NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - } - - // 4. Trigger a reconnect by mocking NETWORK_SSL_READ_ERROR and calling yield. - // Place a CONNACK and SUBACK in the Rx buffer so that connect and 1 subscribe - // succeed. Note that the CONNACK and SUBACK placed in the Rx buffer are not - // effected by the mocked error as it does not change thr content of the Rx - // buffer. - setTLSRxBufferForError(NETWORK_SSL_READ_ERROR); - setTLSRxBufferForConnackAndSuback(&connectParams, 0, "sdk/topic0", 10, QOS0); - rc = aws_iot_mqtt_yield(&iotClient, AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL * 2); - - // 5. Check results of yield call. As only 1 SUBACK was present in the Rx - // buffer, 2 resubscribes must fail. Client should be in a pending - // resubscribe state and the auto reconnect interval should have doubled. - CHECK_EQUAL_C_INT(NETWORK_ATTEMPTING_RECONNECT, rc); - CHECK_EQUAL_C_INT(1, iotClient.clientData.messageHandlers[0].resubscribed); - CHECK_EQUAL_C_INT(0, iotClient.clientData.messageHandlers[1].resubscribed); - CHECK_EQUAL_C_INT(0, iotClient.clientData.messageHandlers[2].resubscribed); - CHECK_EQUAL_C_INT(CLIENT_STATE_CONNECTED_RESUBSCRIBE_IN_PROGRESS, aws_iot_mqtt_get_client_state(&iotClient)); - CHECK_EQUAL_C_INT(2 * AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL, (int) iotClient.clientData.currentReconnectWaitInterval); - - // 6. Add 2 more SUBACKs to the Rx buffer to complete the resubscribe. - setTLSRxBufferForDoubleSuback("sdk/topic1", 10, QOS0, publish); - rc = aws_iot_mqtt_yield(&iotClient, 2 * AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL * 2); - CHECK_EQUAL_C_INT(CLIENT_STATE_CONNECTED_IDLE, aws_iot_mqtt_get_client_state(&iotClient)); - CHECK_EQUAL_C_INT(1, iotClient.clientData.messageHandlers[0].resubscribed); - CHECK_EQUAL_C_INT(1, iotClient.clientData.messageHandlers[1].resubscribed); - CHECK_EQUAL_C_INT(1, iotClient.clientData.messageHandlers[2].resubscribed); - - IOT_DEBUG("-->Success - B:29 - Reconnect attempt succeeds, but resubscribes fail \n"); -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_disconnect.cpp b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_disconnect.cpp deleted file mode 100644 index 09edca39b..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_disconnect.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_disconnect.cpp - * @brief IoT Client Unit Testing - Disconnect API Tests - */ - -#include -#include - -TEST_GROUP_C(DisconnectTests){ - TEST_GROUP_C_SETUP_WRAPPER(DisconnectTests) - TEST_GROUP_C_TEARDOWN_WRAPPER(DisconnectTests) -}; - -/* F:1 - Disconnect with Null/empty client instance */ -TEST_GROUP_C_WRAPPER(DisconnectTests, NullClientDisconnect) -/* F:2 - Set Disconnect Handler with Null/empty Client */ -TEST_GROUP_C_WRAPPER(DisconnectTests, NullClientSetDisconnectHandler) -/* F:3 - Call Set Disconnect handler with Null handler */ -TEST_GROUP_C_WRAPPER(DisconnectTests, SetDisconnectHandlerNullHandler) -/* F:4 - Disconnect attempt, not connected */ -TEST_GROUP_C_WRAPPER(DisconnectTests, disconnectNotConnected) -/* F:5 - Disconnect success */ -TEST_GROUP_C_WRAPPER(DisconnectTests, disconnectNoAckSuccess) -/* F:6 - Disconnect, Handler invoked on disconnect */ -TEST_GROUP_C_WRAPPER(DisconnectTests, HandlerInvokedOnDisconnect) -/* F:7 - Disconnect, with set handler and invoked on disconnect */ -TEST_GROUP_C_WRAPPER(DisconnectTests, SetHandlerAndInvokedOnDisconnect) diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_disconnect_helper.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_disconnect_helper.c deleted file mode 100644 index 681862b43..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_disconnect_helper.c +++ /dev/null @@ -1,244 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_disconnect_helper.c - * @brief IoT Client Unit Testing - Disconnect Tests helper - */ - -#include -#include -#include - -#include "aws_iot_tests_unit_helper_functions.h" -#include "aws_iot_log.h" - -static IoT_Client_Init_Params initParams; -static IoT_Client_Connect_Params connectParams; -static AWS_IoT_Client iotClient; - -static bool handlerInvoked = false; - -void disconnectTestHandler(AWS_IoT_Client *pClient, void *disconHandlerParam) { - IOT_UNUSED(pClient); - IOT_UNUSED(disconHandlerParam); - - handlerInvoked = true; -} - -TEST_GROUP_C_SETUP(DisconnectTests) { - IoT_Error_t rc; - ResetTLSBuffer(); - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, true, disconnectTestHandler); - initParams.mqttCommandTimeout_ms = 2000; - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - connectParams.keepAliveIntervalInSec = 5; - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - IOT_DEBUG("MQTT Status State : %d, RC : %d\n\n", aws_iot_mqtt_get_client_state(&iotClient), rc); - - ResetTLSBuffer(); -} - -TEST_GROUP_C_TEARDOWN(DisconnectTests) { } - - -/* F:1 - Disconnect with Null/empty client instance */ -TEST_C(DisconnectTests, NullClientDisconnect) { - IoT_Error_t rc = aws_iot_mqtt_disconnect(NULL); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -/* F:2 - Set Disconnect Handler with Null/empty Client */ -TEST_C(DisconnectTests, NullClientSetDisconnectHandler) { - IoT_Error_t rc = aws_iot_mqtt_set_disconnect_handler(NULL, disconnectTestHandler, NULL); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -/* F:3 - Call Set Disconnect handler with Null handler */ -TEST_C(DisconnectTests, SetDisconnectHandlerNullHandler) { - IoT_Error_t rc = aws_iot_mqtt_set_disconnect_handler(&iotClient, NULL, NULL); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -/* F:4 - Disconnect attempt, not connected */ -TEST_C(DisconnectTests, disconnectNotConnected) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Disconnect Tests - F:4 - Disconnect attempt, not connected \n"); - - /* First make sure client is disconnected */ - rc = aws_iot_mqtt_disconnect(&iotClient); - - /* Check client is disconnected */ - CHECK_EQUAL_C_INT(false, aws_iot_mqtt_is_client_connected(&iotClient)); - - /* Now call disconnect again */ - rc = aws_iot_mqtt_disconnect(&iotClient); - CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc); - - IOT_DEBUG("-->Success - F:4 - Disconnect attempt, not connected \n"); -} - -/* F:5 - Disconnect success */ -TEST_C(DisconnectTests, disconnectNoAckSuccess) { - IoT_Error_t rc = SUCCESS; - rc = aws_iot_mqtt_disconnect(&iotClient); - CHECK_EQUAL_C_INT(SUCCESS, rc); -} - -/* F:6 - Disconnect, Handler invoked on disconnect */ -TEST_C(DisconnectTests, HandlerInvokedOnDisconnect) { - bool connected = false; - bool currentAutoReconnectStatus = false; - int i; - int j; - int attempt = 3; - uint32_t dcCount = 0; - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Disconnect Tests - F:6 - Disconnect, Handler invoked on disconnect \n"); - - handlerInvoked = false; - - IOT_DEBUG("Current Keep Alive Interval is set to %d sec.\n", connectParams.keepAliveIntervalInSec); - currentAutoReconnectStatus = aws_iot_is_autoreconnect_enabled(&iotClient); - - connected = aws_iot_mqtt_is_client_connected(&iotClient); - CHECK_EQUAL_C_INT(1, connected); - - aws_iot_mqtt_autoreconnect_set_status(&iotClient, false); - - // 3 cycles of half keep alive time expiring - // verify a ping request is sent and give a ping response - for(i = 0; i < attempt; i++) { - /* Set TLS buffer for ping response */ - ResetTLSBuffer(); - setTLSRxBufferForPingresp(); - for(j = 0; j <= connectParams.keepAliveIntervalInSec; j++) { - sleep(1); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - } - CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePingreq()); - } - - // keepalive() waits for 1/2 of keepalive time after sending ping request - // to receive a pingresponse before determining the connection is not alive - // wait for keepalive time and then yield() - sleep(connectParams.keepAliveIntervalInSec); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc); - CHECK_EQUAL_C_INT(1, isLastTLSTxMessageDisconnect()); - - connected = aws_iot_mqtt_is_client_connected(&iotClient); - CHECK_EQUAL_C_INT(0, connected); - - CHECK_EQUAL_C_INT(true, handlerInvoked); - - dcCount = aws_iot_mqtt_get_network_disconnected_count(&iotClient); - CHECK_C(1 == dcCount); - - aws_iot_mqtt_reset_network_disconnected_count(&iotClient); - - dcCount = aws_iot_mqtt_get_network_disconnected_count(&iotClient); - CHECK_C(0 == dcCount); - - ResetTLSBuffer(); - aws_iot_mqtt_autoreconnect_set_status(&iotClient, currentAutoReconnectStatus); - - IOT_DEBUG("-->Success - F:6 - Disconnect, Handler invoked on disconnect \n"); -} - - -/* F:7 - Disconnect, with set handler and invoked on disconnect */ -TEST_C(DisconnectTests, SetHandlerAndInvokedOnDisconnect) { - bool connected = false; - bool currentAutoReconnectStatus = false; - int i; - int j; - int attempt = 3; - uint32_t dcCount = 0; - IoT_Error_t rc = SUCCESS; - IOT_DEBUG("-->Running Disconnect Tests - F:7 - Disconnect, with set handler and invoked on disconnect \n"); - - handlerInvoked = false; - InitMQTTParamsSetup(&initParams, "localhost", AWS_IOT_MQTT_PORT, false, NULL); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - connectParams.keepAliveIntervalInSec = 5; - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - aws_iot_mqtt_set_disconnect_handler(&iotClient, disconnectTestHandler, NULL); - aws_iot_mqtt_autoreconnect_set_status(&iotClient, true); - - IOT_DEBUG("Current Keep Alive Interval is set to %d sec.\n", connectParams.keepAliveIntervalInSec); - currentAutoReconnectStatus = aws_iot_is_autoreconnect_enabled(&iotClient); - - connected = aws_iot_mqtt_is_client_connected(&iotClient); - CHECK_EQUAL_C_INT(1, connected); - - aws_iot_mqtt_autoreconnect_set_status(&iotClient, false); - - // 3 cycles of keep alive time expiring - // verify a ping request is sent and give a ping response - for(i = 0; i < attempt; i++) { - /* Set TLS buffer for ping response */ - ResetTLSBuffer(); - setTLSRxBufferForPingresp(); - for(j = 0; j <= connectParams.keepAliveIntervalInSec; j++) { - sleep(1); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - } - CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePingreq()); - } - ResetTLSBuffer(); - - // keepalive() waits for 1/2 of keepalive time after sending ping request - // to receive a pingresponse before determining the connection is not alive - // wait for keepalive time and then yield() - sleep(connectParams.keepAliveIntervalInSec); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc); - CHECK_EQUAL_C_INT(1, isLastTLSTxMessageDisconnect()); - - connected = aws_iot_mqtt_is_client_connected(&iotClient); - CHECK_EQUAL_C_INT(0, connected); - - CHECK_EQUAL_C_INT(true, handlerInvoked); - - dcCount = aws_iot_mqtt_get_network_disconnected_count(&iotClient); - CHECK_C(1 == dcCount); - - aws_iot_mqtt_reset_network_disconnected_count(&iotClient); - - dcCount = aws_iot_mqtt_get_network_disconnected_count(&iotClient); - CHECK_C(0 == dcCount); - - ResetTLSBuffer(); - aws_iot_mqtt_autoreconnect_set_status(&iotClient, currentAutoReconnectStatus); - - IOT_DEBUG("-->Success - F:7 - Disconnect, with set handler and invoked on disconnect \n"); -} - diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_helper_functions.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_helper_functions.c deleted file mode 100644 index 2f71b1435..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_helper_functions.c +++ /dev/null @@ -1,571 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_helper_functions.c - * @brief IoT Client Unit Testing - Helper Functions - */ - -#include -#include -#include "aws_iot_mqtt_client.h" -#include "aws_iot_tests_unit_mock_tls_params.h" -#include "aws_iot_tests_unit_helper_functions.h" -#include "aws_iot_version.h" - -#if !DISABLE_METRICS -#define SDK_METRICS_LEN 25 -#define SDK_METRICS_TEMPLATE "?SDK=C&Version=%d.%d.%d" -static char pUsernameTemp[SDK_METRICS_LEN] = {0}; -#endif - -#define CONNACK_SUBACK_PACKET_SIZE 9 -#define PUBACK_PACKET_SIZE 4 -#define SUBACK_PACKET_SIZE 5 -#define UNSUBACK_PACKET_SIZE 4 -#define PINGRESP_PACKET_SIZE 2 - -void ResetInvalidParameters(void) { - invalidEndpointFilter = NULL; - invalidRootCAPathFilter = NULL; - invalidCertPathFilter = NULL; - invalidPrivKeyPathFilter = NULL; - invalidPortFilter = 0; -} - -void InitMQTTParamsSetup(IoT_Client_Init_Params *params, char *pHost, uint16_t port, bool enableAutoReconnect, - iot_disconnect_handler disconnectHandler) { - params->pHostURL = pHost; - params->port = port; - params->mqttCommandTimeout_ms = 5000; - params->tlsHandshakeTimeout_ms = 5000; - params->enableAutoReconnect = enableAutoReconnect; - params->disconnectHandler = disconnectHandler; - params->disconnectHandlerData = NULL; - params->isSSLHostnameVerify = true; - params->pDeviceCertLocation = AWS_IOT_ROOT_CA_FILENAME; - params->pDevicePrivateKeyLocation = AWS_IOT_CERTIFICATE_FILENAME; - params->pRootCALocation = AWS_IOT_PRIVATE_KEY_FILENAME; -} - -void ConnectMQTTParamsSetup(IoT_Client_Connect_Params *params, char *pClientID, uint16_t clientIDLen) { - params->keepAliveIntervalInSec = 10; - params->isCleanSession = 1; - params->MQTTVersion = MQTT_3_1_1; - params->pClientID = pClientID; - params->clientIDLen = clientIDLen; - params->isWillMsgPresent = false; - params->pUsername = NULL; - params->usernameLen = 0; - params->pPassword = NULL; - params->passwordLen = 0; -} - -void ConnectMQTTParamsSetup_Detailed(IoT_Client_Connect_Params *params, char *pClientID, uint16_t clientIDLen, QoS qos, - bool isCleanSession, bool isWillMsgPresent, char *pWillTopicName, - uint16_t willTopicNameLen, char *pWillMessage, uint16_t willMsgLen, - char *pUsername, uint16_t userNameLen, char *pPassword, uint16_t passwordLen) { - params->keepAliveIntervalInSec = 10; - params->isCleanSession = isCleanSession; - params->MQTTVersion = MQTT_3_1_1; - params->pClientID = pClientID; - params->clientIDLen = clientIDLen; - params->pUsername = pUsername; - params->usernameLen = userNameLen; - params->pPassword = pPassword; - params->passwordLen = passwordLen; - params->isWillMsgPresent = isWillMsgPresent; - params->will.pMessage = pWillMessage; - params->will.msgLen = willMsgLen; - params->will.pTopicName = pWillTopicName; - params->will.topicNameLen = willTopicNameLen; - params->will.qos = qos; - params->will.isRetained = false; -} - -void printBuffer(unsigned char *buffer, size_t len) { - size_t i; - printf("\n--\n"); - for(i = 0; i < len; i++) { - printf("%d: %c, %d\n", (uint32_t)i, buffer[i], buffer[i]); - } - printf("\n--\n"); -} - -#define CONNACK_PACKET_SIZE 4 - -void setTLSRxBufferForConnack(IoT_Client_Connect_Params *params, unsigned char sessionPresent, - unsigned char connackResponseCode) { - RxBuffer.NoMsgFlag = false; - - if(params->isCleanSession) { - sessionPresent = 0; - } - - RxBuffer.pBuffer[0] = (unsigned char) (0x20); - RxBuffer.pBuffer[1] = (unsigned char) (0x02); - RxBuffer.pBuffer[2] = sessionPresent; - RxBuffer.pBuffer[3] = connackResponseCode; - - RxBuffer.len = CONNACK_PACKET_SIZE; - RxIndex = 0; -} - -void setTLSRxBufferForConnackAndSuback(IoT_Client_Connect_Params *conParams, unsigned char sessionPresent, - char *topicName, size_t topicNameLen, QoS qos) { - IOT_UNUSED(topicName); - IOT_UNUSED(topicNameLen); - - RxBuffer.NoMsgFlag = false; - - if(conParams->isCleanSession) { - sessionPresent = 0; - } - - RxBuffer.pBuffer[0] = (unsigned char) (0x20); - RxBuffer.pBuffer[1] = (unsigned char) (0x02); - RxBuffer.pBuffer[2] = sessionPresent; - RxBuffer.pBuffer[3] = (unsigned char) (0x0); - - RxBuffer.pBuffer[4] = (unsigned char) (0x90); - RxBuffer.pBuffer[5] = (unsigned char) (0x2 + 1); - // Variable header - packet identifier - RxBuffer.pBuffer[6] = (unsigned char) (2); - RxBuffer.pBuffer[7] = (unsigned char) (0); - // payload - RxBuffer.pBuffer[8] = (unsigned char) (qos); - - RxBuffer.len = CONNACK_SUBACK_PACKET_SIZE; - RxIndex = 0; -} - -void setTLSRxBufferForPuback(void) { - size_t i; - - RxBuffer.NoMsgFlag = true; - RxBuffer.len = PUBACK_PACKET_SIZE; - RxIndex = 0; - - for(i = 0; i < RxBuffer.BufMaxSize; i++) { - RxBuffer.pBuffer[i] = 0; - } - - RxBuffer.pBuffer[0] = (unsigned char) (0x40); - RxBuffer.pBuffer[1] = (unsigned char) (0x02); - RxBuffer.pBuffer[2] = (unsigned char) (0x02); - RxBuffer.pBuffer[3] = (unsigned char) (0x00); - RxBuffer.NoMsgFlag = false; -} - -void setTLSRxBufferForSubFail(void) { - RxBuffer.NoMsgFlag = false; - RxBuffer.pBuffer[0] = (unsigned char) (0x90); - RxBuffer.pBuffer[1] = (unsigned char) (0x2 + 1); - // Variable header - packet identifier - RxBuffer.pBuffer[2] = (unsigned char) (2); - RxBuffer.pBuffer[3] = (unsigned char) (0); - // payload - RxBuffer.pBuffer[4] = (unsigned char) (128); - - RxBuffer.len = SUBACK_PACKET_SIZE; - RxIndex = 0; -} - -void setTLSRxBufferForDoubleSuback(char *topicName, size_t topicNameLen, QoS qos, IoT_Publish_Message_Params params) { - IOT_UNUSED(topicName); - IOT_UNUSED(topicNameLen); - IOT_UNUSED(params); - - RxBuffer.NoMsgFlag = false; - RxBuffer.pBuffer[0] = (unsigned char) (0x90); - RxBuffer.pBuffer[1] = (unsigned char) (0x2 + 1); - // Variable header - packet identifier - RxBuffer.pBuffer[2] = (unsigned char) (2); - RxBuffer.pBuffer[3] = (unsigned char) (0); - // payload - RxBuffer.pBuffer[4] = (unsigned char) (qos); - - RxBuffer.pBuffer[5] = (unsigned char) (0x90); - RxBuffer.pBuffer[6] = (unsigned char) (0x2 + 1); - // Variable header - packet identifier - RxBuffer.pBuffer[7] = (unsigned char) (2); - RxBuffer.pBuffer[8] = (unsigned char) (0); - // payload - RxBuffer.pBuffer[9] = (unsigned char) (qos); - - RxBuffer.len = SUBACK_PACKET_SIZE * 2; - RxIndex = 0; -} - -void setTLSRxBufferForSuback(char *topicName, size_t topicNameLen, QoS qos, IoT_Publish_Message_Params params) { - IOT_UNUSED(topicName); - IOT_UNUSED(topicNameLen); - IOT_UNUSED(params); - - RxBuffer.NoMsgFlag = false; - RxBuffer.pBuffer[0] = (unsigned char) (0x90); - RxBuffer.pBuffer[1] = (unsigned char) (0x2 + 1); - // Variable header - packet identifier - RxBuffer.pBuffer[2] = (unsigned char) (2); - RxBuffer.pBuffer[3] = (unsigned char) (0); - // payload - RxBuffer.pBuffer[4] = (unsigned char) (qos); - - RxBuffer.len = SUBACK_PACKET_SIZE; - RxIndex = 0; -} - -void setTLSRxBufferForUnsuback(void) { - RxBuffer.NoMsgFlag = false; - RxBuffer.pBuffer[0] = (unsigned char) (0xB0); - RxBuffer.pBuffer[1] = (unsigned char) (0x02); - // Variable header - packet identifier - RxBuffer.pBuffer[2] = (unsigned char) (2); - RxBuffer.pBuffer[3] = (unsigned char) (0); - // No payload - RxBuffer.len = UNSUBACK_PACKET_SIZE; - RxIndex = 0; -} - -void setTLSRxBufferForPingresp(void) { - RxBuffer.NoMsgFlag = false; - RxBuffer.pBuffer[0] = (unsigned char) (0xD0); - RxBuffer.pBuffer[1] = (unsigned char) (0x00); - RxBuffer.len = PINGRESP_PACKET_SIZE; - RxIndex = 0; -} - -void setTLSRxBufferForError(IoT_Error_t error) { - RxBuffer.mockedError = error; -} - -void setTLSTxBufferForError(IoT_Error_t error) { - TxBuffer.mockedError = error; -} - -void ResetTLSBuffer(void) { - size_t i; - RxBuffer.len = 0; - RxBuffer.NoMsgFlag = true; - - for(i = 0; i < RxBuffer.BufMaxSize; i++) { - RxBuffer.pBuffer[i] = 0; - } - - RxIndex = 0; - RxBuffer.expiry_time.tv_sec = 0; - RxBuffer.expiry_time.tv_usec = 0; - TxBuffer.len = 0; - for(i = 0; i < TxBuffer.BufMaxSize; i++) { - TxBuffer.pBuffer[i] = 0; - } -} - -void setTLSRxBufferDelay(int seconds, int microseconds) { - struct timeval now, duration, result; - duration.tv_sec = seconds; - duration.tv_usec = microseconds; - - gettimeofday(&now, NULL); - timeradd(&now, &duration, &result); - RxBuffer.expiry_time.tv_sec = result.tv_sec; - RxBuffer.expiry_time.tv_usec = result.tv_usec; -} - -void setTLSRxBufferWithMsgOnSubscribedTopic(char *topicName, size_t topicNameLen, QoS qos, - IoT_Publish_Message_Params params, char *pMsg) { - size_t VariableLen = topicNameLen + 2 + 2; - size_t i = 0, cursor = 0, packetIdStartLoc = 0, payloadStartLoc = 0, VarHeaderStartLoc = 0; - size_t PayloadLen = strlen(pMsg) + 1; - - RxBuffer.NoMsgFlag = false; - RxBuffer.pBuffer[0] = (unsigned char) (0x30 | ((params.qos << 1) & 0xF));// QoS1 - cursor++; // Move the cursor - - // Remaining Length - // Translate the Remaining Length into packet bytes - encodeRemainingLength(RxBuffer.pBuffer, &cursor, VariableLen + PayloadLen); - - VarHeaderStartLoc = cursor - 1; - // Variable header - RxBuffer.pBuffer[VarHeaderStartLoc + 1] = (unsigned char) ((topicNameLen & 0xFF00) >> 8); - RxBuffer.pBuffer[VarHeaderStartLoc + 2] = (unsigned char) (topicNameLen & 0xFF); - for(i = 0; i < topicNameLen; i++) { - RxBuffer.pBuffer[VarHeaderStartLoc + 3 + i] = (unsigned char) topicName[i]; - } - - packetIdStartLoc = VarHeaderStartLoc + topicNameLen + 2; - payloadStartLoc = (packetIdStartLoc + 1); - - if(QOS0 != qos) { - // packet id only for QoS 1 or 2 - RxBuffer.pBuffer[packetIdStartLoc + 1] = 2; - RxBuffer.pBuffer[packetIdStartLoc + 2] = 3; - payloadStartLoc = packetIdStartLoc + 3; - } - - // payload - for(i = 0; i < PayloadLen; i++) { - RxBuffer.pBuffer[payloadStartLoc + i] = (unsigned char) pMsg[i]; - } - - RxBuffer.len = VariableLen + PayloadLen + 2; // 2 for fixed header - RxIndex = 0; - //printBuffer(RxBuffer.pBuffer, RxBuffer.len); -} - -unsigned char isLastTLSTxMessagePuback() { - return (unsigned char) (TxBuffer.pBuffer[0] == 0x40 ? 1 : 0); -} - -unsigned char isLastTLSTxMessagePingreq() { - return (unsigned char) (TxBuffer.pBuffer[0] == 0xC0 ? 1 : 0); -} - -unsigned char isLastTLSTxMessageDisconnect() { - return (unsigned char) (TxBuffer.pBuffer[0] == 0xE0 ? 1 : 0); -} - -unsigned char generateMultipleSubTopics(char *des, int boundary) { - int i; - int currLen = 0; - char *op1 = des; - unsigned char ret = (unsigned char) (des == NULL ? 0 : 1); - while(*op1 != '\0') { - currLen++; - op1++; - } - // Save 1 byte for terminator '\0' - for(i = 0; i < boundary - currLen - 1; i++) { - //printf("%d\n", i); - strcat(des, "a"); - } - return ret; -} - -void encodeRemainingLength(unsigned char *buf, size_t *st, size_t length) { - unsigned char c; - // watch out for the type of length, could be over flow. Limits = 256MB - // No boundary check for 256MB!! - do { - c = (unsigned char) (length % 128); - length /= 128; - if(length > 0) c |= (unsigned char) (0x80); // If there is still another byte following - buf[(*st)++] = c; - } while(length > 0); - // At this point, *st should be the next position for a new part of data in the packet -} - -unsigned char *connectTxBufferHeaderParser(ConnectBufferProofread *params, unsigned char *buf) { - unsigned char *op = buf; - // Get packet type - unsigned char *ele1 = op; - unsigned int multiplier = 1; - int cnt = 0; - unsigned char *ele2; - unsigned int x; - unsigned char *op2; - params->PacketType = *ele1; - op++; - // Get remaining length (length bytes more than 4 bytes are ignored) - params->RemainingLength = 0; - do { - ele2 = op; - params->RemainingLength += ((unsigned int) (*ele2 & (0x7F)) * multiplier); - multiplier *= 128; - cnt++; - op++; - } while((*ele2 & (0x80)) != 0 && cnt < 4); - // At this point, op should be updated to the start address of the next chunk of information - // Get protocol length - params->ProtocolLength = 0; - params->ProtocolLength += (256 * (unsigned int) (*op++)); - params->ProtocolLength += (unsigned int) (*op++); - // Get protocol name - for(x = 0; x < params->ProtocolLength; x++) { - params->ProtocolName[x] = *op; - op++; - } - // Get protocol level - params->ProtocolLevel = (unsigned int) (*op++); - // Get connect flags - params->ConnectFlag = (*op++); - // Get keepalive - op2 = op; - params->KeepAlive = 0; - params->KeepAlive += (256 * (unsigned int) (*op2++)); // get rid of the sign bit - op++; - params->KeepAlive += (unsigned int) (*op2++); - op++; - - return op; -} - -bool isConnectTxBufFlagCorrect(IoT_Client_Connect_Params *settings, ConnectBufferProofread *readRes) { - bool ret = true; - int i; - unsigned char myByte[8]; // Construct our own connect flag byte according to the settings -#if !DISABLE_METRICS - myByte[0] = (unsigned char) (1); // User Name Flag -#else - myByte[0] = (unsigned char) (settings->pUsername == NULL ? 0 : 1); // User Name Flag -#endif - myByte[1] = (unsigned char) (settings->pPassword == NULL ? 0 : 1); // Password Flag - myByte[2] = 0; // Will Retain - // QoS - if(QOS1 == settings->will.qos) { - myByte[3] = 0; - myByte[4] = 1; - } else { // default QoS is QOS0 - myByte[3] = 0; - myByte[4] = 0; - } - // - myByte[5] = (unsigned char) settings->isWillMsgPresent; // Will Flag - myByte[6] = (unsigned char) settings->isCleanSession; // Clean Session - myByte[7] = 0; // Retained - // - for(i = 0; i < 8; i++) { - if(myByte[i] != (unsigned char) (((readRes->ConnectFlag) >> (7 - i)) & 0x01)) { - printf("ex %x ac %x\n", (unsigned char) (((readRes->ConnectFlag) >> (7 - i)) & 0x01) + '0', myByte[i]); - ret = false; - break; - } - } - return ret; -} - -bool isConnectTxBufPayloadCorrect(IoT_Client_Connect_Params *settings, unsigned char *payloadBuf) { - // Construct our own payload according to the settings to see if the real one matches with it - unsigned int ClientIDLen = (unsigned int) strlen(settings->pClientID); - unsigned int WillTopicLen = (unsigned int) strlen(settings->will.pTopicName); - unsigned int WillMsgLen = (unsigned int) strlen(settings->will.pMessage); -#if !DISABLE_METRICS - if (0 == strlen(pUsernameTemp)) { - snprintf(pUsernameTemp, SDK_METRICS_LEN, SDK_METRICS_TEMPLATE, - VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH); - } - unsigned int UsernameLen = (unsigned int)strlen(pUsernameTemp); -#else - unsigned int UsernameLen = (unsigned int) settings->usernameLen; -#endif - unsigned int PasswordLen = (unsigned int) settings->passwordLen; - unsigned int myPayloadLen = ClientIDLen + 2 + WillTopicLen + 2 + WillMsgLen + UsernameLen + 2 + PasswordLen; - char *myPayload = (char *) malloc(sizeof(char) * (myPayloadLen + 1)); // reserve 1 byte for '\0' - // Construction starts... - unsigned int i; - bool ret = false; - char *op = myPayload; - *op = (char) (ClientIDLen & 0x0FF00); // MSB There is a writeInt inside paho... MQTTString.lenstring.len != 0 - op++; - *op = (char) (ClientIDLen & 0x00FF); // LSB - op++; - // ClientID - for(i = 0; i < ClientIDLen; i++) { - *op = settings->pClientID[i]; - op++; - } - if(true == settings->isWillMsgPresent) { - // WillTopic - for(i = 0; i < WillTopicLen; i++) { - *op = settings->will.pTopicName[i]; - op++; - } - // WillMsg Len - *op = (char) (WillMsgLen & 0x0FF00); // MSB - op++; - *op = (char) (WillMsgLen & 0x00FF); // LSB - op++; - // WillMsg - for(i = 0; i < WillMsgLen; i++) { - *op = settings->will.pMessage[i]; - op++; - } - } - // Username -#if !DISABLE_METRICS - for(i = 0; i < strlen(pUsernameTemp); i++) - { - *op = pUsernameTemp[i]; - op++; - } -#else - if(NULL != settings->pUsername) { - for(i = 0; i < UsernameLen; i++) { - *op = settings->pUsername[i]; - op++; - } - } -#endif - // PasswordLen + Password - if(NULL != settings->pPassword) { - *op = (char) (PasswordLen & 0x0FF00); // MSB - op++; - *op = (char) (PasswordLen & 0x00FF); // LSB - op++; - // - for(i = 0; i < PasswordLen; i++) { - *op = settings->pPassword[i]; - op++; - } - } - // - *op = '\0'; - ret = strcmp(myPayload, (const char *)payloadBuf) == 0 ? true : false; - free(myPayload); - return ret; -} - -void printPrfrdParams(ConnectBufferProofread *params) { - unsigned int i; - printf("\n----------------\n"); - printf("PacketType: %x\n", params->PacketType); - printf("RemainingLength: %u\n", params->RemainingLength); - printf("ProtocolLength: %u\n", params->ProtocolLength); - printf("ProtocolName: "); - for(i = 0; i < params->ProtocolLength; i++) { - printf("%c", params->ProtocolName[i]); - } - printf("\n"); - printf("ProtocolLevel: %u\n", params->ProtocolLevel); - printf("ConnectFlag: %x\n", params->ConnectFlag); - printf("KeepAliveInterval: %u\n", params->KeepAlive); - printf("----------------\n"); -} - -const char *getJobTopicTypeName(AwsIotJobExecutionTopicType topicType) { - switch (topicType) { - case JOB_UPDATE_TOPIC: return "JOB_UPDATE_TOPIC"; - case JOB_NOTIFY_TOPIC: return "JOB_NOTIFY_TOPIC"; - case JOB_NOTIFY_NEXT_TOPIC: return "JOB_NOTIFY_NEXT_TOPIC"; - case JOB_GET_PENDING_TOPIC: return "JOB_GET_PENDING_TOPIC"; - case JOB_DESCRIBE_TOPIC: return "JOB_DESCRIBE_TOPIC"; - case JOB_START_NEXT_TOPIC: return "JOB_START_NEXT_TOPIC"; - case JOB_WILDCARD_TOPIC: return "JOB_WILDCARD_TOPIC"; - case JOB_UNRECOGNIZED_TOPIC: return "JOB_UNRECOGNIZED_TOPIC"; - default: return "invalid"; - } -} - -const char *getJobReplyTypeName(AwsIotJobExecutionTopicReplyType replyType) { - switch (replyType) { - case JOB_REQUEST_TYPE: return "JOB_REQUEST_TYPE"; - case JOB_ACCEPTED_REPLY_TYPE: return "JOB_ACCEPTED_REPLY_TYPE"; - case JOB_REJECTED_REPLY_TYPE: return "JOB_REJECTED_REPLY_TYPE"; - case JOB_WILDCARD_REPLY_TYPE: return "JOB_WILDCARD_REPLY_TYPE"; - case JOB_UNRECOGNIZED_TOPIC_TYPE: return "JOB_UNRECOGNIZED_TOPIC_TYPE"; - default: return "invalid"; - } -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_jobs.cpp b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_jobs.cpp deleted file mode 100644 index edbf8cee4..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_jobs.cpp +++ /dev/null @@ -1,60 +0,0 @@ -/* -* Copyright 2015-2018 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 - - -TEST_GROUP_C(JobsTypesTests) { - TEST_GROUP_C_SETUP_WRAPPER(JobsTypesTests) - TEST_GROUP_C_TEARDOWN_WRAPPER(JobsTypesTests) -}; - -TEST_GROUP_C_WRAPPER(JobsTypesTests, StringToStatus) -TEST_GROUP_C_WRAPPER(JobsTypesTests, StatusToString) - -TEST_GROUP_C(JobsJsonTests) { - TEST_GROUP_C_SETUP_WRAPPER(JobsJsonTests) - TEST_GROUP_C_TEARDOWN_WRAPPER(JobsJsonTests) -}; - -TEST_GROUP_C_WRAPPER(JobsJsonTests, SerializeUpdateRequest) -TEST_GROUP_C_WRAPPER(JobsJsonTests, SerializeUpdateRequestWithNullBuffer) -TEST_GROUP_C_WRAPPER(JobsJsonTests, SerializeUpdateRequestWithTooSmallBuffer) -TEST_GROUP_C_WRAPPER(JobsJsonTests, SerializeDescribeJobExecutionRequest) -TEST_GROUP_C_WRAPPER(JobsJsonTests, SerializeDescribeJobExecutionRequestWithNullBuffer) -TEST_GROUP_C_WRAPPER(JobsJsonTests, SerializeDescribeJobExecutionRequestWithTooSmallBuffer) -TEST_GROUP_C_WRAPPER(JobsJsonTests, SerializeStartNextRequest) -TEST_GROUP_C_WRAPPER(JobsJsonTests, SerializeStartNextRequestWithNullBuffer) -TEST_GROUP_C_WRAPPER(JobsJsonTests, SerializeStartNextRequestWithTooSmallBuffer) - -TEST_GROUP_C(JobsTopicsTests) { - TEST_GROUP_C_SETUP_WRAPPER(JobsTopicsTests) - TEST_GROUP_C_TEARDOWN_WRAPPER(JobsTopicsTests) -}; - -TEST_GROUP_C_WRAPPER(JobsTopicsTests, GenerateValidTopics) -TEST_GROUP_C_WRAPPER(JobsTopicsTests, GenerateWithMissingJobId) -TEST_GROUP_C_WRAPPER(JobsTopicsTests, GenerateWithInvalidTopicOrReplyType) -TEST_GROUP_C_WRAPPER(JobsTopicsTests, GenerateWithInvalidCombinations) - -TEST_GROUP_C(JobsInterfaceTest) { - TEST_GROUP_C_SETUP_WRAPPER(JobsInterfaceTest) - TEST_GROUP_C_TEARDOWN_WRAPPER(JobsInterfaceTest) -}; - -TEST_GROUP_C_WRAPPER(JobsInterfaceTest, TestSubscribeAndUnsubscribe) -TEST_GROUP_C_WRAPPER(JobsInterfaceTest, TestSendQuery) -TEST_GROUP_C_WRAPPER(JobsInterfaceTest, TestSendUpdate) diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_jobs_interface.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_jobs_interface.c deleted file mode 100644 index c19a38d88..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_jobs_interface.c +++ /dev/null @@ -1,337 +0,0 @@ -/* -* Copyright 2015-2018 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 "aws_iot_tests_unit_mock_tls_params.h" -#include "aws_iot_tests_unit_helper_functions.h" -#include "aws_iot_config.h" -#include -#include -#include - -static AWS_IoT_Client client; -static IoT_Client_Connect_Params connectParams; -static IoT_Client_Init_Params mqttInitParams; - -static const char *THING_NAME = "T1"; -static const char *JOB_ID = "J1"; - -static int CALLBACK_DATA = 5; - -static const char *expectedTopic; -static const void *expectedData; -static size_t expectedDataLen; - -static int callbackCount = 0; - -static bool expectError; -static bool expectedJsonContext; - - -static void testCallback( - AWS_IoT_Client *pClient, - char *topicName, uint16_t topicNameLen, - IoT_Publish_Message_Params *params, void *pData) -{ - callbackCount++; - - CHECK_C(pData == &CALLBACK_DATA); - CHECK_C(pClient == &client); - - CHECK_EQUAL_C_INT((int)strlen(expectedTopic), (int)topicNameLen); - CHECK_C(strncmp(expectedTopic, topicName, (size_t) topicNameLen) == 0); - - CHECK_C(memcmp(expectedData, params->payload, expectedDataLen) == 0); -} - -TEST_GROUP_C_SETUP(JobsInterfaceTest) { - IoT_Error_t ret_val = SUCCESS; - - InitMQTTParamsSetup(&mqttInitParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - ret_val = aws_iot_mqtt_init(&client, &mqttInitParams); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - ConnectMQTTParamsSetup(&connectParams, (char *) AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - ret_val = aws_iot_mqtt_connect(&client, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - ResetTLSBuffer(); - - /* Ensure that old data can't be used */ - lastSubscribeMsgLen = 0; - lastUnsubscribeMsgLen = 0; - lastPublishMessageTopicLen = 0; - lastPublishMessagePayloadLen = 0; - - callbackCount = 0; - expectedTopic = NULL; - expectedData = NULL; - expectedDataLen = 0; - - expectError = false; - expectedJsonContext = false; -} - -TEST_GROUP_C_TEARDOWN(JobsInterfaceTest) { - IoT_Error_t rc = aws_iot_mqtt_disconnect(&client); - IOT_UNUSED(rc); -} - -static void publishTestMessage(AwsIotJobExecutionTopicType topicType, bool withJobId) { - char replyTopic[MAX_JOB_TOPIC_LENGTH_BYTES + 1]; - AwsIotJobExecutionTopicReplyType replyType; - char * message; - - if (topicType == JOB_NOTIFY_TOPIC) { - replyType = JOB_REQUEST_TYPE; - message = "{\"jobs\":{\"IN_PROGRESS\":[{}]},\"timestamp\":5}"; - } else if (topicType == JOB_NOTIFY_NEXT_TOPIC) { - replyType = JOB_REQUEST_TYPE; - message = "{\"execution\":{\"jobId\":\"J1\",\"status\":\"IN_PROGRESS\",\"queuedAt\":50,\"versionNumber\":20},\"timestamp\":5}"; - } - else { - replyType = JOB_REJECTED_REPLY_TYPE; - message = "{\"code\":\"foo\",\"message\":\"bar\", \"clientToken\":\"baz\",\"timestamp\":6}"; - } - - const char *passedJobId = NULL; - if (withJobId) { - if (topicType == JOB_WILDCARD_TOPIC) { - topicType = JOB_DESCRIBE_TOPIC; - } - passedJobId = JOB_ID; - } - - int replyTopicLen = aws_iot_jobs_get_api_topic( - replyTopic, MAX_JOB_TOPIC_LENGTH_BYTES + 1, - topicType, replyType, THING_NAME, passedJobId); - - expectedData = message; - expectedDataLen = strlen(message) + 1; - expectedTopic = replyTopic; - - IoT_Publish_Message_Params params; - params.payload = message; - params.payloadLen = strlen(message); - params.qos = QOS0; - - int preSendCount = callbackCount; - - setTLSRxBufferWithMsgOnSubscribedTopic(replyTopic, (size_t)replyTopicLen, QOS0, params, message); - IoT_Error_t error = aws_iot_mqtt_yield(&client, 100); - - CHECK_EQUAL_C_INT(SUCCESS, error); - CHECK_EQUAL_C_INT(preSendCount + 1, callbackCount); -} - -static void testSubscribeAndUnsubscribe(AwsIotJobExecutionTopicType topicType, bool withJobId) { - char expectedTopic[MAX_JOB_TOPIC_LENGTH_BYTES + 1]; - char topicBuffer[MAX_JOB_TOPIC_LENGTH_BYTES + 1]; - - IOT_DEBUG("\n-->Running Jobs Interface Tests - test subscribe/unsubscribe %s %s \n", getJobTopicTypeName(topicType), (withJobId ? "(w/ job id)" : "")); - - AwsIotJobExecutionTopicReplyType replyType; - if (topicType != JOB_NOTIFY_TOPIC && topicType != JOB_NOTIFY_NEXT_TOPIC) { - replyType = JOB_WILDCARD_REPLY_TYPE; - } else { - replyType = JOB_REQUEST_TYPE; - } - - const char *passedJobId = NULL; - if (withJobId) passedJobId = JOB_ID; - - int expectedTopicLength = aws_iot_jobs_get_api_topic( - expectedTopic, MAX_JOB_TOPIC_LENGTH_BYTES + 1, - topicType, replyType, - THING_NAME, passedJobId); - - CHECK_C(expectedTopicLength > 0 && expectedTopicLength < MAX_JOB_TOPIC_LENGTH_BYTES); - - /* Clear to make sure old data doesn't cause the test to pass when we shouldn't */ - lastSubscribeMsgLen = 0; - lastPublishMessageTopicLen = 0; - - IoT_Publish_Message_Params unused; - - setTLSRxBufferForSuback(expectedTopic, (size_t)expectedTopicLength, QOS0, unused); - - IoT_Error_t iotError; - if (topicType == JOB_WILDCARD_TOPIC && !withJobId) { - iotError = aws_iot_jobs_subscribe_to_all_job_messages( - &client, QOS0, THING_NAME, testCallback, &CALLBACK_DATA, topicBuffer, sizeof(topicBuffer)); - } else { - iotError = aws_iot_jobs_subscribe_to_job_messages( - &client, QOS0, THING_NAME, passedJobId, topicType, replyType, testCallback, &CALLBACK_DATA, topicBuffer, sizeof(topicBuffer)); - } - - CHECK_EQUAL_C_INT(SUCCESS, iotError); - - CHECK_EQUAL_C_INT(expectedTopicLength, (int)strlen(topicBuffer)); - CHECK_EQUAL_C_INT(expectedTopicLength, (int)lastSubscribeMsgLen); - CHECK_EQUAL_C_STRING(expectedTopic, topicBuffer); - CHECK_EQUAL_C_STRING(expectedTopic, LastSubscribeMessage); - - publishTestMessage(topicType, withJobId); - - LastUnsubscribeMessage[0] = 0; - lastUnsubscribeMsgLen = 0; - - setTLSRxBufferForUnsuback(); - iotError = aws_iot_jobs_unsubscribe_from_job_messages(&client, topicBuffer); - - CHECK_EQUAL_C_INT(SUCCESS, iotError); - - CHECK_EQUAL_C_STRING(expectedTopic, LastUnsubscribeMessage); - - IOT_DEBUG("-->Success - test subscribe/unsubscribe %s %s \n", getJobTopicTypeName(topicType), (withJobId ? "(w/ job id)" : "")); -} - -TEST_C(JobsInterfaceTest, TestSubscribeAndUnsubscribe) { - testSubscribeAndUnsubscribe(JOB_NOTIFY_TOPIC, false); - testSubscribeAndUnsubscribe(JOB_NOTIFY_NEXT_TOPIC, false); - testSubscribeAndUnsubscribe(JOB_DESCRIBE_TOPIC, true); - testSubscribeAndUnsubscribe(JOB_GET_PENDING_TOPIC, false); - testSubscribeAndUnsubscribe(JOB_UPDATE_TOPIC, true); - testSubscribeAndUnsubscribe(JOB_WILDCARD_TOPIC, true); - testSubscribeAndUnsubscribe(JOB_WILDCARD_TOPIC, false); - testSubscribeAndUnsubscribe(JOB_START_NEXT_TOPIC, false); -} - -static void testSendQuery(bool withJobId, bool withClientToken, AwsIotJobExecutionTopicType topicType) { - char expectedTopic[MAX_JOB_TOPIC_LENGTH_BYTES + 1]; - char topicBuffer[MAX_JOB_TOPIC_LENGTH_BYTES + 1]; - char messageBuffer[MAX_SIZE_OF_JOB_REQUEST + 1]; - - IOT_DEBUG("\n-->Running Jobs Interface Tests - test send query %s %s \n", getJobTopicTypeName(topicType), (withClientToken ? "(w/ clientToken)" : "")); - - char *clientToken = NULL; - char *bufferToPass = NULL; - size_t bufferLenToPass = 0; - if (withClientToken) { - clientToken = "FooBar"; - bufferToPass = messageBuffer; - bufferLenToPass = MAX_SIZE_OF_JOB_REQUEST + 1; - } - - const char *passedJobId = NULL; - if (withJobId) passedJobId = JOB_ID; - - int expectedTopicLength = aws_iot_jobs_get_api_topic( - expectedTopic, MAX_JOB_TOPIC_LENGTH_BYTES + 1, - topicType, JOB_REQUEST_TYPE, - THING_NAME, passedJobId); - - CHECK_C(expectedTopicLength > 0 && expectedTopicLength <= MAX_JOB_TOPIC_LENGTH_BYTES); - - LastPublishMessageTopic[0] = 0; - lastPublishMessageTopicLen = 0; - LastPublishMessagePayload[0] = 0; - lastPublishMessagePayloadLen = 0; - - setTLSRxBufferForPuback(); - IoT_Error_t iotError; - - if (topicType == JOB_DESCRIBE_TOPIC) { - AwsIotDescribeJobExecutionRequest request; - request.executionNumber = 0; - request.includeJobDocument = false; - request.clientToken = clientToken; - - iotError = aws_iot_jobs_describe( - &client, QOS0, THING_NAME, passedJobId, &request, topicBuffer, sizeof(topicBuffer), bufferToPass, bufferLenToPass); - } else if (topicType == JOB_START_NEXT_TOPIC) { - AwsIotStartNextPendingJobExecutionRequest request; - request.statusDetails = NULL; - request.clientToken = clientToken; - - iotError = aws_iot_jobs_start_next( - &client, QOS0, THING_NAME, &request, topicBuffer, sizeof(topicBuffer), messageBuffer, sizeof(messageBuffer)); - } else { - iotError = aws_iot_jobs_send_query( - &client, QOS0, THING_NAME, passedJobId, clientToken, topicBuffer, sizeof(topicBuffer), bufferToPass, bufferLenToPass, topicType); - } - - CHECK_EQUAL_C_INT(SUCCESS, iotError); - CHECK_EQUAL_C_INT(expectedTopicLength, (int)lastPublishMessageTopicLen); - CHECK_EQUAL_C_STRING(expectedTopic, LastPublishMessageTopic); - - if (withClientToken) { - CHECK_EQUAL_C_INT((int)strlen(LastPublishMessagePayload), (int)lastPublishMessagePayloadLen); - CHECK_EQUAL_C_STRING("{\"clientToken\":\"FooBar\"}", LastPublishMessagePayload); - } else if (topicType == JOB_START_NEXT_TOPIC) { - CHECK_EQUAL_C_INT(2, (int)lastPublishMessagePayloadLen); - CHECK_EQUAL_C_STRING("{}", LastPublishMessagePayload); - } else { - CHECK_EQUAL_C_INT(0, (int)lastPublishMessagePayloadLen); - } - - IOT_DEBUG("-->Success - test send query %s %s \n", getJobTopicTypeName(topicType), (withClientToken ? "(w/ clientToken)" : "")); -} - -TEST_C(JobsInterfaceTest, TestSendQuery) { - int token; - for (token = 0; token < 2; ++token) { - testSendQuery(false, token == 0, JOB_GET_PENDING_TOPIC); - testSendQuery(true, token == 0, JOB_DESCRIBE_TOPIC); - testSendQuery(false, token == 0, JOB_START_NEXT_TOPIC); - } -} - -TEST_C(JobsInterfaceTest, TestSendUpdate) { - AwsIotJobExecutionUpdateRequest updateRequest; - updateRequest.clientToken = "FooBar"; - updateRequest.status = JOB_EXECUTION_SUCCEEDED; - updateRequest.expectedVersion = 1; - updateRequest.executionNumber = 0; - updateRequest.statusDetails = NULL; - updateRequest.includeJobExecutionState = false; - updateRequest.includeJobDocument = false; - - char expectedTopic[MAX_JOB_TOPIC_LENGTH_BYTES + 1]; - char topicBuffer[MAX_JOB_TOPIC_LENGTH_BYTES + 1]; - char messageBuffer[AWS_IOT_MQTT_TX_BUF_LEN + 1]; - - IOT_DEBUG("\n-->Running Jobs Interface Tests - test send update \n"); - - int expectedTopicLength = aws_iot_jobs_get_api_topic( - expectedTopic, MAX_JOB_TOPIC_LENGTH_BYTES + 1, - JOB_UPDATE_TOPIC, JOB_REQUEST_TYPE, - THING_NAME, JOB_ID); - - CHECK_C(expectedTopicLength > 0 && expectedTopicLength <= MAX_JOB_TOPIC_LENGTH_BYTES); - - LastPublishMessageTopic[0] = 0; - lastPublishMessageTopicLen = 0; - LastPublishMessagePayload[0] = 0; - lastPublishMessagePayloadLen = 0; - - setTLSRxBufferForPuback(); - IoT_Error_t iotError; - iotError = aws_iot_jobs_send_update( - &client, QOS0, THING_NAME, JOB_ID, &updateRequest, - topicBuffer, sizeof(topicBuffer), - messageBuffer, sizeof(messageBuffer)); - - CHECK_EQUAL_C_INT(SUCCESS, iotError); - - CHECK_EQUAL_C_INT(expectedTopicLength, (int)lastPublishMessageTopicLen); - CHECK_EQUAL_C_STRING(expectedTopic, LastPublishMessageTopic); - - CHECK_EQUAL_C_STRING("{\"status\":\"SUCCEEDED\",\"expectedVersion\":1,\"clientToken\":\"FooBar\"}", LastPublishMessagePayload); - - IOT_DEBUG("-->Success - test send update \n"); -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_jobs_json.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_jobs_json.c deleted file mode 100644 index 5a04554e1..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_jobs_json.c +++ /dev/null @@ -1,244 +0,0 @@ -/* -* Copyright 2015-2018 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 -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define NUM_TOKENS 50 - -static jsmntok_t tokens[NUM_TOKENS]; - -TEST_GROUP_C_SETUP(JobsJsonTests) { -} - -TEST_GROUP_C_TEARDOWN(JobsJsonTests) { -} - -static const char *defaultUpdateRequestSerialized = - "{\"status\":\"IN_PROGRESS\",\"statusDetails\":{\"Step\":\"1\",\"StepStatus\":\"Foo\"}," - "\"executionNumber\":2,\"expectedVersion\":1,\"includeJobExecutionState\":true,\"includeJobDocument\":true,\"clientToken\":\"1234\"}"; - -static void fillDefaultUpdateRequest(AwsIotJobExecutionUpdateRequest *request) -{ - request->status = JOB_EXECUTION_IN_PROGRESS; - request->statusDetails = "{\"Step\":\"1\",\"StepStatus\":\"Foo\"}"; - request->expectedVersion = 1; - request->executionNumber = 2; - request->includeJobExecutionState = true; - request->includeJobDocument = true; - request->clientToken = "1234"; -} - -TEST_C(JobsJsonTests, SerializeUpdateRequest) { - AwsIotJobExecutionUpdateRequest updateRequest; - - IOT_DEBUG("\n-->Running Jobs Json Tests - serialize update request \n"); - - fillDefaultUpdateRequest(&updateRequest); - - char buffer[256]; - int charsUsed = aws_iot_jobs_json_serialize_update_job_execution_request(buffer, sizeof(buffer), &updateRequest); - CHECK_EQUAL_C_INT((int)strlen(defaultUpdateRequestSerialized), charsUsed); - CHECK_EQUAL_C_STRING(defaultUpdateRequestSerialized, buffer); - - jsmn_parser parser; - jsmn_init(&parser); - - int num_parsed_tokens = jsmn_parse(&parser, buffer, (size_t)charsUsed, tokens, NUM_TOKENS); - CHECK_C(num_parsed_tokens > 0); - - IOT_DEBUG("-->Success - serialize update request \n"); -} - -TEST_C(JobsJsonTests, SerializeUpdateRequestWithNullBuffer) { - AwsIotJobExecutionUpdateRequest updateRequest; - - IOT_DEBUG("\n-->Running Jobs Json Tests - serialize update request w/ null buffer \n"); - - fillDefaultUpdateRequest(&updateRequest); - - int charsUsed = aws_iot_jobs_json_serialize_update_job_execution_request(NULL, 0, &updateRequest); - CHECK_EQUAL_C_INT((int)strlen(defaultUpdateRequestSerialized), charsUsed); - - IOT_DEBUG("-->Success - serialize update request w/ null buffer \n"); -} - -TEST_C(JobsJsonTests, SerializeUpdateRequestWithTooSmallBuffer) { - AwsIotJobExecutionUpdateRequest updateRequest; - - IOT_DEBUG("\n-->Running Jobs Json Tests - serialize update request w/ too small buffer \n"); - - fillDefaultUpdateRequest(&updateRequest); - - char buffer[11]; - // A check character which shouldn't be overwritten as we pass a length of 10 - buffer[10] = -1; - - int charsUsed = aws_iot_jobs_json_serialize_update_job_execution_request(buffer, 10, &updateRequest); - CHECK_EQUAL_C_INT((int)strlen(defaultUpdateRequestSerialized), charsUsed); - - CHECK_EQUAL_C_CHAR(-1, buffer[10]); - CHECK_EQUAL_C_CHAR(0, buffer[9]); - // 9 because the 10th is \0 - CHECK_C(strncmp(defaultUpdateRequestSerialized, buffer, 9) == 0); - - IOT_DEBUG("-->Success - serialize update request w/ too small buffer \n"); -} - -static void fillDefaultDescribeJobExecutionRequest( - AwsIotDescribeJobExecutionRequest *request) -{ - request->executionNumber = 1; - request->includeJobDocument = true; - request->clientToken = "1234"; -} - -static const char *defaultDescribeJobExecutionRequestSerialized = - "{\"clientToken\":\"1234\",\"executionNumber\":1,\"includeJobDocument\":true}"; - -TEST_C(JobsJsonTests, SerializeDescribeJobExecutionRequest) { - AwsIotDescribeJobExecutionRequest describeJobExecutionRequest; - - IOT_DEBUG("\n-->Running Jobs Json Tests - serialize describe job execution request \n"); - - fillDefaultDescribeJobExecutionRequest(&describeJobExecutionRequest); - - char buffer[256]; - int charsUsed = aws_iot_jobs_json_serialize_describe_job_execution_request(buffer, 256, &describeJobExecutionRequest); - CHECK_EQUAL_C_INT((int)strlen(defaultDescribeJobExecutionRequestSerialized), charsUsed); - - CHECK_EQUAL_C_STRING(defaultDescribeJobExecutionRequestSerialized, buffer); - - jsmn_parser parser; - jsmn_init(&parser); - - int num_parsed_tokens = jsmn_parse(&parser, buffer, (size_t)charsUsed, tokens, NUM_TOKENS); - CHECK_C(num_parsed_tokens > 0); - - IOT_DEBUG("-->Success - serialize describe job execution request \n"); -} - -TEST_C(JobsJsonTests, SerializeDescribeJobExecutionRequestWithNullBuffer) { - AwsIotDescribeJobExecutionRequest describeJobExecutionRequest; - - IOT_DEBUG("\n-->Running Jobs Json Tests - serialize describe job execution request w/ null buffer \n"); - - fillDefaultDescribeJobExecutionRequest(&describeJobExecutionRequest); - - int charsUsed = aws_iot_jobs_json_serialize_describe_job_execution_request(NULL, 0, &describeJobExecutionRequest); - CHECK_EQUAL_C_INT(0, charsUsed); - - IOT_DEBUG("-->Success - serialize describe job execution request w/ null buffer \n"); -} - -TEST_C(JobsJsonTests, SerializeDescribeJobExecutionRequestWithTooSmallBuffer) { - AwsIotDescribeJobExecutionRequest describeJobExecutionRequest; - - IOT_DEBUG("\n-->Running Jobs Json Tests - serialize describe job execution request w/ too small buffer \n"); - - fillDefaultDescribeJobExecutionRequest(&describeJobExecutionRequest); - - char buffer[11]; - // A check character which shouldn't be overwritten as we pass a length of 10 - buffer[10] = -1; - - int charsUsed = aws_iot_jobs_json_serialize_describe_job_execution_request(buffer, 10, &describeJobExecutionRequest); - CHECK_EQUAL_C_INT((int)strlen(defaultDescribeJobExecutionRequestSerialized), charsUsed); - - CHECK_EQUAL_C_CHAR(-1, buffer[10]); - CHECK_EQUAL_C_CHAR(0, buffer[9]); - // 9 because the 10th is \0 - CHECK_C(strncmp(defaultDescribeJobExecutionRequestSerialized, buffer, 9) == 0); - - IOT_DEBUG("-->Success - serialize describe job execution request w/ too small buffer \n"); -} - -static void fillDefaultStartNextRequest(AwsIotStartNextPendingJobExecutionRequest *request) -{ - request->statusDetails = "{\"Step\":\"1\",\"StepStatus\":\"Foo\"}"; - request->clientToken = "1234"; -} - -static const char *defaultStartNextRequestSerialized = - "{\"statusDetails\":{\"Step\":\"1\",\"StepStatus\":\"Foo\"},\"clientToken\":\"1234\"}"; - -TEST_C(JobsJsonTests, SerializeStartNextRequest) { - AwsIotStartNextPendingJobExecutionRequest startNextRequest; - fillDefaultStartNextRequest(&startNextRequest); - - IOT_DEBUG("\n-->Running Jobs Json Tests - serialize start next request \n"); - - char buffer[256]; - int charsUsed = aws_iot_jobs_json_serialize_start_next_job_execution_request(buffer, 256, &startNextRequest); - CHECK_EQUAL_C_INT((int)strlen(defaultStartNextRequestSerialized), charsUsed); - - CHECK_EQUAL_C_STRING(defaultStartNextRequestSerialized, buffer); - jsmn_parser parser; - jsmn_init(&parser); - - int num_parsed_tokens = jsmn_parse(&parser, buffer, (size_t)charsUsed, tokens, NUM_TOKENS); - CHECK_C(num_parsed_tokens > 0); - - IOT_DEBUG("-->Success - serialize start next request \n"); -} - -TEST_C(JobsJsonTests, SerializeStartNextRequestWithNullBuffer) { - AwsIotStartNextPendingJobExecutionRequest startNextRequest; - - IOT_DEBUG("\n-->Running Jobs Json Tests - serialize start next request w/ null buffer \n"); - - fillDefaultStartNextRequest(&startNextRequest); - - int charsUsed = aws_iot_jobs_json_serialize_start_next_job_execution_request(NULL, 0, &startNextRequest); - CHECK_EQUAL_C_INT((int)strlen(defaultStartNextRequestSerialized), charsUsed); - - IOT_DEBUG("-->Success - serialize start next request w/ null buffer \n"); -} - -TEST_C(JobsJsonTests, SerializeStartNextRequestWithTooSmallBuffer) { - AwsIotStartNextPendingJobExecutionRequest startNextRequest; - - IOT_DEBUG("\n-->Running Jobs Json Tests - serialize start next request w/ too small buffer \n"); - - fillDefaultStartNextRequest(&startNextRequest); - - char buffer[11]; - // A check character which shouldn't be overwritten as we pass a length of 10 - buffer[10] = -1; - - int charsUsed = aws_iot_jobs_json_serialize_start_next_job_execution_request(buffer, 10, &startNextRequest); - CHECK_EQUAL_C_INT((int) strlen(defaultStartNextRequestSerialized), charsUsed); - - CHECK_EQUAL_C_CHAR(-1, buffer[10]); - CHECK_EQUAL_C_CHAR(0, buffer[9]); - // 9 because the 10th is \0 - CHECK_C(strncmp(defaultStartNextRequestSerialized, buffer, 9) == 0); - - IOT_DEBUG("-->Success - serialize start next request w/ too small buffer \n"); -} - -#ifdef __cplusplus -} -#endif diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_jobs_topics.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_jobs_topics.c deleted file mode 100644 index b6c6ace08..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_jobs_topics.c +++ /dev/null @@ -1,161 +0,0 @@ -/* -* Copyright 2015-2018 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 "aws_iot_jobs_topics.h" -#include -#include -#include -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -TEST_GROUP_C_SETUP(JobsTopicsTests) { -} - -TEST_GROUP_C_TEARDOWN(JobsTopicsTests) { -} - -#define TEST_THING_NAME "TestThing" -#define TEST_TOPIC_PREFIX "$aws/things/" TEST_THING_NAME "/jobs" -#define TEST_JOB_ID "TestJob" -#define TEST_NEXT_JOB_ID "$next" -#define TEST_TOPIC_W_JOB_PREFIX TEST_TOPIC_PREFIX "/" TEST_JOB_ID - -static int generateTopicForTestThingAndJob( - char *buffer, size_t bufferSize, - AwsIotJobExecutionTopicType topicType, AwsIotJobExecutionTopicReplyType replyType) -{ - return aws_iot_jobs_get_api_topic( - buffer, bufferSize, topicType, replyType, TEST_THING_NAME, TEST_JOB_ID); -} - -static int generateTopicForTestThing( - char *buffer, size_t bufferSize, - AwsIotJobExecutionTopicType topicType, AwsIotJobExecutionTopicReplyType replyType) -{ - return aws_iot_jobs_get_api_topic( - buffer, bufferSize, topicType, replyType, TEST_THING_NAME, NULL); -} - -static void testGenerateValidApiTopic( - AwsIotJobExecutionTopicType topicType, AwsIotJobExecutionTopicReplyType replyType, - bool includeThingName, const char *expectedOutput) -{ - int requestedSize; - int expectedSize = (int)strlen(expectedOutput); - - IOT_DEBUG("\n-->Running Jobs Topics Tests - generate valid topics %s w/ reply type \n", getJobTopicTypeName(topicType), getJobReplyTypeName(replyType)); - - if (includeThingName) { - requestedSize = generateTopicForTestThingAndJob(NULL, 0, topicType, replyType); - CHECK_EQUAL_C_INT(expectedSize, requestedSize); - } else { - requestedSize = generateTopicForTestThing(NULL, 0, topicType, replyType); - CHECK_EQUAL_C_INT(expectedSize, requestedSize); - } - - CHECK_C(requestedSize > 3); - char *buffer = (char *) malloc((size_t)(requestedSize + 1) * sizeof(char)); - buffer[3] = -1; - - if (includeThingName) { - requestedSize = generateTopicForTestThingAndJob(buffer, 3, topicType, replyType); - } else { - requestedSize = generateTopicForTestThing(buffer, 3, topicType, replyType); - } - CHECK_EQUAL_C_INT(expectedSize, requestedSize); - - CHECK_EQUAL_C_CHAR(expectedOutput[0], buffer[0]); - CHECK_EQUAL_C_CHAR(expectedOutput[1], buffer[1]); - CHECK_EQUAL_C_CHAR('\0', buffer[2]); - CHECK_EQUAL_C_CHAR(-1, buffer[3]); - - if (includeThingName) { - requestedSize = generateTopicForTestThingAndJob(buffer, (size_t)requestedSize + 1, topicType, replyType); - } else { - requestedSize = generateTopicForTestThing(buffer, (size_t)requestedSize + 1, topicType, replyType); - } - - CHECK_EQUAL_C_INT(expectedSize, requestedSize); - CHECK_EQUAL_C_STRING(expectedOutput, buffer); - - free(buffer); - - IOT_DEBUG("-->Success - generate valid topics %s w/ reply type \n", getJobTopicTypeName(topicType), getJobReplyTypeName(replyType)); -} - -static void testGenerateValidApiTopicWithAllReplyTypes( - AwsIotJobExecutionTopicType topicType, bool includeThingName, - const char *expectedBaseTopic) -{ - char buffer[1024]; - - testGenerateValidApiTopic( - topicType, JOB_REQUEST_TYPE, includeThingName, expectedBaseTopic); - - snprintf(buffer, 1024, "%s/accepted", expectedBaseTopic); - testGenerateValidApiTopic( - topicType, JOB_ACCEPTED_REPLY_TYPE, includeThingName, buffer); - - snprintf(buffer, 1024, "%s/rejected", expectedBaseTopic); - testGenerateValidApiTopic( - topicType, JOB_REJECTED_REPLY_TYPE, includeThingName, buffer); - - snprintf(buffer, 1024, "%s/+", expectedBaseTopic); - testGenerateValidApiTopic( - topicType, JOB_WILDCARD_REPLY_TYPE, includeThingName, buffer); - -} - -TEST_C(JobsTopicsTests, GenerateValidTopics) { - testGenerateValidApiTopicWithAllReplyTypes(JOB_UPDATE_TOPIC, true, TEST_TOPIC_W_JOB_PREFIX "/update"); - testGenerateValidApiTopicWithAllReplyTypes(JOB_DESCRIBE_TOPIC, true, TEST_TOPIC_W_JOB_PREFIX "/get"); - testGenerateValidApiTopicWithAllReplyTypes(JOB_WILDCARD_TOPIC, true, TEST_TOPIC_W_JOB_PREFIX "/+"); - testGenerateValidApiTopic(JOB_WILDCARD_TOPIC, JOB_REQUEST_TYPE, false, TEST_TOPIC_PREFIX "/#"); - testGenerateValidApiTopic(JOB_NOTIFY_TOPIC, JOB_REQUEST_TYPE, false, TEST_TOPIC_PREFIX "/notify"); - testGenerateValidApiTopic(JOB_NOTIFY_NEXT_TOPIC, JOB_REQUEST_TYPE, false, TEST_TOPIC_PREFIX "/notify-next"); - testGenerateValidApiTopic(JOB_START_NEXT_TOPIC, JOB_REQUEST_TYPE, false, TEST_TOPIC_PREFIX "/start-next"); -} - -TEST_C(JobsTopicsTests, GenerateWithMissingJobId) { - CHECK_EQUAL_C_INT(-1, generateTopicForTestThing(NULL, 0, JOB_UPDATE_TOPIC, JOB_REQUEST_TYPE)); - CHECK_EQUAL_C_INT(-1, generateTopicForTestThing(NULL, 0, JOB_DESCRIBE_TOPIC, JOB_REQUEST_TYPE)); -} - -TEST_C(JobsTopicsTests, GenerateWithInvalidTopicOrReplyType) { - CHECK_EQUAL_C_INT(-1, generateTopicForTestThing(NULL, 0, JOB_UNRECOGNIZED_TOPIC, JOB_REQUEST_TYPE)); - CHECK_EQUAL_C_INT(-1, generateTopicForTestThing(NULL, 0, -1, JOB_REQUEST_TYPE)); - - CHECK_EQUAL_C_INT(-1, generateTopicForTestThing(NULL, 0, JOB_DESCRIBE_TOPIC, JOB_UNRECOGNIZED_TOPIC_TYPE)); - CHECK_EQUAL_C_INT(-1, generateTopicForTestThing(NULL, 0, JOB_DESCRIBE_TOPIC, -1)); -} - -TEST_C(JobsTopicsTests, GenerateWithInvalidCombinations) { - CHECK_EQUAL_C_INT(-1, generateTopicForTestThing(NULL, 0, JOB_NOTIFY_TOPIC, JOB_ACCEPTED_REPLY_TYPE)); - CHECK_EQUAL_C_INT(-1, generateTopicForTestThing(NULL, 0, JOB_NOTIFY_TOPIC, JOB_REJECTED_REPLY_TYPE)); - CHECK_EQUAL_C_INT(-1, generateTopicForTestThing(NULL, 0, JOB_NOTIFY_TOPIC, JOB_WILDCARD_REPLY_TYPE)); - CHECK_EQUAL_C_INT(-1, generateTopicForTestThing(NULL, 0, JOB_NOTIFY_NEXT_TOPIC, JOB_ACCEPTED_REPLY_TYPE)); - CHECK_EQUAL_C_INT(-1, generateTopicForTestThing(NULL, 0, JOB_NOTIFY_NEXT_TOPIC, JOB_REJECTED_REPLY_TYPE)); - CHECK_EQUAL_C_INT(-1, generateTopicForTestThing(NULL, 0, JOB_NOTIFY_NEXT_TOPIC, JOB_WILDCARD_REPLY_TYPE)); -} - -#ifdef __cplusplus -} -#endif diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_jobs_types.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_jobs_types.c deleted file mode 100644 index 60dc8c9d3..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_jobs_types.c +++ /dev/null @@ -1,70 +0,0 @@ -/* -* Copyright 2015-2018 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 -#include - -#ifdef __cplusplus -extern "C" { -#endif - -TEST_GROUP_C_SETUP(JobsTypesTests) { -} - -TEST_GROUP_C_TEARDOWN(JobsTypesTests) { -} - -TEST_C(JobsTypesTests, StringToStatus) { - char emptyString = '\0'; - - IOT_DEBUG("\n-->Running Jobs Types Tests - string to status \n"); - - CHECK_EQUAL_C_INT((int)JOB_EXECUTION_STATUS_NOT_SET, (int)aws_iot_jobs_map_string_to_job_status(NULL)); - CHECK_EQUAL_C_INT((int)JOB_EXECUTION_STATUS_NOT_SET, (int)aws_iot_jobs_map_string_to_job_status(&emptyString)); - CHECK_EQUAL_C_INT((int)JOB_EXECUTION_QUEUED, (int)aws_iot_jobs_map_string_to_job_status("QUEUED")); - CHECK_EQUAL_C_INT((int)JOB_EXECUTION_IN_PROGRESS, (int)aws_iot_jobs_map_string_to_job_status("IN_PROGRESS")); - CHECK_EQUAL_C_INT((int)JOB_EXECUTION_FAILED, (int)aws_iot_jobs_map_string_to_job_status("FAILED")); - CHECK_EQUAL_C_INT((int)JOB_EXECUTION_SUCCEEDED, (int)aws_iot_jobs_map_string_to_job_status("SUCCEEDED")); - CHECK_EQUAL_C_INT((int)JOB_EXECUTION_CANCELED, (int)aws_iot_jobs_map_string_to_job_status("CANCELED")); - CHECK_EQUAL_C_INT((int)JOB_EXECUTION_REJECTED, (int)aws_iot_jobs_map_string_to_job_status("REJECTED")); - CHECK_EQUAL_C_INT((int)JOB_EXECUTION_UNKNOWN_STATUS, (int)aws_iot_jobs_map_string_to_job_status("invalidStatus")); - - IOT_DEBUG("-->Success - string to status \n"); -} - -TEST_C(JobsTypesTests, StatusToString) { - IOT_DEBUG("\n-->Running Jobs Types Tests - status to string \n"); - - CHECK_EQUAL_C_STRING("QUEUED", aws_iot_jobs_map_status_to_string(JOB_EXECUTION_QUEUED)); - CHECK_EQUAL_C_STRING("IN_PROGRESS", aws_iot_jobs_map_status_to_string(JOB_EXECUTION_IN_PROGRESS)); - CHECK_EQUAL_C_STRING("FAILED", aws_iot_jobs_map_status_to_string(JOB_EXECUTION_FAILED)); - CHECK_EQUAL_C_STRING("SUCCEEDED", aws_iot_jobs_map_status_to_string(JOB_EXECUTION_SUCCEEDED)); - CHECK_EQUAL_C_STRING("CANCELED", aws_iot_jobs_map_status_to_string(JOB_EXECUTION_CANCELED)); - CHECK_EQUAL_C_STRING("REJECTED", aws_iot_jobs_map_status_to_string(JOB_EXECUTION_REJECTED)); - CHECK_EQUAL_C_STRING(NULL, aws_iot_jobs_map_status_to_string(JOB_EXECUTION_STATUS_NOT_SET)); - CHECK_EQUAL_C_STRING(NULL, aws_iot_jobs_map_status_to_string(JOB_EXECUTION_UNKNOWN_STATUS)); - - IOT_DEBUG("-->Success - status to string \n"); -} - -#ifdef __cplusplus -} -#endif diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_json_utils.cpp b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_json_utils.cpp deleted file mode 100644 index f1fe2e33b..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_json_utils.cpp +++ /dev/null @@ -1,91 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_json_utils.cpp - * @brief IoT Client Unit Testing - JSON Utility Tests - */ - -#include -#include - -TEST_GROUP_C(JsonUtils) { - TEST_GROUP_C_SETUP_WRAPPER(JsonUtils) - TEST_GROUP_C_TEARDOWN_WRAPPER(JsonUtils) -}; - -TEST_GROUP_C_WRAPPER(JsonUtils, ParseStringBasic) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseStringLongerStringIsValid) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseStringWithBufferTooSmall) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseStringEmptyStringIsValid) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseStringErrorOnInteger) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseStringErrorOnBoolean) - -TEST_GROUP_C_WRAPPER(JsonUtils, ParseBooleanTrue) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseBooleanFalse) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseBooleanErrorOnString) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseBooleanErrorOnInvalidJson) - -TEST_GROUP_C_WRAPPER(JsonUtils, ParseDoubleBasic) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseDoubleNumberWithNoDecimal) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseDoubleSmallDouble) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseDoubleErrorOnString) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseDoubleErrorOnBoolean) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseDoubleErrorOnJsonObject) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseDoubleNegativeNumber) - -TEST_GROUP_C_WRAPPER(JsonUtils, ParseFloatBasic) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseFloatNumberWithNoDecimal) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseFloatSmallFloat) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseFloatErrorOnString) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseFloatErrorOnBoolean) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseFloatErrorOnJsonObject) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseFloatNegativeNumber) - -TEST_GROUP_C_WRAPPER(JsonUtils, ParseIntegerBasic) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseIntegerLargeInteger) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseIntegerNegativeInteger) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseIntegerErrorOnBoolean) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseIntegerErrorOnString) - -TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger16bitBasic) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger16bitLargeInteger) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger16bitNegativeInteger) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger16bitErrorOnBoolean) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger16bitErrorOnString) - -TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger8bitBasic) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger8bitLargeInteger) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger8bitNegativeInteger) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger8bitErrorOnBoolean) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseInteger8bitErrorOnString) - -TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedIntegerBasic) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedIntegerLargeInteger) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedIntegerErrorOnNegativeInteger) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedIntegerErrorOnBoolean) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedIntegerErrorOnString) - -TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger16bitBasic) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger16bitLargeInteger) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger16bitErrorOnNegativeInteger) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger16bitErrorOnBoolean) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger16bitErrorOnString) - -TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger8bitBasic) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger8bitLargeInteger) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger8bitErrorOnNegativeInteger) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger8bitErrorOnBoolean) -TEST_GROUP_C_WRAPPER(JsonUtils, ParseUnsignedInteger8bitErrorOnString) diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_json_utils_helper.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_json_utils_helper.c deleted file mode 100644 index 864d379d7..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_json_utils_helper.c +++ /dev/null @@ -1,834 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_json_utils_helper.c - * @brief IoT Client Unit Testing - JSON Utility Tests helper - */ - -#include -#include -#include -#include - -#include "aws_iot_json_utils.h" -#include "aws_iot_tests_unit_helper_functions.h" -#include "aws_iot_log.h" - -#define STRING_BUFFER_LENGTH (50) - -static IoT_Error_t rc = SUCCESS; - -static jsmn_parser test_parser; -static jsmntok_t t[128]; - -TEST_GROUP_C_SETUP(JsonUtils) { - jsmn_init(&test_parser); -} - -TEST_GROUP_C_TEARDOWN(JsonUtils) { - -} - -TEST_C(JsonUtils, ParseStringBasic) { - int r; - const char *json = "{\"x\":\"test1\"}"; - char parsedString[STRING_BUFFER_LENGTH]; - - IOT_DEBUG("\n-->Running Json Utils Tests - Basic String Parsing \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseStringValue(parsedString, STRING_BUFFER_LENGTH, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING("test1", parsedString); -} - -TEST_C(JsonUtils, ParseStringLongerStringIsValid) { - int r; - const char *json = "{\"x\":\"this is a longer string for test 2\"}"; - char parsedString[STRING_BUFFER_LENGTH]; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse long string \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseStringValue(parsedString, STRING_BUFFER_LENGTH, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING("this is a longer string for test 2", parsedString); -} - -/* Test that parsing a string doesn't overflow the given buffer. */ -TEST_C(JsonUtils, ParseStringWithBufferTooSmall) { - static const char* const pJsonString = "{\"key\":\"This value is longer than JSON_BUFFER_LENGTH, which should be 50.\"}"; - char parsedString[STRING_BUFFER_LENGTH] = {0}; - int jsmnReturn, i; - - IOT_DEBUG("\n-->Running Json Utils Tests - String parsing with buffer too small. \n"); - - jsmnReturn = jsmn_parse(&test_parser, pJsonString, strlen(pJsonString), t, sizeof(t)/sizeof(t[0])); - CHECK_EQUAL_C_INT(3, jsmnReturn); - - rc = parseStringValue(parsedString, STRING_BUFFER_LENGTH, pJsonString, t + 2); - - CHECK_EQUAL_C_INT(SHADOW_JSON_ERROR, rc); - - /* Ensure there was no attempt to write to a buffer that's too small. */ - for(i = 0; i < STRING_BUFFER_LENGTH; i++) - { - CHECK_EQUAL_C_CHAR(0, parsedString[i]); - } -} - -TEST_C(JsonUtils, ParseStringEmptyStringIsValid) { int r; - const char *json = "{\"x\":\"\"}"; - char parsedString[STRING_BUFFER_LENGTH]; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse empty string \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseStringValue(parsedString, STRING_BUFFER_LENGTH, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING("", parsedString); -} - -TEST_C(JsonUtils, ParseStringErrorOnInteger) { - int r; - const char *json = "{\"x\":3}"; - char parsedString[STRING_BUFFER_LENGTH]; - - IOT_DEBUG("\n-->Running Json Utils Tests - parse integer as string returns error \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseStringValue(parsedString, STRING_BUFFER_LENGTH, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseStringErrorOnBoolean) { - int r; - const char *json = "{\"x\":true}"; - char parsedString[STRING_BUFFER_LENGTH]; - - IOT_DEBUG("\n-->Running Json Utils Tests - parse boolean as string returns error \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseStringValue(parsedString, STRING_BUFFER_LENGTH, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseBooleanTrue) { - int r; - const char *json = "{\"x\":true}"; - bool parsedBool; - - IOT_DEBUG("\n-->Running Json Utils Tests - parse boolean with true value \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseBooleanValue(&parsedBool, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(1, (int) parsedBool); -} - -TEST_C(JsonUtils, ParseBooleanFalse) { - int r; - const char *json = "{\"x\":false}"; - bool parsedBool; - - IOT_DEBUG("\n-->Running Json Utils Tests - parse boolean with false value \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseBooleanValue(&parsedBool, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(0, (int) parsedBool); -} - -TEST_C(JsonUtils, ParseBooleanErrorOnString) { - int r; - const char *json = "{\"x\":\"not a bool\"}"; - bool parsedBool; - - IOT_DEBUG("\n-->Running Json Utils Tests - parse string as boolean returns error \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseBooleanValue(&parsedBool, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseBooleanErrorOnInvalidJson) { - int r; - const char *json = "{\"x\":frue}"; // Invalid - bool parsedBool; - - IOT_DEBUG("\n-->Running Json Utils Tests - parse boolean returns error with invalid json \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseBooleanValue(&parsedBool, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseDoubleBasic) { - int r; - const char *json = "{\"x\":20.5}"; - double parsedDouble; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse double test \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseDoubleValue(&parsedDouble, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_REAL(20.5, parsedDouble, 0.0); -} - -TEST_C(JsonUtils, ParseDoubleNumberWithNoDecimal) { - int r; - const char *json = "{\"x\":100}"; - double parsedDouble; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse double number with no decimal \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseDoubleValue(&parsedDouble, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_REAL(100, parsedDouble, 0.0); -} - -TEST_C(JsonUtils, ParseDoubleSmallDouble) { - int r; - const char *json = "{\"x\":0.000004}"; - double parsedDouble; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse small double value \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseDoubleValue(&parsedDouble, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_REAL(0.000004, parsedDouble, 0.0); -} - -TEST_C(JsonUtils, ParseDoubleErrorOnString) { - int r; - const char *json = "{\"x\":\"20.5\"}"; - double parsedDouble; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse string as double returns error \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseDoubleValue(&parsedDouble, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseDoubleErrorOnBoolean) { - int r; - const char *json = "{\"x\":true}"; - double parsedDouble; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse boolean as double returns error \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseDoubleValue(&parsedDouble, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseDoubleErrorOnJsonObject) { - int r; - const char *json = "{\"x\":{}}"; - double parsedDouble; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse json object as double returns error \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseDoubleValue(&parsedDouble, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseDoubleNegativeNumber) { - int r; - const char *json = "{\"x\":-56.78}"; - double parsedDouble; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse negative double value \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseDoubleValue(&parsedDouble, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_REAL(-56.78, parsedDouble, 0.0); -} - -TEST_C(JsonUtils, ParseFloatBasic) { - int r; - const char *json = "{\"x\":20.5}"; - float parsedFloat; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse float test \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseFloatValue(&parsedFloat, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_REAL(20.5, parsedFloat, 0.0); -} - -TEST_C(JsonUtils, ParseFloatNumberWithNoDecimal) { - int r; - const char *json = "{\"x\":100}"; - float parsedFloat; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse float number with no decimal \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseFloatValue(&parsedFloat, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_REAL(100, parsedFloat, 0.0); -} - -TEST_C(JsonUtils, ParseFloatSmallFloat) { - int r; - const char *json = "{\"x\":0.0004}"; - float parsedFloat; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse small float value \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseFloatValue(&parsedFloat, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_C(0.0004f == parsedFloat); -} - -TEST_C(JsonUtils, ParseFloatErrorOnString) { - int r; - const char *json = "{\"x\":\"20.5\"}"; - float parsedFloat; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse string as float returns error \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseFloatValue(&parsedFloat, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseFloatErrorOnBoolean) { - int r; - const char *json = "{\"x\":true}"; - float parsedFloat; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse boolean as float returns error \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseFloatValue(&parsedFloat, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseFloatErrorOnJsonObject) { - int r; - const char *json = "{\"x\":{}}"; - float parsedDouble; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse json object as float returns error \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseFloatValue(&parsedDouble, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseFloatNegativeNumber) { - int r; - const char *json = "{\"x\":-56.78}"; - float parsedFloat; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse negative float value \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseFloatValue(&parsedFloat, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_C(-56.78f == parsedFloat); -} - -TEST_C(JsonUtils, ParseIntegerBasic) { - int r; - const char *json = "{\"x\":1}"; - int32_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse 32 bit integer \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseInteger32Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(1, parsedInteger); -} - -TEST_C(JsonUtils, ParseIntegerLargeInteger) { - int r; - const char *json = "{\"x\":2147483647}"; - int32_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse large 32 bit integer \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseInteger32Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(2147483647, parsedInteger); -} - -TEST_C(JsonUtils, ParseIntegerNegativeInteger) { - int r; - const char *json = "{\"x\":-308}"; - int32_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse negative 32 bit integer \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseInteger32Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(-308, parsedInteger); -} - -TEST_C(JsonUtils, ParseIntegerErrorOnBoolean) { - int r; - const char *json = "{\"x\":true}"; - int32_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse 32 bit integer returns error with boolean \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseInteger32Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseIntegerErrorOnString) { - int r; - const char *json = "{\"x\":\"45\"}"; - int32_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse 32 bit integer returns error on string \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseInteger32Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseInteger16bitBasic) { - int r; - const char *json = "{\"x\":1}"; - int16_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse 16 bit integer \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseInteger16Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(1, parsedInteger); -} - -TEST_C(JsonUtils, ParseInteger16bitLargeInteger) { - int r; - const char *json = "{\"x\":32767}"; - int16_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse large 16 bit integer \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseInteger16Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(32767, parsedInteger); -} - -TEST_C(JsonUtils, ParseInteger16bitNegativeInteger) { - int r; - const char *json = "{\"x\":-308}"; - int16_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse negative 16 bit integer \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseInteger16Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(-308, parsedInteger); -} - -TEST_C(JsonUtils, ParseInteger16bitErrorOnBoolean) { - int r; - const char *json = "{\"x\":true}"; - int16_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse 16 bit integer returns error with boolean \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseInteger16Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseInteger16bitErrorOnString) { - int r; - const char *json = "{\"x\":\"45\"}"; - int16_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse 16 bit integer returns error on string \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseInteger16Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseInteger8bitBasic) { - int r; - const char *json = "{\"x\":1}"; - int8_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse 8 bit integer \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseInteger8Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(1, parsedInteger); -} - -TEST_C(JsonUtils, ParseInteger8bitLargeInteger) { - int r; - const char *json = "{\"x\":127}"; - int8_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse large 8 bit integer \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseInteger8Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(127, parsedInteger); -} - -TEST_C(JsonUtils, ParseInteger8bitNegativeInteger) { - int r; - const char *json = "{\"x\":-30}"; - int8_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse negative 8 bit integer \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseInteger8Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(-30, parsedInteger); -} - -TEST_C(JsonUtils, ParseInteger8bitErrorOnBoolean) { - int r; - const char *json = "{\"x\":true}"; - int8_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse 8 bit integer returns error with boolean \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseInteger8Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseInteger8bitErrorOnString) { - int r; - const char *json = "{\"x\":\"45\"}"; - int8_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse 8 bit integer returns error on string \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseInteger8Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseUnsignedIntegerBasic) { - int r; - const char *json = "{\"x\":1}"; - uint32_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 32 bit integer \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseUnsignedInteger32Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_C(1 == parsedInteger); -} - -TEST_C(JsonUtils, ParseUnsignedIntegerLargeInteger) { - int r; - const char *json = "{\"x\":2147483647}"; - uint32_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse large unsigned 32 bit integer \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseUnsignedInteger32Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_C(2147483647 == parsedInteger); -} - -TEST_C(JsonUtils, ParseUnsignedIntegerErrorOnNegativeInteger) { - int r; - const char *json = "{\"x\":-308}"; - uint32_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 32 bit integer returns error with negative value \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseUnsignedInteger32Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseUnsignedIntegerErrorOnBoolean) { - int r; - const char *json = "{\"x\":true}"; - uint32_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 32 bit integer returns error with boolean \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseUnsignedInteger32Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseUnsignedIntegerErrorOnString) { - int r; - const char *json = "{\"x\":\"45\"}"; - uint32_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 32 bit integer returns error on string \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseUnsignedInteger32Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseUnsignedInteger16bitBasic) { - int r; - const char *json = "{\"x\":1}"; - uint16_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 16 bit integer \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseUnsignedInteger16Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(1, parsedInteger); -} - -TEST_C(JsonUtils, ParseUnsignedInteger16bitLargeInteger) { - int r; - const char *json = "{\"x\":65535}"; - uint16_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse large unsigned 16 bit integer \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseUnsignedInteger16Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(65535, parsedInteger); -} - -TEST_C(JsonUtils, ParseUnsignedInteger16bitErrorOnNegativeInteger) { - int r; - const char *json = "{\"x\":-308}"; - uint16_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 16 bit integer returns error on negative value \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseUnsignedInteger16Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseUnsignedInteger16bitErrorOnBoolean) { - int r; - const char *json = "{\"x\":true}"; - uint16_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 16 bit integer returns error with boolean \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseUnsignedInteger16Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseUnsignedInteger16bitErrorOnString) { - int r; - const char *json = "{\"x\":\"45\"}"; - uint16_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 16 bit integer returns error on string \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseUnsignedInteger16Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseUnsignedInteger8bitBasic) { - int r; - const char *json = "{\"x\":1}"; - uint8_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 8 bit integer \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseUnsignedInteger8Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(1, parsedInteger); -} - -TEST_C(JsonUtils, ParseUnsignedInteger8bitLargeInteger) { - int r; - const char *json = "{\"x\":255}"; - uint8_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse large unsigned 8 bit integer \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseUnsignedInteger8Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(255, parsedInteger); -} - -TEST_C(JsonUtils, ParseUnsignedInteger8bitErrorOnNegativeInteger) { - int r; - const char *json = "{\"x\":-30}"; - uint8_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 8 bit integer returns error on negative value \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseUnsignedInteger8Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseUnsignedInteger8bitErrorOnBoolean) { - int r; - const char *json = "{\"x\":true}"; - uint8_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 8 bit integer returns error with boolean \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseUnsignedInteger8Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} - -TEST_C(JsonUtils, ParseUnsignedInteger8bitErrorOnString) { - int r; - const char *json = "{\"x\":\"45\"}"; - uint8_t parsedInteger; - - IOT_DEBUG("\n-->Running Json Utils Tests - Parse unsigned 8 bit integer returns error on string \n"); - - r = jsmn_parse(&test_parser, json, strlen(json), t, sizeof(t) / sizeof(t[0])); - rc = parseUnsignedInteger8Value(&parsedInteger, json, t + 2); - - CHECK_EQUAL_C_INT(3, r); - CHECK_EQUAL_C_INT(JSON_PARSE_ERROR, rc); -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_publish.cpp b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_publish.cpp deleted file mode 100644 index da188e0fe..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_publish.cpp +++ /dev/null @@ -1,48 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_publish.cpp - * @brief IoT Client Unit Testing - Publish API Tests - */ - -#include -#include - -TEST_GROUP_C(PublishTests) { - TEST_GROUP_C_SETUP_WRAPPER(PublishTests) - TEST_GROUP_C_TEARDOWN_WRAPPER(PublishTests) -}; - -/* E:1 - Publish with Null/empty client instance */ -TEST_GROUP_C_WRAPPER(PublishTests, PublishNullClient) -/* E:2 - Publish with Null/empty Topic Name */ -TEST_GROUP_C_WRAPPER(PublishTests, PublishNullTopic) -/* E:3 - Publish with Null/empty payload */ -TEST_GROUP_C_WRAPPER(PublishTests, PublishNullParams) -/* E:4 - Publish with network disconnected */ -TEST_GROUP_C_WRAPPER(PublishTests, PublishNetworkDisconnected) -/* E:5 - Publish with QoS2 */ -/* Not required here, enum value doesn't exist for QoS2 */ -/* E:6 - Publish with QoS1 send success, Puback not received */ -TEST_GROUP_C_WRAPPER(PublishTests, publishQoS1FailureToReceivePuback) -/* E:7 - Publish with QoS1 send success, Delayed Puback received after command timeout */ -TEST_GROUP_C_WRAPPER(PublishTests, publishQoS1FailureDelayedPuback) -/* E:8 - Publish with send success, Delayed Puback received before command timeout */ -TEST_GROUP_C_WRAPPER(PublishTests, publishQoS1Success10msDelayedPuback) -/* E:9 - Publish QoS0 success */ -TEST_GROUP_C_WRAPPER(PublishTests, publishQoS0NoPubackSuccess) -/* E:10 - Publish with QoS1 send success, Puback received */ -TEST_GROUP_C_WRAPPER(PublishTests, publishQoS1Success) diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_publish_helper.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_publish_helper.c deleted file mode 100644 index 2f2c6406c..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_publish_helper.c +++ /dev/null @@ -1,205 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_publish_helper.c - * @brief IoT Client Unit Testing - Publish API Tests Helper - */ - -#include -#include -#include - -#include "aws_iot_mqtt_client_interface.h" -#include "aws_iot_tests_unit_helper_functions.h" -#include "aws_iot_log.h" - -static IoT_Client_Init_Params initParams; -static IoT_Client_Connect_Params connectParams; -static IoT_Publish_Message_Params testPubMsgParams; -static char subTopic[10] = "sdk/Test"; -static uint16_t subTopicLen = 8; - -static AWS_IoT_Client iotClient; -char cPayload[100]; - -TEST_GROUP_C_SETUP(PublishTests) { - IoT_Error_t rc = SUCCESS; - ResetTLSBuffer(); - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - initParams.mqttCommandTimeout_ms = 2000; - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - IOT_DEBUG("MQTT Status State : %d, RC : %d\n\n", aws_iot_mqtt_get_client_state(&iotClient), rc); - - testPubMsgParams.qos = QOS1; - testPubMsgParams.isRetained = 0; - sprintf(cPayload, "%s : %d ", "hello from SDK", 0); - testPubMsgParams.payload = (void *) cPayload; - testPubMsgParams.payloadLen = strlen(cPayload); - - ResetTLSBuffer(); -} - -TEST_GROUP_C_TEARDOWN(PublishTests) { } - -/* E:1 - Publish with Null/empty client instance */ -TEST_C(PublishTests, PublishNullClient) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Publish Tests - E:1 - Publish with Null/empty client instance \n"); - - testPubMsgParams.qos = QOS1; - testPubMsgParams.isRetained = 0; - testPubMsgParams.payload = "Message"; - testPubMsgParams.payloadLen = 7; - - rc = aws_iot_mqtt_publish(NULL, "sdkTest/Sub", 11, &testPubMsgParams); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); - - IOT_DEBUG("-->Success - E:1 - Publish with Null/empty client instance \n"); -} - -/* E:2 - Publish with Null/empty Topic Name */ -TEST_C(PublishTests, PublishNullTopic) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Publish Tests - E:2 - Publish with Null/empty Topic Name \n"); - - testPubMsgParams.qos = QOS1; - testPubMsgParams.isRetained = 0; - testPubMsgParams.payload = "Message"; - testPubMsgParams.payloadLen = 7; - - rc = aws_iot_mqtt_publish(&iotClient, NULL, 11, &testPubMsgParams); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); - - rc = aws_iot_mqtt_publish(&iotClient, "sdkTest/Sub", 0, &testPubMsgParams); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); - - IOT_DEBUG("-->Success - E:2 - Publish with Null/empty Topic Name \n"); -} - -/* E:3 - Publish with Null/empty payload */ -TEST_C(PublishTests, PublishNullParams) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Publish Tests - E:3 - Publish with Null/empty payload \n"); - - rc = aws_iot_mqtt_publish(&iotClient, "sdkTest/Sub", 11, NULL); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); - - testPubMsgParams.qos = QOS1; - testPubMsgParams.isRetained = 0; - testPubMsgParams.payload = NULL; - testPubMsgParams.payloadLen = 0; - - rc = aws_iot_mqtt_publish(&iotClient, "sdkTest/Sub", 11, &testPubMsgParams); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); - - IOT_DEBUG("-->Success - E:3 - Publish with Null/empty payload \n"); -} - -/* E:4 - Publish with network disconnected */ -TEST_C(PublishTests, PublishNetworkDisconnected) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Publish Tests - E:4 - Publish with network disconnected \n"); - - /* Ensure network is disconnected */ - rc = aws_iot_mqtt_disconnect(&iotClient); - - testPubMsgParams.qos = QOS1; - testPubMsgParams.isRetained = 0; - testPubMsgParams.payload = NULL; - testPubMsgParams.payloadLen = 0; - - rc = aws_iot_mqtt_publish(&iotClient, "sdkTest/Sub", 11, &testPubMsgParams); - CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc); - - IOT_DEBUG("-->Success - E:4 - Publish with network disconnected \n"); -} - -/* E:6 - Publish with QoS1 send success, Puback not received */ -TEST_C(PublishTests, publishQoS1FailureToReceivePuback) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Publish Tests - E:6 - Publish with QoS1 send success, Puback not received \n"); - - rc = aws_iot_mqtt_publish(&iotClient, subTopic, subTopicLen, &testPubMsgParams); - CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, rc); - - IOT_DEBUG("-->Success - E:6 - Publish with QoS1 send success, Puback not received \n"); -} - -/* E:7 - Publish with QoS1 send success, Delayed Puback received after command timeout */ -TEST_C(PublishTests, publishQoS1FailureDelayedPuback) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Publish Tests - E:7 - Publish with QoS1 send success, Delayed Puback received after command timeout \n"); - - setTLSRxBufferDelay(10, 0); - setTLSRxBufferForPuback(); - rc = aws_iot_mqtt_publish(&iotClient, subTopic, subTopicLen, &testPubMsgParams); - CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, rc); - - IOT_DEBUG("-->Success - E:7 - Publish with QoS1 send success, Delayed Puback received after command timeout \n"); -} - -/* E:8 - Publish with send success, Delayed Puback received before command timeout */ -TEST_C(PublishTests, publishQoS1Success10msDelayedPuback) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Publish Tests - E:8 - Publish with send success, Delayed Puback received before command timeout \n"); - - ResetTLSBuffer(); - setTLSRxBufferDelay(0, (int) iotClient.clientData.commandTimeoutMs/2); - setTLSRxBufferForPuback(); - rc = aws_iot_mqtt_publish(&iotClient, subTopic, subTopicLen, &testPubMsgParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - IOT_DEBUG("-->Success - E:8 - Publish with send success, Delayed Puback received before command timeout \n"); -} - -/* E:9 - Publish QoS0 success */ -TEST_C(PublishTests, publishQoS0NoPubackSuccess) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Publish Tests - E:9 - Publish QoS0 success \n"); - - testPubMsgParams.qos = QOS0; // switch to a Qos0 PUB - rc = aws_iot_mqtt_publish(&iotClient, subTopic, subTopicLen, &testPubMsgParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - IOT_DEBUG("-->Success - E:9 - Publish QoS0 success \n"); -} - -/* E:10 - Publish with QoS1 send success, Puback received */ -TEST_C(PublishTests, publishQoS1Success) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Publish Tests - E:10 - Publish with QoS1 send success, Puback received \n"); - - setTLSRxBufferForPuback(); - rc = aws_iot_mqtt_publish(&iotClient, subTopic, subTopicLen, &testPubMsgParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - IOT_DEBUG("-->Success - E:10 - Publish with QoS1 send success, Puback received \n"); -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_runner.cpp b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_runner.cpp deleted file mode 100644 index ba1f5cb48..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_runner.cpp +++ /dev/null @@ -1,25 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_runner.cpp - * @brief IoT Client Unit Testing - Runner - */ - -#include - -int main(int ac, char **argv) { - return CommandLineTestRunner::RunAllTests(ac, argv); -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_action.cpp b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_action.cpp deleted file mode 100644 index 32f1be2e1..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_action.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_shadow_action.cpp - * @brief IoT Client Unit Testing - Shadow Action Tests - */ - -#include -#include - -TEST_GROUP_C(ShadowActionTests) { - TEST_GROUP_C_SETUP_WRAPPER(ShadowActionTests) - TEST_GROUP_C_TEARDOWN_WRAPPER(ShadowActionTests) -}; - -TEST_GROUP_C_WRAPPER(ShadowActionTests, GetTheFullJSONDocument) -TEST_GROUP_C_WRAPPER(ShadowActionTests, DeleteTheJSONDocument) -TEST_GROUP_C_WRAPPER(ShadowActionTests, UpdateTheJSONDocument) -TEST_GROUP_C_WRAPPER(ShadowActionTests, GetTheFullJSONDocumentTimeout) -TEST_GROUP_C_WRAPPER(ShadowActionTests, SubscribeToAcceptedRejectedOnGet) -TEST_GROUP_C_WRAPPER(ShadowActionTests, UnSubscribeToAcceptedRejectedOnGetResponse) -TEST_GROUP_C_WRAPPER(ShadowActionTests, UnSubscribeToAcceptedRejectedOnGetTimeout) -TEST_GROUP_C_WRAPPER(ShadowActionTests, UnSubscribeToAcceptedRejectedOnGetTimeoutWithSticky) -TEST_GROUP_C_WRAPPER(ShadowActionTests, WrongTokenInGetResponse) -TEST_GROUP_C_WRAPPER(ShadowActionTests, NoTokenInGetResponse) -TEST_GROUP_C_WRAPPER(ShadowActionTests, InvalidInboundJSONInGetResponse) -TEST_GROUP_C_WRAPPER(ShadowActionTests, AcceptedSubFailsGetRequest) -TEST_GROUP_C_WRAPPER(ShadowActionTests, RejectedSubFailsGetRequest) -TEST_GROUP_C_WRAPPER(ShadowActionTests, PublishFailsGetRequest) -TEST_GROUP_C_WRAPPER(ShadowActionTests, GetVersionFromAckStatus) -TEST_GROUP_C_WRAPPER(ShadowActionTests, StickyNonStickyNeverConflict) -TEST_GROUP_C_WRAPPER(ShadowActionTests, ACKWaitingMoreThanAllowed) -TEST_GROUP_C_WRAPPER(ShadowActionTests, InboundDataTooBigForBuffer) -TEST_GROUP_C_WRAPPER(ShadowActionTests, NoClientTokenForShadowAction) -TEST_GROUP_C_WRAPPER(ShadowActionTests, NoCallbackForShadowAction) -TEST_GROUP_C_WRAPPER(ShadowActionTests, GetAndDeleteRequest) -TEST_GROUP_C_WRAPPER(ShadowActionTests, ExtractClientToken) -TEST_GROUP_C_WRAPPER(ShadowActionTests, IsReceivedJsonValid) diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_action_helper.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_action_helper.c deleted file mode 100644 index 86e603197..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_action_helper.c +++ /dev/null @@ -1,944 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_shadow_action_helper.c - * @brief IoT Client Unit Testing - Shadow Action API Tests Helper - */ - -#include -#include -#include -#include -#include - -#include "aws_iot_tests_unit_mock_tls_params.h" -#include "aws_iot_tests_unit_helper_functions.h" -#include "aws_iot_tests_unit_shadow_helper.h" - -#include "aws_iot_shadow_interface.h" -#include "aws_iot_shadow_actions.h" -#include "aws_iot_shadow_json.h" -#include "aws_iot_log.h" - -#define SIZE_OF_UPDATE_DOCUMENT 200 -#define TEST_JSON_RESPONSE_FULL_DOCUMENT "{\"state\":{\"reported\":{\"sensor1\":98}}, \"clientToken\":\"" AWS_IOT_MQTT_CLIENT_ID "-0\"}" -#define TEST_JSON_RESPONSE_DELETE_DOCUMENT "{\"version\":2,\"timestamp\":1443473857,\"clientToken\":\"" AWS_IOT_MQTT_CLIENT_ID "-0\"}" -#define TEST_JSON_RESPONSE_UPDATE_DOCUMENT "{\"state\":{\"reported\":{\"doubleData\":4.090800,\"floatData\":3.445000}}, \"clientToken\":\"" AWS_IOT_MQTT_CLIENT_ID "-0\"}" -#define TEST_JSON_SIZE 120 -static AWS_IoT_Client client; -static IoT_Client_Connect_Params connectParams; -static IoT_Publish_Message_Params testPubMsgParams; -static ShadowInitParameters_t shadowInitParams; -static ShadowConnectParameters_t shadowConnectParams; - -static Shadow_Ack_Status_t ackStatusRx; -static char jsonFullDocument[200]; -static ShadowActions_t actionRx; - -static void topicNameFromThingAndAction(char *pTopic, const char *pThingName, ShadowActions_t action) { - char actionBuf[10]; - - if(SHADOW_GET == action) { - strcpy(actionBuf, "get"); - } else if(SHADOW_UPDATE == action) { - strcpy(actionBuf, "update"); - } else if(SHADOW_DELETE == action) { - strcpy(actionBuf, "delete"); - } - - snprintf(pTopic, 100, "$aws/things/%s/shadow/%s", pThingName, actionBuf); -} - -TEST_GROUP_C_SETUP(ShadowActionTests) { - IoT_Error_t ret_val = SUCCESS; - char cPayload[100]; - char topic[120]; - - shadowInitParams.pHost = AWS_IOT_MQTT_HOST; - shadowInitParams.port = AWS_IOT_MQTT_PORT; - shadowInitParams.pClientCRT = AWS_IOT_CERTIFICATE_FILENAME; - shadowInitParams.pRootCA = AWS_IOT_ROOT_CA_FILENAME; - shadowInitParams.pClientKey = AWS_IOT_PRIVATE_KEY_FILENAME; - shadowInitParams.disconnectHandler = NULL; - shadowInitParams.enableAutoReconnect = false; - ret_val = aws_iot_shadow_init(&client, &shadowInitParams); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - shadowConnectParams.pMyThingName = AWS_IOT_MY_THING_NAME; - shadowConnectParams.pMqttClientId = AWS_IOT_MQTT_CLIENT_ID; - shadowConnectParams.mqttClientIdLen = (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID); - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - ret_val = aws_iot_shadow_connect(&client, &shadowConnectParams); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - setTLSRxBufferForPuback(); - testPubMsgParams.qos = QOS1; - testPubMsgParams.isRetained = 0; - snprintf(cPayload, 100, "%s : %d ", "hello from SDK", 0); - testPubMsgParams.payload = (void *) cPayload; - testPubMsgParams.payloadLen = strlen(cPayload) + 1; - topicNameFromThingAndAction(topic, AWS_IOT_MY_THING_NAME, SHADOW_GET); - setTLSRxBufferForDoubleSuback(topic, strlen(topic), QOS1, testPubMsgParams); -} - -TEST_GROUP_C_TEARDOWN(ShadowActionTests) { - /* Clean up. Not checking return code here because this is common to all tests. - * A test might have already caused a disconnect by this point. - */ - IoT_Error_t rc = aws_iot_shadow_disconnect(&client); - IOT_UNUSED(rc); -} - -static void actionCallback(const char *pThingName, ShadowActions_t action, Shadow_Ack_Status_t status, - const char *pReceivedJsonDocument, void *pContextData) { - IOT_UNUSED(pThingName); - IOT_UNUSED(pContextData); - IOT_DEBUG("%s", pReceivedJsonDocument); - actionRx = action; - ackStatusRx = status; - if(SHADOW_ACK_TIMEOUT != status) { - strcpy(jsonFullDocument, pReceivedJsonDocument); - } -} - -// Happy path for Get, Update, Delete -TEST_C(ShadowActionTests, GetTheFullJSONDocument) { - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - IoT_Publish_Message_Params params; - - IOT_DEBUG("-->Running Shadow Action Tests - Get full json document \n"); - - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, 4, - false); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - ResetTLSBuffer(); - params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); - params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; - params.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - CHECK_EQUAL_C_STRING(TEST_JSON_RESPONSE_FULL_DOCUMENT, jsonFullDocument); - CHECK_EQUAL_C_INT(SHADOW_GET, actionRx); - CHECK_EQUAL_C_INT(SHADOW_ACK_ACCEPTED, ackStatusRx); - - IOT_DEBUG("-->Success - Get full json document \n"); -} - -TEST_C(ShadowActionTests, DeleteTheJSONDocument) { - IoT_Error_t ret_val = SUCCESS; - IoT_Publish_Message_Params params; - char deleteRequestJson[TEST_JSON_SIZE]; - - IOT_DEBUG("-->Running Shadow Action Tests - Delete json document \n"); - - aws_iot_shadow_internal_delete_request_json(deleteRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_DELETE, deleteRequestJson, TEST_JSON_SIZE, actionCallback, - NULL, 4, false); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - params.payloadLen = strlen(TEST_JSON_RESPONSE_DELETE_DOCUMENT); - params.payload = TEST_JSON_RESPONSE_DELETE_DOCUMENT; - params.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(DELETE_ACCEPTED_TOPIC, strlen(DELETE_ACCEPTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - CHECK_EQUAL_C_STRING(TEST_JSON_RESPONSE_DELETE_DOCUMENT, jsonFullDocument); - CHECK_EQUAL_C_INT(SHADOW_DELETE, actionRx); - CHECK_EQUAL_C_INT(SHADOW_ACK_ACCEPTED, ackStatusRx); - - IOT_DEBUG("-->Success - Delete json document \n"); -} - -TEST_C(ShadowActionTests, UpdateTheJSONDocument) { - IoT_Error_t ret_val = SUCCESS; - char updateRequestJson[SIZE_OF_UPDATE_DOCUMENT]; - char expectedUpdateRequestJson[SIZE_OF_UPDATE_DOCUMENT]; - double doubleData = 4.0908f; - float floatData = 3.445f; - bool boolData = true; - jsonStruct_t dataFloatHandler; - jsonStruct_t dataDoubleHandler; - jsonStruct_t dataBoolHandler; - IoT_Publish_Message_Params params; - - IOT_DEBUG("-->Running Shadow Action Tests - Update json document \n"); - - dataFloatHandler.cb = NULL; - dataFloatHandler.pData = &floatData; - dataFloatHandler.dataLength = sizeof(float); - dataFloatHandler.pKey = "floatData"; - dataFloatHandler.type = SHADOW_JSON_FLOAT; - - dataDoubleHandler.cb = NULL; - dataDoubleHandler.pData = &doubleData; - dataDoubleHandler.dataLength = sizeof(double); - dataDoubleHandler.pKey = "doubleData"; - dataDoubleHandler.type = SHADOW_JSON_DOUBLE; - - dataBoolHandler.cb = NULL; - dataBoolHandler.pData = &boolData; - dataBoolHandler.dataLength = sizeof(bool); - dataBoolHandler.pKey = "boolData"; - dataBoolHandler.type = SHADOW_JSON_BOOL; - - ret_val = aws_iot_shadow_init_json_document(updateRequestJson, SIZE_OF_UPDATE_DOCUMENT); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - ret_val = aws_iot_shadow_add_reported(updateRequestJson, SIZE_OF_UPDATE_DOCUMENT, 2, &dataDoubleHandler, - &dataFloatHandler); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - ret_val = aws_iot_shadow_add_desired(updateRequestJson, SIZE_OF_UPDATE_DOCUMENT, 1, &dataBoolHandler); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - ret_val = aws_iot_finalize_json_document(updateRequestJson, SIZE_OF_UPDATE_DOCUMENT); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - snprintf(expectedUpdateRequestJson, SIZE_OF_UPDATE_DOCUMENT, - "{\"state\":{\"reported\":{\"doubleData\":4.090800,\"floatData\":3.445000},\"desired\":{\"boolData\":true}}, \"clientToken\":\"%s-0\"}", - AWS_IOT_MQTT_CLIENT_ID); - CHECK_EQUAL_C_STRING(expectedUpdateRequestJson, updateRequestJson); - - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_UPDATE, updateRequestJson, SIZE_OF_UPDATE_DOCUMENT, actionCallback, - NULL, 4, false); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - ResetTLSBuffer(); - snprintf(jsonFullDocument, 200, "%s", ""); - params.payloadLen = strlen(TEST_JSON_RESPONSE_UPDATE_DOCUMENT); - params.payload = TEST_JSON_RESPONSE_UPDATE_DOCUMENT; - params.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(UPDATE_ACCEPTED_TOPIC, strlen(UPDATE_ACCEPTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - CHECK_EQUAL_C_STRING(TEST_JSON_RESPONSE_UPDATE_DOCUMENT, jsonFullDocument); - CHECK_EQUAL_C_INT(SHADOW_UPDATE, actionRx); - CHECK_EQUAL_C_INT(SHADOW_ACK_ACCEPTED, ackStatusRx); - - IOT_DEBUG("-->Success - Update json document \n"); -} - -TEST_C(ShadowActionTests, GetTheFullJSONDocumentTimeout) { - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - IoT_Publish_Message_Params params; - - IOT_DEBUG("-->Running Shadow Action Tests - Get full json document timeout \n"); - - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, 4, - false); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - sleep(4 + 1); - - params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); - params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; - params.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - CHECK_EQUAL_C_STRING(TEST_JSON_RESPONSE_FULL_DOCUMENT, jsonFullDocument); - CHECK_EQUAL_C_INT(SHADOW_GET, actionRx); - CHECK_EQUAL_C_INT(SHADOW_ACK_TIMEOUT, ackStatusRx); - - IOT_DEBUG("-->Success - Get full json document timeout \n"); -} - -// Subscribe and UnSubscribe on reception of thing names. Will perform the test with Get operation -TEST_C(ShadowActionTests, SubscribeToAcceptedRejectedOnGet) { - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - - uint8_t firstByte, secondByte; - uint16_t topicNameLen; - char topicName[128] = "test"; - - IOT_DEBUG("-->Running Shadow Action Tests - Subscribe to get/accepted and get/rejected \n"); - - lastSubscribeMsgLen = 11; - snprintf(LastSubscribeMessage, lastSubscribeMsgLen, "No Message"); - secondLastSubscribeMsgLen = 11; - snprintf(SecondLastSubscribeMessage, secondLastSubscribeMsgLen, "No Message"); - - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, 4, - false); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - CHECK_EQUAL_C_STRING(GET_REJECTED_TOPIC, LastSubscribeMessage); - CHECK_EQUAL_C_STRING(GET_ACCEPTED_TOPIC, SecondLastSubscribeMessage); - - firstByte = (uint8_t)(TxBuffer.pBuffer[2]); - secondByte = (uint8_t)(TxBuffer.pBuffer[3]); - topicNameLen = (uint16_t) (secondByte + (256 * firstByte)); - - snprintf(topicName, topicNameLen + 1u, "%s", &(TxBuffer.pBuffer[4])); // Added one for null character - - // Verify publish happens - CHECK_EQUAL_C_STRING(GET_PUB_TOPIC, topicName); - - IOT_DEBUG("-->Success - Subscribe to get/accepted and get/rejected \n"); -} - -TEST_C(ShadowActionTests, UnSubscribeToAcceptedRejectedOnGetResponse) { - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - IoT_Publish_Message_Params params; - - IOT_DEBUG("-->Running Shadow Action Tests - unsubscribe to get/accepted and get/rejected on response \n"); - - lastSubscribeMsgLen = 11; - snprintf(LastSubscribeMessage, lastSubscribeMsgLen, "No Message"); - secondLastSubscribeMsgLen = 11; - snprintf(SecondLastSubscribeMessage, secondLastSubscribeMsgLen, "No Message"); - - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, 4, - false); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); - params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; - params.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - CHECK_EQUAL_C_STRING(GET_REJECTED_TOPIC, LastSubscribeMessage); - CHECK_EQUAL_C_STRING(GET_ACCEPTED_TOPIC, SecondLastSubscribeMessage); - - IOT_DEBUG("-->Success - unsubscribe to get/accepted and get/rejected on response \n"); -} - -TEST_C(ShadowActionTests, UnSubscribeToAcceptedRejectedOnGetTimeout) { - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - IoT_Publish_Message_Params params; - - IOT_DEBUG("-->Running Shadow Action Tests - Unsubscribe to get/accepted and get/rejected on get timeout \n"); - - snprintf(jsonFullDocument, 200, "aa"); - lastSubscribeMsgLen = 11; - snprintf(LastSubscribeMessage, lastSubscribeMsgLen, "No Message"); - secondLastSubscribeMsgLen = 11; - snprintf(SecondLastSubscribeMessage, secondLastSubscribeMsgLen, "No Message"); - - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, 4, - false); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - sleep(4 + 1); - - params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); - params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; - params.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - CHECK_EQUAL_C_STRING("aa", jsonFullDocument); - - CHECK_EQUAL_C_STRING(GET_REJECTED_TOPIC, LastSubscribeMessage); - CHECK_EQUAL_C_STRING(GET_ACCEPTED_TOPIC, SecondLastSubscribeMessage); - - IOT_DEBUG("-->Success - Unsubscribe to get/accepted and get/rejected on get timeout \n"); -} - - -TEST_C(ShadowActionTests, UnSubscribeToAcceptedRejectedOnGetTimeoutWithSticky) { - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - IoT_Publish_Message_Params params; - - IOT_DEBUG("-->Running Shadow Action Tests - No unsubscribe to get/accepted and get/rejected on get timeout with a sticky subscription \n"); - - snprintf(jsonFullDocument, 200, "timeout"); - lastSubscribeMsgLen = 11; - snprintf(LastSubscribeMessage, lastSubscribeMsgLen, "No Message"); - secondLastSubscribeMsgLen = 11; - snprintf(SecondLastSubscribeMessage, secondLastSubscribeMsgLen, "No Message"); - - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, 4, - true); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - sleep(4 + 1); - - ResetTLSBuffer(); - params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); - params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; - params.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - CHECK_EQUAL_C_STRING("timeout", jsonFullDocument); - - CHECK_EQUAL_C_STRING(GET_REJECTED_TOPIC, LastSubscribeMessage); - CHECK_EQUAL_C_STRING(GET_ACCEPTED_TOPIC, SecondLastSubscribeMessage); - - IOT_DEBUG("-->Success - No unsubscribe to get/accepted and get/rejected on get timeout with a sticky subscription \n"); -} - -#define TEST_JSON_RESPONSE_FULL_DOCUMENT_WITH_VERSION(num) "{\"state\":{\"reported\":{\"sensor1\":98}}, \"clientToken\":\"" AWS_IOT_MQTT_CLIENT_ID "-0\",\"version\":" #num "}" - -TEST_C(ShadowActionTests, GetVersionFromAckStatus) { - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - IoT_Publish_Message_Params params; - IoT_Publish_Message_Params params2; - - IOT_DEBUG("-->Running Shadow Action Tests - Get version from Ack status \n"); - - snprintf(jsonFullDocument, 200, "timeout"); - - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, 4, - true); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - ResetTLSBuffer(); - params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT_WITH_VERSION(1); - params.payloadLen = strlen(params.payload); - params.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - CHECK_C(1u == aws_iot_shadow_get_last_received_version()); - - ResetTLSBuffer(); - params2.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT_WITH_VERSION(132387); - params2.payloadLen = strlen(params2.payload); - params2.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params2, - params2.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - CHECK_C(132387u == aws_iot_shadow_get_last_received_version()); - - IOT_DEBUG("-->Success - Get version from Ack status \n"); -} - -#define TEST_JSON_RESPONSE_FULL_DOCUMENT_ALWAYS_WRONG_TOKEN "{\"state\":{\"reported\":{\"sensor1\":98}}, \"clientToken\":\"TroubleToken1234\"}" - -TEST_C(ShadowActionTests, WrongTokenInGetResponse) { - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - IoT_Publish_Message_Params params; - - IOT_DEBUG("-->Running Shadow Action Tests - Wrong token in get response \n"); - - snprintf(jsonFullDocument, 200, "timeout"); - - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, 4, - false); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - sleep(4 + 1); - - params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT_ALWAYS_WRONG_TOKEN); - params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT_ALWAYS_WRONG_TOKEN; - params.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - CHECK_EQUAL_C_STRING("timeout", jsonFullDocument); - CHECK_EQUAL_C_INT(SHADOW_GET, actionRx); - CHECK_EQUAL_C_INT(SHADOW_ACK_TIMEOUT, ackStatusRx); - - IOT_DEBUG("-->Success - Wrong token in get response \n"); -} - -#define TEST_JSON_RESPONSE_FULL_DOCUMENT_NO_TOKEN "{\"state\":{\"reported\":{\"sensor1\":98}}}" - -TEST_C(ShadowActionTests, NoTokenInGetResponse) { - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - IoT_Publish_Message_Params params; - - IOT_DEBUG("-->Running Shadow Action Tests - No token in get response \n"); - - snprintf(jsonFullDocument, 200, "timeout"); - - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, 4, - false); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - sleep(4 + 1); - - params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT_NO_TOKEN); - params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT_NO_TOKEN; - params.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - CHECK_EQUAL_C_STRING("timeout", jsonFullDocument); - CHECK_EQUAL_C_INT(SHADOW_GET, actionRx); - CHECK_EQUAL_C_INT(SHADOW_ACK_TIMEOUT, ackStatusRx); - - IOT_DEBUG("-->Success - No token in get response \n"); -} - -TEST_C(ShadowActionTests, InvalidInboundJSONInGetResponse) { - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - IoT_Publish_Message_Params params; - - IOT_DEBUG("-->Running Shadow Action Tests - Invalid inbound json in get response \n"); - - snprintf(jsonFullDocument, 200, "NOT_VISITED"); - - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, 4, - false); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - params.payloadLen = strlen("{\"state\":{{"); - params.payload = "{\"state\":{{"; - params.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - CHECK_EQUAL_C_STRING("NOT_VISITED", jsonFullDocument); - - IOT_DEBUG("-->Success - Invalid inbound json in get response \n"); -} - -TEST_C(ShadowActionTests, AcceptedSubFailsGetRequest) { - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - IoT_Publish_Message_Params params; - - IOT_DEBUG("-->Running Shadow Action Tests - Accepted sub fails get request \n"); - - snprintf(jsonFullDocument, 200, "NOT_SENT"); - - ResetTLSBuffer(); - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, 4, - false); - CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, ret_val); // Should never subscribe and publish - - ResetTLSBuffer(); - params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); - params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; - params.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - CHECK_EQUAL_C_STRING("NOT_SENT", jsonFullDocument); // Never called callback - - IOT_DEBUG("-->Success - Accepted sub fails get request \n"); -} - -TEST_C(ShadowActionTests, RejectedSubFailsGetRequest) { - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - IoT_Publish_Message_Params params; - - IOT_DEBUG("-->Running Shadow Action Tests - Rejected sub fails get request \n"); - - snprintf(jsonFullDocument, 200, "NOT_SENT"); - - params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); - params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; - params.qos = QOS0; - - ResetTLSBuffer(); - setTLSRxBufferForSuback(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params); - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, 4, - false); - CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, ret_val); // Should never subscribe and publish - - ResetTLSBuffer(); - setTLSRxBufferWithMsgOnSubscribedTopic(GET_REJECTED_TOPIC, strlen(GET_REJECTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - CHECK_EQUAL_C_STRING("NOT_SENT", jsonFullDocument); // Never called callback - - IOT_DEBUG("-->Success - Rejected sub fails get request \n"); -} - -TEST_C(ShadowActionTests, PublishFailsGetRequest) { - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - IoT_Publish_Message_Params params; - - IOT_DEBUG("-->Running Shadow Action Tests - publish fails on get request \n"); - - snprintf(jsonFullDocument, 200, "NOT_SENT"); - - ResetTLSBuffer(); - - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, 4, - false); - CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, ret_val); // Should never subscribe and publish - - ResetTLSBuffer(); - params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); - params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; - params.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - CHECK_EQUAL_C_STRING("NOT_SENT", jsonFullDocument); // Never called callback - - IOT_DEBUG("-->Success - publish fails on get request \n"); -} - -TEST_C(ShadowActionTests, StickyNonStickyNeverConflict) { - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - IoT_Publish_Message_Params params; - - IOT_DEBUG("-->Running Shadow Action Tests - Sticky and non-sticky subscriptions do not conflict \n"); - - lastSubscribeMsgLen = 11; - snprintf(LastSubscribeMessage, lastSubscribeMsgLen, "No Message"); - secondLastSubscribeMsgLen = 11; - snprintf(SecondLastSubscribeMessage, secondLastSubscribeMsgLen, "No Message"); - - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, 4, - true); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); - params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; - params.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - CHECK_EQUAL_C_STRING(TEST_JSON_RESPONSE_FULL_DOCUMENT, jsonFullDocument); - CHECK_EQUAL_C_INT(SHADOW_GET, actionRx); - CHECK_EQUAL_C_INT(SHADOW_ACK_ACCEPTED, ackStatusRx); - - lastSubscribeMsgLen = 11; - snprintf(LastSubscribeMessage, lastSubscribeMsgLen, "No Message"); - secondLastSubscribeMsgLen = 11; - snprintf(SecondLastSubscribeMessage, secondLastSubscribeMsgLen, "No Message"); - - // Non-sticky shadow get, same thing name. Should never unsub since they are sticky - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, 4, - false); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - ResetTLSBuffer(); - - params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); - params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; - params.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - CHECK_EQUAL_C_STRING(TEST_JSON_RESPONSE_FULL_DOCUMENT, jsonFullDocument); - CHECK_EQUAL_C_INT(SHADOW_GET, actionRx); - CHECK_EQUAL_C_INT(SHADOW_ACK_ACCEPTED, ackStatusRx); - - CHECK_EQUAL_C_STRING("No Message", LastSubscribeMessage); - CHECK_EQUAL_C_STRING("No Message", SecondLastSubscribeMessage); - - IOT_DEBUG("-->Success - Sticky and non-sticky subscriptions do not conflict \n"); - -} - -TEST_C(ShadowActionTests, ACKWaitingMoreThanAllowed) { - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - - IOT_DEBUG("-->Running Shadow Action Tests - Ack waiting more than allowed wait time \n"); - - // 1st - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, - 100, false); // 100 sec to timeout - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - // 2nd - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, - 100, false); // 100 sec to timeout - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - // 3rd - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, - 100, false); // 100 sec to timeout - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - // 4th - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, - 100, false); // 100 sec to timeout - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - // 5th - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, - 100, false); // 100 sec to timeout - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - // 6th - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, - 100, false); // 100 sec to timeout - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - // 7th - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, - 100, false); // 100 sec to timeout - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - // 8th - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, - 100, false); // 100 sec to timeout - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - // 9th - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, - 100, false); // 100 sec to timeout - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - // 10th - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, - 100, false); // 100 sec to timeout - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - // 11th - // Should return some error code, since we are running out of ACK space - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, - 100, false); // 100 sec to timeout - CHECK_EQUAL_C_INT(FAILURE, ret_val); - - IOT_DEBUG("-->Success - Ack waiting more than allowed wait time \n"); -} - -TEST_C(ShadowActionTests, InboundDataTooBigForBuffer) { - uint32_t i = 0; - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - IoT_Publish_Message_Params params; - char expectedCallbackString[AWS_IOT_MQTT_RX_BUF_LEN + 2]; - - IOT_DEBUG("-->Running Shadow Action Tests - Inbound data too big for buffer \n"); - - snprintf(jsonFullDocument, 200, "NOT_VISITED"); - - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, 4, - false); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - for(i = 0; i < AWS_IOT_MQTT_RX_BUF_LEN; i++) { - expectedCallbackString[i] = 'X'; - } - expectedCallbackString[i + 1] = '\0'; - - params.payloadLen = strlen(expectedCallbackString); - params.payload = expectedCallbackString; - params.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - CHECK_EQUAL_C_INT(MQTT_RX_BUFFER_TOO_SHORT_ERROR, ret_val); - CHECK_EQUAL_C_STRING("NOT_VISITED", jsonFullDocument); - - IOT_DEBUG("-->Success - Inbound data too big for buffer \n"); -} - -#define TEST_JSON_RESPONSE_NO_TOKEN "{\"state\":{\"reported\":{\"sensor1\":98}}}" - -TEST_C(ShadowActionTests, NoClientTokenForShadowAction) { - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - IoT_Publish_Message_Params params; - - uint8_t firstByte, secondByte; - uint16_t topicNameLen; - char topicName[128] = "test"; - - IOT_DEBUG("-->Running Shadow Action Tests - No client token for shadow action \n"); - - snprintf(getRequestJson, TEST_JSON_SIZE, "{}"); - snprintf(jsonFullDocument, 200, "NOT_VISITED"); - - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, actionCallback, NULL, 4, - false); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - params.payloadLen = strlen(TEST_JSON_RESPONSE_NO_TOKEN); - params.payload = TEST_JSON_RESPONSE_NO_TOKEN; - params.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - // Should never subscribe to accepted/rejected topics since we have no token to track the response - CHECK_EQUAL_C_STRING("NOT_VISITED", jsonFullDocument); - - firstByte = (uint8_t)(TxBuffer.pBuffer[2]); - secondByte = (uint8_t)(TxBuffer.pBuffer[3]); - topicNameLen = (uint16_t) (secondByte + (256 * firstByte)); - - snprintf(topicName, topicNameLen + 1u, "%s", &(TxBuffer.pBuffer[4])); // Added one for null character - - // Verify publish happens - CHECK_EQUAL_C_STRING(GET_PUB_TOPIC, topicName); - - IOT_DEBUG("-->Success - No client token for shadow action \n"); -} - -TEST_C(ShadowActionTests, IsReceivedJsonValid) -{ - bool ret_val; - char getRequestJson[TEST_JSON_SIZE]; - - IOT_DEBUG("-->Running Shadow Action Tests - IsReceivedJsonValid \n"); - - snprintf(getRequestJson, TEST_JSON_SIZE, TEST_JSON_RESPONSE_FULL_DOCUMENT); - - //Test by cutting the JSON document - ret_val = isReceivedJsonValid(getRequestJson, 3); - CHECK_EQUAL_C_INT(false, ret_val); - - //Happy path - ret_val = isReceivedJsonValid(getRequestJson, TEST_JSON_SIZE); - CHECK_EQUAL_C_INT(true, ret_val); - - IOT_DEBUG("-->Success - IsReceivedJsonValid"); -} - -TEST_C(ShadowActionTests, ExtractClientToken) -{ - bool ret_val; - char getRequestJson[TEST_JSON_SIZE]; - char extractedClientToken[MAX_SIZE_CLIENT_ID_WITH_SEQUENCE]; - - IOT_DEBUG("-->Running Shadow Action Tests - ExtractClientToken \n"); - - //Try JSON with no token - snprintf(getRequestJson, TEST_JSON_SIZE, "{}"); - ret_val = extractClientToken(getRequestJson, TEST_JSON_SIZE, extractedClientToken, MAX_SIZE_CLIENT_ID_WITH_SEQUENCE ); - CHECK_EQUAL_C_INT(false, ret_val); - - //Try JSON with token but not enough memory - snprintf(getRequestJson, TEST_JSON_SIZE, TEST_JSON_RESPONSE_FULL_DOCUMENT); - ret_val = extractClientToken(getRequestJson, TEST_JSON_SIZE, extractedClientToken, 1 ); - CHECK_EQUAL_C_INT(false, ret_val); - - //Happy path - ret_val = extractClientToken(getRequestJson, TEST_JSON_SIZE, extractedClientToken, MAX_SIZE_CLIENT_ID_WITH_SEQUENCE ); - CHECK_EQUAL_C_INT(true, ret_val); - - IOT_DEBUG("-->Success - ExtractClientToken"); -} - -TEST_C(ShadowActionTests, GetAndDeleteRequest) { - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - - IOT_DEBUG("-->Running Shadow Action Tests - GetAndDeleteRequest \n"); - - ret_val = aws_iot_shadow_internal_get_request_json(NULL, TEST_JSON_SIZE); - CHECK_EQUAL_C_INT(FAILURE, ret_val); - - ret_val = aws_iot_shadow_internal_get_request_json(getRequestJson, 1); - CHECK_EQUAL_C_INT(FAILURE, ret_val); - - ret_val = aws_iot_shadow_internal_delete_request_json(NULL, TEST_JSON_SIZE); - CHECK_EQUAL_C_INT(FAILURE, ret_val); - - ret_val = aws_iot_shadow_internal_delete_request_json(getRequestJson, 1); - CHECK_EQUAL_C_INT(FAILURE, ret_val); - - IOT_DEBUG("-->Success - GetAndDeleteRequest"); -} - -TEST_C(ShadowActionTests, NoCallbackForShadowAction) { - IoT_Error_t ret_val = SUCCESS; - char getRequestJson[TEST_JSON_SIZE]; - IoT_Publish_Message_Params params; - - uint8_t firstByte, secondByte; - uint16_t topicNameLen; - char topicName[128] = "test"; - - IOT_DEBUG("-->Running Shadow Action Tests - No callback for shadow action \n"); - - snprintf(jsonFullDocument, 200, "NOT_VISITED"); - - aws_iot_shadow_internal_get_request_json(getRequestJson, TEST_JSON_SIZE); - ret_val = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_GET, getRequestJson, TEST_JSON_SIZE, NULL, NULL, 4, false); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - params.payloadLen = strlen(TEST_JSON_RESPONSE_FULL_DOCUMENT); - params.payload = TEST_JSON_RESPONSE_FULL_DOCUMENT; - setTLSRxBufferWithMsgOnSubscribedTopic(GET_ACCEPTED_TOPIC, strlen(GET_ACCEPTED_TOPIC), QOS0, params, - params.payload); - ret_val = aws_iot_shadow_yield(&client, 200); - - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - // Should never subscribe to accepted/rejected topics since we have no callback to track the response - CHECK_EQUAL_C_STRING("NOT_VISITED", jsonFullDocument); - - firstByte = (uint8_t)(TxBuffer.pBuffer[2]); - secondByte = (uint8_t)(TxBuffer.pBuffer[3]); - topicNameLen = (uint16_t) (secondByte + (256 * firstByte)); - - snprintf(topicName, topicNameLen + 1u, "%s", &(TxBuffer.pBuffer[4])); // Added one for null character - - // Verify publish happens - CHECK_EQUAL_C_STRING(GET_PUB_TOPIC, topicName); - - IOT_DEBUG("-->Success - No callback for shadow action"); -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_delta.cpp b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_delta.cpp deleted file mode 100644 index db9c0b25d..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_delta.cpp +++ /dev/null @@ -1,33 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_shadow_delta.cpp - * @brief IoT Client Unit Testing - Shadow Delta Tests - */ - -#include -#include - -TEST_GROUP_C(ShadowDeltaTest){ - TEST_GROUP_C_SETUP_WRAPPER(ShadowDeltaTest) - TEST_GROUP_C_TEARDOWN_WRAPPER(ShadowDeltaTest) -}; - -TEST_GROUP_C_WRAPPER(ShadowDeltaTest, registerDeltaSuccess) -TEST_GROUP_C_WRAPPER(ShadowDeltaTest, registerDeltaInt) -TEST_GROUP_C_WRAPPER(ShadowDeltaTest, registerDeltaIntNoCallback) -TEST_GROUP_C_WRAPPER(ShadowDeltaTest, DeltaNestedObject) -TEST_GROUP_C_WRAPPER(ShadowDeltaTest, DeltaVersionIgnoreOldVersion) diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_delta_helper.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_delta_helper.c deleted file mode 100644 index 1e6cc2a0a..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_delta_helper.c +++ /dev/null @@ -1,324 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_shadow_delta_helper.c - * @brief IoT Client Unit Testing - Shadow Delta Tests Helper - */ - -#include -#include -#include - -#include "aws_iot_shadow_interface.h" -#include "aws_iot_tests_unit_helper_functions.h" -#include "aws_iot_log.h" - -static AWS_IoT_Client client; -static IoT_Client_Connect_Params connectParams; -static ShadowInitParameters_t shadowInitParams; -static ShadowConnectParameters_t shadowConnectParams; - -static char receivedNestedObject[100] = ""; -static char sentNestedObjectData[100] = "{\"sensor1\":23}"; -static char shadowDeltaTopic[MAX_SHADOW_TOPIC_LENGTH_BYTES]; - -#define SHADOW_DELTA_UPDATE "$aws/things/%s/shadow/update/delta" - -#undef AWS_IOT_MY_THING_NAME -#define AWS_IOT_MY_THING_NAME "AWS-IoT-C-SDK" - -void genericCallback(const char *pJsonStringData, uint32_t JsonStringDataLen, jsonStruct_t *pContext) { - printf("\nkey[%s]==Data[%.*s]\n", pContext->pKey, JsonStringDataLen, pJsonStringData); -} - -void nestedObjectCallback(const char *pJsonStringData, uint32_t JsonStringDataLen, jsonStruct_t *pContext) { - printf("\nkey[%s]==Data[%.*s]\n", pContext->pKey, JsonStringDataLen, pJsonStringData); - snprintf(receivedNestedObject, 100, "%.*s", JsonStringDataLen, pJsonStringData); -} - -TEST_GROUP_C_SETUP(ShadowDeltaTest) { - IoT_Error_t ret_val = SUCCESS; - - shadowInitParams.pHost = AWS_IOT_MQTT_HOST; - shadowInitParams.port = AWS_IOT_MQTT_PORT; - shadowInitParams.pClientCRT = AWS_IOT_CERTIFICATE_FILENAME; - shadowInitParams.pRootCA = AWS_IOT_ROOT_CA_FILENAME; - shadowInitParams.pClientKey = AWS_IOT_PRIVATE_KEY_FILENAME; - shadowInitParams.disconnectHandler = NULL; - shadowInitParams.enableAutoReconnect = false; - ret_val = aws_iot_shadow_init(&client, &shadowInitParams); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - shadowConnectParams.pMyThingName = AWS_IOT_MY_THING_NAME; - shadowConnectParams.pMqttClientId = AWS_IOT_MQTT_CLIENT_ID; - shadowConnectParams.mqttClientIdLen = (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID); - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - ret_val = aws_iot_shadow_connect(&client, &shadowConnectParams); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - snprintf(shadowDeltaTopic, MAX_SHADOW_TOPIC_LENGTH_BYTES, SHADOW_DELTA_UPDATE, AWS_IOT_MY_THING_NAME); -} - -TEST_GROUP_C_TEARDOWN(ShadowDeltaTest) { - -} - -TEST_C(ShadowDeltaTest, registerDeltaSuccess) { - jsonStruct_t windowHandler; - char deltaJSONString[] = "{\"state\":{\"delta\":{\"window\":true}},\"version\":1}"; - bool windowOpenData = false; - IoT_Publish_Message_Params params; - IoT_Error_t ret_val = SUCCESS; - - IOT_DEBUG("\n-->Running Shadow Delta Tests - Register delta success \n"); - - windowHandler.cb = genericCallback; - windowHandler.pKey = "window"; - windowHandler.type = SHADOW_JSON_BOOL; - windowHandler.pData = &windowOpenData; - windowHandler.dataLength = sizeof(bool); - - params.payloadLen = strlen(deltaJSONString); - params.payload = deltaJSONString; - params.qos = QOS0; - - ResetTLSBuffer(); - setTLSRxBufferForSuback(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params); - - ret_val = aws_iot_shadow_register_delta(&client, &windowHandler); - - ResetTLSBuffer(); - setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); - - ret_val = aws_iot_shadow_yield(&client, 3000); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - CHECK_EQUAL_C_INT(true, windowOpenData); -} - - -TEST_C(ShadowDeltaTest, registerDeltaInt) { - IoT_Error_t ret_val = SUCCESS; - jsonStruct_t intHandler; - int32_t intData = 0; - char deltaJSONString[] = "{\"state\":{\"delta\":{\"length\":23}},\"version\":1}"; - IoT_Publish_Message_Params params; - - IOT_DEBUG("\n-->Running Shadow Delta Tests - Register delta integer \n"); - - intHandler.cb = genericCallback; - intHandler.pKey = "length"; - intHandler.type = SHADOW_JSON_INT32; - intHandler.pData = &intData; - intHandler.dataLength = sizeof(int32_t); - - params.payloadLen = strlen(deltaJSONString); - params.payload = deltaJSONString; - params.qos = QOS0; - - ResetTLSBuffer(); - setTLSRxBufferForSuback(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params); - - ret_val = aws_iot_shadow_register_delta(&client, &intHandler); - - ResetTLSBuffer(); - setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); - - aws_iot_shadow_yield(&client, 3000); - CHECK_EQUAL_C_INT(23, intData); -} - -TEST_C(ShadowDeltaTest, registerDeltaIntNoCallback) { - IoT_Error_t ret_val = SUCCESS; - jsonStruct_t intHandler; - int32_t intData = 0; - char deltaJSONString[] = "{\"state\":{\"delta\":{\"length_nocb\":23}},\"version\":1}"; - IoT_Publish_Message_Params params; - - IOT_DEBUG("\n-->Running Shadow Delta Tests - Register delta integer with no callback \n"); - - intHandler.cb = NULL; - intHandler.pKey = "length_nocb"; - intHandler.type = SHADOW_JSON_INT32; - intHandler.pData = &intData; - intHandler.dataLength = sizeof(int32_t); - - params.payloadLen = strlen(deltaJSONString); - params.payload = deltaJSONString; - params.qos = QOS0; - - ResetTLSBuffer(); - setTLSRxBufferForSuback(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params); - - ret_val = aws_iot_shadow_register_delta(&client, &intHandler); - - ResetTLSBuffer(); - setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); - - aws_iot_shadow_yield(&client, 3000); - CHECK_EQUAL_C_INT(23, intData); -} - -TEST_C(ShadowDeltaTest, DeltaNestedObject) { - IoT_Error_t ret_val = SUCCESS; - IoT_Publish_Message_Params params; - jsonStruct_t nestedObjectHandler; - char nestedObject[100]; - char deltaJSONString[100]; - - printf("\n-->Running Shadow Delta Tests - Delta received with nested object \n"); - - nestedObjectHandler.cb = nestedObjectCallback; - nestedObjectHandler.pKey = "sensors"; - nestedObjectHandler.type = SHADOW_JSON_OBJECT; - nestedObjectHandler.pData = &nestedObject; - nestedObjectHandler.dataLength = 100; - - snprintf(deltaJSONString, 100, "{\"state\":{\"delta\":{\"%s\":%s}},\"version\":1}", nestedObjectHandler.pKey, - sentNestedObjectData); - params.payloadLen = strlen(deltaJSONString); - params.payload = deltaJSONString; - params.qos = QOS0; - - ResetTLSBuffer(); - setTLSRxBufferForSuback(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params); - - ret_val = aws_iot_shadow_register_delta(&client, &nestedObjectHandler); - - ResetTLSBuffer(); - setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); - - aws_iot_shadow_yield(&client, 3000); - CHECK_EQUAL_C_STRING(sentNestedObjectData, receivedNestedObject); -} - - -// Send back to back version and ensure a wrong version is ignored with old message enabled -TEST_C(ShadowDeltaTest, DeltaVersionIgnoreOldVersion) { - IoT_Error_t ret_val = SUCCESS; - char deltaJSONString[100]; - jsonStruct_t nestedObjectHandler; - char nestedObject[100]; - IoT_Publish_Message_Params params; - - printf("\n-->Running Shadow Delta Tests - delta received, old version ignored \n"); - - nestedObjectHandler.cb = nestedObjectCallback; - nestedObjectHandler.pKey = "sensors"; - nestedObjectHandler.type = SHADOW_JSON_OBJECT; - nestedObjectHandler.pData = &nestedObject; - nestedObjectHandler.dataLength = 100; - - snprintf(deltaJSONString, 100, "{\"state\":{\"delta\":{\"%s\":%s}},\"version\":1}", nestedObjectHandler.pKey, - sentNestedObjectData); - params.payloadLen = strlen(deltaJSONString); - params.payload = deltaJSONString; - params.qos = QOS0; - - ResetTLSBuffer(); - setTLSRxBufferForSuback(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params); - - ret_val = aws_iot_shadow_register_delta(&client, &nestedObjectHandler); - - ResetTLSBuffer(); - setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); - - aws_iot_shadow_yield(&client, 100); - CHECK_EQUAL_C_STRING(sentNestedObjectData, receivedNestedObject); - - snprintf(receivedNestedObject, 100, " "); - snprintf(deltaJSONString, 100, "{\"state\":{\"delta\":{\"%s\":%s}},\"version\":2}", nestedObjectHandler.pKey, - sentNestedObjectData); - params.payloadLen = strlen(deltaJSONString); - params.payload = deltaJSONString; - params.qos = QOS0; - - ResetTLSBuffer(); - setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); - - aws_iot_shadow_yield(&client, 100); - CHECK_EQUAL_C_STRING(sentNestedObjectData, receivedNestedObject); - - snprintf(receivedNestedObject, 100, " "); - snprintf(deltaJSONString, 100, "{\"state\":{\"delta\":{\"%s\":%s}},\"version\":2}", nestedObjectHandler.pKey, - sentNestedObjectData); - params.payloadLen = strlen(deltaJSONString); - params.payload = deltaJSONString; - params.qos = QOS0; - - ResetTLSBuffer(); - setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); - - aws_iot_shadow_yield(&client, 100); - CHECK_EQUAL_C_STRING(" ", receivedNestedObject); - - snprintf(receivedNestedObject, 100, " "); - snprintf(deltaJSONString, 100, "{\"state\":{\"delta\":{\"%s\":%s}},\"version\":3}", nestedObjectHandler.pKey, - sentNestedObjectData); - params.payloadLen = strlen(deltaJSONString); - params.payload = deltaJSONString; - params.qos = QOS0; - - ResetTLSBuffer(); - setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); - - aws_iot_shadow_yield(&client, 100); - CHECK_EQUAL_C_STRING(sentNestedObjectData, receivedNestedObject); - - aws_iot_shadow_reset_last_received_version(); - - snprintf(receivedNestedObject, 100, " "); - snprintf(deltaJSONString, 100, "{\"state\":{\"delta\":{\"%s\":%s}},\"version\":3}", nestedObjectHandler.pKey, - sentNestedObjectData); - params.payloadLen = strlen(deltaJSONString); - params.payload = deltaJSONString; - params.qos = QOS0; - - ResetTLSBuffer(); - setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); - - aws_iot_shadow_yield(&client, 100); - CHECK_EQUAL_C_STRING(sentNestedObjectData, receivedNestedObject); - - snprintf(receivedNestedObject, 100, " "); - snprintf(deltaJSONString, 100, "{\"state\":{\"delta\":{\"%s\":%s}},\"version\":3}", nestedObjectHandler.pKey, - sentNestedObjectData); - params.payloadLen = strlen(deltaJSONString); - params.payload = deltaJSONString; - params.qos = QOS0; - - ResetTLSBuffer(); - setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); - - aws_iot_shadow_yield(&client, 100); - CHECK_EQUAL_C_STRING(" ", receivedNestedObject); - - aws_iot_shadow_disable_discard_old_delta_msgs(); - - snprintf(receivedNestedObject, 100, " "); - snprintf(deltaJSONString, 100, "{\"state\":{\"delta\":{\"%s\":%s}},\"version\":3}", nestedObjectHandler.pKey, - sentNestedObjectData); - params.payloadLen = strlen(deltaJSONString); - params.payload = deltaJSONString; - params.qos = QOS0; - - ResetTLSBuffer(); - setTLSRxBufferWithMsgOnSubscribedTopic(shadowDeltaTopic, strlen(shadowDeltaTopic), QOS0, params, params.payload); - - aws_iot_shadow_yield(&client, 100); - CHECK_EQUAL_C_STRING(sentNestedObjectData, receivedNestedObject); -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_json_builder.cpp b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_json_builder.cpp deleted file mode 100644 index 8feb144e5..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_json_builder.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_shadow_json_builder.cpp - * @brief IoT Client Unit Testing - Shadow JSON Builder Tests - */ - -#include -#include - -TEST_GROUP_C(ShadowJsonBuilderTests){ - TEST_GROUP_C_SETUP_WRAPPER(ShadowJsonBuilderTests) - TEST_GROUP_C_TEARDOWN_WRAPPER(ShadowJsonBuilderTests) -}; - -TEST_GROUP_C_WRAPPER(ShadowJsonBuilderTests, UpdateTheJSONDocumentBuilder) -TEST_GROUP_C_WRAPPER(ShadowJsonBuilderTests, PassingNullValue) -TEST_GROUP_C_WRAPPER(ShadowJsonBuilderTests, SmallBuffer) diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_json_builder_helper.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_json_builder_helper.c deleted file mode 100644 index 3541341b5..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_json_builder_helper.c +++ /dev/null @@ -1,131 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_shadow_json_builder_helper.c - * @brief IoT Client Unit Testing - Shadow JSON Builder Tests Helper - */ - -#include -#include -#include - -#include "aws_iot_shadow_actions.h" -#include "aws_iot_log.h" -#include "aws_iot_tests_unit_helper_functions.h" - -static jsonStruct_t dataFloatHandler; -static jsonStruct_t dataDoubleHandler; -static double doubleData = 4.0908f; -static float floatData = 3.445f; -static AWS_IoT_Client iotClient; -static IoT_Client_Connect_Params connectParams; -static ShadowInitParameters_t shadowInitParams; -static ShadowConnectParameters_t shadowConnectParams; - -TEST_GROUP_C_SETUP(ShadowJsonBuilderTests) { - IoT_Error_t ret_val; - - shadowInitParams.pHost = AWS_IOT_MQTT_HOST; - shadowInitParams.port = AWS_IOT_MQTT_PORT; - shadowInitParams.pClientCRT = AWS_IOT_CERTIFICATE_FILENAME; - shadowInitParams.pRootCA = AWS_IOT_ROOT_CA_FILENAME; - shadowInitParams.pClientKey = AWS_IOT_PRIVATE_KEY_FILENAME; - shadowInitParams.disconnectHandler = NULL; - shadowInitParams.enableAutoReconnect = false; - ret_val = aws_iot_shadow_init(&iotClient, &shadowInitParams); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - shadowConnectParams.pMyThingName = AWS_IOT_MY_THING_NAME; - shadowConnectParams.pMqttClientId = AWS_IOT_MQTT_CLIENT_ID; - shadowConnectParams.mqttClientIdLen = (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID); - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - ret_val = aws_iot_shadow_connect(&iotClient, &shadowConnectParams); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - dataFloatHandler.cb = NULL; - dataFloatHandler.pData = &floatData; - dataFloatHandler.pKey = "floatData"; - dataFloatHandler.type = SHADOW_JSON_FLOAT; - dataFloatHandler.dataLength = sizeof(float); - - dataDoubleHandler.cb = NULL; - dataDoubleHandler.pData = &doubleData; - dataDoubleHandler.pKey = "doubleData"; - dataDoubleHandler.type = SHADOW_JSON_DOUBLE; - dataDoubleHandler.dataLength = sizeof(double); -} - -TEST_GROUP_C_TEARDOWN(ShadowJsonBuilderTests) { - /* Clean up. Not checking return code here because this is common to all tests. - * A test might have already caused a disconnect by this point. - */ - IoT_Error_t rc = aws_iot_mqtt_disconnect(&iotClient); - IOT_UNUSED(rc); -} - -#define TEST_JSON_RESPONSE_UPDATE_DOCUMENT "{\"state\":{\"reported\":{\"doubleData\":4.090800,\"floatData\":3.445000}}, \"clientToken\":\"" AWS_IOT_MQTT_CLIENT_ID "-0\"}" - -#define SIZE_OF_UPFATE_BUF 200 - -TEST_C(ShadowJsonBuilderTests, UpdateTheJSONDocumentBuilder) { - IoT_Error_t ret_val; - char updateRequestJson[SIZE_OF_UPFATE_BUF]; - size_t jsonBufSize = sizeof(updateRequestJson) / sizeof(updateRequestJson[0]); - - IOT_DEBUG("\n-->Running Shadow Json Builder Tests - Update the Json document builder \n"); - - ret_val = aws_iot_shadow_init_json_document(updateRequestJson, jsonBufSize); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - ret_val = aws_iot_shadow_add_reported(updateRequestJson, jsonBufSize, 2, &dataDoubleHandler, &dataFloatHandler); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - ret_val = aws_iot_finalize_json_document(updateRequestJson, jsonBufSize); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - - CHECK_EQUAL_C_STRING(TEST_JSON_RESPONSE_UPDATE_DOCUMENT, updateRequestJson); -} - -TEST_C(ShadowJsonBuilderTests, PassingNullValue) { - IoT_Error_t ret_val; - - IOT_DEBUG("\n-->Running Shadow Json Builder Tests - Passing Null value to Shadow json builder \n"); - - ret_val = aws_iot_shadow_init_json_document(NULL, SIZE_OF_UPFATE_BUF); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, ret_val); - ret_val = aws_iot_shadow_add_reported(NULL, SIZE_OF_UPFATE_BUF, 2, &dataDoubleHandler, &dataFloatHandler); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, ret_val); - ret_val = aws_iot_shadow_add_desired(NULL, SIZE_OF_UPFATE_BUF, 2, &dataDoubleHandler, &dataFloatHandler); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, ret_val); - ret_val = aws_iot_finalize_json_document(NULL, SIZE_OF_UPFATE_BUF); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, ret_val); -} - -TEST_C(ShadowJsonBuilderTests, SmallBuffer) { - IoT_Error_t ret_val; - char updateRequestJson[14]; - size_t jsonBufSize = sizeof(updateRequestJson) / sizeof(updateRequestJson[0]); - - IOT_DEBUG("\n-->Running Shadow Json Builder Tests - Json Buffer is too small \n"); - - ret_val = aws_iot_shadow_init_json_document(updateRequestJson, jsonBufSize); - CHECK_EQUAL_C_INT(SUCCESS, ret_val); - ret_val = aws_iot_shadow_add_reported(updateRequestJson, jsonBufSize, 2, &dataDoubleHandler, &dataFloatHandler); - CHECK_EQUAL_C_INT(SHADOW_JSON_BUFFER_TRUNCATED, ret_val); - ret_val = aws_iot_shadow_add_desired(updateRequestJson, jsonBufSize, 2, &dataDoubleHandler, &dataFloatHandler); - CHECK_EQUAL_C_INT(SHADOW_JSON_ERROR, ret_val); - ret_val = aws_iot_finalize_json_document(updateRequestJson, jsonBufSize); - CHECK_EQUAL_C_INT(SHADOW_JSON_ERROR, ret_val); -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_null_fields.cpp b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_null_fields.cpp deleted file mode 100644 index dd4d02a6b..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_null_fields.cpp +++ /dev/null @@ -1,40 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_shadow_null_fields.cpp - * @brief IoT Client Unit Testing - Shadow APIs NULL field Tests - */ - -#include -#include - -TEST_GROUP_C(ShadowNullFields){ - TEST_GROUP_C_SETUP_WRAPPER(ShadowNullFields) - TEST_GROUP_C_TEARDOWN_WRAPPER(ShadowNullFields) -}; - -TEST_GROUP_C_WRAPPER(ShadowNullFields, NullClientInit) -TEST_GROUP_C_WRAPPER(ShadowNullFields, NullClientConnect) -TEST_GROUP_C_WRAPPER(ShadowNullFields, NullHost) -TEST_GROUP_C_WRAPPER(ShadowNullFields, NullPort) -TEST_GROUP_C_WRAPPER(ShadowNullFields, NullClientID) -TEST_GROUP_C_WRAPPER(ShadowNullFields, NullUpdateDocument) -TEST_GROUP_C_WRAPPER(ShadowNullFields, NullClientYield) -TEST_GROUP_C_WRAPPER(ShadowNullFields, NullClientDisconnect) -TEST_GROUP_C_WRAPPER(ShadowNullFields, NullClientShadowGet) -TEST_GROUP_C_WRAPPER(ShadowNullFields, NullClientShadowUpdate) -TEST_GROUP_C_WRAPPER(ShadowNullFields, NullClientShadowDelete) -TEST_GROUP_C_WRAPPER(ShadowNullFields, NullClientSetAutoreconnect) diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_null_fields_helper.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_null_fields_helper.c deleted file mode 100644 index 0848bd0a5..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_shadow_null_fields_helper.c +++ /dev/null @@ -1,151 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_shadow_null_fields_helper.c - * @brief IoT Client Unit Testing - Shadow APIs NULL field Tests helper - */ - -#include -#include -#include -#include - -#include "aws_iot_tests_unit_helper_functions.h" -#include "aws_iot_shadow_interface.h" -#include "aws_iot_shadow_actions.h" -#include "aws_iot_log.h" - -static AWS_IoT_Client client; -static ShadowInitParameters_t shadowInitParams; -static ShadowConnectParameters_t shadowConnectParams; - -static Shadow_Ack_Status_t ackStatusRx; -static ShadowActions_t actionRx; -static char jsonFullDocument[200]; - -void actionCallbackNullTest(const char *pThingName, ShadowActions_t action, Shadow_Ack_Status_t status, - const char *pReceivedJsonDocument, void *pContextData) { - IOT_UNUSED(pThingName); - IOT_UNUSED(pContextData); - IOT_DEBUG("%s", pReceivedJsonDocument); - actionRx = action; - ackStatusRx = status; - if(status != SHADOW_ACK_TIMEOUT) { - strcpy(jsonFullDocument, pReceivedJsonDocument); - } -} - -TEST_GROUP_C_SETUP(ShadowNullFields) { - ResetTLSBuffer(); -} - -TEST_GROUP_C_TEARDOWN(ShadowNullFields) { } - -TEST_C(ShadowNullFields, NullHost) { - shadowInitParams.pHost = NULL; - shadowInitParams.port = AWS_IOT_MQTT_PORT; - shadowInitParams.disconnectHandler = NULL; - IoT_Error_t rc = aws_iot_shadow_init(&client, &shadowInitParams); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -TEST_C(ShadowNullFields, NullPort) { - shadowInitParams.pHost = AWS_IOT_MQTT_HOST; - shadowInitParams.port = 0; - shadowInitParams.disconnectHandler = NULL; - IoT_Error_t rc = aws_iot_shadow_init(&client, &shadowInitParams); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -TEST_C(ShadowNullFields, NullClientID) { - shadowInitParams.pHost = AWS_IOT_MQTT_HOST; - shadowInitParams.port = AWS_IOT_MQTT_PORT; - shadowInitParams.pClientCRT = AWS_IOT_CERTIFICATE_FILENAME; - shadowInitParams.pRootCA = AWS_IOT_ROOT_CA_FILENAME; - shadowInitParams.pClientKey = AWS_IOT_PRIVATE_KEY_FILENAME; - shadowInitParams.disconnectHandler = NULL; - shadowInitParams.enableAutoReconnect = false; - IoT_Error_t rc = aws_iot_shadow_init(&client, &shadowInitParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - shadowConnectParams.pMyThingName = AWS_IOT_MY_THING_NAME; - shadowConnectParams.pMqttClientId = NULL; - rc = aws_iot_shadow_connect(&client, &shadowConnectParams); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -TEST_C(ShadowNullFields, NullClientInit) { - shadowInitParams.pHost = AWS_IOT_MQTT_HOST; - shadowInitParams.port = AWS_IOT_MQTT_PORT; - shadowInitParams.disconnectHandler = NULL; - IoT_Error_t rc = aws_iot_shadow_init(NULL, &shadowInitParams); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -TEST_C(ShadowNullFields, NullClientConnect) { - shadowInitParams.pHost = AWS_IOT_MQTT_HOST; - shadowInitParams.port = AWS_IOT_MQTT_PORT; - shadowInitParams.pClientCRT = AWS_IOT_CERTIFICATE_FILENAME; - shadowInitParams.pRootCA = AWS_IOT_ROOT_CA_FILENAME; - shadowInitParams.pClientKey = AWS_IOT_PRIVATE_KEY_FILENAME; - shadowInitParams.disconnectHandler = NULL; - shadowInitParams.enableAutoReconnect = false; - IoT_Error_t rc = aws_iot_shadow_init(&client, &shadowInitParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - shadowConnectParams.pMyThingName = AWS_IOT_MY_THING_NAME; - shadowConnectParams.pMqttClientId = AWS_IOT_MQTT_CLIENT_ID; - shadowConnectParams.mqttClientIdLen = (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID); - rc = aws_iot_shadow_connect(NULL, &shadowConnectParams); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -TEST_C(ShadowNullFields, NullUpdateDocument) { - IoT_Error_t rc = aws_iot_shadow_internal_action(AWS_IOT_MY_THING_NAME, SHADOW_UPDATE, NULL, 0, actionCallbackNullTest, - NULL, 4, false); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -TEST_C(ShadowNullFields, NullClientYield) { - IoT_Error_t rc = aws_iot_shadow_yield(NULL, 1000); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -TEST_C(ShadowNullFields, NullClientDisconnect) { - IoT_Error_t rc = aws_iot_shadow_disconnect(NULL); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -TEST_C(ShadowNullFields, NullClientShadowGet) { - IoT_Error_t rc = aws_iot_shadow_get(NULL, AWS_IOT_MY_THING_NAME, actionCallbackNullTest, NULL, 100, true); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -TEST_C(ShadowNullFields, NullClientShadowUpdate) { - IoT_Error_t rc = aws_iot_shadow_update(NULL, AWS_IOT_MY_THING_NAME, jsonFullDocument, - actionCallbackNullTest, NULL, 100, true); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -TEST_C(ShadowNullFields, NullClientShadowDelete) { - IoT_Error_t rc = aws_iot_shadow_delete(NULL, AWS_IOT_MY_THING_NAME, actionCallbackNullTest, NULL, 100, true); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -TEST_C(ShadowNullFields, NullClientSetAutoreconnect) { - IoT_Error_t rc = aws_iot_shadow_set_autoreconnect_status(NULL, true); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_subscribe.cpp b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_subscribe.cpp deleted file mode 100644 index f19a7c9c7..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_subscribe.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_subscribe.cpp - * @brief IoT Client Unit Testing - Subscribe API Tests - */ - -#include -#include - -TEST_GROUP_C(SubscribeTests){ - TEST_GROUP_C_SETUP_WRAPPER(SubscribeTests) - TEST_GROUP_C_TEARDOWN_WRAPPER(SubscribeTests) -}; - -/* C:1 - Subscribe with Null/empty Client Instance */ -TEST_GROUP_C_WRAPPER(SubscribeTests, SubscribeNullClient) -/* C:2 - Subscribe with Null/empty Topic Name */ -TEST_GROUP_C_WRAPPER(SubscribeTests, SubscribeNullTopic) -/* C:3 - Subscribe with Null client callback */ -TEST_GROUP_C_WRAPPER(SubscribeTests, SubscribeNullSubscribeHandler) -/* C:4 - Subscribe with Null client callback data */ -TEST_GROUP_C_WRAPPER(SubscribeTests, SubscribeNullSubscribeHandlerData) -/* C:5 - Subscribe with no connection */ -TEST_GROUP_C_WRAPPER(SubscribeTests, SubscribeNoConnection) -/* C:6 - Subscribe QoS2, error */ -/* Not required, QoS enum doesn't have value for QoS2 */ - -/* C:7 - Subscribe attempt, QoS0, no response timeout */ -TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeQoS0FailureOnNoSuback) -/* C:8 - Subscribe attempt, QoS1, no response timeout */ -TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeQoS1FailureOnNoSuback) - -/* C:9 - Subscribe QoS0 success, suback received */ -TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeQoS0Success) -/* C:10 - Subscribe QoS1 success, suback received */ -TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeQoS1Success) - -/* C:11 - Subscribe, QoS0, delayed suback, success */ -TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeQoS0WithDelayedSubackSuccess) -/* C:12 - Subscribe, QoS1, delayed suback, success */ -TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeQoS1WithDelayedSubackSuccess) - -/* C:13 - Subscribe QoS0 success, no puback sent on message */ -TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeQoS0MsgReceivedAndNoPubackSent) -/* C:14 - Subscribe QoS1 success, puback sent on message */ -TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeQoS1MsgReceivedAndSendPuback) - -/* C:15 - Subscribe, malformed response */ -TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeMalformedResponse) - -/* C:16 - Subscribe, multiple topics, messages on each topic */ -TEST_GROUP_C_WRAPPER(SubscribeTests, SubscribeToMultipleTopicsSuccess) -/* C:17 - Subscribe, max topics, messages on each topic */ -TEST_GROUP_C_WRAPPER(SubscribeTests, SubscribeToMaxAllowedTopicsSuccess) -/* C:18 - Subscribe, max topics, another subscribe */ -TEST_GROUP_C_WRAPPER(SubscribeTests, SubscribeToMaxPlusOneAllowedTopicsFailure) - -/* C:19 - Subscribe, '#' not last character in topic name, Failure */ -TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeTopicWithHashkeyAllSubTopicSuccess) -/* C:20 - Subscribe with '#', subscribed to all subtopics */ -TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeTopicHashkeyMustBeTheLastFail) -/* C:21 - Subscribe with '+' as wildcard success */ -TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeTopicWithPluskeySuccess) -/* C:22 - Subscribe with '+' as last character in topic name, Success */ -TEST_GROUP_C_WRAPPER(SubscribeTests, subscribeTopicPluskeyComesLastSuccess) diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_subscribe_helper.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_subscribe_helper.c deleted file mode 100644 index 53e4c67fc..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_subscribe_helper.c +++ /dev/null @@ -1,606 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_subscribe_helper.c - * @brief IoT Client Unit Testing - Subscribe API Tests Helper - */ - -#include -#include -#include - -#include "aws_iot_tests_unit_helper_functions.h" -#include "aws_iot_log.h" - -static IoT_Client_Init_Params initParams; -static IoT_Client_Connect_Params connectParams; -static IoT_Publish_Message_Params testPubMsgParams; -static char subTopic[10] = "sdk/Test"; -static uint16_t subTopicLen = 8; - -static AWS_IoT_Client iotClient; -static char CallbackMsgString[100]; -char cPayload[100]; - -static char CallbackMsgString1[100] = {"XXXX"}; -static char CallbackMsgString2[100] = {"XXXX"}; -static char CallbackMsgString3[100] = {"XXXX"}; -static char CallbackMsgString4[100] = {"XXXX"}; -static char CallbackMsgString5[100] = {"XXXX"}; -static char CallbackMsgString6[100] = {"XXXX"}; - -static void iot_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, - uint16_t topicNameLen, IoT_Publish_Message_Params *params, void *pData) { - if(NULL == pClient || NULL == topicName || 0 == topicNameLen) { - return; - } - - IOT_UNUSED(pData); - - char *tmp = params->payload; - unsigned int i; - - for(i = 0; i < (params->payloadLen); i++) { - CallbackMsgString[i] = tmp[i]; - } -} - -static void iot_subscribe_callback_handler1(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, - IoT_Publish_Message_Params *params, void *pData) { - if(NULL == pClient || NULL == topicName || 0 == topicNameLen) { - return; - } - - IOT_UNUSED(pData); - - char *tmp = params->payload; - unsigned int i; - - printf("callback topic %.*s\n", topicNameLen, topicName); - for(i = 0; i < (params->payloadLen); i++) { - CallbackMsgString1[i] = tmp[i]; - } -} - -static void iot_subscribe_callback_handler2(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, - IoT_Publish_Message_Params *params, void *pData) { - if(NULL == pClient || NULL == topicName || 0 == topicNameLen) { - return; - } - - IOT_UNUSED(pData); - - char *tmp = params->payload; - unsigned int i; - - for(i = 0; i < (params->payloadLen); i++) { - CallbackMsgString2[i] = tmp[i]; - } -} - -static void iot_subscribe_callback_handler3(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, - IoT_Publish_Message_Params *params, void *pData) { - if(NULL == pClient || NULL == topicName || 0 == topicNameLen) { - return; - } - - IOT_UNUSED(pData); - - char *tmp = params->payload; - unsigned int i; - - for(i = 0; i < (params->payloadLen); i++) { - CallbackMsgString3[i] = tmp[i]; - } -} - -static void iot_subscribe_callback_handler4(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, - IoT_Publish_Message_Params *params, void *pData) { - if(NULL == pClient || NULL == topicName || 0 == topicNameLen) { - return; - } - - IOT_UNUSED(pData); - - char *tmp = params->payload; - unsigned int i; - - for(i = 0; i < (params->payloadLen); i++) { - CallbackMsgString4[i] = tmp[i]; - } -} - -static void iot_subscribe_callback_handler5(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, - IoT_Publish_Message_Params *params, void *pData) { - if(NULL == pClient || NULL == topicName || 0 == topicNameLen) { - return; - } - - IOT_UNUSED(pData); - - char *tmp = params->payload; - unsigned int i; - - for(i = 0; i < (params->payloadLen); i++) { - CallbackMsgString5[i] = tmp[i]; - } -} - -static void iot_subscribe_callback_handler6(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, - IoT_Publish_Message_Params *params, void *pData) { - if(NULL == pClient || NULL == topicName || 0 == topicNameLen) { - return; - } - - IOT_UNUSED(pData); - - char *tmp = params->payload; - unsigned int i; - - for(i = 0; i < (params->payloadLen); i++) { - CallbackMsgString6[i] = tmp[i]; - } -} - -TEST_GROUP_C_SETUP(SubscribeTests) { - IoT_Error_t rc; - ResetTLSBuffer(); - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - initParams.mqttCommandTimeout_ms = 2000; - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - IOT_DEBUG("MQTT Status State : %d, RC : %d\n\n", aws_iot_mqtt_get_client_state(&iotClient), rc); - - testPubMsgParams.qos = QOS1; - testPubMsgParams.isRetained = 0; - snprintf(cPayload, 100, "%s : %d ", "hello from SDK", 0); - testPubMsgParams.payload = (void *) cPayload; - testPubMsgParams.payloadLen = strlen(cPayload); - - ResetTLSBuffer(); -} - -TEST_GROUP_C_TEARDOWN(SubscribeTests) { } - - - -/* C:1 - Subscribe with Null/empty Client Instance */ -TEST_C(SubscribeTests, SubscribeNullClient) { - IoT_Error_t rc = aws_iot_mqtt_subscribe(NULL, "sdkTest/Sub", 11, QOS1, iot_subscribe_callback_handler, &iotClient); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -/* C:2 - Subscribe with Null/empty Topic Name */ -TEST_C(SubscribeTests, SubscribeNullTopic) { - IoT_Error_t rc = aws_iot_mqtt_subscribe(&iotClient, NULL, 11, QOS1, iot_subscribe_callback_handler, &iotClient); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -/* C:3 - Subscribe with Null client callback */ -TEST_C(SubscribeTests, SubscribeNullSubscribeHandler) { - IoT_Error_t rc = aws_iot_mqtt_subscribe(&iotClient, "sdkTest/Sub", 11, QOS1, NULL, &iotClient); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} -/* C:4 - Subscribe with Null client callback data */ -TEST_C(SubscribeTests, SubscribeNullSubscribeHandlerData) { - setTLSRxBufferForSuback(subTopic, subTopicLen, QOS0, testPubMsgParams); - IoT_Error_t rc = aws_iot_mqtt_subscribe(&iotClient, "sdkTest/Sub", 11, QOS1, iot_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); -} -/* C:5 - Subscribe with no connection */ -TEST_C(SubscribeTests, SubscribeNoConnection) { - /* Disconnect first */ - IoT_Error_t rc = aws_iot_mqtt_disconnect(&iotClient); - - rc = aws_iot_mqtt_subscribe(&iotClient, "sdkTest/Sub", 11, QOS1, iot_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc); -} -/* C:6 - Subscribe QoS2, error */ -/* Not required, QoS enum doesn't have value for QoS2 */ - -/* C:7 - Subscribe attempt, QoS0, no response timeout */ -TEST_C(SubscribeTests, subscribeQoS0FailureOnNoSuback) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Subscribe Tests - C:7 - Subscribe attempt, QoS0, no response timeout \n"); - - rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS0, iot_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, rc); - - IOT_DEBUG("-->Success - C:7 - Subscribe attempt, QoS0, no response timeout \n"); -} -/* C:8 - Subscribe attempt, QoS1, no response timeout */ -TEST_C(SubscribeTests, subscribeQoS1FailureOnNoSuback) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Subscribe Tests - C:8 - Subscribe attempt, QoS1, no response timeout \n"); - - rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS1, iot_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, rc); - - IOT_DEBUG("-->Success - C:8 - Subscribe attempt, QoS1, no response timeout \n"); -} - -/* C:9 - Subscribe QoS0 success, suback received */ -TEST_C(SubscribeTests, subscribeQoS0Success) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Subscribe Tests - C:9 - Subscribe QoS0 success, suback received \n"); - - setTLSRxBufferForSuback(subTopic, subTopicLen, QOS0, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS0, iot_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - IOT_DEBUG("-->Success - C:9 - Subscribe QoS0 success, suback received \n"); -} - -/* C:10 - Subscribe QoS1 success, suback received */ -TEST_C(SubscribeTests, subscribeQoS1Success) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Subscribe Tests - C:10 - Subscribe QoS1 success, suback received \n"); - - setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS1, iot_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - IOT_DEBUG("-->Success - C:10 - Subscribe QoS1 success, suback received \n"); -} - -/* C:11 - Subscribe, QoS0, delayed suback, success */ -TEST_C(SubscribeTests, subscribeQoS0WithDelayedSubackSuccess) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Subscribe Tests - C:11 - Subscribe, QoS0, delayed suback, success \n"); - - setTLSRxBufferForSuback(subTopic, subTopicLen, QOS0, testPubMsgParams); - setTLSRxBufferDelay(0, (int) iotClient.clientData.commandTimeoutMs/2); - rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS0, iot_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - IOT_DEBUG("-->Success - C:11 - Subscribe, QoS0, delayed suback, success \n"); -} - -/* C:12 - Subscribe, QoS1, delayed suback, success */ -TEST_C(SubscribeTests, subscribeQoS1WithDelayedSubackSuccess) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Subscribe Tests - C:12 - Subscribe, QoS1, delayed suback, success \n"); - - setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams); - setTLSRxBufferDelay(0, (int) iotClient.clientData.commandTimeoutMs/2); - rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS1, iot_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - IOT_DEBUG("-->Success - C:12 - Subscribe, QoS1, delayed suback, success \n"); -} - -/* C:13 - Subscribe QoS0 success, no puback sent on message */ -TEST_C(SubscribeTests, subscribeQoS0MsgReceivedAndNoPubackSent) { - IoT_Error_t rc = SUCCESS; - char expectedCallbackString[100] = "Test msg - unit test"; - - IOT_DEBUG("-->Running Subscribe Tests - C:13 - Subscribe QoS0 success, no puback sent on message \n"); - - ResetTLSBuffer(); - setTLSRxBufferForSuback(subTopic, subTopicLen, QOS0, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS0, iot_subscribe_callback_handler, NULL); - if(SUCCESS == rc) { - testPubMsgParams.qos = QOS0; - setTLSRxBufferWithMsgOnSubscribedTopic(subTopic, subTopicLen, QOS0, testPubMsgParams, expectedCallbackString); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - if(SUCCESS == rc) { - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); - } - } - CHECK_EQUAL_C_INT(0, isLastTLSTxMessagePuback()); - - IOT_DEBUG("-->Success - C:13 - Subscribe QoS0 success, no puback sent on message \n"); -} - -/* C:14 - Subscribe QoS1 success, puback sent on message */ -TEST_C(SubscribeTests, subscribeQoS1MsgReceivedAndSendPuback) { - IoT_Error_t rc = SUCCESS; - char expectedCallbackString[] = "0xA5A5A3"; - - IOT_DEBUG("-->Running Subscribe Tests - C:14 - Subscribe QoS1 success, puback sent on message \n"); - - setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS1, iot_subscribe_callback_handler, NULL); - if(SUCCESS == rc) { - setTLSRxBufferWithMsgOnSubscribedTopic(subTopic, subTopicLen, QOS1, testPubMsgParams, expectedCallbackString); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - if(SUCCESS == rc) { - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); - } - CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePuback()); - } - - IOT_DEBUG("-->Success - C:14 - Subscribe QoS1 success, puback sent on message \n"); -} - -/* C:15 - Subscribe, malformed response */ -TEST_C(SubscribeTests, subscribeMalformedResponse) {} - -/* C:16 - Subscribe, multiple topics, messages on each topic */ -TEST_C(SubscribeTests, SubscribeToMultipleTopicsSuccess) { - IoT_Error_t rc = SUCCESS; - char expectedCallbackString[] = "0xA5A5A3"; - - IOT_DEBUG("-->Running Subscribe Tests - C:16 - Subscribe, multiple topics, messages on each topic \n"); - - setTLSRxBufferForSuback("sdk/Test1", 9, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test1", 9, QOS1, iot_subscribe_callback_handler1, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - setTLSRxBufferForSuback("sdk/Test2", 9, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test2", 9, QOS1, iot_subscribe_callback_handler2, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test1", 9, QOS1, testPubMsgParams, expectedCallbackString); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString1); - - IOT_DEBUG("-->Success - C:16 - Subscribe, multiple topics, messages on each topic \n"); -} -/* C:17 - Subscribe, max topics, messages on each topic */ -TEST_C(SubscribeTests, SubscribeToMaxAllowedTopicsSuccess) { - IoT_Error_t rc = SUCCESS; - char expectedCallbackString[] = "topics sdk/Test1"; - char expectedCallbackString2[] = "topics sdk/Test2"; - char expectedCallbackString3[] = "topics sdk/Test3"; - char expectedCallbackString4[] = "topics sdk/Test4"; - char expectedCallbackString5[] = "topics sdk/Test5"; - - IOT_DEBUG("-->Running Subscribe Tests - C:17 - Subscribe, max topics, messages on each topic \n"); - - setTLSRxBufferForSuback("sdk/Test1", 9, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test1", 9, QOS1, iot_subscribe_callback_handler1, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - setTLSRxBufferForSuback("sdk/Test2", 9, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test2", 9, QOS1, iot_subscribe_callback_handler2, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - setTLSRxBufferForSuback("sdk/Test3", 9, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test3", 9, QOS1, iot_subscribe_callback_handler3, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - setTLSRxBufferForSuback("sdk/Test4", 9, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test4", 9, QOS1, iot_subscribe_callback_handler4, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - setTLSRxBufferForSuback("sdk/Test5", 9, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test5", 9, QOS1, iot_subscribe_callback_handler5, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test1", 9, QOS1, testPubMsgParams, expectedCallbackString); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test2", 9, QOS1, testPubMsgParams, expectedCallbackString2); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test3", 9, QOS1, testPubMsgParams, expectedCallbackString3); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test4", 9, QOS1, testPubMsgParams, expectedCallbackString4); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test5", 9, QOS1, testPubMsgParams, expectedCallbackString5); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString1); - CHECK_EQUAL_C_STRING(expectedCallbackString2, CallbackMsgString2); - CHECK_EQUAL_C_STRING(expectedCallbackString3, CallbackMsgString3); - CHECK_EQUAL_C_STRING(expectedCallbackString4, CallbackMsgString4); - CHECK_EQUAL_C_STRING(expectedCallbackString5, CallbackMsgString5); - - IOT_DEBUG("-->Success - C:17 - Subscribe, max topics, messages on each topic \n"); -} -/* C:18 - Subscribe, max topics, another subscribe */ -TEST_C(SubscribeTests, SubscribeToMaxPlusOneAllowedTopicsFailure) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Subscribe Tests - C:18 - Subscribe, max topics, another subscribe \n"); - - setTLSRxBufferForSuback("sdk/Test1", 9, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test1", 9, QOS1, iot_subscribe_callback_handler1, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - setTLSRxBufferForSuback("sdk/Test2", 9, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test2", 9, QOS1, iot_subscribe_callback_handler2, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - setTLSRxBufferForSuback("sdk/Test3", 9, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test3", 9, QOS1, iot_subscribe_callback_handler3, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - setTLSRxBufferForSuback("sdk/Test4", 9, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test4", 9, QOS1, iot_subscribe_callback_handler4, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - setTLSRxBufferForSuback("sdk/Test5", 9, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test5", 9, QOS1, iot_subscribe_callback_handler5, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - setTLSRxBufferForSuback("sdk/Test6", 9, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test6", 9, QOS1, iot_subscribe_callback_handler6, NULL); - CHECK_EQUAL_C_INT(MQTT_MAX_SUBSCRIPTIONS_REACHED_ERROR, rc); - - IOT_DEBUG("-->Success - C:18 - Subscribe, max topics, another subscribe \n"); -} - -/* C:19 - Subscribe, '#' not last character in topic name, Failure */ -TEST_C(SubscribeTests, subscribeTopicWithHashkeyAllSubTopicSuccess) { - IoT_Error_t rc = SUCCESS; - char expectedCallbackString[100] = "New message: sub/sub, Hashkey"; - - IOT_DEBUG("-->Running Subscribe Tests - C:19 - Subscribe, '#' not last character in topic name, Failure \n"); - - // Set up the subscribed topic, including '#' - setTLSRxBufferForSuback("sdk/Test/#", strlen("sdk/Test/#"), QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test/#", strlen("sdk/Test/#"), QOS1, - iot_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - // Now provide a published message from a sub topic - IOT_DEBUG("[Matching '#'] Checking first sub topic message, with '#' be the last..\n"); - setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test/sub/sub", strlen("sdk/Test/sub/sub"), QOS1, testPubMsgParams, - expectedCallbackString); - snprintf(CallbackMsgString, 100, "NOT_VISITED"); - - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); - CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePuback()); - - // Re-initialize Rx Tx Buffer - ResetTLSBuffer(); - - // Now provide another message from a different sub topic - IOT_DEBUG("[Matching '#'] Checking second sub topic message, with '#' be the last...\n"); - snprintf(expectedCallbackString, 100, "New message: sub2, Hashkey"); - setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test/sub2", strlen("sdk/Test/sub2"), QOS1, testPubMsgParams, - expectedCallbackString); - snprintf(CallbackMsgString, 100, "NOT_VISITED"); - - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); - CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePuback()); - - IOT_DEBUG("-->Success - C:19 - Subscribe, '#' not last character in topic name, Failure \n"); -} -/* C:20 - Subscribe with '#', subscribed to all subtopics */ -TEST_C(SubscribeTests, subscribeTopicHashkeyMustBeTheLastFail) { - IoT_Error_t rc = SUCCESS; - char expectedCallbackString[100] = "New message: foo1/sub, Hashkey"; - - IOT_DEBUG("-->Running Subscribe Tests - C:20 - Subscribe with '#', subscribed to all subtopics \n"); - - // Set up the subscribed topic, with '#' in the middle - // Topic directory not permitted, should fail - setTLSRxBufferForSuback("sdk/#/sub", strlen("sdk/#/sub"), QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/#/sub", strlen("sdk/#/sub"), QOS1, - iot_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ResetTLSBuffer(); - // Now provide a published message from a sub directoy with this sub topic - IOT_DEBUG("[Matching '#'] Checking sub topic message, with '#' in the middle...\n"); - setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test/foo1/sub", strlen("sdk/Test/foo1/sub"), QOS1, testPubMsgParams, - expectedCallbackString); - snprintf(CallbackMsgString, 100, "NOT_VISITED"); - - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING("NOT_VISITED", CallbackMsgString); - - IOT_DEBUG("-->Success - C:20 - Subscribe with '#', subscribed to all subtopics \n"); -} -/* C:21 - Subscribe with '+' as wildcard success */ -TEST_C(SubscribeTests, subscribeTopicWithPluskeySuccess) { - IoT_Error_t rc = SUCCESS; - char expectedCallbackString[100] = "New message: 1/sub, Pluskey"; - - IOT_DEBUG("-->Running Subscribe Tests - C:21 - Subscribe with '+' as wildcard success \n"); - - // Set up the subscribed topic, including '+' - setTLSRxBufferForSuback("sdk/Test/+/sub", strlen("sdk/Test/+/sub"), QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test/+/sub", strlen("sdk/Test/+/sub"), QOS1, - iot_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - // Now provide a published message from a sub topic - IOT_DEBUG("[Matching '+'] Checking first sub topic message, with '+' in the middle...\n"); - setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test/1/sub", strlen("sdk/Test/1/sub"), QOS1, testPubMsgParams, - expectedCallbackString); - snprintf(CallbackMsgString, 100, "NOT_VISITED"); - - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); - CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePuback()); - - // Re-initialize Rx Tx Buffer - ResetTLSBuffer(); - - // Now provide another message from a different sub topic - IOT_DEBUG("[Matching '+'] Checking second sub topic message, with '+' in the middle...\n"); - snprintf(expectedCallbackString, 100, "New message: 2/sub, Pluskey"); - setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test/2/sub", strlen("sdk/Test/2/sub"), QOS1, testPubMsgParams, - expectedCallbackString); - snprintf(CallbackMsgString, 100, "NOT_VISITED"); - - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); - CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePuback()); - - IOT_DEBUG("-->Success - C:21 - Subscribe with '+' as wildcard success \n"); -} -/* C:22 - Subscribe with '+' as last character in topic name, Success */ -TEST_C(SubscribeTests, subscribeTopicPluskeyComesLastSuccess) { - IoT_Error_t rc = SUCCESS; - char expectedCallbackString[100] = "New message: foo1, Pluskey"; - - IOT_DEBUG("-->Running Subscribe Tests - C:22 - Subscribe with '+' as last character in topic name, Success \n"); - - // Set up the subscribed topic, with '+' comes the last - setTLSRxBufferForSuback("sdk/Test/+", strlen("sdk/Test/+"), QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "sdk/Test/+", strlen("sdk/Test/+"), QOS1, - iot_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - // Now provide a published message from a single layer of sub directroy - IOT_DEBUG("[Matching '+'] Checking first sub topic message, with '+' be the last...\n"); - setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test/foo1", strlen("sdk/Test/foo1"), QOS1, testPubMsgParams, - expectedCallbackString); - snprintf(CallbackMsgString, 100, "NOT_VISITED"); - - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); - CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePuback()); - - // Re-initialize Rx Tx Buffer - ResetTLSBuffer(); - - // Now provide a published message from another single layer of sub directroy - IOT_DEBUG("[Matching '+'] Checking second sub topic message, with '+' be the last...\n"); - snprintf(expectedCallbackString, 100, "New message: foo2, Pluskey"); - setTLSRxBufferWithMsgOnSubscribedTopic("sdk/Test/foo2", strlen("sdk/Test/foo2"), QOS1, testPubMsgParams, - expectedCallbackString); - snprintf(CallbackMsgString, 100, "NOT_VISITED"); - - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); - CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePuback()); - - IOT_DEBUG("-->Success - C:22 - Subscribe with '+' as last character in topic name, Success \n"); -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_unsubscribe.cpp b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_unsubscribe.cpp deleted file mode 100644 index bedea1f38..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_unsubscribe.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_unsubscribe.cpp - * @brief IoT Client Unit Testing - Unsubscribe API Tests - */ - -#include -#include - -TEST_GROUP_C(UnsubscribeTests){ - TEST_GROUP_C_SETUP_WRAPPER(UnsubscribeTests) - TEST_GROUP_C_TEARDOWN_WRAPPER(UnsubscribeTests) -}; - -/* D:1 - Unsubscribe with Null/empty client instance */ -TEST_GROUP_C_WRAPPER(UnsubscribeTests, UnsubscribeNullClient) -/* D:2 - Unsubscribe with Null/empty topic name */ -TEST_GROUP_C_WRAPPER(UnsubscribeTests, UnsubscribeNullTopic) -/* D:3 - Unsubscribe, Not subscribed to topic */ -TEST_GROUP_C_WRAPPER(UnsubscribeTests, UnsubscribeNotSubscribed) - -/* D:4 - Unsubscribe, QoS0, No response, timeout */ -TEST_GROUP_C_WRAPPER(UnsubscribeTests, unsubscribeQoS0FailureOnNoUnsuback) -/* D:5 - Unsubscribe, QoS1, No response, timeout */ -TEST_GROUP_C_WRAPPER(UnsubscribeTests, unsubscribeQoS1FailureOnNoUnsuback) - -/* D:6 - Unsubscribe, QoS0, success */ -TEST_GROUP_C_WRAPPER(UnsubscribeTests, unsubscribeQoS0WithUnsubackSuccess) -/* D:7 - Unsubscribe, QoS0, half command timeout delayed unsuback, success */ -TEST_GROUP_C_WRAPPER(UnsubscribeTests, unsubscribeQoS0WithDelayedUnsubackSuccess) -/* D:8 - Unsubscribe, QoS1, success */ -TEST_GROUP_C_WRAPPER(UnsubscribeTests, unsubscribeQoS1WithUnsubackSuccess) -/* D:9 - Unsubscribe, QoS1, half command timeout delayed unsuback, success */ -TEST_GROUP_C_WRAPPER(UnsubscribeTests, unsubscribeQoS1WithDelayedUnsubackSuccess) - -/* D:10 - Unsubscribe, success, message on topic ignored */ -TEST_GROUP_C_WRAPPER(UnsubscribeTests, MsgAfterUnsubscribe) -/* D:11 - Unsubscribe after max topics reached */ -TEST_GROUP_C_WRAPPER(UnsubscribeTests, MaxTopicsSubscription) -/* D:12 - Repeated Subscribe and Unsubscribe */ -TEST_GROUP_C_WRAPPER(UnsubscribeTests, RepeatedSubUnSub) diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_unsubscribe_helper.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_unsubscribe_helper.c deleted file mode 100644 index a4d245378..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_unsubscribe_helper.c +++ /dev/null @@ -1,343 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_unsubscribe_helper.c - * @brief IoT Client Unit Testing - Unsubscribe API Tests Helper - */ - -#include -#include -#include - -#include "aws_iot_mqtt_client_interface.h" -#include "aws_iot_tests_unit_helper_functions.h" -#include "aws_iot_log.h" - -static IoT_Client_Init_Params initParams; -static IoT_Client_Connect_Params connectParams; -static IoT_Publish_Message_Params testPubMsgParams; -static char subTopic[10] = "sdk/Test"; -static uint16_t subTopicLen = 8; - -static AWS_IoT_Client iotClient; -static char CallbackMsgString[100]; -char cPayload[100]; - -static void iot_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, - IoT_Publish_Message_Params *params, void *pData) { - if(NULL == pClient || NULL == topicName || 0 == topicNameLen) { - return; - } - - IOT_UNUSED(pData); - - char *tmp = params->payload; - unsigned int i; - - for(i = 0; i < (params->payloadLen); i++) { - CallbackMsgString[i] = tmp[i]; - } -} - -TEST_GROUP_C_SETUP(UnsubscribeTests) { - IoT_Error_t rc = SUCCESS; - ResetTLSBuffer(); - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, NULL); - initParams.mqttCommandTimeout_ms = 2000; - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ConnectMQTTParamsSetup(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID)); - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - IOT_DEBUG("MQTT Status State : %d, RC : %d\n\n", aws_iot_mqtt_get_client_state(&iotClient), rc); - - testPubMsgParams.qos = QOS1; - testPubMsgParams.isRetained = 0; - snprintf(cPayload, 100, "%s : %d ", "hello from SDK", 0); - testPubMsgParams.payload = (void *) cPayload; - testPubMsgParams.payloadLen = strlen(cPayload); - - ResetTLSBuffer(); -} - -TEST_GROUP_C_TEARDOWN(UnsubscribeTests) { } - -/* D:1 - Unsubscribe with Null/empty client instance */ -TEST_C(UnsubscribeTests, UnsubscribeNullClient) { - IoT_Error_t rc = aws_iot_mqtt_unsubscribe(NULL, "sdkTest/Sub", 11); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -/* D:2 - Unsubscribe with Null/empty topic name */ -TEST_C(UnsubscribeTests, UnsubscribeNullTopic) { - IoT_Error_t rc = aws_iot_mqtt_unsubscribe(&iotClient, NULL, 11); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -/* D:3 - Unsubscribe, Not subscribed to topic */ -TEST_C(UnsubscribeTests, UnsubscribeNotSubscribed) { - IoT_Error_t rc = aws_iot_mqtt_unsubscribe(&iotClient, "sdkTest/Sub", 11); - CHECK_EQUAL_C_INT(FAILURE, rc); -} - -/* D:4 - Unsubscribe, QoS0, No response, timeout */ -TEST_C(UnsubscribeTests, unsubscribeQoS0FailureOnNoUnsuback) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Unsubscribe Tests - D:4 - Unsubscribe, QoS0, No response, timeout \n"); - - // First, subscribe to a topic - setTLSRxBufferForSuback(subTopic, subTopicLen, QOS0, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS0, iot_subscribe_callback_handler, - NULL); - if(SUCCESS == rc) { - // Then, unsubscribe - rc = aws_iot_mqtt_unsubscribe(&iotClient, subTopic, (uint16_t) strlen(subTopic)); - CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, rc); - } - - IOT_DEBUG("-->Success - D:4 - Unsubscribe, QoS0, No response, timeout \n"); -} - -/* D:5 - Unsubscribe, QoS1, No response, timeout */ -TEST_C(UnsubscribeTests, unsubscribeQoS1FailureOnNoUnsuback) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Unsubscribe Tests - D:5 - Unsubscribe, QoS1, No response, timeout \n"); - - // First, subscribe to a topic - setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS1, iot_subscribe_callback_handler, - NULL); - if(SUCCESS == rc) { - // Then, unsubscribe - rc = aws_iot_mqtt_unsubscribe(&iotClient, subTopic, (uint16_t) strlen(subTopic)); - CHECK_EQUAL_C_INT(MQTT_REQUEST_TIMEOUT_ERROR, rc); - } - - IOT_DEBUG("-->Success - D:5 - Unsubscribe, QoS1, No response, timeout \n"); -} - -/* D:6 - Unsubscribe, QoS0, success */ -TEST_C(UnsubscribeTests, unsubscribeQoS0WithUnsubackSuccess) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Unsubscribe Tests - D:6 - Unsubscribe, QoS0, success \n"); - - // First, subscribe to a topic - setTLSRxBufferForSuback(subTopic, subTopicLen, QOS0, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS0, iot_subscribe_callback_handler, - NULL); - if(SUCCESS == rc) { - // Then, unsubscribe - setTLSRxBufferForUnsuback(); - rc = aws_iot_mqtt_unsubscribe(&iotClient, subTopic, (uint16_t) strlen(subTopic)); - CHECK_EQUAL_C_INT(SUCCESS, rc); - } - - IOT_DEBUG("-->Success - D:6 - Unsubscribe, QoS0, success \n"); -} - -/* D:7 - Unsubscribe, QoS0, half command timeout delayed unsuback, success */ -TEST_C(UnsubscribeTests, unsubscribeQoS0WithDelayedUnsubackSuccess) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Unsubscribe Tests - D:7 - Unsubscribe, QoS0, half command timeout delayed unsuback, success \n"); - - // First, subscribe to a topic - setTLSRxBufferForSuback(subTopic, subTopicLen, QOS0, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS0, iot_subscribe_callback_handler, - NULL); - if(SUCCESS == rc) { - // Then, unsubscribe - setTLSRxBufferForUnsuback(); - setTLSRxBufferDelay(0, (int) iotClient.clientData.commandTimeoutMs/2); - rc = aws_iot_mqtt_unsubscribe(&iotClient, subTopic, (uint16_t) strlen(subTopic)); - CHECK_EQUAL_C_INT(SUCCESS, rc); - } - - IOT_DEBUG("-->Success - D:7 - Unsubscribe, QoS0, half command timeout delayed unsuback, success \n"); -} - -/* D:8 - Unsubscribe, QoS1, success */ -TEST_C(UnsubscribeTests, unsubscribeQoS1WithUnsubackSuccess) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Unsubscribe Tests - D:8 - Unsubscribe, QoS1, success \n"); - - // First, subscribe to a topic - setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS1, iot_subscribe_callback_handler, - NULL); - if(SUCCESS == rc) { - // Then, unsubscribe - setTLSRxBufferForUnsuback(); - rc = aws_iot_mqtt_unsubscribe(&iotClient, subTopic, (uint16_t) strlen(subTopic)); - CHECK_EQUAL_C_INT(SUCCESS, rc); - } - - IOT_DEBUG("-->Success - D:8 - Unsubscribe, QoS1, success \n"); -} - -/* D:9 - Unsubscribe, QoS1, half command timeout delayed unsuback, success */ -TEST_C(UnsubscribeTests, unsubscribeQoS1WithDelayedUnsubackSuccess) { - IoT_Error_t rc = SUCCESS; - - IOT_DEBUG("-->Running Unsubscribe Tests - D:9 - Unsubscribe, QoS1, half command timeout delayed unsuback, success \n"); - - // First, subscribe to a topic - setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS1, iot_subscribe_callback_handler, - NULL); - if(SUCCESS == rc) { - // Then, unsubscribe - setTLSRxBufferForUnsuback(); - setTLSRxBufferDelay(0, (int) iotClient.clientData.commandTimeoutMs/2); - rc = aws_iot_mqtt_unsubscribe(&iotClient, subTopic, (uint16_t) strlen(subTopic)); - CHECK_EQUAL_C_INT(SUCCESS, rc); - } - - IOT_DEBUG("-->Success - D:9 - Unsubscribe, QoS1, half command timeout delayed unsuback, success \n"); -} - -/* D:10 - Unsubscribe, success, message on topic ignored - * 1. Subscribe to topic 1 - * 2. Send message and receive it - * 3. Unsubscribe to topic 1 - * 4. Should not receive message - */ -TEST_C(UnsubscribeTests, MsgAfterUnsubscribe) { - IoT_Error_t rc = SUCCESS; - char expectedCallbackString[100]; - - IOT_DEBUG("-->Running Unsubscribe Tests - D:10 - Unsubscribe, success, message on topic ignored \n"); - - // 1. - setTLSRxBufferForSuback("topic1", 6, QOS0, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, "topic1", 6, QOS0, iot_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - // 2. - snprintf(expectedCallbackString, 100, "Message for topic1"); - setTLSRxBufferWithMsgOnSubscribedTopic("topic1", 6, QOS1, testPubMsgParams, expectedCallbackString); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); - - //3. - setTLSRxBufferForUnsuback(); - rc = aws_iot_mqtt_unsubscribe(&iotClient, "topic1", 6); - CHECK_EQUAL_C_INT(SUCCESS, rc); - //reset the string - snprintf(CallbackMsgString, 100, " "); - - // 4. - // Have a new message published to that topic coming in - snprintf(expectedCallbackString, 100, "Message after unsubscribe"); - setTLSRxBufferWithMsgOnSubscribedTopic("topic1", 6, QOS0, testPubMsgParams, expectedCallbackString); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - // No new msg was received - CHECK_EQUAL_C_STRING(" ", CallbackMsgString); - - IOT_DEBUG("-->Success - D:10 - Unsubscribe, success, message on topic ignored \n"); -} - -/* D:11 - Unsubscribe after max topics reached - * 1. Subscribe to max topics + 1 fail for last subscription - * 2. Unsubscribe from one topic - * 3. Subscribe again and should have no error - * 4. Receive msg test - last subscribed topic - */ -TEST_C(UnsubscribeTests, MaxTopicsSubscription) { - IoT_Error_t rc = SUCCESS; - int i = 0; - char topics[AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS + 1][10]; - char expectedCallbackString[] = "Message after subscribe - topic[i]"; - - IOT_DEBUG("-->Running Unsubscribe Tests - D:11 - Unsubscribe after max topics reached \n"); - - // 1. - for(i = 0; i < AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; i++) { - snprintf(topics[i], 10, "topic-%d", i); - setTLSRxBufferForSuback(topics[i], strlen(topics[i]), QOS0, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, topics[i], (uint16_t) strlen(topics[i]), QOS0, iot_subscribe_callback_handler, - NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - } - snprintf(topics[i], 10, "topic-%d", i); - setTLSRxBufferForSuback(topics[i], strlen(topics[i]), QOS0, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, topics[i], (uint16_t) strlen(topics[i]), QOS0, iot_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(MQTT_MAX_SUBSCRIPTIONS_REACHED_ERROR, rc); - - // 2. - setTLSRxBufferForUnsuback(); - rc = aws_iot_mqtt_unsubscribe(&iotClient, topics[i - 1], (uint16_t) strlen(topics[i - 1])); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - //3. - setTLSRxBufferForSuback(topics[i], strlen(topics[i]), QOS0, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, topics[i], (uint16_t) strlen(topics[i]), QOS0, iot_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - //4. - setTLSRxBufferWithMsgOnSubscribedTopic(topics[i], strlen(topics[i]), QOS1, testPubMsgParams, - expectedCallbackString); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); - - IOT_DEBUG("-->Success - D:11 - Unsubscribe after max topics reached \n"); -} - -/* D:12 - Repeated Subscribe and Unsubscribe - * 1. subscribe and unsubscribe for more than the max subscribed topic - * 2. ensure every time the subscribed topic msg is received - */ -TEST_C(UnsubscribeTests, RepeatedSubUnSub) { - IoT_Error_t rc = SUCCESS; - int i = 0; - char expectedCallbackString[100]; - char topics[3 * AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS][10]; - - IOT_DEBUG("-->Running Unsubscribe Tests - D:12 - Repeated Subscribe and Unsubscribe \n"); - - - for(i = 0; i < 3 * AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS; i++) { - //1. - snprintf(topics[i], 10, "topic-%d", i); - setTLSRxBufferForSuback(topics[i], 10, QOS0, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, topics[i], 10, QOS0, iot_subscribe_callback_handler, NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - snprintf(expectedCallbackString, 10, "message##%d", i); - testPubMsgParams.payload = (void *) expectedCallbackString; - testPubMsgParams.payloadLen = strlen(expectedCallbackString); - setTLSRxBufferWithMsgOnSubscribedTopic(topics[i], strlen(topics[i]), QOS1, testPubMsgParams, - expectedCallbackString); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); - - //2. - setTLSRxBufferForUnsuback(); - rc = aws_iot_mqtt_unsubscribe(&iotClient, topics[i], (uint16_t) strlen(topics[i])); - CHECK_EQUAL_C_INT(SUCCESS, rc); - } - - IOT_DEBUG("-->Success - D:12 - Repeated Subscribe and Unsubscribe \n"); -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_yield.cpp b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_yield.cpp deleted file mode 100644 index afca69c5c..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_yield.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_yield.cpp - * @brief IoT Client Unit Testing - Yield API Tests - */ - -#include -#include - -TEST_GROUP_C(YieldTests){ - TEST_GROUP_C_SETUP_WRAPPER(YieldTests) - TEST_GROUP_C_TEARDOWN_WRAPPER(YieldTests) -}; - -/* G:1 - Yield with Null/empty Client Instance */ -TEST_GROUP_C_WRAPPER(YieldTests, NullClientYield) -/* G:2 - Yield with zero yield timeout */ -TEST_GROUP_C_WRAPPER(YieldTests, ZeroTimeoutYield) -/* G:3 - Yield, network disconnected, never connected */ -TEST_GROUP_C_WRAPPER(YieldTests, YieldNetworkDisconnectedNeverConnected) -/* G:4 - Yield, network disconnected, disconnected manually */ -TEST_GROUP_C_WRAPPER(YieldTests, YieldNetworkDisconnectedDisconnectedManually) -/* G:5 - Yield, network connected, yield called while in subscribe application callback */ -TEST_GROUP_C_WRAPPER(YieldTests, YieldInSubscribeCallback) -/* G:6 - Yield, network disconnected, ping timeout, auto-reconnect disabled */ -TEST_GROUP_C_WRAPPER(YieldTests, disconnectNoAutoReconnect) - -/* G:7 - Yield, network connected, no incoming messages */ -TEST_GROUP_C_WRAPPER(YieldTests, YieldSuccessNoMessages) -/* G:8 - Yield, network connected, ping request/response */ -TEST_GROUP_C_WRAPPER(YieldTests, PingRequestPingResponse) - -/* G:9 - Yield, disconnected, Auto-reconnect timed-out */ -TEST_GROUP_C_WRAPPER(YieldTests, disconnectAutoReconnectTimeout) -/* G:10 - Yield, disconnected, Auto-reconnect successful */ -TEST_GROUP_C_WRAPPER(YieldTests, disconnectAutoReconnectSuccess) -/* G:11 - Yield, disconnected, Manual reconnect */ -TEST_GROUP_C_WRAPPER(YieldTests, disconnectManualAutoReconnect) -/* G:12 - Yield, resubscribe to all topics on reconnect */ -TEST_GROUP_C_WRAPPER(YieldTests, resubscribeSuccessfulReconnect) - -/* G:13 - Delayed Ping response. */ -TEST_GROUP_C_WRAPPER(YieldTests, delayedPingResponse) diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_yield_helper.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_yield_helper.c deleted file mode 100644 index bc4aa0523..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/src/aws_iot_tests_unit_yield_helper.c +++ /dev/null @@ -1,493 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_yield_helper.c - * @brief IoT Client Unit Testing - Yield API Tests Helper - */ - -#include -#include -#include - -#include "aws_iot_tests_unit_helper_functions.h" -#include "aws_iot_tests_unit_mock_tls_params.h" -#include "aws_iot_log.h" - -static IoT_Client_Init_Params initParams; -static IoT_Client_Connect_Params connectParams; -static AWS_IoT_Client iotClient; -static IoT_Publish_Message_Params testPubMsgParams; - -static ConnectBufferProofread prfrdParams; -static char CallbackMsgString[100]; -static char subTopic[10] = "sdk/Test"; -static uint16_t subTopicLen = 8; - -static bool dcHandlerInvoked = false; - -static void iot_tests_unit_acr_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, - uint16_t topicNameLen, - IoT_Publish_Message_Params *params, void *pData) { - char *tmp = params->payload; - unsigned int i; - - IOT_UNUSED(pClient); - IOT_UNUSED(topicName); - IOT_UNUSED(topicNameLen); - IOT_UNUSED(pData); - - for(i = 0; i < params->payloadLen; i++) { - CallbackMsgString[i] = tmp[i]; - } -} - -static void iot_tests_unit_yield_test_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, - uint16_t topicNameLen, - IoT_Publish_Message_Params *params, void *pData) { - char *tmp = params->payload; - unsigned int i; - IoT_Error_t rc = SUCCESS; - - IOT_UNUSED(pClient); - IOT_UNUSED(topicName); - IOT_UNUSED(topicNameLen); - IOT_UNUSED(pData); - - rc = aws_iot_mqtt_yield(pClient, 1000); - CHECK_EQUAL_C_INT(MQTT_CLIENT_NOT_IDLE_ERROR, rc); - - for(i = 0; i < params->payloadLen; i++) { - CallbackMsgString[i] = tmp[i]; - } -} - -void iot_tests_unit_disconnect_handler(AWS_IoT_Client *pClient, void *disconParam) { - IOT_UNUSED(pClient); - IOT_UNUSED(disconParam); - dcHandlerInvoked = true; -} - - -TEST_GROUP_C_SETUP(YieldTests) { - IoT_Error_t rc = SUCCESS; - dcHandlerInvoked = false; - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, iot_tests_unit_disconnect_handler); - rc = aws_iot_mqtt_init(&iotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - - ConnectMQTTParamsSetup_Detailed(&connectParams, AWS_IOT_MQTT_CLIENT_ID, (uint16_t) strlen(AWS_IOT_MQTT_CLIENT_ID), - QOS1, false, true, "willTopicName", (uint16_t) strlen("willTopicName"), "willMsg", - (uint16_t) strlen("willMsg"), NULL, 0, NULL, 0); - connectParams.keepAliveIntervalInSec = 5; - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_connect(&iotClient, &connectParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - rc = aws_iot_mqtt_autoreconnect_set_status(&iotClient, false); - CHECK_EQUAL_C_INT(SUCCESS, rc); - ResetTLSBuffer(); -} - -TEST_GROUP_C_TEARDOWN(YieldTests) { - /* Clean up. Not checking return code here because this is common to all tests. - * A test might have already caused a disconnect by this point. - */ - IoT_Error_t rc = aws_iot_mqtt_disconnect(&iotClient); - IOT_UNUSED(rc); -} - -/* G:1 - Yield with Null/empty Client Instance */ -TEST_C(YieldTests, NullClientYield) { - IoT_Error_t rc = aws_iot_mqtt_yield(NULL, 1000); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} - -/* G:2 - Yield with zero yield timeout */ - -TEST_C(YieldTests, ZeroTimeoutYield) { - IoT_Error_t rc = aws_iot_mqtt_yield(&iotClient, 0); - CHECK_EQUAL_C_INT(NULL_VALUE_ERROR, rc); -} -/* G:3 - Yield, network disconnected, never connected */ - -TEST_C(YieldTests, YieldNetworkDisconnectedNeverConnected) { - AWS_IoT_Client tempIotClient; - IoT_Error_t rc; - - InitMQTTParamsSetup(&initParams, AWS_IOT_MQTT_HOST, AWS_IOT_MQTT_PORT, false, iot_tests_unit_disconnect_handler); - rc = aws_iot_mqtt_init(&tempIotClient, &initParams); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - rc = aws_iot_mqtt_yield(&tempIotClient, 1000); - CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc); -} - -/* G:4 - Yield, network disconnected, disconnected manually */ -TEST_C(YieldTests, YieldNetworkDisconnectedDisconnectedManually) { - IoT_Error_t rc = aws_iot_mqtt_disconnect(&iotClient); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - rc = aws_iot_mqtt_yield(&iotClient, 1000); - CHECK_EQUAL_C_INT(NETWORK_MANUALLY_DISCONNECTED, rc); -} - -/* G:5 - Yield, network connected, yield called while in subscribe application callback */ -TEST_C(YieldTests, YieldInSubscribeCallback) { - IoT_Error_t rc = SUCCESS; - char expectedCallbackString[] = "0xA5A5A3"; - - IOT_DEBUG("-->Running Yield Tests - G:5 - Yield, network connected, yield called while in subscribe application callback \n"); - - setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS1, - iot_tests_unit_yield_test_subscribe_callback_handler, NULL); - if(SUCCESS == rc) { - setTLSRxBufferWithMsgOnSubscribedTopic(subTopic, subTopicLen, QOS1, testPubMsgParams, expectedCallbackString); - rc = aws_iot_mqtt_yield(&iotClient, 1000); - if(SUCCESS == rc) { - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); - } - CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePuback()); - } - - IOT_DEBUG("-->Success - G:5 - Yield, network connected, yield called while in subscribe application callback \n"); -} - -/* G:6 - Yield, network disconnected, ping timeout, auto-reconnect disabled */ -TEST_C(YieldTests, disconnectNoAutoReconnect) { - IoT_Error_t rc = FAILURE; - - IOT_DEBUG("-->Running Yield Tests - G:6 - Yield, network disconnected, ping timeout, auto-reconnect disabled \n"); - - rc = aws_iot_mqtt_autoreconnect_set_status(&iotClient, true); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - CHECK_EQUAL_C_INT(true, aws_iot_mqtt_is_client_connected(&iotClient)); - CHECK_EQUAL_C_INT(true, aws_iot_is_autoreconnect_enabled(&iotClient)); - - /* Disable Autoreconnect, then let ping request time out and call yield */ - aws_iot_mqtt_autoreconnect_set_status(&iotClient, false); - sleep((uint16_t)(iotClient.clientData.keepAliveInterval)); - - ResetTLSBuffer(); - - /* Sleep for keep alive interval to allow the first ping to be sent out */ - sleep(iotClient.clientData.keepAliveInterval); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(true, isLastTLSTxMessagePingreq()); - - /* Let ping request time out and call yield */ - sleep(iotClient.clientData.keepAliveInterval + 1); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc); - CHECK_EQUAL_C_INT(1, isLastTLSTxMessageDisconnect()); - CHECK_EQUAL_C_INT(0, aws_iot_mqtt_is_client_connected(&iotClient)); - CHECK_EQUAL_C_INT(true, dcHandlerInvoked); - - IOT_DEBUG("-->Success - G:6 - Yield, network disconnected, ping timeout, auto-reconnect disabled \n"); -} - -/* G:7 - Yield, network connected, no incoming messages */ -TEST_C(YieldTests, YieldSuccessNoMessages) { - IoT_Error_t rc; - int i; - - IOT_DEBUG("-->Running Yield Tests - G:7 - Yield, network connected, no incoming messages \n"); - - for(i = 0; i < 100; i++) { - CallbackMsgString[i] = 'x'; - } - - rc = aws_iot_mqtt_yield(&iotClient, 1000); - if(SUCCESS == rc) { - /* Check no messages were received */ - for(i = 0; i < 100; i++) { - if('x' != CallbackMsgString[i]) { - rc = FAILURE; - } - } - } - - CHECK_EQUAL_C_INT(SUCCESS, rc); - - IOT_DEBUG("-->Success - G:7 - Yield, network connected, no incoming messages \n"); -} - -/* G:8 - Yield, network connected, ping request/response */ -TEST_C(YieldTests, PingRequestPingResponse) { - IoT_Error_t rc = SUCCESS; - int i = 0; - int j = 0; - int attempt = 3; - - IOT_DEBUG("-->Running Yield Tests - G:8 - Yield, network connected, ping request/response \n"); - IOT_DEBUG("Current Keep Alive Interval is set to %d sec.\n", iotClient.clientData.keepAliveInterval); - - for(i = 0; i < attempt; i++) { - IOT_DEBUG("[Round_%d/Total_%d] Waiting for %d sec...\n", i + 1, attempt, iotClient.clientData.keepAliveInterval); - /* Set TLS buffer for ping response */ - ResetTLSBuffer(); - setTLSRxBufferForPingresp(); - - for(j = 0; j <= iotClient.clientData.keepAliveInterval; j++) { - sleep(1); - IOT_DEBUG("[Waited %d secs]", j + 1); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - } - - /* Check whether ping was processed correctly and new Ping request was generated */ - CHECK_EQUAL_C_INT(1, isLastTLSTxMessagePingreq()); - } - - IOT_DEBUG("-->Success - G:8 - Yield, network connected, ping request/response \n"); -} - -/* G:9 - Yield, disconnected, Auto-reconnect timed-out */ -TEST_C(YieldTests, disconnectAutoReconnectTimeout) { - IoT_Error_t rc = FAILURE; - - IOT_DEBUG("-->Running Yield Tests - G:9 - Yield, disconnected, Auto-reconnect timed-out \n"); - - rc = aws_iot_mqtt_autoreconnect_set_status(&iotClient, true); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - CHECK_EQUAL_C_INT(true, aws_iot_mqtt_is_client_connected(&iotClient)); - CHECK_EQUAL_C_INT(true, aws_iot_is_autoreconnect_enabled(&iotClient)); - - ResetTLSBuffer(); - - /* Sleep for keep alive interval to allow the first ping to be sent out */ - sleep(iotClient.clientData.keepAliveInterval); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(true, isLastTLSTxMessagePingreq()); - - /* Let ping request time out and call yield */ - sleep(iotClient.clientData.keepAliveInterval + 1); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(NETWORK_ATTEMPTING_RECONNECT, rc); - CHECK_EQUAL_C_INT(0, aws_iot_mqtt_is_client_connected(&iotClient)); - CHECK_EQUAL_C_INT(true, dcHandlerInvoked); - - IOT_DEBUG("-->Success - G:9 - Yield, disconnected, Auto-reconnect timed-out \n"); -} - -/* G:10 - Yield, disconnected, Auto-reconnect successful */ -TEST_C(YieldTests, disconnectAutoReconnectSuccess) { - IoT_Error_t rc = FAILURE; - unsigned char *currPayload = NULL; - - IOT_DEBUG("-->Running Yield Tests - G:10 - Yield, disconnected, Auto-reconnect successful \n"); - - rc = aws_iot_mqtt_autoreconnect_set_status(&iotClient, true); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - CHECK_EQUAL_C_INT(true, aws_iot_mqtt_is_client_connected(&iotClient)); - CHECK_EQUAL_C_INT(true, aws_iot_is_autoreconnect_enabled(&iotClient)); - - /* Sleep for keep alive interval to allow the first ping to be sent out */ - sleep(iotClient.clientData.keepAliveInterval); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(true, isLastTLSTxMessagePingreq()); - - /* Let ping request time out and call yield */ - sleep(iotClient.clientData.keepAliveInterval + 1); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(NETWORK_ATTEMPTING_RECONNECT, rc); - - sleep(2); /* Default min reconnect delay is 1 sec */ - printf("\nWakeup"); - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - currPayload = connectTxBufferHeaderParser(&prfrdParams, TxBuffer.pBuffer); - CHECK_C(true == isConnectTxBufFlagCorrect(&connectParams, &prfrdParams)); - CHECK_C(true == isConnectTxBufPayloadCorrect(&connectParams, currPayload)); - CHECK_EQUAL_C_INT(true, aws_iot_mqtt_is_client_connected(&iotClient)); - CHECK_EQUAL_C_INT(true, dcHandlerInvoked); - - IOT_DEBUG("-->Success - G:10 - Yield, disconnected, Auto-reconnect successful \n"); -} - -/* G:11 - Yield, disconnected, Manual reconnect */ -TEST_C(YieldTests, disconnectManualAutoReconnect) { - IoT_Error_t rc = FAILURE; - unsigned char *currPayload = NULL; - - IOT_DEBUG("-->Running Yield Tests - G:11 - Yield, disconnected, Manual reconnect \n"); - - CHECK_C(aws_iot_mqtt_is_client_connected(&iotClient)); - - /* Disable Autoreconnect, then let ping request time out and call yield */ - aws_iot_mqtt_autoreconnect_set_status(&iotClient, false); - CHECK_C(!aws_iot_is_autoreconnect_enabled(&iotClient)); - - /* Sleep for keep alive interval to allow the first ping to be sent out */ - sleep(iotClient.clientData.keepAliveInterval); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(true, isLastTLSTxMessagePingreq()); - - /* Let ping request time out and call yield */ - sleep(iotClient.clientData.keepAliveInterval + 1); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(NETWORK_DISCONNECTED_ERROR, rc); - CHECK_EQUAL_C_INT(1, isLastTLSTxMessageDisconnect()); - CHECK_C(!aws_iot_mqtt_is_client_connected(&iotClient)); - CHECK_EQUAL_C_INT(true, dcHandlerInvoked); - - dcHandlerInvoked = false; - setTLSRxBufferForConnack(&connectParams, 0, 0); - rc = aws_iot_mqtt_attempt_reconnect(&iotClient); - CHECK_EQUAL_C_INT(NETWORK_RECONNECTED, rc); - - currPayload = connectTxBufferHeaderParser(&prfrdParams, TxBuffer.pBuffer); - CHECK_C(true == isConnectTxBufFlagCorrect(&connectParams, &prfrdParams)); - CHECK_C(true == isConnectTxBufPayloadCorrect(&connectParams, currPayload)); - CHECK_C(aws_iot_mqtt_is_client_connected(&iotClient)); - CHECK_EQUAL_C_INT(false, dcHandlerInvoked); - - IOT_DEBUG("-->Success - G:11 - Yield, disconnected, Manual reconnect \n"); -} - -/* G:12 - Yield, resubscribe to all topics on reconnect */ -TEST_C(YieldTests, resubscribeSuccessfulReconnect) { - IoT_Error_t rc = FAILURE; - char cPayload[100]; - bool connected = false; - bool autoReconnectEnabled = false; - char expectedCallbackString[100]; - - IOT_DEBUG("-->Running Yield Tests - G:12 - Yield, resubscribe to all topics on reconnect \n"); - - rc = aws_iot_mqtt_autoreconnect_set_status(&iotClient, true); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - snprintf(CallbackMsgString, 100, "NOT_VISITED"); - - testPubMsgParams.qos = QOS1; - testPubMsgParams.isRetained = 0; - snprintf(cPayload, 100, "%s : %d ", "hello from SDK", 0); - testPubMsgParams.payload = (void *) cPayload; - testPubMsgParams.payloadLen = strlen(cPayload); - - connected = aws_iot_mqtt_is_client_connected(&iotClient); - CHECK_EQUAL_C_INT(1, connected); - - ResetTLSBuffer(); - - /* Subscribe to a topic */ - setTLSRxBufferForSuback(subTopic, subTopicLen, QOS1, testPubMsgParams); - rc = aws_iot_mqtt_subscribe(&iotClient, subTopic, subTopicLen, QOS0, iot_tests_unit_acr_subscribe_callback_handler, - NULL); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - ResetTLSBuffer(); - - /* Check subscribe */ - snprintf(expectedCallbackString, 100, "Message for %s", subTopic); - setTLSRxBufferWithMsgOnSubscribedTopic(subTopic, subTopicLen, QOS1, testPubMsgParams, expectedCallbackString); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); - - ResetTLSBuffer(); - - autoReconnectEnabled = aws_iot_is_autoreconnect_enabled(&iotClient); - CHECK_EQUAL_C_INT(1, autoReconnectEnabled); - - /* Sleep for keep alive interval to allow the first ping to be sent out */ - sleep(iotClient.clientData.keepAliveInterval); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(true, isLastTLSTxMessagePingreq()); - - /* Let ping request time out and call yield */ - sleep(iotClient.clientData.keepAliveInterval + 1); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(NETWORK_ATTEMPTING_RECONNECT, rc); - - sleep(2); /* Default min reconnect delay is 1 sec */ - - ResetTLSBuffer(); - setTLSRxBufferForConnackAndSuback(&connectParams, 0, subTopic, subTopicLen, QOS1); - - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - /* Test if reconnect worked */ - connected = aws_iot_mqtt_is_client_connected(&iotClient); - CHECK_EQUAL_C_INT(true, connected); - - ResetTLSBuffer(); - - /* Check subscribe */ - snprintf(expectedCallbackString, 100, "Message for %s after resub", subTopic); - setTLSRxBufferWithMsgOnSubscribedTopic(subTopic, subTopicLen, QOS1, testPubMsgParams, expectedCallbackString); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_STRING(expectedCallbackString, CallbackMsgString); - CHECK_EQUAL_C_INT(true, dcHandlerInvoked); - - IOT_DEBUG("-->Success - G:12 - Yield, resubscribe to all topics on reconnect \n"); -} - -/* G:13 - Delayed Ping response. */ -TEST_C(YieldTests, delayedPingResponse) -{ - IoT_Error_t rc = FAILURE; - - IOT_DEBUG("-->Running Yield Tests - G:13 - Delayed Ping response. \n"); - - ResetTLSBuffer(); - - /* Sleep for keep alive interval to allow the first ping to be sent out. */ - sleep(iotClient.clientData.keepAliveInterval); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(true, isLastTLSTxMessagePingreq()); - - /* Sleep for half of the keep alive interval to simulate a delayed ping - * response. */ - sleep(iotClient.clientData.keepAliveInterval / 2); - - /* Receive the delayed ping response. */ - ResetTLSBuffer(); - setTLSRxBufferForPingresp(); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - - /* Sleep for half of the keep alive interval - at this time a ping request - * must be sent out because a full keep alive interval has passed since we - * last sent a ping request. This ensures that the timer which tracks when - * to send a ping request does not incorrectly get reset upon receipt of a - * ping response. +1 is done to ensure that we don't hit boundry condition - * where timer does not expire because the time elasped is exactly equal to - * the keep alive interval (as opposed to more than that). */ - sleep(iotClient.clientData.keepAliveInterval / 2 + 1); - ResetTLSBuffer(); - rc = aws_iot_mqtt_yield(&iotClient, 100); - CHECK_EQUAL_C_INT(SUCCESS, rc); - CHECK_EQUAL_C_INT(true, isLastTLSTxMessagePingreq()); - - IOT_DEBUG("-->Success - G:13 - Delayed Ping response. \n"); -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/aws_iot_tests_unit_mock_tls.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/aws_iot_tests_unit_mock_tls.c deleted file mode 100644 index 720202a5f..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/aws_iot_tests_unit_mock_tls.c +++ /dev/null @@ -1,223 +0,0 @@ -#include -#include -#include - -#include "network_interface.h" -#include "aws_iot_tests_unit_mock_tls_params.h" - - -void _iot_tls_set_connect_params(Network *pNetwork, char *pRootCALocation, char *pDeviceCertLocation, - char *pDevicePrivateKeyLocation, char *pDestinationURL, - uint16_t destinationPort, uint32_t timeout_ms, bool ServerVerificationFlag) { - pNetwork->tlsConnectParams.DestinationPort = destinationPort; - pNetwork->tlsConnectParams.pDestinationURL = pDestinationURL; - pNetwork->tlsConnectParams.pDeviceCertLocation = pDeviceCertLocation; - pNetwork->tlsConnectParams.pDevicePrivateKeyLocation = pDevicePrivateKeyLocation; - pNetwork->tlsConnectParams.pRootCALocation = pRootCALocation; - pNetwork->tlsConnectParams.timeout_ms = timeout_ms; - pNetwork->tlsConnectParams.ServerVerificationFlag = ServerVerificationFlag; -} - -IoT_Error_t iot_tls_init(Network *pNetwork, char *pRootCALocation, char *pDeviceCertLocation, - char *pDevicePrivateKeyLocation, char *pDestinationURL, - uint16_t destinationPort, uint32_t timeout_ms, bool ServerVerificationFlag) { - _iot_tls_set_connect_params(pNetwork, pRootCALocation, pDeviceCertLocation, pDevicePrivateKeyLocation, - pDestinationURL, destinationPort, timeout_ms, ServerVerificationFlag); - - pNetwork->connect = iot_tls_connect; - pNetwork->read = iot_tls_read; - pNetwork->write = iot_tls_write; - pNetwork->disconnect = iot_tls_disconnect; - pNetwork->isConnected = iot_tls_is_connected; - pNetwork->destroy = iot_tls_destroy; - - return SUCCESS; -} - -IoT_Error_t iot_tls_connect(Network *pNetwork, TLSConnectParams *params) { - IOT_UNUSED(pNetwork); - - if(NULL != params) { - _iot_tls_set_connect_params(pNetwork, params->pRootCALocation, params->pDeviceCertLocation, - params->pDevicePrivateKeyLocation, params->pDestinationURL, params->DestinationPort, - params->timeout_ms, params->ServerVerificationFlag); - } - - if(NULL != invalidEndpointFilter && 0 == strcmp(invalidEndpointFilter, pNetwork->tlsConnectParams.pDestinationURL)) { - return NETWORK_ERR_NET_UNKNOWN_HOST; - } - - if(invalidPortFilter == pNetwork->tlsConnectParams.DestinationPort) { - return NETWORK_ERR_NET_CONNECT_FAILED; - } - - if(NULL != invalidRootCAPathFilter && 0 == strcmp(invalidRootCAPathFilter, pNetwork->tlsConnectParams.pRootCALocation)) { - return NETWORK_ERR_NET_CONNECT_FAILED; - } - - if(NULL != invalidCertPathFilter && 0 == strcmp(invalidCertPathFilter, pNetwork->tlsConnectParams.pDeviceCertLocation)) { - return NETWORK_ERR_NET_CONNECT_FAILED; - } - - if(NULL != invalidPrivKeyPathFilter && 0 == strcmp(invalidPrivKeyPathFilter, pNetwork->tlsConnectParams.pDevicePrivateKeyLocation)) { - return NETWORK_ERR_NET_CONNECT_FAILED; - } - return SUCCESS; -} - -IoT_Error_t iot_tls_is_connected(Network *pNetwork) { - IOT_UNUSED(pNetwork); - - /* Use this to add implementation which can check for physical layer disconnect */ - return NETWORK_PHYSICAL_LAYER_CONNECTED; -} - -static size_t iot_tls_mqtt_read_variable_length_int(const unsigned char *buffer, size_t startPos) { - size_t result = 0; - size_t pos = startPos; - size_t multiplier = 1; - do { - result = (buffer[pos] & 0x7f) * multiplier; - multiplier *= 0x80; - pos++; - } while ((buffer[pos - 1] & 0x80) && pos - startPos < 4); - - return result; -} - -static size_t iot_tls_mqtt_get_end_of_variable_length_int(const unsigned char *buffer, size_t startPos) { - size_t pos = startPos; - while ((buffer[pos] & 0x80) && pos - startPos < 3) pos++; - pos++; - - return pos; -} - -static uint16_t iot_tls_mqtt_get_fixed_uint16_from_message(const unsigned char *msgBuffer, size_t startPos) { - uint8_t firstByte = (uint8_t)(msgBuffer[startPos]); - uint8_t secondByte = (uint8_t)(msgBuffer[startPos + 1]); - return (uint16_t) (secondByte + (256 * firstByte)); -} - -static uint16_t iot_tls_mqtt_copy_string_from_message(char *dest, const unsigned char *msgBuffer, size_t startPos) { - uint16_t length = iot_tls_mqtt_get_fixed_uint16_from_message(msgBuffer, startPos); - - snprintf(dest, length + 1u, "%s", &(msgBuffer[startPos + 2])); // Added one for null character - return length; -} - -IoT_Error_t iot_tls_write(Network *pNetwork, unsigned char *pMsg, size_t len, Timer *timer, size_t *written_len) { - size_t i = 0; - uint8_t firstPacketByte; - size_t mqttPacketLength; - size_t variableHeaderStart; - IoT_Error_t status = SUCCESS; - IOT_UNUSED(pNetwork); - IOT_UNUSED(timer); - - if(TxBuffer.mockedError != SUCCESS ) { - status = TxBuffer.mockedError; - - /* Clear the error before returning. */ - TxBuffer.mockedError = SUCCESS; - - return status; - } - - for(i = 0; (i < len) && left_ms(timer) > 0; i++) { - TxBuffer.pBuffer[i] = pMsg[i]; - } - TxBuffer.len = len; - *written_len = len; - - mqttPacketLength = iot_tls_mqtt_read_variable_length_int(TxBuffer.pBuffer, 1); - variableHeaderStart = iot_tls_mqtt_get_end_of_variable_length_int(TxBuffer.pBuffer, 1); - - firstPacketByte = TxBuffer.pBuffer[0]; - /* Save last two subscribed topics */ - if((firstPacketByte == 0x82 ? true : false)) { - snprintf(SecondLastSubscribeMessage, lastSubscribeMsgLen + 1u, "%s", LastSubscribeMessage); - secondLastSubscribeMsgLen = lastSubscribeMsgLen; - - lastSubscribeMsgLen = iot_tls_mqtt_copy_string_from_message( - LastSubscribeMessage, TxBuffer.pBuffer, variableHeaderStart + 2); - } else if (firstPacketByte == 0xA2) { - lastUnsubscribeMsgLen = iot_tls_mqtt_copy_string_from_message( - LastUnsubscribeMessage, TxBuffer.pBuffer, variableHeaderStart + 2); - } else if ((firstPacketByte & 0x30) == 0x30) { - QoS qos = (QoS) (firstPacketByte & 0x6 >> 1); - - lastPublishMessageTopicLen = - iot_tls_mqtt_copy_string_from_message(LastPublishMessageTopic, TxBuffer.pBuffer, variableHeaderStart); - - size_t payloadStart = variableHeaderStart + 2 + lastPublishMessageTopicLen; - - if (qos > QOS0) { - payloadStart += 2; - } - - lastPublishMessagePayloadLen = mqttPacketLength - payloadStart + 2; /* + 2 as the first two bytes don't count towards the length */ - memcpy(LastPublishMessagePayload, TxBuffer.pBuffer + payloadStart, lastPublishMessagePayloadLen); - LastPublishMessagePayload[lastPublishMessagePayloadLen] = 0; - } - - return status; -} - -static unsigned char isTimerExpired(struct timeval target_time) { - unsigned char ret_val = 0; - struct timeval now, result; - - if(target_time.tv_sec != 0 || target_time.tv_usec != 0) { - gettimeofday(&now, NULL); - timersub(&(target_time), &now, &result); - if(result.tv_sec < 0 || (result.tv_sec == 0 && result.tv_usec <= 0)) { - ret_val = 1; - } - } else { - ret_val = 1; - } - return ret_val; -} - -IoT_Error_t iot_tls_read(Network *pNetwork, unsigned char *pMsg, size_t len, Timer *pTimer, size_t *read_len) { - IoT_Error_t status = SUCCESS; - - IOT_UNUSED(pNetwork); - IOT_UNUSED(pTimer); - - if(RxBuffer.mockedError != SUCCESS) { - status = RxBuffer.mockedError; - - /* Clear the error before returning. */ - RxBuffer.mockedError = SUCCESS; - - return status; - } - - if(RxIndex > TLSMaxBufferSize - 1) { - RxIndex = TLSMaxBufferSize - 1; - } - - if(RxBuffer.len <= RxIndex || !isTimerExpired(RxBuffer.expiry_time)) { - return NETWORK_SSL_NOTHING_TO_READ; - } - - if((false == RxBuffer.NoMsgFlag) && (RxIndex < RxBuffer.len)) { - memcpy(pMsg, &(RxBuffer.pBuffer[RxIndex]), len); - RxIndex += len; - *read_len = len; - } - - return status; -} - -IoT_Error_t iot_tls_disconnect(Network *pNetwork) { - IOT_UNUSED(pNetwork); - return SUCCESS; -} - -IoT_Error_t iot_tls_destroy(Network *pNetwork) { - IOT_UNUSED(pNetwork); - return SUCCESS; -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/aws_iot_tests_unit_mock_tls_params.c b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/aws_iot_tests_unit_mock_tls_params.c deleted file mode 100644 index c816a7d2d..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/aws_iot_tests_unit_mock_tls_params.c +++ /dev/null @@ -1,47 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_mock_tls_params.c - * @brief IoT Client Unit Testing Mock TLS Params - */ - -#include "aws_iot_tests_unit_mock_tls_params.h" - -unsigned char RxBuf[TLSMaxBufferSize]; -unsigned char TxBuf[TLSMaxBufferSize]; -char LastSubscribeMessage[TLSMaxBufferSize]; -size_t lastSubscribeMsgLen; -char SecondLastSubscribeMessage[TLSMaxBufferSize]; -size_t secondLastSubscribeMsgLen; - -char LastUnsubscribeMessage[TLSMaxBufferSize]; -size_t lastUnsubscribeMsgLen; - -char LastPublishMessageTopic[TLSMaxBufferSize]; -size_t lastPublishMessageTopicLen; -char LastPublishMessagePayload[TLSMaxBufferSize]; -size_t lastPublishMessagePayloadLen; - -TlsBuffer RxBuffer = {.pBuffer = RxBuf,.len = 512, .NoMsgFlag=1, .expiry_time = {0, 0}, .BufMaxSize = TLSMaxBufferSize, .mockedError = SUCCESS}; -TlsBuffer TxBuffer = {.pBuffer = TxBuf,.len = 512, .NoMsgFlag=1, .expiry_time = {0, 0}, .BufMaxSize = TLSMaxBufferSize, .mockedError = SUCCESS}; - -size_t RxIndex = 0; - -char *invalidEndpointFilter; -char *invalidRootCAPathFilter; -char *invalidCertPathFilter; -char *invalidPrivKeyPathFilter; -uint16_t invalidPortFilter; diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/aws_iot_tests_unit_mock_tls_params.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/aws_iot_tests_unit_mock_tls_params.h deleted file mode 100644 index 20262d5bd..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/aws_iot_tests_unit_mock_tls_params.h +++ /dev/null @@ -1,72 +0,0 @@ -/* -* Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. -* -* Licensed under the Apache License, Version 2.0 (the "License"). -* You may not use this file except in compliance with the License. -* A copy of the License is located at -* -* http://aws.amazon.com/apache2.0 -* -* or in the "license" file accompanying this file. This file is distributed -* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either -* express or implied. See the License for the specific language governing -* permissions and limitations under the License. -*/ - -/** - * @file aws_iot_tests_unit_mock_tls_params.h - * @brief IoT Client Unit Testing Mock TLS Params - */ - -#ifndef UNITTESTS_MOCKS_TLS_PARAMS_H_ -#define UNITTESTS_MOCKS_TLS_PARAMS_H_ - -#include -#include -#include -#include -#include - -#define TLSMaxBufferSize 2560 -#define NO_MSG_LENGTH_MENTIONED -1 - -typedef struct { - unsigned char *pBuffer; - size_t len; - bool NoMsgFlag; - struct timeval expiry_time; - size_t BufMaxSize; - IoT_Error_t mockedError; -} TlsBuffer; - - -extern TlsBuffer RxBuffer; -extern TlsBuffer TxBuffer; - -extern size_t RxIndex; -extern unsigned char RxBuf[TLSMaxBufferSize]; -extern unsigned char TxBuf[TLSMaxBufferSize]; -extern char LastSubscribeMessage[TLSMaxBufferSize]; -extern size_t lastSubscribeMsgLen; -extern char SecondLastSubscribeMessage[TLSMaxBufferSize]; -extern size_t secondLastSubscribeMsgLen; - -extern char LastUnsubscribeMessage[TLSMaxBufferSize]; -extern size_t lastUnsubscribeMsgLen; - -extern char LastPublishMessageTopic[TLSMaxBufferSize]; -extern size_t lastPublishMessageTopicLen; -extern char LastPublishMessagePayload[TLSMaxBufferSize]; -extern size_t lastPublishMessagePayloadLen; - -extern char hostAddress[512]; -extern uint16_t port; -extern uint32_t handshakeTimeout_ms; - -extern char *invalidEndpointFilter; -extern char *invalidRootCAPathFilter; -extern char *invalidCertPathFilter; -extern char *invalidPrivKeyPathFilter; -extern uint16_t invalidPortFilter; - -#endif /* UNITTESTS_MOCKS_TLS_PARAMS_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/network_platform.h b/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/network_platform.h deleted file mode 100644 index 1bbec842f..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/aws-iot-device-sdk-embedded-C/tests/unit/tls_mock/network_platform.h +++ /dev/null @@ -1,19 +0,0 @@ -// -// Created by chaurah on 3/22/16. -// - -#ifndef IOTSDKC_NETWORK_MBEDTLS_PLATFORM_H_H - -/** - * @brief TLS Connection Parameters - * - * Defines a type containing TLS specific parameters to be passed down to the - * TLS networking layer to create a TLS secured socket. - */ -typedef struct _TLSDataParams { - uint32_t flags; -}TLSDataParams; - -#define IOTSDKC_NETWORK_MBEDTLS_PLATFORM_H_H - -#endif //IOTSDKC_NETWORK_MBEDTLS_PLATFORM_H_H diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/component.mk b/examples/espidf-aws-iot/components/esp-aws-iot/component.mk deleted file mode 100644 index b9a705a27..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/component.mk +++ /dev/null @@ -1,10 +0,0 @@ -# -# Component Makefile -# - -COMPONENT_ADD_INCLUDEDIRS := port/include aws-iot-device-sdk-embedded-C/include - -COMPONENT_SRCDIRS := aws-iot-device-sdk-embedded-C/src port - -# Check the submodule is initialised -COMPONENT_SUBMODULES := aws-iot-device-sdk-embedded-C diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/README.md b/examples/espidf-aws-iot/components/esp-aws-iot/examples/README.md deleted file mode 100644 index 4a898d1df..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/README.md +++ /dev/null @@ -1,141 +0,0 @@ -# Amazon Web Services IoT Examples - -These examples are adaptations of some of the [AWS IoT C SDK](https://github.com/aws/aws-iot-device-sdk-embedded-C) examples. - -The provisioning/configuration steps for these examples are the same, and are given in this README. - -This README also contains some troubleshooting information for common problems found when connecting to AWS IoT. - -# Provisioning/Configuration - -There are some additional steps that need to be run before you can build this example. - -The [Getting Started section of the AWS IoT Developer Guide](http://docs.aws.amazon.com/iot/latest/developerguide/iot-gs.html) lays out the steps to get started with AWS IoT. - -To build and use this example, follow all the AWS IoT Getting Started steps from the beginning ("Sign in to the AWS Iot Console") up until "Configuring Your Device". For configuring the device, these are the steps: - -# Authentication (Based on X.509 certificates) - -### Device Authentication - -AWS IoT can use AWS IoT-generated certificates or certificates signed by a CA certificate for device authentication. To use a certificate that is not created by AWS IoT, you must register a CA certificate. All device certificates must be signed by the CA certificate you register. Please refer to guide at https://docs.aws.amazon.com/iot/latest/developerguide/device-certs-your-own.html for step-by-step instructions to register custom X.509 certificates. - -### Server Authentication - -Server certificates allow devices to verify that they're communicating with AWS IoT and not another server impersonating AWS IoT. By default [Amazon Root CA 1](https://www.amazontrust.com/repository/AmazonRootCA1.pem) (signed by Amazon Trust Services Endpoints CA) is embedded in applications, for more information please refer to https://docs.aws.amazon.com/iot/latest/developerguide/managing-device-certs.html#server-authentication - -## Configuring Your Device - -### Installing Private Key & Certificate - -As part of creating a device certificate, you downloaded a Private Key (`xxx-private.pem.key`) and a Certificate file (`xxx-certificate.pem.crt`). These keys need to be loaded by the ESP32 to identify itself. - -There are currently two options for how to load the key & cert. - -* Embed the files into the app binary (default) -* Load the files from SD card - -### Option 1: Embedded Key & Cert into App Binary - -Copy the `.pem.key` and `.pem.crt` files to the `main/certs` subdirectory of the example. Rename them by removing the device-specific prefix - the new names are `private.pem.key` and `certificate.pem.crt`. - -As these files are bound to your AWS IoT account, take care not to accidentally commit them to public source control. In a commercial IoT device these files would be flashed to the device via a provisioning step, but for these examples they are compiled in. - -### Option 2: Loading Key & Cert from SD Card - -The alternative to embedding the key and certificate is to load them from a FAT filesystem on an SD card. - -Before loading data from SD, format your SD card as FAT and run the `examples/storage/sd_card` example on it to verify that it's working as expected in ESP-IDF. This helps cut down the possible causes of errors in the more complex AWS IoT examples! - -Run `make menuconfig`, navigate to "Example Configuration" and change "AWS IoT Certificate Source" to "Load from SD card". - -Three new prompts will appear for filenames for the device key, device certificate and root CA certificate path. These paths start with `/sdcard/` as this is where the example mounts the (FAT formatted) SD card. - -Copy the certificate and key files to the SD card, and make sure the file names match the names given in the example configuration (either rename the files, or change the config). For the Root CA certificate file (which is not device-specific), you can find the file in the `main/certs` directory or download it from AWS. - -*Note: By default, esp-idf's FATFS support only allows 8.3 character filenames. However, the AWS IoT examples pre-configure the sdkconfig to enable long filenames. If you're setting up your projects, you will probably want to enable these options as well (under Component Config -> FAT Filesystem Support). You can also consider configure the FAT filesystem for read-only support, if you don't need to write to the SD card.* - -## Find & Set AWS Endpoint Hostname - -Your AWS IoT account has a unique endpoint hostname to connect to. To find it, open the AWS IoT Console and click the "Settings" button on the bottom left side. The endpoint hostname is shown under the "Custom Endpoint" heading on this page. - -Run `make menuconfig` and navigate to `Component Config` -> `Amazon Web Service IoT Config` -> `AWS IoT MQTT Hostname`. Enter the host name here. - -*Note: It may seem odd that you have to configure parts of the AWS settings under Component Config and some under Example Configuration.* The IoT MQTT Hostname and Port are set as part of the component because when using the AWS IoT SDK's Thing Shadow API (in examples or in other projects) the `ShadowInitParametersDefault` structure means the Thing Shadow connection will default to that host & port. You're not forced to use these config values in your own projects, you can set the values in code via the AWS IoT SDK's init parameter structures - `ShadowInitParameters_t` for Thing Shadow API or `IoT_Client_Init_Params` for MQTT API. - -### (Optional) Set Client ID - -Run `make menuconfig`. Under `Example Configuration`, set the `AWS IoT Client ID` to a unique value. - -The Client ID is used in the MQTT protocol used to send messages to/from AWS IoT. AWS IoT requires that each connected device within a single AWS account uses a unique Client ID. Other than this restriction, the Client ID can be any value that you like. The example default should be fine if you're only connecting one ESP32 at a time. - -In a production IoT app this ID would be set dynamically, but for these examples it is compiled in via menuconfig. - -### (Optional) Locally Check The Root Certificate - -The Root CA certificate provides a root-of-trust when the ESP32 connects to AWS IoT. We have supplied the root CA certificate already (in PEM format) in the file `main/certs/aws-root-ca.pem`. - -If you want to locally verify that this Root CA certificate hasn't changed, you can run the following command against your AWS MQTT Host: - -``` -openssl s_client -showcerts -connect hostname:8883 < /dev/null -``` - -(Replace hostname with your AWS MQTT endpoint host.) The Root CA certificate is the last certificate in the list of certificates printed. You can copy-paste this in place of the existing `aws-root-ca.pem` file. - - -# Troubleshooting - -## Tips - -* Raise the ESP debug log level to Debug in order to see messages about the connection to AWS, certificate contents, etc. - -* Enable mbedTLS debugging (under Components -> mbedTLS -> mbedTLS Debug) in order to see even more low-level debug output from the mbedTLS layer. - -* To create a successful AWS IoT connection, the following factors must all be present: - - Endpoint hostname is correct for your AWS account. - - Certificate & private key are both attached to correct Thing in AWS IoT Console. - - Certificate is activated. - - Policy is attached to the Certificate in AWS IoT Console. - - Policy contains sufficient permissions to authorize AWS IoT connection. - -## TLS connection fails - -If connecting fails entirely (handshake doesn't complete), this usually indicates a problem with certification configuration. The error usually looks like this: - -``` -aws_iot: failed! mbedtls_ssl_handshake returned -0x7780 -``` - -(0x7780 is the mbedTLS error code when the server sends an alert message and closes the connection.) - -* Check your client private key and certificate file match a Certificate registered and **activated** in AWS IoT console. You can find the Certificate in IoT Console in one of two ways, via the Thing or via Certificates: - - To find the Certificate directly, click on "Registry" -> "Security Certificates". Then click on the Certificate itself to view it. - - To find the Certificate via the Thing, click on "Registry" -> "Things", then click on the particular Thing you are using. Click "Certificates" in the sidebar to view all Certificates attached to that Thing. Then click on the Certificate itself to view it. - -Verify the Certificate is activated (when viewing the Certificate, it will say "ACTIVE" or "INACTIVE" near the top under the certificate name). - -If the Certificate appears correct and activated, verify that you are connecting to the correct AWS IoT endpoint (see above.) - -## TLS connection closes immediately - -Sometimes connecting is successful (the handshake completes) but as soon as the client sends its `MQTT CONNECT` message the server sends back a TLS alert and closes the connection, without anything else happening. - -The error returned from AWS IoT is usually -28 (`MQTT_REQUEST_TIMEOUT_ERROR`). You may also see mbedtls error `-0x7780` (server alert), although if this error comes during `mbedtls_ssl_handshake` then it's usually a different problem (see above). - -In the subscribe_publish example, the error may look like this in the log: - -``` -subpub: Error(-28) connecting to (endpoint)... -``` - -In the thing_shadow example, the error may look like this in the log: - -``` -shadow: aws_iot_shadow_connect returned error -28, aborting... -``` - -This error implies the Certificate is recognised, but the Certificate is either missing the correct Thing or the correct Policy attached to it. - -* Check in the AWS IoT console that your certificate is activated and has both a **security policy** and a **Thing** attached to it. You can find this in IoT Console by clicking "Registry" -> "Security Certificates", then click the Certificate. Once viewing the Certificate, you can click the "Policies" and "Things" links in the sidebar. - diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/CMakeLists.txt b/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/CMakeLists.txt deleted file mode 100644 index a415bf5de..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -# The following lines of boilerplate have to be in your project's CMakeLists -# in this exact order for cmake to work correctly -cmake_minimum_required(VERSION 3.5) - -include($ENV{IDF_PATH}/tools/cmake/project.cmake) -set (EXTRA_COMPONENT_DIRS "../..") -project(subscribe_publish) diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/Makefile b/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/Makefile deleted file mode 100644 index 798941a9f..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -# -# This is a project Makefile. It is assumed the directory this Makefile resides in is a -# project subdirectory. -# - -PROJECT_NAME := subscribe_publish - -EXTRA_COMPONENT_DIRS := $(realpath ../..) - -include $(IDF_PATH)/make/project.mk - diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/README.md b/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/README.md deleted file mode 100644 index 031dc72a9..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/README.md +++ /dev/null @@ -1,36 +0,0 @@ -# Amazon Web Services IoT MQTT Subscribe/Publish Example - -This is an adaptation of the [AWS IoT C SDK](https://github.com/aws/aws-iot-device-sdk-embedded-C) "subscribe_publish" example for ESP-IDF. - -# Configuration - -See the README.md in the parent directory for information about configuring the AWS IoT examples. - -# Monitoring MQTT Data from the device - -After flashing the example to your ESP32, it should connect to Amazon and start subscribing/publishing MQTT data. - -The example code publishes MQTT data to the topic `test_topic/esp32`. Amazon provides a web interface to subscribe to MQTT topics for testing: - -* On the AWS IoT console, click "MQTT Client" near the top-right. -* Click "Generate Client ID" to generate a random client ID. -* Click "Connect" - -One connection succeeds, you can subscribe to the data published by the ESP32: - -* Click "Subscribe to Topic" -* Enter "Subscription Topic" `test_topic/esp32` -* Click "Subscribe" - -... you should see MQTT data published from the running example. - -To publish data back to the device: - -* Click "Publish to Topic" -* Enter "Publish Topic" `test_topic/esp32` -* Enter a message in the payload field -* Click Publish - -# Important Note - -This example has dependency on `esp-aws-iot` component which is added through `EXTRA_COMPONENT_DIRS` in its `Makefile` or `CMakeLists.txt` (using relative path). Hence if example is moved outside of this repository then this dependency can be resolved by copying `esp_aws_iot` under `components` subdirectory of the example project. diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/main/CMakeLists.txt b/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/main/CMakeLists.txt deleted file mode 100644 index 807ad6ea0..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/main/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -set(COMPONENT_SRCS "subscribe_publish_sample.c") -set(COMPONENT_ADD_INCLUDEDIRS ".") - - -register_component() - -if(CONFIG_EXAMPLE_EMBEDDED_CERTS) -target_add_binary_data(${COMPONENT_TARGET} "certs/aws-root-ca.pem" TEXT) -target_add_binary_data(${COMPONENT_TARGET} "certs/certificate.pem.crt" TEXT) -target_add_binary_data(${COMPONENT_TARGET} "certs/private.pem.key" TEXT) -endif() diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/main/Kconfig.projbuild b/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/main/Kconfig.projbuild deleted file mode 100644 index 96a022a5c..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/main/Kconfig.projbuild +++ /dev/null @@ -1,60 +0,0 @@ -menu "Example Configuration" - - config WIFI_SSID - string "WiFi SSID" - default "myssid" - help - SSID (network name) for the example to connect to. - - config WIFI_PASSWORD - string "WiFi Password" - default "mypassword" - help - WiFi password (WPA or WPA2) for the example to use. - - Can be left blank if the network has no security set. - - config AWS_EXAMPLE_CLIENT_ID - string "AWS IoT Client ID" - default "myesp32" - help - AWS IoT Client ID for the example. Should be unique for every device. - - choice EXAMPLE_CERT_SOURCE - prompt "AWS IoT Certificate Source" - default EXAMPLE_EMBEDDED_CERTS - help - AWS IoT requires loading of a device-specific certificate and private key, - and a common Root CA Certificate. These can be compiled into the example - app, or they can be loaded via the filesystem from an SD card. - - config EXAMPLE_EMBEDDED_CERTS - bool "Embed into app" - config EXAMPLE_SDCARD_CERTS - bool "Load from SD card" - select EXAMPLE_FILESYSTEM_CERTS - endchoice - - # Currently this is equivalent to EXAMPLE_SDCARD_CERTS, - # however eventually we want to support more filesystem - # sources (SPIFFS, etc.) So this hidden config item - # is selected whenever the item should load from filesystem. - config EXAMPLE_FILESYSTEM_CERTS - bool - - config EXAMPLE_CERTIFICATE_PATH - string "Device Certificate Path" - depends on EXAMPLE_FILESYSTEM_CERTS - default "/sdcard/certificate.pem.crt" - - config EXAMPLE_PRIVATE_KEY_PATH - string "Device Private Key Path" - depends on EXAMPLE_FILESYSTEM_CERTS - default "/sdcard/private.pem.key" - - config EXAMPLE_ROOT_CA_PATH - string "Root CA Certificate Path" - depends on EXAMPLE_FILESYSTEM_CERTS - default "/sdcard/aws-root-ca.pem" - -endmenu diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/main/certs/README.md b/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/main/certs/README.md deleted file mode 100644 index d445cc62b..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/main/certs/README.md +++ /dev/null @@ -1,3 +0,0 @@ -Copy certificate files for AWS IoT SDK example here - -See README.md in main example directory for details. diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/main/certs/aws-root-ca.pem b/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/main/certs/aws-root-ca.pem deleted file mode 100644 index a6f3e92af..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/main/certs/aws-root-ca.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF -ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 -b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL -MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv -b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj -ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM -9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw -IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6 -VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L -93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm -jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC -AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA -A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI -U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs -N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv -o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU -5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy -rqXRfboQnoZsG4q5WTP468SQvvG5 ------END CERTIFICATE----- diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/main/component.mk b/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/main/component.mk deleted file mode 100644 index 401de47a5..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/main/component.mk +++ /dev/null @@ -1,14 +0,0 @@ -# -# Main Makefile. This is basically the same as a component makefile. -# - -ifdef CONFIG_EXAMPLE_EMBEDDED_CERTS -# Certificate files. certificate.pem.crt & private.pem.key must be downloaded -# from AWS, see README for details. -COMPONENT_EMBED_TXTFILES := certs/aws-root-ca.pem certs/certificate.pem.crt certs/private.pem.key - -# Print an error if the certificate/key files are missing -$(COMPONENT_PATH)/certs/certificate.pem.crt $(COMPONENT_PATH)/certs/private.pem.key: - @echo "Missing PEM file $@. This file identifies the ESP32 to AWS for the example, see README for details." - exit 1 -endif diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/main/subscribe_publish_sample.c b/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/main/subscribe_publish_sample.c deleted file mode 100644 index c5b48ae8e..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/main/subscribe_publish_sample.c +++ /dev/null @@ -1,332 +0,0 @@ -/* - * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * Additions Copyright 2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://aws.amazon.com/apache2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -/** - * @file subscribe_publish_sample.c - * @brief simple MQTT publish and subscribe on the same topic - * - * This example takes the parameters from the build configuration and establishes a connection to the AWS IoT MQTT Platform. - * It subscribes and publishes to the same topic - "test_topic/esp32" - * - * Some setup is required. See example README for details. - * - */ -#include -#include -#include -#include -#include -#include - -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" -#include "freertos/event_groups.h" -#include "esp_system.h" -#include "esp_wifi.h" -#include "esp_event_loop.h" -#include "esp_log.h" -#include "esp_vfs_fat.h" -#include "driver/sdmmc_host.h" - -#include "nvs.h" -#include "nvs_flash.h" - -#include "aws_iot_config.h" -#include "aws_iot_log.h" -#include "aws_iot_version.h" -#include "aws_iot_mqtt_client_interface.h" - -static const char *TAG = "subpub"; - -/* The examples use simple WiFi configuration that you can set via - 'make menuconfig'. - - If you'd rather not, just change the below entries to strings with - the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid" -*/ -#define EXAMPLE_WIFI_SSID CONFIG_WIFI_SSID -#define EXAMPLE_WIFI_PASS CONFIG_WIFI_PASSWORD - -/* FreeRTOS event group to signal when we are connected & ready to make a request */ -static EventGroupHandle_t wifi_event_group; - -/* The event group allows multiple bits for each event, - but we only care about one event - are we connected - to the AP with an IP? */ -const int CONNECTED_BIT = BIT0; - - -/* CA Root certificate, device ("Thing") certificate and device - * ("Thing") key. - - Example can be configured one of two ways: - - "Embedded Certs" are loaded from files in "certs/" and embedded into the app binary. - - "Filesystem Certs" are loaded from the filesystem (SD card, etc.) - - See example README for more details. -*/ -#if defined(CONFIG_EXAMPLE_EMBEDDED_CERTS) - -extern const uint8_t aws_root_ca_pem_start[] asm("_binary_aws_root_ca_pem_start"); -extern const uint8_t aws_root_ca_pem_end[] asm("_binary_aws_root_ca_pem_end"); -extern const uint8_t certificate_pem_crt_start[] asm("_binary_certificate_pem_crt_start"); -extern const uint8_t certificate_pem_crt_end[] asm("_binary_certificate_pem_crt_end"); -extern const uint8_t private_pem_key_start[] asm("_binary_private_pem_key_start"); -extern const uint8_t private_pem_key_end[] asm("_binary_private_pem_key_end"); - -#elif defined(CONFIG_EXAMPLE_FILESYSTEM_CERTS) - -static const char * DEVICE_CERTIFICATE_PATH = CONFIG_EXAMPLE_CERTIFICATE_PATH; -static const char * DEVICE_PRIVATE_KEY_PATH = CONFIG_EXAMPLE_PRIVATE_KEY_PATH; -static const char * ROOT_CA_PATH = CONFIG_EXAMPLE_ROOT_CA_PATH; - -#else -#error "Invalid method for loading certs" -#endif - -/** - * @brief Default MQTT HOST URL is pulled from the aws_iot_config.h - */ -char HostAddress[255] = AWS_IOT_MQTT_HOST; - -/** - * @brief Default MQTT port is pulled from the aws_iot_config.h - */ -uint32_t port = AWS_IOT_MQTT_PORT; - - -static esp_err_t event_handler(void *ctx, system_event_t *event) -{ - switch(event->event_id) { - case SYSTEM_EVENT_STA_START: - esp_wifi_connect(); - break; - case SYSTEM_EVENT_STA_GOT_IP: - xEventGroupSetBits(wifi_event_group, CONNECTED_BIT); - break; - case SYSTEM_EVENT_STA_DISCONNECTED: - /* This is a workaround as ESP32 WiFi libs don't currently - auto-reassociate. */ - esp_wifi_connect(); - xEventGroupClearBits(wifi_event_group, CONNECTED_BIT); - break; - default: - break; - } - return ESP_OK; -} - -void iot_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, - IoT_Publish_Message_Params *params, void *pData) { - ESP_LOGI(TAG, "Subscribe callback"); - ESP_LOGI(TAG, "%.*s\t%.*s", topicNameLen, topicName, (int) params->payloadLen, (char *)params->payload); -} - -void disconnectCallbackHandler(AWS_IoT_Client *pClient, void *data) { - ESP_LOGW(TAG, "MQTT Disconnect"); - IoT_Error_t rc = FAILURE; - - if(NULL == pClient) { - return; - } - - if(aws_iot_is_autoreconnect_enabled(pClient)) { - ESP_LOGI(TAG, "Auto Reconnect is enabled, Reconnecting attempt will start now"); - } else { - ESP_LOGW(TAG, "Auto Reconnect not enabled. Starting manual reconnect..."); - rc = aws_iot_mqtt_attempt_reconnect(pClient); - if(NETWORK_RECONNECTED == rc) { - ESP_LOGW(TAG, "Manual Reconnect Successful"); - } else { - ESP_LOGW(TAG, "Manual Reconnect Failed - %d", rc); - } - } -} - -void aws_iot_task(void *param) { - char cPayload[100]; - - int32_t i = 0; - - IoT_Error_t rc = FAILURE; - - AWS_IoT_Client client; - IoT_Client_Init_Params mqttInitParams = iotClientInitParamsDefault; - IoT_Client_Connect_Params connectParams = iotClientConnectParamsDefault; - - IoT_Publish_Message_Params paramsQOS0; - IoT_Publish_Message_Params paramsQOS1; - - ESP_LOGI(TAG, "AWS IoT SDK Version %d.%d.%d-%s", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG); - - mqttInitParams.enableAutoReconnect = false; // We enable this later below - mqttInitParams.pHostURL = HostAddress; - mqttInitParams.port = port; - -#if defined(CONFIG_EXAMPLE_EMBEDDED_CERTS) - mqttInitParams.pRootCALocation = (const char *)aws_root_ca_pem_start; - mqttInitParams.pDeviceCertLocation = (const char *)certificate_pem_crt_start; - mqttInitParams.pDevicePrivateKeyLocation = (const char *)private_pem_key_start; - -#elif defined(CONFIG_EXAMPLE_FILESYSTEM_CERTS) - mqttInitParams.pRootCALocation = ROOT_CA_PATH; - mqttInitParams.pDeviceCertLocation = DEVICE_CERTIFICATE_PATH; - mqttInitParams.pDevicePrivateKeyLocation = DEVICE_PRIVATE_KEY_PATH; -#endif - - mqttInitParams.mqttCommandTimeout_ms = 20000; - mqttInitParams.tlsHandshakeTimeout_ms = 5000; - mqttInitParams.isSSLHostnameVerify = true; - mqttInitParams.disconnectHandler = disconnectCallbackHandler; - mqttInitParams.disconnectHandlerData = NULL; - -#ifdef CONFIG_EXAMPLE_SDCARD_CERTS - ESP_LOGI(TAG, "Mounting SD card..."); - sdmmc_host_t host = SDMMC_HOST_DEFAULT(); - sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); - esp_vfs_fat_sdmmc_mount_config_t mount_config = { - .format_if_mount_failed = false, - .max_files = 3, - }; - sdmmc_card_t* card; - esp_err_t ret = esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, &card); - if (ret != ESP_OK) { - ESP_LOGE(TAG, "Failed to mount SD card VFAT filesystem. Error: %s", esp_err_to_name(ret)); - abort(); - } -#endif - - rc = aws_iot_mqtt_init(&client, &mqttInitParams); - if(SUCCESS != rc) { - ESP_LOGE(TAG, "aws_iot_mqtt_init returned error : %d ", rc); - abort(); - } - - /* Wait for WiFI to show as connected */ - xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, - false, true, portMAX_DELAY); - - connectParams.keepAliveIntervalInSec = 10; - connectParams.isCleanSession = true; - connectParams.MQTTVersion = MQTT_3_1_1; - /* Client ID is set in the menuconfig of the example */ - connectParams.pClientID = CONFIG_AWS_EXAMPLE_CLIENT_ID; - connectParams.clientIDLen = (uint16_t) strlen(CONFIG_AWS_EXAMPLE_CLIENT_ID); - connectParams.isWillMsgPresent = false; - - ESP_LOGI(TAG, "Connecting to AWS..."); - do { - rc = aws_iot_mqtt_connect(&client, &connectParams); - if(SUCCESS != rc) { - ESP_LOGE(TAG, "Error(%d) connecting to %s:%d", rc, mqttInitParams.pHostURL, mqttInitParams.port); - vTaskDelay(1000 / portTICK_RATE_MS); - } - } while(SUCCESS != rc); - - /* - * Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h - * #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL - * #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL - */ - rc = aws_iot_mqtt_autoreconnect_set_status(&client, true); - if(SUCCESS != rc) { - ESP_LOGE(TAG, "Unable to set Auto Reconnect to true - %d", rc); - abort(); - } - - const char *TOPIC = "test_topic/esp32"; - const int TOPIC_LEN = strlen(TOPIC); - - ESP_LOGI(TAG, "Subscribing..."); - rc = aws_iot_mqtt_subscribe(&client, TOPIC, TOPIC_LEN, QOS0, iot_subscribe_callback_handler, NULL); - if(SUCCESS != rc) { - ESP_LOGE(TAG, "Error subscribing : %d ", rc); - abort(); - } - - sprintf(cPayload, "%s : %d ", "hello from SDK", i); - - paramsQOS0.qos = QOS0; - paramsQOS0.payload = (void *) cPayload; - paramsQOS0.isRetained = 0; - - paramsQOS1.qos = QOS1; - paramsQOS1.payload = (void *) cPayload; - paramsQOS1.isRetained = 0; - - while((NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc)) { - - //Max time the yield function will wait for read messages - rc = aws_iot_mqtt_yield(&client, 100); - if(NETWORK_ATTEMPTING_RECONNECT == rc) { - // If the client is attempting to reconnect we will skip the rest of the loop. - continue; - } - - ESP_LOGI(TAG, "Stack remaining for task '%s' is %d bytes", pcTaskGetTaskName(NULL), uxTaskGetStackHighWaterMark(NULL)); - vTaskDelay(1000 / portTICK_RATE_MS); - sprintf(cPayload, "%s : %d ", "hello from ESP32 (QOS0)", i++); - paramsQOS0.payloadLen = strlen(cPayload); - rc = aws_iot_mqtt_publish(&client, TOPIC, TOPIC_LEN, ¶msQOS0); - - sprintf(cPayload, "%s : %d ", "hello from ESP32 (QOS1)", i++); - paramsQOS1.payloadLen = strlen(cPayload); - rc = aws_iot_mqtt_publish(&client, TOPIC, TOPIC_LEN, ¶msQOS1); - if (rc == MQTT_REQUEST_TIMEOUT_ERROR) { - ESP_LOGW(TAG, "QOS1 publish ack not received."); - rc = SUCCESS; - } - } - - ESP_LOGE(TAG, "An error occurred in the main loop."); - abort(); -} - -static void initialise_wifi(void) -{ - tcpip_adapter_init(); - wifi_event_group = xEventGroupCreate(); - ESP_ERROR_CHECK( esp_event_loop_init(event_handler, NULL) ); - wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); - ESP_ERROR_CHECK( esp_wifi_init(&cfg) ); - ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM) ); - wifi_config_t wifi_config = { - .sta = { - .ssid = EXAMPLE_WIFI_SSID, - .password = EXAMPLE_WIFI_PASS, - }, - }; - ESP_LOGI(TAG, "Setting WiFi configuration SSID %s...", wifi_config.sta.ssid); - ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA) ); - ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &wifi_config) ); - ESP_ERROR_CHECK( esp_wifi_start() ); -} - - -void app_main() -{ - // Initialize NVS. - esp_err_t err = nvs_flash_init(); - if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) { - ESP_ERROR_CHECK(nvs_flash_erase()); - err = nvs_flash_init(); - } - ESP_ERROR_CHECK( err ); - - initialise_wifi(); - xTaskCreatePinnedToCore(&aws_iot_task, "aws_iot_task", 9216, NULL, 5, NULL, 1); -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/sdkconfig.ci b/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/sdkconfig.ci deleted file mode 100644 index b59dfb870..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/sdkconfig.ci +++ /dev/null @@ -1,2 +0,0 @@ -# For CI build example assuming certificates stored on sdcard -CONFIG_EXAMPLE_SDCARD_CERTS=y diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/sdkconfig.defaults b/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/sdkconfig.defaults deleted file mode 100644 index 1b9028247..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/subscribe_publish/sdkconfig.defaults +++ /dev/null @@ -1,9 +0,0 @@ -# Enable FATFS read only with long filename support -# for loading Cert/CA/etc from filesystem -# (if enabled in config) -CONFIG_FATFS_READONLY=y -CONFIG_FATFS_CODEPAGE_437=y -CONFIG_FATFS_LFN_HEAP=y - -# Enable TLS asymmetric in/out content length -CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN=y diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/CMakeLists.txt b/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/CMakeLists.txt deleted file mode 100644 index 54aa85bc1..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -# The following lines of boilerplate have to be in your project's CMakeLists -# in this exact order for cmake to work correctly -cmake_minimum_required(VERSION 3.5) - -include($ENV{IDF_PATH}/tools/cmake/project.cmake) -set (EXTRA_COMPONENT_DIRS "../..") -project(thing_shadow) diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/Makefile b/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/Makefile deleted file mode 100644 index db8d0136c..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/Makefile +++ /dev/null @@ -1,11 +0,0 @@ -# -# This is a project Makefile. It is assumed the directory this Makefile resides in is a -# project subdirectory. -# - -PROJECT_NAME := thing_shadow - -EXTRA_COMPONENT_DIRS := $(realpath ../..) - -include $(IDF_PATH)/make/project.mk - diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/README.md b/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/README.md deleted file mode 100644 index a508e73a4..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/README.md +++ /dev/null @@ -1,38 +0,0 @@ -# Amazon Web Services IoT Thing Shadow Example - -This is an adaptation of the [AWS IoT C SDK](https://github.com/aws/aws-iot-device-sdk-embedded-C) "shadow_sample" example for ESP-IDF. - -# Provisioning/Configuration - -See the README.md in the parent directory for information about configuring the AWS IoT examples. - -After following those steps, there is one additional step for this exmaple: - -## Set Thing Name - -For this example, you will need to set a Thing Name under `make menuconfig` -> `Example Configuration` -> `AWS IoT Thing Name`. - -The Thing Name should match a Thing that you created while following the Getting Started guide (to check the Things you have registered, go t othe AWS IoT console web interface, click Registry and then click Things). - -# Monitoring Thing Status - -After flashing the example to your ESP32, it should connect to Amazon and start updating the example Thing's shadow. - -In the ESP32's serial output, you should see the message "Update accepted" logged every couple of seconds. - -You can monitor the Thing status from the AWS IoT console web interface: - -* On the left-hand toolbar, click Registry and then click Things. -* Click on the "Thing" you set up for the example. -* Click on the "Shadow" sidebar link. You should see the Thing Shadow updating regularly. -* Click on the "Activity" sidebar link to see all Thing Shadow updates in a list. You can examine each update individually. - -# Troubleshooting - -If you're having problems with the AWS IoT connection itself, check the Troubleshooting section of the README in the parent directory. - -* If your Thing is connecting and appears to be successfully updating, but you don't see any updates in the AWS IoT console, then check that the Thing Name in the Example Configuration under menuconfig matches exactly the thing name in AWS IoT console (including case). - -# Important Note - -This example has dependency on `esp-aws-iot` component which is added through `EXTRA_COMPONENT_DIRS` in its `Makefile` or `CMakeLists.txt` (using relative path). Hence if example is moved outside of this repository then this dependency can be resolved by copying `esp_aws_iot` under `components` subdirectory of the example project. diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/main/CMakeLists.txt b/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/main/CMakeLists.txt deleted file mode 100644 index f97a426c6..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/main/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -set(COMPONENT_SRCS "thing_shadow_sample.c") -set(COMPONENT_ADD_INCLUDEDIRS ".") - - -register_component() - -if(CONFIG_EXAMPLE_EMBEDDED_CERTS) -target_add_binary_data(${COMPONENT_TARGET} "certs/aws-root-ca.pem" TEXT) -target_add_binary_data(${COMPONENT_TARGET} "certs/certificate.pem.crt" TEXT) -target_add_binary_data(${COMPONENT_TARGET} "certs/private.pem.key" TEXT) -endif() diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/main/Kconfig.projbuild b/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/main/Kconfig.projbuild deleted file mode 100644 index d0ee5c2cb..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/main/Kconfig.projbuild +++ /dev/null @@ -1,66 +0,0 @@ -menu "Example Configuration" - - config WIFI_SSID - string "WiFi SSID" - default "myssid" - help - SSID (network name) for the example to connect to. - - config WIFI_PASSWORD - string "WiFi Password" - default "mypassword" - help - WiFi password (WPA or WPA2) for the example to use. - - Can be left blank if the network has no security set. - - config AWS_EXAMPLE_CLIENT_ID - string "AWS IoT Client ID" - default "myesp32" - help - AWS IoT Client ID for the example. Should be unique for every device. - - config AWS_EXAMPLE_THING_NAME - string "AWS IoT Thing Name" - default "myesp32" - help - AWS IoT Thing Name for the example. Should be unique for every device. - - choice EXAMPLE_CERT_SOURCE - prompt "AWS IoT Certificate Source" - default EXAMPLE_EMBEDDED_CERTS - help - AWS IoT requires loading of a device-specific certificate and private key, - and a common Root CA Certificate. These can be compiled into the example - app, or they can be loaded via the filesystem from an SD card. - - config EXAMPLE_EMBEDDED_CERTS - bool "Embed into app" - config EXAMPLE_SDCARD_CERTS - bool "Load from SD card" - select EXAMPLE_FILESYSTEM_CERTS - endchoice - - # Currently this is equivalent to EXAMPLE_SDCARD_CERTS, - # however eventually we want to support more filesystem - # sources (SPIFFS, etc.) So this hidden config item - # is selected whenever the item should load from filesystem. - config EXAMPLE_FILESYSTEM_CERTS - bool - - config EXAMPLE_CERTIFICATE_PATH - string "Device Certificate Path" - depends on EXAMPLE_FILESYSTEM_CERTS - default "/sdcard/certificate.pem.crt" - - config EXAMPLE_PRIVATE_KEY_PATH - string "Device Private Key Path" - depends on EXAMPLE_FILESYSTEM_CERTS - default "/sdcard/private.pem.key" - - config EXAMPLE_ROOT_CA_PATH - string "Root CA Certificate Path" - depends on EXAMPLE_FILESYSTEM_CERTS - default "/sdcard/aws-root-ca.pem" - -endmenu diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/main/certs/README.md b/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/main/certs/README.md deleted file mode 100644 index d445cc62b..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/main/certs/README.md +++ /dev/null @@ -1,3 +0,0 @@ -Copy certificate files for AWS IoT SDK example here - -See README.md in main example directory for details. diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/main/certs/aws-root-ca.pem b/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/main/certs/aws-root-ca.pem deleted file mode 100644 index a6f3e92af..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/main/certs/aws-root-ca.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF -ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 -b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL -MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv -b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj -ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM -9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw -IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6 -VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L -93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm -jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC -AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA -A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI -U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs -N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv -o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU -5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy -rqXRfboQnoZsG4q5WTP468SQvvG5 ------END CERTIFICATE----- diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/main/component.mk b/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/main/component.mk deleted file mode 100644 index 401de47a5..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/main/component.mk +++ /dev/null @@ -1,14 +0,0 @@ -# -# Main Makefile. This is basically the same as a component makefile. -# - -ifdef CONFIG_EXAMPLE_EMBEDDED_CERTS -# Certificate files. certificate.pem.crt & private.pem.key must be downloaded -# from AWS, see README for details. -COMPONENT_EMBED_TXTFILES := certs/aws-root-ca.pem certs/certificate.pem.crt certs/private.pem.key - -# Print an error if the certificate/key files are missing -$(COMPONENT_PATH)/certs/certificate.pem.crt $(COMPONENT_PATH)/certs/private.pem.key: - @echo "Missing PEM file $@. This file identifies the ESP32 to AWS for the example, see README for details." - exit 1 -endif diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/main/thing_shadow_sample.c b/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/main/thing_shadow_sample.c deleted file mode 100644 index 82ef78358..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/main/thing_shadow_sample.c +++ /dev/null @@ -1,370 +0,0 @@ -/* - * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * Additions Copyright 2016 Espressif Systems (Shanghai) PTE LTD - * - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://aws.amazon.com/apache2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -/** - * @file thing_shadow_sample.c - * @brief A simple connected window example demonstrating the use of Thing Shadow - * - * See example README for more details. - */ -#include -#include -#include -#include -#include -#include - -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" -#include "freertos/event_groups.h" -#include "esp_system.h" -#include "esp_wifi.h" -#include "esp_event_loop.h" -#include "esp_log.h" -#include "esp_vfs_fat.h" -#include "driver/sdmmc_host.h" - -#include "nvs.h" -#include "nvs_flash.h" - -#include "aws_iot_config.h" -#include "aws_iot_log.h" -#include "aws_iot_version.h" -#include "aws_iot_mqtt_client_interface.h" -#include "aws_iot_shadow_interface.h" - -/*! - * The goal of this sample application is to demonstrate the capabilities of shadow. - * This device(say Connected Window) will open the window of a room based on temperature - * It can report to the Shadow the following parameters: - * 1. temperature of the room (double) - * 2. status of the window (open or close) - * It can act on commands from the cloud. In this case it will open or close the window based on the json object "windowOpen" data[open/close] - * - * The two variables from a device's perspective are double temperature and bool windowOpen - * The device needs to act on only on windowOpen variable, so we will create a primitiveJson_t object with callback - The Json Document in the cloud will be - { - "reported": { - "temperature": 0, - "windowOpen": false - }, - "desired": { - "windowOpen": false - } - } - */ - -static const char *TAG = "shadow"; - -#define ROOMTEMPERATURE_UPPERLIMIT 32.0f -#define ROOMTEMPERATURE_LOWERLIMIT 25.0f -#define STARTING_ROOMTEMPERATURE ROOMTEMPERATURE_LOWERLIMIT - -#define MAX_LENGTH_OF_UPDATE_JSON_BUFFER 200 - -/* The examples use simple WiFi configuration that you can set via - 'make menuconfig'. - - If you'd rather not, just change the below entries to strings with - the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid" -*/ -#define EXAMPLE_WIFI_SSID CONFIG_WIFI_SSID -#define EXAMPLE_WIFI_PASS CONFIG_WIFI_PASSWORD - - -/* FreeRTOS event group to signal when we are connected & ready to make a request */ -static EventGroupHandle_t wifi_event_group; - -/* The event group allows multiple bits for each event, - but we only care about one event - are we connected - to the AP with an IP? */ -const int CONNECTED_BIT = BIT0; - - -/* CA Root certificate, device ("Thing") certificate and device - * ("Thing") key. - - Example can be configured one of two ways: - - "Embedded Certs" are loaded from files in "certs/" and embedded into the app binary. - - "Filesystem Certs" are loaded from the filesystem (SD card, etc.) - - See example README for more details. -*/ -#if defined(CONFIG_EXAMPLE_EMBEDDED_CERTS) - -extern const uint8_t aws_root_ca_pem_start[] asm("_binary_aws_root_ca_pem_start"); -extern const uint8_t aws_root_ca_pem_end[] asm("_binary_aws_root_ca_pem_end"); -extern const uint8_t certificate_pem_crt_start[] asm("_binary_certificate_pem_crt_start"); -extern const uint8_t certificate_pem_crt_end[] asm("_binary_certificate_pem_crt_end"); -extern const uint8_t private_pem_key_start[] asm("_binary_private_pem_key_start"); -extern const uint8_t private_pem_key_end[] asm("_binary_private_pem_key_end"); - -#elif defined(CONFIG_EXAMPLE_FILESYSTEM_CERTS) - -static const char * DEVICE_CERTIFICATE_PATH = CONFIG_EXAMPLE_CERTIFICATE_PATH; -static const char * DEVICE_PRIVATE_KEY_PATH = CONFIG_EXAMPLE_PRIVATE_KEY_PATH; -static const char * ROOT_CA_PATH = CONFIG_EXAMPLE_ROOT_CA_PATH; - -#else -#error "Invalid method for loading certs" -#endif - -static esp_err_t event_handler(void *ctx, system_event_t *event) -{ - switch(event->event_id) { - case SYSTEM_EVENT_STA_START: - esp_wifi_connect(); - break; - case SYSTEM_EVENT_STA_GOT_IP: - xEventGroupSetBits(wifi_event_group, CONNECTED_BIT); - break; - case SYSTEM_EVENT_STA_DISCONNECTED: - /* This is a workaround as ESP32 WiFi libs don't currently - auto-reassociate. */ - esp_wifi_connect(); - xEventGroupClearBits(wifi_event_group, CONNECTED_BIT); - break; - default: - break; - } - return ESP_OK; -} - -static void simulateRoomTemperature(float *pRoomTemperature) { - static float deltaChange; - - if(*pRoomTemperature >= ROOMTEMPERATURE_UPPERLIMIT) { - deltaChange = -0.5f; - } else if(*pRoomTemperature <= ROOMTEMPERATURE_LOWERLIMIT) { - deltaChange = 0.5f; - } - - *pRoomTemperature += deltaChange; -} - -static bool shadowUpdateInProgress; - -void ShadowUpdateStatusCallback(const char *pThingName, ShadowActions_t action, Shadow_Ack_Status_t status, - const char *pReceivedJsonDocument, void *pContextData) { - IOT_UNUSED(pThingName); - IOT_UNUSED(action); - IOT_UNUSED(pReceivedJsonDocument); - IOT_UNUSED(pContextData); - - shadowUpdateInProgress = false; - - if(SHADOW_ACK_TIMEOUT == status) { - ESP_LOGE(TAG, "Update timed out"); - } else if(SHADOW_ACK_REJECTED == status) { - ESP_LOGE(TAG, "Update rejected"); - } else if(SHADOW_ACK_ACCEPTED == status) { - ESP_LOGI(TAG, "Update accepted"); - } -} - -void windowActuate_Callback(const char *pJsonString, uint32_t JsonStringDataLen, jsonStruct_t *pContext) { - IOT_UNUSED(pJsonString); - IOT_UNUSED(JsonStringDataLen); - - if(pContext != NULL) { - ESP_LOGI(TAG, "Delta - Window state changed to %d", *(bool *) (pContext->pData)); - } -} - -void aws_iot_task(void *param) { - IoT_Error_t rc = FAILURE; - - char JsonDocumentBuffer[MAX_LENGTH_OF_UPDATE_JSON_BUFFER]; - size_t sizeOfJsonDocumentBuffer = sizeof(JsonDocumentBuffer) / sizeof(JsonDocumentBuffer[0]); - float temperature = 0.0; - - bool windowOpen = false; - jsonStruct_t windowActuator; - windowActuator.cb = windowActuate_Callback; - windowActuator.pData = &windowOpen; - windowActuator.pKey = "windowOpen"; - windowActuator.type = SHADOW_JSON_BOOL; - windowActuator.dataLength = sizeof(bool); - - jsonStruct_t temperatureHandler; - temperatureHandler.cb = NULL; - temperatureHandler.pKey = "temperature"; - temperatureHandler.pData = &temperature; - temperatureHandler.type = SHADOW_JSON_FLOAT; - temperatureHandler.dataLength = sizeof(float); - - ESP_LOGI(TAG, "AWS IoT SDK Version %d.%d.%d-%s", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG); - - // initialize the mqtt client - AWS_IoT_Client mqttClient; - - ShadowInitParameters_t sp = ShadowInitParametersDefault; - sp.pHost = AWS_IOT_MQTT_HOST; - sp.port = AWS_IOT_MQTT_PORT; - -#if defined(CONFIG_EXAMPLE_EMBEDDED_CERTS) - sp.pClientCRT = (const char *)certificate_pem_crt_start; - sp.pClientKey = (const char *)private_pem_key_start; - sp.pRootCA = (const char *)aws_root_ca_pem_start; -#elif defined(CONFIG_EXAMPLE_FILESYSTEM_CERTS) - sp.pClientCRT = DEVICE_CERTIFICATE_PATH; - sp.pClientKey = DEVICE_PRIVATE_KEY_PATH; - sp.pRootCA = ROOT_CA_PATH; -#endif - sp.enableAutoReconnect = false; - sp.disconnectHandler = NULL; - -#ifdef CONFIG_EXAMPLE_SDCARD_CERTS - ESP_LOGI(TAG, "Mounting SD card..."); - sdmmc_host_t host = SDMMC_HOST_DEFAULT(); - sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); - esp_vfs_fat_sdmmc_mount_config_t mount_config = { - .format_if_mount_failed = false, - .max_files = 3, - }; - sdmmc_card_t* card; - esp_err_t ret = esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, &card); - if (ret != ESP_OK) { - ESP_LOGE(TAG, "Failed to mount SD card VFAT filesystem. Error: %s", esp_err_to_name(ret)); - abort(); - } -#endif - - /* Wait for WiFI to show as connected */ - xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, - false, true, portMAX_DELAY); - - ESP_LOGI(TAG, "Shadow Init"); - rc = aws_iot_shadow_init(&mqttClient, &sp); - if(SUCCESS != rc) { - ESP_LOGE(TAG, "aws_iot_shadow_init returned error %d, aborting...", rc); - abort(); - } - - ShadowConnectParameters_t scp = ShadowConnectParametersDefault; - scp.pMyThingName = CONFIG_AWS_EXAMPLE_THING_NAME; - scp.pMqttClientId = CONFIG_AWS_EXAMPLE_CLIENT_ID; - scp.mqttClientIdLen = (uint16_t) strlen(CONFIG_AWS_EXAMPLE_CLIENT_ID); - - ESP_LOGI(TAG, "Shadow Connect"); - rc = aws_iot_shadow_connect(&mqttClient, &scp); - if(SUCCESS != rc) { - ESP_LOGE(TAG, "aws_iot_shadow_connect returned error %d, aborting...", rc); - abort(); - } - - /* - * Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h - * #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL - * #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL - */ - rc = aws_iot_shadow_set_autoreconnect_status(&mqttClient, true); - if(SUCCESS != rc) { - ESP_LOGE(TAG, "Unable to set Auto Reconnect to true - %d, aborting...", rc); - abort(); - } - - rc = aws_iot_shadow_register_delta(&mqttClient, &windowActuator); - - if(SUCCESS != rc) { - ESP_LOGE(TAG, "Shadow Register Delta Error"); - } - temperature = STARTING_ROOMTEMPERATURE; - - // loop and publish a change in temperature - while(NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc) { - rc = aws_iot_shadow_yield(&mqttClient, 200); - if(NETWORK_ATTEMPTING_RECONNECT == rc || shadowUpdateInProgress) { - rc = aws_iot_shadow_yield(&mqttClient, 1000); - // If the client is attempting to reconnect, or already waiting on a shadow update, - // we will skip the rest of the loop. - continue; - } - ESP_LOGI(TAG, "======================================================================================="); - ESP_LOGI(TAG, "On Device: window state %s", windowOpen ? "true" : "false"); - simulateRoomTemperature(&temperature); - - rc = aws_iot_shadow_init_json_document(JsonDocumentBuffer, sizeOfJsonDocumentBuffer); - if(SUCCESS == rc) { - rc = aws_iot_shadow_add_reported(JsonDocumentBuffer, sizeOfJsonDocumentBuffer, 2, &temperatureHandler, - &windowActuator); - if(SUCCESS == rc) { - rc = aws_iot_finalize_json_document(JsonDocumentBuffer, sizeOfJsonDocumentBuffer); - if(SUCCESS == rc) { - ESP_LOGI(TAG, "Update Shadow: %s", JsonDocumentBuffer); - rc = aws_iot_shadow_update(&mqttClient, CONFIG_AWS_EXAMPLE_THING_NAME, JsonDocumentBuffer, - ShadowUpdateStatusCallback, NULL, 4, true); - shadowUpdateInProgress = true; - } - } - } - ESP_LOGI(TAG, "*****************************************************************************************"); - ESP_LOGI(TAG, "Stack remaining for task '%s' is %d bytes", pcTaskGetTaskName(NULL), uxTaskGetStackHighWaterMark(NULL)); - - vTaskDelay(1000 / portTICK_RATE_MS); - } - - if(SUCCESS != rc) { - ESP_LOGE(TAG, "An error occurred in the loop %d", rc); - } - - ESP_LOGI(TAG, "Disconnecting"); - rc = aws_iot_shadow_disconnect(&mqttClient); - - if(SUCCESS != rc) { - ESP_LOGE(TAG, "Disconnect error %d", rc); - } - - vTaskDelete(NULL); -} - -static void initialise_wifi(void) -{ - tcpip_adapter_init(); - wifi_event_group = xEventGroupCreate(); - ESP_ERROR_CHECK( esp_event_loop_init(event_handler, NULL) ); - wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); - ESP_ERROR_CHECK( esp_wifi_init(&cfg) ); - ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM) ); - wifi_config_t wifi_config = { - .sta = { - .ssid = EXAMPLE_WIFI_SSID, - .password = EXAMPLE_WIFI_PASS, - }, - }; - ESP_LOGI(TAG, "Setting WiFi configuration SSID %s...", wifi_config.sta.ssid); - ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA) ); - ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &wifi_config) ); - ESP_ERROR_CHECK( esp_wifi_start() ); -} - - -void app_main() -{ - esp_err_t err = nvs_flash_init(); - if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) { - ESP_ERROR_CHECK(nvs_flash_erase()); - err = nvs_flash_init(); - } - ESP_ERROR_CHECK( err ); - - initialise_wifi(); - /* Temporarily pin task to core, due to FPU uncertainty */ - xTaskCreatePinnedToCore(&aws_iot_task, "aws_iot_task", 9216, NULL, 5, NULL, 1); -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/sdkconfig.ci b/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/sdkconfig.ci deleted file mode 100644 index b59dfb870..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/sdkconfig.ci +++ /dev/null @@ -1,2 +0,0 @@ -# For CI build example assuming certificates stored on sdcard -CONFIG_EXAMPLE_SDCARD_CERTS=y diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/sdkconfig.defaults b/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/sdkconfig.defaults deleted file mode 100644 index 8d8e882fc..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/examples/thing_shadow/sdkconfig.defaults +++ /dev/null @@ -1,8 +0,0 @@ -# Enable FATFS read only with long filename support -# for loading Cert/CA/etc from filesystem -# (if enabled in config) -CONFIG_FATFS_CODEPAGE_437=y -CONFIG_FATFS_LFN_HEAP=y - -# Enable TLS asymmetric in/out content length -CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN=y diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/port/include/aws_iot_config.h b/examples/espidf-aws-iot/components/esp-aws-iot/port/include/aws_iot_config.h deleted file mode 100644 index c98f7dea2..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/port/include/aws_iot_config.h +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://aws.amazon.com/apache2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -/** - * @file aws_iot_config.h - * @brief AWS IoT specific configuration file - */ - -#ifndef _AWS_IOT_CONFIG_H_ -#define _AWS_IOT_CONFIG_H_ - -#include "aws_iot_log.h" - -// This configuration macro needs to be available globally to enable threading -#define _ENABLE_THREAD_SUPPORT_ - -// These values are defined in the menuconfig of the AWS IoT component. -// However, you can override these constants from your own code. -#define AWS_IOT_MQTT_HOST CONFIG_AWS_IOT_MQTT_HOST ///< Customer specific MQTT HOST. The same will be used for Thing Shadow -#define AWS_IOT_MQTT_PORT CONFIG_AWS_IOT_MQTT_PORT ///< default port for MQTT/S - -// These values are defaults and are used for ShadowConnectParametersDefault. -// You should override them from your own code. -#define AWS_IOT_MQTT_CLIENT_ID "ESP32" ///< MQTT client ID should be unique for every device -#define AWS_IOT_MY_THING_NAME "ESP32" ///< Thing Name of the Shadow this device is associated with - -// MQTT PubSub -#define AWS_IOT_MQTT_TX_BUF_LEN CONFIG_AWS_IOT_MQTT_TX_BUF_LEN ///< Any time a message is sent out through the MQTT layer. The message is copied into this buffer anytime a publish is done. This will also be used in the case of Thing Shadow -#define AWS_IOT_MQTT_RX_BUF_LEN CONFIG_AWS_IOT_MQTT_RX_BUF_LEN ///< Any message that comes into the device should be less than this buffer size. If a received message is bigger than this buffer size the message will be dropped. -#define AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS CONFIG_AWS_IOT_MQTT_NUM_SUBSCRIBE_HANDLERS ///< Maximum number of topic filters the MQTT client can handle at any given time. This should be increased appropriately when using Thing Shadow - -// Thing Shadow specific configs -#ifdef CONFIG_AWS_IOT_OVERRIDE_THING_SHADOW_RX_BUFFER -#define SHADOW_MAX_SIZE_OF_RX_BUFFER CONFIG_AWS_IOT_SHADOW_MAX_SIZE_OF_RX_BUFFER ///< Maximum size of the SHADOW buffer to store the received Shadow message, including NULL terminating byte -#else -#define SHADOW_MAX_SIZE_OF_RX_BUFFER (AWS_IOT_MQTT_RX_BUF_LEN + 1) -#endif - -#define MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES 80 ///< Maximum size of the Unique Client Id. For More info on the Client Id refer \ref response "Acknowledgments" -#define MAX_SIZE_CLIENT_ID_WITH_SEQUENCE (MAX_SIZE_OF_UNIQUE_CLIENT_ID_BYTES + 10) ///< This is size of the extra sequence number that will be appended to the Unique client Id -#define MAX_SIZE_CLIENT_TOKEN_CLIENT_SEQUENCE (MAX_SIZE_CLIENT_ID_WITH_SEQUENCE + 20) ///< This is size of the the total clientToken key and value pair in the JSON -#define MAX_ACKS_TO_COMEIN_AT_ANY_GIVEN_TIME CONFIG_AWS_IOT_SHADOW_MAX_SIMULTANEOUS_ACKS ///< At Any given time we will wait for this many responses. This will correlate to the rate at which the shadow actions are requested -#define MAX_THINGNAME_HANDLED_AT_ANY_GIVEN_TIME CONFIG_AWS_IOT_SHADOW_MAX_SIMULTANEOUS_THINGNAMES ///< We could perform shadow action on any thing Name and this is maximum Thing Names we can act on at any given time -#define MAX_JSON_TOKEN_EXPECTED CONFIG_AWS_IOT_SHADOW_MAX_JSON_TOKEN_EXPECTED ///< These are the max tokens that is expected to be in the Shadow JSON document. Include the metadata that gets published -#define MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME CONFIG_AWS_IOT_SHADOW_MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME ///< All shadow actions have to be published or subscribed to a topic which is of the formablogt $aws/things/{thingName}/shadow/update/accepted. This refers to the size of the topic without the Thing Name -#define MAX_SIZE_OF_THING_NAME CONFIG_AWS_IOT_SHADOW_MAX_SIZE_OF_THING_NAME ///< The Thing Name should not be bigger than this value. Modify this if the Thing Name needs to be bigger -#define MAX_SHADOW_TOPIC_LENGTH_BYTES (MAX_SHADOW_TOPIC_LENGTH_WITHOUT_THINGNAME + MAX_SIZE_OF_THING_NAME) ///< This size includes the length of topic with Thing Name - -// Auto Reconnect specific config -#define AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL CONFIG_AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL ///< Minimum time before the First reconnect attempt is made as part of the exponential back-off algorithm -#define AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL CONFIG_AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL ///< Maximum time interval after which exponential back-off will stop attempting to reconnect. - -#endif /* _AWS_IOT_CONFIG_H_ */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/port/include/aws_iot_log.h b/examples/espidf-aws-iot/components/esp-aws-iot/port/include/aws_iot_log.h deleted file mode 100644 index 7d83960cc..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/port/include/aws_iot_log.h +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -#pragma once - -/* (these two headers aren't used here, but AWS IoT SDK code relies on them - being included from here...) */ -#include -#include - -#include "esp_log.h" - -/* This is a stub replacement for the aws_iot_log.h header in the AWS IoT SDK, - which redirects their logging framework into the esp-idf logging framework. - - The current (2.1.1) upstream AWS IoT SDK doesn't allow this as some of its - headers include aws_iot_log.h, but our modified fork does. -*/ - -// redefine the AWS IoT log functions to call into the IDF log layer -#undef IOT_DEBUG -#define IOT_DEBUG(format, ...) ESP_LOGD("aws_iot", format, ##__VA_ARGS__) -#undef IOT_INFO -#define IOT_INFO(format, ...) ESP_LOGI("aws_iot", format, ##__VA_ARGS__) -#undef IOT_WARN -#define IOT_WARN(format, ...) ESP_LOGW("aws_iot", format, ##__VA_ARGS__) -#undef IOT_ERROR -#define IOT_ERROR(format, ...) ESP_LOGE("aws_iot", format, ##__VA_ARGS__) - -/* Function tracing macros used in AWS IoT SDK, - mapped to "verbose" level output -*/ -#undef FUNC_ENTRY -#define FUNC_ENTRY ESP_LOGV("aws_iot", "FUNC_ENTRY: %s L#%d \n", __func__, __LINE__) -#undef FUNC_EXIT_RC -#define FUNC_EXIT_RC(x) \ - do { \ - ESP_LOGV("aws_iot", "FUNC_EXIT: %s L#%d Return Code : %d \n", __func__, __LINE__, x); \ - return x; \ - } while(0) diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/port/include/network_platform.h b/examples/espidf-aws-iot/components/esp-aws-iot/port/include/network_platform.h deleted file mode 100644 index a5e87d71a..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/port/include/network_platform.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * Additions Copyright 2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://aws.amazon.com/apache2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -#ifndef IOTSDKC_NETWORK_MBEDTLS_PLATFORM_H_H - -#if !defined(MBEDTLS_CONFIG_FILE) -#include "mbedtls/config.h" -#else -#include MBEDTLS_CONFIG_FILE -#endif - -#include "mbedtls/platform.h" -#include "mbedtls/net_sockets.h" -#include "mbedtls/ssl.h" -#include "mbedtls/entropy.h" -#include "mbedtls/ctr_drbg.h" -#include "mbedtls/certs.h" -#include "mbedtls/x509.h" -#include "mbedtls/error.h" -#include "mbedtls/debug.h" -#include "mbedtls/timing.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @brief TLS Connection Parameters - * - * Defines a type containing TLS specific parameters to be passed down to the - * TLS networking layer to create a TLS secured socket. - */ -typedef struct _TLSDataParams { - mbedtls_entropy_context entropy; - mbedtls_ctr_drbg_context ctr_drbg; - mbedtls_ssl_context ssl; - mbedtls_ssl_config conf; - uint32_t flags; - mbedtls_x509_crt cacert; - mbedtls_x509_crt clicert; - mbedtls_pk_context pkey; - mbedtls_net_context server_fd; -}TLSDataParams; - -#define IOTSDKC_NETWORK_MBEDTLS_PLATFORM_H_H - -#ifdef __cplusplus -} -#endif - -#endif //IOTSDKC_NETWORK_MBEDTLS_PLATFORM_H_H diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/port/include/threads_platform.h b/examples/espidf-aws-iot/components/esp-aws-iot/port/include/threads_platform.h deleted file mode 100644 index 011a1a0b2..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/port/include/threads_platform.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * Additions Copyright 2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://aws.amazon.com/apache2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -#include "threads_interface.h" - -#ifndef AWS_IOTSDK_THREADS_PLATFORM_H -#define AWS_IOTSDK_THREADS_PLATFORM_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include "freertos/FreeRTOS.h" -#include "freertos/semphr.h" - -/** - * @brief Mutex Type - * - * definition of the Mutex struct. Platform specific - * - */ -struct _IoT_Mutex_t { - SemaphoreHandle_t mutex; -}; - -#ifdef __cplusplus -} -#endif - -#endif /* AWS_IOTSDK_THREADS_PLATFORM_H */ - - diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/port/include/timer_platform.h b/examples/espidf-aws-iot/components/esp-aws-iot/port/include/timer_platform.h deleted file mode 100644 index 07e7385db..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/port/include/timer_platform.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * Additions Copyright 2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://aws.amazon.com/apache2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -#ifndef AWS_IOT_PLATFORM_H -#define AWS_IOT_PLATFORM_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include "timer_interface.h" - -/** - * definition of the Timer struct. Platform specific - */ -struct Timer { - uint32_t start_ticks; - uint32_t timeout_ticks; - uint32_t last_polled_ticks; -}; - -#ifdef __cplusplus -} -#endif - -#endif /* AWS_IOT_PLATFORM_H */ diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/port/network_mbedtls_wrapper.c b/examples/espidf-aws-iot/components/esp-aws-iot/port/network_mbedtls_wrapper.c deleted file mode 100644 index 61ddec02b..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/port/network_mbedtls_wrapper.c +++ /dev/null @@ -1,419 +0,0 @@ -/* - * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * Additions Copyright 2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://aws.amazon.com/apache2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -#include -#include -#include -#include -#include - -#include "aws_iot_config.h" -#include "aws_iot_error.h" -#include "network_interface.h" -#include "network_platform.h" - -#include "mbedtls/esp_debug.h" - -#include "esp_log.h" -#include "esp_vfs.h" - -static const char *TAG = "aws_iot"; - -/* This is the value used for ssl read timeout */ -#define IOT_SSL_READ_TIMEOUT 10 - -/* - * This is a function to do further verification if needed on the cert received. - * - * Currently used to print debug-level information about each cert. - */ -static int _iot_tls_verify_cert(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags) { - char buf[256]; - ((void) data); - - if (LOG_LOCAL_LEVEL >= ESP_LOG_DEBUG) { - ESP_LOGD(TAG, "Verify requested for (Depth %d):", depth); - mbedtls_x509_crt_info(buf, sizeof(buf) - 1, "", crt); - ESP_LOGD(TAG, "%s", buf); - - if((*flags) == 0) { - ESP_LOGD(TAG, " This certificate has no flags"); - } else { - ESP_LOGD(TAG, "Verify result:%s", buf); - } - } - - return 0; -} - -static void _iot_tls_set_connect_params(Network *pNetwork, 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 = SUCCESS; - TLSDataParams *tlsDataParams = NULL; - char portBuffer[6]; - char info_buf[256]; - - if(NULL == pNetwork) { - return NULL_VALUE_ERROR; - } - - if(NULL != params) { - _iot_tls_set_connect_params(pNetwork, params->pRootCALocation, params->pDeviceCertLocation, - params->pDevicePrivateKeyLocation, params->pDestinationURL, - params->DestinationPort, params->timeout_ms, params->ServerVerificationFlag); - } - - tlsDataParams = &(pNetwork->tlsDataParams); - - mbedtls_net_init(&(tlsDataParams->server_fd)); - mbedtls_ssl_init(&(tlsDataParams->ssl)); - mbedtls_ssl_config_init(&(tlsDataParams->conf)); - -#ifdef CONFIG_MBEDTLS_DEBUG - mbedtls_esp_enable_debug_log(&(tlsDataParams->conf), 4); -#endif - - mbedtls_ctr_drbg_init(&(tlsDataParams->ctr_drbg)); - mbedtls_x509_crt_init(&(tlsDataParams->cacert)); - mbedtls_x509_crt_init(&(tlsDataParams->clicert)); - mbedtls_pk_init(&(tlsDataParams->pkey)); - - ESP_LOGD(TAG, "Seeding the random number generator..."); - mbedtls_entropy_init(&(tlsDataParams->entropy)); - if((ret = mbedtls_ctr_drbg_seed(&(tlsDataParams->ctr_drbg), mbedtls_entropy_func, &(tlsDataParams->entropy), - (const unsigned char *) TAG, strlen(TAG))) != 0) { - ESP_LOGE(TAG, "failed! mbedtls_ctr_drbg_seed returned -0x%x", -ret); - return NETWORK_MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED; - } - - /* Load root CA... - - Certs/keys can be paths or they can be raw data. These use a - very basic heuristic: if the cert starts with '/' then it's a - path, if it's longer than this then it's raw cert data (PEM or DER, - neither of which can start with a slash. */ - if (pNetwork->tlsConnectParams.pRootCALocation[0] == '/') { - ESP_LOGD(TAG, "Loading CA root certificate from file ..."); - ret = mbedtls_x509_crt_parse_file(&(tlsDataParams->cacert), pNetwork->tlsConnectParams.pRootCALocation); - } else { - ESP_LOGD(TAG, "Loading embedded CA root certificate ..."); - ret = mbedtls_x509_crt_parse(&(tlsDataParams->cacert), (const unsigned char *)pNetwork->tlsConnectParams.pRootCALocation, - strlen(pNetwork->tlsConnectParams.pRootCALocation)+1); - } - - if(ret < 0) { - ESP_LOGE(TAG, "failed! mbedtls_x509_crt_parse returned -0x%x while parsing root cert", -ret); - return NETWORK_X509_ROOT_CRT_PARSE_ERROR; - } - ESP_LOGD(TAG, "ok (%d skipped)", ret); - - /* Load client certificate... */ - if (pNetwork->tlsConnectParams.pDeviceCertLocation[0] == '/') { - ESP_LOGD(TAG, "Loading client cert from file..."); - ret = mbedtls_x509_crt_parse_file(&(tlsDataParams->clicert), - pNetwork->tlsConnectParams.pDeviceCertLocation); - } else { - ESP_LOGD(TAG, "Loading embedded client certificate..."); - ret = mbedtls_x509_crt_parse(&(tlsDataParams->clicert), - (const unsigned char *)pNetwork->tlsConnectParams.pDeviceCertLocation, - strlen(pNetwork->tlsConnectParams.pDeviceCertLocation)+1); - } - if(ret != 0) { - ESP_LOGE(TAG, "failed! mbedtls_x509_crt_parse returned -0x%x while parsing device cert", -ret); - return NETWORK_X509_DEVICE_CRT_PARSE_ERROR; - } - - /* Parse client private key... */ - if (pNetwork->tlsConnectParams.pDevicePrivateKeyLocation[0] == '/') { - ESP_LOGD(TAG, "Loading client private key from file..."); - ret = mbedtls_pk_parse_keyfile(&(tlsDataParams->pkey), - pNetwork->tlsConnectParams.pDevicePrivateKeyLocation, - ""); - } else { - ESP_LOGD(TAG, "Loading embedded client private key..."); - ret = mbedtls_pk_parse_key(&(tlsDataParams->pkey), - (const unsigned char *)pNetwork->tlsConnectParams.pDevicePrivateKeyLocation, - strlen(pNetwork->tlsConnectParams.pDevicePrivateKeyLocation)+1, - (const unsigned char *)"", 0); - } - if(ret != 0) { - ESP_LOGE(TAG, "failed! mbedtls_pk_parse_key returned -0x%x while parsing private key", -ret); - return NETWORK_PK_PRIVATE_KEY_PARSE_ERROR; - } - - /* Done parsing certs */ - ESP_LOGD(TAG, "ok"); - snprintf(portBuffer, 6, "%d", pNetwork->tlsConnectParams.DestinationPort); - ESP_LOGD(TAG, "Connecting to %s/%s...", pNetwork->tlsConnectParams.pDestinationURL, portBuffer); - if((ret = mbedtls_net_connect(&(tlsDataParams->server_fd), pNetwork->tlsConnectParams.pDestinationURL, - portBuffer, MBEDTLS_NET_PROTO_TCP)) != 0) { - ESP_LOGE(TAG, "failed! mbedtls_net_connect returned -0x%x", -ret); - switch(ret) { - case MBEDTLS_ERR_NET_SOCKET_FAILED: - return NETWORK_ERR_NET_SOCKET_FAILED; - case MBEDTLS_ERR_NET_UNKNOWN_HOST: - return NETWORK_ERR_NET_UNKNOWN_HOST; - case MBEDTLS_ERR_NET_CONNECT_FAILED: - default: - return NETWORK_ERR_NET_CONNECT_FAILED; - }; - } - - ret = mbedtls_net_set_block(&(tlsDataParams->server_fd)); - if(ret != 0) { - ESP_LOGE(TAG, "failed! net_set_(non)block() returned -0x%x", -ret); - return SSL_CONNECTION_ERROR; - } ESP_LOGD(TAG, "ok"); - - ESP_LOGD(TAG, "Setting up the SSL/TLS structure..."); - if((ret = mbedtls_ssl_config_defaults(&(tlsDataParams->conf), MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, - MBEDTLS_SSL_PRESET_DEFAULT)) != 0) { - ESP_LOGE(TAG, "failed! mbedtls_ssl_config_defaults returned -0x%x", -ret); - return SSL_CONNECTION_ERROR; - } - - mbedtls_ssl_conf_verify(&(tlsDataParams->conf), _iot_tls_verify_cert, NULL); - - if(pNetwork->tlsConnectParams.ServerVerificationFlag == true) { - mbedtls_ssl_conf_authmode(&(tlsDataParams->conf), MBEDTLS_SSL_VERIFY_REQUIRED); - } else { - mbedtls_ssl_conf_authmode(&(tlsDataParams->conf), MBEDTLS_SSL_VERIFY_OPTIONAL); - } - mbedtls_ssl_conf_rng(&(tlsDataParams->conf), mbedtls_ctr_drbg_random, &(tlsDataParams->ctr_drbg)); - - mbedtls_ssl_conf_ca_chain(&(tlsDataParams->conf), &(tlsDataParams->cacert), NULL); - ret = mbedtls_ssl_conf_own_cert(&(tlsDataParams->conf), &(tlsDataParams->clicert), &(tlsDataParams->pkey)); - if(ret != 0) { - ESP_LOGE(TAG, "failed! mbedtls_ssl_conf_own_cert returned %d", ret); - return SSL_CONNECTION_ERROR; - } - - mbedtls_ssl_conf_read_timeout(&(tlsDataParams->conf), pNetwork->tlsConnectParams.timeout_ms); - -#ifdef CONFIG_MBEDTLS_SSL_ALPN - /* Use the AWS IoT ALPN extension for MQTT, if port 443 is requested */ - if (pNetwork->tlsConnectParams.DestinationPort == 443) { - const char *alpnProtocols[] = { "x-amzn-mqtt-ca", NULL }; - if ((ret = mbedtls_ssl_conf_alpn_protocols(&(tlsDataParams->conf), alpnProtocols)) != 0) { - ESP_LOGE(TAG, "failed! mbedtls_ssl_conf_alpn_protocols returned -0x%x", -ret); - return SSL_CONNECTION_ERROR; - } - } -#endif - - if((ret = mbedtls_ssl_setup(&(tlsDataParams->ssl), &(tlsDataParams->conf))) != 0) { - ESP_LOGE(TAG, "failed! mbedtls_ssl_setup returned -0x%x", -ret); - return SSL_CONNECTION_ERROR; - } - if((ret = mbedtls_ssl_set_hostname(&(tlsDataParams->ssl), pNetwork->tlsConnectParams.pDestinationURL)) != 0) { - ESP_LOGE(TAG, "failed! mbedtls_ssl_set_hostname returned %d", ret); - return SSL_CONNECTION_ERROR; - } - ESP_LOGD(TAG, "SSL state connect : %d ", tlsDataParams->ssl.state); - mbedtls_ssl_set_bio(&(tlsDataParams->ssl), &(tlsDataParams->server_fd), mbedtls_net_send, NULL, - mbedtls_net_recv_timeout); - ESP_LOGD(TAG, "ok"); - - ESP_LOGD(TAG, "SSL state connect : %d ", tlsDataParams->ssl.state); - ESP_LOGD(TAG, "Performing the SSL/TLS handshake..."); - while((ret = mbedtls_ssl_handshake(&(tlsDataParams->ssl))) != 0) { - if(ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { - ESP_LOGE(TAG, "failed! mbedtls_ssl_handshake returned -0x%x", -ret); - if(ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) { - ESP_LOGE(TAG, " Unable to verify the server's certificate. "); - } - return SSL_CONNECTION_ERROR; - } - } - - ESP_LOGD(TAG, "ok [ Protocol is %s ] [ Ciphersuite is %s ]", mbedtls_ssl_get_version(&(tlsDataParams->ssl)), - mbedtls_ssl_get_ciphersuite(&(tlsDataParams->ssl))); - if((ret = mbedtls_ssl_get_record_expansion(&(tlsDataParams->ssl))) >= 0) { - ESP_LOGD(TAG, " [ Record expansion is %d ]", ret); - } else { - ESP_LOGD(TAG, " [ Record expansion is unknown (compression) ]"); - } - - ESP_LOGD(TAG, "Verifying peer X.509 certificate..."); - - if(pNetwork->tlsConnectParams.ServerVerificationFlag == true) { - if((tlsDataParams->flags = mbedtls_ssl_get_verify_result(&(tlsDataParams->ssl))) != 0) { - ESP_LOGE(TAG, "failed"); - mbedtls_x509_crt_verify_info(info_buf, sizeof(info_buf), " ! ", tlsDataParams->flags); - ESP_LOGE(TAG, "%s", info_buf); - ret = SSL_CONNECTION_ERROR; - } else { - ESP_LOGD(TAG, "ok"); - ret = SUCCESS; - } - } else { - ESP_LOGW(TAG, " Server Verification skipped"); - ret = SUCCESS; - } - - if(LOG_LOCAL_LEVEL >= ESP_LOG_DEBUG) { - if (mbedtls_ssl_get_peer_cert(&(tlsDataParams->ssl)) != NULL) { - ESP_LOGD(TAG, "Peer certificate information:"); - mbedtls_x509_crt_info((char *) info_buf, sizeof(info_buf) - 1, " ", mbedtls_ssl_get_peer_cert(&(tlsDataParams->ssl))); - ESP_LOGD(TAG, "%s", info_buf); - } - } - - return (IoT_Error_t) ret; -} - -IoT_Error_t iot_tls_write(Network *pNetwork, unsigned char *pMsg, size_t len, Timer *timer, size_t *written_len) { - size_t written_so_far; - bool isErrorFlag = false; - int frags, ret = 0; - TLSDataParams *tlsDataParams = &(pNetwork->tlsDataParams); - - for(written_so_far = 0, frags = 0; - written_so_far < len && !has_timer_expired(timer); written_so_far += ret, frags++) { - while(!has_timer_expired(timer) && - (ret = mbedtls_ssl_write(&(tlsDataParams->ssl), pMsg + written_so_far, len - written_so_far)) <= 0) { - if(ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE) { - ESP_LOGE(TAG, "failed! mbedtls_ssl_write returned -0x%x", -ret); - /* All other negative return values indicate connection needs to be reset. - * Will be caught in ping request so ignored here */ - isErrorFlag = true; - break; - } - } - if(isErrorFlag) { - break; - } - } - - *written_len = written_so_far; - - if(isErrorFlag) { - return NETWORK_SSL_WRITE_ERROR; - } else if(has_timer_expired(timer) && written_so_far != len) { - return NETWORK_SSL_WRITE_TIMEOUT_ERROR; - } - - return SUCCESS; -} - -IoT_Error_t iot_tls_read(Network *pNetwork, unsigned char *pMsg, size_t len, Timer *timer, size_t *read_len) { - TLSDataParams *tlsDataParams = &(pNetwork->tlsDataParams); - mbedtls_ssl_context *ssl = &(tlsDataParams->ssl); - mbedtls_ssl_config *ssl_conf = &(tlsDataParams->conf); - uint32_t read_timeout; - size_t rxLen = 0; - int ret; - - read_timeout = ssl_conf->read_timeout; - - while (len > 0) { - - /* Make sure we never block on read for longer than timer has left, - but also that we don't block indefinitely (ie read_timeout > 0) */ - mbedtls_ssl_conf_read_timeout(ssl_conf, MAX(1, MIN(read_timeout, left_ms(timer)))); - - ret = mbedtls_ssl_read(ssl, pMsg, len); - - /* Restore the old timeout */ - mbedtls_ssl_conf_read_timeout(ssl_conf, read_timeout); - - if (ret > 0) { - rxLen += ret; - pMsg += ret; - len -= ret; - } else if (ret == 0 || (ret != MBEDTLS_ERR_SSL_WANT_READ && ret != MBEDTLS_ERR_SSL_WANT_WRITE && ret != MBEDTLS_ERR_SSL_TIMEOUT)) { - return NETWORK_SSL_READ_ERROR; - } - - // Evaluate timeout after the read to make sure read is done at least once - if (has_timer_expired(timer)) { - break; - } - } - - if (len == 0) { - *read_len = rxLen; - return SUCCESS; - } - - if (rxLen == 0) { - return NETWORK_SSL_NOTHING_TO_READ; - } else { - return NETWORK_SSL_READ_TIMEOUT_ERROR; - } -} - -IoT_Error_t iot_tls_disconnect(Network *pNetwork) { - mbedtls_ssl_context *ssl = &(pNetwork->tlsDataParams.ssl); - int ret = 0; - do { - ret = mbedtls_ssl_close_notify(ssl); - } while(ret == MBEDTLS_ERR_SSL_WANT_WRITE); - - /* All other negative return values indicate connection needs to be reset. - * No further action required since this is disconnect call */ - - return SUCCESS; -} - -IoT_Error_t iot_tls_destroy(Network *pNetwork) { - TLSDataParams *tlsDataParams = &(pNetwork->tlsDataParams); - - mbedtls_net_free(&(tlsDataParams->server_fd)); - - mbedtls_x509_crt_free(&(tlsDataParams->clicert)); - mbedtls_x509_crt_free(&(tlsDataParams->cacert)); - mbedtls_pk_free(&(tlsDataParams->pkey)); - mbedtls_ssl_free(&(tlsDataParams->ssl)); - mbedtls_ssl_config_free(&(tlsDataParams->conf)); - mbedtls_ctr_drbg_free(&(tlsDataParams->ctr_drbg)); - mbedtls_entropy_free(&(tlsDataParams->entropy)); - - return SUCCESS; -} diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/port/threads_freertos.c b/examples/espidf-aws-iot/components/esp-aws-iot/port/threads_freertos.c deleted file mode 100644 index 065ead78c..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/port/threads_freertos.c +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * Additions Copyright 2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://aws.amazon.com/apache2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - - -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" - -#include "threads_platform.h" - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @brief Initialize the provided mutex - * - * Call this function to initialize the mutex - * - * @param IoT_Mutex_t - pointer to the mutex to be initialized - * @return IoT_Error_t - error code indicating result of operation - */ -IoT_Error_t aws_iot_thread_mutex_init(IoT_Mutex_t *pMutex) { - - pMutex->mutex = xSemaphoreCreateRecursiveMutex(); - return pMutex->mutex ? SUCCESS : MUTEX_INIT_ERROR; -} - -/** - * @brief Lock the provided mutex - * - * Call this function to lock the mutex before performing a state change - * Blocking, thread will block until lock request fails - * - * @param IoT_Mutex_t - pointer to the mutex to be locked - * @return IoT_Error_t - error code indicating result of operation - */ -IoT_Error_t aws_iot_thread_mutex_lock(IoT_Mutex_t *pMutex) { - xSemaphoreTakeRecursive(pMutex->mutex, portMAX_DELAY); - return SUCCESS; -} - -/** - * @brief Try to lock the provided mutex - * - * Call this function to attempt to lock the mutex before performing a state change - * Non-Blocking, immediately returns with failure if lock attempt fails - * - * @param IoT_Mutex_t - pointer to the mutex to be locked - * @return IoT_Error_t - error code indicating result of operation - */ -IoT_Error_t aws_iot_thread_mutex_trylock(IoT_Mutex_t *pMutex) { - if (xSemaphoreTakeRecursive(pMutex->mutex, 0)) { - return SUCCESS; - } else { - return MUTEX_LOCK_ERROR; - } -} - -/** - * @brief Unlock the provided mutex - * - * Call this function to unlock the mutex before performing a state change - * - * @param IoT_Mutex_t - pointer to the mutex to be unlocked - * @return IoT_Error_t - error code indicating result of operation - */ -IoT_Error_t aws_iot_thread_mutex_unlock(IoT_Mutex_t *pMutex) { - if (xSemaphoreGiveRecursive(pMutex->mutex)) { - return SUCCESS; - } else { - return MUTEX_UNLOCK_ERROR; - } -} - -/** - * @brief Destroy the provided mutex - * - * Call this function to destroy the mutex - * - * @param IoT_Mutex_t - pointer to the mutex to be destroyed - * @return IoT_Error_t - error code indicating result of operation - */ -IoT_Error_t aws_iot_thread_mutex_destroy(IoT_Mutex_t *pMutex) { - vSemaphoreDelete(pMutex->mutex); - return SUCCESS; -} - -#ifdef __cplusplus -} -#endif - diff --git a/examples/espidf-aws-iot/components/esp-aws-iot/port/timer.c b/examples/espidf-aws-iot/components/esp-aws-iot/port/timer.c deleted file mode 100644 index ee4d8b5be..000000000 --- a/examples/espidf-aws-iot/components/esp-aws-iot/port/timer.c +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * Additions Copyright 2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://aws.amazon.com/apache2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - -/** - * @file timer.c - * @brief FreeRTOS implementation of the timer interface uses ticks. - */ - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -#include "timer_platform.h" -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" -#include "esp_log.h" - -const static char *TAG = "aws_timer"; - -bool has_timer_expired(Timer *timer) { - uint32_t now = xTaskGetTickCount(); - bool expired = (now - timer->start_ticks) >= timer->timeout_ticks; - - /* AWS IoT SDK isn't very RTOS friendly because it polls for "done - timers" a lot without ever sleeping on them. So we hack in some - amount of sleeping here: if it seems like the caller is polling - an unexpired timer in a tight loop then we delay a tick to let - things progress elsewhere. - */ - if(!expired && now == timer->last_polled_ticks) { - vTaskDelay(1); - } - timer->last_polled_ticks = now; - return expired; -} - -void countdown_ms(Timer *timer, uint32_t timeout) { - timer->start_ticks = xTaskGetTickCount(); - timer->timeout_ticks = timeout / portTICK_PERIOD_MS; - timer->last_polled_ticks = 0; -} - -uint32_t left_ms(Timer *timer) { - uint32_t now = xTaskGetTickCount(); - uint32_t elapsed = now - timer->start_ticks; - if (elapsed < timer->timeout_ticks) { - return (timer->timeout_ticks - elapsed) * portTICK_PERIOD_MS; - } else { - return 0; - } -} - -void countdown_sec(Timer *timer, uint32_t timeout) { - if (timeout > UINT32_MAX / 1000) { - ESP_LOGE(TAG, "timeout is out of range: %ds", timeout); - } - countdown_ms(timer, timeout * 1000); -} - -void init_timer(Timer *timer) { - timer->start_ticks = 0; - timer->timeout_ticks = 0; - timer->last_polled_ticks = 0; -} - -#ifdef __cplusplus -} -#endif diff --git a/examples/espidf-aws-iot/include/README b/examples/espidf-aws-iot/include/README deleted file mode 100644 index 194dcd432..000000000 --- a/examples/espidf-aws-iot/include/README +++ /dev/null @@ -1,39 +0,0 @@ - -This directory is intended for project header files. - -A header file is a file containing C declarations and macro definitions -to be shared between several project source files. You request the use of a -header file in your project source file (C, C++, etc) located in `src` folder -by including it, with the C preprocessing directive `#include'. - -```src/main.c - -#include "header.h" - -int main (void) -{ - ... -} -``` - -Including a header file produces the same results as copying the header file -into each source file that needs it. Such copying would be time-consuming -and error-prone. With a header file, the related declarations appear -in only one place. If they need to be changed, they can be changed in one -place, and programs that include the header file will automatically use the -new version when next recompiled. The header file eliminates the labor of -finding and changing all the copies as well as the risk that a failure to -find one copy will result in inconsistencies within a program. - -In C, the usual convention is to give header files names that end with `.h'. -It is most portable to use only letters, digits, dashes, and underscores in -header file names, and at most one dot. - -Read more about using header files in official GCC documentation: - -* Include Syntax -* Include Operation -* Once-Only Headers -* Computed Includes - -https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html diff --git a/examples/espidf-aws-iot/lib/README b/examples/espidf-aws-iot/lib/README deleted file mode 100644 index 6debab1e8..000000000 --- a/examples/espidf-aws-iot/lib/README +++ /dev/null @@ -1,46 +0,0 @@ - -This directory is intended for project specific (private) libraries. -PlatformIO will compile them to static libraries and link into executable file. - -The source code of each library should be placed in a an own separate directory -("lib/your_library_name/[here are source files]"). - -For example, see a structure of the following two libraries `Foo` and `Bar`: - -|--lib -| | -| |--Bar -| | |--docs -| | |--examples -| | |--src -| | |- Bar.c -| | |- Bar.h -| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html -| | -| |--Foo -| | |- Foo.c -| | |- Foo.h -| | -| |- README --> THIS FILE -| -|- platformio.ini -|--src - |- main.c - -and a contents of `src/main.c`: -``` -#include -#include - -int main (void) -{ - ... -} - -``` - -PlatformIO Library Dependency Finder will find automatically dependent -libraries scanning project source files. - -More information about PlatformIO Library Dependency Finder -- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/examples/espidf-aws-iot/platformio.ini b/examples/espidf-aws-iot/platformio.ini deleted file mode 100644 index 5bf94f9d8..000000000 --- a/examples/espidf-aws-iot/platformio.ini +++ /dev/null @@ -1,26 +0,0 @@ -; PlatformIO Project Configuration File -; -; Build options: build flags, source filter, extra scripting -; Upload options: custom port, speed and extra flags -; Library options: dependencies, extra library storages -; -; Please visit documentation for the other options and examples -; https://docs.platformio.org/page/projectconf.html - -[env:esp32dev] -platform = espressif32 -framework = espidf -board = esp32dev -monitor_speed = 115200 -monitor_filters = colorize - -board_build.embed_txtfiles = - src/certs/private.pem.key - src/certs/certificate.pem.crt - src/certs/aws-root-ca.pem - -# IDF v5 is not supported by ASW-IoT SDK -# https://github.com/espressif/esp-aws-iot/blob/bbaf03d7d1fbf8a3f91dc18489d7bd27d5b9e9df/README.md?plain=1#L21 -platform_packages = - framework-espidf @ ~3.40403.0 - toolchain-xtensa-esp32 @ 8.4.0+2021r2-patch5 diff --git a/examples/espidf-aws-iot/sdkconfig.defaults b/examples/espidf-aws-iot/sdkconfig.defaults deleted file mode 100644 index b1a90483c..000000000 --- a/examples/espidf-aws-iot/sdkconfig.defaults +++ /dev/null @@ -1,13 +0,0 @@ -# Enable FATFS read only with long filename support -# for loading Cert/CA/etc from filesystem -# (if enabled in config) -CONFIG_FATFS_READONLY=y -CONFIG_FATFS_CODEPAGE_437=y -CONFIG_FATFS_LFN_HEAP=y - -# Enable TLS asymmetric in/out content length -CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN=y - -# Example configs -CONFIG_EXAMPLE_WIFI_SSID="MYSSID" -CONFIG_EXAMPLE_WIFI_PASSWORD="MYPASS" diff --git a/examples/espidf-aws-iot/src/CMakeLists.txt b/examples/espidf-aws-iot/src/CMakeLists.txt deleted file mode 100644 index 807ad6ea0..000000000 --- a/examples/espidf-aws-iot/src/CMakeLists.txt +++ /dev/null @@ -1,11 +0,0 @@ -set(COMPONENT_SRCS "subscribe_publish_sample.c") -set(COMPONENT_ADD_INCLUDEDIRS ".") - - -register_component() - -if(CONFIG_EXAMPLE_EMBEDDED_CERTS) -target_add_binary_data(${COMPONENT_TARGET} "certs/aws-root-ca.pem" TEXT) -target_add_binary_data(${COMPONENT_TARGET} "certs/certificate.pem.crt" TEXT) -target_add_binary_data(${COMPONENT_TARGET} "certs/private.pem.key" TEXT) -endif() diff --git a/examples/espidf-aws-iot/src/Kconfig.projbuild b/examples/espidf-aws-iot/src/Kconfig.projbuild deleted file mode 100644 index 96a022a5c..000000000 --- a/examples/espidf-aws-iot/src/Kconfig.projbuild +++ /dev/null @@ -1,60 +0,0 @@ -menu "Example Configuration" - - config WIFI_SSID - string "WiFi SSID" - default "myssid" - help - SSID (network name) for the example to connect to. - - config WIFI_PASSWORD - string "WiFi Password" - default "mypassword" - help - WiFi password (WPA or WPA2) for the example to use. - - Can be left blank if the network has no security set. - - config AWS_EXAMPLE_CLIENT_ID - string "AWS IoT Client ID" - default "myesp32" - help - AWS IoT Client ID for the example. Should be unique for every device. - - choice EXAMPLE_CERT_SOURCE - prompt "AWS IoT Certificate Source" - default EXAMPLE_EMBEDDED_CERTS - help - AWS IoT requires loading of a device-specific certificate and private key, - and a common Root CA Certificate. These can be compiled into the example - app, or they can be loaded via the filesystem from an SD card. - - config EXAMPLE_EMBEDDED_CERTS - bool "Embed into app" - config EXAMPLE_SDCARD_CERTS - bool "Load from SD card" - select EXAMPLE_FILESYSTEM_CERTS - endchoice - - # Currently this is equivalent to EXAMPLE_SDCARD_CERTS, - # however eventually we want to support more filesystem - # sources (SPIFFS, etc.) So this hidden config item - # is selected whenever the item should load from filesystem. - config EXAMPLE_FILESYSTEM_CERTS - bool - - config EXAMPLE_CERTIFICATE_PATH - string "Device Certificate Path" - depends on EXAMPLE_FILESYSTEM_CERTS - default "/sdcard/certificate.pem.crt" - - config EXAMPLE_PRIVATE_KEY_PATH - string "Device Private Key Path" - depends on EXAMPLE_FILESYSTEM_CERTS - default "/sdcard/private.pem.key" - - config EXAMPLE_ROOT_CA_PATH - string "Root CA Certificate Path" - depends on EXAMPLE_FILESYSTEM_CERTS - default "/sdcard/aws-root-ca.pem" - -endmenu diff --git a/examples/espidf-aws-iot/src/certs/README.md b/examples/espidf-aws-iot/src/certs/README.md deleted file mode 100644 index d445cc62b..000000000 --- a/examples/espidf-aws-iot/src/certs/README.md +++ /dev/null @@ -1,3 +0,0 @@ -Copy certificate files for AWS IoT SDK example here - -See README.md in main example directory for details. diff --git a/examples/espidf-aws-iot/src/certs/aws-root-ca.pem b/examples/espidf-aws-iot/src/certs/aws-root-ca.pem deleted file mode 100644 index a6f3e92af..000000000 --- a/examples/espidf-aws-iot/src/certs/aws-root-ca.pem +++ /dev/null @@ -1,20 +0,0 @@ ------BEGIN CERTIFICATE----- -MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF -ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 -b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL -MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv -b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj -ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM -9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw -IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6 -VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L -93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm -jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC -AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA -A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI -U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs -N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv -o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU -5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy -rqXRfboQnoZsG4q5WTP468SQvvG5 ------END CERTIFICATE----- diff --git a/examples/espidf-aws-iot/src/certs/certificate.pem.crt b/examples/espidf-aws-iot/src/certs/certificate.pem.crt deleted file mode 100644 index d831f6f16..000000000 --- a/examples/espidf-aws-iot/src/certs/certificate.pem.crt +++ /dev/null @@ -1,3 +0,0 @@ ------BEGIN CERTIFICATE----- -DUMMY CONTENT ------END CERTIFICATE----- \ No newline at end of file diff --git a/examples/espidf-aws-iot/src/certs/private.pem.key b/examples/espidf-aws-iot/src/certs/private.pem.key deleted file mode 100644 index d831f6f16..000000000 --- a/examples/espidf-aws-iot/src/certs/private.pem.key +++ /dev/null @@ -1,3 +0,0 @@ ------BEGIN CERTIFICATE----- -DUMMY CONTENT ------END CERTIFICATE----- \ No newline at end of file diff --git a/examples/espidf-aws-iot/src/subscribe_publish_sample.c b/examples/espidf-aws-iot/src/subscribe_publish_sample.c deleted file mode 100644 index 833261c86..000000000 --- a/examples/espidf-aws-iot/src/subscribe_publish_sample.c +++ /dev/null @@ -1,358 +0,0 @@ -/* - * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * Additions Copyright 2016 Espressif Systems (Shanghai) PTE LTD - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://aws.amazon.com/apache2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ -/** - * @file subscribe_publish_sample.c - * @brief simple MQTT publish and subscribe on the same topic - * - * This example takes the parameters from the build configuration and establishes a connection to the AWS IoT MQTT Platform. - * It subscribes and publishes to the same topic - "test_topic/esp32" - * - * Some setup is required. See example README for details. - * - */ -#include -#include -#include -#include -#include -#include - -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" -#include "freertos/event_groups.h" -#include "esp_system.h" -#include "esp_wifi.h" -#include "esp_event.h" -#include "esp_log.h" -#include "esp_vfs_fat.h" -#include "driver/sdmmc_host.h" - -#include "nvs.h" -#include "nvs_flash.h" - -#include "aws_iot_config.h" -#include "aws_iot_log.h" -#include "aws_iot_version.h" -#include "aws_iot_mqtt_client_interface.h" - -static const char *TAG = "subpub"; - -/* The examples use simple WiFi configuration that you can set via - 'make menuconfig'. - - If you'd rather not, just change the below entries to strings with - the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid" -*/ -#define EXAMPLE_WIFI_SSID CONFIG_WIFI_SSID -#define EXAMPLE_WIFI_PASS CONFIG_WIFI_PASSWORD - -/* FreeRTOS event group to signal when we are connected & ready to make a request */ -static EventGroupHandle_t wifi_event_group; - -/* The event group allows multiple bits for each event, - but we only care about one event - are we connected - to the AP with an IP? */ -const int CONNECTED_BIT = BIT0; - - -/* CA Root certificate, device ("Thing") certificate and device - * ("Thing") key. - - Example can be configured one of two ways: - - "Embedded Certs" are loaded from files in "certs/" and embedded into the app binary. - - "Filesystem Certs" are loaded from the filesystem (SD card, etc.) - - See example README for more details. -*/ -#if defined(CONFIG_EXAMPLE_EMBEDDED_CERTS) - -extern const uint8_t aws_root_ca_pem_start[] asm("_binary_aws_root_ca_pem_start"); -extern const uint8_t aws_root_ca_pem_end[] asm("_binary_aws_root_ca_pem_end"); -extern const uint8_t certificate_pem_crt_start[] asm("_binary_certificate_pem_crt_start"); -extern const uint8_t certificate_pem_crt_end[] asm("_binary_certificate_pem_crt_end"); -extern const uint8_t private_pem_key_start[] asm("_binary_private_pem_key_start"); -extern const uint8_t private_pem_key_end[] asm("_binary_private_pem_key_end"); - -#elif defined(CONFIG_EXAMPLE_FILESYSTEM_CERTS) - -static const char * DEVICE_CERTIFICATE_PATH = CONFIG_EXAMPLE_CERTIFICATE_PATH; -static const char * DEVICE_PRIVATE_KEY_PATH = CONFIG_EXAMPLE_PRIVATE_KEY_PATH; -static const char * ROOT_CA_PATH = CONFIG_EXAMPLE_ROOT_CA_PATH; - -#else -#error "Invalid method for loading certs" -#endif - -/** - * @brief Default MQTT HOST URL is pulled from the aws_iot_config.h - */ -char HostAddress[255] = AWS_IOT_MQTT_HOST; - -/** - * @brief Default MQTT port is pulled from the aws_iot_config.h - */ -uint32_t port = AWS_IOT_MQTT_PORT; - - -static void event_handler(void* handler_args, esp_event_base_t base, int32_t id, void* event_data) -{ - ESP_LOGI(TAG, "event_handler: %s:%d", base, id); - - if(base == WIFI_EVENT) { - switch(id) { - case WIFI_EVENT_STA_START: - esp_wifi_connect(); - break; - case WIFI_EVENT_STA_CONNECTED: - break; - case WIFI_EVENT_STA_DISCONNECTED: - /* This is a workaround as ESP32 WiFi libs don't currently - auto-reassociate. */ - esp_wifi_connect(); - xEventGroupClearBits(wifi_event_group, CONNECTED_BIT); - break; - default: - break; - } - } - else if(base == IP_EVENT) { - switch(id) { - case IP_EVENT_STA_GOT_IP: - { - ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data; - ESP_LOGI(TAG, "got ip:" IPSTR, IP2STR(&event->ip_info.ip)); - xEventGroupSetBits(wifi_event_group, CONNECTED_BIT); - } - } - } -} - -void iot_subscribe_callback_handler(AWS_IoT_Client *pClient, char *topicName, uint16_t topicNameLen, - IoT_Publish_Message_Params *params, void *pData) { - ESP_LOGI(TAG, "Subscribe callback"); - ESP_LOGI(TAG, "%.*s\t%.*s", topicNameLen, topicName, (int) params->payloadLen, (char *)params->payload); -} - -void disconnectCallbackHandler(AWS_IoT_Client *pClient, void *data) { - ESP_LOGW(TAG, "MQTT Disconnect"); - IoT_Error_t rc = FAILURE; - - if(NULL == pClient) { - return; - } - - if(aws_iot_is_autoreconnect_enabled(pClient)) { - ESP_LOGI(TAG, "Auto Reconnect is enabled, Reconnecting attempt will start now"); - } else { - ESP_LOGW(TAG, "Auto Reconnect not enabled. Starting manual reconnect..."); - rc = aws_iot_mqtt_attempt_reconnect(pClient); - if(NETWORK_RECONNECTED == rc) { - ESP_LOGW(TAG, "Manual Reconnect Successful"); - } else { - ESP_LOGW(TAG, "Manual Reconnect Failed - %d", rc); - } - } -} - -void aws_iot_task(void *param) { - char cPayload[100]; - - int32_t i = 0; - - IoT_Error_t rc = FAILURE; - - AWS_IoT_Client client; - IoT_Client_Init_Params mqttInitParams = iotClientInitParamsDefault; - IoT_Client_Connect_Params connectParams = iotClientConnectParamsDefault; - - IoT_Publish_Message_Params paramsQOS0; - IoT_Publish_Message_Params paramsQOS1; - - ESP_LOGI(TAG, "AWS IoT SDK Version %d.%d.%d-%s", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG); - - mqttInitParams.enableAutoReconnect = false; // We enable this later below - mqttInitParams.pHostURL = HostAddress; - mqttInitParams.port = port; - -#if defined(CONFIG_EXAMPLE_EMBEDDED_CERTS) - mqttInitParams.pRootCALocation = (char *)aws_root_ca_pem_start; - mqttInitParams.pDeviceCertLocation = (char *)certificate_pem_crt_start; - mqttInitParams.pDevicePrivateKeyLocation = (char *)private_pem_key_start; - -#elif defined(CONFIG_EXAMPLE_FILESYSTEM_CERTS) - mqttInitParams.pRootCALocation = ROOT_CA_PATH; - mqttInitParams.pDeviceCertLocation = DEVICE_CERTIFICATE_PATH; - mqttInitParams.pDevicePrivateKeyLocation = DEVICE_PRIVATE_KEY_PATH; -#endif - - mqttInitParams.mqttCommandTimeout_ms = 20000; - mqttInitParams.tlsHandshakeTimeout_ms = 5000; - mqttInitParams.isSSLHostnameVerify = true; - mqttInitParams.disconnectHandler = disconnectCallbackHandler; - mqttInitParams.disconnectHandlerData = NULL; - -#ifdef CONFIG_EXAMPLE_SDCARD_CERTS - ESP_LOGI(TAG, "Mounting SD card..."); - sdmmc_host_t host = SDMMC_HOST_DEFAULT(); - sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); - esp_vfs_fat_sdmmc_mount_config_t mount_config = { - .format_if_mount_failed = false, - .max_files = 3, - }; - sdmmc_card_t* card; - esp_err_t ret = esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, &card); - if (ret != ESP_OK) { - ESP_LOGE(TAG, "Failed to mount SD card VFAT filesystem. Error: %s", esp_err_to_name(ret)); - abort(); - } -#endif - - rc = aws_iot_mqtt_init(&client, &mqttInitParams); - if(SUCCESS != rc) { - ESP_LOGE(TAG, "aws_iot_mqtt_init returned error : %d ", rc); - abort(); - } - - /* Wait for WiFI to show as connected */ - xEventGroupWaitBits(wifi_event_group, CONNECTED_BIT, - false, true, portMAX_DELAY); - - connectParams.keepAliveIntervalInSec = 10; - connectParams.isCleanSession = true; - connectParams.MQTTVersion = MQTT_3_1_1; - /* Client ID is set in the menuconfig of the example */ - connectParams.pClientID = CONFIG_AWS_EXAMPLE_CLIENT_ID; - connectParams.clientIDLen = (uint16_t) strlen(CONFIG_AWS_EXAMPLE_CLIENT_ID); - connectParams.isWillMsgPresent = false; - - ESP_LOGI(TAG, "Connecting to AWS with client ID '%s'", connectParams.pClientID); - do { - rc = aws_iot_mqtt_connect(&client, &connectParams); - if(SUCCESS != rc) { - ESP_LOGE(TAG, "Error(%d) connecting to %s:%d", rc, mqttInitParams.pHostURL, mqttInitParams.port); - vTaskDelay(1000 / portTICK_RATE_MS); - } - } while(SUCCESS != rc); - - /* - * Enable Auto Reconnect functionality. Minimum and Maximum time of Exponential backoff are set in aws_iot_config.h - * #AWS_IOT_MQTT_MIN_RECONNECT_WAIT_INTERVAL - * #AWS_IOT_MQTT_MAX_RECONNECT_WAIT_INTERVAL - */ - rc = aws_iot_mqtt_autoreconnect_set_status(&client, true); - if(SUCCESS != rc) { - ESP_LOGE(TAG, "Unable to set Auto Reconnect to true - %d", rc); - abort(); - } - - const char *TOPIC = "test_topic/esp32"; - const int TOPIC_LEN = strlen(TOPIC); - - ESP_LOGI(TAG, "Subscribing..."); - rc = aws_iot_mqtt_subscribe(&client, TOPIC, TOPIC_LEN, QOS0, iot_subscribe_callback_handler, NULL); - if(SUCCESS != rc) { - ESP_LOGE(TAG, "Error subscribing : %d ", rc); - abort(); - } - - sprintf(cPayload, "%s : %d ", "hello from SDK", i); - - paramsQOS0.qos = QOS0; - paramsQOS0.payload = (void *) cPayload; - paramsQOS0.isRetained = 0; - - paramsQOS1.qos = QOS1; - paramsQOS1.payload = (void *) cPayload; - paramsQOS1.isRetained = 0; - - while((NETWORK_ATTEMPTING_RECONNECT == rc || NETWORK_RECONNECTED == rc || SUCCESS == rc)) { - - //Max time the yield function will wait for read messages - rc = aws_iot_mqtt_yield(&client, 100); - if(NETWORK_ATTEMPTING_RECONNECT == rc) { - // If the client is attempting to reconnect we will skip the rest of the loop. - continue; - } - - ESP_LOGI(TAG, "Stack remaining for task '%s' is %d bytes", pcTaskGetTaskName(NULL), uxTaskGetStackHighWaterMark(NULL)); - vTaskDelay(1000 / portTICK_RATE_MS); - sprintf(cPayload, "%s : %d ", "hello from ESP32 (QOS0)", i++); - paramsQOS0.payloadLen = strlen(cPayload); - rc = aws_iot_mqtt_publish(&client, TOPIC, TOPIC_LEN, ¶msQOS0); - - sprintf(cPayload, "%s : %d ", "hello from ESP32 (QOS1)", i++); - paramsQOS1.payloadLen = strlen(cPayload); - rc = aws_iot_mqtt_publish(&client, TOPIC, TOPIC_LEN, ¶msQOS1); - if (rc == MQTT_REQUEST_TIMEOUT_ERROR) { - ESP_LOGW(TAG, "QOS1 publish ack not received."); - rc = SUCCESS; - } - } - - ESP_LOGE(TAG, "An error occurred in the main loop."); - abort(); -} - -static void initialise_wifi(void) -{ - wifi_event_group = xEventGroupCreate(); - ESP_ERROR_CHECK(esp_netif_init()); - - ESP_ERROR_CHECK(esp_event_loop_create_default()); - esp_netif_create_default_wifi_sta(); - - ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, - ESP_EVENT_ANY_ID, - &event_handler, - NULL, - NULL)); - ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, - IP_EVENT_STA_GOT_IP, - &event_handler, - NULL, - NULL)); - - wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT(); - ESP_ERROR_CHECK( esp_wifi_init(&cfg) ); - ESP_ERROR_CHECK( esp_wifi_set_storage(WIFI_STORAGE_RAM) ); - wifi_config_t wifi_config = { - .sta = { - .ssid = EXAMPLE_WIFI_SSID, - .password = EXAMPLE_WIFI_PASS, - }, - }; - ESP_LOGI(TAG, "Setting WiFi configuration SSID %s...", wifi_config.sta.ssid); - ESP_ERROR_CHECK( esp_wifi_set_mode(WIFI_MODE_STA) ); - ESP_ERROR_CHECK( esp_wifi_set_config(WIFI_IF_STA, &wifi_config) ); - ESP_ERROR_CHECK( esp_wifi_start() ); -} - - -void app_main() -{ - // Initialize NVS. - esp_err_t err = nvs_flash_init(); - if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) { - ESP_ERROR_CHECK(nvs_flash_erase()); - err = nvs_flash_init(); - } - ESP_ERROR_CHECK( err ); - - initialise_wifi(); - xTaskCreatePinnedToCore(&aws_iot_task, "aws_iot_task", 9216, NULL, 5, NULL, 1); -} diff --git a/examples/espidf-aws-iot/test/README b/examples/espidf-aws-iot/test/README deleted file mode 100644 index df5066e64..000000000 --- a/examples/espidf-aws-iot/test/README +++ /dev/null @@ -1,11 +0,0 @@ - -This directory is intended for PIO Unit Testing and project tests. - -Unit Testing is a software testing method by which individual units of -source code, sets of one or more MCU program modules together with associated -control data, usage procedures, and operating procedures, are tested to -determine whether they are fit for use. Unit testing finds problems early -in the development cycle. - -More information about PIO Unit Testing: -- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/monitor/filter_exception_decoder.py b/monitor/filter_exception_decoder.py index 5a646e838..d0f4a39b3 100644 --- a/monitor/filter_exception_decoder.py +++ b/monitor/filter_exception_decoder.py @@ -32,8 +32,9 @@ class Esp32ExceptionDecoder(DeviceMonitorFilterBase): NAME = "esp32_exception_decoder" - BACKTRACE_PATTERN = re.compile(r"^Backtrace:(((\s?0x[0-9a-fA-F]{8}:0x[0-9a-fA-F]{8}))+)") - BACKTRACE_ADDRESS_PATTERN = re.compile(r'0x[0-9a-fA-F]{8}:0x[0-9a-fA-F]{8}') + ADDR_PATTERN = re.compile(r"((?:0x[0-9a-fA-F]{8}[: ]?)+)\s?$") + ADDR_SPLIT = re.compile(r"[ :]") + PREFIX_RE = re.compile(r"^ *") def __call__(self): self.buffer = "" @@ -56,7 +57,8 @@ def __call__(self): def setup_paths(self): self.project_dir = os.path.abspath(self.project_dir) try: - data = load_build_metadata(self.project_dir, self.environment) + data = load_build_metadata(self.project_dir, self.environment, cache=True) + self.firmware_path = data["prog_path"] if not os.path.isfile(self.firmware_path): sys.stderr.write( @@ -100,38 +102,65 @@ def rx(self, text): self.buffer = "" last = idx + 1 - m = self.BACKTRACE_PATTERN.match(line) + m = self.ADDR_PATTERN.search(line) if m is None: continue - trace = self.get_backtrace(m) - if len(trace) != "": + trace = self.build_backtrace(line, m.group(1)) + if trace: text = text[: idx + 1] + trace + text[idx + 1 :] last += len(trace) return text - def get_backtrace(self, match): - trace = "\n" + def is_address_ignored(self, address): + return address in ("", "0x00000000") + + def filter_addresses(self, adresses_str): + addresses = self.ADDR_SPLIT.split(adresses_str) + size = len(addresses) + while size > 1 and self.is_address_ignored(addresses[size-1]): + size -= 1 + return addresses[:size] + + def build_backtrace(self, line, address_match): + addresses = self.filter_addresses(address_match) + if not addresses: + return "" + + prefix_match = self.PREFIX_RE.match(line) + prefix = prefix_match.group(0) if prefix_match is not None else "" + + trace = "" enc = "mbcs" if IS_WINDOWS else "utf-8" args = [self.addr2line_path, u"-fipC", u"-e", self.firmware_path] try: - for i, addr in enumerate(self.BACKTRACE_ADDRESS_PATTERN.findall(match.group(1))): + i = 0 + for addr in addresses: output = ( subprocess.check_output(args + [addr]) .decode(enc) .strip() ) + + # newlines happen with inlined methods output = output.replace( "\n", "\n " - ) # newlines happen with inlined methods + ) + + # throw out addresses not from ELF + if output == "?? ??:0": + continue + output = self.strip_project_dir(output) - trace += " #%-2d %s in %s\n" % (i, addr, output) + trace += "%s #%-2d %s in %s\n" % (prefix, i, addr, output) + i += 1 except subprocess.CalledProcessError as e: sys.stderr.write( "%s: failed to call %s: %s\n" % (self.__class__.__name__, self.addr2line_path, e) ) - return trace + + return trace + "\n" if trace else "" def strip_project_dir(self, trace): while True: diff --git a/platform.json b/platform.json index d14261467..e425a7def 100644 --- a/platform.json +++ b/platform.json @@ -18,7 +18,7 @@ "type": "git", "url": "https://github.com/platformio/platform-espressif32.git" }, - "version": "6.6.0", + "version": "6.7.0", "frameworks": { "arduino": { "package": "framework-arduinoespressif32", @@ -33,22 +33,19 @@ "toolchain-xtensa-esp32": { "type": "toolchain", "owner": "espressif", - "version": "8.4.0+2021r2-patch5", - "optionalVersions": ["12.2.0+20230208"] + "version": "8.4.0+2021r2-patch5" }, "toolchain-xtensa-esp32s2": { "type": "toolchain", "optional": true, "owner": "espressif", - "version": "8.4.0+2021r2-patch5", - "optionalVersions": ["12.2.0+20230208"] + "version": "8.4.0+2021r2-patch5" }, "toolchain-xtensa-esp32s3": { "type": "toolchain", "optional": true, "owner": "espressif", - "version": "8.4.0+2021r2-patch5", - "optionalVersions": ["12.2.0+20230208"] + "version": "8.4.0+2021r2-patch5" }, "toolchain-riscv32-esp": { "type": "toolchain", @@ -57,6 +54,12 @@ "version": "8.4.0+2021r2-patch5", "optionalVersions": ["13.2.0+20230928"] }, + "toolchain-xtensa-esp-elf": { + "type": "toolchain", + "optional": true, + "owner": "platformio", + "version": "13.2.0+20230928" + }, "toolchain-esp32ulp": { "type": "toolchain", "optional": true, @@ -79,14 +82,14 @@ "type": "framework", "optional": true, "owner": "platformio", - "version": "~3.20014.0" + "version": "~3.20016.0" }, "framework-espidf": { "type": "framework", "optional": true, "owner": "platformio", "version": "~3.50201.0", - "optionalVersions": ["~3.40406.0"] + "optionalVersions": ["~3.40407.0"] }, "tool-esptoolpy": { "type": "uploader", diff --git a/platform.py b/platform.py index 54629c4f3..e0537875e 100644 --- a/platform.py +++ b/platform.py @@ -113,34 +113,42 @@ def configure_default_packages(self, variables, targets): if "arduino" in frameworks: # Downgrade the IDF version for mixed Arduino+IDF projects - self.packages["framework-espidf"]["version"] = "~3.40406.0" + self.packages["framework-espidf"]["version"] = "~3.40407.0" + # Delete the latest toolchain packages from config + self.packages.pop("toolchain-xtensa-esp-elf", None) else: - # Use the latest toolchains available for IDF v5.0 + # Disable old toolchain packages and use the latest + # available for IDF v5.0 for target in ( "xtensa-esp32", "xtensa-esp32s2", "xtensa-esp32s3", - "riscv32-esp", ): - self.packages["toolchain-%s" % target]["version"] = ( - "13.2.0+20230928" - if target == "riscv32-esp" - else "12.2.0+20230208" - ) - if target == "riscv32-esp": - # Pull the latest RISC-V toolchain from PlatformIO organization - self.packages["toolchain-%s" % target]["owner"] = "platformio" + self.packages.pop("toolchain-%s" % target, None) + + if mcu in ("esp32c3", "esp32c6"): + self.packages.pop("toolchain-xtensa-esp-elf", None) + else: + self.packages["toolchain-xtensa-esp-elf"][ + "optional" + ] = False + + # Pull the latest RISC-V toolchain from PlatformIO organization + self.packages["toolchain-riscv32-esp"]["owner"] = "platformio" + self.packages["toolchain-riscv32-esp"][ + "version" + ] = "13.2.0+20230928" if "arduino" in frameworks: # Disable standalone GDB packages for Arduino and Arduino/IDF projects for gdb_package in ("tool-xtensa-esp-elf-gdb", "tool-riscv32-esp-elf-gdb"): self.packages.pop(gdb_package, None) - for available_mcu in ("esp32", "esp32s2", "esp32s3"): - if available_mcu == mcu: - self.packages["toolchain-xtensa-%s" % mcu]["optional"] = False - else: - self.packages.pop("toolchain-xtensa-%s" % available_mcu, None) + for available_mcu in ("esp32", "esp32s2", "esp32s3"): + if available_mcu == mcu: + self.packages["toolchain-xtensa-%s" % mcu]["optional"] = False + else: + self.packages.pop("toolchain-xtensa-%s" % available_mcu, None) if mcu in ("esp32s2", "esp32s3", "esp32c3", "esp32c6"): # RISC-V based toolchain for ESP32C3, ESP32C6 ESP32S2, ESP32S3 ULP