...
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( "Device: {} : {} : {} : {}".format( device.id, device.num_id, device.config, device.gateway_config ) ) with io.open(public_key_file) as f: public_key = f.read() if algorithm == "ES256": public_key_format = iot_v1.PublicKeyFormat.ES256_PEM else: 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", } ) if not exists: createDeviceRequest = iot_v1.CreateDeviceRequest( parent=parent, device=gateway ) res = client.create_device(request=createDeviceRequest) print("Created Gateway {}".format(res)) else: print("Gateway exists, skipping") os.environ["CLEARBLADE_CONFIGURATION"] = "/path/to/your-credentials.json" create_gateway() |
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.
Note: Binding is required when using the HTTP bridge.
Console
Go to the Registries page.
Click the gateway’s registry ID.
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, click Unbind device and Unbind 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
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
logger.LogInformation("Successfully bind device");
}
} |
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 |
---|
// 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) (*iot.BindDeviceToGatewayResponse, error) {
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)
bindRequest := &iot.BindDeviceToGatewayRequest{
DeviceId: deviceID,
GatewayId: gatewayID,
}
response, err := service.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
} |
Listing all devices bound to a gateway
Console
Go to the Registries page.
Click the gateway’s registry ID.
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.
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()
{
AssociationsGatewayId = "associated-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 Devices");
// 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() |
Listing all gateways in a registry
Console
Go to the Registries page.
Click the gateway’s registry ID.
On the Registry details page, click Gateways to see a list of the registry’s gateways.
API
Use the Device list method to list all gateways in a registry.
Listing all gateways in a registry 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#
...
...
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)
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 := 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.
Note: Binding is required when using the HTTP bridge.
Console
Go to the Registries page.
Click the gateway’s registry ID.
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, click Unbind device and Unbind 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
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
logger.LogInformation("Successfully bind device");
}
} |
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 |
---|
// 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) (*iot.BindDeviceToGatewayResponse, error) {
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)
bindRequest := &iot.BindDeviceToGatewayRequest{
DeviceId: deviceID,
GatewayId: gatewayID,
}
response, err := service.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
} |
Listing all devices bound to a gateway
Console
Go to the Registries page.
Click the gateway’s registry ID.
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.
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()
{
AssociationsGatewayId = "associated-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 Devices");
// 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
Go to the Registries page.
Click the gateway’s registry ID.
On the Registry details page, click Gateways to see a list of the registry’s gateways.
API
Use the Device list method to list all gateways in a registry.
Listing all gateways in a registry 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", projectID, region, registryID) response, err := service.Projects.Locations.Registries.Devices.List(parent).GatewayListOptionsGatewayType("GATEWAY").Do() if err != nil { return nil, fmt.Errorf("ListGateways: %v", err) } if len(response.Devices) == 0 { loggerfmt.LogInformationFprintln(w, "SucceededNo in getting the list of gatewaysgateways found"); // 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() |
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
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.
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()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
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.
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 := 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
} |
Deleting a gateway
To delete a gateway, you first unbind its devices and then delete the gateway from the registry.
...
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' gateway_id = 'your-gateway-id' print("Delete gateway") client = iot_v1.DeviceManagerClient() device_path = client.device_path(project_id, cloud_region, registry_id, gateway_id) request = iot_v1.DeleteDeviceRequest(name=device_path) return client.delete_device(request=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 } |
...