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 ListThings com um AWS SDK ou CLI
Os exemplos de código a seguir mostram como usar o ListThings.
- .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> /// Lists IoT Things with pagination support. /// </summary> /// <returns>List of Things, or empty list if listing failed.</returns> public async Task<List<ThingAttribute>> ListThingsAsync() { try { // Use pages of 10. var request = new ListThingsRequest() { MaxResults = 10 }; var response = await _amazonIoT.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 _amazonIoT.ListThingsAsync(request); } else hasMoreResults = false; } _logger.LogInformation($"Retrieved {things.Count} Things"); return things; } catch (Amazon.IoT.Model.ThrottlingException ex) { _logger.LogWarning($"Request throttled, please try again later: {ex.Message}"); return new List<ThingAttribute>(); } catch (Exception ex) { _logger.LogError($"Couldn't list Things. Here's why: {ex.Message}"); return new List<ThingAttribute>(); } }-
Para obter detalhes da API, consulte ListThingsa Referência AWS SDK para .NET da API.
-
- CLI
-
- AWS CLI
-
Exemplo 1: listar todas os itens do registro
O
list-thingsexemplo a seguir lista as coisas (dispositivos) que estão definidas no registro de AWS IoT da sua AWS conta.aws iot list-thingsSaída:
{ "things": [ { "thingName": "ThirdBulb", "thingTypeName": "LightBulb", "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/ThirdBulb", "attributes": { "model": "123", "wattage": "75" }, "version": 2 }, { "thingName": "MyOtherLightBulb", "thingTypeName": "LightBulb", "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/MyOtherLightBulb", "attributes": { "model": "123", "wattage": "75" }, "version": 3 }, { "thingName": "MyLightBulb", "thingTypeName": "LightBulb", "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/MyLightBulb", "attributes": { "model": "123", "wattage": "75" }, "version": 1 }, { "thingName": "SampleIoTThing", "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/SampleIoTThing", "attributes": {}, "version": 1 } ] }Exemplo 2: como listar os itens definidos que possuem um atributo específico
O exemplo de
list-thingsa seguir exibe uma lista dos itens que têm um atributo chamadowattage.aws iot list-things \ --attribute-namewattageSaída:
{ "things": [ { "thingName": "MyLightBulb", "thingTypeName": "LightBulb", "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/MyLightBulb", "attributes": { "model": "123", "wattage": "75" }, "version": 1 }, { "thingName": "MyOtherLightBulb", "thingTypeName": "LightBulb", "thingArn": "arn:aws:iot:us-west-2:123456789012:thing/MyOtherLightBulb", "attributes": { "model": "123", "wattage": "75" }, "version": 3 } ] }Para acessar mais informações, consulte Como gerenciar objetos com o registro no Guia do desenvolvedor do AWS IoT.
-
Para obter detalhes da API, consulte ListThings
em Referência de AWS CLI Comandos.
-
- 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 list_things(self): """ Lists AWS IoT things. :return: The list of things. """ try: things = [] paginator = self.iot_client.get_paginator("list_things") for page in paginator.paginate(): things.extend(page["things"]) logger.info("Retrieved %s things.", len(things)) return things except ClientError as err: if err.response["Error"]["Code"] == "ThrottlingException": logger.error("Request throttled. Please try again later.") else: logger.error( "Couldn't list things. Here's why: %s: %s", err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise-
Para obter detalhes da API, consulte a ListThingsReferência da API AWS SDK for Python (Boto3).
-
- Rust
-
- SDK para Rust
-
nota
Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no AWS Code Examples Repository
. async fn show_things(client: &Client) -> Result<(), Error> { let resp = client.list_things().send().await?; println!("Things:"); for thing in resp.things.unwrap() { println!( " Name: {}", thing.thing_name.as_deref().unwrap_or_default() ); println!( " Type: {}", thing.thing_type_name.as_deref().unwrap_or_default() ); println!( " ARN: {}", thing.thing_arn.as_deref().unwrap_or_default() ); println!(); } println!(); Ok(()) }-
Para obter detalhes da API, consulte a ListThings
referência da API AWS SDK for Rust.
-
Para obter uma lista completa dos guias do desenvolvedor do AWS SDK e exemplos de código, consulteUsando AWS IoT com um AWS SDK. Este tópico também inclui informações sobre como começar e detalhes sobre versões anteriores do SDK.