Thursday, May 8, 2025

IoT (Internet of Things) Automation - Smart Energy Usage Tracker

 


Notes:

  • Problem Solved: Logs and analyzes power usage from smart meters.

  • Customization Benefits: Track per-device energy and set alerts.

  • Further Adoption: Sync to cloud dashboards or billing tools.

Python Code:


import random
import csv
from datetime import datetime

def simulate_energy_reading():
    return round(random.uniform(0.1, 2.5), 2)  # kWh usage

with open("energy_log.csv", "a", newline="") as f:
    writer = csv.writer(f)
    usage = simulate_energy_reading()
    timestamp = datetime.now().isoformat()
    writer.writerow([timestamp, usage])
    print(f"Logged: {timestamp} - {usage} kWh")

IoT (Internet of Things) Automation - RFID-Based Access Control

 


Notes:

  • Problem Solved: Authenticates user entry via RFID tags for security.

  • Customization Benefits: Maintain a dynamic list of allowed users.

  • Further Adoption: Integrate with cameras or audit logs.

Python Code:


AUTHORIZED_TAGS = {"1234567890ABC", "AABBCCDDEEFF"}

def read_rfid():
    return input("Scan RFID Tag: ")

def check_access(tag):
    if tag in AUTHORIZED_TAGS:
        print("✅ Access Granted")
    else:
        print("❌ Access Denied")

tag = read_rfid()
check_access(tag)

IoT (Internet of Things) Automation - Real-Time Air Quality Monitor

 


Notes:

  • Problem Solved: Continuously monitors air quality from a sensor and triggers alerts.

  • Customization Benefits: Adjust thresholds or integrate SMS/email alerts.

  • Further Adoption: Push data to cloud dashboards or IoT edge devices.

Python Code:


import random
import time

def read_sensor():
    return random.randint(0, 500)  # Simulated AQI reading

def check_air_quality(aqi):
    if aqi > 150:
        print("⚠️ Poor air quality! Consider ventilation.")
    elif aqi > 100:
        print("🟡 Moderate air quality.")
    else:
        print("🟢 Good air quality.")

while True:
    aqi = read_sensor()
    print(f"Current AQI: {aqi}")
    check_air_quality(aqi)
    time.sleep(10)

IoT (Internet of Things) Automation - Smart Irrigation System

 


Notes:

  • Problem Solved: Activates irrigation based on soil moisture data and weather forecast.

  • Customization Benefits: Calibrate for crop types or integrate with APIs.

  • Further Adoption: Link with physical relay systems and IoT dashboards.

Python Code:


import requests

def should_irrigate(moisture_level, weather_api_key):
    if moisture_level > 30:
        return False
    forecast = requests.get(f"https://api.weatherapi.com/v1/forecast.json?key={weather_api_key}&q=your_city&days=1").json()
    rain_chance = forecast['forecast']['forecastday'][0]['day']['daily_chance_of_rain']
    return rain_chance < 50

# Example usage
if should_irrigate(moisture_level=25, weather_api_key='your_api_key'):
    print("Activate irrigation.")
else:
    print("Irrigation not needed.")

IoT (Internet of Things) Automation - MQTT Sensor Data Logger

 


Notes:

  • Problem Solved: Collects real-time data from IoT sensors via MQTT and stores it locally.

  • Customization Benefits: Add support for multiple topics or cloud sync.

  • Further Adoption: Integrate with InfluxDB, Grafana, or AWS IoT.

Python Code:


import paho.mqtt.client as mqtt

def on_message(client, userdata, msg):
    with open('sensor_log.csv', 'a') as f:
        f.write(f"{msg.topic},{msg.payload.decode()}\n")
    print(f"Logged: {msg.topic} -> {msg.payload.decode()}")

client = mqtt.Client()
client.on_message = on_message
client.connect("broker.hivemq.com", 1883)
client.subscribe("iot/temperature")

print("Listening for sensor data...")
client.loop_forever()

IoT (Internet of Things) Automation - Smart Thermostat Control

 


Notes:

  • Problem Solved: Automatically adjusts temperature based on time of day and occupancy.

  • Customization Benefits: Set your own temperature profiles or integrate weather data.

  • Further Adoption: Connect to smart home systems (Home Assistant, OpenHAB).

Python Code:


from datetime import datetime

def get_temperature_schedule(hour, is_home):
    if not is_home:
        return 18  # Eco mode
    if 6 <= hour < 9:
        return 22  # Morning
    elif 9 <= hour < 17:
        return 20  # Daytime
    elif 17 <= hour < 23:
        return 23  # Evening
    else:
        return 19  # Night

# Example usage
now = datetime.now()
temperature = get_temperature_schedule(now.hour, is_home=True)
print(f"Set thermostat to {temperature}°C")

Web Scraping and Data Extraction - Website Change Tracker

 


Notes:

  • Problem Solved: Monitors a webpage for any HTML/textual changes over time.

  • Customization Benefits: Set up alerts or track competitor website updates.

  • Further Adoption: Integrate with Slack/email APIs to send alerts.

Python Code:


import hashlib
import requests
import time

def get_page_hash(url):
    response = requests.get(url)
    return hashlib.sha256(response.text.encode()).hexdigest()

def track_changes(url, interval=60):
    old_hash = get_page_hash(url)
    print("Monitoring started...")
    while True:
        time.sleep(interval)
        new_hash = get_page_hash(url)
        if new_hash != old_hash:
            print("Website content changed!")
            break
        else:
            print("No change detected...")

# Example usage
# track_changes("https://example.com", interval=300)

IoT (Internet of Things) Automation - Smart Energy Usage Tracker

  Notes: Problem Solved: Logs and analyzes power usage from smart meters. Customization Benefits: Track per-device energy and set ale...