How can computation on an IotEdge module be triggered from within a .net core app?

最后都变了- 提交于 2019-12-11 07:57:59

问题


I need to trigger some computation on an IotEdge module from an Administration-Backend Application.

On https://docs.microsoft.com/en-us/azure/iot-edge/module-development it says

Currently, a module cannot receive cloud-to-device messages

So it seems that calling direct methods seems to be the way to go. How can I implement a direct method and trigger it from within a .NET Core App?


回答1:


In Main or Init Method of your IotEdge module you have to create a ModuleClient and connect it to a MethodHandler:

AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only);
ITransportSettings[] settings = { amqpSetting };

ModuleClient ioTHubModuleClient = await ModuleClient.CreateFromEnvironmentAsync(settings);
await ioTHubModuleClient.OpenAsync();

await ioTHubModuleClient.SetMethodHandlerAsync("MyDirectMethodName", MyDirectMethodHandler, null);

Then you have to add the DirectMethodHandler to your IotEge module:

static async Task<MethodResponse> MyDirectMethodHandler(MethodRequest methodRequest, object userContext)
{
    Console.WriteLine($"My direct method has been called!");
    var payload = methodRequest.DataAsJson;
    Console.WriteLine($"Payload: {payload}");

    try
    {
        // perform your computation using the payload
    }
    catch (Exception e)
    {
         Console.WriteLine($"Computation failed! Error: {e.Message}");
         return new MethodResponse(Encoding.UTF8.GetBytes("{\"errormessage\": \"" + e.Message + "\"}"), 500);
    }

    Console.WriteLine($"Computation successfull.");
    return new MethodResponse(Encoding.UTF8.GetBytes("{\"status\": \"ok\"}"), 200);
}

From within your .Net core Application you can then trigger the direct method like this:

var iotHubConnectionString = "MyIotHubConnectionString";
var deviceId = "MyDeviceId";
var moduleId = "MyModuleId";
var methodName = "MyDirectMethodName";
var payload = "MyJsonPayloadString";

var cloudToDeviceMethod = new CloudToDeviceMethod(methodName, TimeSpan.FromSeconds(10));
cloudToDeviceMethod.SetPayloadJson(payload);

ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString);

try
{
    var methodResult = await serviceClient.InvokeDeviceMethodAsync(deviceId, moduleId, cloudToDeviceMethod);

    if(methodResult.Status == 200)
    {
        // Handle Success
    }
    else if (methodResult.Status == 500)
    {
        // Handle Failure
    }
 }
 catch (Exception e)
 {
     // Device does not exist or is offline
     Console.WriteLine(e.Message);
 }


来源:https://stackoverflow.com/questions/54145260/how-can-computation-on-an-iotedge-module-be-triggered-from-within-a-net-core-ap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!