Google Cloud IoT Core は 2023 年 8 月 16 日に廃止されます。詳細については、担当の Google Cloud アカウント チームにお問い合わせください。

ゲートウェイの作成

このページでは、ゲートウェイを作成、構成、管理する方法について説明します。

ゲートウェイを作成または削除する

ゲートウェイの作成や、既存のゲートウェイの編集は、Google Cloud コンソールまたは gcloud を使用して行えます。ゲートウェイの作成後に、それをゲートウェイ以外のデバイスへ変更することはできません。このセクションの手順を実行する前に、レジストリとデバイスの鍵ペアが作成されていることを確認してください。

Console

新しいゲートウェイを作成するには、次のようにします。

  1. Google Cloud コンソールで、[レジストリ] ページに移動します。

    [レジストリ] ページに移動する

  2. ゲートウェイの [レジストリ ID] をクリックします。
  3. [レジストリの詳細] ページで [ゲートウェイ] をクリックし、[ゲートウェイを作成] をクリックして新しいゲートウェイを作成します。
  4. ゲートウェイの簡単な説明か、簡単に識別できる [ゲートウェイ ID] を入力します(このフィールドを後で編集することはできません)。ゲートウェイの命名と長さの要件については、使用可能な文字と長さの要件をご覧ください。
  5. [ゲートウェイとの通信] で [許可] または [ブロック] を選択します。このオプションを使用すると、ゲートウェイやバインドされている 1 つ以上のデバイスが正常に機能しない場合など、必要に応じて通信をブロックできます。ほとんどの場合、最初にゲートウェイを作成するときに通信を許可することをおすすめします。ゲートウェイがブロックされると、バインドされているすべてのデバイスも Cloud IoT Core との通信がブロックされます。
  6. このゲートウェイの鍵ペアと一致する [公開鍵の形式] を選択します。証明書または鍵を [公開鍵の値] フィールドに貼り付けます。鍵の有効期限を設定することもできます。
  7. ゲートウェイにバインドされているデバイスに使用する認証方法を選択します。
  8. [] フィールドと [] フィールドを使用して、シリアル番号などのゲートウェイのメタデータ(省略可)を追加します。メタデータの鍵と値の命名とサイズの要件については、使用可能な文字と長さの要件をご覧ください。
  9. [Cloud Logging] で、ゲートウェイのアクティビティ ログレベルを選択します。ゲートウェイのログレベルによって、レジストリのログレベルはオーバーライドされます。
  10. [作成] をクリックしてゲートウェイを作成するか、[更新] をクリックして既存のゲートウェイの変更を保存します。

既存のゲートウェイを編集するには、次のようにします。

  1. Google Cloud コンソールで、[レジストリ] ページに移動します。

    [レジストリ] ページに移動する

  2. ゲートウェイの [レジストリ ID] をクリックします。
  3. [レジストリの詳細] をクリックします。
  4. [ゲートウェイ] をクリックします。
  5. 編集するゲートウェイの ID をクリックします。
  6. ページ上部の [編集] をクリックします。

既存のゲートウェイに鍵を追加するには、[デバイスの詳細] ページで [公開鍵を追加] をクリックします。

gcloud

ゲートウェイを作成するには、gcloud iot devices create コマンドを実行します。ゲートウェイは、RS256 か ES256 のうちいずれかの認証情報を使用して作成できます。

RS256 認証情報を使用してゲートウェイを作成するには、次のコマンドを実行します。

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}

ES256 認証情報を使用してゲートウェイを作成するには、次のコマンドを実行します。

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}

ゲートウェイを編集するには、gcloud iot devices update コマンドを実行します。ゲートウェイのさまざまなプロパティは変更できますが、ゲートウェイ以外のデバイスは変更できません。

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

ゲートウェイを作成または編集するには、次のメソッドを使用します。

C#

詳細については、Cloud IoT Core C# の API のリファレンス ドキュメントをご覧ください。

Cloud IoT Core 認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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

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

ゲートウェイで使用するデバイスの作成方法については、デバイスの作成または編集をご覧ください。

ゲートウェイを構成して状態を取得する

Cloud IoT Core では、他のデバイスと同様、ゲートウェイの構成を変更することでゲートウェイを調整できます。MQTT や HTTP ブリッジを介してゲートウェイを構成する方法については、デバイスの構成をご覧ください。

構成をゲートウェイに適用すると、ゲートウェイの状態が Cloud IoT Core に報告されます。ゲートウェイの状態と最新の構成を比較することで、ゲートウェイが本来の役割を果たすかどうかを確認できます。

デバイスのバインドまたはバインド解除

ゲートウェイ以外のデバイスを Cloud IoT Core で認証するには、そのデバイスをゲートウェイにバインドします。バインドすることによって、そのデバイスと、Cloud IoT Core がデバイスを認証するために確認するゲートウェイとの関連付けが作成されます。

