IoT Device Automation with Python

Loading

IoT (Internet of Things) device automation allows remote control, monitoring, and management of smart devices. Using Python, we can automate IoT devices via MQTT, HTTP APIs, WebSockets, and Cloud Services like AWS IoT, Google Cloud IoT, and Azure IoT Hub.


1. Key Components of IoT Automation

IoT device automation involves:

  1. Sensors & Actuators – Collect data and perform actions
  2. Communication Protocols – MQTT, HTTP, CoAP, WebSockets
  3. Cloud Integration – AWS IoT, Firebase, Google IoT Core
  4. Edge Processing – Raspberry Pi, ESP32, Arduino
  5. Automation Scripts – Python scripts for device control
  6. Databases – SQLite, Firebase, PostgreSQL

2. Setting Up Python for IoT Automation

Install the required Python libraries:

pip install paho-mqtt requests gpiozero flask pyserial
  • paho-mqtt – For MQTT communication
  • requests – For API communication
  • gpiozero – For controlling Raspberry Pi GPIO
  • flask – For creating a simple IoT dashboard
  • pyserial – For serial communication with microcontrollers

3. Communicating with IoT Devices

3.1 MQTT-Based IoT Automation

MQTT (Message Queuing Telemetry Transport) is a lightweight protocol for IoT communication.

Python Code to Control an IoT Device via MQTT:

import paho.mqtt.client as mqtt

broker = "broker.hivemq.com"
topic = "home/lights"

client = mqtt.Client()
client.connect(broker, 1883)

def turn_on_light():
client.publish(topic, "ON")

def turn_off_light():
client.publish(topic, "OFF")

turn_on_light()

Sends MQTT commands to turn lights ON/OFF remotely.


3.2 Controlling IoT Devices Using HTTP API

Some smart devices use REST APIs for automation.

Python Code to Control a Smart Plug via API:

import requests

api_url = "http://192.168.1.100/api/device" # Example API endpoint
data = {"device": "smart_plug", "status": "ON"}

response = requests.post(api_url, json=data)
print(response.json())

Sends an HTTP request to turn a smart plug ON.


3.3 Controlling Raspberry Pi GPIO for Home Automation

Use Raspberry Pi GPIO to automate devices.

Python Code to Control an LED with GPIO:

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
LED_PIN = 18
GPIO.setup(LED_PIN, GPIO.OUT)

GPIO.output(LED_PIN, True) # Turn ON LED
time.sleep(5)
GPIO.output(LED_PIN, False) # Turn OFF LED

GPIO.cleanup()

Controls GPIO pins to automate home appliances.


3.4 Automating IoT Devices with Serial Communication

For Arduino, ESP32, or microcontrollers, use serial communication.

Python Code to Send Commands to Arduino:

import serial

ser = serial.Serial('/dev/ttyUSB0', 9600)

ser.write(b'LED_ON\n')
time.sleep(5)
ser.write(b'LED_OFF\n')

Sends commands via UART/Serial to control Arduino devices.


4. IoT Data Logging & Automation with Databases

4.1 Storing Sensor Data in SQLite

Python Code to Save IoT Sensor Data:

import sqlite3

conn = sqlite3.connect('iot_data.db')
cursor = conn.cursor()

cursor.execute('''CREATE TABLE IF NOT EXISTS sensor_data
(id INTEGER PRIMARY KEY, temperature REAL, humidity REAL, timestamp DATETIME DEFAULT CURRENT_TIMESTAMP)''')

def save_data(temp, hum):
cursor.execute("INSERT INTO sensor_data (temperature, humidity) VALUES (?, ?)", (temp, hum))
conn.commit()

save_data(25.3, 60.1)

Stores IoT sensor data in SQLite for analysis.


5. Real-Time IoT Dashboard with Flask

Python Code for a Web-Based IoT Dashboard:

from flask import Flask, jsonify
import random

app = Flask(__name__)

@app.route('/status')
def device_status():
return jsonify({"device": "Smart Light", "status": "ON"})

if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0', port=5000)

Provides a real-time web interface to monitor IoT devices.


6. Cloud-Based IoT Automation with Firebase

Python Code to Send IoT Data to Firebase:

import firebase_admin
from firebase_admin import credentials, db

cred = credentials.Certificate("firebase_credentials.json")
firebase_admin.initialize_app(cred, {'databaseURL': 'https://your-firebase.firebaseio.com/'})

ref = db.reference("iot_device")
ref.set({"status": "ON"})

Sends IoT device status to Firebase.


7. Automating IoT Workflows with Python Scripts

You can schedule automation tasks using cron jobs or Python scripts.

Python Code for Automating IoT Actions Based on Time:

import schedule
import time

def automate_device():
print("Turning on Smart Light...")
# MQTT or API call to control device

schedule.every().day.at("18:00").do(automate_device)

while True:
schedule.run_pending()
time.sleep(60)

Runs automated IoT tasks at scheduled times.

Leave a Reply

Your email address will not be published. Required fields are marked *