특정 기기를 검색하고 세부정보를 출력합니다.
더 살펴보기
이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.
코드 샘플
Go
자세한 내용은 Cloud IoT Core Go API 참조 문서를 확인하세요.
Cloud IoT Core에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
// getDevice retrieves a specific device and prints its details.
func getDevice(w io.Writer, projectID string, region string, registryID string, device 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
}
path := fmt.Sprintf("projects/%s/locations/%s/registries/%s/devices/%s", projectID, region, registryID, device)
response, err := client.Projects.Locations.Registries.Devices.Get(path).Do()
if err != nil {
return nil, err
}
fmt.Fprintf(w, "\tId: %s\n", response.Id)
for _, credential := range response.Credentials {
fmt.Fprintf(w, "\t\tCredential Expire: %s\n", credential.ExpirationTime)
fmt.Fprintf(w, "\t\tCredential Type: %s\n", credential.PublicKey.Format)
fmt.Fprintln(w, "\t\t--------")
}
fmt.Fprintf(w, "\tLast Config Ack: %s\n", response.LastConfigAckTime)
fmt.Fprintf(w, "\tLast Config Send: %s\n", response.LastConfigSendTime)
fmt.Fprintf(w, "\tLast Event Time: %s\n", response.LastEventTime)
fmt.Fprintf(w, "\tLast Heartbeat Time: %s\n", response.LastHeartbeatTime)
fmt.Fprintf(w, "\tLast State Time: %s\n", response.LastStateTime)
fmt.Fprintf(w, "\tNumId: %d\n", response.NumId)
return response, nil
}
Java
자세한 내용은 Cloud IoT Core Java API 참조 문서를 확인하세요.
Cloud IoT Core에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
/** Retrieves device metadata from a registry. * */
protected static Device getDevice(
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("Retrieving device " + devicePath);
return service.projects().locations().registries().devices().get(devicePath).execute();
}
Node.js
자세한 내용은 Cloud IoT Core Node.js API 참조 문서를 확인하세요.
Cloud IoT Core에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
// const cloudRegion = 'us-central1';
// const deviceId = 'my-device';
// 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 getDevice() {
// Construct request
const devicePath = iotClient.devicePath(
projectId,
cloudRegion,
registryId,
deviceId
);
// 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.getDevice({
name: devicePath,
fieldMask,
});
const data = response;
console.log('Found device:', deviceId, data);
}
getDevice();
PHP
자세한 내용은 Cloud IoT Core PHP API 참조 문서를 확인하세요.
Cloud IoT Core에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
use Google\Cloud\Iot\V1\DeviceManagerClient;
use Google\Cloud\Iot\V1\PublicKeyFormat;
/**
* Retrieve the device with the given id.
*
* @param string $registryId IOT Device Registry ID
* @param string $deviceId IOT Device ID
* @param string $projectId Google Cloud project ID
* @param string $location (Optional) Google Cloud region
*/
function get_device(
$registryId,
$deviceId,
$projectId,
$location = 'us-central1'
) {
print('Getting device' . PHP_EOL);
// Instantiate a client.
$deviceManager = new DeviceManagerClient();
$deviceName = $deviceManager->deviceName($projectId, $location, $registryId, $deviceId);
$device = $deviceManager->getDevice($deviceName);
$formats = [
PublicKeyFormat::UNSPECIFIED_PUBLIC_KEY_FORMAT => 'unspecified',
PublicKeyFormat::RSA_X509_PEM => 'RSA_X509_PEM',
PublicKeyFormat::ES256_PEM => 'ES256_PEM',
PublicKeyFormat::RSA_PEM => 'RSA_PEM',
PublicKeyFormat::ES256_X509_PEM => 'ES256_X509_PEM',
];
printf('ID: %s' . PHP_EOL, $device->getId());
printf('Name: %s' . PHP_EOL, $device->getName());
foreach ($device->getCredentials() as $credential) {
print('Certificate:' . PHP_EOL);
printf(' Format: %s' . PHP_EOL,
$formats[$credential->getPublicKey()->getFormat()]);
printf(' Expiration: %s' . PHP_EOL,
$credential->getExpirationTime()->toDateTime()->format('Y-m-d H:i:s'));
}
printf('Data: %s' . PHP_EOL, $device->getConfig()->getBinaryData());
printf('Version: %s' . PHP_EOL, $device->getConfig()->getVersion());
printf('Update Time: %s' . PHP_EOL,
$device->getConfig()->getCloudUpdateTime()->toDateTime()->format('Y-m-d H:i:s'));
}
Python
자세한 내용은 Cloud IoT Core Python API 참조 문서를 확인하세요.
Cloud IoT Core에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.
# project_id = 'YOUR_PROJECT_ID'
# cloud_region = 'us-central1'
# registry_id = 'your-registry-id'
# device_id = 'your-device-id'
print("Getting device")
client = iot_v1.DeviceManagerClient()
device_path = client.device_path(project_id, cloud_region, registry_id, device_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",
]
)
device = client.get_device(request={"name": device_path, "field_mask": field_mask})
print("Id : {}".format(device.id))
print("Name : {}".format(device.name))
print("Credentials:")
if device.credentials is not None:
for credential in device.credentials:
keyinfo = credential.public_key
print("\tcertificate: \n{}".format(keyinfo.key))
if keyinfo.format == 4:
keyformat = "ES256_X509_PEM"
elif keyinfo.format == 3:
keyformat = "RSA_PEM"
elif keyinfo.format == 2:
keyformat = "ES256_PEM"
elif keyinfo.format == 1:
keyformat = "RSA_X509_PEM"
else:
keyformat = "UNSPECIFIED_PUBLIC_KEY_FORMAT"
print("\tformat : {}".format(keyformat))
print("\texpiration: {}".format(credential.expiration_time))
print("Config:")
print("\tdata: {}".format(device.config.binary_data))
print("\tversion: {}".format(device.config.version))
print("\tcloudUpdateTime: {}".format(device.config.cloud_update_time))
return device
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 get a device from"
# device_id = "The identifier of the device to get"
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}"
resource = "#{parent}/registries/#{registry_id}/devices/#{device_id}"
# List the devices in the provided region
device = iot_client.get_project_location_registry_device(
resource
)
puts "Device: #{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}"
puts "\tCertificate formats:"
if device.credentials
device.credentials.each { |cert| puts "\t\t#{cert.public_key.format}" }
else
puts "\t\tNo certificates for device"
end
다음 단계
다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.