Building a Smart Home Automation Dashboard using Python, Azure IoT Hub, and Azure Functions

Build a Smart Home Automation Dashboard using Flask, Azure IoT Hub, and Azure Functions to remotely control devices like lights, fans, and locks. This guide walks you through setting up IoT communication, processing commands, and deploying the solution on Azure Cloud for real-time smart home management.

Flow:

1️⃣ User sends a request via the Flask Web App.
2️⃣ Azure Function processes and forwards the command to Azure IoT Hub.
3️⃣ IoT Hub relays the command to the Smart Device (e.g., turn on a light).
4️⃣ Smart Device sends back a status update to IoT Hub.
5️⃣ Flask Web App receives the update and displays it to the user.

🌟 Overview

This guide will help you build a Flask-based web application that allows users to control smart home devices (lights, fans, door locks) remotely via Azure IoT Hub.

Features:

  • Turn ON/OFF lights, fans, and locks using a web dashboard
  • Send commands to IoT devices via Azure IoT Hub
  • Process commands using Azure Functions
  • Display real-time device status

1️⃣ Prerequisites

✔️ Azure Subscription (Create Free Account)
✔️ Python 3.8+ installed
✔️ Flask Framework installed
✔️ Azure IoT Hub set up
✔️ Azure Functions Core Tools installed


2️⃣ Step 1: Set Up Azure IoT Hub

Create an IoT Hub

  1. Login to Azure CLI
    az login
  2. Create a Resource Group
    az group create --name SmartHomeRG --location eastus
  3. Create an IoT Hub
    az iot hub create --name SmartHomeIoTHub --resource-group SmartHomeRG --sku F1 --location eastus
    
  4. Register an IoT Device
    az iot hub device-identity create --hub-name SmartHomeIoTHub --device-id SmartHomeDevice
    
  5. Get Connection String
    az iot hub device-identity connection-string show --hub-name SmartHomeIoTHub --device-id SmartHomeDevice
    
    Save this connection string (it will be used in our Flask app).

3️⃣ Step 2: Create an Azure Function

Create a Function App

  1. Install Azure Functions Core Tools
    npm install -g azure-functions-core-tools@4 --unsafe-perm true
  2. Create a New Function App
    func init SmartHomeFunctions --python
    cd SmartHomeFunctions
  3. Create an HTTP Triggered Function
    func new --name DeviceControlFunction --template "HTTP trigger" --language Python
    

Modify DeviceControlFunction/__init__.py

Replace with:

import logging
import azure.functions as func
import json
from azure.iot.hub import IoTHubRegistryManager

# Azure IoT Hub connection string (replace with actual connection string)
IOT_HUB_CONNECTION_STRING = "<YOUR_IOT_HUB_CONNECTION_STRING>"
DEVICE_ID = "SmartHomeDevice"

def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info("Received request to control IoT device.")

    try:
        req_body = req.get_json()
        command = req_body.get("command")

        if command not in ["turn_on", "turn_off"]:
            return func.HttpResponse("Invalid command", status_code=400)

        # Send message to IoT device
        registry_manager = IoTHubRegistryManager(IOT_HUB_CONNECTION_STRING)
        registry_manager.send_c2d_message(DEVICE_ID, json.dumps({"command": command}))

        return func.HttpResponse(f"Command '{command}' sent successfully.", status_code=200)

    except Exception as e:
        logging.error(f"Error: {str(e)}")
        return func.HttpResponse("Failed to send command", status_code=500)

Deploy the Function

func azure functionapp publish SmartHomeFunctions

Copy the function URL (needed for Flask API).


4️⃣ Step 3: Build Flask Web App

Install Dependencies

pip install flask requests

Create app.py

from flask import Flask, render_template, request, jsonify
import requests

app = Flask(__name__)

# Azure Function URL (Replace with your actual function URL)
AZURE_FUNCTION_URL = "<YOUR_AZURE_FUNCTION_URL>"

@app.route("/")
def home():
    return render_template("index.html")

@app.route("/control", methods=["POST"])
def control_device():
    command = request.json.get("command")

    if command not in ["turn_on", "turn_off"]:
        return jsonify({"error": "Invalid command"}), 400

    # Send request to Azure Function
    response = requests.post(AZURE_FUNCTION_URL, json={"command": command})

    if response.status_code == 200:
        return jsonify({"message": f"Command '{command}' sent successfully."})
    else:
        return jsonify({"error": "Failed to send command"}), 500

if __name__ == "__main__":
    app.run(debug=True)

5️⃣ Step 4: Create Flask UI

Create templates/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Smart Home Dashboard</title>
    <script>
        async function sendCommand(command) {
            const response = await fetch('/control', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ command: command })
            });
            const data = await response.json();
            alert(data.message || data.error);
        }
    </script>
</head>
<body>
    <h1>Smart Home Automation</h1>
    <button onclick="sendCommand('turn_on')">Turn On Devices</button>
    <button onclick="sendCommand('turn_off')">Turn Off Devices</button>
</body>
</html>

6️⃣ Step 5: Run and Test Locally

  1. Start Flask App
    python app.py
  2. Open http://127.0.0.1:5000/ in your browser.
  3. Click "Turn On Devices" or "Turn Off Devices".
  4. Check if the command is sent to Azure IoT Hub.

7️⃣ Step 6: Deploy Flask App to Azure

  1. Login to Azure
    az login
  2. Create an App Service Plan
    az appservice plan create --name SmartHomePlan --resource-group SmartHomeRG --sku F1 --is-linux
    
  3. Create a Web App
    az webapp create --resource-group SmartHomeRG --plan SmartHomePlan --name SmartHomeApp --runtime "PYTHON:3.8"
    
  4. Deploy Flask App
    az webapp up --name SmartHomeApp --resource-group SmartHomeRG
  5. Access Web App
    Visit https://SmartHomeApp.azurewebsites.net/

🎯 Key Takeaways

Flask Web App provides an interface for users to control IoT devices.
Azure IoT Hub acts as a communication bridge.
Azure Functions process commands and send messages to devices.
Deployment to Azure Web App makes the solution accessible globally.

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete