本文介绍:

将IoT Hub Service SDK 调用Direct Method 封装为Azure Functions Http Trigger(C#)

 

 

视频介绍:

图文介绍:

本文内容比较简单,不做图文介绍了,直接创建functions,采用http 触发,添加如下代码,发布后即可通过调用http请求的方式,向iot hub 发送 direct method 调用。

注意:

1.引用包:using Microsoft.Azure.Devices;

2.本例调用的客户端案例为\azure-iot-samples-node-master\iot-hub\Quickstarts\simulated-device-2

3. 其中iot hub 连接字符串写入functions 配置文件,deviceid 和payload 通过query string 传递

例如,http://localhost:7071/api/CallDierctMethod?deviceId=device-0001&payload=10

表示将名称为device-0001的设备的上报数据频率改为10秒

 

 

using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Microsoft.Azure.Devices;

namespace Company.Function
{
    public static class CallDierctMethod
    {

        private static ServiceClient s_serviceClient;


        // The function will called like :
        // http://localhost:7071/api/CallDierctMethod?deviceId=device-0001&payload=1

        [FunctionName("CallDierctMethod")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");         

          

            string deviceId = req.Query["deviceId"];

            string payload = req.Query["payload"];

             log.LogInformation($"parameter deviceId:{deviceId},payload:{payload}");

            string s_connectionString = System.Environment.GetEnvironmentVariable("IoTHubConnectionString");
                  
            s_serviceClient = ServiceClient.CreateFromConnectionString(s_connectionString);
            var cloudToDeviceMethodResult= InvokeMethod(deviceId,payload).GetAwaiter().GetResult();
      
             log.LogInformation($"Functions Result:{cloudToDeviceMethodResult.GetPayloadAsJson()}");

            return new OkObjectResult(cloudToDeviceMethodResult);
        }



          private static  async Task<CloudToDeviceMethodResult> InvokeMethod(string deviceId,string  payload)
        {
            var methodInvocation = new CloudToDeviceMethod("SetTelemetryInterval") { ResponseTimeout = TimeSpan.FromSeconds(30) };
            methodInvocation.SetPayloadJson(payload);

            // Invoke the direct method asynchronously and get the response from the simulated device.
            var response =  await s_serviceClient.InvokeDeviceMethodAsync(deviceId, methodInvocation);

            return response;

           
        }
    }
}

 

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet",

    "IoTHubConnectionString":"{your iot hub connection string}"
  }
}