Console

  1. Google Cloud コンソールで、[レジストリ] ページに移動します。

    [レジストリ] ページに移動する

  2. ゲートウェイの [レジストリ ID] をクリックします。
  3. [ゲートウェイ] をクリックし、ゲートウェイの ID をクリックします。
  4. [ゲートウェイの詳細] ページで、[バインドされたデバイス] をクリックします。
  5. [デバイスをバインド] をクリックします。
  6. ゲートウェイにバインドするデバイスを選択し、[バインド] をクリックします。
  7. デバイスをバインド解除するには、[ゲートウェイの詳細] ページでデバイスを選択し、[バインド解除] をクリックして、再度 [バインド解除] をクリックして確定します。

gcloud

デバイスをゲートウェイにバインドするには、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

ゲートウェイからデバイスをバインド解除するには、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

ゲートウェイに対してデバイスをバインドまたはバインド解除するには、次のメソッドを使用します。

C#

詳細については、Cloud IoT Core C# の API のリファレンス ドキュメントをご覧ください。

Cloud IoT Core 認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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

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

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

ゲートウェイにバインドされているすべてのデバイスを一覧表示する

Console

  1. Google Cloud コンソールで、[レジストリ] ページに移動します。

    [レジストリ] ページに移動する

  2. ゲートウェイの [レジストリ ID] をクリックします。
  3. [ゲートウェイ] をクリックし、ゲートウェイの ID をクリックします。
  4. [ゲートウェイの詳細] ページで、[バインドされたデバイス] をクリックします。

gcloud

ゲートウェイとデバイスの関連付けをすべて一覧表示するには、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

デバイス list メソッドを使用してゲートウェイ ID を指定し、ゲートウェイにバインドされているすべてのデバイスを一覧表示します。

C#

詳細については、Cloud IoT Core C# の API のリファレンス ドキュメントをご覧ください。

Cloud IoT Core 認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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: %w", 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 = 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);

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

レジストリ内のすべてのゲートウェイを一覧表示する

Console

  1. Google Cloud コンソールで、[レジストリ] ページに移動します。

    [レジストリ] ページに移動する

  2. ゲートウェイの [レジストリ ID] をクリックします。
  3. [レジストリの詳細] ページで、[ゲートウェイ] をクリックして、そのレジストリ内のすべてのゲートウェイの一覧を表示します。

gcloud

レジストリ内のすべてのゲートウェイを一覧表示するには、gcloud iot devices list コマンドを実行します。

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

API

Devices list メソッドを使用して、レジストリ内のすべてのゲートウェイを一覧表示します。

C#

詳細については、Cloud IoT Core C# の API のリファレンス ドキュメントをご覧ください。

Cloud IoT Core 認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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: %w", 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 = 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);

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

ゲートウェイにバインドされたデバイスを削除する

ゲートウェイにバインドされたデバイスを削除するには、まずバインドされているすべてのゲートウェイからデバイスをバインド解除してから、レジストリからデバイスを削除します。

Console

  1. バインドされているすべてのゲートウェイからデバイスをバインド解除します。

  2. [デバイスの詳細] ページで、[削除] をクリックします。

  3. デバイス ID を入力して、[削除] をクリックします。

gcloud

デバイスがバインドされているすべてのゲートウェイを一覧表示するには、gcloud iot devices list コマンドを実行します。

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

デバイスをバインド解除するには、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

デバイスを削除するには、gcloud iot devices delete コマンドを実行します。

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

API

バインドされているすべてのゲートウェイからデバイスをバインド解除した後、Device delete メソッドを使用してデバイスを削除します。

C#

詳細については、Cloud IoT Core C# の API のリファレンス ドキュメントをご覧ください。

Cloud IoT Core 認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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 = 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("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."

ゲートウェイを削除する

ゲートウェイを削除するには、まずデバイスをバインド解除し、つづいてレジストリからゲートウェイを削除します。

Console

  1. ゲートウェイからすべてのデバイスをバインド解除します
  2. ゲートウェイの詳細ページに戻り、[削除] をクリックします。
  3. ゲートウェイの名前を入力して確認し、[削除] をクリックします。

gcloud

デバイスをバインド解除するには、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

ゲートウェイを削除するには、gcloud iot devices delete コマンドを実行します。

gcloud iot devices delete GATEWAY_ID

API

ゲートウェイからすべてのデバイスをバインド解除した後、削除するゲートウェイの ID を指定して Device delete メソッドを使用し、ゲートウェイを削除します。

C#

詳細については、Cloud IoT Core C# の API のリファレンス ドキュメントをご覧ください。

Cloud IoT Core 認証するには、アプリケーションのデフォルト認証情報を設定します。 詳細については、ローカル開発環境の認証の設定をご覧ください。

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 = 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("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."

次のステップ