considering using wifi manager and remove email sending

This commit is contained in:
Muhammad Izza Alfiansyah 2024-05-29 10:37:33 +07:00
parent b88bd5e7d2
commit 1c0d2a8269
3 changed files with 405 additions and 265 deletions

View File

@ -7,10 +7,11 @@
#include <assert.h> #include <assert.h>
#include <NTPClient.h> #include <NTPClient.h>
#include <Callmebot_ESP32.h> #include <Callmebot_ESP32.h>
#include <ESP_Mail_Client.h> // #include <ESP_Mail_Client.h>
// #include <ESPAsyncWebServer.h> #include <ESPAsyncWebServer.h>
// #include <AsyncTCP.h> #include <DNSServer.h>
// #include "SPIFFS.h" #include <AsyncTCP.h>
#include "LittleFS.h"
#define BOARD "ESP-32" #define BOARD "ESP-32"
#define MQPIN 34 #define MQPIN 34
@ -22,24 +23,25 @@
#define SUPABASE_URL "https://oxmfbobxmqldgthethlz.supabase.co" #define SUPABASE_URL "https://oxmfbobxmqldgthethlz.supabase.co"
#define SUPABASE_ANON_KEY "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im94bWZib2J4bXFsZGd0aGV0aGx6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MDgwNjQ1NDksImV4cCI6MjAyMzY0MDU0OX0.pTDI9CsiN8wthOWhHjM1dONrRP_Hd7BcbwfKgeKGhtU" #define SUPABASE_ANON_KEY "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im94bWZib2J4bXFsZGd0aGV0aGx6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MDgwNjQ1NDksImV4cCI6MjAyMzY0MDU0OX0.pTDI9CsiN8wthOWhHjM1dONrRP_Hd7BcbwfKgeKGhtU"
#define WIFI_SSID "Vivo Y21c" // #define WIFI_SSID "Vivo Y21c"
#define WIFI_PASS "12346789" // #define WIFI_PASS "12346789"
#define SMTP_HOST "sandbox.smtp.mailtrap.io" // #define SMTP_HOST "sandbox.smtp.mailtrap.io"
#define SMTP_PORT 2525 // #define SMTP_PORT 2525
#define AUTHOR_EMAIL "16d58b0c89cba1" // #define AUTHOR_EMAIL "16d58b0c89cba1"
#define AUTHOR_PASSWORD "f077a3dc3e2f84" // #define AUTHOR_PASSWORD "f077a3dc3e2f84"
LiquidCrystal_I2C lcd(0x27, 16, 2); LiquidCrystal_I2C lcd(0x27, 16, 2);
DHT dht(DHTPIN, 22); DHT dht(DHTPIN, 22);
Supabase db; Supabase db;
WiFiUDP ntpUDP; WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", 3600 * 7, 60000); // GMT +7 NTPClient timeClient(ntpUDP, "pool.ntp.org", 3600 * 7, 60000); // GMT +7
SMTPSession smtp; // SMTPSession smtp;
// AsyncWebServer server(80); AsyncWebServer server(80);
DNSServer dns;
// String WIFI_SSID; String WIFI_SSID;
// String WIFI_PASS; String WIFI_PASS;
const char* ssidPath = "/ssid.txt"; const char* ssidPath = "/ssid.txt";
const char* passPath = "/pass.txt"; const char* passPath = "/pass.txt";
@ -47,44 +49,93 @@ const char* passPath = "/pass.txt";
float suhu; float suhu;
float kelembaban; float kelembaban;
float persentaseKadarGas; float persentaseKadarGas;
bool pengujian; bool pengujian = true;
float kadarGasVoltase; float kadarGasVoltase;
String status = "Menunggu"; String status = "Menunggu";
JSONVar dataPengujian; JSONVar dataPengujian;
JSONVar pengaturan; JSONVar pengaturan;
void smtpCallback(SMTP_Status status); // void smtpCallback(SMTP_Status status);
// void initSPIFFS() { void initLittleFS() {
// if (!SPIFFS.begin(true)) { if (!LittleFS.begin(true)) {
// Serial.println("An error has occurred while mounting SPIFFS"); Serial.println("An error has occurred while mounting LittleFS");
// } }
// Serial.println("SPIFFS mounted successfully"); Serial.println("LittleFS mounted successfully");
// } }
// String readFile(fs::FS &fs, const char * path){ String readFile(const char * path){
// File file = fs.open(path); File file = LittleFS.open(path);
// if(!file || file.isDirectory()){ if(!file || file.isDirectory()){
// return String(); return String();
// } }
// String fileContent; String fileContent;
// while(file.available()){ while(file.available()){
// fileContent = file.readStringUntil('\n'); fileContent = file.readStringUntil('\n');
// break; break;
// } }
// return fileContent; return fileContent;
// } }
// void writeFile(fs::FS &fs, const char * path, const char * message){ void writeFile(const char * path, const char * message){
// File file = fs.open(path, FILE_WRITE); File file = LittleFS.open(path, FILE_WRITE);
// if(file.print(message)){ if(file.print(message)){
// Serial.println("- file written"); Serial.println("- file written");
// } else { } else {
// Serial.println("- write failed"); Serial.println("- write failed");
// } }
// } }
void generateServer() {
WiFi.softAP("Fermonitor V1", NULL);
IPAddress IP = WiFi.softAPIP();
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(LittleFS, "/wifimanager.html", "text/html");
});
server.serveStatic("/", LittleFS, "/");
server.on("/", HTTP_POST, [](AsyncWebServerRequest *request) {
int params = request->params();
for(int i=0;i<params;i++){
AsyncWebParameter* p = request->getParam(i);
if(p->isPost()){
if (p->name() == "ssid") {
WIFI_SSID = p->value().c_str();
writeFile(ssidPath, WIFI_SSID.c_str());
}
if (p->name() == "pass") {
WIFI_PASS = p->value().c_str();
writeFile(passPath, WIFI_PASS.c_str());
}
}
}
request->send(200, "text/plain", "Berhasil. Pengaturan WiFi berhasil di simpan, sistem akan melakukan restart.");
delay(3000);
ESP.restart();
});
server.begin();
}
class CaptiveRequestHandler : public AsyncWebHandler {
public:
CaptiveRequestHandler() {}
virtual ~CaptiveRequestHandler() {}
bool canHandle(AsyncWebServerRequest *request){
//request->addInterestingHeader("ANY");
return true;
}
void handleRequest(AsyncWebServerRequest *request) {
request->send(LittleFS, "/wifimanager.html", "text/html");
}
};
void setup(){ void setup(){
pinMode(MQPIN, INPUT); pinMode(MQPIN, INPUT);
@ -98,10 +149,11 @@ void setup(){
Serial.begin(115200); Serial.begin(115200);
// initSPIFFS(); // inisialisasi filesystem
initLittleFS();
// WIFI_SSID = readFile(SPIFFS, ssidPath); WIFI_SSID = readFile(ssidPath);
// WIFI_PASS = readFile(SPIFFS, passPath); WIFI_PASS = readFile(passPath);
// inisialisasi LCD // inisialisasi LCD
lcd.init(); lcd.init();
@ -116,57 +168,35 @@ void setup(){
// inisialisasi WiFi // inisialisasi WiFi
WiFi.begin(WIFI_SSID, WIFI_PASS); WiFi.begin(WIFI_SSID, WIFI_PASS);
// if (WiFi.status() != WL_CONNECTED) {
// WiFi.softAP("Fermonitor V1", NULL);
// IPAddress IP = WiFi.softAPIP();
// server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
// request->send(SPIFFS, "/wifimanager.html", "text/html");
// });
// server.serveStatic("/", SPIFFS, "/");
// server.on("/", HTTP_POST, [](AsyncWebServerRequest *request) {
// int params = request->params();
// for(int i=0;i<params;i++){
// AsyncWebParameter* p = request->getParam(i);
// if(p->isPost()){
// if (p->name() == "ssid") {
// WIFI_SSID = p->value().c_str();
// writeFile(SPIFFS, ssidPath, WIFI_SSID.c_str());
// }
// if (p->name() == "pass") {
// WIFI_PASS = p->value().c_str();
// writeFile(SPIFFS, ssidPath, WIFI_PASS.c_str());
// }
// }
// }
// request->send(200, "text/plain", "Berhasil. Pengaturan WiFi berhasil di simpan, sistem akan melakukan restart.");
// delay(3000);
// ESP.restart();
// });
// server.begin();
// }
delay(20000); delay(20000);
// inisialisasi mail client // inisialisasi web server wifi manager
MailClient.networkReconnect(true); generateServer();
smtp.debug(0);
smtp.callback(smtpCallback);
// inisialisasi waktu if (WiFi.status() == WL_CONNECTED) {
timeClient.begin(); // inisialisasi mail client
// MailClient.networkReconnect(true);
// smtp.debug(0);
// smtp.callback(smtpCallback);
// inisialisasi supabase // inisialisasi waktu
db.begin(SUPABASE_URL, SUPABASE_ANON_KEY); timeClient.begin();
getDataPengujian(); // inisialisasi supabase
db.begin(SUPABASE_URL, SUPABASE_ANON_KEY);
getDataPengujian();
}
// inisialisasi dns server
dns.start(53, "*", WiFi.softAPIP());
server.addHandler(new CaptiveRequestHandler()).setFilter(ON_AP_FILTER);
} }
void loop(){ void loop(){
dns.processNextRequest();
if (WiFi.status() == WL_CONNECTED) { if (WiFi.status() == WL_CONNECTED) {
getPengaturan(); getPengaturan();
timeClient.update(); timeClient.update();
@ -177,6 +207,10 @@ void loop(){
if (running) { if (running) {
runFermentasi(); runFermentasi();
} else { } else {
digitalWrite(LAMPPIN, HIGH);
digitalWrite(FANPIN, HIGH);
digitalWrite(BUZZERPIN, LOW);
// menampilkan aku siap jika alat belum dirunning // menampilkan aku siap jika alat belum dirunning
lcd.clear(); lcd.clear();
lcd.setCursor(0, 0); lcd.setCursor(0, 0);
@ -199,7 +233,6 @@ void loop(){
delay(1000); delay(1000);
} }
} else { } else {
// menampilkan gagal terhubung ke jaringan pada LCD
lcd.setCursor(0, 0); lcd.setCursor(0, 0);
lcd.print("Gagal terhubung"); lcd.print("Gagal terhubung");
lcd.setCursor(0, 1); lcd.setCursor(0, 1);
@ -290,8 +323,8 @@ void runFermentasi() {
} }
} else { } else {
digitalWrite(BUZZERPIN, LOW); digitalWrite(BUZZERPIN, LOW);
cekKematangan();
insertKondisiTapai(); insertKondisiTapai();
cekKematangan();
} }
delay(2000); delay(2000);
@ -323,7 +356,10 @@ float getKadarGas() {
// konversi tegangan ke persen berdasarkan rumus yang telah ditentukan // konversi tegangan ke persen berdasarkan rumus yang telah ditentukan
float getPersentaseKadarGas(float voltase) { float getPersentaseKadarGas(float voltase) {
float persentase = 0.2043 * pow(voltase, 2.0) + 0.0611 * voltase - 0.0249; float m = 6.0 / (1.49 / 0.81);
float b = -m * 0.81;
float persentase = m * voltase + b;
// float persentase = 0.2043 * pow(voltase, 2.0) + 0.0611 * voltase - 0.0249;
float hasil = constrain(persentase * 100, 0, 100); float hasil = constrain(persentase * 100, 0, 100);
return hasil; return hasil;
@ -350,63 +386,62 @@ void callUser(bool matang = true) {
Callmebot.telegramCall(pengaturan[0]["telepon"], text, "id-ID-Standard-B"); Callmebot.telegramCall(pengaturan[0]["telepon"], text, "id-ID-Standard-B");
Serial.println(Callmebot.debug()); Serial.println(Callmebot.debug());
sendEmail(text); sendEmail(text);
} }
void sendEmail(String text) { void sendEmail(String text) {
Session_Config config; // Session_Config config;
config.server.host_name = SMTP_HOST; // config.server.host_name = SMTP_HOST;
config.server.port = SMTP_PORT; // config.server.port = SMTP_PORT;
config.login.email = AUTHOR_EMAIL; // config.login.email = AUTHOR_EMAIL;
config.login.password = AUTHOR_PASSWORD; // config.login.password = AUTHOR_PASSWORD;
config.login.user_domain = ""; // config.login.user_domain = "";
config.time.ntp_server = F("pool.ntp.org,time.nist.gov"); // config.time.ntp_server = F("pool.ntp.org,time.nist.gov");
config.time.gmt_offset = 7; // config.time.gmt_offset = 7;
config.time.day_light_offset = 0; // config.time.day_light_offset = 0;
SMTP_Message message; // SMTP_Message message;
String emailRecipient = pengaturan[0]["email"]; // String emailRecipient = pengaturan[0]["email"];
message.sender.name = F("Fermonitor"); // message.sender.name = F("Fermonitor");
message.sender.email = "fermonitor@official.com"; // message.sender.email = "fermonitor@official.com";
message.subject = "Status Fermentasi Tapai"; // message.subject = "Status Fermentasi Tapai";
message.addRecipient(emailRecipient, emailRecipient); // message.addRecipient(emailRecipient, emailRecipient);
message.text.content = text.c_str(); // message.text.content = text.c_str();
message.text.charSet = "us-ascii"; // message.text.charSet = "us-ascii";
message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit; // message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low; // message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay; // message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;
if (!smtp.connect(&config)){ // if (!smtp.connect(&config)){
ESP_MAIL_PRINTF("Connection error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str()); // ESP_MAIL_PRINTF("Connection error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());
return; // return;
} // }
if (!smtp.isLoggedIn()){ // if (!smtp.isLoggedIn()){
Serial.println("Gagal login akun email"); // Serial.println("Gagal login akun email");
} // }
else{ // else{
if (smtp.isAuthenticated()) { // if (smtp.isAuthenticated()) {
Serial.println("Berhasil login email"); // Serial.println("Berhasil login email");
} else { // } else {
Serial.println("Terhubung ke email tanpa otorisasi"); // Serial.println("Terhubung ke email tanpa otorisasi");
} // }
} // }
if (!MailClient.sendMail(&smtp, &message)) { // if (!MailClient.sendMail(&smtp, &message)) {
ESP_MAIL_PRINTF("Error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str()); // ESP_MAIL_PRINTF("Error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());
} // }
} }
void smtpCallback(SMTP_Status status){ // void smtpCallback(SMTP_Status status){
// hapus memory email jika berhasil terkirim // // hapus memory email jika berhasil terkirim
if (status.success()){ // if (status.success()){
smtp.sendingResult.clear(); // smtp.sendingResult.clear();
} // }
} // }
// menyimpan kondisi tapai pada database // menyimpan kondisi tapai pada database
void insertKondisiTapai() { void insertKondisiTapai() {
@ -452,8 +487,8 @@ void insertHistory(bool berhasil = true) {
String json = JSON.stringify(req); String json = JSON.stringify(req);
callUser(true);
db.insert("histori_fermentasi", json, false); db.insert("histori_fermentasi", json, false);
callUser(berhasil);
pengujian = true; pengujian = true;
} }
@ -463,9 +498,10 @@ void cekKematangan() {
int lamaJam = getLamaJamFermentasi(); int lamaJam = getLamaJamFermentasi();
// jika sudah lebih dari 24 jam // jika sudah lebih dari 24 jam
if (lamaJam > 24) { // if (lamaJam > 24) {
if (persentaseKadarGas >= 5.28 || lamaJam > 72) { if (dataPengujian.length() > 0) {
if (persentaseKadarGas >= 5.28 || lamaJam >= 72) {
status = "Matang"; status = "Matang";
insertHistory(true); insertHistory(true);
} }

View File

@ -1,13 +1,17 @@
// #include <ESP32_Supabase.h>
#include <LiquidCrystal_I2C.h> #include <LiquidCrystal_I2C.h>
#include <DHT.h> #include <DHT.h>
#include <WiFi.h> // #include <ESP32_Supabase.h>
// #include <WiFi.h>
// #include <WiFiUdp.h> // #include <WiFiUdp.h>
// #include <Arduino_JSON.h> // #include <Arduino_JSON.h>
// #include <assert.h> // #include <assert.h>
// #include <NTPClient.h> // #include <NTPClient.h>
// #include <Callmebot_ESP32.h> // #include <Callmebot_ESP32.h>
// #include <ESP_Mail_Client.h> // #include <ESP_Mail_Client.h>
#include <ESPAsyncWebServer.h>
#include <DNSServer.h>
#include <AsyncTCP.h>
#include "LittleFS.h"
#define BOARD "ESP-32" #define BOARD "ESP-32"
#define MQPIN 34 #define MQPIN 34
@ -20,24 +24,32 @@
// #define SUPABASE_ANON_KEY "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im94bWZib2J4bXFsZGd0aGV0aGx6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MDgwNjQ1NDksImV4cCI6MjAyMzY0MDU0OX0.pTDI9CsiN8wthOWhHjM1dONrRP_Hd7BcbwfKgeKGhtU" // #define SUPABASE_ANON_KEY "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Im94bWZib2J4bXFsZGd0aGV0aGx6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3MDgwNjQ1NDksImV4cCI6MjAyMzY0MDU0OX0.pTDI9CsiN8wthOWhHjM1dONrRP_Hd7BcbwfKgeKGhtU"
// #define WIFI_SSID "Vivo Y21c" // #define WIFI_SSID "Vivo Y21c"
// #define WIFI_PASSWORD "12346789" // #define WIFI_PASS "12346789"
// #define SMTP_HOST "sandbox.smtp.mailtrap.io" // #define SMTP_HOST "sandbox.smtp.mailtrap.io"
// #define SMTP_PORT 2525 // #define SMTP_PORT 2525
// #define AUTHOR_EMAIL "16d58b0c89cba1" // #define AUTHOR_EMAIL "16d58b0c89cba1"
// #define AUTHOR_PASSWORD "f077a3dc3e2f84" // #define AUTHOR_PASSWORD "f077a3dc3e2f84"
// Supabase db;
LiquidCrystal_I2C lcd(0x27, 16, 2); LiquidCrystal_I2C lcd(0x27, 16, 2);
DHT dht(DHTPIN, 22); DHT dht(DHTPIN, 22);
// Supabase db;
// WiFiUDP ntpUDP; // WiFiUDP ntpUDP;
// NTPClient timeClient(ntpUDP, "pool.ntp.org", 3600 * 7, 60000); // GMT +7 // NTPClient timeClient(ntpUDP, "pool.ntp.org", 3600 * 7, 60000); // GMT +7
// SMTPSession smtp; // SMTPSession smtp;
AsyncWebServer server(80);
DNSServer dns;
String WIFI_SSID;
String WIFI_PASS;
const char* ssidPath = "/ssid.txt";
const char* passPath = "/pass.txt";
float suhu; float suhu;
float kelembaban; float kelembaban;
float persentaseKadarGas; float persentaseKadarGas;
bool pengujian; bool pengujian = true;
float kadarGasVoltase; float kadarGasVoltase;
String status = "Menunggu"; String status = "Menunggu";
// JSONVar dataPengujian; // JSONVar dataPengujian;
@ -45,6 +57,86 @@ String status = "Menunggu";
// void smtpCallback(SMTP_Status status); // void smtpCallback(SMTP_Status status);
void initLittleFS() {
if (!LittleFS.begin(true)) {
Serial.println("An error has occurred while mounting LittleFS");
}
Serial.println("LittleFS mounted successfully");
}
String readFile(const char * path){
File file = LittleFS.open(path);
if(!file || file.isDirectory()){
return String();
}
String fileContent;
while(file.available()){
fileContent = file.readStringUntil('\n');
break;
}
return fileContent;
}
void writeFile(const char * path, const char * message){
File file = LittleFS.open(path, FILE_WRITE);
if(file.print(message)){
Serial.println("- file written");
} else {
Serial.println("- write failed");
}
}
void generateServer() {
WiFi.softAP("Fermonitor V1", NULL);
IPAddress IP = WiFi.softAPIP();
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(LittleFS, "/wifimanager.html", "text/html");
});
server.serveStatic("/", LittleFS, "/");
server.on("/", HTTP_POST, [](AsyncWebServerRequest *request) {
int params = request->params();
for(int i=0;i<params;i++){
AsyncWebParameter* p = request->getParam(i);
if(p->isPost()){
if (p->name() == "ssid") {
WIFI_SSID = p->value().c_str();
writeFile(ssidPath, WIFI_SSID.c_str());
}
if (p->name() == "pass") {
WIFI_PASS = p->value().c_str();
writeFile(passPath, WIFI_PASS.c_str());
}
}
}
request->send(200, "text/plain", "Berhasil. Pengaturan WiFi berhasil di simpan, sistem akan melakukan restart.");
delay(3000);
ESP.restart();
});
server.begin();
}
class CaptiveRequestHandler : public AsyncWebHandler {
public:
CaptiveRequestHandler() {}
virtual ~CaptiveRequestHandler() {}
bool canHandle(AsyncWebServerRequest *request){
//request->addInterestingHeader("ANY");
return true;
}
void handleRequest(AsyncWebServerRequest *request) {
request->send(LittleFS, "/wifimanager.html", "text/html");
}
};
void setup(){ void setup(){
pinMode(MQPIN, INPUT); pinMode(MQPIN, INPUT);
pinMode(LAMPPIN, OUTPUT); pinMode(LAMPPIN, OUTPUT);
@ -57,6 +149,12 @@ void setup(){
Serial.begin(115200); Serial.begin(115200);
// inisialisasi filesystem
initLittleFS();
WIFI_SSID = readFile(ssidPath);
WIFI_PASS = readFile(passPath);
// inisialisasi LCD // inisialisasi LCD
lcd.init(); lcd.init();
lcd.backlight(); lcd.backlight();
@ -68,25 +166,37 @@ void setup(){
dht.begin(); dht.begin();
// inisialisasi WiFi // inisialisasi WiFi
// WiFi.begin(WIFI_SSID, WIFI_PASSWORD); // WiFi.begin(WIFI_SSID, WIFI_PASS);
delay(20000); delay(20000);
// inisialisasi mail client // inisialisasi web server wifi manager
// MailClient.networkReconnect(true); generateServer();
// smtp.debug(0);
// smtp.callback(smtpCallback);
// // inisialisasi waktu // if (WiFi.status() == WL_CONNECTED) {
// timeClient.begin(); // // inisialisasi mail client
// // MailClient.networkReconnect(true);
// // smtp.debug(0);
// // smtp.callback(smtpCallback);
// // inisialisasi supabase // // inisialisasi waktu
// db.begin(SUPABASE_URL, SUPABASE_ANON_KEY); // timeClient.begin();
// getDataPengujian(); // // inisialisasi supabase
// db.begin(SUPABASE_URL, SUPABASE_ANON_KEY);
// getDataPengujian();
// }
// inisialisasi dns server
dns.start(53, "*", WiFi.softAPIP());
server.addHandler(new CaptiveRequestHandler()).setFilter(ON_AP_FILTER);
} }
void loop(){ void loop(){
dns.processNextRequest();
// if (WiFi.status() == WL_CONNECTED) { // if (WiFi.status() == WL_CONNECTED) {
// getPengaturan(); // getPengaturan();
// timeClient.update(); // timeClient.update();
@ -97,6 +207,10 @@ void loop(){
// if (running) { // if (running) {
runFermentasi(); runFermentasi();
// } else { // } else {
// digitalWrite(LAMPPIN, HIGH);
// digitalWrite(FANPIN, HIGH);
// digitalWrite(BUZZERPIN, LOW);
// // menampilkan aku siap jika alat belum dirunning // // menampilkan aku siap jika alat belum dirunning
// lcd.clear(); // lcd.clear();
// lcd.setCursor(0, 0); // lcd.setCursor(0, 0);
@ -119,7 +233,6 @@ void loop(){
// delay(1000); // delay(1000);
// } // }
// } else { // } else {
// // menampilkan gagal terhubung ke jaringan pada LCD
// lcd.setCursor(0, 0); // lcd.setCursor(0, 0);
// lcd.print("Gagal terhubung"); // lcd.print("Gagal terhubung");
// lcd.setCursor(0, 1); // lcd.setCursor(0, 1);
@ -138,7 +251,7 @@ void runFermentasi() {
lcd.setCursor(0, 0); lcd.setCursor(0, 0);
lcd.print("G : "); lcd.print("G : ");
lcd.print(persentaseKadarGas, 1); lcd.print(persentaseKadarGas, 1);
lcd.print("%-"); lcd.print(" %-");
lcd.print(kadarGasVoltase, 2); lcd.print(kadarGasVoltase, 2);
lcd.print("V"); lcd.print("V");
lcd.setCursor(0,1); lcd.setCursor(0,1);
@ -212,8 +325,8 @@ void runFermentasi() {
// } // }
// } else { // } else {
// digitalWrite(BUZZERPIN, LOW); // digitalWrite(BUZZERPIN, LOW);
// cekKematangan();
// insertKondisiTapai(); // insertKondisiTapai();
// cekKematangan();
// } // }
delay(2000); delay(2000);
@ -245,7 +358,10 @@ float getKadarGas() {
// konversi tegangan ke persen berdasarkan rumus yang telah ditentukan // konversi tegangan ke persen berdasarkan rumus yang telah ditentukan
float getPersentaseKadarGas(float voltase) { float getPersentaseKadarGas(float voltase) {
float persentase = 0.2043 * pow(voltase, 2.0) + 0.0611 * voltase - 0.0249; float m = 6.0 / (1.49 / 0.81);
float b = -m * 0.81;
float persentase = m * voltase + b;
// float persentase = 0.2043 * pow(voltase, 2.0) + 0.0611 * voltase - 0.0249;
float hasil = constrain(persentase * 100, 0, 100); float hasil = constrain(persentase * 100, 0, 100);
return hasil; return hasil;
@ -272,56 +388,55 @@ float getPersentaseKadarGas(float voltase) {
// Callmebot.telegramCall(pengaturan[0]["telepon"], text, "id-ID-Standard-B"); // Callmebot.telegramCall(pengaturan[0]["telepon"], text, "id-ID-Standard-B");
// Serial.println(Callmebot.debug()); // Serial.println(Callmebot.debug());
// sendEmail(text); // sendEmail(text);
// } // }
// void sendEmail(String text) { void sendEmail(String text) {
// Session_Config config; // Session_Config config;
// config.server.host_name = SMTP_HOST; // config.server.host_name = SMTP_HOST;
// config.server.port = SMTP_PORT; // config.server.port = SMTP_PORT;
// config.login.email = AUTHOR_EMAIL; // config.login.email = AUTHOR_EMAIL;
// config.login.password = AUTHOR_PASSWORD; // config.login.password = AUTHOR_PASSWORD;
// config.login.user_domain = ""; // config.login.user_domain = "";
// config.time.ntp_server = F("pool.ntp.org,time.nist.gov"); // config.time.ntp_server = F("pool.ntp.org,time.nist.gov");
// config.time.gmt_offset = 7; // config.time.gmt_offset = 7;
// config.time.day_light_offset = 0; // config.time.day_light_offset = 0;
// SMTP_Message message; // SMTP_Message message;
// String emailRecipient = pengaturan[0]["email"]; // String emailRecipient = pengaturan[0]["email"];
// message.sender.name = F("Fermonitor"); // message.sender.name = F("Fermonitor");
// message.sender.email = "fermonitor@official.com"; // message.sender.email = "fermonitor@official.com";
// message.subject = "Status Fermentasi Tapai"; // message.subject = "Status Fermentasi Tapai";
// message.addRecipient(emailRecipient, emailRecipient); // message.addRecipient(emailRecipient, emailRecipient);
// message.text.content = text.c_str(); // message.text.content = text.c_str();
// message.text.charSet = "us-ascii"; // message.text.charSet = "us-ascii";
// message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit; // message.text.transfer_encoding = Content_Transfer_Encoding::enc_7bit;
// message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low; // message.priority = esp_mail_smtp_priority::esp_mail_smtp_priority_low;
// message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay; // message.response.notify = esp_mail_smtp_notify_success | esp_mail_smtp_notify_failure | esp_mail_smtp_notify_delay;
// if (!smtp.connect(&config)){ // if (!smtp.connect(&config)){
// ESP_MAIL_PRINTF("Connection error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str()); // ESP_MAIL_PRINTF("Connection error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());
// return; // return;
// } // }
// if (!smtp.isLoggedIn()){ // if (!smtp.isLoggedIn()){
// Serial.println("Gagal login akun email"); // Serial.println("Gagal login akun email");
// } // }
// else{ // else{
// if (smtp.isAuthenticated()) { // if (smtp.isAuthenticated()) {
// Serial.println("Berhasil login email"); // Serial.println("Berhasil login email");
// } else { // } else {
// Serial.println("Terhubung ke email tanpa otorisasi"); // Serial.println("Terhubung ke email tanpa otorisasi");
// } // }
// } // }
// if (!MailClient.sendMail(&smtp, &message)) { // if (!MailClient.sendMail(&smtp, &message)) {
// ESP_MAIL_PRINTF("Error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str()); // ESP_MAIL_PRINTF("Error, Status Code: %d, Error Code: %d, Reason: %s", smtp.statusCode(), smtp.errorCode(), smtp.errorReason().c_str());
// } // }
// } }
// void smtpCallback(SMTP_Status status){ // void smtpCallback(SMTP_Status status){
// // hapus memory email jika berhasil terkirim // // hapus memory email jika berhasil terkirim
@ -330,7 +445,7 @@ float getPersentaseKadarGas(float voltase) {
// } // }
// } // }
// // menyimpan kondisi tapai pada database // menyimpan kondisi tapai pada database
// void insertKondisiTapai() { // void insertKondisiTapai() {
// JSONVar req; // JSONVar req;
@ -349,8 +464,7 @@ float getPersentaseKadarGas(float voltase) {
// } // }
// } // }
// // melakukan cek kematangan // int getLamaJamFermentasi() {
// void cekKematangan() {
// JSONVar dataPengujianAwal = dataPengujian[0]; // JSONVar dataPengujianAwal = dataPengujian[0];
// int epochTimeAwal = (int) dataPengujianAwal["created_time"]; // int epochTimeAwal = (int) dataPengujianAwal["created_time"];
// int epochTimeSekarang = timeClient.getEpochTime(); // int epochTimeSekarang = timeClient.getEpochTime();
@ -358,41 +472,47 @@ float getPersentaseKadarGas(float voltase) {
// int epochTimeDiff = epochTimeSekarang - epochTimeAwal; // int epochTimeDiff = epochTimeSekarang - epochTimeAwal;
// int lamaJam = epochTimeDiff / 3600; // int lamaJam = epochTimeDiff / 3600;
// return lamaJam;
// }
// void insertHistory(bool berhasil = true) {
// String dataAwalJson = db.from("kondisi_tapai").select("*").order("created_time", "asc", true).limit(1).doSelect();
// String dataAkhirJson = db.from("kondisi_tapai").select("*").order("created_time", "desc", true).limit(1).doSelect();
// JSONVar dataAwal = JSON.parse(dataAwalJson);
// JSONVar dataAkhir = JSON.parse(dataAkhirJson);
// JSONVar req;
// req["berhasil"] = berhasil;
// req["waktu_awal"] = (int) dataAwal[0]["created_time"];
// req["waktu_akhir"] = (int) dataAkhir[0]["created_time"];
// String json = JSON.stringify(req);
// db.insert("histori_fermentasi", json, false);
// callUser(berhasil);
// pengujian = true;
// }
// // melakukan cek kematangan
// void cekKematangan() {
// int lamaJam = getLamaJamFermentasi();
// // jika sudah lebih dari 24 jam // // jika sudah lebih dari 24 jam
// if (lamaJam > 24) { // // if (lamaJam > 24) {
// if (persentaseKadarGas >= 5.28 || lamaJam > 72) { // if (dataPengujian.length() > 0) {
// if (persentaseKadarGas >= 5.28 || lamaJam >= 72) {
// status = "Matang"; // status = "Matang";
// insertHistory(true);
// String dataAwalJson = db.from("kondisi_tapai").select("*").order("created_time", "asc", true).limit(1).doSelect();
// String dataAkhirJson = db.from("kondisi_tapai").select("*").order("created_time", "desc", true).limit(1).doSelect();
// JSONVar dataAwal = JSON.parse(dataAwalJson);
// JSONVar dataAkhir = JSON.parse(dataAkhirJson);
// JSONVar req;
// req["berhasil"] = true;
// req["waktu_awal"] = (int) dataAwal[0]["created_time"];
// req["waktu_akhir"] = (int) dataAkhir[0]["created_time"];
// String json = JSON.stringify(req);
// callUser(true);
// db.insert("histori_fermentasi", json, false);
// pengujian = true;
// } // }
// } // }
// } // }
// // mengecek kegagalan // // mengecek kegagalan
// void cekKegagalan() { // void cekKegagalan() {
// JSONVar dataPengujianAwal = dataPengujian[0]; // int lamaJam = getLamaJamFermentasi();
// int epochTimeAwal = (int) dataPengujianAwal["created_time"];
// int epochTimeSekarang = timeClient.getEpochTime();
// int epochTimeDiff = epochTimeSekarang - epochTimeAwal;
// int lamaJam = epochTimeDiff / 3600;
// float regresiKadarGas = 0.0025 * pow(lamaJam, 2.0) - 0.0397 * lamaJam - 0.1222; // float regresiKadarGas = 0.0025 * pow(lamaJam, 2.0) - 0.0397 * lamaJam - 0.1222;
// float nilaiPerempat = regresiKadarGas / 4.0; // float nilaiPerempat = regresiKadarGas / 4.0;
@ -402,28 +522,9 @@ float getPersentaseKadarGas(float voltase) {
// // if (persentaseKadarGas > (regresiKadarGas + nilaiPerempat) || persentaseKadarGas < (regresiKadarGas - nilaiPerempat)) { // // if (persentaseKadarGas > (regresiKadarGas + nilaiPerempat) || persentaseKadarGas < (regresiKadarGas - nilaiPerempat)) {
// if (persentaseKadarGas < (regresiKadarGas - nilaiPerempat)) { // if (persentaseKadarGas < (regresiKadarGas - nilaiPerempat)) {
// status = "Gagal"; // status = "Gagal";
// insertHistory(false);
// } // }
// } // }
// if (status == "Gagal") {
// String dataAwalJson = db.from("kondisi_tapai").select("*").order("created_time", "asc", true).limit(1).doSelect();
// String dataAkhirJson = db.from("kondisi_tapai").select("*").order("created_time", "desc", true).limit(1).doSelect();
// JSONVar dataAwal = JSON.parse(dataAwalJson);
// JSONVar dataAkhir = JSON.parse(dataAkhirJson);
// JSONVar req;
// req["berhasil"] = false;
// req["waktu_awal"] = (int) dataAwal[0]["created_time"];
// req["waktu_akhir"] = (int) dataAkhir[0]["created_time"];
// String json = JSON.stringify(req);
// callUser(false);
// db.insert("histori_fermentasi", json, false);
// pengujian = true;
// }
// } // }
// // mengambil data pengujian // // mengambil data pengujian

View File

@ -84,32 +84,34 @@ export default function (props: JSX.HTMLAttributes<HTMLDivElement>) {
}; };
const checkStatusDevice = async () => { const checkStatusDevice = async () => {
const lastData1: any = await new Promise(async (res) => { await getLastHistori();
const { data } = await supabase
if (!lastHistori()) {
const lastData1: any = await new Promise(async (res) => {
const { data } = await supabase
.from("kondisi_tapai")
.select("created_time")
.order("created_time", { ascending: false })
.limit(1);
setTimeout(() => {
res(data);
}, 10000);
});
const { data: lastData2 } = await supabase
.from("kondisi_tapai") .from("kondisi_tapai")
.select("created_time") .select("created_time")
.order("created_time", { ascending: false }) .order("created_time", { ascending: false })
.limit(1); .limit(1);
setTimeout(() => {
res(data);
}, 10000);
});
const { data: lastData2 } = await supabase
.from("kondisi_tapai")
.select("created_time")
.order("created_time", { ascending: false })
.limit(1);
if (lastHistori()?.selesai != false) {
if (lastData1![0] == lastData2![0]) { if (lastData1![0] == lastData2![0]) {
alert("Device offline!"); alert("Device offline!");
} else if (lastData1![0].created_time == lastData2![0].created_time) { } else if (lastData1![0].created_time == lastData2![0].created_time) {
alert("Device offline!"); alert("Device offline!");
} }
}
await checkStatusDevice(); await checkStatusDevice();
}
}; };
const checkPengaturan = async () => { const checkPengaturan = async () => {
@ -133,7 +135,6 @@ export default function (props: JSX.HTMLAttributes<HTMLDivElement>) {
}; };
onMount(async () => { onMount(async () => {
await getLastHistori();
await checkPengaturan(); await checkPengaturan();
}); });
@ -159,7 +160,9 @@ export default function (props: JSX.HTMLAttributes<HTMLDivElement>) {
<For each={menus}> <For each={menus}>
{(item) => ( {(item) => (
<A <A
href={canNavigate() ? item.path : "/"} href={
canNavigate() || item.path != "/pengujian" ? item.path : "/"
}
class={ class={
"flex mb-5 items-center transition " + "flex mb-5 items-center transition " +
(location.pathname == item.path ? "text-primary" : "") (location.pathname == item.path ? "text-primary" : "")