Google Cloud IoT Core se retirará el 16 de agosto de 2023. Comunícate con el equipo de cuentas de Google Cloud para obtener más información.

Obtener un registro de dispositivos

Organiza tus páginas con colecciones Guarda y categoriza el contenido según tus preferencias.

Recupera un registro de dispositivo.

Muestra de código

C#

public static object GetRegistry(string projectId, string cloudRegion, string registryId)
{
    var cloudIot = CreateAuthorizedClient();
    // The resource name of the location associated with the key rings.
    var name = $"projects/{projectId}/locations/{cloudRegion}/registries/{registryId}";

    try
    {
        var registry = cloudIot.Projects.Locations.Registries.Get(name).Execute();
        Console.WriteLine($"Registry: {registry.Id}");
        Console.WriteLine("Notification Configurations:");
        registry.EventNotificationConfigs.ToList().ForEach(config =>
        {
            Console.WriteLine($"\tPubSub: {config.PubsubTopicName}");
        });
        Console.WriteLine($"HTTP Enabled: {registry.HttpConfig.HttpEnabledState}");
        Console.WriteLine($"MQTT Enabled: {registry.MqttConfig.MqttEnabledState}");
    }
    catch (Google.GoogleApiException e)
    {
        Console.WriteLine(e.Message);
        if (e.Error != null) return e.Error.Code;
        return -1;
    }
    return 0;
}

Go


// getRegistry gets information about a device registry given a registryID.
func getRegistry(w io.Writer, projectID string, region string, registryID 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/registries/%s", projectID, region, registryID)
	response, err := client.Projects.Locations.Registries.Get(parent).Do()
	if err != nil {
		return nil, err
	}

	fmt.Fprintln(w, "Got registry:")
	fmt.Fprintf(w, "\tID: %s\n", response.Id)
	fmt.Fprintf(w, "\tHTTP: %s\n", response.HttpConfig.HttpEnabledState)
	fmt.Fprintf(w, "\tMQTT: %s\n", response.MqttConfig.MqttEnabledState)
	fmt.Fprintf(w, "\tName: %s\n", response.Name)

	return response, nil
}

Java

/** Retrieves registry metadata from a project. * */
protected static DeviceRegistry getRegistry(
    String projectId, String cloudRegion, String registryName)
    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 registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

  return service.projects().locations().registries().get(registryPath).execute();
}

Node.js

// Client retrieved in callback
// const cloudRegion = 'us-central1';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
const iot = require('@google-cloud/iot');

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

const registryName = iotClient.registryPath(
  projectId,
  cloudRegion,
  registryId
);

async function getDeviceRegistry() {
  // Construct request
  const [response] = await iotClient.getDeviceRegistry({name: registryName});

  console.log('Found registry:', registryId);
  console.log(response);
}

getDeviceRegistry();

PHP

use Google\Cloud\Iot\V1\DeviceManagerClient;

/**
 * Retrieves a device registry.
 *
 * @param string $registryId IOT Device Registry ID
 * @param string $projectId Google Cloud project ID
 * @param string $location (Optional) Google Cloud region
 */
function get_registry(
    $registryId,
    $projectId,
    $location = 'us-central1'
) {
    print('Getting Registry' . PHP_EOL);

    // Instantiate a client.
    $deviceManager = new DeviceManagerClient();
    $registryName = $deviceManager->registryName($projectId, $location, $registryId);

    $registry = $deviceManager->getDeviceRegistry($registryName);

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

Python

# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
client = iot_v1.DeviceManagerClient()
registry_path = client.registry_path(project_id, cloud_region, registry_id)

return client.get_device_registry(request={"name": registry_path})

Ruby

# project_id  = "Your Google Cloud project ID"
# location_id = "The Cloud region that you created the registry in"
# registry_id = "The Google Cloud IoT Core device registry identifier"

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}/registries/#{registry_id}"

# List the devices in the provided region
registry = iot_client.get_project_location_registry(
  resource
)

puts "#{registry.id}:"
puts "\tHTTP Config: #{registry.http_config.http_enabled_state}"
puts "\tMQTT Config: #{registry.mqtt_config.mqtt_enabled_state}"
puts "\tName: #{registry.name}"
if registry.event_notification_configs
  registry.event_notification_configs.each do |config|
    puts "\tTopic: #{config.pubsub_topic_name}"
  end
else
  puts "\tTopic: no associated topics"
end

¿Qué sigue?

Para buscar y filtrar muestras de código en otros productos de Google Cloud, consulta el navegador de muestra de Google Cloud.