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

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

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.Println("Created registry:")
fmt.Println("\tID: ", response.Id)
fmt.Println("\tHTTP: ", response.HttpConfig.HttpEnabledState)
fmt.Println("\tMQTT: ", response.MqttConfig.MqttEnabledState)
fmt.Println("\tName: ", response.Name)

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, data) => {
  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(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);

    // Instantiate a client.
    $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.
def create_registry(
        service_account_json, project_id, cloud_region, pubsub_topic,
        registry_id):
    """ Creates a registry and returns the result. Returns an empty result if
    the registry already exists."""
    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

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

fmt.Println("Registries:")
for _, registry := range response.DeviceRegistries {
	fmt.Println("\t", registry.Name)
}

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, data) => {
  if (err) {
    console.log('Could not list registries');
    console.log(err);
  } else {
    console.log('Current registries in project:', 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.
def list_registries(service_account_json, project_id, cloud_region):
    """List all registries in the project."""
    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

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

	return response, err
}

// getRegistryIam gets the IAM policy for a device registry.
func getRegistryIam(projectID string, region string, registryID string) (*cloudiot.Policy, 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
	}

	var req cloudiot.GetIamPolicyRequest

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

	fmt.Println("Policy:")
	for _, binding := range response.Bindings {
		fmt.Fprintf(os.Stdout, "Role: %s\n", binding.Role)
		for _, member := range binding.Members {
			fmt.Fprintf(os.Stdout, "\tMember: %s\n", member)
		}
	}

	return response, err
}

// listRegistries gets the names of device registries given a project / region.
func listRegistries(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
	}

	fmt.Println("Registries:")
	for _, registry := range response.DeviceRegistries {
		fmt.Println("\t", registry.Name)
	}

	return response.DeviceRegistries, err
}

// setRegistryIam sets the IAM policy for a device registry
func setRegistryIam(projectID string, region string, registryID string, member string, role string) (*cloudiot.Policy, 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
	}

	req := cloudiot.SetIamPolicyRequest{
		Policy: &cloudiot.Policy{
			Bindings: []*cloudiot.Binding{
				{
					Members: []string{member},
					Role:    role,
				},
			},
		},
	}
	path := fmt.Sprintf("projects/%s/locations/%s/registries/%s", projectID, region, registryID)
	response, err := client.Projects.Locations.Registries.SetIamPolicy(path, &req).Do()
	if err != nil {
		return nil, err
	}

	fmt.Println("Set policy!")

	return response, err
}

// Device Management

// createEs creates a device in a registry with ES credentials
func createEs(projectID string, region string, registry string, deviceID string, keyPath string) (*cloudiot.Device, 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
	}

	keyBytes, err := ioutil.ReadFile(keyPath)
	if err != nil {
		return nil, err
	}

	device := cloudiot.Device{
		Id: deviceID,
		Credentials: []*cloudiot.DeviceCredential{
			{
				PublicKey: &cloudiot.PublicKeyCredential{
					Format: "ES256_PEM",
					Key:    string(keyBytes),
				},
			},
		},
	}

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

	fmt.Println("Successfully created device.")

	return response, err
}

// createRsa creates a device in a registry with RS credentials
func createRsa(projectID string, region string, registry string, deviceID string, keyPath string) (*cloudiot.Device, 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
	}

	keyBytes, err := ioutil.ReadFile(keyPath)
	if err != nil {
		return nil, err
	}

	device := cloudiot.Device{
		Id: deviceID,
		Credentials: []*cloudiot.DeviceCredential{
			{
				PublicKey: &cloudiot.PublicKeyCredential{
					Format: "RSA_X509_PEM",
					Key:    string(keyBytes),
				},
			},
		},
	}

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

	fmt.Println("Successfully created device.")

	return response, err
}

// createUnauth creates a device in a registry without credentials
func createUnauth(projectID string, region string, registry string, deviceID string) (*cloudiot.Device, 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
	}

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

	fmt.Println("Successfully created device.")

	return response, err
}

// deleteDevice deletes a device from a registry
func deleteDevice(projectID string, region string, registry string, deviceID 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
	}

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

	fmt.Println("Deleted device!")

	return response, err
}

// getDevice retrieves a specific device and prints its details
func getDevice(projectID string, region string, registry string, device string) (*cloudiot.Device, 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
	}

	path := fmt.Sprintf("projects/%s/locations/%s/registries/%s/devices/%s", projectID, region, registry, device)
	response, err := client.Projects.Locations.Registries.Devices.Get(path).Do()
	if err != nil {
		return nil, err
	}

	fmt.Println("\tId: ", response.Id)
	for _, credential := range response.Credentials {
		fmt.Println("\t\tCredential Expire: ", credential.ExpirationTime)
		fmt.Println("\t\tCredential Type: ", credential.PublicKey.Format)
		fmt.Println("\t\t--------")
	}
	fmt.Println("\tLast Config Ack: ", response.LastConfigAckTime)
	fmt.Println("\tLast Config Send: ", response.LastConfigSendTime)
	fmt.Println("\tLast Event Time: ", response.LastEventTime)
	fmt.Println("\tLast Heartbeat Time: ", response.LastHeartbeatTime)
	fmt.Println("\tLast State Time: ", response.LastStateTime)
	fmt.Println("\tNumId: ", response.NumId)

	return response, err
}

