物联网中心事件python

时间:2018-11-10 18:56:37

标签: python azure iot azure-iot-hub azure-eventhub

我已经搜索了很多,我正在尝试使用python和azure事件sdk将接收器连接到我的azure上的aot上的iot集线器,但是遗憾的是没有成功,我的接收者告诉我它已经与客户端建立了连接,但是它从未真正查看过数据

我的收信人是

    #!/usr/bin/env python

# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

"""
An example to show receiving events from an Event Hub partition.
"""
import os
import sys
import logging
import time
from azure.eventhub import EventHubClient, Receiver, Offset

# Address can be in either of these formats:
# "amqps://<URL-encoded-SAS-policy>:<URL-encoded-SAS-key>@<mynamespace>.servicebus.windows.net/myeventhub"
# "amqps://<mynamespace>.servicebus.windows.net/myeventhub"
ADDRESS ="amqps://iothub-ns-virtualab2-926709-043cc22e89.servicebus.windows.net/virtualab2"

# SAS policy and key are not required if they are encoded in the URL
USER = "iothubowner"
KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
CONSUMER_GROUP = "teststream"
OFFSET = Offset("-1")
PARTITION = "1"


total = 0
last_sn = -1
last_offset = "-1"
client = EventHubClient(ADDRESS, debug=True, username=USER, password=KEY)

try:
    receiver = client.add_receiver(CONSUMER_GROUP, PARTITION, prefetch=5000, offset=OFFSET)
    client.run()
    print("client connected")
    start_time = time.time()
    print("listening")
    batch = receiver.receive(timeout=5000)

    while batch:
        for event_data in batch:
            last_offset = event_data.offset
            last_sn = event_data.sequence_number
            print("Received: {}, {}".format(last_offset.value, last_sn))
            print(event_data.body_as_str())
            total += 1
        batch = receiver.receive(timeout=5000)

    end_time = time.time()
    client.stop()
    run_time = end_time - start_time
    print("Received {} messages in {} seconds".format(total, run_time))

except KeyboardInterrupt:
    pass
finally:
    client.stop()

我正在使用来自物联网中心快速入门的标准发件人

1 个答案:

答案 0 :(得分:0)

您拥有的代码可以正常工作,但是您需要检查以下几点:

  • 如果您使用的是IoT Hub内置事件端点,请确保您使用的是来自Event Hub兼容端点的名称空间名称,以及该名称的Event Hub兼容名称。我测试过的地址如下:amqps://ihsuprodbyresXXXXXXnamespace.servicebus.windows.net/iothub-ehub-sample-XXXXX-XXXXXXXXXX

    • 请确保您使用的是iothubowner键值。

    • 确保您正在使用的使用者组已添加到与事件中心兼容的端点。

    • 默认情况下,与事件中心兼容的终结点具有两个分区-您的代码仅侦听其中一个分区上的消息。