0% found this document useful (0 votes)
65 views

Sourcecode - EnlighterJS Syntax Highlighter

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
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
65 views

Sourcecode - EnlighterJS Syntax Highlighter

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
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

#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 smtp.gmail.com
// YOU MUST ENABLE less secure app option https://myaccount.google.com/lesssecureapps?pli=1
#define emailSenderAccount "XXXXXXXXXXXX"// Sender email address
#define emailSenderPassword "XXXXXXXXXXXX" // Sender email password
#define smtpServer "smtp.gmail.com"
#define smtpServerPort 465
#define emailSubject "[ALERT] ESP32 Temperature" // Email subject

// Default Recipient Email Address


String inputMessage = "[email protected]"; //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){
//Serial.println(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() {
Serial.begin(115200);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.println("WiFi Failed!");
return;
}
Serial.println();
Serial.print("ESP IP Address: http://");
Serial.println(WiFi.localIP());

// Start the DS18B20 sensor


sensors.begin();

// Send web page to client


server.on("/", 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>


server.on("/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";
}
Serial.println(inputMessage);
Serial.println(inputMessage2);
Serial.println(inputMessage3);
request->send(200, "text/html", "HTTP GET request sent to your ESP.<br><a href=\"/\">Return to Home Page</a>");
});
server.onNotFound(notFound);
server.begin();
}

void loop() {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
sensors.requestTemperatures();
// Temperature in Celsius degrees
float temperature = sensors.getTempCByIndex(0);
Serial.print(temperature);
Serial.println(" *C");

// Temperature in Fahrenheit degrees


/*float temperature = sensors.getTempFByIndex(0);
SerialMon.print(temperature);
SerialMon.println(" *F");*/

lastTemperature = String(temperature);

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

bool sendEmailNotification(String emailMessage){


// Set the SMTP Server Email host, port, account and password
smtpData.setLogin(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.
//smtpData.setSTARTTLS(true);

// Set the sender name and Email


smtpData.setSender("ESP32_ElectronicsInnovation", emailSenderAccount);
// Set Email priority or importance High, Normal, Low or 1 to 5 (1 is highest)
smtpData.setPriority("High");

// Set the subject


smtpData.setSubject(emailSubject);

// Set the message with HTML format


smtpData.setMessage(emailMessage, true);

// Add recipients
smtpData.addRecipient(inputMessage);

smtpData.setSendCallback(sendCallback);

// Start sending Email, can be set callback function to track the status
if (!MailClient.sendMail(smtpData)) {
Serial.println("Error sending Email, " + MailClient.smtpErrorReason());
return false;
}
// Clear all data from Email object to free memory
smtpData.empty();
return true;
}

// Callback function to get the Email sending status


void sendCallback(SendStatus msg) {
// Print the current status
Serial.println(msg.info());

// Do something when complete


if (msg.success()) {
Serial.println("----------------");
}
}

You might also like