Skip to content

teamharsh/SmartKrishi_AI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

54 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

SmartKrishi AI — A Precision Agriculture Ecosystem

Agriculture 4.0 for the Indian farmer. An end-to-end IoT + AI-powered Smart Agriculture platform that fuses edge hardware, deep-learning microservices, and a SaaS-gated web dashboard with an integrated B2B/B2C e-commerce store.

Institution: Purnea College of Engineering Department: Electronics and Communication Engineering (ECE) Faculty Mentor: Prof. Dheeraj Kumar


Table of Contents


1. Vision & Business Model

The global agricultural sector must feed a projected 10 billion people by 2050 — a 70 % increase in food output — against 25 % degraded farmland and accelerating climate stress. Local farmers today struggle with:

  • Blind spots — inability to monitor fields 24/7.
  • Water-wasting guesswork — irrigation without soil or weather data.
  • Manual labour — field walks for disease and pest inspection.
  • Delayed disease detection — crop loss before diagnosis.

SmartKrishi AI bridges the gap between traditional farming and Agriculture 4.0. It combines:

  • A plug-and-play "Smart Farm Kit" (one-time hardware cost) — ESP8266 control hub + ESP32-CAM vision node.
  • A minimal yearly SaaS subscription — unlocks cloud ML: hyper-local rain prediction, live pest detection, and botanical diagnostics.
  • A React/Vite web app — live gauges, remote pump control, AI diagnostics, e-commerce.
  • A direct-to-consumer marketplace — farmers buy the kit, seeds, fertilisers, and tools with UPI/Card via PhonePe.

The business model keeps barriers low: cheap hardware, affordable yearly renewal, high-value intelligence.


2. System Architecture

┌────────────────────────────────────────────────────────────────┐
│                     🌾 FARM (Edge Layer)                       │
│                                                                │
│   ┌───────────────────────┐       ┌────────────────────────┐  │
│   │ Control Node          │       │ Vision Node            │  │
│   │ ESP8266 NodeMCU       │       │ ESP32-CAM (planned)    │  │
│   │ DHT11 · BMP180        │       │ MJPEG live stream      │  │
│   │ ADS1115 (soil + rain) │       │ Pest surveillance feed │  │
│   │ Pump Relay · LED      │       │                        │  │
│   └──────────┬────────────┘       └───────────┬────────────┘  │
└──────────────┼──────────────────────────────────┼──────────────┘
               │ HTTPS POST                       │ MJPEG / HTTP
               │ (X-Device-Key auth)              │
               ▼                                  ▼
┌────────────────────────────────────────────────────────────────┐
│                    ☁️  CLOUD (SaaS Layer)                      │
│                                                                │
│   ┌──────────────────────────┐     ┌────────────────────────┐ │
│   │ Node.js / Express API    │────▶│ MongoDB Atlas          │ │
│   │ :8000                    │     │ Users · Products       │ │
│   │ Auth · Orders · Sensors  │     │ Orders · SensorDatas   │ │
│   │ JWT + Hardware Keys      │     │ PlantDetections        │ │
│   │ PhonePe Payments         │     │ WeatherDatas · Dashboard│ │
│   └──────────┬───────────────┘     └────────────────────────┘ │
│              │ HTTP (proxy)                                    │
│              ▼                                                 │
│   ┌──────────────────────────┐                                 │
│   │ Python / Flask AI API    │                                 │
│   │ :5000                    │                                 │
│   │ TFLite Runtime           │                                 │
│   │ • Rain Predictor (LSTM)  │                                 │
│   │ • Leaf Doctor (CNN)      │                                 │
│   │ • Pest Guardian (YOLO)*  │                                 │
│   └──────────────────────────┘                                 │
│                              * planned                         │
└────────────────────────────────────────────────────────────────┘
                              ▲
                              │ HTTPS (JWT cookies)
                              │
┌────────────────────────────────────────────────────────────────┐
│              🖥️  React + Vite Frontend (:5173)                 │
│   Farmer Dashboard · Admin Console · E-commerce Storefront     │
│   TailwindCSS v4 · MUI v7 · Zustand · Recharts · GSAP          │
└────────────────────────────────────────────────────────────────┘

