-
Notifications
You must be signed in to change notification settings - Fork 3
/
SensorServer.ino
2756 lines (2501 loc) · 80.3 KB
/
SensorServer.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
#define OTA
#define IOT //......for IOT thingsSpeak data upload (---IOT--input TBD.)
#define FIX_IP //......for Fixed IP connection as from config.txt
#define OS_API //......for use of command interpreter and remote nodes control
//#define FTP //......for FTP on SPIFFS file
#define TELNET //......for TELNET debug connection on port 23
#define READCONF
#define NO_DELAY //.......if defined unit never sleep..........!
//#define PING_F 1
#define DHT11L 10 //..... for use DTH & RHT family sensors define input pin
/////////////////////////////////////////////////////////////////////////////////////
extern "C" {
#include "user_interface.h"
uint16 readvdd33(void);
bool wifi_set_sleep_type(sleep_type_t);
sleep_type_t wifi_get_sleep_type(void);
}
#include "DHT11lib.h"
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <WiFiUdp.h>
#include <ESP8266mDNS.h>
#include <FS.h>
//#include <SSIDPASSWORD.h>
#include <ArduinoOTA.h>
#include <TimeLib.h>
#include <Wire.h>
#include <RTClib.h>
#include <EEPROM.h>
#include "NPTtimeSync1.h"
//#include <ArduinoJson.h>
#include "ET_penmam.h"
#include "Eeprom_ESP.h"
#include <ESP8266OneWire.h>
#include <DallasTemperature.h>
#include <Arduino-Ping-master\ESP8266ping.h>
#include <ThingSpeak.h>
#define VARIAB Lvalue //define internal variable accessed using function val(position);
long Lvalue[20];
#include "bitlashMio.h" //bitlash interpreter called with espressione("expression formula")
#include "bitlashMio-functions.h" //bitlash interprter functions including added now()->epochtime ; val(i)->internal VARIAB[i]
//#define FTP
#ifdef FTP
#include <ESP8266FtpServer.h>
FtpServer ftpSrv;
#endif
//#define TELNET
byte ntimes = 0;
byte eecode = 255;
#define START_INTERVAL 200000
#ifdef TELNET
WiFiServer Tserver(23);
WiFiClient Tclient;
const char * IotAPIkey = "KX8OBCOWA7MP8H56";
long IotChannel = 178477UL;
byte IOTflag[8] = { 1,0,1,10,11,0,0,0 };
byte n_out_pin=0;
bool noClient = true;
long TimeOUT;
#define ONTIME 2000000L
int getClients()
{
if (noClient) {
Tclient = Tserver.available();
if (Tclient) {
noClient = false;
Serial.print("New client! ");
Tclient.flush();
Tclient.print('>');
TimeOUT = millis();
return 1;
}
return 0;
}
else //noclient false
if (!Tclient.connected() || millis()>TimeOUT + ONTIME) {
Tclient.stop();
noClient = true;
return 0;
}
return 1;
}
#define SP(x) {if(Tclient)Tclient.print(x);Serial.print(x);}
#define SPL(x) {if(Tclient)Tclient.println(x);Serial.println(x);}
#define SPS(x) {if(Tclient){Tclient.print(' ');Tclient.print(x);}Serial.print(x);}
#define SP_D(x) {if(Tclient)Tclient.print(x);Serial.print(x);}
#define SPL_D(x) {if(Tclient)Tclient.println(x);Serial.println(x);}
#define SPS_D(x) {if(Tclient){Tclient.print(' ');Tclient.print(x);}Serial.print(x);}
#else
#define SP(x) Serial.print(x)
#define SPL(x) Serial.println(x)
#define SPS(x) Serial.print(' ');Serial.print(x)
#define SP_D(x) Serial.print(x)
#define SPL_D(x) Serial.println(x)
#define SPS_D(x) Serial.print(' ');Serial.print(x)
#endif
#ifdef DHT11L
//#include <SparkFun_RHT03_Particle_Library-master\firmware\SparkFunRHT03.h>
//#include <Arduino-DHT22-master\DHT22.h>
//#include "DHT11lib.h"
#include <DHT-sensor-library-master\DHT.h>
DHT DHT(DHT11L,DHT22);
#endif
ESP8266WebServer server(80);
#define BUFFDIM 2024
const int led = 16; //.....13 for UNo..... 16 for ModeMCU
int opt[20] = { 360,360,10 ,0 ,12 ,192,168,1,30,10 ,3600, 24, 441247, 82544, 23, 30, 12, 32 };// default values
File logfile;
enum COP { WU_URL, SSID, PSW, ESP_STATION, TIME_STR };
String OpName[10] = {
"/api/48dfa951428393ba/conditions/q/Italy/", //"/api/48dfa951428393ba/conditions/q/Italy/"
"Vodafone-Out",
"paolo-48",
"poolESP"
"t: ",
" ",
" "
};
///-----------------------------class for linear regression--------------------------------------------------
class Level {
public:
#define N3600 360
#define N12 24
byte n_sample = 0, SN[N12];
long sumX, sumY, sumXY, sumX2;
long SX[N12], SY[N12], SX2[N12], SXY[N12];
void levelBegin() {
sumX = 0;
sumX2 = 0;
sumXY = 0;
sumY = 0;
n_sample = 0;
}
void levelFit(long ora, float value) {
sumX += ora;
sumX2 += ora*ora;
sumY += value;
sumXY += value* ora;
SY[ora / N3600] = sumY;
SXY[ora / N3600] = sumXY;
SX[ora / N3600] = sumX;
SX2[ora / N3600] = sumX2;
SN[ora / N3600] = n_sample++;
}
byte levelGet(byte ind1, byte ind2, float * slope, float * inter) {
int ns = SN[ind2] - SN[ind1];
if (ns > 0) {
long s1 = SY[ind2] - SY[ind1];
long s2 = SX[ind2] - SX[ind1];
long s3 = SXY[ind2] - SXY[ind1];
long s4 = SX2[ind2] - SX2[ind1];
*slope = float(s1*(s2 / 10) - ns*(s3 / 10)) / float(s2*(s2 / 10) - ns*(s4 / 10));
*inter = (s1 - *slope*s2) / ns;
SP(ns); SPS(*slope); SPS(*inter); SPL();
}
return ns;
}
};
Level pool;
//-------------------------------weather class---------------------------------------------------
struct Weather
{
time_t time; //"local_epoch" local epoch time
int temp; //"temp_c" temp ° celsius
int humidity; //"relative_humidity" humidity %
int rain1h; //"precip_1h_metric" rain last hour 0.1mm
int rain; //"precip_today_metric" rain today 0.1mm
int wind; //{"wind_kph"} wind speed Km/h
// int atpres; //"pressure_mb" atm. pressure milliBar
int sunrad; //solar radiation from WU station
float penman; //ETo penmam-monteith
float water; //solar KWh on solar panels
void write() {
File wfile;
if (SPIFFS.exists("/weather.log"))
wfile = SPIFFS.open("/weather.log", "r+");
else
wfile = SPIFFS.open("/weather.log", "w+");
if (!wfile) { Serial.println("Cannot open weather.log"); return; }
wfile.seek(0, SeekEnd);
wfile.seek(0, SeekEnd);
wfile.print(time); wfile.print(',');
wfile.print(temp); wfile.print(',');
wfile.print(humidity); wfile.print(',');
wfile.print(rain1h); wfile.print(',');
wfile.print(wind); wfile.print(',');
wfile.print(penman); wfile.print(',');
wfile.print(water); wfile.print(',');
wfile.print(sunrad); wfile.print(',');
wfile.println(rain);
wfile.close();
}
bool read(time_t timev) {
char buf[20];
byte n;
time = 0;
File wfile;
if (SPIFFS.exists("/weather.log"))
wfile = SPIFFS.open("/weather.log", "r+");
else
wfile = SPIFFS.open("/weather.log", "w+");
if (!wfile) {
Serial.println("Cannot open weather.log"); return 0;
}
wfile.seek(0, SeekEnd);
long wfilepos = wfile.position();
wfile.seek(0, SeekSet);
while (time < timev&&wfile.available()) {
if (wfile.find(10)) {
n = wfile.readBytesUntil(',', buf, 20);
buf[n] = 0;
time = atol(buf);
// SPS_D(buf);
}
else {
if (wfile.read()<0) { wfile.close(); return 0; }
}
}
if (!wfile.available()) { wfile.close(); return false; }
n = wfile.readBytesUntil(',', buf, 20);
buf[n] = 0; //SPS_D(buf);
temp = atoi(buf);
n = wfile.readBytesUntil(',', buf, 20);
buf[n] = 0; //SPS_D(buf);
humidity = atoi(buf);
n = wfile.readBytesUntil(',', buf, 20);
buf[n] = 0; //SPS_D(buf);
rain1h = atoi(buf);
n = wfile.readBytesUntil(',', buf, 20);
buf[n] = 0; //SPS_D(buf);
wind = atoi(buf);
n = wfile.readBytesUntil(',', buf, 20);
buf[n] = 0;// SPS_D(buf);
penman = atof(buf);
n = wfile.readBytesUntil(',', buf, 20);
buf[n] = 0;// SPS_D(buf);
water = atof(buf);
n = wfile.readBytesUntil(',', buf, 20);
buf[n] = 0;// SPS_D(buf);
sunrad = atoi(buf);
n = wfile.readBytesUntil(',', buf, 20);
buf[n] = 0;// SPS_D(buf);
rain = atoi(buf);
wfile.seek(wfilepos, SeekSet);
wfile.close();
return true;
}
};
#define MAX_WEATHER_READ 10
Weather weather[MAX_WEATHER_READ]; byte iw = 0;
#define ET0
#define SUNPANELFACTOR opt[17]/100. //0,36
//---------------------------------Geo/sun constant structure
#ifdef ET0
struct Geo
{
float lat;//{"latitude"}
float lon;//{"longitude"}
int alt;//{"elevation"}
float alfa ;//solar panels Elevation
float beta ;//solar panels Azimuth
};
Geo sta;
//{ 44.12474,8.25445,23, 30. / 180. * PI, 12. / 180. * PI };
float slopeV[10]; byte ki = 0;
float rad_ratio = 0.8, prev_elevation = 0;
float ET0_calc(byte type) {
Weather w_mean;
Weather w_max, w_min;
byte iwp = iw + 1;
byte iwm = iw - 1;
if (iw == 0)iwm = MAX_WEATHER_READ - 1;
if (iw == MAX_WEATHER_READ-1)iwp = 0;
if (weather[iwp].time == 0)return -1;
w_mean.time = 0;
w_mean.rain1h = 0;
w_max.time = weather[iw].time;
w_max.rain = weather[iw].rain; // today rain
w_min.rain = weather[iwp].rain;
w_min.time = weather[iwp].time;
w_mean.temp = 0;
w_max.temp = -10;
w_min.temp = 50;
w_mean.humidity = 0;
w_max.humidity = 0;
w_min.humidity = 100;
w_mean.wind = 0;
w_mean.sunrad = 0;
w_max.sunrad = 0;
w_min.sunrad = 1200;
w_mean.water = 0;// (weather[iw].water - weather[iwp].water) / (weather[iw].time - weather[iwp].time) * 3600; //kwH produced last 1 h
byte iel = 0;
time_t timep=0;
byte nwaterread = 0, n_sunrad = 0,n_temp=0,n_wind=0,n_rain1h=0;
float waterp = weather[MAX_WEATHER_READ-1].water;
for (byte i = 0; i < MAX_WEATHER_READ; i++) {
// SPS_D(weather[i].temp); SPS_D(weather[i].humidity); SP_D(" "); SPL_D(weather[i].wind);
w_mean.time += weather[i].time/MAX_WEATHER_READ;
if (weather[i].rain1h > 0)// distance level
{
w_mean.rain1h += weather[i].rain1h;
n_rain1h++;
}
if (weather[i].temp > 0) {
w_mean.temp += weather[i].temp;
if (w_max.temp < weather[i].temp)w_max.temp = weather[i].temp;
if (w_min.temp > weather[i].temp)w_min.temp = weather[i].temp;
n_temp++;
}
if (weather[i].humidity > 0) {
w_mean.humidity += weather[i].humidity;
if (w_max.humidity < weather[i].humidity)w_max.humidity = weather[i].humidity;
if (w_min.humidity > weather[i].humidity)w_min.humidity = weather[i].humidity;
}
if (weather[i].wind >= 0) {
w_mean.wind += weather[i].wind;
n_wind++;
if (w_max.wind < weather[i].wind)w_max.wind = weather[i].wind;
if (w_min.wind > weather[i].wind)w_min.wind = weather[i].wind;
}
if (weather[i].sunrad > 0) {
n_sunrad++;
w_mean.sunrad += weather[i].sunrad;
if (w_max.sunrad < weather[i].sunrad)w_max.sunrad = weather[i].sunrad;
if (w_min.sunrad > weather[i].sunrad)w_min.sunrad = weather[i].sunrad;
}//_________________________________________solar panels Kwh mean computed as------> w
if (timep!=0&&weather[i].water != -1 && waterp != -1&&weather[i].water>waterp&&weather[i].time>timep+60) {
float solar_panels_watts = (weather[i].water - waterp) / (weather[i].time - timep);
if (solar_panels_watts < 2) { //2*3600 ->7200 Watts max
w_mean.water += solar_panels_watts;
// SPS("_"); SPS(weather[i].time - timep); SPS(solar_panels_watts); SPS("_");
// SP(weather[i].water); SP(" "); SPL(waterp);
nwaterread++;
}
}
waterp = weather[i].water;
timep = weather[i].time;
#define SUN_START 300
}
if (n_temp == 0 || n_wind == 0 )return -1;
w_mean.rain1h /= MAX_WEATHER_READ;
w_mean.temp /= n_temp;
w_mean.wind /= n_wind;
w_mean.humidity /= MAX_WEATHER_READ;
if (n_sunrad > 0)w_mean.sunrad /= n_sunrad;
if(nwaterread>0)
w_mean.water = w_mean.water/nwaterread*3600;//*MAX_WATER_READ; back to -------->KwH
else w_mean.water = 0;
long sumProd = 0, sumSqr = 0;
SP(" t "); SPL(w_mean.time);
for (byte i = 0; i < MAX_WEATHER_READ; i++)
if(weather[i].rain1h>0){
//SP(sumProd); SP(' '); SP(sumSqr); SP("Dtime"); SP(long(weather[i].time) - long(w_mean.time)); SP(" D "); SPL(weather[i].rain1h - w_mean.rain1h);
sumProd +=(long(weather[i].time) - long(w_mean.time))*(weather[i].rain1h - w_mean.rain1h);
sumSqr += (long(weather[i].time) - long(w_mean.time))*(long(weather[i].time) - long(w_mean.time));
}
float sunset_time = sunrise__sunset_localtime(sta.lon, sta.lat, 2, 1);
float sunrise_time = sunrise__sunset_localtime(sta.lon, sta.lat,2, 0);
SP("sunrise"); SPS(sunrise_time); SPS("sunset"); SPL(sunset_time);
int doy = (month(w_max.time) - 1) * 30 + day(w_max.time);
#define MID_DAY (sunset_time!=0?(sunset_time+sunrise_time)/2:13.5) //mid day sun hour
// used local time weather.time converted to GMT added latitude time angle ...... better to use GMT time!!
// time_angle as local time_angle referred to south
float time_angle = (hour(weather[iw].time) + minute(weather[iw].time) / 60. - MID_DAY + 12*sta.lon / 180.-0.5);// -0.5h time shift for 1h average data
SP("t_a"); SPS(hour(weather[iw].time)); SPL(time_angle);
float visibility = 50; // _______________best visibility km
float sun_elevation = asin(sin(radians(sta.lat))*sin(sol_dec(doy)) + cos(radians(sta.lat))*cos(sol_dec(doy))*cos(time_angle*3.1415 / 12));
float sun_azimut = acos((sin(sun_elevation)*sin(sta.lat*PI / 180) - sin(sol_dec(doy))) / (cos(sun_elevation)*cos(sta.lat*PI / 180.)));
if (time_angle<0) if( sun_azimut>0)sun_azimut *= -1.;
else if (sun_azimut<0)sun_azimut *= -1.;
prev_elevation = sun_elevation;
float time_factor = cos(sun_azimut)*cos(sta.beta) + sin(sun_azimut)*sin(sta.beta);
float sun_panel_inclination_factor = (cos(sta.alfa)*sin(sun_elevation) + sin(sta.alfa)*cos(sun_elevation)*time_factor);
SPS("sun_el "); SP(sun_elevation); SPS("Az"); SPS(sun_azimut); SPS("P_f"); SPS(sun_panel_inclination_factor);
SP(" corrF"); SPL(sin(sun_elevation) / sun_panel_inclination_factor);
float expected_sunrad = 0;
if (sun_elevation > 0)
expected_sunrad = 1352.*exp(-(39 / visibility + 0.85)*atmos_pres(sta.alt) / atmos_pres(0) / (0.9 + 9.4 * sin(sun_elevation)));
/* SPS_D(sol_dec(doy)); SPS_D(MID_DAY); SPS_D(time_angle); SPS_D(sun_elevation); SPS_D("es"); SPL_D(expected_sunrad);
static int nfactor;
if (expected_sunrad > 10)
if (nfactor == 0)
if (time_angle > 0) // if is a restart and afternoon recompute previous_factor from records
for (byte ii = 1; ii < 6; ii++) {
iwo = iw - ii; if (iwo < 0)iwo = MAX_WEATHER_READ - iwo;
time_angle = (hour(weather[iwo].time) + 2. + minute(weather[iwo].time) / 60. - MID_DAY + sta.lon / 360.);
sun_elevation = asin(sin(radians(sta.lat))*sin(sol_dec(doy)) + cos(radians(sta.lat))*cos(sol_dec(doy))*cos(time_angle*3.1415 / 12));
float expecte_sunrad = 0;
if (sun_elevation > 0)
expecte_sunrad = 1352.*exp(-(39 / visibility + 0.85)*atmos_pres(sta.alt) / atmos_pres(0) / (0.9 + 9.4 * sin(sun_elevation)));
previous_factor = (previous_factor*nfactor + weather[iwo].sunrad) / (nfactor + expecte_sunrad);
nfactor = nfactor + expecte_sunrad;
}
if (savona_result ||
(weather[iw].sunrad > expected_sunrad || weather[iw].sunrad < expected_sunrad*0.05)) //error reading sunrad assume =previous reading
{
SPS_D("apply cal. sunrad");
if (previous_factor < 1.) {
weather[iw].sunrad = expected_sunrad*previous_factor;
}
else weather[iw].sunrad = expected_sunrad;
}
else //----------------------compute previous_factor as average of sunrad/expected_sunrad
if (expected_sunrad > 10) {
previous_factor = (previous_factor*nfactor + weather[iw].sunrad) / (nfactor + expected_sunrad);
nfactor = nfactor + expected_sunrad;
}
else nfactor = 0;
SP("p_f"); SP(previous_factor);
//compute day cumulative sun radiation
float day_sunrad = 0;
for (byte j = 1; j < 24 / FREQ_WEATHER; j++) {
int i = iw - j; if (i < 0)i = MAX_WEATHER_READ + 1 + i;
iwo = i + 1; if (i > MAX_WEATHER_READ)iwo = 0;
// if (j == 0)iwo = iw - 24 / FREQ_WEATHER + 1; if (iwo < 0)iwo = MAX_WEATHER_READ + iwo + 1;
if (weather[i].sunrad >= 0 && weather[i].sunrad < 1100 && weather[iwo].sunrad >= 0 && weather[iwo].sunrad < 1100) {
long dtime;
if (j == 0)
// dtime = -(weather[i].time - weather[iwo].time-SECS_PER_DAY);
dtime = (-hour(weather[iwo].time) * 3600 + minute(weather[iwo].time) * 60) + (hour(weather[i].time) * 3600 + minute(weather[iwo].time) * 60);
else
dtime = -(weather[i].time - weather[iwo].time);
if (dtime > 40000)dtime = 12000; // missing data---max step 3.5 hours
day_sunrad += (weather[iwo].sunrad + weather[i].sunrad) / 2 * (dtime / 1000);
SPS_D(i); SPS_D(iwo); SPS_D(dtime); SPS_D(weather[i].time); SPS_D(weather[i].sunrad); SP_D(" "); SPL_D(day_sunrad);
}
}
if (day_sunrad > 28000.) {
byte ix = iw - 1;
if (ix < 0)ix = MAX_WEATHER_READ;
while (weather[ix].penman > 6.) {
ix--; if (ix < 0)ix = MAX_WEATHER_READ;
}
weather[iw].penman = weather[ix].penman;
}
else
{
w_mean.sunrad = int(day_sunrad);
*/
SP("t"); SPS(w_max.temp); SPS(w_mean.temp); SPS_D(w_min.temp);
SP_D("h"); SPS(w_max.humidity); SPS(w_min.humidity);
SP_D("w"); SPS_D(w_mean.wind);
SP_D("s"); SPS_D(w_mean.sunrad);
SP_D("Sp"); SPL(w_mean.water);
//__________________penman____________________________________________
int sunHours = 10;
float rad_clearsky = clear_sky_rad(
sta.alt,
et_rad(sta.lat, sta.lon,
sunset_hour_angle(sta.lat, sol_dec(doy)),
inv_rel_dist_earth_sun(doy)));
float Sun,ET;
if (type == 0 && w_mean.sunrad< 1200) { // calculate from WU station sunrad
Sun = w_mean.sunrad / 1000;
if (expected_sunrad>100)rad_ratio = Sun / expected_sunrad;
SPS("rad_r"); SPS(rad_ratio);
ET=ETo_hourly(float(w_mean.sunrad), w_mean.temp, w_mean.wind / 3.6,
mean_es(w_min.temp, w_max.temp),
ea_from_tmin(w_min.temp),
delta_sat_vap_pres(w_mean.temp),
psy_const(atmos_pres(sta.alt)),
rad_ratio);
SP("ET-0="); SPL(ET);
if (ET>0)return ET;
else return 0;
}
else if (type == 1 && w_mean.water < 5000) {
Sun = w_mean.water*SUNPANELFACTOR;
if (sun_panel_inclination_factor>0.01)
Sun = w_mean.water * SUNPANELFACTOR *sin(sun_elevation) / sun_panel_inclination_factor; //account for angle and size
SPS("Sun"); SPS(Sun);
if (expected_sunrad> 100)rad_ratio = Sun / expected_sunrad;
SPS("rad_r"); SPS(rad_ratio);
float rad_out = 4.9E-09*pow(w_mean.temp+275., 4.)*(0.34 - 0.14*sqrt(ea_from_tmin(w_min.temp)))*(1.35*rad_ratio - 0.35);
SPS(" r_O "); SPS(rad_out);
ET= ETo_hourly(Sun, w_mean.temp, w_mean.wind / 3.6,
mean_es(w_min.temp, w_max.temp),
ea_from_tmin(w_min.temp),
delta_sat_vap_pres(w_mean.temp),
psy_const(atmos_pres(sta.alt)),
rad_ratio);
SP("ET1="); SPL(ET);
if (ET>0)return ET;
else return 0;
}
else
if (type == 3) {
ki++; if (ki == 10)ki = 0; slopeV[ki] = (sumProd * 3600.) / sumSqr;
return slopeV[ki];
}
else
if (type == 4){float tot = 0;
for (byte iki = 0; iki < 10; iki++)tot += slopeV[iki]; return tot / 10.;
}
else
{ //calculate from Solar panel WATTS
Sun = sol_rad_from_sun_hours(
daylight_hours(doy),
sunHours,
et_rad(sta.lat, sta.lon,
sunset_hour_angle(sta.lat, sol_dec(doy)),
inv_rel_dist_earth_sun(doy)));
}
SP(rad_clearsky); SP(' '); SP(Sun);
float net_radi = net_rad(net_in_sol_rad(Sun),
net_out_lw_rad(
w_min.temp, w_max.temp,
Sun,
rad_clearsky,
ea_from_tmin(w_min.temp)));
SP(' '); SP(net_radi);
weather[iw].penman = penman_monteith_ETo(net_radi, w_mean.temp, w_mean.wind / 3.6,
mean_es(w_min.temp, w_max.temp),
ea_from_tmin(w_min.temp),
delta_sat_vap_pres(w_mean.temp),
psy_const(atmos_pres(sta.alt)),
0.10);
return weather[iw].penman;
}
#endif
void pulseLed(int dur, int pause, int times) {
for (byte i = 0; i < times; i++) { digitalWrite(led, 0); delay(dur); digitalWrite(led, 1); delay(pause); }
}
volatile unsigned long npulses = 0, oldmillis = 0, pulsmils;
void setupinterrupt(byte pin, byte mode) {
pinMode(pin, INPUT_PULLUP);
// digitalWrite(pin,HIGH);
attachInterrupt(digitalPinToInterrupt(pin), count, mode);
}
#define MINPULSDUR 100
void count() {
noInterrupts();
unsigned long dif= millis() - oldmillis;
if (dif > MINPULSDUR) { //____________________________short pulses not considered____________________________
npulses++;
oldmillis = millis();
pulsmils = dif;
}
interrupts();
}
//_________________________________________________________________________________________________________________________________________class SENSOR
class Sensor {
public:
byte nsensors = 0, sensorT[10], pin1[10], pin2[10],kk=0;
float value[30];
unsigned long time_sensor = 0, time_sensor1 = 0;
String name[15];
String param[30];
// byte format[30] = { 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 };
float sumY, sumXY,sumX,sumX2;
float SX[24], SY[24], SX2[24], SXY[24];
byte n_sample, SN[24];
void beginSensor(byte type, byte pin, byte n_par,char nome[], String par[]) {
int temp[2];
sensorT[nsensors] = type;
pin1[nsensors] = pin;
pin2[nsensors] = n_par;
name[nsensors] = nome;
if (type == 1) DHT.begin();
for (byte i = 0; i < n_par; i++)param[kk++] = par[i];
//if (time_sensor == 0)time_sensor = time;
nsensors++;
SP(sensorT[nsensors - 1]); SP(' ');
SP(pin1[nsensors - 1]); SP(' ');
SP(name[nsensors - 1]); SP(' ');
for (byte i = 0; i < n_par; i++)SP(param[kk-1-i]);
SPL();
if (type == 5) { if (start_read_OneWire(pin, temp, 0) < n_par) SPL("not found Temp sensor"); }
else if (type == 8) setupinterrupt(pin, CHANGE);
} //setup sensors (type,byte pin);
//--------------------------------------------------------------------------
#define MIL_JSON_ANS 60000
#define MAX_JSON_STRING 2500
//char json[2600];
byte APIweatherV(String streamId, String nomi[], byte Nval, float val[]) {
WiFiClient client;
char json[2500];
//if (client.connected()) client.stop();
SPL("connecting to WU");
const int httpPort = 80;
if (!client.connect("api.wunderground.com", 80))
{
client.stop();
SP("connection failed ");// SPL(jsonserver);
pulseLed(2000, 0, 1);
return 0;
}
// SP("mem.h."); SPL(ESP.getFreeHeap());
String url = "GET ";
// streamId= "/api/48dfa951428393ba/conditions/q/Italy/pws:ISAVONAL1.json";
url = url + streamId
+ " HTTP/1.1\r\n" + "Host: " + "api.wunderground.com" + "\r\n" + "Connection: close \r\n\r\n";
client.print(url);
int i = 0, json_try = 0; bool ISJSON = false; byte ii = 0;
// Serial.println("Waiting Json");
long time_step = millis() + MIL_JSON_ANS;
char c, cp, cpp; bool obs = false;
delay(500);
while (millis() < time_step)
{
// Read all the lines of the reply from server and print them to Serialbol
while (millis() < time_step -MIL_JSON_ANS / 2 && !obs)
{
int nby = client.available();
if (nby>100) {
#ifdef VERIFY_WU_ANSWER
Serial.print(client.read());
#else
obs = client.find("current_observation");
#endif
}
else
{
SP(nby); SP('-');
pulseLed(nby + 40, 50, 1);
}
}
if (!obs) {
SPL("error");
while (client.available()) SP(client.read());
pulseLed(1000, 0, 1);
client.stop(); return 0;
}
//_________________timestep is connection timeout_______________________________ }}} ____end of jsonstring
while (millis() < time_step&&c != '}'&&cp != '}'&&cpp != '}')
while (obs&&client.available() && i < MAX_JSON_STRING) {
cpp = cp;
cp = c;
c = client.read();
// if (c == '{')
ISJSON = true;
if (ISJSON) {
json[i++] = c;
// SP(c);
}
}
if (ISJSON) {
json[i - 1] = 0;
client.stop();
//SP("Connected ! "); SPL(url);
SP(" Json read!"); SPL(i);
Serial.print("m.b.h."); Serial.println(ESP.getFreeHeap());
#define JSONLIB
#ifndef JSONLIB
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(json);
Serial.print("m.a.h."); Serial.println(ESP.getFreeHeap());
// Test if parsing succeeds.
if (!root.success()) {
SPL("Weather parseObject() failed");
return 0;
}
else {
SPL("Weather Parsing...");
for (byte i = 1; i < Nval + 1; i++) {
if (nomi[i] == "local_epoch")
{
time_t time = root["local_epoch"];
SPL(time);
val[i - 1] = (float)time;
}
else
{
float valore = root[nomi[i]];
// const char * nul= root[nomi[i]];
// if (nul == "--")valore = -1;
val[i - 1] = valore;
SP(nomi[i]); SPL(valore);
// SP_D(valore);
}
}
return 1;
}
#else //va_end(args);
byte ret = JsonDecode(Nval + 1, json, nomi, val);
for (byte i = 1; i <= Nval; i++) {
SP(nomi[i]);
val[i - 1] = val[i];
SPL(val[i]);
}
return ret;
#endif
}
else SPL("no json");
}
client.stop();
// SP("mem.h."); SPL(ESP.getFreeHeap());
return 0;
}
/* byte prova() {
WiFiClient client;
const int httpPort = 80;
if (!client.connect("api.wunderground.com", 80))
{
client.stop();
SP("connection failed ");// SPL(jsonserver);
pulseLed(2000, 0, 1);
return 0;
}
// /api/48dfa951428393ba/conditions/q/Italy/pws:ISAVONAL1.json HTTP/1.1
// Host: api.wunderground.com
// Connection: close
String url = "GET ";
String streamId = "/api/48dfa951428393ba/conditions/q/Italy/pws:ISAVONAL1.json";
//url += "?pw=";
//url += privateKey;
url = url + streamId
+ " HTTP/1.1\r\n" + "Host: " + "api.wunderground.com" + "\r\n" + "Connection: close \r\n\r\n";
//url += "&value=";
//url += value;
// client.flush();
// Serial.print(" Requesting URL: ");
// Serial.print(url);
client.print(url);
// client.print("GET /api/48dfa951428393ba/conditions/q/Italy/pws:ISAVONAL1.json HTTP/1.1 \r\n Connection: close \r\n \r\n");
ulong millismax = millis() + 10000;
while (!client.available() && millis() < millismax)delay(10);
if (!client.available())SPL("no rep");
while (client.available())SP(char(client.read()));
client.stop();
}
*/
//#define MYDECODE
#ifdef MYDECODE
float getvalue(char * buff, String nome) {
char* buffin;
char * p2;
char * p1;
nome = char(34) + nome + char(34);
SPL(nome);
buffin = strtok_r(buff, ",",&p1);
SPL(buffin);
while (buffin != NULL&&strtok_r(buffin, ":", &p2) != nome.c_str()) {
SPL(buffin); buffin = strtok_r(NULL, ",", &p1);
}
if (buffin == NULL)return -1;
else {
float val;
char * pointer = strtok_r(NULL, ",", &p2);
if (strchr(pointer, '.') == NULL) val = (float)atol(pointer);
else val = atof(pointer);
return val;
}
}
byte JsonDecode(byte Nval, char json[], String nomi[], float val[]) {
for (byte i = 0; i < Nval; i++)
val[i] = getvalue(json, nomi[i]);
}
#else
#define MYDECOD
#ifdef MYDECOD
byte JsonDecode(byte k, char buff[], String nome[], float val[]) {
byte ret = 0;
char* buffin;
char * p2;
char * p1;
byte i = 0;
//for (i = 0; i<k; i++)
// nome[i] = char(34) + nome[i] + char(34);
//SPL(nome);
buffin = strtok_r(buff, ",", &p1);
// SPL(buffin);
char * title = " ";
int comp = -1;
while (buffin != NULL)
{
buffin = strtok_r(NULL, ",", &p1);
if (buffin != NULL) {
// SPL(buffin);
title = strchr(strtok_r(buffin, ":", &p2), '"');
if (title != NULL) {
// SP(strlen(title)); SPL(title);
i = 1; //------------------------------first nome not used-------------
while (comp != 0 && i<k) {
String nomev = char(34)+nome[i] + char(34);
comp = strcmp(title,nomev.c_str()); i++;
}
if (comp == 0) {
Serial.print("T "); Serial.println(title);
// float val;
char valore[20];
char * pointer = strtok_r(NULL, ",", &p2);
char *point1 = strchr(pointer, '"'); //if value in between " " extract it
if (point1 != NULL) {
byte kk = 1;
while (point1[kk] != '"') { valore[kk - 1] = point1[kk++]; }
valore[kk - 1] = 0;
}
else strcpy(valore, pointer);
if (strchr(valore, '.') == NULL) {
long v = atol(valore); Serial.println(v);
val[i - 1] = (float)v;
}
else val[i - 1] = atof(valore);
ret = 1;
Serial.println(val[i - 1]);
comp = -1;
}
}
else comp = -1;
}
}
return ret;
}
#else
byte JsonDecode(byte Nval,char * json, String nomi[], float val[]) {
DynamicJsonBuffer jsonBuffer;
JsonObject& root = jsonBuffer.parseObject(json);
//Serial.print("m.a.h."); Serial.println(ESP.getFreeHeap());
// Test if parsing succeeds.
if (!root.success()) {
SPL("Weather parseObject() failed");
SPL(json);
return 0;
}
else {
SPL("Weather Parsing...");
for (byte i = 1; i < Nval + 1; i++) {
if (nomi[i] == "local_epoch")
{
time_t time = root["local_epoch"];
SPL(time);
val[i - 1] = (float)time;
}
else
{
float valore = root[nomi[i]];
// const char * nul= root[nomi[i]];
// if (nul == "--")valore = -1;
val[i - 1] = valore;
SP(nomi[i]); SPL(valore);
// SP_D(valore);
}
}
return 1;
}
}
#endif
#endif
long lvalue[20], sumET0 = 0;
// EEPROM 900--remote commands--------1000--rules---------
#define WEATHERPOS 10 //eeprom pos for weather[i]
#define MYPOS 500 //eeprom pos for pool[24]
#define SUMETPOS 6 //eeprom pos for total dayly ET0
#define WLEV0H 2 //" "" for water level at 0:0 h
#define ERROR_P 0 //" " for errors
#define PINGTIMES 10
#define EELONGW(x, y) { eeprom_write_block(&y,(void *)x,4);}
#define EELONGR(x, y) {eeprom_read_block(&y,(void*)x,4); }
#define POOLFACTOR opt[POOL_FACTOR]//12 // surface of swimming pool area 96mq / area of expansion tank 8mq
#define MININTERVAL 350 // 6 minutes less 10 second tollerance
#define NEW_ET0 // 6 minutes less 10 second tollerance
//_____________________________________________________________________________________________________________________
bool readSensors(long timeint) {//read and record sensors values each time interval sec
if (millis() > time_sensor) {
// 0h first time of the day
if (now() % SECS_PER_DAY < timeint) {
sumET0 = 0;
pool.levelBegin(); //sumY = 0; sumXY = 0; sumX = 0; sumX2 = 0; n_sample = 0;
}
#ifdef PING_F
byte ntry = 0;
SP("ping ");
while (!Ping.ping(IPAddress(192, 168, 1, 1))) {
pulseLed(100, 100, 1); ntry++;
if (ntry > 250)return 0;
}
SP("OK"); SPL(ntry);
#endif
byte k = 0;
time_sensor = millis() + timeint * 1000;
#ifndef NEW_ET0
iw++; if (iw >= MAX_WEATHER_READ)iw = 0;
#endif
for (byte i = 0; i < nsensors; i++) {
if (sensorT[i] == 0) //---------------------- Ultrasonic Distance sensor
{
int readings[PINGTIMES], minv = 0, maxv, it = 0;
byte rept = 0;
SPL((opt[2] > PINGTIMES ? PINGTIMES : opt[2]));
while ((rept<20)&&(it < (opt[2]>PINGTIMES ? PINGTIMES : opt[2]))) {
readings[it] = readDistance(pin1[i] / 16, pin1[i] % 16, weather[iw].temp);//distance 0..1 mm
if (readings[it] > 0) {
minv += readings[it]; it++;
}
rept++;
SP(rept); SP(" "); SPL(it);
}
if (it > 0) {
lvalue[k] = 0;
SPS(maxv); SPS(minv);
maxv = minv*1.1 / it; minv = minv*0.9 / it; it = 0;
for (byte rept = 0; rept < (opt[2]>PINGTIMES ? PINGTIMES : opt[2]); rept++)
if (readings[rept] > minv&&readings[rept] < maxv) {
lvalue[k] += readings[rept]; it++;
}
if (it > 0)lvalue[k] /= it;
}
else lvalue[k] = -(opt[2]>PINGTIMES ? PINGTIMES : opt[2]);
lvalue[k] /= (opt[2]>PINGTIMES ? PINGTIMES : opt[2]);
SP("d_"); SPL(lvalue[k]);
value[k] = lvalue[k];
#ifdef IOT1
ThingSpeak.setField(3, value[k]);
#endif
if (now() % SECS_PER_DAY < timeint)EELONGW(WLEV0H, lvalue[k]);
k++; //value are mm.
//--------------------store on weather-------------------------------
#ifndef NEW_ET0
weather[iw].rain1h = value[k - 1];
#endif
n_sample++;
float p_val= value[k - 1];
long ora = hour() * 3600 + minute() * 60 + second();
pool.levelFit(ora / 10, value[k - 1]);
if (pin2[i] > 1) {
//float sl,si; pool.levelGet(0, 1, &sl, &si); //get 0h water level from least sq. fit
long lev; EELONGR(WLEV0H, lev);
SPS("0h_lev"); SPS(lev); //get 0h water level from EEprom saved val.
value[k++] = p_val - lev;
}
}
else if (sensorT[i] == 1) //-------------------------DHT11other sensors