Each IoT Hub has a built-in endpoint to receive incoming data. By default, all device telemetry is received via this endpoint and it can be accessed by Azure's Event Hub library. This is the method being used in code.py to get the devices' incoming telemetry from their sensors.
client is created as an EventHubConsumerClient with the event_connection Event Hub Compatible endpoint.
# connect to event hub
client = EventHubConsumerClient.from_connection_string(
conn_str = event_connection,
consumer_group = "$default",
)
In the loop, receive_batch() is called, which listens to incoming events.
try:
# recieve incoming events
client.receive_batch(
on_event_batch = on_event_batch,
on_error = on_error
)
The on_event_batch() function iterates through the incoming events. From this incoming feed, the code gets the timestamp with event.enqueued_time and encodes the feed as a JSON to grab the device name from the event.
A series of if statements checks to see which device is sending telemetry data in the event and updates the text objects with the telemetry data.
# iterates through incoming events
for event in events:
# gets timestamp for event
clock = utc_to_local(event.enqueued_time)
...
# gets the incoming event as a JSON feed
telemetry = event.body_as_json()
# grabs the device ID from the JSON
device = event.system_properties[b'iothub-connection-device-id']
# converts the device ID to a string
string_device = device.decode("utf-8")
# updates last device text
lastDevice_text.text = string_device
# if the device is the qt_py
if string_device == qt_py:
# update co2 text
co2_text.text = str(telemetry['CO2'])
# if the device is the tft feather
if string_device == tft_feather:
# update living room sensor text
lr_temp.text = "%s°F" % str(telemetry['Temperature'])
lr_humid.text = "%s%%" % str(telemetry['Humidity'])
lr_press.text = str(telemetry['Pressure'])
# if the device is the s3 feather
if string_device == s3_feather:
# update bedroom sensor text
bd_temp.text = "%s°F" % str(telemetry['Temperature'])
bd_humid.text = "%s%%" % str(telemetry['Humidity'])
bd_press.text = str(telemetry['Pressure'])
Page last edited March 08, 2024
Text editor powered by tinymce.