-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathOpenWeatherOneCall.cpp
1630 lines (1286 loc) · 50.1 KB
/
OpenWeatherOneCall.cpp
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
/*
OpenWeatherOneCall.cpp v4.0.1
Updated for ArduinoJSON v7 on Aug 1, 2024
copyright 2020/2024 - Jessica Hershey
www.github.com/JHershey69
Open Weather Map - Weather Conditions
For ESP32 Only
Viva La Resistance
REVISION HISTORY
See User Manual
**************************************************************
************NO USER EDITABLE LINES IN THIS FILE***************
**************************************************************
*/
#include "OpenWeatherOneCall.h"
void dateTimeConversion(long _epoch, char *_buffer, int _format);
OpenWeatherOneCall::OpenWeatherOneCall()
{
}
// For Normal Weather calls *************
#define DS_URL1 "https://api.openweathermap.org/data/3.0/onecall"
char DS_URL2[100];
#define DS_URL3 "&appid="
// For Air Quality calls current *************
#define AQ_URL1 "https://api.openweathermap.org/data/2.5/air_pollution?lat="
#define AQ_URL2 "&lon="
#define AQ_URL3 "&appid="
// For TIMESTAMP Weather Calls **********
#define TS_URL1 "https://api.openweathermap.org/data/3.0/onecall/timemachine"
#define TS_URL2 "&dt="
// For OVERVIEW weather calls ***********
#define OV_URL1 "https://api.openweathermap.org/data/3.0/onecall/overview"
#define OV_URL2 "&date="
// For CITY Id calls
#define CI_URL1 "api.openweathermap.org/data/3.0/weather?id="
#define CI_URL2 "&appid="
#define SIZEOF(a) sizeof(a)/sizeof(*a)
// Main Method for Weather API Call and Parsing
int OpenWeatherOneCall::parseWeather(void)
{
OpenWeatherOneCall::setOpenWeatherKey(ONECALLKEY);
OpenWeatherOneCall::setExcl(myEXCLUDES);
OpenWeatherOneCall::setUnits(myUNITS);
OpenWeatherOneCall::setDateTimeFormat(myDTF);
OpenWeatherOneCall::setCurrent(myCURRENT);
OpenWeatherOneCall::setAirQuality(myAIRQUALITY);
OpenWeatherOneCall::setTimestamp(myTIMESTAMP, timestampDate);
OpenWeatherOneCall::setOverview(myOVERVIEW, overviewDate);
int error_code = 0;
if (WiFi.status() != WL_CONNECTED)
{
return 25;
}
// LOCATION MODE SET
if(locationMode == 1)
{
OpenWeatherOneCall::setLatLon(myLATITUDE, myLONGITUDE);
}
else if(locationMode == 2)
{
OpenWeatherOneCall::setLatLon(myCITYID);
}
else if(locationMode == 3)
{
OpenWeatherOneCall::setLatLon();
}
unsigned int SIZE_CAPACITY = 32768;
// Bitwise function that sets the bits for the EXCLUDES argument
SIZE_CAPACITY = OpenWeatherOneCall::setExcludes(USER_PARAM.OPEN_WEATHER_EXCLUDES);
if((USER_PARAM.OPEN_WEATHER_LATITUDE) || (USER_PARAM.OPEN_WEATHER_LONGITUDE))
{
OpenWeatherOneCall::getLocationInfo();
if(USER_PARAM.OPEN_WEATHER_TIMESTAMP)
{
int error_code = OpenWeatherOneCall::createTimestamp();
}
else
{
OpenWeatherOneCall::freeTimestampMem();
}
if(USER_PARAM.OPEN_WEATHER_OVERVIEW)
{
int error_code = OpenWeatherOneCall::createOverview();
}
else
{
OpenWeatherOneCall::freeOverviewMem();
}
if(USER_PARAM.OPEN_WEATHER_AIRQUALITY)
{
int error_code = OpenWeatherOneCall::createAQ(384);
}
if(USER_PARAM.OPEN_WEATHER_CURRENT)
{
int error_code = OpenWeatherOneCall::createCurrent(SIZE_CAPACITY);
}
else
{
OpenWeatherOneCall::freeCurrentMem();
}
if(error_code)
{
return error_code;
}
}
else
{
return 24; //Must set Latitude and Longitude somehow
}
return 0;
}
/*
REMOVED LEGACY CALLING METHOD AS OF 3.3.4
*/
int OpenWeatherOneCall::createTimestamp()
{
int error_code = 0;
char timestampURL[200] = {0};
long tempEPOCH = extractDate(USER_PARAM.OPEN_WEATHER_TIMESTAMP_DATE);
//Setup API URL for TIMESTAMP Weather Call [Single Timestamp only]
sprintf(timestampURL,"%s?lat=%.6f&lon=%.6f%s%ld&units=%s%s%s",TS_URL1,USER_PARAM.OPEN_WEATHER_LATITUDE,USER_PARAM.OPEN_WEATHER_LONGITUDE,TS_URL2,tempEPOCH,units,DS_URL3,USER_PARAM.OPEN_WEATHER_DKEY);
HTTPClient http;
http.begin(timestampURL);
int httpCode = http.GET();
if (httpCode > 399)
{
if(httpCode == 401)
{
http.end();
return 22;
}
else
{
http.end();
return 21;
}
}
JsonDocument doc;
deserializeJson(doc, http.getString());
strncpy(location.timezone,doc["timezone"],50);
location.timezoneOffset = doc["timezone_offset"];
if(!timestamp)
{
timestamp = (struct TIMESTAMP *)calloc(25,sizeof(struct TIMESTAMP));
}
//Current in historical is the time of the request on that day
JsonObject current = doc["data"][0];
timestamp[0].dayTime = current["dt"]; // 1607292481
if(current["dt"])
{
// Create human readable date and time
long tempTime = current["dt"];
tempTime += location.timezoneOffset;
dateTimeConversion(tempTime,timestamp[0].readableDateTime,USER_PARAM.OPEN_WEATHER_DATEFORMAT+9);
}
timestamp[0].sunrise = current["sunrise"]; // 1607256309
if(current["sunrise"])
{
// Create human readable date and time
long tempTime = current["sunrise"];
tempTime += location.timezoneOffset;
dateTimeConversion(tempTime,timestamp[0].readableSunrise,USER_PARAM.OPEN_WEATHER_DATEFORMAT+4);
}
timestamp[0].sunset = current["sunset"]; // 1607290280
if(current["sunset"])
{
// Create human readable date and time
long tempTime = current["sunset"];
tempTime += location.timezoneOffset;
dateTimeConversion(tempTime,timestamp[0].readableSunset,USER_PARAM.OPEN_WEATHER_DATEFORMAT+4);
}
timestamp[0].temperature = current["temp"]; // 35.82
timestamp[0].apparentTemperature = current["feels_like"]; // 21.7
timestamp[0].pressure = current["pressure"]; // 1010
timestamp[0].humidity = current["humidity"]; // 51
timestamp[0].dewPoint = current["dew_point"]; // 20.88
timestamp[0].uvIndex = current["uvi"]; // 1.54
timestamp[0].cloudCover = current["clouds"]; // 1
timestamp[0].visibility = current["visibility"]; // 16093
timestamp[0].windSpeed = current["wind_speed"]; // 16.11
timestamp[0].windBearing = current["wind_deg"]; // 300
timestamp[0].windGust = current["wind_gust"]; // 24.16
// New rain and snow =======================
if(current["rain"])
{
if(USER_PARAM.OPEN_WEATHER_UNITS == 2)
{
float temp = current["rain"]["1h"];
timestamp[0].rainVolume = (temp/25.4); // 95
}
else
timestamp[0].rainVolume = current["rain"]["1h"]; // 95
}
else
timestamp[0].rainVolume = 0;
if(current["snow"])
{
if(USER_PARAM.OPEN_WEATHER_UNITS == 2)
{
float temp = current["snow"]["1h"];
timestamp[0].snowVolume = (temp/25.4); // 95
}
else
timestamp[0].snowVolume = current["snow"]["1h"]; // 95
}
else
timestamp[0].snowVolume = 0;
JsonObject current_weather_0 = current["weather"][0];
timestamp[0].id = current_weather_0["id"]; // 800
timestamp[0].main = (char *)realloc(timestamp[0].main,sizeof(char) * strlen(current_weather_0["main"])+1);
strncpy(timestamp[0].main,current_weather_0["main"],strlen(current_weather_0["main"])+1);
timestamp[0].summary = (char *)realloc(timestamp[0].summary,sizeof(char) * strlen(current_weather_0["description"])+1);
strncpy(timestamp[0].summary,current_weather_0["description"],strlen(current_weather_0["description"])+1);
strncpy(timestamp[0].icon,current_weather_0["icon"],strlen(current_weather_0["icon"])+1);
dateTimeConversion(timestamp[0].dayTime,timestamp[0].weekDayName,9);
http.end();
return 0;
}
int OpenWeatherOneCall::createCurrent(int sizeCap)
{
char getURL[200] = {0};
int alertz = 0;
sprintf(getURL,"%s?lat=%.6f&lon=%.6f&lang=%s%s&units=%s%s%s",DS_URL1,USER_PARAM.OPEN_WEATHER_LATITUDE,USER_PARAM.OPEN_WEATHER_LONGITUDE,USER_PARAM.OPEN_WEATHER_LANGUAGE,DS_URL2,units,DS_URL3,USER_PARAM.OPEN_WEATHER_DKEY);
// printf("\n%s\n",getURL);
HTTPClient http;
http.begin(getURL);
int httpCode = http.GET();
if (httpCode > 399)
{
if(httpCode == 401)
{
http.end();
return 22;
}
http.end();
return 21;
}
const size_t capacity = sizeCap;
JsonDocument doc;
deserializeJson(doc, http.getString());
strncpy(location.timezone,doc["timezone"],50);
location.timezoneOffset = doc["timezone_offset"];
if(exclude.current)
{
OpenWeatherOneCall::freeCurrentMem();
}
else
{
if(!current)
{
current = (struct nowData *)calloc(1,sizeof(struct nowData));
if(current == NULL)
{
return 23;
}
}
JsonObject currently = doc["current"];
current->dayTime = currently["dt"]; // 1586781931
if(currently["dt"])
{
// Create human readable date and time
long tempTime = currently["dt"];
tempTime += location.timezoneOffset;
dateTimeConversion(tempTime,current->readableDateTime,USER_PARAM.OPEN_WEATHER_DATEFORMAT);
dateTimeConversion(tempTime,current->readableWeekdayName,9);
}
current->sunriseTime = currently["sunrise"]; // 1612267442
if(currently["sunrise"])
{
// Create human readable date and time
long tempTime = currently["sunrise"];
tempTime += location.timezoneOffset;
dateTimeConversion(tempTime,current->readableSunrise,USER_PARAM.OPEN_WEATHER_DATEFORMAT+4);
}
current->sunsetTime = currently["sunset"]; // 1612304218
if(currently["sunset"])
{
// Create human readable date and time
long tempTime = currently["sunset"];
tempTime += location.timezoneOffset;
dateTimeConversion(tempTime,current->readableSunset,USER_PARAM.OPEN_WEATHER_DATEFORMAT+4);
}
current->temperature = currently["temp"]; // 287.59
current->apparentTemperature = currently["feels_like"]; // 281.42
current->pressure = currently["pressure"]; // 1011
current->humidity = currently["humidity"]; // 93
current->dewPoint = currently["dew_point"]; // 286.47
current->uvIndex = currently["uvi"]; // 6.31
current->cloudCover = currently["clouds"]; // 90
current->visibility = currently["visibility"]; // 8047
current->windSpeed = currently["wind_speed"]; // 10.3
current->windBearing = currently["wind_deg"]; // 170
if(currently["wind_gust"])
{
current->windGust = currently["wind_gust"];
}
if(currently["snow"]["1h"])
{
if(USER_PARAM.OPEN_WEATHER_UNITS == 2)
{
float temp = currently["snow"]["1h"];
current->snowVolume = (temp/25.4); // 95
}
else
current->snowVolume = currently["snow"]["1h"]; // 95
}
else
current->snowVolume = 0;
if(currently["rain"]["1h"])
{
if(USER_PARAM.OPEN_WEATHER_UNITS == 2)
{
float temp = currently["rain"]["1h"];
current->rainVolume = (temp/25.4); // 95
}
else
current->rainVolume = currently["rain"]["1h"]; // 95
}
else
current->rainVolume = 0;
current->id = currently["weather"][0]["id"];
current->main = (char *)realloc(current->main,sizeof(char) * strlen(currently["weather"][0]["main"])+1);
if(current->main == NULL)
{
return 23;
}
strncpy(current->main,currently["weather"][0]["main"],strlen(currently["weather"][0]["main"])+1);
current->summary = (char *)realloc(current->summary,sizeof(char) * strlen(currently["weather"][0]["description"])+1);
if(current->summary == NULL)
{
return 23;
}
strncpy(current->summary,currently["weather"][0]["description"],strlen(currently["weather"][0]["description"])+1);
strncpy(current->icon,currently["weather"][0]["icon"],strlen(currently["weather"][0]["icon"])+1);
}
if(exclude.daily)
{
OpenWeatherOneCall::freeForecastMem();
}
else
{
if(!forecast)
{
forecast = (struct futureData *)calloc(8,sizeof(struct futureData));
if(forecast == NULL)
{
return 23;
}
}
JsonArray daily = doc["daily"];
for (int x = 0; x < 8; x++)
{
forecast[x].dayTime = daily[x]["dt"]; // 1586793600
if(daily[x]["dt"])
{
long tempTime = daily[x]["dt"];
tempTime += location.timezoneOffset;
dateTimeConversion(tempTime,forecast[x].readableDateTime,USER_PARAM.OPEN_WEATHER_DATEFORMAT+9);
}
forecast[x].sunriseTime = daily[x]["sunrise"]; // 1586773262
if(daily[x]["sunrise"])
{
long tempTime = daily[x]["sunrise"];
tempTime += location.timezoneOffset;
dateTimeConversion(tempTime,forecast[x].readableSunrise,USER_PARAM.OPEN_WEATHER_DATEFORMAT+4);
}
forecast[x].sunsetTime = daily[x]["sunset"]; // 1586820773
if(daily[x]["sunset"])
{
long tempTime = daily[x]["sunset"];
tempTime += location.timezoneOffset;
dateTimeConversion(tempTime,forecast[x].readableSunset,USER_PARAM.OPEN_WEATHER_DATEFORMAT+4);
}
forecast[x].temperatureDay = daily[x]["temp"]["day"]; // 288.74
forecast[x].temperatureLow = daily[x]["temp"]["min"]; // 286.56
forecast[x].temperatureHigh = daily[x]["temp"]["max"]; // 293.23
forecast[x].temperatureNight = daily[x]["temp"]["night"]; // 286.56
forecast[x].temperatureEve = daily[x]["temp"]["eve"]; // 293.23
forecast[x].temperatureMorn = daily[x]["temp"]["morn"]; // 286.56
forecast[x].apparentTemperatureHigh = daily[x]["feels_like"]["day"]; // 280.11
forecast[x].apparentTemperatureLow = daily[x]["feels_like"]["night"]; // 280.29
forecast[x].apparentTemperatureEve = daily[x]["feels_like"]["eve"]; // 280.11
forecast[x].apparentTemperatureMorn = daily[x]["feels_like"]["morn"]; // 280.29
forecast[x].pressure = daily[x]["pressure"]; // 1006
forecast[x].humidity = daily[x]["humidity"]; // 91
forecast[x].dewPoint = daily[x]["dew_point"]; // 287.28
forecast[x].windSpeed = daily[x]["wind_speed"]; // 14.2
if(daily[x]["wind_gust"])
{
forecast[x].windGust = daily[x]["wind_gust"];
}
forecast[x].windBearing = daily[x]["wind_deg"]; // 180
forecast[x].id = daily[x]["weather"][0]["id"]; // 800
if(daily[x]["weather"][0]["main"])
{
forecast[x].main = (char *)realloc(forecast[x].main,sizeof(char) * strlen(daily[x]["weather"][0]["main"])+1);
if(forecast[x].main == NULL)
{
return 23;
}
strncpy(forecast[x].main,daily[x]["weather"][0]["main"],strlen(daily[x]["weather"][0]["main"])+1);
}
if(daily[x]["weather"][0]["description"])
{
forecast[x].summary = (char *)realloc(forecast[x].summary,sizeof(char) * strlen(daily[x]["weather"][0]["description"])+1);
if(forecast[x].summary == NULL)
{
return 23;
}
strncpy(forecast[x].summary,daily[x]["weather"][0]["description"],strlen(daily[x]["weather"][0]["description"])+1);
}
strncpy(forecast[x].icon,daily[x]["weather"][0]["icon"],strlen(daily[x]["weather"][0]["icon"])+1);
forecast[x].cloudCover = daily[x]["clouds"]; // 95
forecast[x].pop = daily[x]["pop"]; // 95
if(daily[x]["rain"])
{
if(USER_PARAM.OPEN_WEATHER_UNITS == 2)
{
float temp = daily[x]["rain"];
forecast[x].rainVolume = (temp/25.4); // 95
}
else
forecast[x].rainVolume = daily[x]["rain"]; // 95
}
else
forecast[x].rainVolume = 0; // 95
if(daily[x]["snow"])
{
if(USER_PARAM.OPEN_WEATHER_UNITS == 2)
{
float temp = daily[x]["snow"];
forecast[x].snowVolume = (temp/25.4); // 95
}
else
forecast[x].snowVolume = daily[x]["snow"]; // 95
}
else
forecast[x].snowVolume = 0;
forecast[x].uvIndex = daily[x]["uvi"]; // 6.31
dateTimeConversion(forecast[x].dayTime,forecast[x].weekDayName,9);
}
}
if(exclude.alerts)
{
OpenWeatherOneCall::freeAlertMem();
}
else
{
if(doc["alerts"][0])
{
//count alerts here
for(int z = 0; z < 10; z++)
{
if(doc["alerts"][z])
{
MAX_NUM_ALERTS = z+1;
}
}
if(!alert);
{
alert = (struct ALERTS *)calloc(MAX_NUM_ALERTS,sizeof(struct ALERTS));
if(alert == NULL)
{
return 23;
}
}
//Start for loop of maximum alerts here
for(int x = 0; x < MAX_NUM_ALERTS; x++)
{
JsonObject ALERTS_0 = doc["alerts"][x];
if(ALERTS_0["sender_name"])
{
alert[x].senderName = (char *)realloc(alert[x].senderName,sizeof(char) * strlen(ALERTS_0["sender_name"])+1);
if(alert[x].senderName == NULL)
{
return 23;
}
strncpy(alert[x].senderName,ALERTS_0["sender_name"],strlen(ALERTS_0["sender_name"])+1);
}
if(ALERTS_0["event"])
{
alert[x].event = (char *)realloc(alert[x].event,sizeof(char) * strlen(ALERTS_0["event"])+1);
if(alert[x].event == NULL)
{
return 23;
}
strncpy(alert[x].event,ALERTS_0["event"],strlen(ALERTS_0["event"])+1);
}
if(ALERTS_0["start"])
{
long tempTime = ALERTS_0["start"];
alert[x].alertStart = tempTime;
tempTime += location.timezoneOffset;
dateTimeConversion(tempTime,alert[x].startInfo,USER_PARAM.OPEN_WEATHER_DATEFORMAT);
}
if(ALERTS_0["end"])
{
long tempTime = ALERTS_0["end"];
alert[x].alertEnd = tempTime;
tempTime += location.timezoneOffset;
dateTimeConversion(tempTime,alert[x].endInfo,USER_PARAM.OPEN_WEATHER_DATEFORMAT);
}
if(ALERTS_0["description"])
{
alert[x].summary = (char *)realloc(alert[x].summary,sizeof(char) * strlen(ALERTS_0["description"])+1);
if(alert[x].summary == NULL)
{
return 23;
}
strncpy(alert[x].summary,ALERTS_0["description"],strlen(ALERTS_0["description"])+1);
}
} //end for
}
else
{
// If alerts are not excluded but there are none, reset NUM_MAX_ALERTS and MEMORY
MAX_NUM_ALERTS = 0;
OpenWeatherOneCall::freeAlertMem();
}
}
if(exclude.hourly)
{
OpenWeatherOneCall::freeHourMem();
}
else
{
if(doc["hourly"])
{
if(!hour)
{
hour = (struct HOURLY *)calloc(48, sizeof(struct HOURLY));
if(hour == NULL)
{
return 23;
}
}
JsonArray hourly = doc["hourly"];
for(int h = 0; h < 48; h++)
{
JsonObject hourly_0 = hourly[h];
//hour[h].dayTime = hourly_0["dt"]; // 1604336400
if(hourly_0["dt"])
{
long tempTime = hourly_0["dt"];
hour[h].dayTime = tempTime;
//tempTime += location.timezoneOffset;
dateTimeConversion(tempTime,hour[h].readableTime,6);
}
hour[h].temperature = hourly_0["temp"]; // 46.58
hour[h].apparentTemperature = hourly_0["feels_like"]; // 28.54
hour[h].pressure = hourly_0["pressure"]; // 1015
hour[h].humidity = hourly_0["humidity"]; // 31
hour[h].dewPoint = hourly_0["dew_point"]; // 19.2
hour[h].cloudCover = hourly_0["clouds"]; // 20
hour[h].visibility = hourly_0["visibility"]; // 10000
hour[h].windSpeed = hourly_0["wind_speed"]; // 22.77
hour[h].windBearing = hourly_0["wind_deg"]; // 300
if(hourly_0["snow"])
{
if(USER_PARAM.OPEN_WEATHER_UNITS == 2)
{
float temp = hourly_0["snow"];
hour[h].snowVolume = (temp/25.4); // 95
}
else
hour[h].snowVolume = hourly_0["snow"]; // 95
}
else
hour[h].snowVolume = 0;
if(hourly_0["rain"])
{
if(USER_PARAM.OPEN_WEATHER_UNITS == 2)
{
float temp = hourly_0["rain"];
hour[h].rainVolume = (temp/25.4); // 95
}
else
hour[h].rainVolume = hourly_0["rain"]; // 95
}
else
hour[h].rainVolume = 0;
JsonObject hourly_0_weather_0 = hourly_0["weather"][0];
hour[h].id = hourly_0_weather_0["id"]; // 801
if(hourly_0_weather_0["main"])
{
hour[h].main = (char *)realloc(hour[h].main,sizeof(char) * strlen(hourly_0_weather_0["main"])+1);
if(hour[h].main == NULL)
{
return 23;
}
strncpy(hour[h].main,hourly_0_weather_0["main"],strlen(hourly_0_weather_0["main"])+1);
}
if(hourly_0_weather_0["description"])
{
hour[h].summary = (char *)realloc(hour[h].summary,sizeof(char) * strlen(hourly_0_weather_0["description"])+1);
if(hour[h].summary == NULL)
{
return 23;
}
strncpy(hour[h].summary,hourly_0_weather_0["description"],strlen(hourly_0_weather_0["description"])+1);
}
strncpy(hour[h].icon,hourly_0_weather_0["icon"],strlen(hourly_0_weather_0["icon"])+1);
hour[h].pop = hourly_0["pop"]; // 0
}
}
}
if(exclude.minutely)
{
OpenWeatherOneCall::freeMinuteMem();
}
else
{
if(doc["minutely"])
{
if(!minute)
{
minute = (struct MINUTELY *)calloc(61, sizeof(struct MINUTELY));
if(minute == NULL)
{
return 23;
}
}
JsonArray minutely = doc["minutely"];
for(int x = 0; x<61; x++)
{
minute[x].dayTime = minutely[x]["dt"];
long tempTime = minutely[x]["dt"];
//tempTime += -3600;
dateTimeConversion(tempTime,minute[x].readableTime,USER_PARAM.OPEN_WEATHER_DATEFORMAT+4);
minute[x].precipitation = minutely[x]["precipitation"]; // 0
}
}
}
http.end();
return 0;
}
int OpenWeatherOneCall::createOverview()
{
// NTP Server
const char* ntpServer = "pool.ntp.org";
const long gmtOffset_sec = myTimeZone * 3600;
const int daylightOffset_sec = 3600;
char timeString[11];
int maxRetries = 10;
// Initialize NTP
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
// Get current time
struct tm timeinfo;
int retries = 0;
while (!getLocalTime(&timeinfo) && retries < maxRetries)
{
Serial.println("Failed to obtain time, retrying...");
delay(2000); // Wait 2 seconds before retrying
retries++;
}
if (retries == maxRetries)
{
Serial.println("Failed to obtain time after maximum retries");
return false;
}
Serial.println("Time obtained successfully");
if(strcmp(overviewDate,"TODAY")==0)
{
strftime(timeString, sizeof(timeString), "%Y-%m-%d", &timeinfo);
}
else if(strcmp(overviewDate,"TOMORROW")==0)
{
// Add 1 to the day
timeinfo.tm_mday += 1;
// Normalize the time structure (this handles overflow of days, months, etc.)
mktime(&timeinfo);
strftime(timeString, sizeof(timeString), "%Y-%m-%d", &timeinfo);
}
char overviewURL[200] = {0};
sprintf(overviewURL,"%s?lat=%.6f&lon=%.6f%s%s&units=%s%s%s",OV_URL1,USER_PARAM.OPEN_WEATHER_LATITUDE,USER_PARAM.OPEN_WEATHER_LONGITUDE,OV_URL2,timeString,OV_units,DS_URL3,USER_PARAM.OPEN_WEATHER_DKEY);
//printf("\n%s\n",overviewURL);
HTTPClient http;
http.begin(overviewURL);
int httpCode = http.GET();
if (httpCode > 399)
{
if(httpCode == 401)
{
http.end();
return 22;
}
else
{
http.end();
return 21;
}
}
if(!overView)
{
overView = (struct OVERVIEW *)calloc(1,sizeof(struct OVERVIEW));
if(overView == NULL)
{
return 23;
}
}
// String input;
JsonDocument doc;
DeserializationError error = deserializeJson(doc, http.getString());
if (error)
{
Serial.print("deserializeJson() failed: ");
Serial.println(error.c_str());
return 22;
}
double lat = doc["lat"]; // 39.953701
double lon = doc["lon"]; // -74.197899
const char* tz = doc["tz"]; // "-04:00"
const char* date = doc["date"]; // "2024-08-06"
const char* units = doc["units"]; // "imperial"
const char* weather_overview = doc["weather_overview"]; // "The current weather in our area is overcast ..
overView->lat = doc["lat"]; // 39.953701
overView->lon = doc["lon"]; // -74.197899
overView->tz = strdup(doc["tz"]); // "-04:00"
overView->date = strdup(doc["date"]); // "2024-08-06"
overView->units = strdup(doc["units"]); // "imperial"
overView->weather_overview = strdup(doc["weather_overview"]);
http.end();
return 0;
}
void OpenWeatherOneCall::allocateAndCopy(char** destination, const char* source)
{
*destination = (char*)malloc(strlen(source) + 1); // Allocate memory
if (*destination != NULL)
{
strcpy(*destination, source); // Copy the string
}
}
int OpenWeatherOneCall::setLatLon(float _LAT, float _LON)
{
int error_code = 0;
if(abs(_LAT) <= 90)
{
USER_PARAM.OPEN_WEATHER_LATITUDE = _LAT;
location.LATITUDE = _LAT; //User copy
}
else
error_code += 1;
if(abs(_LON) <= 180)
{
USER_PARAM.OPEN_WEATHER_LONGITUDE = _LON;
location.LONGITUDE = _LON; //User copy
}
else
error_code += 2;
if(error_code)
return error_code;
return (EXIT_SUCCESS);
}
int OpenWeatherOneCall::setLatLon(int _CITY_ID)
{
int error_code = 0;
char cityURL[110];
char* URL1 = "http://api.openweathermap.org/data/3.0/weather?id=";
char* URL2 = "&appid=";
sprintf(cityURL,"%s%d%s%s",URL1,_CITY_ID,URL2,USER_PARAM.OPEN_WEATHER_DKEY);
error_code = OpenWeatherOneCall::parseCityCoordinates(cityURL);
if(error_code)
return error_code;
return (EXIT_SUCCESS);
}
int OpenWeatherOneCall::setLatLon(void)
{
// IP address of NON-CELLULAR WiFi. Hotspots won't work properly.
int error_code = 0;
error_code = OpenWeatherOneCall::getIPLocation();
if(error_code)
{
return error_code;
}
error_code = OpenWeatherOneCall::getIPAPILocation(_ipapiURL);
if(error_code)
{
return error_code;
}
return 0;
}
int OpenWeatherOneCall::parseCityCoordinates(char* CTY_URL)
{
int error_code = 0;
HTTPClient http;
http.begin(CTY_URL);
int httpCode = http.GET();
if(httpCode > 399)