### Install Node.js Repository Source: https://docs.aws.amazon.com/iot/latest/developerguide/connecting-to-existing-device.md Downloads the Node.js v12.x repository setup script. This is the first step to installing Node.js and npm on your Raspberry Pi. ```bash cd ~ curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - ``` -------------------------------- ### Example nmap version output (Windows) Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-quick-start-test-connection.md This is an example of the expected output when checking the nmap version on a Windows system. It confirms the installation and provides build details. ```text Nmap version 7.92 ( https://nmap.org ) Platform: i686-pc-windows-windows Compiled with: nmap-liblua-5.3.5 openssl-1.1.1k nmap-libssh2-1.9.0 nmap-libz-1.2.11 nmap-libpcre-7.6 Npcap-1.50 nmap-libdnet-1.12 ipv6 Compiled without: Available nsock engines: iocp poll select ``` -------------------------------- ### AWS IoT SDK for Kotlin Setup and Usage Source: https://docs.aws.amazon.com/iot/latest/developerguide/example_iot_Scenario_section.md Provides setup instructions and a basic usage example for the AWS SDK for Kotlin with AWS IoT. Requires an SNS topic and an IAM Role. ```kotlin import aws.sdk.kotlin.services.iot.IotClient import aws.sdk.kotlin.services.iot.model.Action import aws.sdk.kotlin.services.iot.model.AttachThingPrincipalRequest import aws.sdk.kotlin.services.iot.model.AttributePayload import aws.sdk.kotlin.services.iot.model.CreateThingRequest import aws.sdk.kotlin.services.iot.model.CreateTopicRuleRequest import aws.sdk.kotlin.services.iot.model.DeleteCertificateRequest import aws.sdk.kotlin.services.iot.model.DeleteThingRequest import aws.sdk.kotlin.services.iot.model.DescribeEndpointRequest import aws.sdk.kotlin.services.iot.model.DescribeThingRequest import aws.sdk.kotlin.services.iot.model.DetachThingPrincipalRequest import aws.sdk.kotlin.services.iot.model.ListTopicRulesRequest import aws.sdk.kotlin.services.iot.model.SearchIndexRequest import aws.sdk.kotlin.services.iot.model.SnsAction import aws.sdk.kotlin.services.iot.model.TopicRulePayload import aws.sdk.kotlin.services.iot.model.UpdateThingRequest import aws.sdk.kotlin.services.iotdataplane.IotDataPlaneClient import aws.sdk.kotlin.services.iotdataplane.model.GetThingShadowRequest import aws.sdk.kotlin.services.iotdataplane.model.UpdateThingShadowRequest import aws.smithy.kotlin.runtime.content.ByteStream import aws.smithy.kotlin.runtime.content.toByteArray import java.util.Scanner import java.util.regex.Pattern import kotlin.system.exitProcess /** * Before running this Kotlin code example, ensure that your development environment * is set up, including configuring your credentials. * * For detailed instructions, refer to the following documentation topic: * [Setting Up Your Development Environment](https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html) * * This code example requires an SNS topic and an IAM Role. * Follow the steps in the documentation to set up these resources: * * - [Creating an SNS Topic](https://docs.aws.amazon.com/sns/latest/dg/sns-getting-started.html#step-create-topic) * - [Creating an IAM Role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html) */ val DASHES = String(CharArray(80)).replace("\u0000", "-") val TOPIC = "your-iot-topic" suspend fun main(args: Array) { val usage = """ Usage: Where: roleARN - The ARN of an IAM role that has permission to work with AWS IOT. snsAction - An ARN of an SNS topic. """.trimIndent() if (args.size != 2) { println(usage) exitProcess(1) } var thingName: String val roleARN = args[0] val snsAction = args[1] val scanner = Scanner(System.`in`) ``` -------------------------------- ### ProvisionDevice Log Entry Example Source: https://docs.aws.amazon.com/iot/latest/developerguide/cwl-format.md Example of a log entry for a ProvisionDevice event. This log captures details about a device being provisioned. ```json { "eventType" : "ProvisionDevice", "provisioningTemplateName" : "myTemplate", "deviceCertificateId" : "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "details" : "Additional details about this log." } ``` -------------------------------- ### AWS CLI Script for IoT Core Setup Source: https://docs.aws.amazon.com/iot/latest/developerguide/example_iot_GettingStarted_063_section.md This Bash script automates the creation of AWS IoT resources, device configuration, and sample application setup. It includes logging and error handling for a robust setup process. ```bash #!/bin/bash # AWS IoT Core Getting Started Script # This script creates AWS IoT resources, configures a device, and runs a sample application # Set up logging LOG_FILE="iot-core-setup.log" echo "Starting AWS IoT Core setup at $(date)" > $LOG_FILE # Function to log commands and their outputs log_cmd() { echo "$(date): Running command: $1" >> $LOG_FILE eval "$1" 2>&1 | tee -a $LOG_FILE return ${PIPESTATUS[0]} } # Function to check for errors check_error() { if [ $1 -ne 0 ]; then echo "ERROR: Command failed with exit code $1" | tee -a $LOG_FILE echo "Please check the log file $LOG_FILE for details" | tee -a $LOG_FILE cleanup_on_error exit $1 fi } # Function to cleanup resources on error cleanup_on_error() { echo "Error encountered. Attempting to clean up resources..." | tee -a $LOG_FILE echo "Resources created:" | tee -a $LOG_FILE if [ ! -z "$CERTIFICATE_ARN" ]; then echo "Certificate ARN: $CERTIFICATE_ARN" | tee -a $LOG_FILE if [ ! -z "$POLICY_NAME" ]; then log_cmd "aws iot detach-policy --policy-name $POLICY_NAME --target $CERTIFICATE_ARN" fi if [ ! -z "$THING_NAME" ]; then log_cmd "aws iot detach-thing-principal --thing-name $THING_NAME --principal $CERTIFICATE_ARN" fi if [ ! -z "$CERTIFICATE_ID" ]; then log_cmd "aws iot update-certificate --certificate-id $CERTIFICATE_ID --new-status INACTIVE" log_cmd "aws iot delete-certificate --certificate-id $CERTIFICATE_ID" fi fi if [ ! -z "$THING_NAME" ]; then echo "Thing Name: $THING_NAME" | tee -a $LOG_FILE log_cmd "aws iot delete-thing --thing-name $THING_NAME" fi if [ ! -z "$POLICY_NAME" ]; then echo "Policy Name: $POLICY_NAME" | tee -a $LOG_FILE log_cmd "aws iot delete-policy --policy-name $POLICY_NAME" fi if [ ! -z "$SHARED_POLICY_NAME" ]; then echo "Shared Policy Name: $SHARED_POLICY_NAME" | tee -a $LOG_FILE log_cmd "aws iot delete-policy --policy-name $SHARED_POLICY_NAME" fi } ``` -------------------------------- ### Shadow Get Rejected Example Source: https://docs.aws.amazon.com/iot/latest/developerguide/using-device-shadows.md This JSON shows an example of a rejected shadow get request, typically occurring when a named shadow has not yet been created. ```json { "code": 404, "message": "No shadow exists with name: 'simShadow1'" } ``` -------------------------------- ### Install Sample App Dependencies Source: https://docs.aws.amazon.com/iot/latest/developerguide/creating-a-virtual-thing.md Navigate to the sample application directory and install its dependencies using npm. This prepares the sample application for execution. ```bash cd ~/aws-iot-device-sdk-js-v2/samples/node/pub_sub npm install ``` -------------------------------- ### Example HTTP GET Request for DescribeJobExecution API Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-data-plane-jobs.md This example shows how an IoT device might make an HTTP GET request to the DescribeJobExecution API. Ensure your device's policy allows this action. ```http GET /things/thingName/jobs/jobId?executionNumber=executionNumber&includeJobDocument=includeJobDocument&namespaceId=namespaceId HTTP/1.1 ``` -------------------------------- ### Run the Sample Application Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-embedded-c-sdk.md Navigate to the bin directory and execute the `mqtt_demo_mutual_auth` application to connect to AWS IoT. ```bash cd bin ./mqtt_demo_mutual_auth ``` -------------------------------- ### GetConnection Log Entry Example Source: https://docs.aws.amazon.com/iot/latest/developerguide/cwl-format.md An example of a log entry generated when a request to get connection information is received. ```json { "timestamp": "2025-08-22 19:19:50.679", "logLevel": "INFO", "traceId": "7a04de1a-d1a3-50bc-3ca5-96b1ee293dae", "accountId": "987654321", "status": "Success", "eventType": "GetConnection", "protocol": "HTTP", "clientId": "aClient", "principalId": "AIDAZPOK3C3545MCMYATF", "sourceIp": "52.94.133.137", "sourcePort": 31983 } ``` -------------------------------- ### Run Sample Program (Linux/macOS) Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-quick-start.md Execute the sample program using the start script. This command is for Linux/macOS operating systems. ```bash ./start.sh ``` -------------------------------- ### Welcome to AWS IoT Example Scenario Source: https://docs.aws.amazon.com/iot/latest/developerguide/example_iot_Scenario_section.md Prints a welcome message and a description of the AWS IoT example scenario. This is the entry point for the demonstration. ```kotlin println(DASHES) println("Welcome to the AWS IoT example scenario.") println( """ This example program demonstrates various interactions with the AWS Internet of Things (IoT) Core service. The program guides you through a series of steps, including creating an IoT thing, generating a device certificate, updating the thing with attributes, and so on. It utilizes the AWS SDK for Kotlin and incorporates functionality for creating and managing IoT things, certificates, rules, shadows, and performing searches. The program aims to showcase AWS IoT capabilities and provides a comprehensive example for developers working with AWS IoT in a Kotlin environment. """.trimIndent() ) print("Press Enter to continue...") scanner.nextLine() println(DASHES) ``` -------------------------------- ### Run MQTT5 Shared Subscription Example Source: https://docs.aws.amazon.com/iot/latest/developerguide/example_iot_GettingStarted_063_section.md Execute the mqtt5_shared_subscription sample application with the necessary parameters including endpoint, CA file, certificate, key, and group identifier. Navigate to the samples directory first. ```bash echo "To run the shared subscription example, execute:" | tee -a $LOG_FILE echo "cd $HOME/aws-iot-device-sdk-python-v2/samples" | tee -a $LOG_FILE echo "python3 mqtt5_shared_subscription.py \" | tee -a $LOG_FILE echo " --endpoint $IOT_ENDPOINT \" | tee -a $LOG_FILE echo " --ca_file $CERTS_DIR/Amazon-root-CA-1.pem \" | tee -a $LOG_FILE echo " --cert $CERTS_DIR/device.pem.crt \" | tee -a $LOG_FILE echo " --key $CERTS_DIR/private.pem.key \" | tee -a $LOG_FILE echo " --group_identifier consumer" | tee -a $LOG_FILE ``` -------------------------------- ### Create Tutorial Directories Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-dc-install-download.md Commands to create the necessary directories on the Raspberry Pi for storing configuration files, policies, messages, and certificates used by the tutorials. ```bash mkdir ~/dc-configs mkdir ~/policies mkdir ~/messages mkdir ~/certs/testconn mkdir ~/certs/pubsub mkdir ~/certs/jobs ``` -------------------------------- ### Example nmap version output (macOS) Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-quick-start-test-connection.md This is an example of the expected output when checking the nmap version on a macOS system. It confirms the installation and provides build details. ```text Nmap version 7.92 ( https://nmap.org ) Platform: x86_64-apple-darwin17.7.0 Compiled with: nmap-liblua-5.3.5 openssl-1.1.1k nmap-libssh2-1.9.0 libz-1.2.11 nmap-libpcre-7.6 nmap-libpcap-1.9.1 nmap-libdnet-1.12 ipv6 Compiled without: Available nsock engines: kqueue poll select ``` -------------------------------- ### Example nmap version output (Linux) Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-quick-start-test-connection.md This is an example of the expected output when checking the nmap version on a Linux system. It confirms the installation and provides build details. ```text Nmap version 6.40 ( http://nmap.org ) Platform: x86_64-koji-linux-gnu Compiled with: nmap-liblua-5.2.2 openssl-1.0.2k libpcre-8.32 libpcap-1.5.3 nmap-libdnet-1.12 ipv6 Compiled without: Available nsock engines: epoll poll select ``` -------------------------------- ### Run Shared Subscription Example (Windows) Source: https://docs.aws.amazon.com/iot/latest/developerguide/using-laptop-as-device.md Execute the MQTT5 shared subscription sample script on a Windows PC. Ensure you replace 'your-iot-endpoint' with your actual AWS IoT endpoint and provide the correct paths to your CA certificate, device certificate, and private key. ```bash python3 mqtt5_shared_subscription.py --endpoint your-iot-endpoint --ca_file %USERPROFILE%\certs\Amazon-root-CA-1.pem --cert %USERPROFILE%\certs\device.pem.crt --key %USERPROFILE%\certs\private.pem.key --group_identifier consumer ``` -------------------------------- ### Start AWS IoT Device Client Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-dc-testconn-subscribe.md Navigate to the build directory and start the AWS IoT Device Client with a specific configuration file. Ensure the configuration file is correctly set up for pub/sub operations. ```bash cd ~/aws-iot-device-client/build ./aws-iot-device-client --config-file ~/dc-configs/dc-pubsub-wild-config.json ``` -------------------------------- ### Get Connection Details for a Standard Client Source: https://docs.aws.amazon.com/iot/latest/developerguide/mqtt.md Example of a GET request to retrieve connection details for a client with a simple ID. The `includeSocketInformation` parameter is set to false. ```http GET /connections/myDevice123?includeSocketInformation=false HTTP/1.1 ``` -------------------------------- ### Deployment Instruction File Example (recipe) Source: https://docs.aws.amazon.com/iot/latest/developerguide/preparing-jobs-for-service-package-catalog.md An example of a deployment instruction file (recipe) used in AWS IoT Jobs, including package and version names. ```json { "packageName": "{{sample-package-name}}", "versionName": "{{sample-package-version}}", ... "recipe": "{...}" } ``` -------------------------------- ### Start Next Job Accepted Response Source: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-mqtt-api.md Example of a successful response when requesting the next job execution. ```json { "execution" : JobExecutionData, "timestamp" : timestamp, "clientToken" : "string" } ``` -------------------------------- ### Create Log Directories and Files Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-dc-testconn-provision.md Set up the necessary directories and log files for the AWS IoT Device Client. ```bash mkdir ~/.aws-iot-device-client mkdir ~/.aws-iot-device-client/log chmod 745 ~/.aws-iot-device-client/log echo " " > ~/.aws-iot-device-client/log/aws-iot-device-client.log echo " " > ~/.aws-iot-device-client/log/pubsub_rx_msgs.log chmod 600 ~/.aws-iot-device-client/log/* ``` -------------------------------- ### Navigate to Sample App Directory Source: https://docs.aws.amazon.com/iot/latest/developerguide/lightbulb-shadow-application.md Change the current directory to the location of the Device SDK sample applications. ```bash cd ~/aws-iot-device-sdk-python-v2/samples/service-clients ``` -------------------------------- ### Step Functions Rule Payload Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-create-rule.md Example payload for a rule that starts an execution of a Step Functions state machine. ```json { "sql": "expression", "ruleDisabled": false, "awsIotSqlVersion": "2016-03-23", "actions": [ { "stepFunctions": { "stateMachineName": "myCoolStateMachine", "executionNamePrefix": "coolRunning", "roleArn": "arn:aws:iam::123456789012:role/my-iot-role" } } ] } ``` -------------------------------- ### Example of get function usage with Object Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-functions.md Retrieves a value from an object using a string key. No conversion is applied to the key. ```sql get({"a":"b"}, "a") ``` -------------------------------- ### Create Sample IoT Things with Attributes Source: https://docs.aws.amazon.com/iot/latest/developerguide/fleet-metrics-get-started.md This bash script creates ten sample IoT things, each with temperature, rack ID, and normal state attributes. It then describes each created thing. ```bash Temperatures=(70 71 72 73 74 75 47 97 98 99) Racks=(Rack1 Rack1 Rack2 Rack2 Rack3 Rack4 Rack5 Rack6 Rack6 Rack6) IsNormal=(true true true true true true false false false false) for ((i=0; i < 10; i++)) do thing=$(aws iot create-thing --thing-name "TempSensor$i" --attribute-payload attributes="{temperature=${Temperatures[@]:$i:1},rackId=${Racks[@]:$i:1},stateNormal=${IsNormal[@]:$i:1}}") aws iot describe-thing --thing-name "TempSensor$i" done ``` -------------------------------- ### Run Shared Subscription Example (Linux/macOS) Source: https://docs.aws.amazon.com/iot/latest/developerguide/using-laptop-as-device.md Execute the MQTT5 shared subscription sample script on Linux or macOS. Ensure you replace 'your-iot-endpoint' with your actual AWS IoT endpoint and provide the correct paths to your CA certificate, device certificate, and private key. ```bash python3 mqtt5_shared_subscription.py --endpoint your-iot-endpoint --ca_file ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key --group_identifier consumer ``` -------------------------------- ### Example of get function usage with String Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-functions.md Extracts a character from a string using a 0-based index. Supports integer conversion for the index. ```sql get("abc", 0) ``` -------------------------------- ### Install Node.js and npm Source: https://docs.aws.amazon.com/iot/latest/developerguide/connecting-to-existing-device.md Installs Node.js and the npm package manager using apt-get. This command should be run after setting up the Node.js repository. ```bash sudo apt-get install -y nodejs ``` -------------------------------- ### Example of get function usage with Array Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-functions.md Extracts an element from an array using a 0-based index. Supports integer conversion for the index. ```sql get(["a", "b", "c"], 1) ``` -------------------------------- ### Publish/Subscribe Example in Python Source: https://docs.aws.amazon.com/iot/latest/developerguide/mqtt.md Demonstrates how to publish and subscribe to MQTT topics using the AWS IoT Device SDK v2 for Python. This sample requires the SDK and appropriate AWS credentials or certificates. ```python import argparse import sys import threading import time from awscrt import io, mqtt, auth, http from awsiot import mqtt_connection_builder # Using a simple callback for when a message is received def on_message_received(topic, payload, **kwargs): print(f"Received message from topic '{topic}': {payload}") def main(): parser = argparse.ArgumentParser(description="AWS IoT MQTT Pub/Sub example using the SDK v2 for Python.") parser.add_argument("--endpoint", required=True, help="Your AWS IoT custom endpoint, custom.amazonaws.com") parser.add_argument("--cert", help="Path to your certificate file, pem.") parser.add_argument("--key", help="Path to your private key file, pem.") parser.add_argument("--root-ca", help="Path to your root CA file, pem.") parser.add_argument("--client-id", default="test-" + str(time.time()), help="Client ID for the MQTT connection.") parser.add_argument("--topic", default="test/topic", help="Targeted topic to publish and subscribe to.") parser.add_argument("--message", default="Hello World!", help="The message payload to publish.") args = parser.parse_args() if not args.cert or not args.key: parser.error("Both --cert and --key must be provided for mutual TLS authentication.") # Initialize the AWS Common Runtime (CRT) I/O system event_loop_group = io.EventLoopGroup() host_resolver = io.DefaultHostResolver(event_loop_group) client_bootstrap = io.ClientBootstrap(event_loop_group, host_resolver) # Create a MQTT connection builder mqtt_connection_builder_obj = mqtt_connection_builder.MqttConnectionBuilder() mqtt_connection_builder_obj.with_endpoint(args.endpoint) mqtt_connection_builder_obj.with_client_id(args.client_id) mqtt_connection_builder_obj.with_transport_operation(http.HttpRequestOptions(client_bootstrap=client_bootstrap)) mqtt_connection_builder_obj.with_tls_connection_options(client_bootstrap=client_bootstrap, tls_options=io.TlsContextOptions.create_client_with_mtls_from_path(args.cert, args.key)) mqtt_connection_builder_obj.with_root_cert_from_path(args.root_ca) # Connect to AWS IoT mqtt_connection = mqtt_connection_builder_obj.build() print(f"Connecting to {args.endpoint} with client ID '{args.client_id}'...") connect_future = mqtt_connection.connect() # Wait for the connection to be established connect_future.result() print("Connected!") # Subscribe to the topic print(f"Subscribing to topic '{args.topic}'...") subscribe_future, packet_id = mqtt_connection.subscribe(topic=args.topic, qos=mqtt.QoS.AT_LEAST_ONCE, callback=on_message_received) subscribe_future.result() # Wait for subscription to complete print(f"Subscribed with packet ID: {packet_id}") # Publish a message print(f"Publishing message '{args.message}' to topic '{args.topic}'...") publish_future, packet_id = mqtt_connection.publish(topic=args.topic, payload=args.message, qos=mqtt.QoS.AT_LEAST_ONCE) publish_future.result() # Wait for publish to complete print(f"Published with packet ID: {packet_id}") # Keep the connection alive for a short period to receive messages print("Waiting for messages...") time.sleep(5) # Adjust as needed # Disconnect print("Disconnecting...") disconnect_future = mqtt_connection.disconnect() disconnect_future.result() # Wait for disconnection to complete print("Disconnected!") if __name__ == '__main__': main() ``` -------------------------------- ### PUT Request to Start Next Pending Job Execution Source: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-http-device-api.md Use this HTTPS request to get and start the next pending job execution for a thing. You can optionally set a step timeout and provide status details. If no jobs are pending, the response will not include an 'execution' field. ```HTTP PUT /things/{{thingName}}/jobs/$next { "statusDetails": { "string": "string" ... }, "stepTimeoutInMinutes": long } ``` -------------------------------- ### Query Thing Group Index Source: https://docs.aws.amazon.com/iot/latest/developerguide/thinggroup-index.md Search for thing groups within the AWS_ThingGroups index using a query string. This example searches for groups starting with 'mythinggroup'. ```bash aws iot search-index --index-name "AWS_ThingGroups" --query-string "thingGroupName:mythinggroup*" ``` -------------------------------- ### Run shadow.py Sample App (Python) Source: https://docs.aws.amazon.com/iot/latest/developerguide/interact-lights-device-shadows.md Execute the shadow.py sample application to interact with AWS IoT Device Shadows. Ensure you replace placeholders with your specific endpoint and thing name. ```python cd ~/aws-iot-device-sdk-python-v2/samples/service-clients python3 shadow.py --ca_file ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key --endpoint {{your-iot-endpoint}} --thing_name {{your-iot-thing-name}} ``` -------------------------------- ### Create Directory and Set Permissions Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-dc-install-configure.md Commands to create a directory for configuration files and set appropriate permissions. ```bash mkdir ~/dc-configs chmod 745 ~/dc-configs ``` -------------------------------- ### StartNextPendingJobExecution Request Payload Source: https://docs.aws.amazon.com/iot/latest/developerguide/jobs-mqtt-api.md Publish this JSON payload to `$aws/things/{{thingName}}/jobs/start-next` to get and start the next pending job execution. Optionally include `stepTimeoutInMinutes` to set a job timer. ```json { "statusDetails": { "string": "{{job-execution-state}}" ... }, "stepTimeoutInMinutes": long, "clientToken": "string" } ``` -------------------------------- ### Setup Index and Retry Search with .NET SDK Source: https://docs.aws.amazon.com/iot/latest/developerguide/example_iot_SearchIndex_section.md Sets up the indexing configuration to REGISTRY mode and retries the search after waiting for the index to be ready. Includes retry logic for index setup. ```.NET /// /// Sets up the indexing configuration and retries the search after waiting for the index to be ready. /// /// The search query string. /// List of Things that match the search criteria, or empty list if setup/search failed. private async Task> SetupIndexAndRetrySearchAsync(string queryString) { try { // Update indexing configuration to REGISTRY mode _logger.LogInformation("Setting up IoT search indexing configuration..."); await _amazonIoT.UpdateIndexingConfigurationAsync( new UpdateIndexingConfigurationRequest() { ThingIndexingConfiguration = new ThingIndexingConfiguration() { ThingIndexingMode = ThingIndexingMode.REGISTRY } }); _logger.LogInformation("Indexing configuration updated. Waiting for index to be ready..."); // Wait for the index to be set up - this can take some time const int maxRetries = 10; const int retryDelaySeconds = 10; for (int attempt = 1; attempt <= maxRetries; attempt++) { try { _logger.LogInformation($"Waiting for index to be ready (attempt {attempt}/{maxRetries})..."); await Task.Delay(TimeSpan.FromSeconds(retryDelaySeconds)); // Try to get the current indexing configuration to see if it's ready var configResponse = await _amazonIoT.GetIndexingConfigurationAsync(new GetIndexingConfigurationRequest()); if (configResponse.ThingIndexingConfiguration?.ThingIndexingMode == ThingIndexingMode.REGISTRY) { // Try the search again var request = new SearchIndexRequest { QueryString = queryString }; ``` -------------------------------- ### Example Device Shadow for AnotherThing Source: https://docs.aws.amazon.com/iot/latest/developerguide/preparing-fleet-indexing.md This JSON structure represents the reported state of a device named 'AnotherThing', detailing multiple installed software packages including 'SamplePackage' and 'OtherPackage' with their respective versions and attributes. ```json { "state": { "reported": { "SamplePackage": { "version": "1.0.0", "attributes": { "s3UrlForSamplePackage": "https://EXAMPIEBUCKET.s3.us-west-2.amazonaws.com/exampleCodeFile1", "packageID": "1111" } }, "OtherPackage": { "version": "1.2.5", "attributes": { "s3UrlForOtherPackage": "https://EXAMPIEBUCKET.s3.us-west-2.amazonaws.com/exampleCodeFile2", "packageID": "2222" } }, } } } ``` -------------------------------- ### Sample Application Output and Interaction Source: https://docs.aws.amazon.com/iot/latest/developerguide/lightbulb-shadow-application.md Observe the initial connection and subscription messages, followed by a prompt to enter a desired shadow value. The application updates the reported value to match the desired value. ```text Connecting to a3qEXAMPLEffp-ats.iot.us-west-2.amazonaws.com with client ID 'test-0c8ae2ff-cc87-49d2-a82a-ae7ba1d0ca5a'... Connected! Subscribing to Delta events... Subscribing to Update responses... Subscribing to Get responses... Requesting current shadow state... Launching thread to read user input... Finished getting initial shadow state. Shadow contains reported value 'off'. Enter desired value: ``` ```text Enter desired value: yellow Changed local shadow value to 'yellow'. Updating reported shadow value to 'yellow'... ``` -------------------------------- ### Handling JSON Property Names with Special Characters Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-json.md When JSON property names contain hyphens or numeric characters, use the 'get' function instead of dot notation. This example demonstrates accessing a property with a hyphen. ```SQL SELECT * from 'iot/rules' WHERE get(get(get(mydata,"item2"),"0"),"my-key") = "myValue" ``` -------------------------------- ### Initialize AWS SDK and List IoT Things in Java Source: https://docs.aws.amazon.com/iot/latest/developerguide/example_iot_Hello_section.md Initializes the AWS SDK for Java 2.x, creates an IoT client, and lists all things in the current account. Uses paginators for efficient retrieval. ```java import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iot.IotClient; import software.amazon.awssdk.services.iot.model.ListThingsRequest; import software.amazon.awssdk.services.iot.model.ListThingsResponse; import software.amazon.awssdk.services.iot.model.ThingAttribute; import software.amazon.awssdk.services.iot.paginators.ListThingsIterable; import java.util.List; public class HelloIoT { public static void main(String[] args) { System.out.println("Hello AWS IoT. Here is a listing of your AWS IoT Things:"); IotClient iotClient = IotClient.builder() .region(Region.US_EAST_1) .build(); listAllThings(iotClient); } public static void listAllThings(IotClient iotClient) { ListThingsRequest listThingsRequest = ListThingsRequest.builder().build(); ListThingsIterable thingsIterable = iotClient.listThingsPaginator(listThingsRequest); for (ThingAttribute thingAttribute : thingsIterable) { System.out.println("Thing name: " + thingAttribute.thingName()); } } } ``` -------------------------------- ### Substring Function Examples Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-sql-functions.md Illustrates the usage of the substring() function with various inputs, including different index types and out-of-bounds values. Demonstrates string slicing from a start index to the end, or between two specified indices. ```sql substring("012345", 0) = "012345" ``` ```sql substring("012345", 2) = "2345" ``` ```sql substring("012345", 2.745) = "2345" ``` ```sql substring(123, 2) = "3" ``` ```sql substring("012345", -1) = "012345" ``` ```sql substring(true, 1.2) = "rue" ``` ```sql substring(false, -2.411E247) = "false" ``` ```sql substring("012345", 1, 3) = "12" ``` ```sql substring("012345", -50, 50) = "012345" ``` ```sql substring("012345", 3, 1) = "" ``` -------------------------------- ### Install and Run JavaScript Sample App for AWS IoT Source: https://docs.aws.amazon.com/iot/latest/developerguide/connecting-to-existing-device.md Install the Node.js SDK and run the JavaScript sample application to connect to AWS IoT, subscribe to a topic, and publish messages. Replace {{your-iot-endpoint}} with your actual AWS IoT endpoint. ```bash cd ~/aws-iot-device-sdk-js-v2/samples/node/pub_sub npm install ``` ```javascript node dist/index.js --topic topic_1 --ca_file ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key --endpoint {{your-iot-endpoint}} ``` -------------------------------- ### Delete AWS IoT Topic Rule in Python (Boto3) Source: https://docs.aws.amazon.com/iot/latest/developerguide/example_iot_DeleteTopicRule_section.md Deletes an AWS IoT topic rule using the AWS SDK for Python (Boto3). This example includes error handling and logging. Ensure Boto3 is installed and configured. ```python class IoTWrapper: """Encapsulates AWS IoT actions.""" def __init__(self, iot_client, iot_data_client=None): """ :param iot_client: A Boto3 AWS IoT client. :param iot_data_client: A Boto3 AWS IoT Data Plane client. """ self.iot_client = iot_client self.iot_data_client = iot_data_client @classmethod def from_client(cls): iot_client = boto3.client("iot") iot_data_client = boto3.client("iot-data") return cls(iot_client, iot_data_client) def delete_topic_rule(self, rule_name): """ Deletes an AWS IoT topic rule. :param rule_name: The name of the rule to delete. """ try: self.iot_client.delete_topic_rule(ruleName=rule_name) logger.info("Deleted topic rule %s.", rule_name) except ClientError as err: logger.error( "Couldn't delete topic rule. Here's why: %s: %s", err.response["Error"Ма "Code"], err.response["Error"Ма "Message"], ) raise ``` -------------------------------- ### Initialize AWS SDK and List IoT Things in C++ Source: https://docs.aws.amazon.com/iot/latest/developerguide/example_iot_Hello_section.md Initializes the AWS SDK, creates an IoT client, and lists all things in the current account. Handles pagination and error reporting. Requires AWS SDK for C++. ```cpp #include #include #include #include /* * A "Hello IoT" starter application which initializes an AWS IoT client and * lists the AWS IoT topics in the current account. * * main function * * Usage: 'hello_iot' * */ int main(int argc, char **argv) { Aws::SDKOptions options; // Optional: change the log level for debugging. // options.loggingOptions.logLevel = Aws::Utils::Logging::LogLevel::Debug; Aws::InitAPI(options); // Should only be called once. { Aws::Client::ClientConfiguration clientConfig; // Optional: Set to the AWS Region (overrides config file). // clientConfig.region = "us-east-1"; Aws::IoT::IoTClient iotClient(clientConfig); // List the things in the current account. Aws::IoT::Model::ListThingsRequest listThingsRequest; Aws::String nextToken; // Used for pagination. Aws::Vector allThings; do { if (!nextToken.empty()) { listThingsRequest.SetNextToken(nextToken); } Aws::IoT::Model::ListThingsOutcome listThingsOutcome = iotClient.ListThings( listThingsRequest); if (listThingsOutcome.IsSuccess()) { const Aws::Vector &things = listThingsOutcome.GetResult().GetThings(); allThings.insert(allThings.end(), things.begin(), things.end()); nextToken = listThingsOutcome.GetResult().GetNextToken(); } else { std::cerr << "List things failed" << listThingsOutcome.GetError().GetMessage() << std::endl; break; } } while (!nextToken.empty()); std::cout << allThings.size() << " thing(s) found." << std::endl; for (auto const &thing: allThings) { std::cout << thing.GetThingName() << std::endl; } } Aws::ShutdownAPI(options); // Should only be called once. return 0; } ``` -------------------------------- ### GetPendingJobExecution Log Entry Example Source: https://docs.aws.amazon.com/iot/latest/developerguide/cwl-format.md This JSON object illustrates a log entry created when the AWS IoT Jobs service processes a request to get a pending job execution. It contains information about the client, topic, and request status. ```json { "timestamp": "2018-06-13 17:45:17.197", "logLevel": "DEBUG", "accountId": "123456789012", "status": "Success", "eventType": "GetPendingJobExecution", "protocol": "MQTT", "clientId": "299966ad-54de-40b4-99d3-4fc8b52da0c5", "topicName": "$aws/things/299966ad-54de-40b4-99d3-4fc8b52da0c5/jobs/get", "clientToken": "24b9a741-15a7-44fc-bd3c-1ff2e34e5e82", "details": "The request status is SUCCESS." } ``` -------------------------------- ### Query AWS IoT Fleet Index (C++) Source: https://docs.aws.amazon.com/iot/latest/developerguide/example_iot_SearchIndex_section.md This C++ snippet demonstrates how to query the AWS IoT fleet index, including handling pagination and potential errors. Refer to the AWS Code Examples Repository for setup and execution details. ```C++ //! Query the AWS IoT fleet index. //! For query information, see https://docs.aws.amazon.com/iot/latest/developerguide/query-syntax.html /*! \param: query: The query string. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::IoT::searchIndex(const Aws::String &query, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::IoT::IoTClient iotClient(clientConfiguration); Aws::IoT::Model::SearchIndexRequest request; request.SetQueryString(query); Aws::Vector allThingDocuments; Aws::String nextToken; // Used for pagination. do { if (!nextToken.empty()) { request.SetNextToken(nextToken); } Aws::IoT::Model::SearchIndexOutcome outcome = iotClient.SearchIndex(request); if (outcome.IsSuccess()) { const Aws::IoT::Model::SearchIndexResult &result = outcome.GetResult(); allThingDocuments.insert(allThingDocuments.end(), result.GetThings().cbegin(), result.GetThings().cend()); nextToken = result.GetNextToken(); } else { std::cerr << "Error in SearchIndex: " << outcome.GetError().GetMessage() << std::endl; return false; } } while (!nextToken.empty()); ``` -------------------------------- ### Python Sample App Output (Initial State) Source: https://docs.aws.amazon.com/iot/latest/developerguide/interact-lights-device-shadows.md View the initial output of the shadow.py sample app when it connects, retrieves the current shadow state, and sets default values if the shadow document is missing properties. ```text Connecting to a3qEXAMPLEffp-ats.iot.us-west-2.amazonaws.com with client ID 'test-0c8ae2ff-cc87-49d2-a82a-ae7ba1d0ca5a'... Connected! Subscribing to Delta events... Subscribing to Update responses... Subscribing to Get responses... Requesting current shadow state... Launching thread to read user input... Finished getting initial shadow state. Shadow document lacks 'color' property. Setting defaults... Changed local shadow value to 'off'. Updating reported shadow value to 'off'... Update request published. Finished updating reported shadow value to 'off'... Enter desired value: ``` -------------------------------- ### Create Build Directory Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-embedded-c-sdk.md Navigate to the SDK's root directory and create a build directory. This is where the build process will take place. ```bash mkdir build && cd build ``` -------------------------------- ### Get AWS IoT Logging Options with Python (Boto3) Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-connect-service.md This Python snippet retrieves the account's currently configured AWS IoT logging options using the Boto3 SDK. Ensure the SDK is installed and configured for your AWS account. ```python import boto3 import json ``` -------------------------------- ### Step Functions Rule Action Configuration Source: https://docs.aws.amazon.com/iot/latest/developerguide/stepfunctions-rule-action.md Example JSON configuration for an AWS IoT rule to start a Step Functions state machine. Specifies the state machine name, an optional execution name prefix, and the IAM role ARN. ```json { "topicRulePayload": { "sql": "SELECT * FROM 'some/topic'", "ruleDisabled": false, "awsIotSqlVersion": "2016-03-23", "actions": [ { "stepFunctions": { "stateMachineName": "myStateMachine", "executionNamePrefix": "myExecution", "roleArn": "arn:aws:iam::123456789012:role/aws_iot_step_functions" } } ] } } ``` -------------------------------- ### IoT Agent Java Example Source: https://docs.aws.amazon.com/iot/latest/developerguide/configure-remote-device.md This Java code demonstrates how to implement an IoT agent using the AWS IoT Device SDK and ProcessBuilder. It connects to AWS IoT, subscribes to tunnel notification topics, and starts a local proxy process upon receiving a valid MQTT message. ```java // Find the IoT device endpoint for your AWS account final String endpoint = iotClient.describeEndpoint(new DescribeEndpointRequest().withEndpointType("iot:Data-ATS")).getEndpointAddress(); // Instantiate the IoT Agent with your AWS credentials final String thingName = "RemoteDeviceA"; final String tunnelNotificationTopic = String.format("$aws/things/%s/tunnels/notify", thingName); final AWSIotMqttClient mqttClient = new AWSIotMqttClient(endpoint, thingName, "your_aws_access_key", "your_aws_secret_key"); try { mqttClient.connect(); final TunnelNotificationListener listener = new TunnelNotificationListener(tunnelNotificationTopic); mqttClient.subscribe(listener, true); } finally { mqttClient.disconnect(); } private static class TunnelNotificationListener extends AWSIotTopic { public TunnelNotificationListener(String topic) { super(topic); } @Override public void onMessage(AWSIotMessage message) { try { // Deserialize the MQTT message final JSONObject json = new JSONObject(message.getStringPayload()); final String accessToken = json.getString("clientAccessToken"); final String region = json.getString("region"); final String clientMode = json.getString("clientMode"); if (!clientMode.equals("destination")) { throw new RuntimeException("Client mode " + clientMode + " in the MQTT message is not expected"); } final JSONArray servicesArray = json.getJSONArray("services"); if (servicesArray.length() > 1) { throw new RuntimeException("Services in the MQTT message has more than 1 service"); } final String service = servicesArray.get(0).toString(); if (!service.equals("SSH")) { throw new RuntimeException("Service " + service + " is not supported"); } // Start the destination local proxy in a separate process to connect to the SSH Daemon listening port 22 final ProcessBuilder pb = new ProcessBuilder("localproxy", "-t", accessToken, "-r", region, "-d", "localhost:22"); pb.start(); } catch (Exception e) { log.error("Failed to start the local proxy", e); } } } ``` -------------------------------- ### Create Fleet Metric Example Source: https://docs.aws.amazon.com/iot/latest/developerguide/fleet-indexing-troubleshooting.md This is an example command for creating a fleet metric. Ensure your thing objects match the query criteria to see data points in CloudWatch. ```bash aws iot create-fleet-metric --metric-name "MyMetric" --metric-query-string "thingName:TempSensor* AND shadow.desired.temperature>80" --period 300 --unit "Count" --aggregation-field-names "TempSensor" ``` -------------------------------- ### Run Pub/Sub Sample on Windows Source: https://docs.aws.amazon.com/iot/latest/developerguide/using-laptop-as-device.md Command to run the Python pub/sub sample script on Windows. Ensure you replace placeholders with your actual endpoint and certificate paths. ```bash cd %USERPROFILE%\aws-iot-device-sdk-python-v2\samples python3 pubsub.py --endpoint your-iot-endpoint --ca_file %USERPROFILE%\certs\Amazon-root-CA-1.pem --cert %USERPROFILE%\certs\device.pem.crt --key %USERPROFILE%\certs\private.pem.key ``` -------------------------------- ### StartNextPendingJobExecution Log Entry Example Source: https://docs.aws.amazon.com/iot/latest/developerguide/cwl-format.md This JSON structure represents a log entry generated when AWS IoT Jobs starts the next pending job execution. It includes details like timestamp, log level, account ID, event type, protocol, client ID, and topic name. ```json { "timestamp": "2018-06-13 17:49:51.036", "logLevel": "DEBUG", "accountId": "123456789012", "status": "Success", "eventType": "StartNextPendingJobExecution", "protocol": "MQTT", "clientId": "95c47808-b1ca-4794-bc68-a588d6d9216c", "topicName": "$aws/things/95c47808-b1ca-4794-bc68-a588d6d9216c/jobs/start-next", "clientToken": "bd7447c4-3a05-49f4-8517-dd89b2c68d94", "details": "The request status is SUCCESS." } ``` -------------------------------- ### Check pip3 Installation Source: https://docs.aws.amazon.com/iot/latest/developerguide/connecting-to-existing-device.md Verify if pip3, the package installer for Python, is installed on your system. This is necessary for installing Python packages. ```bash pip3 --version ``` -------------------------------- ### AWS CLI Configuration Example Source: https://docs.aws.amazon.com/iot/latest/developerguide/creating-a-virtual-thing.md Provides example values for AWS CLI configuration. Replace these with your actual credentials and region. ```bash AWS Access Key ID [None]: {{AKIAIOSFODNN7EXAMPLE}} AWS Secret Access Key [None]: {{wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY}} Default region name [None]: {{us-west-2}} Default output format [None]: {{json}} ``` -------------------------------- ### Install pip3 on Debian/Ubuntu Source: https://docs.aws.amazon.com/iot/latest/developerguide/connecting-to-existing-device.md Install pip3 using the apt package manager. This command is used on Debian-based Linux distributions to install the Python package installer. ```bash sudo apt install python3-pip ``` -------------------------------- ### AWS Start Application Job Document Source: https://docs.aws.amazon.com/iot/latest/developerguide/job-templates-managed.md This job document defines how to start services using the 'start-services.sh' handler. It requires the 'services' parameter and supports optional 'runAsUser' and 'pathToHandler'. ```json { "version": "1.0", "steps": [ { "action": { "name": "Start-Application", "type": "runHandler", "input": { "handler": "start-services.sh", "args": [ "${aws:iot:parameter:services}" ], "path": "${aws:iot:parameter:pathToHandler}" }, "runAsUser": "${aws:iot:parameter:runAsUser}" } } ] } ``` -------------------------------- ### Check Git Installation Source: https://docs.aws.amazon.com/iot/latest/developerguide/connecting-to-existing-device.md Verify if Git is already installed on your system. This is a prerequisite for installing the AWS IoT Device SDK for JavaScript. ```bash git --version ``` -------------------------------- ### Run the shadow.py Sample Application Source: https://docs.aws.amazon.com/iot/latest/developerguide/lightbulb-shadow-application.md Execute the `shadow.py` script with your AWS IoT endpoint and thing name. Ensure you have the correct CA file, certificate, and private key paths. ```bash python3 shadow.py --ca_file ~/certs/Amazon-root-CA-1.pem --cert ~/certs/device.pem.crt --key ~/certs/private.pem.key --endpoint {{your-iot-endpoint}} --thing_name {{your-iot-thing-name}} ``` -------------------------------- ### Install AWS CLI on Raspberry Pi Source: https://docs.aws.amazon.com/iot/latest/developerguide/iot-dc-prepare-device-test.md Installs the AWS CLI on your Raspberry Pi. Ensure you have git and pip3 installed. This process can take up to 15 minutes. ```bash export PATH=$PATH:~/.local/bin # configures the path to include the directory with the AWS CLI ``` ```bash git clone https://github.com/aws/aws-cli.git # download the AWS CLI code from GitHub ``` ```bash cd aws-cli && git checkout v2 # go to the directory with the repo and checkout version 2 ``` ```bash pip3 install -r requirements.txt # install the prerequisite software ``` ```bash pip3 install . # install the AWS CLI ``` ```bash aws --version ```