#include <ESP8266WiFi.h>
extern "C" {
#include "gpio.h"
#include "user_interface.h"
}
const char* ssid = "Slacky";
const char* password = "************";
WiFiClient client;
#define HOT_PIN D1 /* Number of Pin for hot water */
#define COLD_PIN D2 /* Number of Pin for cold water */
#define EXT_POWER_PIN D0
volatile unsigned long counterHotWater, counterColdWater;
bool offWiFi;
int powerPause;
void setup() {
Serial.begin(115200);
Serial.println("\n\nInitializing GPIOs");
initPin();
initInterrupt();
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
delay(1000);
counterHotWater = 0; counterColdWater = 0;
powerPause = 0;
}
void loop() {
Serial.printf("counterHotWater: %lu\n", counterHotWater);
Serial.printf("counterColdWater: %lu\n", counterColdWater);
Serial.printf("powerPause: %d\n", powerPause);
ESP.wdtFeed();
offWiFi = false;
checkExtPower();
if (offWiFi) sleepNow();
delay(1000);
}
void sleepNow() {
Serial.println("going to light sleep...");
wifi_station_disconnect();
wifi_set_opmode(NULL_MODE);
wifi_fpm_set_sleep_type(LIGHT_SLEEP_T); //light sleep mode
gpio_pin_wakeup_enable(GPIO_ID_PIN(HOT_PIN), GPIO_PIN_INTR_LOLEVEL); //set the interrupt to look for HIGH pulses on Pin 0 (the PIR).
gpio_pin_wakeup_enable(GPIO_ID_PIN(COLD_PIN), GPIO_PIN_INTR_LOLEVEL); //set the interrupt to look for HIGH pulses on Pin 0 (the PIR).
wifi_fpm_open();
delay(100);
wifi_fpm_set_wakeup_cb(wakeupFromMotion); //wakeup callback
wifi_fpm_do_sleep(0xFFFFFFF);
delay(100);
}
void wakeupFromMotion(void) {
ESP.wdtFeed();
initInterrupt();
wifi_fpm_close();
wifi_set_opmode(STATION_MODE);
wifi_station_connect();
Serial.println("Woke up from sleep");
}
void initPin() {
pinMode(HOT_PIN, INPUT);
digitalWrite(HOT_PIN, HIGH);
pinMode(COLD_PIN, INPUT);
digitalWrite(COLD_PIN, HIGH);
pinMode(EXT_POWER_PIN, INPUT_PULLDOWN_16);
}
/* Init external interrupt */
void initInterrupt() {
attachInterrupt(digitalPinToInterrupt(HOT_PIN), hotInterrupt, RISING);
attachInterrupt(digitalPinToInterrupt(COLD_PIN), coldInterrupt, RISING);
}
/* External interrupt for hot water */
void hotInterrupt() {
counterHotWater++;
Serial.printf("counterHotWater: %lu\n", counterHotWater);
}
/* External interrupt for cold water */
void coldInterrupt() {
counterColdWater++;
Serial.printf("counterColdWater: %lu\n", counterColdWater);
}
bool checkExtPower() {
int val = digitalRead(EXT_POWER_PIN);
if (val) {
powerPause = 0;
if (offWiFi) {
Serial.println("External power high. WiFi on");
offWiFi = false;
}
return true;
}
else {
if (!offWiFi) {
if (powerPause > 9) {
Serial.println("External power low. WiFi off.");
offWiFi = true;
powerPause = 0;
return false;
} else {
powerPause++;
}
}
return false;
}
}