From 82d4c0707467a8a2fb769da1933ccfe70742207d Mon Sep 17 00:00:00 2001 From: DINMAY KUMAR BRAHMA <131891590+dino65-dev@users.noreply.github.com> Date: Tue, 5 Nov 2024 15:56:26 +0000 Subject: [PATCH 1/4] add iot control using python --- Automation_Tools/Iot_control/Readme.md | 24 ++++++++ Automation_Tools/Iot_control/iot_control.py | 66 +++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 Automation_Tools/Iot_control/Readme.md create mode 100644 Automation_Tools/Iot_control/iot_control.py diff --git a/Automation_Tools/Iot_control/Readme.md b/Automation_Tools/Iot_control/Readme.md new file mode 100644 index 0000000000..0acf006f62 --- /dev/null +++ b/Automation_Tools/Iot_control/Readme.md @@ -0,0 +1,24 @@ +# 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. + +## 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. Clone the repository: + ```bash + git clone https://github.com/yourusername/iot-device-control.git + cd Iot_control +``` \ No newline at end of file diff --git a/Automation_Tools/Iot_control/iot_control.py b/Automation_Tools/Iot_control/iot_control.py new file mode 100644 index 0000000000..8314e03577 --- /dev/null +++ b/Automation_Tools/Iot_control/iot_control.py @@ -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()) From 2340b20a9e997be05e8ca3082bda9f405fe4134f Mon Sep 17 00:00:00 2001 From: dino65-dev Date: Tue, 5 Nov 2024 15:57:27 +0000 Subject: [PATCH 2/4] updating Project-Structure.md --- Project-Structure.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Project-Structure.md b/Project-Structure.md index 506fc89e90..20f9f78ee3 100644 --- a/Project-Structure.md +++ b/Project-Structure.md @@ -212,6 +212,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 From 1a894d49db2fd1a34d599e069e9df8ec049f66a1 Mon Sep 17 00:00:00 2001 From: DINMAY KUMAR BRAHMA <131891590+dino65-dev@users.noreply.github.com> Date: Tue, 5 Nov 2024 21:42:50 +0530 Subject: [PATCH 3/4] Update Readme.md --- Automation_Tools/Iot_control/Readme.md | 48 ++++++++++++++++++++++++-- 1 file changed, 46 insertions(+), 2 deletions(-) diff --git a/Automation_Tools/Iot_control/Readme.md b/Automation_Tools/Iot_control/Readme.md index 0acf006f62..11a8579657 100644 --- a/Automation_Tools/Iot_control/Readme.md +++ b/Automation_Tools/Iot_control/Readme.md @@ -1,7 +1,33 @@ -# IoT Device Control Using MQTT and Python +## 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. @@ -21,4 +47,22 @@ Before you begin, ensure you have the following installed: ```bash git clone https://github.com/yourusername/iot-device-control.git cd Iot_control -``` \ No newline at end of file + ``` +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 +``` From 060d126950a26af7c76c8b9d51f3db89cf00d1c2 Mon Sep 17 00:00:00 2001 From: DINMAY KUMAR BRAHMA <131891590+dino65-dev@users.noreply.github.com> Date: Tue, 5 Nov 2024 21:45:57 +0530 Subject: [PATCH 4/4] Update Readme.md --- Automation_Tools/Iot_control/Readme.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/Automation_Tools/Iot_control/Readme.md b/Automation_Tools/Iot_control/Readme.md index 11a8579657..ba30a4dc5f 100644 --- a/Automation_Tools/Iot_control/Readme.md +++ b/Automation_Tools/Iot_control/Readme.md @@ -43,9 +43,8 @@ Before you begin, ensure you have the following installed: ## Installation -1. Clone the repository: +1. After cloning the repository ```bash - git clone https://github.com/yourusername/iot-device-control.git cd Iot_control ``` 2. Install the required Python packages: