Stream Sensor Data In Real-Time With IoT Hub Using PowerBI

Introduction

 
This article demonstrates how to send the temperature data into the cloud via Azure IoT Hub and PowerBI.
 
Requirement 
  1. DHT11 - Temperature and Humidity Sensor Module
  2. Azure Subscription 
  3. Analysis - IoT - Hub  (8,000 messages per day)
  4. Power PI Account
  5. Raspberry Pi
  6. Stream Analytics Job
DHT11 - Temperature and Humidity Sensor Module
 
The DHT11 humidity and temperature sensor make it really easy to add humidity and temperature data to your IoT Hub. 
 
 
Item Measurement Range
 Humidity Accuracy
Temperature
Accuracy  
Resolution Package  
 DHT11  20-90%RH 0-50 ℃  ±5%RH  ±2℃  1  4 Pin Single Row
 
Raspberry Pi and dh11 interconnection diagram 
 
 
Step 1
  • Navigate to IoT devices within your IoT Hub.
  • Click "Add".
  • Populate the Device ID (e.g. raspberrypi).
  • Click "Save".
 
Create an IoT device named as "raspberrypi" and select the authentication type.
 
 
Create a Consumer Group
  • Navigate to Endpoints within your IoT Hub.
  • Click on the Events (messages/events) endpoint.
  • Add a Consumer Group (e.g. streamanalytics_consumergroup).
  • Click "Save".
Step 2
  • Create a Stream Analytics job; the job name is Stream - Analysis.
 
Step 3
  • Navigate to Input alias.
  • Select IoT Hub from your subscriptions.
  • Add a Consumer Group (e.g. streamanalytics_consumergroup).
  • Endpoint (ex: Message).
  • Click "Save". 
 
Step 4
  • Navigate to Outputs.
  • Click Add > Power BI.
 
  • Output alias (e.g. powerbioutput).
  • Dataset Name (e.g. temperatureDataset).
  • Table Name (e.g. temperatureTable).
  • Click "Authorize".
  • Click "Save".
 
 
Stream Analytics SQL
  • Navigate to Query within Stream Analytics.
  • Copy and paste the SQL below into your Stream Analytics query window.
  • Sample data has returned, click "Test".
  • Click "Save".
  • Click "Start".
    1. SELECT    
    2.     CAST(iothub.EnqueuedTime AS datetime) AS event_date,    
    3.     CAST(temp AS floatAS temp    
    4. INTO    
    5.     powerbioutput    
    6. FROM    
    7.     iothubinput   
Source Code (Python)
  1. from base64 import b64encode, b64decode  
  2. from hashlib import sha256  
  3. from urllib import quote_plus, urlencode  
  4. from hmac import HMAC  
  5. import requests  
  6. import json  
  7. import os  
  8. import time  
  9.   
  10. # Temperature Sensor  
  11. BASE_DIR = '/sys/bus/w1/devices/'  
  12. SENSOR_DEVICE_ID = 'YOUR_DEVICE_ID'  
  13. DEVICE_FILE = BASE_DIR + SENSOR_DEVICE_ID + '/w1_slave'  
  14.   
  15. # Azure IoT Hub  
  16. URI = 'YOUR_IOT_HUB_NAME.azure-devices.net'  
  17. KEY = 'YOUR_IOT_HUB_PRIMARY_KEY'  
  18. IOT_DEVICE_ID = 'YOUR_REGISTED_IOT_DEVICE_ID'  
  19. POLICY = 'iothubowner'  
  20.   
  21. def generate_sas_token():  
  22.     expiry=3600  
  23.     ttl = time.time() + expiry  
  24.     sign_key = "%s\n%d" % ((quote_plus(URI)), int(ttl))  
  25.     signature = b64encode(HMAC(b64decode(KEY), sign_key, sha256).digest())  
  26.   
  27. rawtoken = {  
  28. 'sr' : URI,  
  29. 'sig': signature,  
  30. 'se' : str(int(ttl))  
  31. }  
  32.   
  33. rawtoken['skn'] = POLICY  
  34.   
  35. return 'SharedAccessSignature ' + urlencode(rawtoken)  
  36.   
  37. def read_temp_raw():  
  38.     f = open(DEVICE_FILE, 'r')  
  39.     lines = f.readlines()  
  40.    f.close()  
  41.    return lines  
  42.   
  43. def read_temp():  
  44.     lines = read_temp_raw()  
  45.     while lines[0].strip()[-3:] != 'YES':  
  46.           time.sleep(0.2)  
  47.      lines = read_temp_raw()  
  48.      equals_pos = lines[1].find('t=')  
  49.      if equals_pos != -1:  
  50.           temp_string = lines[1][equals_pos+2:]  
  51.      temp_c = float(temp_string) / 1000.0  
  52.      return temp_c  
  53.   
  54. def send_message(token, message):  
  55.     url = 'https://{0}/devices/{1}/messages/events?api-version=2016-11-14'.format(URI, IOT_DEVICE_ID)  
  56.     headers = {  
  57. "Content-Type""application/json",  
  58. "Authorization": token  
  59.      }  
  60.     data = json.dumps(message)  
  61.     print data  
  62.     response = requests.post(url, data=data, headers=headers)  
  63.   
  64. if __name__ == '__main__':  
  65. # 1. Enable Temperature Sensor  
  66. os.system('modprobe w1-gpio')  
  67. os.system('modprobe w1-therm')  
  68.   
  69. # 2. Generate SAS Token  
  70. token = generate_sas_token()  
  71.   
  72. # 3. Send Temperature to IoT Hub  
  73. while True:  
  74.     temp = read_temp()  
  75.     message = { "temp": str(temp) }  
  76.     send_message(token, message)  
  77.     time.sleep(1)  
Step 5 - Power BI
  • Log on to Power BI.
  • Create a new dashboard.
  • Add two tiles.
 
Card
  1. Click "Add tile" >> "Custom Streaming Data" >> "Next".
  2. Select the temperatureDataset
Properties.
  • Visualization Type: Card
  • Fields: temp
  • Decimal Places: 2
  • Title: Temperature
Line Chart
  • Click Add tile.
  • Click Custom Streaming Data.
  • Click Next.
  • Select temperatureDataset.
Properties.
  • Visualization Type: Line chart
  • Axis: event_date
  • Values: temp
  • Time window: 1 minute
  • Title: Temperature (Celsius)
OUTPUT
 

Summary

 
Finally, we have successfully created a graph that streams the sensor data in real-time with IoT Hub using Powe BI.

Similar Articles