0% found this document useful (0 votes)
17 views3 pages

ESP32 Email Alerts for Temperature

This code summarizes an ESP32 project that monitors temperature using a DS18B20 sensor, sends email alerts when the temperature exceeds a threshold, and allows configuring email settings and the threshold through a web interface. The ESP32 connects to WiFi, sets up the temperature sensor and an AsyncWebServer on port 80. It displays the current temperature on the home page and allows changing the recipient, enabling alerts, and threshold through GET requests. On each sensor reading, it checks if the temperature exceeds the threshold and sends an email if so. It also sends an email when the temperature drops below the threshold if a previous alert was sent.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views3 pages

ESP32 Email Alerts for Temperature

This code summarizes an ESP32 project that monitors temperature using a DS18B20 sensor, sends email alerts when the temperature exceeds a threshold, and allows configuring email settings and the threshold through a web interface. The ESP32 connects to WiFi, sets up the temperature sensor and an AsyncWebServer on port 80. It displays the current temperature on the home page and allows changing the recipient, enabling alerts, and threshold through GET requests. On each sensor reading, it checks if the temperature exceeds the threshold and sends an email if so. It also sends an email when the temperature drops below the threshold if a previous alert was sent.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

#include <WiFi.

h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include "ESP32_MailClient.h"

// REPLACE WITH YOUR AVAILABLE WIFI NETWORK CREDENTIALS


const char* ssid = "XXXXXXXXXX";//SSID of Wifi network
const char* password = "XXXXXXXXXX";// Password of wifi network

// To send Email using Gmail use port 465 (SSL) and SMTP Server [Link]
// YOU MUST ENABLE less secure app option [Link]
#define emailSenderAccount "XXXXXXXXXXXX"// Sender email address
#define emailSenderPassword "XXXXXXXXXXXX" // Sender email password
#define smtpServer "[Link]"
#define smtpServerPort 465
#define emailSubject "[ALERT] ESP32 Temperature" // Email subject

// Default Recipient Email Address


String inputMessage = "[Link]@[Link]"; //Reciepent email alert.
String enableEmailChecked = "checked";
String inputMessage2 = "true";
// Default Threshold Temperature Value
String inputMessage3 = "25.0";// Default temperature
String lastTemperature;

// HTML web page to handle 3 input fields (email_input, enable_email_input, threshold_input)


const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html><head>
<title>Email Notification with Temperature</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head><body>
<h2>DS18B20 Temperature</h2>
<h3>%TEMPERATURE% &deg;C</h3>
<h2>ESP Email Notification</h2>
<form action="/get">
Email Address <input type="email" name="email_input" value="%EMAIL_INPUT%" required><br>
Enable Email Notification <input type="checkbox" name="enable_email_input" value="true" %ENABLE_EMAIL%><br>
Temperature Threshold <input type="number" step="0.1" name="threshold_input" value="%THRESHOLD%" required><br>
<input type="submit" value="Submit">
</form>
</body></html>)rawliteral";

void notFound(AsyncWebServerRequest *request) {


request->send(404, "text/plain", "Not found");
}

AsyncWebServer server(80);

// Replaces placeholder with DS18B20 values


String processor(const String& var){
//[Link](var);
if(var == "TEMPERATURE"){
return lastTemperature;
}
else if(var == "EMAIL_INPUT"){
return inputMessage;
}
else if(var == "ENABLE_EMAIL"){
return enableEmailChecked;
}
else if(var == "THRESHOLD"){
return inputMessage3;
}
return String();
}

// Flag variable to keep track if email notification was sent or not


bool emailSent = false;

const char* PARAM_INPUT_1 = "email_input";


const char* PARAM_INPUT_2 = "enable_email_input";
const char* PARAM_INPUT_3 = "threshold_input";

// Interval between sensor readings.


unsigned long previousMillis = 0;
const long interval = 5000;

// GPIO where the DS18B20 is connected to


const int oneWireBus = 4;
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(oneWireBus);
// Pass our oneWire reference to Dallas Temperature sensor
DallasTemperature sensors(&oneWire);

// The Email Sending data object contains config and data to send
SMTPData smtpData;

