Créer des passerelles

Cette page explique comment créer, configurer et gérer des passerelles.

Créer ou modifier une passerelle

Vous pouvez créer une passerelle ou en modifier une existante à l'aide de Google Cloud Console ou de gcloud. Une fois que vous avez créé une passerelle, vous ne pouvez pas la transformer en appareil autre qu'une passerelle. Avant de suivre la procédure décrite dans cette section, assurez-vous d'avoir créé un registre et une paire de clés d'appareil.

Console

Pour créer une nouvelle passerelle, procédez comme suit :

  1. Accédez à la page Registres de Google Cloud Console.

    Accéder à la page Registres

  2. Cliquez sur l'ID du registre de la passerelle.
  3. Sur la page Détails du registre, cliquez sur Passerelles, puis sur Ajouter une passerelle pour en créer une.
  4. Saisissez un ID de passerelle qui décrit brièvement la passerelle ou vous permet de l'identifier. (Vous ne pourrez pas modifier ce champ ultérieurement.) Pour en savoir plus sur les exigences concernant la taille et le nom de la passerelle, consultez Caractères autorisés et tailles requises.
  5. Dans la section Communications de la passerelle, sélectionnez Autoriser ou Bloquer. Cette option vous permet de bloquer la communication lorsque cela est nécessaire, par exemple lorsqu'une passerelle ou un ou plusieurs appareils qui y sont liés ne fonctionnent pas correctement. Dans la plupart des cas, vous souhaiterez autoriser la communication lors de la création de la passerelle, Lorsqu'une passerelle est bloquée, tous les appareils qui lui sont associés ne peuvent pas communiquer avec Cloud IoT Core.
  6. Sélectionnez le format de clé publique correspondant à la paire de clés pour cette passerelle. Collez le certificat ou la clé dans le champ Valeur de la clé publique. Vous pouvez également définir une date d'expiration pour la clé.
  7. Sélectionnez la méthode d'authentification à utiliser pour les appareils associés à la passerelle.
  8. Utilisez les champs Clé et Valeur pour ajouter des métadonnées de passerelle facultatives, telles qu'un numéro de série. Pour en savoir plus sur les exigences concernant la taille et le nom des clés-valeurs de métadonnées, consultez Exigences relatives aux caractères et à la taille autorisés.
  9. Sous Stackdriver Logging, sélectionnez un niveau de journal d'activité pour la passerelle. Le niveau de journalisation de la passerelle remplace celui de la registre.
  10. Cliquez sur Créer pour créer la passerelle ou sur Mettre à jour pour enregistrer les modifications apportées à une passerelle existante.

Pour modifier une passerelle existante, procédez comme suit :

  1. Accédez à la page Registres de Google Cloud Console.

    Accéder à la page Registres

  2. Cliquez sur l'ID du registre de la passerelle.
  3. Cliquez sur Détails du registre.
  4. Cliquez sur Passerelles.
  5. Cliquez sur l'ID de la passerelle que vous souhaitez modifier.
  6. Cliquez sur Modifier en haut de la page.

Pour ajouter une clé à une passerelle existante, cliquez sur Ajouter une clé publique sur la page Détails de l'appareil.

gcloud

Pour créer une passerelle, exécutez la commande gcloud iot devices create. Vous pouvez créer une passerelle avec les identifiants RS256 ou ES256.

Pour créer une passerelle avec des identifiants RS256, exécutez la commande suivante :

gcloud iot devices create
    --device-type=gateway \
    --project=PROJECT_ID \
    --region=REGION \
    --registry=REGISTRY_ID \
    --public-key path=rsa_cert.pem,type=rs256 \
    --auth-method={ASSOCIATION_ONLY|AUTH_TOKEN_ONLY|AUTH_TOKEN_AND_ASSOCIATION}

Pour créer une passerelle avec les identifiants ES256, exécutez la commande suivante :

