View a markdown version of this page

Utilizzare ListThingscon un AWS SDK o CLI - AWS IoT Core

Le traduzioni sono generate tramite traduzione automatica. In caso di conflitto tra il contenuto di una traduzione e la versione originale in Inglese, quest'ultima prevarrà.

Utilizzare ListThingscon un AWS SDK o CLI

Gli esempi di codice seguenti mostrano come utilizzare ListThings.

Gli esempi di operazioni sono estratti di codice da programmi più grandi e devono essere eseguiti nel contesto. È possibile visualizzare questa operazione nel contesto nel seguente esempio di codice:

.NET
SDK per .NET (v4)
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

/// <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>(); } }
  • Per i dettagli sull'API, consulta la ListThingssezione AWS SDK per .NET API Reference.

CLI
AWS CLI

Esempio 1: come elencare tutti gli oggetti presenti nel registro

L'list-thingsesempio seguente elenca gli oggetti (dispositivi) definiti nel registro AWS IoT per il tuo AWS account.

aws iot list-things

Output:

{ "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 } ] }

Esempio 2: come elencare gli oggetti definiti con un attributo specifico

L’esempio list-things seguente visualizza un elenco degli oggetti contenenti un attributo denominato wattage.

aws iot list-things \ --attribute-name wattage

Output:

{ "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 } ] }

Per ulteriori informazioni, consulta Come gestire gli oggetti con il registro nella Guida per gli sviluppatori di AWS IoT.

Python
SDK per Python (Boto3)
Nota

C'è altro su GitHub. Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

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
  • Per i dettagli sull'API, consulta ListThings AWSSDK for Python (Boto3) API Reference.

Rust
SDK per Rust
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

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(()) }
  • Per i dettagli sulle API, consulta la ListThingsguida di riferimento all'API AWS SDK for Rust.

SAP ABAP
SDK per SAP ABAP
Nota

C'è altro da fare. GitHub Trova l'esempio completo e scopri di più sulla configurazione e l'esecuzione nel Repository di esempi di codice AWS.

CONSTANTS cv_pfl TYPE /aws1/rt_profile_id VALUE 'ZCODE_DEMO'. DATA(lo_session) = /aws1/cl_rt_session_aws=>create( cv_pfl ). DATA(lo_iot) = /aws1/cl_iot_factory=>create( lo_session ). TRY. " Collect all things by following the pagination token. DATA lv_nexttoken TYPE /aws1/iotnexttoken. DATA lv_count TYPE i. DO. oo_result = lo_iot->listthings( iv_nexttoken = lv_nexttoken ). lv_count = lv_count + lines( oo_result->get_things( ) ). lv_nexttoken = oo_result->get_nexttoken( ). IF lv_nexttoken IS INITIAL. EXIT. ENDIF. ENDDO. MESSAGE |Retrieved { lv_count } IoT things.| TYPE 'I'. CATCH /aws1/cx_iotthrottlingex INTO DATA(lo_throttle_ex). MESSAGE 'Request throttled. Please try again later.' TYPE 'I'. RAISE EXCEPTION lo_throttle_ex. CATCH /aws1/cx_rt_service_generic INTO DATA(lo_ex). MESSAGE lo_ex->get_text( ) TYPE 'I'. RAISE EXCEPTION lo_ex. ENDTRY.
  • Per i dettagli sulle API, ListThingsconsulta AWS SDK for SAP ABAP API reference.

Per un elenco completo delle guide per sviluppatori AWS SDK e degli esempi di codice, consulta. Utilizzo AWS IoT con un AWS SDK Questo argomento include anche informazioni su come iniziare e dettagli sulle versioni precedenti dell’SDK.