Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Note

This documentation is still in development - use at your own risk

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

Creating or editing a gateway

After you create a gateway, you can't change it to a non-gateway device. Make sure Ensure you've created a registry and a device key pair before completing the steps in this sectionbelow.

Console

...

Create a new gateway

...

1. Go to the Registries page

...

.

...

Click

...

a registry ID.

2. On the Registry details page, click Gateways

...

and Add gateway to create a new gateway.

3. Enter a

...

gateway ID that

...

describes the gateway

...

and helps you identify it

...

(

...

this field can't be edited later).

...

4. For Gateway communication, select Allow or Block.

...

The latter allows you to block communication when needed, such as when a gateway or one or more devices bound to it are not functioning properly.

...

You’ll most likely want to allow communication when

...

creating the gateway. When a gateway is blocked, all devices bound to it are

...

blocked from communicating with ClearBlade IoT Core.

5. Select the

...

public key format that matches

...

this gateway’s key pair

...

. Paste the certificate or key in the Public key value field. You can also set

...

the key’s expiration date

...

.

6. Select the authentication method to use for devices bound to the gateway.

7. Use the Key and Value fields to add optional gateway metadata, such as a serial number.

...

Under Stackdriver Logging, select an activity log level for the gateway. The gateway's log level overrides its registry's log level.

...

8. Click Submit to create the gateway or Update to save changes to an existing gateway.To edit

Edit an existing gateway

...

1. Go to the Registries page.

2. Click the

...

gateway’s registry ID.

3. Click Registry details.

4. Click Gateways.

5. Click the gateway’s ID

...

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.

API

Use the following these methods to create or edit a gateway:

  • Device create method to add gateways to registries

  • Device patch method to edit existing gateways

...

Creating or editing a

...

gateway code samples

Node.js

C#

Code Block
public// staticconst objectcloudRegion 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"
        },
 = 'us-central1';
// const deviceId = 'my-unauth-device';
// const gatewayId = 'my-gateway';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
// const gatewayAuthMethod = 'ASSOCIATION_ONLY';
import { DeviceManagerClient } from '@clearblade/iot';

const iotClient = new 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 = [
      Credentials{
=         publicKey: new{
List<DeviceCredential>()          {format:  publicKeyFormat,
          new DeviceCredentialkey: readFileSync(publicKeyFile).toString()
        }
    {  }
     ];
   }
 
   const PublicKeydevice = new{
PublicKeyCredential()    id: gatewayId,
     credentials:  credentials,
     gatewayConfig: {
         gatewayType: 'GATEWAY',
          Key = File.ReadAllText(publicKeyFilePath),
gatewayAuthMethod: gatewayAuthMethod
     }
     };
 
   const  request Format = (algorithm == "ES256" ?
     {
    parent: regPath,
     device
   };
 
   const   "ES256_PEM" : "RSA_X509_PEM")
                },
     [response] = await iotClient.createDevice(request);
  console.log('Created device:', response);
}

createDevice();

C#
Code Block
{
    logger.LogInformation("Create a new gateway");

     string }id    = "Sample-New-Gateway";
    }string  name   }= "projects/developmentenv/locations/us-central1/registries/Sample-New-Registry/Devices/Sample-New-Gateway";

    DeviceString createdDevicekeyText = cloudIot.Projects.Locations.RegistriesFile.ReadAllText("path/to/key");

     var credentials   .Devices.Create(body, registryPath).Execute();= new List<DeviceCredential>
    Console.WriteLine("Created gateway: {0}", createdDevice.ToString());{
        new DeviceCredential()
        {
      return 0;}

Go

Code Block
// 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.      PublicKey = new PublicKeyCredential()
            {
                Key = keyText,
                Format = "ES256_PEM"
            },
        }
    };

    var gatewayConfig = new GatewayConfig()
    {
        //GatewayType See https://g.co/dv/identity/protocols/application-default-credentials= "GATEWAY",
        ctxGatewayAuthMethod := context.Background()"ASSOCIATION_ONLY"
    };

    httpClient,var errresult := googleawait mClient.DefaultClient(ctx, cloudiot.CloudPlatformScope)
   CreateDevice(4, id, name, credentials, gatewayConfig);
    if err != nil {
   (!result.Item1 || (result.Item2 == null))
            return nil, errlogger.LogError("Failed to create new device");
    else
    }{
        client, err := cloudiot.New(httpClient)
logger.LogInformation("Successfully created new device");

        if err != nil {
            // The result.Item2 object can be used to refer to newly created device
    return nil, err
        }

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

        gateway := &cloudiot.Device{
                Id: gatewayID,
                Credentials: []*cloudiot.DeviceCredential{
                        {
   }
}

Python
Code Block
import os
import io
from clearblade.cloud import iot_v1

def create_gateway():
  project_id = 'YOUR_PROJECT_ID'
  cloud_region = 'us-central1'
  registry_id = 'your-registry-id'
  device_id = 'your-device-id'
  gateway_id = 'your-gateway-id'
  public_key_file = 'path/to/ec_public.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)

  listDevicesRequest = iot_v1.ListDevicesRequest(parent=parent)
  devices = list(client.list_devices(request=listDevicesRequest))

  for device in devices:
    if device.id == gateway_id:
       exists  =  True
     print(
          PublicKey: &cloudiot.PublicKeyCredential{
     "Device: {} : {} : {} : {}".format(
               device.id, device.num_id, device.config, device.gateway_config
       )
     )
 
  Format: "RSA_X509_PEM",
   with io.open(public_key_file) as f:
     public_key      = f.read()

   if  algorithm    == "ES256":
         public_key_format = iot_v1.PublicKeyFormat.ES256_PEM
    Keyelse:
   string(keyBytes),
         public_key_format = iot_v1.PublicKeyFormat.RSA_X509_PEM

   #  TODO:  Auth  type
   gateway    = iot_v1.Device(
    }name=gateway_id,
     credentials=[{
                  },"publicKey": { "format": public_key_format, "key": public_key }
    }],
    gateway_config={
        }"gatewayType": "GATEWAY",
        "gatewayAuthMethod": "ASSOCIATION_ONLY",
     }
  GatewayConfig: &cloudiot.GatewayConfig{)

   if  not  exists:
     createDeviceRequest    = iot_v1.CreateDeviceRequest(
      GatewayType:parent=parent,
      "GATEWAY",device=gateway
     )
     res    = client.create_device(request=createDeviceRequest)
        GatewayAuthMethod: gatewayAuthMethod,print("Created Gateway {}".format(res))
   else:
            },
        }

        parent := fmt.Sprintf("projects/%s/locations/%s/registries/%s", projectID, region, registryID)
        response, err := client.Projects.Locations.Registries.Devices.Create(parent, gateway).Do()
   print("Gateway exists, skipping")

os.environ["CLEARBLADE_CONFIGURATION"] = "/path/to/your-credentials.json"
create_gateway()

Go
Code Block
// getDevice retrieves a specific device and prints its details.
func createGateway(w io.Writer, projectID string, region string, registryID string, gatewayID string, gatewayAuthMethod string, publicKeyPath string) (*iot.Device, error) {
    ctx := context.Background()
    service, err := iot.NewService(ctx)
    if err != nil {
       
        return nil, err
    }

    }keyBytes, err    := ioutil.ReadFile(publicKeyPath)
    fmt.Fprintln(w, "Successfully created gateway:", gatewayID)

if err != nil {
        return responsenil, nil}

Java

Code Block
GoogleCredentials credential =
err
    GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();HttpRequestInitializer init = new HttpCredentialsAdapter(credential);final CloudIot service =}

    gateway := &cloudiot.Device{
        Id: gatewayID,
        new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)Credentials: []*cloudiot.DeviceCredential{
            .setApplicationName(APP_NAME){
        .build();
final String registryPath =         PublicKey: String.format(&cloudiot.PublicKeyCredential{
        "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            Format: "RSA_X509_PEM",
                    Key:    string(keyBytes),
                },
            },
        },
        GatewayConfig: &cloudiot.GatewayConfig{
            GatewayType:       "GATEWAY",
  .projects()          .locations()GatewayAuthMethod: gatewayAuthMethod,
        .registries()},
     }
 
.devices()
     parent  := fmt.create(registryPath, deviceSprintf("projects/%s/locations/%s/registries/%s", projectID, region, registryID)
     response,   .execute();
System.out.println("Created gateway: " + createdDevice.toPrettyString());

Node.js

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

Code Block
# 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_PEMelse:
    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

Code Block
# 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 scopeCloudiot   = 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}"

Configuring the gateway and getting state

With ClearBlade 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 ClearBlade 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 ClearBlade IoT Core by binding them to the gateway. Binding creates an association between the devices and the gateway that ClearBlade IoT Core checks to authenticate the devices.

Note: Binding is required when using the HTTP bridge.

Console

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

API

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

C#

Code Block
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

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

Code Block
createDevice(projectId, cloudRegion, registryName, deviceId);
GoogleCredentials credential =
    GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());JsonFactory jsonFactory = JacksonFactory.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

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

Code Block
# 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

Code Block
# 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 scopeCloudiot   = 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.

    Click the ID of the registry for the gateway.

  2. Click Gateways, then click the gateway's ID.

  3. On the Gateway details page, click Bound devices.

API

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

C#

Code Block
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

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

Code Block
GoogleCredentials credential =
    GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());JsonFactory jsonFactory = JacksonFactory.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

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

Code Block
# 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 = Falsefor 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

Code Block
# 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 scopeCloudiot   = 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.

  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.

API

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

C#

Code Block
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);
       err := service.Projects.Locations.Registries.Devices.Create(parent, gateway).Do()
    if err != nil {
        return nil, err
    }

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

    return response, nil
}

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

Configuring the gateway and getting state

With ClearBlade IoT Core, you can control a gateway by modifying its configuration, like 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 ClearBlade IoT Core. You can compare the gateway's state and its most recent configuration to ensure it’s functioning properly.

Binding or unbinding a device

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

Binding is required when using the HTTP bridge.

Console

1. Go to the Registries page.

2. Click the gateway’s registry ID.

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 and Unbind to confirm.

API

Use these methods to bind a device to or unbind a device from a gateway:

Binding a device to or unbinding a device from a gateway code samples

Node.js
Code Block
// const cloudRegion = 'us-central1';
// const deviceId = 'my-unauth-device';
// const gatewayId = 'my-gateway';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
import { DeviceManagerClient } from '@clearblade/iot';

const iotClient = new 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();

C#
Code Block
if (bBindUnBindDevice)
{
    logger.LogInformation("Get configuration of a device");

    // While running this sample, it is assumed that device with name
    // "Sample-New-Device" exists and Gateway with name "TestGateway" exists
    // "Sample-New-Registry" is the registry name

    // Sample - Bind Device
    var result = await mClient.BindDeviceToGateway(4, "projects/developmentenv/locations/us-central1/registries/Sample-New-Registry", "TestGateway", "Sample-New-Device");
    if (!result)
    {
        logger.LogError("Failed To Bind Device");
    }
    else
    {
        // Actual test - UnBind Device
        result = await mClient.UnBindDeviceFromGateway(4, "projects/developmentenv/locations/us-central1/registries/Sample-New-Registry", "TestGateway", "Sample-New-Device");
        if (!result)
            logger.LogError("Failed to unbind a device");
        else
           if  (device.Config != null)
logger.LogInformation("Successfully bind device");

                   {
                       Console.WriteLine("Config: {0}", device.Config.ToString());
                   }
               }
           }
        );
    }
    else
    {
        Console.WriteLine("Registry has no gateway devices");
    }

    return 0;}}
}

Python
Code Block
import os
from clearblade.cloud import iot_v1

def bind_device_to_gateway():
  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()

  parent = client.registry_path(project_id, cloud_region, registry_id)

  request = iot_v1.BindDeviceToGatewayRequest(
    parent=parent,
    gatewayId=gateway_id,
    deviceId=device_id
  )
  res = client.bind_device_to_gateway(request=request)

  print("Device Bound! {}".format(res))

os.environ["CLEARBLADE_CONFIGURATION"] = "/path/to/your-credentials.json"
bind_device_to_gateway()

Go
Code Block
// listGatewaysbindDeviceToGateway creates listsan allassociation thebetween gatewaysan inexisting adevice specificand registrygateway.
func listGatewaysbindDeviceToGateway(w io.Writer, projectID string, region string, registryID string) ([]*cloudiot.Device, error)gatewayID {string,  deviceID       // Authorize the client using Application Default Credentials.
        // See https://g.co/dv/identity/protocols/application-default-credentials
   string) (*iot.BindDeviceToGatewayResponse, error) {
    ctx := context.Background()
        httpClientservice, err := googleiot.DefaultClientNewService(ctx, cloudiot.CloudPlatformScope)
 
      if err != nil {
                return nil, err
 
      }
        client, errparent := cloudiotfmt.New(httpClient)
   Sprintf("projects/%s/locations/%s/registries/%s", projectID, region, registryID)
    ifbindRequest err !:= nil {
                return nil, err&iot.BindDeviceToGatewayRequest{
        }DeviceId:  deviceID,
        parent GatewayId:= fmt.Sprintf("projects/%s/locations/%s/registries/%s", projectID, region, registryID)
    gatewayID,
    }

    response, err := clientservice.Projects.Locations.Registries.Devices.ListBindDeviceToGateway(parent).GatewayListOptionsGatewayType("GATEWAY", bindRequest).Do()

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

    }
if response.HTTPStatusCode/100 != 2 {
        if len(response.Devices) == 0 {
 return nil, fmt.Errorf("BindDeviceToGateway: HTTP status code not 2xx\n %v", response)
     }
 
      fmt.FprintlnFprintf(w, "NoBound %s gatewaysto found%s"),            deviceID, gatewayID)

    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

Code Block
GoogleCredentials credential =
    GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());JsonFactory jsonFactory = JacksonFactory.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)}

Listing all devices bound to a gateway

Console

1. Go to the Registries page. Click the gateway’s registry ID.

2. Click Gateways, then click the gateway's ID.

3. On the Gateway details page, click Bound devices.

API

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

Listing all devices bound to the gateway code samples

Node.js
Code Block
// const cloudRegion = 'us-central1';
// const gatewayId = 'my-gateway';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
import { DeviceManagerClient } from '@clearblade/iot';
const iotClient = new 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();

C#
Code Block
{
    logger.LogInformation("Obtain list of devices for a particular registry and gateway");

    // While running this sample, it is assumed that gateway with name
    // "associated-gateway" exists

    GatewayListOptionsModel gatewayListOptions = new GatewayListOptionsModel()
    {
      //  NoteAssociationsGatewayId that this will show the device config in Base64 encoded format.
      System.out.println("Config: " + d.getGatewayConfig().toPrettyString()= "associated-gateway",
    };
    var result = await mClient.GetDevicesList(4, "projects/developmentenv/locations/us-central1/registries/Sample-New-Registry", gatewayListOptions);
    }
    System.out.println();if (!result.Item1)
  }} else {      Systemlogger.out.printlnLogError("Registry has noFailed to get list of devices.");}

Node.js

Code Block
// 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({
    else
    {
        logger.LogInformation("Succeeded in getting the list of Devices");

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

Code Block
# 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

Code Block
# 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 scopeCloudiot   = 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
  endelse
  puts "\tNo gateways found in this registry."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.

API

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

C#

Code Block
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

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

Code Block
/** 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 = JacksonFactory.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(
           Use the list
    }
}

Python
Code Block
import os
from clearblade.cloud import iot_v1

def list_bound_devices():
  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)

  request = iot_v1.ListDevicesRequest(
    parent=path,
    gatewayListOptions={ "associationsGatewayId": gateway_id }
  )
  
  devices = list(client.list_devices(request=request))

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

os.environ["CLEARBLADE_CONFIGURATION"] = "/path/to/your-credentials.json"
list_bound_devices()

Go
Code Block

// listDevicesForGateway lists the devices that are bound to a gateway.
func listDevicesForGateway(w io.Writer, projectID string, region string, registryID, gatewayID string) ([]*iot.Device, error) {
    // Authorize the client using Application Default Credentials.
    // See https://g.co/dv/identity/protocols/application-default-credentials
    ctx := context.Background()
    service, err := iot.NewService(ctx)
    if err != nil {
        return nil, err
    }
    parent := fmt.Sprintf("projects/%s/locations/%s/registries/%s", projectID, region, registryID)
    response, err := service.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
}

Listing all gateways in a registry

Console

1. Go to the Registries page.

2. Click a registry ID.

3. On the Registry details page, click Gateways to see a list of the registry’s gateways.

API

Use the device list method to list a registry’s gateways.

Listing a registry’s gateways code samples

Node.js
Code Block
// const cloudRegion = 'us-central1';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
import { DeviceManagerClient } from '@clearblade/iot';
const iotClient = new 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'] },
    gatewayListOptions: {
      gatewayType: 'GATEWAY'
    }
  });
  const devices = response;

  devices.forEach((device) => {
    console.log('----\n', device);
  });
}

listDevices();

C#
Code Block
{
    logger.LogInformation("Obtain list of gateways in a registry");

    GatewayListOptionsModel gatewayListOptions = new GatewayListOptionsModel()
    {
        GatewayType = core.Enums.GatewayTypeEnum.GATEWAY,
    };

    var result = await mClient.GetDevicesList(4, "projects/developmentenv/locations/us-central1/registries/Sample-New-Registry", gatewayListOptions);
    if (!result.Item1)
        logger.LogError("Failed to get list of devices");
    else
    {
        logger.LogInformation("Succeeded in getting the list of gateways");

        // Use the list
    }
}

Python
Code Block
import os
from clearblade.cloud import iot_v1

def list_gateways():
  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 = "config,gateway_config"

  request = iot_v1.ListDevicesRequest(
    parent=path,
    # fieldMask=mask
  )
  
  devices = list(client.list_devices(request=request))

  for device in devices:
    print(device.id)
    if device.gateway_config is not None:
      print(f"gateway_config: {device.gateway_config}")
      if device.gateway_config['gatewayType'] == 1:
        print("Gateway ID: {}\n\t{}".format(device.id, device))

os.environ["CLEARBLADE_CONFIGURATION"] = "/path/to/your-credentials.json"
list_gateways()

Go
Code Block
// listGateways lists all the gateways in a specific registry.
func listGateways(w io.Writer, projectID string, region string, registryID string) ([]*iot.Device, error) {
    ctx := context.Background()
    service, err := iot.NewService(ctx)
    if err != nil {
        return nil, err
    }

    parent := fmt.Sprintf("projects/%s/locations/%s/registries/%s/devices/%s",           projectIdprojectID, cloudRegionregion, registryName, deviceIdregistryID);
    System.out.println("Deleting device " + devicePath);
 response, err := service.projects().locations().registries().devices().delete(devicePath).execute();}

Node.js

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

Code Block
# 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

Code Block
# 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 scopeCloudiot   = 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.

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#

Code Block
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

Code Block
// 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)
   Projects.Locations.Registries.Devices.List(parent).GatewayListOptionsGatewayType("GATEWAY").Do()

    if err != nil {
        return nil, fmt.Errorf("ListGateways: %v", 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
}

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 it from the registry.

Console

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

2. In the Device details page, click Delete.

API

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

Deleting a device bound to a gateway code samples

Node.js
Code Block
// const cloudRegion = 'us-central1';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
import { DeviceManagerClient } from '@clearblade/iot';

const iotClient = new 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();

C#
Code Block
{
    logger.LogInformation("Unbind the device");

    var unbindResult = await mClient.UnBindDeviceFromGateway(4, "projects/developmentenv/locations/us-central1/registries/Sample-New-Registry", "TestGateway", "Sample-New-Device");
    if (!unbindResult)
        logger.LogError("Failed to unbind a device");
    else
        logger.LogInformation("Successfully unbind device");

    logger.LogInformation("Delete the device");

    string id = "Sample-New-Device";
    string name = "projects/developmentenv/locations/us-central1/registries/Sample-New-Registry/Devices/Sample-New-Device";

    var deleteResult = await mClient.DeleteDevice(4, id, name);
    if (!deleteResult.Item1 || (deleteResult.Item2 == null))
        logger.LogError("Failed to delete device");
    else
    {
        logger.LogInformation("Successfully deleted the device");
    }
}

Python
Code Block
import os
from clearblade.cloud import iot_v1

def delete_device():
  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)

  request = iot_v1.DeleteDeviceRequest(name=device_path)

  return client.delete_device(request=request)

os.environ["CLEARBLADE_CONFIGURATION"] = "/path/to/your-credentials.json"
delete_device()

Go
Code Block
// deleteDevice deletes a device from a registry.
func deleteDevice(w io.Writer, projectID string, region string, registryID string, deviceID string) (*iot.Empty, error) {
    ctx := context.Background()
    service, err := iot.NewService(ctx)
    if err != nil {
                return nil, err
 
      }

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

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

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

        return response, nil}

Java

Code Block
/** 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 = JacksonFactory.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

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

Code Block
# return response, nil
}

Deleting a gateway

To delete a gateway, you first unbind its devices and 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.

API

After unbinding all devices from the gateway, use the device delete method to delete the gateway, specifying the gateway’s ID you want to delete.

Deleting a gateway code samples

Node.js
Code Block
// const cloudRegion = 'us-central1';
// const projectId = 'adjective-noun-123';
// const registryId = 'my-registry';
import { DeviceManagerClient } from '@clearblade/iot';

const iotClient = new 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();

C#
Code Block
{
    logger.LogInformation("Unbind the device");

    var unbindResult = await mClient.UnBindDeviceFromGateway(4, "projects/developmentenv/locations/us-central1/registries/Sample-New-Registry", "TestGateway", "Sample-New-Device");
    if (!unbindResult)
        logger.LogError("Failed to unbind a device");
    else
        logger.LogInformation("Successfully unbind device");

    logger.LogInformation("Delete the device");

    string id = "Sample-New-Device";
    string name = "projects/developmentenv/locations/us-central1/registries/Sample-New-Registry/Devices/Sample-New-Device";

    var deleteResult = await mClient.DeleteDevice(4, id, name);
    if (!deleteResult.Item1 || (deleteResult.Item2 == null))
        logger.LogError("Failed to delete device");
    else
    {
        logger.LogInformation("Successfully deleted the device");
    }
}

Python
Code Block
import os
from clearblade.cloud import iot_v1

def delete_gateway():
  project_id = 'YOUR_PROJECT_ID'#
  cloud_region = 'us-central1'#
  registry_id = 'your-registry-id'#
  devicegateway_id = 'your-devicegateway-id'
  
  print("Delete devicegateway")
  client = iot_v1.DeviceManagerClient()

  device_path = client.device_path(project_id, cloud_region, registry_id, device_id)
_id, gateway_id)

  request = iot_v1.DeleteDeviceRequest(name=device_path)

  return client.delete_device(request={"name": device_path})

Ruby

Code Block
# 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 scopeCloudiot   = 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."request)

os.environ["CLEARBLADE_CONFIGURATION"] = "/path/to/your-credentials.json"
delete_gateway()

Go
Code Block
// deleteDevice deletes a device from a registry.
func deleteDevice(w io.Writer, projectID string, region string, registryID string, deviceID string) (*iot.Empty, error) {
    ctx := context.Background()
    service, err := iot.NewService(ctx)
    if err != nil {
        return nil, err
    }

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

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

    return response, nil
}

What's next

  • Use the MQTT or HTTP bridge to relay messages and configuration data between the devices and ClearBlade IoT Core.