3. Hardware — The Edge Layer

The kit is decoupled into two nodes so each can be installed / relocated independently.

3.1 Control Node — ESP8266 NodeMCU

The static "brain" of the field. Powered by 5 V, interfaces with environmental telemetry and machinery.

Channel Component Purpose Status
D5 DHT11 Ambient temperature & humidity ✅ Implemented
I2C (D1/D2) BMP180 Barometric pressure (storm prediction) ✅ Implemented
I2C via ADS1115 Soil Moisture Sensor Root-zone hydration ✅ Implemented (A0)
I2C via ADS1115 Analog Rain Sensor Active rainfall detection ✅ Implemented (A1)
I2C via ADS1115 MQ-135 AQI / pesticide toxicity 🟡 Planned
Digital HC-SR04 Ultrasonic Reservoir water level 🟡 Planned
D7 5 V Relay → 220 V Submersible Pump Irrigation actuator 🟡 Currently drives an LED; relay wiring pending
Digital via 2N2222 NPN 12 V DC Exhaust Fan Greenhouse ventilation on toxic AQI 🟡 Planned
Digital Passive Buzzer Critical field alarms 🟡 Planned

Firmware: Arduino/local_sensor_testing.ino Transport: HTTPS POST every 10 s to /api/sensors/data with X-Device-Key header (matched against Dashboard.device.deviceId). Payload: nested JSON — readings.{temperature,humidity,soilMoisture,rain,barometricPressure} + pumpAction.

3.2 Vision Node — ESP32-CAM (planned)

A portable, completely wireless visual surveillance module.

  • Streams live MJPEG video to the dashboard.
  • Acts as an edge-node feeding frames into the Pest Guardian (YOLO) and Leaf Doctor (MobileNetV2) pipelines.
  • Currently disease detection is supported via manual image upload from the dashboard (react-dropzone).

4. Artificial Intelligence — The SaaS Layer

Three ML microservices served by a single Flask app on port 5000, loading TFLite models lazily.

4.1 Model 1 — Purnea Rain Predictor (LSTM)

  • File: aibackend/services/weather_prediction_service.py
  • Model: aibackend/models/weather_prediction_model.tflite
  • Dataset: purnia_weather_2016_2025_model_training.csv — 10 years of Purnea weather (2016–2025).
  • Training script: train_lstm_model.py
  • Cross-reference: pulls live macro weather via OpenWeatherMap (OPENWEATHER_API_KEY) using the farm's GPS coordinates for a "double-check" against local pressure drops.
  • Current output: 14-value vector → 7-day [temp_day_1..7, rain_chance_day_1..7].
  • Target (per spec): 2-layer LSTM (128 → 64), Dropout 0.3, Dense(32, ReLU), 9 input features, 30-day lookback sequence window, 19-class condition head, 91.3 % rain accuracy, RMSE 1.8 °C. → retraining planned to match spec.
  • Action: When rain probability exceeds 70 %, the system preemptively blocks the water pump relay (conserving electricity, preventing waterlogging). This override is on the roadmap — see Implementation Status.

4.2 Model 2 — Leaf Doctor (CNN / MobileNetV2)

  • File: aibackend/services/plant_disease_service.py
  • Model: aibackend/models/plant_disease_model.tflite
  • Class labels: aibackend/models/class_names.json (currently 38–43 classes; source = PlantVillage + Rice/Wheat extensions).
  • Pipeline: image → resize to 224×224 → feed to MobileNetV2 backbone (frozen ImageNet weights) → GlobalAveragePooling2D → Dense(256, ReLU) → Dropout(0.4) → Softmax over disease classes.
  • Dataset: PlantVillage (14 crop types, 11 000+ images) + additional Rice & Wheat rust classes.
  • Reported metrics: Accuracy 96.4 %, Precision 95.8 %, Recall 96.1 %, F1 95.9 %.
  • Action: returns structured remedial plans — chemical pesticides (with dosage / frequency / safety period), organic alternatives, prevention tips, and urgency — sourced from the built-in DISEASE_INFO knowledge base for 30+ blights and rusts.

