Azure IoT 中心、EventHub 和函数 [英] Azure IoT Hub, EventHub and Functions
问题描述
我有一个带有 route 指向触发函数的 EventHub.
I have an IoTHub with a route that points to an EventHub which triggers a Functions.
我在从事件对象获取 DeviceId 和其他 IoT 中心属性时遇到问题,而没有将它们显式添加到有效负载中.
I'm having problem getting the DeviceId and other IoT Hub properties from the event object without adding those explicitly to the payload.
如果我将输入类型设置为 string
(或自定义类型):
If I set the input type to a string
(or a custom type):
public static void Run(string iotMessage, TraceWriter log) {
log.Info($"C# Event Hub trigger function processed a message: {iotMessage}");
}
我只获取负载,没有任何其他 IoT 中心属性,例如 DeviceId、CorrelationId 或 MessageId.
I only get the payload without any other IoT Hub properties like DeviceId, CorrelationId or MessageId.
我尝试将类型设置为 EventData
:
I tried to set the type to EventData
instead:
public static void Run(EventData iotMessage, TraceWriter log) {
log.Info($"C# Event Hub trigger function processed a message: {JsonConvert.SerializeObject(iotMessage)}");
}
现在我可以通过两个 getter 访问 IoT 中心属性:Properties 和 SystemProperties.例如,我可以像 iotMessage.SystemProperties["iothub-connection-device-id"]
那样访问 DeviceId.但它不会暴露有效载荷.
Now I can access the IoT Hub properties via two getters: Properties and SystemProperties. For example I can access DeviceId like this iotMessage.SystemProperties["iothub-connection-device-id"]
. But it does not expose the payload.
那么如何访问 IoT 中心属性和有效负载?
So how do I access both IoT Hub properties and the payload?
推荐答案
我遗漏了 EventData 文档中的一件事.它有一个名为 GetBytes() 的方法,并将正文作为字节数组返回.获取 IoT 中心属性和正文的示例:
I missed a thing in the documentation for EventData. It has a method called GetBytes() and returns the body as a byte array. Example of getting both the IoT Hub properties and the body:
public static async void Run(EventData telemetryMessage, TraceWriter log)
{
var deviceId = GetDeviceId(telemetryMessage);
var payload = GetPayload(telemetryMessage.GetBytes());
log.Info($"C# Event Hub trigger function processed a message. deviceId: { deviceId }, payload: { JsonConvert.SerializeObject(payload) }");
}
private static Payload GetPayload(byte[] body)
{
var json = System.Text.Encoding.UTF8.GetString(body);
return JsonConvert.DeserializeObject<Payload>(json);
}
private static string GetDeviceId(EventData message)
{
return message.SystemProperties["iothub-connection-device-id"].ToString();
}
这篇关于Azure IoT 中心、EventHub 和函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!