简体   繁体   中英

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. I managed to trigger the function when Azure IoT Hub receives data using 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

{'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 )

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? Any help would be appreciated.

You need to add message routing from IoT hub blade . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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