Real-Time Temperature Monitoring with Azure IoT & SMS Alerts Using Azure Communication Services

Explanation of the Sequence:

  1. IoT_Device sends temperature data (as JSON) to the IoT_Hub.
  2. The IoT_Hub triggers an event to Event_Grid when new telemetry data is received.
  3. Event_Grid passes the event data to the Azure_Function.
  4. Azure_Function processes the data to check if the temperature exceeds the defined threshold.
    • If the temperature exceeds the threshold, the function proceeds to send an SMS.
    • If the temperature is within the normal range, no SMS is sent.
  5. Azure_Function sends an SMS request to SMS_Client.
  6. SMS_Client communicates with ACS_SMS_API to send the SMS.
  7. ACS_SMS_API confirms the SMS has been sent, and the response is passed back to the SMS_Client and Azure_Function.

To set up an Azure IoT-based temperature sensing system with an Azure Function that sends an SMS when the temperature exceeds a certain threshold using Azure Communication Services (ACS), follow these steps from scratch:

1. Set Up Azure IoT Hub

  • Create an IoT Hub in the Azure portal:

    • Go to the Azure portal → Create a resource → Search for IoT HubCreate.
    • Follow the setup steps (Subscription, Resource Group, Region, etc.).
    • After the IoT Hub is created, get the Connection String from IoT Hub > Shared access policies > iothubowner.
  • Set up your IoT Device:

    • Create a device in the IoT Hub by going to IoT Hub > DevicesAdd Device.
    • Note the Device ID and Primary Connection String.

2. Set Up Azure Communication Services (ACS) for SMS

  • Go to the Azure portalCreate a resource → Search for Azure Communication Services.
  • Create the ACS resource and note the Connection String.
  • Get a phone number for sending SMS from the ACS portal (under Phone Numbers).

3. Create an Azure Function

  • Go to the Azure portalCreate a resource → Search for Function AppCreate.
  • Select Python as the runtime stack and configure the rest of the settings.
  • After deployment, go to Function App > Functions and create a new Function with the Event Grid trigger (which will be used to listen to IoT Hub messages).

4. Set Up Azure Function to Monitor IoT Device Telemetry

  • Set up your Azure Function to trigger based on incoming telemetry from your IoT Hub. For this, you'll need to integrate with the Event Grid:
    • In the Azure Function, you'll receive telemetry data from your IoT device.

5. Write Python Code for the Azure Function

Here's the Python code that will process the incoming temperature data, check if it exceeds a threshold, and send an SMS using ACS.

import logging
import azure.functions as func
from azure.communication.sms import SmsClient
from azure.core.exceptions import HttpResponseError
import json

# Your ACS connection string and phone numbers
ACS_CONNECTION_STRING = 'your_acs_connection_string'
FROM_PHONE_NUMBER = '+1234567890'  # your ACS phone number
TO_PHONE_NUMBER = '+0987654321'    # recipient phone number
TEMP_THRESHOLD = 30  # Example temperature threshold (in Celsius)

def main(event: func.EventGridEvent):
    # Decode the incoming event data
    telemetry_data = json.loads(event.get_body())
    temperature = telemetry_data.get('temperature', 0)

    logging.info(f"Received temperature data: {temperature}°C")

    if temperature > TEMP_THRESHOLD:
        logging.info(f"Temperature exceeds threshold! Sending SMS.")
        send_sms(temperature)
    else:
        logging.info(f"Temperature is within normal range.")

def send_sms(temperature):
    # Initialize ACS SMS client
    sms_client = SmsClient.from_connection_string(ACS_CONNECTION_STRING)

    message = f"Alert: Temperature has exceeded the threshold! Current temperature: {temperature}°C"

    try:
        # Send SMS
        response = sms_client.send(
            from_=FROM_PHONE_NUMBER,
            to=[TO_PHONE_NUMBER],
            message=message
        )
        logging.info(f"SMS sent successfully. Message ID: {response[0].message_id}")
    except HttpResponseError as e:
        logging.error(f"Error sending SMS: {e.message}")

6. Deploy the Azure Function

  • In the Azure portal, go to Function App > Functions > Add.
  • Choose the Event Grid trigger and link it to your IoT Hub as the source for events.
  • Deploy the function code from the portal or via your local development setup using Azure Functions Tools.

7. Connect IoT Hub and Event Grid to Trigger the Function

  • In your IoT Hub, go to Events > Event Grid.
  • Add an Event Grid subscription that triggers your Azure Function when a new event (telemetry data) is received.
  • Set the function as the Event Handler.

8. Send Temperature Data from IoT Device

  • On your IoT device, implement code to send temperature readings to the IoT Hub.
  • Use MQTT or HTTPS protocol to send data like this:
from azure.iot.device import IoTHubDeviceClient, Message

conn_str = "your_device_connection_string"
device_client = IoTHubDeviceClient.create_from_connection_string(conn_str)

# Simulate sending temperature data
temperature = 35  # Example value
message = Message(f'{{"temperature": {temperature}}}')
device_client.send_message(message)

9. Test the System

  • Test the system by sending data from your IoT device. If the temperature exceeds the threshold, the Azure Function will send an SMS through ACS.

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example