Tuesday, 6 October 2026

IoT-Enabled Real-Time Solar Energy Monitoring and Environmental Parameter Analysis Using ESP8266 and ThingSpeak Cloud

IoT-Enabled Real-Time Solar Energy Monitoring and Environmental Parameter Analysis Using ESP8266 and ThingSpeak Cloud | IoT-Enabled Real-Time Monitoring and Performance Analysis of Solar PV Systems.

************************************************

🛠️   Do  You  Want  to  Purchase  the  Full  Working  Project  KIT?   ðŸ› ️

Mail Us:                svsembedded@gmail.com

Title  Name  Along  With  You-Tube  Video  Link

🔌 CODE   &   CIRCUIT DIAGRAMS FOR SALE 🔧
💡 Reliable – Affordable – Ready to Use

http://svsembedded.com/                              è               http://www.svskit.com/

m1:            +91 9491535690                           è               M2:            +91 7842358459
We Will Send Working Model Project KIT through   DTDC / India Post / Blue Dart
We Will Provide Project Soft Data through Google Drive
1.       Project Abstract / Synopsis
2.       Project Related Datasheets of Each Component
3.       Project Sample Report / Documentation
4.       Project Kit Circuit / Schematic Diagram
5.       Project Kit Working Software Code
6.       Project Related Software Compilers
7.       Project Related Sample PPT’s
8.       Project Kit Photos & Working Video links
Latest Projects with Year Wise YouTube video Links
216 Projects è https://svsembedded.com/ieee_2026.php
218 Projects è https://svsembedded.com/ieee_2025.php
152 Projects è https://svsembedded.com/ieee_2024.php
133 Projects è https://svsembedded.com/ieee_2023.php
157 Projects è https://svsembedded.com/ieee_2022.php
135 Projects è https://svsembedded.com/ieee_2021.php
151 Projects è https://svsembedded.com/ieee_2020.php
103 Projects è https://svsembedded.com/ieee_2019.php
61 Projects   è https://svsembedded.com/ieee_2018.php
171 Projects è https://svsembedded.com/ieee_2017.php
170 Projects è https://svsembedded.com/ieee_2016.php
67 Projects  è  https://svsembedded.com/ieee_2015.php
55 Projects  è  https://svsembedded.com/ieee_2014.php
43 Projects  è  https://svsembedded.com/ieee_2013.php
*************************************************

1.SolarPulse: An IoT-Enabled Real-Time Solar Energy Performance and Environmental Intelligence System.
2.Real-Time Solar Energy Monitoring Using Arduino Nano, ESP8266 & ThingSpeak Cloud.
3.IoT-Based Solar Energy Monitoring and Environmental Parameter Analysis System.
4.Design and Implementation of an IoT-Enabled Real-Time Solar Energy Monitoring and Environmental Parameter Analysis System.
5.SolarSense: Intelligent IoT-Based Solar Energy and Environmental Monitoring System.
6.A Smart IoT Framework for Real-Time Photovoltaic Energy Monitoring, Environmental Sensing, and Cloud Analytics.
7.SolarIQ: Intelligent IoT-Based Solar Energy Performance and Environmental Analytics System.
8.IoT-Based Solar Energy Monitoring System Using Arduino Nano and ESP8266.
9.Smart Solar Energy Monitoring Using Arduino Nano, ESP8266 and ThingSpeak.
10.SolarVision: An Intelligent IoT Platform for Real-Time Solar Power and Environmental Performance Analysis.
11.Real-Time Solar Panel Monitoring System Using Arduino Nano, ESP8266 and ThingSpeak.
12.An IoT-Based Cloud-Connected Framework for Real-Time Solar Energy Performance and Environmental Monitoring.
13.SolarPulse Intelligence: Real-Time Renewable Energy and Environmental Analytics Using IoT.
14.IoT-Enabled Integrated Monitoring of Solar Energy Generation and Environmental Parameters for Smart Renewable Energy Management.
15.SolarNexus: A Cloud-Connected IoT Architecture for Intelligent Solar Energy Monitoring and Analytics.
16.Solar Energy and Environmental Monitoring Using Arduino Nano, ESP8266 and ThingSpeak Cloud.
17.Development of a Smart IoT Architecture for Solar Energy Generation Monitoring and Environmental Parameter Analytics.
18.SolarPredict: IoT-Based Solar Energy Performance Monitoring and Predictive Environmental Analytics.
19.Smart Solar Power Monitoring System with Real-Time IoT Data Visualization Using ThingSpeak.
20.Cloud-Connected Intelligent Monitoring and Environmental Analysis of Solar Energy Systems Using IoT.
21.SolarGuard: Real-Time IoT-Based Monitoring and Performance Assessment of Photovoltaic Systems.
22.IoT-Based Solar Power Monitoring and Environmental Parameter Analysis Using ESP8266.
23.SunTrack: Smart IoT-Based Solar Energy Monitoring with Real-Time Environmental Analytics.
24.Real-Time Photovoltaic Performance Monitoring Using IoT-Based Sensing and Cloud Analytics.
25.SolarScope: Real-Time IoT Visualization and Analytics for Solar Energy and Environmental Monitoring.
26.Smart Solar Energy Monitoring and Environmental Sensing Using Arduino Nano and ESP8266.
27.An IoT-Driven Solar Energy Monitoring Framework with Real-Time Environmental Sensing and Cloud-Based Visualization.
28.EcoVolt: Smart Solar Energy and Environmental Parameter Monitoring Using IoT.
29.Solar Energy Generation Monitoring and Environmental Data Analytics Using IoT and ThingSpeak.
30.SunMetrics: An IoT-Based Real-Time Solar Energy and Environmental Data Intelligence Platform.
31.Design and Development of a Cloud-Connected IoT System for Solar Energy Assessment and Environmental Intelligence.
32.IoT-Based Real-Time Solar Panel Performance Monitoring and Environmental Condition Analysis.
33.SolarBrain: An Intelligent IoT Platform for Solar Energy and Environmental Data Analytics.
34.Smart Renewable Energy Monitoring Platform with Integrated Solar and Environmental Data Fusion.
35.SolarWatch: Real-Time IoT Monitoring of Solar Energy Generation and Environmental Conditions.
36.A Cloud-Connected IoT Framework for Real-Time Photovoltaic Energy Monitoring and Environmental Analytics.
37.SolarFusion: Multivariate IoT Analytics for Solar Energy and Environmental Performance Assessment.
38.IoT Solar Power Monitoring System Using Arduino Nano, ESP8266 and ThingSpeak.
39.Integrated Solar-Environmental Intelligence System for Real-Time Renewable Energy Assessment.
40.SolarNet: A Cloud-Connected IoT Framework for Real-Time Solar Energy and Environmental Monitoring.
41.Real-Time Solar Power and Environmental Monitoring Using ESP8266 and ThingSpeak Cloud.
42.PhotonTrack: Smart IoT-Based Solar Energy Harvesting and Environmental Parameter Analysis.
43.Context-Aware Photovoltaic Performance Monitoring System Using Distributed IoT Sensing.
44.Smart Solar Monitoring with IoT: Arduino Nano, ESP8266 and ThingSpeak-Based Cloud Analytics.
45.SolarXpert: Intelligent Monitoring and Analytics of Solar Energy Generation Using IoT.
46.Real-Time Solar Energy Monitoring and Environmental Analysis Using IoT and Cloud Computing.
47.EcoPhoton: An Intelligent IoT Framework for Solar Energy Monitoring and Environmental Analytics.
48.Distributed IoT Architecture for Real-Time Solar Energy Monitoring and Environmental Condition Analysis.
49.SunSync: IoT-Based Intelligent Solar Energy Monitoring and Environmental Analytics Platform.
50.Complete IoT Solar Energy Monitoring System Using Arduino Nano, ESP8266 and ThingSpeak.
51.SolarPulse: An IoT-Enabled Real-Time Solar Energy Performance and Environmental Intelligence System.
52.Design and Implementation of an IoT-Enabled Real-Time Solar Energy Monitoring and Environmental Parameter Analysis System.
53.SolarSense: Intelligent IoT-Based Solar Energy and Environmental Monitoring System.
54.A Smart IoT Framework for Real-Time Photovoltaic Energy Monitoring, Environmental Sensing, and Cloud Analytics.
55.SolarIQ: Intelligent IoT-Based Solar Energy Performance and Environmental Analytics System.
56.An IoT-Based Cloud-Connected Framework for Real-Time Solar Energy Performance and Environmental Monitoring.
57.SolarVision: An Intelligent IoT Platform for Real-Time Solar Power and Environmental Performance Analysis.
58.IoT-Enabled Integrated Monitoring of Solar Energy Generation and Environmental Parameters for Smart Renewable Energy Management.
59.SolarNexus: A Cloud-Connected IoT Architecture for Intelligent Solar Energy Monitoring and Analytics.
60.Real-Time Photovoltaic Performance Monitoring Using IoT-Based Sensing and Cloud Analytics.

Monday, 5 October 2026

AI Diabetes Prediction System using Machine Learning

