Creating gateways

This page explains how to create, configure, and manage gateways.

Creating or editing a gateway

You can create a gateway or edit an existing one using GCP Console, or gcloud. After you create a gateway, you can't change it to a non-gateway device. Make sure you've created a registry and a device key pair before completing the steps in this section.

Console

To create a new gateway:

  1. Go to the Registries page in GCP Console.

    Go to the Registries page

  2. Click the ID of the registry for the gateway.
  3. On the Registry details page, click Gateways, then click Add gateway to create a new gateway.
  4. Enter a Gateway ID that briefly describes the gateway or otherwise helps you identify it. (This field can't be edited later.) For information on gateway naming and size requirements, see Permitted characters and size requirements.
  5. For Gateway communication, select Allow or Block. This option allows you to block communication when needed, such as when a gateway or one or more devices bound to it are not functioning properly. In most cases, you'll want to allow communication when first creating the gateway. When a gateway is blocked, all devices bound to it are also blocked from communicating with Cloud IoT Core.
  6. Select the Public key format that matches the key pair for this gateway. Paste the certificate or key in the Public key value field. You can also set an expiration date for the key.
  7. Select the authentication method to use for devices bound to the gateway.
  8. Use the Key and Value fields to add optional gateway metadata, such as a serial number. For information on metadata key-value naming and size requirements, see Permitted characters and size requirements.
  9. Under Stackdriver Logging, select an activity log level for the gateway. The gateway's log level overrides its registry's log level.
  10. Click Create to create the gateway or Update to save changes to an existing gateway.

To edit an existing gateway:

  1. Go to the Registries page in GCP Console.

    Go to the Registries page

  2. Click the ID of the registry for the gateway.
  3. Click Registry details.
  4. Click Gateways.
  5. Click the ID of the gateway you want to edit.
  6. Click Edit at the top of the page.

To add a key to an existing gateway, click Add public key on the Device details page.

gcloud

To create a gateway, run the gcloud iot devices create command. You can create a gateway with either RS256 or ES256 credentials.

To create a gateway with RS256 credentials, run the following command:

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}

To create a gateway with ES256 credentials, run the following command:

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}

To edit a gateway, run the gcloud iot devices update command command. You can change various properties of the gateway, but you can't change it to a non-gateway device.

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

Use the following methods to create or edit a gateway:

C#

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

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

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

Go

// createGateway creates a new IoT Core gateway with a given id, public key, and auth method.
// gatewayAuthMethod can be one of: ASSOCIATION_ONLY, DEVICE_AUTH_TOKEN_ONLY, ASSOCIATION_AND_DEVICE_AUTH_TOKEN.
// https://cloud.google.com/iot/docs/reference/cloudiot/rest/v1/projects.locations.registries.devices#gatewayauthmethod
func createGateway(w io.Writer, projectID string, region string, registryID string, gatewayID string, gatewayAuthMethod string, publicKeyPath string) (*cloudiot.Device, error) {
	// Authorize the client using Application Default Credentials.
	// See https://g.co/dv/identity/protocols/application-default-credentials
	ctx := context.Background()
	httpClient, err := google.DefaultClient(ctx, cloudiot.CloudPlatformScope)
	if err != nil {
		return nil, err
	}
	client, err := cloudiot.New(httpClient)
	if err != nil {
		return nil, err
	}

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

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

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

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

	return response, nil
}

Java

GoogleCredential credential =
    GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