gcloud iot devices create
    --device-type=gateway \
    --project=PROJECT_ID \
    --region=REGION \
    --registry=REGISTRY_ID \
    --public-key path=ec_public.pem,type=es256 \
    --auth-method={ASSOCIATION_ONLY|AUTH_TOKEN_ONLY|AUTH_TOKEN_AND_ASSOCIATION}

Pour modifier une passerelle, exécutez la commande gcloud iot devices update. Vous pouvez modifier différentes propriétés de la passerelle, mais vous ne pouvez pas le modifier en tant que passerelle.

gcloud iot devices update DEVICE_ID \
    --project=PROJECT_ID \
    --region=REGION \
    --registry=REGISTRY_ID \
    --auth-method={ASSOCIATION_ONLY|AUTH_TOKEN_ONLY|AUTH_TOKEN_AND_ASSOCIATION}

API

Utilisez les méthodes suivantes pour créer ou modifier une passerelle :

C#

public static object CreateGateway(string projectId, string cloudRegion,
    string registryName, string gatewayId, string publicKeyFilePath,
    string algorithm)
{
    var cloudIot = CreateAuthorizedClient();
    var registryPath = $"projects/{projectId}/locations/{cloudRegion}"
        + $"/registries/{registryName}";
    Console.WriteLine("Creating gateway with id: {0}", gatewayId);

    Device body = new Device()
    {
        Id = gatewayId,
        GatewayConfig = new GatewayConfig()
        {
            GatewayType = "GATEWAY",
            GatewayAuthMethod = "ASSOCIATION_ONLY"
        },
        Credentials =
        new List<DeviceCredential>()
        {
            new DeviceCredential()
            {
                PublicKey = new PublicKeyCredential()
                {
                    Key = File.ReadAllText(publicKeyFilePath),
                    Format = (algorithm == "ES256" ?
                        "ES256_PEM" : "RSA_X509_PEM")
                },
            }
        }
    };

    Device createdDevice = cloudIot.Projects.Locations.Registries
        .Devices.Create(body, registryPath).Execute();
    Console.WriteLine("Created gateway: {0}", createdDevice.ToString());
    return 0;
}

Go


// createGateway creates a new IoT Core gateway with a given id, public key, and auth method.
// gatewayAuthMethod can be one of: ASSOCIATION_ONLY, DEVICE_AUTH_TOKEN_ONLY, ASSOCIATION_AND_DEVICE_AUTH_TOKEN.
// https://cloud.google.com/iot/docs/reference/cloudiot/rest/v1/projects.locations.registries.devices#gatewayauthmethod
func createGateway(w io.Writer, projectID string, region string, registryID string, gatewayID string, gatewayAuthMethod string, publicKeyPath 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
	}

	keyBytes, err := ioutil.ReadFile(publicKeyPath)
	if err != nil {
		return nil, err
	}

	gateway := &cloudiot.Device{
		Id: gatewayID,
		Credentials: []*cloudiot.DeviceCredential{
			{
				PublicKey: &cloudiot.PublicKeyCredential{
					Format: "RSA_X509_PEM",
					Key:    string(keyBytes),
				},
			},
		},
		GatewayConfig: &cloudiot.GatewayConfig{
			GatewayType:       "GATEWAY",
			GatewayAuthMethod: gatewayAuthMethod,
		},
	}

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

	fmt.Fprintln(w, "Successfully created gateway:", gatewayID)

	return response, nil
}

