Google Cloud IoT Core는 2023년 8월 16일에 지원 중단됩니다. 자세한 내용은 Google Cloud 계정팀에 문의하세요.

게이트웨이 만들기

이 페이지에서는 게이트웨이 만들기, 구성, 관리 방법을 설명합니다.

게이트웨이 만들기 또는 편집

Google Cloud 콘솔 또는 gcloud를 사용하여 게이트웨이를 만들거나 기존 게이트웨이를 수정할 수 있습니다. 게이트웨이를 만든 후에는 이를 비게이트웨이 기기로 변경할 수 없습니다. 이 섹션의 단계를 완료하려면 먼저 레지스트리 및 기기 키 쌍이 생성되었는지 확인합니다.

콘솔

새 게이트웨이를 만들려면 다음 안내를 따르세요.

  1. Google Cloud 콘솔에서 레지스트리 페이지로 이동합니다.

    레지스트리 페이지로 이동

  2. 게이트웨이 레지스트리 ID를 클릭합니다.
  3. 레지스트리 세부정보 페이지에서 게이트웨이를 클릭한 후 게이트웨이 추가를 클릭하여 새 게이트웨이를 만듭니다.
  4. 게이트웨이를 간단하게 설명하는 또는 이를 식별하는 데 도움이 되는 게이트웨이 ID를 입력합니다. (이 필드를 나중에 수정할 수 없습니다.) 게이트웨이 이름 지정 및 크기 요구사항에 대한 자세한 내용은 허용되는 문자 및 크기 요구사항을 참조하세요.
  5. 게이트웨이 통신에 대해 허용 또는 차단을 선택합니다. 이 옵션을 사용하면 게이트웨이 또는 여기에 결합된 하나 이상의 기기가 올바르게 작동하지 않는 경우에 필요에 따라 통신을 차단할 수 있습니다. 대부분의 경우 게이트웨이를 처음 만들 때 통신을 허용합니다. 게이트웨이가 차단되면 여기에 결합된 모든 기기도 Cloud IoT Core와 통신하지 못하도록 차단됩니다.
  6. 이 게이트웨이의 키 상과 일치하는 공개 키 형식을 선택합니다. 공개 키 값 필드에 인증서 또는 키를 붙여넣습니다. 또한 키의 만료 날짜를 설정할 수 있습니다.
  7. 게이트웨이에 결합되는 기기에 사용할 인증 방법을 선택합니다.
  8. 필드를 사용하여 일련 번호와 같은 선택적인 게이트웨이 메타데이터를 추가합니다. 메타데이터 키-값 이름 지정 및 크기 요구사항에 대한 자세한 내용은 허용되는 문자 및 크기 요구사항을 참조하세요.
  9. Stackdriver 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에서 기기 인증을 위해 확인되는 기기와 게이트웨이 사이의 연결이 생성됩니다.

콘솔

  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"

게이트웨이에 결합된 모든 기기 나열

콘솔

  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

레지스트리의 모든 게이트웨이 나열

콘솔

  1. Google Cloud 콘솔에서 레지스트리 페이지로 이동합니다.

    레지스트리 페이지로 이동

  2. 게이트웨이 레지스트리 ID를 클릭합니다.
  3. 레지스트리 세부정보 페이지에서 게이트웨이를 클릭하여 해당 레지스트리에 있는 모든 게이트웨이 목록을 표시합니다.

gcloud

모든 레지스트리를 나열하려면 gcloud iot devices list 명령어를 실행합니다.

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

API

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

게이트웨이에 결합된 기기 삭제

게이트웨이에 결합된 기기를 삭제하려면 먼저 결합된 모든 게이트웨이에서 기기를 결합 해제한 후 레지스트리에서 기기를 삭제합니다.

콘솔

  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

결합된 모든 게이트웨이에서 기기를 결합 해제한 후 기기 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."

게이트웨이 삭제

게이트웨이를 삭제하려면 먼저 기기를 결합 해제한 후 레지스트리에서 게이트웨이를 삭제합니다.

콘솔

  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를 지정하여 기기 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."

다음 단계