Absolutely. I can structure this as a **complete final-year/engineering project documentation package** for: > **AI-Powered Diabetes Prediction & IoT Health Monitoring System using Machine Learning, ESP32, n8n Agentic Automation, Telegram Voice Alerts, Google Sheets, ThingSpeak, and a Web Dashboard** The system can combine **ML-based diabetes-risk prediction**, **ESP32 IoT sensing**, **cloud visualization**, and an **AI agent that automatically interprets readings and triggers Telegram voice/text alerts**. ## 1\. Project Title **AI-Powered Diabetes Prediction and IoT Health Monitoring System using ESP32, Machine Learning, n8n Agentic Automation, Telegram Voice Alerts, Google Sheets and ThingSpeak** ### Short title **Agentic IoT-Based AI Diabetes Prediction System** --- # 2\. Abstract This project proposes an intelligent healthcare monitoring system that combines **Artificial Intelligence, Machine Learning, Internet of Things (IoT), ESP32, cloud dashboards, and workflow automation** to assist with diabetes-risk monitoring. The ESP32 acts as the IoT controller and collects physiological/environmental information from connected sensors. The collected measurements are transmitted through Wi-Fi to an IoT/cloud platform such as ThingSpeak and can also be forwarded to an automation workflow implemented using n8n. A trained Machine Learning model analyzes relevant health parameters and estimates the user's diabetes-risk category. The n8n automation layer functions as an **agentic orchestration layer**, receiving sensor/prediction data, applying decision logic and optionally an AI model, storing records in Google Sheets, updating cloud services, and sending notifications through Telegram. When a potentially abnormal condition or high-risk prediction is detected, the system can automatically generate a Telegram notification and, where configured, a voice alert. The user can also interact with the system through Telegram. The proposed system therefore creates an end-to-end pipeline: **Sensors → ESP32 → Wi-Fi → Cloud/API → n8n → AI/ML Analysis → Decision → Google Sheets/ThingSpeak → Telegram Alert** > **Important:** A diabetes prediction model should be presented as a **screening/research tool, not a medical diagnostic device**. Actual diagnosis requires appropriate clinical testing and professional medical evaluation. --- # 3\. Main Objectives The project has several objectives: 1. Develop a Machine Learning model capable of estimating diabetes risk from health-related input parameters. 2. Build an ESP32-based IoT monitoring device. 3. Collect sensor/user health data automatically. 4. Send data to a cloud platform. 5. Develop a web-based monitoring dashboard. 6. Integrate n8n for workflow automation. 7. Introduce an AI-agent layer for interpreting incoming information. 8. Store historical measurements in Google Sheets. 9. Visualize time-series data using ThingSpeak. 10. Send Telegram notifications when configurable thresholds/risk conditions are reached. 11. Generate Telegram voice notifications where supported by the selected implementation. 12. Provide an extensible architecture for future healthcare/IoT applications. --- # 4\. Proposed System Architecture ``` ┌──────────────────────────┐ │ USER / PATIENT │ │ Age, BMI, Glucose, etc. │ └────────────┬─────────────┘ │ ▼ ┌──────────────────────────┐ │ ESP32 IoT DEVICE │ │ │ │ Sensors / Display / WiFi │ └────────────┬─────────────┘ │ Wi-Fi / HTTP │ ▼ ┌──────────────────────────┐ │ IoT CLOUD │ │ ThingSpeak │ └────────────┬─────────────┘ │ │ API / Webhook ▼ ┌──────────────────────────┐ │ n8n │ │ Automation Workflow │ └────────────┬─────────────┘ │ ┌──────────────┼──────────────┐ │ │ │ ▼ ▼ ▼ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ ML Model │ │ AI Agent │ │ Validation │ │ Prediction │ │ Reasoning │ │ / Rules │ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ └───────────────┼───────────────┘ ▼ ┌──────────────────────────┐ │ DECISION ENGINE │ │ Normal / Warning / High │ └────────────┬─────────────┘ │ ┌──────────────────┼──────────────────┐ ▼ ▼ ▼ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ Google Sheets│ │ ThingSpeak │ │ Telegram │ │ Data Storage │ │ Dashboard │ │ Notification │ └──────────────┘ └──────────────┘ └──────┬───────┘ │ ▼ ┌──────────────┐ │ Voice Alert │ └──────────────┘ ``` --- # 5\. Overall Data Flow The complete data flow is: ``` START │ ▼ Power ON ESP32 │ ▼ Initialize Sensors │ ▼ Connect to Wi-Fi │ ▼ Read Sensor/User Parameters │ ▼ Validate Data │ ├── Invalid ──► Reject / Retry │ ▼ Send Data │ ├──────────────► ThingSpeak │ └──────────────► n8n Webhook │ ▼ Preprocess Data │ ▼ ML Prediction │ ▼ Risk Classification │ ┌───────────┼───────────┐ ▼ ▼ ▼ LOW MODERATE HIGH │ │ │ ▼ ▼ ▼ Record Record Record │ │ │ └───────────┼───────────┘ ▼ AI Agent Analysis │ ▼ Generate Response │ ┌───────────┼────────────┐ ▼ ▼ ▼ Google Sheets ThingSpeak Telegram │ ▼ Voice Notification ``` --- # 6\. Hardware Requirements A practical prototype can contain: | Component | Purpose | | --- | --- | | ESP32 development board | Main IoT controller | | MAX30102 | Heart-rate / SpO₂ sensing\* | | DS18B20 | Temperature measurement | | OLED display | Local information display | | Push button | User interaction | | Buzzer | Local alarm | | LED | Status indication | | Wi-Fi | Internet communication | | 5 V USB supply | Power | \*Sensor measurements such as SpO₂ and heart rate should not automatically be treated as clinically accurate unless the hardware and measurement procedure have been properly validated. For a diabetes-prediction prototype, some model inputs may not actually be measurable by the ESP32. For example: - Age - BMI - Pregnancies - Blood glucose - Blood pressure - Insulin - Diabetes pedigree information can instead be entered through the web interface or Telegram. This gives the system two input paths: ``` ┌───────────────┐ │ ESP32 Sensors │ └───────┬───────┘ │ ▼ IoT Measurements │ │ ┌──────────────┐ │ │ Web Interface│─────┤ └──────────────┘ │ ▼ Combined Patient Data │ ▼ ML Model ``` --- # 7\. ESP32 Hardware Block Diagram ``` ┌─────────────┐ │ ESP32 │ │ │ │ GPIO/I2C │ └──────┬──────┘ │ ┌────────────────┼────────────────┐ │ │ │ ▼ ▼ ▼ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ MAX30102│ │ DS18B20 │ │ OLED │ │ Sensor │ │ Temp. │ │ Display │ └─────────┘ └─────────┘ └─────────┘ │ │ ▼ Health Data ┌─────────────┐ │ Wi-Fi Router│ └──────┬──────┘ │ Internet │ ▼ Cloud / n8n ``` --- # 8\. Suggested ESP32 Pin Configuration Example configuration: ``` ESP32 │ ├── GPIO 21 → I2C SDA ├── GPIO 22 → I2C SCL │ ├── I2C → MAX30102 ├── I2C → OLED │ ├── GPIO 4 → DS18B20 DATA ├── GPIO 25 → Buzzer ├── GPIO 26 → Status LED └── GPIO 27 → Push Button ``` ### Important I²C devices can share SDA/SCL as long as their I²C addresses do not conflict. Also verify the voltage requirements of every module before connecting it to the ESP32. --- # 9\. Schematic-Level Connection ``` ESP32 ┌───────────────┐ │ │ │ GPIO21 ───────┼──── SDA ─────┐ │ GPIO22 ───────┼──── SCL ─────┤ │ │ │ │ 3V3 ──────────┼──────────────┼───┐ │ GND ──────────┼──────────────┼───┤ │ │ │ │ └───────────────┘ │ │ │ │ ┌────────▼───▼──────┐ │ MAX30102 │ │ │ │ SDA SCL VCC GND │ └───────────────────┘ GPIO4 ───────────── DATA 3V3 ────────────── VCC GND ────────────── GND ┌─────────┐ │ DS18B20 │ └─────────┘ GPIO21 ───────── SDA GPIO22 ───────── SCL 3V3 ──────────── VCC GND ──────────── GND ┌───────┐ │ OLED │ └───────┘ GPIO25 ───────── Buzzer GPIO26 ───────── LED GPIO27 ───────── Push Button ``` For a physical build, include appropriate resistors, decoupling, pull-ups and transistor/driver stages where required by the specific modules. --- # 10\. Software Architecture ``` ┌───────────────────────────────────────────────┐ │ USER INTERFACE │ │ HTML / CSS / JavaScript Web App │ └───────────────────────┬───────────────────────┘ │ ▼ ┌───────────────────────────────────────────────┐ │ API / BACKEND │ │ Python Flask / FastAPI / Node.js │ └───────────────────────┬───────────────────────┘ │ ┌──────────┴──────────┐ ▼ ▼ ┌──────────────┐ ┌──────────────┐ │ ML Prediction│ │ n8n Webhook │ └──────────────┘ └──────┬───────┘ │ ▼ ┌──────────────┐ │ AI Agent │ └──────┬───────┘ │ ┌────────────────┼───────────────┐ ▼ ▼ ▼ Google Sheets ThingSpeak Telegram ``` --- # 11\. Machine Learning Component A commonly used academic dataset for demonstrating diabetes prediction is the **Pima Indians Diabetes Database**. Typical features include: ``` Pregnancies Glucose BloodPressure SkinThickness Insulin BMI DiabetesPedigreeFunction Age ``` Target: ``` Outcome 0 = lower predicted diabetes-risk class 1 = higher predicted diabetes-risk class ``` For an academic project, compare several algorithms rather than assuming one is automatically best: - Logistic Regression - Decision Tree - Random Forest - Support Vector Machine - K-Nearest Neighbors - Gradient Boosting Useful evaluation metrics: ``` Accuracy Precision Recall F1-score ROC-AUC Confusion Matrix ``` For health-related screening, **recall/sensitivity and false-negative behavior are especially important**, so reporting only accuracy would be inadequate. --- # 12\. ML Training Code Example Python implementation: ``` import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline from sklearn.linear_model import LogisticRegression from sklearn.metrics import ( accuracy_score, precision_score, recall_score, f1_score, roc_auc_score, confusion_matrix ) # Load dataset df = pd.read_csv("diabetes.csv") # Input features X = df.drop("Outcome", axis=1) # Target y = df["Outcome"] # Train/test split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.20, random_state=42, stratify=y ) # Pipeline model = Pipeline([ ("scaler", StandardScaler()), ("classifier", LogisticRegression(max_iter=1000)) ]) # Train model.fit(X_train, y_train) # Prediction y_pred = model.predict(X_test) y_prob = model.predict_proba(X_test)[:, 1] # Metrics print("Accuracy:", accuracy_score(y_test, y_pred)) print("Precision:", precision_score(y_test, y_pred)) print("Recall:", recall_score(y_test, y_pred)) print("F1:", f1_score(y_test, y_pred)) print("ROC-AUC:", roc_auc_score(y_test, y_prob)) print("Confusion Matrix:") print(confusion_matrix(y_test, y_pred)) ``` --- # 13\. Saving the ML Model ``` import joblib joblib.dump(model, "diabetes_model.pkl") print("Model saved successfully.") ``` The resulting model: ``` diabetes_model.pkl ``` can be loaded by the backend. --- # 14\. Prediction API A simple FastAPI implementation: ``` from fastapi import FastAPI import joblib app = FastAPI() model = joblib.load("diabetes_model.pkl") @app.get("/") def home(): return { "status": "online", "service": "AI Diabetes Prediction API" } @app.post("/predict") def predict(data: dict): features = [[ data["Pregnancies"], data["Glucose"], data["BloodPressure"], data["SkinThickness"], data["Insulin"], data["BMI"], data["DiabetesPedigreeFunction"], data["Age"] ]] prediction = int(model.predict(features)[0]) probability = float( model.predict_proba(features)[0][1] ) if prediction == 1: risk = "HIGH" else: risk = "LOW" return { "prediction": prediction, "risk": risk, "probability": probability } ``` --- # 15\. Webpage The webpage can provide: ``` +--------------------------------------------------+ | AI DIABETES & IoT MONITORING SYSTEM | +--------------------------------------------------+ | | | Patient Information | | | | Age: [ 45 ] | | Glucose: [ 145 ] | | Blood Pressure: [ 85 ] | | BMI: [ 28.5 ] | | | | [ PREDICT DIABETES RISK ] | | | +--------------------------------------------------+ | LIVE IoT DATA | +--------------------------------------------------+ | Heart Rate: 78 BPM | | SpO2: 97 % | | Temperature: 36.7 °C | +--------------------------------------------------+ | AI RESULT | | | | Risk: MODERATE/HIGH | | Probability: XX % | | | +--------------------------------------------------+ | ThingSpeak Graph | | | | /\/\/\/\__/\/\/\/\ | | | +--------------------------------------------------+ ``` --- # 16\. Example HTML ``` AI Diabetes Monitoring

AI Diabetes Prediction



ESP32 Live Monitoring

Heart Rate: --

SpO2: --

Temperature: --

