Google Cloud IoT Core verrà ritirato il 16 agosto 2023. Per saperne di più, contatta il team dedicato al tuo account Google Cloud.

Impostazione della configurazione di un dispositivo

Mantieni tutto organizzato con le raccolte Salva e classifica i contenuti in base alle tue preferenze.

Invia i dati di configurazione a un dispositivo.

Per saperne di più

Per la documentazione dettagliata che include questo esempio di codice, vedi quanto segue:

Esempio di codice

Go

Per saperne di più, consulta la documentazione di riferimento per l'API Cloud IoT Core Go.


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

Per saperne di più, consulta la documentazione di riferimento per l'API Cloud IoT Core Java.

/** 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 = 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);

  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

Per saperne di più, consulta la documentazione di riferimento per l'API Cloud IoT Core Node.js.

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

Per saperne di più, consulta la documentazione di riferimento per l'API Cloud IoT Core PHP.

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

Per saperne di più, consulta la documentazione di riferimento per l'API Cloud IoT Core Python.

# 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

Per saperne di più, consulta la documentazione di riferimento per l'API 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 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!"

Passaggi successivi

Per cercare e filtrare esempi di codice per altri prodotti Google Cloud, consulta il browser di esempio Google Cloud.