1
votes

I am getting this error when I am trying to connect to IoT Hub using Azure functions:

The listener for function 'IoTHubDataFunction' was unable to start. Microsoft.Azure.EventHubs.Processor: Encountered error while fetching the list of EventHub PartitionIds. System.Private.CoreLib: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

This is my function app code. It simply has an IoT Hub trigger and a consumer group and it logs the incoming message.

[FunctionName("IoTHubDataFunction")]
public static void Run([IoTHubTrigger("messages/events", Connection = "IoTHubTriggerConnection", ConsumerGroup = "funcgroup")]EventData message, ILogger log)
{
    log.LogInformation($"C# IoT Hub trigger function processed a message: {Encoding.UTF8.GetString(message.Body.Array)}");
}

And this is my local.settings.json file

{
  "IsEncrypted": false,

  "Values": {
    "IoTHubTriggerConnection": "My IoT Hub connection string",
    "AzureWebJobsStorage": "Storage connection string",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet"
  }
}

I am getting the IoT Hub connection string from Azure portal:

enter image description here

2

2 Answers

0
votes

I can't tell you what's wrong with your code but I can tell you this works for me:

[FunctionName("QueueTrigger")]
        public static void Run(
            [EventHubTrigger("<hubname>", Connection = "hub2", ConsumerGroup = "<optional>")]string myEventHubMessage, 
            ILogger log)
        {
            log.LogInformation($" Queue trigger function processed: {myEventHubMessage}");
        }

The connection string, hub2 in my instance, in localsettings.json (or the environment when running in Azure) is the same as the one you referred to. Essentially this just treats the IoT hub as an Event Hub.

0
votes

Try the following working sample:

using IoTHubTrigger = Microsoft.Azure.WebJobs.EventHubTriggerAttribute;
using System.Linq;
//...

[FunctionName("IoTHubDataFunction")]
public static void Run2([IoTHubTrigger("messages/events", Connection = "IoTHubTriggerConnection", ConsumerGroup = "funcgroup")]EventData message, ILogger log)
{
    log.LogInformation($"\nBody:\n\t{Encoding.UTF8.GetString(message.Body.Array)}" +
                       $"\nSystemProperties:\n\t{string.Join("\n\t", message.SystemProperties.Select(i => $"{i.Key}={i.Value}"))}" +
                       $"\nProperties:\n\t{string.Join("\n\t", message.Properties.Select(i => $"{ i.Key}={ i.Value}"))}");
}