首页 > 解决方案 > 将 Azure Function 连接到 IoT Hub 云到设备反馈端点

问题描述

是否有可能以某种方式将 Azure Function 连接到 IoT Hub 云到设备反馈端点?此终结点似乎与 Azure 事件中心不兼容。

编写自定义事件触发器?

我使用 C# Azure 函数。

标签: c#azure-iot-hub

解决方案


是的,您可以为 IoT 中心创建自定义函数。每当 IoT 中心为事件中心兼容终结点提供新消息时,都会运行此函数。您可以按照以下步骤操作:

  1. 使用 IoT 中心(事件中心)模板创建自定义函数。 在此处输入图像描述
  2. 创建一个名为project.json的 json 文件,其内容如下:

    {
      "frameworks": {
        "net46":{
          "dependencies": {
            "Microsoft.Azure.Devices": "1.4.1"
          }
        }
       }
    }
    
  3. 上传 project.json 文件,用于引用 Microsoft.Azure.Devices 的程序集。您可以查看此文档以获取更多信息。 在此处输入图像描述

  4. 将 IoT 中心连接字符串添加到函数应用程序设置。 在此处输入图像描述

  5. 将 run.csx 修改为以下代码:

    #r "Microsoft.ServiceBus"
    
    using System.Configuration;
    using System.Text;
    using System.Net;
    using Microsoft.Azure.Devices;
    using Microsoft.ServiceBus.Messaging;
    using Newtonsoft.Json;
    
    static Microsoft.Azure.Devices.ServiceClient client =     ServiceClient.CreateFromConnectionString(ConfigurationManager.AppSettings["iothubConnectionstring"]);
    
    public static async void Run(EventData myIoTHubMessage, TraceWriter log)
    {
        log.Info($"{myIoTHubMessage.SystemProperties["iothub-connection-device-id"]}");
        var deviceId = myIoTHubMessage.SystemProperties["iothub-connection-device-id"].ToString();
        var msg = JsonConvert.SerializeObject(new { temp = 20.5 });
        var c2dmsg = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(msg));
    
        await client.SendAsync(deviceId, c2dmsg);
    }
    

保存并运行该函数后,如果 IoT Hub 下发了一条新消息,该函数将被触发,并在该函数中发送一条云到设备的消息。


推荐阅读