简体   繁体   English

使用 Azure 函数 (Python) 从 Azure EventHub 消息中检索传感器数据

[英]Retrieve sensor data from Azure EventHub Message with Azure Function (Python)

I'm trying to send sensor data from a device to Azure IoT Hub and process it inside Azure Function.我正在尝试将传感器数据从设备发送到 Azure IoT 中心并在 Azure Function 中对其进行处理。 I managed to trigger the function when Azure IoT Hub receives data using EventHubTrigger.当 Azure IoT 中心使用 EventHubTrigger 接收数据时,我设法触发了该功能。

However, I cannot find any way to retrieve sensor data.但是,我找不到任何方法来检索传感器数据。

The following data is sent from the device:以下数据从设备发送:

{"temperature": 27.5, "humidity": 63.0}

And the bellow is what I get from EventHubEvent body下面是我从 EventHubEvent 正文中得到的

{'properties': {}, 'systemProperties': {'iothub-connection-device-id': 'raspberrypi', 'iothub-connection-auth-method': '{"scope":"device","type":"sas","issuer":"iothub","acceptingIpFilterRule":null}', 'iothub-connection-auth-generation-id': '637374141338740275', 'iothub-enqueuedtime': '2020-10-04T16:21:15.0190000Z', 'iothub-message-source': 'Telemetry'}, 'body': 'eyJ0ZW1wZXJhdHVyZSI6IDI3LjUsICJodW1pZGl0eSI6IDYzLjB9'}

Source code for the sender and function app is as follows:发送方和函数应用的源代码如下:

Sender/device (related part only)发送器/设备(仅相关部分)

# Define the JSON message to send to IoT Hub.
MSG_TXT = '{{"temperature": {temperature}, "humidity": {humidity}}}'

client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)

msg_txt_formatted = MSG_TXT.format(temperature=sensor_data["temperature"]["value"], humidity=sensor_data["humidity"]["value"])
message = Message(msg_txt_formatted)
client.send_message(message)

Function app ( __init__.py )函数应用程序( __init__.py

from typing import List
import logging
import json

import azure.functions as func

def main(event: List[func.EventHubEvent]):
    body = event.get_body()
    logging.info(body)
    my_json = body.decode('utf8').replace("'", '"')
    event_data_json = json.loads(my_json)
    logging.info(event_data_json[0]["data"])

Is there any additional setting necessary to route IoTHub telemetry data?路由 IoTHub 遥测数据是否需要任何其他设置? Any help would be appreciated.任何帮助,将不胜感激。

You need to add message routing from IoT hub blade .您需要添加来自IoT hub blade message routing If using Built in end point event hub, route the DeviceTelemetry messages to events endpoint else route to the custom endpoint ie in this case it is your event hub created in event hub namespace.如果使用内置端点事件中心,则将 DeviceTelemetry 消息路由到events端点,否则路由到自定义端点,即在这种情况下,它是在事件中心命名空间中创建的事件中心。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM