Como criar registros e dispositivos

Esta página explica como criar, editar e excluir registros de dispositivos e dispositivos dentro deles.

Um dispositivo é um "elemento" da "Internet das Coisas", uma unidade de processamento capaz de se conectar à Internet (direta ou indiretamente) e trocar dados com a nuvem. Um registro de dispositivo é um contêiner de dispositivos com propriedades compartilhadas. Para mais detalhes sobre dispositivos e registros, consulte Dispositivos.

Se você ainda não tiver feito isso, conclua as etapas de Primeiros passos antes de continuar.

como criar um registro de dispositivos

Para usar o Cloud IoT Core, você precisa criar pelo menos um registro de dispositivo. É possível criar um registro usando o console do Google Cloud, a API ou a gcloud.

Console

  1. Acesse a página Registros no Console do Google Cloud.

    Acessar a página Registros

  2. Na parte superior da página, clique em Criar um registro.

  3. Digite um ID do registro e selecione uma região da nuvem. Saiba mais sobre requisitos de nome e tamanho de registro em Requisitos de caracteres e tamanho permitidos.

  4. Selecione os Protocolos que os dispositivos neste registro usarão para se conectar ao Cloud IoT Core: MQTT, HTTP ou ambos.

  5. Selecione um tópico de telemetria padrão ou crie um novo.

    O tópico padrão é usado para eventos de telemetria publicados que não têm uma subpasta ou se a subpasta usada não tem um tópico do Cloud Pub/Sub correspondente.

  6. (Opcional) Se você quiser publicar fluxos separados de dados de um dispositivo, adicione mais tópicos de telemetria.

    Cada tópico é mapeado para uma subpasta especificada no caminho do tópico MQTT ou na solicitação HTTP quando os dados são publicados.

    Para criar outros tópicos de telemetria:

    a. Clique em Adicionar mais tópicos de telemetria e, em seguida, clique em Adicionar tópico e subpasta.

    b. Selecione um tópico do Pub/Sub ou crie um novo.

    c. Digite um nome de subpasta descritivo.

    Para informações sobre nomes de subpastas e requisitos de tamanho, consulte Requisitos de caracteres e tamanhos permitidos.

  7. (Opcional) Selecione um Tópico de estado do dispositivo ou crie um novo. Este tópico pode ser igual a um tópico de telemetria ou pode ser usado apenas para dados de estado.

    Os dados de estado são publicados no Cloud Pub/Sub com base no melhor esforço: se a publicação no tópico falhar, ela não será repetida. Se nenhum tópico for definido, as atualizações de estado do dispositivo serão mantidas internamente pelo Cloud IoT Core, mas somente os últimos 10 estados serão mantidos.

    Para mais informações, consulte Como saber o estado do dispositivo.

  8. Clique em Criar para continuar.

gcloud

Para criar um registro, execute o comando gcloud iot registries create:

gcloud iot registries create REGISTRY_ID \
    --project=PROJECT_ID \
    --region=REGION \
    [--event-notification-config=topic=TOPIC,[subfolder=SUBFOLDER] [--event-notification-config=...]]
    [--state-pubsub-topic=STATE_PUBSUB_TOPIC]

Na versão atual do Cloud IoT Core, as regiões disponíveis são us-central1, europe-west1 e asia-east1.

É possível usar as sinalizações --enable-http-config e --enable-mqtt-config para ativar e desativar protocolos para o registro. Por padrão, os dois protocolos estão ativados.

É possível especificar vários tópicos do Pub/Sub e as subpastas correspondentes repetindo a sinalização --event-notification-config. Se você especificar vários tópicos do Pub/Sub, selecione um tópico padrão que não tenha subpastas. Este tópico padrão será usado para eventos de telemetria publicados que não têm uma subpasta ou se a subpasta usada não tem um tópico do Pub/Sub correspondente. Se você não selecionar um tópico padrão, esses eventos de telemetria serão perdidos.

API

Use o método create do DeviceRegistry para criar um registro:

C#

Para uma amostra de CreateAuthorizedClient, consulte Como autenticar aplicativos.
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. */
protected static void createRegistry(
    String cloudRegion, String projectId, String registryName, String pubsubTopicPath)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(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

Para uma amostra de getClient, consulte Como autenticar aplicativos.
// Client retrieved in callback
// const cloudRegion = 'us-central1';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
// function errCb = lookupRegistry; // Lookup registry if already exists.
const iot = require('@google-cloud/iot');

// Lookup the pubsub topic
const topicPath = `projects/${projectId}/topics/${pubsubTopicId}`;

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

async function createDeviceRegistry() {
  // Construct request
  const newParent = iotClient.locationPath(projectId, cloudRegion);
  const deviceRegistry = {
    eventNotificationConfigs: [
      {
        pubsubTopicName: topicPath,
      },
    ],
    id: registryId,
  };
  const request = {
    parent: newParent,
    deviceRegistry: deviceRegistry,
  };

  const [response] = await iotClient.createDeviceRegistry(request);

  console.log('Successfully created registry');
  console.log(response);
}

createDeviceRegistry();

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

Neste exemplo, usamos a biblioteca de cliente de APIs do Google para Python. Para uma amostra de get client, consulte Como autenticar aplicativos.
# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# pubsub_topic = 'your-pubsub-topic'
# registry_id = 'your-registry-id'
client = iot_v1.DeviceManagerClient()
parent = f"projects/{project_id}/locations/{cloud_region}"

if not pubsub_topic.startswith("projects/"):
    pubsub_topic = "projects/{}/topics/{}".format(project_id, pubsub_topic)

body = {
    "event_notification_configs": [{"pubsub_topic_name": pubsub_topic}],
    "id": registry_id,
}

try:
    response = client.create_device_registry(
        request={"parent": parent, "device_registry": body}
    )
    print("Created registry")
    return response
except HttpError:
    print("Error, registry not created")
    raise
except AlreadyExists:
    print("Error, registry already exists")
    raise

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

Papel de IAM para publicação do Pub/Sub

Quando você ativa a API Cloud IoT Core para um projeto pela primeira vez, uma nova conta de serviço do projeto recebe automaticamente um papel (cloudiot.serviceAgent) que permite a publicação. a todos os tópicos do Pub/Sub definidos nos registros do projeto. Remover esse papel padrão da conta de serviço do projeto relevante posteriormente pode causar erros. Veja detalhes em Solução de problemas.

Como criar um registro de dispositivo com vários tópicos do Pub/Sub

Conforme observado em Como criar um registro de dispositivo, você precisa criar pelo menos um registro de dispositivo para usar o Cloud IoT Core. Um registro pode ter um ou mais tópicos do Pub/Sub em que os dispositivos no registro podem publicar dados.

É possível combinar tópicos do Pub/Sub com subpastas MQTT/HTTP para publicar eventos de telemetria em tópicos separados. Cada tópico é mapeado para uma subpasta. Portanto, quando você publica dados para a subpasta, ele é encaminhado para o tópico. Por exemplo, imagine que você tem um dispositivo que publica vários tipos de dados, como temperatura, umidade e dados de registros. Ao direcionar esses streams de dados para os próprios tópicos Pub/Sub, você elimina a necessidade de separar os dados em diferentes categorias após a publicação.

É possível mapear um único tópico do Pub/Sub para várias subpastas, mas o inverso não é verdadeiro. Cada subpasta precisa ser exclusiva e não é possível mapear uma subpasta para tópicos diferentes.

Para informações detalhadas sobre a publicação em tópicos separados do Pub/Sub, consulte as seções sobre como usar a ponte MQTT e como usar a ponte HTTP.

Como criar pares de chaves do dispositivo

Antes de criar um dispositivo, primeiro crie um par de chaves pública/privada para ele. Ao se conectar ao Cloud IoT Core, cada dispositivo cria um JSON Web Token (JWT) assinado com a chave privada, que o Cloud IoT Core autentica usando a chave pública do dispositivo.

Criar ou editar um dispositivo

É possível criar um dispositivo ou editar um existente usando o console do Google Cloud, a API ou a gcloud. Verifique se você criou um registro e um par de chaves antes de concluir as etapas desta seção.

Console

  1. Acesse a página Registros no Console do Google Cloud.

    Acessar a página Registros

  2. Clique no ID do registro do dispositivo.

  3. No menu de registro à esquerda, clique em Dispositivos.

  4. Clique em Criar um dispositivo.

    Para editar um dispositivo, clique no código dele na página Dispositivos e, depois, em Editar dispositivo na parte superior da página.

  5. Digite um Código do dispositivo que descreva o dispositivo brevemente ou que ajude a identificá-lo. Não será possível editar esse campo mais tarde. Para saber mais sobre as exigências do tamanho para nomes e dispositivos, consulte Requisitos de caracteres e tamanhos permitidos.

  6. Em Comunicação do dispositivo, selecione Permitir ou Bloquear. Essa opção permite bloquear a comunicação quando necessário, como quando um dispositivo não está funcionando corretamente. Na maioria dos casos, convém permitir a comunicação ao criar o dispositivo pela primeira vez.

  7. Se estiver criando um novo dispositivo, selecione o Método de entrada que você quer usar para inserir a chave pública:

    • Manual: copie e cole a chave pública no campo Valor da chave pública.
    • Upload:no campo Valor da chave pública, clique em Procurar para selecionar um arquivo no seu computador.
  8. Selecione o Formato da chave pública que corresponde ao par de chaves deste dispositivo. Cole o certificado ou a chave no campo Valor da chave pública. Também é possível definir uma data de validade para a chave.

    Para adicionar uma chave a um dispositivo, clique em Adicionar chave pública na página Detalhes do dispositivo.

  9. Use os campos Chave e Valor para adicionar metadados do dispositivo opcionais, como um número de série. Para informações sobre requisitos de tamanho e nomenclatura de chave-valor de metadados, consulte Requisitos de caracteres e tamanho permitidos.

  10. Selecione um nível do Cloud Logging para determinar quais eventos do dispositivo são enviados para o Cloud Logging.

  11. Clique em Criar para criar o dispositivo ou Atualizar para salvar as alterações em um dispositivo.

gcloud

Para criar um dispositivo, execute o comando gcloud iot devices create.

Para criar um dispositivo com uma chave pública RSA, execute o seguinte comando:

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

Para criar um dispositivo com um certificado de chave pública RSA, execute o seguinte comando:

gcloud iot devices create DEVICE_ID \
  --project=PROJECT_ID \
  --region=REGION \
  --registry=REGISTRY_ID \
  --public-key path=rsa_public.pem,type=rsa-x509-pem

Para criar um dispositivo com uma chave pública ES256, execute o seguinte comando:

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

Para criar um dispositivo com um certificado de chave pública ES256, execute o seguinte comando:

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

Para editar um dispositivo, execute o comando gcloud iot devices update:

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

API

Use os seguintes métodos para criar ou editar dispositivos:

Ao criar um dispositivo, as chaves públicas são especificadas no campo credentials do recurso Device na API Cloud IoT Core. Também é possível adicionar ou modificar esse campo ao atualizar o recurso do dispositivo. Se um ou mais certificados no nível do registro estiverem presentes ao adicionar uma nova credencial do dispositivo (por meio de criação ou de modificações), a credencial da chave pública precisa ser assinada por um dos certificados no nível do registro. Consulte DeviceCredential no recurso Dispositivo para ver mais informações.

Para RSAs, o campo Device.credentials[i].public_key.key precisa ser definido como o conteúdo de rsa_cert.pem (incluindo o cabeçalho e o rodapé). O campo Device.credentials[i].public_key.format precisa ser definido como RSA_PEM ou RSA_X509_PEM.

Para o ES256, o campo Device.credentials[i].public_key.key precisa ser definido como o conteúdo de ec_public.pem (incluindo o cabeçalho e o rodapé). O campo Device.credentials[i].public_key.format precisa ser definido como ES256_PEM ou ES256_X509_PEM.

O exemplo a seguir mostra como criar um dispositivo com credenciais do RSA:

C#

public static object CreateRsaDevice(string projectId, string cloudRegion, string registryId, string deviceId, string keyPath)
{
    var cloudIot = CreateAuthorizedClient();
    var parent = $"projects/{projectId}/locations/{cloudRegion}/registries/{registryId}";

    try
    {
        String keyText = File.ReadAllText(keyPath);
        Device body = new Device()
        {
            Id = deviceId
        };
        body.Credentials = new List<DeviceCredential>();
        body.Credentials.Add(new DeviceCredential()
        {
            PublicKey = new PublicKeyCredential()
            {
                Key = keyText,
                Format = "RSA_X509_PEM"
            },
        });

        var device = cloudIot.Projects.Locations.Registries.Devices.Create(body, parent).Execute();
        Console.WriteLine("Device created: ");
        Console.WriteLine($"{device.Id}");
        Console.WriteLine($"\tBlocked: {device.Blocked == true}");
        Console.WriteLine($"\tConfig version: {device.Config.Version}");
        Console.WriteLine($"\tName: {device.Name}");
        Console.WriteLine($"\tState:{device.State}");
    }
    catch (Google.GoogleApiException e)
    {
        Console.WriteLine(e.Message);
        if (e.Error != null) return e.Error.Code;
        return -1;
    }
    return 0;
}

Go


// createRSA creates a device in a registry given RSA X.509 credentials.
func createRSA(w io.Writer, projectID string, region string, registryID 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, registryID)
	response, err := client.Projects.Locations.Registries.Devices.Create(parent, &device).Do()
	if err != nil {
		return nil, err
	}

	fmt.Fprintf(w, "Successfully created RSA256 X.509 device: %s", deviceID)

	return response, nil
}

Java

/** Create a device that is authenticated using RS256. */
protected static void createDeviceWithRs256(
    String deviceId,
    String certificateFilePath,
    String projectId,
    String cloudRegion,
    String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

  final String registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

  PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
  String key = Files.asCharSource(new File(certificateFilePath), StandardCharsets.UTF_8).read();
  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(Collections.singletonList(devCredential));
  Device createdDevice =
      service
          .projects()
          .locations()
          .registries()
          .devices()
          .create(registryPath, device)
          .execute();

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

Node.js

// const cloudRegion = 'us-central1';
// const deviceId = 'my-rsa-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 createDevice() {
  // Construct request
  const regPath = iotClient.registryPath(projectId, cloudRegion, registryId);
  const device = {
    id: deviceId,
    credentials: [
      {
        publicKey: {
          format: 'RSA_X509_PEM',
          key: readFileSync(rsaCertificateFile).toString(),
        },
      },
    ],
  };

  const request = {
    parent: regPath,
    device,
  };

  const [response] = await iotClient.createDevice(request);
  console.log('Created device', response);
}

createDevice();

PHP

use Google\Cloud\Iot\V1\DeviceManagerClient;
use Google\Cloud\Iot\V1\Device;
use Google\Cloud\Iot\V1\DeviceCredential;
use Google\Cloud\Iot\V1\PublicKeyCredential;
use Google\Cloud\Iot\V1\PublicKeyFormat;

/**
 * Create a new device with the given id, using RS256 for
 * authentication.
 *
 * @param string $registryId IOT Device Registry ID
 * @param string $deviceId IOT Device ID
 * @param string $certificateFile Path to RS256 certificate file.
 * @param string $projectId (optional) Google Cloud project ID
 * @param string $location (Optional) Google Cloud region
 */
function create_rsa_device(
    $registryId,
    $deviceId,
    $certificateFile,
    $projectId,
    $location = 'us-central1'
) {
    print('Creating new RS256 Device' . PHP_EOL);

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

    $publicKey = (new PublicKeyCredential())
        ->setFormat(PublicKeyFormat::RSA_X509_PEM)
        ->setKey(file_get_contents($certificateFile));

    $credential = (new DeviceCredential())
        ->setPublicKey($publicKey);

    $device = (new Device())
        ->setId($deviceId)
        ->setCredentials([$credential]);

    $device = $deviceManager->createDevice($registryName, $device);

    printf('Device: %s : %s' . PHP_EOL,
        $device->getNumId(),
        $device->getId());
}

Python

Neste exemplo, usamos a biblioteca de cliente de APIs do Google para Python.
# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
# device_id = 'your-device-id'
# certificate_file = 'path/to/certificate.pem'

client = iot_v1.DeviceManagerClient()

parent = client.registry_path(project_id, cloud_region, registry_id)

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": [
        {
            "public_key": {
                "format": iot_v1.PublicKeyFormat.RSA_X509_PEM,
                "key": certificate,
            }
        }
    ],
}

return client.create_device(request={"parent": parent, "device": device_template})

Ruby

# project_id  = "Your Google Cloud project ID"
# location_id = "The Cloud region the registry is located in"
# registry_id = "The registry to create a device in"
# device_id   = "The identifier of the device to create"
# cert_path   = "The path to the RSA certificate"

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
parent = "projects/#{project_id}/locations/#{location_id}/registries/#{registry_id}"

credential = Google::Apis::CloudiotV1::DeviceCredential.new
credential.public_key = Google::Apis::CloudiotV1::PublicKeyCredential.new
credential.public_key.format = "RSA_X509_PEM"
credential.public_key.key = File.read cert_path

device = Cloudiot::Device.new
device.id = device_id
device.credentials = [credential]

# Create the device
device = iot_client.create_project_location_registry_device parent, device

puts "Device: #{device.id}"
puts "\tBlocked: #{device.blocked}"
puts "\tLast Event Time: #{device.last_event_time}"
puts "\tLast State Time: #{device.last_state_time}"
puts "\tName: #{device.name}"

O exemplo a seguir mostra como criar um dispositivo com credenciais de curva elíptica (EC):

C#

public static object CreateEsDevice(string projectId, string cloudRegion, string registryId, string deviceId, string keyPath)
{
    var cloudIot = CreateAuthorizedClient();
    var parent = $"projects/{projectId}/locations/{cloudRegion}/registries/{registryId}";

    try
    {
        String keyText = File.ReadAllText(keyPath);
        Device body = new Device()
        {
            Id = deviceId
        };
        body.Credentials = new List<DeviceCredential>();
        body.Credentials.Add(new DeviceCredential()
        {
            PublicKey = new PublicKeyCredential()
            {
                Key = keyText,
                Format = "ES256_PEM"
            },
        });

        var device = cloudIot.Projects.Locations.Registries.Devices.Create(body, parent).Execute();
        Console.WriteLine("Device created: ");
        Console.WriteLine($"{device.Id}");
        Console.WriteLine($"\tBlocked: {device.Blocked == true}");
        Console.WriteLine($"\tConfig version: {device.Config.Version}");
        Console.WriteLine($"\tName: {device.Name}");
        Console.WriteLine($"\tState:{device.State}");
    }
    catch (Google.GoogleApiException e)
    {
        Console.WriteLine(e.Message);
        if (e.Error != null) return e.Error.Code;
        return -1;
    }
    return 0;
}

Go


// createES creates a device in a registry with ES256 credentials.
func createES(w io.Writer, projectID string, region string, registryID 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, registryID)
	response, err := client.Projects.Locations.Registries.Devices.Create(parent, &device).Do()
	if err != nil {
		return nil, err
	}

	fmt.Fprintf(w, "Successfully created ES256 device: %s\n", deviceID)

	return response, nil
}

Java

/** Create a device that is authenticated using ES256. */
protected static void createDeviceWithEs256(
    String deviceId,
    String publicKeyFilePath,
    String projectId,
    String cloudRegion,
    String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

  final String registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

  PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
  final String key =
      Files.asCharSource(new File(publicKeyFilePath), StandardCharsets.UTF_8).read();
  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(Collections.singletonList(devCredential));

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

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

Node.js

// const cloudRegion = 'us-central1';
// const deviceId = 'my-es-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 createDevice() {
  // Construct request
  const regPath = iotClient.registryPath(projectId, cloudRegion, registryId);
  const device = {
    id: deviceId,
    credentials: [
      {
        publicKey: {
          format: 'ES256_PEM',
          key: readFileSync(esCertificateFile).toString(),
        },
      },
    ],
  };
  const request = {
    parent: regPath,
    device,
  };

  const [response] = await iotClient.createDevice(request);
  console.log('Created device', response);
}

createDevice();

PHP

use Google\Cloud\Iot\V1\DeviceManagerClient;
use Google\Cloud\Iot\V1\Device;
use Google\Cloud\Iot\V1\DeviceCredential;
use Google\Cloud\Iot\V1\PublicKeyCredential;
use Google\Cloud\Iot\V1\PublicKeyFormat;

/**
 * Create a new device with the given id, using ES256 for
 * authentication.
 *
 * @param string $registryId IOT Device Registry ID
 * @param string $deviceId IOT Device ID
 * @param string $publicKeyFile Path to public ES256 key file.
 * @param string $projectId (optional) Google Cloud project ID
 * @param string $location (Optional) Google Cloud region
 */
function create_es_device(
    $registryId,
    $deviceId,
    $publicKeyFile,
    $projectId,
    $location = 'us-central1'
) {
    print('Creating new ES256 Device' . PHP_EOL);

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

    $publicKey = (new PublicKeyCredential())
        ->setFormat(PublicKeyFormat::ES256_PEM)
        ->setKey(file_get_contents($publicKeyFile));

    $credential = (new DeviceCredential())
        ->setPublicKey($publicKey);

    $device = (new Device())
        ->setId($deviceId)
        ->setCredentials([$credential]);

    $device = $deviceManager->createDevice($registryName, $device);

    printf('Device: %s : %s' . PHP_EOL,
        $device->getNumId(),
        $device->getId());
}

Python

Neste exemplo, usamos a biblioteca de cliente de APIs do Google para Python.
# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
# device_id = 'your-device-id'
# public_key_file = 'path/to/certificate.pem'

client = iot_v1.DeviceManagerClient()

parent = client.registry_path(project_id, cloud_region, registry_id)

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": [
        {
            "public_key": {
                "format": iot_v1.PublicKeyFormat.ES256_PEM,
                "key": public_key,
            }
        }
    ],
}

return client.create_device(request={"parent": parent, "device": device_template})

Ruby

# project_id  = "Your Google Cloud project ID"
# location_id = "The Cloud region the registry is located in"
# registry_id = "The registry to create a device in"
# device_id   = "The identifier of the device to create"
# cert_path   = "The path to the EC certificate"

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
parent = "projects/#{project_id}/locations/#{location_id}/registries/#{registry_id}"

device = Cloudiot::Device.new
device.id = device_id

pubkey = Google::Apis::CloudiotV1::PublicKeyCredential.new
pubkey.key = File.read cert_path
pubkey.format = "ES256_PEM"

cred = Google::Apis::CloudiotV1::DeviceCredential.new
cred.public_key = pubkey

device.credentials = [cred]

# Create the device
device = iot_client.create_project_location_registry_device parent, device

puts "Device: #{device.id}"
puts "\tBlocked: #{device.blocked}"
puts "\tLast Event Time: #{device.last_event_time}"
puts "\tLast State Time: #{device.last_state_time}"
puts "\tName: #{device.name}"

Veja na amostra a seguir como corrigir um dispositivo com credenciais RSA:

C#

public static object PatchRsaDevice(string projectId, string cloudRegion, string registryId, string deviceId, string keyPath)
{
    var cloudIot = CreateAuthorizedClient();
    var name = $"projects/{projectId}/locations/{cloudRegion}/registries/{registryId}/devices/{deviceId}";

    try
    {
        String keyText = File.ReadAllText(keyPath);
        Device body = new Device();
        body.Credentials = new List<DeviceCredential>();
        body.Credentials.Add(new DeviceCredential()
        {
            PublicKey = new PublicKeyCredential()
            {
                Key = keyText,
                Format = "RSA_X509_PEM"
            },
        });

        var req = cloudIot.Projects.Locations.Registries.Devices.Patch(body, name);
        req.UpdateMask = "credentials";
        var device = req.Execute();
        Console.WriteLine("Device patched: ");
        Console.WriteLine($"{device.Id}");
        Console.WriteLine($"\tBlocked: {device.Blocked == true}");
        Console.WriteLine($"\tConfig version: {device.Config.Version}");
        Console.WriteLine($"\tName: {device.Name}");
        Console.WriteLine($"\tState:{device.State}");
    }
    catch (Google.GoogleApiException e)
    {
        Console.WriteLine(e.Message);
        if (e.Error != null) return e.Error.Code;
        return -1;
    }
    return 0;
}

Go


// patchDeviceRSA patches a device to use RSA256 X.509 credentials.
func patchDeviceRSA(w io.Writer, projectID string, region string, registryID 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, registryID, deviceID)
	response, err := client.Projects.Locations.Registries.Devices.
		Patch(parent, &device).UpdateMask("credentials").Do()
	if err != nil {
		return nil, err
	}

	fmt.Fprintln(w, "Successfully patched device with RSA256 X.509 credentials")

	return response, nil
}

Java

/** Patch the device to add an RSA256 key for authentication. */
protected static void patchRsa256ForAuth(
    String deviceId,
    String publicKeyFilePath,
    String projectId,
    String cloudRegion,
    String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

  final String devicePath =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryName, deviceId);

  PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
  String key = Files.asCharSource(new File(publicKeyFilePath), StandardCharsets.UTF_8).read();
  publicKeyCredential.setKey(key);
  publicKeyCredential.setFormat("RSA_X509_PEM");

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

  Device device = new Device();
  device.setCredentials(Collections.singletonList(devCredential));

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

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

Node.js

// const cloudRegion = 'us-central1';
// const deviceId = 'my-rsa-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 updateDevice() {
  // Construct request
  const devPath = iotClient.devicePath(
    projectId,
    cloudRegion,
    registryId,
    deviceId
  );

  const device = {
    name: devPath,
    credentials: [
      {
        publicKey: {
          format: 'RSA_X509_PEM',
          key: readFileSync(rsaPublicKeyFile).toString(),
        },
      },
    ],
  };

  const [response] = await iotClient.updateDevice({
    device: device,
    updateMask: {paths: ['credentials']},
  });

  console.log('Patched device:', deviceId);
  console.log('Response', response);
}

updateDevice();

PHP

use Google\Cloud\Iot\V1\DeviceManagerClient;
use Google\Cloud\Iot\V1\Device;
use Google\Cloud\Iot\V1\DeviceCredential;
use Google\Cloud\Iot\V1\PublicKeyCredential;
use Google\Cloud\Iot\V1\PublicKeyFormat;
use Google\Protobuf\FieldMask;

/**
 * Patch the device to add an RSA256 public key to the device.
 *
 * @param string $registryId IOT Device Registry ID
 * @param string $deviceId IOT Device ID
 * @param string $certificateFile Path to RS256 certificate file.
 * @param string $projectId Google Cloud project ID
 * @param string $location (Optional) Google Cloud region
 */
function patch_rsa(
    $registryId,
    $deviceId,
    $certificateFile,
    $projectId,
    $location = 'us-central1'
) {
    print('Patch device with RSA256 certificate' . PHP_EOL);

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

    $publicKey = (new PublicKeyCredential())
        ->setFormat(PublicKeyFormat::RSA_X509_PEM)
        ->setKey(file_get_contents($certificateFile));

    $credential = (new DeviceCredential())
        ->setPublicKey($publicKey);

    $device = (new Device())
        ->setName($deviceName)
        ->setCredentials([$credential]);

    $updateMask = (new FieldMask())
        ->setPaths(['credentials']);

    $device = $deviceManager->updateDevice($device, $updateMask);
    printf('Updated device %s' . PHP_EOL, $device->getName());
}

Python

Neste exemplo, usamos a biblioteca de cliente de APIs do Google para Python.
# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
# device_id = 'your-device-id'
# public_key_file = 'path/to/certificate.pem'
print("Patch device with RSA256 certificate")

client = iot_v1.DeviceManagerClient()
device_path = client.device_path(project_id, cloud_region, registry_id, device_id)

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

key = iot_v1.PublicKeyCredential(
    format=iot_v1.PublicKeyFormat.RSA_X509_PEM, key=public_key_bytes
)

cred = iot_v1.DeviceCredential(public_key=key)
device = client.get_device(request={"name": device_path})

device.id = b""
device.num_id = 0
device.credentials.append(cred)

mask = gp_field_mask.FieldMask()
mask.paths.append("credentials")

return client.update_device(request={"device": device, "update_mask": mask})

Ruby

# project_id  = "Your Google Cloud project ID"
# location_id = "The Cloud region the registry is located in"
# registry_id = "The registry to create a device in"
# device_id   = "The identifier of the device to patch"
# cert_path   = "The path to the RSA certificate"

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
parent = "projects/#{project_id}/locations/#{location_id}/registries/#{registry_id}"
path   = "#{parent}/devices/#{device_id}"

credential = Google::Apis::CloudiotV1::DeviceCredential.new
credential.public_key = Google::Apis::CloudiotV1::PublicKeyCredential.new
credential.public_key.format = "RSA_X509_PEM"
credential.public_key.key = File.read cert_path

device = Cloudiot::Device.new
device.credentials = [credential]

# Create the device
device = iot_client.patch_project_location_registry_device(
  path, device, update_mask: "credentials"
)

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

Consulte Amostras de gerenciamento de dispositivos para ver mais exemplos de código.

Datas de validade de credenciais e certificados

Ao criar um dispositivo e adicionar uma chave pública, é possível definir uma data de validade para a chave. Se a chave foi gerada com um certificado X.509 autoassinado, o próprio certificado também tem uma data de validade. No entanto, essas duas datas de validade são separadas.

Se a chave expirar ou o certificado X.509 autoassinado na chave expirar, o dispositivo não poderá se conectar ao Cloud IoT Core. Além disso, se você tentar criar ou atualizar um dispositivo com um certificado X.509 expirado, o Cloud IoT Core retornará um erro.

Recebendo detalhes do dispositivo

É possível ver detalhes sobre um ou mais dispositivos usando o console do Google Cloud, a API ou a gcloud.

Console

  1. Acesse a página Registros no Console do Google Cloud.

    Acessar a página Registros

  2. Clique no ID do registro do dispositivo.

  3. No menu à esquerda, clique em Dispositivos.

  4. Clique no código do dispositivo para acessar a página Detalhes do dispositivo. Esta página resume a atividade recente do dispositivo, incluindo a última vez que uma mensagem foi publicada e a hora do erro mais recente. Essa página também mostra o código numérico do dispositivo.

  5. Clique na guia Histórico de configuração e estado para ver as versões recentes e os horários de atualização do dispositivo.

Os campos referentes ao último sinal de funcionamento e à última vez em que uma configuração foi confirmada são apenas para a ponte MQTT. A ponte HTTP não é compatível com sinais de funcionamento ou ACKs explícitas.

gcloud

Para listar os dispositivos em um registro, execute o comando gcloud iot devices list:

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

Para ver detalhes sobre um conjunto de dados, execute o comando gcloud iot devices describe.

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

API

Use os seguintes métodos para ver detalhes sobre os dispositivos:

Veja na amostra a seguir como listar os dispositivos em um registro:

C#

public static object ListDevices(string projectId, string cloudRegion, string registryId)
{
    var cloudIot = CreateAuthorizedClient();
    // The resource name of the location associated with the key rings.
    var parent = $"projects/{projectId}/locations/{cloudRegion}/registries/{registryId}";
    try
    {
        var result = cloudIot.Projects.Locations.Registries.Devices.List(parent).Execute();
        Console.WriteLine("Devices: ");
        result.Devices.ToList().ForEach(response =>
        {
            Console.WriteLine($"{response.Id}");
            Console.WriteLine($"\t{response.Config}");
            Console.WriteLine($"\t{response.Name}");
        });
    }
    catch (Google.GoogleApiException e)
    {
        Console.WriteLine(e.Message);
        return e.Error.Code;
    }
    return 0;
}

Go


// listDevices gets the identifiers of devices for a specific registry.
func listDevices(w io.Writer, projectID string, region string, registryID 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, registryID)
	response, err := client.Projects.Locations.Registries.Devices.List(parent).Do()
	if err != nil {
		return nil, err
	}

	fmt.Fprintln(w, "Devices:")
	for _, device := range response.Devices {
		fmt.Fprintf(w, "\t%s\n", device.Id)
	}

	return response.Devices, nil
}

Java

/** Print all of the devices in this registry to standard out. */
protected static void listDevices(String projectId, String cloudRegion, String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

  final String registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

  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

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

async function listDevices() {
  // Construct request
  const parentName = iotClient.registryPath(
    projectId,
    cloudRegion,
    registryId
  );

  // See full list of device fields: https://cloud.google.com/iot/docs/reference/cloudiot/rest/v1/projects.locations.registries.devices
  // Warning! Use snake_case field names.
  const fieldMask = {
    paths: [
      'id',
      'name',
      'num_id',
      'credentials',
      'last_heartbeat_time',
      'last_event_time',
      'last_state_time',
      'last_config_ack_time',
      'last_config_send_time',
      'blocked',
      'last_error_time',
      'last_error_status',
      'config',
      'state',
      'log_level',
      'metadata',
      'gateway_config',
    ],
  };

  const [response] = await iotClient.listDevices({
    parent: parentName,
    fieldMask,
  });
  const devices = response;

  if (devices.length > 0) {
    console.log('Current devices in registry:');
  } else {
    console.log('No devices in registry.');
  }

  for (let i = 0; i < devices.length; i++) {
    const device = devices[i];
    console.log(`Device ${i}: `, device);
  }
}

listDevices();

PHP

use Google\Cloud\Iot\V1\DeviceManagerClient;

/**
 * List all devices in the registry.
 *
 * @param string $registryId IOT Device Registry ID
 * @param string $projectId Google Cloud project ID
 * @param string $location (Optional) Google Cloud region
 */
function list_devices(
    $registryId,
    $projectId,
    $location = 'us-central1'
) {
    print('Listing devices' . PHP_EOL);

    // Instantiate a client.
    $deviceManager = new DeviceManagerClient();

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

    // Call the API
    $devices = $deviceManager->listDevices($registryName);

    // Print the result
    foreach ($devices->iterateAllElements() as $device) {
        printf('Device: %s : %s' . PHP_EOL,
            $device->getNumId(),
            $device->getId());
    }
}

Python

Neste exemplo, usamos a biblioteca de cliente de APIs do Google para Python.
# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
print("Listing devices")

client = iot_v1.DeviceManagerClient()
registry_path = client.registry_path(project_id, cloud_region, registry_id)

# See full list of device fields: https://cloud.google.com/iot/docs/reference/cloudiot/rest/v1/projects.locations.registries.devices
# Warning! Use snake_case field names.
field_mask = gp_field_mask.FieldMask(
    paths=[
        "id",
        "name",
        "num_id",
        "credentials",
        "last_heartbeat_time",
        "last_event_time",
        "last_state_time",
        "last_config_ack_time",
        "last_config_send_time",
        "blocked",
        "last_error_time",
        "last_error_status",
        "config",
        "state",
        "log_level",
        "metadata",
        "gateway_config",
    ]
)

devices = list(
    client.list_devices(request={"parent": registry_path, "field_mask": field_mask})
)
for device in devices:
    print(device)

return devices

Ruby

# project_id  = "Your Google Cloud project ID"
# location_id = "The Cloud region the registry is located in"
# registry_id = "The registry to list devices from"

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
response = iot_client.list_project_location_registry_devices(
  resource
)

puts "Devices:"
if response.devices && response.devices.any?
  response.devices.each { |device| puts "\t#{device.id}" }
else
  puts "\tNo device registries found in this region for your project."
end

O exemplo a seguir mostra como recuperar um dispositivo e os metadados dele de um registro de dispositivo:

C#

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

    try
    {
        var device = cloudIot.Projects.Locations.Registries.Devices.Get(name).Execute();
        Console.WriteLine("Device: ");
        Console.WriteLine($"{device.Id}");
        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}");
        Console.WriteLine($"\tState:{device.State}");
    }
    catch (Google.GoogleApiException e)
    {
        Console.WriteLine(e.Message);
        if (e.Error != null) return e.Error.Code;
        return -1;
    }
    return 0;
}

Go


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

Java

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

  final String devicePath =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryName, deviceId);

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

Node.js

// 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(
    projectId,
    cloudRegion,
    registryId,
    deviceId
  );

  // See full list of device fields: https://cloud.google.com/iot/docs/reference/cloudiot/rest/v1/projects.locations.registries.devices
  // Warning! Use snake_case field names.
  const fieldMask = {
    paths: [
      'id',
      'name',
      'num_id',
      'credentials',
      'last_heartbeat_time',
      'last_event_time',
      'last_state_time',
      'last_config_ack_time',
      'last_config_send_time',
      'blocked',
      'last_error_time',
      'last_error_status',
      'config',
      'state',
      'log_level',
      'metadata',
      'gateway_config',
    ],
  };

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

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

getDevice();

PHP

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(
    $registryId,
    $deviceId,
    $projectId,
    $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,
            $formats[$credential->getPublicKey()->getFormat()]);
        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'));
}

Python

Neste exemplo, usamos a biblioteca de cliente de APIs do Google para Python.
# 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: https://cloud.google.com/iot/docs/reference/cloudiot/rest/v1/projects.locations.registries.devices
# Warning! Use snake_case field names.
field_mask = gp_field_mask.FieldMask(
    paths=[
        "id",
        "name",
        "num_id",
        "credentials",
        "last_heartbeat_time",
        "last_event_time",
        "last_state_time",
        "last_config_ack_time",
        "last_config_send_time",
        "blocked",
        "last_error_time",
        "last_error_status",
        "config",
        "state",
        "log_level",
        "metadata",
        "gateway_config",
    ]
)

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

print("Id : {}".format(device.id))
print("Name : {}".format(device.name))
print("Credentials:")

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"
        else:
            keyformat = "UNSPECIFIED_PUBLIC_KEY_FORMAT"
        print("\tformat : {}".format(keyformat))
        print("\texpiration: {}".format(credential.expiration_time))

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

return device

Ruby

# 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 = 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
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(
  resource
)

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

O exemplo a seguir mostra como recuperar o estado do dispositivo de um registro de dispositivo:

C#

public static object GetDeviceStates(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}";

    try
    {
        Console.WriteLine("States: ");
        var res = cloudIot.Projects.Locations.Registries.Devices.States.List(name).Execute();
        res.DeviceStates.ToList().ForEach(state =>
        {
            Console.WriteLine($"\t{state.UpdateTime}: {state.BinaryData}");
        });
    }
    catch (Google.GoogleApiException e)
    {
        Console.WriteLine(e.Message);
        if (e.Error != null) return e.Error.Code;
        return -1;
    }
    return 0;
}

Go


// getDeviceStates retrieves and lists device states.
func getDeviceStates(w io.Writer, projectID string, region string, registryID 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, registryID, device)
	response, err := client.Projects.Locations.Registries.Devices.States.List(path).Do()
	if err != nil {
		return nil, err
	}

	fmt.Fprintln(w, "Successfully retrieved device states!")

	for _, state := range response.DeviceStates {
		fmt.Fprintf(w, "%s : %s\n", state.UpdateTime, state.BinaryData)
	}

	return response.DeviceStates, nil
}

Java

/** Retrieves device metadata from a registry. * */
protected static List<DeviceState> getDeviceStates(
    String deviceId, String projectId, String cloudRegion, String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

  final String devicePath =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryName, deviceId);

  System.out.println("Retrieving device states " + devicePath);

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

  return resp.getDeviceStates();
}

Node.js

// 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 listDeviceStates() {
  const devicePath = iotClient.devicePath(
    projectId,
    cloudRegion,
    registryId,
    deviceId
  );

  const [response] = await iotClient.listDeviceStates({name: devicePath});
  const states = response.deviceStates;
  if (states.length === 0) {
    console.log(`No States for device: ${deviceId}`);
  } else {
    console.log(`States for device: ${deviceId}`);
  }

  for (let i = 0; i < states.length; i++) {
    const state = states[i];
    console.log(
      'State:',
      state,
      '\nData:\n',
      state.binaryData.toString('utf8')
    );
  }
}

listDeviceStates();

PHP

use Google\Cloud\Iot\V1\DeviceManagerClient;

/**
 * Retrieve a device's state blobs.
 *
 * @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_state(
    $registryId,
    $deviceId,
    $projectId,
    $location = 'us-central1'
) {
    print('Getting device state' . PHP_EOL);

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

    $response = $deviceManager->listDeviceStates($deviceName);

    foreach ($response->getDeviceStates() as $state) {
        print('State:' . PHP_EOL);
        printf('    Data: %s' . PHP_EOL, $state->getBinaryData());
        printf('    Update Time: %s' . PHP_EOL,
            $state->getUpdateTime()->toDateTime()->format('Y-m-d H:i:s'));
    }
}

Python

Neste exemplo, usamos a biblioteca de cliente de APIs do Google para Python.
# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
# device_id = 'your-device-id'
client = iot_v1.DeviceManagerClient()
device_path = client.device_path(project_id, cloud_region, registry_id, device_id)

device = client.get_device(request={"name": device_path})
print("Last state: {}".format(device.state))

print("State history")
states = client.list_device_states(request={"name": device_path}).device_states
for state in states:
    print("State: {}".format(state))

return states

Ruby

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

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
parent   = "projects/#{project_id}/locations/#{location_id}"
resource = "#{parent}/registries/#{registry_id}/devices/#{device_id}"

# List the configurations for the provided device
result = iot_client.list_project_location_registry_device_states(
  resource
)
if result.device_states
  result.device_states.each do |state|
    puts "#{state.update_time}: #{state.binary_data}"
  end
else
  puts "No state messages"
end

Consulte Amostras de gerenciamento de dispositivos para ver mais exemplos de código.

Como excluir dispositivos e registros

É possível excluir dispositivos e registros usando o console do Google Cloud, a API ou o gcloud. Para excluir um registro, primeiro exclua todos os dispositivos dele.

Console

É possível excluir um ou mais dispositivos da lista de registros do dispositivo.

Para excluir dispositivos, faça o seguinte:

  1. Acesse a página Registros no Console do Google Cloud.

    Acessar a página Registros

  2. Clique no ID do registro do dispositivo.

  3. No menu à esquerda, clique em Dispositivos.

  4. Selecione os dispositivos que você quer excluir e clique em Excluir.

  5. Confirme que você quer excluir os dispositivos selecionados e clique em Excluir.

gcloud

Para excluir um dispositivo, execute o comando gcloud iot devices delete:

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

Para excluir um registro, execute o comando gcloud iot registries delete:

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

API

Use os seguintes métodos para excluir dispositivos e registros:

O exemplo a seguir mostra como excluir um dispositivo de um registro:

C#

public static object DeleteDevice(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}";

    try
    {
        var res = cloudIot.Projects.Locations.Registries.Devices.Delete(name).Execute();
        Console.WriteLine($"Removed device: {deviceId}");
    }
    catch (Google.GoogleApiException e)
    {
        Console.WriteLine(e.Message);
        if (e.Error != null) return e.Error.Code;
        return -1;
    }
    return 0;
}

Go


// deleteDevice deletes a device from a registry.
func deleteDevice(w io.Writer, projectID string, region string, registryID 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, registryID, deviceID)
	response, err := client.Projects.Locations.Registries.Devices.Delete(path).Do()
	if err != nil {
		return nil, err
	}

	fmt.Fprintf(w, "Deleted device: %s\n", deviceID)

	return response, nil
}

Java

/** Delete the given device from the registry. */
protected static void deleteDevice(
    String deviceId, String projectId, String cloudRegion, String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

  final String devicePath =
      String.format(
          "projects/%s/locations/%s/registries/%s/devices/%s",
          projectId, cloudRegion, registryName, deviceId);

  System.out.println("Deleting device " + devicePath);
  service.projects().locations().registries().devices().delete(devicePath).execute();
}

Node.js

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

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

async function deleteDevice() {
  // Construct request
  const devPath = iotClient.devicePath(
    projectId,
    cloudRegion,
    registryId,
    deviceId
  );

  const [responses] = await iotClient.deleteDevice({name: devPath});
  console.log('Successfully deleted device', responses);
}

deleteDevice();

PHP

use Google\Cloud\Iot\V1\DeviceManagerClient;

/**
 * Delete 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 delete_device(
    $registryId,
    $deviceId,
    $projectId,
    $location = 'us-central1'
) {
    print('Deleting Device' . PHP_EOL);

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

    $response = $deviceManager->deleteDevice($deviceName);

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

Python

Neste exemplo, usamos a biblioteca de cliente de APIs do Google para Python.
# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
# device_id = 'your-device-id'
print("Delete device")
client = iot_v1.DeviceManagerClient()

device_path = client.device_path(project_id, cloud_region, registry_id, device_id)

return client.delete_device(request={"name": device_path})

Ruby

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

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
parent = "projects/#{project_id}/locations/#{location_id}"
device_path = "#{parent}/registries/#{registry_id}/devices/#{device_id}"

# Delete the device
result = iot_client.delete_project_location_registry_device(
  device_path
)

puts "Deleted device."

Veja na amostra a seguir como excluir um registro:

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. */
protected static void deleteRegistry(String cloudRegion, String projectId, String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredentials credential =
      GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
  HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
  final CloudIot service =
      new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
          .setApplicationName(APP_NAME)
          .build();

  final String registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

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

Node.js

// Client retrieved in callback
// const cloudRegion = 'us-central1';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';

const iot = require('@google-cloud/iot');

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

async function deleteDeviceRegistry() {
  // Construct request
  const registryName = iotClient.registryPath(
    projectId,
    cloudRegion,
    registryId
  );

  const [response] = await iotClient.deleteDeviceRegistry({
    name: registryName,
  });
  console.log(response);
  console.log('Successfully deleted registry');
}

deleteDeviceRegistry();

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

Neste exemplo, usamos a biblioteca de cliente de APIs do Google para Python.
# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
print("Delete registry")

client = iot_v1.DeviceManagerClient()
registry_path = client.registry_path(project_id, cloud_region, registry_id)

try:
    client.delete_device_registry(request={"name": registry_path})
    print("Deleted registry")
    return "Registry deleted"
except HttpError:
    print("Error, registry not deleted")
    raise

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

Consulte as Amostras de gerenciamento de registros e as Amostras de gerenciamento de dispositivos para mais exemplos de código.

A seguir