我需要触发从管理,后台应用程序的IotEdge模块上的一些计算。
在https://docs.microsoft.com/en-us/azure/iot-edge/module-development它说
目前,一个模块不能接收云对设备的消息
如此看来,直接调用方法似乎是要走的路。 我如何能实现的直接方法,并从.NET核心应用内触发呢?
我需要触发从管理,后台应用程序的IotEdge模块上的一些计算。
在https://docs.microsoft.com/en-us/azure/iot-edge/module-development它说
目前,一个模块不能接收云对设备的消息
如此看来,直接调用方法似乎是要走的路。 我如何能实现的直接方法,并从.NET核心应用内触发呢?
在你IotEdge模块的主要或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);
}
从你的.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);
}