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.

AI-Based Smart Library Management and Book Recommendation System

<?php echo $title; ?>

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

1. Full Project Description

The AI-Based Smart Library Management and Book Recommendation System is an advanced IoT and Artificial Intelligence project designed to automate library operations.

The system uses ESP32 as the main IoT controller. RFID technology is used to identify library users and books. When a student scans an RFID card and a book RFID tag, the ESP32 reads the unique identification numbers and sends the data to a PHP-based web server using Wi-Fi.

The PHP backend processes the received data and communicates with a MySQL database. The database stores user details, book information, issue transactions, return transactions, recommendation history, and power consumption information.

The Artificial Intelligence recommendation module analyzes a user's previous borrowing history, preferred categories, authors, and reading behavior. Based on this information, the system generates personalized book recommendations.

The n8n automation platform works as an automation engine and AI agent layer. It receives events from the PHP server, analyzes them, updates Google Sheets, sends data to ThingSpeak, and sends real-time Telegram notifications.

The system can also generate Telegram voice notifications for important events such as book issue, book return, unknown RFID detection, overdue book alerts, and abnormal power consumption.

Main Objective: To create an intelligent, automated, cloud-connected library management system that reduces manual work and provides personalized book recommendations.

2. Project Objectives

  • Automate library book issue operations.
  • Automate library book return operations.
  • Identify students using RFID cards.
  • Identify books using RFID tags.
  • Store all transactions in a MySQL database.
  • Provide a PHP IoT web dashboard.
  • Generate AI-based book recommendations.
  • Monitor device power consumption.
  • Predict future power consumption.
  • Send Telegram text notifications.
  • Send Telegram voice alerts.
  • Store records in Google Sheets.
  • Visualize IoT data using ThingSpeak.
  • Automate workflows using n8n.

3. Hardware Components

Component Purpose
ESP32 Development Board Main IoT controller with Wi-Fi connectivity.
MFRC522 RFID Reader Reads RFID cards and RFID book tags.
RFID Student Card Identifies the library user.
RFID Book Tag Identifies the selected book.
OLED Display Displays system status and messages.
Buzzer Provides audio confirmation.
LED Indicates successful or failed operations.
Current Sensor Measures electrical current.
Voltage Sensor Measures supply voltage.
Power Supply Provides electrical power.

4. Software Components

ESP32 Firmware

Arduino C/C++ firmware reads RFID cards, controls the display, activates the buzzer, measures sensors, and sends JSON data to the PHP server.

PHP Backend

PHP receives ESP32 data, processes library transactions, communicates with MySQL, and provides REST API services.

MySQL Database

Stores users, books, transactions, recommendations, and power data.

AI Engine

Analyzes borrowing history and generates personalized recommendations.

n8n Automation

Connects the PHP server with Telegram, Google Sheets, ThingSpeak, and AI services.

5. System Architecture Diagram

+-------------------------------------------------------------+ | SMART LIBRARY SYSTEM | +-------------------------------------------------------------+ +----------------------+ | RFID STUDENT CARD | +----------+-----------+ | v +----------------------+ | RFID BOOK TAG | +----------+-----------+ | v +----------------------+ | ESP32 | | | | RFID Reader | | OLED Display | | Buzzer | | Power Sensors | | Wi-Fi | +----------+-----------+ | | HTTP JSON v +----------------------+ | PHP API | | esp32_event.php | +----------+-----------+ | v +----------------------+ | MySQL | | | | Users | | Books | | Transactions | | Power Data | +----------+-----------+ | +-------+-------+ | | v v +----------------+ +----------------+ | AI ENGINE | | n8n AUTOMATION | | | | | | Recommendations| | AI Agent | | Power Prediction| | Workflow | +--------+-------+ +--------+-------+ | | +---------+----------+ | +-----------+------------+ | | | v v v +-------------+ +----------+ +------------+ | Telegram | | Google | | ThingSpeak | | Text/Voice | | Sheets | | Dashboard | +-------------+ +----------+ +------------+

6. Complete System Flowchart

START | v Power ON ESP32 | v Connect to Wi-Fi | v Is Wi-Fi Connected? | +------ NO ------+ | | | v | Retry Connection | | +----------------+ | YES | v Initialize RFID Reader | v Wait for Student RFID | v Student Card Detected | v Read Student UID | v Validate Student | +------ INVALID ------> Send Alert | VALID | v Wait for Book RFID | v Book Tag Detected | v Read Book UID | v Send Data to PHP API | v PHP Searches MySQL | v Is Book Available? | +------ YES ------> ISSUE BOOK | +------ NO -------> RETURN BOOK | v Save Transaction | v Run AI Recommendation | v Trigger n8n Webhook | +----------+------------+ | | | v v v Telegram Google ThingSpeak Alert Sheets Dashboard | v Voice Notification | v END

7. Circuit Schematic Diagram

+----------------------+ | ESP32 | | | | GPIO 5 <---------- SDA | GPIO 18 <---------- SCK | GPIO 23 <---------- MOSI | GPIO 19 ----------> MISO | GPIO 4 ----------> RST | | | GPIO 21 ----------> SDA OLED | GPIO 22 ----------> SCL OLED | | | GPIO 25 ----------> BUZZER | GPIO 26 ----------> GREEN LED | GPIO 27 ----------> RED LED | | | GPIO 34 <---------- CURRENT SENSOR | GPIO 35 <---------- VOLTAGE SENSOR +----------+-----------+ | | v +---------------+ | MFRC522 | | | | SDA | | SCK | | MOSI | | MISO | | RST | | 3.3V | | GND | +---------------+ +---------------+ | OLED DISPLAY | | | | VCC | | GND | | SDA | | SCL | +---------------+ +---------------+ | POWER SENSOR | | | | VOLTAGE | | CURRENT | +---------------+
Important: The MFRC522 RFID module must normally be powered using 3.3V logic. Always verify the specific hardware module specifications before connecting it to the ESP32.

8. Database Design

Table Purpose
users Stores student and library user information.
books Stores book details and availability.
transactions Stores issue and return operations.
recommendations Stores AI recommendation results.
power_data Stores voltage, current, power, and energy data.
CREATE DATABASE smart_library; USE smart_library; CREATE TABLE users ( id INT AUTO_INCREMENT PRIMARY KEY, user_id VARCHAR(50) UNIQUE NOT NULL, rfid_uid VARCHAR(100) UNIQUE NOT NULL, name VARCHAR(100) NOT NULL, department VARCHAR(100), email VARCHAR(150), status VARCHAR(20) DEFAULT 'ACTIVE', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE books ( id INT AUTO_INCREMENT PRIMARY KEY, book_id VARCHAR(50) UNIQUE NOT NULL, rfid_uid VARCHAR(100) UNIQUE NOT NULL, title VARCHAR(200) NOT NULL, author VARCHAR(150), category VARCHAR(100), availability VARCHAR(20) DEFAULT 'AVAILABLE', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE transactions ( id INT AUTO_INCREMENT PRIMARY KEY, user_id VARCHAR(50), book_id VARCHAR(50), action VARCHAR(20), timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE power_data ( id INT AUTO_INCREMENT PRIMARY KEY, voltage FLOAT, current FLOAT, power FLOAT, energy FLOAT, timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP );

9. PHP Backend Software

The PHP backend is the central server-side layer. It receives data from the ESP32 using HTTP POST requests.

JSON Data Received from ESP32

{ "device_id": "ESP32_LIBRARY_01", "card_uid": "A3B79122", "book_uid": "BOOK_RFID_001", "event_type": "LIBRARY_TRANSACTION", "voltage": 5.0, "current": 0.25, "power": 1.25 }

PHP API Code

"error", "message" => "Invalid JSON" ] ); exit; } $cardUid = $data["card_uid"] ?? ""; $bookUid = $data["book_uid"] ?? ""; $voltage = $data["voltage"] ?? 0; $current = $data["current"] ?? 0; $power = $data["power"] ?? 0; $userQuery = $pdo->prepare( "SELECT * FROM users WHERE rfid_uid = ?" ); $userQuery->execute( [ $cardUid ] ); $user = $userQuery->fetch( PDO::FETCH_ASSOC ); if ( !$user ) { echo json_encode( [ "status" => "error", "message" => "Unknown RFID User" ] ); exit; } $bookQuery = $pdo->prepare( "SELECT * FROM books WHERE rfid_uid = ?" ); $bookQuery->execute( [ $bookUid ] ); $book = $bookQuery->fetch( PDO::FETCH_ASSOC ); if ( !$book ) { echo json_encode( [ "status" => "error", "message" => "Book Not Found" ] ); exit; } if ( $book["availability"] == "AVAILABLE" ) { $action = "ISSUE"; $status = "ISSUED"; } else { $action = "RETURN"; $status = "AVAILABLE"; } $update = $pdo->prepare( "UPDATE books SET availability = ? WHERE book_id = ?" ); $update->execute( [ $status, $book["book_id"] ] ); $transaction = $pdo->prepare( "INSERT INTO transactions ( user_id, book_id, action ) VALUES ( ?, ?, ? )" ); $transaction->execute( [ $user["user_id"], $book["book_id"], $action ] ); $powerInsert = $pdo->prepare( "INSERT INTO power_data ( voltage, current, power ) VALUES ( ?, ?, ? )" ); $powerInsert->execute( [ $voltage, $current, $power ] ); echo json_encode( [ "status" => "success", "user" => $user["name"], "book" => $book["title"], "action" => $action ] ); ?>