HttpRequestInitializer init = new RetryHttpInitializerWrapper(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 (algorithm == "ES256") {
  keyFormat = "ES256_PEM";
}

PublicKeyCredential publicKeyCredential = new PublicKeyCredential();

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

device.setGatewayConfig(gwConfig);
device.setCredentials(Arrays.asList(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 parentName = `projects/${projectId}/locations/${cloudRegion}/registries/${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: fs.readFileSync(publicKeyFile).toString(),
      },
    },
  ];
}

const createRequest = {
  parent: parentName,
  resource: {
    id: gatewayId,
    credentials: credentials,
    gatewayConfig: {
      gatewayType: 'GATEWAY',
      gatewayAuthMethod: 'ASSOCIATION_ONLY',
    },
  },
};

client.projects.locations.registries.devices.create(
  createRequest,
  (err, res) => {
    if (err) {
      console.log('Could not create device');
      console.log(err);
    } else {
      console.log('Created device');
      console.log(res.data);
    }
  }
);

Python

# Check that the gateway doesn't already exist
exists = False
client = get_client(service_account_json)
registry_path = 'projects/{}/locations/{}/registries/{}'.format(
        project_id, cloud_region, registry_id)

devices = client.projects().locations().registries().devices(
        ).list(
                parent=registry_path, fieldMask='config,gatewayConfig'
        ).execute().get('devices', [])

for device in devices:
        if device.get('id') == gateway_id:
            exists = True
        print('Device: {} : {} : {} : {}'.format(
            device.get('id'),
            device.get('numId'),
            device.get('config'),
            device.get('gatewayConfig')
            ))

# Create the gateway
registry_name = 'projects/{}/locations/{}/registries/{}'.format(
        project_id, cloud_region, registry_id)

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

if algorithm == 'ES256':
    certificate_format = 'ES256_PEM'
else:
    certificate_format = 'RSA_X509_PEM'

# TODO: Auth type
device_template = {
    'id': gateway_id,
    'credentials': [{
        'publicKey': {
            'format': certificate_format,
            'key': certificate
        }
    }],
    'gatewayConfig': {
      'gatewayType': 'GATEWAY',
      'gatewayAuthMethod': 'ASSOCIATION_ONLY'
    }
}
devices = client.projects().locations().registries().devices()

if not exists:
    res = devices.create(
            parent=registry_name, body=device_template).execute()
    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}"

To learn how to create the devices you'll use with the gateway, see Creating or editing a device.

Configuring the gateway and getting state

With Cloud IoT Core, you can control a gateway by modifying its configuration, just as you would with any other device. See Configuring Devices to learn how to configure a gateway over the MQTT or HTTP bridge.

After a configuration has been applied to a gateway, the gateway can report its state to Cloud IoT Core. You can compare the gateway's state and its most recent configuration to make sure the gateway is doing what it's supposed to be doing.

Binding or unbinding a device

You can authenticate non-gateway devices to Cloud IoT Core by binding them to the gateway. Binding creates an association between the devices and the gateway that Cloud IoT Core checks to authenticate the devices.

Console

  1. Go to the Registries page in GCP Console.

    Go to the Registries page

  2. Click the ID of the registry for the gateway.
  3. Click Gateways, then click the gateway's ID.
  4. On the Gateway details page, click Bound devices.
  5. Click Bind device.
  6. Select the devices you want to bind to the gateway, then click Bind.
  7. To unbind a device, select the device in the Gateway details page and click Unbind device, then click Unbind again to confirm.

gcloud

To bind a device to a gateway, run the gcloud iot devices gateways bind command:

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

To unbind a device from a gateway, run the gcloud iot devices gateways unbind command:

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

Use the following methods to bind a device to or unbind a device from a gateway:

C#

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

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

    return 0;
}

Go

// bindDeviceToGateway creates an association between an existing device and gateway.
func bindDeviceToGateway(w io.Writer, projectID string, region string, registryID string, gatewayID string, deviceID string) (*cloudiot.BindDeviceToGatewayResponse, error) {
	// Authorize the client using Application Default Credentials.
	// See https://g.co/dv/identity/protocols/application-default-credentials
	ctx := context.Background()
	httpClient, err := google.DefaultClient(ctx, cloudiot.CloudPlatformScope)
	if err != nil {
		return nil, err
	}
	client, err := cloudiot.New(httpClient)
	if err != nil {
		return nil, err
	}

	parent := fmt.Sprintf("projects/%s/locations/%s/registries/%s", projectID, region, registryID)
	bindRequest := &cloudiot.BindDeviceToGatewayRequest{
		DeviceId:  deviceID,
		GatewayId: gatewayID,
	}

	response, err := client.Projects.Locations.Registries.BindDeviceToGateway(parent, bindRequest).Do()

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

	if response.HTTPStatusCode/100 != 2 {
		return nil, fmt.Errorf("BindDeviceToGateway: HTTP status code not 2xx\n %v", response)
	}

	fmt.Fprintf(w, "Bound %s to %s", deviceID, gatewayID)

	return response, nil
}

Java

createDevice(projectId, cloudRegion, registryName, deviceId);

GoogleCredential credential =
    GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
HttpRequestInitializer init = new RetryHttpInitializerWrapper(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';

console.log(`Binding device: ${deviceId}`);
const parentName = `projects/${projectId}/locations/${cloudRegion}/registries/${registryId}`;

const bindRequest = {
  parent: parentName,
  deviceId: deviceId,
  gatewayId: gatewayId,
};

client.projects.locations.registries.bindDeviceToGateway(bindRequest, err => {
  if (err) {
    console.log('Could not bind device', err);
  } else {
    console.log(`Bound ${deviceId} to`, gatewayId);
  }
});

Python

client = get_client(service_account_json)

create_device(
        service_account_json, project_id, cloud_region, registry_id,
        device_id)

registry_name = 'projects/{}/locations/{}/registries/{}'.format(
        project_id, cloud_region, registry_id)
bind_request = {
    'deviceId': device_id,
    'gatewayId': gateway_id
}
client.projects().locations().registries().bindDeviceToGateway(
        parent=registry_name, body=bind_request).execute()
print('Device Bound!')

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"

Listing all devices bound to a gateway

Console

  1. Go to the Registries page in GCP Console.

    Go to the Registries page

  2. Click the ID of the registry for the gateway.
  3. Click Gateways, then click the gateway's ID.
  4. On the Gateway details page, click Bound devices.

gcloud

To list all associations between a gateway and its devices, run the gcloud iot devices gateways list-bound-devices command:

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

API

Use the Devices list method and specify a gateway ID to list all devices bound to the gateway.

C#

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

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

    return 0;
}

Go

// listDevicesForGateway lists the devices that are bound to a gateway.
func listDevicesForGateway(w io.Writer, projectID string, region string, registryID, gatewayID string) ([]*cloudiot.Device, error) {
	// Authorize the client using Application Default Credentials.
	// See https://g.co/dv/identity/protocols/application-default-credentials
	ctx := context.Background()
	httpClient, err := google.DefaultClient(ctx, cloudiot.CloudPlatformScope)
	if err != nil {
		return nil, err
	}
	client, err := cloudiot.New(httpClient)
	if err != nil {
		return nil, err
	}

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

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

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

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

	return response.Devices, nil
}

Java

GoogleCredential credential =
    GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
HttpRequestInitializer init = new RetryHttpInitializerWrapper(credential);
final CloudIot service =
    new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
        .setApplicationName(APP_NAME)
        .build();

final String gatewayPath =
    String.format(
        "projects/%s/locations/%s/registries/%s/devices/%s",
        projectId, cloudRegion, registryName, gatewayId);

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 parentName = `projects/${projectId}/locations/${cloudRegion}/registries/${registryId}`;
const request = {
  parent: parentName,
  'gatewayListOptions.associationsGatewayId': gatewayId,
};

client.projects.locations.registries.devices.list(request, (err, res) => {
  if (err) {
    console.log('Could not list devices');
    console.log(err);
  } else {
    console.log('Current devices bound to gateway: ', gatewayId);
    const data = res.data;
    if (data.devices && data.devices.length > 0) {
      data.devices.forEach(device => {
        console.log(`\tDevice: ${device.numId} : ${device.id}`);
      });
    } else {
      console.log('No devices bound to this gateway.');
    }
  }
});

Python

client = get_client(service_account_json)

registry_name = 'projects/{}/locations/{}/registries/{}'.format(
        project_id, cloud_region, registry_id)

devices = client.projects().locations().registries().devices(
    ).list(
            parent=registry_name,
            gatewayListOptions_associationsGatewayId=gateway_id
    ).execute()

found = False
for device in devices.get('devices', []):
    found = True
    print('Device: {} : {}'.format(
            device.get('numId'),
            device.get('id')))

if devices.get('deviceNumIds') is not None:
    for device_id in devices.get('deviceNumIds'):
        device_name = '{}/devices/{}'.format(
                registry_name, device_id)
        device = client.projects().locations().registries().devices().get(
                name=device_name).execute()
        print('Id: {}\n\tName: {}\n\traw: {}'.format(
                device_id, device.get('id'), device))
else:
    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

Listing all gateways in a registry

Console

  1. Go to the Registries page in GCP Console.

    Go to the Registries page

  2. Click the ID of the registry for the gateway.
  3. On the Registry details page, click Gateways to see a list of all gateways in that registry.

gcloud

To list all gateways in a registry, run the gcloud iot devices list command:

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

API

Use the Device list method to list all gateways in a registry.

C#

public static object ListDevices(string projectId, string cloudRegion, string registryId)
{
    var cloudIot = CreateAuthorizedClient();
    // The resource name of the location associated with the key rings.
    var parent = $"projects/{projectId}/locations/{cloudRegion}/registries/{registryId}";
    try
    {
        var result = cloudIot.Projects.Locations.Registries.Devices.List(parent).Execute();
        Console.WriteLine("Devices: ");
        result.Devices.ToList().ForEach(response =>
        {
            Console.WriteLine($"{response.Id}");
            Console.WriteLine($"\t{response.Config}");
            Console.WriteLine($"\t{response.Name}");
        });
    }
    catch (Google.GoogleApiException e)
    {
        Console.WriteLine(e.Message);
        return e.Error.Code;
    }
    return 0;
}

Go

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

/** Print all of the devices in this registry to standard out. */
public static void listDevices(String projectId, String cloudRegion, String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredential credential =
      GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpRequestInitializer init = new RetryHttpInitializerWrapper(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

// Client retrieved in callback
// getClient(serviceAccountJson, function(client) {...});
// const cloudRegion = 'us-central1';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
const parentName = `projects/${projectId}/locations/${cloudRegion}`;
const registryName = `${parentName}/registries/${registryId}`;

const request = {
  parent: registryName,
};

client.projects.locations.registries.devices.list(request, (err, res) => {
  if (err) {
    console.log('Could not list devices');
    console.log(err);
  } else {
    const data = res.data;
    console.log('Current devices in registry:', data['devices']);
  }
});

Python

print('Listing devices')
registry_path = 'projects/{}/locations/{}/registries/{}'.format(
        project_id, cloud_region, registry_id)
client = get_client(service_account_json)
devices = client.projects().locations().registries().devices(
        ).list(parent=registry_path).execute().get('devices', [])

for device in devices:
        print('Device: {} : {}'.format(
                device.get('numId'),
                device.get('id')))

return devices

Ruby

# 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

Deleting devices bound to a gateway

To delete a device bound to a gateway, you first unbind the device from all gateways it's bound to, then delete the device from the registry.

Console

  1. Unbind the device from every gateway it's bound to.

  2. In the Device details page, click Delete.

  3. Enter the device ID to confirm and click Delete.

gcloud

To list all gateways a device is bound to, run the gcloud iot devices list command:

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

To unbind a device, run the gcloud iot devices gateways unbind command:

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

To delete a device, run the gcloud iot devices delete command:

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

API

After unbinding the device from all gateways it's bound to, use the Device delete method to delete the device.

C#

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

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

Go

// deleteDevice deletes a device from a registry.
func deleteDevice(w io.Writer, projectID string, region string, registryID string, deviceID string) (*cloudiot.Empty, error) {
	// Authorize the client using Application Default Credentials.
	// See https://g.co/dv/identity/protocols/application-default-credentials
	ctx := context.Background()
	httpClient, err := google.DefaultClient(ctx, cloudiot.CloudPlatformScope)
	if err != nil {
		return nil, err
	}
	client, err := cloudiot.New(httpClient)
	if err != nil {
		return nil, err
	}

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

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

	return response, nil
}

Java

/** Delete the given device from the registry. */
public static void deleteDevice(
    String deviceId, String projectId, String cloudRegion, String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredential credential =
      GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpRequestInitializer init = new RetryHttpInitializerWrapper(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

// Client retrieved in callback
// getClient(serviceAccountJson, function(client) {...});
// const cloudRegion = 'us-central1';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
const parentName = `projects/${projectId}/locations/${cloudRegion}`;
const registryName = `${parentName}/registries/${registryId}`;
const request = {
  name: `${registryName}/devices/${deviceId}`,
};

client.projects.locations.registries.devices.delete(request, (err, res) => {
  if (err) {
    console.log('Could not delete device:', deviceId);
    console.log(err);
  } else {
    console.log('Successfully deleted device:', deviceId);
    console.log(res.data);
    if (cb) {
      cb();
    }
  }
});

Python

print('Delete device')
client = get_client(service_account_json)
registry_name = 'projects/{}/locations/{}/registries/{}'.format(
        project_id, cloud_region, registry_id)

device_name = '{}/devices/{}'.format(registry_name, device_id)

devices = client.projects().locations().registries().devices()
return devices.delete(name=device_name).execute()

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

Deleting a gateway

To delete a gateway, you first unbind its devices then delete the gateway from the registry.

Console

  1. Unbind all devices from the gateway.
  2. Go back to the Gateway details page and click Delete.
  3. Enter the gateway's name to confirm, then click Delete.

gcloud

To unbind a device, run the gcloud iot devices gateways unbind command:

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

To delete a gateway, run the gcloud iot devices delete command:

gcloud iot devices delete GATEWAY_ID

API

After unbinding all devices from the gateway, use the Device delete method to delete the gateway, specifying the ID of the gateway you want to delete.

C#

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

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

Go

// deleteDevice deletes a device from a registry.
func deleteDevice(w io.Writer, projectID string, region string, registryID string, deviceID string) (*cloudiot.Empty, error) {
	// Authorize the client using Application Default Credentials.
	// See https://g.co/dv/identity/protocols/application-default-credentials
	ctx := context.Background()
	httpClient, err := google.DefaultClient(ctx, cloudiot.CloudPlatformScope)
	if err != nil {
		return nil, err
	}
	client, err := cloudiot.New(httpClient)
	if err != nil {
		return nil, err
	}

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

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

	return response, nil
}

Java

/** Delete the given device from the registry. */
public static void deleteDevice(
    String deviceId, String projectId, String cloudRegion, String registryName)
    throws GeneralSecurityException, IOException {
  GoogleCredential credential =
      GoogleCredential.getApplicationDefault().createScoped(CloudIotScopes.all());
  JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
  HttpRequestInitializer init = new RetryHttpInitializerWrapper(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

// Client retrieved in callback
// getClient(serviceAccountJson, function(client) {...});
// const cloudRegion = 'us-central1';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
const parentName = `projects/${projectId}/locations/${cloudRegion}`;
const registryName = `${parentName}/registries/${registryId}`;
const request = {
  name: `${registryName}/devices/${deviceId}`,
};

client.projects.locations.registries.devices.delete(request, (err, res) => {
  if (err) {
    console.log('Could not delete device:', deviceId);
    console.log(err);
  } else {
    console.log('Successfully deleted device:', deviceId);
    console.log(res.data);
    if (cb) {
      cb();
    }
  }
});

Python

print('Delete device')
client = get_client(service_account_json)
registry_name = 'projects/{}/locations/{}/registries/{}'.format(
        project_id, cloud_region, registry_id)

device_name = '{}/devices/{}'.format(registry_name, device_id)

devices = client.projects().locations().registries().devices()
return devices.delete(name=device_name).execute()

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

What's next

Learn how to use the MQTT bridge or HTTP bridge to relay messages and configuration data between the devices and Cloud IoT Core.

Esta página foi útil? Conte sua opinião sobre:

Enviar comentários sobre…

Cloud IoT Core Documentation