Registry management samples

The samples on this page show you how to programmatically manage device registries using the Cloud IoT Core API.

Create a registry

The following sample shows you how to create a registry that you can then add devices to:

C#

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

    Console.WriteLine(parent);

    try
    {
        Console.WriteLine($"Creating {registryId}");


        DeviceRegistry body = new DeviceRegistry()
        {
            Id = registryId,
        };
        body.EventNotificationConfigs = new List<EventNotificationConfig>();
        var toAdd = new EventNotificationConfig()
        {
            PubsubTopicName = pubsubTopic.StartsWith("projects/") ?
                pubsubTopic : $"projects/{projectId}/topics/{pubsubTopic}",
        };
        body.EventNotificationConfigs.Add(toAdd);
        var registry = cloudIot.Projects.Locations.Registries.Create(body, parent).Execute();
        Console.WriteLine("Registry: ");
        Console.WriteLine($"{registry.Id}");
        Console.WriteLine($"\tName: {registry.Name}");
        Console.WriteLine($"\tHTTP Enabled: {registry.HttpConfig.HttpEnabledState}");
        Console.WriteLine($"\tMQTT 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

// createRegistry creates a IoT Core device registry associated with a PubSub topic
func createRegistry(w io.Writer, projectID string, region string, registryID string, topicName string) (*cloudiot.DeviceRegistry, error) {
	client, err := getClient()
	if err != nil {
		return nil, err
	}

	registry := cloudiot.DeviceRegistry{
		Id: registryID,
		EventNotificationConfigs: []*cloudiot.EventNotificationConfig{
			{
				PubsubTopicName: topicName,
			},
		},
	}

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

	fmt.Fprintln(w, "Created 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

/** Create a registry for Cloud IoT. */
public static void createRegistry(
    String cloudRegion, String projectId, String registryName, String pubsubTopicPath)
    throws GeneralSecurityException, IOException {
  GoogleCredential credential =
      GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpRequestInitializer init = new RetryHttpInitializerWrapper(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

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

  DeviceRegistry registry = new DeviceRegistry();
  EventNotificationConfig notificationConfig = new EventNotificationConfig();
  notificationConfig.setPubsubTopicName(fullPubsubPath);
  List<EventNotificationConfig> notificationConfigs = new ArrayList<EventNotificationConfig>();
  notificationConfigs.add(notificationConfig);
  registry.setEventNotificationConfigs(notificationConfigs);
  registry.setId(registryName);

  DeviceRegistry reg =
      service.projects().locations().registries().create(projectPath, registry).execute();
  System.out.println("Created registry: " + reg.getName());
}

Node.js

// Client retrieved in callback
// getClient(serviceAccountJson, function(client) {...});
// const cloudRegion = 'us-central1';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
// function errCb = lookupRegistry; // Lookup registry if already exists.
const parentName = `projects/${projectId}/locations/${cloudRegion}`;
const pubsubTopic = `projects/${projectId}/topics/${pubsubTopicId}`;

const request = {
  parent: parentName,
  resource: {
    eventNotificationConfigs: [
      {
        pubsubTopicName: pubsubTopic,
      },
    ],
    id: registryId,
  },
};

client.projects.locations.registries.create(request, (err, res) => {
  if (err) {
    if (err.code === 409) {
      // The registry already exists - look it up instead.
      foundCb(client, registryId, projectId, cloudRegion);
    } else {
      console.log('Could not create registry');
      console.log(err);
    }
  } else {
    console.log('Successfully created registry');
    console.log(res.data);
  }
});

PHP

use Google\Cloud\Iot\V1\DeviceManagerClient;
use Google\Cloud\Iot\V1\DeviceRegistry;
use Google\Cloud\Iot\V1\EventNotificationConfig;

/**
 * Creates a registry if it doesn't exist and prints the result.
 *
 * @param string $registryId IOT Device Registry ID
 * @param string $pubsubTopic PubSub topic name for the new registry's event change notification.
 * @param string $projectId Google Cloud project ID
 * @param string $location (Optional) Google Cloud region
 */
function create_registry(
    $registryId,
    $pubsubTopic,
    $projectId,
    $location = 'us-central1'
) {
    print('Creating Registry' . 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);

    $pubsubTopicPath = sprintf('projects/%s/topics/%s', $projectId, $pubsubTopic);
    $eventNotificationConfig = (new EventNotificationConfig)
        ->setPubsubTopicName($pubsubTopicPath);

    $registry = (new DeviceRegistry)
        ->setId($registryId)
        ->setEventNotificationConfigs([$eventNotificationConfig]);

    $registry = $deviceManager->createDeviceRegistry($locationName, $registry);

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

Python

This sample uses the Google API Client Library for Python.
client = get_client(service_account_json)
registry_parent = 'projects/{}/locations/{}'.format(
        project_id,
        cloud_region)
body = {
    'eventNotificationConfigs': [{
        'pubsubTopicName': pubsub_topic
    }],
    'id': registry_id
}
request = client.projects().locations().registries().create(
    parent=registry_parent, body=body)

try:
    response = request.execute()
    print('Created registry')
    return response
except HttpError:
    print('Error, registry not created')
    return ""

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"
# pubsub_topic = "The Google Cloud PubSub topic to use for this registry"

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 project / location where the registry is created.
parent = "projects/#{project_id}/locations/#{location_id}"

registry = Cloudiot::DeviceRegistry.new
registry.id = registry_id
registry.event_notification_configs = [Cloudiot::EventNotificationConfig::new]
registry.event_notification_configs[0].pubsub_topic_name = pubsub_topic

registry = iot_client.create_project_location_registry(
    parent, registry
)

puts "Created registry: #{registry.name}"

List registries

The following sample shows you how to list registries:

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. */
public static void listRegistries(String projectId, String cloudRegion)
    throws GeneralSecurityException, IOException {
  GoogleCredential credential =
      GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpRequestInitializer init = new RetryHttpInitializerWrapper(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

// Client retrieved in callback
// getClient(serviceAccountJson, function(client) {...});
// const cloudRegion = 'us-central1';
// const projectId = 'adjective-noun-123';
const parentName = `projects/${projectId}/locations/${cloudRegion}`;

const request = {
  parent: parentName,
};

client.projects.locations.registries.list(request, (err, res) => {
  if (err) {
    console.log('Could not list registries');
    console.log(err);
  } else {
    let data = res.data;
    console.log('Current registries in project:\n', data['deviceRegistries']);
  }
});

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

This sample uses the Google API Client Library for Python.
print('Listing Registries')
registry_path = 'projects/{}/locations/{}'.format(
        project_id, cloud_region)
client = get_client(service_account_json)
registries = client.projects().locations().registries().list(
    parent=registry_path).execute().get('deviceRegistries', [])

for registry in registries:
        print('id: {}\n\tname: {}'.format(
                registry.get('id'),
                registry.get('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

Get a registry

The following sample shows you how to retrieve a registry:

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. * */
public static DeviceRegistry getRegistry(
    String projectId, String cloudRegion, String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredential credential =
      GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpRequestInitializer init = new RetryHttpInitializerWrapper(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
// getClient(serviceAccountJson, function(client) {...});
// const cloudRegion = 'us-central1';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
const parentName = `projects/${projectId}/locations/${cloudRegion}`;
const registryName = `${parentName}/registries/${registryId}`;
const request = {
  name: `${registryName}`,
};

client.projects.locations.registries.get(request, (err, data) => {
  if (err) {
    console.log('Could not find registry:', registryId);
    console.log(err);
  } else {
    console.log('Found registry:', registryId);
    console.log(data.data);
  }
});

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

This sample uses Google API Client Library for Python.
client = get_client(service_account_json)
registry_parent = 'projects/{}/locations/{}'.format(
        project_id,
        cloud_region)
topic_name = '{}/registries/{}'.format(registry_parent, registry_id)
request = client.projects().locations().registries().get(name=topic_name)
return request.execute()

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

Delete a registry

The following sample shows you how to delete a registry:

C#

public static object DeleteRegistry(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.Delete(name).Execute();
    }
    catch (Google.GoogleApiException e)
    {
        Console.WriteLine(e.Message);
        if (e.Error != null) return e.Error.Code;
        return -1;
    }
    return 0;
}

Go

// deleteRegistry deletes a device registry if it is empty.
func deleteRegistry(w io.Writer, projectID string, region string, registryID string) (*cloudiot.Empty, 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
	}

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

	fmt.Fprintf(w, "Deleted registry: %s\n", registryID)

	return response, nil
}

Java

/** Delete this registry from Cloud IoT. */
public static void deleteRegistry(String cloudRegion, String projectId, String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredential credential =
      GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpRequestInitializer init = new RetryHttpInitializerWrapper(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);

  System.out.println("Deleting: " + registryPath);
  service.projects().locations().registries().delete(registryPath).execute();
}

Node.js

// Client retrieved in callback
// getClient(serviceAccountJson, function(client) {...});
// const cloudRegion = 'us-central1';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
const parentName = `projects/${projectId}/locations/${cloudRegion}`;
const registryName = `${parentName}/registries/${registryId}`;
const request = {
  name: registryName,
};

client.projects.locations.registries.delete(request, (err, res) => {
  if (err) {
    console.log('Could not delete registry');
    console.log(err);
  } else {
    console.log('Successfully deleted registry');
    console.log(res);
  }
});

PHP

use Google\Cloud\Iot\V1\DeviceManagerClient;

/**
 * Deletes the specified registry.
 *
 * @param string $registryId IOT Device Registry ID
 * @param string $projectId Google Cloud project ID
 * @param string $location (Optional) Google Cloud region
 */
function delete_registry(
    $registryId,
    $projectId,
    $location = 'us-central1'
) {
    // Instantiate a client.
    $deviceManager = new DeviceManagerClient();

    // Format the full registry path
    $registryName = $deviceManager->registryName($projectId, $location, $registryId);

    $deviceManager->deleteDeviceRegistry($registryName);

    printf('Deleted Registry %s' . PHP_EOL, $registryId);
}

Python

This sample uses the Google API Client Library for Python.
print('Delete registry')
client = get_client(service_account_json)
registry_name = 'projects/{}/locations/{}/registries/{}'.format(
        project_id, cloud_region, registry_id)

registries = client.projects().locations().registries()
return registries.delete(name=registry_name).execute()

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

result = iot_client.delete_project_location_registry(resource)
puts "Deleted registry: #{registry_id}"

このページは役立ちましたか?評価をお願いいたします。

フィードバックを送信...

Cloud IoT Core Documentation