void setup() {
[Link](115200);
[Link](WIFI_STA);
[Link](ssid, password);
if ([Link]() != WL_CONNECTED) {
[Link]("WiFi Failed!");
return;
}
[Link]();
[Link]("ESP IP Address: [Link]
[Link]([Link]());

// Start the DS18B20 sensor


[Link]();

// Send web page to client


[Link]("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html, processor);
});

// Receive an HTTP GET request at <ESP_IP>/get?email_input=<inputMessage>&enable_email_input=<inputMessage2>&threshold_input=<inputMessage3>


[Link]("/get", HTTP_GET, [] (AsyncWebServerRequest *request) {
// GET email_input value on <ESP_IP>/get?email_input=<inputMessage>
if (request->hasParam(PARAM_INPUT_1)) {
inputMessage = request->getParam(PARAM_INPUT_1)->value();
// GET enable_email_input value on <ESP_IP>/get?enable_email_input=<inputMessage2>
if (request->hasParam(PARAM_INPUT_2)) {
inputMessage2 = request->getParam(PARAM_INPUT_2)->value();
enableEmailChecked = "checked";
}
else {
inputMessage2 = "false";
enableEmailChecked = "";
}
// GET threshold_input value on <ESP_IP>/get?threshold_input=<inputMessage3>
if (request->hasParam(PARAM_INPUT_3)) {
inputMessage3 = request->getParam(PARAM_INPUT_3)->value();
}
}
else {
inputMessage = "No message sent";
}
[Link](inputMessage);
[Link](inputMessage2);
[Link](inputMessage3);
request->send(200, "text/html", "HTTP GET request sent to your ESP.<br><a href=\"/\">Return to Home Page</a>");
});
[Link](notFound);
[Link]();
}

void loop() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
[Link]();
// Temperature in Celsius degrees
float temperature = [Link](0);
[Link](temperature);
[Link](" *C");

// Temperature in Fahrenheit degrees


/*float temperature = [Link](0);
[Link](temperature);
[Link](" *F");*/

lastTemperature = String(temperature);

// Check if temperature is above threshold and if it needs to send the Email alert
if(temperature > [Link]() && inputMessage2 == "true" && !emailSent){
String emailMessage = String("Temperature above threshold. Current temperature: ") +
String(temperature) + String("C");
if(sendEmailNotification(emailMessage)) {
[Link](emailMessage);
emailSent = true;
}
else {
[Link]("Email failed to send");
}
}
// Check if temperature is below threshold and if it needs to send the Email alert
else if((temperature < [Link]()) && inputMessage2 == "true" && emailSent) {
String emailMessage = String("Temperature below threshold. Current temperature: ") +
String(temperature) + String(" C");
if(sendEmailNotification(emailMessage)) {
[Link](emailMessage);
emailSent = false;
}
else {
[Link]("Email failed to send");
}
}
}
}

bool sendEmailNotification(String emailMessage){


// Set the SMTP Server Email host, port, account and password
[Link](smtpServer, smtpServerPort, emailSenderAccount, emailSenderPassword);

// For library version 1.2.0 and later which STARTTLS protocol was supported,the STARTTLS will be
// enabled automatically when port 587 was used, or enable it manually using setSTARTTLS function.
//[Link](true);

// Set the sender name and Email


[Link]("ESP32_ElectronicsInnovation", emailSenderAccount);
// Set Email priority or importance High, Normal, Low or 1 to 5 (1 is highest)
[Link]("High");

// Set the subject


[Link](emailSubject);

// Set the message with HTML format


[Link](emailMessage, true);

// Add recipients
[Link](inputMessage);

[Link](sendCallback);

// Start sending Email, can be set callback function to track the status
if (![Link](smtpData)) {
[Link]("Error sending Email, " + [Link]());
return false;
}
// Clear all data from Email object to free memory
[Link]();
return true;
}

// Callback function to get the Email sending status


void sendCallback(SendStatus msg) {
// Print the current status
[Link]([Link]());

// Do something when complete


if ([Link]()) {
[Link]("----------------");
}
}

Common questions

Powered by AI

The ESP32 manages and processes temperature data from the DS18B20 sensor using the OneWire library to communicate with the sensor and the DallasTemperature library to obtain temperature readings. The setup function initializes the sensor with `sensors.begin()`, and within the main loop, the temperatures are requested using `sensors.requestTemperatures()`. The latest temperature in Celsius is retrieved using `sensors.getTempCByIndex(0)`, and stored as a string in `lastTemperature`. This data can be accessed and displayed on the web interface or compared against the threshold for email alerts .

