Azure IoT Hub trigger for Azure Functions
This article explains how to work with Azure Functions bindings for IoT Hub. The IoT Hub support is based on the Azure Event Hubs Binding.
For information on setup and configuration details, see the overview.
Important
While the following code samples use the Event Hub API, the given syntax is applicable for IoT Hub functions.
Use the function trigger to respond to an event sent to an event hub event stream. You must have read access to the underlying event hub to set up the trigger. When the function is triggered, the message passed to the function is typed as a string.
Event Hubs scaling decisions for the Consumption and Premium plans are done via Target Based Scaling. For more information, see Target Based Scaling.
For information about how Azure Functions responds to events sent to an event hub event stream using triggers, see Integrate Event Hubs with serverless functions on Azure.
Azure Functions supports two programming models for Python. The way that you define your bindings depends on your chosen programming model.
The Python v2 programming model lets you define bindings using decorators directly in your Python function code. For more information, see the Python developer guide.
This article supports both programming models.
Important
The Python v2 programming model is currently in preview.
Example
The following example shows a C# function that logs the message body of the Event Hubs trigger.
[FunctionName("EventHubTriggerCSharp")]
public void Run([EventHubTrigger("samples-workitems", Connection = "EventHubConnectionAppSetting")] string myEventHubMessage, ILogger log)
{
log.LogInformation($"C# function triggered to process a message: {myEventHubMessage}");
}
To get access to event metadata in function code, bind to an EventData object. You can also access the same properties by using binding expressions in the method signature. The following example shows both ways to get the same data:
[FunctionName("EventHubTriggerCSharp")]
public void Run(
[EventHubTrigger("samples-workitems", Connection = "EventHubConnectionAppSetting")] EventData myEventHubMessage,
DateTime enqueuedTimeUtc,
Int64 sequenceNumber,
string offset,
ILogger log)
{
log.LogInformation($"Event: {Encoding.UTF8.GetString(myEventHubMessage.Body)}");
// Metadata accessed by binding to EventData
log.LogInformation($"EnqueuedTimeUtc={myEventHubMessage.SystemProperties.EnqueuedTimeUtc}");
log.LogInformation($"SequenceNumber={myEventHubMessage.SystemProperties.SequenceNumber}");
log.LogInformation($"Offset={myEventHubMessage.SystemProperties.Offset}");
// Metadata accessed by using binding expressions in method parameters
log.LogInformation($"EnqueuedTimeUtc={enqueuedTimeUtc}");
log.LogInformation($"SequenceNumber={sequenceNumber}");
log.LogInformation($"Offset={offset}");
}
To receive events in a batch, make string
or EventData
an array.
Note
When receiving in a batch you cannot bind to method parameters like in the above example with DateTime enqueuedTimeUtc
and must receive these from each EventData
object
[FunctionName("EventHubTriggerCSharp")]
public void Run([EventHubTrigger("samples-workitems", Connection = "EventHubConnectionAppSetting")] EventData[] eventHubMessages, ILogger log)
{
foreach (var message in eventHubMessages)
{
log.LogInformation($"C# function triggered to process a message: {Encoding.UTF8.GetString(message.Body)}");
log.LogInformation($"EnqueuedTimeUtc={message.SystemProperties.EnqueuedTimeUtc}");
}
}
The following example shows an Event Hubs trigger binding in a function.json file and a JavaScript function that uses the binding. The function reads event metadata and logs the message.
The following example shows an Event Hubs binding data in the function.json file, which is different for version 1.x of the Functions runtime compared to later versions.
{
"type": "eventHubTrigger",
"name": "myEventHubMessage",
"direction": "in",
"eventHubName": "MyEventHub",
"connection": "myEventHubReadConnectionAppSetting"
}
Here's the JavaScript code:
module.exports = function (context, myEventHubMessage) {
context.log('Function triggered to process a message: ', myEventHubMessage);
context.log('EnqueuedTimeUtc =', context.bindingData.enqueuedTimeUtc);
context.log('SequenceNumber =', context.bindingData.sequenceNumber);
context.log('Offset =', context.bindingData.offset);
context.done();
};
To receive events in a batch, set cardinality
to many
in the function.json file, as shown in the following examples.
{
"type": "eventHubTrigger",
"name": "eventHubMessages",
"direction": "in",
"eventHubName": "MyEventHub",
"cardinality": "many",
"connection": "myEventHubReadConnectionAppSetting"
}
Here's the JavaScript code:
module.exports = function (context, eventHubMessages) {
context.log(`JavaScript eventhub trigger function called for message array ${eventHubMessages}`);
eventHubMessages.forEach((message, index) => {
context.log(`Processed message ${message}`);
context.log(`EnqueuedTimeUtc = ${context.bindingData.enqueuedTimeUtcArray[index]}`);
context.log(`SequenceNumber = ${context.bindingData.sequenceNumberArray[index]}`);
context.log(`Offset = ${context.bindingData.offsetArray[index]}`);
});
context.done();
};
Here's the PowerShell code:
param($eventHubMessages, $TriggerMetadata)
Write-Host "PowerShell eventhub trigger function called for message array: $eventHubMessages"
$eventHubMessages | ForEach-Object { Write-Host "Processed message: $_" }
The following example shows an Event Hubs trigger binding and a Python function that uses the binding. The function reads event metadata and logs the message. The example depends on whether you use the v1 or v2 Python programming model.
import logging
import azure.functions as func
app = func.FunctionApp()
@app.function_name(name="EventHubTrigger1")
@app.event_hub_message_trigger(arg_name="myhub",
event_hub_name="<EVENT_HUB_NAME>",
connection="<CONNECTION_SETTING>")
def test_function(myhub: func.EventHubEvent):
logging.info('Python EventHub trigger processed an event: %s',
myhub.get_body().decode('utf-8'))
The following example shows an Event Hubs trigger binding which logs the message body of the Event Hubs trigger.
@FunctionName("ehprocessor")
public void eventHubProcessor(
@EventHubTrigger(name = "msg",
eventHubName = "myeventhubname",
connection = "myconnvarname") String message,
final ExecutionContext context )
{
context.getLogger().info(message);
}
In the Java functions runtime library, use the EventHubTrigger
annotation on parameters whose value comes from the event hub. Parameters with these annotations cause the function to run when an event arrives. This annotation can be used with native Java types, POJOs, or nullable values using Optional<T>
.
The following example illustrates extensive use of SystemProperties
and other Binding options for further introspection of the Event along with providing a well-formed BlobOutput
path that is Date hierarchical.
package com.example;
import java.util.Map;
import java.time.ZonedDateTime;
import com.microsoft.azure.functions.annotation.*;
import com.microsoft.azure.functions.*;
/**
* Azure Functions with Event Hub trigger.
* and Blob Output using date in path along with message partition ID
* and message sequence number from EventHub Trigger Properties
*/
public class EventHubReceiver {
@FunctionName("EventHubReceiver")
@StorageAccount("bloboutput")
public void run(
@EventHubTrigger(name = "message",
eventHubName = "%eventhub%",
consumerGroup = "%consumergroup%",
connection = "eventhubconnection",
cardinality = Cardinality.ONE)
String message,
final ExecutionContext context,
@BindingName("Properties") Map<String, Object> properties,
@BindingName("SystemProperties") Map<String, Object> systemProperties,
@BindingName("PartitionContext") Map<String, Object> partitionContext,
@BindingName("EnqueuedTimeUtc") Object enqueuedTimeUtc,
@BlobOutput(
name = "outputItem",
path = "iotevents/{datetime:yy}/{datetime:MM}/{datetime:dd}/{datetime:HH}/" +
"{datetime:mm}/{PartitionContext.PartitionId}/{SystemProperties.SequenceNumber}.json")
OutputBinding<String> outputItem) {
var et = ZonedDateTime.parse(enqueuedTimeUtc + "Z"); // needed as the UTC time presented does not have a TZ
// indicator
context.getLogger().info("Event hub message received: " + message + ", properties: " + properties);
context.getLogger().info("Properties: " + properties);
context.getLogger().info("System Properties: " + systemProperties);
context.getLogger().info("partitionContext: " + partitionContext);
context.getLogger().info("EnqueuedTimeUtc: " + et);
outputItem.setValue(message);
}
}
Attributes
Both in-process and isolated worker process C# libraries use attribute to configure the trigger. C# script instead uses a function.json configuration file.
In C# class libraries, use the EventHubTriggerAttribute, which supports the following properties.
Parameters | Description |
---|---|
EventHubName | The name of the event hub. When the event hub name is also present in the connection string, that value overrides this property at runtime. Can be referenced in app settings, like %eventHubName% |
ConsumerGroup | An optional property that sets the consumer group used to subscribe to events in the hub. When omitted, the $Default consumer group is used. |
Connection | The name of an app setting or setting collection that specifies how to connect to Event Hubs. To learn more, see Connections. |
Decorators
Applies only to the Python v2 programming model.
For Python v2 functions defined using a decorator, the following properties on the cosmos_db_trigger
:
Property | Description |
---|---|
arg_name |
The name of the variable that represents the event item in function code. |
event_hub_name |
The name of the event hub. When the event hub name is also present in the connection string, that value overrides this property at runtime. |
connection |
The name of an app setting or setting collection that specifies how to connect to Event Hubs. See Connections. |
For Python functions defined by using function.json, see the Configuration section.
Annotations
In the Java functions runtime library, use the EventHubTrigger annotation, which supports the following settings:
Configuration
Applies only to the Python v1 programming model.
The following table explains the trigger configuration properties that you set in the function.json file, which differs by runtime version.
function.json property | Description |
---|---|
type | Must be set to eventHubTrigger . This property is set automatically when you create the trigger in the Azure portal. |
direction | Must be set to in . This property is set automatically when you create the trigger in the Azure portal. |
name | The name of the variable that represents the event item in function code. |
eventHubName | The name of the event hub. When the event hub name is also present in the connection string, that value overrides this property at runtime. Can be referenced via app settings %eventHubName% |
consumerGroup | An optional property that sets the consumer group used to subscribe to events in the hub. If omitted, the $Default consumer group is used. |
cardinality | Set to many in order to enable batching. If omitted or set to one , a single message is passed to the function. |
connection | The name of an app setting or setting collection that specifies how to connect to Event Hubs. See Connections. |
When you're developing locally, add your application settings in the local.settings.json file in the Values
collection.
Usage
To learn more about how Event Hubs trigger and IoT Hub trigger scales, see Consuming Events with Azure Functions.
The parameter type supported by the Event Hubs output binding depends on the Functions runtime version, the extension package version, and the C# modality used.
In-process C# class library functions supports the following types:
- Azure.Messaging.EventHubs.EventData
- String
- Byte array
- Plain-old CLR object (POCO)
This version of EventData drops support for the legacy Body
type in favor of EventBody.
The parameter type can be one of the following:
- Any native Java types such as int, String, byte[].
- Nullable values using Optional.
- Any POJO type.
To learn more, see the EventHubTrigger reference.
Event metadata
The Event Hubs trigger provides several metadata properties. Metadata properties can be used as part of binding expressions in other bindings or as parameters in your code. The properties come from the EventData class.
Property | Type | Description |
---|---|---|
PartitionContext |
PartitionContext | The PartitionContext instance. |
EnqueuedTimeUtc |
DateTime |
The enqueued time in UTC. |
Offset |
string |
The offset of the data relative to the event hub partition stream. The offset is a marker or identifier for an event within the Event Hubs stream. The identifier is unique within a partition of the Event Hubs stream. |
PartitionKey |
string |
The partition to which event data should be sent. |
Properties |
IDictionary<String,Object> |
The user properties of the event data. |
SequenceNumber |
Int64 |
The logical sequence number of the event. |
SystemProperties |
IDictionary<String,Object> |
The system properties, including the event data. |
See code examples that use these properties earlier in this article.
Connections
The connection
property is a reference to environment configuration that contains name of an application setting containing a connection string. You can get this connection string by selecting the Connection Information button for the namespace. The connection string must be for an Event Hubs namespace, not the event hub itself.
The connection string must have at least "read" permissions to activate the function.
This connection string should be stored in an application setting with a name matching the value specified by the connection
property of the binding configuration.
Note
Identity-based connections aren't supported by the IoT Hub trigger. If you need to use managed identities end-to-end, you can instead use IoT Hub Routing to send data to an event hub you control. In that way, outbound routing can be authenticated with managed identity the event can be read from that event hub using managed identity.
host.json properties
The host.json file contains settings that control Event Hub trigger behavior. See the host.json settings section for details regarding available settings.