4.3 Model 3 — Pest Guardian (YOLO Object Detection) — edge-ready foundation implemented

  • Endpoint available at POST /predict/pest in aibackend/routes/pest_routes.py.
  • Returns robust pipeline diagnostics for edge cases: adaptive confidence, quality flags (dark/bright/blur/contrast), temporal filter state (3/5 default), and stream freeze hints.
  • Current build keeps detections empty until final YOLO decoder/weights integration is completed, while preserving a stable contract for backend and frontend.

5. Software & Cloud Architecture

5.1 Backend Microservices

Service Stack Port Purpose
API Gateway Node.js · Express 5 8000 Auth, payments, hardware routing, e-commerce, admin
ML Inference Python 3 · Flask 5000 TFLite model serving
Database MongoDB Atlas cloud Time-series + relational

Security layers:

  • JWT sessions (httpOnly cookies + Authorization header).
  • Hardware Authentication Keys (X-Device-Key) — each IoT kit has a unique device ID matched against Dashboard.device.deviceId.
  • Rate limiting (rateLimiter.middleware.js), Helmet, NoSQL-injection protection.
  • Feature-gate middleware (checkFeature.middleware.js) — locks dashboard sections behind SaaS subscription tier.

5.2 MongoDB Collections

Collection Purpose
Users Profiles, auth credentials, OTP state, subscription role
Products E-commerce catalogue (kits, seeds, fertilisers, tools)
Orders Purchase records, PhonePe transaction IDs, AWB tracking
SensorDatas Time-series telemetry from ESP8266
PlantDetections History of AI leaf diagnoses
WeatherDatas Aggregated ML + API forecasts
Dashboard Per-farmer feature unlocks, pump state, device binding, preferences

5.3 Frontend (React 19 + Vite 7)

Styled with TailwindCSS v4 and Material UI v7, animated with GSAP, charted with Recharts, state managed by Zustand.

  • Farmer Dashboard — live gauges, remote pump toggle, Weather AI widget, plant scan, order tracking, locked-feature screens for non-subscribers.
  • Admin Console — product inventory, separate "add product" and "add subscription plan" flows, subscription lifecycle management, order logistics (AWB/events), user management, global audit, system logs.
  • Storefront — catalogue, checkout, PhonePe callback, OTP verification, password reset.

6. End-to-End User Flow

  1. Create Account — farmer registers via email + OTP (mobile OTP planned).
  2. Secure Purchase — browses the storefront, buys the "Smart Farm Kit" (one-time) and "Yearly AI Subscription" via PhonePe UPI/Card.
  3. Sensors Sync Live — hardware is delivered and installed. ESP8266 begins POSTing telemetry to SensorDatas every 10 s.
  4. Remote Control + Smart Automation — farmer toggles the pump from the dashboard. The LSTM cross-checks local pressure drops with OpenWeatherMap. (Rain > 70 % auto-pump-block is planned.)
  5. AI Disease Cure — farmer uploads a leaf photo (ESP32-CAM stream planned). MobileNetV2 identifies the disease and returns a structured organic + chemical remedy.
  6. Pest Surveillance (planned) — ESP32-CAM continuously scans the field; YOLO flags locusts; buzzer deters them; dashboard logs an event.
  7. Renewal (planned) — automated annual-subscription renewal prompts via email.

7. Repository Layout