Java

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 registryPath =
    String.format(
        "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

System.out.println("Creating gateway with id: " + gatewayId);
Device device = new Device();
device.setId(gatewayId);

GatewayConfig gwConfig = new GatewayConfig();
gwConfig.setGatewayType("GATEWAY");
gwConfig.setGatewayAuthMethod("ASSOCIATION_ONLY");

String keyFormat = "RSA_X509_PEM";
if ("ES256".equals(algorithm)) {
  keyFormat = "ES256_PEM";
}

PublicKeyCredential publicKeyCredential = new PublicKeyCredential();

byte[] keyBytes = java.nio.file.Files.readAllBytes(Paths.get(certificateFilePath));
publicKeyCredential.setKey(new String(keyBytes, StandardCharsets.US_ASCII));
publicKeyCredential.setFormat(keyFormat);
DeviceCredential deviceCredential = new DeviceCredential();
deviceCredential.setPublicKey(publicKeyCredential);

device.setGatewayConfig(gwConfig);
device.setCredentials(Collections.singletonList(deviceCredential));
Device createdDevice =
    service
        .projects()
        .locations()
        .registries()
        .devices()
        .create(registryPath, device)
        .execute();

System.out.println("Created gateway: " + createdDevice.toPrettyString());

Node.js

// const cloudRegion = 'us-central1';
// const deviceId = 'my-unauth-device';
// const gatewayId = 'my-gateway';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
// const gatewayAuthMethod = 'ASSOCIATION_ONLY';
const iot = require('@google-cloud/iot');

const iotClient = new iot.v1.DeviceManagerClient({
  // optional auth parameters.
});

async function createDevice() {
  // Construct request
  const regPath = iotClient.registryPath(projectId, cloudRegion, registryId);

  console.log('Creating gateway:', gatewayId);

  let credentials = [];

  // if public key format and path are specified, use those
  if (publicKeyFormat && publicKeyFile) {
    credentials = [
      {
        publicKey: {
          format: publicKeyFormat,
          key: readFileSync(publicKeyFile).toString(),
        },
      },
    ];
  }

  const device = {
    id: gatewayId,
    credentials: credentials,
    gatewayConfig: {
      gatewayType: 'GATEWAY',
      gatewayAuthMethod: gatewayAuthMethod,
    },
  };

  const request = {
    parent: regPath,
    device,
  };

  const [response] = await iotClient.createDevice(request);
  console.log('Created device:', response);
}

createDevice();

Python

# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
# device_id = 'your-device-id'
# gateway_id = 'your-gateway-id'
# certificate_file = 'path/to/certificate.pem'
# algorithm = 'ES256'
# Check that the gateway doesn't already exist
exists = False
client = iot_v1.DeviceManagerClient()

parent = client.registry_path(project_id, cloud_region, registry_id)
devices = list(client.list_devices(request={"parent": parent}))

for device in devices:
    if device.id == gateway_id:
        exists = True
    print(
        "Device: {} : {} : {} : {}".format(
            device.id, device.num_id, device.config, device.gateway_config
        )
    )

with io.open(certificate_file) as f:
    certificate = f.read()

if algorithm == "ES256":
    certificate_format = iot_v1.PublicKeyFormat.ES256_PEM
else:
    certificate_format = iot_v1.PublicKeyFormat.RSA_X509_PEM

# TODO: Auth type
device_template = {
    "id": gateway_id,
    "credentials": [
        {"public_key": {"format": certificate_format, "key": certificate}}
    ],
    "gateway_config": {
        "gateway_type": iot_v1.GatewayType.GATEWAY,
        "gateway_auth_method": iot_v1.GatewayAuthMethod.ASSOCIATION_ONLY,
    },
}

if not exists:
    res = client.create_device(
        request={"parent": parent, "device": device_template}
    )
    print("Created Gateway {}".format(res))
else:
    print("Gateway exists, skipping")

Ruby

# project_id  = "Your Google Cloud project ID"
# location_id = "The Cloud region the registry is located in"
# registry_id = "The registry to create a gateway in"
# gateway_id  = "The identifier of the gateway to create"
# cert_path   = "The path to the certificate"
# alg         = "ES256 || RS256"

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

device = Cloudiot::Device.new
device.id = gateway_id

certificate_format = if alg == "ES256"
                       "ES256_PEM"
                     else
                       "RSA_X509_PEM"
                     end

pubkey = Google::Apis::CloudiotV1::PublicKeyCredential.new
pubkey.key = File.read cert_path
pubkey.format = certificate_format

cred = Google::Apis::CloudiotV1::DeviceCredential.new
cred.public_key = pubkey

device.credentials = [cred]

gateway_config = Google::Apis::CloudiotV1::GatewayConfig.new
gateway_config.gateway_type = "GATEWAY"
gateway_config.gateway_auth_method = "ASSOCIATION_ONLY"

device.gateway_config = gateway_config

# Create the Gateway
device = iot_client.create_project_location_registry_device parent, device

puts "Gateway: #{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}"

Pour savoir comment créer les appareils que vous utiliserez avec la passerelle, consultez Créer ou modifier un appareil.

Configurer la passerelle et obtenir l'état

Avec Cloud IoT Core, vous pouvez contrôler une passerelle en modifiant sa configuration, comme vous le feriez avec n'importe quel autre appareil. Consultez la section Configurer des appareils pour savoir comment configurer une passerelle via le pont MQTT ou HTTP.

Une fois qu'une configuration a été appliquée à une passerelle, celle-ci peut signaler son état à Cloud IoT Core. Vous pouvez comparer l'état de la passerelle et sa configuration la plus récente pour vous assurer qu'elle fonctionne comme prévu.

Associer ou dissocier un appareil

Vous pouvez authentifier des appareils autres que des passerelles auprès de Cloud IoT Core en les associant à la passerelle. Une liaison crée une association entre les appareils et la passerelle que Cloud IoT Core vérifie pour authentifier les appareils.

Console

  1. Accédez à la page Registres de Google Cloud Console.

    Accéder à la page Registres

  2. Cliquez sur l'ID du registre de la passerelle.
  3. Cliquez sur Passerelles, puis sur l'ID de la passerelle.
  4. Sur la page Détails de la passerelle, cliquez sur Appareils associés.
  5. Cliquez sur Associer à l'appareil.
  6. Sélectionnez les appareils que vous souhaitez associer à la passerelle, puis cliquez sur Lier.
  7. Pour annuler la liaison d'un appareil, sélectionnez-le sur la page Détails de la passerelle et cliquez sur Annuler la liaison de l'appareil, puis à nouveau sur Annuler la liaison pour confirmer l'opération.

gcloud

Pour lier un appareil à une passerelle, exécutez la commande gcloud iot devices gateways bind :

gcloud iot devices gateways bind --gateway=GATEWAY_ID \
    --device=DEVICE_ID \
    --project=PROJECT_ID \
    --device-region=DEVICE_REGION \
    --device-registry=DEVICE_REGISTRY \
    --gateway-region=GATEWAY_REGION \
    --gateway-registry=GATEWAY_REGISTRY

Pour annuler la liaison d'un appareil à une passerelle, exécutez la commande gcloud iot devices gateways unbind :

gcloud iot devices gateways unbind --gateway=GATEWAY_ID \
    --device=DEVICE_ID \
    --project=PROJECT_ID \
    --device-region=DEVICE_REGION \
    --device-registry=DEVICE_REGISTRY \
    --gateway-region=GATEWAY_REGION \
    --gateway-registry=GATEWAY_REGISTRY

API

Utilisez les méthodes suivantes pour lier un appareil à une passerelle ou annuler sa liaison :

C#

public static object BindDeviceToGateway(string projectId, string cloudRegion,
    string registryName, string deviceId, string gatewayId)
{
    CreateDevice(projectId, cloudRegion, registryName, deviceId);
    var cloudIot = CreateAuthorizedClient();
    var registryPath = $"projects/{projectId}" +
        $"/locations/{cloudRegion}" +
        $"/registries/{registryName}";
    BindDeviceToGatewayRequest req = new BindDeviceToGatewayRequest
    {
        DeviceId = deviceId,
        GatewayId = gatewayId
    };

    var res = cloudIot
        .Projects
        .Locations
        .Registries
        .BindDeviceToGateway(req, registryPath)
        .Execute();
    Console.WriteLine("Device bound: {0}", res.ToString());

    return 0;
}

Go


// 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: %v", 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

createDevice(projectId, cloudRegion, registryName, deviceId);

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

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

Python

# 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

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

Répertorier tous les appareils liés à une passerelle

Console

  1. Accédez à la page Registres de Google Cloud Console.

    Accéder à la page Registres

  2. Cliquez sur l'ID du registre de la passerelle.
  3. Cliquez sur Passerelles, puis sur l'ID de la passerelle.
  4. Sur la page Détails de la passerelle, cliquez sur Appareils associés.

gcloud

Pour répertorier toutes les associations entre une passerelle et ses appareils, exécutez la commande gcloud iot devices gateways list-bound-devices :

gcloud iot devices gateways list-bound-devices --gateway=GATEWAY_ID \
    --registry=REGISTRY \
    --region=REGION \
    --project=PROJECT_ID

API

Utilisez la méthode list des appareils et spécifiez un ID de passerelle pour répertorier tous les appareils liés à la passerelle.

C#

public static object ListDevicesForGateways(string projectId,
 string cloudRegion, string registryName, string gatewayId)
{
    var cloudIot = CreateAuthorizedClient();
    var gatewayPath = $"projects/{projectId}/locations/{cloudRegion}" +
        $"/registries/{registryName}/devices/{gatewayId}";
    var registryPath = $"projects/{projectId}/locations/{cloudRegion}" +
        $"/registries/{registryName}";
    var req = cloudIot.Projects.Locations.Registries.Devices.List(registryPath);
    req.GatewayListOptionsAssociationsGatewayId = gatewayId;
    var devices = req.Execute().Devices;

    if (devices != null)
    {
        Console.WriteLine("Found {0} devices", devices.Count);
        foreach (var device in devices)
        {
            Console.WriteLine("ID: {0}", device.Id);
        }
    }
    else
    {
        Console.WriteLine("Gateway has no bound devices.");
    }

    return 0;
}

Go


// listDevicesForGateway lists the devices that are bound to a gateway.
func listDevicesForGateway(w io.Writer, projectID string, region string, registryID, gatewayID 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
	}

	parent := fmt.Sprintf("projects/%s/locations/%s/registries/%s", projectID, region, registryID)
	response, err := client.Projects.Locations.Registries.Devices.List(parent).GatewayListOptionsAssociationsGatewayId(gatewayID).Do()

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

	if len(response.Devices) == 0 {
		fmt.Fprintln(w, "\tNo devices found")
		return response.Devices, nil
	}

	fmt.Fprintf(w, "Devices for %s:\n", gatewayID)
	for _, gateway := range response.Devices {
		fmt.Fprintf(w, "\t%s\n", gateway.Id)
	}

	return response.Devices, nil
}

