Skip to content
cic1337xdaPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

I-PED Smart Farm Vision System

An AI-powered plant health monitoring system that uses a Raspberry Pi camera module, a YOLO object detection model, and a vertical gantry mechanism to autonomously inspect and treat crops affected by chlorosis.


Table of Contents


Overview

I-PED (Intelligent Plant Evaluation & Diagnosis) is a Final Year Project (FYP) system designed to:

  1. Stream live video from a Raspberry Pi camera mounted on a vertical gantry.
  2. Detect plant diseases (specifically chlorosis) in real-time using YOLOv8 object detection.
  3. Actuate treatment (spray) via an ESP32-controlled mechanism when disease is detected.
  4. Collect labelled training data through a human-in-the-loop correction interface.

The system operates across three hardware nodes:

Node Role
Raspberry Pi Camera streaming + WiFi captive portal for network configuration
Central Server Docker-hosted AI backend running YOLO inference, serving the web dashboard
ESP32 Actuator controller for the vertical gantry slider, robotic arm, and spray pump (connected via WebSocket)

System Architecture

                         Internet (Cloudflare Tunnel)
                                    |
 [Raspberry Pi]                     |                  [Central Server]
 +------------------+               |          +---------------------------+
 | PiCamera Module  |               |          |  Docker: iped_vision_engine|
 |       |          |               |          |                           |
 | streamer.py :5000|---> cloudflared tunnel -->| main.py :8000             |
 |                  |               |          |   - Fetches MJPEG stream  |
 | portal.py :80    |               |          |   - YOLO inference        |
 | (WiFi config)    |               |          |   - WebSocket to ESP32    |
 +------------------+               |          |   - Serves web dashboard  |
                                    |          |                           |
                                    |          | static/                   |
                                    |          |   - index.html            |
                                    |          |   - database.html         |
 [ESP32 Actuator]                   |          |   - script.js, style.css  |
 +------------------+               |          +---------------------------+
 | Vertical Slider  |               |                     |
 | Robotic Arm      |<--- WebSocket /ws/actuator ----------+
 | Spray Pump       |
 +------------------+

Project Structure

iped/
├── .env                          # Environment variables (HOST_PORT, ENVIRONMENT)
├── docker-compose.yml            # Docker Compose service definition
├── README.md                     # This file
│
├── backend/
│   ├── Dockerfile                # Python 3.11-slim container build
│   ├── main.py                   # FastAPI backend (AI inference, stream proxy, WebSocket)
│   ├── requirements.txt          # Python dependencies
│   ├── ipednanobest.pt           # YOLOv8 Nano trained weights
│   ├── ipedsmallbest.pt          # YOLOv8 Small trained weights
│   ├── best.pt                   # General best weights
│   └── iped-age+vision.pt        # Combined age + vision model weights
│
├── Raspberry Pi Code/
│   ├── streamer.py               # MJPEG camera stream server (port 5000)
│   ├── portal.py                 # WiFi captive portal (port 80)
│   ├── RASPBERRY_PI_SETUP.md     # Full Raspberry Pi deployment guide
│   └── MODEL_TRAINING.md         # Guide for training custom YOLO models
│
├── ESP32 Code/
│   └── ipedmotors/
│       └── ipedmotors.ino        # Arduino sketch: WebSocket client, servo/stepper control, relay spray
│
└── static/
    ├── index.html                # Main vision dashboard (live stream + controls)
    ├── database.html             # Telemetry archive viewer
    ├── script.js                 # Frontend logic (stream, corrections, polling)
    └── style.css                 # Apple-inspired glassmorphism UI theme

How It Works

Streaming Pipeline

  1. The Raspberry Pi runs streamer.py, which captures frames from the PiCamera2 module at 640x480 resolution and serves them as an MJPEG stream on port 5000.
  2. A Cloudflare Tunnel (cloudflared) exposes port 5000 to a public subdomain (e.g., ipedstream.yourdomain.com).
  3. The server's main.py continuously fetches frames from the tunnel URL using OpenCV's VideoCapture.