``` --- # 17\. ESP32 Firmware Arduino-style ESP32 example: ``` #include #include const char* ssid = "YOUR_WIFI"; const char* password = "YOUR_PASSWORD"; const char* serverURL = "https://YOUR_SERVER/api/iot"; void setup() { Serial.begin(115200); WiFi.begin(ssid, password); Serial.print("Connecting"); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(); Serial.println("WiFi connected"); } void loop() { float heartRate = 78.0; float spo2 = 97.0; float temperature = 36.7; if (WiFi.status() == WL_CONNECTED) { HTTPClient http; http.begin(serverURL); http.addHeader( "Content-Type", "application/json" ); String json = "{"; json += "\"heartRate\":" + String(heartRate) + ","; json += "\"spo2\":" + String(spo2) + ","; json += "\"temperature\":" + String(temperature); json += "}"; int responseCode = http.POST(json); Serial.print("HTTP Response: "); Serial.println(responseCode); http.end(); } delay(30000); } ``` Replace the example sensor values with actual sensor-library readings after integrating the hardware. --- # 18\. ThingSpeak Integration A useful ThingSpeak channel structure could be: ``` Field 1 → Heart Rate Field 2 → SpO2 Field 3 → Temperature Field 4 → Glucose Field 5 → BMI Field 6 → ML Risk Probability Field 7 → Risk Class ``` Conceptually: ``` ESP32 │ ▼ ThingSpeak API │ ├── Field 1 ── Heart Rate ├── Field 2 ── SpO2 ├── Field 3 ── Temperature ├── Field 4 ── Glucose ├── Field 5 ── BMI ├── Field 6 ── ML Probability └── Field 7 ── Risk ``` The ThingSpeak graph then provides a historical view of measurements. --- # 19\. n8n Automation Architecture The n8n workflow is the central automation layer. ``` ┌─────────────────┐ │ Webhook Trigger │ └────────┬────────┘ │ ▼ ┌─────────────────┐ │ Validate Input │ └────────┬────────┘ │ ▼ ┌─────────────────┐ │ Data Processing │ └────────┬────────┘ │ ▼ ┌─────────────────┐ │ ML Prediction │ └────────┬────────┘ │ ▼ ┌─────────────────┐ │ AI Agent │ │ Interpretation │ └────────┬────────┘ │ ▼ ┌─────────────┐ │ IF / Switch │ └──────┬──────┘ │ ┌──────────┼───────────┐ ▼ ▼ ▼ NORMAL WARNING HIGH │ │ │ ▼ ▼ ▼ Store Store Store │ │ │ └──────────┼───────────┘ ▼ Google Sheets │ ▼ Telegram │ ▼ Voice Alert ``` --- # 20\. Example n8n Workflow Recommended nodes: ``` Webhook ↓ Set / Edit Fields ↓ Code ↓ HTTP Request ↓ AI Agent ↓ Switch ├── LOW ├── MODERATE └── HIGH ↓ Google Sheets ↓ Telegram ↓ Voice generation / audio delivery ``` ### Webhook JSON ESP32/backend can send: ``` { "device_id": "ESP32_001", "heart_rate": 82, "spo2": 97, "temperature": 36.8, "glucose": 142, "bmi": 28.4, "age": 45 } ``` --- # 21\. n8n Code Node Example: ``` const data = $json; const glucose = Number(data.glucose); const bmi = Number(data.bmi); const age = Number(data.age); let status = "NORMAL"; if (glucose >= 200) { status = "HIGH"; } else if (glucose >= 140) { status = "WARNING"; } return [{ json: { ...data, preliminary_status: status, timestamp: new Date().toISOString() } }]; ``` This should be treated as **workflow demonstration logic**, not as a clinical diagnostic threshold engine. --- # 22\. AI Agent Role The AI agent should **not replace the ML model**. Instead: ``` ML Model │ │ numerical prediction ▼ AI Agent │ ├── Interpret result ├── Generate explanation ├── Decide notification wording ├── Summarize recent readings └── Trigger appropriate workflow action ``` This separation is important. ### ML model Answers: > "What does the trained statistical model predict?" ### AI agent Answers: > "How should this information be interpreted and communicated within the automation workflow?" --- # 23\. Example AI Agent Prompt ``` You are an IoT health-monitoring workflow assistant. Your task is to interpret incoming device data and the output of a diabetes-risk machine-learning model. Do not diagnose disease. Do not invent medical measurements. Use only the information supplied by the workflow. Return: 1. Risk category 2. Short explanation 3. Whether a notification should be generated 4. Concise Telegram message If the data appears incomplete or invalid, report that instead of making assumptions. If the ML system reports elevated risk, advise the user to consider appropriate professional medical evaluation rather than claiming that the user has diabetes. ``` --- # 24\. Google Sheets Database Create columns such as: ``` Timestamp Device_ID Age Glucose BloodPressure BMI HeartRate SpO2 Temperature ML_Probability Risk_Class AI_Message Alert_Status ``` Example: | Timestamp | Glucose | BMI | HR | Temp | ML Probability | Risk | | --- | --- | --- | --- | --- | --- | --- | | 08:00 | 120 | 24.5 | 76 | 36.6 | 0.21 | LOW | | 09:00 | 145 | 28.1 | 81 | 36.8 | 0.58 | MODERATE | | 10:00 | 165 | 30.2 | 88 | 37.0 | 0.76 | HIGH | --- # 25\. Telegram Notification Example normal message: ``` 🟢 HEALTH MONITORING UPDATE Device: ESP32_001 Heart Rate: 76 BPM SpO2: 98% Temperature: 36.6°C ML Risk Probability: 21% Status: LOW No automated alert is required. ``` Warning: ``` 🟠 HEALTH MONITORING ALERT The latest measurements produced an elevated ML risk estimate. Please review the recorded measurements and consider appropriate medical follow-up. This system is a screening/monitoring aid and is not a medical diagnosis. ``` High-risk workflow: ``` 🔴 ATTENTION REQUIRED The latest data has produced a high-risk prediction from the configured ML model. Please review the measurements and seek appropriate professional medical advice. This automated message does not constitute a diagnosis. ``` --- # 26\. Telegram Voice Alert The workflow can be: ``` ML Prediction ↓ Risk = HIGH ↓ AI Agent creates message ↓ Text-to-Speech service ↓ Audio file ↓ Telegram Bot ↓ Voice message ``` Example: ``` "Attention. The latest health measurements have produced an elevated risk prediction. Please review your measurements and consider contacting a qualified healthcare professional." ``` The exact text-to-speech implementation can be selected according to the services available in your deployment. --- # 27\. Complete Agentic IoT Workflow ``` ┌──────────────┐ │ ESP32 │ └──────┬───────┘ │ Sensor Measurements │ ▼ ┌──────────────┐ │ Wi-Fi │ └──────┬───────┘ │ ▼ ┌──────────────┐ │ n8n │ │ Webhook │ └──────┬───────┘ │ ▼ ┌──────────────┐ │ Data Validate │ └──────┬───────┘ │ ▼ ┌──────────────┐ │ ML Prediction │ └──────┬───────┘ │ ▼ ┌──────────────┐ │ AI Agent │ └──────┬───────┘ │ ┌────────┴────────┐ │ │ ▼ ▼ Normal/Low Elevated │ │ ▼ ▼ Log Information Generate Alert │ ┌──────────┼──────────┐ ▼ ▼ ▼ Sheet Telegram Voice │ │ │ └──────────┴──────────┘ │ ▼ User Response ``` --- # 28\. Telegram Chat Interface The system can also accept commands: ``` USER /start BOT Welcome to AI Health Monitor. Commands: /status /latest /prediction /history /help ``` ### Example ``` USER: /status BOT: ESP32_001 Heart Rate: 78 BPM SpO2: 97% Temperature: 36.7°C Latest ML Risk: LOW Last update: 10:42 AM ``` Another example: ``` USER: /prediction BOT: Latest prediction: Risk probability: 0.32 Classification: LOW This is an automated ML screening result and is not a medical diagnosis. ``` --- # 29\. Bidirectional Agentic Architecture The more advanced version allows the user to communicate back to the system. ``` ┌──────────────┐ │ USER │ └──────┬───────┘ │ Telegram │ ▼ ┌──────────────┐ │ Telegram Bot │ └──────┬───────┘ │ ▼ ┌──────────────┐ │ n8n │ └──────┬───────┘ │ ▼ ┌───────────┐ │ AI Agent │ └─────┬─────┘ │ ┌──────────┼──────────┐ ▼ ▼ ▼ Status Prediction History │ │ │ └──────────┼──────────┘ ▼ Response │ ▼ Telegram ``` This is what makes the project more **agentic** rather than simply a sensor + alert system. --- # 30\. Data Security Because this involves health-related information, security should be included in the project. Recommended measures: - HTTPS for API communication. - Do not hard-code Telegram bot tokens into publicly shared code. - Store credentials in environment variables or n8n credentials. - Authenticate API requests. - Use device IDs and authentication tokens. - Avoid exposing Google Sheets publicly. - Restrict access to dashboards. - Do not transmit unnecessary personally identifiable information. - Keep logs protected. - Use encrypted communication wherever possible. Example: ``` ESP32 │ │ HTTPS ▼ Authenticated API │ ▼ n8n │ ├── secured credentials ├── ML service ├── Google Sheets └── Telegram ``` --- # 31\. Failure Handling A professional project should demonstrate what happens when something fails. ### Wi-Fi failure ``` ESP32 ↓ Wi-Fi disconnected ↓ Retry connection ↓ Store temporary reading ↓ Reconnect ↓ Upload buffered data ``` ### n8n failure ``` ESP32 ↓ API unavailable ↓ Retry ↓ Log error ↓ Continue local monitoring ``` ### Invalid sensor data ``` Sensor ↓ Invalid reading ↓ Validation ↓ Reject value ↓ Retry sensor ``` ### AI service unavailable ``` ML result available ↓ AI service unavailable ↓ Use predefined safe notification template ↓ Continue logging ``` This is particularly important because **an AI agent should not become a single point of failure**. --- # 32\. Complete Project Flowchart ``` START │ ▼ Initialize ESP32 │ ▼ Initialize Sensors │ ▼ Connect Wi-Fi │ ┌─────┴─────┐ │ Connected?│ └─────┬─────┘ No │ Yes │ │ └───┘ Retry │ ▼ Read Sensors │ ▼ Validate Values │ ┌──────┴──────┐ │ Valid Data? │ └──────┬───────┘ │ Yes │ No │ │ │ Retry ▼ Send IoT Data │ ▼ n8n Webhook │ ▼ Preprocess Data │ ▼ ML Prediction │ ▼ AI Agent │ ▼ Decision Engine │ ┌─────────┼─────────┐ ▼ ▼ ▼ LOW MODERATE HIGH │ │ │ └─────────┼─────────┘ ▼ Google Sheets │ ▼ ThingSpeak │ ▼ Telegram Alert │ ▼ Voice Notification │ ▼ Repeat ``` --- # 33. Recommended Project Folder Structure ``` AI-Diabetes-IoT/ │ ├── README.md │ ├── esp32/ │ ├── esp32_main.ino │ ├── sensors.h │ └── config.h │ ├── ml/ │ ├── diabetes.csv │ ├── train_model.py │ ├── evaluate_model.py │ └── diabetes_model.pkl │ ├── backend/ │ ├── main.py │ ├── requirements.txt │ └── models/ │ ├── web/ │ ├── index.html │ ├── style.css │ └── app.js │ ├── n8n/ │ └── diabetes_iot_workflow.json │ ├── telegram/ │ └── bot_logic.md │ ├── docs/ │ ├── architecture.md │ ├── hardware.md │ ├── software.md │ ├── testing.md │ └── project_report.md │ └── diagrams/ ├── system_architecture.png ├── flowchart.png └── circuit.png ``` --- # 34\. Testing Plan | Test | Input | Expected Result | | --- | --- | --- | | ESP32 boot | Power ON | Device starts | | Wi-Fi | Correct credentials | Connected | | Sensor | Valid measurement | Reading displayed | | API | Valid JSON | HTTP success | | ML | Valid features | Prediction generated | | Invalid input | Missing feature | Validation error | | n8n | Webhook data | Workflow executes | | Google Sheets | Valid record | Row inserted | | ThingSpeak | Valid fields | Graph updated | | Telegram | Alert condition | Message delivered | | Voice | High-risk workflow | Audio notification | | Network loss | Disconnect Wi-Fi | Retry/recovery | --- # 35\. Performance Metrics ### Machine Learning Report: ``` Accuracy Precision Recall F1-score ROC-AUC Confusion Matrix ``` ### IoT Measure: ``` Sensor sampling interval API latency n8n workflow execution time Telegram notification latency Packet loss Wi-Fi reconnection time ``` ### System Measure: ``` End-to-end latency Sensor reading ↓ Cloud ↓ n8n ↓ ML ↓ AI Agent ↓ Telegram Total response time = ______ seconds ``` --- # 36\. Advantages - Combines AI, ML and IoT. - ESP32 provides a low-cost IoT platform. - Automated workflow reduces manual monitoring. - Historical data can be stored automatically. - ThingSpeak provides visualization. - Google Sheets provides simple data analysis/export. - Telegram enables remote notifications. - Voice alerts improve accessibility. - AI-agent architecture allows natural-language interaction. - Modular design allows additional sensors and models. --- # 37\. Limitations A good academic report should explicitly acknowledge: 1. The system is not a medical diagnostic device. 2. ML performance depends heavily on the training dataset. 3. Dataset bias can affect predictions. 4. Consumer sensors may not provide clinically validated measurements. 5. Internet connectivity is required for cloud automation. 6. AI-generated explanations may be imperfect. 7. Threshold-based alerts are not equivalent to clinical decision-making. 8. Personal health data requires careful security and privacy management. --- # 38\. Future Enhancements The system can later be extended with: ``` Continuous glucose monitoring integration ↓ Mobile application ↓ Wearable device ↓ Federated learning ↓ Personalized ML models ↓ Anomaly detection ↓ Long-term trend analysis ↓ Voice-based AI assistant ↓ Multilingual Telegram assistant ↓ Doctor/caregiver dashboard ``` An advanced version could use: ``` ESP32 ↓ MQTT ↓ IoT Broker ↓ n8n ↓ AI Agent ↓ Tool Calling ├── ML prediction ├── Database ├── Google Sheets ├── ThingSpeak └── Telegram ``` --- # 39\. Final System Architecture The strongest version of the project can therefore be presented as: ``` ┌───────────────────┐ │ USER │ └─────────┬─────────┘ │ ┌─────────────┴─────────────┐ │ │ ▼ ▼ Web Dashboard Telegram │ │ │ │ └─────────────┬─────────────┘ ▼ ┌──────────────────┐ │ n8n │ │ Automation Layer │ └────────┬─────────┘ │ ┌─────────────┼──────────────┐ │ │ │ ▼ ▼ ▼ ESP32 IoT ML Model AI Agent │ │ │ │ └──────┬───────┘ │ │ ▼ ▼ Sensor Data Decision │ │ └──────────┬─────────┘ ▼ ┌──────────────┐ │ Cloud Storage│ └──────┬───────┘ │ ┌───────────┴───────────┐ ▼ ▼ Google Sheets ThingSpeak │ ▼ Cloud Dashboard AI Agent │ ┌────────────┴────────────┐ ▼ ▼ Telegram Text Voice Alert ``` ## 40\. Suggested Final Project Name For your **project report, PPT, GitHub repository and viva**, I recommend using one consistent title: > **“AI-Powered IoT-Based Diabetes Risk Prediction and Health Monitoring System Using ESP32, Machine Learning and n8n Agentic Automation with Telegram Voice Alerts”** This title captures the complete project without making the stronger—and medically inappropriate—claim that the system itself diagnoses diabetes. If you are building this as a **college/final-year project**, the documentation can be organized into **Chapter 1: Introduction, Chapter 2: Literature Survey, Chapter 3: Requirements, Chapter 4: System Design, Chapter 5: Hardware Design, Chapter 6: ML Model, Chapter 7: ESP32 Programming, Chapter 8: n8n/AI Agent, Chapter 9: Telegram/Cloud Integration, Chapter 10: Implementation, Chapter 11: Testing & Results, Chapter 12: Conclusion and Future Scope**, followed by references and appendices.

Project Summary

AI-Powered IoT-Based Diabetes Risk Prediction and Health Monitoring System combines Machine Learning, ESP32 IoT, n8n automation, an AI agent, Telegram alerts, Google Sheets, ThingSpeak, and a web dashboard into one automated healthcare-monitoring prototype.

Core workflow

ESP32 Sensors / Web Input
          ↓
       Wi-Fi
          ↓
    ThingSpeak / API
          ↓
        n8n
          ↓
   Data Validation
          ↓
   ML Diabetes-Risk Model
          ↓
       AI Agent
          ↓
   Decision / Risk Level
     ↙      ↓       ↘
  Normal  Warning    High
     ↓      ↓         ↓
     └──────┼─────────┘
            ↓
      Google Sheets
            +
       ThingSpeak
            +
        Telegram
            ↓
       Voice Alert

Main components

  • ESP32: collects IoT measurements and communicates over Wi-Fi.

  • Machine Learning: predicts diabetes risk from features such as glucose, BMI, age, blood pressure, etc.

  • Web application: allows users to enter patient/model inputs and view IoT data.

  • n8n: coordinates the complete automation workflow.

  • AI Agent: interprets ML results and generates appropriate responses/notifications.

  • ThingSpeak: provides cloud-based IoT visualization and historical graphs.

  • Google Sheets: maintains a simple historical database.

  • Telegram: delivers text and voice notifications.

  • Sensors: examples include MAX30102, DS18B20, OLED, buzzer and status LED.

ML component

A dataset such as the Pima Indians Diabetes Database can be used for academic model development. Candidate algorithms include:

  • Logistic Regression

  • Random Forest

  • Decision Tree

  • SVM

  • KNN

  • Gradient Boosting

Evaluate the model using accuracy, precision, recall, F1-score, ROC-AUC and a confusion matrix.

Important design principle

The ML model should make the statistical prediction, while the AI agent interprets and communicates the result. The AI agent should not independently diagnose diabetes.

Final project outcome

The completed system demonstrates an end-to-end Agentic IoT architecture:

Sense → Transmit → Predict → Reason → Automate → Store → Visualize → Alert

For an academic project, describe it as a diabetes-risk screening/monitoring prototype, not as a clinically validated diagnostic system.

 

AI Battery State of Charge Estimation System

AI Battery State-of-Charge Estimation & Agentic IoT System

Below is a complete reference design for an ESP32-based AI Battery State-of-Charge (SOC) monitoring system integrating:

  • ESP32

  • Battery voltage/current/temperature sensing

  • SOC estimation

  • Optional AI/ML SOC correction

  • Local ESP32 IoT webpage

  • n8n automation

  • n8n AI Agent

  • Telegram text + voice alerts

  • Google Sheets data logging

  • ThingSpeak cloud dashboard

  • Fault/anomaly detection

  • Historical analysis

  • Remote monitoring

The architecture is deliberately designed so that the ESP32 remains capable of measuring and estimating SOC locally, while n8n acts as the cloud automation and AI-agent layer.

n8n is suitable for this because it provides workflow automation, integrations and AI functionality. n8n Documentation


1. Project Title

AI-Powered Battery State-of-Charge Estimation and Agentic IoT Monitoring System Using ESP32, n8n, Telegram Voice Alerts, Google Sheets and ThingSpeak


2. Abstract

This project implements an intelligent battery-monitoring system using an ESP32 microcontroller.

The ESP32 continuously measures:

  • Battery voltage

  • Battery current

  • Battery temperature

  • Estimated State of Charge (SOC)

  • Charging/discharging status

  • Battery power

  • Energy consumed

  • Energy returned during charging

The measurements are processed locally by the ESP32 using a hybrid SOC estimation algorithm based on:

  1. Battery voltage

  2. Coulomb counting

  3. Battery current

  4. Temperature compensation

  5. Optional AI/ML correction

The ESP32 publishes the measurements through Wi-Fi to an n8n automation server.

n8n acts as the central Agentic IoT orchestration layer.

The n8n workflow can:

  • Receive ESP32 measurements

  • Validate sensor data

  • Calculate additional battery parameters

  • Store measurements in Google Sheets

  • Update ThingSpeak

  • Send Telegram notifications

  • Generate Telegram voice alerts

  • Invoke an AI Agent

  • Detect abnormal battery behavior

  • Explain the reason for an alert

  • Recommend an action

  • Maintain alert history

  • Respond to Telegram commands

The result is an end-to-end IoT architecture:

Battery → Sensors → ESP32 → Wi-Fi → n8n → AI Agent → Cloud/Telegram/Dashboard


3. Main Objectives

The system has the following objectives.

Primary objectives

  • Measure battery voltage accurately.

  • Measure charge/discharge current.

  • Measure battery temperature.

  • Estimate battery SOC.

  • Display real-time battery information.

  • Store historical measurements.

  • Detect abnormal battery conditions.

  • Automatically notify the user.

  • Provide voice alerts.

  • Provide cloud visualization.

  • Use an AI Agent for intelligent interpretation.

Secondary objectives

The system can also:

  • Estimate remaining energy.

  • Detect unusually high current.

  • Detect rapid SOC loss.

  • Detect overheating.

  • Detect sensor failures.

  • Detect battery disconnection.

  • Detect charging problems.

  • Generate maintenance recommendations.


4. Important Design Principle

The AI Agent should not be the only source of battery safety decisions.

A robust architecture is:

                 ┌──────────────────────────────┐
                 │     HARD REAL-TIME LAYER     │
                 │                              │
Battery ────────►│ ESP32 + Sensors              │
                 │                              │
                 │ Voltage                      │
                 │ Current                      │
                 │ Temperature                  │
                 │ SOC estimator                │
                 │ Safety thresholds            │
                 └──────────────┬───────────────┘
                                │
                                ▼
                 ┌──────────────────────────────┐
                 │      CLOUD/AI LAYER          │
                 │                              │
                 │ n8n                          │
                 │ AI Agent                     │
                 │ Historical analysis          │
                 │ Recommendations              │
                 └──────────────┬───────────────┘
                                │
              ┌─────────────────┼──────────────────┐
              ▼                 ▼                  ▼
        Telegram            Google Sheets      ThingSpeak
        Text/Voice          Data Logging       Dashboard

The ESP32 should therefore continue to protect the system using deterministic thresholds even if:

  • Wi-Fi fails

  • n8n fails

  • the AI API is unavailable

  • Telegram is unavailable

  • the Internet connection is lost


5. Recommended Battery Configuration

For the reference implementation, use:

4S Li-ion battery pack

Nominal voltage:

4 × 3.7 V = 14.8 V

Typical voltage range:

Fully charged ≈ 16.8 V
Nominal ≈ 14.8 V
Discharged region ≈ 12 V

Use a proper 4S BMS.

Do not connect an unprotected lithium battery pack to the experimental circuit.

The same architecture can be adapted for:

  • 1S Li-ion

  • 2S Li-ion

  • 3S Li-ion

  • 4S Li-ion

  • LiFePO4

  • Lead-acid

  • AGM

  • other battery chemistries

However, the voltage/SOC lookup curve must be changed according to the chemistry.


6. System Block Diagram

                         BATTERY PACK
                    ┌────────────────────┐
                    │                    │
                    │  4S Li-ion + BMS   │
                    │                    │
                    └───────┬───────┬────┘
                            │       │
                            │       │
                     Voltage       Current
                      Sensor       Sensor
                            │       │
                            ▼       ▼
                    ┌─────────────────────┐
                    │       ESP32         │
                    │                     │
                    │ ADC                 │
                    │ INA219/INA226       │
                    │ DS18B20             │
                    │                     │
                    │ SOC Algorithm       │
                    │ Energy Calculation  │
                    │ Fault Detection     │
                    └──────────┬──────────┘
                               │
                             Wi-Fi
                               │
                               ▼
                    ┌─────────────────────┐
                    │        n8n          │
                    │                     │
                    │ Webhook             │
                    │ Validation          │
                    │ AI Agent            │
                    │ Rules Engine        │
                    │ Automation           │
                    └─────┬──────┬────────┘
                          │      │
              ┌───────────┘      └─────────────┐
              ▼                                ▼
       Google Sheets                       ThingSpeak
       Historical Data                     Cloud Charts
              │
              ▼
          AI Analysis
              │
              ▼
       Telegram Bot
       ┌──────────────┐
       │ Text Alert   │
       │ Voice Alert  │
       └──────────────┘

7. Hardware Architecture

7.1 Main components

Recommended components:

Component Purpose
ESP32 DevKit Main controller
INA219 or INA226 Current/voltage monitoring
Voltage divider Battery voltage measurement
DS18B20 Battery temperature
4S BMS Battery protection
12 V/5 V buck converter ESP32 power
Battery Device under test
Resistors Voltage divider
Capacitors ADC filtering
LEDs Local status
Push button Optional reset/configuration
OLED Optional local display

8. Recommended Sensor Arrangement

A practical arrangement is:

Battery +
   │
   │
   ▼
BMS
   │
   │
   ├──────────────► Voltage measurement
   │
   ▼
INA219 / INA226
   │
   │
   ▼
Load +

Temperature sensor:

DS18B20
   │
   └──── attached thermally to battery pack

ESP32:

             ┌──────────────────┐
Voltage ────►│                  │
Current ────►│      ESP32       │──── Wi-Fi
Temperature ►│                  │
             └──────────────────┘

9. Schematic Diagram