Java

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 registryPath =
    String.format(
        "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

List<Device> deviceNumIds =
    service
        .projects()
        .locations()
        .registries()
        .devices()
        .list(registryPath)
        .setGatewayListOptionsAssociationsGatewayId(gatewayId)
        .execute()
        .getDevices();

if (deviceNumIds != null) {
  System.out.println("Found " + deviceNumIds.size() + " devices");
  for (Device device : deviceNumIds) {
    System.out.println(String.format("ID: %s", device.getId()));
  }
} else {
  System.out.println("Gateway has no bound devices.");
}

Node.js

// const cloudRegion = 'us-central1';
// 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 listDevices() {
  // Construct request
  const parentName = iotClient.registryPath(
    projectId,
    cloudRegion,
    registryId
  );
  const [response] = await iotClient.listDevices({
    parent: parentName,
    gatewayListOptions: {associationsGatewayId: gatewayId},
  });
  const devices = response;

  if (devices.length > 0) {
    console.log('Current devices bound to gateway: ', gatewayId);
  } else {
    console.log('No devices bound to this gateway.');
  }

  for (let i = 0; i < devices.length; i++) {
    const device = devices[i];
    console.log(`\tDevice: ${device.numId}: ${device.id}`);
  }
}

listDevices();

Python

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

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

devices = list(
    client.list_devices(
        request={
            "parent": path,
            "gateway_list_options": {"associations_gateway_id": gateway_id},
        }
    )
)

found = False
for device in devices:
    found = True
    print("Device: {} : {}".format(device.num_id, device.id))

if not found:
    print("No devices bound to gateway {}".format(gateway_id))

Ruby

# project_id  = "Your Google Cloud project ID"
# location_id = "The Cloud region for the registry"
# registry_id = "The registry to list gateway-bound devices in"
# gateway_id = "The gateway to list devices on"

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
resource = "projects/#{project_id}/locations/#{location_id}/registries/#{registry_id}"

# List the devices in the provided region
response = iot_client.list_project_location_registry_devices(
  resource, gateway_list_options_associations_gateway_id: gateway_id.to_s
)

puts "Devices:"
if response.devices && response.devices.any?
  response.devices.each { |device| puts "\t#{device.id}" }
else
  puts "\tNo device registries found in this region for your project."
end

Répertorier toutes les passerelles dans un registre

Console

  1. Accédez à la page Registres de Google Cloud Console.

    Accéder à la page Registres

  2. Cliquez sur l'ID du registre de la passerelle.
  3. Sur la page Détails du registre, cliquez sur Passerelles pour afficher la liste de toutes les passerelles de ce registre.