AI Inference

  1. A background thread (continuous_inference_worker) runs YOLO object detection on each captured frame when the system is in ANALYZING state.
  2. Detection results are overlaid on the stream served to the web dashboard.
  3. A majority-voting mechanism scans for 6 seconds, collecting predictions. If the majority class contains "chlorosis", the system triggers treatment.

Vertical Gantry Sequence

When triggered from the web dashboard, the system executes a 3-level vertical scan:

  1. Level 1 -- Slider moves to home position, arm articulates to position 1, 6-second scan.
  2. Level 2 -- Slider moves to position 2, arm to position 2, 6-second scan.
  3. Level 3 -- Slider moves to position 3, arm to position 3, 6-second scan.
  4. Reset -- Slider returns to home.

At each level, if chlorosis is detected, the system sends SPRAY commands to the ESP32 via WebSocket.

Important: The vertical scan sequence requires an ESP32 to be connected to the server via WebSocket (/ws/actuator). If no ESP32 is connected, clicking "Start Vertical Sequence" will immediately show "Hardware Disconnected" and the scan will not run. Even an ESP32 with just the base firmware (no motors attached) is sufficient to establish the connection and allow the scan sequence to proceed.

Human-in-the-Loop Training

The web dashboard includes a correction interface where users can:

  • Capture a snapshot from the live stream.
  • Review AI predictions with bounding boxes.
  • Correct misclassifications by selecting the right class.
  • Add missing detections manually.
  • Submit corrections as YOLO-format labels saved to the server's persistent storage.

These corrected labels accumulate on the server in the configured DATA_PATH (e.g., /mnt/hdd1tb/iped/data/) and can be used to retrain the model for improved accuracy.

AI Model Origin

The .pt weight files were produced using a combination of two platforms:

Platform Purpose
Roboflow Dataset management -- uploading images, drawing bounding box annotations, and applying augmentations (blur, rotation, noise, flipping, etc.) to expand the dataset.
Google Colab Model training -- Roboflow's built-in model export requires a paid plan, so the augmented dataset is exported from Roboflow and used in Google Colab to train YOLOv8 models locally with the Ultralytics library.

Two model variants are trained and deployed:

Model File Architecture Characteristics
ipednanobest.pt YOLOv8 Nano Faster inference, lower accuracy. Suitable for real-time monitoring.
ipedsmallbest.pt YOLOv8 Small Slower inference, higher accuracy. Suitable for detailed analysis.

The model can be hot-swapped from the web dashboard without restarting the server.

For the full training procedure, see Raspberry Pi Code/MODEL_TRAINING.md.


Prerequisites

Server

  • Docker and Docker Compose installed
  • An external Docker network named pwn20wnd-network (create with docker network create pwn20wnd-network)
  • Persistent storage mount directory (configurable via DATA_PATH in .env)

Raspberry Pi

  • Raspberry Pi 3B+, 4, or 5 with Raspberry Pi OS (Bookworm or later)
  • Raspberry Pi Camera Module connected and enabled
  • Cloudflare account with a registered domain
  • See Raspberry Pi Code/RASPBERRY_PI_SETUP.md for full setup instructions

ESP32 (Actuator)

  • ESP32 development board (e.g., ESP32-WROOM-32)
  • Arduino IDE (2.x recommended) or PlatformIO
  • Required Arduino libraries (install via Library Manager):
    • WiFiManager by tzapu
    • WebSockets by Markus Sattler
    • ESP32Servo by Kevin Harrington
  • Hardware connected to the ESP32:
    • 4x servo motors (4-axis SCARA arm) on GPIO 23, 33, 25, 26
    • 1x stepper motor + driver (vertical gantry slider) on GPIO 12 (DIR) and 14 (STEP)
    • 1x relay module (spray pump) on GPIO 27
  • The ESP32 must be on a network with internet access to reach the server's WebSocket endpoint

Server Deployment

1. Clone the Repository

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

2. Create the External Docker Network (if it doesn't exist)

docker network create pwn20wnd-network

3. Configure Environment Variables

Create and edit a .env file (you can copy .env.example) to set your configuration parameters:

HOST_PORT=8090
ENVIRONMENT=development

# Raspberry Pi stream URL (Cloudflare Tunnel domain pointing to the Pi's streamer)
RPI_STREAM_URL=https://ipedstream.yourdomain.com/stream

# Host path for persistent data storage (detected images and labels)
# Change this to any directory on your server where you want to store data
DATA_PATH=/mnt/hdd1tb/iped/data

4. Build and Start

docker compose up -d --build

The dashboard will be accessible at http://<server-ip>:8090.

5. Verify

  • Visit http://<server-ip>:8090 -- you should see the vision dashboard.
  • Visit http://<server-ip>:8090/database -- you should see the telemetry archive.
  • If the Raspberry Pi is online and the Cloudflare Tunnel is active, the live stream will appear in the dashboard.

Raspberry Pi Setup

See the full guide: Raspberry Pi Code/RASPBERRY_PI_SETUP.md

Quick summary:

  1. Transfer streamer.py and portal.py to the Pi.
  2. Install dependencies (picamera2, fastapi, uvicorn, opencv).
  3. Install and configure Cloudflare Tunnel.
  4. Create systemd services for both scripts.
  5. Update the server's stream URL to match your tunnel domain.

ESP32 Setup

The ESP32 acts as the actuator node, controlling the vertical gantry slider, robotic arm, and spray pump. It connects to the server via WebSocket and executes commands received during the automated scan sequence.

Note: The ESP32 connection is mandatory for the scan sequence to work. Without an ESP32 connected to the /ws/actuator WebSocket endpoint, the "Start Vertical Sequence" button on the dashboard will return "Hardware Disconnected." You do not need motors or hardware attached -- just an ESP32 running the firmware and connected to WiFi is enough to establish the link and allow the system to operate.

Hardware Wiring

Component GPIO Pin Notes
Servo 1 (Base) 23 SCARA arm base rotation
Servo 2 (Elbow 1) 33 First elbow joint
Servo 3 (Elbow 2) 25 Second elbow joint
Servo 4 (Elbow 3) 26 Third elbow joint (wrist)
Stepper DIR 12 Stepper motor direction pin
Stepper STEP 14 Stepper motor pulse pin
Relay (Spray Pump) 27 Controls the spray pump via relay module

Arm Positions (Servo Angles)

Position Base Elbow 1 Elbow 2 Elbow 3 Description
Home (POS1) 176 152 124 74 Retracted safe position
POS2 180 146 90 74 Mid-reach position
POS3 180 130 46 74 Full-reach position

Slider Positions (Stepper Steps)

Position Step Count Description
Home 0 Bottom level
POS2 730 Middle level
POS3 1460 Top level

Flashing the Firmware

  1. Open ESP32 Code/ipedmotors/ipedmotors.ino in Arduino IDE.

  2. Install the required libraries via Sketch > Include Library > Manage Libraries:

    • Search and install WiFiManager by tzapu
    • Search and install WebSockets by Markus Sattler
    • Search and install ESP32Servo by Kevin Harrington
  3. Select your board: Tools > Board > ESP32 Dev Module.

  4. Update the WebSocket server URL in the code. Find this line:

    webSocket.beginSSL("ipedvision.flowkraft.xyz", 443, "/ws/actuator");

    Change ipedvision.flowkraft.xyz to your server's domain (the same domain where the Docker backend is hosted, accessible via HTTPS).

  5. Connect the ESP32 via USB, select the correct port under Tools > Port, and click Upload.

First Boot (WiFi Configuration)

The ESP32 uses WiFiManager for network configuration:

  1. On first boot (or when it can't connect to a saved network), the ESP32 creates a WiFi access point named IPED-AGV-SETUP.
  2. Connect to this network from your phone or laptop.
  3. A captive portal will open automatically. Select your WiFi network and enter the password.
  4. The ESP32 will save the credentials and connect. On successful connection, it will establish a WebSocket tunnel to the server.

WebSocket Commands

Once connected, the ESP32 receives text commands from the server and maps them to hardware actions:

Command Action
SLIDER_HOME Move vertical slider to home position (step 0)
SLIDER_POS2 Move vertical slider to level 2 (step 730)
SLIDER_POS3 Move vertical slider to level 3 (step 1460)
ARM_POS1 Articulate arm to home/retracted position
ARM_POS2 Articulate arm to mid-reach position
ARM_POS3 Articulate arm to full-reach position
SPRAY Energize relay (spray pump) for 10 seconds

Verifying the Connection

Open the Arduino Serial Monitor at 115200 baud. You should see:

[CORE 0] Secure tunnel established via NAT!

This confirms the ESP32 has connected to the server's /ws/actuator WebSocket endpoint. On the server side, you will see a corresponding log:

[WEBSOCKET] ESP32 Actuator successfully bridged into secure public tunnel.

AI Model Training

See the full guide: Raspberry Pi Code/MODEL_TRAINING.md

Quick summary:

  1. Annotate and augment your dataset in Roboflow.
  2. Export the dataset via a download link.
  3. Train YOLOv8 Nano and Small models in Google Colab.
  4. Download the resulting .pt weight files.
  5. Place them in the backend/ directory and rebuild the Docker container.

Web Dashboard

The system includes two web pages served by the backend:

Live Vision (/)

  • Real-time MJPEG stream with AI detection overlays.
  • Dynamic Island-style status pill showing current system state (IDLE, ANALYZING, SPRAYING, MOVING).
  • Model switcher (Nano / Small) for hot-swapping inference models.
  • "Start Vertical Sequence" button to trigger the 3-level gantry scan.
  • "Incorrect AI Detection?" button to enter correction mode for human-in-the-loop retraining.

Telemetry Archive (/database)

  • Grid view of all captured and corrected images.
  • Displays YOLO-format annotation data for each record.
  • Data stored persistently on the server's external storage.

Both pages support dark/light theme toggling.


API Reference

Stream Endpoints

Method Endpoint Description
GET /api/stream?mode=raw Raw MJPEG stream from the Pi camera
GET /api/stream?mode=inference MJPEG stream with AI detection overlays

System State

Method Endpoint Description
GET /api/state Returns current system status (IDLE, ANALYZING, SPRAYING, MOVING, SWAPPING)

AI Inference

Method Endpoint Description
POST /api/detect Upload an image for one-shot inference
POST /api/detect_live Run inference on the current live frame
POST /api/model/switch Hot-swap AI model. Body: {"model_name": "ipednanobest.pt"}

Automation

Method Endpoint Description
POST /api/trigger_scan Trigger the vertical gantry scan sequence
POST /api/start_static_test Alias for trigger_scan

Training Data

Method Endpoint Description
POST /api/feedback Submit a label correction (YOLO format)
GET /api/database/list List all saved training records
GET /api/database/image/{id} Retrieve a saved image by ID

WebSocket

Endpoint Description
ws://.../ws/actuator ESP32 actuator connection. Receives text commands: SLIDER_HOME, SLIDER_POS2, SLIDER_POS3, ARM_POS1, ARM_POS2, ARM_POS3, SPRAY

Configuration

Environment Variables (.env)

Variable Default Description
HOST_PORT 8090 Port exposed on the host machine
ENVIRONMENT development Deployment environment flag
RPI_STREAM_URL https://ipedstream.yourdomain.com/stream Cloudflare Tunnel URL for the Pi camera stream. Must be changed to your own domain.
DATA_PATH /mnt/hdd1tb/iped/data Host path for persistent data storage (images and labels)

Docker Volumes

Host Path Container Path Purpose
./static /app/static Hot-reloadable frontend assets
${DATA_PATH} /app/data Persistent storage for captured images and labels

License

This project was developed as a Final Year Project (FYP 2026-2027). License terms to be determined by the project author.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages