Tuesday, 21 July 2026

AI-Based Smart Traffic Ambulance Clearance System

``` AI-Based Smart Traffic Ambulance Clearance System ```
```

🚑 AI-Based Smart Traffic Ambulance Clearance System

ESP32 + AI Agent + n8n Automation + Telegram Voice Alerts + Google Sheets + ThingSpeak + PHP + MySQL

```
```

1. Full Project Description

The AI-Based Smart Traffic Ambulance Clearance System is an intelligent Agentic IoT project designed to detect an approaching ambulance, monitor traffic conditions, analyze traffic density, and assist authorized traffic personnel in creating a clear path for the ambulance.

The system uses ESP32 sensors to collect real-time traffic and emergency data. The collected data is sent through the Internet to a PHP backend and n8n automation workflow.

An AI Agent analyzes ambulance status, traffic density, vehicle count, emergency level, and other parameters. Based on the analysis, the AI generates a recommended emergency traffic clearance action.

Main Concept: SENSE → ANALYZE → DECIDE → AUTOMATE → ALERT → LOG → PREDICT
```
```

2. Project Objectives

  1. Detect an approaching ambulance.
  2. Monitor traffic density.
  3. Count vehicles.
  4. Calculate emergency priority.
  5. Analyze traffic conditions using AI.
  6. Generate traffic clearance recommendations.
  7. Send Telegram text alerts.
  8. Send Telegram voice notifications.
  9. Store emergency data in Google Sheets.
  10. Upload IoT data to ThingSpeak.
  11. Display data on a PHP dashboard.
  12. Predict future power consumption.
```
```

3. Components List

Component Purpose
ESP32 DevKit Main IoT controller
HC-SR04 Ultrasonic Sensor Vehicle detection
IR Vehicle Sensor Traffic counting
NEO-6M GPS Module Ambulance location tracking
RC522 RFID Reader Ambulance authentication
RFID Card or Tag Emergency vehicle identification
OLED Display Local data display
Buzzer Local emergency alert
Red LED Emergency status
Green LED Normal status
Current Sensor Power monitoring
Voltage Sensor Voltage measurement
5V Power Supply System power
```
```

4. Complete System Architecture

``` AMBULANCE ↓ GPS / RFID / SOS ↓ ESP32 CONTROLLER ↓ TRAFFIC SENSORS ↓ WiFi INTERNET ↓ PHP API + MySQL ↓ n8n AUTOMATION ↓ AI AGENT ↓ ┌────────────────────────────┐ │ Telegram Text Alert │ │ Telegram Voice Alert │ │ Google Sheets Logging │ │ ThingSpeak Cloud │ │ PHP Web Dashboard │ └────────────────────────────┘ ```
```
```

5. Circuit Schematic Diagram


                     +--------------------+
                     |       ESP32        |
                     |                    |
                     | GPIO 5  ----------|---- TRIG SENSOR 1
                     | GPIO 18 ----------|---- ECHO SENSOR 1
                     |                    |
                     | GPIO 19 ----------|---- TRIG SENSOR 2
                     | GPIO 21 ----------|---- ECHO SENSOR 2
                     |                    |
                     | GPIO 4  ----------|---- RFID SDA
                     | GPIO 22 ----------|---- RFID RST
                     | GPIO 27 ----------|---- EMERGENCY BUTTON
                     | GPIO 26 ----------|---- RED LED
                     | GPIO 25 ----------|---- GREEN LED
                     | GPIO 33 ----------|---- BUZZER
                     |                    |
                     |       WiFi         |
                     +---------┬----------+
                               |
                               ▼
                          INTERNET
                               |
          ┌────────────────────┼───────────────────┐
          ▼                    ▼                   ▼
    PHP + MySQL              n8n              ThingSpeak
     Dashboard            Automation             Cloud
                               |
                               ▼
                           AI AGENT
                               |
          ┌────────────────────┼───────────────────┐
          ▼                    ▼                   ▼
      Telegram            Google Sheets        Voice Alert

Important: The HC-SR04 ECHO pin may output 5V. ESP32 GPIO pins use 3.3V logic. Use a voltage divider for the ECHO signal.
```
```

6. Complete Flowchart

``` SYSTEM START ↓ INITIALIZE ESP32 ↓ CONNECT TO WiFi ↓ READ TRAFFIC SENSORS ↓ DETECT AMBULANCE ↓ ┌───────────────┐ │ Ambulance? │ └───────┬───────┘ │ ┌────┴────┐ │ │ NO YES │ │ ▼ ▼ NORMAL READ TRAFFIC DATA ↓ CALCULATE DENSITY ↓ AI ANALYSIS ↓ CALCULATE PRIORITY ↓ GENERATE ACTION ↓ SEND n8n ↓ ┌───────────┼───────────┐ ▼ ▼ ▼ Telegram Voice Google Sheets │ │ │ └───────────┼───────────┘ ▼ ThingSpeak ↓ PHP Dashboard ↓ LOOP ```
```
```

7. Ambulance Detection

RFID Method

``` RFID READER ↓ READ RFID UID ↓ COMPARE WITH REGISTERED ID ↓ AMBULANCE AUTHENTICATED ```

GPS Method

``` AMBULANCE GPS ↓ LATITUDE + LONGITUDE ↓ DISTANCE FROM JUNCTION ↓ ESTIMATE ARRIVAL TIME ```

Emergency Button Method

``` EMERGENCY BUTTON ↓ ESP32 ↓ WiFi ↓ EMERGENCY ALERT ```
```
```

8. AI Decision Logic

The AI Agent receives ambulance status, traffic density, vehicle count, emergency level, distance and power data.

```

Example:

Ambulance Detected = TRUE

Traffic Density = 85

Vehicle Count = 42

Emergency Level = 5

Priority Score =
Emergency Level × 30
+
Traffic Density × 0.3
+
Distance Factor

Priority > 150
= CRITICAL

Priority 100 to 150
= HIGH

Priority 50 to 100
= MEDIUM

Priority < 50
= NORMAL

```
```
```

9. ESP32 Source Code


```

#include 
#include 
#include 
#include 
#include 

#define TRIG1 5
#define ECHO1 18

#define TRIG2 19
#define ECHO2 21

#define RFID_SS 4
#define RFID_RST 22

#define EMERGENCY_BUTTON 27
#define RED_LED 26
#define GREEN_LED 25
#define BUZZER 33

const char* WIFI_SSID =
"YOUR_WIFI_NAME";

const char* WIFI_PASSWORD =
"YOUR_WIFI_PASSWORD";

const char* SERVER_URL =
"https://your-domain.com/api/ambulance_data.php";

MFRC522 rfid(
RFID_SS,
RFID_RST
);

long readDistance(
int trigPin,
int echoPin
)
{
digitalWrite(
trigPin,
LOW
);

```
delayMicroseconds(
    2
);

digitalWrite(
    trigPin,
    HIGH
);

delayMicroseconds(
    10
);

digitalWrite(
    trigPin,
    LOW
);

long duration =
pulseIn(
    echoPin,
    HIGH,
    30000
);

long distance =
duration *
0.034 /
2;

return distance;
```

}

void connectWiFi()
{
WiFi.begin(
WIFI_SSID,
WIFI_PASSWORD
);

```
while(
    WiFi.status()
    != WL_CONNECTED
)
{
    delay(
        500
    );
}
```

}