gcloud

Pour répertorier toutes les passerelles d'un registre, exécutez la commande gcloud iot devices list :

gcloud iot devices list \
    --device-type=gateway DEVICE_ID \
    --registry=REGISTRY_ID

API

Utilisez la méthode list de l'appareil pour lister toutes les passerelles dans un registre.

C#

public static object ListGateways(string projectId, string cloudRegion, string registryName)
{
    var cloudIot = CreateAuthorizedClient();
    var registryPath = $"projects/{projectId}/locations/{cloudRegion}/registries/{registryName}";

    var req = cloudIot
        .Projects
        .Locations
        .Registries
        .Devices
        .List(registryPath);
    req.FieldMask = "config,gatewayConfig";

    var devices = req.Execute().Devices;

    if (devices != null)
    {
        Console.WriteLine("Found {0} devices", devices.Count);
        devices.ToList().ForEach(device =>
           {
               if (device.GatewayConfig != null
               && device.GatewayConfig.GatewayType != null
                  && device.GatewayConfig.GatewayType.Equals("GATEWAY"))
               {
                   Console.WriteLine("Id :{0}", device.Id);
                   if (device.Config != null)
                   {
                       Console.WriteLine("Config: {0}", device.Config.ToString());
                   }
               }
           }
        );
    }
    else
    {
        Console.WriteLine("Registry has no gateway devices");
    }

    return 0;
}

Go


// listGateways lists all the gateways in a specific registry.
func listGateways(w io.Writer, projectID string, region string, registryID 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
	}

	parent := fmt.Sprintf("projects/%s/locations/%s/registries/%s", projectID, region, registryID)
	response, err := client.Projects.Locations.Registries.Devices.List(parent).GatewayListOptionsGatewayType("GATEWAY").Do()

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

	if len(response.Devices) == 0 {
		fmt.Fprintln(w, "No gateways found")
		return response.Devices, nil
	}

	fmt.Fprintln(w, len(response.Devices), "devices:")
	for _, gateway := range response.Devices {
		fmt.Fprintf(w, "\t%s\n", gateway.Id)
	}

	return response.Devices, nil
}

Java

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 registryPath =
    String.format(
        "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

List<Device> gateways =
    service
        .projects()
        .locations()
        .registries()
        .devices()
        .list(registryPath)
        .setGatewayListOptionsGatewayType("GATEWAY")
        .execute()
        .getDevices();

if (gateways != null) {
  System.out.println("Found " + gateways.size() + " devices");
  for (Device d : gateways) {
    System.out.println("Id: " + d.getId());
    if (d.getConfig() != null) {
      // Note that this will show the device config in Base64 encoded format.
      System.out.println("Config: " + d.getGatewayConfig().toPrettyString());
    }
    System.out.println();
  }
} else {
  System.out.println("Registry has no devices.");
}

Node.js

// const cloudRegion = 'us-central1';
// 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 listDevices() {
  // Construct request
  const registryPath = iotClient.registryPath(
    projectId,
    cloudRegion,
    registryId
  );

  console.log('Current gateways in registry:');
  const [response] = await iotClient.listDevices({
    parent: registryPath,
    fieldMask: {paths: ['config', 'gateway_config']},
  });
  const devices = response;

  devices.forEach(device => {
    if (
      device.gatewayConfig !== undefined &&
      device.gatewayConfig.gatewayType === 'GATEWAY'
    ) {
      console.log('----\n', device);
    }
  });
}

