-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.cpp
More file actions
1163 lines (1069 loc) · 30.9 KB
/
Copy pathindex.cpp
File metadata and controls
1163 lines (1069 loc) · 30.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
#include <esp_system.h>
// ==================== PIN DEFINITIONS ====================
#define DHTPIN 13
#define DHTTYPE DHT22
#define SOIL_PIN 34
#define LDR_PIN 35
#define RAIN_PIN 32
#define WATER_LEVEL_PIN 33
#define PUMP_RELAY 16
#define FAN1_RELAY 26
#define FAN2_RELAY 27
#define MANUAL_BUTTON 4
#define WIFI_STATUS_LED 2
#define PROJECT_NAME "SmartFarm"
#define VERSION "v3.2"
// ==================== TEMPERATURE THRESHOLDS ====================
#define TEMP_FAN1_ON 22
#define TEMP_FAN1_OFF 18
#define TEMP_FAN2_ON 24
#define TEMP_FAN2_OFF 20
#define TEMP_CRITICAL 35
// ==================== SOIL MOISTURE THRESHOLDS (0-4095) ====================
#define SOIL_VERY_DRY 3500
#define SOIL_DRY 2800
#define SOIL_OPTIMAL_MAX 2200
#define SOIL_WET 1500
#define SOIL_VERY_WET 800
// ==================== RAIN SENSOR THRESHOLDS ====================
#define RAIN_CLEAR 3500
#define RAIN_LIGHT 2500
#define RAIN_THRESHOLD 3500
#define RAIN_HEAVY 1000
#define RAIN_HEAVY_THRESH 1500
// ==================== WATER LEVEL THRESHOLDS (higher = more water) ====================
#define WATER_CRITICAL 1000
#define WATER_PUMP_OFF 2400
#define WATER_PUMP_ON 2600
#define WATER_FULL 4500
// ==================== NETWORK & CLOUD ====================
#define THINGSPEAK_WRITE_KEY "NC47N46ACJUARDCK"
const char *server = "http://api.thingspeak.com/update";
const char *ssid = "Kuet21";
const char *password = "89777145!!";
#define BOT_TOKEN "8435066468:AAGJiyvhtlUxYoXluewx7oV0zcy53vYaXaM"
#define CHAT_ID "6436948731"
WiFiClientSecure secured_client;
UniversalTelegramBot bot(BOT_TOKEN, secured_client);
// ==================== TIMING INTERVALS (ms) ====================
#define UPLOAD_INTERVAL 15000
#define SENSOR_READ_INTERVAL 1000
#define LCD_UPDATE_INTERVAL 500
#define TELEGRAM_ALERT_INTERVAL 60000
#define TELEGRAM_STATUS_INTERVAL 600000
#define TELEGRAM_POLL_INTERVAL 2000
#define RELAY_SWITCH_DELAY 50 // minimum time between relay changes
// ==================== PUMP TIMING & SAFETY ====================
const unsigned long MIN_PUMP_ON_TIME = 10000;
const unsigned long MIN_PUMP_OFF_TIME = 10000;
const unsigned long SAFETY_STARTUP_DELAY = 5000;
bool systemReady = false;
DHT dht(DHTPIN, DHTTYPE);
LiquidCrystal_I2C lcd(0x27, 16, 2);
unsigned long lastUpload = 0;
unsigned long lastSensorRead = 0;
unsigned long lastLCDUpdate = 0;
unsigned long lastTelegramAlert = 0;
unsigned long lastTelegramStatus = 0;
unsigned long lastTelegramPoll = 0;
unsigned long lastDHTRead = 0;
unsigned long pumpStartTime = 0;
unsigned long lastPumpChange = 0;
float temperature = 0;
float humidity = 0;
int soilMoisture = 0;
int lightLevel = 0;
int rainLevel = 0;
int waterLevel = 0;
bool pumpStatus = false;
bool fan1Status = false;
bool fan2Status = false;
bool manualMode = false;
bool manualPumpRequest = false;
bool isRaining = false;
bool isHeavyRain = false;
int lcdScreen = 0;
const int TOTAL_SCREENS = 7;
bool criticalTempAlertSent = false;
bool criticalWaterAlertSent = false;
bool criticalSoilAlertSent = false;
bool heavyRainAlertSent = false;
bool pumpStuckAlertSent = false;
bool wifiDisconnectAlertSent = false;
bool dhtFaultAlertSent = false;
String pumpReason = "";
String activeFaults = "";
unsigned long faultStartTime = 0;
// Moving average buffers
const int AVG_SAMPLES = 5;
int waterReadings[5] = {0};
int soilReadings[5] = {0};
int waterIndex = 0, soilIndex = 0;
int waterTotal = 0, soilTotal = 0;
// Debug
unsigned long lastDebugPrint = 0;
#define DEBUG_INTERVAL 5000
// ---------- Non‑blocking relay control ----------
unsigned long lastRelayChange = 0; // timestamp of last relay write
bool pendingRelayChanges = false; // flag to retry on next loop
struct RelayCommand
{
uint8_t pin;
bool state; // true = LOW (relay ON), false = HIGH (relay OFF)
};
RelayCommand nextRelayCmd; // command to execute when cooldown allows
// ==================== FUNCTION DECLARATIONS ====================
String getTimeString();
String getSoilCondition();
String getRainCondition();
String getPlantGrowthStatus();
bool isSoilDry();
bool isSoilVeryDry();
bool isSoilWet();
bool shouldPumpRun();
void checkAndReportFaults();
void sendStatusUpdate();
void readSensors();
void controlIrrigation();
void controlPoultryFans();
void checkButton();
void updateLCD();
void printData();
void sendToThingSpeak();
void handleTelegramMessages();
void debugManualState();
void debugWaterLevelLogic();
void setRelayNonBlocking(uint8_t pin, bool state);
// ==================== UTILITY ====================
void printResetReason()
{
esp_reset_reason_t reason = esp_reset_reason();
Serial.print("Reset reason: ");
switch (reason)
{
case ESP_RST_POWERON:
Serial.println("Power-on");
break;
case ESP_RST_EXT:
Serial.println("External pin");
break;
case ESP_RST_SW:
Serial.println("Software");
break;
case ESP_RST_PANIC:
Serial.println("Exception/panic");
break;
case ESP_RST_INT_WDT:
Serial.println("Interrupt watchdog");
break;
case ESP_RST_TASK_WDT:
Serial.println("Task watchdog");
break;
case ESP_RST_WDT:
Serial.println("Other watchdog");
break;
case ESP_RST_DEEPSLEEP:
Serial.println("Deep sleep wake");
break;
case ESP_RST_BROWNOUT:
Serial.println("Brownout (power dip!)");
break;
case ESP_RST_SDIO:
Serial.println("SDIO");
break;
default:
Serial.println("Unknown");
}
}
String getTimeString()
{
unsigned long seconds = millis() / 1000;
int hours = (seconds / 3600) % 24;
int minutes = (seconds / 60) % 60;
int secs = seconds % 60;
char timeStr[9];
sprintf(timeStr, "%02d:%02d:%02d", hours, minutes, secs);
return String(timeStr);
}
// ==================== SOIL / RAIN / PLANT ====================
String getSoilCondition()
{
if (soilMoisture > SOIL_VERY_DRY)
return "VERY DRY";
if (soilMoisture > SOIL_DRY)
return "DRY";
if (soilMoisture > SOIL_OPTIMAL_MAX)
return "OPTIMAL";
if (soilMoisture > SOIL_WET)
return "WET";
return "VERY WET";
}
bool isSoilDry() { return (soilMoisture > SOIL_DRY); }
bool isSoilVeryDry() { return (soilMoisture > SOIL_VERY_DRY); }
bool isSoilWet() { return (soilMoisture < SOIL_WET); }
String getRainCondition()
{
if (rainLevel < RAIN_HEAVY_THRESH)
return "HEAVY";
if (rainLevel < RAIN_THRESHOLD)
return "LIGHT";
if (rainLevel > RAIN_CLEAR)
return "CLEAR";
return "DAMP";
}
String getPlantGrowthStatus()
{
if (soilMoisture == 0 || lightLevel == 0)
return "SENSOR ERR";
bool soilGood = (soilMoisture >= SOIL_WET && soilMoisture <= SOIL_DRY);
bool lightGood = (lightLevel > 1500);
if (soilMoisture > SOIL_VERY_DRY)
return "WILTING!";
if (soilMoisture < SOIL_VERY_WET)
return "ROT!";
if (lightLevel < 500)
return "NO LIGHT!";
if (soilGood && lightGood)
return "THRIVING!";
if (!soilGood && !lightGood)
return "CRITICAL";
if (!soilGood)
return "SOIL BAD";
if (!lightGood)
return "LIGHT BAD";
return "FAIR";
}
// ==================== PUMP DECISION (HYSTERESIS + SAFETY) ====================
// Safety overrides ALWAYS take precedence.
// Hysteresis: pump stays ON until water drops below OFF threshold;
// pump stays OFF until water rises above ON threshold.
bool shouldPumpRun()
{
if (!systemReady)
{
pumpReason = "System starting";
return false;
}
// 1. CRITICAL SAFETY – absolute block
if (waterLevel < WATER_CRITICAL)
{
pumpReason = "EMERGENCY: Critical low water";
return false;
}
// 2. TANK FULL PROTECTION – prevent overflow
if (waterLevel > WATER_FULL)
{
pumpReason = "Tank full - overflow prevention";
return false;
}
// 3. HYSTERESIS (stable ON/OFF)
if (pumpStatus)
{
// Pump is ON → keep ON until water drops below OFF threshold
if (waterLevel < WATER_PUMP_OFF)
{
pumpReason = "Water dropped below OFF threshold";
return false;
}
}
else
{
// Pump is OFF → only allow start if water is above ON threshold
if (waterLevel < WATER_PUMP_ON)
{
pumpReason = "Water too low to start (needs >" + String(WATER_PUMP_ON) + ")";
return false;
}
}
// 4. MANUAL OVERRIDE (safety already applied above)
if (manualMode)
{
pumpReason = manualPumpRequest ? "Manual ON" : "Manual OFF";
return manualPumpRequest;
}
// 5. RAIN LOGIC
if (isHeavyRain)
{
pumpReason = "Heavy rain - pump disabled";
return false;
}
if (isRaining)
{
if (isSoilVeryDry())
{
pumpReason = "Light rain, but soil VERY dry";
return true;
}
else
{
pumpReason = "Raining, soil moisture OK";
return false;
}
}
// 6. SOIL MOISTURE
if (isSoilVeryDry())
{
pumpReason = "Soil VERY dry - urgent watering needed";
return true;
}
if (isSoilDry())
{
pumpReason = "Soil dry - watering needed";
return true;
}
if (soilMoisture <= SOIL_OPTIMAL_MAX)
{
pumpReason = "Soil moisture optimal";
return false;
}
if (isSoilWet())
{
pumpReason = "Soil wet - no watering needed";
return false;
}
pumpReason = "Conditions not met for watering";
return false;
}
// ==================== DEBUG ====================
void debugWaterLevelLogic()
{
Serial.println("\n========== WATER LEVEL DEBUG ==========");
Serial.print("Water Level Reading: ");
Serial.println(waterLevel);
Serial.print("Pump Status: ");
Serial.println(pumpStatus ? "ON" : "OFF");
Serial.print("Manual Mode: ");
Serial.println(manualMode ? "YES" : "NO");
Serial.println("\nThresholds:");
Serial.print(" CRITICAL: < ");
Serial.print(WATER_CRITICAL);
Serial.print(" (Current: ");
Serial.print(waterLevel < WATER_CRITICAL ? "BELOW" : "ABOVE");
Serial.println(")");
Serial.print(" PUMP OFF: < ");
Serial.print(WATER_PUMP_OFF);
Serial.print(" (Current: ");
Serial.print(waterLevel < WATER_PUMP_OFF ? "BELOW" : "ABOVE");
Serial.println(")");
Serial.print(" PUMP ON : > ");
Serial.print(WATER_PUMP_ON);
Serial.print(" (Current: ");
Serial.print(waterLevel >= WATER_PUMP_ON ? "ABOVE" : "BELOW");
Serial.println(")");
Serial.print(" FULL : > ");
Serial.print(WATER_FULL);
Serial.print(" (Current: ");
Serial.print(waterLevel > WATER_FULL ? "ABOVE" : "BELOW");
Serial.println(")");
Serial.println("\nDecision:");
Serial.print(" Pump reason: ");
Serial.println(pumpReason);
Serial.println("========================================\n");
}
// ==================== TELEGRAM & FAULTS ====================
void sendTelegramMessage(String message, bool isAlert)
{
if (WiFi.status() != WL_CONNECTED)
return;
String prefix = isAlert ? "⚠️ ALERT: " : "📱 ";
String fullMessage = prefix + message + "\n\n⏰ Time: " + getTimeString();
for (int attempts = 0; attempts < 3; attempts++)
{
yield();
if (bot.sendMessage(CHAT_ID, fullMessage, ""))
break;
delay(1000);
}
}
void updateRainStatus()
{
bool wasRaining = isRaining;
bool wasHeavyRain = isHeavyRain;
isHeavyRain = (rainLevel < RAIN_HEAVY_THRESH);
isRaining = (rainLevel < RAIN_THRESHOLD);
if (isHeavyRain)
isRaining = true;
if (isRaining != wasRaining || isHeavyRain != wasHeavyRain)
{
if (isHeavyRain)
sendTelegramMessage("HEAVY RAIN STARTED!\nPump disabled.\nRain level: " + String(rainLevel), true);
else if (isRaining && !wasRaining)
sendTelegramMessage("RAIN DETECTED!\nPump only if soil very dry.\nRain level: " + String(rainLevel), true);
else if (!isRaining && wasRaining)
sendTelegramMessage("RAIN STOPPED!\nResuming normal pump.\nRain level: " + String(rainLevel), true);
}
}
void checkAndReportFaults()
{
String currentFaults = "";
bool hasFault = false;
if (temperature > TEMP_CRITICAL)
{
currentFaults += "🔥 CRITICAL TEMPERATURE: " + String(temperature, 1) + "°C\n";
hasFault = true;
if (!criticalTempAlertSent)
{
sendTelegramMessage("⚠️ CRITICAL TEMPERATURE FAULT!\nTemperature: " + String(temperature, 1) + "°C\nBoth fans activated automatically!", true);
criticalTempAlertSent = true;
}
}
else if (temperature < 5 && temperature > 0)
{
currentFaults += "❄️ VERY LOW TEMPERATURE: " + String(temperature, 1) + "°C\n";
hasFault = true;
if (!criticalTempAlertSent)
{
sendTelegramMessage("⚠️ LOW TEMPERATURE FAULT!\nTemperature: " + String(temperature, 1) + "°C\nPlant frost risk detected!", true);
criticalTempAlertSent = true;
}
}
else
{
criticalTempAlertSent = false;
}
if (waterLevel < WATER_CRITICAL)
{
currentFaults += "💧 CRITICAL WATER LEVEL: " + String(waterLevel) + "\n";
hasFault = true;
if (!criticalWaterAlertSent)
{
sendTelegramMessage("⚠️ CRITICAL WATER FAULT!\nWater level critically low: " + String(waterLevel) + "\nPump emergency stopped!\nPlease refill water tank immediately!", true);
criticalWaterAlertSent = true;
}
}
else if (waterLevel < WATER_PUMP_OFF)
{
currentFaults += "💧 LOW WATER LEVEL: " + String(waterLevel) + "\n";
hasFault = true;
if (!criticalWaterAlertSent)
{
sendTelegramMessage("⚠️ LOW WATER WARNING!\nWater level low: " + String(waterLevel) + "\nPlease refill water tank soon.", true);
criticalWaterAlertSent = true;
}
}
else if (waterLevel > WATER_FULL)
{
currentFaults += "💧 TANK FULL: " + String(waterLevel) + "\n";
hasFault = true;
}
else
{
criticalWaterAlertSent = false;
}
// Other fault checks (soil, pump stuck, etc.) remain unchanged for brevity.
// ... [Include your existing fault checks here]
if (hasFault)
{
if (activeFaults != currentFaults)
{
if (activeFaults != "")
sendTelegramMessage("📋 FAULT SUMMARY:\n" + currentFaults, true);
activeFaults = currentFaults;
faultStartTime = millis();
}
}
else
{
if (activeFaults != "")
{
sendTelegramMessage("✅ All faults cleared!\nSystem restored to normal operation.", true);
activeFaults = "";
}
}
}
void sendStatusUpdate()
{
String status = "📊 SYSTEM STATUS REPORT\n\n";
status += "🌡️ Temperature: " + String(temperature, 1) + "°C\n";
status += "💧 Humidity: " + String(humidity, 1) + "%\n";
status += "🌱 Soil Moisture: " + String(soilMoisture) + " (" + getSoilCondition() + ")\n";
status += "💧 Water Level: " + String(waterLevel);
if (waterLevel < WATER_CRITICAL)
status += " (CRITICAL!)";
else if (waterLevel < WATER_PUMP_OFF)
status += " (LOW)";
else if (waterLevel > WATER_FULL)
status += " (FULL)";
else
status += " (OK)";
status += "\n☀️ Light: " + String(lightLevel) + "\n";
status += "☔ Rain: " + getRainCondition() + " (" + String(rainLevel) + ")\n";
status += "💧 Pump: " + String(pumpStatus ? "ON" : "OFF");
if (pumpStatus)
status += " (" + pumpReason + ")";
status += "\n🌀 Fan1: " + String(fan1Status ? "ON" : "OFF");
status += " Fan2: " + String(fan2Status ? "ON" : "OFF") + "\n";
status += "⚙️ Mode: " + String(manualMode ? "MANUAL" : "AUTO") + "\n";
status += "🌱 Plant: " + getPlantGrowthStatus();
sendTelegramMessage(status, false);
}
// ==================== SENSOR READING ====================
void readSensors()
{
int rawSoil = analogRead(SOIL_PIN);
int rawWater = analogRead(WATER_LEVEL_PIN);
waterTotal -= waterReadings[waterIndex];
waterReadings[waterIndex] = rawWater;
waterTotal += rawWater;
waterIndex = (waterIndex + 1) % AVG_SAMPLES;
waterLevel = waterTotal / AVG_SAMPLES;
soilTotal -= soilReadings[soilIndex];
soilReadings[soilIndex] = rawSoil;
soilTotal += rawSoil;
soilIndex = (soilIndex + 1) % AVG_SAMPLES;
soilMoisture = soilTotal / AVG_SAMPLES;
lightLevel = analogRead(LDR_PIN);
rainLevel = analogRead(RAIN_PIN);
if (millis() - lastDHTRead >= 2000)
{
lastDHTRead = millis();
float newTemp = dht.readTemperature();
float newHum = dht.readHumidity();
if (!isnan(newTemp))
temperature = newTemp;
if (!isnan(newHum))
humidity = newHum;
}
updateRainStatus();
}
// ---------- Non‑blocking relay setter ----------
// Schedules a relay change; the change happens immediately if cooldown allows,
// otherwise it is queued for the next loop iteration.
void setRelayNonBlocking(uint8_t pin, bool state)
{
// If cooldown has passed, execute immediately
if (millis() - lastRelayChange >= RELAY_SWITCH_DELAY)
{
digitalWrite(pin, state ? LOW : HIGH); // active LOW
lastRelayChange = millis();
pendingRelayChanges = false;
}
else
{
// Queue the command for next opportunity
nextRelayCmd.pin = pin;
nextRelayCmd.state = state;
pendingRelayChanges = true;
}
}
// Call this in loop() to process any queued relay command
void processPendingRelay()
{
if (pendingRelayChanges && (millis() - lastRelayChange >= RELAY_SWITCH_DELAY))
{
digitalWrite(nextRelayCmd.pin, nextRelayCmd.state ? LOW : HIGH);
lastRelayChange = millis();
pendingRelayChanges = false;
}
}
// ==================== AGRICULTURE CONTROL (PUMP ONLY) ====================
void controlIrrigation()
{
bool newPumpState;
if (manualMode)
{
// Manual mode – enforce safety
if (waterLevel < WATER_CRITICAL)
{
newPumpState = false;
pumpReason = "Manual blocked: Critical low water";
}
else if (waterLevel > WATER_FULL && manualPumpRequest)
{
newPumpState = false;
pumpReason = "Manual blocked: Tank full";
}
else
{
newPumpState = manualPumpRequest;
pumpReason = manualPumpRequest ? "Manual ON" : "Manual OFF";
}
}
else
{
newPumpState = shouldPumpRun();
}
if (newPumpState != pumpStatus)
{
unsigned long timeSinceLastChange = millis() - lastPumpChange;
unsigned long requiredDelay = pumpStatus ? MIN_PUMP_OFF_TIME : MIN_PUMP_ON_TIME;
if (timeSinceLastChange >= requiredDelay)
{
pumpStatus = newPumpState;
setRelayNonBlocking(PUMP_RELAY, pumpStatus); // non‑blocking
lastPumpChange = millis();
Serial.printf("PUMP: %s | Water: %d | Soil: %d | Reason: %s\n",
pumpStatus ? "ON" : "OFF", waterLevel, soilMoisture, pumpReason.c_str());
if (pumpStatus)
{
pumpStartTime = millis();
sendTelegramMessage("💧 PUMP TURNED ON\nReason: " + pumpReason, false);
}
else
{
if (pumpReason != "Conditions not met" && pumpReason != "Soil optimal" && pumpReason != "Soil wet")
sendTelegramMessage("💧 PUMP TURNED OFF\nReason: " + pumpReason, false);
}
}
}
// Pump stuck protection
if (pumpStatus && (millis() - pumpStartTime > 1800000))
{
pumpStatus = false;
setRelayNonBlocking(PUMP_RELAY, false);
lastPumpChange = millis();
sendTelegramMessage("⚠️ PUMP AUTO-SHUTDOWN\nRan 30 min! Check for leaks!", true);
}
}
// ==================== POULTRY CONTROL (FANS ONLY) ====================
void controlPoultryFans()
{
// Fan 1
bool newFan1 = fan1Status;
if (temperature > TEMP_FAN1_ON)
newFan1 = true;
else if (temperature < TEMP_FAN1_OFF)
newFan1 = false;
if (newFan1 != fan1Status)
{
fan1Status = newFan1;
setRelayNonBlocking(FAN1_RELAY, fan1Status);
if (fan1Status)
sendTelegramMessage("🌀 FAN 1 ACTIVATED\nTemperature: " + String(temperature, 1) + "°C", false);
}
// Fan 2
bool newFan2 = fan2Status;
if (temperature > TEMP_FAN2_ON)
newFan2 = true;
else if (temperature < TEMP_FAN2_OFF)
newFan2 = false;
if (newFan2 != fan2Status)
{
fan2Status = newFan2;
setRelayNonBlocking(FAN2_RELAY, fan2Status);
if (fan2Status)
sendTelegramMessage("🌀🌀 FAN 2 ACTIVATED\nTemperature: " + String(temperature, 1) + "°C", false);
}
// Critical temperature override
if (temperature > TEMP_CRITICAL)
{
if (!fan1Status)
{
fan1Status = true;
setRelayNonBlocking(FAN1_RELAY, true);
}
if (!fan2Status)
{
fan2Status = true;
setRelayNonBlocking(FAN2_RELAY, true);
}
}
}
// ==================== BUTTON HANDLING ====================
void checkButton()
{
static unsigned long lastDebounceTime = 0;
static bool lastButtonState = HIGH;
static bool buttonState = HIGH;
static unsigned long pressStart = 0;
static bool longPressDetected = false;
const unsigned long debounceDelay = 50;
const unsigned long longPressTime = 2000;
bool reading = digitalRead(MANUAL_BUTTON);
if (reading != lastButtonState)
lastDebounceTime = millis();
if ((millis() - lastDebounceTime) > debounceDelay)
{
if (reading != buttonState)
{
buttonState = reading;
if (buttonState == LOW)
{
pressStart = millis();
longPressDetected = false;
}
else
{
if (!longPressDetected)
{
manualMode = !manualMode;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(PROJECT_NAME);
lcd.print(" ");
lcd.print(VERSION);
lcd.setCursor(0, 1);
lcd.print("Mode: ");
lcd.print(manualMode ? "MANUAL" : "AUTO");
delay(1500);
lcd.clear();
lcdScreen = -1;
sendTelegramMessage("🔄 SYSTEM MODE CHANGED\nMode: " + String(manualMode ? "MANUAL" : "AUTO"), false);
controlIrrigation();
}
}
}
if (buttonState == LOW && !longPressDetected && (millis() - pressStart >= longPressTime))
{
longPressDetected = true;
if (manualMode)
{
manualPumpRequest = !manualPumpRequest;
lcd.clear();
lcd.setCursor(0, 0);
lcd.print(PROJECT_NAME);
lcd.print(" ");
lcd.print(VERSION);
lcd.setCursor(0, 1);
lcd.print("Pump ");
lcd.print(manualPumpRequest ? "ON" : "OFF");
delay(1500);
lcd.clear();
lcdScreen = -1;
sendTelegramMessage("💧 MANUAL PUMP CONTROL\nPump: " + String(manualPumpRequest ? "ON" : "OFF"), false);
controlIrrigation();
}
}
}
lastButtonState = reading;
}
// ==================== LCD ====================
void updateLCD()
{
if (millis() - lastLCDUpdate < LCD_UPDATE_INTERVAL)
return;
lastLCDUpdate = millis();
lcdScreen = (lcdScreen + 1) % TOTAL_SCREENS;
lcd.clear();
switch (lcdScreen)
{
case 0:
lcd.setCursor(0, 0);
lcd.print(PROJECT_NAME);
lcd.print(" ");
lcd.print(VERSION);
lcd.setCursor(0, 1);
lcd.print("Uptime: ");
lcd.print(getTimeString());
break;
case 1:
lcd.setCursor(0, 0);
lcd.print("Temp:");
lcd.setCursor(0, 1);
lcd.print(temperature, 1);
lcd.print("C");
break;
case 2:
lcd.setCursor(0, 0);
lcd.print("Humidity:");
lcd.setCursor(0, 1);
lcd.print(humidity, 1);
lcd.print("%");
break;
case 3:
lcd.setCursor(0, 0);
lcd.print("Water:");
lcd.setCursor(0, 1);
lcd.print(waterLevel);
lcd.print(" (");
if (waterLevel >= WATER_PUMP_ON)
lcd.print("HIGH");
else if (waterLevel < WATER_PUMP_OFF)
lcd.print("LOW");
else
lcd.print("MID");
lcd.print(")");
break;
case 4:
lcd.setCursor(0, 0);
lcd.print("Soil:");
lcd.print(soilMoisture);
lcd.print(" ");
lcd.print(getSoilCondition());
lcd.setCursor(0, 1);
lcd.print("Rain:");
lcd.print(getRainCondition());
lcd.print(" ");
lcd.print(rainLevel);
break;
case 5:
lcd.setCursor(0, 0);
lcd.print("Plant: ");
lcd.print(getPlantGrowthStatus());
lcd.setCursor(0, 1);
lcd.print("Soil:");
lcd.print(soilMoisture);
lcd.print(" L:");
lcd.print(lightLevel);
break;
case 6:
lcd.setCursor(0, 0);
lcd.print("P:");
lcd.print(pumpStatus ? "ON " : "OFF");
lcd.print("F1:");
lcd.print(fan1Status ? "ON " : "OFF");
lcd.print("F2:");
lcd.print(fan2Status ? "ON" : "OFF");
lcd.setCursor(0, 1);
lcd.print("Light:");
lcd.print(lightLevel);
break;
}
}
// ==================== SERIAL OUTPUT ====================
void printData()
{
Serial.println("\n=== " + String(PROJECT_NAME) + " " + String(VERSION) + " ===");
Serial.print("Uptime: ");
Serial.println(getTimeString());
Serial.print("Temp: ");
Serial.print(temperature);
Serial.println(" C");
Serial.print("Humidity: ");
Serial.print(humidity);
Serial.println(" %");
Serial.print("Soil: ");
Serial.print(soilMoisture);
Serial.print(" (");
Serial.print(getSoilCondition());
Serial.println(")");
Serial.print("Light: ");
Serial.println(lightLevel);
Serial.print("Water: ");
Serial.println(waterLevel);
Serial.print("Rain: ");
Serial.print(rainLevel);
Serial.print(" - ");
Serial.println(getRainCondition());
Serial.print("Pump: ");
Serial.print(pumpStatus ? "ON" : "OFF");
Serial.print(" (");
Serial.print(pumpReason);
Serial.println(")");
Serial.print("Plant: ");
Serial.println(getPlantGrowthStatus());
Serial.print("Mode: ");
Serial.println(manualMode ? "MANUAL" : "AUTO");
Serial.println("================================");
if (millis() - lastDebugPrint >= DEBUG_INTERVAL)
{
lastDebugPrint = millis();
debugWaterLevelLogic();
}
}
// ==================== THINGSPEAK ====================
void sendToThingSpeak()
{
if (WiFi.status() != WL_CONNECTED)
return;
HTTPClient http;
http.setTimeout(5000);
String url = String(server) + "?api_key=" + THINGSPEAK_WRITE_KEY +
"&field1=" + String(temperature) + "&field2=" + String(humidity) +
"&field3=" + String(soilMoisture) + "&field4=" + String(lightLevel) +
"&field5=" + String(rainLevel) + "&field6=" + String(waterLevel) +
"&field7=" + String(pumpStatus ? 1 : 0) + "&field8=" + String(isRaining ? 1 : 0);
http.begin(url);
yield();
int httpCode = http.GET();
if (httpCode == 200)
Serial.println("✓ ThingSpeak sent");
else
Serial.println("✗ ThingSpeak failed");
http.end();
}
// ==================== TELEGRAM HANDLER ====================
void handleTelegramMessages()
{
if (WiFi.status() != WL_CONNECTED)
return;
int newMessages = bot.getUpdates(bot.last_message_received + 1);
while (newMessages)
{
for (int i = 0; i < newMessages; i++)
{
String text = bot.messages[i].text;
String chat_id = bot.messages[i].chat_id;
if (chat_id != CHAT_ID)
continue;
text.toLowerCase();
if (text == "/pump_on")
{
manualMode = true;
manualPumpRequest = true;
bot.sendMessage(chat_id, "✅ Pump ON (Manual mode)", "");
controlIrrigation();
}
else if (text == "/pump_off")
{
manualMode = true;
manualPumpRequest = false;
bot.sendMessage(chat_id, "✅ Pump OFF (Manual mode)", "");
controlIrrigation();
}
else if (text == "/auto")
{
manualMode = false;
bot.sendMessage(chat_id, "✅ Switched to AUTO mode", "");
controlIrrigation();
}
else if (text == "/status")
{
sendStatusUpdate();
}
else if (text == "/debug")
{