FinalYearProject/
├── frontend/                        React 19 + Vite 7 SPA
│   ├── src/
│   │   ├── pages/
│   │   │   ├── farmer/              FarmerDashboard, SensorDashboard,
│   │   │   │                        WeatherDashboard, WeatherAiDashboard,
│   │   │   │                        PlantAiScanPage, AiDiagnosisResult,
│   │   │   │                        OrderTracking, DashboardCatalogue,
│   │   │   │                        ProfilePage, SettingsPage, AuditLogsPage
│   │   │   ├── admin/               AdminDashboard, ProductInventory,
│   │   │   │                        OrderManagement, UserManagement,
│   │   │   │                        GlobalAudit, SystemLogs, ManageUserStatus
│   │   │   └── public/              Landing, Login, Register, OTP,
│   │   │                            Checkout, PaymentCallback, ProductCatalog
│   │   ├── components/              Sidebar, BottomNav, ProtectedRoute,
│   │   │                            LockedFeatureScreen, ThemeToggle
│   │   ├── store/                   Zustand stores
│   │   ├── api/                     Axios wrappers
│   │   └── hooks/
│   └── vite.config.js
│
├── backend/                         Node.js + Express REST API
│   ├── routes/                      auth, weather, sensor, product, order,
│   │                                plantDetection, dashboard, admin
│   ├── controllers/
│   ├── models/                      User, Product, Order, SensorData,
│   │                                PlantDetection, WeatherData, Dashboard
│   ├── middleware/                  auth, checkFeature, rateLimiter,
│   │                                errorHandler, upload
│   ├── config/                      DB connection
│   ├── swagger/                     OpenAPI docs
│   └── app.js
│
├── aibackend/                       Python Flask ML microservice
│   ├── routes/                      detect_routes, recommend_routes, health
│   ├── services/                    plant_disease_service,
│   │                                weather_prediction_service
│   │                                (pest_guardian_service — planned)
│   ├── models/                      plant_disease_model.tflite,
│   │                                weather_prediction_model.tflite,
│   │                                class_names.json
│   ├── requirements.txt
│   └── app.py
│
├── Arduino/                         ESP8266 firmware + hardware docs
│   ├── local_sensor_testing.ino
│   └── README.md
│
├── train_lstm_model.py              Weather LSTM training pipeline
├── purnia_weather_2016_2025_model_training.csv   Purnea 10-yr dataset
├── WEATHER_PREDICTION_SETUP.md      In-depth weather system docs
└── Readme.md                        ← this file

8. Prerequisites

Tool Version Link
Node.js ≥ 18.x https://nodejs.org/
npm ≥ 9.x bundled with Node
Python ≥ 3.10 https://www.python.org/
pip latest bundled with Python
Git latest https://git-scm.com/
MongoDB Atlas cloud https://www.mongodb.com/atlas
Arduino IDE 2.x https://www.arduino.cc/ (for flashing the ESP8266)

9. Environment Variables

9.1 backend/.env

PORT=8000
NODE_ENV=development
CLIENT_URL=http://localhost:5173

# MongoDB
MONGO_URI=mongodb+srv://<user>:<pass>@<cluster>.mongodb.net/?retryWrites=true&w=majority

# JWT
JWT_SECRET=your_jwt_secret_key
JWT_EXPIRES_IN=7d

# Flask AI server
ML_MODEL_URL=http://localhost:5000

# OpenWeatherMap
OPENWEATHER_API_KEY=your_openweathermap_api_key

# Email (Gmail SMTP)
GMAIL_USER=your_email@gmail.com
GMAIL_APP_PASSWORD=your_gmail_app_password
GMAIL_SENDER_NAME=SmartKrishiAI

# PhonePe
PHONEPE_ENV=test
PHONEPE_MERCHANT_ID=PGTESTPAYUAT86
PHONEPE_SALT_KEY=your_phonepe_salt_key
PHONEPE_SALT_INDEX=1

Get a free OpenWeatherMap API key at https://openweathermap.org/api

9.2 aibackend/.env

PORT=5000
FLASK_DEBUG=1
FLASK_ENV=development

ALLOWED_ORIGINS=http://localhost:8000,http://localhost:5173
OPENWEATHER_API_KEY=your_openweathermap_api_key

PLANT_DISEASE_MODEL_PATH=models/plant_disease_model.tflite
WEATHER_PREDICTION_MODEL_PATH=models/weather_prediction_model.tflite

9.3 frontend/.env

VITE_API_BASE_URL=http://localhost:8000/api

10. Installation & Setup

10.1 Clone

git clone https://github.com/<your-username>/FinalYearProject.git
cd FinalYearProject