listDevices();

Python

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

path = client.registry_path(project_id, cloud_region, registry_id)
mask = gp_field_mask.FieldMask()
mask.paths.append("config")
mask.paths.append("gateway_config")
devices = list(client.list_devices(request={"parent": path, "field_mask": mask}))

for device in devices:
    if device.gateway_config is not None:
        if device.gateway_config.gateway_type == 1:
            print("Gateway ID: {}\n\t{}".format(device.id, device))

Ruby

# project_id  = "Your Google Cloud project ID"
# location_id = "The Cloud region for the registry"
# registry_id = "The registry to list gateways in"

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
resource = "projects/#{project_id}/locations/#{location_id}/registries/#{registry_id}"

# List the devices in the provided region
gateways = iot_client.list_project_location_registry_devices(
  resource, field_mask: "config,gatewayConfig"
)

puts "Gateways:"
if gateways.devices && gateways.devices.any?
  gateways.devices.each do |gateway|
    if gateway.gateway_config && gateway.gateway_config.gateway_type == "GATEWAY"
      puts "\t#{gateway.id}"
    end
  end
else
  puts "\tNo gateways found in this registry."
end

Supprimer les appareils associés à une passerelle

Pour supprimer un appareil lié à une passerelle, commencez par dissocier cet appareil de toutes les passerelles auxquelles il est lié, puis supprimez-le du registre.

Console

  1. Dissociez l'appareil de toutes les passerelles auxquelles il est lié.

  2. Sur la page Détails de l'appareil, cliquez sur Supprimer.

  3. Saisissez l'ID de l'appareil pour confirmer, puis cliquez sur Supprimer.

gcloud

Pour répertorier toutes les passerelles auxquelles un appareil est lié, exécutez la commande gcloud iot devices list :

gcloud iot devices list DEVICE_ID \
  --project=PROJECT_ID \
  --registry=REGISTRY_ID \
  --region=REGION

Pour annuler la liaison d'un appareil, exécutez la commande gcloud iot devices gateways unbind :

gcloud iot devices gateways unbind --gateway=GATEWAY_ID \
  --device=DEVICE_ID \
  --project=PROJECT_ID \
  --device-region=DEVICE_REGION \
  --device-registry=DEVICE_REGISTRY \
  --gateway-region=GATEWAY_REGION \
  --gateway-registry=GATEWAY_REGISTRY

Pour supprimer un appareil, exécutez la commande gcloud iot devices delete :

gcloud iot devices delete DEVICE_ID \
  --project=PROJECT_ID \
  --registry=REGISTRY_ID \
  --region=REGION

API

Après avoir dissociez l'appareil de toutes les passerelles auxquelles il est lié, utilisez la méthode delete de l'appareil pour le supprimer.

C#

public static object DeleteDevice(string projectId, string cloudRegion, string registryId, string deviceId)
{
    var cloudIot = CreateAuthorizedClient();
    // The resource name of the location associated with the key rings.
    var name = $"projects/{projectId}/locations/{cloudRegion}/registries/{registryId}/devices/{deviceId}";

    try
    {
        var res = cloudIot.Projects.Locations.Registries.Devices.Delete(name).Execute();
        Console.WriteLine($"Removed device: {deviceId}");
    }
    catch (Google.GoogleApiException e)
    {
        Console.WriteLine(e.Message);
        if (e.Error != null) return e.Error.Code;
        return -1;
    }
    return 0;
}

Go


