Raspberry Pi with Azure IoT and Power BI

Prerequisites

You can follow my previous documentation to setup up raspberry pi and remote development using visual studio

Once we connected the raspberry pi using visual studio code you have to enable the python extension and this will install the python on raspberry pi

After the installation reload the visual studio code

Now install IoT Device cube on locally and reload the visual studio

Install IoT tool on rasbery pi

Login int to Raspberry pi again and run sudo raspi-config and Select 5 Interfacing options

And enable I2C

Create requerment.txt and add below packages and install

Rpi.bme280

azure-iot-device

RPi.GPIO


Login to Azure portal and create the IoT Hub

Select    Public endpoint (all networks)

Select  standard tier (you can choose appropriate accordingly the price and use cases )

Register the IoT Device

  1. Navigate to IoT Devices within your IoT Hub.
  2. Click Add.
  3. Populate the Device ID (e.g. raspberrypi).
  4. Click Save

Connect the IoT Hub from Visual studio code using azure login

Create a Consumer Group

  1. Navigate to Endpoints within your IoT Hub.
  2. Click on the Events (messages/events) endpoint.
  3. Add a Consumer Group (e.g. streamanalytics_consumergroup).
  4. Click Save.

Setup Stream Analytics (Input and Output)

  1. Navigate to Inputs within your Stream Analytics resource.
  2. Click Add stream input > IoT Hub
    1. Provide an Input Alias (e.g. iothub).
    1. Select the Consumer Group (streamanalytics_consumergroup).
    1. Click Save.

Navigate to Outputs and Click Add Power BI.

It will ask for Power BI  authentication and follow the below steps to create the outputs

  1. Provide an Output Alias (e.g. powerbi).
  2. Provider a Dataset Name (e.g. temperature).
  3. Provide a Table Name (e.g. temperature).
  4. Click Authorize.
  5. Click Save.

Update the script with Azure IoT data

Update Connection device string on below scripts and upload to raspberry pi

import smbus2

import bme280

import asyncio

import time

import json

import RPi.GPIO as GPIO

from azure.iot.device.aio import IoTHubDeviceClient

port = 1

address = 0x76

bus = smbus2.SMBus(port)

calibration_params = bme280.load_calibration_params(bus, address)

GPIO.setmode(GPIO.BCM)

GPIO.setup(24, GPIO.OUT)

def get_temp():

    data = bme280.sample(bus, address, calibration_params)

    return data.temperature

def handle_twin(twin):

    print(“Twin received”, twin)

    if (‘desired’ in twin):

        desired = twin[‘desired’]

        if (‘led’ in desired):

            GPIO.output(24, desired[‘led’])

async def main():

    conn_str = “***********************”

    device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)

    await device_client.connect()

    last_temp = “”

    while True:

        temp = “{0:0.1f}”.format(get_temp())

        print(“Temperature”, temp)

        if temp != last_temp:

            last_temp = temp;

            data = {}

            data[‘temperature’] = temp

            json_body = json.dumps(data)

            print(“Sending message: “, json_body)

            await device_client.send_message(json_body)

        twin = await device_client.get_twin()

        handle_twin(twin)

        time.sleep(1)

    await device_client.disconnect()

if __name__ == “__main__”:

    asyncio.run(main())

Stream Analytics SQL

  1. Navigate to Query within Stream Analytics.
  2. Copy and paste the SQL below into your Stream Analytics query window.
  3. Click on the ellipsis next to your IoT Hub input and click Sample data from input.
  4. Set duration to 1 minute and click OK.
  5. Once the sample data has returned, click Test.
  6. Click Save.
  7. Click Overview.
  8. Click Start and then click Start once more.

SELECT

    CAST(iothub.EnqueuedTime AS datetime) AS event_date,

    CAST(temperature AS float) AS temperature

INTO

    powerbioutput

FROM

    iothub

Power BI

  1. Log on to Power BI.
  2. Create a new Dashboard (My Workspace > Create > Dashbaord).
  3. Add two tiles.

Tile #1: Card

  1. Click Add tile.
  2. Click Custom Streaming Data.
  3. Click Next.
  4. Select the temperatureDataset and click Next.
  5. Populate the properties.
    1. Visualization Type: Card
    1. Fields: temp
    1. Decimal Places: 2
    1. Title: Temperature (Celsius)

You can test temperature sensor using heater after I apply some heat to sensor its start changing the Celsius