Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IoT Device Control Script #1105

Merged
merged 6 commits into from
Nov 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions Automation_Tools/Iot_control/Readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
## IoT Device Control Using MQTT and Python

This project demonstrates how to control IoT devices using the MQTT protocol with Python. It uses the `paho-mqtt` library to publish messages to an MQTT broker, which are then used to control an IoT device.

## Compatibility
**IoT Devices Compatible with MQTT:**
1. **Smart Lights:** Devices like Philips Hue or any other smart lighting system that can connect to an MQTT broker can be controlled to turn on/off, change color, or adjust brightness.
2. **Smart Thermostats:** Devices like the Nest Thermostat or Ecobee can use MQTT for setting temperature, scheduling, or mode changes.
3. **Home Security Systems:** Sensors and alarms that support MQTT can be armed/disarmed and monitored through the script.
4. **Smart Plugs:** Devices like TP-Link HS100 can be turned on/off remotely using MQTT commands.
5. **Industrial Sensors:** Many industrial IoT devices like temperature sensors, pressure sensors, or flow meters that support MQTT can be monitored and controlled.
6. **Agricultural Sensors:** IoT devices used in farming to monitor soil moisture, weather conditions, or control irrigation systems.

## Example IoT-Based Projects:
1. **Home Automation System:**
- Project Description: Create a centralized system to control various smart home devices such as lights, thermostats, and security cameras.
- MQTT Usage: Use MQTT to send commands to different devices and receive their statuses.
2. **Remote Monitoring System:**
- Project Description: Set up a system to monitor environmental parameters like temperature, humidity, and air quality in real-time.
- MQTT Usage: Sensors publish their data to specific topics, and the central system subscribes to these topics to collect and analyze data.
3. **Smart Farming Solution:**
- Project Description: Implement a solution for monitoring and controlling agricultural environments, optimizing water usage, and managing crop health.
- MQTT Usage: Use MQTT to communicate with soil moisture sensors, weather stations, and irrigation controllers.
4. **Industrial Automation:**
- Project Description: Develop a system for monitoring and controlling industrial machines, ensuring efficient operations and safety.
- MQTT Usage: Machines and sensors communicate their status and receive control commands over MQTT.
5. **Health Monitoring System:**
- Project Description: A system for remote health monitoring of patients, tracking vital signs and providing alerts.
- MQTT Usage: Wearable devices send patient data to a central server via MQTT, which then processes and responds to critical alerts.

## Features

- **Secure Communication**: Utilizes TLS/SSL for secure communication with the MQTT broker.
- **Dynamic Topic Management**: Supports dynamic subscription and publishing to topics.
- **Enhanced Error Handling**: Robust error handling for connection issues and message delivery failures.
- **Logging**: Detailed logging for monitoring and troubleshooting.

## Prerequisites

Before you begin, ensure you have the following installed:
- Python 3.6 or higher
- pip (Python package installer)

## Installation

1. After cloning the repository
```bash
cd Iot_control
```
2. Install the required Python packages:
```bash
pip install paho-mqtt python-dotenv
```
## Configuration
1. Update the .env file with your MQTT broker details:
```bash
MQTT_BROKER=mqtt.example.com
MQTT_PORT=8883
MQTT_TOPIC=home/device/control
MQTT_RESPONSE_TOPIC=home/device/response
```
2. Ensure your MQTT broker is configured to support TLS/SSL and is accessible from your network.
## Usage
To run the script, use the following command:
```bash
python iot_control.py
```
66 changes: 66 additions & 0 deletions Automation_Tools/Iot_control/iot_control.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import asyncio
import os
import ssl
import logging
import paho.mqtt.client as mqtt
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Configure logging
logging.basicConfig(level=logging.INFO)

# MQTT Broker details from environment variables
broker = os.getenv('MQTT_BROKER', 'mqtt.example.com')
port = int(os.getenv('MQTT_PORT', '8883'))
topic = os.getenv('MQTT_TOPIC', 'home/device/control')
response_topic = os.getenv('MQTT_RESPONSE_TOPIC', 'home/device/response')

# Define the message to send to the IoT device
message = "TURN_ON"

# Callback function when the client receives a CONNACK response from the server
async def on_connect(client, userdata, flags, rc):
if rc == 0:
logging.info("Connected successfully")
await client.subscribe(response_topic)
else:
logging.error(f"Connection failed with code {rc}")

# Callback function when a PUBLISH message is received from the server
async def on_message(client, userdata, msg):
logging.info(f"Received message '{msg.payload.decode()}' on topic '{msg.topic}'")

# Create an asynchronous MQTT client instance
client = mqtt.Client(asyncio=True)

# Set up TLS/SSL with certificate-based mutual authentication
client.tls_set(
ca_certs="/path/to/ca.crt",
certfile="/path/to/client.crt",
keyfile="/path/to/client.key",
tls_version=ssl.PROTOCOL_TLS
)

# Assign the callback functions
client.on_connect = on_connect
client.on_message = on_message

async def main():
try:
# Connect to the MQTT broker
await client.connect(broker, port, 60)
# Publish the message to the specified topic
await client.publish(topic, message)
logging.info(f"Message '{message}' sent to topic '{topic}'")
# Start the loop to process network traffic and dispatch callbacks
await asyncio.get_event_loop().run_forever()
except Exception as e:
logging.error(f"An error occurred: {e}")
finally:
# Disconnect from the broker
await client.disconnect()

if __name__ == "__main__":
asyncio.run(main())
2 changes: 2 additions & 0 deletions Project-Structure.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,8 @@
* [Extract Aadhar Details](Automation_Tools/Autofill%20personal%20info%20using%20Aadhar%20Card%20Image/extract_aadhar_details.ipynb)
* Image-Tool
* [Image Tool](Automation_Tools/Image-Tool/Image_Tool.py)
* Iot Control
* [Iot Control](Automation_Tools/Iot_control/iot_control.py)
* Playlist-Downloader
* [Setup](Automation_Tools/Playlist-downloader/setup.py)
* Web Scrapping
Expand Down