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

Associazione di un dispositivo

Associare un dispositivo a un gateway.

Per saperne di più

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

Esempio di codice

Go

Per maggiori informazioni, consulta la documentazione di riferimento per le API Cloud IoT Core Go.

Per eseguire l'autenticazione in Cloud IoT Core, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.


// bindDeviceToGateway creates an association between an existing device and gateway.
func bindDeviceToGateway(w io.Writer, projectID string, region string, registryID string, gatewayID string, deviceID string) (*cloudiot.BindDeviceToGatewayResponse, 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)
	bindRequest := &cloudiot.BindDeviceToGatewayRequest{
		DeviceId:  deviceID,
		GatewayId: gatewayID,
	}

	response, err := client.Projects.Locations.Registries.BindDeviceToGateway(parent, bindRequest).Do()

	if err != nil {
		return nil, fmt.Errorf("BindDeviceToGateway: %w", err)
	}

	if response.HTTPStatusCode/100 != 2 {
		return nil, fmt.Errorf("BindDeviceToGateway: HTTP status code not 2xx\n %v", response)
	}

	fmt.Fprintf(w, "Bound %s to %s", deviceID, gatewayID)

	return response, nil
}

Java

Per maggiori informazioni, consulta la documentazione di riferimento per le API Cloud IoT Core Java.

Per eseguire l'autenticazione in Cloud IoT Core, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

createDevice(projectId, cloudRegion, registryName, deviceId);

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

BindDeviceToGatewayRequest request = new BindDeviceToGatewayRequest();
request.setDeviceId(deviceId);
request.setGatewayId(gatewayId);

BindDeviceToGatewayResponse response =
    service
        .projects()
        .locations()
        .registries()
        .bindDeviceToGateway(registryPath, request)
        .execute();

System.out.println(String.format("Device bound: %s", response.toPrettyString()));

Node.js

Per maggiori informazioni, consulta la documentazione di riferimento per le API Cloud IoT Core Node.js.

Per eseguire l'autenticazione in Cloud IoT Core, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

// const cloudRegion = 'us-central1';
// const deviceId = 'my-unauth-device';
// const gatewayId = 'my-gateway';
// 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 bindDeviceToGateway() {
  // Construct request
  const regPath = iotClient.registryPath(projectId, cloudRegion, registryId);

  const bindRequest = {
    parent: regPath,
    deviceId: deviceId,
    gatewayId: gatewayId,
  };

  console.log(`Binding device: ${deviceId}`);

  await iotClient.bindDeviceToGateway(bindRequest);

  console.log(`Bound ${deviceId} to`, gatewayId);
}

bindDeviceToGateway();

PHP

Per maggiori informazioni, consulta la documentazione di riferimento per le API Cloud IoT Core PHP.

Per eseguire l'autenticazione in Cloud IoT Core, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

use Google\Cloud\Iot\V1\DeviceManagerClient;

/**
 * Binds a device to a gateway.
 *
 * @param string $registryId IOT Device Registry ID
 * @param string $deviceId the device ID to bind
 * @param string $gatewayId the ID for the gateway to bind to
 * @param string $projectId Google Cloud project ID
 * @param string $location Google Cloud region
 */
function bind_device_to_gateway(
    $registryId,
    $gatewayId,
    $deviceId,
    $projectId,
    $location = 'us-central1'
) {
    print('Binding Device to Gateway' . PHP_EOL);

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

    $result = $deviceManager->bindDeviceToGateway($registryName, $gatewayId, $deviceId);

    print('Device bound');
}

Python

Per maggiori informazioni, consulta la documentazione di riferimento per le API Cloud IoT Core Python.

Per eseguire l'autenticazione in Cloud IoT Core, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
# device_id = 'your-device-id'
# gateway_id = 'your-gateway-id'
client = iot_v1.DeviceManagerClient()

create_device(
    service_account_json, project_id, cloud_region, registry_id, device_id
)

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

res = client.bind_device_to_gateway(
    request={"parent": parent, "gateway_id": gateway_id, "device_id": device_id}
)

print("Device Bound! {}".format(res))

Ruby

Per maggiori informazioni, consulta la documentazione di riferimento per le API Cloud IoT Core Ruby.

Per eseguire l'autenticazione in Cloud IoT Core, configura le Credenziali predefinite dell'applicazione. Per saperne di più, consulta Configurare l'autenticazione per un ambiente di sviluppo locale.

# 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"
# gateway_id  = "The Gateway to bind to"
# device_id   = "The identifier of the device to bind"

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

bind_req = Google::Apis::CloudiotV1::BindDeviceToGatewayRequest.new
bind_req.gateway_id = gateway_id
bind_req.device_id = device_id

res = iot_client.bind_registry_device_to_gateway parent, bind_req
puts "Device bound"

Passaggi successivi

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