10.2 Backend (Node.js)

cd backend
npm install
# configure .env (see section 9.1)
npm run dev

Runs at http://localhost:8000 · Swagger at http://localhost:8000/api-docs

10.3 AI Backend (Flask)

cd aibackend
python -m venv .venv
source .venv/bin/activate      # Linux / macOS
# .venv\Scripts\activate       # Windows
pip install -r requirements.txt
# configure .env (see section 9.2)
python app.py

Runs at http://localhost:5000

Method Endpoint Description
GET /health Health probe
POST /api/detect Plant disease classification (Leaf Doctor)
POST /predict/weather 7-day forecast (Rain Predictor)
GET /debug Dependency + model file check

10.4 Frontend (Vite)

cd frontend
npm install
# configure .env (see section 9.3)
npm run dev

Open http://localhost:5173

10.5 Arduino / IoT Hardware

  1. Open Arduino/local_sensor_testing.ino in the Arduino IDE.
  2. Install libraries: Adafruit_BMP085, DHT, Adafruit_ADS1X15, ArduinoJson.
  3. Set WIFI_SSID, WIFI_PASSWORD, SERVER_URL, and DEVICE_KEY (must match Dashboard.device.deviceId in MongoDB).
  4. Flash to an ESP8266 NodeMCU board.
  5. Watch the serial monitor at 115200 baud — you should see nested-JSON uploads every 10 s.

See Arduino/README.md for wiring diagrams and pin-outs.

10.6 Retrain the Weather LSTM (optional)

A pre-trained .tflite already ships at aibackend/models/weather_prediction_model.tflite.

pip install tensorflow pandas scikit-learn numpy
python train_lstm_model.py

This will:

  1. Load purnia_weather_2016_2025_model_training.csv.
  2. Train a 2-layer LSTM (128 → 64) on 9 input features with a 30-day lookback.
  3. Export to aibackend/models/weather_prediction_model.tflite.

11. Running the Full Stack

Three terminals in parallel:

# Directory Command URL
1 backend/ npm run dev http://localhost:8000
2 aibackend/ python app.py http://localhost:5000
3 frontend/ npm run dev http://localhost:5173

Then open the frontend in a browser.


12. API Overview

Node.js backend exposes these route groups under /api:

Prefix Description
/api/auth Register, login, OTP verification, profile
/api/weather Unified 3-layer weather data (sensor + API + LSTM)
/api/sensors IoT ingestion (POST /data) + retrieval
/api/detect Plant disease detection (proxied to Flask)
/api/product Product catalogue + CRUD (admin)
/api/order Order creation + PhonePe payment
/api/dashboard Per-farmer dashboard state + feature unlocks
/api/admin Admin user + system management

Full interactive docs: http://localhost:8000/api-docs (Swagger UI).


13. Implementation Status

Honest snapshot of what's working today vs. planned. Use this as the single source of truth when discussing the project.

✅ Implemented

  • Node.js/Express REST API with JWT + hardware-key auth, Swagger, rate limiting
  • MongoDB Atlas with 7 collections (Users, Products, Orders, SensorDatas, PlantDetections, WeatherDatas, Dashboard)
  • Flask AI microservice with lazy-loaded TFLite models
  • Leaf Doctor (MobileNetV2, 38+ classes, PlantVillage) with structured treatment plans
  • Rain Predictor (LSTM → TFLite) with 7-day forecast + OpenWeatherMap cross-check
  • ESP8266 firmware — DHT11, BMP180, soil moisture, rain sensor, HTTPS upload every 10 s, moisture-threshold pump trigger
  • React + Vite + MUI + Tailwind frontend with Farmer Dashboard, Admin Console, Storefront
  • OTP + Google sign-in, PhonePe checkout, feature-gated SaaS unlocks via LockedFeatureScreen
  • Admin global audit, system logs, user status management
  • Admin product suite upgrades: add physical products, add subscription plans (yearly/AI), richer SKU types (vision_kit, yearly_ai, consumable), stock and status controls
  • Subscription operations: farmer subscription dashboard + admin subscription table with run-lifecycle and cancellation controls
  • AWB logistics tracking in admin orders + farmer order timeline events
  • Pest Guardian full-stack wiring:
    • aibackend: edge-case diagnostics pipeline in /predict/pest
    • backend: persistence of pipeline diagnostics in PestDetection, buzzer cooldown guard (PEST_BUZZER_COOLDOWN_MINUTES, default 10)
    • frontend: diagnostics surfaced in Pest Detection and Detail pages

