Compare commits

...

4 Commits

View File

@ -1,3 +1,5 @@
// Board: Adafruit Feather HUZZAH ESP8266
#include <ArduinoMqttClient.h>
#include <ESP8266WiFi.h>
@ -11,8 +13,10 @@
#define NUM_SAMPLES 20
#define SAMPLE_TIME 100
#define WATER_THRESHOLD 750
#define SENSE_THRESHOLD 100
#define MESSAGE_INTERVAL 1000 * 60 * 60 // one hour
#define MESSAGE_INTERVAL 1000 * 60 * 20 // 20 minutes
#define RESTART_INTERVAL 1000 * 60 * 60 * 24 * 7 // 7 days
WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);
@ -58,6 +62,16 @@ bool sampleWater() {
return waterDetected;
}
bool senseCable() {
int sample = analogRead(ADC_PIN);
if (sample < SENSE_THRESHOLD) {
return false;
} else {
return true;
}
}
void sendWaterLeakTrue() {
mqttClient.beginMessage(topic);
mqttClient.print("{\"id\": \"");
@ -74,8 +88,17 @@ void sendWaterLeakFalse() {
mqttClient.endMessage();
}
void sendCableDisconnected() {
mqttClient.beginMessage(topic);
mqttClient.print("{\"id\": \"");
mqttClient.print(deviceName);
mqttClient.print("\", \"cable_disconnected\": true}");
mqttClient.endMessage();
}
void setup() {
pinMode(RELAY_PIN, OUTPUT);
relayOff();
Serial.begin(115200);
delay(1000);
@ -92,6 +115,8 @@ void setup() {
delay(500);
Serial.print(".");
}
WiFi.setAutoReconnect(true);
WiFi.persistent(true);
Serial.println("");
Serial.println("[WIFI] Connected to the network");
@ -110,25 +135,39 @@ void setup() {
Serial.println("[MQTT] Connected to the MQTT broker.");
Serial.println("Turning relay on.");
Serial.println("Finished setup, turning relay on...");
delay(1000);
relayOn();
delay(5000);
}
void loop() {
static unsigned long last_pos_message = 0;
static unsigned long last_neg_message = 0;
static unsigned long last_sense_message = 0;
static bool hasTriggered = false;
bool leakDetected = sampleWater();
bool cableDetected = senseCable();
if (leakDetected) {
relayOff();
Serial.println("Leak detected");
hasTriggered = true;
Serial.println("Leak detected!");
}
if (!hasTriggered && millis() > RESTART_INTERVAL) {
Serial.println("Weekly restarting Arduino...");
relayOff();
ESP.restart();
}
mqttClient.poll();
if (WiFi.status() != WL_CONNECTED) {
Serial.println("[WIFI] Lost connection. Reconnecting...");
WiFi.disconnect();
WiFi.begin(SECRET_SSID, SECRET_PASS);
return;
} else if (!mqttClient.connected()) {
@ -153,4 +192,12 @@ void loop() {
sendWaterLeakFalse();
}
}
if (!cableDetected) {
Serial.println("Cable not detected!");
if (!last_sense_message || millis() - last_sense_message > MESSAGE_INTERVAL) {
last_sense_message = millis();
sendCableDisconnected();
}
}
}