10. AI Book Recommendation System

The AI recommendation engine studies the user's previous borrowing history.

The system can use the following factors:

  • Previously borrowed book categories.
  • Previously borrowed authors.
  • Popular books.
  • Recently added books.
  • User department.
  • Reading frequency.

Recommendation Score

IF category matches previous category THEN score = score + 5 IF author matches previous author THEN score = score + 3 IF book is popular THEN score = score + 2 IF book is available THEN score = score + 1 SORT books by score DISPLAY TOP 5 BOOKS

PHP AI Recommendation Logic

prepare( "SELECT books.category, books.author FROM transactions INNER JOIN books ON transactions.book_id = books.book_id WHERE transactions.user_id = ?" ); $historyQuery->execute( [ $userId ] ); $history = $historyQuery ->fetchAll( PDO::FETCH_ASSOC ); $categories = []; $authors = []; foreach ( $history as $item ) { $categories[] = $item["category"]; $authors[] = $item["author"]; } $books = $pdo->query( "SELECT * FROM books WHERE availability = 'AVAILABLE'" ); $recommendations = []; foreach ( $books as $book ) { $score = 0; if ( in_array( $book["category"], $categories ) ) { $score += 5; } if ( in_array( $book["author"], $authors ) ) { $score += 3; } $recommendations[] = [ "title" => $book["title"], "author" => $book["author"], "category" => $book["category"], "score" => $score ]; } usort( $recommendations, function( $a, $b ) { return $b["score"] <=> $a["score"]; } ); return array_slice( $recommendations, 0, 5 ); } ?>

11. AI Power Consumption Prediction

The system calculates electrical power using:

POWER = VOLTAGE × CURRENT P = V × I

The system can estimate future power consumption using previous readings.

Previous Power Data | v Calculate Average | v Analyze Trend | v Estimate Future Power | v Generate Alert if Limit Exceeded
10 ) { return $power * 1.10; } return $power * 1.05; } ?>

12. n8n Automation Workflow

PHP WEBHOOK | v n8n WEBHOOK NODE | v READ JSON DATA | v VALIDATE DATA | +----------------+ | | v v TRANSACTION POWER DATA | | v v Google Sheets ThingSpeak | v AI Recommendation | v Telegram Message | v Voice Notification

n8n Workflow Nodes

Node Function
Webhook Receives data from PHP.
Set Organizes incoming data.
IF Checks issue, return, or error.
Google Sheets Stores transaction data.
HTTP Request Sends data to ThingSpeak.
Telegram Sends notification.
AI Agent Generates intelligent responses.

13. Telegram Bot Setup

  1. Open Telegram.
  2. Search for BotFather.
  3. Create a new bot.
  4. Copy the bot token.
  5. Find the Telegram chat ID.
  6. Add the values to config.php.

Example Alert

SMART LIBRARY ALERT Student: John Book: Artificial Intelligence Action: BOOK ISSUED Time: 10:30 AM Recommendation: Machine Learning Fundamentals

14. Google Sheets Integration

Google Sheets can be used as a cloud-based transaction backup system.

Timestamp User ID Student Name Book Action
2026-07-21 STU001 Student AI Book ISSUE

n8n receives the transaction from the PHP server and automatically appends the data to Google Sheets.

15. ThingSpeak Cloud Dashboard

ThingSpeak can be used to monitor IoT sensor data remotely.

Field Data
Field 1 Voltage
Field 2 Current
Field 3 Power
Field 4 Energy
ESP32 | v PHP API | v n8n | v ThingSpeak | v Cloud Graphs

16. Telegram Voice Notification Automation

LIBRARY EVENT | v PHP SERVER | v n8n WEBHOOK | v CREATE MESSAGE | v TEXT-TO-SPEECH | v AUDIO FILE | v TELEGRAM VOICE MESSAGE

Example voice message:

"Library notification. Student John has successfully issued the book Artificial Intelligence."

17. Complete Project Folder Structure

