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

In this article, let us see how to stream Sensor Data in Real-Time with IoT Hub using PowerBI and send temperature data into the cloud via Azure IoT Hub.

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 Analytic Job
DHT11 - Temperature and Humidity Sensor Module
 
The DHT11 humidity and temperature sensor makes it really easy to add humidity and temperature data to your IoT Hub. 
 
 
 
 Item Measurement Range
 Humidity Accuracy
Temperature
Accuracy  
 ResolutionPackage  
 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 Analytic 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 float) AS 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. # Temperature Sensor
  10. BASE_DIR = '/sys/bus/w1/devices/'
  11. SENSOR_DEVICE_ID = 'YOUR_DEVICE_ID'
  12. DEVICE_FILE = BASE_DIR + SENSOR_DEVICE_ID + '/w1_slave'
  13. # Azure IoT Hub
  14. URI = 'YOUR_IOT_HUB_NAME.azure-devices.net'
  15. KEY = 'YOUR_IOT_HUB_PRIMARY_KEY'
  16. IOT_DEVICE_ID = 'YOUR_REGISTED_IOT_DEVICE_ID'
  17. POLICY = 'iothubowner'
  18. def generate_sas_token():
  19. expiry=3600
  20. ttl = time.time() + expiry
  21. sign_key = "%s\n%d" % ((quote_plus(URI)), int(ttl))
  22. signature = b64encode(HMAC(b64decode(KEY), sign_key, sha256).digest())
  23. rawtoken = {
  24. 'sr' : URI,
  25. 'sig': signature,
  26. 'se' : str(int(ttl))
  27. }
  28. rawtoken['skn'] = POLICY
  29. return 'SharedAccessSignature ' + urlencode(rawtoken)
  30. def read_temp_raw():
  31. f = open(DEVICE_FILE, 'r')
  32. lines = f.readlines()
  33. f.close()
  34. return lines
  35. def read_temp():
  36. lines = read_temp_raw()
  37. while lines[0].strip()[-3:] != 'YES':
  38. time.sleep(0.2)
  39. lines = read_temp_raw()
  40. equals_pos = lines[1].find('t=')
  41. if equals_pos != -1:
  42. temp_string = lines[1][equals_pos+2:]
  43. temp_c = float(temp_string) / 1000.0
  44. return temp_c
  45. def send_message(token, message):
  46. url = 'https://{0}/devices/{1}/messages/events?api-version=2016-11-14'.format(URI, IOT_DEVICE_ID)
  47. headers = {
  48. "Content-Type": "application/json",
  49. "Authorization": token
  50. }
  51. data = json.dumps(message)
  52. print data
  53. response = requests.post(url, data=data, headers=headers)
  54. if __name__ == '__main__':
  55. # 1. Enable Temperature Sensor
  56. os.system('modprobe w1-gpio')
  57. os.system('modprobe w1-therm')
  58. # 2. Generate SAS Token
  59. token = generate_sas_token()
  60. # 3. Send Temperature to IoT Hub
  61. while True:
  62. temp = read_temp()
  63. message = { "temp": str(temp) }
  64. send_message(token, message)
  65. 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 the 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.