void sendDataToServer(
bool ambulance,
int trafficDensity,
int vehicleCount,
int emergencyLevel
)
{
if(
WiFi.status()
== WL_CONNECTED
)
{
HTTPClient http;

```
    http.begin(
        SERVER_URL
    );

    http.addHeader(
        "Content-Type",
        "application/json"
    );

    StaticJsonDocument<512>
    json;

    json[
        "device_id"
    ] =
    "ESP32_AMBULANCE_001";

    json[
        "ambulance_detected"
    ] =
    ambulance;

    json[
        "traffic_density"
    ] =
    trafficDensity;

    json[
        "vehicle_count"
    ] =
    vehicleCount;

    json[
        "emergency_level"
    ] =
    emergencyLevel;

    json[
        "signal_status"
    ] =
    ambulance
    ?
    "CLEARANCE_REQUIRED"
    :
    "NORMAL";

    String requestBody;

    serializeJson(
        json,
        requestBody
    );

    http.POST(
        requestBody
    );

    http.end();
}
```

}

void setup()
{
Serial.begin(
115200
);

```
pinMode(
    TRIG1,
    OUTPUT
);

pinMode(
    ECHO1,
    INPUT
);

pinMode(
    TRIG2,
    OUTPUT
);

pinMode(
    ECHO2,
    INPUT
);

pinMode(
    EMERGENCY_BUTTON,
    INPUT_PULLUP
);

pinMode(
    RED_LED,
    OUTPUT
);

pinMode(
    GREEN_LED,
    OUTPUT
);

pinMode(
    BUZZER,
    OUTPUT
);

SPI.begin();

rfid.PCD_Init();

connectWiFi();

digitalWrite(
    GREEN_LED,
    HIGH
);
```

}

void loop()
{
long distance1 =
readDistance(
TRIG1,
ECHO1
);

```
long distance2 =
readDistance(
    TRIG2,
    ECHO2
);

int vehicleCount =
0;

if(
    distance1
    < 30
)
{
    vehicleCount++;
}

if(
    distance2
    < 30
)
{
    vehicleCount++;
}

int trafficDensity =
vehicleCount *
50;

bool emergencyButton =
digitalRead(
    EMERGENCY_BUTTON
)
==
LOW;

if(
    emergencyButton
)
{
    digitalWrite(
        RED_LED,
        HIGH
    );

    digitalWrite(
        GREEN_LED,
        LOW
    );

    digitalWrite(
        BUZZER,
        HIGH
    );

    sendDataToServer(
        true,
        trafficDensity,
        vehicleCount,
        5
    );

    delay(
        5000
    );

    digitalWrite(
        BUZZER,
        LOW
    );
}
else
{
    digitalWrite(
        RED_LED,
        LOW
    );

    digitalWrite(
        GREEN_LED,
        HIGH
    );

    sendDataToServer(
        false,
        trafficDensity,
        vehicleCount,
        0
    );
}

delay(
    10000
);
```

}

```
```
```

10. n8n Workflow Automation

``` ESP32 HTTP REQUEST ↓ WEBHOOK ↓ JSON VALIDATION ↓ AI AGENT ↓ EMERGENCY CONDITION ↓ ┌────────────────────────────┐ │ Telegram Text │ │ Telegram Voice │ │ Google Sheets │ │ ThingSpeak │ │ PHP Dashboard │ └────────────────────────────┘ ```

AI Agent Prompt

```

You are an intelligent emergency traffic management AI agent.

Analyze the following ambulance traffic data:

Ambulance Detected:
{{ $json.ambulance_detected }}

Traffic Density:
{{ $json.traffic_density }}

Vehicle Count:
{{ $json.vehicle_count }}

Emergency Level:
{{ $json.emergency_level }}

Your task is to:

1. Determine emergency priority.
2. Classify traffic condition.
3. Recommend a safe traffic clearance action.
4. Generate a Telegram alert.
5. Generate a voice notification.
6. Return JSON only.

Required JSON:

{
"priority": "CRITICAL",
"traffic_condition": "HIGH",
"recommended_action":
"Clear emergency lane and notify traffic controller",
"telegram_message":
"Emergency ambulance detected. Please clear the emergency lane immediately.",
"voice_message":
"Attention. Emergency ambulance approaching. Please clear the emergency lane immediately."
}

```

n8n Workflow JSON


```

{
"name":
"AI Ambulance Traffic Clearance",

```
"nodes":
[
    {
        "name":
        "ESP32 Webhook",

        "type":
        "n8n-nodes-base.webhook",

        "parameters":
        {
            "path":
            "ambulance-alert",

            "httpMethod":
            "POST"
        }
    },

    {
        "name":
        "Emergency Detected?",

        "type":
        "n8n-nodes-base.if",

        "parameters":
        {
            "conditions":
            {
                "boolean":
                [
                    {
                        "value1":
                        "={{$json.ambulance_detected}}",

                        "operation":
                        "isTrue"
                    }
                ]
            }
        }
    },

    {
        "name":
        "Telegram Alert",

        "type":
        "n8n-nodes-base.telegram",

        "parameters":
        {
            "chatId":
            "YOUR_TELEGRAM_CHAT_ID",

            "text":
            "AMBULANCE ALERT: Traffic clearance required immediately."
        }
    },

    {
        "name":
        "Google Sheets Log",

        "type":
        "n8n-nodes-base.googleSheets",

        "parameters":
        {
            "operation":
            "append",

            "documentId":
            "YOUR_GOOGLE_SHEET_ID",

            "sheetName":
            "AmbulanceData"
        }
    }
]
```

}

```
```
```

11. Telegram Bot Setup

  1. Open Telegram.
  2. Search for BotFather.
  3. Send: /newbot
  4. Enter your bot name.
  5. Copy the generated Bot Token.
  6. Create a Telegram group.
  7. Add the bot to the group.
  8. Configure the bot credentials in n8n.

Example Telegram Alert

```

🚨 CRITICAL EMERGENCY 🚨

Ambulance detected.

Traffic Density: HIGH

Vehicle Count: 42

Emergency Level: CRITICAL

Please clear the emergency lane immediately.

```
```
```

12. Voice Notification Automation

``` AI TEXT ↓ TEXT-TO-SPEECH SERVICE ↓ AUDIO FILE ↓ TELEGRAM VOICE MESSAGE ```

Example voice notification:

```

Attention.

Critical emergency.

Ambulance approaching.

Traffic density is high.

Please clear the emergency lane immediately.

```
```
```

13. Google Sheets Integration

Create a Google Sheet with the following columns:

Column Description
Timestamp Event date and time
Device ID ESP32 identification
Ambulance Detected YES or NO
Traffic Density Traffic percentage
Vehicle Count Number of detected vehicles
Emergency Level Emergency priority
Recommended Action AI recommendation
Power Consumption Measured system power
```
```

14. ThingSpeak Cloud Dashboard

Recommended ThingSpeak fields:

  • Field 1: Traffic Density
  • Field 2: Vehicle Count
  • Field 3: Ambulance Status
  • Field 4: Emergency Level
  • Field 5: Power Consumption
  • Field 6: Priority Score

ThingSpeak can display real-time graphs, gauges, emergency events, and power consumption trends.

```
```

15. AI Power Consumption Prediction

```

Power = Voltage × Current

Example:

Voltage = 5V

Current = 0.5A

Power = 5 × 0.5

Power = 2.5 Watts

Energy = Power × Time

```
``` COLLECT POWER DATA ↓ STORE HISTORICAL DATA ↓ AI TREND ANALYSIS ↓ PREDICT FUTURE POWER ↓ GENERATE WARNING ↓ TELEGRAM NOTIFICATION ```
```
```

16. Agentic IoT Decision-Making

``` OBSERVE ↓ ANALYZE ↓ DECIDE ↓ ACT ↓ LEARN ```

Example:

  1. Ambulance is detected.
  2. Traffic density is analyzed.
  3. AI determines emergency priority.
  4. AI generates a clearance recommendation.
  5. n8n sends Telegram alerts.
  6. Voice notification is generated.
  7. Google Sheets stores the event.
  8. ThingSpeak displays the data.
  9. PHP dashboard shows the live status.
```
```

17. Recommended Project Folder Structure

```

ambulance-smart-system/

│
├── index.html
│
├── config.php
│
├── database.sql
│
├── api/
│   ├── ambulance_data.php
│   ├── get_latest_data.php
│   └── power_data.php
│
├── admin/
│   ├── login.php
│   └── dashboard.php
│
├── assets/
│   ├── css/
│   │   └── style.css
│   │
│   └── js/
│       └── dashboard.js
│
├── esp32/
│   └── ambulance_traffic.ino
│
├── n8n/
│   └── ambulance_workflow.json
│
└── README.md

```
```
```

18. Step-by-Step Deployment Guide

  1. Assemble the ESP32 hardware.
  2. Connect traffic sensors.
  3. Connect ambulance detection system.
  4. Connect emergency button.
  5. Connect LEDs and buzzer.
  6. Create the MySQL database.
  7. Deploy the PHP backend.
  8. Configure the ESP32 WiFi.
  9. Configure the API URL.
  10. Test ESP32 data transmission.
  11. Configure the n8n webhook.
  12. Configure the AI Agent.
  13. Configure Telegram Bot.
  14. Configure voice notification automation.
  15. Configure Google Sheets.
  16. Configure ThingSpeak.
  17. Test emergency ambulance detection.
```
```

19. Complete Operating Workflow

``` 🚑 AMBULANCE ↓ 📡 ESP32 DETECTION ↓ 🚦 TRAFFIC SENSOR DATA ↓ 🌐 INTERNET ↓ 🧠 AI AGENT ↓ ⚙️ n8n AUTOMATION ↓ 📱 TELEGRAM TEXT ALERT ↓ 🔊 TELEGRAM VOICE ALERT ↓ 📊 GOOGLE SHEETS ↓ ☁️ THINGSPEAK ↓ 🖥️ PHP WEB DASHBOARD ```
```
```

20. Future Enhancements

Computer Vision Vehicle Detection
AI Traffic Prediction
GPS Ambulance Tracking
ETA Prediction
Multi-Junction Green Corridor
Android Mobile Application
Solar-Powered IoT Node
Accident Detection
Edge AI Processing
5G Communication
Multiple Ambulance Coordination
Hospital Arrival Prediction
```
```

21. Safety Consideration

For real public-road deployment, this prototype should not directly control traffic signals without approval from authorized traffic authorities.
``` DETECTION ↓ AI RECOMMENDATION ↓ AUTHORIZED CONTROLLER APPROVAL ↓ TRAFFIC CLEARANCE ```
```
```

22. Final Project Summary

This project integrates ESP32, IoT sensors, Artificial Intelligence, n8n automation, Telegram notifications, voice alerts, Google Sheets, ThingSpeak, PHP and MySQL.

Final System Concept: SENSE → UNDERSTAND → DECIDE → AUTOMATE → ALERT → LOG → PREDICT

The system is suitable for Electrical Engineering, Electronics Engineering, IoT, Embedded Systems, Artificial Intelligence, Automation, Smart City, Final-Year Engineering and Research Projects.

```
```

© 2026 AI Smart Traffic Ambulance Clearance System

ESP32 + AI Agent + n8n + Telegram + Google Sheets + ThingSpeak + PHP + MySQL

```

Monday, 20 July 2026

AI-Based Smart Retail Inventory Monitoring System

Yes. Below is the same complete Smart Retail Inventory Monitoring project converted into a PHP-based project structure, with the web dashboard, APIs, database, AI logic, n8n integration, Telegram alerts, Google Sheets integration, ThingSpeak integration, and documentation pages. Important: ESP32 firmware must remain .ino/Arduino C++ code because ESP32 cannot execute PHP. PHP is used for the web server, APIs, database, AI logic, cloud integration, and dashboard. 1. Complete PHP Project Structure smart-retail-inventory/ │ ├── index.php ├── dashboard.php ├── products.php ├── alerts.php ├── predictions.php ├── settings.php │ ├── config/ │ ├── database.php │ ├── config.php │ └── api_keys.php │ ├── api/ │ ├── esp32_data.php │ ├── inventory.php │ ├── products.php │ ├── alerts.php │ ├── prediction.php │ ├── telegram.php │ ├── thingspeak.php │ └── google_sheets.php │ ├── ai/ │ ├── inventory_ai.php │ ├── consumption_prediction.php │ └── reorder_prediction.php │ ├── includes/ │ ├── header.php │ ├── footer.php │ ├── navbar.php │ └── functions.php │ ├── assets/ │ ├── css/ │ │ └── style.css │ └── js/ │ └── dashboard.js │ ├── database/ │ └── smart_retail.sql │ ├── n8n/ │ └── inventory_workflow.json │ ├── documentation/ │ ├── project_description.php │ ├── components.php │ ├── circuit.php │ ├── flowchart.php │ ├── installation.php │ └── future_enhancements.php │ └── esp32/ └── smart_retail_inventory.ino 2. config/database.php connect_error) { die( "Database connection failed: " . $conn->connect_error ); } $conn->set_charset("utf8mb4"); ?> 3. config/config.php 4. config/api_keys.php "YOUR_N8N_SECRET_KEY", "esp32" => "YOUR_ESP32_SECRET_KEY", "telegram" => "YOUR_TELEGRAM_BOT_TOKEN", "thingspeak" => "YOUR_THINGSPEAK_WRITE_API_KEY" ]; ?> 5. Database SQL File database/smart_retail.sql CREATE DATABASE IF NOT EXISTS smart_retail; USE smart_retail; CREATE TABLE products ( id INT AUTO_INCREMENT PRIMARY KEY, product_id VARCHAR(100) NOT NULL UNIQUE, product_name VARCHAR(200) NOT NULL, rfid_uid VARCHAR(100), category VARCHAR(100), unit_weight FLOAT DEFAULT 0, minimum_stock INT DEFAULT 10, reorder_level INT DEFAULT 10, supplier_name VARCHAR(200), supplier_contact VARCHAR(100), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE inventory ( id INT AUTO_INCREMENT PRIMARY KEY, product_id VARCHAR(100), quantity INT DEFAULT 0, weight FLOAT DEFAULT 0, temperature FLOAT DEFAULT 0, humidity FLOAT DEFAULT 0, daily_consumption FLOAT DEFAULT 0, predicted_consumption FLOAT DEFAULT 0, days_remaining FLOAT DEFAULT 0, stock_status VARCHAR(50), risk_level VARCHAR(50), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (product_id) REFERENCES products(product_id) ); CREATE TABLE inventory_history ( id INT AUTO_INCREMENT PRIMARY KEY, product_id VARCHAR(100), quantity INT, weight FLOAT, temperature FLOAT, humidity FLOAT, recorded_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE alerts ( id INT AUTO_INCREMENT PRIMARY KEY, product_id VARCHAR(100), alert_type VARCHAR(100), message TEXT, severity VARCHAR(50), sent_to_telegram BOOLEAN DEFAULT FALSE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE predictions ( id INT AUTO_INCREMENT PRIMARY KEY, product_id VARCHAR(100), average_daily_consumption FLOAT, predicted_consumption FLOAT, estimated_days_remaining FLOAT, recommended_reorder_quantity INT, risk_level VARCHAR(50), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); 6. includes/header.php <?= SITE_NAME ?> 7. includes/navbar.php 8. includes/footer.php

AI Smart Retail Inventory Monitoring System

ESP32 + AI Agent + n8n + Telegram + Google Sheets + ThingSpeak

9. includes/functions.php 10. Main Dashboard index.php query( "SELECT i.*, p.product_name, p.category FROM inventory i LEFT JOIN products p ON i.product_id = p.product_id ORDER BY i.id DESC" ); $total_products = $conn->query( "SELECT COUNT(*) AS total FROM products" )->fetch_assoc()["total"]; $low_stock = $conn->query( "SELECT COUNT(*) AS total FROM inventory WHERE stock_status = 'LOW_STOCK'" )->fetch_assoc()["total"]; $out_of_stock = $conn->query( "SELECT COUNT(*) AS total FROM inventory WHERE stock_status = 'OUT_OF_STOCK'" )->fetch_assoc()["total"]; ?> AI Smart Retail Dashboard

AI Smart Retail Inventory Dashboard

Total Products

Low Stock Products

Out of Stock

AI Agent

ONLINE

fetch_assoc() ) { ?>
Product ID Product Name Quantity Weight Temperature Humidity Daily Consumption Days Remaining Status Risk
11. ESP32 Data API api/esp32_data.php This PHP file receives data from ESP32. false, "message" => "Invalid JSON data" ]); exit; } $product_id = $data["product_id"] ?? ""; $quantity = intval( $data["quantity"] ?? 0 ); $weight = floatval( $data["weight"] ?? 0 ); $temperature = floatval( $data["temperature"] ?? 0 ); $humidity = floatval( $data["humidity"] ?? 0 ); $product_query = $conn->prepare( "SELECT minimum_stock FROM products WHERE product_id = ?" ); $product_query->bind_param( "s", $product_id ); $product_query->execute(); $product_result = $product_query->get_result(); if ( $product_result->num_rows == 0 ) { echo json_encode([ "success" => false, "message" => "Product not found" ]); exit; } $product = $product_result->fetch_assoc(); $minimum_stock = $product["minimum_stock"]; $status = calculateStockStatus( $quantity, $minimum_stock ); $risk = calculateRiskLevel( $quantity, $minimum_stock ); $insert = $conn->prepare( "INSERT INTO inventory ( product_id, quantity, weight, temperature, humidity, stock_status, risk_level ) VALUES (?, ?, ?, ?, ?, ?, ?)" ); $insert->bind_param( "isddsss", $product_id, $quantity, $weight, $temperature, $humidity, $status, $risk ); $insert->execute(); $history = $conn->prepare( "INSERT INTO inventory_history ( product_id, quantity, weight, temperature, humidity ) VALUES (?, ?, ?, ?, ?)" ); $history->bind_param( "isddd", $product_id, $quantity, $weight, $temperature, $humidity ); $history->execute(); echo json_encode([ "success" => true, "product_id" => $product_id, "quantity" => $quantity, "stock_status" => $status, "risk_level" => $risk ]); ?> 12. Product Registration products.php prepare( "INSERT INTO products ( product_id, product_name, rfid_uid, category, unit_weight, minimum_stock, supplier_name ) VALUES (?, ?, ?, ?, ?, ?, ?)" ); $stmt->bind_param( "ssssdis", $product_id, $product_name, $rfid_uid, $category, $unit_weight, $minimum_stock, $supplier_name ); $stmt->execute(); } ?> Product Management

Add Retail Product








13. AI Inventory Logic ai/inventory_ai.php prepare( "SELECT quantity, daily_consumption FROM inventory WHERE product_id = ? ORDER BY id DESC LIMIT 1" ); $query->bind_param( "s", $product_id ); $query->execute(); $result = $query->get_result(); $data = $result->fetch_assoc(); if (!$data) { echo json_encode([ "success" => false, "message" => "No inventory data" ]); exit; } $quantity = $data["quantity"]; $daily_consumption = $data["daily_consumption"]; $days_remaining = calculateDaysRemaining( $quantity, $daily_consumption ); if ($days_remaining <= 1) { $risk = "CRITICAL"; } elseif ($days_remaining <= 3) { $risk = "HIGH"; } elseif ($days_remaining <= 7) { $risk = "MEDIUM"; } else { $risk = "LOW"; } echo json_encode([ "product_id" => $product_id, "current_stock" => $quantity, "daily_consumption" => $daily_consumption, "estimated_days_remaining" => $days_remaining, "risk_level" => $risk ]); ?> 14. Consumption Prediction ai/consumption_prediction.php prepare( "SELECT quantity, recorded_at FROM inventory_history WHERE product_id = ? ORDER BY recorded_at ASC" ); $query->bind_param( "s", $product_id ); $query->execute(); $result = $query->get_result(); $records = []; while ( $row = $result->fetch_assoc() ) { $records[] = $row; } if ( count($records) < 2 ) { echo json_encode([ "success" => false, "message" => "Insufficient historical data" ]); exit; } $consumption_values = []; for ( $i = 1; $i < count($records); $i++ ) { $previous = $records[$i - 1]["quantity"]; $current = $records[$i]["quantity"]; $consumption = $previous - $current; if ($consumption > 0) { $consumption_values[] = $consumption; } } if ( count($consumption_values) == 0 ) { $average_consumption = 0; } else { $average_consumption = array_sum( $consumption_values ) / count( $consumption_values ); } echo json_encode([ "product_id" => $product_id, "average_daily_consumption" => round( $average_consumption, 2 ) ]); ?> 15. Reorder Prediction ai/reorder_prediction.php $current_stock, "daily_consumption" => $daily_consumption, "lead_time" => $lead_time, "safety_stock" => $safety_stock, "recommended_reorder_quantity" => $reorder_quantity ]); ?> 16. Telegram Alert PHP File api/telegram.php TELEGRAM_CHAT_ID, "text" => $message ]; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt( $ch, CURLOPT_POST, true ); curl_setopt( $ch, CURLOPT_POSTFIELDS, $data ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); $response = curl_exec($ch); curl_close($ch); return $response; } $product = $_POST["product"] ?? ""; $quantity = $_POST["quantity"] ?? ""; $status = $_POST["status"] ?? ""; $message = "🚨 SMART RETAIL INVENTORY ALERT 🚨\n\n" . "Product: " . $product . "\n\n" . "Current Stock: " . $quantity . "\n\n" . "Status: " . $status . "\n\n" . "Please check inventory."; $response = sendTelegramMessage( $message ); echo $response; ?> 17. Telegram Voice Notification api/telegram_voice.php TELEGRAM_CHAT_ID, "voice" => new CURLFile( $audio_file, "audio/mpeg", "inventory_alert.mp3" ) ]; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt( $ch, CURLOPT_POST, true ); curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_fields ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); $response = curl_exec($ch); curl_close($ch); echo $response; ?> 18. ThingSpeak PHP Integration api/thingspeak.php true, "response" => $response ]); ?> 19. Google Sheets Integration Through n8n PHP sends inventory data to n8n: api/google_sheets.php $_POST["product_id"], "quantity" => $_POST["quantity"], "weight" => $_POST["weight"], "temperature" => $_POST["temperature"], "humidity" => $_POST["humidity"], "stock_status" => $_POST["stock_status"] ]; $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, N8N_WEBHOOK_URL ); curl_setopt( $ch, CURLOPT_POST, true ); curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) ); curl_setopt( $ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json" ] ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); $response = curl_exec($ch); curl_close($ch); echo $response; ?> 20. n8n Workflow JSON n8n/inventory_workflow.json { "name": "AI Smart Retail Inventory Automation", "nodes": [ { "parameters": { "httpMethod": "POST", "path": "inventory" }, "name": "ESP32 PHP Webhook", "type": "n8n-nodes-base.webhook", "typeVersion": 2, "position": [ 200, 300 ] }, { "parameters": { "jsCode": "const data = $json;\nconst quantity = Number(data.quantity || 0);\nconst minimumStock = 10;\nlet status = 'NORMAL';\nif (quantity <= 0) {\n status = 'OUT_OF_STOCK';\n} else if (quantity <= minimumStock) {\n status = 'LOW_STOCK';\n}\nreturn [{json: {...data, stock_status: status, alert_required: status !== 'NORMAL'}}];" }, "name": "AI Inventory Analysis", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 450, 300 ] }, { "parameters": { "conditions": { "boolean": [ { "value1": "={{$json.alert_required}}", "value2": true } ] } }, "name": "Low Stock Decision", "type": "n8n-nodes-base.if", "typeVersion": 2, "position": [ 700, 300 ] }, { "parameters": { "chatId": "YOUR_TELEGRAM_CHAT_ID", "text": "🚨 INVENTORY ALERT 🚨\nProduct: {{$json.product_id}}\nQuantity: {{$json.quantity}}\nStatus: {{$json.stock_status}}" }, "name": "Telegram Alert", "type": "n8n-nodes-base.telegram", "typeVersion": 1, "position": [ 950, 200 ] }, { "parameters": { "operation": "append", "documentId": "YOUR_GOOGLE_SHEET_ID", "sheetName": "Inventory" }, "name": "Google Sheets", "type": "n8n-nodes-base.googleSheets", "typeVersion": 4, "position": [ 950, 400 ] } ], "connections": { "ESP32 PHP Webhook": { "main": [ [ { "node": "AI Inventory Analysis", "type": "main", "index": 0 } ] ] }, "AI Inventory Analysis": { "main": [ [ { "node": "Low Stock Decision", "type": "main", "index": 0 } ] ] }, "Low Stock Decision": { "main": [ [ { "node": "Telegram Alert", "type": "main", "index": 0 } ], [ { "node": "Google Sheets", "type": "main", "index": 0 } ] ] } } } 21. PHP Flowchart Page documentation/flowchart.php

Smart Retail Inventory Flowchart

START
ESP32 Initializes
Connect Wi-Fi
Read RFID Product
Read Weight
Read Temperature
Read Humidity
Send JSON Data
PHP API / n8n Webhook
AI Inventory Analysis
Check Stock Level
LOW STOCK?
Telegram Voice Alert
Google Sheets Update
ThingSpeak Update
PHP Dashboard
22. PHP Project Description Page documentation/project_description.php

AI-Based Smart Retail Inventory Monitoring System

Project Description

This project is an AI-powered IoT inventory monitoring system designed to automatically monitor retail products using ESP32, RFID, load cells, environmental sensors, PHP, MySQL, n8n automation, Telegram notifications, Google Sheets and ThingSpeak.

The ESP32 collects product and inventory data and sends it through Wi-Fi to the PHP API or n8n webhook.

The AI Agent analyzes current stock, historical consumption, stock depletion rate and future inventory requirements.

When the inventory reaches a critical level, the system automatically sends Telegram text and voice notifications.

Inventory information is stored in MySQL and Google Sheets and visualized through a PHP dashboard and ThingSpeak cloud platform.

Main Technologies

  • ESP32
  • RFID
  • Load Cell
  • PHP
  • MySQL
  • n8n
  • AI Agent
  • Telegram
  • Google Sheets
  • ThingSpeak
23. PHP Components Page documentation/components.php

Hardware Components

Component Purpose
ESP32 Main IoT controller
RFID RC522 Product identification
Load Cell Stock weight measurement
HX711 Load cell amplifier
DHT22 Temperature and humidity
OLED Display Local data display
Buzzer Local alert
24. CSS File assets/css/style.css body { font-family: Arial; margin: 0; padding: 20px; background: #f4f4f4; } .navbar { background: #222; padding: 20px; margin-bottom: 30px; } .navbar a { color: white; margin-right: 20px; text-decoration: none; } .dashboard-cards { display: flex; gap: 20px; flex-wrap: wrap; } .card { background: white; padding: 25px; min-width: 200px; border-radius: 10px; box-shadow: 0 0 10px rgba( 0, 0, 0, 0.15 ); } table { width: 100%; border-collapse: collapse; margin-top: 30px; background: white; } th, td { padding: 12px; border: 1px solid #ddd; } th { background: #222; color: white; } input, button { padding: 12px; margin: 8px; } button { cursor: pointer; } .flowchart { text-align: center; font-size: 20px; } .flowchart div { background: white; padding: 20px; margin: 10px auto; max-width: 500px; border-radius: 10px; box-shadow: 0 0 8px rgba( 0, 0, 0, 0.2 ); } 25. ESP32 to PHP API Connection In the ESP32 source code, the endpoint becomes: #define PHP_API_URL \ "https://your-domain.com/smart-retail/api/esp32_data.php" The ESP32 sends: { "product_id": "MILK001", "quantity": 5, "weight": 5200, "temperature": 28.5, "humidity": 61.4 } to: api/esp32_data.php PHP then: Receive JSON ↓ Validate Data ↓ Find Product ↓ Calculate Stock Status ↓ Calculate Risk ↓ Save MySQL Data ↓ Save History ↓ Send Response 26. Final PHP-Based System Architecture ┌──────────────────────────────┐ │ ESP32 │ │ │ │ RFID + Load Cell + DHT22 │ └──────────────┬───────────────┘ │ │ HTTP POST JSON ▼ ┌──────────────────────────────┐ │ PHP API SERVER │ │ │ │ esp32_data.php │ └──────────────┬───────────────┘ │ ▼ ┌──────────────────────────────┐ │ MySQL │ │ │ │ Products │ │ Inventory │ │ History │ │ Alerts │ │ Predictions │ └──────────────┬───────────────┘ │ ▼ ┌──────────────────────────────┐ │ PHP AI LOGIC │ │ │ │ Stock Analysis │ │ Consumption Prediction │ │ Reorder Prediction │ └──────────────┬───────────────┘ │ ┌───────┼────────┐ ▼ ▼ ▼ n8n Telegram ThingSpeak │ │ │ ▼ ▼ ▼ AI Voice Cloud Agent Alerts Dashboard │ ▼ Google Sheets 27. Complete Working Sequence 1. Product enters the retail shelf. 2. RFID identifies the product. 3. Load cell measures the product weight. 4. ESP32 reads environmental conditions. 5. ESP32 sends JSON data to PHP. 6. PHP validates the data. 7. PHP stores data in MySQL. 8. AI logic calculates stock status. 9. AI predicts future consumption. 10. AI estimates remaining stock days. 11. AI calculates reorder quantity. 12. n8n receives inventory data. 13. n8n updates Google Sheets. 14. n8n updates ThingSpeak. 15. Telegram text alert is sent. 16. Voice notification is generated. 17. Telegram voice alert is delivered. 18. PHP dashboard displays current status. 19. Store manager takes action. 28. Important Deployment Configuration For local testing: XAMPP Apache MySQL PHP Project location: C:\xampp\htdocs\smart-retail\ Open: http://localhost/smart-retail/ For Internet access: PHP Hosting MySQL Database HTTPS Domain n8n Cloud or VPS Telegram Bot Google Sheets API ThingSpeak Channel Final Result This PHP version gives you the complete software architecture for: ESP32 + RFID + Load Cell + DHT22 + PHP + MySQL + AI Inventory Prediction + n8n Automation + Telegram Text Alerts + Telegram Voice Notifications + Google Sheets + ThingSpeak + PHP IoT Web Dashboard. The only part that should not be written in PHP is the ESP32 firmware, because the ESP32 requires Arduino C++/C code to directly control sensors and hardware.

AI-Based Smart Poultry Farm Monitoring System

Yes. Below is the same complete Smart Poultry Farm project documentation converted into PHP file format. You can save the content below as: poultry_farm_documentation.php Each line is valid PHP output syntax. "; ""; ""; ""; ""; "AI-Based Smart Poultry Farm Monitoring System"; ""; ""; ""; "
"; "

🐔 AI-Based Smart Poultry Farm Monitoring System

"; "

ESP32 + AI Agent + n8n + Telegram + Google Sheets + ThingSpeak + PHP Dashboard

"; "

Agentic IoT Poultry Farm Monitoring and Automation Platform

"; "
"; "
"; "

1. Full Project Description

"; "

"; "The AI-Based Smart Poultry Farm Monitoring System is an advanced IoT and Artificial Intelligence based solution designed to monitor and automate poultry farm environmental conditions."; "

"; "

"; "The system uses an ESP32 microcontroller to collect real-time data from temperature, humidity, gas, light, water-level, feed-level, motion and power sensors."; "

"; "

"; "The ESP32 sends the collected sensor data through Wi-Fi to an n8n automation platform. The n8n workflow analyzes the data, communicates with an AI Agent, stores information in Google Sheets, updates ThingSpeak cloud dashboards and sends Telegram text and voice alerts."; "

"; "

"; "The system can automatically control poultry farm fans, lighting systems, water pumps and other actuators."; "

"; "
"; "
"; "

2. Main Objectives

"; "
    "; "
  • Monitor poultry farm temperature.
  • "; "
  • Monitor poultry farm humidity.
  • "; "
  • Detect harmful gases and ammonia.
  • "; "
  • Monitor lighting conditions.
  • "; "
  • Monitor water tank level.
  • "; "
  • Monitor poultry feed level.
  • "; "
  • Detect poultry movement.
  • "; "
  • Monitor electrical power consumption.
  • "; "
  • Automatically control ventilation fans.
  • "; "
  • Automatically control poultry lighting.
  • "; "
  • Automatically control water pumps.
  • "; "
  • Use AI for farm condition analysis.
  • "; "
  • Predict future power consumption.
  • "; "
  • Send Telegram text notifications.
  • "; "
  • Send Telegram voice notifications.
  • "; "
  • Store data in Google Sheets.
  • "; "
  • Display data using ThingSpeak.
  • "; "
  • Provide a PHP and MySQL web dashboard.
  • "; "
"; "
"; "
"; "

3. System Architecture

"; "
";

  "
                    POULTRY FARM
                         |
                         v
              +----------------------+
              |      IoT SENSORS     |
              |----------------------|
              | Temperature          |
              | Humidity             |
              | Gas / Ammonia        |
              | Light                |
              | Water Level          |
              | Feed Level           |
              | Motion               |
              | Power Consumption    |
              +----------+-----------+
                         |
                         v
              +----------------------+
              |        ESP32         |
              |----------------------|
              | Sensor Collection    |
              | Local Automation     |
              | Relay Control        |
              | Wi-Fi Communication  |
              +----------+-----------+
                         |
                         v
                    INTERNET
                         |
                         v
              +----------------------+
              |        n8n            |
              |----------------------|
              | Webhook              |
              | Data Processing      |
              | AI Agent             |
              | Alert Automation     |
              | Google Sheets        |
              | Telegram             |
              | ThingSpeak           |
              +----------+-----------+
                         |
          +--------------+---------------+
          |                              |
          v                              v
   +--------------+               +-------------+
   | AI AGENT     |               | TELEGRAM    |
   | Farm Analysis|               | Text Alert  |
   | Prediction   |               | Voice Alert |
   +--------------+               +-------------+
          |
          v
   +----------------------+
   | Cloud Dashboard      |
   | Google Sheets        |
   | ThingSpeak           |
   | PHP / MySQL Website  |
   +----------------------+
";

  "
"; "
"; "
"; "

4. Components List

"; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; "
ComponentPurpose
ESP32 DevKitMain IoT controller
DHT22Temperature and humidity monitoring
MQ-135 / MQ-137Gas and ammonia detection
LDRLight intensity measurement
HC-SR04 / JSN-SR04TWater and feed level measurement
PIR SensorMotion detection
PZEM-004T / ACS712Power consumption monitoring
Relay ModuleFan, light and pump control
BuzzerLocal emergency warning
Wi-Fi RouterInternet connectivity
"; "
"; "
"; "

5. Circuit Schematic Diagram

"; "
";

  "
                         +-------------------+
                         |       ESP32       |
                         |                   |
       DHT22 DATA ------| GPIO 4            |
                         |                   |
       MQ-135 AO -------| GPIO 34           |
                         |                   |
       LDR AO ----------| GPIO 35           |
                         |                   |
       Water TRIG ------| GPIO 5            |
       Water   ------| GPIO 18           |
                         |                   |
       Feed TRIG -------| GPIO 19           |
       Feed   -------| GPIO 21           |
                         |                   |
       PIR OUT ---------| GPIO 27           |
                         |                   |
       Fan Relay <------| GPIO 25           |
       Light Relay <----| GPIO 26           |
       Pump Relay <-----| GPIO 33           |
                         |                   |
       Buzzer <----------| GPIO 14           |
                         +---------+---------+
                                   |
                                   | Wi-Fi
                                   v
                             +-----------+
                             | INTERNET  |
                             +-----+-----+
                                   |
                                   v
                             +-----------+
                             |    n8n    |
                             +-----+-----+
                                   |
                   +---------------+---------------+
                   |                               |
                   v                               v
             +-----------+                   +-----------+
             | AI AGENT  |                   | TELEGRAM  |
             +-----------+                   +-----------+
";

  "
"; "
"; "Safety Note: AC mains powered fans, pumps and lights must use proper electrical isolation, fuses, enclosures and qualified electrical installation procedures."; "
"; "
"; "
"; "

6. ESP32 Pin Configuration

"; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; "
DeviceESP32 Pin
DHT22 DataGPIO 4
Gas Sensor AnalogGPIO 34
LDRGPIO 35
Water Ultrasonic TriggerGPIO 5
Water Ultrasonic GPIO 18
Feed Ultrasonic TriggerGPIO 19
Feed Ultrasonic GPIO 21
PIR SensorGPIO 27
Fan RelayGPIO 25
Light RelayGPIO 26
Pump RelayGPIO 33
BuzzerGPIO 14
"; "
"; "
"; "

7. Complete ESP32 Source Code

"; "
";

  htmlspecialchars('
#include 
#include 
#include 
#include "DHT.h"

#define DHTPIN 4
#define DHTTYPE DHT22

#define GAS_PIN 34
#define LDR_PIN 35

#define WATER_TRIG 5
#define WATER_  18

#define FEED_TRIG 19
#define FEED_  21

#define PIR_PIN 27

#define FAN_RELAY 25
#define LIGHT_RELAY 26
#define PUMP_RELAY 33

#define BUZZER_PIN 14

const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";

const char* N8N_WEBHOOK =
"https://YOUR_N8N_DOMAIN/webhook/poultry-data";

DHT dht(DHTPIN, DHTTYPE);

float temperature;
float humidity;

int gasValue;
int lightValue;

long waterDistance;
long feedDistance;

int motionStatus;

bool fanStatus = false;
bool lightStatus = false;
bool pumpStatus = false;

long readUltrasonic(int trigPin, int  Pin)
{
    digitalWrite(trigPin, LOW);

    delayMicroseconds(2);

    digitalWrite(trigPin, HIGH);

    delayMicroseconds(10);

    digitalWrite(trigPin, LOW);

    long duration =
    pulseIn( Pin, HIGH, 30000);

    long distance =
    duration * 0.034 / 2;

    return distance;
}

void connectWiFi()
{
    Serial.print("Connecting to WiFi");

    WiFi.begin(
        WIFI_SSID,
        WIFI_PASSWORD
    );

    while (
        WiFi.status()
        != WL_CONNECTED
    )
    {
        delay(500);

        Serial.print(".");
    }

    Serial.println();

    Serial.println(
        "WiFi Connected"
    );

    Serial.println(
        WiFi.localIP()
    );
}

void readSensors()
{
    temperature =
    dht.readTemperature();

    humidity =
    dht.readHumidity();

    gasValue =
    analogRead(GAS_PIN);

    lightValue =
    analogRead(LDR_PIN);

    waterDistance =
    readUltrasonic(
        WATER_TRIG,
        WATER_ 
    );

    feedDistance =
    readUltrasonic(
        FEED_TRIG,
        FEED_ 
    );

    motionStatus =
    digitalRead(PIR_PIN);
}

void localControl()
{
    if (
        temperature > 30
        ||
        gasValue > 1800
    )
    {
        digitalWrite(
            FAN_RELAY,
            LOW
        );

        fanStatus =
        true;
    }
    else
    {
        digitalWrite(
            FAN_RELAY,
            HIGH
        );

        fanStatus =
        false;
    }

    if (
        lightValue < 1000
    )
    {
        digitalWrite(
            LIGHT_RELAY,
            LOW
        );

        lightStatus =
        true;
    }
    else
    {
        digitalWrite(
            LIGHT_RELAY,
            HIGH
        );

        lightStatus =
        false;
    }

    if (
        waterDistance > 30
    )
    {
        digitalWrite(
            PUMP_RELAY,
            LOW
        );

        pumpStatus =
        true;
    }
    else
    {
        digitalWrite(
            PUMP_RELAY,
            HIGH
        );

        pumpStatus =
        false;
    }

    if (
        gasValue > 2500
    )
    {
        digitalWrite(
            BUZZER_PIN,
            HIGH
        );
    }
    else
    {
        digitalWrite(
            BUZZER_PIN,
            LOW
        );
    }
}

void sendDataToN8N()
{
    if (
        WiFi.status()
        != WL_CONNECTED
    )
    {
        connectWiFi();
    }

    HTTPClient http;

    http.begin(
        N8N_WEBHOOK
    );

    http.addHeader(
        "Content-Type",
        "application/json"
    );

    StaticJsonDocument<1024>
    doc;

    doc["device_id"] =
    "POULTRY_ESP32_001";

    doc["temperature"] =
    temperature;

    doc["humidity"] =
    humidity;

    doc["gas_value"] =
    gasValue;

    doc["light_value"] =
    lightValue;

    doc["water_distance"] =
    waterDistance;

    doc["feed_distance"] =
    feedDistance;

    doc["motion"] =
    motionStatus;

    doc["fan"] =
    fanStatus;

    doc["light"] =
    lightStatus;

    doc["pump"] =
    pumpStatus;

    doc["timestamp"] =
    millis();

    String jsonData;

    serializeJson(
        doc,
        jsonData
    );

    int responseCode =
    http.POST(
        jsonData
    );

    Serial.print(
        "n8n Response: "
    );

    Serial.println(
        responseCode
    );

    http.end();
}

void setup()
{
    Serial.begin(
        115200
    );

    pinMode(
        WATER_TRIG,
        OUTPUT
    );

    pinMode(
        WATER_ ,
        INPUT
    );

    pinMode(
        FEED_TRIG,
        OUTPUT
    );

    pinMode(
        FEED_ ,
        INPUT
    );

    pinMode(
        PIR_PIN,
        INPUT
    );

    pinMode(
        FAN_RELAY,
        OUTPUT
    );

    pinMode(
        LIGHT_RELAY,
        OUTPUT
    );

    pinMode(
        PUMP_RELAY,
        OUTPUT
    );

    pinMode(
        BUZZER_PIN,
        OUTPUT
    );

    digitalWrite(
        FAN_RELAY,
        HIGH
    );

    digitalWrite(
        LIGHT_RELAY,
        HIGH
    );

    digitalWrite(
        PUMP_RELAY,
        HIGH
    );

    dht.begin();

    connectWiFi();
}

void loop()
{
    readSensors();

    localControl();

    sendDataToN8N();

    delay(
        60000
    );
}
', ENT_QUOTES);

  "
"; "
"; "
"; "

8. ESP32 JSON Data Format

"; "
";

  htmlspecialchars('{
    "device_id": "POULTRY_ESP32_001",
    "temperature": 32.5,
    "humidity": 75.4,
    "gas_value": 2100,
    "light_value": 850,
    "water_distance": 42,
    "feed_distance": 15,
    "motion": 1,
    "fan": true,
    "light": true,
    "pump": true,
    "timestamp": 123456
}', ENT_QUOTES);

  "
"; "
"; "
"; "

9. Complete System Flowchart

"; "
";

  "
START
  |
  v
ESP32 POWER ON
  |
  v
CONNECT TO Wi-Fi
  |
  +---- FAILED ----> RETRY
  |
  v
READ ALL SENSORS
  |
  +---- Temperature
  +---- Humidity
  +---- Gas
  +---- Light
  +---- Water
  +---- Feed
  +---- Motion
  +---- Power
  |
  v
LOCAL CONTROL
  |
  +---- Temperature HIGH --> FAN ON
  |
  +---- Gas HIGH ---------> FAN ON
  |
  +---- Water LOW --------> PUMP ON
  |
  +---- Light LOW --------> LIGHT ON
  |
  v
SEND JSON TO n8n
  |
  v
n8n WEBHOOK
  |
  v
AI AGENT ANALYSIS
  |
  +---- NORMAL
  |
  +---- WARNING
  |
  +---- CRITICAL
  |
  v
SAVE DATA
  |
  +---- Google Sheets
  +---- ThingSpeak
  +---- MySQL
  |
  v
SEND ALERT
  |
  +---- Telegram Text
  |
  +---- Telegram Voice
  |
  v
REPEAT
";

  "
"; "
"; "
"; "

10. n8n Automation Workflow

"; "
";

  "
ESP32
  |
  v
WEBHOOK
  |
  v
DATA VALIDATION
  |
  v
AI AGENT
  |
  v
RISK ANALYSIS
  |
  +---- NORMAL ------> Google Sheets
  |
  +---- WARNING -----> Telegram Message
  |
  +---- CRITICAL ----> Telegram Text
                         |
                         v
                    Voice Alert
                         |
                         v
                    Google Sheets
                         |
                         v
                    ThingSpeak
";

  "
"; "
"; "
"; "

11. n8n Workflow JSON

"; "
";

  htmlspecialchars('{
  "name": "AI Poultry Farm Monitoring",

  "nodes": [

    {
      "parameters": {
        "httpMethod": "POST",
        "path": "poultry-data",
        "responseMode": "onReceived"
      },

      "name": "ESP32 Webhook",

      "type": "n8n-nodes-base.webhook",

      "typeVersion": 2
    },

    {
      "parameters": {

        "jsCode":

        "const data = $json.body || $json;\\n\\nlet risk = \\'NORMAL\\';\\nlet message = \\'Poultry farm conditions are normal.\\';\\n\\nif (data.temperature > 35) {\\n risk = \\'CRITICAL\\';\\n message = \\'Critical temperature detected.\\';\\n}\\n\\nif (data.gas_value > 2500) {\\n risk = \\'CRITICAL\\';\\n message = \\'Critical harmful gas level detected.\\';\\n}\\n\\nif (data.water_distance > 40) {\\n risk = \\'WARNING\\';\\n message = \\'Water level is low.\\';\\n}\\n\\nreturn [{ json: { ...data, risk_level: risk, ai_message: message } }];"

      },

      "name": "Farm Risk Analysis",

      "type": "n8n-nodes-base.code"

    },

    {

      "parameters": {

        "chatId": "YOUR_TELEGRAM_CHAT_ID",

        "text": "POULTRY FARM ALERT"

      },

      "name": "Telegram Alert",

      "type": "n8n-nodes-base.telegram"

    }

  ]

}', ENT_QUOTES);

  "
"; "
"; "
"; "

12. Telegram Bot Setup

"; "
    "; "
  1. Open Telegram.
  2. "; "
  3. Search for BotFather.
  4. "; "
  5. Send /newbot.
  6. "; "
  7. Enter the poultry farm bot name.
  8. "; "
  9. Copy the generated BOT TOKEN.
  10. "; "
  11. Create Telegram credentials in n8n.
  12. "; "
  13. Send a message to your bot.
  14. "; "
  15. Find your Telegram Chat ID.
  16. "; "
  17. Configure the Telegram node.
  18. "; "
"; "

Example Telegram Alert

"; "
";

  "🚨 POULTRY FARM CRITICAL ALERT 🚨

Temperature: 38 °C

Humidity: 82 %

Gas Level: HIGH

Fan: ACTIVATED

Please inspect the poultry farm immediately.";

  "
"; "
"; "
"; "

13. Telegram Voice Notification Workflow

"; "
";

  "
CRITICAL SENSOR DATA
        |
        v
      n8n
        |
        v
    AI AGENT
        |
        v
GENERATE ALERT TEXT
        |
        v
TEXT-TO-SPEECH
        |
        v
AUDIO FILE
        |
        v
TELEGRAM VOICE MESSAGE
        |
        v
FARMER MOBILE PHONE
";

  "
"; "
"; "
"; "

14. Google Sheets Integration

"; "

Create a Google Sheet with the following columns:

"; "
";

  "
Timestamp
Device ID
Temperature
Humidity
Gas Level
Light Level
Water Level
Feed Level
Motion
Fan Status
Light Status
Pump Status
Power Consumption
Risk Level
AI Recommendation
";

  "
"; "
"; "
"; "

15. ThingSpeak Dashboard Configuration

"; ""; ""; ""; ""; ""; ""; ""; ""; ""; ""; "
FieldData
Field 1Temperature
Field 2Humidity
Field 3Gas Level
Field 4Light Intensity
Field 5Water Level
Field 6Feed Level
Field 7Motion
Field 8Power Consumption
"; "
"; "
"; "

16. AI Farm Risk Classification

"; "
";

  "
IF temperature > 35
    RISK = CRITICAL

IF gas > 2500
    RISK = CRITICAL

IF humidity > 85
    RISK = WARNING

IF water_level < 25
    RISK = WARNING

IF feed_level < 20
    RISK = WARNING

IF motion = 0 FOR LONG TIME
    RISK = WARNING
";

  "
"; ""; ""; ""; ""; ""; ""; "
Risk ScoreCondition
0 - 2NORMAL
3 - 5WARNING
6 - 8HIGH
9+CRITICAL
"; "
"; "
"; "

17. AI Power Consumption Prediction

"; "

"; "The system records power consumption together with temperature, fan runtime, pump runtime and lighting operation."; "

"; "
";

  "
Temperature Increases
        |
        v
Fan Runtime Increases
        |
        v
Power Consumption Increases
        |
        v
AI Predicts Future Power Usage
";

  "
"; "

Example Prediction

"; "

"; "Current temperature is 34 degrees Celsius."; "

"; "

"; "Fan runtime is 70 percent."; "

"; "

"; "Current power consumption is 550 watts."; "

"; "

"; "AI Prediction: Expected power consumption may increase to approximately 650 watts if temperature continues to rise."; "

"; "
"; "
"; "

18. PHP Web Dashboard

"; "
";

  "
+--------------------------------------+
|       AI POULTRY FARM DASHBOARD      |
+--------------------------------------+
| Temperature       32.5 °C            |
| Humidity          72 %               |
| Gas Level         NORMAL             |
| Water Level       65 %               |
| Feed Level        80 %               |
| Power             480 W              |
+--------------------------------------+
| FAN               ON                 |
| LIGHT             OFF                |
| WATER PUMP        ON                 |
+--------------------------------------+
| AI STATUS: WARNING                    |
+--------------------------------------+
";

  "
"; "
"; "
"; "

19. PHP Project Folder Structure

"; "
";

  "
poultry-farm/
|
|-- index.php
|
|-- dashboard.php
|
|-- config.php
|
|-- database.php
|
|-- api/
|   |-- sensor_data.php
|   |-- latest_data.php
|   |-- device_control.php
|
|-- ai/
|   |-- ai_analysis.php
|   |-- power_prediction.php
|
|-- assets/
|   |-- css/
|   |-- js/
|
|-- database/
|   |-- poultry.sql
|
|-- n8n/
|   |-- workflow.json
|
|-- documentation/
|   |-- poultry_farm_documentation.php
";

  "
"; "
"; "
"; "

20. MySQL Database

"; "
";

  htmlspecialchars("
CREATE DATABASE poultry_farm;

USE poultry_farm;

CREATE TABLE sensor_data (

    id INT AUTO_INCREMENT PRIMARY KEY,

    device_id VARCHAR(100),

    temperature FLOAT,

    humidity FLOAT,

    gas_value INT,

    light_value INT,

    water_distance FLOAT,

    feed_distance FLOAT,

    motion INT,

    fan_status BOOLEAN,

    light_status BOOLEAN,

    pump_status BOOLEAN,

    power_consumption FLOAT,

    risk_level VARCHAR(50),

    ai_message TEXT,

    created_at TIMESTAMP
    DEFAULT CURRENT_TIMESTAMP

);
", ENT_QUOTES);

  "
"; "
"; "
"; "

21. PHP Sensor Data API

"; "
";

  htmlspecialchars("
 35
    ||
    $gas > 2500
)
{
    $risk =
    'CRITICAL';
}
elseif (
    $temperature > 30
    ||
    $humidity > 80
)
{
    $risk =
    'WARNING';
}
else
{
    $risk =
    'NORMAL';
}

  json_encode(

    [

        'success' => true,

        'risk_level' =>
        $risk,

        'temperature' =>
        $temperature,

        'humidity' =>
        $humidity,

        'gas' =>
        $gas

    ]

);

?>
", ENT_QUOTES);

  "
"; "
"; "
"; "

22. Complete System Operation

"; "
";

  "
1. ESP32 starts.
        |
        v
2. ESP32 connects to Wi-Fi.
        |
        v
3. Sensors collect farm data.
        |
        v
4. ESP32 performs local control.
        |
        v
5. Sensor data becomes JSON.
        |
        v
6. JSON is sent to n8n.
        |
        v
7. n8n receives webhook data.
        |
        v
8. AI Agent analyzes farm conditions.
        |
        v
9. Risk level is calculated.
        |
        v
10. Data is saved to Google Sheets.
        |
        v
11. Data is sent to ThingSpeak.
        |
        v
12. PHP dashboard is updated.
        |
        v
13. Telegram alert is generated.
        |
        v
14. Critical condition generates voice alert.
        |
        v
15. System continues monitoring.
";

  "
"; "
"; "
"; "

23. Testing Procedure

"; "

Temperature Test

"; "

Increase the temperature reading and verify that the fan automatically turns ON.

"; "

Gas Test

"; "

Test the gas sensor using a safe test method and verify that the fan, buzzer and Telegram alert operate correctly.

"; "

Water Test

"; "

Reduce the water level and verify that the water pump activates.

"; "

Internet Failure Test

"; "

Disconnect Wi-Fi and verify that local ESP32 automation continues operating.

"; "
"; "
"; "

24. Future Enhancements

"; "
    "; "
  • AI-based poultry disease detection.
  • "; "
  • ESP32-CAM bird behavior monitoring.
  • "; "
  • Computer vision-based bird counting.
  • "; "
  • Automatic feed dispensing.
  • "; "
  • Solar-powered poultry farm system.
  • "; "
  • Predictive maintenance for fans and pumps.
  • "; "
  • Mobile Android application.
  • "; "
  • Advanced machine learning power prediction.
  • "; "
  • Cloud-based multi-farm management.
  • "; "
  • AI-based mortality detection.
  • "; "
"; "
"; "
"; "

25. Final Project Summary

"; "
"; "

"; "The AI-Based Smart Poultry Farm Monitoring System combines ESP32 IoT hardware, environmental sensors, AI analysis, n8n workflow automation, Telegram notifications, voice alerts, Google Sheets, ThingSpeak cloud monitoring and a PHP/MySQL web dashboard."; "

"; "

"; "The ESP32 performs real-time monitoring and local automation. n8n acts as the central automation engine. The AI Agent analyzes farm conditions and generates intelligent recommendations. Google Sheets stores historical information. ThingSpeak provides cloud visualization. Telegram sends text and voice alerts. The PHP and MySQL dashboard provides centralized monitoring."; "

"; "
"; "
";

  "
SENSORS
   |
   v
ESP32
   |
   v
Wi-Fi
   |
   v
n8n
   |
   v
AI AGENT
   |
   v
DECISION
   |
   +---- FAN
   |
   +---- LIGHT
   |
   +---- PUMP
   |
   +---- BUZZER
   |
   +---- TELEGRAM
   |
   +---- VOICE ALERT
   |
   +---- GOOGLE SHEETS
   |
   +---- THINGSPEAK
   |
   +---- PHP DASHBOARD
";

  "
"; "
"; "
"; "

"; "AI-Based Smart Poultry Farm Monitoring System | ESP32 + AI + n8n + Telegram + Google Sheets + ThingSpeak"; "

"; "
"; ""; ""; ?> Recommended project files For the actual working project, use separate PHP files rather than putting the entire documentation into one file: poultry-farm/ │ ├── index.php ├── dashboard.php ├── config.php ├── database.php ├── sensor_api.php ├── ai_analysis.php ├── power_prediction.php ├── telegram_alert.php ├── thingspeak.php ├── google_sheets.php │ ├── api/ │ ├── receive_sensor_data.php │ ├── get_latest_data.php │ └── control_device.php │ ├── database/ │ └── poultry.sql │ ├── n8n/ │ └── workflow.json │ └── documentation/ └── poultry_farm_documentation.php Important: The PHP file above is a documentation webpage. The ESP32 code remains Arduino/C++ code, while n8n uses JSON. A PHP application cannot directly execute ESP32 Arduino code or n8n workflow JSON; PHP acts as the web/API/dashboard layer.

AI-Based Smart Medicine Reminder and Health Monitoring System

Yes. Below is a PHP-file-based project structure for the complete AI-Based Smart Medicine Reminder and Health Monitoring System. Because the complete system is large, it is best organized into multiple PHP files rather than putting everything into one extremely large file. 1. Complete PHP Project Folder Structure smart_medicine_system/ │ ├── config/ │ ├── database.php │ ├── config.php │ └── security.php │ ├── api/ │ ├── esp32_data.php │ ├── medicine_reminder.php │ ├── medicine_confirm.php │ ├── health_data.php │ ├── power_data.php │ ├── ai_analysis.php │ └── telegram_alert.php │ ├── admin/ │ ├── login.php │ ├── dashboard.php │ ├── add_medicine.php │ ├── edit_medicine.php │ ├── delete_medicine.php │ └── logout.php │ ├── dashboard/ │ ├── index.php │ ├── health_chart.php │ ├── medicine_status.php │ ├── power_prediction.php │ └── alerts.php │ ├── includes/ │ ├── header.php │ ├── footer.php │ ├── navbar.php │ └── auth.php │ ├── n8n/ │ └── workflow.json │ ├── database/ │ └── smart_medicine.sql │ ├── index.php ├── README.php └── style.css 2. Database SQL File database/smart_medicine.sql 3. Database Connection config/database.php connect_error) { die( "Database Connection Failed: " . $conn->connect_error ); } $conn->set_charset("utf8mb4"); ?> 4. Main Configuration File config/config.php 5. Security File config/security.php 6. Main Home Page index.php AI Smart Medicine System

AI-Based Smart Medicine Reminder and Health Monitoring System

ESP32 + IoT + AI Agent + n8n + Telegram + Google Sheets + ThingSpeak

Admin Login

Open IoT Dashboard
7. Admin Login admin/login.php prepare($sql); $stmt->bind_param( "s", $username ); $stmt->execute(); $result = $stmt->get_result(); if ( $result->num_rows > 0 ) { $user = $result->fetch_assoc(); if ( password_verify( $password, $user["password"] ) ) { $_SESSION[ "admin_logged_in" ] = true; $_SESSION["username"] = $user["username"]; header( "Location: dashboard.php" ); exit; } } $message = "Invalid username or password"; } ?> Admin Login

Admin Login





8. Admin Dashboard admin/dashboard.php Admin Dashboard

AI Smart Medicine Admin Dashboard

Add Medicine

Health Monitoring Dashboard

Logout 9. Add Medicine admin/add_medicine.php prepare($sql); $stmt->bind_param( "sss", $medicine_name, $dosage, $reminder_time ); if ($stmt->execute()) { $message = "Medicine added successfully"; } } ?> Add Medicine

Add Medicine Schedule










10. ESP32 API Endpoint api/esp32_data.php This file receives data from ESP32. "error", "message" => "Invalid JSON data" ] ); exit; } $device_id = $data["device_id"] ?? ""; $temperature = $data["temperature"] ?? 0; $heart_rate = $data["heart_rate"] ?? 0; $spo2 = $data["spo2"] ?? 0; $humidity = $data["humidity"] ?? 0; $battery_voltage = $data["battery_voltage"] ?? 0; $power_consumption = $data["power_consumption"] ?? 0; $sql = "INSERT INTO health_data ( device_id, temperature, heart_rate, spo2, humidity, battery_voltage, power_consumption ) VALUES (?, ?, ?, ?, ?, ?, ?)"; $stmt = $conn->prepare($sql); $stmt->bind_param( "sdddddd", $device_id, $temperature, $heart_rate, $spo2, $humidity, $battery_voltage, $power_consumption ); if ($stmt->execute()) { echo json_encode( [ "status" => "success", "message" => "Health data saved" ] ); } else { echo json_encode( [ "status" => "error", "message" => "Database error" ] ); } ?> 11. Medicine Reminder API api/medicine_reminder.php prepare($sql); $stmt->bind_param( "ss", $current_time, $current_time ); $stmt->execute(); $result = $stmt->get_result(); $medicines = []; while ( $row = $result->fetch_assoc() ) { $medicines[] = $row; } echo json_encode( [ "status" => "success", "current_time" => $current_time, "medicines" => $medicines ] ); ?> 12. Medicine Confirmation API api/medicine_confirm.php prepare($sql); $stmt->bind_param( "iss", $medicine_id, $medicine_name, $status ); if ($stmt->execute()) { echo json_encode( [ "status" => "success", "message" => "Medicine confirmation saved" ] ); } ?> 13. Health Data API api/health_data.php query($sql); $data = $result->fetch_assoc(); echo json_encode( [ "status" => "success", "data" => $data ] ); ?> 14. PHP Health Dashboard dashboard/index.php query($sql); $data = $result->fetch_assoc(); ?> Smart Health Dashboard

