-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathchickendoor.ino
1131 lines (962 loc) · 32.5 KB
/
chickendoor.ino
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 <Wire.h>
#include <BH1750.h>
#include <BME280I2C.h>
#include <WiFi.h>
#include <ezTime.h>
#include <Ticker.h>
#include <Preferences.h>
#include <Adafruit_INA219.h>
#include <AsyncEventSource.h>
#include <AsyncJson.h>
#include <SPIFFSEditor.h>
#include <WebHandlerImpl.h>
#include <ESPAsyncWebServer.h>
#include <AsyncElegantOTA.h>
#include <WebAuthentication.h>
#include <AsyncWebSynchronization.h>
#include <AsyncWebSocket.h>
#include <WebResponseImpl.h>
#include <StringArray.h>
#include <AsyncTCP.h>
#include <DNSServer.h>
#include <ESPUI.h>
#include <Update.h>
#include <PubSubClient.h>
#include <esp_task_wdt.h>
// logging to google sheets
#include <ESP_Google_Sheet_Client.h>
// MQTT library for home assistant
#include <ArduinoHA.h>
//10 seconds WDT ; Less screws up OTA
#define WDT_TIMEOUT 10
#define WL_MAC_ADDR_LENGTH 6
const byte DNS_PORT = 53;
IPAddress apIP(192, 168, 1, 1);
DNSServer dnsServer;
#if defined(ESP32)
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif
//OTA with ESPUI solution thanks to user ENWI (https://githubmemory.com/repo/s00500/ESPUI/issues/116)
const char* OTA_INDEX PROGMEM
= R"=====(<!DOCTYPE html><html><head><meta charset=utf-8><title>OTA</title></head><body><div class="upload"><form method="POST" action="/ota" enctype="multipart/form-data"><input type="file" name="data" /><input type="submit" name="upload" value="Upload" title="Upload Files"></form></div></body></html>)=====";
#include "secrets.h"
#define DOOR_UNDEFINED 0
#define DOOR_OPEN 1
#define DOOR_CLOSED 2
#define OP_MODE_MANUAL 0
#define OP_MODE_LUX 1
#define OP_MODE_TIME 2
Adafruit_INA219 ina219;
const char ssid[] = WIFI_SSID;
const char password[] = WIFI_PASSWD;
const char titleVersion[] = "Chicken Door Control V1.3.0";
WiFiClient client;
HADevice hadevice;
HAMqtt mqtt(client, hadevice);
//HASensor chickendoor("chickendoor");
HACover chickendoor("chickendoor", HACover::DefaultFeatures);
HASensorNumber volierelux("volierelux", HASensorNumber::PrecisionP1);
HASensor hadoorstate("doorstate");
// Service Account's private key
const char PRIVATE_KEY[] PROGMEM = PRIVATE_KEY_DEF;
// The ID of the spreadsheet where you'll publish the data
const char spreadsheetId[] = SPREADSHEET_ID;
// Token Callback function
void tokenStatusCallback(TokenInfo info);
//End of google sheet api config
Timezone myTZ;
BH1750 lightMeter;
BME280I2C bme;
unsigned int doorState = DOOR_UNDEFINED; // 1 is open, 2 is closed, use the defines above.
int motorPinForward = 18;
int motorPinBackward = 19;
int motorRunningSeconds = 0;
int motorRunDuration = 60;
boolean motorRunning = false;
int doorCylclingState = 0;
int networkUnreachableCount = 0;
int motorNumberPin;
int upButtonPin = 26;
int downButtonPin = 27;
// Instance of the button.
Preferences preferences;
// Web UI controls
uint16_t luxLabelId;
uint16_t luxCountdownLabelId;
uint16_t temperatureLabelId;
uint16_t pressureLabelId;
uint16_t humidityLabelId;
uint16_t currentLabelId;
uint16_t doorStateLabelId;
uint16_t logfileLabelId;
uint16_t openOperationModeSelectorId;
uint16_t closeOperationModeSelectorId;
uint16_t openOperationModeLabelId;
uint16_t closeOperationModeLabelId;
uint16_t dateTimeLabelId;
uint16_t openButtonId;
uint16_t closeButtonId;
uint16_t restartButtonId;
uint16_t closingLuxTextId;
uint16_t openingLuxTextId;
uint16_t closingLuxDelayTextId;
uint16_t openingLuxDelayTextId;
uint16_t closingTimeTextId;
uint16_t openingTimeTextId;
boolean luxTickerRunning = false;
char* modeStrings[] = {"Manual", "Lux", "Time"};
// Measurement Values
float lux;
float temperature;
float pressure;
float humidity;
/*
If the light stays below closingLux for closingLuxdelay seconds, the door closes.
If the light is above openingLux for openingLuxdelay seconds, the door opens.
*/
float closingLux = 300; // if light is smaller than closingLux for closingLuxDelay in minutes, then close the door
float openingLux = 500; // if light is more than openingLux for openingLuxDelay in minutes, then open the door
int closingLuxDelay;
int openingLuxDelay;
long closingLuxSeconds;
long openingLuxSeconds;
long tempClosingLuxSeconds;
long tempOpeningLuxSeconds;
char openingTime[10] = "08:00";
char closingTime[10] = "19:00";
int openingHour = 8;
int openingMinute = 0;
int closingHour = 19;
int closingMinute = 0;
unsigned int openOperationMode = OP_MODE_MANUAL;
unsigned int closeOperationMode = OP_MODE_MANUAL;
static long oldTime = 0;
double current = 0.0;
double zeroCurrent = 0.0;
int runs = 0;
int last = millis();
void checkclosingLuxDuration();
void checkopeningLuxDuration();
void checkMotorRunning();
float readLux();
void checkLux();
void checkButtons();
Ticker closingLuxTicker;
Ticker openingLuxTicker;
Ticker readCurrentTicker;
Ticker readLuxTicker;
Ticker checkLuxTicker;
Ticker buttonTicker;
Ticker startMotorTicker;
Ticker motorRunningSecondsCounter;
Ticker networkAliveTicker;
Ticker restartTicker;
long lastReconnectAttempt; // for mqttclient update in the loop function
void setup() {
String message;
Wire.begin(16, 17);
delay(500);
// sets the two motor pins (open, close) as outputs:
GSheet.printf("ESP Google Sheet Client v%s\n\n", ESP_GOOGLE_SHEET_CLIENT_VERSION);
pinMode(motorPinForward, OUTPUT);
pinMode(motorPinBackward, OUTPUT);
Serial.begin(115200);
WiFi.setHostname("ChickenDoor");
WiFi.setAutoReconnect(true);
WiFi.begin(ssid, password);
if (! ina219.begin()) {
Serial.println("Failed to find INA219 chip");
while (1) {
delay(10);
}
}
while ( WiFi.status() != WL_CONNECTED ) {
delay ( 500 );
Serial.print ( "." );
}
waitForSync();
Serial.print("Wifi connected with IP ");
Serial.println(WiFi.localIP());
// Set the callback for Google API access token generation status (for debug only)
GSheet.setTokenCallback(tokenStatusCallback);
// Set the seconds to refresh the auth token before expire (60 to 3540, default is 300 seconds)
GSheet.setPrerefreshSeconds(10 * 60);
// Begin the access token generation for Google API authentication
GSheet.begin(CLIENT_EMAIL, PROJECT_ID, PRIVATE_KEY);
writelog("Chicken Door Control (re)started");
writelog(String(WiFi.localIP().toString().c_str()));
writelog(WiFi.SSID());
writelog(String(WiFi.RSSI()));
myTZ.setLocation(F("Europe/Berlin"));
loadPreferences();
message = "Network unreachable count: ";
message.concat(networkUnreachableCount);
writelog(message);
setupWebUI();
setupMQTT();
pinMode(upButtonPin, INPUT_PULLDOWN);
pinMode(downButtonPin, INPUT_PULLDOWN);
lightMeter.begin();
bme.begin();
networkUnreachableCount = 0;
networkAliveTicker.attach(20, checkNetworkAlive);
for (int i = 0; i < 10; i++) readLux();
esp_task_wdt_init(WDT_TIMEOUT, true); //enable panic so ESP32 restarts
esp_task_wdt_add(NULL); //add current thread to WDT watch
lastReconnectAttempt = 0;
}
//************************
//This is the central loop
//************************
void loop() {
checkButtons();
checkMotorRunning();
updateWebUI();
if (openOperationMode == OP_MODE_LUX || closeOperationMode == OP_MODE_LUX)
{
checkLux();
}
if (openOperationMode == OP_MODE_TIME || closeOperationMode == OP_MODE_TIME)
{
checkTime();
}
if (millis() - last >= 8000) {
esp_task_wdt_reset();
last = millis();
}
mqtt.loop();
delay(200);
}
void checkButtons()
{
int upButtonState = digitalRead(upButtonPin);
int downButtonState = digitalRead(downButtonPin);
// Serial.print("upButtonPin: "); // Serial.println(upButtonState); // Serial.print("downButtonPin: "); // Serial.println(downButtonState); // if (downButtonState == 1 && doorState == DOOR_OPEN) closeDoor(); // else if (upButtonState == 1 && doorState == DOOR_CLOSED) openDoor();
if (downButtonState == 1)
{
writelog("The down button was pressed manually");
closeDoor();
}
else if (upButtonState == 1)
{
writelog("The up button was pressed manually");
openDoor();
}
}
void checkLux()
{
if (luxTickerRunning)
{
//Serial.println("Lux Ticker is already running");
return;
}
if (closeOperationMode == OP_MODE_LUX && lux < closingLux && doorState == DOOR_OPEN)
{
String message = "Door closing in " + String(closingLuxDelay - (closingLuxSeconds / 60)) + " minutes";
writelog(message);
ESPUI.print(luxCountdownLabelId, message);
closingLuxSeconds = 0;
tempClosingLuxSeconds = 0;
luxTickerRunning = true;
closingLuxTicker.attach(1, checkClosingLuxDuration);
return;
}
if (openOperationMode == OP_MODE_LUX && lux > openingLux && doorState == DOOR_CLOSED)
{
String message = "Door opening in " + String(openingLuxDelay - (openingLuxSeconds / 60)) + " minutes";
ESPUI.print(luxCountdownLabelId, message);
writelog(message);
openingLuxSeconds = 0;
tempOpeningLuxSeconds = 0;
luxTickerRunning = true;
openingLuxTicker.attach(1, checkOpeningLuxDuration);
return;
}
}
void setupWebUI()
{
uint16_t dashboardTab = ESPUI.addControl( ControlType::Tab, "Dashboard", "Dashboard" );
uint16_t settingsTab = ESPUI.addControl( ControlType::Tab, "Settings", "Settings" );
openOperationModeSelectorId = ESPUI.addControl( ControlType::Select, "Opening Mode", modeStrings[openOperationMode], ControlColor::Alizarin, settingsTab, &operationModeSelector );
ESPUI.addControl( ControlType::Option, modeStrings[0], modeStrings[0], ControlColor::Alizarin, openOperationModeSelectorId );
ESPUI.addControl( ControlType::Option, modeStrings[1], modeStrings[1], ControlColor::Alizarin, openOperationModeSelectorId);
ESPUI.addControl( ControlType::Option, modeStrings[2], modeStrings[2], ControlColor::Alizarin, openOperationModeSelectorId );
closeOperationModeSelectorId = ESPUI.addControl( ControlType::Select, "Closing Mode", modeStrings[closeOperationMode], ControlColor::Alizarin, settingsTab, &operationModeSelector );
ESPUI.addControl( ControlType::Option, modeStrings[0], modeStrings[0], ControlColor::Alizarin, closeOperationModeSelectorId );
ESPUI.addControl( ControlType::Option, modeStrings[1], modeStrings[1], ControlColor::Alizarin, closeOperationModeSelectorId);
ESPUI.addControl( ControlType::Option, modeStrings[2], modeStrings[2], ControlColor::Alizarin, closeOperationModeSelectorId );
openingLuxTextId = ESPUI.addControl( ControlType::Text, "Opening Lux", String(openingLux), ControlColor::Alizarin, settingsTab, &textHandler);
closingLuxTextId = ESPUI.addControl( ControlType::Text, "Closing Lux", String(closingLux), ControlColor::Alizarin, settingsTab, &textHandler);
openingLuxDelayTextId = ESPUI.addControl( ControlType::Text, "Opening Delay [min]", String(openingLuxDelay), ControlColor::Alizarin, settingsTab, &textHandler);
closingLuxDelayTextId = ESPUI.addControl( ControlType::Text, "Closing Delay [min]", String(closingLuxDelay), ControlColor::Alizarin, settingsTab, &textHandler);
snprintf(openingTime, sizeof(openingTime), "%02i:%02i", openingHour, openingMinute);
snprintf(closingTime, sizeof(closingTime), "%02i:%02i", closingHour, closingMinute);
openingTimeTextId = ESPUI.addControl( ControlType::Text, "Opening Time [hh:mm]", String(openingTime), ControlColor::Alizarin, settingsTab, &textHandler);
closingTimeTextId = ESPUI.addControl( ControlType::Text, "Closing Time [hh:mm]", String(closingTime), ControlColor::Alizarin, settingsTab, &textHandler);
openButtonId = ESPUI.addControl( ControlType::Button, "Door Control", "Open Door", ControlColor::Emerald, dashboardTab, &buttonHandler);
closeButtonId = ESPUI.addControl( ControlType::Button, "Door Control", "Close Door", ControlColor::Emerald, dashboardTab, &buttonHandler);
dateTimeLabelId = ESPUI.addControl( ControlType::Label, "Date/Time", "", ControlColor::Peterriver, dashboardTab);
luxLabelId = ESPUI.addControl( ControlType::Label, "Lux", "lux", ControlColor::Peterriver, dashboardTab);
luxCountdownLabelId = ESPUI.addControl( ControlType::Label, "Lux Countdown", "Not ticking", ControlColor::Peterriver, dashboardTab);
doorStateLabelId = ESPUI.addControl( ControlType::Label, "Door State", "", ControlColor::Peterriver, dashboardTab);
temperatureLabelId = ESPUI.addControl( ControlType::Label, "Temperature [°C]", "", ControlColor::Peterriver, dashboardTab);
pressureLabelId = ESPUI.addControl( ControlType::Label, "Pressure [hPa]", "", ControlColor::Peterriver, dashboardTab);
humidityLabelId = ESPUI.addControl( ControlType::Label, "Humidity [%]", "", ControlColor::Peterriver, dashboardTab);
currentLabelId = ESPUI.addControl( ControlType::Label, "Current [mA]", "", ControlColor::Peterriver, dashboardTab);
openOperationModeLabelId = ESPUI.addControl( ControlType::Label, "Opening Mode", "", ControlColor::Peterriver, dashboardTab);
closeOperationModeLabelId = ESPUI.addControl( ControlType::Label, "Closing Mode", "", ControlColor::Peterriver, dashboardTab);
restartButtonId = ESPUI.addControl( ControlType::Button, "Chicken Door Control Device", "Restart Device", ControlColor::Alizarin, dashboardTab, &buttonHandler);
//logfileLabelId = ESPUI.addControl( ControlType::Label, "logfile", "", ControlColor::Peterriver,dashboardTab);
ESPUI.begin(titleVersion);
ESPUI.server->on("/ota",
HTTP_POST,
[](AsyncWebServerRequest * request) {
request->send(200);
},
handleOTAUpload);
ESPUI.server->on("/ota",
HTTP_GET,
[](AsyncWebServerRequest * request) {
AsyncWebServerResponse* response = request->beginResponse_P(200, "text/html", OTA_INDEX);
request->send(response);
}
);
}
void updateWebUI()
{
String message;
if (luxTickerRunning == false) ESPUI.print(luxCountdownLabelId, "Not ticking");
if (millis() - oldTime > 5000) {
readLux();
readClimateData();
readCurrent();
reportMQTT();
ESPUI.print(dateTimeLabelId, String(myTZ.dateTime()));
ESPUI.print(luxLabelId, String(readLux()));
ESPUI.print(temperatureLabelId, String(temperature));
ESPUI.print(pressureLabelId, String(pressure / 100));
ESPUI.print(humidityLabelId, String(humidity));
ESPUI.print(currentLabelId, String(readCurrent()));
switch (doorState)
{
case DOOR_OPEN:
ESPUI.print(doorStateLabelId, "Open");
break;
case DOOR_CLOSED:
ESPUI.print(doorStateLabelId, "Closed");
break;
case DOOR_UNDEFINED:
ESPUI.print(doorStateLabelId, "Undefined");
break;
}
switch (openOperationMode)
{
case OP_MODE_MANUAL:
ESPUI.print(openOperationModeLabelId, modeStrings[0]);
break;
case OP_MODE_LUX:
message = modeStrings[1];
message += " > "; message += openingLux; message += ", delay "; message += openingLuxDelay; message += " min";
ESPUI.print(openOperationModeLabelId, message);
break;
case OP_MODE_TIME:
message = modeStrings[2];
message += " "; message += openingTime;
ESPUI.print(openOperationModeLabelId, message);
break;
}
switch (closeOperationMode)
{
case OP_MODE_MANUAL:
ESPUI.print(closeOperationModeLabelId, modeStrings[0]);
break;
case OP_MODE_LUX:
message = modeStrings[1];
message += " < "; message += closingLux; message += ", delay "; message += closingLuxDelay; message += " min";
ESPUI.print(closeOperationModeLabelId, message);
break;
case OP_MODE_TIME:
message = modeStrings[2];
message += " "; message += closingTime;
ESPUI.print(closeOperationModeLabelId, message);
break;
}
oldTime = millis();
}
}
void loadPreferences()
{
//Serial.println("Reading Preferences: ");
preferences.begin("chickendoor", false);
unsigned int tempDoorState = preferences.getUInt("doorstate", 0);
openOperationMode = preferences.getUInt("opopmod", 0);
//Serial.print("openOperationMode: "); Serial.println(openOperationMode);
closeOperationMode = preferences.getUInt("clopmod", 0);
//Serial.print("closeOperationMode: "); Serial.println(closeOperationMode);
closingLux = preferences.getFloat("cllux");
openingLux = preferences.getFloat("oplux");
closingLuxDelay = preferences.getFloat("clluxdel");
openingLuxDelay = preferences.getFloat("opluxdel");
openingHour = preferences.getUInt("optimehh");
openingMinute = preferences.getUInt("optimemm");
closingHour = preferences.getUInt("cltimehh");
closingMinute = preferences.getUInt("cltimemm");
networkUnreachableCount = preferences.getUInt("netuc");
preferences.end();
// postprocessing of preferences
//if (tempDoorState == DOOR_UNDEFINED)
//{
// writelog("door state undefined. Cycling door states ...");
// checkDoorCycled();
//}
//else doorState = tempDoorState;
}
void operationModeSelector(Control *sender, int type)
{
int tempOpMode;
if (sender->value == "Manual") tempOpMode = OP_MODE_MANUAL;
else if (sender->value == "Lux") tempOpMode = OP_MODE_LUX;
else if (sender->value == "Time") tempOpMode = OP_MODE_TIME;
if (sender->id == openOperationModeSelectorId) openOperationMode = tempOpMode;
else if (sender->id == closeOperationModeSelectorId) closeOperationMode = tempOpMode;
preferences.begin("chickendoor", false);
Serial.println(preferences.putUInt("opopmod", openOperationMode));
Serial.print("Writing setting -> openOperationMode: "); Serial.println(openOperationMode);
Serial.println(preferences.putUInt("clopmod", closeOperationMode));
Serial.print("Writing setting -> closeOperationMode: "); Serial.println(closeOperationMode);
preferences.end();
if (tempOpMode == OP_MODE_MANUAL || tempOpMode == OP_MODE_TIME)
{
if (luxTickerRunning)
{
luxTickerRunning = false;
closingLuxTicker.detach();
openingLuxTicker.detach();
}
}
}
void buttonHandler(Control *sender, int type)
{
if (type == B_UP)
{
Serial.println(sender->id);
Serial.println(sender->value);
if (sender->id == openButtonId)
{
writelog("The open button was pressed in the web interface");
openDoor();
return;
}
if (sender->id == closeButtonId)
{
writelog("The close button was pressed in the web interface");
closeDoor();
return;
}
if (sender->id == restartButtonId)
{
writelog("The restart button was pressed in the web interface");
ESP.restart();
return;
}
}
}
void textHandler(Control *sender, int type)
{
String message;
int tempInt;
float tempFloat;
if (sender->id == openingLuxTextId)
{
tempInt = sender->value.toInt();
if (tempInt > 0)
{
openingLux = tempInt;
preferences.begin("chickendoor", false);
preferences.putFloat("oplux", openingLux);
preferences.end();
}
}
if (sender->id == closingLuxTextId)
{
tempInt = sender->value.toInt();
if (tempInt > 0)
{
closingLux = tempInt;
preferences.begin("chickendoor", false);
preferences.putFloat("cllux", closingLux);
preferences.end();
}
}
if (sender->id == closingLuxDelayTextId)
{
tempInt = sender->value.toInt();
if (tempInt > 0)
{
closingLuxDelay = tempInt;
preferences.begin("chickendoor", false);
preferences.putFloat("clluxdel", closingLuxDelay);
preferences.end();
}
}
if (sender->id == openingLuxDelayTextId)
{
tempInt = sender->value.toInt();
if (tempInt > 0)
{
openingLuxDelay = tempInt;
preferences.begin("chickendoor", false);
preferences.putFloat("opluxdel", openingLuxDelay);
preferences.end();
}
}
if (sender->id == openingTimeTextId)
{
int tempHour = getHour(sender->value);
int tempMinute = getMinute(sender->value);
message = "Opening Time changed to ";
message.concat(tempHour);
message.concat(":");
message.concat(tempMinute);
writelog(message);
if (tempHour > -1 && tempMinute > -1)
{
openingHour = tempHour;
openingMinute = tempMinute;
preferences.begin("chickendoor", false);
preferences.putUInt("optimehh", openingHour);
preferences.putUInt("optimemm", openingMinute);
preferences.end();
}
}
if (sender->id == closingTimeTextId)
{
int tempHour = getHour(sender->value);
int tempMinute = getMinute(sender->value);
if (tempHour > -1 && tempMinute > -1)
{
closingHour = tempHour;
closingMinute = tempMinute;
preferences.begin("chickendoor", false);
preferences.putUInt("cltimehh", closingHour);
preferences.putUInt("cltimemm", closingMinute);
preferences.end();
}
}
}
int getHour(String timeString)
{
int hourInt = -1;
int colonIndex = timeString.indexOf(':');
if (colonIndex > 0)
{
hourInt = timeString.substring(0, colonIndex).toInt();
}
return hourInt;
}
int getMinute(String timeString)
{
int minuteInt = -1;
int colonIndex = timeString.indexOf(':');
if (colonIndex > 0)
{
minuteInt = timeString.substring(colonIndex + 1, timeString.length()).toInt();
}
return minuteInt;
}
void openDoor()
{
writelog("call to openDoor");
if (motorRunning == false)
{
moveDoor(motorPinBackward);
doorState = DOOR_UNDEFINED;
hadoorstate.setValue("Undefined");
preferences.begin("chickendoor", false);
preferences.putUInt("doorstate", doorState);
preferences.end();
writelog("Starting to open door ...");
writelog("Setting door state to UNDEFINED");
}
else Serial.println("Motor already moving");
luxTickerRunning = false;
openingLuxTicker.detach();
}
void closeDoor()
{
writelog("call to closeDoor");
if (motorRunning == false)
{
moveDoor(motorPinForward);
doorState = DOOR_UNDEFINED;
hadoorstate.setValue("Undefined");
preferences.begin("chickendoor", false);
preferences.putUInt("doorstate", doorState);
preferences.end();
writelog("Starting to close door ...");
writelog("Setting door state to UNDEFINED");
}
else Serial.println("Motor already moving");
luxTickerRunning = false;
closingLuxTicker.detach();
}
void moveDoor(int thisMotorNumberPin)
{
motorNumberPin = thisMotorNumberPin;
digitalWrite(motorNumberPin, HIGH);
motorRunning = true;
}
boolean checkDoorCycled()
{
writelog("Cycling door to get to defined state");
if (doorState == DOOR_UNDEFINED)
//closeDoor();
//while (motorRunning == true)
//{
// checkMotorRunning();
// delay(1000);
//}
openDoor();
while (motorRunning == true)
{
checkMotorRunning();
delay(1000);
}
}
void checkMotorRunning()
{
if (motorRunning == false) return;
if (readCurrent() < 10.0)
{
writelog("Switching motor off");
digitalWrite(motorNumberPin, LOW);
motorRunning = false;
if (motorNumberPin == motorPinForward)
{
doorState = DOOR_CLOSED;
hadoorstate.setValue("closed");
preferences.begin("chickendoor", false);
preferences.putUInt("doorstate", doorState);
preferences.end();
writelog("Written DOOR_CLOSED to settings");
chickendoor.setState(HACover::StateClosed);
}
else
{
doorState = DOOR_OPEN;
hadoorstate.setValue("open");
preferences.begin("chickendoor", false);
preferences.putUInt("doorstate", doorState);
preferences.end();
writelog("Written DOOR_OPEN to settings");
chickendoor.setState(HACover::StateOpen);
}
}
}
float readLux()
{
lux = lightMeter.readLightLevel();
//Serial.print("Lux: "); Serial.println(lux);
return lux;
}
void checkTime()
{
if (doorState == DOOR_OPEN && closeOperationMode == OP_MODE_TIME )
{
if (myTZ.hour() == closingHour && myTZ.minute() == closingMinute)
closeDoor();
return;
}
if (doorState == DOOR_CLOSED && openOperationMode == OP_MODE_TIME)
{
if (myTZ.hour() == openingHour && myTZ.minute() == openingMinute)
openDoor();
return;
}
}
void checkNetworkAlive()
{
if ((WiFi.status() != WL_CONNECTED)) {
networkUnreachableCount++;
preferences.putUInt("netuc", networkUnreachableCount);
restartESP();
WiFi.disconnect();
WiFi.reconnect();
writelog("Lost network. Now successfully reconnected to WIFI network");
}
else
{
Serial.println("Network still alive");
}
}
void restartESP()
{
if (motorRunning == false && luxTickerRunning == false)
{
writelog("Restarting ESP");
ESP.restart();
}
}
void checkClosingLuxDuration()
{
// Serial.print("Inside checkclosingLuxDuration for ");
// Serial.print(closingLuxSeconds );
// Serial.print(" seconds.");
String message;
if (motorRunning == false && lux > closingLux) //Running motor can lead to wrong readings of sensor
{
writelog("Lux above threshold. Stopping door countdown.");
closingLuxSeconds = 0;
luxTickerRunning = false;
closingLuxTicker.detach();
ESPUI.print(luxCountdownLabelId, "Not ticking");
return;
}
closingLuxSeconds++;
if (closingLuxSeconds > tempClosingLuxSeconds + 60)
{
tempClosingLuxSeconds = closingLuxSeconds;
String message = String("Door closing in ") + (closingLuxDelay - (closingLuxSeconds / 60)) + String(" minutes");
ESPUI.print(luxCountdownLabelId, message);
}
if (closingLuxSeconds > closingLuxDelay * 60) // the delay is giving in minutes, the counter counts seconds
{
message = "Lux has been below threshold for ";
message.concat(closingLuxSeconds);
message.concat(" seconds. Closing door. ");
writelog(message);
closeDoor();
ESPUI.print(luxCountdownLabelId, "Not ticking");
closingLuxSeconds = 0;
tempClosingLuxSeconds = 0;
}
}
void checkOpeningLuxDuration()
{
// Serial.print("Inside checkopeningLuxDuration for ");
// Serial.print(openingLuxSeconds );
// Serial.print(" seconds.");
String message;
if (motorRunning == false && lux < openingLux) // running motor can lead to wrong readings of sensors
{
writelog("Lux below threshold. Stopping door countdown.");
openingLuxSeconds = 0;
luxTickerRunning = false;
openingLuxTicker.detach();
ESPUI.print(luxCountdownLabelId, "Not ticking");
return;
}
openingLuxSeconds++;
if (openingLuxSeconds > tempOpeningLuxSeconds + 60)
{
tempOpeningLuxSeconds = openingLuxSeconds;
String message = "Door opening in " + String(openingLuxDelay - (openingLuxSeconds / 60)) + " minutes";
ESPUI.print(luxCountdownLabelId, message);
}
if (openingLuxSeconds > openingLuxDelay * 60)
{
luxTickerRunning = false;
openingLuxTicker.detach();
Serial.print("Lux has been above threshold for ");
Serial.print(openingLuxSeconds);
Serial.println(" seconds. Opening door. ");
message = "Lux has been above threshold for ";
message.concat(openingLuxSeconds);
message.concat(" seconds. Opening door. ");
writelog(message);
openDoor();
ESPUI.print(luxCountdownLabelId, "Not ticking");
openingLuxSeconds = 0;
tempOpeningLuxSeconds = 0;
}
}
void reportData()
{
Serial.print(F("Germany: "));
Serial.println(myTZ.dateTime());
Serial.print("Light: ");
Serial.print(lux);
Serial.println(" lx");
}
void readClimateData()
{
bme.read(pressure, temperature, humidity);
// Serial.print("Temperature: ");
// Serial.print(temperature);
// Serial.println("°C");
//
// Serial.print("Humidity: ");
// Serial.print(humidity);
// Serial.println(" %rH");
//
// Serial.print("Pressure: ");
// Serial.print(pressure/100);
// Serial.println(" mBar");
}
float readCurrent()
{
float current_mA = 0;
int counter = 0;
float tempCurrent = 0;
for (int i = 0; i < 7; i++)
{
tempCurrent = abs(ina219.getCurrent_mA());
//Serial.print("Temp Current: "); Serial.print(tempCurrent); Serial.println(" mA");
if (tempCurrent > 0.0)
{
current_mA += tempCurrent;
counter ++;
}
delay(10);
}
current_mA = current_mA / counter;
//Serial.print("Current: "); Serial.print(current_mA); Serial.println(" mA");
return current_mA;
}
// The following methods is from https://randomnerdtutorials.com/esp32-esp8266-publish-sensor-readings-to-google-sheets/
// to log messages to a google sheet using webhooks from IFTTT
//NOTE: At the momement, this is a mix of mqtt looging to my home assistant and to google sheets, because IFTTT is making webhooks commercial
void setupMQTT() {
String message;
byte mac[WL_MAC_ADDR_LENGTH];
WiFi.macAddress(mac);
hadevice.setUniqueId(mac, sizeof(mac));
hadevice.setName("Chickendoor");
hadevice.enableSharedAvailability();
hadevice.enableLastWill();
hadevice.setSoftwareVersion("1.3.0");
hadevice.setManufacturer("Wonky Workshop");
hadevice.setModel("CD-1");
chickendoor.setIcon("mdi:home");
chickendoor.setName("chickendoor");
chickendoor.setDeviceClass("door");
chickendoor.onCommand(onCoverCommand);
chickendoor.setAvailability(true);
volierelux.setIcon("mdi:home");
volierelux.setName("Voliere lux");
volierelux.setUnitOfMeasurement("lx");
volierelux.setDeviceClass("illuminance");
volierelux.setAvailability(true);
hadoorstate.setIcon("mdi:home");
hadoorstate.setName("doorstate");
hadoorstate.setAvailability(true);
mqtt.begin(BROKER_ADDR, MQTTUSER, MQTTPW);
writelog("MQTT setup finished");
}
void reportMQTT()
{