forked from arkhipenko/IoT_apis2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIoT_apis2.ino
3165 lines (2572 loc) · 90.7 KB
/
IoT_apis2.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
/* -------------------------------------
IoT enabled Automatic Plant Irrigation System - IOT APIS2
Based on ESP8622 NODEMCU v2 dev kit chip
Code Version 1.2.1
Parameters Version 03
Change Log:
2016-11-29
v0.1.0 - work started
2016-12-17:
v1.0.0 - First release
2016-12-20:
v1.0.1 - Replaced ultrasonic sensor from HC-SR04 (4 pins) to Ping sensor from Dexter tech (3 pins) to free up one pin.
The issue is I ranout of pins, and device refuses to reset with pins D3 and D4 connected to HC-SR04 echo and trig pins
(probably due to overuse of pin functions on esp8266). Also went with straight PulseIn apprioach for distance measurement.
Reason: it is only 1500 microseconds tops for 23 cm max distance, so not much of a delay.
- Added a 10 second delay after initialization to allow voltage and current to stabilize after extensive use of LEDs before
taking ADC measurement.
- Webserver is stopped during measurement and watering runs. According to Expressif docu ADC measurements could be incorrect
if device is transmitting during taking a measurement.
- PowerSave deep sleep timeout is extended to 3 minutes if client connects to the webserver to allow adequate time for parameter
updates
2016-12-21:
v1.0.2 - TaskScheduler 2.2.1 yieldOnce
- For PowerSave mode: allow 10 minutes for configuration after cold boot
- Log data to a tab separated datafile as well as to IoT
- Round next wake up time to the ticker period, so wake ups happen on an hour/half hour/10 min, etc.
- Various minor bug fixes
2017-01-05:
v1.0.3 - feature: Periodic connection status checking (not sure if that is needed, but don't trust events 100% for now)
- feature: Periodic IoT reporting even when online
- feature: Reset if IoT reporting fails 3 times (3 x 4 individual http requests: 12 requests)
2017-01-06:
v1.0.4 - feature: Internal RTC precision compensation
- bug: Prevent any LEDs in night mode
2017-01-21:
v1.0.5 - programming: hide WiFi settings in the header file outside of github (for publishing)
2017-02-07:
v1.0.6 - bug: use dynamic measurement interval instead of the constant
2017-02-15:
v1.0.7 - feature: additional IoT update _before_watering (more accurate graph)
- bug: periodic ntp update scheduling fixed
- bug: reconnect cycle corrected from forever to timeout
2017-02-24:
v1.0.8 - feature: RTC adjustment is self-calibrating based on the actual and NTP times
- bug: sleep delay is extended only if remaining delay is less than requested
- dependency: TaskScheduler 2.3.0
2017-02-29:
v1.0.9 - feature: allow 5 min later/earlier for "isNight" determination
2017-03-09:
v1.1.0 - feature: align ticker interval with respective real clock interval, e.g. if ticker interval in 30 minutes,
then each tick will align with full hour and half-hour time (11:00, 11:30, 12:00, etc)
2017-03-12:
v1.2.0 - feature: check for water leak in the bottom tray every 1 second during watering, and every 10 seconds during saturation.
Stop watering immediately as the leak is detected.
2017-04-04:
v1.2.1 - bug: IoT report should be called before watering ADC settle delay.
----------------------------------------*/
// TEST/DEBUG defines
// ------------------
//#define _DEBUG_
//#define _TEST_
// IoT framework selection
// -----------------------
#define _IOT_BLYNK_
// INCLUDES
// ========
// TaskScheduler options:
//#define _TASK_TIMECRITICAL // Enable monitoring scheduling overruns
#define _TASK_SLEEP_ON_IDLE_RUN // Enable 1 ms SLEEP_IDLE powerdowns between tasks if no callback methods were invoked during the pass
#define _TASK_STATUS_REQUEST // Compile with support for StatusRequest functionality - triggering tasks on status change events in addition to time only
//#define _TASK_WDT_IDS // Compile with support for wdt control points and task ids
//#define _TASK_LTS_POINTER // Compile with support for local task storage pointer
//#define _TASK_PRIORITY // Support for layered scheduling priority
//#define _TASK_MICRO_RES // Support for microsecond resolutionMM
//#define _TASK_DEBUG
#include <TaskScheduler.h>
#include <EEPROM.h>
#include <AvgFilter.h>
#include <TimeLib.h> // just including Time.h does not work anymore for now() method (for some reason)
#include <Timezone.h>
#include <RTClib.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <FS.h>
#include <IoT_APIS_WiFi.h>
// DEFINES AND GLOBAL VARIABLES
// ============================
// Natural constants
#define US_TO_MM_FACTOR (100000/583) // factor to convert microseconds to millimeters (times 1000)
#ifdef _TEST_
#define STATIC_TIME 1482320760UL // set initial time to:
//Epoch timestamp: 1482321360
//Timestamp in milliseconds: 1482321360000
//Human time (your time zone): 12/21/2016, 6:56:00 AM
//Human time (GMT): Wed, 21 Dec 2016 11:56:00 GMT
#else
#define STATIC_TIME 1451606400UL // set initial time to Jan 1, 2016
#endif
#define PING_TIMEOUT 2000UL // pinf timeout in uS - (about 34 cm of distance measurement)
#define HALF_HOUR 1800 // seconds
#define SD3 10 // SD3 pin on NodeMCU is GPIO10
#define ADC_SETTLE_TOUT 10 // seconds to let ADC settle after all LEDs are off
#define NIGHT_TOLERANCE 5 // minutes after night start and before it ends
/*
Compensating factor for imperfections of built-in RTC:
Comparing epoch times between internal RTC and external RTC after 10 minute deep sleep
Internal RTC:1483693345
External RTC:1483693318
Internal RTC is *ahead* meaning that the device will wake up *earlier* than necessary,
so we need to *add* time to sleep request to compensate
(Internal - External)/10 min = 27 sec / 600 sec = 0.045 seconds/second or 45000 uSec/sec of sleep
*/
// Watering parameter defaults (from APIS v1)
// ---------------------------
#define RETRIES 2
#define RETRIES_MIN 1
#define RETRIES_MAX 10
// Time to run pump within one water run
#define WATERTIME 20 //Seconds
#define WATERTIME_MIN 5 //Seconds
#define WATERTIME_MAX 120 //Seconds
// Time to saturate
#define SATURATE 1 // 1 minute
#define SATURATE_MIN 1 // 1 minute
#define SATURATE_MAX 90 // 10 minutes
// % soil humidity to start pumping (low threshold)
#define NEEDWATER 65 // % to start pumping
#define NEEDWATER_MIN 20 // % to start pumping
#define NEEDWATER_MAX 75 // % to start pumping
// % soil humidity to stop pumping (high threshold)
#define STOPWATER 70 // % to stop pumping
#define STOPWATER_MIN 25 // % to stop pumping
#define STOPWATER_MAX 90 // % to stop pumping
// Hour of the day to "go to sleep" (i.e., do not operate after this hour)
#define GOTOSLEEP 22 // hour to go to sleep
#define GOTOSLEEP_MIN 0 // hour to go to sleep
#define GOTOSLEEP_MAX 24 // hour to go to sleep
// Hour of the day to "wake up" (i.e., operate after this hour)
#define WAKEUP 7 // hour to wake up
#define WAKEUP_MIN 0 // hour to wake up
#define WAKEUP_MAX 24 // hour to wake up
// Number of hours to add to wake up time on a weekend
#define WEEKENDADJ 3 // number of hours to add for the wakeup on a weekend
#define WEEKENDADJ_MIN 0 // number of hours to add for the wakeup on a weekend
#define WEEKENDADJ_MAX 12 // number of hours to add for the wakeup on a weekend
#define WLDEPTH 240 // mm, total depth of the water bucket
#define WLLOW 30 // mm, low level of water bucket
// Wifi
// ----
#define CONNECT_TIMEOUT 30 //seconds
#define NTP_TIMEOUT 30 //seconds
#define CONNECT_BLINK 260 // ms
#define WL_PERIOD 100 // ms
#define CONNECT_INTRVL 2000 // check every 2 seconds
#define NTPUPDT_INTRVL 2000 // check every 2 seconds
// PINs
// ----
// Moisture probe analog pin
#define MOISTURE_PIN A0 // ADC
#define MOISTURE_PWR_PIN D8 // This pin provides voltage to the moisture sensor
#define SENSOR_OUT_VALUE 1000 // Consider anything above this value as 100%
#define LEAK_PIN D5 // This pin provides voltage to the bottom tray leak sensor
// RGB LED
#define RGBLED_RED_PIN SD3 // red LED pin
#define RGBLED_GREEN_PIN D1 // green LED pin
#define RGBLED_BLUE_PIN D6 // blue LED pin
#define LEDON 1 // Turn LED ON
#define LEDOFF 0 // Turn LED OFF
#define LEDSTAY (-1) // Keep LED in current state
// Dexter Tech Ping ))) ultrasound sensor - three pin version
#define SR04_ECHO_PIN D3 // combined trigger/echo pin
// PUMP pins
#define PUMP_PWR_PIN D2 // Pump activation pin
// EEPROM token for parameters
#ifdef _TEST_
const char *CToken = "APIS00\0"; // Eeprom token: Automatic Plant Irrigation System (for testing)
#else
const char *CToken = "APIS03\0"; // Eeprom token: Automatic Plant Irrigation System
#endif
//const char *CSsid = "wifi_network";
//const char *CPwd = "wifi_password";
const char *CDSsid = "Plant_";
const char *CDPwd = "changeme!";
const char *CHost = "plant.io";
String ssid, pwd;
#ifndef _TEST_ // "Real" parameters
#define TICKER 30 // probe soil humidity every 30 minutes
int currentHumidity = 0; // current humidity level
int currentWaterLevel = 0; // current water level in the bucket
#else // "Test" parameters
#define TICKER 5 // in test mose probe every 5 minutes
int currentHumidity = 60;
int currentWaterLevel = 200;
#endif
#define SLEEP_TOUT TASK_MINUTE // in powersave mode the system will enter powersave mode after 1 minute
#define SLEEP_TOUT_CONN (TASK_MINUTE * 3) // in powersave mode: if http connection is detected - the system will stay on for this amount of time
#define CONFIG_DELAY (TASK_MINUTE * 10) // in powersave mode: initial delay to allow parameter configuration (after first power on)
#define HTTP_ERRORS 12 // reset the device if this many http errors were detected sequentially (resets every time http is successful)
const char* CWakeReasonSleep = "Deep-Sleep Wake"; // reason code for device wake up
const char* CWakeReasonReset = "External System"; // reason code for device cold reset
bool coldBoot; // a flag indicating system was hard reset as opposed to warm boot or woke up from timer
// Forward definition of all callback methods is now required as of v1.6.6
// ---------------------------------------------------------------------
void cfgInit();
void cfgLed();
void ledOnDisable();
bool ledOnEnable();
void ntpUpdate();
void connectedChk();
void measureCallback();
void measureWL();
bool measureWLOnEnable();
void measureMS();
bool measureMSOnEnable();
void measureMSOnDisable();
void ticker();
void measureRestart();
void waterCallback();
bool waterOnEnable();
void waterOnDisable();
void handleClientCallback();
void serverHandleRoot();
void serverHandleNotFound();
void sleepCallback();
void postWaterCallback();
void resetDevice();
void iot_report();
void connectionEnforcer();
void waterleakChecker();
// Task Scheduling
// ---------------
StatusRequest measurementsReady; // event signalling that all measurements (soil and water level) are done and values are ready
StatusRequest probeIdle; // event signalling that the humidity probe is idle (not under voltage)
StatusRequest pageLoaded; // event signalling completion of the html page load (to reset after the reset picture fully loads)
StatusRequest wateringDone; // event signalling watering procedure has completed
StatusRequest httpError; // event counting the number of http put errors - to reset device if too many errors occured
Scheduler ts; // TaskScheduler scheduler object
#ifdef _TEST_
void testTicker();
Task tTest (TASK_MINUTE, TASK_FOREVER, &testTicker, &ts, true); // Test task displaying information to the Serial monitor
#endif
Task tConfigure (TASK_IMMEDIATE, TASK_ONCE, &cfgInit, &ts, true);
Task tLedBlink (TASK_IMMEDIATE, TASK_FOREVER, &cfgLed, &ts, false, &ledOnEnable, &ledOnDisable);
Task tTimeout (TASK_IMMEDIATE, TASK_FOREVER, NULL, &ts);
Task tNtpUpdater (NTPUPDT_INTRVL, NTP_TIMEOUT, &ntpUpdate, &ts);
Task tConnected (TASK_SECOND, CONNECT_TIMEOUT, &connectedChk, &ts);
Task tHandleClients (TASK_SECOND, TASK_FOREVER, &handleClientCallback, &ts);
Task tTicker (TICKER * TASK_MINUTE, TASK_FOREVER, &ticker, &ts);
Task tMeasure (&measureCallback, &ts);
Task tMeasureRestart(&measureRestart, &ts);
Task tPostWater (&postWaterCallback, &ts);
Task tMesrLevel (WL_PERIOD, TASK_FOREVER, &measureWL, &ts, false, &measureWLOnEnable, NULL);
Task tMesrMoisture (TASK_SECOND, TASK_FOREVER, &measureMS, &ts, false, &measureMSOnEnable, &measureMSOnDisable);
Task tWater (TASK_IMMEDIATE, TASK_ONCE, &waterCallback, &ts, false, &waterOnEnable, &waterOnDisable);
Task tLeakChecker (TASK_SECOND, TASK_FOREVER, &waterleakChecker, &ts, false);
Task tSleep (&sleepCallback, &ts);
Task tIotReport (TASK_IMMEDIATE, TASK_ONCE, &iot_report, &ts);
Task tReset (&resetDevice, &ts);
Task tErrorReset (&resetDevice, &ts);
Task tEnforcer (TICKER * 2 * TASK_MINUTE, TASK_ONCE, &connectionEnforcer, &ts);
// Parameters
// ----------
typedef struct {
// token
char token[7]; // 6 digit token = APISxx, where xx is a version + '\0'
// watering parameters
byte high; // high humidity mark - stop watering
byte low; // low humidity mark - start watering
byte retries; // number of watering runs before give up (if high not reached)
byte watertime; // pumping duration
byte saturate; // saturation duration
byte gotosleep; // hour to go goodnight (e.g., 22)
byte wakeup; // hour to wake up (e.g., 08)
byte wkendadj; // weekend wake up adjustment time
int wl_depth; // water container depth (empty), in mm
int wl_low; // water container level low mark, in mm
// 12 bytes
// wifi parameters
byte is_ap; // is this system configured to be an access point or connect to a network
char ssid[32]; // SSID of the network to connect to -OR- SSID of the AP to create
char pwd[65]; // Password for the network to be connected to -OR- AP password
char ssid_ap[32]; // SSID of the network to connect to -OR- SSID of the AP to create
char pwd_ap[65]; // Password for the network to be connected to -OR- AP password
// 195 bytes
// power parameters
bool powersave; // false: run continuosly, true: run in a power saving mode
// 2 bytes
// other parameters
int ping_interval; // soil humidity check interval, minutes
byte led_use; // LED use option: 0 - depending on night mode, 1 - always, 2 - never
char ntp_server[32]; // hostname of the ntp server
// 35 bytes
// total of 246 bytes
} TParameters;
TParameters parameters;
typedef struct {
unsigned long magic; // 4b: token: 1234567890 for validation
unsigned long ccode; // 4b: control code for the magic number = ~magic
unsigned long ttime; // 4b: unix time at the time of reset
bool hasntp; // 2b: was the time ntp driven?
unsigned long ntptime; // 4b: epoch time at the last NTP update
long rtccomp; // 4b: current rtc_comp value
bool rtcreq; // 2b: rtc recalc requested
// Total of 22 bytes
} TTimeStored;
TTimeStored time_restore;
#define MAGIC_NUMBER 1234567890UL
#define WAKE_DELAY 0 // number of seconds spent waking up
typedef struct {
time_t water_start; // time watering run started
byte hum_start; // humidity at the start
int wl_start; // water level when started, in mm
byte num_runs; // number of runs it took to water
byte run_duration; // run durations
time_t water_end; // time watering stopped
byte hum_end; // humidity at the end of run
int wl_end; // water level when ended, in mm
} TWaterLog;
TWaterLog water_log;
// Support for timezones:
// ======================
//US Eastern Time Zone (New York)
TimeChangeRule myDST = {"EDT", Second, Sun, Mar, 2, -240}; //Daylight time = UTC - 4 hours
TimeChangeRule mySTD = {"EST", First, Sun, Nov, 2, -300}; //Standard time = UTC - 5 hours
Timezone myTZ(myDST, mySTD);
// NTP Related Definitions
// =======================
#define NTP_PACKET_SIZE 48 // NTP time stamp is in the first 48 bytes of the message
/* Don't hardwire the IP address or we won't get the benefits of the pool.
Lookup the IP address for the host name instead */
IPAddress timeServerIP; // time.nist.gov NTP server address
const char* ntpServerName = "time.nist.gov";
byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
// A UDP instance to let us send and receive packets over UDP
WiFiUDP udp;
#define LOCAL_NTP_PORT 2390
#define LOCAL_HTTP_PORT 80
#define LOCAL_DNS_PORT 53
IPAddress apIP(192, 168, 1, 1); // Local IP address for the Access Point mode
ESP8266WebServer server(LOCAL_HTTP_PORT); // local webserver
DNSServer dnsServer; // local dns server for AP mode
RTC_Millis rtc;
time_t bootTime; // Timestamp of the device start up
time_t tickTime; // Timestamp of the current tick
unsigned long epoch; // Time reported by NTP
bool nightMode = false; // Determine whether it is night once during tick, and then use the variable instead.
unsigned long ledOnDuration, ledOffDuration; // durations for LED on and off states - for fancy blinking
bool tickerIdleRun = true; // Indicates that a ticker run is idle (i.e. will do measurment w/o watering - for more accurate IoT update in time)
// Execution
bool connectedToAP = false; // if connected to AP, presumably can query and set the time via NTP
bool runningAsAP = false; // running as AP, internet is not available, no correct time is available
bool hasNtp; // Indicates that device was able to update time from NTP servers at some point
long rtcComp; // dynamically calculated microseconds of adjustment per 1 second of deep sleep to compensate for internal RTC error
bool rtcCompRequested;
// WiFi specific events
WiFiEventHandler disconnectedEventHandler;
WiFiEventHandler clientConnectedEventHandler;
WiFiEventHandler clientDisconnectedEventHandler;
unsigned int numClients;
// Ultrasonic measurment related
unsigned long distance;
// Code
// ------------------------------------------------------------------
#ifdef _TEST_
/**
A Test function to make sure 3 way LED works
*/
void TESTLEDS() {
digitalWrite(RGBLED_RED_PIN, HIGH); delay(1000); digitalWrite(RGBLED_RED_PIN, LOW); delay(1000);
digitalWrite(RGBLED_GREEN_PIN, HIGH); delay(1000); digitalWrite(RGBLED_GREEN_PIN, LOW); delay(1000);
digitalWrite(RGBLED_BLUE_PIN, HIGH); delay(1000); digitalWrite(RGBLED_BLUE_PIN, LOW); delay(1000);
digitalWrite(RGBLED_RED_PIN, HIGH); digitalWrite(RGBLED_GREEN_PIN, HIGH); digitalWrite(RGBLED_BLUE_PIN, HIGH); delay(1000);
ledOff();
}
/**
If compiled with _TEST_ definition will simulate soil humidity changes for testing purposes
*/
void testTicker() {
long i = tTest.getRunCounter();
if ( tWater.isEnabled() ) {
currentHumidity += 5;
if ( tWater.getRunCounter() & 1 ) currentWaterLevel -= 4;
}
else {
currentHumidity -= 1;
}
if ( currentHumidity < 20 ) currentHumidity = 20;
if ( currentHumidity > 100 ) currentHumidity = 100;
if ( currentWaterLevel < 0 ) currentWaterLevel = 0;
Serial.println();
Serial.println(F("TEST MODE"));
Serial.println(F("========="));
time_t tnow = myTZ.toLocal( now() );
Serial.print(F("Current local time: ")); printTime(DateTime(tnow)); Serial.println();
Serial.print(F("Current humidity : ")); Serial.print(currentHumidity); Serial.println("%");
Serial.print(F("Current water level: ")); Serial.print(currentWaterLevel); Serial.println(" mm");
Serial.print(F("Status: "));
if (tWater.isEnabled() ) {
if (tWater.getRunCounter() & 1) Serial.println(F("watering..."));
else Serial.println(F("saturating..."));
}
else {
Serial.println(F("idle."));
}
}
#endif
// Utility methods
// ---------------
/**
Calculates water level based on the distance to water surface
measured by the utrasonic sensor
*/
#define WL_SAMPLES 10
long wlData[WL_SAMPLES]; // Water level is averaged based on 5 measurements
avgFilter wl(WL_SAMPLES, wlData); // Average filter for water level measurements
void ping(unsigned long aTimeout) { // in micros
#ifdef _TEST_
return;
#endif
pinMode(SR04_ECHO_PIN, OUTPUT);
digitalWrite(SR04_ECHO_PIN, LOW);
delayMicroseconds(2);
digitalWrite(SR04_ECHO_PIN, HIGH);
delayMicroseconds(5);
digitalWrite(SR04_ECHO_PIN, LOW);
pinMode(SR04_ECHO_PIN, INPUT);
delayMicroseconds(5);
long duration, cwl;
duration = pulseIn(SR04_ECHO_PIN, HIGH, aTimeout);
if ( duration == 0 ) duration = aTimeout;
cwl = parameters.wl_depth - ( duration * 100UL / 580UL + 10UL );
if ( cwl < 0 ) cwl = 0;
if ( cwl > parameters.wl_depth ) cwl = parameters.wl_depth;
currentWaterLevel = wl.value(cwl);
#ifdef _DEBUG_
// long d, mm;
// d = pulseStop - pulseStart;
// mm = d * US_TO_MM_FACTOR / 1000;
// Serial.print(millis());
// Serial.print(F(": waterLevelCalc. d = "));
// Serial.println(d);
// Serial.print(F("mm = "));
// Serial.println(mm);
// Serial.print(F("cwl = "));
// Serial.println(currentWaterLevel);
#endif
}
// Pump Motor methods
// ------------------
/**
Turns pump motor on/off depending on the state
@param: aState: true - turn the pump on; false - turn the pump off
*/
void motorState(bool aState) {
digitalWrite(PUMP_PWR_PIN, aState ? HIGH : LOW);
}
/**
Turn pump on
*/
void motorOn() {
motorState(true);
}
/**
Turn pump off
*/
void motorOff() {
motorState(false);
}
/**
Turns the power on soil humidity probe ON
*/
void probePowerOn() {
digitalWrite(MOISTURE_PWR_PIN, HIGH);
}
/**
Turns the power on soil humidity probe OFF
*/
void probePowerOff() {
digitalWrite(MOISTURE_PWR_PIN, LOW);
}
/**
Retruns TRUE if there is water in the tray under the flower pot
*/
bool hasLeaked() {
pinMode(LEAK_PIN, INPUT_PULLUP);
delay(5);
bool hasleaked = ( digitalRead(LEAK_PIN) == LOW );
#ifdef _DEBUG_
Serial.print(millis());
Serial.print(F(": hasLeaked = ")); Serial.println(hasleaked ? "YES" : "NO");
Serial.print(F("LEAK_PIN = ")); Serial.println(digitalRead(LEAK_PIN));
#endif
pinMode(LEAK_PIN, OUTPUT);
digitalWrite(LEAK_PIN, LOW);
return hasleaked;
}
/**
Returns TRUE if all conditions permit watering run
*/
bool canWater() {
return !( hasLeaked() || currentWaterLevel < parameters.wl_low || isNight() );
}
/**
Returns TRUE if it is night time according to local clock and night parameters
*/
bool isNight() {
#ifdef _TEST_
// return true;
#endif
nightMode = false;
if ( hasNtp ) {
time_t tnow = myTZ.toLocal( now() );
// Allow 5 min "grace" period for wakeup/go to sleep due to clock imperfections
// Defined as NIGHT_TOLERANCE
int hr = hour(tnow) * 60 + minute(tnow);
int wkp = parameters.wakeup * 60 - NIGHT_TOLERANCE; // wakep could occur up to 5 min earlier
int gts = parameters.gotosleep * 60 + NIGHT_TOLERANCE; // go to sleep could occur up to 5 min later
#ifdef _DEBUG_
// Serial.print(millis());
// Serial.print(F(": isNight. hr="));
// Serial.println(hr);
// // return false;
#endif
// Add adjusting hours to the wakeup time for Saturday and Sunday
if ( weekday(tnow) == dowSunday || weekday(tnow) == dowSaturday ) wkp += parameters.wkendadj * 60;
nightMode = ( hr >= gts || hr < wkp );
#ifdef _DEBUG_
// Serial.print(F("parameters.gotosleep = ")); Serial.println(parameters.gotosleep);
// Serial.print(F("wkp = ")); Serial.println(wkp);
// Serial.print(F("nightMode = ")); Serial.println(nightMode);
// // return false;
#endif
}
return nightMode;
}
/**
Determines if and how the LEDs should be used
*/
bool useLed() {
if ( parameters.led_use == 0 ) return nightMode; // 0 - depending on Night Mode
else if ( parameters.led_use == 1 ) return false; // 1 - always
return true;
}
// 3 Color LED methods
// -------------------
/**
Displays appropriate color on the LED
@param: aR - Reg LED component. LEDOFF to turn LED color off; LEDSTAY to keep current, LEDON to turn on
@param: aG - Green LED component. LEDOFF to turn LED color off; LEDSTAY to keep current, LEDON to turn on
@param: aB - Blue LED component. LEDOFF to turn LED color off; LEDSTAY to keep current, LEDON to turn on
*/
int rgbRed = LEDOFF, rgbGreen = LEDOFF, rgbBlue = LEDOFF;
void led(int aR = LEDSTAY, int aG = LEDSTAY, int aB = LEDSTAY) {
if (aR >= 0) rgbRed = aR;
if (aG >= 0) rgbGreen = aG;
if (aB >= 0) rgbBlue = aB;
if (rgbRed < 0) rgbRed = LEDOFF; if (rgbRed > LEDON) rgbRed = LEDON;
if (rgbGreen < 0) rgbGreen = LEDOFF; if (rgbGreen > LEDON) rgbGreen = LEDON;
if (rgbBlue < 0) rgbBlue = LEDOFF; if (rgbBlue > LEDON) rgbBlue = LEDON;
if ( useLed() ) {
digitalWrite(RGBLED_RED_PIN, LEDOFF);
digitalWrite(RGBLED_GREEN_PIN, LEDOFF);
digitalWrite(RGBLED_BLUE_PIN, LEDOFF);
}
else {
digitalWrite(RGBLED_RED_PIN, rgbRed <= LEDOFF ? LOW : HIGH );
digitalWrite(RGBLED_GREEN_PIN, rgbGreen <= LEDOFF ? LOW : HIGH );
digitalWrite(RGBLED_BLUE_PIN, rgbBlue <= LEDOFF ? LOW : HIGH );
}
}
/**
Turns all LED colors OFF
*/
void ledOff() {
led(LEDOFF, LEDOFF, LEDOFF);
}
// Parameter methods
// -----------------
/**
Loads parameters from EEPROM
*/
void loadParameters() {
#ifdef _DEBUG_
Serial.print(millis());
Serial.println(F(": loadParameters."));
#endif
// Let's see if we have the parameters stored already
// First lets read the token.
EEPROM.get(0, parameters);
if (strcmp(CToken, parameters.token) != 0) { // tokens do not match - load defaults
// Write down token and defaults
strncpy(parameters.token, CToken, 7);
parameters.high = (byte) STOPWATER;
parameters.low = (byte) NEEDWATER;
parameters.retries = (byte) RETRIES;
parameters.watertime = (byte) WATERTIME;
parameters.saturate = (byte) SATURATE;
parameters.gotosleep = (byte) GOTOSLEEP;
parameters.wakeup = (byte) WAKEUP;
parameters.wkendadj = (byte) WEEKENDADJ;
parameters.wl_depth = (int) WLDEPTH;
parameters.wl_low = (int) WLLOW;
parameters.is_ap = 0; // not an Access Point
// parameters.is_ap = 1; // Access Point
strncpy(parameters.ssid, CSsid, 32);
strncpy(parameters.pwd, CPwd, 65);
ssid = CDSsid + String( ESP.getChipId() );
strncpy(parameters.ssid_ap, ssid.c_str(), 32);
strncpy(parameters.pwd_ap, CDPwd, 65);
parameters.powersave = false;
parameters.ping_interval = TICKER;
parameters.led_use = 0;
strncpy(parameters.ntp_server, ntpServerName, 32);
saveParameters();
}
}
/**
Saves parameters to the EEPROM
*/
void saveParameters() {
#ifdef _DEBUG_
Serial.print(millis());
Serial.println(F(": saveParameters."));
Serial.print(F("Token: ")); Serial.println(parameters.token);
Serial.print(F("High : ")); Serial.println(parameters.high);
Serial.print(F("Low : ")); Serial.println(parameters.low);
Serial.print(F("Retries: ")); Serial.println(parameters.retries);
Serial.print(F("WaterTm: ")); Serial.println(parameters.watertime);
Serial.print(F("Saturate: ")); Serial.println(parameters.saturate);
Serial.print(F("Gotosleep: ")); Serial.println(parameters.gotosleep);
Serial.print(F("Wakeup: ")); Serial.println(parameters.wakeup);
Serial.print(F("WkendAdj: ")); Serial.println(parameters.wkendadj);
Serial.print(F("WL Depth: ")); Serial.println(parameters.wl_depth);
Serial.print(F("WL Low: ")); Serial.println(parameters.wl_low);
Serial.print(F("SSID: ")); Serial.println(parameters.ssid);
Serial.print(F("PWD: ")); Serial.println(parameters.pwd);
Serial.print(F("AP SSID: ")); Serial.println(parameters.ssid_ap);
Serial.print(F("AP PWD: ")); Serial.println(parameters.pwd_ap);
Serial.print(F("PWRSave: ")); Serial.println(parameters.powersave);
Serial.print(F("Ping Interval: ")); Serial.println(parameters.ping_interval);
Serial.print(F("Use LED: ")); Serial.println(parameters.led_use);
Serial.print(F("NTP Server: ")); Serial.println(parameters.ntp_server);
#endif
EEPROM.put(0, parameters);
EEPROM.commit();
}
// Configuration methods
// ---------------------
/**
Initiates connection to the wireless network of choice
-or- sets up the requested Access Point mode
Passes control to connection checking callback method
*/
void cfgInit() { // Initiate connection
#ifdef _DEBUG_
Serial.print(millis());
Serial.println(F(": cfgInit."));
#endif
ssid = parameters.ssid;
pwd = parameters.pwd;
#ifdef _DEBUG_
Serial.println(F("WiFi parameters: "));
Serial.print(F("SSID: ")); Serial.println(ssid);
Serial.print(F("PWD : ")); Serial.println(pwd);
Serial.println(F("AP parameters: "));
Serial.print(F("SSID: ")); Serial.println(parameters.ssid_ap);
Serial.print(F("PWD : ")); Serial.println(parameters.pwd_ap);
#endif
runningAsAP = false; // true if setting up as an Access Point was successful
connectedToAP = false; // true if connection to the wireless network of choice was successful
if (parameters.is_ap == 0) { // If not explicitly requested to be an Access Point
// attempt to connect to an exiting AP
initiate_wifi_connection();
// flash led green
rgbRed = 0; rgbGreen = LEDON; rgbBlue = 0;
ledOnDuration = CONNECT_BLINK;
ledOffDuration = CONNECT_BLINK;
tLedBlink.set(TASK_IMMEDIATE, TASK_FOREVER, &cfgLed, &ledOnEnable, &ledOnDisable);
tLedBlink.enable();
// check connection periodically
tConfigure.set(CONNECT_INTRVL, TASK_FOREVER, &cfgChkConnect);
tConfigure.enableDelayed();
// set a connection attempts timeout
tTimeout.set(CONNECT_TIMEOUT * TASK_SECOND, TASK_ONCE, &connectTOut);
tTimeout.enableDelayed();
httpError.setWaiting( HTTP_ERRORS );
tErrorReset.waitFor( &httpError );
}
else {
// Set the AP parameters and setup the AP mode
ssid = parameters.ssid_ap;
pwd = parameters.pwd_ap;
tConfigure.yield(&cfgSetAP);
}
}
/**
Initial WIFI connection to the AP
*/
void initiate_wifi_connection() {
WiFi.hostname( CHost );
WiFi.mode( WIFI_STA );
WiFi.persistent ( true );
// yield();
WiFi.begin( ssid.c_str(), pwd.c_str() );
yield();
}
/**
Periodically check if the connection was established
Re-request connection to AP on every 5th iteration
*/
void cfgChkConnect() { // Wait for connection to AP
#ifdef _DEBUG_
Serial.print(millis());
Serial.println(F(": cfgChkConnect."));
#endif
if (WiFi.status() == WL_CONNECTED) {
disconnectedEventHandler = WiFi.onStationModeDisconnected(&onDisconnected);
connectedToAP = true;
#ifdef _DEBUG_
Serial.print(F("Connected to AP. Local ip: "));
Serial.println(WiFi.localIP());
#endif
// flash led green rapidly
rgbRed = 0; rgbGreen = LEDON; rgbBlue = 0;
ledOnDuration = CONNECT_BLINK / 4;
ledOffDuration = ledOnDuration;
tLedBlink.set(TASK_IMMEDIATE, TASK_FOREVER, &cfgLed, &ledOnEnable, &ledOnDisable);
tLedBlink.enable();
// check connection periodically
tConfigure.set(CONNECT_INTRVL, TASK_FOREVER, &cfgChkNTP);
tConfigure.restartDelayed();
// set timeout
tTimeout.set(NTP_TIMEOUT * TASK_SECOND, TASK_ONCE, &ntpTOut);
tTimeout.enableDelayed();
}
else {
// delay(100);
// yield();
if (tConfigure.getRunCounter() % 5 == 0) {
#ifdef _DEBUG_
Serial.println(F("Re-requesting connection to AP..."));
#endif
// wifi_set_phy_mode(PHY_MODE_11G);
// WiFi.setOutputPower(20.5);
// WiFi.setAutoConnect(false);
WiFi.disconnect();
yield();
initiate_wifi_connection();
}
}
}
/**
Initiates call to NTP server to get current time
*/
void doNtpUpdateInit() {
#ifdef _DEBUG_
Serial.print(millis());
Serial.println(F(": doNtpUpdateInit."));
Serial.print(F("connectedToAP="));
Serial.println(connectedToAP);
#endif
if ( connectedToAP ) { // only if connected to wifi network
// request NTP update
udp.begin(LOCAL_NTP_PORT);
if ( WiFi.hostByName(parameters.ntp_server, timeServerIP) ) { //get a random server from the pool
#ifdef _DEBUG_
Serial.print(F("timeServerIP = "));
Serial.println(timeServerIP);
#endif
sendNTPpacket(timeServerIP); // send an NTP packet to a time server
}
}
}
/**
Sends an NTP request to the time server at the given address
*/
unsigned long sendNTPpacket(IPAddress & address)
{
#ifdef _DEBUG_
Serial.print(millis());
Serial.println(F(": sendNTPpacket."));
#endif
// Serial.println(F("sending NTP packet..."));
// set all bytes in the buffer to 0
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
udp.beginPacket(address, 123); //NTP requests are to port 123