【问题标题】:How can computation on an IotEdge module be triggered from within a .net core app?如何从 .net 核心应用程序中触发 IotEdge 模块上的计算?
【发布时间】:2019-01-11 11:04:12
【问题描述】:

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

https://docs.microsoft.com/en-us/azure/iot-edge/module-development 上面写着

目前,模块无法接收云端到设备的消息

所以看起来调用直接方法似乎是要走的路。如何实现直接方法并从 .NET Core 应用程序中触发它?

【问题讨论】:

    标签: c# azure-iot-hub azure-iot-edge


    【解决方案1】:

    在您的 IotEdge 模块的 Main 或 Init Method 中,您必须创建一个 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);
    }
    

    然后,您可以从您的 .Net 核心应用程序中触发直接方法,如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      • 2018-05-14
      • 2017-05-12
      • 2019-09-07
      • 2021-09-26
      • 1970-01-01
      • 2021-12-05
      相关资源
      最近更新 更多