AI Smart Medicine Health Dashboard


Latest Health Data

Temperature: °C

Heart Rate: BPM

SpO2: %

Humidity: %

Battery Voltage: V

Power Consumption: W

Last Updated:

15. AI Analysis PHP File api/ai_analysis.php query($sql); $data = $result->fetch_assoc(); $temperature = $data["temperature"]; $heart_rate = $data["heart_rate"]; $spo2 = $data["spo2"]; $status = "NORMAL"; $message = "Health parameters are within normal monitoring limits."; if ( $temperature > 38 ) { $status = "WARNING"; $message = "High temperature detected."; } if ( $spo2 > 0 && $spo2 < 94 ) { $status = "WARNING"; $message = "Low oxygen saturation detected."; } if ( $heart_rate > 120 || ( $heart_rate > 0 && $heart_rate < 50 ) ) { $status = "WARNING"; $message = "Abnormal heart rate detected."; } echo json_encode( [ "status" => $status, "message" => $message, "temperature" => $temperature, "heart_rate" => $heart_rate, "spo2" => $spo2 ] ); ?> These thresholds are only example monitoring rules and should not be treated as medical diagnosis. 16. Telegram Alert PHP File api/telegram_alert.php TELEGRAM_CHAT_ID, "text" => $message ]; $ch = curl_init($url); curl_setopt( $ch, CURLOPT_POST, true ); curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_data ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); $response = curl_exec($ch); curl_close($ch); echo $response; ?> 17. Power Consumption PHP File api/power_data.php prepare($sql); $stmt->bind_param( "dddd", $voltage, $current_amp, $power_watt, $battery_percentage ); $stmt->execute(); echo json_encode( [ "status" => "success", "voltage" => $voltage, "current" => $current_amp, "power" => $power_watt, "battery" => $battery_percentage ] ); ?> 18. Power Prediction PHP File dashboard/power_prediction.php = DATE_SUB( NOW(), INTERVAL 24 HOUR )"; $result = $conn->query($sql); $row = $result->fetch_assoc(); $average_power = $row["average_power"]; if ( $average_power > 2 ) { $prediction = "HIGH POWER CONSUMPTION"; } else if ( $average_power > 1 ) { $prediction = "MEDIUM POWER CONSUMPTION"; } else { $prediction = "LOW POWER CONSUMPTION"; } ?> Power Prediction

