Codebeispiele für die AWS IoT Verwendung AWS SDKs - AWS IoT Core

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

Codebeispiele für die AWS IoT Verwendung AWS SDKs

Die folgenden Codebeispiele zeigen, wie die Verwendung AWS IoT mit einem AWS Software Development Kit (SDK) funktioniert.

Bei Grundlagen handelt es sich um Codebeispiele, die Ihnen zeigen, wie Sie die wesentlichen Vorgänge innerhalb eines Services ausführen.

Aktionen sind Codeauszüge aus größeren Programmen und müssen im Kontext ausgeführt werden. Während Aktionen Ihnen zeigen, wie Sie einzelne Service-Funktionen aufrufen, können Sie Aktionen im Kontext der zugehörigen Szenarien anzeigen.

Eine vollständige Liste der AWS SDK-Entwicklerhandbücher und Codebeispiele finden Sie unterVerwendung AWS IoT mit einem SDK AWS. Dieses Thema enthält auch Informationen zu den ersten Schritten und Details zu früheren SDK-Versionen.

Erste Schritte

Die folgenden Codebeispiele zeigen, wie Sie mit der Verwendung von AWS IoT beginnen.

.NET
SDK für .NET(v4)
Anmerkung

Es gibt noch mehr dazu GitHub. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das AWS-Code-Beispiel- einrichten und ausführen.

/// <summary> /// Hello AWS IoT example. /// </summary> public class HelloIoT { /// <summary> /// Main method to run the Hello IoT example. /// </summary> /// <param name="args">Command line arguments.</param> /// <returns>A Task object.</returns> public static async Task Main(string[] args) { var iotClient = new AmazonIoTClient(); try { Console.WriteLine("Hello AWS IoT! Let's list your IoT Things:"); Console.WriteLine(new string('-', 80)); // Use pages of 10. var request = new ListThingsRequest() { MaxResults = 10 }; var response = await iotClient.ListThingsAsync(request); // Since there is not a built-in paginator, use the NextMarker to paginate. bool hasMoreResults = true; var things = new List<ThingAttribute>(); while (hasMoreResults) { things.AddRange(response.Things); // If NextMarker is not null, there are more results. Get the next page of results. if (!String.IsNullOrEmpty(response.NextMarker)) { request.Marker = response.NextMarker; response = await iotClient.ListThingsAsync(request); } else hasMoreResults = false; } if (things is { Count: > 0 }) { Console.WriteLine($"Found {things.Count} IoT Things:"); foreach (var thing in things) { Console.WriteLine($"- Thing Name: {thing.ThingName}"); Console.WriteLine($" Thing ARN: {thing.ThingArn}"); Console.WriteLine($" Thing Type: {thing.ThingTypeName ?? "No type specified"}"); Console.WriteLine($" Version: {thing.Version}"); if (thing.Attributes?.Count > 0) { Console.WriteLine(" Attributes:"); foreach (var attr in thing.Attributes) { Console.WriteLine($" {attr.Key}: {attr.Value}"); } } Console.WriteLine(); } } else { Console.WriteLine("No IoT Things found in your account."); Console.WriteLine("You can create IoT Things using the IoT Basics scenario example."); } Console.WriteLine("Hello IoT completed successfully."); } catch (Amazon.IoT.Model.ThrottlingException ex) { Console.WriteLine($"Request throttled, please try again later: {ex.Message}"); } catch (Exception ex) { Console.WriteLine($"Couldn't list Things. Here's why: {ex.Message}"); } } }
  • Weitere API-Informationen finden Sie unter listThings in der AWS SDK für .NET-API-Referenz.

C++
SDK für C++

Code für die CMake Datei CMake Lists.txt.

