Reputation: 48402
I'd like to create an Azure Function that fires whenever a message is sent to an Azure IoT hub. In a C# app I wrote, I create a method that pulls messages off the hub. In that method I have access to the ServiceBus.Messaging.EventData object that contains all available information about a message. The method looks as follows:
private static async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct)
{
var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, System.DateTime.UtcNow);
while (true)
{
if (ct.IsCancellationRequested)
break;
EventData eventData = await eventHubReceiver.ReceiveAsync();
if (eventData == null)
continue;
// Get the Device Id which is included in the SystemProperties dictionary
string deviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString();
string data = Encoding.UTF8.GetString(eventData.GetBytes());
Console.WriteLine("Message received - DeviceId: {0}; Partition: {1}; Data: '{2}'", deviceId, partition, data);
}
}
When I attempt to create a C# based Azure Function in the portal, the default method created looks as follows:
public static void Run(string myIoTHubMessage, TraceWriter log)
{
log.Info($"C# IoT Hub trigger function processed a message: {myIoTHubMessage}");
}
I was wondering if there was someway I could get access to the entire message object, like I can in my C# app, as opposed to just the message itself ('myIotHubMessage')?
Note: I tried the following but Azure Functions didn't like the first using reference. It couldn't find the reference.
using Microsoft.ServiceBus.Messaging;
using System.Text;
public static void Run(EventData eventData, TraceWriter log)
{
var data = Encoding.UTF8.GetString(eventData.GetBytes());
log.Info($"C# IoT Hub trigger function processed a message: {data}");
}
Upvotes: 0
Views: 838
Reputation: 4432
You can follow the next steps to create an Azure Function that fires whenever a message is sent to an Azure IoT hub.
#r "Microsoft.ServiceBus" using System.Text; using Microsoft.ServiceBus.Messaging; public static void Run(EventData myIoTHubMessage, TraceWriter log) { log.Info($"{Encoding.UTF8.GetString(myIoTHubMessage.GetBytes())}"); }
When you use a device client send messages to IoT Hub, the function app will fire, it will show in the logs.
Upvotes: 1
Reputation: 35134
Yes, just replace string
with EventData
, add reference to the package and using
for the namespace:
#r "Microsoft.ServiceBus"
using System.Text;
using Microsoft.ServiceBus.Messaging;
public static void Run(EventData myEventHubMessage, TraceWriter log)
{
log.Info($"{Encoding.UTF8.GetString(myEventHubMessage.GetBytes())}");
}
Upvotes: 1