// getDeviceConfigs retrieves and lists device configurations
func getDeviceConfigs(projectID string, region string, registry string, device string) ([]*cloudiot.DeviceConfig, 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
	}

	path := fmt.Sprintf("projects/%s/locations/%s/registries/%s/devices/%s", projectID, region, registry, device)
	response, err := client.Projects.Locations.Registries.Devices.ConfigVersions.List(path).Do()
	if err != nil {
		return nil, err
	}

	for _, config := range response.DeviceConfigs {
		fmt.Println(config.Version, " : ", config.BinaryData)
	}

	return response.DeviceConfigs, err
}

// getDeviceStates retrieves and lists device states
func getDeviceStates(projectID string, region string, registry string, device string) ([]*cloudiot.DeviceState, 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
	}

	path := fmt.Sprintf("projects/%s/locations/%s/registries/%s/devices/%s", projectID, region, registry, device)
	response, err := client.Projects.Locations.Registries.Devices.States.List(path).Do()
	if err != nil {
		return nil, err
	}

	fmt.Println("Successfully retrieved device states!")

	for _, state := range response.DeviceStates {
		fmt.Println(state.UpdateTime, " : ", state.BinaryData)
	}

	return response.DeviceStates, err
}

// listDevices gets the identifiers of devices given a registry name
func listDevices(projectID string, region string, registry string) ([]*cloudiot.Device, 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, registry)
	response, err := client.Projects.Locations.Registries.Devices.List(parent).Do()
	if err != nil {
		return nil, err
	}

	fmt.Println("Devices:")
	for _, device := range response.Devices {
		fmt.Println("\t", device.Id)
	}

	return response.Devices, err
}

// patchDeviceEs patches a device to use ES credentials
func patchDeviceEs(projectID string, region string, registry string, deviceID string, keyPath string) (*cloudiot.Device, 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
	}

	keyBytes, err := ioutil.ReadFile(keyPath)
	if err != nil {
		return nil, err
	}

	device := cloudiot.Device{
		Id: deviceID,
		Credentials: []*cloudiot.DeviceCredential{
			{
				PublicKey: &cloudiot.PublicKeyCredential{
					Format: "ES256_PEM",
					Key:    string(keyBytes),
				},
			},
		},
	}

	parent := fmt.Sprintf("projects/%s/locations/%s/registries/%s/devices/%s", projectID, region, registry, deviceID)
	response, err := client.Projects.Locations.Registries.Devices.
		Patch(parent, &device).UpdateMask("credentials").Do()
	if err != nil {
		return nil, err
	}

	fmt.Println("Successfully patched device.")

	return response, err
}

// patchDeviceRsa patches a device to use RSA credentials
func patchDeviceRsa(projectID string, region string, registry string, deviceID string, keyPath string) (*cloudiot.Device, 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
	}

	keyBytes, err := ioutil.ReadFile(keyPath)
	if err != nil {
		return nil, err
	}

	device := cloudiot.Device{
		Id: deviceID,
		Credentials: []*cloudiot.DeviceCredential{
			{
				PublicKey: &cloudiot.PublicKeyCredential{
					Format: "RSA_X509_PEM",
					Key:    string(keyBytes),
				},
			},
		},
	}

	parent := fmt.Sprintf("projects/%s/locations/%s/registries/%s/devices/%s", projectID, region, registry, deviceID)
	response, err := client.Projects.Locations.Registries.Devices.
		Patch(parent, &device).UpdateMask("credentials").Do()
	if err != nil {
		return nil, err
	}

	fmt.Println("Successfully patched device.")

	return response, err
}

// setConfig sends a configuration change to a device.
func setConfig(projectID string, region string, registry string, deviceID string, configData string) (*cloudiot.DeviceConfig, 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
	}

	req := cloudiot.ModifyCloudToDeviceConfigRequest{
		BinaryData: configData,
	}

	path := fmt.Sprintf("projects/%s/locations/%s/registries/%s/devices/%s", projectID, region, registry, deviceID)
	response, err := client.Projects.Locations.Registries.Devices.ModifyCloudToDeviceConfig(path, &req).Do()
	if err != nil {
		return nil, err
	}

	fmt.Fprintf(os.Stdout, "Config set!\nVersion now: %d", response.Version)

	return response, err
}

type command struct {
	name string
	fn   interface{}
	args []string
}

func (c command) usage() string {
	var buf bytes.Buffer
	buf.WriteString(c.name)
	buf.WriteString(" ")
	for _, arg := range c.args {
		buf.WriteString("<")
		buf.WriteString(arg)
		buf.WriteString("> ")
	}
	buf.UnreadByte()
	return buf.String()
}

func main() {
	registryManagementCommands := []command{
		{"createRegistry", createRegistry, []string{"cloud-region", "registry-id", "pubsub-topic"}},
		{"deleteRegistry", deleteRegistry, []string{"cloud-region", "registry-id"}},
		{"getRegistry", getRegistry, []string{"cloud-region", "registry-id"}},
		{"getRegistryIam", getRegistryIam, []string{"cloud-region", "registry-id"}},
		{"setRegistryIam", setRegistryIam, []string{"cloud-region", "registry-id", "member", "role"}},
	}

	deviceManagementCommands := []command{
		{"createEs", createEs, []string{"cloud-region", "registry-id", "device-id", "keyfile-path"}},
		{"createRsa", createRsa, []string{"cloud-region", "registry-id", "device-id", "keyfile-path"}},
		{"createUnauth", createUnauth, []string{"cloud-region", "registry-id", "device-id"}},
		{"deleteDevice", deleteDevice, []string{"cloud-region", "registry-id", "device-id"}},
		{"getDevice", getDevice, []string{"cloud-region", "registry-id", "device-id"}},
		{"getDeviceConfigs", getDeviceConfigs, []string{"cloud-region", "registry-id", "device-id"}},
		{"getDeviceStates", getDeviceStates, []string{"cloud-region", "registry-id", "device-id"}},
		{"listDevices", listDevices, []string{"cloud-region", "registry-id"}},
		{"patchDeviceEs", patchDeviceEs, []string{"cloud-region", "registry-id", "device-id", "keyfile-path"}},
		{"patchDeviceRsa", patchDeviceRsa, []string{"cloud-region", "registry-id", "device-id", "keyfile-path"}},
		{"setConfig", setConfig, []string{"cloud-region", "registry-id", "device-id", "config-data"}},
	}

	var commands []command
	commands = append(commands, registryManagementCommands...)
	commands = append(commands, deviceManagementCommands...)

	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage:\n")
		fmt.Fprintf(os.Stderr, "\tRegistry Management\n")
		fmt.Fprintf(os.Stderr, "\t-----\n")
		for _, cmd := range registryManagementCommands {
			fmt.Fprintf(os.Stderr, "\t%s %s\n", filepath.Base(os.Args[0]), cmd.usage())
		}
		fmt.Fprintln(os.Stderr)
		fmt.Fprintf(os.Stderr, "\tDevice Management\n")
		fmt.Fprintf(os.Stderr, "\t-----\n")
		for _, cmd := range deviceManagementCommands {
			fmt.Fprintf(os.Stderr, "\t%s %s\n", filepath.Base(os.Args[0]), cmd.usage())
		}
	}
	flag.Parse()

	// Retrieve project ID from console
	projectID := os.Getenv("GCLOUD_PROJECT")
	if projectID == "" {
		projectID = os.Getenv("GOOGLE_CLOUD_PROJECT")
	}
	if projectID == "" {
		fmt.Fprintln(os.Stderr, "Set the GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable.")
	}

	if len(flag.Args()) == 0 {
		flag.Usage()
		os.Exit(1)
	}

	commandName := flag.Args()[0]
	commandArgs := flag.Args()[1:]

	for _, cmd := range commands {
		if cmd.name == commandName {
			if len(commandArgs[1:]) != len(cmd.args)-1 {
				fmt.Fprintf(os.Stderr, "Wrong number of arguments. Usage:\n\t%s\n", cmd.usage())
				os.Exit(1)
			}
			var fnArgs []reflect.Value
			fnArgs = append(fnArgs, reflect.ValueOf(projectID))
			for _, arg := range commandArgs {
				fnArgs = append(fnArgs, reflect.ValueOf(arg))
			}
			retValues := reflect.ValueOf(cmd.fn).Call(fnArgs)
			err := retValues[len(retValues)-1].Interface().(error)
			if err != nil {
				fmt.Fprintf(os.Stderr, "%v\n", err)
				os.Exit(1)
			}
			os.Exit(0)
		}
	}

	// Unknown command
	flag.Usage()
	os.Exit(1)
}

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);
  }
});

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.
def get_registry(
        service_account_json, project_id, cloud_region, registry_id):
    """ Retrieves a device registry."""
    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

// 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.Println("Deleted registry")

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, data) => {
  if (err) {
    console.log('Could not delete registry');
    console.log(err);
  } else {
    console.log('Successfully deleted registry');
    console.log(data);
  }
});

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.
def delete_registry(
       service_account_json, project_id, cloud_region, registry_id):
    """Deletes the specified registry."""
    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}"

Was this page helpful? Let us know how we did:

Send feedback about...

Google Cloud Internet of Things Core