-
Notifications
You must be signed in to change notification settings - Fork 6
/
55_DWD_OpenData.pm
3150 lines (2447 loc) · 116 KB
/
55_DWD_OpenData.pm
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
# -----------------------------------------------------------------------------
# $Id: 55_DWD_OpenData.pm 23797 2021-02-21 19:49:57Z jensb $
# -----------------------------------------------------------------------------
=encoding UTF-8
=head1 NAME
DWD_OpenData - A FHEM Perl module to retrieve forecasts and alerts from the
DWD Open Data Server.
=head1 LICENSE AND COPYRIGHT
Copyright (C) 2018 Jens B.
Use of HttpUtils instead of LWP::Simple:
Copyright (C) 2018 JoWiemann
see https://forum.fhem.de/index.php/topic,83097.msg761015.html#msg761015
Sun position:
Copyright (c) Plataforma Solar de Almerýa, Spain
see http://www.psa.es/sdg/sunpos.htm
Sunrise and sunset:
see https://www.aa.quae.nl/en/reken/zonpositie.html
see https://en.wikipedia.org/wiki/Sunrise_equation
Julian date conversion:
Copyright (C) 2012 E. G. Richards
see Explanatory Supplement to the Astronomical Almanac, 3rd edition, S.E Urban and P.K. Seidelmann eds., chapter 15.11.3, Interconverting Dates and Julian Day Numbers, Algorithm 4
This script is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This script is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this script; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
A copy of the GNU General Public License, Version 2 can also be found at
http://www.gnu.org/licenses/old-licenses/gpl-2.0.
This copyright notice MUST APPEAR in all copies of the script!
=cut
package AstroSun;
use strict;
use warnings;
use Math::Trig qw(pi pi2 asin acos tan);
use POSIX 'floor';
use Time::Local 'timegm';
use Time::Piece 'gmtime';
require Exporter;
our $VERSION = '1.000003';
our @ISA = qw(Exporter);
our @EXPORT = qw(AzimuthElevation RiseSet);
our @EXPORT_OK = qw(EpochToJulianDate JulianDateToEpoch);
=head2 EpochToJulianDate(;$)
=over
=item * param time: epoch time [s], optional, default: now
=item * return Julian date
=back
=cut
sub EpochToJulianDate {
my ($epoch) = @_;
if (!defined($epoch)) {
$epoch = time();
}
return gmtime($epoch)->julian_day;
}
=head2 EpochToGreenwichMeanSideralDate(;$)
Copyright (c) Plataforma Solar de Almerýa, Spain
simplified algorithm, accurate to within 0.5 minutes of arc for the year 1999-2015
=over
=item * param time: epoch time [s], optional, default: now
=item * return Greenwich mean sideral date [h]
=back
=cut
sub EpochToGreenwichMeanSideralDate {
my ($epoch) = @_;
if (!defined($epoch)) {
$epoch = time();
}
my $elapsedDays = EpochToJulianDate($epoch) - 2451545 + 0.0008;
my ($seconds, $minutes, $hours, $day, $month, $year, $wday, $yday, $isdst) = gmtime($epoch);
my $timeAsHours = $hours + $minutes/60.0 + $seconds/3600.0;
return 6.6974243242 + 0.0657098283*$elapsedDays + $timeAsHours;
}
=head2 JulianDateToEpoch(;$)
Copyright (C) 2012 E. G. Richards
=over
=item * param jd: Julian date [day], optional, default: now
=item * return Gregorian date [epoch]
=back
=cut
sub JulianDateToEpoch {
my ($jd) = @_;
if (!defined($jd)) {
return time();
} else {
my $j = floor($jd);
my $f = $j + 1401;
$f += 3*floor(floor((4*$jd + 274277.0)/146097)/4) - 38;
my $e = 4*$f + 3;
my $g = floor(($e%1461)/4);
my $h = 5*$g + 2;
my $day = floor(($h%153)/5) + 1;
my $month = (floor($h/153) + 2)%12 + 1;
my $year = floor($e/1461) - 4716 + floor((14 - $month)/12);
my $seconds = sprintf("%0.0f", 86400*($jd - $j + 0.5)); # round()
return timegm(0, 0, 0, $day, $month - 1, $year - 1900) + $seconds;
}
}
=head2 CelestialPosition($)
Copyright (c) Plataforma Solar de Almerýa, Spain
simplified algorithm, accurate to within 0.5 minutes of arc for the year 1999-2015
=over
=item * param epoch: epoch time [s], optional, default: now
=item * return array of rightAscension and declination [rad]
=back
=cut
sub CelestialPosition {
my ($epoch) = @_;
# Calculate ecliptic coordinates (ecliptic longitude and obliquity of the
# ecliptic in radians but without limiting the angle to 2*pi
# (i.e., the result may be greater than 2*pi)
my $elapsedDays = EpochToJulianDate($epoch) - 2451545 + (32.184 + 37)/86400; # 2019: 37 leap seconds
my $omega = 2.1429 - 0.0010394594 * $elapsedDays; # [rad]
my $meanLongitude = 4.8950630 + 0.017202791698 * $elapsedDays; # [rad]
my $meanAnomaly = 6.2400600 + 0.0172019699 * $elapsedDays; # [rad]
my $eclipticLongitude = $meanLongitude + 0.03341607*sin($meanAnomaly) + 0.00034894*sin(2*$meanAnomaly) - 0.0001134 - 0.0000203*sin($omega);
my $eclipticObliquity = 0.4090928 - 6.2140e-9*$elapsedDays + 0.0000396*cos($omega);
# Calculate celestial coordinates (right ascension and declination) in radians
# but without limiting the angle to 2*pi (i.e., the result may be
# greater than 2*pi)
my $sinEclipticLongitude = sin($eclipticLongitude);
my $y1 = cos($eclipticObliquity)*$sinEclipticLongitude;
my $x1 = cos($eclipticLongitude);
my $rightAscension = atan2($y1, $x1);
if ($rightAscension < 0.0) {
$rightAscension = $rightAscension + pi2;
}
my $declination = asin(sin($eclipticObliquity)*$sinEclipticLongitude);
return ($rightAscension, $declination);
}
=head2 AzimuthElevation(;$$$)
Calculate the azimuth and elevation of the sun for the given time and location.
Copyright (c) Plataforma Solar de Almerýa, Spain
simplified algorithm, accurate to within 0.5 minutes of arc for the year 1999-2015
=over
=item * param epoch: epoch time [s], optional, default: now
=item * param longitude: geographic longitude [deg], optional, default: global longitude or Frankfurt, Germany
=item * param latitude: geographic latitude [deg], optional, default: global latitude or Frankfurt, Germany
=item * return array of azimuth and elevation [deg]
=back
=cut
sub AzimuthElevation {
my ($epoch, $longitudeEast, $latitudeNorth) = @_;
if (!defined($longitudeEast) || !defined($latitudeNorth)) {
# undefined: use Frankfurt, Germany
$longitudeEast = ::AttrVal("global", "longitude", "8.686");
$latitudeNorth = ::AttrVal("global", "latitude", "50.112");
}
my ($rightAscensionRadians, $declinationRadians) = CelestialPosition($epoch);
# Calculate local coordinates (azimuth [deg] and zenith angle [rad])
my $rad = pi/180;
my $greenwichMeanSiderealDate = EpochToGreenwichMeanSideralDate($epoch);
my $localMeanSiderealDateRadians = ($greenwichMeanSiderealDate*15 + $longitudeEast)*$rad;
my $hourAngleRadians = $localMeanSiderealDateRadians - $rightAscensionRadians;
my $cosHourAngle = cos($hourAngleRadians);
my $latitudeRadians = $latitudeNorth*$rad;
my $cosLatitude = cos($latitudeRadians);
my $sinLatitude = sin($latitudeRadians);
my $zenithAngleRadians = acos($cosLatitude*$cosHourAngle*cos($declinationRadians) + sin($declinationRadians)*$sinLatitude);
my $y = -sin($hourAngleRadians);
my $x = tan($declinationRadians)*$cosLatitude - $sinLatitude*$cosHourAngle;
my $azimuthRadians = atan2($y, $x);
if ($azimuthRadians < 0.0) {
$azimuthRadians = $azimuthRadians + pi2;
}
my $azimuth = sprintf("%0.1f", $azimuthRadians/$rad); # round(1)
# Parallax correction of zenith angle [deg]
my $meanEarthRadius = 6371.01; # [km]
my $astronomicalUnit = 149597890; # [km]
my $parallax = ($meanEarthRadius/$astronomicalUnit)*sin($zenithAngleRadians);
my $zenithAngle = ($zenithAngleRadians + $parallax)/$rad;
# Elevation [deg]
my $elevation = 90 - $zenithAngle;
$elevation = sprintf("%0.1f", $elevation); # round(1)
return ($azimuth, $elevation);
}
=head2 Mod($$)
Calculate the arithmetic remainder of a division including fractions.
=cut
sub Mod {
my ($dividend, $divisor) = @_;
return 0 if ($divisor == 0);
return $dividend - int($dividend/$divisor)*$divisor;
}
=head2 MeanSolarAnomaly($)
Calculate mean solar anomaly for Julian date.
see https://www.aa.quae.nl/en/reken/zonpositie.html
=over
=item * param jd: Julian date
=item * return mean solar anomaly [deg]
=back
=cut
sub MeanSolarAnomaly {
my ($jd) = @_;
return Mod(357.5291 + 0.98560028*($jd - 2451545), 360);
}
=head2 EclipticalLongitude($)
Calculate ecliptical longitude of the sun.
see https://www.aa.quae.nl/en/reken/zonpositie.html
=over
=item * param meanSolarAnomalyRadians: mean solar anomaly [rad]
=item * return ecliptical longitude [rad]
=back
=cut
sub EclipticalLongitude {
my ($meanSolarAnomalyRadians) = @_;
my $rad = pi/180;
my $equationOfcenter = 1.9148*sin($meanSolarAnomalyRadians) + 0.0200*sin(2*$meanSolarAnomalyRadians) + 0.0003*sin(3*$meanSolarAnomalyRadians);
return Mod($meanSolarAnomalyRadians/$rad + $equationOfcenter + 180 + 102.9372, 360)*$rad;
}
=head2 EquatorialCoordinates($)
Calculate equatorial coordinates of the sun.
see https://www.aa.quae.nl/en/reken/zonpositie.html
=over
=item * param eclipticLongitudeRadians: ecliptic longitude of the sun [rad]
=item * return right ascension and declination [rad]
=back
=cut
sub EquatorialCoordinates {
my ($eclipticLongitudeRadians) = @_;
my $rad = pi/180;
my $rightAscensionRadians = atan2(sin($eclipticLongitudeRadians)*cos(23.4393*$rad), cos($eclipticLongitudeRadians));
my $declinationRadians = asin(sin($eclipticLongitudeRadians)*sin(23.4393*$rad));
return ($rightAscensionRadians, $declinationRadians);
}
=head2 HourAngle($$$)
Calculate sun hour angle for Julian date.
see https://www.aa.quae.nl/en/reken/zonpositie.html
=over
=item * param jd: Julian date
=item * param rightAscension: right ascension of sun [deg]
=item * param longitudeEast: geographical longitude [deg]
=item * return hour angle of sun [deg], limited to -180 ... +180
=back
=cut
sub HourAngle {
my ($jd, $rightAscension, $longitudeEast) = @_;
my $sideralTime = Mod(280.1470 + 360.9856235*($jd - 2451545) + $longitudeEast, 360);
my $hourAngle = $sideralTime - $rightAscension;
$hourAngle -= 360 if ($hourAngle > 180);
$hourAngle += 360 if ($hourAngle < -180);
return $hourAngle;
}
=head2 Transit($$$)
Calculate solar transit date for Julian date.
see https://en.wikipedia.org/wiki/Sunrise_equation
=over
=item * param jd: Julian date
=item * param meanSolarAnomalyRadians: mean solar anomaly [rad]
=item * param eclipticalLongitudeRadians: ecliptical longitude of sun [rad]
=item * return date of solar transit [Julian date]
=back
=cut
sub Transit {
my ($jd, $meanSolarAnomalyRadians, $eclipticalLongitudeRadians) = @_;
return $jd + 0.0053*sin($meanSolarAnomalyRadians) - 0.0069*sin(2*$eclipticalLongitudeRadians);
}
=head2 ElevationCorrection(;$)
Calculate upper solar limb elevation offset angle caused by sun diameter, typical atmospheric refraction and altitude of observer for sunrise.
see https://en.wikipedia.org/wiki/Sunrise_equation
=over
=item * param altitude: altitude of observer [m], optional, default: 0 m
=item * return elevation offset angle of upper solar limb at sunrise [deg]
=back
=cut
sub ElevationCorrection {
my ($altitude) = @_;
if (!defined($altitude)) {
# undefined: use 0 m (see level)
$altitude = 0;
}
return -0.83 - 2.076*sqrt($altitude)/60
}
=head2 HourAngleOptimization($$$;$$$)
Iteratively improve sun rise (mode = -1), sun transit (mode = 0) and sun set (mode = +1) dates by minimizing hour angle change.
see https://en.wikipedia.org/wiki/Sunrise_equation
=over
=item * param mode: sun rise (mode = -1), sun transit (mode = 0) and sun set (mode = +1)
=item * param jd: estimated Julian date
=item * param longitudeEast: geographical longitude [deg]
=item * param latitudeNorth: geographical latitude [deg], optional, not used for mode = 0
=item * param altitude: altitude of observer [m], optional, not used for mode = 0
=item * param twilightAngle: twilight angle [deg], optional, not used for mode = 0
=item * return array of optimized Julian date and the declination of the sun [rad]
=back
=cut
sub HourAngleOptimization {
my ($mode, $jd, $longitudeEast, $latitudeNorth, $altitude, $twilightAngle) = @_;
# iteratively improve sun rise date
my $rad = pi/180;
my $loops = 0;
my $rightAscensionRadians;
my $declinationRadians;
my $hourAngleDelta;
do {
# hour angle
my $meanSolarAnomalyRadians = MeanSolarAnomaly($jd)*$rad;
my $eclipticalLongitudeRadians = EclipticalLongitude($meanSolarAnomalyRadians);
($rightAscensionRadians, $declinationRadians) = EquatorialCoordinates($eclipticalLongitudeRadians);
my $hourAngle = HourAngle($jd, $rightAscensionRadians/$rad, $longitudeEast);
if ($mode) {
# sun rise/set hour angle
my $hourAngleRiseSet = acos((sin((ElevationCorrection($altitude) + $twilightAngle)*$rad) - sin($latitudeNorth*$rad)*sin($declinationRadians))/(cos($latitudeNorth*$rad)*cos($declinationRadians)))/$rad;
# improved sun rise/set date
$hourAngleDelta = $hourAngle - $mode*$hourAngleRiseSet;
$jd -= $hourAngleDelta/360;
#::Log3 "", 3, "HourAngleOptimization meanSolarAnomaly ". $meanSolarAnomalyRadians/$rad . " eclipticalLongitude " . $eclipticalLongitudeRadians/$rad . " rightAscensionRadians " . $rightAscensionRadians/$rad . " declinationRadians " . $declinationRadians/$rad . " jd $jd hourAngle $hourAngle hourAngleRiseSet $hourAngleRiseSet hourAngleDelta $hourAngleDelta" . JulianDateToEpoch($jd);
} else {
# improved solar transit date
$hourAngleDelta = $hourAngle;
$jd -= $hourAngleDelta/360;
#::Log3 "", 3, "HourAngleOptimization meanSolarAnomaly ". $meanSolarAnomalyRadians/$rad . " eclipticalLongitude " . $eclipticalLongitudeRadians/$rad . " rightAscensionRadians " . $rightAscensionRadians/$rad . " declinationRadians " . $declinationRadians/$rad . " jd $jd hourAngle $hourAngle " . JulianDateToEpoch($jd);
}
$loops++;
} while (abs($hourAngleDelta) > 0.0005 && $loops < 5);
return ($jd, $declinationRadians);
}
=head2 RiseSet(;$$$$$)
Calculate time of sunrise, sun transit and sunset for given time and position including corrections for astronomical refraction, solar disc diameter and altitude of observer.
see https://www.aa.quae.nl/en/reken/zonpositie.html
see https://en.wikipedia.org/wiki/Sunrise_equation
Note: The calculated times belong to the day in the GMT timezone. If your location is in a different timezone you must add your timezone offset to the epoch time to get the same result for all times between 0:00 and 23:59 of your local time.
Adjust epoch time by time zone offset
=over
=item * param epoch: epoch time [s], optional, default: now
=item * param longitudeEast: geographic longitude [deg], optional, default: global longitude or Frankfurt, Germany
=item * param latitude: geographic latitude [deg], optional, default: global latitude or Frankfurt, Germany
=item * param altitude: altitude of obeserver [m], optional, default: 0 m
=item * param twilightAngle: twilight angle [deg], optional, default: 0 °
=item * return array of sunrise, sun transit and sunset date for a day in the GMT timezone [epoch]
=back
=cut
sub RiseSet {
my ($epoch, $longitudeEast, $latitudeNorth, $altitude, $twilightAngle) = @_;
if (!defined($epoch)) {
$epoch = time();
}
if (!defined($longitudeEast) || !defined($latitudeNorth)) {
# undefined: use Frankfurt, Germany
$longitudeEast = ::AttrVal("global", "longitude", "8.686");
$latitudeNorth = ::AttrVal("global", "latitude", "50.112");
}
#$longitudeEast = 5;
#$latitudeNorth = 52;
if (!defined($altitude)) {
# undefined: use 0 m (see level)
$altitude = 0;
}
#$altitude = 0;
if (!defined($twilightAngle)) {
# undefined: use 0°
$twilightAngle = 0;
}
#$twilightAngle = 0;
# initial estimate of solar transit date
my $julianDateOffset = 2451545 + (32.184 + 37)/86400 - $longitudeEast/360; # 2019: 37 leap seconds
my $julianCycle = floor(EpochToJulianDate($epoch) - $julianDateOffset + 0.5);
#$julianCycle = floor(2453097 - $julianDateOffset + 0.5);
my $solarTransitJD = $julianCycle + $julianDateOffset;
# improve estimate of solar transit date
my $rad = pi/180;
my $meanSolarAnomalyRadians = MeanSolarAnomaly($solarTransitJD)*$rad;
my $eclipticalLongitudeRadians = EclipticalLongitude($meanSolarAnomalyRadians);
$solarTransitJD = Transit($solarTransitJD, $meanSolarAnomalyRadians, $eclipticalLongitudeRadians);
# iteratively improve solar transit date at given longitude
($solarTransitJD, my $declinationRadians) = HourAngleOptimization(0, $solarTransitJD, $longitudeEast);
# initial estimate of sun rise/set hour angle at given latitude and altitude
my $hourAngleRiseSet = acos((sin((ElevationCorrection($altitude) + $twilightAngle)*$rad) - sin($latitudeNorth*$rad)*sin($declinationRadians))/(cos($latitudeNorth*$rad)*cos($declinationRadians)))/$rad;
my $hourAngleRiseSetRatio = $hourAngleRiseSet/360;
# initial estimate of sun rise and sun set date
my $sunRiseJD = $solarTransitJD - $hourAngleRiseSetRatio;
my $sunSetJD = $solarTransitJD + $hourAngleRiseSetRatio;
# iteratively improve sun rise and sun set date
($sunRiseJD) = HourAngleOptimization(-1, $sunRiseJD, $longitudeEast, $latitudeNorth, $altitude, $twilightAngle);
($sunSetJD) = HourAngleOptimization(+1, $sunSetJD, $longitudeEast, $latitudeNorth, $altitude, $twilightAngle);
#::Log3 "", 3, "RiseSet: sunRiseJD $sunRiseJD solarTransitJD $solarTransitJD sunSetJD $sunSetJD";
return (JulianDateToEpoch($sunRiseJD), JulianDateToEpoch($solarTransitJD), JulianDateToEpoch($sunSetJD));
}
# -----------------------------------------------------------------------------
package DWD_OpenData;
use strict;
use warnings;
use Encode 'encode';
use File::Temp 'tempfile';
use IO::Uncompress::Unzip qw(unzip $UnzipError);
use POSIX qw(floor strftime);
use Scalar::Util 'looks_like_number';
use Storable qw(freeze thaw);
use Time::HiRes qw(gettimeofday usleep);
use Time::Local qw(timelocal timegm);
use Time::Piece qw(localtime gmtime);
use Blocking;
use HttpUtils;
use feature qw(switch);
no if $] >= 5.017011, warnings => 'experimental::smartmatch';
use constant UPDATE_DISTRICTS => -1;
use constant UPDATE_COMMUNEUNIONS => -2;
use constant UPDATE_ALL => -3;
require Exporter;
our $VERSION = '1.016003';
our @ISA = qw(Exporter);
our @EXPORT = qw(GetForecast GetAlerts UpdateAlerts UPDATE_DISTRICTS UPDATE_COMMUNEUNIONS UPDATE_ALL);
our @EXPORT_OK = qw(IsCommuneUnionWarncellId);
my %forecastPropertyAliases = ( 'TX' => 'Tx', 'TN' => 'Tn', 'TG' => 'Tg', 'TM' => 'Tm' );
my %forecastPropertyPeriods = (
'DD' => 1, 'DRR1' => 1, 'E_DD' => 1, 'E_FF' => 1, 'E_PPP' => 1, 'E_Td' => 1, 'E_TTT' => 1, 'FF' => 1, 'FX1' => 1, 'FX3' => 1, 'FX625' => 1, 'FX640' => 1, 'FX655' => 1, 'FXh' => 1, 'FXh25' => 1, 'FXh40' => 1, 'FXh55' => 1, 'N' => 1, 'N05' => 1, 'Neff' => 1, 'Nh' => 1, 'Nl' => 1, 'Nlm' => 1, 'Nm' => 1, 'PPPP' => 1, 'R101' => 1, 'R102' => 1, 'R103' => 1, 'R105' => 1, 'R107' => 1, 'R110' => 1, 'R120' => 1, 'R130' => 1, 'R150' => 1, 'R600' => 1, 'R602' => 1, 'R610' => 1, 'R650' => 1, 'RR1c' => 1, 'RR1o1' => 1, 'RR1u1' => 1, 'RR1w1' => 1, 'RR3c' => 1, 'RR6c' => 1, 'RRL1c' => 1, 'RRS1c' => 1, 'RRS3c' => 1, 'RRad1' => 1, 'Rad1h' => 1, 'RRhc' => 1, 'Rh00' => 1, 'Rh02' => 1, 'Rh10' => 1, 'Rh50' => 1, 'SunAz' => 1, 'SunD1' => 1, 'SunD3' => 1, 'SunEl' => 1, 'SunUp' => 1, 'T5cm' => 1, 'Td' => 1, 'TTT' => 1, 'VV' => 1, 'VV10' => 1, 'W1W2' => 1, 'WPc11' => 1, 'WPc31' => 1, 'WPc61' => 1, 'WPcd1' => 1, 'WPch1' => 1, 'ww' => 1, 'ww3' => 1, 'wwC' => 1, 'wwC6' => 1, 'wwCh' => 1, 'wwD' => 1, 'wwD6' => 1, 'wwDh' => 1, 'wwF' => 1, 'wwF6' => 1, 'wwFh' => 1, 'wwL' => 1, 'wwL6' => 1, 'wwLh' => 1, 'wwM' => 1, 'wwM6' => 1, 'wwMd' => 1, 'wwMh' => 1, 'wwP' => 1, 'wwP6' => 1, 'wwPd' => 1, 'wwPh' => 1, 'wwS' => 1, 'wwS6' => 1, 'wwSh' => 1, 'wwT' => 1, 'wwT6' => 1, 'wwTd' => 1, 'wwTh' => 1, 'wwZ' => 1, 'wwZ6' => 1, 'wwZh' => 1,
'PEvap' => 24, 'PSd00' => 24, 'PSd30' => 24, 'PSd60' => 24, 'RRdc' => 24, 'RSunD' => 24, 'Rd00' => 24, 'Rd02' => 24, 'Rd10' => 24, 'Rd50' => 24, 'SunD' => 24, 'SunRise' => 24, 'SunSet' => 24, 'Tg' => 24, 'Tm' => 24, 'Tn' => 24, 'Tx' => 24
);
my %forecastDefaultProperties = (
'Tg' => 1, 'Tn' => 1, 'Tx' => 1, 'DD' => 1, 'FX1' => 1, 'Neff' => 1, 'RR6c' => 1, 'R600' => 1, 'RRhc' => 1, 'Rh00' => 1, 'TTT' => 1, 'ww' => 1, 'SunUp' => 1
);
# conversion of DWD value to: 1 = temperature in K, 2 = integer value, 3 = wind speed in m/s, 4 = pressure in Pa
my %forecastPropertyTypes = (
'Tx' => 1, 'Tn' => 1, 'Tg' => 1, 'Tm'=> 1, 'Td' => 1, 'T5cm' => 1, 'TTT' => 1,
'DD' => 2, 'Neff' => 2, 'Nh' => 2, 'Nl' => 2, 'Nlm' => 2, 'Nm' => 2, 'Rh00' => 2, 'ww' => 2, 'ww3' => 2, 'WPc11' => 2, 'WPc31' => 2, 'WPc61' => 2, 'WPch1' => 2, 'WPcd1' => 2,
'FF' => 3, 'FX1' => 3, 'FX3' => 3, 'FXh' => 3,
'PPPP' => 4
);
my @wwdText = ('Bewölkungsentwicklung nicht beobachtet',
'Bewölkung abnehmend',
'Bewölkung unverändert',
'Bewölkung zunehmend',
# 4 Dunst, Rauch, Staub oder Sand
'Sicht durch Rauch oder Asche vermindert',
'trockener Dunst (relative Feuchte < 80 %)',
'verbreiteter Schwebstaub, nicht vom Wind herangeführt',
'Staub oder Sand bzw. Gischt, vom Wind herangeführt',
'gut entwickelte Staub- oder Sandwirbel',
'Staub- oder Sandsturm im Gesichtskreis, aber nicht an der Station',
# 10 Trockenereignisse
'feuchter Dunst (relative Feuchte > 80 %)',
'Schwaden von Bodennebel',
'durchgehender Bodennebel',
'Wetterleuchten sichtbar, kein Donner gehört',
'Niederschlag im Gesichtskreis, nicht den Boden erreichend',
'Niederschlag in der Ferne (> 5 km), aber nicht an der Station',
'Niederschlag in der Nähe (< 5 km), aber nicht an der Station',
'Gewitter (Donner hörbar), aber kein Niederschlag an der Station',
'Markante Böen im Gesichtskreis, aber kein Niederschlag an der Station',
'Tromben (trichterförmige Wolkenschläuche) im Gesichtskreis',
# 20 Ereignisse der letzten Stunde, aber nicht zur Beobachtungszeit
'nach Sprühregen oder Schneegriesel',
'nach Regen',
'nach Schneefall',
'nach Schneeregen oder Eiskörnern',
'nach gefrierendem Regen',
'nach Regenschauer',
'nach Schneeschauer',
'nach Graupel- oder Hagelschauer',
'nach Nebel',
'nach Gewitter',
# 30 Staubsturm, Sandsturm, Schneefegen oder -treiben
'leichter oder mäßiger Sandsturm, an Intensität abnehmend',
'leichter oder mäßiger Sandsturm, unveränderte Intensität',
'leichter oder mäßiger Sandsturm, an Intensität zunehmend',
'schwerer Sandsturm, an Intensität abnehmend',
'schwerer Sandsturm, unveränderte Intensität',
'schwerer Sandsturm, an Intensität zunehmend',
'leichtes oder mäßiges Schneefegen, unter Augenhöhe',
'starkes Schneefegen, unter Augenhöhe',
'leichtes oder mäßiges Schneetreiben, über Augenhöhe',
'starkes Schneetreiben, über Augenhöhe',
# 40 Nebel oder Eisnebel
'Nebel in einiger Entfernung',
'Nebel in Schwaden oder Bänken',
'Nebel, Himmel erkennbar, dünner werdend',
'Nebel, Himmel nicht erkennbar, dünner werdend',
'Nebel, Himmel erkennbar, unverändert',
'Nebel, Himmel nicht erkennbar, unverändert',
'Nebel, Himmel erkennbar, dichter werdend',
'Nebel, Himmel nicht erkennbar, dichter werdend',
'Nebel mit Reifansatz, Himmel erkennbar',
'Nebel mit Reifansatz, Himmel nicht erkennbar',
# 50 Sprühregen
'unterbrochener leichter Sprühregen',
'durchgehend leichter Sprühregen',
'unterbrochener mäßiger Sprühregen',
'durchgehend mäßiger Sprühregen',
'unterbrochener starker Sprühregen',
'durchgehend starker Sprühregen',
'leichter gefrierender Sprühregen',
'mäßiger oder starker gefrierender Sprühregen',
'leichter Sprühregen mit Regen',
'mäßiger oder starker Sprühregen mit Regen',
# 60 Regen
'unterbrochener leichter Regen oder einzelne Regentropfen',
'durchgehend leichter Regen',
'unterbrochener mäßiger Regen',
'durchgehend mäßiger Regen',
'unterbrochener starker Regen',
'durchgehend starker Regen',
'leichter gefrierender Regen',
'mäßiger oder starker gefrierender Regen',
'leichter Schneeregen',
'mäßiger oder starker Schneeregen',
# 70 Schnee
'unterbrochener leichter Schneefall oder einzelne Schneeflocken',
'durchgehend leichter Schneefall',
'unterbrochener mäßiger Schneefall',
'durchgehend mäßiger Schneefall',
'unterbrochener starker Schneefall',
'durchgehend starker Schneefall',
'Eisnadeln (Polarschnee)',
'Schneegriesel',
'Schneekristalle',
'Eiskörner (gefrorene Regentropfen)',
# 80 Schauer
'leichter Regenschauer',
'mäßiger oder starker Regenschauer',
'äußerst heftiger Regenschauer',
'leichter Schneeregenschauer',
'mäßiger oder starker Schneeregenschauer',
'leichter Schneeschauer',
'mäßiger oder starker Schneeschauer',
'leichter Graupelschauer',
'mäßiger oder starker Graupelschauer',
'leichter Hagelschauer',
'mäßiger oder starker Hagelschauer',
# 90 Gewitter
'Gewitter in der letzten Stunde, zurzeit leichter Regen',
'Gewitter in der letzten Stunde, zurzeit mäßiger oder starker Regen',
'Gewitter in der letzten Stunde, zurzeit leichter Schneefall/Schneeregen/Graupel/Hagel',
'Gewitter in der letzten Stunde, zurzeit mäßiger oder starker Schneefall/Schneeregen/Graupel/Hagel',
'leichtes oder mäßiges Gewitter mit Regen oder Schnee',
'leichtes oder mäßiges Gewitter mit Graupel oder Hagel',
'starkes Gewitter mit Regen oder Schnee',
'starkes Gewitter mit Sandsturm',
'starkes Gewitter mit Graupel oder Hagel');
my @alertsData = [ undef, undef ];
my @alertsReceived = [ undef, undef ];
my @alertsUpdating = [ undef, undef ];
my @alertsErrorMessage = [ undef, undef ];
=head1 FHEM CALLBACK FUNCTIONS
=head2 Define($$)
FHEM I<DefFn>
=over
=item * param hash: hash of DWD_OpenData device
=item * param def: module define parameters, will be ignored
=item * return undef on success or error message
=back
=cut
sub Define {
my ($hash, $def) = @_;
my $name = $hash->{NAME};
# module version
$hash->{VERSION} = $VERSION;
# test TZ environment variable
if (!defined($ENV{"TZ"})) {
$hash->{FHEM_TZ} = undef;
} else {
$hash->{FHEM_TZ} = $ENV{"TZ"};
}
# cache timezone attribute
$hash->{'.TZ'} = ::AttrVal($hash, 'timezone', $hash->{FHEM_TZ});
::readingsSingleUpdate($hash, 'state', ::IsDisabled($name)? 'disabled' : 'defined', 1);
::InternalTimer(gettimeofday() + 3, 'DWD_OpenData::Timer', $hash, 0);
return undef;
}
=head2 Undef($$)
FHEM I<UndefFn>
=over
=item * param hash: hash of DWD_OpenData device
=item * param arg: module undefine arguments, will be ignored
=back
=cut
sub Undef {
my ($hash, $arg) = @_;
Shutdown($hash);
return undef;
}
=head2 Shutdown($)
FHEM I<ShutdownFn>
=over
=item * param hash: hash of DWD_OpenData device
=back
=cut
sub Shutdown {
my ($hash) = @_;
my $name = $hash->{NAME};
::RemoveInternalTimer($hash);
if (defined($hash->{".alertsBlockingCall"})) {
::BlockingKill($hash->{".alertsBlockingCall"});
}
my $warncellId = $hash->{".warncellId"};
if (defined($warncellId)) {
my $communeUnion = IsCommuneUnionWarncellId($warncellId);
if (defined($hash->{".alertsFile".$communeUnion})) {
close($hash->{".alertsFileHandle".$communeUnion});
unlink($hash->{".alertsFile".$communeUnion});
delete($hash->{".alertsFile".$communeUnion});
}
}
if (defined($hash->{".forecastBlockingCall"})) {
::BlockingKill($hash->{".forecastBlockingCall"});
}
if (defined($hash->{".forecastFile"})) {
close($hash->{".forecastFileHandle"});
unlink($hash->{".forecastFile"});
delete($hash->{".forecastFile"});
}
return undef;
}
=head2 Attr(@)
FHEM I<AttrFn>
=over
=item * param command: "set" or "del"
=item * param name: name of DWD_OpenData device
=item * param attribute: attribute name
=item * param value: attribute value
=item * return C<undef> on success or error message
=back
=cut
sub Attr {
my ($command, $name, $attribute, $value) = @_;
my $hash = $::defs{$name};
for ($command) {
when ("set") {
for ($attribute) {
when ("disable") {
# enable/disable polling
if ($::init_done) {
if ($value) {
::RemoveInternalTimer($hash);
::readingsSingleUpdate($hash, 'state', 'disabled', 1);
} else {
::readingsSingleUpdate($hash, 'state', 'defined', 1);
::InternalTimer(gettimeofday() + 3, 'DWD_OpenData::Timer', $hash, 0);
}
}
}
when ("forecastResolution") {
if (defined($value) && looks_like_number($value) && $value > 0) {
my $oldForecastResolution = ::AttrVal($name, 'forecastResolution', 6);
if ($::init_done && defined($oldForecastResolution) && $oldForecastResolution != $value) {
::CommandDeleteReading(undef, "$name ^fc.*");
}
} else {
return "invalid value for forecastResolution (possible values are 1, 3 and 6)";
}
}
when ("forecastStation") {
my $oldForecastStation = ::AttrVal($name, 'forecastStation', undef);
if ($::init_done && defined($oldForecastStation) && $oldForecastStation ne $value) {
::CommandDeleteReading(undef, "$name ^fc.*");
}
}
when ("forecastWW2Text") {
if ($::init_done && !$value) {
::CommandDeleteReading(undef, "$name ^fc.*wwd\$");
}
}
when ("timezone") {
if (defined($value) && length($value) > 0) {
$hash->{'.TZ'} = $value;
} else {
return "timezone (e.g. Europe/Berlin) required";
}
}
}
}
when ("del") {
for ($attribute) {
when ("disable") {
::readingsSingleUpdate($hash, 'state', 'defined', 1);
::InternalTimer(gettimeofday() + 3, 'DWD_OpenData::Timer', $hash, 0);
}
when ("forecastResolution") {
my $oldForecastResolution = ::AttrVal($name, 'forecastResolution', 6);
if ($oldForecastResolution != 6) {
::CommandDeleteReading(undef, "$name ^fc.*");
}
}
when ("forecastStation") {
::CommandDeleteReading(undef, "$name ^fc.*");
}
when ("forecastWW2Text") {
::CommandDeleteReading(undef, "$name ^fc.*wwd\$");
}
when ("timezone") {
$hash->{'.TZ'} = $hash->{FHEM_TZ};
}
}
}
}
return undef;
}
=head2 Get($@)
FHEM I<GetFn>
=over
=item * param hash: hash of DWD_OpenData device
=item * param a: array of FHEM command line arguments, min. length 2, a[1] holds get command
=item * return requested data or error message
=back
=cut
sub Get {
my ($hash, @a) = @_;
my $name = $hash->{NAME};
my $result = undef;
my $command = lc($a[1]);
for ($command) {
when ("alerts") {
my $warncellId = $a[2];
$warncellId = ::AttrVal($name, 'alertArea', undef) if (!defined($warncellId));
if (defined($warncellId)) {
my $communeUnion = IsCommuneUnionWarncellId($warncellId);
if (defined($alertsUpdating[$communeUnion]) && (time() - $alertsUpdating[$communeUnion] < 60)) {
# abort if update is in progress
$result = "alerts cache update in progress, please wait and try again";
} elsif (defined($alertsReceived[$communeUnion]) && (time() - $alertsReceived[$communeUnion] < 900)) {
# use cache if not older than 15 minutes
$result = UpdateAlerts($hash, $warncellId);
} else {
# update cache if older than 15 minutes