Sense when the cable is disconnected

This commit is contained in:
Tanner Collin 2024-07-01 13:08:18 -06:00
parent 59a53a6aca
commit 8b22554c94

View File

@ -13,8 +13,9 @@
#define NUM_SAMPLES 20 #define NUM_SAMPLES 20
#define SAMPLE_TIME 100 #define SAMPLE_TIME 100
#define WATER_THRESHOLD 750 #define WATER_THRESHOLD 750
#define SENSE_THRESHOLD 100
#define MESSAGE_INTERVAL 1000 * 60 * 60 // one hour #define MESSAGE_INTERVAL 1000 * 60 * 50 // 50 minutes
WiFiClient wifiClient; WiFiClient wifiClient;
MqttClient mqttClient(wifiClient); MqttClient mqttClient(wifiClient);
@ -60,6 +61,16 @@ bool sampleWater() {
return waterDetected; return waterDetected;
} }
bool senseCable() {
int sample = analogRead(ADC_PIN);
if (sample < SENSE_THRESHOLD) {
return false;
} else {
return true;
}
}
void sendWaterLeakTrue() { void sendWaterLeakTrue() {
mqttClient.beginMessage(topic); mqttClient.beginMessage(topic);
mqttClient.print("{\"id\": \""); mqttClient.print("{\"id\": \"");
@ -76,8 +87,17 @@ void sendWaterLeakFalse() {
mqttClient.endMessage(); mqttClient.endMessage();
} }
void sendCableDisconnected() {
mqttClient.beginMessage(topic);
mqttClient.print("{\"id\": \"");
mqttClient.print(deviceName);
mqttClient.print("\", \"cable_disconnected\": true}");
mqttClient.endMessage();
}
void setup() { void setup() {
pinMode(RELAY_PIN, OUTPUT); pinMode(RELAY_PIN, OUTPUT);
relayOff();
Serial.begin(115200); Serial.begin(115200);
delay(1000); delay(1000);
@ -112,19 +132,23 @@ void setup() {
Serial.println("[MQTT] Connected to the MQTT broker."); Serial.println("[MQTT] Connected to the MQTT broker.");
Serial.println("Turning relay on."); Serial.println("Finished setup, turning relay on...");
delay(1000);
relayOn(); relayOn();
delay(5000);
} }
void loop() { void loop() {
static unsigned long last_pos_message = 0; static unsigned long last_pos_message = 0;
static unsigned long last_neg_message = 0; static unsigned long last_neg_message = 0;
static unsigned long last_sense_message = 0;
bool leakDetected = sampleWater(); bool leakDetected = sampleWater();
bool cableDetected = senseCable();
if (leakDetected) { if (leakDetected) {
relayOff(); relayOff();
Serial.println("Leak detected"); Serial.println("Leak detected!");
} }
mqttClient.poll(); mqttClient.poll();
@ -155,4 +179,12 @@ void loop() {
sendWaterLeakFalse(); sendWaterLeakFalse();
} }
} }
if (!cableDetected) {
Serial.println("Cable not detected!");
if (!last_sense_message || millis() - last_sense_message > MESSAGE_INTERVAL) {
last_sense_message = millis();
sendCableDisconnected();
}
}
} }