#include <Arduino.h>
#if defined(ESP32) || defined(ARDUINO_RASPBERRY_PI_PICO_W)
#include <WiFi.h>
#elif defined(ESP8266)
#include <ESP8266WiFi.h>
#elif __has_include(<WiFiNINA.h>)
#include <WiFiNINA.h>
#elif __has_include(<WiFi101.h>)
#include <WiFi101.h>
#elif __has_include(<WiFiS3.h>)
#include <WiFiS3.h>
#endif
#define ESP_DRD_USE_SPIFFS true
#include <ESP_Mail_Client.h>
// File System Library
#include <FS.h>
// SPI Flash Syetem Library
#include <SPIFFS.h>
// WiFiManager Library
#include <WiFiManager.h>
// Arduino JSON library
#include <ArduinoJson.h>
#include <HTTPClient.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
// Variables to save date and time
String formattedDate;
String dayStamp;
String timeStamp;
String date_time;
// JSON configuration file
#define JSON_CONFIG_FILE "/test_config.json"
// Flag for saving data
bool shouldSaveConfig = false;
// Variables to hold data from custom textboxes
char receiver_email_id[100] = "[email protected]";
char sender_email_id[100] = "[email protected]";
char sender_password[40] = "Alerts@123";
// char sender_email_id[100] = "[email protected]";
// char sender_password[40] = "Alpha@0404";
// char device_id[35] = "000000000000000000000000000000";
//char device_id[40] = "00000000000U01TL015KV100AH0001";
char device_id[40] = "0000000000000000A303B30ANDH210";
// Define WiFiManager Object
WiFiManager wm;
/** For Gmail, the app password will be used for log in
* Check out https://github.com/mobizt/ESP-Mail-Client#gmail-smtp-and-imap-required-app-passwords-to-sign-in
*
* For Yahoo mail, log in to your yahoo mail in web browser and generate app password by go to
* https://login.yahoo.com/account/security/app-passwords/add/confirm?src=noSrc
*
* To use Gmai and Yahoo's App Password to sign in, define the AUTHOR_PASSWORD with your App Password
* and AUTHOR_EMAIL with your account email.
*/
/** The smtp host name e.g. smtp.gmail.com for GMail or smtp.office365.com for Outlook or smtp.mail.yahoo.com */
//#define SMTP_HOST "smtp.gmail.com"
// #define SMTP_HOST "smtpout.secureserver.net"
#define SMTP_HOST "smtpout.asia.secureserver.net"
/** The smtp port e.g.
* 25 or esp_mail_smtp_port_25
* 425 or esp_mail_smtp_port_465
* 587 or esp_mail_smtp_port_587
*/
#define SMTP_PORT esp_mail_smtp_port_465 // port 465 is not available for Outlook.com
/* Declare the global used SMTPSession object for SMTP transport */
SMTPSession smtp;
/* Callback function to get the Email sending status */
void smtpCallback(SMTP_Status status);
#if defined(ARDUINO_RASPBERRY_PI_PICO_W)
WiFiMulti multi;
#endif
#define RXD2 16
#define TXD2 17
char incoming_char = 0;
String content = "";
bool isValid = false;
int num = 0;
void saveConfigFile()
// Save Config in JSON format
{
Serial.println(F("Saving configuration..."));
// Create a JSON document
StaticJsonDocument<512> json;
json["receiver_email_id"] = receiver_email_id;
json["sender_email_id"] = sender_email_id;
json["sender_password"] = sender_password;
json["device_id"] = device_id;
// Open config file
File configFile = SPIFFS.open(JSON_CONFIG_FILE, "w");
if (!configFile) {
// Error, file did not open
Serial.println("failed to open config file for writing");
}
// Serialize JSON data to write to file
serializeJsonPretty(json, Serial);
if (serializeJson(json, configFile) == 0) {
// Error writing file
Serial.println(F("Failed to write to file"));
}
// Close file
configFile.close();
}
bool loadConfigFile()
// Load existing configuration file
{
// Uncomment if we need to format filesystem
// SPIFFS.format();
// Read configuration from FS json
Serial.println("Mounting File System...");
// May need to make it begin(true) first time you are using SPIFFS
if (SPIFFS.begin(false) || SPIFFS.begin(true)) {
Serial.println("mounted file system");
if (SPIFFS.exists(JSON_CONFIG_FILE)) {
// The file exists, reading and loading
Serial.println("reading config file");
File configFile = SPIFFS.open(JSON_CONFIG_FILE, "r");
if (configFile) {
Serial.println("Opened configuration file");
StaticJsonDocument<512> json;
DeserializationError error = deserializeJson(json, configFile);
serializeJsonPretty(json, Serial);
if (!error) {
Serial.println("Parsing JSON");
strcpy(receiver_email_id, json["receiver_email_id"]);
strcpy(sender_email_id, json["sender_email_id"]);
strcpy(sender_password, json["sender_password"]);
strcpy(device_id, json["device_id"]);
return true;
} else {
// Error loading JSON data
Serial.println("Failed to load json config");
}
}
}
} else {
// Error mounting file system
Serial.println("Failed to mount FS");
}
return false;
}
void saveConfigCallback()
// Callback notifying us of the need to save configuration
{
Serial.println("Should save config");
shouldSaveConfig = true;
}
void configModeCallback(WiFiManager *myWiFiManager)
// Called when config mode launched
{
Serial.println("Entered Configuration Mode");
Serial.print("Config SSID: ");
Serial.println(myWiFiManager->getConfigPortalSSID());
Serial.print("Config IP Address: ");
Serial.println(WiFi.softAPIP());
}
#define LEAP_YEAR(Y) ( (Y>0) && !(Y%4) && ( (Y%100) || !(Y%400) ) )
// Based on https://github.com/PaulStoffregen/Time/blob/master/Time.cpp
// currently assumes UTC timezone, instead of using this->_timeOffset
String getFormattedDate(unsigned long secs) {
unsigned long rawTime = (secs ? secs : timeClient.getEpochTime()) / 86400L; // in days
unsigned long days = 0, year = 1970;
uint8_t month;
static const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31};
while((days += (LEAP_YEAR(year) ? 366 : 365)) <= rawTime)
year++;
rawTime -= days - (LEAP_YEAR(year) ? 366 : 365); // now it is days in this year, starting at 0
days=0;
for (month=0; month<12; month++) {
uint8_t monthLength;
if (month==1) { // february
monthLength = LEAP_YEAR(year) ? 29 : 28;
} else {
monthLength = monthDays[month];
}
if (rawTime < monthLength) break;
rawTime -= monthLength;
}
String monthStr = ++month < 10 ? "0" + String(month) : String(month); // jan is month 1
String dayStr = ++rawTime < 10 ? "0" + String(rawTime) : String(rawTime); // day of month
return String(year) + "-" + monthStr + "-" + dayStr + "T" + this->getFormattedTime(secs ? secs : 0) + "Z";
}
String get_date_time(void) {
String final;
int tryNTP = 0;
while (!timeClient.update() || (tryNTP > 10)) {
timeClient.forceUpdate();
tryNTP++;
}
if (tryNTP >= 10) {
Serial.print("Failed to get NTP , hence set default as 00: ");
final = "1970-01-01 01:00:00";
return final;
}
// The formattedDate comes with the following format:
// 2018-05-28T16:00:13Z
// We need to extract date and time
formattedDate = getFormattedDate();
// Serial.println(formattedDate);
// Extract date
int splitT = formattedDate.indexOf("T");
dayStamp = formattedDate.substring(0, splitT);
// Serial.print("DATE: ");
// Serial.println(dayStamp);
// Extract time
timeStamp = formattedDate.substring(splitT + 1, formattedDate.length() - 1);
// Serial.print("HOUR: ");
// Serial.println(timeStamp);
final = dayStamp + " " + timeStamp;
Serial.print("FINAL TIME STAMP: ");
Serial.println(final);
return final;
}
void post_ups_data_to_cloud() {
//Send an HTTP POST request
//Check WiFi connection status
Serial.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
Serial.println("%% post_ups_data_to_cloud %%");
Serial.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
if (WiFi.status() == WL_CONNECTED) {
Serial.println("WiFi Connected");
IPAddress result;
int err = WiFi.hostByName("www.google.com", result);
if (err == 1) {
Serial.print("IP address: ");
Serial.println(result);
Serial.println("Internet Available");
} else {
Serial.print("Error code: ");
Serial.println(err);
Serial.println("Internet not available");
delay(1000);
ESP.restart();
}
WiFiClient client;
HTTPClient http;
Serial.println("WiFi Connected - post http");
const char *serverName = "http://iot.alphaconnect.ai/postdevicenewrawdata.php";
// Your Domain name with URL path or IP address with path
http.begin(client, serverName);
// If you need Node-RED/server authentication, insert user and password below
//http.setAuthorization("REPLACE_WITH_SERVER_USERNAME", "REPLACE_WITH_SERVER_PASSWORD");
// Specify content-type header
http.addHeader("Content-Type", "application/json");
// Data to send with HTTP POST
date_time = get_date_time();
String httpRequestData = "{\"raw_data\" :\"" + content + "\",\"rawdata_readtime\" :\"" + date_time + "\"}";
Serial.print("HTTP Request: ");
Serial.println(httpRequestData);
// Send HTTP POST request
int httpResponseCode = http.POST(httpRequestData);
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
// Free resources
http.end();
} else {
Serial.println("WiFi Disconnected");
}
}
boolean count = false;
void setup_wifi() {
// Change to true when testing to force configuration every time we run
bool forceConfig = false;
bool spiffsSetup = loadConfigFile();
if (!spiffsSetup) {
Serial.println(F("Forcing config mode as there is no saved config"));
forceConfig = true;
}
// Explicitly set WiFi mode
WiFi.mode(WIFI_STA);
// // Reset settings (only for development)
// wm.resetSettings(); //daya
// Set config save notify callback
wm.setSaveConfigCallback(saveConfigCallback);
// Set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
wm.setAPCallback(configModeCallback);
// // Text box (Number) - 7 characters maximum
// WiFiManagerParameter custom_text_box_num("key_num", "Receiver email ID", convertedValue, 7);
WiFiManagerParameter custom_text_box_receiver("key_text1", "Receiver email ID", receiver_email_id, 100);
WiFiManagerParameter custom_text_box_sender("key_text2", "Sender email ID", sender_email_id, 100);
WiFiManagerParameter custom_text_box_sender_password("key_text3", "Sender password:", sender_password, 40);
WiFiManagerParameter custom_text_box_device_id("key_text4", "Device ID", device_id, 100);
// Add all defined parameters
wm.addParameter(&custom_text_box_receiver);
wm.addParameter(&custom_text_box_sender);
wm.addParameter(&custom_text_box_sender_password);
wm.addParameter(&custom_text_box_device_id);
if (forceConfig)
// Run if we need a configuration
{
if (!wm.startConfigPortal("NEWTEST_AP", "password")) {
Serial.println("failed to connect and hit timeout");
delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.restart();
delay(5000);
}
} else {
// if (!wm.autoConnect("NEWTEST_AP", "password")) {
if (!wm.autoConnect()) {
Serial.println("failed to connect and hit timeout");
delay(3000);
// if we still have not connected restart and try all over again
if (!wm.autoConnect("NEWTEST_AP", "password")) {
delay(1000);
ESP.restart();
delay(5000);
}
// ESP.restart();
// delay(5000);
}
}
// If we get here, we are connected to the WiFi
Serial.println("");
Serial.print("WiFi connected: ");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Lets deal with the user config values
strncpy(sender_email_id, custom_text_box_sender.getValue(), sizeof(sender_email_id));
// Serial.print("sender_email_id: ");
// Serial.println(sender_email_id);
strncpy(receiver_email_id, custom_text_box_receiver.getValue(), sizeof(receiver_email_id));
// Serial.print("receiver_email_id: ");
// Serial.println(receiver_email_id);
strncpy(sender_password, custom_text_box_sender_password.getValue(), sizeof(sender_password));
// Serial.print("sender_password: ");
// Serial.println(sender_password);
strncpy(device_id, custom_text_box_device_id.getValue(), sizeof(device_id));
// Serial.print("device_id: ");
// Serial.println(device_id);
// Save the custom parameters to FS
if (shouldSaveConfig) {
saveConfigFile();
}
}
void setup() {
// Setup Serial monitor
Serial.begin(9600);
delay(10);
setup_wifi();
Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
Serial.println("ESP32 hardware serial test on Serial2 RECEIVER");
Serial.println("Txd is on pin: " + String(TXD2));
Serial.println("Rxd is on pin: " + String(RXD2));
// Initialize a NTPClient to get time
timeClient.begin();
// Set offset time in seconds to adjust for your timezone, for example:
// GMT +1 = 3600
// GMT +8 = 28800
// GMT -1 = -3600
// GMT 0 = 0
timeClient.setTimeOffset(3600 * 5.5); //5.5 for IST
}
int notify_fault_via_email(char *tr_alert_subject, char *tr_alert_email_msg) {
/* Set the network reconnection option */
MailClient.networkReconnect(true);
// The WiFi credentials are required for Pico W
// due to it does not have reconnect feature.
#if defined(ARDUINO_RASPBERRY_PI_PICO_W)
MailClient.clearAP();
// MailClient.addAP(WIFI_SSID, WIFI_PASSWORD);
MailClient.addAP(wm.getWiFiSSID(), WiFi.psk());
#endif
/** Enable the debug via Serial port
* 0 for no debugging
* 1 for basic level debugging
*
* Debug port can be changed via ESP_MAIL_DEFAULT_DEBUG_PORT in ESP_Mail_FS.h
*/
smtp.debug(1);
/* Set the callback function to get the sending results */
smtp.callback(smtpCallback);
/* Declare the Session_Config for user defined session credentials */
Session_Config config;
/* Set the session config */
config.server.host_name = SMTP_HOST;
config.server.port = SMTP_PORT;
Serial.print(" sender_email_id:__");
Serial.print(sender_email_id);
Serial.println("__");
config.login.email = sender_email_id;
config.login.password = sender_password;
/** Assign your host name or you public IPv4 or IPv6 only
* as this is the part of EHLO/HELO command to identify the client system
* to prevent connection rejection.
* If host name or public IP is not available, ignore this or
* use loopback address "127.0.0.1".
*
* Assign any text to this option may cause the connection rejection.
*/
config.login.user_domain = F("127.0.0.1");
/** If non-secure port is prefered (not allow SSL and TLS connection), use
* config.secure.mode = esp_mail_secure_mode_nonsecure;
*
* If SSL and TLS are always required, use
* config.secure.mode = esp_mail_secure_mode_ssl_tls;
*
* To disable SSL permanently (use less program space), define ESP_MAIL_DISABLE_SSL in ESP_Mail_FS.h
* or Custom_ESP_Mail_FS.h
*/
// config.secure.mode = esp_mail_secure_mode_nonsecure;
/*
Set the NTP config time
For times east of the Prime Meridian use 0-12
For times west of the Prime Meridian add 12 to the offset.
Ex. American/Denver GMT would be -6. 6 + 12 = 18
See https://en.wikipedia.org/wiki/Time_zone for a list of the GMT/UTC timezone offsets
*/
config.time.ntp_server = F("pool.ntp.org,time.nist.gov");
config.time.gmt_offset = 3;
config.time.day_light_offset = 0;
/* The full message sending logs can now save to file */
/* Since v3.0.4, the sent logs stored in smtp.sendingResult will store only the latest message logs */
// config.sentLogs.filename = "/path/to/log/file";
// config.sentLogs.storage_type = esp_mail_file_storage_type_flash;
/** In ESP32, timezone environment will not keep after wake up boot from sleep.
* The local time will equal to GMT time.
*
* To sync or set time with NTP server with the valid local time after wake up boot,
* set both gmt and day light offsets to 0 and assign the timezone environment string e.g.
config.time.ntp_server = F("pool.ntp.org,time.nist.gov");
config.time.gmt_offset = 0;
config.time.day_light_offset = 0;
config.time.timezone_env_string = "JST-9"; // for Tokyo
* The library will get (sync) the time from NTP server without GMT time offset adjustment
* and set the timezone environment variable later.
*
* This timezone environment string will be stored to flash or SD file named "/tze.txt"
* which set via config.time.timezone_file.
*
* See the timezone environment string list from
* https://github.com/nayarsystems/posix_tz_db/blob/master/zones.csv
*
*/
/* Declare the message class */
SMTP_Message message;
/* Set the message headers */
message.sender.name = F("ALPHA POWER SOLUTIONS");
message.sender.email = sender_email_id;
// In case of sending non-ASCII characters in message envelope,
// that non-ASCII words should be encoded with proper charsets and encodings
// in form of `encoded-words` per RFC2047
// https://datatracker.ietf.org/doc/html/rfc2047
String subject = String(tr_alert_subject);
message.subject = subject;
message.addRecipient(F("Someone alphaconnect"), receiver_email_id);
String textMsg = String(tr_alert_email_msg);
message.text.content = textMsg;
/** The content transfer encoding e.g.
* enc_7bit or "7bit" (not encoded)
* enc_qp or "quoted-printable" (encoded)
* enc_base64 or "base64" (encoded)
* enc_binary or "binary" (not encoded)
* enc_8bit or "8bit" (not encoded)
* The default value is "7bit"
*/
message.text.transfer_encoding = "base64"; // recommend for non-ASCII words in message.
/** If the message to send is a large string, to reduce the memory used from internal copying while sending,
* you can assign string to message.text.blob by cast your string to uint8_t array like this
*
* String myBigString = "..... ......";
* message.text.blob.data = (uint8_t *)myBigString.c_str();
* message.text.blob.size = myBigString.length();
*
* or assign string to message.text.nonCopyContent, like this
*
* message.text.nonCopyContent = myBigString.c_str();
*
* Only base64 encoding is supported for content transfer encoding in this case.
*/
/** The Plain text message character set e.g.
* us-ascii
* utf-8
* utf-7
* The default value is utf-8
*/
message.text.charSet = F("utf-8"); // recommend for non-ASCII words in message.
// If this is a reply message
// message.in_reply_to = "<parent message id>";
// message.references = "<parent references> <parent message id>";
/** The message priority
* esp_mail_smtp_priority_high or 1
* esp_mail_smtp_priority_normal or 3
* esp_mail_smtp_priority_low or 5
* The default value is esp_mail_smtp_priority_low
*/
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
// message.response.reply_to = "[email protected]";
// message.response.return_path = "[email protected]";
/** The Delivery Status Notifications e.g.
* esp_mail_smtp_notify_never
* esp_mail_smtp_notify_success
* esp_mail_smtp_notify_failure
* esp_mail_smtp_notify_delay
* The default value is esp_mail_smtp_notify_never
*/
// message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;
/* Set the custom message header */
message.addHeader(F("Message-ID: <[email protected]>"));
// For Root CA certificate verification (ESP8266 and ESP32 only)
// config.certificate.cert_data = rootCACert;
// or
// config.certificate.cert_file = "/path/to/der/file";
// config.certificate.cert_file_storage_type = esp_mail_file_storage_type_flash; // esp_mail_file_storage_type_sd
// config.certificate.verify = true;
// The WiFiNINA firmware the Root CA certification can be added via the option in Firmware update tool in Arduino IDE
/* Connect to server with the session config */
// Library will be trying to sync the time with NTP server if time is never sync or set.
// This is 10 seconds blocking process.
// If time reading was timed out, the error "NTP server time reading timed out" will show via debug and callback function.
// You can manually sync time by yourself with NTP library or calling configTime in ESP32 and ESP8266.
// Time can be set manually with provided timestamp to function smtp.setSystemTime.
/* Set the TCP response read timeout in seconds */
// smtp.setTCPTimeout(10);
/* Connect to the server */
if (!smtp.connect(&config)) {
MailClient.printf("Connection error, Status Code: %d, Error Code: %d, Reason: %s\n", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());
return 0;
}
/** Or connect without log in and log in later
if (!smtp.connect(&config, false))
return;
if (!smtp.loginWithPassword(AUTHOR_EMAIL, AUTHOR_PASSWORD))
return;
*/
if (!smtp.isLoggedIn()) {
Serial.println("Not logged");
} else {
if (smtp.isAuthenticated())
Serial.println("Logged in.");
else
Serial.println("No Auth.");
}
/* Start sending Email and close the session */
if (!MailClient.sendMail(&smtp, &message))
MailClient.printf("Error, Status Code: %d, Error Code: %d, Reason: %s\n", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());
// to clear sending result log
smtp.sendingResult.clear();
return 1;
}
bool isAlphaValidChar(char ch) {
if ((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch == '@') || (ch == '$') || (ch == '_') || (ch == '-') || (ch == '.') || (ch == '#')) {
return true;
}
return false;
}
//Hamsy
void show_test() {
static int n_loops = 0;
content = "$DR_R00000000000U01TL015KV100AH0001001.2000.8000.9001.0001.1001.0001.0001.1001.0134.3134.4134.4050.0001.5000.5000.01401400DR_R#";
if (content.length() == 127) {
// content = "$DR_R00000000000U01TL015KV100AH0001001.2000.8000.9001.0001.1001.0001.0001.1001.0134.3134.4134.4050.0001.5000.5000.01400400DR_R#";
post_ups_data_to_cloud();
send_fault_alert_via_email();
send_warning_alert_via_email();
Serial.println("Data Uploaded to the Cloud");
} else {
Serial.println("Length Check Failed");
}
delay(1000);
n_loops++;
Serial.printf("Show test count : %d\n", n_loops);
}
void show() {
while (Serial2.available() != 0) {
if (Serial2.available() > 0) {
incoming_char = Serial2.read();
//content = content + String(char(incoming_char));
isValid = isAlphaValidChar(char(incoming_char));
if (isValid) {
content = content + String(char(incoming_char));
}
if (char(incoming_char) == '$') {
count = true;
}
if (char(incoming_char) == '#' and count == true) {
count = false;
Serial.print("Content is:");
Serial.println(content);
Serial.print("Content length is:");
Serial.println(content.length());
if (content.length() == 127) {
// content = "$DR_R00000000000U01TL015KV100AH0001001.2000.8000.9001.0001.1001.0001.0001.1001.0134.3134.4134.4050.0001.5000.5000.01400400DR_R#";
post_ups_data_to_cloud();
send_fault_alert_via_email();
send_warning_alert_via_email();
Serial.println("Data Uploaded to the Cloud");
} else {
Serial.println("Length Check Failed");
}
content = "";
}
}
}
// //content = "$DR_R00000000000U01TL015KV100AH0001001.2000.8000.9001.0001.1001.0001.0001.1001.0134.3134.4134.4050.0001.5000.5000.01400400DR_R#";
// content = "$DR_R00000000000U01TL015KV100AH0001001.2000.8000.9001.0001.1001.0001.0001.1001.0134.3134.4134.4050.0001.5000.5000.01412400DR_R#";
// send_fault_alert_via_email();
// post_ups_data_to_cloud();
// // delay(10);
// delay(90 * 1000);
}
int send_warning_alert_via_email() {
static bool warningDetectedBL = false;
static bool warningDetectedOL = false;
static bool warningDetectedOT = false;
static bool warningDetectedNG = false;
static bool warningDetectedUK = false;
Serial.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
Serial.println("%% send_warning_alert_via_email %%");
Serial.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
int tr_email_status = 0;
Serial.println(content);
delay(100);
String warning = content.substring(119, 120);
int warning_int = warning.toInt();
Serial.println("warning: " + warning);
Serial.println(warning_int);
date_time = get_date_time();
String warningStr = "";
switch (warning_int) {
case 0:
warningStr = ""; // 0=====no warning,
warningDetectedBL = false;
warningDetectedOL = false;
warningDetectedOT = false;
warningDetectedNG = false;
warningDetectedUK = false;
break;
case 1:
if (warningDetectedBL == false) {
warningStr = "Low Battery"; // 1=====Low Battery
warningDetectedBL = true;
}
break;
case 2:
if (warningDetectedOL == false) {
warningStr = "Overload"; // 2=====Overload
warningDetectedOL = true;
}
break;
case 3:
if (warningDetectedOT == false) {
warningStr = "Over Temperature"; // 3=====Over Temperature
warningDetectedOT = true;
}
break;
case 4:
if (warningDetectedNG == false) {
warningStr = "No Grid"; // 4=====No Grid
warningDetectedNG = true;
}
break;
default:
if (warningDetectedUK == false) {
warningStr = "Unknown Warning";
warningDetectedUK = true;
}
break;
}
Serial.print("WARNING: ");
Serial.println(warningStr);
if (warningStr != "") {
String tr_alert_subject;
String tr_alert_email_msg;
if (date_time == "1970-01-01 01:00:00") {
tr_alert_subject = String(warningStr) + String(" for ") + String(device_id);
tr_alert_email_msg = String("Request to check the device ") + String(device_id) + String(" for ") + String(warningStr);
} else {
tr_alert_subject = String(warningStr) + String(" for ") + String(device_id) + String(" at around ") + String(date_time);
tr_alert_email_msg = String("Request to check the device ") + String(device_id) + String(" for ") + String(warningStr) + String(" at around ") + String(date_time);
}
Serial.print("tr_alert_subject: ");
Serial.println(tr_alert_subject);
Serial.print("tr_alert_email_msg: ");
Serial.println(tr_alert_email_msg);
int ArrayLength1 = tr_alert_subject.length() + 1;
char tr_alert_subject_char[ArrayLength1];
tr_alert_subject.toCharArray(tr_alert_subject_char, ArrayLength1);
int ArrayLength2 = tr_alert_email_msg.length() + 1;
char tr_alert_email_msg_char[ArrayLength2];
tr_alert_email_msg.toCharArray(tr_alert_email_msg_char, ArrayLength2);
tr_email_status = notify_fault_via_email(tr_alert_subject_char, tr_alert_email_msg_char);
if (tr_email_status) {
Serial.print("fails to send email:");
Serial.println(tr_alert_subject);
return -1;
} else {
return 0;
}
} else {
//reset the previously sentWarningFlag = 0;
return 0;
}
}
int send_fault_alert_via_email() {
static bool faultDetectedOC110 = false;
static bool faultDetectedOC125 = false;
static bool faultDetectedOC125Plus = false;
static bool faultDetectedST = false;
static bool faultDetectedB_OV = false;
static bool faultDetectedB_UV = false;
static bool faultDetectedO_OV = false;
static bool faultDetectedO_UV = false;
static bool faultDetectedOT = false;
static bool faultDetectedPSR = false;
static bool faultDetectedGBF = false;
static bool faultDetectedSWF = false;
static bool faultDetectedVFF = false;
static bool faultDetectedUK = false;
Serial.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
Serial.println("%% send_fault_alert_via_email %%");
Serial.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
int tr_email_status = 0;
Serial.println(content);
delay(100);
String fault = content.substring(117, 119);
int fault_int = fault.toInt();
Serial.println("fault :" + fault);
Serial.println(fault_int);
date_time = get_date_time();
String faultStr = "";
switch (fault_int) {
case 0:
faultStr = ""; // 00=====no fault,
faultDetectedOC110 = false;
faultDetectedOC125 = false;
faultDetectedOC125Plus = false;
faultDetectedST = false;
faultDetectedB_OV = false;
faultDetectedB_UV = false;
faultDetectedO_OV = false;
faultDetectedO_UV = false;
faultDetectedOT = false;
faultDetectedPSR = false;
faultDetectedGBF = false;
faultDetectedSWF = false;
faultDetectedVFF = false;
faultDetectedUK = false;
break;
case 1:
if (faultDetectedOC110 == false) {
faultStr = "Overcurrent 100-110%"; // 01=====overcurrent 100-110%
faultDetectedOC110 = true;
}
break;
case 2:
if (faultDetectedOC125 == false) {
faultStr = "Overcurrent 110-125%"; // 02=====overcurrent 110-125%
faultDetectedOC125 = true;
}
break;
case 3:
if (faultDetectedOC125Plus == false) {
faultStr = "Overcurrent >125%"; // 03=====overcurrent >125%
faultDetectedOC125Plus = true;
}
break;
case 4:
if (faultDetectedST == false) {
faultStr = "Short Circuit"; // 04=====short circuit
faultDetectedST = true;
}
break;
case 5:
if (faultDetectedB_OV == false) {
faultStr = "Battery Overvoltage,"; // 05=====battery overvoltage,
faultDetectedB_OV = true;
}
break;
case 6:
if (faultDetectedB_UV == false) {
faultStr = "Battery Undervoltage"; // 06=====battery undervoltage
faultDetectedB_UV = true;
}
break;
case 7:
if (faultDetectedO_OV == false) {
faultStr = "Output Overvoltage"; // 07=====output overvoltage
faultDetectedO_OV = true;
}
break;
case 8:
if (faultDetectedO_UV == false) {
faultStr = "Output Undervoltage"; // 08=====output undervoltage
faultDetectedO_UV = true;
}
break;
case 9:
if (faultDetectedOT == false) {
faultStr = "Over Temperature"; // 09=====over temperature
faultDetectedOT = true;
}
break;
case 10:
if (faultDetectedPSR == false) {
faultStr = "Phase Sequence Reverse"; // 10=====phase sequence reverse
faultDetectedPSR = true;
}
break;
case 11:
if (faultDetectedGBF == false) {
faultStr = "Grid Bypass Failed"; // 11=====grid thyristor fault
faultDetectedGBF = true;
}
break;
case 12:
if (faultDetectedSWF == false) {
faultStr = "Static Switch Failed"; // 12=====ups thyristor fault
faultDetectedSWF = true;
}
break;
case 13:
if (faultDetectedVFF == false) {
faultStr = "Voltage Feedback Fault"; // 13=====voltage feedback fault
faultDetectedVFF = true;
}
break;
default:
if (faultDetectedUK == false) {
faultStr = "Unknown Fault";
faultDetectedUK = true;
}
break;
}
Serial.print("FALUT: ");
Serial.println(faultStr);
if (faultStr != "") {
String tr_alert_subject;
String tr_alert_email_msg;
if (date_time == "1970-01-01 01:00:00") {
tr_alert_subject = String(faultStr) + String(" for ") + String(device_id);
tr_alert_email_msg = String("Request to check the device ") + String(device_id) + String(" for ") + String(faultStr);
} else {
tr_alert_subject = String(faultStr) + String(" for ") + String(device_id) + String(" at around ") + String(date_time);
tr_alert_email_msg = String("Request to check the device ") + String(device_id) + String(" for ") + String(faultStr) + String(" at around ") + String(date_time);
}
Serial.print("tr_alert_subject: ");
Serial.println(tr_alert_subject);
Serial.print("tr_alert_email_msg: ");
Serial.println(tr_alert_email_msg);
int ArrayLength1 = tr_alert_subject.length() + 1;
char tr_alert_subject_char[ArrayLength1];
tr_alert_subject.toCharArray(tr_alert_subject_char, ArrayLength1);
int ArrayLength2 = tr_alert_email_msg.length() + 1;
char tr_alert_email_msg_char[ArrayLength2];
tr_alert_email_msg.toCharArray(tr_alert_email_msg_char, ArrayLength2);
tr_email_status = notify_fault_via_email(tr_alert_subject_char, tr_alert_email_msg_char);
if (tr_email_status) {
Serial.print("fails to send email:");
Serial.println(tr_alert_subject);
return -1;
} else {
return 0;
}
} else {
return 0;
}
}
void loop() {
//show();
show_test();
}
/* Callback function to get the Email sending status */
void smtpCallback(SMTP_Status status) {
/* Print the current status */
Serial.println(status.info());
/* Print the sending result */
if (status.success()) {
// MailClient.printf used in the examples is for format printing via debug Serial port
// that works for all supported Arduino platform SDKs e.g. SAMD, ESP32 and ESP8266.
// In ESP8266 and ESP32, you can use Serial.printf directly.
Serial.println("------\n");
MailClient.printf("Message sent success: %d\n", status.completedCount());
MailClient.printf("Message sent failed: %d\n", status.failedCount());
Serial.println("------\n");
for (size_t i = 0; i < smtp.sendingResult.size(); i++) {
/* Get the result item */
SMTP_Result result = smtp.sendingResult.getItem(i);
// In case, ESP32, ESP8266 and SAMD device, the timestamp get from result.timestamp should be valid if
// your device time was synched with NTP server.
// Other devices may show invalid timestamp as the device time was not set i.e. it will show Jan 1, 1970.
// You can call smtp.setSystemTime(xxx) to set device time manually. Where xxx is timestamp (seconds since Jan 1, 1970)
MailClient.printf("Message No: %d\n", i + 1);
MailClient.printf("Status: %s\n", result.completed ? "success" : "failed");
MailClient.printf("Date/Time: %s\n", MailClient.Time.getDateTimeString(result.timestamp, "%B %d, %Y %H:%M:%S").c_str());
MailClient.printf("Recipient: %s\n", result.recipients.c_str());
MailClient.printf("Subject: %s\n", result.subject.c_str());
}
Serial.println("------\n");
// You need to clear sending result as the memory usage will grow up.
smtp.sendingResult.clear();
}
}