Get a device

Retrieve a specific device and prints its details.

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample


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

        var device = cloudIot.Projects.Locations.Registries.Devices.Get(name).Execute();
        Console.WriteLine("Device: ");
        Console.WriteLine($"\tBlocked: {device.Blocked == true}");
        Console.WriteLine($"\tConfig version: {device.Config.Version}");
        Console.WriteLine($"\tFirst Credential Expiry: {device.Credentials.First().ExpirationTime}");
        Console.WriteLine($"\tLast State Time:{device.LastStateTime}");
        Console.WriteLine($"\tName: {device.Name}");
    catch (Google.GoogleApiException e)
        if (e.Error != null) return e.Error.Code;
        return -1;
    return 0;


// getDevice retrieves a specific device and prints its details.
func getDevice(w io.Writer, projectID string, region string, registryID string, device string) (*cloudiot.Device, error) {
	// Authorize the client using Application Default Credentials.
	// See
	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, registryID, device)
	response, err := client.Projects.Locations.Registries.Devices.Get(path).Do()
	if err != nil {
		return nil, err

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

	return response, nil


/** Retrieves device metadata from a registry. * */
protected static Device getDevice(
    String deviceId, String projectId, String cloudRegion, String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)

  final String devicePath =
          projectId, cloudRegion, registryName, deviceId);

  System.out.println("Retrieving device " + devicePath);
  return service.projects().locations().registries().devices().get(devicePath).execute();


// const cloudRegion = 'us-central1';
// const deviceId = 'my-device';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
const iot = require('@google-cloud/iot');
const iotClient = new iot.v1.DeviceManagerClient({
  // optional auth parameters.

async function getDevice() {
  // Construct request
  const devicePath = iotClient.devicePath(

  // See full list of device fields:
  // Warning! Use snake_case field names.
  const fieldMask = {
    paths: [

  const [response] = await iotClient.getDevice({
    name: devicePath,
  const data = response;

  console.log('Found device:', deviceId, data);



use Google\Cloud\Iot\V1\DeviceManagerClient;
use Google\Cloud\Iot\V1\PublicKeyFormat;

 * Retrieve the device with the given id.
 * @param string $registryId IOT Device Registry ID
 * @param string $deviceId IOT Device ID
 * @param string $projectId Google Cloud project ID
 * @param string $location (Optional) Google Cloud region
function get_device(
    $location = 'us-central1'
) {
    print('Getting device' . PHP_EOL);

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

    $device = $deviceManager->getDevice($deviceName);

    $formats = [
        PublicKeyFormat::UNSPECIFIED_PUBLIC_KEY_FORMAT => 'unspecified',
        PublicKeyFormat::RSA_X509_PEM => 'RSA_X509_PEM',
        PublicKeyFormat::ES256_PEM => 'ES256_PEM',
        PublicKeyFormat::RSA_PEM => 'RSA_PEM',
        PublicKeyFormat::ES256_X509_PEM => 'ES256_X509_PEM',

    printf('ID: %s' . PHP_EOL, $device->getId());
    printf('Name: %s' . PHP_EOL, $device->getName());
    foreach ($device->getCredentials() as $credential) {
        print('Certificate:' . PHP_EOL);
        printf('    Format: %s' . PHP_EOL,
        printf('    Expiration: %s' . PHP_EOL,
            $credential->getExpirationTime()->toDateTime()->format('Y-m-d H:i:s'));
    printf('Data: %s' . PHP_EOL, $device->getConfig()->getBinaryData());
    printf('Version: %s' . PHP_EOL, $device->getConfig()->getVersion());
    printf('Update Time: %s' . PHP_EOL,
        $device->getConfig()->getCloudUpdateTime()->toDateTime()->format('Y-m-d H:i:s'));


# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
# device_id = 'your-device-id'
print("Getting device")
client = iot_v1.DeviceManagerClient()
device_path = client.device_path(project_id, cloud_region, registry_id, device_id)

# See full list of device fields:
# Warning! Use snake_case field names.
field_mask = gp_field_mask.FieldMask(

device = client.get_device(request={"name": device_path, "field_mask": field_mask})

print("Id : {}".format(
print("Name : {}".format(

if device.credentials is not None:
    for credential in device.credentials:
        keyinfo = credential.public_key
        print("\tcertificate: \n{}".format(keyinfo.key))

        if keyinfo.format == 4:
            keyformat = "ES256_X509_PEM"
        elif keyinfo.format == 3:
            keyformat = "RSA_PEM"
        elif keyinfo.format == 2:
            keyformat = "ES256_PEM"
        elif keyinfo.format == 1:
            keyformat = "RSA_X509_PEM"
            keyformat = "UNSPECIFIED_PUBLIC_KEY_FORMAT"
        print("\tformat : {}".format(keyformat))
        print("\texpiration: {}".format(credential.expiration_time))

print("\tdata: {}".format(device.config.binary_data))
print("\tversion: {}".format(device.config.version))
print("\tcloudUpdateTime: {}".format(device.config.cloud_update_time))

return device


# project_id  = "Your Google Cloud project ID"
# location_id = "The Cloud region the registry is located in"
# registry_id = "The registry to get a device from"
# device_id   = "The identifier of the device to get"

require "google/apis/cloudiot_v1"

# Initialize the client and authenticate with the specified scope
Cloudiot   = Google::Apis::CloudiotV1
iot_client =
iot_client.authorization = Google::Auth.get_application_default(

# The resource name of the location associated with the project
parent = "projects/#{project_id}/locations/#{location_id}"
resource = "#{parent}/registries/#{registry_id}/devices/#{device_id}"

# List the devices in the provided region
device = iot_client.get_project_location_registry_device(

puts "Device: #{}"
puts "\tBlocked: #{device.blocked}"
puts "\tLast Event Time: #{device.last_event_time}"
puts "\tLast State Time: #{device.last_state_time}"
puts "\tName: #{}"
puts "\tCertificate formats:"
if device.credentials
  device.credentials.each { |cert| puts "\t\t#{cert.public_key.format}" }
  puts "\t\tNo certificates for device"

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser