You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

接收Azure IoT Hub遥测数据时,如何通过编程获取device_id?

获取Azure IoT Hub遥测数据中的设备ID

你完全不需要为每个设备单独创建事件流——IoT Hub在把遥测数据转发到Event Hub时,已经把设备ID放在事件的系统属性里了,直接提取就行,不用额外操作。

解决方法:从EventData的系统属性中提取Device ID

IoT Hub转发的每条事件都会自动添加元数据到system_properties字典中,其中iothub-connection-device-id字段就是发送遥测的设备ID。修改你的代码如下:

from azure.eventhub import EventData
from azure.eventhub.aio import EventHubConsumerClient
import asyncio
from typing import Any

CONN_STR = "你的Event Hub连接字符串"

async def receive_events(consumer_client: EventHubConsumerClient):
    async def on_event(partition_context: Any, event: EventData) -> None:
        # 从系统属性中获取设备ID
        device_id = event.system_properties.get("iothub-connection-device-id")
        print(f"设备 [{device_id}] 的遥测数据:")
        print(event.body_as_str())
        # 可选:更新 checkpoint,避免重启后重复接收
        await partition_context.update_checkpoint(event)

    async with consumer_client:
        await consumer_client.receive(
            on_event=on_event,
            starting_position="-1"  # 从最新的事件开始接收
        )

if __name__ == "__main__":
    consumer_client = EventHubConsumerClient.from_connection_string(
        conn_str=CONN_STR,
        consumer_group="$Default"
    )
    asyncio.run(receive_events(consumer_client))

额外说明

除了设备ID,system_properties里还包含其他实用元数据,比如:

  • iothub-enqueuedtime:消息被IoT Hub入队的时间
  • iothub-message-source:消息的来源类型(比如遥测数据是Telemetry)
  • iothub-connection-auth-method:设备的认证方式

这种方式只需要一个Event Hub消费者就能处理所有设备的遥测数据,比为每个设备单独建流高效得多。

内容的提问来源于stack exchange,提问作者SRobertJames

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 16:20:01