0% found this document useful (0 votes)
5 views12 pages

Experiment 7: Introduction To Iot and Web-Based Control

The document outlines an experiment to create an IoT device control system using Flask and ngrok, allowing remote control of an LED-like device. It details the objectives, tools used, and the theory behind IoT and web-based control, along with the program code and procedures for setting up the server and testing the API. The conclusion emphasizes the successful demonstration of remote control capabilities and suggests extending the program to include additional devices.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views12 pages

Experiment 7: Introduction To Iot and Web-Based Control

The document outlines an experiment to create an IoT device control system using Flask and ngrok, allowing remote control of an LED-like device. It details the objectives, tools used, and the theory behind IoT and web-based control, along with the program code and procedures for setting up the server and testing the API. The conclusion emphasizes the successful demonstration of remote control capabilities and suggests extending the program to include additional devices.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Hunny Mane

IU2341051286
CE-C A1

Experiment 7

Aim

To develop a simple IoT-based device control system using Flask as a web framework and ngrok for
exposing the local server to the internet, allowing remote control of an LED-like device.

Objectives

● To implement a web-based interface for controlling an IoT device (LED).


● To use Flask to create a lightweight API for device control.
● To expose the local Flask server to the internet using ngrok.
● To enable remote control of the device via API calls.

Tools Used

● Python (Version 3.x)


● Flask (for creating the web server)
● ngrok (for exposing Flask to the internet)
● pip (Python package manager)
● Web Browser (for testing API)
● Postman (optional, for API testing)
● Command Prompt/Terminal (for running the server)

Theory

Introduction to IoT and Web-based Control

The Internet of Things (IoT) enables physical devices, such as sensors and actuators, to be
controlled remotely via the internet. In this experiment, we simulate an IoT device (an LED) that
can be turned ON or OFF using a Flask web server and control it remotely through ngrok.

The main components of this system include:

● Flask (Python-based Web Framework): Handles HTTP requests and processes


commands.
● ngrok (Tunneling Tool): Exposes the locally running Flask application to the public
internet, allowing remote control.
● REST API (GET Requests): Allows users to send commands to control the LED state.

Why Use Flask?

Flask is a lightweight and easy-to-use web framework that allows:

● Handling HTTP requests efficiently.


● Creating RESTful APIs to interact with IoT devices.
● Providing JSON-based responses that can be used in mobile apps or web dashboards.
Hunny Mane
IU2341051286
CE-C A1

Understanding Flask API Endpoints

APIs allow external systems (e.g., web apps, mobile apps, or other computers) to interact with
our IoT device.

In this experiment, we define three Flask API endpoints:

Endpoint Method Description

/ GET Displays instructions on how to use the API.

/control?device=LE GET Turns the LED ON.


D&state=ON

/control?device=LE GET Turns the LED OFF.


D&state=OFF

/status GET Returns the current state of the LED.

Role of ngrok

Flask runs on a local server (127.0.0.1:5000), which is only accessible on the local machine. To
control the LED from outside the local network, we need ngrok.

ngrok provides:

A Public URL for Flask Server


● Converts http://127.0.0.1:5000 → http://your-ngrok-url.ngrok.io
● Secure Tunneling
● No need to configure firewalls or routers.
● Remote Access
● Users can send API requests from any device, anywhere in the world.

How Flask and ngrok Work Together


● Flask starts a local web server on 127.0.0.1:5000.
● ngrok creates a public URL, forwarding all requests to the Flask server.
● Users send HTTP requests (via a web browser or API tools like Postman) to control the
LED.
● Flask processes the requests and updates the LED state
Hunny Mane
IU2341051286
CE-C A1

Program Code cum Procedure


Step 1: Install Required Packages
Before running the program, install dependencies:
pip install flask pyngrok
Step 2: Save the Flask Code as app.py

Create a new file named app.py and copy-paste the following code:

from flask import Flask, request, jsonify


from pyngrok import ngrok
app = Flask( name )
device_states = {"LED": "OFF"}
@app.route("/")
def home():
return "<h1>LED Controller</h1><p>Use /toggle?device=LED&state=ON or
OFF</p>"
@app.route("/toggle", methods=["GET"])
def toggle_led():
device = request.args.get("device") # Get device name
state = request.args.get("state") # Get desired state

if device == "LED" and state in ["ON", "OFF"]:


device_states[device] = state
return jsonify({"message": f"{device} turned {state}"})
else:
return jsonify({"error": "Invalid request"}), 400

@app.route("/status", methods=["GET"])
def check_status():
return jsonify(device_states)

public_url = ngrok.connect(5002).public_url
print(f"Public URL: {public_url}")

if name == " main ":


app.run(host="0.0.0.0", port=5002)

Step 3: Run Flask Server


Hunny Mane
IU2341051286
CE-C A1

Open Command Prompt (Windows) or Terminal (Linux/Mac) and navigate to the directory where
app.py is saved:
python app.py
Output:
Step 4: Start ngrok
In a new terminal window, run:
ngrok http 5002
It will generate a public URL, e.g.:
https://5ba6-35-229-35-139.ngrok-free.app -> http://127.0.0.1:5002
Step 5: Test the API
Use your browser or Postman to access the following URLs:
Home Page
https://5ba6-35-229-35-139.ngrok-free.app

Expected Output:
<h1>IoT Device Control</h1><p>Use /control?device=LED&state=ON to control
the device.</p>
Turn LED ON
https://5ba6-35-229-35-139.ngrok-free.app/control?device=LED&state=ON
Expected JSON Response:
{"message": "LED turned ON"}
Turn LED OFF
https://5ba6-35-229-35-139.ngrok-free.app/control?device=LED&state=OFF
Expected JSON Response:
{"message": "LED turned OFF"}
Check LED Status
https://5ba6-35-229-35-139.ngrok-free.app/status
Expected JSON Response:
{"LED": "ON"} # or "OFF" depending on last action

Explanation of the Program

1. Importing Required Libraries:

from flask import Flask, request, jsonify


from pyngrok import ngrok

● Flask: Used to create the web server and define API routes.
● request: Parses URL parameters for handling API requests.
● jsonify: Returns responses in JSON format.
● pyngrok: Exposes the local Flask app to the internet.

2. Initializing the Flask App:

app = Flask( name )


Hunny Mane
IU2341051286
CE-C A1

● This initializes an instance of the Flask web application.

3. Defining LED State:

led_state = "OFF"

● The variable led_state stores the current state of the LED, initially set to "OFF".

4. API Endpoints:

Home Page:

@app.route('/')

def home():

return "<h1>LED Controller</h1><p>Use /control?device=LED&state=ON or OFF</p>"

● Returns a basic HTML page with usage instructions.

Control LED State:

@app.route('/control', methods=['GET'])

def control_led():

global led_state

device = request.args.get('device')

state = request.args.get('state')

if device != "LED":

return jsonify({"error": "Invalid device"}), 400

if state in ["ON", "OFF"]:

led_state = state

return jsonify({"message": f"LED turned {state}"})

else:

return jsonify({"error": "Invalid state"}), 400

● Checks if the requested device is "LED".


● If valid, updates the LED state and returns confirmation.

How It Works:
Hunny Mane
IU2341051286
CE-C A1

●Extracts device name (LED) and desired state (ON or OFF) from the query
parameters.
● If valid, it updates the device state and returns a confirmation message.
● If invalid, it returns an error message.
Example Usage:
http://127.0.0.1:5002/control?device=LED&state=ON
Response:
{"message": "LED turned ON"}
http://127.0.0.1:5002/control?device=LED&state=OFF
Response:
{"message": "LED turned OFF"}
Define the Status Route (/status)
@app.route('/status', methods=['GET'])
def device_status():
return jsonify(device_state) # Returns the current state of the LED
● Returns the current state of the LED in JSON format.
● Example Usage:
http://127.0.0.1:5002/status
{"LED": "ON"}
Start the Flask Server
if name == ' main ':
app.run(host='0.0.0.0', port=5002)
● Runs Flask on port 5000.
● host='0.0.0.0' allows access from any network.
Exposing Flask via ngrok
After starting Flask, we need to expose it to the internet:
Run this command in a new terminal window:
ngrok http 5002
Expected output:
Forwarding https://5ba6-35-229-35-139.ngrok-free.app ->
http://127.0.0.1:5002
Now, use the ngrok URL to access the API from anywhere.

Expected Outputs (Attach readable size of screenshots of following 4 pages then remove these all)
Running https://5ba6-35-229-35-139.ngrok-free.app/status should show:
{"LED": "OFF"}
Hunny Mane
IU2341051286
CE-C A1

Sending https://5ba6-35-229-35-139.ngrok-free.app/control?device=LED&state=ON
updates the
LED state:
{"message": "LED turned ON"}

Checking status again (/status) shows:


{"LED": "ON"}

Turning the LED OFF (/control?device=LED&state=OFF) results in:


{"message": "LED turned OFF"}

Conclusion:
This experiment successfully demonstrates remote control of an IoT device using Flask and ngrok.
Flask provides a lightweight, easy-to-use API for controlling the LED.ngrok allows secure remote
access without configuring firewalls.This approach can be extended to control real IoT hardware
(Raspberry Pi, Arduino, ESP32, etc.).
Hunny Mane
IU2341051286
CE-C A1

Homework Assigned: Task: Extend the program by adding another virtual IoT device (e.g., a fan) and
allow users to control its state. Hint: Modify the device_state dictionary to include a "Fan" and
update the /control API to handle it.