The ESP32 system can be extended to include more sensors, such as humidity or pressure sensors, that augment its environmental monitoring capabilities. Implementing real-time data visualization could also be added through more sophisticated web interfaces or dashboards. Integrating with IoT platforms like AWS IoT Core or Azure can enhance its ability to manage and analyze data. Additionally, utilizing more secure methods for credential storage and management, such as using secure elements or hardware modules for encryption, can improve security. Adding support for more advanced email protocols and services that do not require insecure access might also be beneficial for a secure deployment .

The ESP32 handles email notifications based on temperature readings through the use of the DallasTemperature library for sensor interaction and SMTP protocols for email communication. Notifications are triggered when the temperature exceeds a specified threshold stored in `inputMessage3`, and notifications are enabled (`inputMessage2` is 'true'). If the temperature exceeds this threshold and notifications are enabled, the program constructs an email message stating that the "Temperature is above threshold" and sends it using the `sendEmailNotification` function. If the temperature drops below the threshold and an alert email has already been sent, another email is sent to notify that the "Temperature is below threshold." Email notifications are only sent if the condition changes and `emailSent` is correctly toggled to avoid repetitive sending .

In the Arduino sketch, the `PROGMEM` keyword indicates that specific data, in this case, the HTML content (`index_html`), should be stored in Flash (program) memory instead of RAM. This is critical in memory-constrained environments like microcontrollers, where conserving RAM is a priority. By storing constant data such as web page templates in Flash, the ESP32 can prevent its limited RAM from being overwhelmed by large data structures or strings, ensuring more memory is available for dynamic operations and other processes .

The ESP32 handles network connectivity by initiating a Wi-Fi connection using the credentials provided (`ssid` and `password`). It sets the Wi-Fi mode to station (WiFi.mode(WIFI_STA)) and attempts to connect. If the connection attempt fails (WiFi.waitForConnectResult() != WL_CONNECTED), the setup function prints "WiFi Failed!" to the serial output and halts further execution, effectively preventing any web server functionality or sensor data collection from initializing. This prevents proceeding with operations requiring network access until connection is successfully established .

The security considerations in using this ESP32 email system include managing credentials such as the email account and password, which are hardcoded in the program. The use of Gmail as the SMTP server requires enabling 'less secure apps,' which can pose a security risk by allowing less authenticated methods of accessing accounts. Furthermore, embedding credentials directly within the code may expose these sensitive details to unauthorized users if the code is shared or compromised. This necessitates employing encryption or keeping sensitive data hidden and only accessible at runtime. Additionally, the handling of SSL/TLS protocols and proper validation of server certificates is crucial to prevent man-in-the-middle attacks when sending emails .

The `sendCallback` function serves as a callback to track the status of the email-sending process. It is invoked by the MailClient library to provide information on the success or failure of email transmission. As messages are processed, the function outputs the current status and, upon successful completion, prints confirmation markers to the console. This allows the developer to monitor and debug the email-sending operation, ensuring that issues can be identified and addressed promptly .

Choosing an email service and protocol for the ESP32 notification system involves several considerations, such as security, reliability, and ease of integration. Using Gmail involves configuring "less secure app" access, which may not meet security policies in professional or sensitive deployments due to weaker authentication methods. Protocols like SMTP with SSL/TLS are essential for secure communications but may add complexity. The selection of an email provider should also consider the provider's API limits, throughput capabilities, and response times. Compatibility with the ESP32 libraries and support for REST APIs or token-based authentication instead of hardcoded passwords could enhance security and performance .

The ESP32 serves a web page to the client using the ESPAsyncWebServer library. This process involves specifying routes and handling HTTP requests. When a GET request is made to the root URL ('/'), the ESP32 sends an HTML page (`index_html`) to the client. This page is processed with placeholders replaced by current values such as temperature, email settings, and threshold values. For parameterized requests like `/get`, the parameters are extracted from the request, and values are updated accordingly. If a request doesn't match any defined route, the `notFound` function returns a 404 error. This server logic enables dynamic interactions between the client and server, updating configurations in real-time .

The system uses a boolean flag `emailSent` to ensure email notifications are not sent repeatedly for the same temperature condition. When a notification is triggered due to the temperature crossing the threshold, `emailSent` is set to `true`, thereby preventing any subsequent emails from being sent under the same condition. The flag is reset to `false` if the temperature falls back below the threshold, thereby allowing a new notification to be sent if the condition occurs again. This toggling logic ensures that emails are only sent when the condition changes, preventing redundant notifications .

You might also like