Created
January 23, 2022 07:37
-
-
Save wiless/3e08680eef2fe0c270fc70e6cfaa8512 to your computer and use it in GitHub Desktop.
Code for NodeMCU to update status from PES DG Indicator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <ESP8266WiFi.h> | |
#include <ESP8266mDNS.h> | |
#include <ArduinoOTA.h> | |
#include <Firebase_ESP_Client.h> | |
#include <addons/TokenHelper.h> | |
#define HOSTNAME "DG_INDICATOR2" // Name of the | |
#define API_KEY "" | |
#define DATABASE_URL "*firebasedatabase.app" // without https | |
#define USER_EMAIL "" | |
#define USER_PASSWORD "" | |
//Define Firebase Data object | |
FirebaseData fbdo; | |
FirebaseAuth auth; | |
FirebaseConfig config; | |
int val = 0; | |
volatile bool GotInterrupt; | |
#define BLINKPIN LED_BUILTIN | |
#define LDR_DETECT D5 // LDR module connected to D5 | |
#define OTA_PIN LED_BUILTIN_AUX | |
#define RED_LED D6 // External LED connected to D6 to reflect PES-DG-LED | |
#define SSID "WIFISSID" // Name of the SSID | |
#define SSIDPASSWORD "password" // Password for the SSID | |
ICACHE_RAM_ATTR void ISR() | |
{ | |
GotInterrupt = true; | |
digitalWrite(RED_LED, !digitalRead(LDR_DETECT)); | |
} | |
unsigned long starttime = 0; | |
unsigned long pvsblink = 0; | |
const long int TZOFFFSET = 19800; // 5.5hrs IST India | |
bool firstboot = true; | |
void initPINS() | |
{ | |
pinMode(BLINKPIN, OUTPUT); | |
pinMode(OTA_PIN, OUTPUT); | |
pinMode(RED_LED, OUTPUT); | |
pinMode(LDR_DETECT, INPUT); | |
// | |
} | |
void setupWiFI() | |
{ | |
WiFi.mode(WIFI_STA); | |
WiFi.hostname(HOSTNAME); | |
WiFi.begin(SSID, SSIDPASSWORD); | |
while (WiFi.status() != WL_CONNECTED) | |
{ | |
delay(100); | |
digitalWrite(BLINKPIN, !digitalRead(BLINKPIN)); // BLINK ONBOARD LED while connecting to wifi | |
} | |
Serial.print("IP address: "); | |
Serial.println(WiFi.localIP()); | |
Serial.println("Wifi Connected.."); | |
} | |
void setupFirebase() | |
{ | |
config.api_key = API_KEY; | |
auth.user.email = USER_EMAIL; | |
auth.user.password = USER_PASSWORD; | |
config.database_url = DATABASE_URL; | |
config.token_status_callback = tokenStatusCallback; //see addons/TokenHelper.h | |
Firebase.begin(&config, &auth); | |
Firebase.reconnectWiFi(true); | |
} | |
void setupFirebaseTime() | |
{ | |
// unsigned long attempt = millis(); | |
String path = "/SAREPH3/devel/live/status/boottime"; | |
bool ok = Firebase.RTDB.setTimestamp(&fbdo, path); | |
// Serial.printf("\n[boottime] DATAtype? %s ", fbdo.dataType().c_str()); | |
unsigned long boottime = fbdo.to<int>(); | |
while (boottime == 0) | |
{ | |
/* code */ | |
ok = Firebase.RTDB.setTimestamp(&fbdo, path); | |
boottime = fbdo.to<int>(); | |
Serial.printf("\n[/status/boottime] ? %s\n", ok ? fbdo.to<FirebaseJson>().raw() : fbdo.errorReason().c_str()); | |
Serial.print(".."); | |
delay(300); | |
} | |
if (!Firebase.setSystemTime(boottime + TZOFFFSET)) | |
{ | |
Serial.println("Unable to set System time through Firebase"); | |
} | |
} | |
void setupOTA() | |
{ | |
digitalWrite(OTA_PIN, LOW); | |
ArduinoOTA.setHostname(HOSTNAME); | |
ArduinoOTA.onStart([]() { // switch off all the PWMs during upgrade | |
Serial.println("Started OTA"); | |
detachInterrupt(digitalPinToInterrupt(LDR_DETECT)); | |
// digitalWrite(OTA_PIN, LOW); | |
}); | |
ArduinoOTA.onEnd([]() { // do a fancy thing with our board led at end | |
//digitalWrite(OTA_PIN, HIGH); | |
Serial.println("Completed OTA"); | |
}); | |
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) | |
{ | |
digitalWrite(OTA_PIN, !digitalRead(OTA_PIN)); | |
// Serial.printf("Progress: %u%%\r", (progress / (total / 100))); | |
}); | |
ArduinoOTA.onError([](ota_error_t error) | |
{ | |
(void)error; | |
ESP.restart(); | |
}); | |
/* setup the OTA server */ | |
ArduinoOTA.begin(); | |
digitalWrite(OTA_PIN, HIGH); | |
} | |
void setup() | |
{ | |
digitalWrite(RED_LED, HIGH); | |
Serial.begin(115200); | |
Serial.println("Initialize PINS"); | |
initPINS(); | |
Serial.println("Connecting to Wifi "); | |
setupWiFI(); | |
setupOTA(); | |
Serial.println("Setup Firebase "); | |
setupFirebase(); | |
Serial.println("Setup Firebase Timings"); | |
setupFirebaseTime(); | |
/// Final readiness | |
Serial.println("Initialize variables"); | |
pvsblink = millis(); | |
starttime = millis(); | |
// GotInterrupt = true; | |
Serial.println("Initialize Interrupt"); | |
digitalWrite(RED_LED, LOW); | |
attachInterrupt(digitalPinToInterrupt(LDR_DETECT), ISR, CHANGE); | |
Serial.println("Finished setup"); | |
GotInterrupt = true; | |
} | |
unsigned pvsHeartBeat = 0; | |
unsigned currentMillis = 0; | |
void loop() | |
{ | |
ArduinoOTA.handle(); | |
currentMillis = millis(); | |
if (currentMillis - pvsblink > 500) | |
{ | |
pvsblink = millis(); | |
bool oldstart = digitalRead(BLINKPIN); | |
digitalWrite(BLINKPIN, !oldstart); | |
} | |
if (currentMillis - pvsHeartBeat > 90000) | |
{ | |
// Send Hearbeat every 90seconds to firebase server | |
pvsHeartBeat = millis(); | |
Firebase.RTDB.setTimestampAsync(&fbdo, "/SAREPH3/devel/live/heartbeat"); | |
} | |
unsigned duration = 15 * 60000; //15 min | |
unsigned awaketime = (millis() - starttime); | |
// Turn OFF this entire below BLOCK, if this MODULE connected to ALWAYS ON power supply !! | |
// BLOCK START | |
if (!val && (awaketime > duration)) | |
{ | |
// Sleep the device, if DG is OFF for more than 15mins | |
Serial.println("Good to sleep now.. "); | |
ESP.deepSleep(0); | |
} | |
// BLOCK END | |
// PROCESS INTERUPT RECEIVED ON D5 | |
if (GotInterrupt) | |
{ | |
GotInterrupt = false; | |
starttime = millis(); // reset SLEEP timer | |
time_t now = time(nullptr); | |
Serial.printf("\n%s : Got Interrupt ", ctime(&now)); | |
Serial.printf("\nWaiting 7 seconds before posting : %d", !digitalRead(LDR_DETECT)); | |
unsigned long ticker = millis(); | |
// Insert Delayed Action, to avoid fluctuating interrupt | |
while (millis() - ticker < 7000) | |
{ | |
if (((millis() - ticker) % 1000) == 0) | |
{ | |
Serial.printf(".."); | |
} | |
} | |
Serial.printf("\nReady to execute "); | |
// SEND if only NEW Status, this avoids the 45second repeated interrupt | |
if (val != !digitalRead(LDR_DETECT) || firstboot) { | |
val = !digitalRead(LDR_DETECT); | |
Serial.printf("\nSending now PIN is %d", val); | |
firstboot = false; | |
if (Firebase.ready()) | |
{ | |
FirebaseJson json; | |
json.set("DGversion", "PESindicator"); | |
if (!val) | |
{ | |
json.set("DG", false); | |
json.set("lastOFFtime", now - TZOFFFSET); | |
json.set("updatedtime/.sv", "timestamp"); | |
} | |
else | |
{ | |
json.set("DG", true); | |
json.set("lastONtime", now - TZOFFFSET); | |
json.set("lastOFFtime", 0); | |
json.set("updatedtime/.sv", "timestamp"); | |
} | |
Firebase.RTDB.updateNode(&fbdo, "/SAREPH3/devel/live/status", &json); | |
Firebase.RTDB.setTimestampAsync(&fbdo, "/SAREPH3/devel/live/heartbeat"); | |
} | |
} | |
else { | |
Serial.printf("\nIgnoring Interrupt"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks