/
api.php
1746 lines (1640 loc) · 69.8 KB
/
api.php
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
<?php
############################################################################
#
# Meteotemplate
# http://www.meteotemplate.com
# Free website template for weather enthusiasts
# Author: Jachym
# Brno, Czech Republic
# First release: 2015
#
############################################################################
#
# v2.0 2017-04-20 Now also handle data of update programs
# v2.1 2017-04-24 Handling of fallen rain between 23:55 and 00:00:00
# v2.2 2017-07-02 Added Extra sensors; fixed bug rain at begin of day
# v3.0 2017-08-11 Added multipliers
# v3.1 2017-12-20 Discard outdated parameters; added mysql error logging
#
############################################################################
//error_reporting(E_ALL);
$apiLog = array();
$rawInput = array();
$utc = time();
$timeId = "Time";
if(isset($apiUpdate)){
############################################################################
// api included by CUMULUS, WU, CUSTOM, NETATMO, WLIP
############################################################################
$rawUpdate['SW'] = $apiUpdate;
$apiLog['info'][] = "Handling data from ".$apiUpdate;
// load data
foreach ($rawUpdate as $key => $value) {
$rawInput[$key] = $value;
if($key == 'U'){
$apiLog['info'][] = "update 'U' = ".$rawInput['U']." (".date("Y-m-d H:i:s",$rawInput['U']).")";
}
else{
$apiLog['info'][] = "update '".$key."' = ".$rawInput[$key];
}
}
}
else{
############################################################################
// api section called by http
############################################################################
$base = "";
// load main info
require($base."config.php");
// load dependencies
require($base."scripts/functions.php");
// check acces authorization
if(isset($_GET['PASS'])){
$password = $_GET['PASS'];
}
else if(isset($_GET['PASSWORD'])){
$password = $_GET['PASSWORD'];
}
else{
die("No password provided");
}
// check if password is correct
if($password!=$updatePassword){
if($password==$adminPassword){ // if admin password provided accept, but notify
echo "Authorized via admin password";
}
else{
die("Unauthorized");
}
}
$apiLog['info'][] = "Authorized access.";
$apiLog['info'][] = "Current date/time: ".date("Y-m-d H:i:s");
$apiLog['info'][] = "api called by http";
// read raw input
if(isset($_GET)){
foreach($_GET as $urlParameter=>$value){
if($urlParameter!="PASSWORD" && $urlParameter!="PASS"){
$rawInput[$urlParameter] = $value;
$apiLog['info'][] = "update ".$urlParameter.": ".$value;
}
}
}
else{
// no data in api
$apiLog['error'][] = "api: no data";
generateAPILog();
die("api: no data");
}
############################################################################
// end of api section
############################################################################
}
############################################################################
// common part for both:
// apiUpdate section called by /update/update.php
// api section called by http
############################################################################
$apiLog['info'][] = "Begin of common part of api script";
############################################################################
# HANDLING LIVE DATA
############################################################################
$apiLog['info'][] = "Start handling live data";
// Preset time of live update
foreach ($rawInput as $key => $value) {
$rawInput[$key.$timeId] = $utc;
}
// multipliers
if($multiplierT != 0 && isset($rawInput['T'])){
$rawInput["T"] = $rawInput["T"] + $multiplierT;
}
if($multiplierP != 0 && isset($rawInput['P'])){
$rawInput["P"] = $rawInput["P"] + $multiplierP;
}
if($multiplierW != 1 && isset($rawInput['W'])){
$rawInput["W"] = $rawInput["W"] * $multiplierW;
}
if($multiplierR != 1 && isset($rawInput['R'])){
$rawInput["R"] = $rawInput["R"] * $multiplierR;
}
if($multiplierW != 1 && isset($rawInput['G'])){
$rawInput["G"] = $rawInput["G"] * $multiplierW;
}
if($multiplierR != 1 && isset($rawInput['RR'])){
$rawInput["RR"] = $rawInput["RR"] * $multiplierR;
}
// Check if extra sensors should be loaded
$apiLog['info'][] = "Checking if extra sensors should be logged";
$extraSensors = array();
if(file_exists($base."update/apiSettings.txt")){
$extraAPIRaw = json_decode(file_get_contents($base."update/apiSettings.txt"),true);
foreach($extraAPIRaw as $extraParam=>$extraValue){
if($extraValue==1){
$extraSensors[] = $extraParam;
}
}
}
else{
$apiLog['info'][] = "Extra sensor settings file not found.";
}
$apiLog['info'][] = "Extra sensors data to save in db: " . implode(", ",$extraSensors);
// read previous live data
if(file_exists($base."meteotemplateLive.txt")){
// get latest date from cache file
$mtLive = file_get_contents($base."meteotemplateLive.txt");
$liveInput = json_decode($mtLive,true);
if(array_key_exists("R".$timeId,$liveInput)){ // check if rain is from yesterday, if so, delete it
$dayRain = date("Ymd",$liveInput['R'.$timeId]);
$dayNow = date("Ymd");
if($dayRain!=$dayNow){
unset($liveInput['R']);
unset($liveInput['RTime']);
}
}
foreach ($liveInput as $key => $value) {
$pos = strpos($key,$timeId);
if ($pos > 0) {
// time parameter
if($utc-$value > 600) {
// value more than 10 minutes ago; skip writing back
$apiLog['info'][] = "Variable too old, remove from meteotemplateLive.txt: ".$key.": ".date("Y-m-d H:i:s",$value);
$keyValue = substr($key,0,$pos);
// remove value and timestamp from array
unset($liveInput[$keyValue]); // remove value
unset($liveInput[$key]); // remove timestamp
}
}
else {
// value parameter
$liveInput[$key] = $value;
}
}
}
// convert UGP to P when needed
if(isset($rawInput['UGP']) && !isset($rawInput['P'])){
$apiLog['info'][] = "convert UGP: ".$rawInput['UGP'];
// get station elevation from config
// $stationElevation
// $stationElevationUnits - m/ft
// define constants for SLP calculations
// convert elevation to m if in ft
if($stationElevationUnits=="ft"){
$elevationM = $stationElevation * 0.3048;
}
else{
$elevationM = $stationElevation;
}
$apiLog['info'][] = "elevationM: ".$elevationM;
$apiLog['info'][] = "liveInput['T']: ".$liveInput['T'];
if(isset($liveInput['T'])){ // temperature is available, use more accurate formula
$temperatureK = $liveInput['T'] + 273.15; // temperature in K
$constant['g'] = 9.80665; // Earth-surface gravitational constant [m/s2]
$constant['M'] = 0.0289644; // molar mass of dry air [kg/mol]
$constant['R'] = 8.31447; // universal gas constant
$partA = ($constant['g'] * $constant['M'] * $elevationM) / ($constant['R'] * $temperatureK);
$convertedP = $rawInput['UGP'] / exp(- $partA);
$apiLog['info'][] = "more accurate convertedP: ".$convertedP;
}
else{ // temperature is N/A use less accurate formula
$convertedP = $rawInput['UGP'] - ($elevationM/9.2);
$apiLog['info'][] = "less accurate convertedP: ".$convertedP;
}
$rawInput['P'] = (string)(round($convertedP,3));
$rawInput['P'.$timeId] = $utc;
$apiLog['info'][] = "calculated P: ".$rawInput['P'];
// multiplier for converted UGP to P
if($multiplierP != 0 && isset($rawInput['P'])){
$rawInput["P"] = $rawInput["P"] + $multiplierP;
}
}
// add saved live data fields for not updated fields
foreach ($liveInput as $key => $value) {
if(!isset($rawInput[$key])){
// if live data key not present use saved live data
$rawInput[$key] = $value;
// time fields ($rawInput[$key.$timeId]) will be copied too
$apiLog['info'][] = "add live data: ".$key.": ".$value;
}
}
// calculate dewpoint
$rawInput['D'] = (string)dewpoint($rawInput['T'], $rawInput['H']);
$rawInput['D'.$timeId] = $utc;
$apiLog['info'][] = "calculated D: ".$rawInput['D'];
// calculate apparent temp
$rawInput['A'] = (string)apparent($rawInput['T'], $rawInput['H'], $rawInput['W'] / 3.6);
$rawInput['A'.$timeId] = $utc;
$apiLog['info'][] = "calculated A: ".$rawInput['A'];
// save raw input
$rawOutput = json_encode($rawInput,JSON_NUMERIC_CHECK);
$apiLog['info'][] = "Save meteotemplateLive.txt: ".$rawOutput;
file_put_contents($base."meteotemplateLive.txt",$rawOutput);
// check we have write permissions for the cache folder and meteotemplateLive.txt
if(!file_exists($base."meteotemplateLive.txt")){
$apiLog['error'][] = "meteotemplateLive.txt was not created! Probably incorrect permissions for the template root folder.";
echo "Live conditions file not created. Check permissions!";
}
############################################################################
# PARSING
############################################################################
$apiLog['info'][] = "Start data parsing";
$convertUgp = false;
// save live data fields to raw data
foreach ($rawInput as $key => $value) {
$rawData[$key] = $value;
}
// ESSENTIAL
// Date and time
$apiLog['info'][] = "Parsing date; Server time: ".date("Y-m-d H:i:s");
$valid['date'] = true;
if(!isset($rawData['U'])){
$valid['date'] = false;
$apiLog['error'][] = "No value for date specified.";
}
else{
// date must be passed as UNIX timestamp
// checking: date must be numeric, must be after 1990 and must not be in the future
$apiLog['info'][] = "Validating date: ".$rawData['U']." (".date("Y-m-d H:i:s",$rawData['U']).")";
if(is_numeric($rawData['U'])){
if($rawData['U']>631152000 && $rawData['U']<(time()+10*60)){ // 10 minutes tolerance
$data['timestamp'] = ($rawData['U']); // also save the timestamp
$data['date'] = date("Y-m-d H:i:s",$rawData['U']); // convert to MySQL accepted format
$apiLog['info'][] = "Date is valid; difference with server time is ".($rawData['U'] - $utc)." s" ;
}
else{
$valid['date'] = false;
$apiLog['error'][] = "Date is invalid; difference with server time is ".($rawData['U'] - $utc)." s";
}
}
else{
$valid['date'] = false;
$apiLog['error'][] = "Date is invalid (not numeric)";
}
}
############################################################################
// Parameters
############################################################################
############################################################################
// Outside Temperature
$apiLog['info'][] = "Parsing temperature";
$valid['T'] = true;
if(!isset($rawData['T'])){
$valid['T'] = false;
$apiLog['error'][] = "No temperature data provided.";
}
else{
$rawT = trim($rawData['T']);
$apiLog['info'][] = "Temperature: ".$rawT." C";
if($rawT===""){
$valid['T'] = false;
$apiLog['error'][] = "Temperature field blank.";
}
elseif(!is_numeric($rawT)){
$valid['T'] = false;
$apiLog['error'][] = "Temperature is not a number.";
}
}
// apply conversion - API uses Celsius
if($valid['T']){
$apiLog['info'][] = "Database units: ".$dataTempUnits;
if($dataTempUnits!="C"){
$rawT = convertor($rawT, "C", $dataTempUnits);
$apiLog['info'][] = "Temperature converted to: ".$rawT." ".$dataTempUnits;
}
// check limits
$apiLog['info'][] = "Checking temperature is between limits specified in template Main settings.";
$apiLog['info'][] = "Minimum temperature limit: ".$limitTempMin." ".$dataTempUnits;
$apiLog['info'][] = "Maximum temperature limit: ".$limitTempMax." ".$dataTempUnits;
if($rawT>=$limitTempMin && $rawT<=$limitTempMax){
$apiLog['info'][] = "Temperature is OK and within the allowed limits";
$data['T'] = $rawT;
}
else{
$apiLog['error'][] = "Temperature is outside the allowed limits.";
$valid['T'] = false;
}
}
############################################################################
// Outside Max Temperature
$apiLog['info'][] = "Parsing maximum temperature";
$valid['Tmax'] = true;
if(!isset($rawData['TMX'])){
$valid['Tmax'] = false;
$apiLog['error'][] = "No max temperature data provided.";
}
else{
$rawTmax = trim($rawData['TMX']);
$apiLog['info'][] = "Max Temperature: ".$rawTmax." C";
if($rawTmax===""){
$valid['Tmax'] = false;
$apiLog['error'][] = "Max Temperature field blank.";
}
elseif(!is_numeric($rawTmax)){
$valid['Tmax'] = false;
$apiLog['error'][] = "Max Temperature is not a number.";
}
}
// apply conversion - API uses Celsius
if($valid['Tmax']){
$apiLog['info'][] = "Database units: ".$dataTempUnits;
if($dataTempUnits!="C"){
$rawTmax = convertor($rawTmax, "C", $dataTempUnits);
$apiLog['info'][] = "Temperature converted to: ".$rawTmax." ".$dataTempUnits;
}
// check limits
$apiLog['info'][] = "Checking max temperature is between limits specified in template Main settings.";
$apiLog['info'][] = "Minimum temperature limit: ".$limitTempMin." ".$dataTempUnits;
$apiLog['info'][] = "Maximum temperature limit: ".$limitTempMax." ".$dataTempUnits;
if($rawTmax>=$limitTempMin && $rawTmax<=$limitTempMax){
$apiLog['info'][] = "Max Temperature is OK and within the allowed limits";
$data['Tmax'] = $rawTmax;
}
else{
$apiLog['error'][] = "Max Temperature is outside the allowed limits.";
$valid['Tmax'] = false;
}
}
############################################################################
// Outside Min Temperature
$apiLog['info'][] = "Parsing minimum temperature";
$valid['Tmin'] = true;
if(!isset($rawData['TMN'])){
$valid['Tmin'] = false;
$apiLog['error'][] = "No min temperature data provided.";
}
else{
$rawTmin = trim($rawData['TMN']);
$apiLog['info'][] = "Min Temperature: ".$rawTmin." C";
if($rawTmin===""){
$valid['Tmin'] = false;
$apiLog['error'][] = "Min Temperature field blank.";
}
elseif(!is_numeric($rawTmin)){
$valid['Tmin'] = false;
$apiLog['error'][] = "Min Temperature is not a number.";
}
}
// apply conversion - API uses Celsius
if($valid['Tmin']){
$apiLog['info'][] = "Database units: ".$dataTempUnits;
if($dataTempUnits!="C"){
$rawTmin = convertor($rawTmin, "C", $dataTempUnits);
$apiLog['info'][] = "Temperature converted to: ".$rawTmin." ".$dataTempUnits;
}
// check limits
$apiLog['info'][] = "Checking min temperature is between limits specified in template Main settings.";
$apiLog['info'][] = "Minimum temperature limit: ".$limitTempMin." ".$dataTempUnits;
$apiLog['info'][] = "Maximum temperature limit: ".$limitTempMax." ".$dataTempUnits;
if($rawTmin>=$limitTempMin && $rawTmin<=$limitTempMax){
$apiLog['info'][] = "Min Temperature is OK and within the allowed limits";
$data['Tmin'] = $rawTmin;
}
else{
$apiLog['error'][] = "Min Temperature is outside the allowed limits.";
$valid['Tmin'] = false;
}
}
############################################################################
// Humidity
$apiLog['info'][] = "Parsing humidity";
$valid['H'] = true;
if(!isset($rawData['H'])){
$valid['H'] = false;
$apiLog['error'][] = "No humidity data provided.";
}
else{
$rawH = trim($rawData['H']);
$apiLog['info'][] = "Humidity: ".$rawH." percent";
if($rawH===""){
$valid['H'] = false;
$apiLog['error'][] = "Humidity field blank.";
}
elseif(!is_numeric($rawH)){
$valid['H'] = false;
$apiLog['error'][] = "Humidity is not a number.";
}
}
if($valid['H']){
// discard nonsense
if($rawH<0 && $rawH>100){
$valid['H'] = false;
$apiLog['error'][] = "Humidity is outside sensible range (0-100%).";
}
else{
// check limits from main settings
$apiLog['info'][] = "Checking humidity is between limits specified in template Main settings.";
$apiLog['info'][] = "Minimum humidity limit: ".$limitHumidityMin." %";
$apiLog['info'][] = "Maximum humidity limit: ".$limitHumidityMax." %";
if($rawH>=$limitHumidityMin && $rawH<=$limitHumidityMax){
$apiLog['info'][] = "Humidity is OK and within the allowed limits";
$data['H'] = $rawH;
}
else{
$apiLog['error'][] = "Humidity is outside the allowed limits.";
$valid['H'] = false;
}
}
}
############################################################################
// Wind Speed
$apiLog['info'][] = "Parsing wind speed";
$valid['W'] = true;
if(!isset($rawData['W'])){
$valid['W'] = false;
$apiLog['error'][] = "No wind speed data provided.";
}
else{
$rawW = trim($rawData['W']);
$apiLog['info'][] = "Wind speed: ".$rawW." kmh";
if($rawW===""){
$valid['W'] = false;
$apiLog['error'][] = "Wind speed field blank.";
}
elseif(!is_numeric($rawW)){
$valid['W'] = false;
$apiLog['info'][] = "Wind speed is not a number.";
}
}
// apply conversion - API uses km/h
if($valid['W']){
$apiLog['info'][] = "Database wind speed units: ".$dataWindUnits;
if($dataWindUnits!="kmh"){
$rawW = convertor($rawW, "kmh", $dataWindUnits);
$apiLog['info'][] = "Wind speed converted to: ".$rawW." ".$dataWindUnits;
}
// discard nonsense
if($rawW<0){
$valid['W'] = false;
$apiLog['error'][] = "Wind speed cannot be negative.";
}
else{
// check limits
$apiLog['info'][] = "Checking wind speed is between limits specified in template Main settings.";
$apiLog['info'][] = "Minimum wind speed limit: ".$limitWindMin." ".$dataWindUnits;
$apiLog['info'][] = "Maximum wind speed limit: ".$limitWindMax." ".$dataWindUnits;
if($rawW>=$limitWindMin && $rawW<=$limitWindMax){
$apiLog['info'][] = "Wind speed is OK and within the allowed limits";
$data['W'] = $rawW;
}
else{
$apiLog['error'][] = "Wind speed is outside the allowed limits.";
$valid['W'] = false;
}
}
}
############################################################################
// Wind Gust
$apiLog['info'][] = "Parsing wind gust";
$valid['G'] = true;
if(!isset($rawData['G'])){
$valid['G'] = false;
$apiLog['error'][] = "No wind gust data provided.";
}
else{
$rawG = trim($rawData['G']);
$apiLog['info'][] = "Wind gust: ".$rawG." kmh";
if($rawG===""){
$valid['G'] = false;
$apiLog['error'][] = "Wind gust field blank.";
}
elseif(!is_numeric($rawG)){
$valid['G'] = false;
$apiLog['error'][] = "Wind gust is not a number.";
}
}
// apply conversion - API uses km/h
if($valid['G']){
$apiLog['info'][] = "Database wind units: ".$dataWindUnits;
if($dataWindUnits!="kmh"){
$rawG = convertor($rawG, "kmh", $dataWindUnits);
$apiLog['info'][] = "Wind gust converted to: ".$rawG." ".$dataWindUnits;
}
// discard nonsense
if($rawG<0){
$valid['G'] = false;
$apiLog['error'][] = "Wind gust cannot be negative.";
}
else{
// check limits
$apiLog['info'][] = "Checking wind gust is between limits specified in template Main settings.";
$apiLog['info'][] = "Minimum wind gust limit: ".$limitWindMin." ".$dataWindUnits;
$apiLog['info'][] = "Maximum wind gust limit: ".$limitWindMax." ".$dataWindUnits;
if($rawG>=$limitWindMin && $rawG<=$limitWindMax){
$apiLog['info'][] = "Wind gust is OK and within the allowed limits";
$data['G'] = $rawG;
}
else{
$apiLog['error'][] = "Wind gust is outside the allowed limits.";
$valid['G'] = false;
}
}
}
############################################################################
// Wind direction (bearing)
$apiLog['info'][] = "Parsing wind direction";
$valid['B'] = true;
if(!isset($rawData['B'])){
$valid['B'] = false;
$apiLog['error'][] = "No wind direction data provided.";
}
else{
$rawB = trim($rawData['B']);
$apiLog['info'][] = "Wind direction: ".$rawB." degrees";
if($rawB===""){
$valid['B'] = false;
$apiLog['error'][] = "Wind direction field blank.";
}
elseif(!is_numeric($rawB)){
$valid['B'] = false;
$apiLog['error'][] = "Wind direction is not a number.";
}
}
if($valid['B']){
// discard nonsense
if($rawB<0 && $rawB>360){
$valid['B'] = false;
$apiLog['error'][] = "Wind direction is outside sensible range (0-360 degrees).";
}
else{
$apiLog['info'][] = "Wind direction is OK and within the allowed limits";
$data['B'] = $rawB;
}
}
############################################################################
// Precipitation
$apiLog['info'][] = "Parsing daily cumulative precipitation";
$valid['R'] = true;
if(!isset($rawData['R'])){
$valid['R'] = false;
$apiLog['error'][] = "No precipitation data provided.";
}
else{
$rawR = trim($rawData['R']);
$apiLog['info'][] = "Precipitation: ".$rawR." mm";
if($rawR===""){
$valid['R'] = false;
$apiLog['error'][] = "Precipitation field blank.";
}
elseif(!is_numeric($rawR)){
$valid['R'] = false;
$apiLog['error'][] = "Precipitation is not a number.";
}
}
// apply conversion - API uses mm
if($valid['R']){
$apiLog['info'][] = "Database precipitation units: ".$dataRainUnits;
if($dataRainUnits!="mm"){
$rawR = convertor($rawR, "mm", $dataRainUnits);
$apiLog['info'][] = "Precipitation converted to: ".$rawR." ".$dataRainUnits;
}
// discard nonsense
if($rawR<0){
$valid['R'] = false;
$apiLog['error'][] = "Precipitation cannot be negative.";
}
else{
// check limits
$apiLog['info'][] = "Checking precipitation is between limits specified in template Main settings.";
$apiLog['info'][] = "Minimum precipitation limit: ".$limitRainMin." ".$dataRainUnits;
$apiLog['info'][] = "Maximum precipitation limit: ".$limitRainMax." ".$dataRainUnits;
if($rawR>=$limitRainMin && $rawR<=$limitRainMax){
$apiLog['info'][] = "Precipitation is OK and within the allowed limits";
$data['R'] = $rawR;
}
else{
$apiLog['error'][] = "Precipitation is outside the allowed limits.";
$valid['R'] = false;
}
}
}
############################################################################
// Rain rate
$apiLog['info'][] = "Parsing rain rate";
$valid['RR'] = true;
if(!isset($rawData['RR'])){
$valid['RR'] = false;
$apiLog['error'][] = "No rain rate data provided.";
}
else{
$rawRR = trim($rawData['RR']);
$apiLog['info'][] = "Rain rate: ".$rawRR." mm/h";
if($rawRR===""){
$valid['RR'] = false;
$apiLog['error'][] = "Rain rate field blank.";
}
elseif(!is_numeric($rawR)){
$valid['RR'] = false;
$apiLog['error'][] = "Rain rate is not a number.";
}
}
// apply conversion - API uses mm/h
if($valid['RR']){
$apiLog['info'][] = "Database rain units: ".$dataRainUnits."/h";
if($dataRainUnits!="mm"){
$rawRR = convertor($rawRR, "mm", $dataRainUnits);
$apiLog['info'][] = "Rain rate converted to: ".$rawRR." ".$dataRainUnits."/h";
}
// discard nonsense
if($rawRR<0){
$valid['RR'] = false;
$apiLog['error'][] = "Rain rate cannot be negative.";
}
else{
// check limits
$apiLog['info'][] = "Checking rain rate is between limits specified in template Main settings.";
$apiLog['info'][] = "Minimum rain rate limit: ".$limitRainRateMin." ".$dataRainUnits."/h";
$apiLog['info'][] = "Maximum rain rate limit: ".$limitRainRateMax." ".$dataRainUnits."/h";
if($rawRR>=$limitRainRateMin && $rawRR<=$limitRainRateMax){
$apiLog['info'][] = "Rain rate is OK and within the allowed limits";
$data['RR'] = $rawRR;
}
else{
$apiLog['error'][] = "Rain rate is outside the allowed limits.";
$valid['RR'] = false;
}
}
}
############################################################################
// Solar radiation
$valid['S'] = true;
if($solarSensor){
$apiLog['info'][] = "Parsing solar radiation";
if(!isset($rawData['S'])){
$valid['S'] = false;
$apiLog['error'][] = "No solar radiation data provided.";
}
else{
$rawS = trim($rawData['S']);
$apiLog['info'][] = "Solar radiation: ".$rawS." w/m2";
if($rawS===""){
$valid['S'] = false;
$apiLog['error'][] = "Solar radiation field blank.";
}
elseif(!is_numeric($rawS)){
$valid['S'] = false;
$apiLog['error'][] = "Solar radiation is not a number.";
}
}
if($valid['S']){
// discard nonsense
if($rawS<0){
$valid['S'] = false;
$apiLog['error'][] = "Solar radiation cannot be negative.";
}
else{
// check limits from main settings
$apiLog['info'][] = "Checking solar radiation is between limits specified in template Main settings.";
$apiLog['info'][] = "Minimum solar radiation limit: ".$limitSolarMin." W/m2";
$apiLog['info'][] = "Maximum solar radiation limit: ".$limitSolarMax." W/m2";
if($rawS>=$limitSolarMin && $rawS<=$limitSolarMax){
$apiLog['info'][] = "Solar radiation is OK and within the allowed limits";
$data['S'] = $rawS;
}
else{
$apiLog['error'][] = "Solar radiation is outside the allowed limits.";
$valid['S'] = false;
}
}
}
}
else{
$valid['S'] = false;
$apiLog['info'][] = "Solar radiation sensor disabled in Main settings - skipping.";
}
############################################################################
// EXTRA SENSORS
############################################################################
// Now parse extra sensors
if(count($extraSensors)>0){
$extraQueryParams = array();
$extraQueryValues = array();
$apiLog['info'][] = "Now parsing extra sensors.";
foreach($extraSensors as $extraSensor){
if($extraSensor == "TIN"){
$thisSensorName = "indoor temperature";
$thisSensorLimits = array(1,50);
$thisSensorUnits = "deg C";
$thisSensorDecimals = 1;
}
if($extraSensor == "HIN"){
$thisSensorName = "indoor humidity";
$thisSensorLimits = array(0.01,100);
$thisSensorUnits = "%";
$thisSensorDecimals = 1;
}
if($extraSensor == "SN"){
$thisSensorName = "daily snowfall";
$thisSensorLimits = array(0,5000);
$thisSensorUnits = "mm";
$thisSensorDecimals = 0;
}
if($extraSensor == "SD"){
$thisSensorName = "snow depth";
$thisSensorLimits = array(0,10000);
$thisSensorUnits = "mm";
$thisSensorDecimals = 0;
}
if($extraSensor == "NL"){
$thisSensorName = "noise level";
$thisSensorLimits = array(0,200);
$thisSensorUnits = "dB";
$thisSensorDecimals = 1;
}
if($extraSensor == "L"){
$thisSensorName = "lightning";
$thisSensorLimits = array(0,1000);
$thisSensorUnits = "";
$thisSensorDecimals = 0;
}
if($extraSensor == "LD"){
$thisSensorName = "lightning distance";
$thisSensorLimits = array(0,100);
$thisSensorUnits = "";
$thisSensorDecimals = 0;
}
if($extraSensor == "LT"){
$thisSensorName = "lightning time";
$thisSensorLimits = array(0,10000000000);
$thisSensorUnits = "";
$thisSensorDecimals = 0;
}
if($extraSensor == "SS"){
$thisSensorName = "sunshine";
$thisSensorLimits = array(0,24);
$thisSensorUnits = "h";
$thisSensorDecimals = 1;
}
if($extraSensor == "UV"){
$thisSensorName = "UV";
$thisSensorLimits = array(0,20);
$thisSensorUnits = "";
$thisSensorDecimals = 1;
}
//$for($g=1;$g<=4;$g++){
for($g=1;$g<=4;$g++){
if($extraSensor == "T".$g){
$thisSensorName = "extra temperature sensor ".$g;
$thisSensorLimits = array(-60,60);
$thisSensorUnits = "deg C";
$thisSensorDecimals = 1;
}
if($extraSensor == "H".$g){
$thisSensorName = "extra humidity sensor ".$g;
$thisSensorLimits = array(0.01,100);
$thisSensorUnits = "%";
$thisSensorDecimals = 1;
}
if($extraSensor == "TS".$g){
$thisSensorName = "soil temperature sensor ".$g;
$thisSensorLimits = array(-60,80);
$thisSensorUnits = "deg C";
$thisSensorDecimals = 1;
}
if($extraSensor == "SM".$g){
$thisSensorName = "soil moisture sensor ".$g;
$thisSensorLimits = array(0.01,200);
$thisSensorUnits = "";
$thisSensorDecimals = 1;
}
if($extraSensor == "LT".$g){
$thisSensorName = "leaf temperature sensor ".$g;
$thisSensorLimits = array(-60,80);
$thisSensorUnits = "deg C";
$thisSensorDecimals = 1;
}
if($extraSensor == "LW".$g){
$thisSensorName = "leaf wetness sensor ".$g;
$thisSensorLimits = array(0,15);
$thisSensorUnits = "";
$thisSensorDecimals = 1;
}
if($extraSensor == "CO2_".$g){
$thisSensorName = "CO2 sensor ".$g;
$thisSensorLimits = array(300,600);
$thisSensorUnits = "ppm";
$thisSensorDecimals = 0;
}
if($extraSensor == "CO_".$g){
$thisSensorName = "CO sensor ".$g;
$thisSensorLimits = array(0.1,50);
$thisSensorUnits = "ppm";
$thisSensorDecimals = 0;
}
if($extraSensor == "NO2_".$g){
$thisSensorName = "NO2 sensor ".$g;
$thisSensorLimits = array(0,10);
$thisSensorUnits = "ppm";
$thisSensorDecimals = 0;
}
if($extraSensor == "SO2_".$g){
$thisSensorName = "SO2 sensor ".$g;
$thisSensorLimits = array(0,1000);
$thisSensorUnits = "ppb";
$thisSensorDecimals = 0;
}
if($extraSensor == "O3_".$g){
$thisSensorName = "O3 sensor ".$g;
$thisSensorLimits = array(0,100);
$thisSensorUnits = "ppb";
$thisSensorDecimals = 0;
}
if($extraSensor == "PP".$g){
$thisSensorName = "particulate pollution ".$g;
$thisSensorLimits = array(0,1000);
$thisSensorUnits = "ug/m3";
$thisSensorDecimals = 0;
}
}
if(isset($rawData[$extraSensor])){
$thisSensorVal = $rawData[$extraSensor];
$apiLog['info'][] = "Sensor ".$thisSensorName." raw value: " . $thisSensorVal . " " . $thisSensorUnits;
$apiLog['info'][] = "Limits for this sensor: " . $thisSensorLimits[0] ." to " . $thisSensorLimits[1];
if($thisSensorVal >= $thisSensorLimits[0] && $thisSensorValue <= $thisSensorLimits[1] && is_numeric($thisSensorVal)){
$apiLog['info'][] = "Sensor data within acceptable limits.";
$extraQueryParams[] = $extraSensor;
$extraQueryValues[] = number_format($thisSensorVal, $thisSensorDecimals, ".", "");
}
else{
$apiLog['info'][] = "Sensor data outside acceptable limits or value invalid.";
}
}
else{
$apiLog['info'][] = "Sensor: ".$thisSensorName." not found in API file, skipping...";
}
}
}
else{
$apiLog['info'][] = "No extra sensors set to log to extra alldata table.";
}
############################################################################
// Create/load cache file
############################################################################
// first check how old the cache is, if it is older than 30 minutes delete it to prevent averaging current values with very old values when station offline
if(file_exists($base."cache/apiCache.txt")){
// get latest date from cache file
$cacheRaw = file_get_contents($base."cache/apiCache.txt");
$cache = json_decode($cacheRaw,true);
$latestCacheDate = $cache['timestamp'][count($cache['timestamp'])-1];
if (time()-$latestCacheDate > 60 * 30) {
unlink($base."cache/apiCache.txt");
$apiLog['info'][] = "Cache file is over 30 minutes old, deleting it.";
}
}
// cache file exists - i.e. it is valid, load it
if(file_exists($base."cache/apiCache.txt")){
$cacheRaw = file_get_contents($base."cache/apiCache.txt");
$cache = json_decode($cacheRaw,true);
$apiLog['info'][] = "Cached data loaded from cache/apiCache.txt.";
}
// cache file does not exist, create empty file
else{
$cache = array();
$apiLog['info'][] = "No cache file found, create empty file.";
}
############################################################################
// Check for partial data
############################################################################
// Check for partial data in cache when data is not present
$validCachedT = false;
if(!isset($rawData['T'])){
// use cached data instead when present
if(count($cache['T']) > 0) {
$T = $cache['T'][count($cache['T'])-1];
$validCachedT = true;
$apiLog['info'][] = "Use cached Temperature for calculations: ".$T;
}
}
else {
if($valid['T']) {
$T = $data['T'];
}
}
$validCachedH = false;
if(!isset($rawData['H'])){
// use cached data instead when present
if(count($cache['H']) > 0) {
$H = $cache['H'][count($cache['H'])-1];
$validCachedH = true;
$apiLog['info'][] = "Use cached Humidity for calculations: ".$H;
}
}
else {
if($valid['H']) {
$H = $data['H'];
}
}
$validCachedW = false;
if(!isset($rawData['W'])){
// use cached data instead when present
if(count($cache['W']) > 0) {
$W = $cache['W'][count($cache['W'])-1];
$validCachedW = true;
$apiLog['info'][] = "Use cached Wind for calculations: ".$W;
}
}
else {
if($valid['W']) {
$W = $data['W'];
}
}
############################################################################
// Unadjusted gauge pressure
// convert UGP to P when needed
if(isset($rawData['UGP']) && !isset($rawData['P'])){
$convertUgp = true;
$apiLog['info'][] = "convert UGP: ".$rawData['UGP'];
// get station elevation from config
// $stationElevation