Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Azure.Iot.Hub.Service.Models;

namespace Azure.Iot.Hub.Service.Samples
{
/// <summary>
/// This sample goes through the lifecycle of a Module Identity for a device
/// This sample goes through the lifecycle of a Module Identity for a device.
/// </summary>
internal class ModuleIdentityLifecycleSamples
{
Expand All @@ -24,40 +26,37 @@ public async Task RunSampleAsync()
string moduleId = $"module{Random.Next(MaxRandomValue)}";

// Create a DeviceIdentity.
DeviceIdentity deviceIdentity = await CreateDeviceIdentityAsync(deviceId);
await CreateDeviceIdentityAsync(deviceId);

// Create a ModuleIdentity.
ModuleIdentity moduleIdentity = await CreateModuleIdentityAsync(deviceIdentity, moduleId);
await CreateModuleIdentityAsync(deviceId, moduleId);

// List all modules within the device.
await ListAllModulesAsync();
await ListAllModulesAsync(deviceId);

// Get the Module Identity.
await GetModuleIdentityAsync();
await GetModuleIdentityAsync(deviceId, moduleId);

// Update Module Identity.
await UpdateModuleIdentityAsync();
await UpdateModuleIdentityAsync(deviceId, moduleId);

// Get Module Twin,
await GetModuleTwinAsync();
// Get Module Twin.
await GetModuleTwinAsync(deviceId, moduleId);

// Update Module Twin.
await UpdateModuleTwinAsync();
await UpdateModuleTwinAsync(deviceId, moduleId);

// Invoke a method on the ModuleTwin
await InvokeMethodAsync();
// Delete the module identity.
await DeleteModuleIdentityAsync(deviceId, moduleId);

// Delete the module identity
await DeleteModuleIdentityAsync(moduleIdentity);

// Delete the device (cleanup)
await DeleteDeviceIdentityAsync(deviceIdentity);
// Delete the device (cleanup).
await DeleteDeviceIdentityAsync(deviceId);
}

/// <summary>
/// Creates a new device identity
/// Creates a new device identity.
/// </summary>
/// <param name="deviceId">Device Id for the device identity</param>
/// <param name="deviceId">Unique identifier of the device.</param>
public async Task<DeviceIdentity> CreateDeviceIdentityAsync(string deviceId)
{
SampleLogger.PrintHeader("CREATE DEVICE IDENTITY");
Expand All @@ -72,10 +71,9 @@ public async Task<DeviceIdentity> CreateDeviceIdentityAsync(string deviceId)
{
Console.WriteLine($"Creating a new device with Id '{deviceId}'");

// Call APIs to create the device identity.
Response<DeviceIdentity> response = await IoTHubServiceClient.Devices.CreateOrUpdateIdentityAsync(deviceIdentity);

SampleLogger.PrintSuccess($"Successfully create a new device identity with Id: '{deviceId}'");
SampleLogger.PrintSuccess($"Successfully create a new device identity with Id: '{response.Value.DeviceId}', ETag: '{response.Value.Etag}'");

return response.Value;
}
Expand All @@ -87,18 +85,18 @@ public async Task<DeviceIdentity> CreateDeviceIdentityAsync(string deviceId)
}

/// <summary>
/// Creates a new module identity
/// Creates a new module identity.
/// </summary>
/// <param name="deviceIdentity">Device identity</param>
/// <param name="moduleId">Module Id for the module identity</param>
public async Task<ModuleIdentity> CreateModuleIdentityAsync(DeviceIdentity deviceIdentity, string moduleId)
/// <param name="deviceId">Unique identifier of the device.</param>
/// <param name="moduleId">Unique identifier of the new module.</param>
public async Task<ModuleIdentity> CreateModuleIdentityAsync(string deviceId, string moduleId)
{
SampleLogger.PrintHeader("CREATE MODULE IDENTITY");

// Construct the module identity object.
var moduleIdentity = new ModuleIdentity
{
DeviceId = deviceIdentity.DeviceId,
DeviceId = deviceId,
ModuleId = moduleId
};

Expand All @@ -109,7 +107,7 @@ public async Task<ModuleIdentity> CreateModuleIdentityAsync(DeviceIdentity devic
// Call APIs to create the module identity.
Response<ModuleIdentity> response = await IoTHubServiceClient.Modules.CreateOrUpdateIdentityAsync(moduleIdentity);

SampleLogger.PrintSuccess($"Successfully created a new module identity with Id: '{moduleId}'");
SampleLogger.PrintSuccess($"Successfully created a new module identity: DeviceId: '{deviceId}', ModuleId: '{response.Value.ModuleId}', ETag: '{response.Value.Etag}'");

return response.Value;
}
Expand All @@ -120,53 +118,185 @@ public async Task<ModuleIdentity> CreateModuleIdentityAsync(DeviceIdentity devic
}
}

public Task ListAllModulesAsync()
/// <summary>
/// List all module identities within a device.
/// </summary>
/// <param name="deviceId">Unique identifier of the device to query.</param>
public async Task<IReadOnlyList<ModuleIdentity>> ListAllModulesAsync(string deviceId)
{
return Task.CompletedTask;
}
SampleLogger.PrintHeader("LIST ALL MODULES");

public Task GetModuleIdentityAsync()
{
return Task.CompletedTask;
try
{
Console.WriteLine($"Listing all modules in device with Id: '{deviceId}'\n");

Response<IReadOnlyList<ModuleIdentity>> response = await IoTHubServiceClient.Modules.GetIdentitiesAsync(deviceId);

foreach (ModuleIdentity moduleIdentity in response.Value)
{
SampleLogger.PrintSuccess($"\t- Device Id: '{moduleIdentity.DeviceId}', Module Id: '{moduleIdentity.ModuleId}', ETag: '{moduleIdentity.Etag}'");
}

return response.Value;
}
catch (Exception ex)
{
SampleLogger.FatalError($"Failed to list module identities due to:\n{ex}");
throw;
}
}

public Task UpdateModuleIdentityAsync()
/// <summary>
/// Get a module identity.
/// </summary>
/// <param name="deviceId">Unique identifier of the device the module belongs to.</param>
/// <param name="moduleId">Unique identifier of the module to get.</param>
public async Task<ModuleIdentity> GetModuleIdentityAsync(string deviceId, string moduleId)
{
return Task.CompletedTask;
SampleLogger.PrintHeader("GET A MODULE");

try
{
Console.WriteLine($"Getting module identity with Id: '{moduleId}'\n");

Response<ModuleIdentity> response = await IoTHubServiceClient.Modules.GetIdentityAsync(deviceId, moduleId);

ModuleIdentity moduleIdentity = response.Value;

SampleLogger.PrintSuccess($"\t- Device Id: '{moduleIdentity.DeviceId}', Module Id: '{moduleIdentity.ModuleId}', ETag: '{moduleIdentity.Etag}'");

return moduleIdentity;
}
catch (Exception ex)
{
SampleLogger.FatalError($"Failed to get a module identity due to:\n{ex}");
throw;
}
}

public Task GetModuleTwinAsync()
/// <summary>
/// Update a module identity.
/// </summary>
/// <param name="deviceId">Unique identifier of the device the module belongs to.</param>
/// <param name="moduleId">Unique identifier of the module to be updated.</param>
public async Task<ModuleIdentity> UpdateModuleIdentityAsync(string deviceId, string moduleId)
{
return Task.CompletedTask;
SampleLogger.PrintHeader("UPDATE A MODULE");

try
{
Response<ModuleIdentity> getResponse = await IoTHubServiceClient.Modules.GetIdentityAsync(deviceId, moduleId);

ModuleIdentity moduleIdentity = getResponse.Value;
Console.WriteLine($"Current module identity: DeviceId: '{moduleIdentity.DeviceId}', ModuleId: '{moduleIdentity.ModuleId}', ManagedBy: '{moduleIdentity.ManagedBy ?? "N/A"}', ETag: '{moduleIdentity.Etag}'");

Console.WriteLine($"Updating module identity with Id: '{moduleIdentity.ModuleId}'. Setting 'ManagedBy' property to: '{Environment.UserName}'");
moduleIdentity.ManagedBy = Environment.UserName;

Response<ModuleIdentity> response = await IoTHubServiceClient.Modules.CreateOrUpdateIdentityAsync(moduleIdentity, IfMatchPrecondition.UnconditionalIfMatch);

ModuleIdentity updatedModule = response.Value;

SampleLogger.PrintSuccess($"Successfully updated module identity: DeviceId: '{updatedModule.DeviceId}', ModuleId: '{updatedModule.ModuleId}', ManagedBy: '{updatedModule.ManagedBy}', ETag: '{updatedModule.Etag}'");

return updatedModule;
}
catch (Exception ex)
{
SampleLogger.FatalError($"Failed to update a module identity due to:\n{ex}");
throw;
}
}

public Task UpdateModuleTwinAsync()
/// <summary>
/// Get module twin.
/// </summary>
/// <param name="deviceId">Unique identifier of the device the module belongs to.</param>
/// <param name="moduleId">Unique identifier of the module to be updated.</param>
public async Task<TwinData> GetModuleTwinAsync(string deviceId, string moduleId)
{
return Task.CompletedTask;
SampleLogger.PrintHeader("GET A MODULE TWIN");

try
{
Console.WriteLine($"Getting module twin with Id: '{moduleId}'");

Response<TwinData> response = await IoTHubServiceClient.Modules.GetTwinAsync(deviceId, moduleId);

SampleLogger.PrintSuccess($"\t- Module Twin: DeviceId: '{response.Value.DeviceId}', ModuleId: '{response.Value.ModuleId}', Status: '{response.Value.Status}', ETag: '{response.Value.Etag}'");

return response.Value;
}
catch (Exception ex)
{
SampleLogger.FatalError($"Failed to get a module twin due to:\n{ex}");
throw;
}
}

public Task InvokeMethodAsync()
/// <summary>
/// Update a module twin desired properties.
/// </summary>
/// <param name="deviceId">Unique identifier of the device the module belongs to.</param>
/// <param name="moduleId">Unique identifier of the module to be updated.</param>
public async Task<TwinData> UpdateModuleTwinAsync(string deviceId, string moduleId)
{
return Task.CompletedTask;
SampleLogger.PrintHeader("UPDATE A MODULE TWIN");

string userPropName = "user";

try
{
// Get the device module
Response<TwinData> getResponse = await IoTHubServiceClient.Modules.GetTwinAsync(deviceId, moduleId);
TwinData moduleTwin = getResponse.Value;

Console.WriteLine($"Updating module twin: DeviceId: '{moduleTwin.DeviceId}', ModuleId: '{moduleTwin.ModuleId}', ETag: '{moduleTwin.Etag}'");
Console.WriteLine($"Setting a new desired property {userPropName} to: '{Environment.UserName}'");

moduleTwin.Properties.Desired.Add(new KeyValuePair<string, object>(userPropName, Environment.UserName));

Response<TwinData> response = await IoTHubServiceClient.Modules.UpdateTwinAsync(moduleTwin, IfMatchPrecondition.UnconditionalIfMatch);

TwinData updatedTwin = response.Value;

var userPropValue = (string) updatedTwin.Properties.Desired
.Where(p => p.Key == userPropName)
.First()
.Value;

SampleLogger.PrintSuccess($"Successfully updated module twin: DeviceId: '{updatedTwin.DeviceId}', ModuleId: '{updatedTwin.ModuleId}', desired property: [{userPropName}: '{userPropValue}'], ETag: '{updatedTwin.Etag}',");

return updatedTwin;
}
catch (Exception ex)
{
SampleLogger.FatalError($"Failed to update a module identity due to:\n{ex}");
throw;
}
}

/// <summary>
/// Deletes a module identity
/// Deletes a module identity.
/// </summary>
/// <param name="moduleIdentity">Module identity to delete</param>
public async Task DeleteModuleIdentityAsync(ModuleIdentity moduleIdentity)
/// <param name="deviceId">Unique identifier of the device the module belongs to.</param>
/// <param name="moduleId">Unique identifier of the module to be updated.</param>
public async Task DeleteModuleIdentityAsync(string deviceId, string moduleId)
{
SampleLogger.PrintHeader("DELETE MODULE IDENTITY");

try
{
Console.WriteLine($"Deleting module identity with Id: '{moduleIdentity.ModuleId}'");
// Get the module identity first.
Response<ModuleIdentity> getResponse = await IoTHubServiceClient.Modules.GetIdentityAsync(deviceId, moduleId);
ModuleIdentity moduleIdentity = getResponse.Value;

// Call APIs to delete the module identity.
// We use UnconditionalIfMatch to force delete the Module Identity (disregard the IfMatch ETag)
Console.WriteLine($"Deleting module identity: DeviceId: '{moduleIdentity.DeviceId}', ModuleId: '{moduleIdentity.ModuleId}', ETag: '{moduleIdentity.Etag}'");

// We use UnconditionalIfMatch to force delete the Module Identity (disregard the IfMatch ETag).
Response response = await IoTHubServiceClient.Modules.DeleteIdentityAsync(moduleIdentity, IfMatchPrecondition.UnconditionalIfMatch);

SampleLogger.PrintSuccess($"Successfully deleted module identity with Id: '{moduleIdentity.ModuleId}'");
SampleLogger.PrintSuccess($"Successfully deleted module identity: DeviceId: '{deviceId}', ModuleId: '{moduleId}'");
}
catch (Exception ex)
{
Expand All @@ -175,19 +305,22 @@ public async Task DeleteModuleIdentityAsync(ModuleIdentity moduleIdentity)
}

/// <summary>
/// Deletes a device identity
/// Deletes a device identity.
/// </summary>
/// <param name="deviceIdentity">Device identity to delete</param>
public async Task DeleteDeviceIdentityAsync(DeviceIdentity deviceIdentity)
/// <param name="deviceId">Unique identifier of the device.</param>
public async Task DeleteDeviceIdentityAsync(string deviceId)
{
SampleLogger.PrintHeader("DELETE DEVICE IDENTITY");

try
{
// Get the device identity first.
Response<DeviceIdentity> getResponse = await IoTHubServiceClient.Devices.GetIdentityAsync(deviceId);
DeviceIdentity deviceIdentity = getResponse.Value;

Console.WriteLine($"Deleting device identity with Id: '{deviceIdentity.DeviceId}'");

// Call APIs to delete the device identity.
// We use UnconditionalIfMatch to force delete the Device Identity (disregard the IfMatch ETag)
// We use UnconditionalIfMatch to force delete the Device Identity (disregard the IfMatch ETag).
Response response = await IoTHubServiceClient.Devices.DeleteIdentityAsync(deviceIdentity, IfMatchPrecondition.UnconditionalIfMatch);

SampleLogger.PrintSuccess($"Successfully deleted device identity with Id: '{deviceIdentity.DeviceId}'");
Expand Down
Loading