# Set the minimum required version of CMake for this project. cmake_minimum_required(VERSION 3.13) # Set the AWS service components used by this project. set(SERVICE_COMPONENTS iot) # Set this project's name. project("hello_iot") # Set the C++ standard to use to build this target. # At least C++ 11 is required for the AWS SDK for C++. set(CMAKE_CXX_STANDARD 11) # Use the MSVC variable to determine if this is a Windows build. set(WINDOWS_BUILD ${MSVC}) if (WINDOWS_BUILD) # Set the location where CMake can find the installed libraries for the AWS SDK. string(REPLACE ";" "/aws-cpp-sdk-all;" SYSTEM_MODULE_PATH "${CMAKE_SYSTEM_PREFIX_PATH}/aws-cpp-sdk-all") list(APPEND CMAKE_PREFIX_PATH ${SYSTEM_MODULE_PATH}) endif () # Find the AWS SDK for C++ package. find_package(AWSSDK REQUIRED COMPONENTS ${SERVICE_COMPONENTS}) if (WINDOWS_BUILD AND AWSSDK_INSTALL_AS_SHARED_LIBS) # Copy relevant AWS SDK for C++ libraries into the current binary directory for running and debugging. # set(BIN_SUB_DIR "/Debug") # If you are building from the command line, you may need to uncomment this # and set the proper subdirectory to the executables' location. AWSSDK_CPY_DYN_LIBS(SERVICE_COMPONENTS "" ${CMAKE_CURRENT_BINARY_DIR}${BIN_SUB_DIR}) endif () add_executable(${PROJECT_NAME} hello_iot.cpp) target_link_libraries(${PROJECT_NAME} ${AWSSDK_LINK_LIBRARIES})

Code für die Quelldatei „hello_iot.cpp“.

#include <aws/core/Aws.h> #include <aws/iot/IoTClient.h> #include <aws/iot/model/ListThingsRequest.h> #include <iostream> /* * 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<Aws::IoT::Model::ThingAttribute> allThings; do { if (!nextToken.empty()) { listThingsRequest.SetNextToken(nextToken); } Aws::IoT::Model::ListThingsOutcome listThingsOutcome = iotClient.ListThings( listThingsRequest); if (listThingsOutcome.IsSuccess()) { const Aws::Vector<Aws::IoT::Model::ThingAttribute> &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; }
  • Weitere API-Informationen finden Sie unter listThings in der AWS SDK für C++-API-Referenz.

Anmerkung

Es gibt noch mehr dazu GitHub. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das AWS-Code-Beispiel- einrichten und ausführen.

Java
SDK für Java 2.x
Anmerkung

Es gibt noch mehr GitHub. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das AWS-Code-Beispiel- einrichten und ausführen.

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) { iotClient.listThingsPaginator(ListThingsRequest.builder() .maxResults(10) .build()) .stream() .flatMap(response -> response.things().stream()) .forEach(attribute -> { System.out.println("Thing name: " + attribute.thingName()); System.out.println("Thing ARN: " + attribute.thingArn()); }); } }
  • Weitere API-Informationen finden Sie unter listThings in der AWS SDK for Java 2.x-API-Referenz.

Kotlin
SDK für Kotlin
Anmerkung

Es gibt noch mehr GitHub. Hier finden Sie das vollständige Beispiel und erfahren, wie Sie das AWS-Code-Beispiel- einrichten und ausführen.

import aws.sdk.kotlin.services.iot.IotClient import aws.sdk.kotlin.services.iot.model.ListThingsRequest suspend fun main() { println("A listing of your AWS IoT Things:") listAllThings() } suspend fun listAllThings() { val thingsRequest = ListThingsRequest { maxResults = 10 } IotClient.fromEnvironment { region = "us-east-1" }.use { iotClient -> val response = iotClient.listThings(thingsRequest) val thingList = response.things if (thingList != null) { for (attribute in thingList) { println("Thing name ${attribute.thingName}") println("Thing ARN: ${attribute.thingArn}") } } } }
  • Weitere API-Informationen finden Sie unter listThings in der API-Referenz zum AWS SDK für Kotlin.