如何在IoT Hub触发的Azure Function中获取消息的DeviceId
获取IoT Hub触发Azure Function中的设备ID
嘿,这个问题我熟!在IoT Hub触发的Azure Function里获取设备ID其实很简单,关键是找对系统属性的位置,我分两种常用语言给你举例子:
C# 实现
如果你的Function用C#编写,IoT Hub传递的EventData对象里,设备ID存储在SystemProperties字典中,对应的键是iothub-connection-device-id。直接通过这个键就能取出设备ID:
using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.EventHub; using Microsoft.Azure.EventHubs; using Microsoft.Extensions.Logging; public static void Run(EventData myIoTHubMessage, ILogger log) { // 安全获取设备ID,避免键不存在的异常 if (myIoTHubMessage.SystemProperties.TryGetValue("iothub-connection-device-id", out var deviceIdObj)) { string deviceId = deviceIdObj.ToString(); log.LogInformation($"获取到设备ID: {deviceId}"); } // 处理消息内容(可选) string messageContent = System.Text.Encoding.UTF8.GetString( myIoTHubMessage.Body.Array, myIoTHubMessage.Body.Offset, myIoTHubMessage.Body.Count ); log.LogInformation($"收到消息内容: {messageContent}"); }
Python 实现
对于Python版的Azure Function,触发参数是func.EventHubEvent类型,设备ID藏在metadata字典里,同样用iothub-connection-device-id作为键来获取:
import azure.functions as func import logging def main(event: func.EventHubEvent): # 获取设备ID device_id = event.metadata.get("iothub-connection-device-id") if device_id: logging.info(f"获取到设备ID: {device_id}") # 处理消息内容(可选) message_content = event.get_body().decode("utf-8") logging.info(f"收到消息内容: {message_content}")
小提示
你提到的ConnectionDeviceId其实就是IoT Hub给这个系统属性定义的逻辑名称,对应到代码里就是用iothub-connection-device-id这个键来访问,不用额外引入其他类,直接用默认的EventData/EventHubEvent对象就能拿到啦。
内容的提问来源于stack exchange,提问作者Aparna
相关产品推荐
相关产品推荐

