AI-Based Smart Factory Automation with Predictive Maintenance
ESP32 + AI Agent + Agentic IoT + n8n Automation + Telegram Voice Alerts + Google Sheets + ThingSpeak Cloud Dashboard
1. Full Project Description
The AI-Based Smart Factory Automation with Predictive Maintenance system is an intelligent Industrial IoT solution designed to continuously monitor factory machines and predict possible equipment failures before they occur.
The system uses an ESP32 microcontroller as the primary IoT controller. Multiple sensors are connected to the ESP32 to monitor temperature, vibration, voltage, current, power consumption, machine runtime and operational conditions.
The ESP32 collects real-time sensor data and transmits the data through Wi-Fi to an IoT webpage and an n8n automation workflow.
The n8n workflow acts as an automation engine. It receives the machine data, stores the data in Google Sheets, updates ThingSpeak cloud dashboards, sends the sensor information to an AI Agent and automatically generates predictive maintenance decisions.
The AI Agent analyzes machine health parameters and predicts whether the machine is operating normally, showing warning symptoms or approaching a possible failure condition.
When a dangerous condition is detected, n8n automatically sends Telegram text alerts and voice notifications to the maintenance team.
The complete system represents an Agentic IoT architecture because the AI Agent can analyze data, make decisions, generate recommendations and trigger automated actions.
2. Project Objectives
- Monitor industrial machines in real time.
- Measure machine temperature.
- Measure vibration levels.
- Monitor voltage and current.
- Calculate power consumption.
- Predict possible machine failures.
- Detect abnormal energy consumption.
- Store historical machine data.
- Generate AI maintenance recommendations.
- Send Telegram text alerts.
- Send Telegram voice notifications.
- Display machine status on an IoT webpage.
- Store data in Google Sheets.
- Display cloud analytics using ThingSpeak.
- Automatically control warning devices.
3. System Architecture
INDUSTRIAL MACHINE
|
v
TEMPERATURE SENSOR
VIBRATION SENSOR
CURRENT SENSOR
VOLTAGE SENSOR
|
v
ESP32 IoT CONTROLLER
|
| Wi-Fi
v
IOT WEBPAGE / PHP API
|
v
n8n AUTOMATION WORKFLOW
|
+-------------------------+
| |
v v
AI AGENT GOOGLE SHEETS
PREDICTIVE DATA STORAGE
ANALYSIS
|
v
THINGSPEAK CLOUD
DASHBOARD
|
v
FAILURE DECISION
|
+-------------------------+
| |
v v
TELEGRAM TEXT TELEGRAM VOICE
ALERT NOTIFICATION
|
v
MAINTENANCE ACTION
4. Hardware Components List
| Component | Purpose |
|---|---|
| ESP32 Development Board | Main IoT controller |
| DS18B20 / DHT22 | Temperature monitoring |
| MPU6050 / ADXL345 | Vibration monitoring |
| ACS712 / PZEM | Current measurement |
| ZMPT101B / PZEM | Voltage measurement |
| OLED Display | Local machine status display |
| Relay Module | Automatic control |
| Buzzer | Local warning notification |
| Red LED | Critical status indication |
| Green LED | Normal status indication |
| Wi-Fi Router | Internet connectivity |
| Industrial Motor | Machine under monitoring |
5. Circuit Schematic Diagram
+----------------------+
| ESP32 |
| |
| GPIO 4 <------------ DS18B20 DATA
| |
| GPIO 21 <------------ MPU6050 SDA
| |
| GPIO 22 <------------ MPU6050 SCL
| |
| GPIO 34 <------------ Current Sensor
| |
| GPIO 35 <------------ Voltage Sensor
| |
| GPIO 25 ------------> Relay Module
| |
| GPIO 26 ------------> Buzzer
| |
| GPIO 27 ------------> RED LED
| |
| GPIO 14 ------------> GREEN LED
| |
| 3.3V ---------------> Sensors
| |
| GND ----------------> Common GND
+----------------------+
6. Detailed Circuit Connections
DS18B20 Temperature Sensor
| DS18B20 Pin | ESP32 Pin |
|---|---|
| VCC | 3.3V |
| GND | GND |
| DATA | GPIO 4 |
A 4.7 kΩ pull-up resistor should be connected between DATA and 3.3V.
MPU6050 Vibration Sensor
| MPU6050 | ESP32 |
|---|---|
| VCC | 3.3V |
| GND | GND |
| SDA | GPIO 21 |
| SCL | GPIO 22 |
7. Complete Flowchart
START
|
v
INITIALIZE ESP32
|
v
CONNECT TO WI-FI
|
v
READ TEMPERATURE
|
v
READ VIBRATION
|
v
READ VOLTAGE
|
v
READ CURRENT
|
v
CALCULATE POWER
|
v
SEND DATA TO SERVER
|
v
n8n RECEIVES DATA
|
v
AI AGENT ANALYZES DATA
|
v
CALCULATE FAILURE RISK
|
+---------------------------+
| |
v v
NORMAL WARNING / CRITICAL
| |
v v
STORE DATA SEND TELEGRAM ALERT
| |
v v
UPDATE CLOUD GENERATE VOICE ALERT
|
v
MAINTENANCE ACTION
|
v
REPEAT MONITORING
8. Predictive Maintenance Logic
The system calculates a machine health score based on multiple parameters.
Temperature Risk = 25 Percent Vibration Risk = 30 Percent Power Consumption Risk = 25 Percent Current Risk = 20 Percent Total Risk Score = Temperature Risk * 0.25 + Vibration Risk * 0.30 + Power Risk * 0.25 + Current Risk * 0.20
Temperature Threshold
| Temperature | Status |
|---|---|
| Below 60 °C | NORMAL |
| 60 °C to 75 °C | WARNING |
| Above 75 °C | CRITICAL |
Machine Risk Score
0 to 30 = NORMAL 31 to 60 = WARNING 61 to 100 = CRITICAL
9. AI Power Consumption Prediction Logic
The system records historical power consumption and uses the historical trend to identify abnormal energy usage.
09:00 = 2200 W 09:10 = 2300 W 09:20 = 2500 W 09:30 = 2800 W
The AI Agent detects that power consumption is increasing abnormally.
CURRENT POWER: 2800 W PREDICTED FUTURE POWER: 3400 W POSSIBLE CAUSES: 1. Motor overload 2. Bearing friction 3. Mechanical obstruction 4. Voltage instability
10. ESP32 Source Code
#include <WiFi.h>
#include <HTTPClient.h>
#include <Wire.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <ArduinoJson.h>
const char* ssid = "YOUR_WIFI_NAME";
const char* password = "YOUR_WIFI_PASSWORD";
const char* serverURL =
"https://your-domain.com/api/receive_data.php";
#define ONE_WIRE_BUS 4
#define RELAY_PIN 25
#define BUZZER_PIN 26
#define RED_LED 27
#define GREEN_LED 14
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
float temperature;
float vibration;
float voltage;
float current;
float power;
void setup()
{
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(RED_LED, OUTPUT);
pinMode(GREEN_LED, OUTPUT);
sensors.begin();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("WiFi Connected");
}
void loop()
{
sensors.requestTemperatures();
temperature = sensors.getTempCByIndex(0);
vibration = analogRead(34);
voltage = analogRead(35) * 0.1;
current = analogRead(32) * 0.01;
power = voltage * current;
String status = "NORMAL";
if (
temperature > 75 ||
vibration > 3000 ||
power > 3000
)
{
status = "CRITICAL";
digitalWrite(RED_LED, HIGH);
digitalWrite(GREEN_LED, LOW);
digitalWrite(BUZZER_PIN, HIGH);
}
else if (
temperature > 60 ||
vibration > 2000 ||
power > 2500
)
{
status = "WARNING";
digitalWrite(RED_LED, HIGH);
digitalWrite(GREEN_LED, LOW);
digitalWrite(BUZZER_PIN, LOW);
}
else
{
status = "NORMAL";
digitalWrite(RED_LED, LOW);
digitalWrite(GREEN_LED, HIGH);
digitalWrite(BUZZER_PIN, LOW);
}
if (WiFi.status() == WL_CONNECTED)
{
HTTPClient http;
http.begin(serverURL);
http.addHeader(
"Content-Type",
"application/json"
);
StaticJsonDocument<512> doc;
doc["machine_id"] = "MACHINE_01";
doc["temperature"] = temperature;
doc["vibration"] = vibration;
doc["voltage"] = voltage;
doc["current"] = current;
doc["power"] = power;
doc["status"] = status;
String jsonData;
serializeJson(doc, jsonData);
int httpResponseCode =
http.POST(jsonData);
Serial.println(httpResponseCode);
http.end();
}
delay(10000);
}
11. PHP IoT API File
Save the following file as:
receive_data.php
<?php
header("Content-Type: application/json");
$data = json_decode(
file_get_contents("php://input"),
true
);
if (!$data)
{
echo json_encode(
[
"status" => "error",
"message" => "Invalid JSON data"
]
);
exit;
}
$machine_id =
$data["machine_id"] ?? "UNKNOWN";
$temperature =
$data["temperature"] ?? 0;
$vibration =
$data["vibration"] ?? 0;
$voltage =
$data["voltage"] ?? 0;
$current =
$data["current"] ?? 0;
$power =
$data["power"] ?? 0;
$status =
$data["status"] ?? "UNKNOWN";
$file = "machine_data.json";
$old_data = [];
if (file_exists($file))
{
$old_data =
json_decode(
file_get_contents($file),
true
);
}
$record =
[
"machine_id" => $machine_id,
"temperature" => $temperature,
"vibration" => $vibration,
"voltage" => $voltage,
"current" => $current,
"power" => $power,
"status" => $status,
"timestamp" => date(
"Y-m-d H:i:s"
)
];
$old_data[] = $record;
file_put_contents(
$file,
json_encode(
$old_data,
JSON_PRETTY_PRINT
)
);
echo json_encode(
[
"status" => "success",
"message" =>
"Machine data received",
"data" => $record
]
);
?>
12. IoT Web Dashboard
The dashboard displays real-time machine information.
SMART FACTORY MONITORING DASHBOARD Machine Status: NORMAL Temperature: 45 °C Vibration: 1.5 mm/s Voltage: 230 V Current: 9.5 A Power: 2200 W Health Score: 92 Percent
13. n8n Automation Workflow
ESP32
|
v
WEBHOOK
|
v
JSON DATA PROCESSING
|
v
DATA VALIDATION
|
v
AI PREDICTIVE MAINTENANCE AGENT
|
v
FAILURE RISK ANALYSIS
|
+--------------------------+
| |
v v
NORMAL HIGH RISK
| |
v v
GOOGLE SHEETS TELEGRAM ALERT
| |
v v
THINGSPEAK CLOUD VOICE ALERT
|
v
MAINTENANCE ACTION
14. AI Agent Prompt
You are an industrial predictive maintenance AI Agent. Analyze the following machine data. Machine ID: Temperature: Vibration: Voltage: Current: Power: Determine: 1. Machine health status. 2. Failure risk. 3. Failure probability. 4. Possible failure cause. 5. Recommended maintenance action. 6. Whether Telegram alert is required. Return the result in JSON format.
15. Example AI Prediction
{
"health_status": "WARNING",
"failure_risk": "HIGH",
"failure_probability": 78,
"possible_cause":
"Motor bearing overheating",
"recommendation":
"Inspect bearing lubrication",
"alert_required": true
}
16. Telegram Bot Setup
Create a Telegram bot using BotFather.
Step 1: Open Telegram. Step 2: Search for BotFather. Step 3: Send: /newbot Step 4: Enter: Smart Factory Alert Bot Step 5: Copy the generated BOT TOKEN. Step 6: Configure the token inside the n8n Telegram node.
17. Telegram Alert Message
SMART FACTORY ALERT Machine ID: MACHINE_01 Temperature: 78 °C Vibration: HIGH Power Consumption: 3400 W AI Failure Risk: 85 Percent Predicted Problem: Motor bearing failure. Recommended Action: Inspect motor bearing and lubrication immediately.
18. Voice Notification Automation
AI PREDICTION
|
v
GENERATE ALERT TEXT
|
v
TEXT-TO-SPEECH
|
v
GENERATE AUDIO FILE
|
v
SEND AUDIO THROUGH TELEGRAM
Example voice message:
Warning. Machine number one is showing a high failure risk. The motor temperature is 78 degrees Celsius. Vibration is above the safe operating limit. Immediate maintenance inspection is recommended.
19. Google Sheets Integration
| Column | Data |
|---|---|
| Timestamp | Machine timestamp |
| Machine ID | Machine identification number |
| Temperature | Temperature value |
| Vibration | Vibration value |
| Voltage | Voltage value |
| Current | Current value |
| Power | Power consumption |
| Health Status | Normal, Warning or Critical |
| Failure Risk | AI predicted risk |
| Recommendation | AI maintenance recommendation |
20. ThingSpeak Cloud Dashboard
FIELD 1: Temperature FIELD 2: Vibration FIELD 3: Voltage FIELD 4: Current FIELD 5: Power FIELD 6: Health Score
The ThingSpeak dashboard can display real-time and historical machine sensor data using charts and graphs.
21. Agentic IoT Architecture
SENSOR | v ESP32 | v AI AGENT | v ANALYZE | v DECIDE | v TAKE ACTION | +----------------------------+ | | v v SEND TELEGRAM ALERT LOG DATA | | v v VOICE NOTIFICATION GOOGLE SHEETS | v CONTROL RELAY | v MAINTENANCE RECOMMENDATION
22. Project Software Requirements
- Arduino IDE
- ESP32 Board Package
- Wi-Fi Library
- HTTP Client Library
- ArduinoJson Library
- OneWire Library
- DallasTemperature Library
- PHP Server
- n8n Automation
- Telegram Bot
- Google Sheets
- ThingSpeak Cloud
- AI API
- Text-to-Speech Service
23. Project Folder Structure
smart-factory-project/ | |-- esp32/ | | | |-- smart_factory.ino | |-- web/ | | | |-- index.php | | | |-- receive_data.php | | | |-- machine_data.json | |-- n8n/ | | | |-- smart_factory_workflow.json | |-- docs/ | | | |-- circuit_diagram | | | |-- flowchart | | | |-- project_report | |-- README.md
24. Complete Project Operation
MACHINE STARTS
|
v
ESP32 STARTS
|
v
WI-FI CONNECTION
|
v
SENSOR READING
|
v
TEMPERATURE MONITORING
|
v
VIBRATION MONITORING
|
v
CURRENT MONITORING
|
v
VOLTAGE MONITORING
|
v
POWER CALCULATION
|
v
DATA SENT TO n8n
|
v
AI AGENT ANALYSIS
|
v
FAILURE PREDICTION
|
+---------------------------+
| |
v v
NORMAL WARNING / CRITICAL
| |
v v
STORE DATA TELEGRAM ALERT
| |
v v
CLOUD UPDATE VOICE NOTIFICATION
|
v
MAINTENANCE ACTION
25. Advantages
- Real-time machine monitoring.
- Early failure detection.
- Reduced machine downtime.
- Reduced maintenance cost.
- AI-based predictive analysis.
- Energy consumption monitoring.
- Telegram notifications.
- Voice notification support.
- Cloud data storage.
- Historical machine analysis.
- Remote monitoring.
- Scalable architecture.
- Agentic IoT automation.
26. Future Enhancements
- Digital Twin of the factory.
- Advanced machine learning models.
- LSTM-based failure prediction.
- Random Forest prediction.
- XGBoost predictive analytics.
- Computer vision for machine inspection.
- Oil leakage detection.
- Smoke detection.
- Multi-machine monitoring.
- Mobile application.
- Advanced energy analytics.
- Automatic maintenance scheduling.
- Voice-controlled factory automation.
- AI-based spare parts prediction.
27. Deployment Guide
- Assemble the ESP32 and industrial sensors.
- Connect the sensors according to the circuit diagram.
- Upload the ESP32 firmware.
- Configure Wi-Fi credentials.
- Deploy the PHP IoT webpage.
- Create the n8n workflow.
- Configure the AI Agent.
- Configure Google Sheets authentication.
- Create the ThingSpeak channel.
- Create and configure the Telegram Bot.
- Configure the voice notification system.
- Test normal machine conditions.
- Test warning conditions.
- Test critical conditions.
- Verify Telegram notifications.
- Verify Google Sheets data logging.
- Verify ThingSpeak cloud charts.
28. Final Project Summary
The AI-Based Smart Factory Automation with Predictive Maintenance system integrates ESP32, industrial sensors, AI Agent technology, n8n automation, Telegram notifications, voice alerts, Google Sheets and ThingSpeak cloud monitoring into one intelligent industrial automation platform.
The system collects real-time machine data, analyzes machine health, detects abnormal conditions, predicts possible failures, estimates future power consumption and automatically sends alerts to the maintenance team.
This project demonstrates the complete concept of Agentic IoT, where sensors collect data, the ESP32 transmits the data, AI analyzes the information, n8n automates the workflow and the system automatically performs appropriate actions.


