Creating Registries and Devices

This page explains how to create, edit, and delete device registries and devices within them.

A device is a "Thing" in "Internet of Things": a processing unit that is capable of connecting to the internet and exchanging data with the cloud. A device registry is a container of devices with shared properties. For more details about devices and registries, see Devices.

If you haven't already, complete the Getting Started steps before proceeding.

Creating a device registry

To use Cloud IoT Core, you must create at least one device registry. You can create a registry using Cloud Platform Console, the API, or gcloud.

Console

  1. Go to the Device registries page in Cloud Platform Console.

    Go to the Device registries page

  2. At the top of the page, click Create device registry.

  3. Enter a Registry ID and select a cloud region.

  4. Select the Protocols that devices in this registry will use to connect to Cloud IoT Core: MQTT, HTTP, or both.

  5. Select a Telemetry topic or create a new one. All device telemetry (the event data sent from devices to the cloud) will be published to the Cloud Pub/Sub topic you specify in this field.

  6. (Optional) Select a Device state topic or create a new one. This topic can be the same as or different from the telemetry topic.

    State data is published to Cloud Pub/Sub on a best-effort basis: if publication to the topic fails, it will not be retried. If no topic is defined, device state updates are still persisted internally by Cloud IoT Core, but only the last 10 states are retained.

    For more information, see Getting device state.

  7. Click Create to continue. A message prompts you to confirm that you want to grant the necessary permission to allow telemetry events to be sent to the Cloud Pub/Sub topic you selected. For more information, see Devices.

gcloud

To create a registry, run the gcloud beta iot registries create command:

gcloud beta iot registries create REGISTRY_ID \
    --project=PROJECT_ID \
    --region=REGION \
    [--event-pubsub-topic=EVENT_PUBSUB_TOPIC]
    [--state-pubsub-topic=STATE_PUBSUB_TOPIC]

In the current release of Cloud IoT Core, the available regions are us-central1, europe-west1, and asia-east1.

You can use the --enable-http-config and --enable-mtt-config flags to enable and disable protocols for the registry. By default, both protocols are enabled.

API

Use the DeviceRegistry create method to create a registry:

Java

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

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

Creating device key pairs

Before creating a device, first create a public/private key pair for it. When connecting to Cloud IoT Core, each device creates a JSON Web Token (JWT) signed with its private key, which Cloud IoT Core authenticates using the device's public key.

Creating or editing a device

You can create a device or edit an existing one using Cloud Platform Console, the API, or gcloud. Make sure you've created a registry and a key pair before completing the steps in this section.

