/*
source : https://github.com/erkobg/WiFiManager-OTA/blob/master/main.ino
partition :
4MB with spiffs
1.2MB flash
1.5 spiffs
result :
partition :
4MB with min spiffs
1.9MB flash
190kb spiffs
result :
903713 bytes (45%) program storage space
48376 bytes (14%) dynamic memory
*/
#include <WiFi.h>
#include <DNSServer.h>
#include <WiFiManager.h>
#include <WiFiUdp.h>
#include "CTBot.h";
//#include <ArduinoJson.h>;
CTBot myBot;
#include "ArduinoOTA.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <PubSubClient.h>
//pass real
//String ssid = "MeteoJuanda-Pertek" ; // REPLACE ssid YOUR WIFI NAME, IF ANY
//String pass = "hiluxpertek"; // REPLACE myPassword YOUR WIFI PASSWORD, IF ANY
//pass wokwi
String ssid = "Wokwi-GUEST" ; // REPLACE ssid YOUR WIFI NAME, IF ANY
String pass = ""; // REPLACE myPassword YOUR WIFI PASSWORD, IF ANY
//Variabel token dan id telegram
String token = "5180148063:AAGv8JFbJWNjVVLYro3P33uztmuB5t0HLPY";
const int id = 858200416;
int status = 0;
String getstatus;
// MQTT Broker
const char *mqtt_server = "broker.emqx.io";
const char *topic = "bmkg/sistoringsuser";
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;
//MQUnifiedsensor by Miguel Califa
//https://github.com/RobTillaart/DHTstable?tab=readme-ov-file
//The DHTStable library is a "frozen" version of the DHTlib. This version is stable for both ARM and AVR.
//https://github.com/RobTillaart/DHTNEW
#include "DHTStable.h"
//change this with the pin that you use
int pinMQ2 = 35;
float lpg, co, smoke, mq2val;
String smokeDetect = "AMAN";
bool smokeState = false;
int mq2adc = 0;
DHTStable DHT;
#define DHT22_PIN 12
bool temptState = false;
bool humidState = false;
String pesanKirim = "Server AMAN";
String serverState = "aman";
#define LEDA 26
#define BUZZ 4
// Set the LCD address to 0x27 for a 16 chars and 2 line display
LiquidCrystal_I2C lcd(0x27, 20, 4);
#define MODEA_PIN 15
#define MODEB_PIN 2
bool ModeWiFi = false;
bool ModeOTA = false;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void blinkLED() {
digitalWrite(LEDA, !digitalRead(LEDA));
}
String sgetIP = "";
void SetWiFi() {
//Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
//reset saved settings
//wifiManager.resetSettings();
wifiManager.autoConnect("otaESP");
//or use this for auto generated name ESP + ChipID
//wifiManager.autoConnect();
Serial.println("connected...yeey :)");
sgetIP = String(WiFi.localIP());
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ESP8266Client-";
clientId += String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
client.publish(topic, "hello world");
// ... and resubscribe
client.subscribe(topic);
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
unsigned long rtim0 = 0, tim0 = 3000;
unsigned long rtim1 = 0, tim1 = 5000;
unsigned long rtim2 = 0, tim2 = 3000;
struct
{
uint32_t total;
uint32_t ok;
uint32_t crc_error;
uint32_t time_out;
uint32_t connect;
uint32_t ack_l;
uint32_t ack_h;
uint32_t unknown;
} counter = { 0, 0, 0, 0, 0, 0, 0, 0};
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setup() {
unsigned long cts = millis();
Serial.begin(115200);
Serial.println("program initiate");
pinMode(LEDA, OUTPUT);
pinMode(BUZZ, OUTPUT);
digitalWrite(LEDA, HIGH);
pinMode(MODEA_PIN, INPUT_PULLUP);
pinMode(MODEB_PIN, INPUT_PULLUP);
ModeWiFi = !digitalRead(MODEA_PIN);
ModeOTA = !digitalRead(MODEB_PIN);
Serial.println("MODEA:" + String(ModeWiFi));
Serial.println("MODEB:" + String(ModeOTA));
// initialize the LCD
lcd.begin();
// Turn on the blacklight and print a message.
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("mqtt buzz project");
Serial.println(__FILE__);
Serial.print("LIBRARY VERSION: ");
Serial.println(DHTSTABLE_LIB_VERSION);
Serial.println();
Serial.println("Type,\tstatus,\tHumidity (%),\tTemperature (C)\tTime (us)");
lcd.setCursor(0, 1);
lcd.print("DHTSTABLE_LIB_VERSION");
lcd.setCursor(0, 2);
lcd.print("MQ2 ADC");
lcd.setCursor(0, 3);
lcd.print("READY");
delay(3000);
if (ModeOTA == true && ModeWiFi == true) {
SetWiFi();
ArduinoOTA.setHostname("otaESP");
ArduinoOTA.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
type = "sketch";
else // U_SPIFFS
type = "filesystem";
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("Start updating " + type);
});
ArduinoOTA.onEnd([]() {
Serial.println("\nEnd");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
Serial.println("Ready OTA");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("mqtt buzz project");
lcd.setCursor(0, 1);
lcd.print("WiFi-OTA Enabled");
} else if (ModeOTA == false && ModeWiFi == true) {
SetWiFi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("mqtt buzz project");
lcd.setCursor(0, 1);
lcd.print("WiFi-Only Enabled");
//set token tele
myBot.setTelegramToken(token);
//cek konek wifi
if (myBot.testConnection()) {
Serial.println("konek wifi sukses");
lcd.setCursor(0, 2);
lcd.print("Telegram Enabled");
}
else {
Serial.println("konek wifi gagal");
lcd.setCursor(0, 2);
lcd.print("Telegram Failed");
}
delay(3000);
} else if (ModeOTA == true && ModeWiFi == false) {
myBot.wifiConnect(ssid, pass);
// set the telegram bot token
myBot.setTelegramToken(token);
// check if all things are ok
if (myBot.testConnection())
Serial.println("\ntestConnection OK");
else
Serial.println("\ntestConnection NOK");
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("mqtt buzz project");
lcd.setCursor(0, 1);
lcd.print("Custom ModeA Enabled");
lcd.setCursor(0, 2);
lcd.print("Fixed WiFi");
delay(3000);
} else {
//how to erase previous credentials
//https://github.com/tzapu/WiFiManager/issues/142
//WiFi.disconnect();
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("mqtt buzz project");
lcd.setCursor(0, 1);
lcd.print("Custom ModeB Enabled");
delay(3000);
}
for (int i = 0; i < 10; i++) {
//blinkLED();
}
}//END-SETUP
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
unsigned long rtimer00 = 0, timer00 = 100;
unsigned long rtimer01 = 0, timer01 = 1000;
unsigned long rtimer02 = 0, timer02 = 1000;
unsigned long rtimer03 = 0, timer03 = 1000;
long cnt0 = 0, cnt1 = 0, cnt2 = 0;
int countA = 0;
int countB = 0;
int countC = 0;
int countD = 0;
int16_t x, y;
uint16_t textWidth, textHeight;
const char strHello[] = "otaESP Started";
long SuhuC = 0.00, HumidP = 0.00, Smoke = 0.00;
bool modeWifi = false, modeA = false, modeB = false;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//BEGIN-LOOP
void loop() {
ModeWiFi = !digitalRead(MODEA_PIN);
ModeOTA = !digitalRead(MODEB_PIN);
TBMessage msg;
if (ModeOTA == true && ModeWiFi == true) {
ArduinoOTA.handle();
} else if (ModeOTA == false && ModeWiFi == true) {
if (!client.connected()) {
reconnect();
}
client.loop();
if (myBot.getNewMessage(msg)) {
//tampil serial monitor
Serial.println("pesan masuk : " + msg.text);
}
} else {
modeWifi = false;
}
unsigned long ct = millis();
//BEGIN-TIMER00
if (ct - rtimer00 >= timer00) {
if (ModeWiFi == true) {
//String message = String(gassensorAnalog) + "," + String(gassensorDigital) + "," + String(temp) + "," + String(hum) + "," + String(getstatus);
String message = String(mq2adc) + "," + String(smokeState) + "," + String(SuhuC) + "," + String(HumidP) + "," + String(serverState);
client.publish(topic, message.c_str());
Serial.println(message);
}
rtimer00 = ct;
}//END-TIMER00
//BEGIN-TIMER01
if (ct - rtimer01 >= timer01) {
//digitalWrite(BUZZ,!digitalRead(BUZZ));
// READ DATA
Serial.print("DHT22, \t");
uint32_t start = micros();
int chk = DHT.read22(DHT22_PIN);
uint32_t stop = micros();
counter.total++;
switch (chk)
{
case DHTLIB_OK:
counter.ok++;
Serial.print("OK,\t");
break;
case DHTLIB_ERROR_CHECKSUM:
counter.crc_error++;
Serial.print("Checksum error,\t");
break;
case DHTLIB_ERROR_TIMEOUT:
counter.time_out++;
Serial.print("Time out error,\t");
break;
default:
counter.unknown++;
Serial.print("Unknown error,\t");
break;
}
// DISPLAY DATA
Serial.print(DHT.getHumidity(), 1);
Serial.print(",\t");
HumidP = DHT.getHumidity();
Serial.print(DHT.getTemperature(), 1);
Serial.print(",\t");
SuhuC = DHT.getTemperature();
Serial.print(stop - start);
Serial.println();
mq2adc = analogRead(pinMQ2);
if (mq2adc > 1000) {
smokeState = true;
smokeDetect = "ADA ASAP !!!";
} else {
smokeState = false;
smokeDetect = "TIDAK BERASAP";
}
if (smokeState == false) {
if (SuhuC > 18 && SuhuC < 36) { //SuhuC > 18 && SuhuC < 26
if (HumidP >= 45 && HumidP <= 60 ) { //HumidP >= 45 && HumidP <= 60
pesanKirim = "Server Normal";
serverState = "normal";
} else if (HumidP >= 42 && HumidP <= 44) {
pesanKirim = "Server Alert !";
serverState = "alert";
} else if (HumidP >= 0 && HumidP <= 41) {
pesanKirim = "Server DANGER !!!";
serverState = "danger";
digitalWrite(BUZZ, !digitalRead(BUZZ));
} else {
pesanKirim = "Server Alert !";
serverState = "alert";
}
} else {
pesanKirim = "Server DANGER !!!";
serverState = "danger";
digitalWrite(BUZZ, !digitalRead(BUZZ));
}
} else {
pesanKirim = "Server DANGER !!!";
serverState = "danger";
digitalWrite(BUZZ, !digitalRead(BUZZ));
}
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("mqtt buzz project");
lcd.setCursor(0, 1);
lcd.print("Temp : " + String(SuhuC) + " C");
lcd.setCursor(0, 2);
lcd.print("Humid: " + String(HumidP) + " %");
lcd.setCursor(0, 3);
lcd.print("mq2val: " + String(mq2adc) + " ppm");
//lcd.print("Smoke: " + smokeDetect);
// DISPLAY COUNTERS
if (counter.total % 20 == 0)
{
Serial.println("\nTOT\tOK\tCRC\tTO\tUNK");
Serial.print(counter.total);
Serial.print("\t");
Serial.print(counter.ok);
Serial.print("\t");
Serial.print(counter.crc_error);
Serial.print("\t");
Serial.print(counter.time_out);
Serial.print("\t");
Serial.print(counter.connect);
Serial.print("\t");
Serial.print(counter.ack_l);
Serial.print("\t");
Serial.print(counter.ack_h);
Serial.print("\t");
Serial.print(counter.unknown);
Serial.println("\n");
}
rtimer01 = ct;
}//END-TIMER01
String foto1 = "https://cdn0-production-images-kly.akamaized.net/007WEOXgMomjPtjedNUNji3sZaI=/640x360/smart/filters:quality(75):strip_icc():format(jpeg)/kly-media-production/medias/3594799/original/007415500_1633566598-1_wkwkland_real.JPG";
//BEGIN-TIMER02
if (ct - rtimer02 >= timer02) {
if (ModeWiFi == true) {
String pesan = msg.text;
if (pesan == "hai") {
myBot.sendMessage(id, foto1);
Serial.println("pesan terkirim : " + foto1);
}
}
rtimer02 = ct;
}//END-TIMER02
//BEGIN-TIMER03
if (ct - rtimer03 >= timer03) {
rtimer03 = ct;
}//END-TIMER03
}//END-LOOP