Skip to content

Instantly share code, notes, and snippets.

Created March 7, 2021 16:27
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save elbruno/1718bf01dc4527cebcfaaa5af2ab9a4b to your computer and use it in GitHub Desktop.
# 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:
# 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
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:")
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
client = iothub_client_init()
twin_update_listener_thread = threading.Thread(target=twin_update_listener, args=(client,))
twin_update_listener_thread.daemon = True
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 =
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) )
except KeyboardInterrupt:
print ( "IoTHubClient sample stopped" )
if __name__ == '__main__':
print ( "El Bruno - Sample telemetry message" )
print ( "Press Ctrl-C to exit" )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment