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

Gerätekonfiguration festlegen

Konfigurationsdaten an ein Gerät senden.

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.


// setConfig sends a configuration change to a device.
func setConfig(w io.Writer, projectID string, region string, registryID string, deviceID string, configData 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
	}

	req := cloudiot.ModifyCloudToDeviceConfigRequest{
		BinaryData: b64.StdEncoding.EncodeToString([]byte(configData)),
	}

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

	fmt.Fprintf(w, "Config set!\nVersion now: %d\n", response.Version)

	return response, 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.

/** Set a device configuration to the specified data (string, JSON) and version (0 for latest). */
protected static void setDeviceConfiguration(
    String deviceId,
    String projectId,
    String cloudRegion,
    String registryName,
    String data,
    long version)
    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);

  ModifyCloudToDeviceConfigRequest req = new ModifyCloudToDeviceConfigRequest();
  req.setVersionToUpdate(version);

  // Data sent through the wire has to be base64 encoded.
  Base64.Encoder encoder = Base64.getEncoder();
  String encPayload = encoder.encodeToString(data.getBytes(StandardCharsets.UTF_8.name()));
  req.setBinaryData(encPayload);

  DeviceConfig config =
      service
          .projects()
          .locations()
          .registries()
          .devices()
          .modifyCloudToDeviceConfig(devicePath, req)
          .execute();

  System.out.println("Updated: " + config.getVersion());
}

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 data = 'test-data';
// const version = 0;
const iot = require('@google-cloud/iot');
const iotClient = new iot.v1.DeviceManagerClient({
  // optional auth parameters.
});

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

  const binaryData = Buffer.from(data).toString('base64');
  const request = {
    name: formattedName,
    versionToUpdate: version,
    binaryData: binaryData,
  };

  const [response] = await iotClient.modifyCloudToDeviceConfig(request);
  console.log('Success:', response);
}

modifyCloudToDeviceConfig();

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;

/**
 * Set a device's configuration.
 *
 * @param string $registryId IOT Device Registry ID
 * @param string $deviceId IOT Device ID
 * @param string $config Configuration sent to a device
 * @param string $version Version number for setting device configuration
 * @param string $projectId Google Cloud project ID
 * @param string $location (Optional) Google Cloud region
 */
function set_device_config(
    $registryId,
    $deviceId,
    $config,
    $version,
    $projectId,
    $location = 'us-central1'
) {
    print('Set device configuration' . PHP_EOL);

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

    $config = $deviceManager->modifyCloudToDeviceConfig($deviceName, $config, [
        'versionToUpdate' => $version,
    ]);

    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'
# version = '0'
# config= 'your-config-data'
print("Set device configuration")
client = iot_v1.DeviceManagerClient()
device_path = client.device_path(project_id, cloud_region, registry_id, device_id)

data = config.encode("utf-8")

return client.modify_cloud_to_device_config(
    request={"name": device_path, "binary_data": data, "version_to_update": version}
)

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 set configurations on"
# data        = "The data, e.g. {fan: on} to send to the device"

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

config = Cloudiot::DeviceConfig.new
config.binary_data = data

# Set configuration for the provided device
iot_client.modify_cloud_to_device_config resource, config
puts "Configuration updated!"

Nächste Schritte

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