Use GetThingShadow com um AWS SDK ou CLI - AWS Exemplos de código do SDK

Há mais exemplos de AWS SDK disponíveis no repositório AWS Doc SDK Examples GitHub .

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Use GetThingShadow com um AWS SDK ou CLI

Os exemplos de código a seguir mostram como usar o GetThingShadow.

.NET
SDK para .NET (v4)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

/// <summary> /// Gets the Thing's shadow information. /// </summary> /// <param name="thingName">The name of the Thing.</param> /// <returns>The shadow data as a string, or null if retrieval failed.</returns> public async Task<string?> GetThingShadowAsync(string thingName) { try { var request = new GetThingShadowRequest { ThingName = thingName }; var response = await _amazonIotData.GetThingShadowAsync(request); using var reader = new StreamReader(response.Payload); var shadowData = await reader.ReadToEndAsync(); _logger.LogInformation($"Retrieved shadow for Thing {thingName}"); return shadowData; } catch (Amazon.IotData.Model.ResourceNotFoundException ex) { _logger.LogError($"Cannot get Thing shadow - resource not found: {ex.Message}"); return null; } catch (Exception ex) { _logger.LogError($"Couldn't get Thing shadow. Here's why: {ex.Message}"); return null; } }
  • Para obter detalhes da API, consulte GetThingShadowa Referência AWS SDK para .NET da API.

C++
SDK para C++
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

//! Get the shadow of an AWS IoT thing. /*! \param thingName: The name for the thing. \param documentResult: String to receive the state information, in JSON format. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::IoT::getThingShadow(const Aws::String &thingName, Aws::String &documentResult, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::IoTDataPlane::IoTDataPlaneClient iotClient(clientConfiguration); Aws::IoTDataPlane::Model::GetThingShadowRequest request; request.SetThingName(thingName); auto outcome = iotClient.GetThingShadow(request); if (outcome.IsSuccess()) { std::stringstream ss; ss << outcome.GetResult().GetPayload().rdbuf(); documentResult = ss.str(); } else { std::cerr << "Error getting thing shadow: " << outcome.GetError().GetMessage() << std::endl; } return outcome.IsSuccess(); }
  • Para obter detalhes da API, consulte GetThingShadowa Referência AWS SDK para C++ da API.

CLI
AWS CLI

Para obter um documento de sombra de item

O exemplo get-thing-shadow a seguir obtém o documento de sombra do item para o item IoT especificado.

aws iot-data get-thing-shadow \ --thing-name MyRPi \ output.txt

O comando não produz nenhuma saída na tela, mas o seguinte mostra o conteúdo de output.txt:

{ "state":{ "reported":{ "moisture":"low" } }, "metadata":{ "reported":{ "moisture":{ "timestamp":1560269319 } } }, "version":1,"timestamp":1560269405 }

Para obter mais informações, consulte Fluxo de dados da sombra do dispositivo no Guia do desenvolvedor da AWS IoT.

  • Para obter detalhes da API, consulte GetThingShadowem Referência de AWS CLI Comandos.

Java
SDK para Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

/** * Retrieves the payload of a Thing's shadow asynchronously. * * @param thingName The name of the IoT Thing. * * This method initiates an asynchronous request to get the payload of a Thing's shadow. * If the request is successful, it prints the shadow data. * If an exception occurs, it prints the error message. */ public void getPayload(String thingName) { GetThingShadowRequest getThingShadowRequest = GetThingShadowRequest.builder() .thingName(thingName) .build(); CompletableFuture<GetThingShadowResponse> future = getAsyncDataPlaneClient().getThingShadow(getThingShadowRequest); future.whenComplete((getThingShadowResponse, ex) -> { if (getThingShadowResponse != null) { // Extracting payload from response. SdkBytes payload = getThingShadowResponse.payload(); String payloadString = payload.asUtf8String(); System.out.println("Received Shadow Data: " + payloadString); } else { Throwable cause = ex != null ? ex.getCause() : null; if (cause instanceof IotException) { System.err.println(((IotException) cause).awsErrorDetails().errorMessage()); } else if (cause != null) { System.err.println("Unexpected error: " + cause.getMessage()); } else { System.err.println("Failed to get Thing Shadow payload."); } } }); future.join(); }
  • Para obter detalhes da API, consulte GetThingShadowa Referência AWS SDK for Java 2.x da API.

Kotlin
SDK para Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

suspend fun getPayload(thingNameVal: String?) { val getThingShadowRequest = GetThingShadowRequest { thingName = thingNameVal } IotDataPlaneClient.fromEnvironment { region = "us-east-1" }.use { iotPlaneClient -> val getThingShadowResponse = iotPlaneClient.getThingShadow(getThingShadowRequest) val payload = getThingShadowResponse.payload val payloadString = payload?.let { java.lang.String(it, Charsets.UTF_8) } println("Received shadow data: $payloadString") } }
  • Para obter detalhes da API, consulte a GetThingShadowreferência da API AWS SDK for Kotlin.

Python
SDK para Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository.

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 get_thing_shadow(self, thing_name): """ Gets the shadow for an AWS IoT thing. :param thing_name: The name of the thing. :return: The shadow state as a dictionary. """ import json try: response = self.iot_data_client.get_thing_shadow(thingName=thing_name) shadow = json.loads(response["payload"].read()) logger.info("Retrieved shadow for thing %s.", thing_name) except ClientError as err: if err.response["Error"]["Code"] == "ResourceNotFoundException": logger.error("Cannot get thing shadow. Resource not found.") return None logger.error( "Couldn't get thing shadow. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return shadow
  • Para obter detalhes da API, consulte a GetThingShadowReferência da API AWS SDK for Python (Boto3).