Program Code

from flask import Flask, request, jsonify


from pyngrok import ngrok

app = Flask( name )

devices = {
"LED": "OFF",
"Fan": "OFF"
}
@app.route('/')
def home():
return "<h1>Device Controller</h1><p>Use /control?device=LED/Fan&state=ON/OFF</p>"

@app.route('/control', methods=['GET'])
def control_device():
device = request.args.get('device')
state = request.args.get('state')

if device not in devices:


return jsonify({"error": "Invalid device. Use 'LED' or 'Fan'."}), 400
if state in ["ON", "OFF"]:
devices[device] = state
return jsonify({"message": f"{device} turned {state}"})
else:
return jsonify({"error": "Invalid state. Use 'ON' or 'OFF'."}), 400

@app.route('/status', methods=['GET'])
def device_status():
return jsonify(devices)

public_url = ngrok.connect(5001).public_url
print(f"Public URL: {public_url}")

if name == ' main ':


app.run(host="0.0.0.0", port=5001)
Hunny Mane
IU2341051286
CE-C A1

Run Flask Server


Open Command Prompt (Windows) or Terminal (Linux/Mac) and navigate to the directory where
app.py is saved:
python app.py
Output:
Start ngrok
In a new terminal window, run:
ngrok http 5001
It will generate a public URL, e.g.:
https://223a-35-229-35-139.ngrok-free.app -> http://127.0.0.1:5001
Test the API
Use your browser or Postman to access the following URLs:
Home Page
https://223a-35-229-35-139.ngrok-free.app

Expected Output:
<h1>IoT Device Control</h1><p>Use /control?device=LED&state=ON or
/control?device=Fan&state=ON to control the device.</p>
Turn LED ON
https://223a-35-229-35-139.ngrok-free.app/control?device=LED&state=ON
Expected JSON Response:
{"message": "LED turned ON"}
Turn LED OFF
https://223a-35-229-35-139.ngrok-free.app/control?device=LED&state=OFF
Expected JSON Response:
{"message": "LED turned OFF"}
Check LED Status
https://223a-35-229-35-139.ngrok-free.app/status
Expected JSON Response:
{"LED": "ON"} # or "OFF" depending on last action

Turn ON the Fan:


https://223a-35-229-35-139.ngrok-free.app/control?device=Fan&state=ON

Expected JSON Response:


{"message": "Fan turned ON"}

Turn OFF the Fan :


https://223a-35-229-35-139.ngrok-free.app/control?device=Fan&state=OFF

Expected JSON Response:


{"message": "Fan turned OFF"}

Check LED and FAN Status


Hunny Mane
IU2341051286
CE-C A1

https://223a-35-229-35-139.ngrok-free.app/status

Expected JSON Response:


{"Fan":"ON","LED":"ON"}

Explanation of program :

1. Importing Required Libraries

from flask import Flask, request, jsonify


from pyngrok import ngrok

Flask: Used to create the web server and define API routes.
request: Handles incoming HTTP GET requests and extracts parameters.

2. Initializing the Flask App & Device States

app = Flask( name )


devices = {
"LED": "OFF",
"Fan": "OFF"
}

● The Flask app is initialized.

● A dictionary devices is created to store the current state (ON/OFF) of each device.

3. Defining API Endpoints

Home Page
@app.route('/')
def home():
return "<h1>Device Controller</h1><p>Use
/control?device=LED/Fan&state=ON/OFF</p>"

● Returns a simple HTML page with instructions on how to use the API.

4. Controlling Devices

@app.route('/control', methods=['GET'])
def control_device():
device = request.args.get('device') # Get the device name from the URL
state = request.args.get('state') # Get the desired state (ON/OFF)
Hunny Mane
IU2341051286
CE-C A1

if device not in devices:


return jsonify({"error": "Invalid device. Use 'LED' or 'Fan'."}),
400
if state in ["ON", "OFF"]:
devices[device] = state
return jsonify({"message": f"{device} turned {state}"})
else:
return jsonify({"error": "Invalid state. Use 'ON' or 'OFF'."}), 40

5. Running the Flask App

if name == ' main ':


app.run(host="0.0.0.0", port=5001)

● The Flask app runs on port 5001, listening for incoming requests.

Outputs :

Running Check :

Turning the LED ON statshows:


Hunny Mane
IU2341051286
CE-C A1

Turning the FAN ON :

Turning the LED OFF :

Turning the FAN OFF :

Conclusion :

This project successfully demonstrates how to build a simple yet effective IoT control system using
Flask and ngrok. By exposing the Flask server through ngrok, users can control their devices remotely
via HTTP requests. The system is highly adaptable and can be expanded to include more devices or
integrate with IoT platforms. It serves as a foundation for building smart home automation or other
IoT-based applications.

You might also like