Metadata-Version: 2.1
Name: iotlabkit
Version: 1.0.3
Summary: A Beginner-Friendly IoT Lab Code Generator for MSc/MCA Practicals (Programs 5-17)
Author: IoT Lab Contributors
License: MIT
Keywords: iot,mqtt,coap,rest-api,machine-learning,data-analytics,education,laboratory,code-generator
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Education
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Education
Classifier: Topic :: Home Automation
Classifier: Topic :: Scientific/Engineering
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: analytics
Requires-Dist: requests>=2.28.0; extra == "analytics"
Requires-Dist: pandas>=1.5.0; extra == "analytics"
Requires-Dist: matplotlib>=3.6.0; extra == "analytics"
Provides-Extra: ml
Requires-Dist: pandas>=1.5.0; extra == "ml"
Requires-Dist: matplotlib>=3.6.0; extra == "ml"
Requires-Dist: scikit-learn>=1.2.0; extra == "ml"
Requires-Dist: joblib>=1.2.0; extra == "ml"
Provides-Extra: iot
Requires-Dist: requests>=2.28.0; extra == "iot"
Requires-Dist: paho-mqtt>=1.6.1; extra == "iot"
Requires-Dist: python-dotenv>=1.0.0; extra == "iot"
Provides-Extra: dashboard
Requires-Dist: streamlit>=1.25.0; extra == "dashboard"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Provides-Extra: all
Requires-Dist: requests>=2.28.0; extra == "all"
Requires-Dist: pandas>=1.5.0; extra == "all"
Requires-Dist: matplotlib>=3.6.0; extra == "all"
Requires-Dist: scikit-learn>=1.2.0; extra == "all"
Requires-Dist: joblib>=1.2.0; extra == "all"
Requires-Dist: paho-mqtt>=1.6.1; extra == "all"
Requires-Dist: python-dotenv>=1.0.0; extra == "all"
Requires-Dist: streamlit>=1.25.0; extra == "all"
Requires-Dist: pytest>=7.0.0; extra == "all"

# iotlabkit — Beginner-Friendly IoT Lab Code Generator

[![Python 3.9+](https://img.shields.io/badge/python-3.9%2B-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![Practicals: 5-17](https://img.shields.io/badge/Practicals-5--17%20Supported-brightgreen.svg)](#3-supported-practical-programs)
[![Zero-Config CoAP](https://img.shields.io/badge/CoAP-Pure%20Python%20RFC%207252-orange.svg)](#program-8--coap-client-and-server)

A complete, beginner-friendly Python package and CLI tool designed specifically for **MSc / MCA Semester 3 IoT Laboratory practicals**.

`iotlabkit` generates complete, readable, production-grade project code for **Programs 5 through 17**, supporting two interchangeable presentation modes:
- **Learning Mode (`--mode learning`)**: Rich architectural diagrams, plain-English comments, troubleshooting tips, function walkthroughs, and viva questions.
- **Exam Mode (`--mode exam`)**: Concise, minimal, practical code ready for university laboratory examination submission.

---

## Table of Contents

1. [What is iotlabkit?](#1-what-is-iotlabkit)
2. [What Can It Do?](#2-what-can-it-do)
3. [Supported Practical Programs](#3-supported-practical-programs)
4. [Python Installation Guide](#4-python-installation-guide)
5. [Creating a Virtual Environment](#5-creating-a-virtual-environment)
6. [Installing iotlabkit](#6-installing-iotlabkit)
7. [Listing Practicals (`list`)](#7-listing-practicals-list)
8. [Inspecting a Practical (`info`)](#8-inspecting-a-practical-info)
9. [Generating a Project (`create`)](#9-generating-a-project-create)
10. [Installing Project Dependencies](#10-installing-project-dependencies)
11. [Configuring Cloud Services & Credentials](#11-configuring-cloud-services--credentials)
12. [Dataset Management & Offline Testing](#12-dataset-management--offline-testing)
13. [Running Each Practical](#13-running-each-practical)
14. [Running Diagnostics (`doctor`)](#14-running-diagnostics-doctor)
15. [Troubleshooting & Common Errors](#15-troubleshooting--common-errors)
16. [Uninstalling the Package](#16-uninstalling-the-package)

---

## 1. What is iotlabkit?

In university IoT laboratory curricula, students often face hurdles configuring diverse communication protocols (HTTP REST, MQTT, CoAP), cloud databases (Supabase, Firebase, ThingsBoard), and machine learning pipelines (Decision Trees, Linear Regression, Random Forests).

`iotlabkit` solves this by automating the boilerplate generation while maintaining **100% genuine code, real APIs, and authentic datasets**. It does not generate fake sensor readings or synthetic ML data. Every project generated is self-contained and immediately runnable.

---

## 2. What Can It Do?

- **Generates complete, runnable projects** with a single command: `iotlabkit create <id>`.
- **Supports 13 university practicals** across Communication, Analytics, and Machine Learning layers.
- **Built-in Pure-Python RFC 7252 CoAP implementation**: Runs CoAP client and server on UDP port 56830 with **zero external pip dependencies**.
- **Real live API integrations**: Connects directly to Open-Meteo Weather, Open-Meteo Air Quality, USGS Earthquakes, and ISS Orbital coordinates.
- **Authentic datasets bundled & downloadable**: Pre-bundles balanced genuine subsets of UCI Occupancy (#357), UCI Beijing PM2.5 (#501), and Kaggle India Air Quality (`city_day.csv`), with official downloaders for the full datasets.
- **Dual Presentation Modes**: Switch effortlessly between verbose educational code (`learning`) and concise exam submission code (`exam`).
- **Interactive Web Dashboards**: Generates instant Streamlit dashboards for real-time visualization.

---

## 3. Supported Practical Programs

Strictly implements Programs 5 through 17 from the syllabus. Programs 1–4 and 18 are excluded.

| ID | Title | Layer | External Dependencies | Internet Needed? | Cloud Keys? |
| :-: | :--- | :--- | :--- | :-: | :-: |
| **5** | **HTTP REST API + Cloud DB + Dashboard** | Communication | Flask, Requests, Streamlit | Yes | Yes (Supabase/Firebase) |
| **6** | **MQTT + Cloud DB + Dashboard** | Communication | Paho-MQTT, Requests, Streamlit | Yes | Yes (Supabase/Firebase) |
| **7** | **ThingsBoard + MQTT Telemetry** | Communication | Paho-MQTT, python-dotenv | Yes | Yes (Device Token) |
| **8** | **CoAP Client and Server** | Communication | *None (Standard Library)* | **No** | **No** |
| **9** | **Online & Local MQTT Brokers** | Communication | Paho-MQTT, python-dotenv | Online only | No |
| **10** | **CoAP Environmental Monitoring** | Communication | Requests, Streamlit | Yes | Yes (Supabase/Firebase) |
| **11** | **ISS Real-Time Orbit Tracking** | Data Analytics | Requests, Pandas, Matplotlib, Streamlit | Yes | No |
| **12** | **USGS Global Earthquake Analysis** | Data Analytics | Requests, Pandas, Matplotlib, Streamlit | Yes | No |
| **13** | **Kochi Weather Trend Analysis** | Data Analytics | Requests, Pandas, Matplotlib, Streamlit | Yes | No |
| **14** | **Kochi Hourly Air Quality Analysis** | Data Analytics | Requests, Pandas, Matplotlib, Streamlit | Yes | No |
| **15** | **Decision Tree Occupancy Detection** | Machine Learning | Scikit-learn, Pandas, Joblib, Matplotlib | **No** (Bundled) | No |
| **16** | **Linear Regression Temp Prediction** | Machine Learning | Scikit-learn, Pandas, Joblib, Matplotlib | **No** (Bundled) | No |
| **17** | **Random Forest Air Quality Classifier**| Machine Learning | Scikit-learn, Pandas, Joblib, Matplotlib | **No** (Bundled) | No |

---

## 4. Python Installation Guide

Verify you have Python 3.9 or higher installed:

```bash
python3 --version
# Output should be Python 3.9.x, 3.10.x, 3.11.x, 3.12.x, or 3.13.x
```

### Linux (Ubuntu / Debian)
```bash
sudo apt update
sudo apt install -y python3 python3-pip python3-venv
```

### Linux (Fedora / RHEL)
```bash
sudo dnf install -y python3 python3-pip
```

### Windows (PowerShell)
Download the official Python installer from [python.org](https://www.python.org/downloads/). During installation, **make sure to check the box: "Add Python to PATH"**.

---

## 5. Creating a Virtual Environment

Always use a Python virtual environment to keep your system packages clean.

### On Linux / macOS (Bash)
```bash
# Create a virtual environment named .venv
python3 -m venv .venv

# Activate the virtual environment
source .venv/bin/activate
```

### On Windows (PowerShell)
```powershell
# Create a virtual environment named .venv
python -m venv .venv

# Activate the virtual environment
.\.venv\Scripts\Activate.ps1
```
*(If PowerShell shows an execution policy error, run: `Set-ExecutionPolicy -Scope Process -ExecutionPolicy RemoteSigned`)*

---

## 6. Installing iotlabkit

Install `iotlabkit` in editable development mode directly from this repository:

### Linux / macOS
```bash
python3 -m pip install -e .
```

### Windows
```powershell
python -m pip install -e .
```

To install optional extra dependencies (e.g. for ML or dashboards):
```bash
pip install -e ".[all]"         # Install all dependencies
pip install -e ".[analytics]"   # Pandas, Matplotlib, Requests
pip install -e ".[ml]"          # Scikit-learn, Joblib, Pandas, Matplotlib
pip install -e ".[iot]"         # Paho-MQTT, Requests, Python-dotenv
pip install -e ".[dashboard]"   # Streamlit
```

Verify installation:
```bash
iotlabkit --version
# Output: iotlabkit 1.0.0
```

---

## 7. Listing Practicals (`list`)

To view all supported programs and their operational flags:

```bash
iotlabkit list
```

Sample output:
```
==========================================================================================
           iotlabkit — MSc/MCA IoT Laboratory Practicals (Programs 5-17)
==========================================================================================
ID   | Title                                         | Net  | Keys  | Broker | Data  | Server
------------------------------------------------------------------------------------------
--- Communication and Application Layer ---
5    | HTTP REST API + Cloud Database + Dashboard    | Yes  | Yes   | No     | No    | Yes   
6    | MQTT + Cloud Database + Dashboard             | Yes  | Yes   | Yes    | No    | No    
7    | ThingsBoard + MQTT Telemetry                  | Yes  | Yes   | Yes    | No    | No    
8    | CoAP Client and Server Environmental Monit... | No   | No    | No     | No    | Yes   
...
```

---

## 8. Inspecting a Practical (`info`)

To view detailed prerequisites, objectives, generated files, and viva questions for any program:

```bash
iotlabkit info 8
iotlabkit info 15
```

---

## 9. Generating a Project (`create`)

Generate a practical project using its program number:

### Learning Mode (Default)
Generates complete educational code with detailed docstrings, architecture diagrams, step-by-step instructions, and comprehensive viva Q&A:
```bash
iotlabkit create 5
iotlabkit create 12
iotlabkit create 15
```

### Exam Mode (`--mode exam`)
Generates concise, focused, production-grade code designed for laboratory examination submission:
```bash
iotlabkit create 5 --mode exam
iotlabkit create 15 --mode exam
```

### Custom Output Directory & Overwrite Flags
```bash
# Generate into a custom directory name
iotlabkit create 8 --output my_coap_lab

# Overwrite existing files without interactive prompt
iotlabkit create 8 --force
```

---

## 10. Installing Project Dependencies

Each generated project contains a self-contained `requirements.txt`:

```bash
cd lab05
pip install -r requirements.txt
```

*(Note: Program 8 uses pure standard library and requires **zero** external pip packages!)*

---

## 11. Configuring Cloud Services & Credentials

For programs requiring cloud integration (Programs 5, 6, 7, and 10), each generated project includes a `.env.example` template.

1. Navigate to the project folder and copy the template:
   ```bash
   # Linux / macOS:
   cp .env.example .env

   # Windows (PowerShell):
   Copy-Item .env.example .env
   ```
2. Open `.env` in any text editor (VS Code, Notepad, Nano).

### Supabase Setup (Programs 5, 6, 10)
- Sign up at [supabase.com](https://supabase.com).
- Create a project.
- Open the SQL Editor and run the provided `supabase_schema.sql` file.
- Copy your **Project URL** and **anon public key** into `.env`:
  ```ini
  SUPABASE_URL=https://your-project-ref.supabase.co
  SUPABASE_KEY=your-anon-public-key
  ```

### Firebase Setup (Programs 5, 6, 10 Alternative)
- Open [Firebase Console](https://console.firebase.google.com).
- Create a project -> Build -> **Realtime Database**.
- In `.env`:
  ```ini
  CLOUD_PROVIDER=firebase
  FIREBASE_DATABASE_URL=https://your-project.firebaseio.com
  ```

### ThingsBoard Setup (Program 7)
- Sign up at [thingsboard.cloud](https://thingsboard.cloud).
- Navigate to **Entities -> Devices -> Add new device** (e.g. `Lab_Sensor_01`).
- Copy the **Access Token** from Device Details.
- In `.env`:
  ```ini
  THINGSBOARD_ACCESS_TOKEN=your-device-access-token
  ```

> **Offline Fallback Guarantee**: If cloud credentials are not supplied, Programs 5, 6, and 10 automatically fall back to local JSON caching (`data/local_*.json`) so you can complete and test the practical offline without internet!

---

## 12. Dataset Management & Offline Testing

- **Program 15 (Occupancy Detection)**: Comes pre-bundled with 800 authentic records from UCI Dataset #357 in `data/datatraining.txt`. Run `python data/download_dataset.py` to fetch the full 8,143 records.
- **Program 16 (Beijing Temperature)**: Comes pre-bundled with 800 authentic records from UCI Dataset #501 in `data/beijing_sample.csv`. Run `python column_inspection.py` to inspect features.
- **Program 17 (India Air Quality)**: Comes pre-bundled with 900 balanced records across all 6 CPCB categories in `data/city_day_sample.csv`. Run `python data/download_dataset.py` for full Kaggle dataset instructions.

---

## 13. Running Each Practical

### Program 5 — HTTP REST API + Cloud DB + Dashboard
```bash
# Terminal 1: Start REST Server
python server.py

# Terminal 2: Stream Sensor Telemetry
python client_sender.py

# Terminal 3: Launch Web Dashboard
streamlit run dashboard.py
```

### Program 6 — MQTT + Cloud DB + Dashboard
```bash
# Terminal 1: Start Subscriber
python subscriber.py

# Terminal 2: Publish Real Readings
python publisher.py

# Terminal 3: View Dashboard
streamlit run dashboard.py
```

### Program 7 — ThingsBoard + MQTT
```bash
python main.py
# Follow `thingsboard_dashboard_guide.md` to configure ThingsBoard widgets.
```

### Program 8 — CoAP Client and Server (Zero Dependencies!)
```bash
# Terminal 1: Start CoAP Server
python server.py

# Terminal 2: Query CoAP Server
python client.py

# Continuous live observation:
python client.py --watch 3
```

### Program 9 — Online & Local MQTT Brokers
```bash
# Online Mode (HiveMQ Public Cloud Broker):
python subscriber.py --broker online
python publisher.py --broker online

# Local Mode (Mosquitto Edge Broker):
python subscriber.py --broker local
python publisher.py --broker local
```

### Program 10 — CoAP Environmental Monitoring (Open-Meteo)
```bash
# Terminal 1: CoAP Server (fetches Open-Meteo & serves CoAP)
python coap_env_server.py

# Terminal 2: CoAP Client (queries CoAP & stores to DB)
python coap_env_client.py

# Terminal 3: Dashboard
streamlit run dashboard.py
```

### Program 11 — ISS Location Tracking
```bash
# Collect 100 live orbital points at 5-second intervals (~8.3 minutes):
python collector.py --count 100 --interval 5

# Compute orbital statistics & generate trend plots:
python analyzer.py

# View interactive orbit map:
streamlit run dashboard.py
```

### Program 12 — USGS Earthquake Analysis
```bash
# Retrieve past 7 weeks of live seismic data from USGS:
python fetch_data.py

# Compute statistical distribution & plots:
python analyzer.py

# Launch interactive seismic dashboard:
streamlit run dashboard.py
```

### Program 13 — Weather Analysis (Kochi)
```bash
# Fetch hourly meteorological data from Open-Meteo:
python fetch_weather.py

# Compute Pearson correlation & trend curves:
python analyzer.py

# Launch dashboard:
streamlit run dashboard.py
```

### Program 14 — Air Quality Analysis (Kochi)
```bash
# Fetch hourly PM10, PM2.5, and US AQI:
python fetch_air_quality.py

# Calculate particulate statistics & WHO threshold curves:
python analyzer.py

# Launch dashboard:
streamlit run dashboard.py
```

### Program 15 — Decision Tree Room Occupancy Classifier
```bash
# Train Decision Tree model and export artifacts:
python train.py

# Classify occupancy for a new sensor reading:
python predict.py --temp 23.2 --humidity 27.2 --light 426 --co2 721

# Launch Streamlit predictor:
streamlit run dashboard.py
```

### Program 16 — Linear Regression Temperature Prediction
```bash
# Inspect actual dataset columns:
python column_inspection.py

# Train Linear Regression model (MAE, RMSE, R²):
python train.py

# Predict temperature for new readings:
python predict.py --dewp -16.0 --pres 1020.0 --pm25 120.0 --wind 2.0
```

### Program 17 — Random Forest Air Quality Classification
```bash
# Train Random Forest classifier across 6 CPCB classes:
python train.py

# Predict air quality bucket for new pollutant readings:
python predict.py --pm25 85 --pm10 140 --no2 32 --co 1.2 --so2 15 --o3 45

# Launch interactive dashboard:
streamlit run dashboard.py
```

---

## 14. Running Diagnostics (`doctor`)

Check your Python environment, installed tools, and optional packages:

```bash
iotlabkit doctor
```

The doctor tool safely checks environment variables without exposing sensitive secret values.

---

## 15. Troubleshooting & Common Errors

### `Errno 111: Connection Refused` (Programs 5, 8, 10)
**Cause:** The client was started before the corresponding server was active.  
**Fix:** Keep Terminal 1 running with the server (`python server.py`) before running the client script in Terminal 2.

### `ModuleNotFoundError: No module named 'iotlabkit'`
**Cause:** Package was not installed in editable mode or virtual environment is not activated.  
**Fix:** Activate your virtual environment and run `pip install -e .`.

### `Mosquitto Connection Refused (Port 1883)` (Program 9 Local Mode)
**Cause:** Mosquitto service is not running on your computer.  
**Fix:**  
- Linux: `sudo systemctl start mosquitto`  
- Windows: Start Mosquitto from the Services window or run `net start mosquitto`.

### `Supabase 401 Unauthorized` (Programs 5, 6, 10)
**Cause:** Invalid `SUPABASE_KEY` or missing `anon` key.  
**Fix:** Check that your `.env` contains the full `anon` key from Project Settings -> API.

---

## 16. Uninstalling the Package

To remove `iotlabkit` from your environment:

```bash
pip uninstall iotlabkit -y
```

---

## License

This project is licensed under the [MIT License](LICENSE).  
Datasets and APIs used belong to their respective creators:
- UCI Machine Learning Repository (Occupancy Detection #357, Beijing PM2.5 #501) — CC BY 4.0
- Rohan Rao Indian Air Quality Dataset (`city_day.csv`) — CC0: Public Domain
- Open-Meteo & Open-Meteo Air Quality APIs — Non-commercial educational use
- USGS Earthquake API — U.S. Geological Survey (Public Domain)
- Open-Notify & WhereTheISS APIs — Open satellite telemetry data