Console

  1. Go to the Device registries page in Cloud Platform Console.

    Go to the Device registries page

  2. Click the ID of the registry for the device.

  3. On the Registry details page, click Add device to create a new device.

    To edit an existing device, click its ID on the Registry details page, and then click Edit device at the top of the page.

  4. Enter a Device ID that briefly describes the device or otherwise helps you identify it. (This field can't be edited later.)

  5. For Device communication, select Allow or Block. This option allows you to block communication when needed, such as when a device is not functioning properly. In most cases, you'll want to allow communication when first creating the device.

  6. If you're creating a new device, select the Public key format that matches the key pair for this device. Paste the certificate or key in the Public key value field. You can also set an expiration date for the key.

    To add a key to an existing device, click Add public key on the Device details page.

  7. Use the Key and Value fields to add optional device metadata, such as a serial number. Keys and values must meet the following requirements:

    • Keys: Only letters, numbers, hyphens, and underscores; no longer than 128 characters
    • Value size: Maximum 32 KB
    • Combined total size of all key-value pairs: Maximum 256 KB
  8. Click Add to create the device or Update to save changes to an existing device.

gcloud

To create a device, run the gcloud beta iot devices create command.

To create a device with RS256 credentials, run the following command:

gcloud beta iot devices create DEVICE_ID \
  --project=PROJECT_ID \
  --region=REGION \
  --registry=REGISTRY_ID \
  --public-key path=rsa_cert.pem,type=rs256

To create a device with ES256 credentials, run the following command:

gcloud beta iot devices create DEVICE_ID \
  --project=PROJECT_ID \
  --region=REGION \
  --registry=REGISTRY_ID \
  --public-key path=ec_public.pem,type=es256

To edit a device, run the gcloud beta iot devices update command:

gcloud beta iot devices update DEVICE_ID \
  --project=PROJECT_ID \
  --region=REGION \
  --registry=REGISTRY_ID \

API

Use the following methods to create or edit devices:

When creating a device, public keys are specified in the credentials field of the Device resource in the Cloud IoT Core API. You can also add or modify this field when you update the device resource.

For RSA, theDevice.credentials[i].public_key.key field must be set to the contents of rsa_cert.pem (including the header and the footer). The Device.credentials[i].public_key.format field must be set to RSA_X509_PEM.

For ES256, the Device.credentials[i].public_key.key field must be set to the contents of ec_public.pem (including the header and the footer). The Device.credentials[i].public_key.format field must be set to ES256_PEM.

The following sample shows how to create a device with RSA credentials:

Java

public static void createDeviceWithRs256(String deviceId, String certificateFilePath,
                                         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 = "projects/" + projectId + "/locations/" + cloudRegion
      + "/registries/" + registryName;

  PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
  String key = Files.toString(new File(certificateFilePath), Charsets.UTF_8);
  publicKeyCredential.setKey(key);
  publicKeyCredential.setFormat("RSA_X509_PEM");

  DeviceCredential devCredential = new DeviceCredential();
  devCredential.setPublicKey(publicKeyCredential);

  System.out.println("Creating device with id: " + deviceId);
  Device device = new Device();
  device.setId(deviceId);
  device.setCredentials(Arrays.asList(devCredential));
  Device createdDevice =
      service
          .projects()
          .locations()
          .registries()
          .devices()
          .create(registryPath, device)
          .execute();

  System.out.println("Created device: " + createdDevice.toPrettyString());
}

Node.js

// Client retrieved in callback
// getClient(serviceAccountJson, function(client) {...});
// const cloudRegion = 'us-central1';
// const deviceId = 'my-rsa-device';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
const parentName = `projects/${projectId}/locations/${cloudRegion}`;
const registryName = `${parentName}/registries/${registryId}`;
const body = {
  id: deviceId,
  credentials: [
    {
      publicKey: {
        format: 'RSA_X509_PEM',
        key: fs.readFileSync(rsaCertificateFile).toString()
      }
    }
  ]
};

const request = {
  parent: registryName,
  resource: body
};

console.log(JSON.stringify(request));

client.projects.locations.registries.devices.create(request, (err, data) => {
  if (err) {
    console.log('Could not create device');
    console.log(err);
  } else {
    console.log('Created device');
    console.log(data);
  }
});

Python

This sample uses the Google API Client Library for Python.
def create_rs256_device(
        service_account_json, project_id, cloud_region, registry_id, device_id,
        certificate_file):
    """Create a new device with the given id, using RS256 for
    authentication."""
    registry_name = 'projects/{}/locations/{}/registries/{}'.format(
            project_id, cloud_region, registry_id)

    client = get_client(service_account_json)
    with io.open(certificate_file) as f:
        certificate = f.read()

    # Note: You can have multiple credentials associated with a device.
    device_template = {
        'id': device_id,
        'credentials': [{
            'publicKey': {
                'format': 'RSA_X509_PEM',
                'key': certificate
            }
        }]
    }

    devices = client.projects().locations().registries().devices()
    return devices.create(parent=registry_name, body=device_template).execute()

The following sample shows how to create a device with Elliptic Curve (EC) credentials:

Java

public static void createDeviceWithEs256(String deviceId, String publicKeyFilePath,
    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 = "projects/" + projectId + "/locations/" + cloudRegion
      + "/registries/" + registryName;

  PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
  final String key = Files.toString(new File(publicKeyFilePath), Charsets.UTF_8);
  publicKeyCredential.setKey(key);
  publicKeyCredential.setFormat("ES256_PEM");

  DeviceCredential devCredential  = new DeviceCredential();
  devCredential.setPublicKey(publicKeyCredential);

  System.out.println("Creating device with id: " + deviceId);
  Device device = new Device();
  device.setId(deviceId);
  device.setCredentials(Arrays.asList(devCredential));

  Device createdDevice =
      service
          .projects()
          .locations()
          .registries()
          .devices()
          .create(registryPath, device)
          .execute();

  System.out.println("Created device: " + createdDevice.toPrettyString());
}

Node.js

// Client retrieved in callback
// getClient(serviceAccountJson, function(client) {...});
// const cloudRegion = 'us-central1';
// const deviceId = 'my-es-device';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
const parentName = `projects/${projectId}/locations/${cloudRegion}`;
const registryName = `${parentName}/registries/${registryId}`;
const body = {
  id: deviceId,
  credentials: [
    {
      publicKey: {
        format: 'ES256_PEM',
        key: fs.readFileSync(esCertificateFile).toString()
      }
    }
  ]
};

const request = {
  parent: registryName,
  resource: body
};

client.projects.locations.registries.devices.create(request, (err, data) => {
  if (err) {
    console.log('Could not create device');
    console.log(err);
  } else {
    console.log('Created device');
    console.log(data);
  }
});

Python

This sample uses the Google API Client Library for Python.
def create_es256_device(
        service_account_json, project_id, cloud_region, registry_id,
        device_id, public_key_file):
    """Create a new device with the given id, using ES256 for
    authentication."""
    registry_name = 'projects/{}/locations/{}/registries/{}'.format(
            project_id, cloud_region, registry_id)

    client = get_client(service_account_json)
    with io.open(public_key_file) as f:
        public_key = f.read()

    # Note: You can have multiple credentials associated with a device.
    device_template = {
        'id': device_id,
        'credentials': [{
            'publicKey': {
                'format': 'ES256_PEM',
                'key': public_key
            }
        }]
    }

    devices = client.projects().locations().registries().devices()
    return devices.create(parent=registry_name, body=device_template).execute()

The following sample shows how to patch a device with RSA credentials:

Java

public static void patchRsa256ForAuth(String deviceId, String publicKeyFilePath, 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 = "projects/" + projectId + "/locations/" + cloudRegion
      + "/registries/" + registryName;

  final String devicePath = registryPath + "/devices/" + deviceId;
  PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
  String key = Files.toString(new File(publicKeyFilePath), Charsets.UTF_8);
  publicKeyCredential.setKey(key);
  publicKeyCredential.setFormat("RSA_X509_PEM");

  DeviceCredential devCredential = new DeviceCredential();
  devCredential.setPublicKey(publicKeyCredential);

  Device device = new Device();
  device.setCredentials(Arrays.asList(devCredential));

  Device patchedDevice =
      service
          .projects()
          .locations()
          .registries()
          .devices()
          .patch(devicePath, device)
          .setUpdateMask("credentials")
          .execute();

  System.out.println("Patched device is " + patchedDevice.toPrettyString());
}

Node.js

// Client retrieved in callback
// getClient(serviceAccountJson, function(client) {...});
// const cloudRegion = 'us-central1';
// const deviceId = 'my-rsa-device';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
const parentName =
    `projects/${projectId}/locations/${cloudRegion}`;
const registryName = `${parentName}/registries/${registryId}`;
const request = {
  name: `${registryName}/devices/${deviceId}`,
  updateMask: 'credentials',
  resource: {
    credentials: [
      {
        publicKey: {
          format: 'RSA_X509_PEM',
          key: fs.readFileSync(rsaPublicKeyFile).toString()
        }
      }
    ]
  }
};

client.projects.locations.registries.devices.patch(request, (err, data) => {
  if (err) {
    console.log('Error patching device:', deviceId);
    console.log(err);
  } else {
    console.log('Patched device:', deviceId);
    console.log(data);
  }
});

Python

This sample uses the Google API Client Library for Python.
def patch_rsa256_auth(
        service_account_json, project_id, cloud_region, registry_id, device_id,
        public_key_file):
    """Patch the device to add an RSA256 public key to the device."""
    print('Patch device with RSA256 certificate')
    client = get_client(service_account_json)
    registry_path = 'projects/{}/locations/{}/registries/{}'.format(
            project_id, cloud_region, registry_id)

    with io.open(public_key_file) as f:
        public_key = f.read()

    patch = {
        'credentials': [{
            'publicKey': {
                'format': 'RSA_X509_PEM',
                'key': public_key
            }
        }]
    }

    device_name = '{}/devices/{}'.format(registry_path, device_id)

    return client.projects().locations().registries().devices().patch(
            name=device_name, updateMask='credentials', body=patch).execute()

See the Device Management Samples for more code samples in Python, Java, and Node.js.

Getting device details

You can get details about one or more devices using Cloud Platform Console, the API, or gcloud.

Console

  1. Go to the Device registries page in Cloud Platform Console.

    Go to the Device registries page

  2. Click the ID of the registry for the device.

  3. Click the ID of the device to go to the Device details page. This page summarizes recent device activity, including the last time a message was published and the time of the most recent error.

  4. Click the Configuration history tab to see recent configuration versions and update times for the device.

The fields for the last heartbeat time and the last time a configuration was ACKed are for the MQTT bridge only. The HTTP bridge does not support heartbeat or explicit ACKs.

gcloud

To list the devices in a registry, run the gcloud iot devices list command:

gcloud beta iot devices list \
  --project=PROJECT_ID \
  --registry=REGISTRY_ID \
  --region=REGION

To get details about a device, run the gcloud iot devices describe command:

gcloud beta iot devices describe DEVICE_ID \
  --project=PROJECT_ID \
  --registry=REGISTRY_ID \
  --region=REGION

API

Use the following methods to get details about devices:

The following sample shows how to list the devices in a registry:

Java

public static void listDevices(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();

  String registryPath = "projects/" + projectId + "/locations/" + cloudRegion + "/registries/"
      + registryName;

  List<Device> devices =
      service
          .projects()
          .locations()
          .registries()
          .devices()
          .list(registryPath)
          .execute()
          .getDevices();

  if (devices != null) {
    System.out.println("Found " + devices.size() + " devices");
    for (Device d : devices) {
      System.out.println("Id: " + d.getId());
      if (d.getConfig() != null) {
        // Note that this will show the device config in Base64 encoded format.
        System.out.println("Config: " + d.getConfig().toPrettyString());
      }
      System.out.println();
    }
  } else {
    System.out.println("Registry has no devices.");
  }
}

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 = {
  parent: registryName
};

client.projects.locations.registries.devices.list(request, (err, data) => {
  if (err) {
    console.log('Could not list devices');
    console.log(err);
  } else {
    console.log('Current devices in registry:', data['devices']);
  }
});

Python

This sample uses the Google API Client Library for Python.
def list_devices(
        service_account_json, project_id, cloud_region, registry_id):
    """List all devices in the registry."""
    print('Listing devices')
    registry_path = 'projects/{}/locations/{}/registries/{}'.format(
            project_id, cloud_region, registry_id)
    client = get_client(service_account_json)
    devices = client.projects().locations().registries().devices(
            ).list(parent=registry_path).execute().get('devices', [])

    for device in devices:
            print('Device: {} : {}'.format(
                    device.get('numId'),
                    device.get('id')))

    return devices

The following sample shows how to retrieve a device and its metadata from a device registry:

Java

public static Device getDevice(String deviceId, 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();

  String registryPath = "projects/" + projectId + "/locations/" + cloudRegion + "/registries/"
      + registryName;

  String devicePath = registryPath + "/devices/" + deviceId;
  System.out.println("Retrieving device " + devicePath);
  return service.projects().locations().registries().devices().get(devicePath).execute();
}

Node.js

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

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

Python

This sample uses the Google API Client Library for Python.
def get_device(
        service_account_json, project_id, cloud_region, registry_id,
        device_id):
    """Retrieve the device with the given id."""
    print('Getting device')
    client = get_client(service_account_json)
    registry_name = 'projects/{}/locations/{}/registries/{}'.format(
            project_id, cloud_region, registry_id)

    device_name = '{}/devices/{}'.format(registry_name, device_id)
    devices = client.projects().locations().registries().devices()
    device = devices.get(name=device_name).execute()

    print('Id : {}'.format(device.get('id')))
    print('Name : {}'.format(device.get('name')))
    print('Credentials:')
    if device.get('credentials') is not None:
        for credential in device.get('credentials'):
            keyinfo = credential.get('publicKey')
            print('\tcertificate: \n{}'.format(keyinfo.get('key')))
            print('\tformat : {}'.format(keyinfo.get('format')))
            print('\texpiration: {}'.format(credential.get('expirationTime')))

    print('Config:')
    print('\tdata: {}'.format(device.get('config').get('data')))
    print('\tversion: {}'.format(device.get('config').get('version')))
    print('\tcloudUpdateTime: {}'.format(device.get('config').get(
            'cloudUpdateTime')))

    return device

The following sample shows how to retrieve device state from a device registry:

Java

public static List<DeviceState> getDeviceStates(
    String deviceId, 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();

  String registryPath = "projects/" + projectId + "/locations/" + cloudRegion + "/registries/"
      + registryName;

  String devicePath = registryPath + "/devices/" + deviceId;
  System.out.println("Retrieving device states " + devicePath);

  ListDeviceStatesResponse resp  = service.projects().locations().registries().devices().states()
      .list(devicePath).execute();
  return resp.getDeviceStates();
}

Node.js

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

client.projects.locations.registries.devices.states.list(request,
    (err, data) => {
      if (err) {
        console.log('Could not find device:', deviceId);
        console.log(err);
      } else {
        console.log('State:', data);
      }
    });

Python

This sample uses the Google API Client Library for Python.
def get_state(
        service_account_json, project_id, cloud_region, registry_id,
        device_id):
    """Retrieve a device's state blobs."""
    client = get_client(service_account_json)
    registry_name = 'projects/{}/locations/{}/registries/{}'.format(
            project_id, cloud_region, registry_id)

    device_name = '{}/devices/{}'.format(registry_name, device_id)
    devices = client.projects().locations().registries().devices()
    state = devices.states().list(name=device_name, numStates=5).execute()

    print('State: {}\n'.format(state))

    return state

See the Device Management Samples for more code samples in Python, Java, and Node.js.

Deleting devices and registries

You can delete devices and registries using Cloud Platform Console, the API, or gcloud. To delete a registry, first delete all the devices within it.

Console

To delete a device:

  1. Go to the Device registries page in Cloud Platform Console.

    Go to the Device registries page

  2. Click the ID of the registry for the device.

  3. Click the ID of the device to go to the Device details page.

  4. Click the trash can icon on the Device details page in Cloud Platform Console.

To delete a registry:

  1. Go to the Device registries page in Cloud Platform Console.

    Go to the Device registries page

  2. Click the ID of the registry for the device.

  3. Click the trash can icon on the Registry details page in Cloud Platform Console.

gcloud

To delete a device, run the gcloud beta iot devices delete command:

gcloud beta iot devices delete DEVICE_ID \
  --project=PROJECT_ID \
  --registry=REGISTRY_ID \
  --region=REGION

To delete a registry, run the gcloud beta iot registries delete command:

gcloud beta iot registries delete REGISTRY_ID \
  --project=PROJECT_ID \
  --region=REGION

API

Use the following methods to delete devices and registries:

The following sample shows how to delete a device from a registry:

Java

public static void deleteDevice(String deviceId, 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 = "projects/" + projectId + "/locations/" + cloudRegion
      + "/registries/" + registryName;

  final String devicePath = registryPath + "/devices/" + deviceId;
  System.out.println("Deleting device " + devicePath);
  service.projects().locations().registries().devices().delete(devicePath).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}/devices/${deviceId}`
};

client.projects.locations.registries.devices.delete(request, (err, data) => {
  if (err) {
    console.log('Could not delete device:', deviceId);
    console.log(err);
  } else {
    console.log('Successfully deleted device:', deviceId);
    console.log(data);
    if (cb) {
      cb();
    }
  }
});

Python

This sample uses the Google API Client Library for Python.
def delete_device(
        service_account_json, project_id, cloud_region, registry_id,
        device_id):
    """Delete the device with the given id."""
    print('Delete device')
    client = get_client(service_account_json)
    registry_name = 'projects/{}/locations/{}/registries/{}'.format(
            project_id, cloud_region, registry_id)

    device_name = '{}/devices/{}'.format(registry_name, device_id)

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

The following sample shows how to delete a registry:

Java

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

  String projectPath = "projects/" + projectId + "/locations/" + cloudRegion;
  String registryPath = projectPath + "/registries/" + 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);
  }
});

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()

See the Registry Management Device Samples for more code samples in Python, Java, and Node.js.

What's next

Monitor your resources on the go

Get the Google Cloud Console app to help you manage your projects.

Send feedback about...

Google Cloud Internet of Things Core