官术网_书友最值得收藏!

How to do it...

In this section, we will start with registering the new device, followed by some more device management operations such as: retrieve, delete, list, export, and import.

  1. Create a device identity by initializing the Azure IoT Hub registry connection:
string deviceId = "myFirstDevice";
registryManager = RegistryManager.CreateFromConnectionString(connectionString);
Device device = new Device();
try
{
device = await registryManager.AddDeviceAsync(new Device(deviceId));
success = true;
}
catch (DeviceAlreadyExistsException)
{
success = false;
}
  1. Retrieve the device identity by deviceId:
string deviceId = "myFirstDevice";
Device device = new Device();
try
{
device = await registryManager.GetDeviceAsync(deviceId);
}
catch (DeviceAlreadyExistsException)
{
return device;
}
  1. Delete the device identity:
string deviceId = "myFirstDevice";
Device device = new Device();
try
{
device = GetDevice(deviceId);
await registryManager.RemoveDeviceAsync(device);
success = true;
}
catch (Exception ex)
{
success = false;
}
  1. Disable the IoT device from the device registry. This can be handled through an IoT solution in certain scenarios, such as if the device is tampered with or these are some critical issues with the device:
   string deviceId = "myFirstDevice";    
Device device = new Device();
try
{
device = GetDevice(deviceId);
device.Status = DeviceStatus.Disabled;
// Update the device registry
await registryManager.UpdateDeviceAsync(device);
success = true;
}
catch (Exception ex)
{
success = false;
}
  1. List up to 1000 identities:
try
{
var devicelist = registryManager.GetDevicesAsync(1000);
return devicelist.Result;
}
catch (Exception ex)
{
//
  1. Export all the identities to Azure Blob storage:
var blobClient = storageAccount.CreateCloudBlobClient();

string Containername = "iothubdevices";

//Get a reference to a container
var container = blobClient.GetContainerReference(Containername);
container.CreateIfNotExists();

//Generate a SAS token
var storageUri = GetContainerSasUri(container);
await registryManager.ExportDevicesAsync(storageUri, "devices1.txt", false);
}
  1. Import all the identities to Azure Blob storage:
await registryManager.ImportDevicesAsync(storageUri, OutputStorageUri);

The output of ImportDevice methods creates a job which can be used to perform bulk operation like create and delete.

主站蜘蛛池模板: 临猗县| 太康县| 贺兰县| 绩溪县| 南通市| 安达市| 永宁县| 郧西县| 孟州市| 金华市| 吉林市| 曲阳县| 防城港市| 宁远县| 三门县| 赤水市| 夏津县| 南投市| 金华市| 江油市| 凉城县| 肥城市| 文山县| 和平县| 岑巩县| 四平市| 孝感市| 峨山| 耒阳市| 会泽县| 基隆市| 化德县| 永嘉县| 都兰县| 寿光市| 遵义县| 永平县| 平武县| 华宁县| 金川县| 新郑市|