🟡 In Progress / Partial

  • Pump control: dashboard toggle exists, but physical relay is currently wired as an LED indicator
  • Rain Predictor metrics: reports 7-day forecast but the 19-class condition head + 91.3 % rain accuracy spec needs retraining to match
  • Leaf Doctor class list: has 38–43 entries (includes Rice + Wheat rust beyond classic PlantVillage); to be normalised
  • Pest Guardian inference: final YOLO decode + real bounding-box detection remains pending model deployment validation

🔴 Planned (not yet built)

  • Rain > 70 % → auto pump-block (end-to-end: ML → backend → Arduino relay)
  • ESP32-CAM Vision Node — firmware + MJPEG live stream + dashboard viewer
  • ESP8266 extensions — MQ-135 (AQI), HC-SR04 (water level), 12 V exhaust fan driver (2N2222), passive buzzer
  • Renewal reminders — proactive email/WhatsApp nudges before subscription expiry
  • AI Chatbot (LLM-based farmer Q&A)
  • WhatsApp / SMS alerts (SMS preference flag exists; no provider wired yet)

14. Roadmap / Future Scope

  • AI Chatbot Support — LLM-based assistant answering conversational questions using the farmer's own soil + crop history.
  • WhatsApp & SMS Alerts — real-time push for storm warnings, disease risk, and fertiliser schedules.
  • Smart Field Robot — autonomous ground robot for soil sampling, close-range disease detection, and manual-labour reduction.
  • Drone Crop Monitoring — UAV capture of high-resolution aerial imagery, generating farm-wide AI health maps.

Pest Guardian Edge-Case Build Notes (Latest Update)

The following updates were applied across all three app layers:

aibackend/

  • Enhanced routes/pest_routes.py to return:
    • adaptive confidence suggestion from frame brightness/contrast
    • frame-quality flags (isTooDark, isTooBright, isLowContrast, isBlurry, glare ratio)
    • temporal filter counters (windowSize, positiveFrames, confirmation state)
    • stream freeze hints (isFrozen, lastFrameAt)
  • Keeps API response stable even when YOLO weights are missing.

backend/

  • Extended models/pestDetection.model.js with pipeline diagnostics schema.
  • Updated controllers/pestDetection.controller.js to:
    • persist pipeline data from AI response
    • write compatible summary keys (totalPests, totalPestsDetected, totalDetections)
    • enforce buzzer cooldown before retriggering high/critical alerts.

frontend/

  • Updated pages/farmer/PestDetectionPage.jsx to show frame-quality and temporal-gate diagnostics after each analysis.
  • Updated pages/farmer/PestDetectionDetailPage.jsx to display stored edge-case diagnostics for historical detections.

15. Datasets & References

Datasets

  • 10-Year Purnea Weather Dataset (2016–2025) — 29 224 3-hourly records aggregated into 3 653 days, 19 weather-condition classes, 9 input features, 655 rainy days. Shipped as purnia_weather_2016_2025_model_training.csv.
  • PlantVillage Dataset — 11 000+ labelled leaf images across 14 crops and 38 disease classes.

Research Papers Consulted

  1. Internet of Things (IoT) and Machine Learning based Smart Agriculture System.
  2. Deep Learning for Plant Disease Detection using MobileNetV2 Architecture.
  3. Time Series Weather Forecasting using Long Short-Term Memory (LSTM).

16. License

Released under the MIT License.

About

IoT + AI precision agriculture platform with plant disease detection, pest monitoring, weather prediction, crop recommendation, and smart irrigation.

Topics

Resources

License

Stars

0 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors