Google Cloud IoT Core se retirará el 16 de agosto de 2023. Comunícate con el equipo de cuentas de Google Cloud para obtener más información.

Obtener un dispositivo

Organiza tus páginas con colecciones Guarda y categoriza el contenido según tus preferencias.

Recupera un dispositivo específico e imprime los detalles.

Explora más

Para obtener documentación en la que se incluye esta muestra de código, consulta lo siguiente:

Muestra de código

Go

Si quieres obtener más información, consulta la documentación de referencia de la API de Cloud IoT Core 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

Si quieres obtener más información, consulta la documentación de referencia de la API de Cloud IoT Core 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 = JacksonFactory.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

Si quieres obtener más información, consulta la documentación de referencia de la API de Cloud IoT Core 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

Si quieres obtener más información, consulta la documentación de referencia de la API de Cloud IoT Core 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

Si quieres obtener más información, consulta la documentación de referencia de la API de Cloud IoT Core 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

Si quieres obtener más información, consulta la documentación de referencia de la API de Cloud IoT Core 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

¿Qué sigue?

Para buscar y filtrar muestras de código en otros productos de Google Cloud, consulta el navegador de muestra de Google Cloud.