A simplified electrical schematic is:

                    4S BATTERY
                 ┌───────────────┐
                 │               │
 BAT+ ───────────┤ +           - ├───────────────┐
                 │               │               │
                 └───────────────┘               │
                       │                         │
                       │                         │
                       ▼                         │
                  ┌─────────┐                    │
                  │  4S BMS │                    │
                  └────┬────┘                    │
                       │                          │
                 PACK+ │                          │ PACK-
                       │                          │
                       ▼                          │
                  INA219/226                     │
                 ┌────────────┐                  │
                 │            │                  │
                 │ VIN+ VIN-  │                  │
                 │            │                  │
                 └─────┬──────┘                  │
                       │                          │
                       ▼                          │
                      LOAD+                       │
                                                  │
                      LOAD- ──────────────────────┘


INA219/226
   │
   ├── VCC ───── ESP32 3.3 V
   ├── GND ───── ESP32 GND
   ├── SDA ───── GPIO 21
   └── SCL ───── GPIO 22


Battery voltage divider:

Battery +
    │
    │
   R1
    │
    ├──────────── GPIO34 / ADC
    │
   R2
    │
   GND


DS18B20:

ESP32 GPIO 4 ───── DATA
                   │
                  4.7k
                   │
                  3.3V

DS18B20:
VCC ─────────────── 3.3V
GND ─────────────── GND
DATA ────────────── GPIO4

10. Voltage Divider Calculation

ESP32 ADC input must remain within the allowed ADC range.

For a maximum battery voltage of approximately:

Vbattery(max) = 16.8 V

A suitable divider is:

R1 = 100 kΩ
R2 = 22 kΩ

Output voltage:

Vadc = Vbattery × R2 / (R1 + R2)

Therefore:

Vadc = 16.8 × 22 / 122

approximately:

Vadc ≈ 3.03 V

This provides reasonable headroom for a 3.3 V ADC system.

For production hardware, verify the actual ESP32 ADC characteristics and calibrate the divider using a precision multimeter.


11. Current Measurement

INA219/INA226 can be used for current monitoring.

Example:

Battery → Current Sensor → Load

The sensor measures:

Voltage
Current
Power

Power is:

P = V × I

For example:

V = 15.2 V
I = 2.0 A

P = 15.2 × 2
P = 30.4 W

12. Temperature Measurement

Use a DS18B20 temperature sensor.

The temperature is important because battery behavior depends strongly on temperature.

The ESP32 records:

temperature = 31.5 °C

The AI layer can detect:

Temperature increasing rapidly

rather than only:

Temperature > fixed limit

That makes the system more intelligent.


13. What Is SOC?

SOC means:

State of Charge

It represents the estimated remaining usable battery capacity.

For example:

SOC = 100 %

means approximately full.

SOC = 50 %

means approximately half of the usable capacity remains.

SOC = 10 %

means the battery is nearly depleted.

SOC is an estimate, not a direct physical measurement.


14. SOC Estimation Methods

Three methods are useful.

Method 1 — Voltage-based SOC

The battery voltage is mapped to a SOC curve.

Example:

Voltage       SOC

16.8 V       100 %
16.4 V        90 %
16.0 V        80 %
15.6 V        65 %
15.2 V        50 %
14.8 V        35 %
14.4 V        20 %
13.2 V        10 %
12.0 V         0 %

These numbers are illustrative only and must be replaced with a curve appropriate to the actual battery.

Voltage-only SOC is simple but inaccurate when the battery is under load.


15. Coulomb Counting

Coulomb counting tracks current over time.

The basic equation is:

SOCnew = SOCold - I × Δt / Capacity

where:

I = battery current
Δt = elapsed time
Capacity = battery capacity in Ah

For a 10 Ah battery:

I = 2 A
Δt = 1 hour

Consumed capacity = 2 Ah

SOC decrease = 2 / 10 × 100

SOC decrease = 20 %

Coulomb counting provides good short-term tracking but accumulates error over time.


16. Hybrid SOC Algorithm

The recommended algorithm combines:

Voltage
+
Current
+
Temperature
+
Coulomb counting

Conceptually:

             Voltage
                │
                ▼
        ┌───────────────┐
Current ─► Coulomb      │
        │ Counter       │
        └───────┬───────┘
                │
Temperature ───►│
                │
                ▼
        ┌────────────────┐
        │ Hybrid SOC     │
        │ Estimator      │
        └───────┬────────┘
                │
                ▼
              SOC %

17. AI Enhancement

The AI Agent should not simply receive:

SOC = 32 %

and guess.

Instead, provide it with a structured observation:

{
  "battery_voltage": 14.82,
  "battery_current": 3.42,
  "temperature": 36.8,
  "soc": 31.7,
  "power": 50.7,
  "charging": false,
  "soc_change_5min": -4.2,
  "temperature_change_5min": 3.5,
  "device": "BATTERY-01"
}

The AI Agent can then reason about:

  • rapid SOC loss

  • overheating

  • excessive current

  • abnormal voltage sag

  • sensor failure

  • possible battery degradation


18. AI Agent Role

The AI Agent can receive battery telemetry and produce:

{
  "severity": "WARNING",
  "alert": true,
  "reason": "Battery SOC is falling rapidly while current remains high.",
  "recommendation": "Reduce the load and inspect the battery.",
  "voice_message": "Warning. Battery charge is falling rapidly. Please reduce the load."
}

The AI Agent is therefore an interpretation and orchestration layer, not the primary electrical protection mechanism.


19. Complete Data Flow

┌───────────┐
│  Battery  │
└─────┬─────┘
      │
      ▼
┌───────────────────────┐
│ Voltage/current/temp  │
│ Sensors               │
└──────────┬────────────┘
           │
           ▼
┌───────────────────────┐
│ ESP32                 │
│                       │
│ Sensor acquisition    │
│ Filtering             │
│ SOC calculation       │
│ Energy calculation    │
│ Local safety rules    │
└──────────┬────────────┘
           │ JSON/HTTPS
           ▼
┌───────────────────────┐
│ n8n Webhook           │
└──────────┬────────────┘
           │
           ▼
┌───────────────────────┐
│ Data validation       │
└──────────┬────────────┘
           │
           ├───────────────► Google Sheets
           │
           ├───────────────► ThingSpeak
           │
           ▼
┌───────────────────────┐
│ AI Agent              │
│                       │
│ Analyze telemetry     │
│ Detect anomalies      │
│ Classify severity     │
│ Recommend action      │
└──────────┬────────────┘
           │
           ▼
      ┌────┴─────┐
      │ Alert?   │
      └────┬─────┘
           │
       YES │
           ▼
┌───────────────────────┐
│ Telegram              │
│                       │
│ Text alert            │
│ Voice alert           │
└───────────────────────┘

20. ESP32 Software Architecture

The ESP32 firmware contains these modules:

main.cpp
│
├── Wi-Fi Manager
│
├── Battery Sensor
│   ├── INA219/INA226
│   ├── Voltage ADC
│   └── DS18B20
│
├── SOC Estimator
│
├── Energy Counter
│
├── Fault Detector
│
├── HTTP Client
│
└── Local Web Server

21. ESP32 JSON Telemetry

The ESP32 sends:

{
  "device_id": "BATTERY-01",
  "voltage": 15.72,
  "current": 2.31,
  "temperature": 32.4,
  "soc": 72.5,
  "power": 36.31,
  "energy_wh": 142.6,
  "charging": false,
  "wifi_rssi": -57,
  "uptime": 8421
}

22. ESP32 Arduino Code

Install these Arduino libraries:

WiFi
WebServer
HTTPClient
ArduinoJson
Wire
Adafruit INA219
OneWire
DallasTemperature

Example firmware:

#include <WiFi.h>
#include <WebServer.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <Wire.h>
#include <Adafruit_INA219.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// --------------------------------------------------
// Wi-Fi
// --------------------------------------------------

const char* WIFI_SSID = "YOUR_WIFI";
const char* WIFI_PASSWORD = "YOUR_PASSWORD";

// n8n webhook
const char* N8N_URL =
  "https://YOUR_N8N_DOMAIN/webhook/battery";

// --------------------------------------------------
// Pins
// --------------------------------------------------

#define BATTERY_ADC_PIN 34
#define TEMP_PIN 4

// Voltage divider
const float R1 = 100000.0;
const float R2 = 22000.0;

// Battery capacity
const float BATTERY_CAPACITY_AH = 10.0;

// --------------------------------------------------
// Objects
// --------------------------------------------------

WebServer server(80);

Adafruit_INA219 ina219;

OneWire oneWire(TEMP_PIN);
DallasTemperature tempSensor(&oneWire);

// --------------------------------------------------
// Battery state
// --------------------------------------------------

float batteryVoltage = 0.0;
float batteryCurrent = 0.0;
float batteryTemperature = 0.0;
float batteryPower = 0.0;

float soc = 100.0;
float energyWh = 0.0;

unsigned long lastMeasurement = 0;
unsigned long lastUpload = 0;

// --------------------------------------------------
// Read battery voltage
// --------------------------------------------------

float readBatteryVoltage()
{
  int raw = analogRead(BATTERY_ADC_PIN);

  float adcVoltage =
      ((float)raw / 4095.0) * 3.3;

  float battery =
      adcVoltage * (R1 + R2) / R2;

  return battery;
}

// --------------------------------------------------
// Voltage based SOC
// --------------------------------------------------

float voltageSOC(float voltage)
{
  // Example curve for demonstration.
  // Replace with experimentally measured
  // curve for your battery.

  if (voltage >= 16.8) return 100.0;
  if (voltage >= 16.4) return 90.0;
  if (voltage >= 16.0) return 80.0;
  if (voltage >= 15.6) return 65.0;
  if (voltage >= 15.2) return 50.0;
  if (voltage >= 14.8) return 35.0;
  if (voltage >= 14.4) return 20.0;
  if (voltage >= 13.2) return 10.0;

  return 0.0;
}

// --------------------------------------------------
// Hybrid SOC
// --------------------------------------------------

float calculateSOC(float voltage,
                   float current,
                   float dtHours)
{
  // Coulomb counting

  float deltaSOC =
      (current * dtHours /
       BATTERY_CAPACITY_AH) * 100.0;

  // Positive current = discharge
  soc -= deltaSOC;

  soc = constrain(soc, 0.0, 100.0);

  // Voltage correction.
  //
  // Stronger correction when current is low,
  // because loaded battery voltage is less
  // representative of open-circuit voltage.

  if (fabs(current) < 0.3)
  {
    float voltageSOCValue =
        voltageSOC(voltage);

    soc =
      0.85 * soc +
      0.15 * voltageSOCValue;
  }

  return soc;
}

// --------------------------------------------------
// Read sensors
// --------------------------------------------------

void readSensors()
{
  batteryVoltage =
      readBatteryVoltage();

  batteryCurrent =
      ina219.getCurrent_mA() / 1000.0;

  batteryPower =
      batteryVoltage *
      batteryCurrent;

  tempSensor.requestTemperatures();

  batteryTemperature =
      tempSensor.getTempCByIndex(0);
}

// --------------------------------------------------
// Local fault detection
// --------------------------------------------------

String detectFault()
{
  if (batteryTemperature >= 55.0)
    return "OVER_TEMPERATURE";

  if (batteryVoltage < 12.0)
    return "LOW_VOLTAGE";

  if (batteryCurrent > 10.0)
    return "OVER_CURRENT";

  if (soc < 10.0)
    return "LOW_SOC";

  return "NORMAL";
}

// --------------------------------------------------
// Send data to n8n
// --------------------------------------------------

void sendToN8N()
{
  if (WiFi.status() != WL_CONNECTED)
    return;

  HTTPClient http;

  http.begin(N8N_URL);

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

  StaticJsonDocument<512> doc;

  doc["device_id"] = "BATTERY-01";
  doc["voltage"] = batteryVoltage;
  doc["current"] = batteryCurrent;
  doc["temperature"] = batteryTemperature;
  doc["soc"] = soc;
  doc["power"] = batteryPower;
  doc["energy_wh"] = energyWh;

  doc["charging"] =
      batteryCurrent < -0.1;

  doc["fault"] =
      detectFault();

  doc["wifi_rssi"] =
      WiFi.RSSI();

  doc["uptime"] =
      millis() / 1000;

  String payload;

  serializeJson(doc, payload);

  int response =
      http.POST(payload);

  Serial.print("n8n HTTP response: ");
  Serial.println(response);

  http.end();
}

// --------------------------------------------------
// Webpage
// --------------------------------------------------

String htmlPage()
{
  String html = R"rawliteral(

<!DOCTYPE html>

<html>

<head>

<meta name="viewport"
content="width=device-width, initial-scale=1">

<title>AI Battery Monitor</title>

<style>

body {
  font-family: Arial;
  background:#101820;
  color:white;
  text-align:center;
}

.card {
  background:#1d2b36;
  margin:15px;
  padding:20px;
  border-radius:15px;
}

.value {
  font-size:32px;
  color:#00e5ff;
}

.warning {
  color:#ffcc00;
}

.danger {
  color:#ff4444;
}

</style>

</head>

<body>

<h1>AI Battery Monitor</h1>

<div class="card">
<h2>Battery Voltage</h2>
<div class="value">
)rawliteral";

  html += String(batteryVoltage, 2);

  html += R"rawliteral(
 V
</div>
</div>

<div class="card">
<h2>Current</h2>
<div class="value">
)rawliteral";

  html += String(batteryCurrent, 2);

  html += R"rawliteral(
 A
</div>
</div>

<div class="card">
<h2>Temperature</h2>
<div class="value">
)rawliteral";

  html += String(batteryTemperature, 1);

  html += R"rawliteral(
 °C
</div>
</div>

<div class="card">
<h2>State of Charge</h2>
<div class="value">
)rawliteral";

  html += String(soc, 1);

  html += R"rawliteral(
 %
</div>
</div>

<div class="card">
<h2>Status</h2>
<div class="value">
)rawliteral";

  html += detectFault();

  html += R"rawliteral(
</div>
</div>

</body>

</html>

)rawliteral";

  return html;
}

// --------------------------------------------------
// Web server
// --------------------------------------------------

void handleRoot()
{
  server.send(
      200,
      "text/html",
      htmlPage());
}

// --------------------------------------------------
// Setup
// --------------------------------------------------

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

  Wire.begin();

  ina219.begin();

  tempSensor.begin();

  analogReadResolution(12);

  WiFi.begin(
      WIFI_SSID,
      WIFI_PASSWORD);

  Serial.print("Connecting WiFi");

  while (
      WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }

  Serial.println();

  Serial.print("ESP32 IP: ");
  Serial.println(WiFi.localIP());

  server.on(
      "/",
      handleRoot);

  server.begin();

  lastMeasurement = millis();
  lastUpload = millis();
}

// --------------------------------------------------
// Main loop
// --------------------------------------------------

void loop()
{
  server.handleClient();

  unsigned long now = millis();

  if (now - lastMeasurement >= 1000)
  {
    float dtHours =
        (now - lastMeasurement)
        / 3600000.0;

    lastMeasurement = now;

    readSensors();

    soc =
        calculateSOC(
          batteryVoltage,
          batteryCurrent,
          dtHours);

    energyWh +=
        batteryPower * dtHours;

    Serial.println("--------------------");

    Serial.print("Voltage: ");
    Serial.println(batteryVoltage);

    Serial.print("Current: ");
    Serial.println(batteryCurrent);

    Serial.print("Temperature: ");
    Serial.println(batteryTemperature);

    Serial.print("SOC: ");
    Serial.println(soc);

    Serial.print("Fault: ");
    Serial.println(detectFault());
  }

  if (now - lastUpload >= 15000)
  {
    lastUpload = now;

    sendToN8N();
  }
}

23. Important ESP32 Code Note

The example voltage/SOC table is deliberately a starting point.

Do not use it as a battery-management safety curve.

For an actual product, characterize the battery experimentally.

Measure:

Voltage
Current
Temperature
Discharged Ah

over several discharge cycles.

Then generate a battery-specific SOC curve.


24. Local IoT Webpage

The ESP32 creates a webpage such as:

http://192.168.1.50/

The page displays:

┌──────────────────────────────────┐
│       AI BATTERY MONITOR         │
├──────────────────────────────────┤
│                                  │
│ Voltage             15.72 V      │
│                                  │
│ Current              2.31 A      │
│                                  │
│ Temperature         32.4 °C      │
│                                  │
│ SOC                  72.5 %      │
│                                  │
│ Power                36.3 W      │
│                                  │
│ Status               NORMAL      │
│                                  │
└──────────────────────────────────┘

25. Improved Web Dashboard

For a more professional dashboard, use JavaScript polling:

ESP32
   │
   ▼
/api/status
   │
   ▼
JavaScript
   │
   ├── Voltage gauge
   ├── Current gauge
   ├── SOC gauge
   ├── Temperature
   └── Status indicator

Example API response:

{
  "voltage": 15.72,
  "current": 2.31,
  "temperature": 32.4,
  "soc": 72.5,
  "power": 36.3,
  "status": "NORMAL"
}

26. n8n Architecture

The n8n workflow should be divided into logical stages.

Webhook
   │
   ▼
Validate Data
   │
   ▼
Normalize Data
   │
   ├──────────────► Google Sheets
   │
   ├──────────────► ThingSpeak
   │
   ▼
Rule Engine
   │
   ▼
AI Agent
   │
   ▼
Decision
   │
   ├── NORMAL → Log only
   │
   ├── WARNING → Telegram
   │
   └── CRITICAL → Telegram + Voice

n8n's Telegram integration provides Telegram automation capabilities, while unsupported operations can also be accessed through HTTP/API calls. n8n Documentation


27. n8n Workflow Nodes

Create the following nodes.

Node 1

Webhook

Name:

Battery Telemetry Webhook

HTTP method:

POST

Path:

battery

Your ESP32 sends:

POST /webhook/battery

Node 2

Code / Function

Name:

Validate Telemetry

Example:

const d = $json;

const required = [
  "device_id",
  "voltage",
  "current",
  "temperature",
  "soc"
];

for (const key of required) {
  if (d[key] === undefined) {
    throw new Error(`Missing field: ${key}`);
  }
}

if (d.voltage < 0 || d.voltage > 100) {
  throw new Error("Invalid voltage");
}

if (d.soc < 0 || d.soc > 100) {
  throw new Error("Invalid SOC");
}

return [{
  json: {
    ...d,
    timestamp: new Date().toISOString(),
    valid: true
  }
}];

28. Data Normalization Node

Calculate:

power
SOC category
temperature status
battery status

Example:

const d = $json;

const power =
  Number(d.voltage) *
  Number(d.current);

let socStatus = "NORMAL";

if (d.soc <= 10) {
  socStatus = "CRITICAL";
}
else if (d.soc <= 20) {
  socStatus = "WARNING";
}

let temperatureStatus = "NORMAL";

if (d.temperature >= 55) {
  temperatureStatus = "CRITICAL";
}
else if (d.temperature >= 45) {
  temperatureStatus = "WARNING";
}

return [{
  json: {
    ...d,
    power,
    socStatus,
    temperatureStatus
  }
}];

29. Google Sheets

Create a spreadsheet:

AI Battery Monitoring

Worksheet:

Telemetry

Columns:

Timestamp
Device ID
Voltage
Current
Temperature
SOC
Power
Energy Wh
Charging
Fault
WiFi RSSI
AI Severity
AI Recommendation

Example:

2026-10-06 06:00
BATTERY-01
15.72
2.31
32.4
72.5
36.3
142.6
FALSE
NORMAL
-57
NORMAL
No action required

This creates a simple historical database.


30. ThingSpeak Integration

ThingSpeak can store numerical IoT data and provide charts.

ThingSpeak supports REST APIs for writing channel data. MathWorks+1

Create a channel called:

AI Battery Monitor

Configure:

Field 1 = Battery Voltage
Field 2 = Current
Field 3 = Temperature
Field 4 = SOC
Field 5 = Power
Field 6 = Energy
Field 7 = Battery Status

The ThingSpeak REST endpoint can be updated using HTTP POST/GET. MathWorks


31. ThingSpeak n8n HTTP Request

Create an n8n:

HTTP Request

Method:

POST

URL:

https://api.thingspeak.com/update.json

Parameters:

api_key = YOUR_WRITE_API_KEY

field1 = {{$json.voltage}}

field2 = {{$json.current}}

field3 = {{$json.temperature}}

field4 = {{$json.soc}}

field5 = {{$json.power}}

field6 = {{$json.energy_wh}}

ThingSpeak returns the created entry information when the update succeeds; a failed update returns 0. MathWorks


32. ThingSpeak Dashboard

The cloud dashboard can contain:

┌────────────────────────────────────┐
│       AI BATTERY CLOUD             │
├────────────────────────────────────┤
│                                    │
│ SOC                                │
│ ███████████████████░░░ 72 %        │
│                                    │
│ Voltage                            │
│ ────────────────╮                 │
│                 ╰────────           │
│                                    │
│ Current                            │
│ ────────────╮                     │
│             ╰────────               │
│                                    │
│ Temperature                        │
│ ────────────────                   │
│                                    │
└────────────────────────────────────┘

ThingSpeak supports both REST and MQTT approaches for channel updates; REST is particularly useful when you need HTTP request/response behavior. MathWorks


33. AI Agent

The n8n AI Agent receives the normalized battery data.

Example prompt:

You are an intelligent battery monitoring agent.

Analyze the battery telemetry.

Your responsibilities are:

1. Determine whether the battery is NORMAL,
   WARNING, or CRITICAL.

2. Look for:
   - Low SOC
   - Rapid SOC decrease
   - High temperature
   - Excessive current
   - Abnormal voltage
   - Voltage sag
   - Sensor failure
   - Charging anomalies

3. Do not invent sensor values.

4. Do not claim that a battery is safe when
   sensor information is insufficient.

5. Return valid JSON only.

Return:

{
  "severity": "NORMAL|WARNING|CRITICAL",
  "alert": true/false,
  "reason": "...",
  "recommendation": "...",
  "voice_message": "..."
}

34. Example AI Input

{
  "device_id": "BATTERY-01",
  "voltage": 13.4,
  "current": 5.8,
  "temperature": 48.2,
  "soc": 14.3,
  "power": 77.72,
  "charging": false,
  "soc_change_5min": -11.4
}

35. Example AI Output

{
  "severity": "WARNING",
  "alert": true,
  "reason": "SOC is low and decreasing rapidly while the battery is supplying a high load.",
  "recommendation": "Reduce the load and recharge the battery.",
  "voice_message": "Warning. Battery charge is low and decreasing rapidly. Please reduce the load and recharge the battery."
}

36. AI Agent Decision Flow

             Battery Data
                  │
                  ▼
          ┌───────────────┐
          │ AI Agent      │
          └───────┬───────┘
                  │
       ┌──────────┼───────────┐
       │          │           │
       ▼          ▼           ▼
    NORMAL     WARNING     CRITICAL
       │          │           │
       ▼          ▼           ▼
    Log only   Telegram    Telegram
               message     message
                              │
                              ▼
                         Voice Alert

37. Rule Engine

The AI should work together with deterministic rules.

Example:

SOC < 20%
       ↓
WARNING

SOC < 10%
       ↓
CRITICAL

Temperature > 45°C
       ↓
WARNING

Temperature > 55°C
       ↓
CRITICAL

Current > configured maximum
       ↓
CRITICAL

The exact thresholds must be configured for the particular battery, BMS and load.


38. Rapid SOC Drop Detection

One of the useful AI features is detecting:

SOC = 80%

followed shortly by:

SOC = 65%

while the current is normal.

The AI Agent can investigate:

Possible causes:
- incorrect SOC calibration
- battery degradation
- sensor error
- unexpected load
- voltage sag

39. Telegram Integration

Create a Telegram bot using BotFather.

The bot receives:

/battery
/status
/soc
/temperature
/history
/help

The Telegram Bot API supports sending voice messages using sendVoice. Telegram Core


40. Telegram Text Alert

Example:

🔋 BATTERY ALERT

Device: BATTERY-01