AI Power Consumption Prediction

Average Power: Watts

Prediction:

19. Alerts Dashboard dashboard/alerts.php query($sql); ?> Health Alerts

System Alerts

fetch_assoc() ) { ?>
Type Message Level Date
20. PHP-to-n8n Webhook Integration api/send_to_n8n.php $_POST["device_id"] ?? "MEDESP32_001", "temperature" => $_POST["temperature"] ?? 0, "heart_rate" => $_POST["heart_rate"] ?? 0, "spo2" => $_POST["spo2"] ?? 0, "medicine_status" => $_POST["medicine_status"] ?? "PENDING" ]; $ch = curl_init( N8N_WEBHOOK_URL ); curl_setopt( $ch, CURLOPT_POST, true ); curl_setopt( $ch, CURLOPT_HTTPHEADER, [ "Content-Type: application/json" ] ); curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode($data) ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); $response = curl_exec($ch); curl_close($ch); echo $response; ?> 21. Google Sheets Integration Through n8n The PHP system sends JSON to n8n: "MEDESP32_001", "temperature" => 36.8, "heart_rate" => 78, "spo2" => 97, "medicine_status" => "TAKEN" ]; ?> The n8n flow is: PHP / ESP32 | v Webhook | v Data Processing | v AI Analysis | v Google Sheets 22. n8n Workflow JSON File n8n/workflow.json { "name": "Smart Medicine AI Automation", "nodes": [ { "parameters": { "httpMethod": "POST", "path": "medicine-data", "responseMode": "onReceived" }, "name": "ESP32 Webhook", "type": "n8n-nodes-base.webhook", "typeVersion": 2, "position": [ 200, 300 ] }, { "parameters": { "jsCode": "const data = $json.body || $json;\n\nlet status = 'NORMAL';\nlet message = 'Health readings are normal.';\n\nif (data.temperature > 38) {\n status = 'WARNING';\n message = 'High temperature detected.';\n}\n\nif (data.spo2 && data.spo2 < 94) {\n status = 'WARNING';\n message = 'Low SpO2 detected.';\n}\n\nif (data.heart_rate && (data.heart_rate < 50 || data.heart_rate > 120)) {\n status = 'WARNING';\n message = 'Abnormal heart rate detected.';\n}\n\nreturn [{json: {...data, status, message}}];" }, "name": "AI Health Analysis", "type": "n8n-nodes-base.code", "typeVersion": 2, "position": [ 450, 300 ] }, { "parameters": { "conditions": { "string": [ { "value1": "={{$json.status}}", "operation": "equal", "value2": "WARNING" } ] } }, "name": "Alert Decision", "type": "n8n-nodes-base.if", "typeVersion": 2, "position": [ 700, 300 ] }, { "parameters": { "chatId": "YOUR_CHAT_ID", "text": "🚨 SMART MEDICINE ALERT\n\n{{$json.message}}" }, "name": "Telegram Alert", "type": "n8n-nodes-base.telegram", "typeVersion": 1, "position": [ 950, 200 ] }, { "parameters": {}, "name": "Google Sheets", "type": "n8n-nodes-base.googleSheets", "typeVersion": 4, "position": [ 950, 400 ] } ], "connections": { "ESP32 Webhook": { "main": [ [ { "node": "AI Health Analysis", "type": "main", "index": 0 } ] ] }, "AI Health Analysis": { "main": [ [ { "node": "Alert Decision", "type": "main", "index": 0 } ] ] }, "Alert Decision": { "main": [ [ { "node": "Telegram Alert", "type": "main", "index": 0 } ], [ { "node": "Google Sheets", "type": "main", "index": 0 } ] ] } } } 23. PHP Flowchart Representation README.php 24. Important Architecture ┌──────────────────────────┐ │ ESP32 │ │ │ │ RTC + Sensors + Buzzer │ │ Servo + OLED + Wi-Fi │ └────────────┬─────────────┘ │ ▼ ┌──────────────────────────┐ │ PHP API │ │ esp32_data.php │ └────────────┬─────────────┘ │ ▼ ┌──────────────────────────┐ │ MySQL Database │ └────────────┬─────────────┘ │ ▼ ┌──────────────────────────┐ │ PHP Dashboard │ └──────────────────────────┘ │ ▼ ┌──────────────────────────┐ │ n8n │ │ AI Automation │ └────────────┬─────────────┘ │ ┌─────┼──────┐ ▼ ▼ ▼ Telegram Google ThingSpeak Alert Sheets Cloud 25. Final Deployment Steps 1. Install XAMPP 2. Start Apache 3. Start MySQL 4. Create smart_medicine database 5. Import smart_medicine.sql 6. Copy project folder to: C:/xampp/htdocs/ 7. Configure database.php 8. Configure config.php 9. Configure Telegram Bot Token 10. Configure n8n Webhook URL 11. Configure ThingSpeak API Key 12. Upload ESP32 Code 13. Connect Sensors 14. Test Medicine Reminder 15. Test Health Monitoring 16. Test Telegram Alert 17. Test Google Sheets 18. Test ThingSpeak 19. Open PHP Dashboard Final Project Execution ESP32 ↓ Medicine Reminder ↓ Health Sensors ↓ Wi-Fi ↓ PHP API ↓ MySQL Database ↓ n8n Automation ↓ AI Agent ↓ Telegram Text Alert ↓ Telegram Voice Alert ↓ Google Sheets ↓ ThingSpeak Cloud ↓ PHP Web Dashboard This gives you the complete PHP-based web application structure, database design, REST APIs, dashboard, AI analysis logic, n8n integration, Telegram alert system, power-monitoring module, and cloud-monitoring architecture for the project.