Google Cloud IoT Core wird am 16. August 2023 eingestellt. Weitere Informationen erhalten Sie von Ihrem Google Cloud-Account-Management-Team.

Gerätekonfigurationen abrufen

Gerätekonfigurationen abrufen und auflisten.

Weitere Informationen

Eine ausführliche Dokumentation, die dieses Codebeispiel enthält, finden Sie hier:

Codebeispiel

Go

Weitere Informationen finden Sie in der Cloud IoT Core Go-Referenzdokumentation.

Für die Authentifizierung bei Cloud IoT Core richten Sie Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


// getDeviceConfigs retrieves and lists device configurations.
func getDeviceConfigs(w io.Writer, projectID string, region string, registryID string, device string) ([]*cloudiot.DeviceConfig, error) {
	// Authorize the client using Application Default Credentials.
	// See https://g.co/dv/identity/protocols/application-default-credentials
	ctx := context.Background()
	httpClient, err := google.DefaultClient(ctx, cloudiot.CloudPlatformScope)
	if err != nil {
		return nil, err
	}
	client, err := cloudiot.New(httpClient)
	if err != nil {
		return nil, err
	}

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

	for _, config := range response.DeviceConfigs {
		fmt.Fprintf(w, "%d : %s\n", config.Version, config.BinaryData)
	}

	return response.DeviceConfigs, nil
}

Java

Weitere Informationen finden Sie in der Cloud IoT Core Java-Referenzdokumentation.

Für die Authentifizierung bei Cloud IoT Core richten Sie Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

/** List all of the configs for the given device. */
protected static void listDeviceConfigs(
    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("Listing device configs for " + devicePath);
  List<DeviceConfig> deviceConfigs =
      service
          .projects()
          .locations()
          .registries()
          .devices()
          .configVersions()
          .list(devicePath)
          .execute()
          .getDeviceConfigs();

  for (DeviceConfig config : deviceConfigs) {
    System.out.println("Config version: " + config.getVersion());
    System.out.println("Contents: " + config.getBinaryData());
    System.out.println();
  }
}

Node.js

Weitere Informationen finden Sie in der Cloud IoT Core Node.js-Referenzdokumentation.

Für die Authentifizierung bei Cloud IoT Core richten Sie Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

  const [response] = await iotClient.listDeviceConfigVersions({
    name: devicePath,
  });
  const configs = response.deviceConfigs;

  if (configs.length === 0) {
    console.log(`No configs for device: ${deviceId}`);
  } else {
    console.log('Configs:');
  }

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

listDeviceConfigVersions();

PHP

Weitere Informationen finden Sie in der Cloud IoT Core PHP-Referenzdokumentation.

Für die Authentifizierung bei Cloud IoT Core richten Sie Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

use Google\Cloud\Iot\V1\DeviceManagerClient;

/**
 * Lists versions of a device config in descending order (newest first).
 *
 * @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_configs(
    $registryId,
    $deviceId,
    $projectId,
    $location = 'us-central1'
) {
    print('Getting device configs' . PHP_EOL);

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

    $configs = $deviceManager->listDeviceConfigVersions($deviceName);

    foreach ($configs->getDeviceConfigs() as $config) {
        print('Config:' . PHP_EOL);
        printf('    Version: %s' . PHP_EOL, $config->getVersion());
        printf('    Data: %s' . PHP_EOL, $config->getBinaryData());
        printf('    Update Time: %s' . PHP_EOL,
            $config->getCloudUpdateTime()->toDateTime()->format('Y-m-d H:i:s'));
    }
}

Python

Weitere Informationen finden Sie in der Cloud IoT Core Python-Referenzdokumentation.

Für die Authentifizierung bei Cloud IoT Core richten Sie Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

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

configs = client.list_device_config_versions(request={"name": device_path})

for config in configs.device_configs:
    print(
        "version: {}\n\tcloudUpdateTime: {}\n\t data: {}".format(
            config.version, config.cloud_update_time, config.binary_data
        )
    )

return configs

Ruby

Weitere Informationen finden Sie in der Cloud IoT Core Ruby-Referenzdokumentation.

Für die Authentifizierung bei Cloud IoT Core richten Sie Standardanmeldedaten für Anwendungen ein. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

# 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 configurations 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
configs = iot_client.list_project_location_registry_device_config_versions(
  resource
)
configs.device_configs.each do |config|
  puts "Version [#{config.version}]: #{config.binary_data}"
end

Nächste Schritte

Informationen zum Suchen und Filtern von Codebeispielen für andere Google Cloud-Produkte finden Sie unter Google Cloud-Beispielbrowser.