Connect Azure Function to Iot Hub cloud to device

2019-06-14 10:51发布

Is it possible to somehow connect Azure Function to Iot Hub cloud to device feedback endpoint? It looks like this endpoint isn't compatible with Azure Event Hubs.

Write custom event trigger?

I use C# Azure Function.

2条回答
趁早两清
2楼-- · 2019-06-14 11:40

Currently the Cloud to device feedback endpoint doesn't support subscribed for the Azure function directly.

A normal scenario is that we should handle the feedback after sending the C2D messages immediately. That is implement by the IoT Hub Service SDK via ServiceClient.GetFeedbackReceiver(). More detail about handling feedback of C2D messages you can refer Receive delivery feedback.

And if you also want to handle these feedback from Azure function, you can forward it from your ServiceClient using the HTTP Request where you send the C2D messages. Then you can create a Azure function with the Http trigger to receive it.

And if you have any idea and feedback about Azure IoT Hub you can submit it from here.

查看更多
乱世女痞
3楼-- · 2019-06-14 11:45

Yes, you can create a custom function for IoT Hub. This function will be run whenever an IoT Hub delivers a new message for Event Hub compatible endpoints. You can follow below steps:

  1. Create a custom function with IoT Hub(Event Hub) template. enter image description here
  2. Create a json file named project.json with the content like:

    {
      "frameworks": {
        "net46":{
          "dependencies": {
            "Microsoft.Azure.Devices": "1.4.1"
          }
        }
       }
    }
    
  3. Upload the project.json file, it is used to reference the assembly of Microsoft.Azure.Devices.You can see this document to get more information. enter image description here

  4. Add the IoT Hub connection string to the function application Settings. enter image description here

  5. Modified the run.csx as these code:

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

After that save and run the function, if IoT Hub delivers a new message, the function will be triggered, and in the function it will send a cloud-to-device message.

查看更多
登录 后发表回答