I want to create an azure function to monitor the health of my edge modules in the iothub. By Retrieving the twin Properties of the module i will be able to do it. Infact i have a C# code which is giving the desired result. But I am very new to the concept of azure functions and i am stuck on how to work with them. following is the code i am using to retrieve module twin properties:
public class TwinSample
{
private ModuleClient _moduleClient;
public TwinSample(ModuleClient moduleClient)
{
_moduleClient = moduleClient ?? throw new ArgumentNullException(nameof(moduleClient));
}
public async Task<string> RunSampleAsync()
{
Console.WriteLine("Retrieving twin...");
Twin twin = await _moduleClient.GetTwinAsync().ConfigureAwait(false);
Console.WriteLine("\tInitial twin value received:");
Console.WriteLine($"\t{twin.ToJson()}");
return twin.ToJson();
}
}
public static void Main(string[] args)
{
if (string.IsNullOrEmpty(s_moduleConnectionString) && args.Length > 0)
{
s_moduleConnectionString = args[0];
}
ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(s_moduleConnectionString, s_transportType);
var sample = new TwinSample(moduleClient);
Sample.RunSampleAsync().GetAwaiter().GetResult();
Console.ReadLine();
}
Can any one explain me how to make the same functionality work in azure function?
Thank You.
It depends on which trigger you want to use (the condition to run your Function). Here is a sample for Timer based function:
public static class MyApp
{
[FunctionName("TimerTriggerCSharp")]
public static async Task Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer)
{
var moduleConnectionString = Environment.GetEnvironmentVariable("ModuleConnectionString", EnvironmentVariableTarget.Process);
var transportType = Environment.GetEnvironmentVariable("TransportType", EnvironmentVariableTarget.Process);
ModuleClient moduleClient = ModuleClient.CreateFromConnectionString(moduleConnectionString, transportType);
var sample = new TwinSample(moduleClient);
await sample.RunSampleAsync();
}
}
Definition of TwinSample
can be reused from your original code.
You would need to set the values for ModuleConnectionString
and TransportType
in Application settings of Azure Functions (e.g. via the portal).
P.S. Welcome to Stack Overflow. Your question is a bit broad for the standards of this site, because it just asks "how do I do this" instead of giving the code/approach that you already tried. Next time, please go though Getting Started samples of Azure Functions and try to apply your code to them before asking a question.