SOC: 14.3%
Voltage: 13.40 V
Current: 5.80 A
Temperature: 48.2 °C

Severity: WARNING

Reason:
SOC is low and decreasing rapidly.

Recommendation:
Reduce the load and recharge the battery.

41. Telegram Voice Alert

The n8n workflow can generate speech from:

voice_message

For example:

Warning. Battery charge is low and decreasing rapidly.
Please reduce the load and recharge the battery.

The generated audio is then passed to Telegram as a voice message.

Telegram's API specifically distinguishes voice messages from ordinary audio files. Telegram Core


42. Voice Alert Architecture

AI Agent
   │
   ▼
voice_message
   │
   ▼
Text-to-Speech
   │
   ▼
MP3/OGG audio
   │
   ▼
n8n Binary Data
   │
   ▼
Telegram Send Voice
   │
   ▼
User's phone

A TTS provider can be connected through an n8n integration or HTTP Request node.


43. Telegram Example Conversation

USER:
 /battery

BOT:
🔋 Battery Status

SOC: 72.5%
Voltage: 15.72 V
Current: 2.31 A
Temperature: 32.4°C
Power: 36.3 W

Status: NORMAL

Then:

USER:
/temperature

BOT:

🌡 Battery Temperature

Current: 32.4°C
Status: NORMAL

44. AI Telegram Conversation

A more advanced system can allow natural-language questions.

USER:

Why is my battery draining quickly?

The AI Agent can receive recent telemetry and answer:

The battery has dropped approximately
11% in the last 5 minutes.

The current load is 5.8 A and the
temperature is 48.2°C.

The most likely reason is high load
combined with low remaining capacity.

Recommendation:
Reduce the load and recharge the battery.

45. Complete n8n Workflow

Recommended workflow:

                  ┌──────────────┐
                  │ ESP32        │
                  └──────┬───────┘
                         │
                         ▼
                 ┌───────────────┐
                 │ Webhook       │
                 └──────┬────────┘
                        │
                        ▼
                 ┌───────────────┐
                 │ Validate      │
                 └──────┬────────┘
                        │
                        ▼
                 ┌───────────────┐
                 │ Normalize     │
                 └──────┬────────┘
                        │
           ┌────────────┼──────────────┐
           │            │              │
           ▼            ▼              ▼
     Google Sheets  ThingSpeak     Database
           │            │              │
           └────────────┼──────────────┘
                        │
                        ▼
                 ┌───────────────┐
                 │ Rule Engine   │
                 └──────┬────────┘
                        │
                        ▼
                 ┌───────────────┐
                 │ AI Agent      │
                 └──────┬────────┘
                        │
                        ▼
                 ┌───────────────┐
                 │ Parse JSON     │
                 └──────┬────────┘
                        │
                        ▼
                  ┌────────────┐
                  │ Alert?     │
                  └─────┬──────┘
                        │
               ┌────────┴────────┐
               │                 │
              NO                YES
               │                 │
               ▼                 ▼
             Finish       Telegram Text
                                 │
                                 ▼
                             TTS Engine
                                 │
                                 ▼
                           Telegram Voice

46. Recommended n8n Nodes

A practical workflow can contain:

1. Webhook
2. Code – Validate Data
3. Code – Calculate Derived Values
4. Google Sheets – Append Row
5. HTTP Request – ThingSpeak
6. IF – Safety Threshold
7. AI Agent
8. Structured Output Parser
9. IF – Alert Required
10. Telegram – Send Message
11. HTTP Request/TTS
12. Telegram – Send Voice
13. Respond to Webhook

47. AI Agent Tools

The AI Agent can be given tools such as:

Tool 1:
Get latest battery status

Tool 2:
Get recent historical data

Tool 3:
Get Google Sheets history

Tool 4:
Send Telegram notification

Tool 5:
Update device configuration

Tool 6:
Get ThingSpeak data

This is what makes the architecture more agentic rather than simply a fixed automation workflow.


48. Agentic IoT Architecture

Traditional IoT:

Sensor
  ↓
Cloud
  ↓
Dashboard

Agentic IoT:

Sensor
  ↓
ESP32
  ↓
Telemetry
  ↓
AI Agent
  ↓
Observe
  ↓
Reason
  ↓
Decide
  ↓
Act
  ↓
Notify / Log / Recommend

For example:

OBSERVE:
SOC = 12%
Temperature = 49°C
Current = 6A

REASON:
Low SOC + high temperature + high load

DECIDE:
WARNING

ACT:
Send Telegram notification
Generate voice alert
Record event

49. Battery Fault Classification

The system can classify:

NORMAL
LOW_SOC
HIGH_TEMPERATURE
OVER_CURRENT
LOW_VOLTAGE
RAPID_SOC_DROP
SENSOR_ERROR
COMMUNICATION_ERROR
POSSIBLE_BATTERY_DEGRADATION

50. Sensor Failure Detection

Suppose:

Voltage = 15.7 V
Current = 0 A
Temperature = -127°C

The ESP32/AI layer should recognize:

Temperature sensor failure

instead of reporting:

Battery temperature = -127°C

Similarly:

Voltage = 0 V
Current = 0 A

could indicate:

Battery disconnected

rather than necessarily meaning:

Battery is empty

51. Battery Degradation Detection

Over multiple cycles, record:

Cycle number
Maximum capacity
Minimum voltage
Temperature
Internal resistance estimate
SOC error

Suppose:

Cycle 1  → 10.0 Ah
Cycle 50 → 9.2 Ah
Cycle 100 → 8.4 Ah
Cycle 150 → 7.8 Ah

The AI Agent can identify:

Capacity is decreasing over time.
Possible battery degradation.

52. Internal Resistance Estimation

If load current changes rapidly:

ΔV
───
ΔI

can provide an approximate resistance:

R ≈ ΔV / ΔI

For example:

Before load:
V1 = 15.8 V

After load:
V2 = 15.2 V

Current change:
ΔI = 5 A

R ≈ 0.6 / 5
R ≈ 0.12 Ω

This should be treated as an estimate because wiring resistance, sensor delay, battery temperature and dynamic battery behavior also influence the measurement.


53. AI Anomaly Detection

Historical features can include:

SOC
Voltage
Current
Temperature
Power
Voltage sag
SOC derivative
Temperature derivative
Estimated resistance

The AI layer can detect patterns such as:

Normal:
SOC slowly decreases
Temperature stable
Voltage stable

versus:

Abnormal:
SOC rapidly decreases
Temperature rises rapidly
Voltage sag increases

54. Optional Machine-Learning SOC Model

For a more advanced academic/project implementation, collect thousands of samples.

Dataset:

timestamp
voltage
current
temperature
power
previous_soc
time_delta
measured_capacity
true_soc

Train a regression model:

Inputs:

Voltage
Current
Temperature
Power
Time
Previous SOC

          ↓

ML Model

          ↓

Estimated SOC

55. ML Training Pipeline

Battery Test
     │
     ▼
Data Logger
     │
     ▼
CSV Dataset
     │
     ▼
Python
     │
     ▼
Data Cleaning
     │
     ▼
Feature Engineering
     │
     ▼
ML Training
     │
     ▼
Validation
     │
     ▼
Model
     │
     ├── ESP32 TinyML
     │
     └── n8n/cloud inference

56. Example Python Training Code

A simple prototype can use Random Forest regression:

import pandas as pd

from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error
import joblib

# Load dataset

df = pd.read_csv("battery_dataset.csv")

features = [
    "voltage",
    "current",
    "temperature",
    "power"
]

X = df[features]
y = df["true_soc"]

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.2,
    random_state=42
)

model = RandomForestRegressor(
    n_estimators=200,
    random_state=42
)

model.fit(X_train, y_train)

prediction = model.predict(X_test)

mae = mean_absolute_error(
    y_test,
    prediction
)

print("MAE:", mae)

joblib.dump(
    model,
    "battery_soc_model.pkl"
)

The result can be evaluated using:

MAE
RMSE
R²

57. AI SOC Architecture

An advanced system can combine:

Coulomb SOC
       │
       ├─────────┐
       │         │
Voltage SOC      │
       │         │
       └────┬────┘
            │
            ▼
       ML Correction
            │
            ▼
        Final SOC

For example:

Coulomb SOC = 67%
Voltage SOC = 63%
ML estimate = 65%

Final SOC = 65%

The exact fusion algorithm should be validated against experimentally measured capacity.


58. Why Hybrid SOC Is Better

Voltage-only:

Simple
but load-sensitive

Coulomb-only:

Good short-term tracking
but accumulates error

AI-only:

Can model nonlinear behavior
but requires good training data

Hybrid:

Voltage
+
Coulomb counting
+
Temperature
+
ML correction

provides a much stronger engineering approach.


59. Complete Communication Architecture

             BATTERY
                │
                ▼
             ESP32
                │
          HTTPS / JSON
                │
                ▼
             n8n
                │
     ┌──────────┼────────────┐
     │          │            │
     ▼          ▼            ▼
 Google      ThingSpeak     AI
 Sheets                     Agent
                              │
                         ┌────┴─────┐
                         │          │
                         ▼          ▼
                     Telegram     TTS
                         │          │
                         └────┬─────┘
                              ▼
                       Voice Alert

60. Security

Do not hard-code production secrets into publicly shared firmware.

Avoid:

const char* API_KEY = "my-real-key";

in code that will be uploaded to GitHub.

Use:

Environment variables
Secret manager
n8n credentials
Device-specific credentials

At minimum:

HTTPS
Webhook authentication
Telegram bot token protection
ThingSpeak API key protection
Wi-Fi credentials protection

61. ESP32 → n8n Authentication

A better approach than an open webhook is:

ESP32
  │
  │ Authorization: Bearer DEVICE_SECRET
  ▼
n8n

The ESP32 sends:

Authorization: Bearer YOUR_DEVICE_SECRET
Content-Type: application/json

n8n verifies the secret before accepting telemetry.


62. Example ESP32 Authentication

Add:

http.addHeader(
  "Authorization",
  "Bearer YOUR_DEVICE_SECRET"
);

Then n8n validates it.

For production systems, use device-specific credentials rather than one global token.


63. Telegram Security

Only allow authorized users.

The workflow should verify:

Telegram chat_id

against an allowlist.

Example:

AUTHORIZED_CHAT_ID_1
AUTHORIZED_CHAT_ID_2

If an unknown user sends:

/status

the bot should respond:

Unauthorized user.

64. Google Sheets Security

Do not make the spreadsheet public unless the project specifically requires it.

Recommended:

Private Sheet
      ↓
n8n authenticated account
      ↓
Append telemetry

65. ThingSpeak Security

Keep the Write API Key private.

Use:

ESP32 → n8n → ThingSpeak

rather than exposing the ThingSpeak write key unnecessarily on the ESP32.

ThingSpeak provides separate channel/API mechanisms for reading and writing channel data. MathWorks


66. Testing Procedure

Test 1 — ESP32 boot

Expected:

ESP32 starts
Wi-Fi connects
IP address displayed

Test 2 — Voltage

Use a multimeter.

Compare:

Multimeter = 15.72 V
ESP32 = 15.70 V

Calculate error:

Error =
|15.72 - 15.70| / 15.72 × 100

Test 3 — Current

Use a calibrated current meter.

Compare:

Reference = 2.30 A
ESP32 = 2.31 A

67. Temperature Test

Place the sensor on the battery.

Compare against a trusted thermometer.

Test:

Room temperature
Warm battery
High-load condition

68. SOC Calibration Test

Start from a known full battery.

Record:

100%

Then discharge using a controlled load.

Record:

95%
90%
85%
...
10%
5%

Calculate actual consumed Ah.

Generate the battery-specific SOC curve.


69. n8n Testing

Send test JSON manually:

{
  "device_id": "TEST-01",
  "voltage": 13.2,
  "current": 5.5,
  "temperature": 49,
  "soc": 12,
  "power": 72.6,
  "energy_wh": 120,
  "charging": false
}

Expected:

Webhook
 ↓
Validation
 ↓
Google Sheets
 ↓
ThingSpeak
 ↓
AI Agent
 ↓
WARNING
 ↓
Telegram

70. Critical Alert Test

Send:

{
  "device_id": "TEST-01",
  "voltage": 11.8,
  "current": 8.2,
  "temperature": 58,
  "soc": 5
}

Expected:

Severity = CRITICAL

Then:

Telegram text
+
Telegram voice

should be generated.


71. Network Failure Test

Turn off Wi-Fi.

Expected:

ESP32 continues measuring
ESP32 continues calculating SOC
Local webpage may remain available if local network is available
Cloud upload fails

The firmware should not crash because the cloud service is unavailable.


72. n8n Failure Test

Stop n8n.

Expected:

ESP32 continues operating

When n8n returns:

ESP32 reconnects
Telemetry resumes

A production version can add local buffering in ESP32 flash/SD card.


73. Recommended Offline Buffer

Advanced ESP32 architecture:

Sensor
 ↓
SOC
 ↓
RAM buffer
 ↓
Wi-Fi available?
 ├── YES → Upload
 └── NO  → Store locally

Then:

Wi-Fi returns
     ↓
Upload buffered records

74. Final Project Flowchart

              START
                │
                ▼
        Initialize ESP32
                │
                ▼
        Connect to Wi-Fi
                │
                ▼
        Initialize Sensors
                │
                ▼
       Read Battery Voltage
                │
                ▼
       Read Battery Current
                │
                ▼
       Read Temperature
                │
                ▼
      Calculate Battery Power
                │
                ▼
        Calculate SOC
                │
                ▼
        Check Local Faults
                │
                ▼
         Update Webpage
                │
                ▼
       Send Telemetry to n8n
                │
                ▼
        n8n Validates Data
                │
                ▼
        Store Google Sheets
                │
                ▼
        Update ThingSpeak
                │
                ▼
          AI Agent
                │
                ▼
        Analyze Condition
                │
                ▼
        ┌───────┴────────┐
        │                │
      NORMAL           ALERT
        │                │
        ▼                ▼
       Log         Telegram Text
                         │
                         ▼
                       TTS
                         │
                         ▼
                  Telegram Voice
                         │
                         ▼
                       END

75. Complete Hardware BOM

Recommended prototype BOM:

1 × ESP32 DevKit
1 × INA219 or INA226 module
1 × DS18B20 temperature sensor
1 × 4S Li-ion battery pack
1 × 4S BMS
1 × 100 kΩ resistor
1 × 22 kΩ resistor
1 × 4.7 kΩ resistor
1 × DC-DC buck converter
1 × Fuse
1 × Prototype PCB
1 × OLED display (optional)
1 × enclosure

For high-current batteries, use a properly rated current sensor, wiring, connector, fuse and protection hardware. Do not route high battery current through a small breadboard.


76. Software BOM

Arduino IDE
ESP32 Arduino Core

Libraries:
- WiFi
- WebServer
- HTTPClient
- ArduinoJson
- Wire
- Adafruit INA219
- OneWire
- DallasTemperature

Cloud:
- n8n
- Google Sheets
- ThingSpeak
- Telegram Bot

Optional:
- AI model/API
- TTS provider
- Python
- scikit-learn
- joblib

77. Final System Architecture

                         ┌────────────────────┐
                         │   4S BATTERY/BMS   │
                         └─────────┬──────────┘
                                   │
                    ┌──────────────┼──────────────┐
                    │              │              │
                    ▼              ▼              ▼
                Voltage         Current       Temperature
                 Sensor          Sensor          DS18B20
                    │              │              │
                    └──────────────┼──────────────┘
                                   ▼
                         ┌──────────────────┐
                         │      ESP32       │
                         │                  │
                         │ Sensor Reading   │
                         │ SOC Estimation   │
                         │ Energy           │
                         │ Fault Detection  │
                         │ Web Server       │
                         └────────┬─────────┘
                                  │
                                HTTPS
                                  │
                                  ▼
                         ┌──────────────────┐
                         │       n8n        │
                         │                  │
                         │ Webhook          │
                         │ Validation       │
                         │ Automation       │
                         │ AI Agent         │
                         └───────┬──────────┘
                                 │
             ┌───────────────────┼────────────────────┐
             │                   │                    │
             ▼                   ▼                    ▼
      ┌─────────────┐     ┌─────────────┐     ┌──────────────┐
      │Google Sheets│     │ ThingSpeak  │     │  AI Agent    │
      │             │     │             │     │              │
      │History      │     │Cloud Charts │     │Reasoning     │
      │Data Logger  │     │Telemetry    │     │Anomaly       │
      └─────────────┘     └─────────────┘     └──────┬───────┘
                                                      │
                                                      ▼
                                               ┌─────────────┐
                                               │ Decision    │
                                               └──────┬──────┘
                                                      │
                                             ┌────────┴────────┐
                                             │                 │
                                           NORMAL             ALERT
                                             │                 │
                                             ▼                 ▼
                                           LOG          Telegram Text
                                                               │
                                                               ▼
                                                           TTS Engine
                                                               │
                                                               ▼
                                                        Telegram Voice

78. Expected Final Output

When the system is operating normally:

ESP32
 │
 ├─ Voltage: 15.72 V
 ├─ Current: 2.31 A
 ├─ Temperature: 32.4 °C
 ├─ SOC: 72.5 %
 └─ Power: 36.3 W

        ↓

n8n

        ↓

Google Sheets ✓
ThingSpeak ✓
AI Agent ✓
Telegram: No alert

When a problem occurs:

ESP32
 │
 ├─ Voltage: 13.4 V
 ├─ Current: 5.8 A
 ├─ Temperature: 48.2 °C
 └─ SOC: 14.3 %

        ↓

n8n

        ↓

AI Agent

        ↓

WARNING

        ↓

Telegram Text
        +
Telegram Voice

        ↓

"Warning. Battery charge is low
and decreasing rapidly. Please
reduce the load and recharge
the battery."

79. Project Advantages

This architecture combines five different technologies:

Embedded system

ESP32 measures and processes the physical battery.

IoT

Wi-Fi transfers telemetry to the cloud.

Automation

n8n connects all services.

Artificial intelligence

The AI Agent interprets telemetry and historical behavior.

Voice notification

Telegram delivers the warning as both text and voice.

Therefore, the project is more than a conventional battery monitor.

It is an:

AI-powered Agentic IoT Battery Monitoring and Decision-Support System.


80. Suggested Project/Thesis Chapter Structure

For an academic project report, use:

Chapter 1
Introduction

Chapter 2
Literature Survey

Chapter 3
System Requirements

Chapter 4
Hardware Design

Chapter 5
Battery SOC Estimation

Chapter 6
ESP32 Firmware

Chapter 7
IoT Web Interface

Chapter 8
n8n Automation

Chapter 9
AI Agent Design

Chapter 10
Telegram Voice Alert System

Chapter 11
Google Sheets Integration

Chapter 12
ThingSpeak Cloud Dashboard

Chapter 13
Testing and Results

Chapter 14
Performance Analysis

Chapter 15
Limitations

Chapter 16
Future Scope

Chapter 17
Conclusion

81. Future Enhancements

The project can be upgraded with:

✓ TinyML SOC estimation
✓ LSTM battery prediction
✓ Remaining Useful Life (RUL)
✓ Battery State of Health (SOH)
✓ Internal resistance estimation
✓ Cell-level monitoring
✓ CAN bus BMS integration
✓ MQTT
✓ OTA ESP32 firmware updates
✓ Mobile application
✓ Voice commands
✓ AI-generated maintenance reports
✓ Predictive failure detection
✓ Solar charging integration
✓ EV battery monitoring
✓ Multi-battery monitoring

For example:

Battery SOC
     +
Battery SOH
     +
Temperature
     +
Current
     +
Historical cycles
     ↓
AI Predictive Model
     ↓
Remaining Useful Life

82. Important Engineering Limitation

This project is suitable for:

  • educational projects

  • IoT prototypes

  • research

  • demonstrations

  • battery telemetry

  • non-safety-critical monitoring

It should not replace the battery manufacturer's BMS or certified protection circuitry.

The BMS remains responsible for electrical protection such as:

Overcharge
Over-discharge
Overcurrent
Short circuit
Cell imbalance
Temperature protection

The ESP32/n8n/AI system should be considered a monitoring and decision-support system, unless the entire protection architecture is engineered and certified for the intended application.


83. Final One-Line Architecture

The complete project can be summarized as:

BATTERY
   ↓
V/I/T SENSORS
   ↓
ESP32
   ↓
HYBRID SOC ESTIMATION
   ↓
Wi-Fi / HTTPS
   ↓
n8n
   ↓
AI AGENT
   ↓
┌────────────┬─────────────┬───────────────┐
│            │             │               │
Google       ThingSpeak    Telegram       AI
Sheets       Dashboard     Text/Voice      Analysis

This gives you a complete ESP32 + AI + Agentic IoT + n8n + Telegram Voice + Google Sheets + ThingSpeak battery SOC platform.

Current implementation notes

A few pieces are worth treating as production-hardening steps rather than copy/paste defaults:

  • The SOC lookup table in the firmware must be calibrated for your exact battery chemistry, capacity and discharge conditions.

  • For lithium batteries, keep the physical BMS independent of the ESP32/software layer.

  • ThingSpeak's REST API supports channel writes and historical reads, so it works well as the cloud visualization/history layer. MathWorks+1

  • Telegram's current Bot API supports sendVoice, which is the appropriate mechanism for Telegram-style voice messages. Telegram Core

  • n8n has a native Telegram integration, while HTTP Request nodes can be used for services that don't have a dedicated node. n8n Documentation

If you want to turn this into a fully buildable project, the next useful step is to define the exact battery—e.g. 12 V lead-acid, 4S Li-ion 14.8 V/16.8 V, or 4S LiFePO4—because that determines the correct SOC curve, sensor range, thresholds and calibration procedure.

Project Summary

AI-Powered Battery State-of-Charge (SOC) Estimation & Agentic IoT System is an ESP32-based smart battery-monitoring platform that combines embedded sensing, AI, cloud dashboards and automated notifications.

Core workflow

Battery
   ↓
Voltage + Current + Temperature Sensors
   ↓
ESP32
   ↓
Hybrid SOC Estimation
   ↓
Wi-Fi / HTTPS
   ↓
n8n Automation
   ↓
AI Agent
   ↓
┌──────────────┬──────────────┬──────────────┐
Google Sheets  ThingSpeak     Telegram
Data Logging   Dashboard      Text + Voice

Main functions

  • ESP32 measures battery voltage, current and temperature.

  • SOC algorithm combines voltage and coulomb counting, with optional ML correction.

  • Local IoT webpage displays real-time voltage, current, temperature, SOC, power and status.

  • n8n receives telemetry and automates the complete workflow.

  • AI Agent analyzes battery conditions and identifies anomalies such as low SOC, rapid discharge, overheating and abnormal voltage.

  • Google Sheets stores historical battery data.

  • ThingSpeak provides cloud visualization and historical graphs.

  • Telegram sends automatic text alerts.

  • Text-to-Speech + Telegram provides voice warnings.

  • Local ESP32 safety rules continue operating even if Wi-Fi, n8n or AI services fail.

Example alert

🔋 BATTERY ALERT

SOC: 14.3%
Voltage: 13.40 V
Current: 5.80 A
Temperature: 48.2 °C

Severity: WARNING

Reason:
Battery SOC is low and decreasing rapidly.

Recommendation:
Reduce the load and recharge the battery.

Advanced capabilities

The project can later be expanded to:

  • AI/ML SOC prediction

  • State of Health (SOH)

  • Remaining Useful Life (RUL)

  • Battery degradation detection

  • Internal-resistance estimation

  • Cell-level monitoring

  • Predictive failure detection

  • CAN-BMS integration

  • OTA ESP32 updates

  • Voice commands

  • Multi-battery monitoring

In short: the project transforms a conventional ESP32 battery monitor into an AI-powered Agentic IoT battery-management and notification system, with real-time monitoring, historical data, intelligent analysis and automated Telegram voice alerts.