├── .github └── workflows │ ├── issue_comment.yml │ ├── new_issues.yml │ └── new_prs.yml ├── .gitignore ├── .gitlab-ci.yml ├── .gitmodules ├── LICENSE ├── MigrationGuide.md ├── README.md ├── examples ├── README.md ├── fleet_provisioning │ └── fleet_provisioning_with_csr │ │ ├── CMakeLists.txt │ │ ├── README.md │ │ ├── example_claim_policy.json │ │ ├── main │ │ ├── CMakeLists.txt │ │ ├── Kconfig.projbuild │ │ ├── app_main.c │ │ ├── demo_config.h │ │ ├── fleet_provisioning_serializer.c │ │ ├── fleet_provisioning_serializer.h │ │ ├── fleet_provisioning_with_csr_demo.c │ │ ├── idf_component.yml │ │ ├── mbedtls_pkcs11_posix.c │ │ ├── mbedtls_pkcs11_posix.h │ │ ├── mqtt_operations.c │ │ ├── mqtt_operations.h │ │ ├── pkcs11_operations.c │ │ └── pkcs11_operations.h │ │ ├── partitions.csv │ │ ├── sdkconfig.defaults │ │ └── spiffs_image │ │ └── certs │ │ ├── AmazonRootCA1.crt │ │ ├── claim_cert.crt │ │ └── claim_private.key ├── http │ └── http_mutual_auth │ │ ├── CMakeLists.txt │ │ ├── main │ │ ├── CMakeLists.txt │ │ ├── Kconfig.projbuild │ │ ├── app_main.c │ │ ├── certs │ │ │ ├── client.crt │ │ │ ├── client.key │ │ │ └── root_cert_auth.crt │ │ ├── demo_config.h │ │ ├── http_demo_mutual_auth.c │ │ ├── http_demo_utils.c │ │ ├── http_demo_utils.h │ │ └── idf_component.yml │ │ ├── partitions.csv │ │ └── sdkconfig.defaults ├── jobs │ ├── CMakeLists.txt │ ├── main │ │ ├── CMakeLists.txt │ │ ├── JobsDemoExample.c │ │ ├── Kconfig.projbuild │ │ ├── app_main.c │ │ ├── certs │ │ │ ├── client.crt │ │ │ ├── client.key │ │ │ └── root_cert_auth.crt │ │ ├── demo_config.h │ │ ├── idf_component.yml │ │ ├── mqtt_demo_helpers.c │ │ └── mqtt_demo_helpers.h │ ├── partitions.csv │ └── sdkconfig.defaults ├── mqtt │ └── tls_mutual_auth │ │ ├── CMakeLists.txt │ │ ├── README.md │ │ ├── main │ │ ├── CMakeLists.txt │ │ ├── Kconfig.projbuild │ │ ├── app_main.c │ │ ├── certs │ │ │ ├── client.crt │ │ │ ├── client.key │ │ │ └── root_cert_auth.crt │ │ ├── demo_config.h │ │ ├── idf_component.yml │ │ └── mqtt_demo_mutual_auth.c │ │ ├── partitions.csv │ │ └── sdkconfig.defaults ├── ota │ └── README.md └── thing_shadow │ ├── CMakeLists.txt │ ├── README.md │ ├── main │ ├── CMakeLists.txt │ ├── Kconfig.projbuild │ ├── app_main.c │ ├── certs │ │ ├── client.crt │ │ ├── client.key │ │ └── root_cert_auth.crt │ ├── demo_config.h │ ├── idf_component.yml │ ├── shadow_demo_helpers.c │ ├── shadow_demo_helpers.h │ └── shadow_demo_main.c │ ├── partitions.csv │ └── sdkconfig.defaults └── libraries ├── Device-Defender-for-AWS-IoT-embedded-sdk ├── CMakeLists.txt ├── Kconfig └── config │ └── defender_config.h ├── Device-Shadow-for-AWS-IoT-embedded-sdk ├── CMakeLists.txt ├── Kconfig └── config │ └── shadow_config.h ├── Fleet-Provisioning-for-AWS-IoT-embedded-sdk ├── CMakeLists.txt ├── Kconfig └── config │ └── fleet_provisioning_config.h ├── Jobs-for-AWS-IoT-embedded-sdk └── CMakeLists.txt ├── aws-iot-core-mqtt-file-streams-embedded-c ├── CMakeLists.txt ├── Kconfig ├── config │ └── ota_config.h └── port │ ├── aws_esp_ota_ops.c │ ├── aws_esp_ota_ops.h │ ├── ota_os_freertos.c │ ├── ota_os_freertos.h │ ├── ota_pal.c │ └── ota_pal.h ├── backoffAlgorithm └── CMakeLists.txt ├── common ├── logging │ ├── logging_levels.h │ └── logging_stack.h └── posix_compat │ ├── CMakeLists.txt │ ├── clock.h │ ├── clock_esp.c │ ├── semaphore.c │ └── semaphore.h ├── coreHTTP ├── CMakeLists.txt ├── Kconfig ├── config │ └── core_http_config.h └── port │ └── network_transport │ ├── network_transport.c │ └── network_transport.h ├── coreJSON └── CMakeLists.txt ├── coreMQTT-Agent ├── CMakeLists.txt ├── Kconfig ├── config │ └── core_mqtt_agent_config.h └── port │ ├── freertos_agent_message.c │ ├── freertos_agent_message.h │ ├── freertos_command_pool.c │ └── freertos_command_pool.h ├── coreMQTT ├── CMakeLists.txt ├── Kconfig ├── config │ └── core_mqtt_config.h └── port │ └── network_transport │ ├── network_transport.c │ └── network_transport.h └── corePKCS11 ├── CMakeLists.txt ├── Kconfig ├── config └── core_pkcs11_config.h └── port ├── core_pkcs11_pal.c ├── iot_crypto.c └── iot_crypto.h /.github/workflows/issue_comment.yml: -------------------------------------------------------------------------------- 1 | name: Sync issue comments to JIRA 2 | 3 | # This workflow will be triggered when new issue comment is created (including PR comments) 4 | on: issue_comment 5 | 6 | jobs: 7 | sync_issue_comments_to_jira: 8 | name: Sync Issue Comments to Jira 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@master 12 | - name: Sync issue comments to JIRA 13 | uses: espressif/github-actions/sync_issues_to_jira@master 14 | env: 15 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 16 | JIRA_PASS: ${{ secrets.JIRA_PASS }} 17 | JIRA_PROJECT: CA 18 | JIRA_URL: ${{ secrets.JIRA_URL }} 19 | JIRA_USER: ${{ secrets.JIRA_USER }} 20 | -------------------------------------------------------------------------------- /.github/workflows/new_issues.yml: -------------------------------------------------------------------------------- 1 | name: Sync issues to Jira 2 | 3 | # This workflow will be triggered when a new issue is opened 4 | on: issues 5 | 6 | jobs: 7 | sync_issues_to_jira: 8 | name: Sync issues to Jira 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@master 12 | - name: Sync GitHub issues to Jira project 13 | uses: espressif/github-actions/sync_issues_to_jira@master 14 | env: 15 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 16 | JIRA_PASS: ${{ secrets.JIRA_PASS }} 17 | JIRA_PROJECT: CA 18 | JIRA_URL: ${{ secrets.JIRA_URL }} 19 | JIRA_USER: ${{ secrets.JIRA_USER }} 20 | -------------------------------------------------------------------------------- /.github/workflows/new_prs.yml: -------------------------------------------------------------------------------- 1 | name: Sync remain PRs to Jira 2 | 3 | # This workflow will be triggered every hour, to sync remaining PRs (i.e. PRs with zero comment) to Jira project 4 | # Note that, PRs can also get synced when new PR comment is created 5 | on: 6 | schedule: 7 | - cron: "0 * * * *" 8 | 9 | jobs: 10 | sync_prs_to_jira: 11 | name: Sync PRs to Jira 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@master 15 | - name: Sync PRs to Jira project 16 | uses: espressif/github-actions/sync_issues_to_jira@master 17 | with: 18 | cron_job: true 19 | env: 20 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 21 | JIRA_PASS: ${{ secrets.JIRA_PASS }} 22 | JIRA_PROJECT: CA 23 | JIRA_URL: ${{ secrets.JIRA_URL }} 24 | JIRA_USER: ${{ secrets.JIRA_USER }} 25 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.o 2 | 3 | # Example project files 4 | examples/**/sdkconfig 5 | examples/**/sdkconfig.old 6 | examples/**/build 7 | examples/**/managed_components 8 | 9 | **/.DS_Store -------------------------------------------------------------------------------- /.gitlab-ci.yml: -------------------------------------------------------------------------------- 1 | stages: 2 | - build 3 | 4 | variables: 5 | V: "0" 6 | MAKEFLAGS: "-j8 --no-keep-going" 7 | GIT_SUBMODULE_STRATEGY: recursive 8 | 9 | before_script: 10 | # add gitlab ssh key 11 | - mkdir -p ~/.ssh 12 | - chmod 700 ~/.ssh 13 | - echo -n $GITLAB_KEY > ~/.ssh/id_rsa_base64 14 | - base64 --decode --ignore-garbage ~/.ssh/id_rsa_base64 > ~/.ssh/id_rsa 15 | - chmod 600 ~/.ssh/id_rsa 16 | - echo -e "Host gitlab.espressif.cn\n\tStrictHostKeyChecking no\n" >> ~/.ssh/config 17 | # Create esp-rainmaker-bins-${CI_JOB_ID}/ dir (to copy binaries into for artifacts) 18 | - mkdir -p $CI_PROJECT_DIR/esp-rainmaker-bins-${CI_JOB_ID} 19 | 20 | .build_all_examples: &build_all_examples 21 | - pip install --upgrade idf-component-manager 22 | - for EXAMPLE in $EXAMPLES; do 23 | - cd $CI_PROJECT_DIR/examples/$EXAMPLE 24 | - echo Building $EXAMPLE 25 | - for TARGET in $EXAMPLE_TARGETS; do 26 | - echo Building for $TARGET 27 | - idf.py set-target $TARGET 28 | - idf.py build 29 | - done 30 | - echo Build Complete for $EXAMPLE 31 | - done 32 | 33 | .build_template: 34 | stage: build 35 | image: espressif/idf:latest 36 | tags: 37 | - build 38 | variables: 39 | PEDANTIC_FLAGS: "-Werror=deprecated-declarations -Wno-error=cpp" 40 | EXTRA_CFLAGS: "${PEDANTIC_FLAGS}" 41 | EXTRA_CXXFLAGS: "${PEDANTIC_FLAGS}" 42 | EXAMPLE_TARGETS: "esp32" 43 | EXAMPLES: "mqtt/tls_mutual_auth http/http_mutual_auth jobs mqtt/tls_mutual_auth ota/ota_mqtt ota/ota_http thing_shadow fleet_provisioning/fleet_provisioning_with_csr" 44 | script: 45 | - *build_all_examples 46 | 47 | build_idf_v4.3: 48 | extends: .build_template 49 | image: espressif/idf:release-v4.3 50 | variables: 51 | EXAMPLE_TARGETS: "esp32 esp32s2 esp32c3" 52 | 53 | build_idf_v4.4: 54 | extends: .build_template 55 | image: espressif/idf:release-v4.4 56 | variables: 57 | EXAMPLE_TARGETS: "esp32 esp32s2 esp32c3 esp32s3" 58 | 59 | build_idf_v5.0: 60 | extends: .build_template 61 | image: espressif/idf:release-v5.0 62 | variables: 63 | EXAMPLE_TARGETS: "esp32 esp32s2 esp32c3 esp32s3 esp32c2" 64 | 65 | build_idf_v5.1: 66 | extends: .build_template 67 | image: espressif/idf:release-v5.1 68 | variables: 69 | EXAMPLE_TARGETS: "esp32 esp32c3 esp32s3 esp32c2 esp32c6" 70 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "libraries/coreMQTT/coreMQTT"] 2 | path = libraries/coreMQTT/coreMQTT 3 | url = https://github.com/FreeRTOS/coreMQTT.git 4 | [submodule "libraries/coreMQTT-Agent/coreMQTT-Agent"] 5 | path = libraries/coreMQTT-Agent/coreMQTT-Agent 6 | url = https://github.com/FreeRTOS/coreMQTT-Agent.git 7 | [submodule "libraries/Device-Shadow-for-AWS-IoT-embedded-sdk/Device-Shadow-for-AWS-IoT-embedded-sdk"] 8 | path = libraries/Device-Shadow-for-AWS-IoT-embedded-sdk/Device-Shadow-for-AWS-IoT-embedded-sdk 9 | url = https://github.com/aws/Device-Shadow-for-AWS-IoT-embedded-sdk.git 10 | [submodule "libraries/backoffAlgorithm/backoffAlgorithm"] 11 | path = libraries/backoffAlgorithm/backoffAlgorithm 12 | url = https://github.com/FreeRTOS/backoffAlgorithm.git 13 | [submodule "libraries/Device-Defender-for-AWS-IoT-embedded-sdk/Device-Defender-for-AWS-IoT-embedded-sdk"] 14 | path = libraries/Device-Defender-for-AWS-IoT-embedded-sdk/Device-Defender-for-AWS-IoT-embedded-sdk 15 | url = https://github.com/aws/Device-Defender-for-AWS-IoT-embedded-sdk.git 16 | [submodule "libraries/coreJSON/coreJSON"] 17 | path = libraries/coreJSON/coreJSON 18 | url = https://github.com/FreeRTOS/coreJSON.git 19 | [submodule "libraries/corePKCS11/corePKCS11"] 20 | path = libraries/corePKCS11/corePKCS11 21 | url = https://github.com/FreeRTOS/corePKCS11.git 22 | [submodule "libraries/coreHTTP/coreHTTP"] 23 | path = libraries/coreHTTP/coreHTTP 24 | url = https://github.com/FreeRTOS/coreHTTP.git 25 | [submodule "libraries/Jobs-for-AWS-IoT-embedded-sdk/Jobs-for-AWS-IoT-embedded-sdk"] 26 | path = libraries/Jobs-for-AWS-IoT-embedded-sdk/Jobs-for-AWS-IoT-embedded-sdk 27 | url = https://github.com/aws/Jobs-for-AWS-IoT-embedded-sdk.git 28 | [submodule "libraries/Fleet-Provisioning-for-AWS-IoT-embedded-sdk/Fleet-Provisioning-for-AWS-IoT-embedded-sdk"] 29 | path = libraries/Fleet-Provisioning-for-AWS-IoT-embedded-sdk/Fleet-Provisioning-for-AWS-IoT-embedded-sdk 30 | url = https://github.com/aws/Fleet-Provisioning-for-AWS-IoT-embedded-sdk 31 | [submodule "libraries/aws-iot-core-mqtt-file-streams-embedded-c/aws-iot-core-mqtt-file-streams-embedded-c"] 32 | path = libraries/aws-iot-core-mqtt-file-streams-embedded-c/aws-iot-core-mqtt-file-streams-embedded-c 33 | url = https://github.com/aws/aws-iot-core-mqtt-file-streams-embedded-c 34 | -------------------------------------------------------------------------------- /MigrationGuide.md: -------------------------------------------------------------------------------- 1 | # Migration Guide for esp-aws-iot Releases 2 | 3 | ## esp-aws-iot Release 202012.04-LTS to esp-aws-iot Release 202210.01-LTS 4 | 5 | 1. Change in `NetworkContext` struct 6 | 7 | - "Pem" has been removed from member names, the new member names are as follows: `pcServerRootCA`, `pcClientCert`, `pcClientKey`. 8 | - `pcServerRootCASize`, `pcClientCertSize`, `pcClientKeySize` members have been added. 9 | - It is now required to set these `*Size` members in addition to the pointers to the certificates. 10 | 11 | **Example:** 12 | 13 | **Old Code Snippet**: 14 | ```c 15 | pNetworkContext->pcClientCertPem = client_cert_pem_start; 16 | ``` 17 | 18 | **New Code Snippet**: 19 | ```c 20 | pNetworkContext->pcClientCert = client_cert_start; 21 | pNetworkContext->pcClientCertSize = client_cert_end - client_cert_start; 22 | ``` 23 | 24 | 2. This releases includes a version >=v2.0.0 of the `coreMQTT` library. 25 | Please refer to the [coreMQTT Migration Guide](https://github.com/FreeRTOS/coreMQTT/blob/main/MigrationGuide.md) for more details. 26 | 27 | 3. The `*_USE_DS_PERIPHERAL` and `*_USE_SECURE_ELEMENT` config options have been removed and no longer need to be set while using `coreMQTT` and `coreHTTP` libraries. 28 | -------------------------------------------------------------------------------- /examples/README.md: -------------------------------------------------------------------------------- 1 | # Amazon Web Services IoT Examples 2 | 3 | These examples are adaptations of some of the [AWS IoT C SDK](https://github.com/aws/aws-iot-device-sdk-embedded-C) examples. 4 | 5 | The provisioning/configuration steps for these examples are the same, and are given in this README. 6 | 7 | This README also contains some troubleshooting information for common problems found when connecting to AWS IoT. 8 | 9 | # Provisioning/Configuration 10 | 11 | There are some additional steps that need to be run before you can build this example. 12 | 13 | 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. 14 | 15 | 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: 16 | 17 | # Authentication (Based on X.509 certificates) 18 | 19 | ### Device Authentication 20 | 21 | 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. 22 | 23 | ### Server Authentication 24 | 25 | 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 26 | 27 | ## Configuring Your Device 28 | 29 | ### Installing Private Key & Certificate 30 | 31 | 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. 32 | 33 | There is currently only one option for how to load the key & cert. 34 | 35 | * Embed the files into the app binary (default) 36 | 37 | ### Embedded Key & Cert into App Binary 38 | 39 | 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 `client.key` and `client.crt`. 40 | 41 | 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. 42 | 43 | # Troubleshooting 44 | 45 | ## Tips 46 | 47 | * Raise the ESP debug log level to Debug in order to see messages about the connection to AWS, certificate contents, etc. 48 | 49 | * Enable mbedTLS debugging (under Components -> mbedTLS -> mbedTLS Debug) in order to see even more low-level debug output from the mbedTLS layer. 50 | 51 | * To create a successful AWS IoT connection, the following factors must all be present: 52 | - Endpoint hostname is correct for your AWS account. 53 | - Certificate & private key are both attached to correct Thing in AWS IoT Console. 54 | - Certificate is activated. 55 | - Policy is attached to the Certificate in AWS IoT Console. 56 | - Policy contains sufficient permissions to authorize AWS IoT connection. 57 | 58 | ## TLS connection fails 59 | 60 | If connecting fails entirely (handshake doesn't complete), this usually indicates a problem with certification configuration. The error usually looks like this: 61 | 62 | ``` 63 | failed! mbedtls_ssl_handshake returned -0x7780 64 | ``` 65 | 66 | (0x7780 is the mbedTLS error code when the server sends an alert message and closes the connection.) 67 | 68 | * 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: 69 | - To find the Certificate directly, click on "Registry" -> "Security Certificates". Then click on the Certificate itself to view it. 70 | - 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. 71 | 72 | Verify the Certificate is activated (when viewing the Certificate, it will say "ACTIVE" or "INACTIVE" near the top under the certificate name). 73 | 74 | If the Certificate appears correct and activated, verify that you are connecting to the correct AWS IoT endpoint (see above.) 75 | 76 | ## TLS connection closes immediately 77 | 78 | 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. 79 | 80 | 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). 81 | 82 | In the subscribe_publish example, the error may look like this in the log: 83 | 84 | ``` 85 | MQTT_DEMO: Error(-28) connecting to (endpoint)... 86 | ``` 87 | 88 | In the thing_shadow example, the error may look like this in the log: 89 | 90 | ``` 91 | ShadowDemo: aws_iot_shadow_connect returned error -28, aborting... 92 | ``` 93 | 94 | This error implies the Certificate is recognised, but the Certificate is either missing the correct Thing or the correct Policy attached to it. 95 | 96 | * 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. 97 | -------------------------------------------------------------------------------- /examples/fleet_provisioning/fleet_provisioning_with_csr/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # The following five lines of boilerplate have to be in your project's 2 | # CMakeLists in this exact order for cmake to work correctly 3 | cmake_minimum_required(VERSION 3.5) 4 | 5 | set(EXTRA_COMPONENT_DIRS "$ENV{IDF_PATH}/examples/common_components/protocol_examples_common" 6 | "${CMAKE_CURRENT_LIST_DIR}/../../../libraries/backoffAlgorithm" 7 | "${CMAKE_CURRENT_LIST_DIR}/../../../libraries/coreMQTT" 8 | "${CMAKE_CURRENT_LIST_DIR}/../../../libraries/corePKCS11" 9 | "${CMAKE_CURRENT_LIST_DIR}/../../../libraries/Fleet-Provisioning-for-AWS-IoT-embedded-sdk" 10 | "${CMAKE_CURRENT_LIST_DIR}/../../../libraries/common/posix_compat" 11 | ) 12 | 13 | include($ENV{IDF_PATH}/tools/cmake/project.cmake) 14 | project(fleet_provisioning_with_csr) 15 | 16 | # Create a SPIFFS image from the contents of the 'spiffs_image' directory 17 | # that fits the partition named 'storage'. FLASH_IN_PROJECT indicates that 18 | # the generated image should be flashed when the entire project is flashed to 19 | # the target with 'idf.py -p PORT flash'. 20 | spiffs_create_partition_image(spiffs_storage ./spiffs_image FLASH_IN_PROJECT) 21 | -------------------------------------------------------------------------------- /examples/fleet_provisioning/fleet_provisioning_with_csr/README.md: -------------------------------------------------------------------------------- 1 | # Amazon Web Services IoT MQTT (Fleet Provisioning With CSR) Example 2 | 3 | This is an adaptation of the [AWS IoT C SDK](https://github.com/aws/aws-iot-device-sdk-embedded-C) "fleet_provisioning_with_csr" example for ESP-IDF. 4 | 5 | > **Note**: This example is currently in release preview but supports the full functionality of the Fleet Provisioning library. 6 | > It uses a SPIFFS partition to store the claim credentials and the received certificate and private key are stored in the NVS partition but are not encrypted by default. 7 | 8 | # Provisioning/Configuration 9 | 10 | ## Cloud Configuration 11 | To create a provisioning template and claim credentials, sign into your AWS account and visit [here](https://console.aws.amazon.com/iot/home#/provisioningtemplate/create/instruction). 12 | Once you have created the template and credentials, modify the claim certificate's policy to match the [sample policy](examples/fleet_provisioning/fleet_provisioning_with_csr/example_claim_policy.json). 13 | 14 | 15 | ## Device Configuration 16 | 17 | * Set your custom endpoint under `Example Configuration` in `idf.py menuconfig`. 18 | The endpoint can found on the *Settings* page of the AWS IoT Console and has a format of `ABCDEFG1234567.iot.us-east-2.amazonaws.com`. 19 | * Replace the `fleet_provisioning_with_csr/spiffs_image/certs/claim_cert.crt` and `claim_private.key` files with your claim certificate and claim private key. 20 | * Set the name of the provisioning template that you have created. 21 | * Set the device serial number to an arbitrary string representing a device identifier. 22 | 23 | # Troubleshooting 24 | 25 | If you're having problems with the AWS IoT connection itself, check the Troubleshooting section of the README in the parent directory. 26 | -------------------------------------------------------------------------------- /examples/fleet_provisioning/fleet_provisioning_with_csr/example_claim_policy.json: -------------------------------------------------------------------------------- 1 | { 2 | "Version": "2012-10-17", 3 | "Statement": [ 4 | { 5 | "Effect": "Allow", 6 | "Action": [ 7 | "iot:Connect" 8 | ], 9 | "Resource": "*" 10 | }, 11 | { 12 | "Effect": "Allow", 13 | "Action": [ 14 | "iot:Publish", 15 | "iot:Receive" 16 | ], 17 | "Resource": [ 18 | "arn:aws:iot:::topic/$aws/certificates/create-from-csr/*", 19 | "arn:aws:iot:::topic/$aws/provisioning-templates//provision/*" 20 | ] 21 | }, 22 | { 23 | "Effect": "Allow", 24 | "Action": "iot:Subscribe", 25 | "Resource": [ 26 | "arn:aws:iot:::topicfilter/$aws/certificates/create-from-csr/*", 27 | "arn:aws:iot:::topicfilter/$aws/provisioning-templates//provision/*" 28 | ] 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /examples/fleet_provisioning/fleet_provisioning_with_csr/main/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(COMPONENT_SRCS 2 | "app_main.c" 3 | "fleet_provisioning_with_csr_demo.c" 4 | "mqtt_operations.c" 5 | "fleet_provisioning_serializer.c" 6 | "pkcs11_operations.c" 7 | "mbedtls_pkcs11_posix.c" 8 | ) 9 | 10 | set(COMPONENT_ADD_INCLUDEDIRS 11 | "." 12 | "${CMAKE_CURRENT_LIST_DIR}" 13 | ) 14 | 15 | idf_component_register(SRCS "${COMPONENT_SRCS}" 16 | INCLUDE_DIRS ${COMPONENT_ADD_INCLUDEDIRS} 17 | ) -------------------------------------------------------------------------------- /examples/fleet_provisioning/fleet_provisioning_with_csr/main/Kconfig.projbuild: -------------------------------------------------------------------------------- 1 | menu "Example Configuration" 2 | 3 | config MQTT_CLIENT_IDENTIFIER 4 | string "The MQTT client identifier used in this example" 5 | default "testClient" 6 | help 7 | The MQTT client identifier used in this example. Each client identifier must be unique. 8 | so edit as required to ensure that no two clients connecting to the same broker use the same client identifier. 9 | 10 | config MQTT_BROKER_ENDPOINT 11 | string "Endpoint of the MQTT broker to connect to" 12 | default "test.mosquitto.org" 13 | help 14 | This example can be run with any MQTT broker, that supports server authentication. 15 | 16 | config MQTT_BROKER_PORT 17 | int "Port of the MQTT broker use" 18 | default 8883 19 | help 20 | In general, port 8883 is for secured MQTT connections. 21 | Port 443 requires use of the ALPN TLS extension with the ALPN protocol name. 22 | When using port 8883, ALPN is not required. 23 | 24 | config HARDWARE_PLATFORM_NAME 25 | string "The hardware platform" 26 | default "ESP32" 27 | help 28 | The name of the hardware platform the application is running on. 29 | 30 | config MQTT_NETWORK_BUFFER_SIZE 31 | int "Size of the network buffer for MQTT packets" 32 | range 1024 2048 33 | default 1024 34 | help 35 | Size of the network buffer for MQTT packets. 36 | 37 | config PROVISIONING_TEMPLATE_NAME 38 | string "Name of the provisioning template" 39 | default "FleetProvisioningDemoTemplate" 40 | help 41 | Name of the provisioning template to use for the RegisterThing 42 | portion of the Fleet Provisioning workflow. 43 | 44 | config DEVICE_SERIAL_NUMBER 45 | string "The device serial number" 46 | default "0000" 47 | help 48 | This is sent as a parameter to the provisioning template, 49 | which uses it to generate a unique Thing name. 50 | This should be unique per device. 51 | 52 | choice EXAMPLE_CHOOSE_PKI_ACCESS_METHOD 53 | prompt "Choose PKI credentials access method" 54 | default EXAMPLE_USE_PLAIN_FLASH_STORAGE 55 | help 56 | ESP devices support multiple ways to secure store the PKI credentials. 57 | Currently Secure Element (ATECC608A) and DS peripheral are supported. 58 | The default behaviour is to access the PKI credentials which are embedded in the binary. 59 | Consult the ESP-TLS documentation in ESP-IDF Programming guide for more details. 60 | 61 | config EXAMPLE_USE_PLAIN_FLASH_STORAGE 62 | bool "Use flash storage (default)" 63 | help 64 | This option expects the Private key and Device certificate to be embedded in the binary. 65 | This is the default behaviour. 66 | endchoice 67 | 68 | endmenu 69 | -------------------------------------------------------------------------------- /examples/fleet_provisioning/fleet_provisioning_with_csr/main/app_main.c: -------------------------------------------------------------------------------- 1 | /* fleet_provisioning_with_csr example 2 | 3 | This example code is in the Public Domain (or CC0 licensed, at your option.) 4 | 5 | Unless required by applicable law or agreed to in writing, this 6 | software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 7 | CONDITIONS OF ANY KIND, either express or implied. 8 | */ 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "esp_system.h" 14 | #include "nvs_flash.h" 15 | #include "esp_event.h" 16 | #include "esp_netif.h" 17 | #include "protocol_examples_common.h" 18 | #include "esp_spiffs.h" 19 | #include "esp_log.h" 20 | 21 | int aws_iot_demo_main( int argc, char ** argv ); 22 | 23 | static const char *TAG = "FLEET_PROVISIONING_EXAMPLE"; 24 | 25 | esp_vfs_spiffs_conf_t conf = { 26 | .base_path = "/spiffs", 27 | .partition_label = "spiffs_storage", 28 | .max_files = 5, 29 | .format_if_mount_failed = true 30 | }; 31 | 32 | void filesystem_init(void) 33 | { 34 | ESP_LOGI(TAG, "Initializing SPIFFS"); 35 | 36 | // Use settings defined above to initialize and mount SPIFFS filesystem. 37 | // Note: esp_vfs_spiffs_register is an all-in-one convenience function. 38 | esp_err_t ret = esp_vfs_spiffs_register(&conf); 39 | 40 | if (ret != ESP_OK) { 41 | if (ret == ESP_FAIL) { 42 | ESP_LOGE(TAG, "Failed to mount or format filesystem"); 43 | } else if (ret == ESP_ERR_NOT_FOUND) { 44 | ESP_LOGE(TAG, "Failed to find SPIFFS partition"); 45 | } else { 46 | ESP_LOGE(TAG, "Failed to initialize SPIFFS (%s)", esp_err_to_name(ret)); 47 | } 48 | return; 49 | } 50 | 51 | #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(4, 4, 0) 52 | ESP_LOGI(TAG, "Performing SPIFFS_check()."); 53 | ret = esp_spiffs_check(conf.partition_label); 54 | if (ret != ESP_OK) { 55 | ESP_LOGE(TAG, "SPIFFS_check() failed (%s)", esp_err_to_name(ret)); 56 | return; 57 | } else { 58 | ESP_LOGI(TAG, "SPIFFS_check() successful"); 59 | } 60 | #endif 61 | 62 | size_t total = 0, used = 0; 63 | ret = esp_spiffs_info(conf.partition_label, &total, &used); 64 | if (ret != ESP_OK) { 65 | ESP_LOGE(TAG, "Failed to get SPIFFS partition information (%s). Formatting...", esp_err_to_name(ret)); 66 | esp_spiffs_format(conf.partition_label); 67 | return; 68 | } else { 69 | ESP_LOGI(TAG, "Partition size: total: %d, used: %d", total, used); 70 | } 71 | } 72 | 73 | void filesystem_deinit(void) 74 | { 75 | // All done, unmount partition and disable SPIFFS 76 | esp_vfs_spiffs_unregister(conf.partition_label); 77 | ESP_LOGI(TAG, "SPIFFS unmounted"); 78 | } 79 | 80 | /* 81 | * Prototypes for the demos that can be started from this project. Note the 82 | * MQTT demo is not actually started until the network is already. 83 | */ 84 | 85 | void app_main() 86 | { 87 | ESP_LOGI(TAG, "[APP] Startup.."); 88 | ESP_LOGI(TAG, "[APP] Free memory: %"PRIu32" bytes", esp_get_free_heap_size()); 89 | ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version()); 90 | 91 | esp_log_level_set("*", ESP_LOG_INFO); 92 | 93 | filesystem_init(); 94 | 95 | /* Initialize NVS partition */ 96 | esp_err_t ret = nvs_flash_init(); 97 | if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { 98 | /* NVS partition was truncated 99 | * and needs to be erased */ 100 | ESP_ERROR_CHECK(nvs_flash_erase()); 101 | 102 | /* Retry nvs_flash_init */ 103 | ESP_ERROR_CHECK(nvs_flash_init()); 104 | } 105 | 106 | ESP_ERROR_CHECK(esp_netif_init()); 107 | ESP_ERROR_CHECK(esp_event_loop_create_default()); 108 | 109 | /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig. 110 | * Read "Establishing Wi-Fi or Ethernet Connection" section in 111 | * examples/protocols/README.md for more information about this function. 112 | */ 113 | ESP_ERROR_CHECK(example_connect()); 114 | 115 | aws_iot_demo_main(0,NULL); 116 | 117 | vTaskDelay(pdMS_TO_TICKS(10 * 1000)); 118 | 119 | filesystem_deinit(); 120 | } 121 | -------------------------------------------------------------------------------- /examples/fleet_provisioning/fleet_provisioning_with_csr/main/fleet_provisioning_serializer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * AWS IoT Device SDK for Embedded C 202211.00 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy 6 | * of this software and associated documentation files (the "Software"), to deal 7 | * in the Software without restriction, including without limitation the rights 8 | * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | * copies of the Software, and to permit persons to whom the Software is 10 | * furnished to do so, subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in 13 | * all copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | * SOFTWARE. 22 | */ 23 | 24 | /** 25 | * This file declares functions for serializing and parsing CBOR encoded Fleet 26 | * Provisioning API payloads. 27 | */ 28 | 29 | /* Standard includes. */ 30 | #include 31 | #include 32 | #include 33 | 34 | /** 35 | * @brief Creates the request payload to be published to the 36 | * CreateCertificateFromCsr API in order to request a certificate from AWS IoT 37 | * for the included Certificate Signing Request (CSR). 38 | * 39 | * @param[in] pBuffer Buffer into which to write the publish request payload. 40 | * @param[in] bufferLength Length of #pBuffer. 41 | * @param[in] pCsr The CSR to include in the request payload. 42 | * @param[in] csrLength The length of #pCsr. 43 | * @param[out] pOutLengthWritten The length of the publish request payload. 44 | */ 45 | bool generateCsrRequest( uint8_t * pBuffer, 46 | size_t bufferLength, 47 | const char * pCsr, 48 | size_t csrLength, 49 | size_t * pOutLengthWritten ); 50 | 51 | /** 52 | * @brief Creates the request payload to be published to the RegisterThing API 53 | * in order to activate the provisioned certificate and receive a Thing name. 54 | * 55 | * @param[in] pBuffer Buffer into which to write the publish request payload. 56 | * @param[in] bufferLength Length of #buffer. 57 | * @param[in] pCertificateOwnershipToken The certificate's certificate 58 | * ownership token. 59 | * @param[in] certificateOwnershipTokenLength Length of 60 | * #certificateOwnershipToken. 61 | * @param[out] pOutLengthWritten The length of the publish request payload. 62 | */ 63 | bool generateRegisterThingRequest( uint8_t * pBuffer, 64 | size_t bufferLength, 65 | const char * pCertificateOwnershipToken, 66 | size_t certificateOwnershipTokenLength, 67 | const char * pSerial, 68 | size_t serialLength, 69 | size_t * pOutLengthWritten ); 70 | 71 | /** 72 | * @brief Extracts the certificate, certificate ID, and certificate ownership 73 | * token from a CreateCertificateFromCsr accepted response. These are copied 74 | * to the provided buffers so that they can outlive the data in the response 75 | * buffer and as CBOR strings may be chunked. 76 | * 77 | * @param[in] pResponse The response payload. 78 | * @param[in] length Length of #pResponse. 79 | * @param[in] pCertificateBuffer The buffer to which to write the certificate. 80 | * @param[in,out] pCertificateBufferLength The length of #pCertificateBuffer. 81 | * The length written is output here. 82 | * @param[in] pCertificateIdBuffer The buffer to which to write the certificate 83 | * ID. 84 | * @param[in,out] pCertificateIdBufferLength The length of 85 | * #pCertificateIdBuffer. The length written is output here. 86 | * @param[in] pOwnershipTokenBuffer The buffer to which to write the 87 | * certificate ownership token. 88 | * @param[in,out] pOwnershipTokenBufferLength The length of 89 | * #pOwnershipTokenBuffer. The length written is output here. 90 | */ 91 | bool parseCsrResponse( const uint8_t * pResponse, 92 | size_t length, 93 | char * pCertificateBuffer, 94 | size_t * pCertificateBufferLength, 95 | char * pCertificateIdBuffer, 96 | size_t * pCertificateIdBufferLength, 97 | char * pOwnershipTokenBuffer, 98 | size_t * pOwnershipTokenBufferLength ); 99 | 100 | /** 101 | * @brief Extracts the Thing name from a RegisterThing accepted response. 102 | * 103 | * @param[in] pResponse The response document. 104 | * @param[in] length Length of #pResponse. 105 | * @param[in] pThingNameBuffer The buffer to which to write the Thing name. 106 | * @param[in,out] pThingNameBufferLength The length of #pThingNameBuffer. The 107 | * written length is output here. 108 | */ 109 | bool parseRegisterThingResponse( const uint8_t * pResponse, 110 | size_t length, 111 | char * pThingNameBuffer, 112 | size_t * pThingNameBufferLength ); 113 | 114 | /** 115 | * @brief Converts a CBOR document into a pretty printed string. 116 | * 117 | * @param[in] cbor The CBOR document. 118 | * @param[in] length The length of the CBOR document. 119 | * 120 | * @returns The pretty printed string on success. "" on error. 121 | */ 122 | const char * getStringFromCbor( const uint8_t * cbor, 123 | size_t length ); 124 | -------------------------------------------------------------------------------- /examples/fleet_provisioning/fleet_provisioning_with_csr/main/idf_component.yml: -------------------------------------------------------------------------------- 1 | ## IDF Component Manager Manifest File 2 | dependencies: 3 | espressif/cbor: 4 | version: ">=0.5.4,<1.0.0" 5 | rules: 6 | - if: "idf_version >=5.0" -------------------------------------------------------------------------------- /examples/fleet_provisioning/fleet_provisioning_with_csr/main/mqtt_operations.h: -------------------------------------------------------------------------------- 1 | /* 2 | * AWS IoT Device SDK for Embedded C 202211.00 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | * this software and associated documentation files (the "Software"), to deal in 7 | * the Software without restriction, including without limitation the rights to 8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | * the Software, and to permit persons to whom the Software is furnished to do so, 10 | * subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #ifndef MQTT_OPERATIONS_H_ 24 | #define MQTT_OPERATIONS_H_ 25 | 26 | /* MQTT API header. */ 27 | #include "core_mqtt.h" 28 | 29 | /* corePKCS11 include. */ 30 | #include "core_pkcs11.h" 31 | 32 | /** 33 | * @brief Application callback type to handle the incoming publishes. 34 | * 35 | * @param[in] pPublishInfo Pointer to publish info of the incoming publish. 36 | * @param[in] packetIdentifier Packet identifier of the incoming publish. 37 | */ 38 | typedef void (* MQTTPublishCallback_t )( MQTTPublishInfo_t * pPublishInfo, 39 | uint16_t packetIdentifier ); 40 | 41 | /** 42 | * @brief Establish a MQTT connection. 43 | * 44 | * @param[in] publishCallback The callback function to receive incoming 45 | * publishes from the MQTT broker. 46 | * @param[in] p11Session The PKCS #11 session to use. 47 | * @param[in] pClientCertLabel The client certificate PKCS #11 label to use. 48 | * @param[in] pPrivateKeyLabel The private key PKCS #11 label for the client certificate. 49 | * 50 | * @return true if an MQTT session is established; 51 | * false otherwise. 52 | */ 53 | bool EstablishMqttSession( MQTTPublishCallback_t publishCallback, 54 | CK_SESSION_HANDLE p11Session, 55 | char * pClientCertLabel, 56 | char * pPrivateKeyLabel ); 57 | 58 | /** 59 | * @brief Disconnect the MQTT connection. 60 | * 61 | * @return true if the MQTT session was successfully disconnected; 62 | * false otherwise. 63 | */ 64 | bool DisconnectMqttSession( void ); 65 | 66 | /** 67 | * @brief Subscribe to a MQTT topic filter. 68 | * 69 | * @param[in] pTopicFilter The topic filter to subscribe to. 70 | * @param[in] topicFilterLength Length of the topic buffer. 71 | * 72 | * @return true if subscribe operation was successful; 73 | * false otherwise. 74 | */ 75 | bool SubscribeToTopic( const char * pTopicFilter, 76 | uint16_t topicFilterLength ); 77 | 78 | /** 79 | * @brief Unsubscribe from a MQTT topic filter. 80 | * 81 | * @param[in] pTopicFilter The topic filter to unsubscribe from. 82 | * @param[in] topicFilterLength Length of the topic buffer. 83 | * 84 | * @return true if unsubscribe operation was successful; 85 | * false otherwise. 86 | */ 87 | bool UnsubscribeFromTopic( const char * pTopicFilter, 88 | uint16_t topicFilterLength ); 89 | 90 | /** 91 | * @brief Publish a message to a MQTT topic. 92 | * 93 | * @param[in] pTopic The topic to publish the message on. 94 | * @param[in] topicLength Length of the topic. 95 | * @param[in] pMessage The message to publish. 96 | * @param[in] messageLength Length of the message. 97 | * 98 | * @return true if PUBLISH was successfully sent; 99 | * false otherwise. 100 | */ 101 | bool PublishToTopic( const char * pTopic, 102 | uint16_t topicLength, 103 | const char * pMessage, 104 | size_t messageLength ); 105 | 106 | /** 107 | * @brief Invoke the core MQTT library's process loop function. 108 | * 109 | * @return true if process loop was successful; 110 | * false otherwise. 111 | */ 112 | bool ProcessLoopWithTimeout( void ); 113 | 114 | #endif /* ifndef MQTT_OPERATIONS_H_ */ 115 | -------------------------------------------------------------------------------- /examples/fleet_provisioning/fleet_provisioning_with_csr/main/pkcs11_operations.h: -------------------------------------------------------------------------------- 1 | /* 2 | * AWS IoT Device SDK for Embedded C 202211.00 3 | * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | * this software and associated documentation files (the "Software"), to deal in 7 | * the Software without restriction, including without limitation the rights to 8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | * the Software, and to permit persons to whom the Software is furnished to do so, 10 | * subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #ifndef PKCS11_OPERATIONS_H_ 24 | #define PKCS11_OPERATIONS_H_ 25 | 26 | /* Standard includes. */ 27 | #include 28 | #include 29 | 30 | /* corePKCS11 include. */ 31 | #include "core_pkcs11.h" 32 | 33 | /** 34 | * @brief Loads the claim credentials into the PKCS #11 module. Claim 35 | * credentials are used in "Provisioning by Claim" workflow of Fleet 36 | * Provisioning feature of AWS IoT Core. For more information, refer to the 37 | * [AWS documentation](https://docs.aws.amazon.com/iot/latest/developerguide/provision-wo-cert.html#claim-based) 38 | * 39 | * Note: This function is for demonstration purposes, and the claim credentials 40 | * should be securely stored in production devices. For example, the 41 | * shared claim credentials could be loaded into a secure element on the devices 42 | * in your fleet at the time of manufacturing. 43 | * 44 | * @param[in] p11Session The PKCS #11 session to use. 45 | * @param[in] pClaimCertPath Path to the claim certificate. 46 | * @param[in] pClaimCertLabel PKCS #11 label for the claim certificate. 47 | * @param[in] pClaimPrivKeyPath Path to the claim private key. 48 | * @param[in] pClaimPrivKeyLabel PKCS #11 label for the claim private key. 49 | * 50 | * @return True on success. 51 | */ 52 | bool loadClaimCredentials( CK_SESSION_HANDLE p11Session, 53 | const char * pClaimCertPath, 54 | const char * pClaimCertLabel, 55 | const char * pClaimPrivKeyPath, 56 | const char * pClaimPrivKeyLabel ); 57 | 58 | /** 59 | * @brief Generate a new public-private key pair in the PKCS #11 module, and 60 | * generate a certificate signing request (CSR) for them. 61 | * 62 | * This device-generated private key and CSR can be used with the 63 | * CreateCertificateFromCsr API of the the Fleet Provisioning feature of AWS IoT 64 | * Core in order to provision a unique client certificate. 65 | * 66 | * @param[in] p11Session The PKCS #11 session to use. 67 | * @param[in] pPrivKeyLabel PKCS #11 label for the private key. 68 | * @param[in] pPubKeyLabel PKCS #11 label for the public key. 69 | * @param[out] pCsrBuffer The buffer to write the CSR to. 70 | * @param[in] csrBufferLength Length of #pCsrBuffer. 71 | * @param[out] pOutCsrLength The length of the written CSR. 72 | * 73 | * @return True on success. 74 | */ 75 | bool generateKeyAndCsr( CK_SESSION_HANDLE p11Session, 76 | const char * pPrivKeyLabel, 77 | const char * pPubKeyLabel, 78 | char * pCsrBuffer, 79 | size_t csrBufferLength, 80 | size_t * pOutCsrLength ); 81 | 82 | /** 83 | * @brief Save the device client certificate into the PKCS #11 module. 84 | * 85 | * @param[in] p11Session The PKCS #11 session to use. 86 | * @param[in] pCertificate The certificate to save. 87 | * @param[in] pLabel PKCS #11 label for the certificate. 88 | * @param[in] certificateLength Length of #pCertificate. 89 | * 90 | * @return True on success. 91 | */ 92 | bool loadCertificate( CK_SESSION_HANDLE p11Session, 93 | const char * pCertificate, 94 | const char * pLabel, 95 | size_t certificateLength ); 96 | 97 | /** 98 | * @brief Close the PKCS #11 session. 99 | * 100 | * @param[in] p11Session The PKCS #11 session to use. 101 | * 102 | * @return True on success. 103 | */ 104 | bool pkcs11CloseSession( CK_SESSION_HANDLE p11Session ); 105 | 106 | #endif /* ifndef PKCS11_OPERATIONS_H_ */ 107 | -------------------------------------------------------------------------------- /examples/fleet_provisioning/fleet_provisioning_with_csr/partitions.csv: -------------------------------------------------------------------------------- 1 | # Name, Type, SubType, Offset, Size, Flags 2 | # Note: if you have increased the bootloader size, make sure to update the offsets to avoid overlap 3 | nvs, data, nvs, 0x9000, 0x6000, 4 | storage, data, nvs, , 0x4000, 5 | phy_init, data, phy, , 0x1000, 6 | factory, app, factory, , 1200K, 7 | spiffs_storage, data, spiffs, , 0xF0000, 8 | -------------------------------------------------------------------------------- /examples/fleet_provisioning/fleet_provisioning_with_csr/sdkconfig.defaults: -------------------------------------------------------------------------------- 1 | # newlib for ESP32 and ESP8266 platform 2 | 3 | CONFIG_NEWLIB_ENABLE=y 4 | CONFIG_NEWLIB_LIBRARY_LEVEL_NORMAL=y 5 | CONFIG_NEWLIB_NANO_FORMAT= 6 | CONFIG_SSL_USING_MBEDTLS=y 7 | CONFIG_LWIP_IPV6=y 8 | CONFIG_MBEDTLS_THREADING_C=y 9 | # CONFIG_MBEDTLS_THREADING_ALT is not set 10 | CONFIG_MBEDTLS_THREADING_PTHREAD=y 11 | CONFIG_PTHREAD_TASK_STACK_SIZE_DEFAULT=8192 12 | CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y 13 | CONFIG_BOOTLOADER_APP_ROLLBACK_ENABLE=y 14 | CONFIG_MBEDTLS_CMAC_C=y 15 | CONFIG_PARTITION_TABLE_CUSTOM=y 16 | CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" 17 | CONFIG_PARTITION_TABLE_FILENAME="partitions.csv" 18 | CONFIG_MQTT_NETWORK_BUFFER_SIZE=2048 19 | CONFIG_ESP_MAIN_TASK_STACK_SIZE=16384 20 | -------------------------------------------------------------------------------- /examples/fleet_provisioning/fleet_provisioning_with_csr/spiffs_image/certs/AmazonRootCA1.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF 3 | ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 4 | b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL 5 | MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv 6 | b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj 7 | ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM 8 | 9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw 9 | IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6 10 | VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L 11 | 93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm 12 | jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC 13 | AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA 14 | A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI 15 | U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs 16 | N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv 17 | o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU 18 | 5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy 19 | rqXRfboQnoZsG4q5WTP468SQvvG5 20 | -----END CERTIFICATE----- -------------------------------------------------------------------------------- /examples/fleet_provisioning/fleet_provisioning_with_csr/spiffs_image/certs/claim_cert.crt: -------------------------------------------------------------------------------- 1 | Certificate goes here. -------------------------------------------------------------------------------- /examples/fleet_provisioning/fleet_provisioning_with_csr/spiffs_image/certs/claim_private.key: -------------------------------------------------------------------------------- 1 | Key goes here. -------------------------------------------------------------------------------- /examples/http/http_mutual_auth/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # The following five lines of boilerplate have to be in your project's 2 | # CMakeLists in this exact order for cmake to work correctly 3 | cmake_minimum_required(VERSION 3.5) 4 | 5 | set(EXTRA_COMPONENT_DIRS "$ENV{IDF_PATH}/examples/common_components/protocol_examples_common" 6 | "${CMAKE_CURRENT_LIST_DIR}/../../../libraries/coreHTTP" 7 | "${CMAKE_CURRENT_LIST_DIR}/../../../libraries/backoffAlgorithm" 8 | "${CMAKE_CURRENT_LIST_DIR}/../../../libraries/common/posix_compat" 9 | ) 10 | 11 | include($ENV{IDF_PATH}/tools/cmake/project.cmake) 12 | project(http_mutual_auth) 13 | 14 | target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/certs/root_cert_auth.crt" TEXT) 15 | target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/certs/client.crt" TEXT) 16 | target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/certs/client.key" TEXT) 17 | -------------------------------------------------------------------------------- /examples/http/http_mutual_auth/main/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(COMPONENT_SRCS 2 | "app_main.c" 3 | "http_demo_mutual_auth.c" 4 | "http_demo_utils.c" 5 | ) 6 | 7 | set(COMPONENT_ADD_INCLUDEDIRS 8 | "." 9 | "${CMAKE_CURRENT_LIST_DIR}" 10 | ) 11 | 12 | idf_component_register(SRCS "${COMPONENT_SRCS}" 13 | INCLUDE_DIRS ${COMPONENT_ADD_INCLUDEDIRS} 14 | ) -------------------------------------------------------------------------------- /examples/http/http_mutual_auth/main/Kconfig.projbuild: -------------------------------------------------------------------------------- 1 | menu "Example Configuration" 2 | 3 | config AWS_IOT_ENDPOINT 4 | string "AWS IoT Core endpoint to connect to" 5 | 6 | config AWS_HTTPS_PORT 7 | int "AWS IoT Core server port number for HTTPS connections" 8 | default 8443 9 | help 10 | Port 443 requires use of the ALPN TLS extension with the ALPN protocol name. 11 | When using port 8443, ALPN is not required. 12 | 13 | config HARDWARE_PLATFORM_NAME 14 | string "The hardware platform" 15 | default "ESP32" 16 | help 17 | The name of the hardware platform the application is running on. 18 | 19 | choice EXAMPLE_CHOOSE_PKI_ACCESS_METHOD 20 | prompt "Choose PKI credentials access method" 21 | default EXAMPLE_USE_PLAIN_FLASH_STORAGE 22 | help 23 | ESP devices support multiple ways to secure store the PKI credentials. 24 | Currently Secure Element (ATECC608A) and DS peripheral 25 | (using ESP Secure Cert Manager) are supported. 26 | The default behaviour is to access the PKI credentials which are embedded in the binary. 27 | Consult the ESP-TLS documentation in ESP-IDF Programming guide for more details. 28 | 29 | config EXAMPLE_USE_SECURE_ELEMENT 30 | bool "Use secure element (ATECC608A)" 31 | depends on (IDF_TARGET_ESP32 || IDF_TARGET_ESP32C2) && ESP_TLS_USING_MBEDTLS 32 | # To confirm that we are satisfying the dependencies of secure element 33 | select ESP_TLS_USE_SECURE_ELEMENT 34 | help 35 | Enable the use of secure element for the example. 36 | The esp-cryptoauthlib component is required for enabling 37 | this option. 38 | 39 | config EXAMPLE_USE_ESP_SECURE_CERT_MGR 40 | bool "Use ESP Secure Certificate Manager" 41 | help 42 | Enable the use of ESP Secure Certificate Manager APIs for the example. 43 | Please refer to ESP Secure Certificate Manager documentation for more details. 44 | 45 | config EXAMPLE_USE_PLAIN_FLASH_STORAGE 46 | bool "Use flash storage (default)" 47 | help 48 | This option expects the Private key and Device certificate to be embedded in the binary. 49 | This is the default behaviour. 50 | endchoice 51 | endmenu 52 | -------------------------------------------------------------------------------- /examples/http/http_mutual_auth/main/app_main.c: -------------------------------------------------------------------------------- 1 | /* http_mutual_auth example 2 | 3 | This example code is in the Public Domain (or CC0 licensed, at your option.) 4 | 5 | Unless required by applicable law or agreed to in writing, this 6 | software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 7 | CONDITIONS OF ANY KIND, either express or implied. 8 | */ 9 | 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include "esp_system.h" 15 | #include "nvs_flash.h" 16 | #include "esp_event.h" 17 | #include "esp_netif.h" 18 | #include "protocol_examples_common.h" 19 | #include "esp_log.h" 20 | 21 | static const char *TAG = "HTTP_MUTUAL_AUTH"; 22 | 23 | int aws_iot_demo_main( int argc, char ** argv ); 24 | 25 | /* 26 | * Prototypes for the demos that can be started from this project. Note the 27 | * demo is not actually started until the network is already. 28 | */ 29 | 30 | void app_main() 31 | { 32 | ESP_LOGI(TAG, "[APP] Startup.."); 33 | ESP_LOGI(TAG, "[APP] Free memory: %"PRIu32" bytes", esp_get_free_heap_size()); 34 | ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version()); 35 | 36 | esp_log_level_set("*", ESP_LOG_INFO); 37 | 38 | /* Initialize NVS partition */ 39 | esp_err_t ret = nvs_flash_init(); 40 | if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { 41 | /* NVS partition was truncated 42 | * and needs to be erased */ 43 | ESP_ERROR_CHECK(nvs_flash_erase()); 44 | 45 | /* Retry nvs_flash_init */ 46 | ESP_ERROR_CHECK(nvs_flash_init()); 47 | } 48 | 49 | ESP_ERROR_CHECK(esp_netif_init()); 50 | ESP_ERROR_CHECK(esp_event_loop_create_default()); 51 | 52 | /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig. 53 | * Read "Establishing Wi-Fi or Ethernet Connection" section in 54 | * examples/protocols/README.md for more information about this function. 55 | */ 56 | ESP_ERROR_CHECK(example_connect()); 57 | 58 | aws_iot_demo_main(0,NULL); 59 | } 60 | -------------------------------------------------------------------------------- /examples/http/http_mutual_auth/main/certs/client.crt: -------------------------------------------------------------------------------- 1 | Certificate goes here. -------------------------------------------------------------------------------- /examples/http/http_mutual_auth/main/certs/client.key: -------------------------------------------------------------------------------- 1 | Key goes here. -------------------------------------------------------------------------------- /examples/http/http_mutual_auth/main/certs/root_cert_auth.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF 3 | ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 4 | b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL 5 | MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv 6 | b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj 7 | ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM 8 | 9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw 9 | IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6 10 | VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L 11 | 93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm 12 | jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC 13 | AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA 14 | A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI 15 | U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs 16 | N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv 17 | o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU 18 | 5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy 19 | rqXRfboQnoZsG4q5WTP468SQvvG5 20 | -----END CERTIFICATE----- 21 | 22 | -------------------------------------------------------------------------------- /examples/http/http_mutual_auth/main/demo_config.h: -------------------------------------------------------------------------------- 1 | /* 2 | * AWS IoT Device SDK for Embedded C 202103.00 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | * this software and associated documentation files (the "Software"), to deal in 7 | * the Software without restriction, including without limitation the rights to 8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | * the Software, and to permit persons to whom the Software is furnished to do so, 10 | * subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #ifndef DEMO_CONFIG_H_ 24 | #define DEMO_CONFIG_H_ 25 | 26 | /**************************************************/ 27 | /******* DO NOT CHANGE the following order ********/ 28 | /**************************************************/ 29 | 30 | /* Logging config definition and header files inclusion are required in the following order: 31 | * 1. Include the header file "logging_levels.h". 32 | * 2. Define the LIBRARY_LOG_NAME and LIBRARY_LOG_LEVEL macros depending on 33 | * the logging configuration for DEMO. 34 | * 3. Include the header file "logging_stack.h", if logging is enabled for DEMO. 35 | */ 36 | 37 | /* Include header that defines log levels. */ 38 | #include "logging_levels.h" 39 | 40 | /* Logging configuration for the Demo. */ 41 | #ifndef LIBRARY_LOG_NAME 42 | #define LIBRARY_LOG_NAME "DEMO" 43 | #endif 44 | 45 | #ifndef LIBRARY_LOG_LEVEL 46 | #define LIBRARY_LOG_LEVEL LOG_INFO 47 | #endif 48 | 49 | #include "logging_stack.h" 50 | 51 | /************ End of logging configuration ****************/ 52 | 53 | /** 54 | * @brief Your AWS IoT Core endpoint. 55 | * 56 | * @note Your AWS IoT Core endpoint can be found in the AWS IoT console under 57 | * Settings/Custom Endpoint, or using the describe-endpoint API. 58 | * 59 | */ 60 | #define AWS_IOT_ENDPOINT CONFIG_AWS_IOT_ENDPOINT 61 | 62 | /** 63 | * @brief AWS IoT Core server port number for HTTPS connections. 64 | * 65 | * For this demo, an X.509 certificate is used to verify the client. 66 | * 67 | * @note Port 443 requires use of the ALPN TLS extension with the ALPN protocol 68 | * name being x-amzn-http-ca. When using port 8443, ALPN is not required. 69 | */ 70 | #ifndef AWS_HTTPS_PORT 71 | #define AWS_HTTPS_PORT CONFIG_AWS_HTTPS_PORT 72 | #endif 73 | 74 | /** 75 | * @brief This endpoint can be used to publish a message to a topic named topic 76 | * on AWS IoT Core. 77 | * 78 | * Each client certificate has an associated policy document that must be 79 | * configured to support the path below for this demo to work correctly. 80 | * 81 | * @note QoS=1 implies the message is delivered to all subscribers of the topic 82 | * at least once. 83 | */ 84 | #define POST_PATH "/topics/topic?qos=1" 85 | 86 | /** 87 | * @brief Transport timeout in milliseconds for transport send and receive. 88 | */ 89 | #define TRANSPORT_SEND_RECV_TIMEOUT_MS ( 1500 ) 90 | 91 | /** 92 | * @brief The length in bytes of the user buffer. 93 | */ 94 | #define USER_BUFFER_LENGTH ( 2048 ) 95 | 96 | /** 97 | * @brief Request body to send for PUT and POST requests in this demo. 98 | */ 99 | #define REQUEST_BODY "{ \"message\": \"Hello, world\" }" 100 | 101 | #endif /* ifndef DEMO_CONFIG_H_ */ 102 | -------------------------------------------------------------------------------- /examples/http/http_mutual_auth/main/http_demo_utils.h: -------------------------------------------------------------------------------- 1 | /* 2 | * AWS IoT Device SDK for Embedded C 202103.00 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | * this software and associated documentation files (the "Software"), to deal in 7 | * the Software without restriction, including without limitation the rights to 8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | * the Software, and to permit persons to whom the Software is furnished to do so, 10 | * subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | /* Standard includes. */ 24 | #include 25 | #include 26 | 27 | /* Transport interface include. */ 28 | #include "transport_interface.h" 29 | 30 | /* HTTP API header. */ 31 | #include "core_http_client.h" 32 | 33 | /** 34 | * @brief Function pointer for establishing connection to a server. 35 | * 36 | * @param[out] pNetworkContext Implementation-defined network context. 37 | * 38 | * @return EXIT_FAILURE on failure; EXIT_SUCCESS on successful connection. 39 | */ 40 | typedef int32_t ( * TransportConnect_t )( NetworkContext_t * pNetworkContext ); 41 | 42 | /** 43 | * @brief Connect to a server with reconnection retries. 44 | * 45 | * If connection fails, retry is attempted after a timeout. 46 | * Timeout value will exponentially increase until maximum 47 | * timeout value is reached or the number of attempts are exhausted. 48 | * 49 | * @param[in] connectFunction Function pointer for establishing connection to a server. 50 | * @param[out] pNetworkContext Implementation-defined network context. 51 | * 52 | * @return EXIT_FAILURE on failure; EXIT_SUCCESS on successful connection. 53 | */ 54 | int32_t connectToServerWithBackoffRetries( TransportConnect_t connectFunction, 55 | NetworkContext_t * pNetworkContext ); 56 | 57 | /** 58 | * @brief Retrieve the path from the input URL. 59 | * 60 | * This function retrieves the location and length of the path from within the 61 | * input the URL. The query is not included in the length returned. 62 | * 63 | * The URL MUST start with "http://" or "https://" to find the path. 64 | * 65 | * For example, if pUrl is: 66 | * "https://www.somewebsite.com/path/to/item.txt?optionalquery=stuff" 67 | * 68 | * Then pPath and pPathLen will be the following: 69 | * *pPath = "/path/to/item.txt?optionalquery=stuff" 70 | * *pPathLen = 17 71 | * 72 | * @param[in] pUrl URL string to parse. 73 | * @param[in] urlLen The length of the URL string input. 74 | * @param[out] pPath pointer within input url that the path starts at. 75 | * @param[out] pPathLen Length of the path. 76 | * 77 | * @return The status of the parsing attempt: 78 | * HTTPSuccess if the path was successfully parsed, 79 | * HTTPParserInternalError if there was an error parsing the URL, 80 | * or HTTPNoResponse if the path was not found. 81 | */ 82 | HTTPStatus_t getUrlPath( const char * pUrl, 83 | size_t urlLen, 84 | const char ** pPath, 85 | size_t * pPathLen ); 86 | 87 | /** 88 | * @brief Retrieve the Address from the input URL. 89 | * 90 | * This function retrieves the location and length of the address from within 91 | * the input URL. The path and query are not included in the length returned. 92 | * 93 | * The URL MUST start with "http://" or "https://" to find the address. 94 | * 95 | * For example, if pUrl is: 96 | * "https://www.somewebsite.com/path/to/item.txt?optionalquery=stuff" 97 | * 98 | * Then pAddress and pAddressLen will be the following: 99 | * *pAddress = "www.somewebsite.com/path/to/item.txt?optionalquery=stuff" 100 | * *pAddressLen = 19 101 | * 102 | * @param[in] pUrl URL string to parse. 103 | * @param[in] urlLen The length of the URL string input. 104 | * @param[out] pAddress pointer within input url that the address starts at. 105 | * @param[out] pAddressLen Length of the address. 106 | * 107 | * @return The status of the parsing attempt: 108 | * HTTPSuccess if the path was successfully parsed, 109 | * HTTPParserInternalError if there was an error parsing the URL, 110 | * or HTTPNoResponse if the path was not found. 111 | */ 112 | HTTPStatus_t getUrlAddress( const char * pUrl, 113 | size_t urlLen, 114 | const char ** pAddress, 115 | size_t * pAddressLen ); 116 | -------------------------------------------------------------------------------- /examples/http/http_mutual_auth/main/idf_component.yml: -------------------------------------------------------------------------------- 1 | ## IDF Component Manager Manifest File 2 | dependencies: 3 | espressif/esp_secure_cert_mgr: "^2.0.5" 4 | -------------------------------------------------------------------------------- /examples/http/http_mutual_auth/partitions.csv: -------------------------------------------------------------------------------- 1 | # Name, Type, SubType, Offset, Size, Flags 2 | # Note: if you change the phy_init or app partition offset, make sure to change the offset in Kconfig.projbuild 3 | esp_secure_cert, 0x3F, , 0xD000, 0x2000, encrypted 4 | nvs, data, nvs, , 0x9000 5 | phy_init, data, phy, , 0x1000 6 | factory, app, factory, 0x20000, 1M, 7 | -------------------------------------------------------------------------------- /examples/http/http_mutual_auth/sdkconfig.defaults: -------------------------------------------------------------------------------- 1 | # newlib for ESP32 and ESP8266 platform 2 | 3 | CONFIG_NEWLIB_ENABLE=y 4 | CONFIG_NEWLIB_LIBRARY_LEVEL_NORMAL=y 5 | CONFIG_NEWLIB_NANO_FORMAT= 6 | CONFIG_SSL_USING_MBEDTLS=y 7 | CONFIG_LWIP_IPV6=y 8 | CONFIG_PARTITION_TABLE_CUSTOM=y 9 | CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" 10 | CONFIG_PARTITION_TABLE_FILENAME="partitions.csv" 11 | -------------------------------------------------------------------------------- /examples/jobs/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # The following five lines of boilerplate have to be in your project's 2 | # CMakeLists in this exact order for cmake to work correctly 3 | cmake_minimum_required(VERSION 3.5) 4 | 5 | set(EXTRA_COMPONENT_DIRS "$ENV{IDF_PATH}/examples/common_components/protocol_examples_common" 6 | "${CMAKE_CURRENT_LIST_DIR}/../../libraries/coreMQTT" 7 | "${CMAKE_CURRENT_LIST_DIR}/../../libraries/coreJSON" 8 | "${CMAKE_CURRENT_LIST_DIR}/../../libraries/Jobs-for-AWS-IoT-embedded-sdk" 9 | "${CMAKE_CURRENT_LIST_DIR}/../../libraries/backoffAlgorithm" 10 | "${CMAKE_CURRENT_LIST_DIR}/../../libraries/common/posix_compat" 11 | ) 12 | 13 | include($ENV{IDF_PATH}/tools/cmake/project.cmake) 14 | project(jobs) 15 | 16 | target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/certs/root_cert_auth.crt" TEXT) 17 | target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/certs/client.crt" TEXT) 18 | target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/certs/client.key" TEXT) 19 | -------------------------------------------------------------------------------- /examples/jobs/main/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(COMPONENT_SRCS 2 | "app_main.c" 3 | "JobsDemoExample.c" 4 | "mqtt_demo_helpers.c" 5 | ) 6 | 7 | set(COMPONENT_ADD_INCLUDEDIRS 8 | "." 9 | "${PROJECT_DIR}/../../libraries/common/logging" 10 | ) 11 | 12 | idf_component_register(SRCS "${COMPONENT_SRCS}" 13 | INCLUDE_DIRS ${COMPONENT_ADD_INCLUDEDIRS} 14 | ) -------------------------------------------------------------------------------- /examples/jobs/main/Kconfig.projbuild: -------------------------------------------------------------------------------- 1 | menu "Example Configuration" 2 | 3 | config MQTT_CLIENT_IDENTIFIER 4 | string "The MQTT client identifier used in this example" 5 | default "testClient" 6 | help 7 | The MQTT client identifier used in this example. Each client identifier must be unique. 8 | so edit as required to ensure that no two clients connecting to the same broker use the same client identifier. 9 | 10 | config MQTT_BROKER_ENDPOINT 11 | string "Endpoint of the MQTT broker to connect to" 12 | default "test.mosquitto.org" 13 | help 14 | This example can be run with any MQTT broker, that supports server authentication. 15 | 16 | config MQTT_BROKER_PORT 17 | int "Port of the MQTT broker use" 18 | default 8883 19 | help 20 | In general, port 8883 is for secured MQTT connections. 21 | Port 443 requires use of the ALPN TLS extension with the ALPN protocol name. 22 | When using port 8883, ALPN is not required. 23 | 24 | config HARDWARE_PLATFORM_NAME 25 | string "The hardware platform" 26 | default "ESP32" 27 | help 28 | The name of the hardware platform the application is running on. 29 | 30 | config MQTT_NETWORK_BUFFER_SIZE 31 | int "Size of the network buffer for MQTT packets" 32 | range 1024 2048 33 | default 1024 34 | help 35 | Size of the network buffer for MQTT packets. 36 | 37 | choice EXAMPLE_CHOOSE_PKI_ACCESS_METHOD 38 | prompt "Choose PKI credentials access method" 39 | default EXAMPLE_USE_PLAIN_FLASH_STORAGE 40 | help 41 | ESP devices support multiple ways to secure store the PKI credentials. 42 | Currently Secure Element (ATECC608A) and DS peripheral 43 | (using ESP Secure Cert Manager) are supported. 44 | The default behaviour is to access the PKI credentials which are embedded in the binary. 45 | Consult the ESP-TLS documentation in ESP-IDF Programming guide for more details. 46 | 47 | config EXAMPLE_USE_SECURE_ELEMENT 48 | bool "Use secure element (ATECC608A)" 49 | depends on (IDF_TARGET_ESP32 || IDF_TARGET_ESP32C2) && ESP_TLS_USING_MBEDTLS 50 | # To confirm that we are satisfying the dependencies of secure element 51 | select ESP_TLS_USE_SECURE_ELEMENT 52 | help 53 | Enable the use of secure element for the example. 54 | The esp-cryptoauthlib component is required for enabling 55 | this option. 56 | 57 | config EXAMPLE_USE_ESP_SECURE_CERT_MGR 58 | bool "Use ESP Secure Certificate Manager" 59 | help 60 | Enable the use of ESP Secure Certificate Manager APIs for the example. 61 | Please refer to ESP Secure Certificate Manager documentation for more details. 62 | 63 | config EXAMPLE_USE_PLAIN_FLASH_STORAGE 64 | bool "Use flash storage (default)" 65 | help 66 | This option expects the Private key and Device certificate to be embedded in the binary. 67 | This is the default behaviour. 68 | endchoice 69 | 70 | endmenu 71 | -------------------------------------------------------------------------------- /examples/jobs/main/app_main.c: -------------------------------------------------------------------------------- 1 | /* jobs example 2 | 3 | This example code is in the Public Domain (or CC0 licensed, at your option.) 4 | 5 | Unless required by applicable law or agreed to in writing, this 6 | software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 7 | CONDITIONS OF ANY KIND, either express or implied. 8 | */ 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "esp_system.h" 14 | #include "nvs_flash.h" 15 | #include "esp_event.h" 16 | #include "esp_netif.h" 17 | #include "protocol_examples_common.h" 18 | 19 | #include "esp_log.h" 20 | 21 | static const char *TAG = "JOBS_EXAMPLE"; 22 | 23 | /* 24 | * Prototypes for the demos that can be started from this project. Note the 25 | * Jobs demo is not actually started until the network is already. 26 | */ 27 | void vStartJobsDemo( void ); 28 | 29 | void app_main() 30 | { 31 | ESP_LOGI(TAG, "[APP] Startup.."); 32 | ESP_LOGI(TAG, "[APP] Free memory: %"PRIu32" bytes", esp_get_free_heap_size()); 33 | ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version()); 34 | 35 | esp_log_level_set("*", ESP_LOG_INFO); 36 | 37 | /* Initialize NVS partition */ 38 | esp_err_t ret = nvs_flash_init(); 39 | if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { 40 | /* NVS partition was truncated 41 | * and needs to be erased */ 42 | ESP_ERROR_CHECK(nvs_flash_erase()); 43 | 44 | /* Retry nvs_flash_init */ 45 | ESP_ERROR_CHECK(nvs_flash_init()); 46 | } 47 | 48 | ESP_ERROR_CHECK(esp_netif_init()); 49 | ESP_ERROR_CHECK(esp_event_loop_create_default()); 50 | 51 | /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig. 52 | * Read "Establishing Wi-Fi or Ethernet Connection" section in 53 | * examples/protocols/README.md for more information about this function. 54 | */ 55 | ESP_ERROR_CHECK(example_connect()); 56 | 57 | vStartJobsDemo(); 58 | } 59 | -------------------------------------------------------------------------------- /examples/jobs/main/certs/client.crt: -------------------------------------------------------------------------------- 1 | Certificate goes here. -------------------------------------------------------------------------------- /examples/jobs/main/certs/client.key: -------------------------------------------------------------------------------- 1 | Key goes here. -------------------------------------------------------------------------------- /examples/jobs/main/certs/root_cert_auth.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF 3 | ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 4 | b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL 5 | MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv 6 | b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj 7 | ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM 8 | 9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw 9 | IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6 10 | VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L 11 | 93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm 12 | jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC 13 | AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA 14 | A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI 15 | U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs 16 | N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv 17 | o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU 18 | 5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy 19 | rqXRfboQnoZsG4q5WTP468SQvvG5 20 | -----END CERTIFICATE----- 21 | 22 | -------------------------------------------------------------------------------- /examples/jobs/main/demo_config.h: -------------------------------------------------------------------------------- 1 | /* 2 | * FreeRTOS Kernel V10.3.0 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | * this software and associated documentation files (the "Software"), to deal in 7 | * the Software without restriction, including without limitation the rights to 8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | * the Software, and to permit persons to whom the Software is furnished to do so, 10 | * subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | * 22 | * http://www.FreeRTOS.org 23 | * http://aws.amazon.com/freertos 24 | * 25 | */ 26 | 27 | #ifndef DEMO_CONFIG_H 28 | #define DEMO_CONFIG_H 29 | 30 | /* FreeRTOS config include. */ 31 | #include "freertos/FreeRTOSConfig.h" 32 | 33 | /**************************************************/ 34 | /******* DO NOT CHANGE the following order ********/ 35 | /**************************************************/ 36 | 37 | /* Include logging header files and define logging macros in the following order: 38 | * 1. Include the header file "logging_levels.h". 39 | * 2. Define the LIBRARY_LOG_NAME and LIBRARY_LOG_LEVEL macros depending on 40 | * the logging configuration for DEMO. 41 | * 3. Include the header file "logging_stack.h", if logging is enabled for DEMO. 42 | */ 43 | 44 | #include "logging_levels.h" 45 | 46 | /* Logging configuration for the Demo. */ 47 | #ifndef LIBRARY_LOG_NAME 48 | #define LIBRARY_LOG_NAME "JobsDemo" 49 | #endif 50 | 51 | #ifndef LIBRARY_LOG_LEVEL 52 | #define LIBRARY_LOG_LEVEL LOG_INFO 53 | #endif 54 | 55 | #include "logging_stack.h" 56 | 57 | /************ End of logging configuration ****************/ 58 | 59 | /** 60 | * @brief The MQTT client identifier used in this example. Each client identifier 61 | * must be unique; so edit as required to ensure that no two clients connecting to 62 | * the same broker use the same client identifier. 63 | * 64 | *!!! Please note a #defined constant is used for convenience of demonstration 65 | *!!! only. Production devices can use something unique to the device that can 66 | *!!! be read by software, such as a production serial number, instead of a 67 | *!!! hard coded constant. 68 | * 69 | */ 70 | #define democonfigCLIENT_IDENTIFIER CONFIG_MQTT_CLIENT_IDENTIFIER 71 | 72 | /** 73 | * @brief Endpoint of the MQTT broker to connect to. 74 | * 75 | * This demo application can be run with any MQTT broker, that supports server 76 | * authentication. 77 | * 78 | * @note If you would like to setup an MQTT broker for running this demo, 79 | * please see `mqtt_broker_setup.txt`. 80 | * 81 | */ 82 | #define democonfigMQTT_BROKER_ENDPOINT CONFIG_MQTT_BROKER_ENDPOINT 83 | 84 | /** 85 | * @brief The port to use for the demo. 86 | * 87 | * In general, port 8883 is for secured MQTT connections. 88 | * 89 | * @note Port 443 requires use of the ALPN TLS extension with the ALPN protocol 90 | * name. When using port 8883, ALPN is not required. 91 | * 92 | * #define democonfigMQTT_BROKER_PORT ( insert here ) 93 | */ 94 | #define democonfigMQTT_BROKER_PORT CONFIG_MQTT_BROKER_PORT 95 | 96 | /** 97 | * @brief The username value for authenticating client to the MQTT broker when 98 | * username/password based client authentication is used. 99 | * 100 | * For AWS IoT MQTT broker, refer to the AWS IoT documentation below for 101 | * details regarding client authentication with a username and password. 102 | * https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html 103 | * An authorizer setup needs to be done, as mentioned in the above link, to use 104 | * username/password based client authentication. 105 | * 106 | * #define democonfigCLIENT_USERNAME "...insert here..." 107 | */ 108 | 109 | /** 110 | * @brief The password value for authenticating client to the MQTT broker when 111 | * username/password based client authentication is used. 112 | * 113 | * For AWS IoT MQTT broker, refer to the AWS IoT documentation below for 114 | * details regarding client authentication with a username and password. 115 | * https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html 116 | * An authorizer setup needs to be done, as mentioned in the above link, to use 117 | * username/password based client authentication. 118 | * 119 | * #define democonfigCLIENT_PASSWORD "...insert here..." 120 | */ 121 | 122 | /** 123 | * @brief The name of the operating system that the application is running on. 124 | * The current value is given as an example. Please update for your specific 125 | * operating system. 126 | */ 127 | #define democonfigOS_NAME "FreeRTOS" 128 | 129 | /** 130 | * @brief The version of the operating system that the application is running 131 | * on. The current value is given as an example. Please update for your specific 132 | * operating system version. 133 | */ 134 | #define democonfigOS_VERSION tskKERNEL_VERSION_NUMBER 135 | 136 | /** 137 | * @brief The name of the hardware platform the application is running on. The 138 | * current value is given as an example. Please update for your specific 139 | * hardware platform. 140 | */ 141 | #define democonfigHARDWARE_PLATFORM_NAME CONFIG_HARDWARE_PLATFORM_NAME 142 | 143 | /** 144 | * @brief The name of the MQTT library used and its version, following an "@" 145 | * symbol. 146 | */ 147 | #define democonfigMQTT_LIB "core-mqtt@1.0.0" 148 | 149 | /** 150 | * @brief Size of the network buffer for MQTT packets. 151 | */ 152 | #define democonfigNETWORK_BUFFER_SIZE CONFIG_MQTT_NETWORK_BUFFER_SIZE 153 | 154 | #endif /* DEMO_CONFIG_H */ 155 | -------------------------------------------------------------------------------- /examples/jobs/main/idf_component.yml: -------------------------------------------------------------------------------- 1 | ## IDF Component Manager Manifest File 2 | dependencies: 3 | espressif/esp_secure_cert_mgr: "^2.0.5" 4 | -------------------------------------------------------------------------------- /examples/jobs/main/mqtt_demo_helpers.h: -------------------------------------------------------------------------------- 1 | /* 2 | * AWS IoT Device SDK for Embedded C 202103.00 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | * this software and associated documentation files (the "Software"), to deal in 7 | * the Software without restriction, including without limitation the rights to 8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | * the Software, and to permit persons to whom the Software is furnished to do so, 10 | * subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #ifndef MQTT_DEMO_HELPERS_H_ 24 | #define MQTT_DEMO_HELPERS_H_ 25 | 26 | /* Include Demo Config as the first non-system header. */ 27 | #include "demo_config.h" 28 | 29 | /* MQTT API header. */ 30 | #include "core_mqtt.h" 31 | 32 | /* Transport interface implementation include header for TLS. */ 33 | #include "network_transport.h" 34 | 35 | /** 36 | * @brief Timeout for MQTT_ProcessLoop function in milliseconds. 37 | */ 38 | #define MQTT_PROCESS_LOOP_TIMEOUT_MS ( 1500U ) 39 | 40 | /** 41 | * @brief Establish a MQTT connection. 42 | * 43 | * @param[in] appCallback The callback function used to receive incoming 44 | * publishes and incoming acks from MQTT library. 45 | * 46 | * @return EXIT_SUCCESS if an MQTT session is established; 47 | * EXIT_FAILURE otherwise. 48 | */ 49 | int32_t EstablishMqttSession( MQTTEventCallback_t eventCallback ); 50 | 51 | /** 52 | * @brief Handle the incoming packet if it's not related to the device shadow. 53 | * 54 | * @param[in] pPacketInfo Packet Info pointer for the incoming packet. 55 | * @param[in] packetIdentifier Packet identifier of the incoming packet. 56 | */ 57 | void HandleOtherIncomingPacket( MQTTPacketInfo_t * pPacketInfo, 58 | uint16_t packetIdentifier ); 59 | 60 | /** 61 | * @brief Close the MQTT connection. 62 | * 63 | * @return EXIT_SUCCESS if DISCONNECT was successfully sent; 64 | * EXIT_FAILURE otherwise. 65 | */ 66 | int32_t DisconnectMqttSession( void ); 67 | 68 | /** 69 | * @brief Subscribe to a MQTT topic filter. 70 | * 71 | * @param[in] pTopicFilter Pointer to the shadow topic buffer. 72 | * @param[in] topicFilterLength Indicates the length of the shadow 73 | * topic buffer. 74 | * 75 | * @return EXIT_SUCCESS if SUBSCRIBE was successfully sent; 76 | * EXIT_FAILURE otherwise. 77 | */ 78 | int32_t SubscribeToTopic( const char * pTopicFilter, 79 | uint16_t topicFilterLength ); 80 | 81 | /** 82 | * @brief Sends an MQTT UNSUBSCRIBE to unsubscribe from the shadow 83 | * topic. 84 | * 85 | * @param[in] pTopicFilter Pointer to the shadow topic buffer. 86 | * @param[in] topicFilterLength Indicates the length of the shadow 87 | * topic buffer. 88 | * 89 | * @return EXIT_SUCCESS if UNSUBSCRIBE was successfully sent; 90 | * EXIT_FAILURE otherwise. 91 | */ 92 | int32_t UnsubscribeFromTopic( const char * pTopicFilter, 93 | uint16_t topicFilterLength ); 94 | 95 | /** 96 | * @brief Publish a message to a MQTT topic. 97 | * 98 | * @param[in] pTopicFilter Points to the topic. 99 | * @param[in] topicFilterLength The length of the topic. 100 | * @param[in] pPayload Points to the payload. 101 | * @param[in] payloadLength The length of the payload. 102 | * 103 | * @return EXIT_SUCCESS if PUBLISH was successfully sent; 104 | * EXIT_FAILURE otherwise. 105 | */ 106 | int32_t PublishToTopic( const char * pTopicFilter, 107 | int32_t topicFilterLength, 108 | const char * pPayload, 109 | size_t payloadLength ); 110 | 111 | /** 112 | * @brief Call #MQTT_ProcessLoop in a loop for the duration of a timeout or 113 | * #MQTT_ProcessLoop returns a failure. 114 | * 115 | * @param[in] ulTimeoutMs Duration to call #MQTT_ProcessLoop for. 116 | * 117 | * @return Returns the return value of the last call to #MQTT_ProcessLoop. 118 | */ 119 | MQTTStatus_t processLoopWithTimeout( uint32_t ulTimeoutMs ); 120 | 121 | /** 122 | * @brief Call #MQTT_ProcessLoop on the static global MQTT context. 123 | * @return Returns the return value #MQTT_ProcessLoop. 124 | */ 125 | MQTTStatus_t processLoop( void ); 126 | 127 | #endif /* ifndef SHADOW_DEMO_HELPERS_H_ */ 128 | -------------------------------------------------------------------------------- /examples/jobs/partitions.csv: -------------------------------------------------------------------------------- 1 | # Name, Type, SubType, Offset, Size, Flags 2 | # Note: if you change the phy_init or app partition offset, make sure to change the offset in Kconfig.projbuild 3 | esp_secure_cert, 0x3F, , 0xD000, 0x2000, encrypted 4 | nvs, data, nvs, , 0x9000 5 | phy_init, data, phy, , 0x1000 6 | factory, app, factory, 0x20000, 1M, 7 | -------------------------------------------------------------------------------- /examples/jobs/sdkconfig.defaults: -------------------------------------------------------------------------------- 1 | # newlib for ESP32 and ESP8266 platform 2 | 3 | CONFIG_NEWLIB_ENABLE=y 4 | CONFIG_NEWLIB_LIBRARY_LEVEL_NORMAL=y 5 | CONFIG_NEWLIB_NANO_FORMAT= 6 | CONFIG_SSL_USING_MBEDTLS=y 7 | CONFIG_LWIP_IPV6=y 8 | CONFIG_PARTITION_TABLE_CUSTOM=y 9 | CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" 10 | CONFIG_PARTITION_TABLE_FILENAME="partitions.csv" 11 | -------------------------------------------------------------------------------- /examples/mqtt/tls_mutual_auth/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # The following five lines of boilerplate have to be in your project's 2 | # CMakeLists in this exact order for cmake to work correctly 3 | cmake_minimum_required(VERSION 3.5) 4 | 5 | set(EXTRA_COMPONENT_DIRS "$ENV{IDF_PATH}/examples/common_components/protocol_examples_common" 6 | "${CMAKE_CURRENT_LIST_DIR}/../../../libraries/backoffAlgorithm" 7 | "${CMAKE_CURRENT_LIST_DIR}/../../../libraries/coreMQTT" 8 | "${CMAKE_CURRENT_LIST_DIR}/../../../libraries/common/posix_compat" 9 | ) 10 | 11 | include($ENV{IDF_PATH}/tools/cmake/project.cmake) 12 | project(tls_mutual_auth) 13 | 14 | target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/certs/root_cert_auth.crt" TEXT) 15 | target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/certs/client.crt" TEXT) 16 | target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/certs/client.key" TEXT) 17 | -------------------------------------------------------------------------------- /examples/mqtt/tls_mutual_auth/README.md: -------------------------------------------------------------------------------- 1 | # Amazon Web Services IoT MQTT (TLS Mutual Authentication) Example 2 | 3 | This is an adaptation of the [AWS IoT C SDK](https://github.com/aws/aws-iot-device-sdk-embedded-C) "mqtt_demo_mutual_auth" example for ESP-IDF. 4 | 5 | # Provisioning/Configuration 6 | 7 | See the README.md in the parent directory for information about configuring the AWS IoT examples. 8 | 9 | Few additional steps to be carried out: 10 | 11 | ## Find & Set AWS Endpoint Hostname 12 | 13 | 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. 14 | 15 | Run `idf.py menuconfig`. Under `Example Configuration`, set the `MQTT Broker Endpoint` to the host name. 16 | 17 | ## Set Client ID 18 | 19 | Run `idf.py menuconfig`. Under `Example Configuration`, set the `MQTT Client ID` to a unique value. 20 | 21 | 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. 22 | 23 | In a production IoT app this ID would be set dynamically, but for these examples it is compiled in via menuconfig. 24 | 25 | ## (Optional) Locally Check The Root Certificate 26 | 27 | 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/root_cert_auth.pem`. 28 | 29 | 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: 30 | 31 | ``` 32 | openssl s_client -showcerts -connect hostname:8883 < /dev/null 33 | ``` 34 | 35 | (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 `root_cert_auth.pem` file. 36 | 37 | # Console 38 | 39 | After flashing the example to your ESP32, it should connect to Amazon and start subscriping and publishing to example/topic. 40 | 41 | In the ESP32's serial output, you should see the logs every couple of seconds. 42 | 43 | ``` 44 | [INFO] [MQTT_DEMO] [subscribePublishLoop:1342] Creating an MQTT connection to a2hokgmhoqmk0-ats.iot.us-east-1.amazonaws.com. 45 | [INFO] [MQTT_DEMO] [establishMqttSession:1111] MQTT connection successfully established with broker. 46 | 47 | [INFO] [MQTT_DEMO] [subscribePublishLoop:1374] A clean MQTT connection is established. Cleaning up all the stored outgoing publishes. 48 | 49 | [INFO] [MQTT_DEMO] [subscribePublishLoop:1392] Subscribing to the MQTT topic thingname/example/topic. 50 | [INFO] [MQTT_DEMO] [subscribeToTopic:1175] SUBSCRIBE sent for topic thingname/example/topic to broker. 51 | 52 | [INFO] [MQTT_DEMO] [eventCallback:998] Subscribed to the topic thingname/example/topic. with maximum QoS 1. 53 | 54 | [INFO] [MQTT_DEMO] [subscribePublishLoop:1436] Sending Publish to the MQTT topic thingname/example/topic. 55 | [INFO] [MQTT_DEMO] [publishToTopic:1273] PUBLISH sent for topic thingname/example/topic to broker with packet ID 2. 56 | ``` 57 | # Troubleshooting 58 | 59 | If you're having problems with the AWS IoT connection itself, check the Troubleshooting section of the README in the parent directory. 60 | -------------------------------------------------------------------------------- /examples/mqtt/tls_mutual_auth/main/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(COMPONENT_SRCS 2 | "app_main.c" 3 | "mqtt_demo_mutual_auth.c" 4 | ) 5 | 6 | set(COMPONENT_ADD_INCLUDEDIRS 7 | "." 8 | "${CMAKE_CURRENT_LIST_DIR}" 9 | ) 10 | 11 | idf_component_register(SRCS "${COMPONENT_SRCS}" 12 | INCLUDE_DIRS ${COMPONENT_ADD_INCLUDEDIRS} 13 | ) -------------------------------------------------------------------------------- /examples/mqtt/tls_mutual_auth/main/Kconfig.projbuild: -------------------------------------------------------------------------------- 1 | menu "Example Configuration" 2 | 3 | config MQTT_CLIENT_IDENTIFIER 4 | string "The MQTT client identifier used in this example" 5 | default "testClient" 6 | help 7 | The MQTT client identifier used in this example. Each client identifier must be unique. 8 | so edit as required to ensure that no two clients connecting to the same broker use the same client identifier. 9 | 10 | config MQTT_BROKER_ENDPOINT 11 | string "Endpoint of the MQTT broker to connect to" 12 | default "test.mosquitto.org" 13 | help 14 | This example can be run with any MQTT broker, that supports server authentication. 15 | 16 | config MQTT_BROKER_PORT 17 | int "Port of the MQTT broker use" 18 | default 8883 19 | help 20 | In general, port 8883 is for secured MQTT connections. 21 | Port 443 requires use of the ALPN TLS extension with the ALPN protocol name. 22 | When using port 8883, ALPN is not required. 23 | 24 | config HARDWARE_PLATFORM_NAME 25 | string "The hardware platform" 26 | default "ESP32" 27 | help 28 | The name of the hardware platform the application is running on. 29 | 30 | config MQTT_NETWORK_BUFFER_SIZE 31 | int "Size of the network buffer for MQTT packets" 32 | range 1024 2048 33 | default 1024 34 | help 35 | Size of the network buffer for MQTT packets. 36 | 37 | choice EXAMPLE_CHOOSE_PKI_ACCESS_METHOD 38 | prompt "Choose PKI credentials access method" 39 | default EXAMPLE_USE_PLAIN_FLASH_STORAGE 40 | help 41 | ESP devices support multiple ways to secure store the PKI credentials. 42 | Currently Secure Element (ATECC608A) and DS peripheral 43 | (using ESP Secure Cert Manager) are supported. 44 | The default behaviour is to access the PKI credentials which are embedded in the binary. 45 | Consult the ESP-TLS documentation in ESP-IDF Programming guide for more details. 46 | 47 | config EXAMPLE_USE_SECURE_ELEMENT 48 | bool "Use secure element (ATECC608A)" 49 | depends on (IDF_TARGET_ESP32 || IDF_TARGET_ESP32C2) && ESP_TLS_USING_MBEDTLS 50 | select ESP_TLS_USE_SECURE_ELEMENT 51 | help 52 | Enable the use of secure element for the example. 53 | The esp-cryptoauthlib component is required for enabling 54 | this option. 55 | 56 | config EXAMPLE_USE_ESP_SECURE_CERT_MGR 57 | bool "Use ESP Secure Certificate Manager" 58 | help 59 | Enable the use of ESP Secure Certificate Manager APIs for the example. 60 | Please refer to ESP Secure Certificate Manager documentation for more details. 61 | 62 | config EXAMPLE_USE_PLAIN_FLASH_STORAGE 63 | bool "Use flash storage (default)" 64 | help 65 | This option expects the Private key and Device certificate to be embedded in the binary. 66 | This is the default behaviour. 67 | endchoice 68 | 69 | endmenu 70 | -------------------------------------------------------------------------------- /examples/mqtt/tls_mutual_auth/main/app_main.c: -------------------------------------------------------------------------------- 1 | /* tls-mutual-auth example 2 | 3 | This example code is in the Public Domain (or CC0 licensed, at your option.) 4 | 5 | Unless required by applicable law or agreed to in writing, this 6 | software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 7 | CONDITIONS OF ANY KIND, either express or implied. 8 | */ 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "esp_system.h" 14 | #include "nvs_flash.h" 15 | #include "esp_event.h" 16 | #include "esp_netif.h" 17 | #include "protocol_examples_common.h" 18 | 19 | #include "esp_log.h" 20 | 21 | int aws_iot_demo_main( int argc, char ** argv ); 22 | 23 | static const char *TAG = "MQTT_EXAMPLE"; 24 | 25 | /* 26 | * Prototypes for the demos that can be started from this project. Note the 27 | * MQTT demo is not actually started until the network is already. 28 | */ 29 | 30 | void app_main() 31 | { 32 | ESP_LOGI(TAG, "[APP] Startup.."); 33 | ESP_LOGI(TAG, "[APP] Free memory: %"PRIu32" bytes", esp_get_free_heap_size()); 34 | ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version()); 35 | 36 | esp_log_level_set("*", ESP_LOG_INFO); 37 | 38 | /* Initialize NVS partition */ 39 | esp_err_t ret = nvs_flash_init(); 40 | if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { 41 | /* NVS partition was truncated 42 | * and needs to be erased */ 43 | ESP_ERROR_CHECK(nvs_flash_erase()); 44 | 45 | /* Retry nvs_flash_init */ 46 | ESP_ERROR_CHECK(nvs_flash_init()); 47 | } 48 | 49 | ESP_ERROR_CHECK(esp_netif_init()); 50 | ESP_ERROR_CHECK(esp_event_loop_create_default()); 51 | 52 | /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig. 53 | * Read "Establishing Wi-Fi or Ethernet Connection" section in 54 | * examples/protocols/README.md for more information about this function. 55 | */ 56 | ESP_ERROR_CHECK(example_connect()); 57 | 58 | aws_iot_demo_main(0,NULL); 59 | } 60 | -------------------------------------------------------------------------------- /examples/mqtt/tls_mutual_auth/main/certs/client.crt: -------------------------------------------------------------------------------- 1 | Certificate goes here. -------------------------------------------------------------------------------- /examples/mqtt/tls_mutual_auth/main/certs/client.key: -------------------------------------------------------------------------------- 1 | Key goes here. -------------------------------------------------------------------------------- /examples/mqtt/tls_mutual_auth/main/certs/root_cert_auth.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF 3 | ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 4 | b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL 5 | MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv 6 | b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj 7 | ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM 8 | 9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw 9 | IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6 10 | VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L 11 | 93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm 12 | jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC 13 | AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA 14 | A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI 15 | U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs 16 | N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv 17 | o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU 18 | 5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy 19 | rqXRfboQnoZsG4q5WTP468SQvvG5 20 | -----END CERTIFICATE----- -------------------------------------------------------------------------------- /examples/mqtt/tls_mutual_auth/main/demo_config.h: -------------------------------------------------------------------------------- 1 | /* 2 | * AWS IoT Device SDK for Embedded C 202103.00 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | * this software and associated documentation files (the "Software"), to deal in 7 | * the Software without restriction, including without limitation the rights to 8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | * the Software, and to permit persons to whom the Software is furnished to do so, 10 | * subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #ifndef DEMO_CONFIG_H_ 24 | #define DEMO_CONFIG_H_ 25 | 26 | /**************************************************/ 27 | /******* DO NOT CHANGE the following order ********/ 28 | /**************************************************/ 29 | 30 | /* Logging related header files are required to be included in the following order: 31 | * 1. Include the header file "logging_levels.h". 32 | * 2. Define LIBRARY_LOG_NAME and LIBRARY_LOG_LEVEL. 33 | * 3. Include the header file "logging_stack.h". 34 | */ 35 | 36 | /* Include header that defines log levels. */ 37 | #include "logging_levels.h" 38 | 39 | /* Logging configuration for the Demo. */ 40 | #ifndef LIBRARY_LOG_NAME 41 | #define LIBRARY_LOG_NAME "MQTT_DEMO" 42 | #endif 43 | #ifndef LIBRARY_LOG_LEVEL 44 | #define LIBRARY_LOG_LEVEL LOG_INFO 45 | #endif 46 | 47 | #include "logging_stack.h" 48 | 49 | /************ End of logging configuration ****************/ 50 | 51 | 52 | /** 53 | * @brief Details of the MQTT broker to connect to. 54 | * 55 | * @note Your AWS IoT Core endpoint can be found in the AWS IoT console under 56 | * Settings/Custom Endpoint, or using the describe-endpoint API. 57 | * 58 | */ 59 | #ifndef AWS_IOT_ENDPOINT 60 | #define AWS_IOT_ENDPOINT CONFIG_MQTT_BROKER_ENDPOINT 61 | #endif 62 | 63 | /** 64 | * @brief AWS IoT MQTT broker port number. 65 | * 66 | * In general, port 8883 is for secured MQTT connections. 67 | * 68 | * @note Port 443 requires use of the ALPN TLS extension with the ALPN protocol 69 | * name. When using port 8883, ALPN is not required. 70 | */ 71 | #ifndef AWS_MQTT_PORT 72 | #define AWS_MQTT_PORT ( CONFIG_MQTT_BROKER_PORT ) 73 | #endif 74 | 75 | /** 76 | * @brief The username value for authenticating client to MQTT broker when 77 | * username/password based client authentication is used. 78 | * 79 | * Refer to the AWS IoT documentation below for details regarding client 80 | * authentication with a username and password. 81 | * https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html 82 | * As mentioned in the link above, an authorizer setup needs to be done to use 83 | * username/password based client authentication. 84 | * 85 | * @note AWS IoT message broker requires either a set of client certificate/private key 86 | * or username/password to authenticate the client. If this config is defined, 87 | * the username and password will be used instead of the client certificate and 88 | * private key for client authentication. 89 | * 90 | * #define CLIENT_USERNAME "...insert here..." 91 | */ 92 | 93 | /** 94 | * @brief The password value for authenticating client to MQTT broker when 95 | * username/password based client authentication is used. 96 | * 97 | * Refer to the AWS IoT documentation below for details regarding client 98 | * authentication with a username and password. 99 | * https://docs.aws.amazon.com/iot/latest/developerguide/custom-authentication.html 100 | * As mentioned in the link above, an authorizer setup needs to be done to use 101 | * username/password based client authentication. 102 | * 103 | * @note AWS IoT message broker requires either a set of client certificate/private key 104 | * or username/password to authenticate the client. 105 | * 106 | * #define CLIENT_PASSWORD "...insert here..." 107 | */ 108 | 109 | /** 110 | * @brief MQTT client identifier. 111 | * 112 | * No two clients may use the same client identifier simultaneously. 113 | */ 114 | #ifndef CLIENT_IDENTIFIER 115 | #define CLIENT_IDENTIFIER CONFIG_MQTT_CLIENT_IDENTIFIER 116 | #endif 117 | 118 | /** 119 | * @brief Size of the network buffer for MQTT packets. 120 | */ 121 | #define NETWORK_BUFFER_SIZE ( CONFIG_MQTT_NETWORK_BUFFER_SIZE ) 122 | 123 | /** 124 | * @brief The name of the operating system that the application is running on. 125 | * The current value is given as an example. Please update for your specific 126 | * operating system. 127 | */ 128 | #define OS_NAME "FreeRTOS" 129 | 130 | /** 131 | * @brief The version of the operating system that the application is running 132 | * on. The current value is given as an example. Please update for your specific 133 | * operating system version. 134 | */ 135 | #define OS_VERSION tskKERNEL_VERSION_NUMBER 136 | 137 | /** 138 | * @brief The name of the hardware platform the application is running on. The 139 | * current value is given as an example. Please update for your specific 140 | * hardware platform. 141 | */ 142 | #define HARDWARE_PLATFORM_NAME CONFIG_HARDWARE_PLATFORM_NAME 143 | 144 | /** 145 | * @brief The name of the MQTT library used and its version, following an "@" 146 | * symbol. 147 | */ 148 | #include "core_mqtt.h" 149 | #define MQTT_LIB "core-mqtt@" MQTT_LIBRARY_VERSION 150 | 151 | #endif /* ifndef DEMO_CONFIG_H_ */ 152 | -------------------------------------------------------------------------------- /examples/mqtt/tls_mutual_auth/main/idf_component.yml: -------------------------------------------------------------------------------- 1 | ## IDF Component Manager Manifest File 2 | dependencies: 3 | espressif/esp_secure_cert_mgr: "^2.0.5" 4 | -------------------------------------------------------------------------------- /examples/mqtt/tls_mutual_auth/partitions.csv: -------------------------------------------------------------------------------- 1 | # Name, Type, SubType, Offset, Size, Flags 2 | # Note: if you change the phy_init or app partition offset, make sure to change the offset in Kconfig.projbuild 3 | esp_secure_cert, 0x3F, , 0xD000, 0x2000, encrypted 4 | nvs, data, nvs, , 0x9000 5 | phy_init, data, phy, , 0x1000 6 | factory, app, factory, 0x20000, 1M, 7 | -------------------------------------------------------------------------------- /examples/mqtt/tls_mutual_auth/sdkconfig.defaults: -------------------------------------------------------------------------------- 1 | # newlib for ESP32 and ESP8266 platform 2 | 3 | CONFIG_NEWLIB_ENABLE=y 4 | CONFIG_NEWLIB_LIBRARY_LEVEL_NORMAL=y 5 | CONFIG_NEWLIB_NANO_FORMAT= 6 | CONFIG_SSL_USING_MBEDTLS=y 7 | CONFIG_LWIP_IPV6=y 8 | CONFIG_PARTITION_TABLE_CUSTOM=y 9 | CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" 10 | CONFIG_PARTITION_TABLE_FILENAME="partitions.csv" 11 | -------------------------------------------------------------------------------- /examples/ota/README.md: -------------------------------------------------------------------------------- 1 | The FreeRTOS 202406.01-LTS release uses the new and completely refactored 'Modular OTA' approach for Over the Air updates. 2 | It makes use of the new [AWS IoT MQTT File Streams Library](https://github.com/espressif/esp-aws-iot/tree/master/libraries/aws-iot-core-mqtt-file-streams-embedded-c) for OTA application design. 3 | More information about the approach can be found [here](https://www.freertos.org/freertos-core/over-the-air-updates/index.html#:~:text=OTA%20update%20provider.-,Modular%20OTA%20approach,-Modular%20OTA%20consists). 4 | 5 | Please refer to the [iot-reference example](https://github.com/FreeRTOS/iot-reference-esp32c3) for a production-ready starting point that uses this new approach. 6 | -------------------------------------------------------------------------------- /examples/thing_shadow/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # The following five lines of boilerplate have to be in your project's 2 | # CMakeLists in this exact order for cmake to work correctly 3 | cmake_minimum_required(VERSION 3.5) 4 | 5 | set(EXTRA_COMPONENT_DIRS "$ENV{IDF_PATH}/examples/common_components/protocol_examples_common" 6 | "${CMAKE_CURRENT_LIST_DIR}/../../libraries/coreMQTT" 7 | "${CMAKE_CURRENT_LIST_DIR}/../../libraries/Device-Shadow-for-AWS-IoT-embedded-sdk" 8 | "${CMAKE_CURRENT_LIST_DIR}/../../libraries/coreJSON" 9 | "${CMAKE_CURRENT_LIST_DIR}/../../libraries/backoffAlgorithm" 10 | "${CMAKE_CURRENT_LIST_DIR}/../../libraries/common/posix_compat" 11 | ) 12 | 13 | include($ENV{IDF_PATH}/tools/cmake/project.cmake) 14 | project(thing_shadow) 15 | 16 | target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/certs/root_cert_auth.crt" TEXT) 17 | target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/certs/client.crt" TEXT) 18 | target_add_binary_data(${CMAKE_PROJECT_NAME}.elf "main/certs/client.key" TEXT) 19 | -------------------------------------------------------------------------------- /examples/thing_shadow/README.md: -------------------------------------------------------------------------------- 1 | # Amazon Web Services IoT Thing Shadow Example 2 | 3 | This is an adaptation of the [AWS IoT C SDK](https://github.com/aws/aws-iot-device-sdk-embedded-C) "shadow_demo_main" example for ESP-IDF. 4 | 5 | # Provisioning/Configuration 6 | 7 | See the README.md in the parent directory for information about configuring the AWS IoT examples. 8 | 9 | Few additional steps to be carried out: 10 | 11 | ## Find & Set AWS Endpoint Hostname 12 | 13 | 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. 14 | 15 | Run `idf.py menuconfig`. Under `Example Configuration`, set the `MQTT Broker Endpoint` to the host name. 16 | 17 | ## Set Thing Name 18 | 19 | Run `idf.py menuconfig`. Under `Example Configuration`, set the `MQTT Client Identifier` to the thing name. 20 | 21 | The Thing Name should match a Thing that you created while following the Getting Started guide (to check the Things you have registered, go to the AWS IoT console web interface, click Registry and then click Things). 22 | 23 | ## (Optional) Locally Check The Root Certificate 24 | 25 | 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/root_cert_auth.pem`. 26 | 27 | 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: 28 | 29 | ``` 30 | openssl s_client -showcerts -connect hostname:8883 < /dev/null 31 | ``` 32 | 33 | (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 `root_cert_auth.pem` file. 34 | 35 | 36 | # Monitoring Thing Status 37 | 38 | After flashing the example to your ESP32, it should connect to Amazon and start updating the example Thing's shadow. 39 | 40 | In the ESP32's serial output, you should see the logs every couple of seconds. 41 | 42 | ``` 43 | [INFO] [ShadowDemo] [EstablishMqttSession:683] MQTT connection successfully established with broker. 44 | [INFO] [ShadowDemo] [EstablishMqttSession:703] An MQTT session with broker is re-established. Resending unacked publishes. 45 | [INFO] [ShadowDemo] [SubscribeToTopic:795] SUBSCRIBE topic $aws/things/thingname/shadow/delete/accepted to broker. 46 | [INFO] [ShadowDemo] [HandleOtherIncomingPacket:505] MQTT_PACKET_TYPE_SUBACK. 47 | [INFO] [ShadowDemo] [SubscribeToTopic:795] SUBSCRIBE topic $aws/things/thingname/shadow/delete/rejected to broker. 48 | [INFO] [ShadowDemo] [HandleOtherIncomingPacket:505] MQTT_PACKET_TYPE_SUBACK. 49 | [INFO] [ShadowDemo] [PublishToTopic:908] Published payload: 50 | [INFO] [ShadowDemo] [PublishToTopic:936] PUBLISH sent for topic $aws/things/thingname/shadow/delete to broker with packet ID 3. 51 | [INFO] [ShadowDemo] [HandleOtherIncomingPacket:526] PUBACK received for packet id 3. 52 | [INFO] [ShadowDemo] [cleanupOutgoingPublishWithPacketID:490] Cleaned up outgoing publish packet with packet id 3. 53 | [INFO] [SHADOW] [eventCallback:579] pPublishInfo->pTopicName:$aws/things/thingname/shadow/delete/accepted. 54 | 55 | ``` 56 | 57 | You can monitor the Thing status from the AWS IoT console web interface: 58 | 59 | * On the left-hand toolbar, click Registry and then click Things. 60 | * Click on the "Thing" you set up for the example. 61 | * Click on the "Shadow" sidebar link. You should see the Thing Shadow updating regularly. 62 | * Click on the "Activity" sidebar link to see all Thing Shadow updates in a list. You can examine each update individually. 63 | 64 | # Troubleshooting 65 | 66 | If you're having problems with the AWS IoT connection itself, check the Troubleshooting section of the README in the parent directory. 67 | 68 | * 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 `MQTT Client Identifier` in the Example Configuration under menuconfig matches exactly the thing name in AWS IoT console (including case). 69 | -------------------------------------------------------------------------------- /examples/thing_shadow/main/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(COMPONENT_SRCS 2 | "app_main.c" 3 | "shadow_demo_main.c" 4 | "shadow_demo_helpers.c" 5 | ) 6 | 7 | set(COMPONENT_ADD_INCLUDEDIRS 8 | "." 9 | "${CMAKE_CURRENT_LIST_DIR}" 10 | "${PROJECT_DIR}/../../libraries/common/logging/" 11 | ) 12 | 13 | idf_component_register(SRCS "${COMPONENT_SRCS}" 14 | INCLUDE_DIRS ${COMPONENT_ADD_INCLUDEDIRS} 15 | ) 16 | -------------------------------------------------------------------------------- /examples/thing_shadow/main/Kconfig.projbuild: -------------------------------------------------------------------------------- 1 | menu "Example Configuration" 2 | 3 | config MQTT_CLIENT_IDENTIFIER 4 | string "The MQTT client identifier used in this example. Also used as Thing Name" 5 | default "testClient" 6 | help 7 | The MQTT client identifier used in this example. Each client identifier must be unique. 8 | so edit as required to ensure that no two clients connecting to the same broker use the same client identifier. 9 | 10 | config MQTT_BROKER_ENDPOINT 11 | string "Endpoint of the MQTT broker to connect to" 12 | default "test.mosquitto.org" 13 | help 14 | This example can be run with any MQTT broker, that supports server authentication. 15 | 16 | config MQTT_BROKER_PORT 17 | int "Port of the MQTT broker use" 18 | default 8883 19 | help 20 | In general, port 8883 is for secured MQTT connections. 21 | Port 443 requires use of the ALPN TLS extension with the ALPN protocol name. 22 | When using port 8883, ALPN is not required. 23 | 24 | config HARDWARE_PLATFORM_NAME 25 | string "The hardware platform" 26 | default "ESP32" 27 | help 28 | The name of the hardware platform the application is running on. 29 | 30 | config MQTT_NETWORK_BUFFER_SIZE 31 | int "Size of the network buffer for MQTT packets" 32 | range 1024 2048 33 | default 1024 34 | help 35 | Size of the network buffer for MQTT packets. 36 | 37 | choice EXAMPLE_CHOOSE_PKI_ACCESS_METHOD 38 | prompt "Choose PKI credentials access method" 39 | default EXAMPLE_USE_PLAIN_FLASH_STORAGE 40 | help 41 | ESP devices support multiple ways to secure store the PKI credentials. 42 | Currently Secure Element (ATECC608A) and DS peripheral 43 | (using ESP Secure Cert Manager) are supported. 44 | The default behaviour is to access the PKI credentials which are embedded in the binary. 45 | Consult the ESP-TLS documentation in ESP-IDF Programming guide for more details. 46 | 47 | config EXAMPLE_USE_SECURE_ELEMENT 48 | bool "Use secure element (ATECC608A)" 49 | depends on (IDF_TARGET_ESP32 || IDF_TARGET_ESP32C2) && ESP_TLS_USING_MBEDTLS 50 | # To confirm that we are satisfying the dependencies of secure element 51 | select ESP_TLS_USE_SECURE_ELEMENT 52 | help 53 | Enable the use of secure element for the example. 54 | The esp-cryptoauthlib component is required for enabling 55 | this option. 56 | 57 | config EXAMPLE_USE_ESP_SECURE_CERT_MGR 58 | bool "Use ESP Secure Certificate Manager" 59 | help 60 | Enable the use of ESP Secure Certificate Manager APIs for the example. 61 | Please refer to ESP Secure Certificate Manager documentation for more details. 62 | 63 | config EXAMPLE_USE_PLAIN_FLASH_STORAGE 64 | bool "Use flash storage (default)" 65 | help 66 | This option expects the Private key and Device certificate to be embedded in the binary. 67 | This is the default behaviour. 68 | endchoice 69 | 70 | endmenu 71 | -------------------------------------------------------------------------------- /examples/thing_shadow/main/app_main.c: -------------------------------------------------------------------------------- 1 | /* thing-shadow example 2 | 3 | This example code is in the Public Domain (or CC0 licensed, at your option.) 4 | 5 | Unless required by applicable law or agreed to in writing, this 6 | software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 7 | CONDITIONS OF ANY KIND, either express or implied. 8 | */ 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include "esp_system.h" 14 | #include "nvs_flash.h" 15 | #include "esp_event.h" 16 | #include "esp_netif.h" 17 | #include "protocol_examples_common.h" 18 | 19 | int aws_iot_demo_main( int argc, char ** argv ); 20 | 21 | #include "esp_log.h" 22 | 23 | static const char *TAG = "SHADOW_EXAMPLE"; 24 | 25 | /* 26 | * Prototypes for the demos that can be started from this project. Note the 27 | * Shadow demo is not actually started until the network is already. 28 | */ 29 | 30 | void app_main() 31 | { 32 | ESP_LOGI(TAG, "[APP] Startup.."); 33 | ESP_LOGI(TAG, "[APP] Free memory: %"PRIu32" bytes", esp_get_free_heap_size()); 34 | ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version()); 35 | 36 | esp_log_level_set("*", ESP_LOG_INFO); 37 | 38 | /* Initialize NVS partition */ 39 | esp_err_t ret = nvs_flash_init(); 40 | if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) { 41 | /* NVS partition was truncated 42 | * and needs to be erased */ 43 | ESP_ERROR_CHECK(nvs_flash_erase()); 44 | 45 | /* Retry nvs_flash_init */ 46 | ESP_ERROR_CHECK(nvs_flash_init()); 47 | } 48 | 49 | ESP_ERROR_CHECK(esp_netif_init()); 50 | ESP_ERROR_CHECK(esp_event_loop_create_default()); 51 | 52 | /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig. 53 | * Read "Establishing Wi-Fi or Ethernet Connection" section in 54 | * examples/protocols/README.md for more information about this function. 55 | */ 56 | ESP_ERROR_CHECK(example_connect()); 57 | 58 | aws_iot_demo_main(0,NULL); 59 | } 60 | -------------------------------------------------------------------------------- /examples/thing_shadow/main/certs/client.crt: -------------------------------------------------------------------------------- 1 | Certificate goes here. -------------------------------------------------------------------------------- /examples/thing_shadow/main/certs/client.key: -------------------------------------------------------------------------------- 1 | Key goes here. -------------------------------------------------------------------------------- /examples/thing_shadow/main/certs/root_cert_auth.crt: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDQTCCAimgAwIBAgITBmyfz5m/jAo54vB4ikPmljZbyjANBgkqhkiG9w0BAQsF 3 | ADA5MQswCQYDVQQGEwJVUzEPMA0GA1UEChMGQW1hem9uMRkwFwYDVQQDExBBbWF6 4 | b24gUm9vdCBDQSAxMB4XDTE1MDUyNjAwMDAwMFoXDTM4MDExNzAwMDAwMFowOTEL 5 | MAkGA1UEBhMCVVMxDzANBgNVBAoTBkFtYXpvbjEZMBcGA1UEAxMQQW1hem9uIFJv 6 | b3QgQ0EgMTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALJ4gHHKeNXj 7 | ca9HgFB0fW7Y14h29Jlo91ghYPl0hAEvrAIthtOgQ3pOsqTQNroBvo3bSMgHFzZM 8 | 9O6II8c+6zf1tRn4SWiw3te5djgdYZ6k/oI2peVKVuRF4fn9tBb6dNqcmzU5L/qw 9 | IFAGbHrQgLKm+a/sRxmPUDgH3KKHOVj4utWp+UhnMJbulHheb4mjUcAwhmahRWa6 10 | VOujw5H5SNz/0egwLX0tdHA114gk957EWW67c4cX8jJGKLhD+rcdqsq08p8kDi1L 11 | 93FcXmn/6pUCyziKrlA4b9v7LWIbxcceVOF34GfID5yHI9Y/QCB/IIDEgEw+OyQm 12 | jgSubJrIqg0CAwEAAaNCMEAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMC 13 | AYYwHQYDVR0OBBYEFIQYzIU07LwMlJQuCFmcx7IQTgoIMA0GCSqGSIb3DQEBCwUA 14 | A4IBAQCY8jdaQZChGsV2USggNiMOruYou6r4lK5IpDB/G/wkjUu0yKGX9rbxenDI 15 | U5PMCCjjmCXPI6T53iHTfIUJrU6adTrCC2qJeHZERxhlbI1Bjjt/msv0tadQ1wUs 16 | N+gDS63pYaACbvXy8MWy7Vu33PqUXHeeE6V/Uq2V8viTO96LXFvKWlJbYK8U90vv 17 | o/ufQJVtMVT8QtPHRh8jrdkPSHCa2XV4cdFyQzR1bldZwgJcJmApzyMZFo6IQ6XU 18 | 5MsI+yMRQ+hDKXJioaldXgjUkK642M4UwtBV8ob2xJNDd2ZhwLnoQdeXeGADbkpy 19 | rqXRfboQnoZsG4q5WTP468SQvvG5 20 | -----END CERTIFICATE----- 21 | 22 | -------------------------------------------------------------------------------- /examples/thing_shadow/main/demo_config.h: -------------------------------------------------------------------------------- 1 | /* 2 | * AWS IoT Device SDK for Embedded C 202103.00 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | * this software and associated documentation files (the "Software"), to deal in 7 | * the Software without restriction, including without limitation the rights to 8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | * the Software, and to permit persons to whom the Software is furnished to do so, 10 | * subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #ifndef DEMO_CONFIG_H_ 24 | #define DEMO_CONFIG_H_ 25 | 26 | /**************************************************/ 27 | /******* DO NOT CHANGE the following order ********/ 28 | /**************************************************/ 29 | 30 | /* Logging related header files are required to be included in the following order: 31 | * 1. Include the header file "logging_levels.h". 32 | * 2. Define LIBRARY_LOG_NAME and LIBRARY_LOG_LEVEL. 33 | * 3. Include the header file "logging_stack.h". 34 | */ 35 | 36 | /* Include header that defines log levels. */ 37 | #include "logging_levels.h" 38 | 39 | /* Logging configuration for the Demo. */ 40 | #ifndef LIBRARY_LOG_NAME 41 | #define LIBRARY_LOG_NAME "SHADOW_DEMO" 42 | #endif 43 | #ifndef LIBRARY_LOG_LEVEL 44 | #define LIBRARY_LOG_LEVEL LOG_INFO 45 | #endif 46 | 47 | #include "logging_stack.h" 48 | 49 | /************ End of logging configuration ****************/ 50 | 51 | 52 | /** 53 | * @brief Details of the MQTT broker to connect to. 54 | * 55 | * @note Your AWS IoT Core endpoint can be found in the AWS IoT console under 56 | * Settings/Custom Endpoint, or using the describe-endpoint API. 57 | * 58 | */ 59 | #ifndef AWS_IOT_ENDPOINT 60 | #define AWS_IOT_ENDPOINT CONFIG_MQTT_BROKER_ENDPOINT 61 | #endif 62 | 63 | /** 64 | * @brief AWS IoT MQTT broker port number. 65 | * 66 | * In general, port 8883 is for secured MQTT connections. 67 | * 68 | * @note Port 443 requires use of the ALPN TLS extension with the ALPN protocol 69 | * name. When using port 8883, ALPN is not required. 70 | */ 71 | #ifndef AWS_MQTT_PORT 72 | #define AWS_MQTT_PORT ( CONFIG_MQTT_BROKER_PORT ) 73 | #endif 74 | 75 | /** 76 | * @brief MQTT client identifier. 77 | * 78 | * No two clients may use the same client identifier simultaneously. 79 | */ 80 | #ifndef CLIENT_IDENTIFIER 81 | #define CLIENT_IDENTIFIER CONFIG_MQTT_CLIENT_IDENTIFIER 82 | #endif 83 | 84 | /** 85 | * @brief Size of the network buffer for MQTT packets. 86 | */ 87 | #define NETWORK_BUFFER_SIZE ( CONFIG_MQTT_NETWORK_BUFFER_SIZE ) 88 | 89 | /** 90 | * @brief The name of the operating system that the application is running on. 91 | * The current value is given as an example. Please update for your specific 92 | * operating system. 93 | */ 94 | #define OS_NAME "FreeRTOS" 95 | 96 | /** 97 | * @brief The version of the operating system that the application is running 98 | * on. The current value is given as an example. Please update for your specific 99 | * operating system version. 100 | */ 101 | #define OS_VERSION tskKERNEL_VERSION_NUMBER 102 | 103 | /** 104 | * @brief The name of the hardware platform the application is running on. The 105 | * current value is given as an example. Please update for your specific 106 | * hardware platform. 107 | */ 108 | #define HARDWARE_PLATFORM_NAME CONFIG_HARDWARE_PLATFORM_NAME 109 | 110 | /** 111 | * @brief The name of the MQTT library used and its version, following an "@" 112 | * symbol. 113 | */ 114 | #include "core_mqtt.h" 115 | #define MQTT_LIB "core-mqtt@" MQTT_LIBRARY_VERSION 116 | 117 | /** 118 | * @brief Predefined thing name. 119 | * 120 | * This is the example predefine thing name and could be compiled in ROM code. 121 | */ 122 | #define THING_NAME CONFIG_MQTT_CLIENT_IDENTIFIER 123 | 124 | /** 125 | * @brief The length of #THING_NAME. 126 | */ 127 | #define THING_NAME_LENGTH ( ( uint16_t ) ( sizeof( THING_NAME ) - 1 ) ) 128 | 129 | /** 130 | * @brief Predefined shadow name. 131 | * 132 | * Defaults to unnamed "Classic" shadow. Change to a custom string to use a named shadow. 133 | */ 134 | #ifndef SHADOW_NAME 135 | #define SHADOW_NAME SHADOW_NAME_CLASSIC 136 | #endif 137 | 138 | /** 139 | * @brief The length of #SHADOW_NAME. 140 | */ 141 | #define SHADOW_NAME_LENGTH ( ( uint16_t ) ( sizeof( SHADOW_NAME ) - 1 ) ) 142 | 143 | #endif /* ifndef DEMO_CONFIG_H_ */ 144 | -------------------------------------------------------------------------------- /examples/thing_shadow/main/idf_component.yml: -------------------------------------------------------------------------------- 1 | ## IDF Component Manager Manifest File 2 | dependencies: 3 | espressif/esp_secure_cert_mgr: "^2.0.5" 4 | -------------------------------------------------------------------------------- /examples/thing_shadow/main/shadow_demo_helpers.h: -------------------------------------------------------------------------------- 1 | /* 2 | * AWS IoT Device SDK for Embedded C 202103.00 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | * this software and associated documentation files (the "Software"), to deal in 7 | * the Software without restriction, including without limitation the rights to 8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | * the Software, and to permit persons to whom the Software is furnished to do so, 10 | * subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #ifndef MQTT_DEMO_HELPERS_H_ 24 | #define MQTT_DEMO_HELPERS_H_ 25 | 26 | /* Include Demo Config as the first non-system header. */ 27 | #include "demo_config.h" 28 | 29 | /* MQTT API header. */ 30 | #include "core_mqtt.h" 31 | 32 | /** 33 | * @brief Establish a MQTT connection. 34 | * 35 | * @param[in] appCallback The callback function used to receive incoming 36 | * publishes and incoming acks from MQTT library. 37 | * 38 | * @return EXIT_SUCCESS if an MQTT session is established; 39 | * EXIT_FAILURE otherwise. 40 | */ 41 | int32_t EstablishMqttSession( MQTTEventCallback_t eventCallback ); 42 | 43 | /** 44 | * @brief Handle the incoming packet if it's not related to the device shadow. 45 | * 46 | * @param[in] pPacketInfo Packet Info pointer for the incoming packet. 47 | * @param[in] packetIdentifier Packet identifier of the incoming packet. 48 | */ 49 | void HandleOtherIncomingPacket( MQTTPacketInfo_t * pPacketInfo, 50 | uint16_t packetIdentifier ); 51 | 52 | /** 53 | * @brief Close the MQTT connection. 54 | * 55 | * @return EXIT_SUCCESS if DISCONNECT was successfully sent; 56 | * EXIT_FAILURE otherwise. 57 | */ 58 | int32_t DisconnectMqttSession( void ); 59 | 60 | /** 61 | * @brief Subscribe to a MQTT topic filter. 62 | * 63 | * @param[in] pTopicFilter Pointer to the shadow topic buffer. 64 | * @param[in] topicFilterLength Indicates the length of the shadow 65 | * topic buffer. 66 | * 67 | * @return EXIT_SUCCESS if SUBSCRIBE was successfully sent; 68 | * EXIT_FAILURE otherwise. 69 | */ 70 | int32_t SubscribeToTopic( const char * pTopicFilter, 71 | uint16_t topicFilterLength ); 72 | 73 | /** 74 | * @brief Sends an MQTT UNSUBSCRIBE to unsubscribe from the shadow 75 | * topic. 76 | * 77 | * @param[in] pTopicFilter Pointer to the shadow topic buffer. 78 | * @param[in] topicFilterLength Indicates the length of the shadow 79 | * topic buffer. 80 | * 81 | * @return EXIT_SUCCESS if UNSUBSCRIBE was successfully sent; 82 | * EXIT_FAILURE otherwise. 83 | */ 84 | int32_t UnsubscribeFromTopic( const char * pTopicFilter, 85 | uint16_t topicFilterLength ); 86 | 87 | /** 88 | * @brief Publish a message to a MQTT topic. 89 | * 90 | * @param[in] pTopicFilter Points to the topic. 91 | * @param[in] topicFilterLength The length of the topic. 92 | * @param[in] pPayload Points to the payload. 93 | * @param[in] payloadLength The length of the payload. 94 | * 95 | * @return EXIT_SUCCESS if PUBLISH was successfully sent; 96 | * EXIT_FAILURE otherwise. 97 | */ 98 | int32_t PublishToTopic( const char * pTopicFilter, 99 | int32_t topicFilterLength, 100 | const char * pPayload, 101 | size_t payloadLength ); 102 | 103 | #endif /* ifndef SHADOW_DEMO_HELPERS_H_ */ 104 | -------------------------------------------------------------------------------- /examples/thing_shadow/partitions.csv: -------------------------------------------------------------------------------- 1 | # Name, Type, SubType, Offset, Size, Flags 2 | # Note: if you change the phy_init or app partition offset, make sure to change the offset in Kconfig.projbuild 3 | esp_secure_cert, 0x3F, , 0xD000, 0x2000, encrypted 4 | nvs, data, nvs, , 0x9000 5 | phy_init, data, phy, , 0x1000 6 | factory, app, factory, 0x20000, 1M, 7 | -------------------------------------------------------------------------------- /examples/thing_shadow/sdkconfig.defaults: -------------------------------------------------------------------------------- 1 | # newlib for ESP32 and ESP8266 platform 2 | 3 | CONFIG_NEWLIB_ENABLE=y 4 | CONFIG_NEWLIB_LIBRARY_LEVEL_NORMAL=y 5 | CONFIG_NEWLIB_NANO_FORMAT= 6 | CONFIG_SSL_USING_MBEDTLS=y 7 | CONFIG_LWIP_IPV6=y 8 | CONFIG_PARTITION_TABLE_CUSTOM=y 9 | CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" 10 | CONFIG_PARTITION_TABLE_FILENAME="partitions.csv" 11 | -------------------------------------------------------------------------------- /libraries/Device-Defender-for-AWS-IoT-embedded-sdk/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This gives DEFENDER_INCLUDE_PUBLIC_DIRS, and DEFENDER_SOURCES 2 | include(${CMAKE_CURRENT_LIST_DIR}/Device-Defender-for-AWS-IoT-embedded-sdk/defenderFilePaths.cmake) 3 | 4 | 5 | set(DEVICE_DEFENDER_INCLUDE_DIRS 6 | ${DEFENDER_INCLUDE_PUBLIC_DIRS} 7 | ${CMAKE_CURRENT_LIST_DIR}/config 8 | ) 9 | 10 | set(DEVICE_DEFENDER_SRCS 11 | ${DEFENDER_SOURCES} 12 | ) 13 | 14 | set(DEVICE_DEFENDER_REQUIRES 15 | ) 16 | 17 | idf_component_register( 18 | SRCS 19 | ${DEVICE_DEFENDER_SRCS} 20 | INCLUDE_DIRS 21 | ${DEVICE_DEFENDER_INCLUDE_DIRS} 22 | REQUIRES 23 | ${DEVICE_DEFENDER_REQUIRES} 24 | ) -------------------------------------------------------------------------------- /libraries/Device-Defender-for-AWS-IoT-embedded-sdk/Kconfig: -------------------------------------------------------------------------------- 1 | menu "Device Defender" 2 | 3 | config DEFENDER_USE_LONG_KEYS 4 | bool "Use long key names." 5 | default n 6 | help 7 | AWS IoT Device Defender Service supports both long and short names for keys 8 | in the report sent by a device. 9 | 10 | menu "Logging" 11 | 12 | config DEVICE_DEFENDER_LOG_ERROR 13 | bool "Enable Error Logging" 14 | default n 15 | 16 | config DEVICE_DEFENDER_LOG_WARN 17 | bool "Enable Warning Logging" 18 | default n 19 | 20 | config DEVICE_DEFENDER_LOG_INFO 21 | bool "Enable Info Logging" 22 | default y 23 | 24 | config DEVICE_DEFENDER_LOG_DEBUG 25 | bool "Enable Debug Logging" 26 | default n 27 | 28 | endmenu # Logging 29 | 30 | endmenu # Device Defender -------------------------------------------------------------------------------- /libraries/Device-Defender-for-AWS-IoT-embedded-sdk/config/defender_config.h: -------------------------------------------------------------------------------- 1 | #ifndef DEFENDER_CONFIG_H 2 | #define DEFENDER_CONFIG_H 3 | 4 | #include "sdkconfig.h" 5 | #define EXTRACT_ARGS( ... ) __VA_ARGS__ 6 | #define STRIP_PARENS( X ) X 7 | #define REMOVE_PARENS( X ) STRIP_PARENS( EXTRACT_ARGS X ) 8 | 9 | /* Logging configurations */ 10 | #if CONFIG_DEVICE_DEFENDER_LOG_ERROR || CONFIG_DEVICE_DEFENDER_LOG_WARN || CONFIG_DEVICE_DEFENDER_LOG_INFO || CONFIG_DEVICE_DEFENDER_LOG_DEBUG 11 | 12 | /* Set logging level for the Device Defender component to highest level, 13 | * so any defined logging level below is printed. */ 14 | #ifdef LOG_LOCAL_LEVEL 15 | #undef LOG_LOCAL_LEVEL 16 | #endif 17 | #define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE 18 | #include "esp_log.h" 19 | 20 | /* Change LIBRARY_LOG_NAME to "DeviceDefender" if defined somewhere else. */ 21 | #ifdef LIBRARY_LOG_NAME 22 | #undef LIBRARY_LOG_NAME 23 | #endif 24 | #define LIBRARY_LOG_NAME "DeviceDefender" 25 | 26 | #endif 27 | 28 | /* Undefine logging macros if they were defined somewhere else like another AWS/FreeRTOS library. */ 29 | #ifdef LogError 30 | #undef LogError 31 | #endif 32 | 33 | #ifdef LogWarn 34 | #undef LogWarn 35 | #endif 36 | 37 | #ifdef LogInfo 38 | #undef LogInfo 39 | #endif 40 | 41 | #ifdef LogDebug 42 | #undef LogDebug 43 | #endif 44 | 45 | /* Define logging macros based on configurations in sdkconfig.h. */ 46 | #if CONFIG_DEVICE_DEFENDER_LOG_ERROR 47 | #define LogError( message, ... ) ESP_LOGE( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 48 | #endif 49 | 50 | #if CONFIG_DEVICE_DEFENDER_LOG_WARN 51 | #define LogWarn( message, ... ) ESP_LOGW( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 52 | #endif 53 | 54 | #if CONFIG_DEVICE_DEFENDER_LOG_INFO 55 | #define LogInfo( message, ... ) ESP_LOGI( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 56 | #endif 57 | 58 | #if CONFIG_DEVICE_DEFENDER_LOG_DEBUG 59 | #define LogDebug( message, ... ) ESP_LOGD( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 60 | #endif 61 | 62 | /* Device Defender configurations */ 63 | 64 | 65 | #endif /* DEFENDER_CONFIG_H */ -------------------------------------------------------------------------------- /libraries/Device-Shadow-for-AWS-IoT-embedded-sdk/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Include Device Shadow library's source and header path variables. 2 | 3 | include( "${CMAKE_CURRENT_LIST_DIR}/Device-Shadow-for-AWS-IoT-embedded-sdk/shadowFilePaths.cmake" ) 4 | 5 | idf_component_register( 6 | SRCS 7 | "${SHADOW_SOURCES}" 8 | INCLUDE_DIRS 9 | "${SHADOW_INCLUDE_PUBLIC_DIRS}" 10 | "config" 11 | "." 12 | ) 13 | -------------------------------------------------------------------------------- /libraries/Device-Shadow-for-AWS-IoT-embedded-sdk/Kconfig: -------------------------------------------------------------------------------- 1 | menu "Device Shadow" 2 | 3 | menu "Logging" 4 | 5 | config DEVICE_SHADOW_LOG_ERROR 6 | bool "Enable Error Logging" 7 | default y 8 | 9 | config DEVICE_SHADOW_LOG_WARN 10 | bool "Enable Warning Logging" 11 | default n 12 | 13 | config DEVICE_SHADOW_LOG_INFO 14 | bool "Enable Info Logging" 15 | default y 16 | 17 | config DEVICE_SHADOW_LOG_DEBUG 18 | bool "Enable Debug Logging" 19 | default n 20 | 21 | endmenu # Device Shadow Logging 22 | 23 | endmenu # Device Shadow -------------------------------------------------------------------------------- /libraries/Device-Shadow-for-AWS-IoT-embedded-sdk/config/shadow_config.h: -------------------------------------------------------------------------------- 1 | #ifndef SHADOW_CONFIG_H 2 | #define SHADOW_CONFIG_H 3 | 4 | #include "sdkconfig.h" 5 | #define EXTRACT_ARGS( ... ) __VA_ARGS__ 6 | #define STRIP_PARENS( X ) X 7 | #define REMOVE_PARENS( X ) STRIP_PARENS( EXTRACT_ARGS X ) 8 | 9 | /* Logging configurations */ 10 | #if CONFIG_DEVICE_SHADOW_LOG_ERROR || CONFIG_DEVICE_SHADOW_LOG_WARN || CONFIG_DEVICE_SHADOW_LOG_INFO || CONFIG_DEVICE_SHADOW_LOG_DEBUG 11 | 12 | /* Set logging level for the Device SHADOW component to highest level, 13 | * so any defined logging level below is printed. */ 14 | #ifdef LOG_LOCAL_LEVEL 15 | #undef LOG_LOCAL_LEVEL 16 | #endif 17 | #define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE 18 | #include "esp_log.h" 19 | 20 | /* Change LIBRARY_LOG_NAME to "DeviceShadow" if defined somewhere else. */ 21 | #ifdef LIBRARY_LOG_NAME 22 | #undef LIBRARY_LOG_NAME 23 | #endif 24 | #define LIBRARY_LOG_NAME "DeviceShadow" 25 | 26 | #endif 27 | 28 | /* Undefine logging macros if they were defined somewhere else like another AWS/FreeRTOS library. */ 29 | #ifdef LogError 30 | #undef LogError 31 | #endif 32 | 33 | #ifdef LogWarn 34 | #undef LogWarn 35 | #endif 36 | 37 | #ifdef LogInfo 38 | #undef LogInfo 39 | #endif 40 | 41 | #ifdef LogDebug 42 | #undef LogDebug 43 | #endif 44 | 45 | /* Define logging macros based on configurations in sdkconfig.h. */ 46 | #if CONFIG_DEVICE_SHADOW_LOG_ERROR 47 | #define LogError( message, ... ) ESP_LOGE( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 48 | #endif 49 | 50 | #if CONFIG_DEVICE_SHADOW_LOG_WARN 51 | #define LogWarn( message, ... ) ESP_LOGW( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 52 | #endif 53 | 54 | #if CONFIG_DEVICE_SHADOW_LOG_INFO 55 | #define LogInfo( message, ... ) ESP_LOGI( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 56 | #endif 57 | 58 | #if CONFIG_DEVICE_SHADOW_LOG_DEBUG 59 | #define LogDebug( message, ... ) ESP_LOGD( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 60 | #endif 61 | 62 | #endif /* SHADOW_CONFIG_H */ -------------------------------------------------------------------------------- /libraries/Fleet-Provisioning-for-AWS-IoT-embedded-sdk/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Include Fleet Provisioning library's source and header path variables. 2 | 3 | include( "${CMAKE_CURRENT_LIST_DIR}/Fleet-Provisioning-for-AWS-IoT-embedded-sdk/fleetprovisioningFilePaths.cmake" ) 4 | 5 | idf_component_register( 6 | SRCS 7 | "${FLEET_PROVISIONING_SOURCES}" 8 | INCLUDE_DIRS 9 | "${FLEET_PROVISIONING_INCLUDE_PUBLIC_DIRS}" 10 | "config" 11 | "." 12 | ) 13 | -------------------------------------------------------------------------------- /libraries/Fleet-Provisioning-for-AWS-IoT-embedded-sdk/Kconfig: -------------------------------------------------------------------------------- 1 | menu "Fleet Provisioning" 2 | 3 | menu "Logging" 4 | 5 | config FLEET_PROVISIONING_LOG_ERROR 6 | bool "Enable Error Logging" 7 | default y 8 | 9 | config FLEET_PROVISIONING_LOG_WARN 10 | bool "Enable Warning Logging" 11 | default n 12 | 13 | config FLEET_PROVISIONING_LOG_INFO 14 | bool "Enable Info Logging" 15 | default y 16 | 17 | config FLEET_PROVISIONING_LOG_DEBUG 18 | bool "Enable Debug Logging" 19 | default n 20 | 21 | endmenu # Fleet Provisioning Logging 22 | 23 | endmenu # Fleet Provisioning -------------------------------------------------------------------------------- /libraries/Fleet-Provisioning-for-AWS-IoT-embedded-sdk/config/fleet_provisioning_config.h: -------------------------------------------------------------------------------- 1 | #ifndef SHADOW_CONFIG_H 2 | #define SHADOW_CONFIG_H 3 | 4 | #include "sdkconfig.h" 5 | #define EXTRACT_ARGS( ... ) __VA_ARGS__ 6 | #define STRIP_PARENS( X ) X 7 | #define REMOVE_PARENS( X ) STRIP_PARENS( EXTRACT_ARGS X ) 8 | 9 | /* Logging configurations */ 10 | #if CONFIG_FLEET_PROVISIONING_LOG_ERROR || CONFIG_FLEET_PROVISIONING_LOG_WARN || CONFIG_FLEET_PROVISIONING_LOG_INFO || CONFIG_FLEET_PROVISIONING_LOG_DEBUG 11 | 12 | /* Set logging level for the Device SHADOW component to highest level, 13 | * so any defined logging level below is printed. */ 14 | #ifdef LOG_LOCAL_LEVEL 15 | #undef LOG_LOCAL_LEVEL 16 | #endif 17 | #define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE 18 | #include "esp_log.h" 19 | 20 | /* Change LIBRARY_LOG_NAME to "FleetProvisioning" if defined somewhere else. */ 21 | #ifdef LIBRARY_LOG_NAME 22 | #undef LIBRARY_LOG_NAME 23 | #endif 24 | #define LIBRARY_LOG_NAME "FleetProvisioning" 25 | 26 | #endif 27 | 28 | /* Undefine logging macros if they were defined somewhere else like another AWS/FreeRTOS library. */ 29 | #ifdef LogError 30 | #undef LogError 31 | #endif 32 | 33 | #ifdef LogWarn 34 | #undef LogWarn 35 | #endif 36 | 37 | #ifdef LogInfo 38 | #undef LogInfo 39 | #endif 40 | 41 | #ifdef LogDebug 42 | #undef LogDebug 43 | #endif 44 | 45 | /* Define logging macros based on configurations in sdkconfig.h. */ 46 | #if CONFIG_FLEET_PROVISIONING_LOG_ERROR 47 | #define LogError( message, ... ) ESP_LOGE( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 48 | #endif 49 | 50 | #if CONFIG_FLEET_PROVISIONING_LOG_WARN 51 | #define LogWarn( message, ... ) ESP_LOGW( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 52 | #endif 53 | 54 | #if CONFIG_FLEET_PROVISIONING_LOG_INFO 55 | #define LogInfo( message, ... ) ESP_LOGI( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 56 | #endif 57 | 58 | #if CONFIG_FLEET_PROVISIONING_LOG_DEBUG 59 | #define LogDebug( message, ... ) ESP_LOGD( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 60 | #endif 61 | 62 | #endif /* SHADOW_CONFIG_H */ -------------------------------------------------------------------------------- /libraries/Jobs-for-AWS-IoT-embedded-sdk/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | include( "${CMAKE_CURRENT_LIST_DIR}/Jobs-for-AWS-IoT-embedded-sdk/jobsFilePaths.cmake" ) 2 | 3 | idf_component_register( 4 | SRCS 5 | "${JOBS_SOURCES}" 6 | "${OTA_HANDLER_SOURCES}" 7 | INCLUDE_DIRS 8 | "${JOBS_INCLUDE_PUBLIC_DIRS}" 9 | "${OTA_HANDLER_INCLUDES}" 10 | "." 11 | REQUIRES 12 | coreJSON 13 | ) -------------------------------------------------------------------------------- /libraries/aws-iot-core-mqtt-file-streams-embedded-c/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This gives OTA_INCLUDE_PUBLIC_DIRS, and OTA_SOURCES 2 | include(${CMAKE_CURRENT_LIST_DIR}/aws-iot-core-mqtt-file-streams-embedded-c/mqttFileDownloaderFilePaths.cmake) 3 | 4 | set(AWS_OTA_PORT_INCLUDE_DIRS 5 | ${CMAKE_CURRENT_LIST_DIR}/port 6 | ${CMAKE_CURRENT_LIST_DIR}/../common/logging/ 7 | ) 8 | 9 | set(AWS_OTA_INCLUDE_DIRS 10 | ${MQTT_FILE_DOWNLOADER_INCLUDES} 11 | ${CMAKE_CURRENT_LIST_DIR}/config 12 | ${AWS_OTA_PORT_INCLUDE_DIRS} 13 | ) 14 | 15 | set(AWS_OTA_PORT_SRCS 16 | ${CMAKE_CURRENT_LIST_DIR}/port/aws_esp_ota_ops.c 17 | ${CMAKE_CURRENT_LIST_DIR}/port/ota_pal.c 18 | ${CMAKE_CURRENT_LIST_DIR}/port/ota_os_freertos.c 19 | ) 20 | 21 | set(AWS_OTA_SRCS 22 | ${MQTT_FILE_DOWNLOADER_SOURCES} 23 | ${AWS_OTA_PORT_SRCS} 24 | ) 25 | 26 | set(AWS_OTA_REQUIRES 27 | esp_rom 28 | mbedtls 29 | corePKCS11 30 | coreJSON 31 | esp_common 32 | spi_flash 33 | Jobs-for-AWS-IoT-embedded-sdk 34 | bootloader_support 35 | efuse 36 | log 37 | app_update 38 | cbor 39 | ) 40 | 41 | idf_component_register( 42 | SRCS 43 | ${AWS_OTA_SRCS} 44 | INCLUDE_DIRS 45 | ${AWS_OTA_INCLUDE_DIRS} 46 | PRIV_INCLUDE_DIRS 47 | ${OTA_INCLUDE_PRIVATE_DIRS} 48 | REQUIRES 49 | ${AWS_OTA_REQUIRES} 50 | ) 51 | 52 | set_source_files_properties( 53 | "${CMAKE_CURRENT_LIST_DIR}/aws-iot-core-mqtt-file-streams-embedded-c/source/MQTTFileDownloader.c" 54 | PROPERTIES COMPILE_FLAGS -Wno-format) 55 | 56 | if (NOT CONFIG_MQTT_STREAMS_USE_CUSTOM_CONFIG) 57 | target_compile_definitions( ${COMPONENT_TARGET} PUBLIC MQTT_STREAMS_DO_NOT_USE_CUSTOM_CONFIG=1 ) 58 | endif() 59 | -------------------------------------------------------------------------------- /libraries/aws-iot-core-mqtt-file-streams-embedded-c/Kconfig: -------------------------------------------------------------------------------- 1 | menu "AWS MQTT File Streams" 2 | 3 | menu "Logging" 4 | 5 | config AWS_OTA_LOG_ERROR 6 | bool "Enable Error Logging" 7 | default y 8 | 9 | config AWS_OTA_LOG_WARN 10 | bool "Enable Warning Logging" 11 | default y 12 | 13 | config AWS_OTA_LOG_INFO 14 | bool "Enable Info Logging" 15 | default y 16 | 17 | config AWS_OTA_LOG_DEBUG 18 | bool "Enable Debug Logging" 19 | default n 20 | 21 | endmenu # AWS OTA Logging 22 | 23 | config MQTT_STREAMS_USE_CUSTOM_CONFIG 24 | bool "MQTT Streams use custom config" 25 | default n 26 | help 27 | This configuration parameter allows you to provide custom configurations for OTA over MQTT. 28 | 29 | endmenu # AWS OTA 30 | -------------------------------------------------------------------------------- /libraries/aws-iot-core-mqtt-file-streams-embedded-c/config/ota_config.h: -------------------------------------------------------------------------------- 1 | /* 2 | * AWS IoT Device SDK for Embedded C 202103.00 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | * this software and associated documentation files (the "Software"), to deal in 7 | * the Software without restriction, including without limitation the rights to 8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | * the Software, and to permit persons to whom the Software is furnished to do so, 10 | * subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | /** 24 | * @file ota_config.h 25 | * @brief OTA user configurable settings. 26 | */ 27 | 28 | #ifndef OTA_CONFIG_H_ 29 | #define OTA_CONFIG_H_ 30 | 31 | #include "sdkconfig.h" 32 | #include "MQTTFileDownloader.h" 33 | #include "MQTTFileDownloader_defaults.h" 34 | 35 | #define OTA_DATA_BLOCK_SIZE ( mqttFileDownloader_CONFIG_BLOCK_SIZE ) 36 | #define JOB_DOC_SIZE ( 2048U ) 37 | 38 | #define EXTRACT_ARGS( ... ) __VA_ARGS__ 39 | #define STRIP_PARENS( X ) X 40 | #define REMOVE_PARENS( X ) STRIP_PARENS( EXTRACT_ARGS X ) 41 | 42 | /* Logging configurations */ 43 | #if CONFIG_AWS_OTA_LOG_ERROR || CONFIG_AWS_OTA_LOG_WARN || CONFIG_AWS_OTA_LOG_INFO || CONFIG_AWS_OTA_LOG_DEBUG 44 | 45 | /* Set logging level for the AWS_OTA to highest level, 46 | * so any defined logging level below is printed. */ 47 | #ifdef LOG_LOCAL_LEVEL 48 | #undef LOG_LOCAL_LEVEL 49 | #endif 50 | #define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE 51 | #include "esp_log.h" 52 | 53 | /* Change LIBRARY_LOG_NAME to "AWS_OTA" if defined somewhere else. */ 54 | #ifdef LIBRARY_LOG_NAME 55 | #undef LIBRARY_LOG_NAME 56 | #endif 57 | #define LIBRARY_LOG_NAME "AWS_OTA" 58 | 59 | #endif 60 | 61 | /* Undefine logging macros if they were defined somewhere else like another AWS/FreeRTOS library. */ 62 | #ifdef LogError 63 | #undef LogError 64 | #endif 65 | 66 | #ifdef LogWarn 67 | #undef LogWarn 68 | #endif 69 | 70 | #ifdef LogInfo 71 | #undef LogInfo 72 | #endif 73 | 74 | #ifdef LogDebug 75 | #undef LogDebug 76 | #endif 77 | 78 | /* Define logging macros based on configurations in sdkconfig.h. */ 79 | #if CONFIG_AWS_OTA_LOG_ERROR 80 | #define LogError( message, ... ) ESP_LOGE( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 81 | #else 82 | #define LogError( message, ... ) 83 | #endif 84 | 85 | #if CONFIG_AWS_OTA_LOG_WARN 86 | #define LogWarn( message, ... ) ESP_LOGW( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 87 | #else 88 | #define LogWarn( message, ... ) 89 | #endif 90 | 91 | #if CONFIG_AWS_OTA_LOG_INFO 92 | #define LogInfo( message, ... ) ESP_LOGI( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 93 | #else 94 | #define LogInfo( message, ... ) 95 | #endif 96 | 97 | #if CONFIG_AWS_OTA_LOG_DEBUG 98 | #define LogDebug( message, ... ) ESP_LOGD( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 99 | #else 100 | #define LogDebug( message, ... ) 101 | #endif 102 | 103 | /************ End of logging configuration ****************/ 104 | 105 | #endif /* OTA_CONFIG_H_ */ 106 | -------------------------------------------------------------------------------- /libraries/aws-iot-core-mqtt-file-streams-embedded-c/port/aws_esp_ota_ops.c: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | #include "esp_err.h" 26 | #include "esp_partition.h" 27 | #if ESP_IDF_VERSION >= ESP_IDF_VERSION_VAL(5, 0, 0) 28 | #include "spi_flash_mmap.h" 29 | #else 30 | #include "esp_spi_flash.h" 31 | #endif 32 | #include "esp_image_format.h" 33 | #include "esp_secure_boot.h" 34 | #include "esp_flash_encrypt.h" 35 | #include "sdkconfig.h" 36 | 37 | #include "esp_ota_ops.h" 38 | #include "aws_esp_ota_ops.h" 39 | #include "sys/queue.h" 40 | 41 | #include "esp_log.h" 42 | #include "esp_flash_partitions.h" 43 | #include "esp_efuse.h" 44 | #include "bootloader_common.h" 45 | 46 | typedef esp_ota_select_entry_t ota_select; 47 | 48 | const static char *TAG = "esp_ota_ops"; 49 | 50 | static bool ota_select_valid(const ota_select *s) 51 | { 52 | return bootloader_common_ota_select_valid(s); 53 | } 54 | 55 | static const esp_partition_t *_esp_get_otadata_partition(uint32_t *offset, ota_select *entry, bool active_part) 56 | { 57 | esp_err_t ret; 58 | const esp_partition_t *find_partition = NULL; 59 | spi_flash_mmap_handle_t ota_data_map; 60 | const void *result = NULL; 61 | ota_select s_ota_select[2]; 62 | 63 | find_partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_OTA, NULL); 64 | if (find_partition != NULL) { 65 | ret = esp_partition_mmap(find_partition, 0, find_partition->size, SPI_FLASH_MMAP_DATA, &result, &ota_data_map); 66 | if (ret != ESP_OK) { 67 | ESP_LOGW(TAG, "mmap failed %d", ret); 68 | return NULL; 69 | } else { 70 | memcpy(&s_ota_select[0], result, sizeof(ota_select)); 71 | memcpy(&s_ota_select[1], result + SPI_FLASH_SEC_SIZE, sizeof(ota_select)); 72 | spi_flash_munmap(ota_data_map); 73 | } 74 | uint32_t gen_0_seq = ota_select_valid(&s_ota_select[0]) ? s_ota_select[0].ota_seq : 0; 75 | uint32_t gen_1_seq = ota_select_valid(&s_ota_select[1]) ? s_ota_select[1].ota_seq : 0; 76 | if (gen_0_seq == 0 && gen_1_seq == 0) { 77 | ESP_LOGW(TAG, "otadata partition is invalid, factory/ota_0 is boot partition"); 78 | memcpy(entry, &s_ota_select[0], sizeof(ota_select)); 79 | *offset = 0; 80 | } else if ((gen_0_seq >= gen_1_seq && active_part) || (gen_1_seq > gen_0_seq && !active_part)) { 81 | memcpy(entry, &s_ota_select[0], sizeof(ota_select)); 82 | *offset = 0; 83 | ESP_LOGI(TAG, "[0] aflags/seq:0x%"PRIx32"/0x%"PRIx32", pflags/seq:0x%"PRIx32"/0x%"PRIx32"", 84 | s_ota_select[0].ota_state, gen_0_seq, s_ota_select[1].ota_state, gen_1_seq); 85 | } else { 86 | memcpy(entry, &s_ota_select[1], sizeof(ota_select)); 87 | *offset = SPI_FLASH_SEC_SIZE; 88 | ESP_LOGI(TAG, "[1] aflags/seq:0x%"PRIx32"/0x%"PRIx32", pflags/seq:0x%"PRIx32"/0x%"PRIx32"", 89 | s_ota_select[1].ota_state, gen_1_seq, s_ota_select[0].ota_state, gen_0_seq); 90 | } 91 | } else { 92 | ESP_LOGE(TAG, "no otadata partition found"); 93 | } 94 | return find_partition; 95 | } 96 | 97 | #ifdef CONFIG_APP_ANTI_ROLLBACK 98 | static esp_err_t esp_ota_set_anti_rollback(void) { 99 | const esp_app_desc_t *app_desc = esp_ota_get_app_description(); 100 | return esp_efuse_update_secure_version(app_desc->secure_version); 101 | } 102 | #endif 103 | 104 | esp_err_t aws_esp_ota_set_boot_flags(uint32_t flags, bool active_part) 105 | { 106 | const esp_partition_t *part = NULL; 107 | uint32_t offset; 108 | ota_select entry; 109 | 110 | ESP_LOGI(TAG, "%s: %"PRIi32" %d", __func__, flags, active_part); 111 | part = _esp_get_otadata_partition(&offset, &entry, active_part); 112 | if (part == NULL) { 113 | return ESP_FAIL; 114 | } 115 | entry.ota_state = flags; 116 | esp_err_t ret = esp_partition_erase_range(part, offset, SPI_FLASH_SEC_SIZE); 117 | if (ret != ESP_OK) { 118 | ESP_LOGE(TAG, "failed to erase partition %"PRIi32" %d", offset, ret); 119 | return ret; 120 | } 121 | ret = esp_partition_write(part, offset, &entry, sizeof(ota_select)); 122 | if (ret != ESP_OK) { 123 | ESP_LOGE(TAG, "failed to write partition %"PRIi32" %d", offset, ret); 124 | return ret; 125 | } 126 | #ifdef CONFIG_APP_ANTI_ROLLBACK 127 | if (flags == ESP_OTA_IMG_VALID) { 128 | return esp_ota_set_anti_rollback(); 129 | } 130 | #endif 131 | return ret; 132 | } 133 | 134 | esp_err_t aws_esp_ota_get_boot_flags(uint32_t *flags, bool active_part) 135 | { 136 | const esp_partition_t *part = NULL; 137 | uint32_t offset; 138 | ota_select entry; 139 | 140 | ESP_LOGI(TAG, "%s: %d", __func__, active_part); 141 | *flags = ESP_OTA_IMG_INVALID; 142 | part = _esp_get_otadata_partition(&offset, &entry, active_part); 143 | if (part == NULL) { 144 | return ESP_FAIL; 145 | } 146 | *flags = entry.ota_state; 147 | return ESP_OK; 148 | } -------------------------------------------------------------------------------- /libraries/aws-iot-core-mqtt-file-streams-embedded-c/port/aws_esp_ota_ops.h: -------------------------------------------------------------------------------- 1 | // Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | #ifndef _AWS_ESP_OTA_OPS_H 16 | #define _AWS_ESP_OTA_OPS_H 17 | 18 | #include 19 | #include 20 | #include 21 | #include "esp_err.h" 22 | 23 | #ifdef __cplusplus 24 | extern "C" 25 | { 26 | #endif 27 | 28 | /* Set firmware image flags, `active_part` if true then sets current running firmware flags, else passive (non-executing) firmware flags */ 29 | esp_err_t aws_esp_ota_set_boot_flags(uint32_t flags, bool active_part); 30 | 31 | /* Get firmware image flags, `active_part` if true then gets current running firmware flags, else passive (non-executing) firmware flags */ 32 | esp_err_t aws_esp_ota_get_boot_flags(uint32_t *flags, bool active_part); 33 | 34 | #ifdef __cplusplus 35 | } 36 | #endif 37 | 38 | #endif /* AWS_ESP_OTA_OPS_H */ -------------------------------------------------------------------------------- /libraries/aws-iot-core-mqtt-file-streams-embedded-c/port/ota_os_freertos.c: -------------------------------------------------------------------------------- 1 | /* 2 | * AWS IoT Over-the-air Update v3.3.0 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | * this software and associated documentation files (the "Software"), to deal in 7 | * the Software without restriction, including without limitation the rights to 8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | * the Software, and to permit persons to whom the Software is furnished to do so, 10 | * subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | /** 24 | * @file ota_os_freertos.c 25 | * @brief Example implementation of the OTA OS Functional Interface for 26 | * FreeRTOS. 27 | */ 28 | 29 | /* FreeRTOS includes. */ 30 | #include "freertos/FreeRTOS.h" 31 | #include "freertos/timers.h" 32 | #include "freertos/queue.h" 33 | 34 | /* OTA OS POSIX Interface Includes.*/ 35 | #include "ota_os_freertos.h" 36 | 37 | #include "ota_config.h" 38 | 39 | /* OTA Event queue attributes.*/ 40 | #define MAX_MESSAGES 20 41 | #define MAX_MSG_SIZE sizeof( OtaEventMsg_t ) 42 | 43 | /* Array containing pointer to the OTA event structures used to send events to the OTA task. */ 44 | static OtaEventMsg_t queueData[ MAX_MESSAGES * MAX_MSG_SIZE ]; 45 | 46 | /* The queue control structure. .*/ 47 | static StaticQueue_t staticQueue; 48 | 49 | /* The queue control handle. .*/ 50 | static QueueHandle_t otaEventQueue; 51 | 52 | OtaOsStatus_t OtaInitEvent_FreeRTOS( void ) 53 | { 54 | OtaOsStatus_t otaOsStatus = OtaOsSuccess; 55 | 56 | otaEventQueue = xQueueCreateStatic( ( UBaseType_t ) MAX_MESSAGES, 57 | ( UBaseType_t ) MAX_MSG_SIZE, 58 | ( uint8_t * ) queueData, 59 | &staticQueue ); 60 | 61 | if( otaEventQueue == NULL ) 62 | { 63 | otaOsStatus = OtaOsEventQueueCreateFailed; 64 | 65 | LogError( ( "Failed to create OTA Event Queue: " 66 | "xQueueCreateStatic returned error: " 67 | "OtaOsStatus_t=%i ", 68 | otaOsStatus ) ); 69 | } 70 | else 71 | { 72 | LogDebug( ( "OTA Event Queue created." ) ); 73 | } 74 | 75 | return otaOsStatus; 76 | } 77 | 78 | OtaOsStatus_t OtaSendEvent_FreeRTOS( const void * pEventMsg ) 79 | { 80 | OtaOsStatus_t otaOsStatus = OtaOsSuccess; 81 | BaseType_t retVal = pdFALSE; 82 | 83 | /* Send the event to OTA event queue.*/ 84 | retVal = xQueueSendToBack( otaEventQueue, pEventMsg, ( TickType_t ) 0 ); 85 | 86 | if( retVal == pdTRUE ) 87 | { 88 | LogDebug( ( "OTA Event Sent." ) ); 89 | } 90 | else 91 | { 92 | otaOsStatus = OtaOsEventQueueSendFailed; 93 | 94 | LogError( ( "Failed to send event to OTA Event Queue: " 95 | "xQueueSendToBack returned error: " 96 | "OtaOsStatus_t=%i ", 97 | otaOsStatus ) ); 98 | } 99 | 100 | return otaOsStatus; 101 | } 102 | 103 | OtaOsStatus_t OtaReceiveEvent_FreeRTOS( void * pEventMsg ) 104 | { 105 | OtaOsStatus_t otaOsStatus = OtaOsSuccess; 106 | BaseType_t retVal = pdFALSE; 107 | 108 | /* Temp buffer.*/ 109 | uint8_t buff[ sizeof( OtaEventMsg_t ) ]; 110 | 111 | retVal = xQueueReceive( otaEventQueue, &buff, portMAX_DELAY ); 112 | 113 | if( retVal == pdTRUE ) 114 | { 115 | /* copy the data from local buffer.*/ 116 | memcpy( pEventMsg, buff, MAX_MSG_SIZE ); 117 | LogDebug( ( "OTA Event received" ) ); 118 | } 119 | else 120 | { 121 | otaOsStatus = OtaOsEventQueueReceiveFailed; 122 | 123 | LogError( ( "Failed to receive event from OTA Event Queue: " 124 | "xQueueReceive returned error: " 125 | "OtaOsStatus_t=%i ", 126 | otaOsStatus ) ); 127 | } 128 | 129 | return otaOsStatus; 130 | } 131 | 132 | OtaOsStatus_t OtaDeinitEvent_FreeRTOS( void ) 133 | { 134 | OtaOsStatus_t otaOsStatus = OtaOsSuccess; 135 | 136 | /* Remove the event queue.*/ 137 | if( otaEventQueue != NULL ) 138 | { 139 | vQueueDelete( otaEventQueue ); 140 | 141 | LogDebug( ( "OTA Event Queue Deleted." ) ); 142 | } 143 | 144 | return otaOsStatus; 145 | } 146 | 147 | void * Malloc_FreeRTOS( size_t size ) 148 | { 149 | return pvPortMalloc( size ); 150 | } 151 | 152 | void Free_FreeRTOS( void * ptr ) 153 | { 154 | vPortFree( ptr ); 155 | } 156 | -------------------------------------------------------------------------------- /libraries/backoffAlgorithm/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This gives BACKOFF_ALGORITHM_INCLUDE_PUBLIC_DIRS, and BACKOFF_ALGORITHM_SOURCES 2 | include(${CMAKE_CURRENT_LIST_DIR}/backoffAlgorithm/backoffAlgorithmFilePaths.cmake) 3 | 4 | set(BACKOFF_ALGORITHM_INCLUDE_DIRS 5 | ${BACKOFF_ALGORITHM_INCLUDE_PUBLIC_DIRS} 6 | ) 7 | 8 | set(BACKOFF_ALGORITHM_SRCS 9 | ${BACKOFF_ALGORITHM_SOURCES} 10 | ) 11 | 12 | set(BACKOFF_ALGORITHM_REQUIRES 13 | ) 14 | 15 | idf_component_register( 16 | SRCS 17 | ${BACKOFF_ALGORITHM_SRCS} 18 | INCLUDE_DIRS 19 | ${BACKOFF_ALGORITHM_INCLUDE_DIRS} 20 | REQUIRES 21 | ${BACKOFF_ALGORITHM_REQUIRES} 22 | ) -------------------------------------------------------------------------------- /libraries/common/logging/logging_levels.h: -------------------------------------------------------------------------------- 1 | /* 2 | * FreeRTOS Kernel V10.3.0 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | * this software and associated documentation files (the "Software"), to deal in 7 | * the Software without restriction, including without limitation the rights to 8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | * the Software, and to permit persons to whom the Software is furnished to do so, 10 | * subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | * 22 | * http://www.FreeRTOS.org 23 | * http://aws.amazon.com/freertos 24 | * 25 | * 1 tab == 4 spaces! 26 | */ 27 | 28 | /** 29 | * @file logging_levels.h 30 | * @brief Defines the configuration constants for all logging verbosity levels. 31 | */ 32 | 33 | #ifndef LOGGING_LEVELS_H 34 | #define LOGGING_LEVELS_H 35 | 36 | /** 37 | * @constantspage{logging,logging library} 38 | * 39 | * @section logging_constants_levels Log levels 40 | * @brief Log levels for the libraries in this SDK. 41 | * 42 | * Each library should specify a log level by setting @ref LIBRARY_LOG_LEVEL. 43 | * All log messages with a level at or below the specified level will be printed 44 | * for that library. 45 | * 46 | * Currently, there are 4 log levels. In the order of lowest to highest, they are: 47 | * - #LOG_NONE
48 | * @copybrief LOG_NONE 49 | * - #LOG_ERROR
50 | * @copybrief LOG_ERROR 51 | * - #LOG_WARN
52 | * @copybrief LOG_WARN 53 | * - #LOG_INFO
54 | * @copybrief LOG_INFO 55 | * - #LOG_DEBUG
56 | * @copybrief LOG_DEBUG 57 | */ 58 | 59 | /** 60 | * @brief No log messages. 61 | * 62 | * When @ref LIBRARY_LOG_LEVEL is #LOG_NONE, logging is disabled and no 63 | * logging messages are printed. 64 | */ 65 | #define LOG_NONE 0 66 | 67 | /** 68 | * @brief Represents erroneous application state or event. 69 | * 70 | * These messages describe the situations when a library encounters an error from 71 | * which it cannot recover. 72 | * 73 | * These messages are printed when @ref LIBRARY_LOG_LEVEL is defined as either 74 | * of #LOG_ERROR, #LOG_WARN, #LOG_INFO or #LOG_DEBUG. 75 | */ 76 | #define LOG_ERROR 1 77 | 78 | /** 79 | * @brief Message about an abnormal event. 80 | * 81 | * These messages describe the situations when a library encounters 82 | * abnormal event that may be indicative of an error. Libraries continue 83 | * execution after logging a warning. 84 | * 85 | * These messages are printed when @ref LIBRARY_LOG_LEVEL is defined as either 86 | * of #LOG_WARN, #LOG_INFO or #LOG_DEBUG. 87 | */ 88 | #define LOG_WARN 2 89 | 90 | /** 91 | * @brief A helpful, informational message. 92 | * 93 | * These messages describe normal execution of a library. They provide 94 | * the progress of the program at a coarse-grained level. 95 | * 96 | * These messages are printed when @ref LIBRARY_LOG_LEVEL is defined as either 97 | * of #LOG_INFO or #LOG_DEBUG. 98 | */ 99 | #define LOG_INFO 3 100 | 101 | /** 102 | * @brief Detailed and excessive debug information. 103 | * 104 | * Debug log messages are used to provide the 105 | * progress of the program at a fine-grained level. These are mostly used 106 | * for debugging and may contain excessive information such as internal 107 | * variables, buffers, or other specific information. 108 | * 109 | * These messages are only printed when @ref LIBRARY_LOG_LEVEL is defined as 110 | * #LOG_DEBUG. 111 | */ 112 | #define LOG_DEBUG 4 113 | 114 | #endif /* ifndef LOGGING_LEVELS_H */ -------------------------------------------------------------------------------- /libraries/common/posix_compat/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | idf_component_register( 2 | SRCS 3 | "clock_esp.c" 4 | "semaphore.c" 5 | INCLUDE_DIRS 6 | "." 7 | REQUIRES 8 | esp_timer 9 | ) 10 | -------------------------------------------------------------------------------- /libraries/common/posix_compat/clock.h: -------------------------------------------------------------------------------- 1 | /* 2 | * AWS IoT Device SDK for Embedded C 202108.00 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | * this software and associated documentation files (the "Software"), to deal in 7 | * the Software without restriction, including without limitation the rights to 8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | * the Software, and to permit persons to whom the Software is furnished to do so, 10 | * subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | /** 24 | * @file clock.h 25 | * @brief Time-related functions used by demos and tests in this SDK. 26 | */ 27 | 28 | #ifndef CLOCK_H_ 29 | #define CLOCK_H_ 30 | 31 | /* Standard includes. */ 32 | #include 33 | 34 | /* *INDENT-OFF* */ 35 | #ifdef __cplusplus 36 | extern "C" { 37 | #endif 38 | /* *INDENT-ON* */ 39 | 40 | /** 41 | * @brief The timer query function. 42 | * 43 | * This function returns the elapsed time. 44 | * 45 | * @return Time in milliseconds. 46 | */ 47 | uint32_t Clock_GetTimeMs( void ); 48 | 49 | /** 50 | * @brief Millisecond sleep function. 51 | * 52 | * @param[in] sleepTimeMs milliseconds to sleep. 53 | */ 54 | void Clock_SleepMs( uint32_t sleepTimeMs ); 55 | 56 | /* *INDENT-OFF* */ 57 | #ifdef __cplusplus 58 | } 59 | #endif 60 | /* *INDENT-ON* */ 61 | 62 | #endif /* ifndef CLOCK_H_ */ 63 | -------------------------------------------------------------------------------- /libraries/common/posix_compat/clock_esp.c: -------------------------------------------------------------------------------- 1 | // Copyright 2021 Espressif Systems (Shanghai) CO LTD 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // http://www.apache.org/licenses/LICENSE-2.0 7 | // 8 | // Unless required by applicable law or agreed to in writing, software 9 | // distributed under the License is distributed on an "AS IS" BASIS, 10 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | // See the License for the specific language governing permissions and 12 | // limitations under the License 13 | 14 | /* Platform clock include. */ 15 | #include "clock.h" 16 | 17 | #include "esp_timer.h" 18 | #include "freertos/FreeRTOS.h" 19 | #include "freertos/task.h" 20 | 21 | uint32_t Clock_GetTimeMs( void ) 22 | { 23 | /* esp_timer_get_time is in microseconds, converting to milliseconds */ 24 | int64_t timeMs = esp_timer_get_time() / 1000; 25 | 26 | /* Libraries need only the lower 32 bits of the time in milliseconds, since 27 | * this function is used only for calculating the time difference. 28 | * Also, the possible overflows of this time value are handled by the 29 | * libraries. */ 30 | return ( uint32_t ) timeMs; 31 | } 32 | 33 | /*-----------------------------------------------------------*/ 34 | 35 | void Clock_SleepMs( uint32_t sleepTimeMs ) 36 | { 37 | vTaskDelay( sleepTimeMs/portTICK_PERIOD_MS ); 38 | } -------------------------------------------------------------------------------- /libraries/common/posix_compat/semaphore.c: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * 3 | * Copyright (C) 2015 Google, Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at: 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | ******************************************************************************/ 18 | 19 | 20 | #include "semaphore.h" 21 | 22 | /*-----------------------------------------------------------------------------------*/ 23 | // Creates and returns a new semaphore. The "init_count" argument specifies 24 | // the initial state of the semaphore, "max_count" specifies the maximum value 25 | // that can be reached. 26 | int osi_sem_new(osi_sem_t *sem, uint32_t max_count, uint32_t init_count) 27 | { 28 | int ret = -1; 29 | 30 | if (sem) { 31 | *sem = xSemaphoreCreateCounting(max_count, init_count); 32 | if ((*sem) != NULL) { 33 | ret = 0; 34 | } 35 | } 36 | 37 | return ret; 38 | } 39 | 40 | /*-----------------------------------------------------------------------------------*/ 41 | // Give a semaphore 42 | void osi_sem_give(osi_sem_t *sem) 43 | { 44 | xSemaphoreGive(*sem); 45 | } 46 | 47 | /* 48 | Blocks the thread while waiting for the semaphore to be 49 | signaled. If the "timeout" argument is non-zero, the thread should 50 | only be blocked for the specified time (measured in 51 | milliseconds). 52 | 53 | */ 54 | int 55 | osi_sem_take(osi_sem_t *sem, uint32_t timeout) 56 | { 57 | int ret = 0; 58 | 59 | if (timeout == OSI_SEM_MAX_TIMEOUT) { 60 | if (xSemaphoreTake(*sem, portMAX_DELAY) != pdTRUE) { 61 | ret = -1; 62 | } 63 | } else { 64 | if (xSemaphoreTake(*sem, timeout / portTICK_PERIOD_MS) != pdTRUE) { 65 | ret = -2; 66 | } 67 | } 68 | 69 | return ret; 70 | } 71 | 72 | // Deallocates a semaphore 73 | int osi_sem_free(osi_sem_t *sem) 74 | { 75 | vSemaphoreDelete(*sem); 76 | *sem = NULL; 77 | return 0; 78 | } 79 | -------------------------------------------------------------------------------- /libraries/common/posix_compat/semaphore.h: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | * 3 | * Copyright (C) 2015 Google, Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at: 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | * 17 | ******************************************************************************/ 18 | 19 | #ifndef __SEMAPHORE_H__ 20 | #define __SEMAPHORE_H__ 21 | 22 | #include "freertos/FreeRTOS.h" 23 | #include "freertos/task.h" 24 | #include "freertos/queue.h" 25 | #include "freertos/semphr.h" 26 | 27 | #define OSI_SEM_MAX_TIMEOUT 0xffffffffUL 28 | 29 | typedef SemaphoreHandle_t osi_sem_t; 30 | 31 | #define osi_sem_valid( x ) ( ( ( *x ) == NULL) ? pdFALSE : pdTRUE ) 32 | #define osi_sem_set_invalid( x ) ( ( *x ) = NULL ) 33 | 34 | int osi_sem_new(osi_sem_t *sem, uint32_t max_count, uint32_t init_count); 35 | 36 | int osi_sem_free(osi_sem_t *sem); 37 | 38 | int osi_sem_take(osi_sem_t *sem, uint32_t timeout); 39 | 40 | void osi_sem_give(osi_sem_t *sem); 41 | 42 | 43 | #endif /* __SEMAPHORE_H__ */ 44 | -------------------------------------------------------------------------------- /libraries/coreHTTP/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Include HTTP library's source and header path variables. 2 | include( "${CMAKE_CURRENT_LIST_DIR}/coreHTTP/httpFilePaths.cmake" ) 3 | 4 | idf_component_register( 5 | SRCS 6 | "${HTTP_SOURCES}" 7 | "${HTTP_THIRD_PARTY_SOURCES}" 8 | "${CMAKE_CURRENT_LIST_DIR}/port/network_transport/network_transport.c" 9 | INCLUDE_DIRS 10 | "${HTTP_INCLUDE_PUBLIC_DIRS}" 11 | "${CMAKE_CURRENT_LIST_DIR}/../common/logging/" 12 | "${CMAKE_CURRENT_LIST_DIR}/port/network_transport" 13 | "config" 14 | "." 15 | REQUIRES 16 | esp-tls 17 | ) 18 | 19 | set_source_files_properties( 20 | "${CMAKE_CURRENT_LIST_DIR}/coreHTTP/source/core_http_client.c" 21 | PROPERTIES COMPILE_FLAGS -Wno-stringop-truncation 22 | ) -------------------------------------------------------------------------------- /libraries/coreHTTP/Kconfig: -------------------------------------------------------------------------------- 1 | menu "coreHTTP" 2 | 3 | menu "Logging" 4 | 5 | config DEVICE_SHADOW_LOG_ERROR 6 | bool "Enable Error Logging" 7 | default y 8 | 9 | config DEVICE_SHADOW_LOG_WARN 10 | bool "Enable Warning Logging" 11 | default n 12 | 13 | config DEVICE_SHADOW_LOG_INFO 14 | bool "Enable Info Logging" 15 | default y 16 | 17 | config DEVICE_SHADOW_LOG_DEBUG 18 | bool "Enable Debug Logging" 19 | default n 20 | 21 | endmenu # coreHTTP Logging 22 | 23 | endmenu # coreHTTP 24 | -------------------------------------------------------------------------------- /libraries/coreHTTP/config/core_http_config.h: -------------------------------------------------------------------------------- 1 | /* 2 | * AWS IoT Device SDK for Embedded C 202103.00 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | * this software and associated documentation files (the "Software"), to deal in 7 | * the Software without restriction, including without limitation the rights to 8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | * the Software, and to permit persons to whom the Software is furnished to do so, 10 | * subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | */ 22 | 23 | #ifndef CORE_HTTP_CONFIG_H_ 24 | #define CORE_HTTP_CONFIG_H_ 25 | 26 | /**************************************************/ 27 | /******* DO NOT CHANGE the following order ********/ 28 | /**************************************************/ 29 | 30 | /* Logging config definition and header files inclusion are required in the following order: 31 | * 1. Include the header file "logging_levels.h". 32 | * 2. Define the LIBRARY_LOG_NAME and LIBRARY_LOG_LEVEL macros depending on 33 | * the logging configuration for HTTP. 34 | * 3. Include the header file "logging_stack.h", if logging is enabled for HTTP. 35 | */ 36 | 37 | #include "logging_levels.h" 38 | 39 | /* Logging configuration for the HTTP library. */ 40 | #ifndef LIBRARY_LOG_NAME 41 | #define LIBRARY_LOG_NAME "HTTP" 42 | #endif 43 | 44 | #ifndef LIBRARY_LOG_LEVEL 45 | #define LIBRARY_LOG_LEVEL LOG_INFO 46 | #endif 47 | 48 | #include "logging_stack.h" 49 | 50 | 51 | /************ End of logging configuration ****************/ 52 | 53 | #endif /* ifndef CORE_HTTP_CONFIG_H_ */ 54 | -------------------------------------------------------------------------------- /libraries/coreHTTP/port/network_transport/network_transport.c: -------------------------------------------------------------------------------- 1 | #include "freertos/FreeRTOS.h" 2 | #include "freertos/semphr.h" 3 | #include 4 | #include "esp_log.h" 5 | #include "esp_tls.h" 6 | #include "network_transport.h" 7 | #include "sdkconfig.h" 8 | 9 | TlsTransportStatus_t xTlsConnect( NetworkContext_t* pxNetworkContext ) 10 | { 11 | TlsTransportStatus_t xRet = TLS_TRANSPORT_SUCCESS; 12 | 13 | esp_tls_cfg_t xEspTlsConfig = { 14 | .cacert_buf = (const unsigned char*) ( pxNetworkContext->pcServerRootCA ), 15 | .cacert_bytes = pxNetworkContext->pcServerRootCASize, 16 | .clientcert_buf = (const unsigned char*) ( pxNetworkContext->pcClientCert ), 17 | .clientcert_bytes = pxNetworkContext->pcClientCertSize, 18 | .skip_common_name = pxNetworkContext->disableSni, 19 | .alpn_protos = pxNetworkContext->pAlpnProtos, 20 | .use_secure_element = pxNetworkContext->use_secure_element, 21 | .ds_data = pxNetworkContext->ds_data, 22 | .clientkey_buf = ( const unsigned char* )( pxNetworkContext->pcClientKey ), 23 | .clientkey_bytes = pxNetworkContext->pcClientKeySize, 24 | .timeout_ms = 1000, 25 | }; 26 | 27 | esp_tls_t* pxTls = esp_tls_init(); 28 | 29 | xSemaphoreTake(pxNetworkContext->xTlsContextSemaphore, portMAX_DELAY); 30 | pxNetworkContext->pxTls = pxTls; 31 | 32 | if (esp_tls_conn_new_sync( pxNetworkContext->pcHostname, 33 | strlen( pxNetworkContext->pcHostname ), 34 | pxNetworkContext->xPort, 35 | &xEspTlsConfig, pxTls) <= 0) 36 | { 37 | if (pxNetworkContext->pxTls) 38 | { 39 | esp_tls_conn_destroy(pxNetworkContext->pxTls); 40 | pxNetworkContext->pxTls = NULL; 41 | } 42 | xRet = TLS_TRANSPORT_CONNECT_FAILURE; 43 | } 44 | 45 | xSemaphoreGive(pxNetworkContext->xTlsContextSemaphore); 46 | 47 | return xRet; 48 | } 49 | 50 | TlsTransportStatus_t xTlsDisconnect( NetworkContext_t* pxNetworkContext ) 51 | { 52 | BaseType_t xRet = TLS_TRANSPORT_SUCCESS; 53 | 54 | xSemaphoreTake(pxNetworkContext->xTlsContextSemaphore, portMAX_DELAY); 55 | if (pxNetworkContext->pxTls != NULL && 56 | esp_tls_conn_destroy(pxNetworkContext->pxTls) < 0) 57 | { 58 | xRet = TLS_TRANSPORT_DISCONNECT_FAILURE; 59 | } 60 | pxNetworkContext->pxTls = NULL; 61 | xSemaphoreGive(pxNetworkContext->xTlsContextSemaphore); 62 | 63 | return xRet; 64 | } 65 | 66 | int32_t espTlsTransportSend(NetworkContext_t* pxNetworkContext, 67 | const void* pvData, size_t uxDataLen) 68 | { 69 | if (pvData == NULL || uxDataLen == 0) 70 | { 71 | return -1; 72 | } 73 | 74 | int32_t lBytesSent = 0; 75 | 76 | if(pxNetworkContext != NULL && pxNetworkContext->pxTls != NULL) 77 | { 78 | xSemaphoreTake(pxNetworkContext->xTlsContextSemaphore, portMAX_DELAY); 79 | lBytesSent = esp_tls_conn_write(pxNetworkContext->pxTls, pvData, uxDataLen); 80 | xSemaphoreGive(pxNetworkContext->xTlsContextSemaphore); 81 | } 82 | else 83 | { 84 | lBytesSent = -1; 85 | } 86 | 87 | return lBytesSent; 88 | } 89 | 90 | int32_t espTlsTransportRecv(NetworkContext_t* pxNetworkContext, 91 | void* pvData, size_t uxDataLen) 92 | { 93 | if (pvData == NULL || uxDataLen == 0) 94 | { 95 | return -1; 96 | } 97 | int32_t lBytesRead = 0; 98 | if(pxNetworkContext != NULL && pxNetworkContext->pxTls != NULL) 99 | { 100 | xSemaphoreTake(pxNetworkContext->xTlsContextSemaphore, portMAX_DELAY); 101 | lBytesRead = esp_tls_conn_read(pxNetworkContext->pxTls, pvData, uxDataLen); 102 | xSemaphoreGive(pxNetworkContext->xTlsContextSemaphore); 103 | } 104 | else 105 | { 106 | return -1; /* pxNetworkContext or pxTls uninitialised */ 107 | } 108 | if (lBytesRead == ESP_TLS_ERR_SSL_WANT_WRITE || lBytesRead == ESP_TLS_ERR_SSL_WANT_READ) { 109 | return 0; 110 | } 111 | if (lBytesRead < 0) { 112 | return lBytesRead; 113 | } 114 | if (lBytesRead == 0) { 115 | /* Connection closed */ 116 | return -1; 117 | } 118 | return lBytesRead; 119 | } 120 | -------------------------------------------------------------------------------- /libraries/coreHTTP/port/network_transport/network_transport.h: -------------------------------------------------------------------------------- 1 | #ifndef ESP_TLS_TRANSPORT_H 2 | #define ESP_TLS_TRANSPORT_H 3 | 4 | #include "freertos/FreeRTOS.h" 5 | #include "freertos/semphr.h" 6 | #include "transport_interface.h" 7 | #include "esp_tls.h" 8 | 9 | #ifdef __cplusplus 10 | extern "C" { 11 | #endif /* __cplusplus */ 12 | 13 | typedef enum TlsTransportStatus 14 | { 15 | TLS_TRANSPORT_SUCCESS = 0, /**< Function successfully completed. */ 16 | /**< -1 is reserved for ESP_FAIL */ 17 | TLS_TRANSPORT_INVALID_PARAMETER = -2, /**< At least one parameter was invalid. */ 18 | TLS_TRANSPORT_INSUFFICIENT_MEMORY = -3, /**< Insufficient memory required to establish connection. */ 19 | TLS_TRANSPORT_INVALID_CREDENTIALS = -4, /**< Provided credentials were invalid. */ 20 | TLS_TRANSPORT_HANDSHAKE_FAILED = -5, /**< Performing TLS handshake with server failed. */ 21 | TLS_TRANSPORT_INTERNAL_ERROR = -6, /**< A call to a system API resulted in an internal error. */ 22 | TLS_TRANSPORT_CONNECT_FAILURE = -7, /**< Initial connection to the server failed. */ 23 | TLS_TRANSPORT_DISCONNECT_FAILURE = -8 /**< Failed to disconnect from server. */ 24 | } TlsTransportStatus_t; 25 | 26 | struct NetworkContext 27 | { 28 | SemaphoreHandle_t xTlsContextSemaphore; 29 | esp_tls_t* pxTls; 30 | const char *pcHostname; /**< @brief Server host name. */ 31 | int xPort; /**< @brief Server port in host-order. */ 32 | const char *pcServerRootCA; /**< @brief Trusted server root certificate bytes. */ 33 | uint32_t pcServerRootCASize; /**< @brief Number of trusted server root certificate bytes. */ 34 | const char *pcClientCert; /**< @brief Client certificate bytes. */ 35 | uint32_t pcClientCertSize; /**< @brief Number of client certificate bytes. */ 36 | const char *pcClientKey; /**< @brief Client certificate's private key bytes. */ 37 | uint32_t pcClientKeySize; /**< @brief Number of client certificate's private key bytes. */ 38 | bool use_secure_element; /**< @brief Boolean representing the use of secure element 39 | for the TLS connection. */ 40 | void *ds_data; /**< @brief Pointer for digital signature peripheral context */ 41 | 42 | /** 43 | * @brief To use ALPN, set this to a NULL-terminated list of supported 44 | * protocols in decreasing order of preference. 45 | * 46 | * See [this link] 47 | * (https://aws.amazon.com/blogs/iot/mqtt-with-tls-client-authentication-on-port-443-why-it-is-useful-and-how-it-works/) 48 | * for more information. 49 | */ 50 | const char ** pAlpnProtos; 51 | 52 | /** 53 | * @brief Disable server name indication (SNI) for a TLS session. 54 | */ 55 | BaseType_t disableSni; 56 | }; 57 | 58 | TlsTransportStatus_t xTlsConnect(NetworkContext_t* pxNetworkContext ); 59 | 60 | TlsTransportStatus_t xTlsDisconnect( NetworkContext_t* pxNetworkContext ); 61 | 62 | int32_t espTlsTransportSend( NetworkContext_t* pxNetworkContext, 63 | const void* pvData, size_t uxDataLen ); 64 | 65 | int32_t espTlsTransportRecv( NetworkContext_t* pxNetworkContext, 66 | void* pvData, size_t uxDataLen ); 67 | 68 | #ifdef __cplusplus 69 | } 70 | #endif /* __cplusplus */ 71 | #endif /* ESP_TLS_TRANSPORT_H */ 72 | -------------------------------------------------------------------------------- /libraries/coreJSON/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Include coreJSON library's source and header path variables. 2 | include( "${CMAKE_CURRENT_LIST_DIR}/coreJSON/jsonFilePaths.cmake" ) 3 | 4 | idf_component_register( 5 | SRCS 6 | "${JSON_SOURCES}" 7 | INCLUDE_DIRS 8 | "${JSON_INCLUDE_PUBLIC_DIRS}" 9 | "." 10 | ) 11 | -------------------------------------------------------------------------------- /libraries/coreMQTT-Agent/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This gives MQTT_AGENT_INCLUDE_PUBLIC_DIRS and MQTT_AGENT_SOURCES 2 | include(${CMAKE_CURRENT_LIST_DIR}/coreMQTT-Agent/mqttAgentFilePaths.cmake) 3 | 4 | set(COREMQTT_AGENT_PORT_INCLUDE_DIRS 5 | ${CMAKE_CURRENT_LIST_DIR}/port 6 | ) 7 | 8 | set(COREMQTT_AGENT_CONFIG_INCLUDE_DIRS 9 | ${CMAKE_CURRENT_LIST_DIR}/config 10 | ) 11 | 12 | set(COREMQTT_AGENT_INCLUDE_DIRS 13 | ${MQTT_AGENT_INCLUDE_PUBLIC_DIRS} 14 | ${COREMQTT_AGENT_PORT_INCLUDE_DIRS} 15 | ${COREMQTT_AGENT_CONFIG_INCLUDE_DIRS} 16 | ) 17 | 18 | set(COREMQTT_AGENT_PORT_SRCS 19 | ${CMAKE_CURRENT_LIST_DIR}/port/freertos_agent_message.c 20 | ${CMAKE_CURRENT_LIST_DIR}/port/freertos_command_pool.c 21 | ) 22 | 23 | set(COREMQTT_AGENT_SRCS 24 | ${MQTT_AGENT_SOURCES} 25 | ${COREMQTT_AGENT_PORT_SRCS} 26 | ) 27 | 28 | set(COREMQTT_AGENT_REQUIRES 29 | coreMQTT 30 | ) 31 | 32 | idf_component_register( 33 | SRCS 34 | ${COREMQTT_AGENT_SRCS} 35 | INCLUDE_DIRS 36 | ${COREMQTT_AGENT_INCLUDE_DIRS} 37 | REQUIRES 38 | ${COREMQTT_AGENT_REQUIRES} 39 | ) 40 | -------------------------------------------------------------------------------- /libraries/coreMQTT-Agent/Kconfig: -------------------------------------------------------------------------------- 1 | menu "coreMQTT-Agent" 2 | 3 | config MQTT_AGENT_MAX_OUTSTANDING_ACKS 4 | int "Max Pending ACKS Per Connection" 5 | default 10 6 | help 7 | This can be set to any positive integer up to SIZE_MAX. 8 | The maximum number of pending acknowledgments to track for a single connection. 9 | The MQTT agent tracks MQTT commands (such as PUBLISH and SUBSCRIBE) that are still 10 | waiting to be acknowledged. MQTT_AGENT_MAX_OUTSTANDING_ACKS set the maximum number 11 | of acknowledgments that can be outstanding at any one time. The higher this number 12 | is the greater the agent's RAM consumption will be. 13 | 14 | config MQTT_AGENT_MAX_EVENT_QUEUE_WAIT_TIME 15 | int "Max Event Queue Wait Time Milliseconds" 16 | default 1000 17 | range 0 4294967295 18 | help 19 | Time in milliseconds that the MQTT agent task will wait in the Blocked state 20 | (so not using any CPU time) for a command to arrive in its command queue before 21 | exiting the blocked state so it can call MQTT_ProcessLoop(). 22 | It is important that MQTT_ProcessLoop() is called often if there is known MQTT 23 | traffic, but calling it too often can take processing time away from lower priority 24 | tasks and waste CPU time and power. 25 | 26 | endmenu # coreMQTT-Agent -------------------------------------------------------------------------------- /libraries/coreMQTT-Agent/config/core_mqtt_agent_config.h: -------------------------------------------------------------------------------- 1 | /* Wait only a short interval each iteration for faster 2 | * processing of incoming data. */ 3 | #define MQTT_AGENT_MAX_EVENT_QUEUE_WAIT_TIME ( 10U ) 4 | 5 | /* We will be downloading the OTA image one block at a time. 6 | * Limit the number of outstanding ACK we need. */ 7 | #define MQTT_AGENT_MAX_OUTSTANDING_ACKS ( 10U ) -------------------------------------------------------------------------------- /libraries/coreMQTT-Agent/port/freertos_agent_message.c: -------------------------------------------------------------------------------- 1 | /* 2 | * ThirdEye 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 7 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 8 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 9 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | /** 14 | * @file freertos_agent_message.c 15 | * @brief Implements functions to interact with queues. 16 | */ 17 | 18 | /* Standard includes. */ 19 | #include 20 | #include 21 | 22 | /* Kernel includes. */ 23 | #include "freertos/FreeRTOS.h" 24 | #include "freertos/semphr.h" 25 | #include "freertos/queue.h" 26 | 27 | /* Header include. */ 28 | #include "freertos_agent_message.h" 29 | #include "core_mqtt_agent_message_interface.h" 30 | 31 | /*-----------------------------------------------------------*/ 32 | 33 | bool Agent_MessageSend( MQTTAgentMessageContext_t * pMsgCtx, 34 | MQTTAgentCommand_t * const * pCommandToSend, 35 | uint32_t blockTimeMs ) 36 | { 37 | BaseType_t queueStatus = pdFAIL; 38 | 39 | if( ( pMsgCtx != NULL ) && ( pCommandToSend != NULL ) ) 40 | { 41 | queueStatus = xQueueSendToBack( pMsgCtx->queue, pCommandToSend, pdMS_TO_TICKS( blockTimeMs ) ); 42 | } 43 | 44 | return ( queueStatus == pdPASS ) ? true : false; 45 | } 46 | 47 | /*-----------------------------------------------------------*/ 48 | 49 | bool Agent_MessageReceive( MQTTAgentMessageContext_t * pMsgCtx, 50 | MQTTAgentCommand_t ** pReceivedCommand, 51 | uint32_t blockTimeMs ) 52 | { 53 | BaseType_t queueStatus = pdFAIL; 54 | 55 | if( ( pMsgCtx != NULL ) && ( pReceivedCommand != NULL ) ) 56 | { 57 | queueStatus = xQueueReceive( pMsgCtx->queue, pReceivedCommand, pdMS_TO_TICKS( blockTimeMs ) ); 58 | } 59 | 60 | return ( queueStatus == pdPASS ) ? true : false; 61 | } 62 | -------------------------------------------------------------------------------- /libraries/coreMQTT-Agent/port/freertos_agent_message.h: -------------------------------------------------------------------------------- 1 | /* 2 | * ThirdEye 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 7 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 8 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 9 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | /** 14 | * @file freertos_agent_message.h 15 | * @brief Functions to interact with queues. 16 | */ 17 | #ifndef FREERTOS_AGENT_MESSAGE_H 18 | #define FREERTOS_AGENT_MESSAGE_H 19 | 20 | #include 21 | #include 22 | #include 23 | 24 | /* FreeRTOS includes. */ 25 | #include "freertos/FreeRTOS.h" 26 | #include "freertos/queue.h" 27 | 28 | /* Include MQTT agent messaging interface. */ 29 | #include "core_mqtt_agent_message_interface.h" 30 | 31 | #ifdef __cplusplus 32 | extern "C" { 33 | #endif /* __cplusplus */ 34 | 35 | /** 36 | * @ingroup mqtt_agent_struct_types 37 | * @brief Context with which tasks may deliver messages to the agent. 38 | */ 39 | struct MQTTAgentMessageContext 40 | { 41 | QueueHandle_t queue; 42 | }; 43 | 44 | /*-----------------------------------------------------------*/ 45 | 46 | /** 47 | * @brief Send a message to the specified context. 48 | * Must be thread safe. 49 | * 50 | * @param[in] pMsgCtx An #MQTTAgentMessageContext_t. 51 | * @param[in] pData Pointer to element to send to queue. 52 | * @param[in] blockTimeMs Block time to wait for a send. 53 | * 54 | * @return `true` if send was successful, else `false`. 55 | */ 56 | bool Agent_MessageSend( MQTTAgentMessageContext_t * pMsgCtx, 57 | MQTTAgentCommand_t * const * pCommandToSend, 58 | uint32_t blockTimeMs ); 59 | 60 | /** 61 | * @brief Receive a message from the specified context. 62 | * Must be thread safe. 63 | * 64 | * @param[in] pMsgCtx An #MQTTAgentMessageContext_t. 65 | * @param[in] pBuffer Pointer to buffer to write received data. 66 | * @param[in] blockTimeMs Block time to wait for a receive. 67 | * 68 | * @return `true` if receive was successful, else `false`. 69 | */ 70 | bool Agent_MessageReceive( MQTTAgentMessageContext_t * pMsgCtx, 71 | MQTTAgentCommand_t ** pReceivedCommand, 72 | uint32_t blockTimeMs ); 73 | 74 | #ifdef __cplusplus 75 | } 76 | #endif /* __cplusplus */ 77 | #endif /* FREERTOS_AGENT_MESSAGE_H */ 78 | -------------------------------------------------------------------------------- /libraries/coreMQTT-Agent/port/freertos_command_pool.c: -------------------------------------------------------------------------------- 1 | /* 2 | * ThirdEye 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 7 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 8 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 9 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | /** 14 | * @file freertos_command_pool.c 15 | * @brief Implements functions to obtain and release commands. 16 | */ 17 | 18 | /* Standard includes. */ 19 | #include 20 | #include 21 | 22 | /* Kernel includes. */ 23 | #include "freertos/FreeRTOS.h" 24 | #include "freertos/semphr.h" 25 | 26 | /* Header include. */ 27 | #include "freertos_command_pool.h" 28 | #include "freertos_agent_message.h" 29 | 30 | /*-----------------------------------------------------------*/ 31 | 32 | #define QUEUE_NOT_INITIALIZED ( 0U ) 33 | #define QUEUE_INITIALIZED ( 1U ) 34 | 35 | #define MQTT_COMMAND_CONTEXTS_POOL_SIZE ( 10 ) 36 | 37 | /** 38 | * @brief The pool of command structures used to hold information on commands (such 39 | * as PUBLISH or SUBSCRIBE) between the command being created by an API call and 40 | * completion of the command by the execution of the command's callback. 41 | */ 42 | static MQTTAgentCommand_t commandStructurePool[ MQTT_COMMAND_CONTEXTS_POOL_SIZE ]; 43 | 44 | /** 45 | * @brief The message context used to guard the pool of MQTTAgentCommand_t structures. 46 | * For FreeRTOS, this is implemented with a queue. Structures may be 47 | * obtained by receiving a pointer from the queue, and returned by 48 | * sending the pointer back into it. 49 | */ 50 | static MQTTAgentMessageContext_t commandStructMessageCtx; 51 | 52 | /** 53 | * @brief Initialization status of the queue. 54 | */ 55 | static volatile uint8_t initStatus = QUEUE_NOT_INITIALIZED; 56 | 57 | /*-----------------------------------------------------------*/ 58 | 59 | void Agent_InitializePool( void ) 60 | { 61 | size_t i; 62 | MQTTAgentCommand_t * pCommand; 63 | static uint8_t staticQueueStorageArea[ MQTT_COMMAND_CONTEXTS_POOL_SIZE * sizeof( MQTTAgentCommand_t * ) ]; 64 | static StaticQueue_t staticQueueStructure; 65 | bool commandAdded = false; 66 | 67 | if( initStatus == QUEUE_NOT_INITIALIZED ) 68 | { 69 | memset( ( void * ) commandStructurePool, 0x00, sizeof( commandStructurePool ) ); 70 | commandStructMessageCtx.queue = xQueueCreateStatic( MQTT_COMMAND_CONTEXTS_POOL_SIZE, 71 | sizeof( MQTTAgentCommand_t * ), 72 | staticQueueStorageArea, 73 | &staticQueueStructure ); 74 | configASSERT( commandStructMessageCtx.queue ); 75 | 76 | /* Populate the queue. */ 77 | for( i = 0; i < MQTT_COMMAND_CONTEXTS_POOL_SIZE; i++ ) 78 | { 79 | /* Store the address as a variable. */ 80 | pCommand = &commandStructurePool[ i ]; 81 | /* Send the pointer to the queue. */ 82 | commandAdded = Agent_MessageSend( &commandStructMessageCtx, &pCommand, 0U ); 83 | configASSERT( commandAdded ); 84 | } 85 | 86 | initStatus = QUEUE_INITIALIZED; 87 | } 88 | } 89 | 90 | /*-----------------------------------------------------------*/ 91 | 92 | MQTTAgentCommand_t * Agent_GetCommand( uint32_t blockTimeMs ) 93 | { 94 | MQTTAgentCommand_t * structToUse = NULL; 95 | bool structRetrieved = false; 96 | 97 | /* Check queue has been created. */ 98 | configASSERT( initStatus == QUEUE_INITIALIZED ); 99 | 100 | /* Retrieve a struct from the queue. */ 101 | structRetrieved = Agent_MessageReceive( &commandStructMessageCtx, &( structToUse ), blockTimeMs ); 102 | 103 | if( !structRetrieved ) 104 | { 105 | //LogError( ( "No command structure available." ) ); 106 | } else { 107 | //LogDebug( ( "Removed Command Context %d from pool", 108 | // ( int ) ( structToUse - commandStructurePool ) ) ); 109 | } 110 | 111 | return structToUse; 112 | } 113 | 114 | /*-----------------------------------------------------------*/ 115 | 116 | bool Agent_ReleaseCommand( MQTTAgentCommand_t * pCommandToRelease ) 117 | { 118 | bool structReturned = false; 119 | 120 | configASSERT( initStatus == QUEUE_INITIALIZED ); 121 | 122 | /* See if the structure being returned is actually from the pool. */ 123 | if( ( pCommandToRelease >= commandStructurePool ) && 124 | ( pCommandToRelease < ( commandStructurePool + MQTT_COMMAND_CONTEXTS_POOL_SIZE ) ) ) 125 | { 126 | structReturned = Agent_MessageSend( &commandStructMessageCtx, &pCommandToRelease, 0U ); 127 | 128 | /* The send should not fail as the queue was created to hold every command 129 | * in the pool. */ 130 | configASSERT( structReturned ); 131 | //LogDebug( ( "Returned Command Context %d to pool", 132 | // ( int ) ( pCommandToRelease - commandStructurePool ) ) ); 133 | } 134 | 135 | return structReturned; 136 | } 137 | -------------------------------------------------------------------------------- /libraries/coreMQTT-Agent/port/freertos_command_pool.h: -------------------------------------------------------------------------------- 1 | /* 2 | * ThirdEye 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 6 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 7 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 8 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 9 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 10 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 11 | * 12 | */ 13 | /** 14 | * @file freertos_command_pool.h 15 | * @brief Functions to obtain and release a command. 16 | */ 17 | #ifndef FREERTOS_COMMAND_POOL_H 18 | #define FREERTOS_COMMAND_POOL_H 19 | 20 | /* MQTT agent includes. */ 21 | #include "core_mqtt_agent.h" 22 | 23 | #ifdef __cplusplus 24 | extern "C" { 25 | #endif /* __cplusplus */ 26 | 27 | /** 28 | * @brief Initialize the common task pool. Not thread safe. 29 | */ 30 | void Agent_InitializePool( void ); 31 | 32 | /** 33 | * @brief Obtain a MQTTAgentCommand_t structure from the pool of structures managed by the agent. 34 | * 35 | * @note MQTTAgentCommand_t structures hold everything the MQTT agent needs to process a 36 | * command that originates from application. Examples of commands are PUBLISH and 37 | * SUBSCRIBE. The MQTTAgentCommand_t structure must persist for the duration of the command's 38 | * operation so are obtained from a pool of statically allocated structures when a 39 | * new command is created, and returned to the pool when the command is complete. 40 | * The MQTT_COMMAND_CONTEXTS_POOL_SIZE configuration file constant defines how many 41 | * structures the pool contains. 42 | * 43 | * @param[in] blockTimeMs The length of time the calling task should remain in the 44 | * Blocked state (so not consuming any CPU time) to wait for a MQTTAgentCommand_t structure to 45 | * become available should one not be immediately at the time of the call. 46 | * 47 | * @return A pointer to a MQTTAgentCommand_t structure if one becomes available before 48 | * blockTimeMs time expired, otherwise NULL. 49 | */ 50 | MQTTAgentCommand_t * Agent_GetCommand( uint32_t blockTimeMs ); 51 | 52 | /** 53 | * @brief Give a MQTTAgentCommand_t structure back to the the pool of structures managed by 54 | * the agent. 55 | * 56 | * @note MQTTAgentCommand_t structures hold everything the MQTT agent needs to process a 57 | * command that originates from application. Examples of commands are PUBLISH and 58 | * SUBSCRIBE. The MQTTAgentCommand_t structure must persist for the duration of the command's 59 | * operation so are obtained from a pool of statically allocated structures when a 60 | * new command is created, and returned to the pool when the command is complete. 61 | * The MQTT_COMMAND_CONTEXTS_POOL_SIZE configuration file constant defines how many 62 | * structures the pool contains. 63 | * 64 | * @param[in] pCommandToRelease A pointer to the MQTTAgentCommand_t structure to return to 65 | * the pool. The structure must first have been obtained by calling 66 | * Agent_GetCommand(), otherwise Agent_ReleaseCommand() will 67 | * have no effect. 68 | * 69 | * @return true if the MQTTAgentCommand_t structure was returned to the pool, otherwise false. 70 | */ 71 | bool Agent_ReleaseCommand( MQTTAgentCommand_t * pCommandToRelease ); 72 | 73 | #ifdef __cplusplus 74 | } 75 | #endif /* __cplusplus */ 76 | #endif /* FREERTOS_COMMAND_POOL_H */ 77 | -------------------------------------------------------------------------------- /libraries/coreMQTT/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This gives MQTT_INCLUDE_PUBLIC_DIRS, MQTT_SOURCES, and MQTT_SERIALIZER_SOURCES 2 | include(${CMAKE_CURRENT_LIST_DIR}/coreMQTT/mqttFilePaths.cmake) 3 | 4 | set(COREMQTT_PORT_INCLUDE_DIRS 5 | ${CMAKE_CURRENT_LIST_DIR}/port/network_transport 6 | ) 7 | 8 | set(COREMQTT_INCLUDE_DIRS 9 | ${MQTT_INCLUDE_PUBLIC_DIRS} 10 | ${CMAKE_CURRENT_LIST_DIR}/config 11 | ${CMAKE_CURRENT_LIST_DIR}/../common/logging/ 12 | ${COREMQTT_PORT_INCLUDE_DIRS} 13 | ) 14 | 15 | set(COREMQTT_PORT_SRCS 16 | ${CMAKE_CURRENT_LIST_DIR}/port/network_transport/network_transport.c 17 | ) 18 | 19 | set(COREMQTT_SRCS 20 | ${MQTT_SOURCES} 21 | ${MQTT_SERIALIZER_SOURCES} 22 | ${COREMQTT_PORT_SRCS} 23 | ) 24 | 25 | set(COREMQTT_REQUIRES 26 | esp-tls 27 | ) 28 | 29 | idf_component_register( 30 | SRCS 31 | ${COREMQTT_SRCS} 32 | INCLUDE_DIRS 33 | ${COREMQTT_INCLUDE_DIRS} 34 | REQUIRES 35 | ${COREMQTT_REQUIRES} 36 | ) 37 | 38 | set_source_files_properties( 39 | "${CMAKE_CURRENT_LIST_DIR}/coreMQTT/source/core_mqtt.c" 40 | PROPERTIES COMPILE_FLAGS -Wno-format) -------------------------------------------------------------------------------- /libraries/coreMQTT/Kconfig: -------------------------------------------------------------------------------- 1 | menu "coreMQTT" 2 | 3 | config MQTT_STATE_ARRAY_MAX_COUNT 4 | int "Max Incoming/Outgoing Publish Messages Pending ACK" 5 | default 10 6 | range 0 4294967295 7 | help 8 | Determines the maximum number of MQTT PUBLISH messages, pending 9 | acknowledgment at a time, that are supported for incoming and outgoing 10 | direction of messages, separately. 11 | 12 | QoS 1 and 2 MQTT PUBLISHes require acknowledgment from the server before 13 | they can be completed. While they are awaiting the acknowledgment, the 14 | client must maintain information about their state. The value of this 15 | macro sets the limit on how many simultaneous PUBLISH states an MQTT 16 | context maintains, separately, for both incoming and outgoing direction of 17 | PUBLISHes. 18 | 19 | The MQTT context maintains separate state records for outgoing 20 | and incoming PUBLISHes, and thus, 2 * MQTT_STATE_ARRAY_MAX_COUNT amount 21 | of memory is statically allocated for the state records. 22 | 23 | config MQTT_MAX_CONNACK_RECEIVE_RETRY_COUNT 24 | int "Max CONNACK Retries" 25 | default 5 26 | range 0 65535 27 | help 28 | The number of retries for receiving CONNACK. 29 | 30 | The MQTT_MAX_CONNACK_RECEIVE_RETRY_COUNT will be used only when the 31 | timeoutMs parameter of #MQTT_Connect is passed as 0 . The transport 32 | receive for CONNACK will be retried MQTT_MAX_CONNACK_RECEIVE_RETRY_COUNT 33 | times before timing out. A value of 0 for this config will cause the 34 | transport receive for CONNACK to be invoked only once. 35 | 36 | config MQTT_PINGRESP_TIMEOUT_MS 37 | int "Ping Response Timeout Milliseconds" 38 | default 5000 39 | help 40 | This can be any positive integer up to SIZE_MAX. 41 | 42 | Maximum number of milliseconds to wait for a ping response to a ping 43 | request as part of the keep-alive mechanism. 44 | 45 | If a ping response is not received before this timeout, then 46 | MQTT_ProcessLoop function will return MQTTKeepAliveTimeout. 47 | 48 | If this value is more than half of the keep alive interval, and the 49 | server does not receive the previous ping request, then it is likely that the 50 | server will disconnect the client before #MQTTKeepAliveTimeout can be returned. 51 | 52 | If a dummy implementation of the MQTTGetCurrentTimeFunc_t timer function, 53 | is supplied to the library, then the keep-alive mechanism is not supported by the 54 | MQTT_ProcessLoop API function. In that case, the value of MQTT_PINGRESP_TIMEOUT_MS 55 | is irrelevant to the behavior of the library. 56 | 57 | config MQTT_RECV_POLLING_TIMEOUT_MS 58 | int "MQTT Packet Receive Polling Timeout" 59 | default 10 60 | range 0 4294967295 61 | help 62 | The maximum duration between non-empty network reads while 63 | receiving an MQTT packet via the MQTT_ProcessLoop or MQTT_ReceiveLoop 64 | API functions. 65 | 66 | When an incoming MQTT packet is detected, the transport receive function 67 | may be called multiple times until all of the expected number of bytes of the 68 | packet are received. This timeout represents the maximum polling duration that 69 | is allowed without any data reception from the network for the incoming packet. 70 | 71 | If the timeout expires, the MQTT_ProcessLoop and MQTT_ReceiveLoop functions 72 | return MQTTRecvFailed. 73 | 74 | If a dummy implementation of the MQTTGetCurrentTimeFunc_t timer function, 75 | is supplied to the library, then MQTT_RECV_POLLING_TIMEOUT_MS MUST be set to 0. 76 | 77 | config MQTT_SEND_TIMEOUT_MS 78 | int "MQTT Send Timeout Milliseconds" 79 | default 20000 80 | range 0 4294967295 81 | help 82 | The maximum duration allowed to send an MQTT packet over the transport 83 | interface. 84 | 85 | When sending an MQTT packet, the transport send or writev functions may be 86 | called multiple times until all of the required number of bytes are sent. 87 | This timeout represents the maximum duration that is allowed to send the MQTT 88 | packet while calling the transport send or writev functions. 89 | 90 | If the timeout expires, #MQTTSendFailed will be returned by the public API 91 | functions. 92 | 93 | If a dummy implementation of the #MQTTGetCurrentTimeFunc_t timer function, 94 | is supplied to the library, then #MQTT_SEND_TIMEOUT_MS MUST be set to 0. 95 | 96 | menu "Logging" 97 | 98 | config CORE_MQTT_LOG_ERROR 99 | bool "Enable Error Logging" 100 | default y 101 | 102 | config CORE_MQTT_LOG_WARN 103 | bool "Enable Warning Logging" 104 | default n 105 | 106 | config CORE_MQTT_LOG_INFO 107 | bool "Enable Info Logging" 108 | default y 109 | 110 | config CORE_MQTT_LOG_DEBUG 111 | bool "Enable Debug Logging" 112 | default n 113 | 114 | endmenu # coreMQTT Logging 115 | 116 | endmenu # coreMQTT 117 | -------------------------------------------------------------------------------- /libraries/coreMQTT/config/core_mqtt_config.h: -------------------------------------------------------------------------------- 1 | #ifndef COREMQTT_CONFIG_H 2 | #define COREMQTT_CONFIG_H 3 | 4 | #include "sdkconfig.h" 5 | #define EXTRACT_ARGS( ... ) __VA_ARGS__ 6 | #define STRIP_PARENS( X ) X 7 | #define REMOVE_PARENS( X ) STRIP_PARENS( EXTRACT_ARGS X ) 8 | 9 | /* Logging configurations */ 10 | #if CONFIG_CORE_MQTT_LOG_ERROR || CONFIG_CORE_MQTT_LOG_WARN || CONFIG_CORE_MQTT_LOG_INFO || CONFIG_CORE_MQTT_LOG_DEBUG 11 | 12 | /* Set logging level for the coreMQTT and coreMQTT-Agent components to highest level, 13 | * so any defined logging level below is printed. */ 14 | #ifdef LOG_LOCAL_LEVEL 15 | #undef LOG_LOCAL_LEVEL 16 | #endif 17 | #define LOG_LOCAL_LEVEL ESP_LOG_VERBOSE 18 | #include "esp_log.h" 19 | 20 | /* Change LIBRARY_LOG_NAME to "coreMQTT" if defined somewhere else. */ 21 | #ifdef LIBRARY_LOG_NAME 22 | #undef LIBRARY_LOG_NAME 23 | #endif 24 | #define LIBRARY_LOG_NAME "coreMQTT" 25 | 26 | #endif 27 | 28 | /* Undefine logging macros if they were defined somewhere else like another AWS/FreeRTOS library. */ 29 | #ifdef LogError 30 | #undef LogError 31 | #endif 32 | 33 | #ifdef LogWarn 34 | #undef LogWarn 35 | #endif 36 | 37 | #ifdef LogInfo 38 | #undef LogInfo 39 | #endif 40 | 41 | #ifdef LogDebug 42 | #undef LogDebug 43 | #endif 44 | 45 | /* Define logging macros based on configurations in sdkconfig.h. */ 46 | #if CONFIG_CORE_MQTT_LOG_ERROR 47 | #define LogError( message, ... ) ESP_LOGE( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 48 | #else 49 | #define LogError( message, ... ) 50 | #endif 51 | 52 | #if CONFIG_CORE_MQTT_LOG_WARN 53 | #define LogWarn( message, ... ) ESP_LOGW( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 54 | #else 55 | #define LogWarn( message, ... ) 56 | #endif 57 | 58 | #if CONFIG_CORE_MQTT_LOG_INFO 59 | #define LogInfo( message, ... ) ESP_LOGI( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 60 | #else 61 | #define LogInfo( message, ... ) 62 | #endif 63 | 64 | #if CONFIG_CORE_MQTT_LOG_DEBUG 65 | #define LogDebug( message, ... ) ESP_LOGD( LIBRARY_LOG_NAME, REMOVE_PARENS( message ), ##__VA_ARGS__ ) 66 | #else 67 | #define LogDebug( message, ... ) 68 | #endif 69 | 70 | /* coreMQTT configurations */ 71 | #define MQTT_STATE_ARRAY_MAX_COUNT CONFIG_MQTT_STATE_ARRAY_MAX_COUNT 72 | #define MQTT_MAX_CONNACK_RECEIVE_RETRY_COUNT CONFIG_MQTT_MAX_CONNACK_RECEIVE_RETRY_COUNT 73 | #define MQTT_PINGRESP_TIMEOUT_MS CONFIG_MQTT_PINGRESP_TIMEOUT_MS 74 | #define MQTT_RECV_POLLING_TIMEOUT_MS CONFIG_MQTT_RECV_POLLING_TIMEOUT_MS 75 | #define MQTT_SEND_TIMEOUT_MS CONFIG_MQTT_SEND_TIMEOUT_MS 76 | 77 | /* coreMQTT-Agent configurations */ 78 | #define MQTT_AGENT_MAX_OUTSTANDING_ACKS CONFIG_MQTT_AGENT_MAX_OUTSTANDING_ACKS 79 | #define MQTT_AGENT_MAX_EVENT_QUEUE_WAIT_TIME CONFIG_MQTT_AGENT_MAX_EVENT_QUEUE_WAIT_TIME 80 | 81 | #endif /* COREMQTT_CONFIG_H */ -------------------------------------------------------------------------------- /libraries/coreMQTT/port/network_transport/network_transport.h: -------------------------------------------------------------------------------- 1 | #ifndef ESP_TLS_TRANSPORT_H 2 | #define ESP_TLS_TRANSPORT_H 3 | 4 | /* *INDENT-OFF* */ 5 | #ifdef __cplusplus 6 | extern "C" { 7 | #endif 8 | /* *INDENT-ON* */ 9 | 10 | #include "freertos/FreeRTOS.h" 11 | #include "freertos/semphr.h" 12 | #include "transport_interface.h" 13 | #include "esp_tls.h" 14 | 15 | typedef enum TlsTransportStatus 16 | { 17 | TLS_TRANSPORT_SUCCESS = 0, /**< Function successfully completed. */ 18 | /**< -1 is reserved for ESP_FAIL */ 19 | TLS_TRANSPORT_INVALID_PARAMETER = -2, /**< At least one parameter was invalid. */ 20 | TLS_TRANSPORT_INSUFFICIENT_MEMORY = -3, /**< Insufficient memory required to establish connection. */ 21 | TLS_TRANSPORT_INVALID_CREDENTIALS = -4, /**< Provided credentials were invalid. */ 22 | TLS_TRANSPORT_HANDSHAKE_FAILED = -5, /**< Performing TLS handshake with server failed. */ 23 | TLS_TRANSPORT_INTERNAL_ERROR = -6, /**< A call to a system API resulted in an internal error. */ 24 | TLS_TRANSPORT_CONNECT_FAILURE = -7, /**< Initial connection to the server failed. */ 25 | TLS_TRANSPORT_DISCONNECT_FAILURE = -8 /**< Failed to disconnect from server. */ 26 | } TlsTransportStatus_t; 27 | 28 | struct NetworkContext 29 | { 30 | SemaphoreHandle_t xTlsContextSemaphore; 31 | esp_tls_t* pxTls; 32 | const char *pcHostname; /**< @brief Server host name. */ 33 | int xPort; /**< @brief Server port in host-order. */ 34 | const char *pcServerRootCA; /**< @brief Trusted server root certificate bytes. */ 35 | uint32_t pcServerRootCASize; /**< @brief Number of trusted server root certificate bytes. */ 36 | const char *pcClientCert; /**< @brief Client certificate bytes. */ 37 | uint32_t pcClientCertSize; /**< @brief Number of client certificate bytes. */ 38 | const char *pcClientKey; /**< @brief Client certificate's private key bytes. */ 39 | uint32_t pcClientKeySize; /**< @brief Number of client certificate's private key bytes. */ 40 | bool use_secure_element; /**< @brief Boolean representing the use of secure element 41 | for the TLS connection. */ 42 | void *ds_data; /**< @brief Pointer for digital signature peripheral context */ 43 | 44 | /** 45 | * @brief To use ALPN, set this to a NULL-terminated list of supported 46 | * protocols in decreasing order of preference. 47 | * 48 | * See [this link] 49 | * (https://aws.amazon.com/blogs/iot/mqtt-with-tls-client-authentication-on-port-443-why-it-is-useful-and-how-it-works/) 50 | * for more information. 51 | */ 52 | const char ** pAlpnProtos; 53 | 54 | /** 55 | * @brief Disable server name indication (SNI) for a TLS session. 56 | */ 57 | BaseType_t disableSni; 58 | }; 59 | 60 | /** 61 | * @brief Structure to configure timeouts for individual TLS operations in milliseconds resolution. 62 | * Note that it uses FreeRTOS software timer internally and hence minimum resolution is the tick duration. 63 | * These timeouts can be specified before any receive or send operation. Timout of 0 will act as a non-blocking mode. 64 | * 65 | * Defaults are: 66 | * Connection timeout - 4 seconds 67 | * Send timeout - 10 seconds 68 | * Receive timeout - 2 seconds 69 | */ 70 | typedef struct Timeouts 71 | { 72 | uint16_t connectionTimeoutMs; 73 | uint16_t sendTimeoutMs; 74 | uint16_t recvTimeoutMs; 75 | } Timeouts_t; 76 | 77 | TlsTransportStatus_t xTlsConnect(NetworkContext_t* pxNetworkContext ); 78 | 79 | TlsTransportStatus_t xTlsDisconnect( NetworkContext_t* pxNetworkContext ); 80 | 81 | int32_t espTlsTransportSend( NetworkContext_t* pxNetworkContext, 82 | const void* pvData, size_t uxDataLen ); 83 | 84 | int32_t espTlsTransportRecv( NetworkContext_t* pxNetworkContext, 85 | void* pvData, size_t uxDataLen ); 86 | 87 | void vTlsSetConnectTimeout( uint16_t connectionTimeoutMs ); 88 | 89 | void vTlsSetSendTimeout( uint16_t sendTimeoutMs ); 90 | 91 | void vTlsSetRecvTimeout( uint16_t recvTimeoutMs ); 92 | 93 | /* *INDENT-OFF* */ 94 | #ifdef __cplusplus 95 | } 96 | #endif 97 | /* *INDENT-ON* */ 98 | 99 | #endif /* ESP_TLS_TRANSPORT_H */ 100 | -------------------------------------------------------------------------------- /libraries/corePKCS11/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This gives PKCS_INCLUDE_PUBLIC_DIRS, and PKCS_SOURCES 2 | include(${CMAKE_CURRENT_LIST_DIR}/corePKCS11/pkcsFilePaths.cmake) 3 | 4 | set(COREPKCS11_LOCATION "${CMAKE_CURRENT_LIST_DIR}/corePKCS11") 5 | 6 | set(CORE_PKCS11_3RDPARTY_LOCATION "${COREPKCS11_LOCATION}/source/dependency/3rdparty") 7 | 8 | set(COREPKCS_PORT_INCLUDE_DIRS 9 | ${CMAKE_CURRENT_LIST_DIR}/port 10 | ${CMAKE_CURRENT_LIST_DIR}/../common/logging/ 11 | ) 12 | 13 | set(COREPKCS_INCLUDE_DIRS 14 | ${PKCS_INCLUDE_PUBLIC_DIRS} 15 | ${CMAKE_CURRENT_LIST_DIR}/config 16 | ${COREPKCS_PORT_INCLUDE_DIRS} 17 | ) 18 | 19 | set(COREPKCS_PORT_SRCS 20 | ${CMAKE_CURRENT_LIST_DIR}/port/core_pkcs11_pal.c 21 | ${CMAKE_CURRENT_LIST_DIR}/port/iot_crypto.c 22 | ) 23 | 24 | set(COREPKCS_SRCS 25 | ${PKCS_SOURCES} 26 | ${COREPKCS_PORT_SRCS} 27 | ) 28 | 29 | set(COREPKCS_REQUIRES 30 | mbedtls 31 | nvs_flash 32 | log 33 | bootloader_support 34 | spi_flash 35 | ) 36 | 37 | idf_component_register( 38 | SRCS 39 | ${COREPKCS_SRCS} 40 | "${CORE_PKCS11_3RDPARTY_LOCATION}/mbedtls_utils/mbedtls_utils.c" 41 | INCLUDE_DIRS 42 | ${COREPKCS_INCLUDE_DIRS} 43 | ${CORE_PKCS11_3RDPARTY_LOCATION}/mbedtls_utils 44 | PRIV_INCLUDE_DIRS 45 | 46 | REQUIRES 47 | ${COREPKCS_REQUIRES} 48 | ) 49 | -------------------------------------------------------------------------------- /libraries/corePKCS11/Kconfig: -------------------------------------------------------------------------------- 1 | menu "corePKCS11" 2 | 3 | menu "Logging" 4 | 5 | config CORE_PKCS_LOG_ERROR 6 | bool "Enable Error Logging" 7 | default y 8 | 9 | config CORE_PKCS_LOG_WARN 10 | bool "Enable Warning Logging" 11 | default n 12 | 13 | config CORE_PKCS_LOG_INFO 14 | bool "Enable Info Logging" 15 | default y 16 | 17 | config CORE_PKCS_LOG_DEBUG 18 | bool "Enable Debug Logging" 19 | default n 20 | 21 | endmenu # Logging 22 | 23 | endmenu # corePKCS11 -------------------------------------------------------------------------------- /libraries/corePKCS11/port/iot_crypto.h: -------------------------------------------------------------------------------- 1 | /* 2 | * FreeRTOS Crypto V1.1.2 3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. 4 | * 5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of 6 | * this software and associated documentation files (the "Software"), to deal in 7 | * the Software without restriction, including without limitation the rights to 8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 9 | * the Software, and to permit persons to whom the Software is furnished to do so, 10 | * subject to the following conditions: 11 | * 12 | * The above copyright notice and this permission notice shall be included in all 13 | * copies or substantial portions of the Software. 14 | * 15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | * 22 | * http://aws.amazon.com/freertos 23 | * http://www.FreeRTOS.org 24 | */ 25 | 26 | #ifndef __AWS_CRYPTO__H__ 27 | #define __AWS_CRYPTO__H__ 28 | 29 | #include "freertos/FreeRTOS.h" 30 | 31 | #ifdef __cplusplus 32 | extern "C" { 33 | #endif /* __cplusplus */ 34 | 35 | /** 36 | * @brief Commonly used buffer sizes for storing cryptographic hash computation 37 | * results. 38 | */ 39 | #define cryptoSHA1_DIGEST_BYTES 20 40 | #define cryptoSHA256_DIGEST_BYTES 32 41 | 42 | /** 43 | * @brief Initializes the heap and threading functions for cryptography libraries. 44 | */ 45 | void CRYPTO_Init( void ); 46 | 47 | /** 48 | * @brief Initializes the mbedTLS mutex functions. 49 | * 50 | * Provides mbedTLS access to mutex create, destroy, take and free. 51 | * 52 | * @see MBEDTLS_THREADING_ALT 53 | */ 54 | void CRYPTO_ConfigureThreading( void ); 55 | 56 | /** 57 | * @brief Library-independent cryptographic algorithm identifiers. 58 | */ 59 | #define cryptoHASH_ALGORITHM_SHA1 1 60 | #define cryptoHASH_ALGORITHM_SHA256 2 61 | #define cryptoASYMMETRIC_ALGORITHM_RSA 1 62 | #define cryptoASYMMETRIC_ALGORITHM_ECDSA 2 63 | 64 | /** 65 | * @brief Initializes digital signature verification. 66 | * 67 | * @param[out] ppvContext Opaque context structure. 68 | * @param[in] xAsymmetricAlgorithm Cryptographic public key cryptosystem. 69 | * @param[in] xHashAlgorithm Cryptographic hash algorithm that was used for signing. 70 | * 71 | * @return pdTRUE if initialization succeeds, or pdFALSE otherwise. 72 | */ 73 | BaseType_t CRYPTO_SignatureVerificationStart( void ** ppvContext, 74 | BaseType_t xAsymmetricAlgorithm, 75 | BaseType_t xHashAlgorithm ); 76 | 77 | /** 78 | * @brief Updates a cryptographic hash computation with the specified byte array. 79 | * 80 | * @param[in] pvContext Opaque context structure. 81 | * @param[in] pucData Byte array that was signed. 82 | * @param[in] xDataLength Length in bytes of data that was signed. 83 | */ 84 | void CRYPTO_SignatureVerificationUpdate( void * pvContext, 85 | const uint8_t * pucData, 86 | size_t xDataLength ); 87 | 88 | /** 89 | * @brief Verifies a digital signature computation using the public key from the 90 | * specified certificate. 91 | * 92 | * @param[in] pvContext Opaque context structure. 93 | * @param[in] pucSignerCertificate Base64 and DER encoded X.509 certificate of the 94 | * signer. 95 | * @param[in] xSignerCertificateLength Length in bytes of the certificate. 96 | * @param[in] pucSignature Digital signature result to verify. 97 | * @param[in] xSignatureLength in bytes of digital signature result. 98 | * 99 | * @return pdTRUE if the signature is correct or pdFALSE if the signature is invalid. 100 | */ 101 | BaseType_t CRYPTO_SignatureVerificationFinal( void * pvContext, 102 | char * pcSignerCertificate, 103 | size_t xSignerCertificateLength, 104 | uint8_t * pucSignature, 105 | size_t xSignatureLength ); 106 | #ifdef __cplusplus 107 | } 108 | #endif /* __cplusplus */ 109 | #endif /* ifndef __AWS_CRYPTO__H__ */ 110 | --------------------------------------------------------------------------------