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 you've created a registry and a device key pair before completing the steps in this section.
Console
To create a new gateway:
Go to the Registries page in Google Cloud console.
Click the ID of the registry for the gateway.
On the Registry details page, click Gateways, then click Add gateway to create a new gateway.
Enter a Gateway ID that briefly describes the gateway or otherwise helps you identify it. (This field can't be edited later.)
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 ClearBlade IoT Core.
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.
Select the authentication method to use for devices bound to the gateway.
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.
Click Create to create the gateway or Update to save changes to an existing gateway.
To edit an existing gateway:
Go to the Registries page.
Click the ID of the registry for the gateway.
Click Registry details.
Click Gateways.
Click the ID of the gateway you want to edit.
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 methods to create or edit a gateway:
To learn how to create the devices you'll use with the gateway, see Creating or editing a device.
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
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); System.out.println("Creating gateway with id: " + gatewayId);Device device = new Device(); device.setId(gatewayId); GatewayConfig gwConfig = new GatewayConfig(); gwConfig.setGatewayType("GATEWAY"); gwConfig.setGatewayAuthMethod("ASSOCIATION_ONLY"); String keyFormat = "RSA_X509_PEM";if ("ES256".equals(algorithm)) { keyFormat = "ES256_PEM";} PublicKeyCredential publicKeyCredential = new PublicKeyCredential(); byte[] keyBytes = java.nio.file.Files.readAllBytes(Paths.get(certificateFilePath)); publicKeyCredential.setKey(new String(keyBytes, StandardCharsets.US_ASCII)); publicKeyCredential.setFormat(keyFormat);DeviceCredential deviceCredential = new DeviceCredential(); deviceCredential.setPublicKey(publicKeyCredential); device.setGatewayConfig(gwConfig); device.setCredentials(Collections.singletonList(deviceCredential));Device createdDevice = service .projects() .locations() .registries() .devices() .create(registryPath, device) .execute(); System.out.println("Created gateway: " + createdDevice.toPrettyString());
Node.js
// const cloudRegion = 'us-central1';// const deviceId = 'my-unauth-device';// const gatewayId = 'my-gateway';// const projectId = 'adjective-noun-123';// const registryId = 'my-registry';// const gatewayAuthMethod = 'ASSOCIATION_ONLY';const iot = require('@google-cloud/iot'); const iotClient = new iot.v1.DeviceManagerClient({ // optional auth parameters.}); async function createDevice() { // Construct request const regPath = iotClient.registryPath(projectId, cloudRegion, registryId); console.log('Creating gateway:', gatewayId); let credentials = []; // if public key format and path are specified, use those if (publicKeyFormat && publicKeyFile) { credentials = [ { publicKey: { format: publicKeyFormat, key: readFileSync(publicKeyFile).toString(), }, }, ]; } const device = { id: gatewayId, credentials: credentials, gatewayConfig: { gatewayType: 'GATEWAY', gatewayAuthMethod: gatewayAuthMethod, }, }; const request = { parent: regPath, device, }; const [response] = await iotClient.createDevice(request); console.log('Created device:', response);} createDevice();
Python
# project_id = 'YOUR_PROJECT_ID'# cloud_region = 'us-central1'# registry_id = 'your-registry-id'# device_id = 'your-device-id'# gateway_id = 'your-gateway-id'# certificate_file = 'path/to/certificate.pem'# algorithm = 'ES256'# Check that the gateway doesn't already exist exists = False client = iot_v1.DeviceManagerClient() parent = client.registry_path(project_id, cloud_region, registry_id) devices = list(client.list_devices(request={"parent": parent})) for device in devices: if device.id == gateway_id: exists = True print( "Device: {} : {} : {} : {}".format( device.id, device.num_id, device.config, device.gateway_config ) ) with io.open(certificate_file) as f: certificate = f.read() if algorithm == "ES256": certificate_format = iot_v1.PublicKeyFormat.ES256_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
# 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
Go to the Registries page.
Click the ID of the registry for the gateway.
Click Gateways, then click the gateway's ID.
On the Gateway details page, click Bound devices.
Click Bind device.
Select the devices you want to bind to the gateway, then click Bind.
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:
Registries BindDeviceToGateway method to bind devices to gateways
Registries UnbindDeviceFromGateway method to unbind devices from gateways
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); 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
// const cloudRegion = 'us-central1';// const deviceId = 'my-unauth-device';// const gatewayId = 'my-gateway';// const projectId = 'adjective-noun-123';// const registryId = 'my-registry';const iot = require('@google-cloud/iot'); const iotClient = new iot.v1.DeviceManagerClient({ // optional auth parameters.}); async function bindDeviceToGateway() { // Construct request const regPath = iotClient.registryPath(projectId, cloudRegion, registryId); const bindRequest = { parent: regPath, deviceId: deviceId, gatewayId: gatewayId, }; console.log(`Binding device: ${deviceId}`); await iotClient.bindDeviceToGateway(bindRequest); console.log(`Bound ${deviceId} to`, gatewayId);} bindDeviceToGateway();
Python
# project_id = 'YOUR_PROJECT_ID'# cloud_region = 'us-central1'# registry_id = 'your-registry-id'# device_id = 'your-device-id'# gateway_id = 'your-gateway-id' client = iot_v1.DeviceManagerClient() create_device( service_account_json, project_id, cloud_region, registry_id, device_id) parent = client.registry_path(project_id, cloud_region, registry_id) res = client.bind_device_to_gateway( request={"parent": parent, "gateway_id": gateway_id, "device_id": device_id}) print("Device Bound! {}".format(res))
Ruby
# project_id = "Your Google Cloud project ID"# location_id = "The Cloud region the registry is located in"# registry_id = "The registry to create a device in"# gateway_id = "The Gateway to bind to"# device_id = "The identifier of the device to bind" require "google/apis/cloudiot_v1" # Initialize the client and authenticate with the specified 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
Go to the Registries page.
Click the ID of the registry for the gateway.
Click Gateways, then click the gateway's ID.
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#
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
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
// const cloudRegion = 'us-central1';// const gatewayId = 'my-gateway';// const projectId = 'adjective-noun-123';// const registryId = 'my-registry';const iot = require('@google-cloud/iot');const iotClient = new iot.v1.DeviceManagerClient({ // optional auth parameters.}); async function listDevices() { // Construct request const parentName = iotClient.registryPath( projectId, cloudRegion, registryId ); const [response] = await iotClient.listDevices({ parent: parentName, gatewayListOptions: {associationsGatewayId: gatewayId}, }); const devices = response; if (devices.length > 0) { console.log('Current devices bound to gateway: ', gatewayId); } else { console.log('No devices bound to this gateway.'); } for (let i = 0; i < devices.length; i++) { const device = devices[i]; console.log(`\tDevice: ${device.numId}: ${device.id}`); }} listDevices();
Python
# project_id = 'YOUR_PROJECT_ID'# cloud_region = 'us-central1'# registry_id = 'your-registry-id'# gateway_id = 'your-gateway-id' client = iot_v1.DeviceManagerClient() path = client.registry_path(project_id, cloud_region, registry_id) devices = list( client.list_devices( request={ "parent": path, "gateway_list_options": {"associations_gateway_id": gateway_id}, } )) found = 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
# 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
Go to the Registries page.
Click the ID of the registry for the gateway.
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#
public static object ListGateways(string projectId, string cloudRegion, string registryName){ var cloudIot = CreateAuthorizedClient(); var registryPath = $"projects/{projectId}/locations/{cloudRegion}/registries/{registryName}"; var req = cloudIot .Projects .Locations .Registries .Devices .List(registryPath); req.FieldMask = "config,gatewayConfig"; var devices = req.Execute().Devices; if (devices != null) { Console.WriteLine("Found {0} devices", devices.Count); devices.ToList().ForEach(device => { if (device.GatewayConfig != null && device.GatewayConfig.GatewayType != null && device.GatewayConfig.GatewayType.Equals("GATEWAY")) { Console.WriteLine("Id :{0}", device.Id); if (device.Config != null) { Console.WriteLine("Config: {0}", device.Config.ToString()); } } } ); } else { Console.WriteLine("Registry has no gateway devices"); } return 0;}
Go
// listGateways lists all the gateways in a specific registry. func listGateways(w io.Writer, projectID string, region string, registryID string) ([]*cloudiot.Device, error) { // Authorize the client using Application Default Credentials. // See https://g.co/dv/identity/protocols/application-default-credentials ctx := context.Background() httpClient, err := google.DefaultClient(ctx, cloudiot.CloudPlatformScope) if err != nil { return nil, err } client, err := cloudiot.New(httpClient) if err != nil { return nil, err } parent := fmt.Sprintf("projects/%s/locations/%s/registries/%s", projectID, region, registryID) response, err := client.Projects.Locations.Registries.Devices.List(parent).GatewayListOptionsGatewayType("GATEWAY").Do() if err != nil { return nil, fmt.Errorf("ListGateways: %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}
Java
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) { // Note that this will show the device config in Base64 encoded format. System.out.println("Config: " + d.getGatewayConfig().toPrettyString()); } System.out.println(); }} else { System.out.println("Registry has no devices.");}
Node.js
// const cloudRegion = 'us-central1';// const projectId = 'adjective-noun-123';// const registryId = 'my-registry';const iot = require('@google-cloud/iot');const iotClient = new iot.v1.DeviceManagerClient({ // optional auth parameters.}); async function listDevices() { // Construct request const registryPath = iotClient.registryPath( projectId, cloudRegion, registryId ); console.log('Current gateways in registry:'); const [response] = await iotClient.listDevices({ parent: registryPath, fieldMask: {paths: ['config', 'gateway_config']}, }); const devices = response; devices.forEach(device => { if ( device.gatewayConfig !== undefined && device.gatewayConfig.gatewayType === 'GATEWAY' ) { console.log('----\n', device); } });} listDevices();
Python
# project_id = 'YOUR_PROJECT_ID'# cloud_region = 'us-central1'# registry_id = 'your-registry-id' client = iot_v1.DeviceManagerClient() path = client.registry_path(project_id, cloud_region, registry_id) mask = gp_field_mask.FieldMask() mask.paths.append("config") mask.paths.append("gateway_config") devices = list(client.list_devices(request={"parent": path, "field_mask": mask})) for device in devices: if device.gateway_config is not None: if device.gateway_config.gateway_type == 1: print("Gateway ID: {}\n\t{}".format(device.id, device))
Ruby
# project_id = "Your Google Cloud project ID"# location_id = "The Cloud region for the registry"# registry_id = "The registry to list gateways in" require "google/apis/cloudiot_v1" # Initialize the client and authenticate with the specified 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
Unbind the device from every gateway it's bound to.
In the Device details page, click Delete.
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#
public static object DeleteDevice(string projectId, string cloudRegion, string registryId, string deviceId){ var cloudIot = CreateAuthorizedClient(); // The resource name of the location associated with the key rings. var name = $"projects/{projectId}/locations/{cloudRegion}/registries/{registryId}/devices/{deviceId}"; try { var res = cloudIot.Projects.Locations.Registries.Devices.Delete(name).Execute(); Console.WriteLine($"Removed device: {deviceId}"); } catch (Google.GoogleApiException e) { Console.WriteLine(e.Message); if (e.Error != null) return e.Error.Code; return -1; } return 0;}
Go
// deleteDevice deletes a device from a registry. func deleteDevice(w io.Writer, projectID string, region string, registryID string, deviceID string) (*cloudiot.Empty, error) { // Authorize the client using Application Default Credentials. // See https://g.co/dv/identity/protocols/application-default-credentials ctx := context.Background() httpClient, err := google.DefaultClient(ctx, cloudiot.CloudPlatformScope) if err != nil { return nil, err } client, err := cloudiot.New(httpClient) if err != nil { return nil, err } path := fmt.Sprintf("projects/%s/locations/%s/registries/%s/devices/%s", projectID, region, registryID, deviceID) response, err := client.Projects.Locations.Registries.Devices.Delete(path).Do() if err != nil { return nil, err } fmt.Fprintf(w, "Deleted device: %s\n", deviceID) return response, nil}
Java
/** Delete the given device from the registry. */protected static void deleteDevice( String deviceId, String projectId, String cloudRegion, String registryName) throws GeneralSecurityException, IOException { GoogleCredentials credential = GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all()); JsonFactory jsonFactory = 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
// const cloudRegion = 'us-central1';// const projectId = 'adjective-noun-123';// const registryId = 'my-registry';const iot = require('@google-cloud/iot'); const iotClient = new iot.v1.DeviceManagerClient({ // optional auth parameters.}); async function deleteDevice() { // Construct request const devPath = iotClient.devicePath( projectId, cloudRegion, registryId, deviceId ); const [responses] = await iotClient.deleteDevice({name: devPath}); console.log('Successfully deleted device', responses);} deleteDevice();
Python
# project_id = 'YOUR_PROJECT_ID'# cloud_region = 'us-central1'# registry_id = 'your-registry-id'# device_id = 'your-device-id'print("Delete device") client = iot_v1.DeviceManagerClient() device_path = client.device_path(project_id, cloud_region, registry_id, device_id) return client.delete_device(request={"name": device_path})
Ruby
# project_id = "Your Google Cloud project ID"# location_id = "The Cloud region the registry is located in"# registry_id = "The registry to create a device in"# device_id = "The identifier of the device to delete" require "google/apis/cloudiot_v1" # Initialize the client and authenticate with the specified 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
Go back to the Gateway details page and click Delete.
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#
public static object DeleteDevice(string projectId, string cloudRegion, string registryId, string deviceId){ var cloudIot = CreateAuthorizedClient(); // The resource name of the location associated with the key rings. var name = $"projects/{projectId}/locations/{cloudRegion}/registries/{registryId}/devices/{deviceId}"; try { var res = cloudIot.Projects.Locations.Registries.Devices.Delete(name).Execute(); Console.WriteLine($"Removed device: {deviceId}"); } catch (Google.GoogleApiException e) { Console.WriteLine(e.Message); if (e.Error != null) return e.Error.Code; return -1; } return 0;}
Go
// deleteDevice deletes a device from a registry. func deleteDevice(w io.Writer, projectID string, region string, registryID string, deviceID string) (*cloudiot.Empty, error) { // Authorize the client using Application Default Credentials. // See https://g.co/dv/identity/protocols/application-default-credentials ctx := context.Background() httpClient, err := google.DefaultClient(ctx, cloudiot.CloudPlatformScope) if err != nil { return nil, err } client, err := cloudiot.New(httpClient) if err != nil { return nil, err } path := fmt.Sprintf("projects/%s/locations/%s/registries/%s/devices/%s", projectID, region, registryID, deviceID) response, err := client.Projects.Locations.Registries.Devices.Delete(path).Do() if err != nil { return nil, err } fmt.Fprintf(w, "Deleted device: %s\n", deviceID) return response, nil}
Java
/** Delete the given device from the registry. */protected static void deleteDevice( String deviceId, String projectId, String cloudRegion, String registryName) throws GeneralSecurityException, IOException { GoogleCredentials credential = GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all()); JsonFactory jsonFactory = 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
// const cloudRegion = 'us-central1';// const projectId = 'adjective-noun-123';// const registryId = 'my-registry';const iot = require('@google-cloud/iot'); const iotClient = new iot.v1.DeviceManagerClient({ // optional auth parameters.}); async function deleteDevice() { // Construct request const devPath = iotClient.devicePath( projectId, cloudRegion, registryId, deviceId ); const [responses] = await iotClient.deleteDevice({name: devPath}); console.log('Successfully deleted device', responses);} deleteDevice();
Python
# project_id = 'YOUR_PROJECT_ID'# cloud_region = 'us-central1'# registry_id = 'your-registry-id'# device_id = 'your-device-id'print("Delete device") client = iot_v1.DeviceManagerClient() device_path = client.device_path(project_id, cloud_region, registry_id, device_id) return client.delete_device(request={"name": device_path})
Ruby
# project_id = "Your Google Cloud project ID"# location_id = "The Cloud region the registry is located in"# registry_id = "The registry to create a device in"# device_id = "The identifier of the device to delete" require "google/apis/cloudiot_v1" # Initialize the client and authenticate with the specified 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."