// deleteDevice deletes a device from a registry.
func deleteDevice(w io.Writer, projectID string, region string, registryID string, deviceID string) (*cloudiot.Empty, 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, deviceID)
	response, err := client.Projects.Locations.Registries.Devices.Delete(path).Do()
	if err != nil {
		return nil, err
	}

	fmt.Fprintf(w, "Deleted device: %s\n", deviceID)

	return response, nil
}

Java

/** Delete the given device from the registry. */
protected static void deleteDevice(
    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("Deleting device " + devicePath);
  service.projects().locations().registries().devices().delete(devicePath).execute();
}

Node.js

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

  const [responses] = await iotClient.deleteDevice({name: devPath});
  console.log('Successfully deleted device', responses);
}

deleteDevice();

Python

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

device_path = client.device_path(project_id, cloud_region, registry_id, device_id)

return client.delete_device(request={"name": device_path})

Ruby

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

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}"
device_path = "#{parent}/registries/#{registry_id}/devices/#{device_id}"

# Delete the device
result = iot_client.delete_project_location_registry_device(
  device_path
)

puts "Deleted device."

Supprimer une passerelle

Pour supprimer une passerelle, vous devez d'abord dissocier ses appareils, puis supprimer la passerelle du registre.

Console

  1. Dissocier tous les appareils de la passerelle.
  2. Revenez à la page Détails de la passerelle et cliquez sur Supprimer.
  3. Saisissez le nom de la passerelle pour confirmer votre choix, puis cliquez sur Supprimer.

gcloud

Pour annuler la liaison d'un appareil, exécutez la commande gcloud iot devices gateways unbind :

gcloud iot devices gateways unbind --gateway=GATEWAY_ID \
    --device=DEVICE_ID \
    --project=PROJECT_ID \
    --device-region=DEVICE_REGION \
    --device-registry=DEVICE_REGISTRY \
    --gateway-region=GATEWAY_REGION \
    --gateway-registry=GATEWAY_REGISTRY

Pour supprimer une passerelle, exécutez la commande gcloud iot devices delete :

gcloud iot devices delete GATEWAY_ID

API

Après avoir dissocié tous les appareils de la passerelle, utilisez la méthode delete de l'appareil pour supprimer la passerelle, en spécifiant l'ID de la passerelle que vous souhaitez supprimer.

C#

public static object DeleteDevice(string projectId, string cloudRegion, string registryId, string deviceId)
{
    var cloudIot = CreateAuthorizedClient();
    // The resource name of the location associated with the key rings.
    var name = $"projects/{projectId}/locations/{cloudRegion}/registries/{registryId}/devices/{deviceId}";

    try
    {
        var res = cloudIot.Projects.Locations.Registries.Devices.Delete(name).Execute();
        Console.WriteLine($"Removed device: {deviceId}");
    }
    catch (Google.GoogleApiException e)
    {
        Console.WriteLine(e.Message);
        if (e.Error != null) return e.Error.Code;
        return -1;
    }
    return 0;
}

Go


// deleteDevice deletes a device from a registry.
func deleteDevice(w io.Writer, projectID string, region string, registryID string, deviceID string) (*cloudiot.Empty, 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, deviceID)
	response, err := client.Projects.Locations.Registries.Devices.Delete(path).Do()
	if err != nil {
		return nil, err
	}

	fmt.Fprintf(w, "Deleted device: %s\n", deviceID)

	return response, nil
}

Java

/** Delete the given device from the registry. */
protected static void deleteDevice(
    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("Deleting device " + devicePath);
  service.projects().locations().registries().devices().delete(devicePath).execute();
}

Node.js

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

  const [responses] = await iotClient.deleteDevice({name: devPath});
  console.log('Successfully deleted device', responses);
}

deleteDevice();

Python

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

device_path = client.device_path(project_id, cloud_region, registry_id, device_id)

return client.delete_device(request={"name": device_path})

Ruby

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

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}"
device_path = "#{parent}/registries/#{registry_id}/devices/#{device_id}"

# Delete the device
result = iot_client.delete_project_location_registry_device(
  device_path
)

puts "Deleted device."

Étapes suivantes