#AzureIoT – Using a Raspberry Pi Grove Sensor in an ☁ Azure IoT Edge Module (2/N)

Buy Me A Coffee

Hi !

Following on my previous post on reading the sensor values, today’s I’ll share a new code sample, triggering this information as device telemetry in Azure IoT.

In the references section, you can find some tutorials on how to create an Azure IoT Hub, and also how to create a Edge Device on the Azure IoT Hub. At the end, for this sample, we will need the connection string associated the new created device.

Once we have the connection string, the following code:

  • Create a new Azure IoT Device client and connect to the Azure IoT Hub using the connection string.
  • Create a new thread listening for device twin properties changes. If a property named. “RefreshInterval” is defined, the app will use the property value as new refresh interval in the read sensor values loop.
  • Initialize a sensor using the Grove libraries.
  • Read the temperature and humidity and trigger a new message including this information in the body, and also temperature and humidity as message properties
# Copyright (c) Bruno Capuano. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for full license information.
# Using the Python Device SDK for IoT Hub:
# https://github.com/Azure/azure-iot-sdk-python
# Azure IoT dependencies installed with >> pip install azure-iot-device
# read temp and humi from DHT11 Sensor
# read values are triggered device message with the information
import random
import time
import seeed_dht
import os
import threading
from azure.iot.device import IoTHubDeviceClient, Message
CONNECTION_STRING = "CNN STRING GOES HERE"
refresh_interval = 1
# Define the JSON message to send to IoT Hub.
MSG_TXT = '{{"temperature": {temperature},"humidity": {humidity}}}'
def twin_update_listener(client):
global refresh_interval
while True:
patch = client.receive_twin_desired_properties_patch() # blocking call
print("Twin desired properties patch received:")
print(patch)
refreshIntervalKey = 'RefreshInterval'
if refreshIntervalKey in patch:
refresh_interval = patch[refreshIntervalKey]
print(f"Refresh Interval Updated to {refresh_interval}")
def iothub_client_init():
# Create an IoT Hub client
client = IoTHubDeviceClient.create_from_connection_string(CONNECTION_STRING)
return client
def iothub_client_telemetry_sample_run():
global refresh_interval
try:
client = iothub_client_init()
twin_update_listener_thread = threading.Thread(target=twin_update_listener, args=(client,))
twin_update_listener_thread.daemon = True
twin_update_listener_thread.start()
print ( "IoT Hub device sending periodic messages, press Ctrl-C to exit" )
sensor = seeed_dht.DHT("11", 12)
while True:
# read current values from sensor
humi, temp = sensor.read()
msg_txt_formatted = MSG_TXT.format(temperature=temp, humidity=humi)
message = Message(msg_txt_formatted)
# Add a application property to the message with humi and temp
message.custom_properties["temperature"] = temp
message.custom_properties["humidity"] = humi
# Send the message.
print( "Sending message: {}".format(message) )
client.send_message(message)
time.sleep(refresh_interval)
except KeyboardInterrupt:
print ( "IoTHubClient sample stopped" )
if __name__ == '__main__':
print ( "El Bruno – Sample telemetry message" )
print ( "Press Ctrl-C to exit" )
iothub_client_telemetry_sample_run()

Once the app is running on the Raspberry Pi, we can use Azure IoT Explorer to check the messages. Note the body with the JSON information, and also the message properties including humidity and temperature as separated properties.

Of course the same information is also printed to the console.

And, finally the photo with the simple layout of the device parts.

In my next post, let’s package all of this in an Azure IoT Module.

References

Happy coding!

Greetings

El Bruno



¿Con ganas de ponerte al día?

En Lemoncode te ofrecemos formación online impartida por profesionales que se baten el cobre en consultoría:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.