smart-library/ │ ├── index.php ├── config.php ├── database.php │ ├── database/ │ └── smart_library.sql │ ├── api/ │ ├── esp32_event.php │ ├── recommendations.php │ ├── power_prediction.php │ ├── send_to_n8n.php │ └── dashboard_data.php │ ├── ai/ │ ├── recommendation_engine.php │ └── power_prediction_engine.php │ ├── admin/ │ ├── dashboard.php │ ├── books.php │ ├── users.php │ └── transactions.php │ ├── integrations/ │ ├── telegram.php │ ├── telegram_voice.php │ ├── google_sheets.php │ └── thingspeak.php │ ├── n8n/ │ └── library_workflow.json │ └── esp32/ └── esp32_library.ino

18. Complete Installation Steps

  1. Install XAMPP or another PHP server.
  2. Start Apache.
  3. Start MySQL.
  4. Create a database named smart_library.
  5. Import the SQL database file.
  6. Copy the project folder into the web server directory.
  7. Configure database credentials.
  8. Configure Telegram Bot Token.
  9. Configure Telegram Chat ID.
  10. Configure ThingSpeak API Key.
  11. Configure Google Sheets credentials.
  12. Create the n8n workflow.
  13. Copy the n8n webhook URL into config.php.
  14. Upload the ESP32 firmware.
  15. Connect the ESP32 to Wi-Fi.
  16. Test RFID student scanning.
  17. Test RFID book scanning.
  18. Verify the MySQL transaction.
  19. Verify the Telegram notification.
  20. Verify Google Sheets data.
  21. Verify ThingSpeak data.

19. Deployment Guide

LOCAL DEVELOPMENT ESP32 | v XAMPP | v PHP + MySQL PRODUCTION DEPLOYMENT ESP32 | v Internet | v Cloud PHP Hosting | v Cloud MySQL | +------------+ | | v v n8n Cloud ThingSpeak | v Telegram

Production Requirements

  • Use HTTPS.
  • Use strong database passwords.
  • Protect API endpoints.
  • Use API authentication.
  • Validate all ESP32 data.
  • Use prepared SQL statements.
  • Do not expose private API keys.
  • Use secure environment variables.
  • Create regular database backups.

20. Future Enhancements

  • Face recognition for student authentication.
  • Mobile application.
  • Voice-controlled library search.
  • AI chatbot for book queries.
  • Advanced machine learning recommendation algorithms.
  • Automatic overdue prediction.
  • Book demand forecasting.
  • Smart shelf monitoring.
  • Computer vision for book recognition.
  • Cloud-based user authentication.
  • Multi-library support.
  • AI-based reading behavior analysis.

21. Final Project Summary

The AI-Based Smart Library Management and Book Recommendation System combines embedded systems, Internet of Things technology, Artificial Intelligence, cloud services, automation, and web development.

The ESP32 provides the hardware intelligence. RFID provides automatic identification. PHP provides the server-side processing. MySQL stores the library database. AI provides personalized book recommendations and power prediction. n8n connects different cloud services. Telegram provides instant notifications and voice alerts. Google Sheets provides cloud-based data storage and ThingSpeak provides IoT visualization.

Final Architecture: ESP32 + RFID → PHP API → MySQL → AI Engine → n8n Automation → Telegram → Google Sheets → ThingSpeak → Web Dashboard

AI-Based Smart Library Management and Book Recommendation System

ESP32 | PHP | MySQL | AI | n8n | Telegram | Google Sheets | ThingSpeak

Recommended actual project files The documentation above is one PHP file, but the working system should be separated into individual files: smart-library/ │ ├── smart_library_documentation.php │ ├── index.php ├── config.php ├── database.php │ ├── database/ │ └── smart_library.sql │ ├── api/ │ ├── esp32_event.php │ ├── recommendations.php │ ├── power_prediction.php │ ├── send_to_n8n.php │ └── dashboard_data.php │ ├── ai/ │ ├── recommendation_engine.php │ └── power_prediction_engine.php │ ├── admin/ │ ├── dashboard.php │ ├── books.php │ ├── users.php │ └── transactions.php │ ├── integrations/ │ ├── telegram.php │ ├── telegram_voice.php │ ├── google_sheets.php │ └── thingspeak.php │ ├── n8n/ │ └── library_workflow.json │ └── esp32/ └── esp32_library.ino This format provides the full project description, detailed documentation, flow diagrams, architecture diagram, circuit schematic representation, AI logic, PHP backend code, database design, automation flow, Telegram integration, Google Sheets integration, ThingSpeak integration, deployment guide, and future enhancements in PHP-based documentation format.