C# 如何从.net核心应用程序中触发IoEdge模块上的计算?

C# 如何从.net核心应用程序中触发IoEdge模块上的计算?,c#,azure-iot-hub,azure-iot-edge,C#,Azure Iot Hub,Azure Iot Edge,我需要从管理后端应用程序在IotEdge模块上触发一些计算 上面写着 当前,模块无法接收云到设备消息 因此,调用直接方法似乎是一条可行之路。如何在.NET核心应用程序中实现直接方法并触发它?在IoEdge模块的Main或Init方法中,您必须创建一个ModuleClient并将其连接到MethodHandler: AmqpTransportSettings amqpSetting = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only);

我需要从管理后端应用程序在IotEdge模块上触发一些计算

上面写着

当前,模块无法接收云到设备消息


因此,调用直接方法似乎是一条可行之路。如何在.NET核心应用程序中实现直接方法并触发它?

在IoEdge模块的Main或Init方法中,您必须创建一个ModuleClient并将其连接到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);
然后,您必须将DirectMethodHandler添加到IotEge模块:

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);
}
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);
 }