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

기기 나열

특정 레지스트리의 기기 식별자를 검색합니다.

더 살펴보기

이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.

코드 샘플

Go

자세한 내용은 Cloud IoT Core Go API 참조 문서를 확인하세요.

Cloud IoT Core에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


// listDevices gets the identifiers of devices for a specific registry.
func listDevices(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).Do()
	if err != nil {
		return nil, err
	}

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

	return response.Devices, nil
}

Java

자세한 내용은 Cloud IoT Core Java API 참조 문서를 확인하세요.

Cloud IoT Core에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/** Print all of the devices in this registry to standard out. */
protected static void listDevices(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 registryPath =
      String.format(
          "projects/%s/locations/%s/registries/%s", projectId, cloudRegion, registryName);

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

  if (devices != null) {
    System.out.println("Found " + devices.size() + " devices");
    for (Device d : devices) {
      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.getConfig().toPrettyString());
      }
      System.out.println();
    }
  } else {
    System.out.println("Registry has no devices.");
  }
}

Node.js

자세한 내용은 Cloud IoT Core Node.js API 참조 문서를 확인하세요.

Cloud IoT Core에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// 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 parentName = iotClient.registryPath(
    projectId,
    cloudRegion,
    registryId
  );

  // See full list of device fields: https://cloud.google.com/iot/docs/reference/cloudiot/rest/v1/projects.locations.registries.devices
  // Warning! Use snake_case field names.
  const fieldMask = {
    paths: [
      'id',
      'name',
      'num_id',
      'credentials',
      'last_heartbeat_time',
      'last_event_time',
      'last_state_time',
      'last_config_ack_time',
      'last_config_send_time',
      'blocked',
      'last_error_time',
      'last_error_status',
      'config',
      'state',
      'log_level',
      'metadata',
      'gateway_config',
    ],
  };

  const [response] = await iotClient.listDevices({
    parent: parentName,
    fieldMask,
  });
  const devices = response;

  if (devices.length > 0) {
    console.log('Current devices in registry:');
  } else {
    console.log('No devices in registry.');
  }

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

listDevices();

PHP

자세한 내용은 Cloud IoT Core PHP API 참조 문서를 확인하세요.

Cloud IoT Core에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

use Google\Cloud\Iot\V1\DeviceManagerClient;

/**
 * List all devices in the registry.
 *
 * @param string $registryId IOT Device Registry ID
 * @param string $projectId Google Cloud project ID
 * @param string $location (Optional) Google Cloud region
 */
function list_devices(
    $registryId,
    $projectId,
    $location = 'us-central1'
) {
    print('Listing devices' . PHP_EOL);

    // Instantiate a client.
    $deviceManager = new DeviceManagerClient();

    // Format the full registry path
    $registryName = $deviceManager->registryName($projectId, $location, $registryId);

    // Call the API
    $devices = $deviceManager->listDevices($registryName);

    // Print the result
    foreach ($devices->iterateAllElements() as $device) {
        printf('Device: %s : %s' . PHP_EOL,
            $device->getNumId(),
            $device->getId());
    }
}

Python

자세한 내용은 Cloud IoT Core Python API 참조 문서를 확인하세요.

Cloud IoT Core에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
print("Listing devices")

client = iot_v1.DeviceManagerClient()
registry_path = client.registry_path(project_id, cloud_region, registry_id)

# See full list of device fields: https://cloud.google.com/iot/docs/reference/cloudiot/rest/v1/projects.locations.registries.devices
# Warning! Use snake_case field names.
field_mask = gp_field_mask.FieldMask(
    paths=[
        "id",
        "name",
        "num_id",
        "credentials",
        "last_heartbeat_time",
        "last_event_time",
        "last_state_time",
        "last_config_ack_time",
        "last_config_send_time",
        "blocked",
        "last_error_time",
        "last_error_status",
        "config",
        "state",
        "log_level",
        "metadata",
        "gateway_config",
    ]
)

devices = list(
    client.list_devices(request={"parent": registry_path, "field_mask": field_mask})
)
for device in devices:
    print(device)

return devices

Ruby

자세한 내용은 Cloud IoT Core Ruby API 참조 문서를 확인하세요.

Cloud IoT Core에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

# project_id  = "Your Google Cloud project ID"
# location_id = "The Cloud region the registry is located in"
# registry_id = "The registry to list devices from"

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
)

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

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.