Listar registros

Recuperar registros de dispositivos de um projeto ou região.

Mais informações

Para ver a documentação detalhada que inclui este exemplo de código, consulte:

Exemplo de código

C#

public static object ListRegistries(string projectId, string cloudRegion)
{
    var cloudIot = CreateAuthorizedClient();
    // The resource name of the location associated with the key rings.
    var parent = $"projects/{projectId}/locations/{cloudRegion}";
    Console.WriteLine("Registries:");
    try
    {
        var result = cloudIot.Projects.Locations.Registries.List(parent).Execute();

        result.DeviceRegistries.ToList().ForEach(registry =>
        {
            Console.WriteLine($"\t{registry.Id}");
        });
    }
    catch (Google.GoogleApiException e)
    {
        Console.WriteLine(e.Message);
        if (e.Error != null) return e.Error.Code;
        return -1;
    }
    return 0;
}

Go


// listRegistries gets the names of device registries given a project / region.
func listRegistries(w io.Writer, projectID string, region string) ([]*cloudiot.DeviceRegistry, error) {
	// Authorize the client using Application Default Credentials.
	// See https://g.co/dv/identity/protocols/application-default-credentials
	ctx := context.Background()
	httpClient, err := google.DefaultClient(ctx, cloudiot.CloudPlatformScope)
	if err != nil {
		return nil, err
	}
	client, err := cloudiot.New(httpClient)
	if err != nil {
		return nil, err
	}

	parent := fmt.Sprintf("projects/%s/locations/%s", projectID, region)
	response, err := client.Projects.Locations.Registries.List(parent).Do()
	if err != nil {
		return nil, err
	}

	if len(response.DeviceRegistries) == 0 {
		fmt.Fprintln(w, "No registries found")
		return response.DeviceRegistries, nil
	}

	fmt.Fprintf(w, "%d registries:\n", len(response.DeviceRegistries))
	for _, registry := range response.DeviceRegistries {
		fmt.Fprintf(w, "\t%s\n", registry.Name)
	}

	return response.DeviceRegistries, nil
}

Java

/** Lists all of the registries associated with the given project. */
protected static void listRegistries(String projectId, String cloudRegion)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

  final String projectPath = "projects/" + projectId + "/locations/" + cloudRegion;

  List<DeviceRegistry> registries =
      service
          .projects()
          .locations()
          .registries()
          .list(projectPath)
          .execute()
          .getDeviceRegistries();

  if (registries != null) {
    System.out.println("Found " + registries.size() + " registries");
    for (DeviceRegistry r : registries) {
      System.out.println("Id: " + r.getId());
      System.out.println("Name: " + r.getName());
      if (r.getMqttConfig() != null) {
        System.out.println("Config: " + r.getMqttConfig().toPrettyString());
      }
      System.out.println();
    }
  } else {
    System.out.println("Project has no registries.");
  }
}

Node.js

// const cloudRegion = 'us-central1';
// const projectId = 'adjective-noun-123';
const iot = require('@google-cloud/iot');

const newClient = new iot.v1.DeviceManagerClient({
  // optional auth parameters.
});

async function listDeviceRegistries() {
  // Construct request
  // Iterate over all elements.
  const formattedParent = newClient.locationPath(projectId, cloudRegion);

  const [response] = await newClient.listDeviceRegistries({
    parent: formattedParent,
  });
  const resources = response;
  console.log('Current registries in project:\n', resources);
}

listDeviceRegistries();

PHP

use Google\Cloud\Iot\V1\DeviceManagerClient;

/**
 * List all registries in the project.
 *
 * @param string $projectId Google Cloud project ID
 * @param string $location (Optional) Google Cloud region
 */
function list_registries(
    $projectId,
    $location = 'us-central1'
) {
    print('Listing Registries' . PHP_EOL);

    // The Google Cloud Client Library automatically checks the environment
    // variable GOOGLE_APPLICATION_CREDENTIALS for the Service Account
    // credentials, and defaults scopes to [
    //    'https://www.googleapis.com/auth/cloud-platform',
    //    'https://www.googleapis.com/auth/cloudiot'
    // ].
    $deviceManager = new DeviceManagerClient();
    $locationName = $deviceManager->locationName($projectId, $location);

    $response = $deviceManager->listDeviceRegistries($locationName);

    foreach ($response->iterateAllElements() as $registry) {
        printf(' - Id: %s, Name: %s' . PHP_EOL,
            $registry->getId(),
            $registry->getName());
    }
}

Python

# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
print("Listing Registries")
client = iot_v1.DeviceManagerClient()
parent = f"projects/{project_id}/locations/{cloud_region}"

registries = list(client.list_device_registries(request={"parent": parent}))
for registry in registries:
    print("id: {}\n\tname: {}".format(registry.id, registry.name))

return registries

Ruby

# project_id  = "Your Google Cloud project ID"
# location_id = "The Cloud region to list registries in"

require "google/apis/cloudiot_v1"

# Initialize the client and authenticate with the specified scope
Cloudiot   = Google::Apis::CloudiotV1
iot_client = Cloudiot::CloudIotService.new
iot_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/cloud-platform"
)

# The resource name of the location associated with the project
resource = "projects/#{project_id}/locations/#{location_id}"

# List the devices in the provided region
registries = iot_client.list_project_location_registries(
  resource
)

puts "Registries:"
if registries.device_registries && registries.device_registries.any?
  registries.device_registries.each { |registry| puts "\t#{registry.id}" }
else
  puts "\tNo device registries found in this region for your project."
end

A seguir

Para pesquisar e filtrar amostras de código de outros produtos do Google Cloud, consulte a Amostra do navegador do Google Cloud.