blib/lib/Weather/MOSMIX.pm

filter: Statementstmt 22.7% 41 / 180 Branchbran 0.0% 0 / 26 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 52.1% 12 / 23 Podpod 10.0% 1 / 10 totaltotal 22.1% 54 / 244 CC 24 SCAR 29.0
CC
24
Cov
20%
format_forecast_range_concise
42.0
format_forecast_day
42.0
format_forecast_dbh
30.0
CRAP 18.1
« blib/lib/Weather/MOSMIX/Weathercodes.pm ↑ Summary blib/lib/Weather/MOSMIX/Reader.pm »
1 package Weather::MOSMIX;
2 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 3 ▶use Moo 2;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use Filter::signatures;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use feature 'signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 3 ▶no warnings 'experimental::signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 3 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 3 ▶use JSON;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 3 ▶use DBD::SQLite 1.56; # some virtual table bugfixes
Subroutine BEGIN: called CC=1 SCAR=0.0
10 3 ▶use Weather::MOSMIX::Weathercodes 'mosmix_weathercode';
Subroutine BEGIN: called CC=1 SCAR=0.0
11 3 ▶use Storable 'dclone';
Subroutine BEGIN: called CC=1 SCAR=0.0
12 3 ▶use Time::Piece;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 3 ▶use Encode 'encode', 'decode';
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 3 our $VERSION = '0.02';
16  
17 =head1 NAME
18  
19 Weather::MOSMIX - Reader for MOSMIX weather forecast files
20  
21 =head1 SYNOPSIS
22  
23 =cut
24  
25 3 with 'MooX::Role::DBIConnection';
26  
27 3 our $TIMESTAMP = '%Y-%m-%dT%H:%M:%S';
28  
29 has 'json' => (
30 is => 'lazy',
31 default => sub {
32 0 ▶ JSON->new()
Subroutine __ANON__: not called CC=1 SCAR=6.9
33 },
34 3 );
35  
36 # Convert an array into an SQLite virtual table
37 # This should move into its own module/role, maybe
38 0 ▶sub as_dbh( $table_name, $rows, $colnames=[keys %{ $rows->[0]}]) {
Subroutine as_dbh: not called CC=2 SCAR=17.9
Pod undocumented
39 0 my $dbh = DBI->connect('dbi:SQLite:dbname=:memory:',undef,undef,{AutoCommit => 1, RaiseError => 1,PrintError => 0});
40 0 $dbh->sqlite_create_module(perl => "DBD::SQLite::VirtualTable::PerlData");
41  
42 0 $colnames = join ",", @$colnames;
43 0 our $table_000;
44 0 local $table_000 = $rows;
45 0 my $tablevar = __PACKAGE__ . '::table_000';
46 0 my $sql = qq(CREATE VIRTUAL TABLE "$table_name" USING perl($colnames, hashrefs="$tablevar"););
47 0 $dbh->do($sql);
48  
49 0 return $dbh
50 }
51  
52 ▶sub forecast( $self, %options ) {
Subroutine forecast: not called CC=2 SCAR=17.9
Pod undocumented
53 0 my $cos_lat_sq = cos( $options{ latitude } ) ^ 2;
54 my $res =
55 0 $self->dbh->selectall_arrayref(<<'SQL', { Slice => {}}, $options{latitude}, $options{latitude}, $options{longitude},$options{longitude}, $cos_lat_sq);
56 select *,
57 ((l.latitude - ?)*(l.latitude - ?))
58 + ((l.longitude - ?)*(l.longitude - ?)*?) as distance
59 from forecast_location l
60 join forecast f on l.name = f.name
61 order by distance asc, expiry desc
62 limit 1
63 SQL
64 0 for (@$res) {
65 $_->{forecasts} = $self->json->decode($_->{forecasts})
66 0 };
67 0 $res->[0]
68 };
69  
70 ▶sub forecast_dbh( $self, %options ) {
Subroutine forecast_dbh: not called CC=2 SCAR=17.9
Pod undocumented
71 0 my $res = $self->forecast( %options );
72 # Convert from UTC to CET. This happens to work because my machines
73 # are located within CET ...
74 0 my $time = Time::Piece->strptime( $res->{issuetime}, $TIMESTAMP.'Z' );
75 0 $time = $time->_mktime( $time->epoch, 1 );
76 0 $time->tzoffset(2*3600); # at least until October ...
77  
78 #for my $i ($offset..$offset+$count-1) {
79 # my $c = $weathercode->{values}->[ $i ];
80 # if( length $c ) {
81 # my $v = sprintf '%02d', 0+$c;
82 # push @{ $weather }, {
83 # timestamp => $time->new(),
84 # description => mosmix_weathercode($v),
85 # };
86 # $time += 3600;
87  
88 # zip ww and TTT to AoH
89 0 my $hour_ofs;
90 my @rows = map {
91 0 my $ts = $time->new;
92 0 $time += 3600;
93  
94 my $res = +{
95 $res->{forecasts}->[0]->{type} => $res->{forecasts}->[0]->{values}->[$_],
96 $res->{forecasts}->[1]->{type} => $res->{forecasts}->[1]->{values}->[$_],
97 timestamp => $ts->strftime($TIMESTAMP),
98 date => $ts->strftime('%Y-%m-%d'),
99 hour => $ts->strftime('%H'),
100 hour_ofs => $hour_ofs++,
101 weekday => $ts->strftime('%a'),
102 description => $res->{description},
103 issuetime => $res->{issuetime}
104 0 };
105 0 my $descr = mosmix_weathercode($res->{ww}, 'emoji');
106 0 $res->{emoji} = encode('UTF-8', $descr);
107 0 ▶ length $res->{TTT} ? $res : ()
Branch: 1 branch
BranchTrueFalseTotal
length $res->{'TTT'} ? : 0 0 0
108 0 } 0..$#{$res->{forecasts}->[0]->{values}};
109 0 return as_dbh( 'forecast', \@rows )
110 }
111  
112 sub format_forecast_range_concise {
113 0 ▶ my( $ts, $temp, $weathercode, $offset, $count ) = @_;
Subroutine format_forecast_range_concise: not called CC=6 SCAR=37.4
Pod undocumented
114  
115 0 my ($min, $max) = (1000,0);
116 0 for my $f (grep { length $_ } @{ $temp->{values} }[$offset..$offset+$count-1]) {
117 0 ▶ if( $f < $min ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($f < $min) 0 0 0
118 0 $min = $f;
119 };
120 0 ▶ if( $f > $max ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($f > $max) 0 0 0
121 0 $max = $f;
122 };
123 };
124  
125 0 $max -= 273.15;
126 0 $min -= 273.15;
127  
128 0 my $weather = [];
129  
130 0 my %forecast = (
131 date => $ts->new(),
132 weather => $weather,
133 min => $min,
134 max => $max,
135 );
136  
137 0 my $time = $ts->new();
138 0 $time->tzoffset(2*3600); # at least until October ...
139 # Do the min/max for the 4 6-hour windows
140 # Find the "representative" weather code for each window
141 # This should be done in SQL instead of hacking Perl code for this
142 0 my %count;
143 # with range as (
144 # select * from perldata
145 # where rownum() between ? and ?
146 # )
147 # select min(temp) as mintemp over ()
148 # , max(temp) as maxtemp over ()
149 # from range
150 0 for my $i ($offset..$offset+$count-1) {
151 0 my $c = $weathercode->{values}->[ $i ];
152 0 ▶ if( length $c ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $c) 0 0 0
153 0 my $v = sprintf '%02d', 0+$c;
154 0 $count{ $v }++;
155 0 $time += 3600;
156 };
157 };
158  
159 # Use the prevalent weather ...
160 0 my ($prevalent_weather) = (sort { $count{$a} cmp $count{$a} } keys %count )[0];
161 0 push @{ $weather }, {
162 timestamp => $ts->new(),
163 description => mosmix_weathercode($prevalent_weather),
164 };
165  
166 0 return \%forecast
167 }
168  
169 ▶sub format_forecast_day_concise( $ts, $temp, $weathercode, $offset, $count ) {
Subroutine format_forecast_day_concise: not called CC=2 SCAR=17.9
Pod undocumented
170  
171 # with range as (
172 # select * from perldata
173 # )
174 # , minmax as (
175 # select min(temp) as mintemp over (partition by offset / 6)
176 # , max(temp) as maxtemp over (partition by offset / 6)
177 # , weathercode
178 # select
179 # lead(min,0) lead(max,0), lead(weathercode,0)
180 # lead(min,1) lead(max,1), lead(weathercode,1)
181 # lead(min,2) lead(max,2), lead(weathercode,2)
182 # lead(min,3) lead(max,3), lead(weathercode,3)
183 # from range
184 0 my @res;
185 0 for (1..4) {
186 0 push @res, format_forecast_range_concise( $ts, $temp, $weathercode, $offset, 6 );
187 0 $offset += 6;
188 };
189 # put all of the information into a single line:
190 # location / ts / 3-9 / 10-15 / 16-21 / 22-2
191 # location / ts / min/max/w / min/max/w / min/max/w / min/max/w
192 };
193  
194 sub format_forecast_day {
195 0 ▶ my( $self, $ts, $temp, $weathercode, $offset, $count ) = @_;
Subroutine format_forecast_day: not called CC=6 SCAR=37.4
Pod undocumented
196  
197 0 my ($min, $max) = (1000,0);
198 0 for my $f (grep { length $_ } @{ $temp->{values} }[$offset..$offset+$count-1]) {
199 0 ▶ if( $f < $min ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($f < $min) 0 0 0
200 0 $min = $f;
201 };
202 0 ▶ if( $f > $max ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($f > $max) 0 0 0
203 0 $max = $f;
204 };
205 };
206  
207 0 $max -= 273.15;
208 0 $min -= 273.15;
209  
210 0 my $weather = [];
211 0 my %forecast = (
212 date => $ts->new(),
213 weather => $weather,
214 min => $min,
215 max => $max,
216 );
217  
218 0 my $time = $ts->new();
219 0 $time->tzoffset(2*3600); # at least until October ...
220 0 for my $i ($offset..$offset+$count-1) {
221 0 my $c = $weathercode->{values}->[ $i ];
222 0 ▶ if( length $c ) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $c) 0 0 0
223 0 my $v = sprintf '%02d', 0+$c;
224 0 push @{ $weather }, {
225 timestamp => $time->new(),
226 description => mosmix_weathercode($v),
227 };
228 0 $time += 3600;
229 };
230 };
231  
232 0 return \%forecast,
233 };
234  
235 0 ▶sub format_forecast_dbh( $self, $dbh, $interval, $offset=0 ) {
Subroutine format_forecast_dbh: not called CC=5 SCAR=34.0
Pod undocumented
236 # We need some offset for the first set, which will not contain the full
237 # six (or whatever) hours
238 0 my $sql = <<SQL;
239 with
240 partitioned as (
241 select
242 round((hour_ofs*1.0)/$interval -0.5) as part
243 , (hour_ofs*1.0)/$interval as weather_partition
244 , $interval as size
245 , *
246 from forecast
247 )
248 , minmax as (
249 select
250 max(TTT) over (partition by part) as maxtemp
251 , min(TTT) over (partition by part) as mintemp
252 , row_number() over (partition by part order by timestamp) as row
253 --, min(weather_partition) over (partition by part) as use_this
254 -- , date
255 -- , timestamp -- TZ-adjusted
256 , *
257 from partitioned
258 )
259 select
260 'active' as status
261 , *
262 from minmax
263 where row = 1
264 order by timestamp
265 SQL
266  
267 0 my $res = $dbh->selectall_arrayref($sql, { Slice => {} });
268  
269 # Now, add dummy data for slots we don't have
270 # this would likely be parts of the day that have already passed
271 0 ▶ while( $res->[0]->{hour} > $offset+$interval) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->[0]{"hour"} > $offset + $interval) 0 0 0
272 0 my $new = dclone( $res->[0]);
273 0 $new->{hour}-= $interval;
274 0 $new->{status} = 'past';
275 0 unshift @$res, $new;
276 };
277  
278 0 for( @$res ) {
279 0 ▶ if( exists $_->{emoji}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $_->{"emoji"}) 0 0 0
280 0 $_->{emoji} = decode('UTF-8', $_->{emoji});
281 }
282 }
283  
284 # fix up the data we have
285 # $time->tzoffset(2*3600); # at least until October ...
286 #for my $i ($offset..$offset+$count-1) {
287 # my $c = $weathercode->{values}->[ $i ];
288 # if( length $c ) {
289 # my $v = sprintf '%02d', 0+$c;
290 # push @{ $weather }, {
291 # timestamp => $time->new(),
292 # description => mosmix_weathercode($v),
293 # };
294 # $time += 3600;
295 # };
296 #};
297  
298 0 return $res;
299 };
300  
301 ▶sub format_forecast( $self, $f ) {
Subroutine format_forecast: not called CC=4 SCAR=30.0
Pod undocumented
302 0 my $loc = $f->{description};
303 0 (my $temp) = grep{ $_->{type} eq 'TTT' } @{ $f->{forecasts}};
304 0 (my $weathercode) = grep{ $_->{type} eq 'ww' } @{ $f->{forecasts}};
305  
306 # Convert from UTC to CET. This happens to work because my machines
307 # are located within CET ...
308 0 my $time = Time::Piece->strptime( $f->{issuetime}, '%Y-%m-%dT%H:%M:%SZ' );
309 0 $time = $time->_mktime( $time->epoch, 1 );
310  
311 # Find where today ends, and add a linebreak, resp. move to the next array ...
312 0 my @forecasts;
313 0 my %weather = (
314 #today => $weath,
315 #tomorrow => [],
316 #tomnext => [],
317 days => \@forecasts,
318 );
319 0 my %sequence = (
320 today => 'tomorrow',
321 tomorrow => 'tomnext',
322 );
323  
324 0 my $count = 0;
325 0 my $today = $time->truncate(to => 'day');
326 0 my $start = $time->new();
327 0 my $offset = $start->hour;
328 0 my $slot = 'today';
329  
330 0 ▶ while( $offset < @{$weathercode->{values}} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($offset < @{$weathercode->{"values"};}) 0 0 0
331 0 $time += 3600;
332 0 $count++;
333 0 ▶ if( $time->truncate( to => 'day' ) != $today ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($time->truncate("to", "day") != $today) 0 0 0
334 0 push @forecasts, $self->format_forecast_day( $start, $temp, $weathercode, $offset, $count );
335 0 $offset += $count;
336 0 $count = 0;
337 0 ▶ if( defined $slot ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $slot) 0 0 0
338 #print "$slot ($today) -> $sequence{ $slot } ($time)\n";
339 0 $slot = $sequence{ $slot };
340 };
341 0 $today = $time->truncate( to => 'day' );
342 0 $start = $today;
343 };
344 };
345  
346 0 $weather{ today } = $forecasts[0];
347 0 $weather{ tomorrow } = $forecasts[1];
348 0 $weather{ tomnext } = $forecasts[2];
349  
350 return {
351 issuetime => $f->{issuetime},
352 0 location => $loc,
353 weather => \%weather,
354 }
355 }
356  
357 ▶sub formatted_forecast( $self, %options ) {
Subroutine formatted_forecast: not called CC=1 SCAR=6.9
Pod undocumented
358 0 my $f = $self->forecast( %options );
359 0 $self->format_forecast( $f )
360 }
361  
362 =head2 C<< $mosmix->locations >>
363  
364 Lists all locations with their names and longitude/latitude. If a longitude
365 / latitude pair is passed in, the list is ordered by the distance from
366 that position.
367  
368 =cut
369  
370 ▶sub locations( $self, %options ) {
Subroutine locations: not called CC=3 SCAR=24.8
Pod documented
371 0 my $order_by = 'description asc';
372 0 ▶ if( exists $options{ longitude }
Branch: 1 branch
BranchTrueFalseTotal
if (exists $options{'longitude'} and exists $options{'latitude'}) { } 0 0 0
Condition0%0/3
exists $options{"longitude"} and exists $options{"latitude"}
!ll&&!rl&&r
000
MC/DC0%0/2
exists $options{"longitude"} and exists $options{"latitude"}
exists $options{"longitude"} exists $options{"latitude"}
Truth table0%0/3
A and B
A= exists $options{"longitude"}B= exists $options{"latitude"}
ABresult
0X0
100
111
373 and exists $options{ latitude } ) {
374 0 $order_by = 'distance asc';
375 } else {
376 0 $options{ latitude } = 0;
377 };
378 0 my $cos_lat_sq = cos( $options{ latitude } ) ^ 2;
379 my $res =
380 0 $self->dbh->selectall_arrayref(<<SQL, { Slice => {}}, $options{latitude}, $options{latitude}, $options{longitude},$options{longitude}, $cos_lat_sq);
381 select
382 description
383 , latitude
384 , longitude
385 , ((l.latitude - ?)*(l.latitude - ?))
386 + ((l.longitude - ?)*(l.longitude - ?)*?) as distance
387 from forecast_location l
388 order by $order_by
389 SQL
390 0 $res
391 };
392  
393 =head1 SETUP
394  
395 =over 4
396  
397 =item 1
398  
399 Install the module
400  
401 =item 2
402  
403 Create a directory for the database
404  
405 mkdir ~/weather ; cd ~/weather
406  
407 =item 3
408  
409 Create the database
410  
411 mosmix-import.pl --create
412  
413 =item 4
414  
415 Set up a cron job to fetch the MOSMIX forecast
416  
417 01 6,12,18,0 * * * cd /home/corion/weather; mosmix-import.pl
418 15 6,12,18,0 * * * cd /home/corion/weather; mosmix-purge.pl
419  
420 =item 5
421  
422 Query the current forecast
423  
424 cd /home/corion/weather; mosmix-query.pl
425  
426 =back
427  
428 =head1 SEE ALSO
429  
430 German Weather Service
431  
432 L<https://opendata.dwd.de/weather/>
433  
434 L<https://opendata.dwd.de/weather/local_forecasts/mos/MOSMIX_S/all_stations/kml/>
435  
436 Other Weather APIs
437  
438 L<https://openweathermap.org/api> - international, signup required
439  
440 L<https://www.weatherbit.io/api> - international, signup required
441  
442 L<https://developer.accuweather.com/> - international, signup required
443  
444 L<https://darksky.net/dev> - paid, international, signup required
445  
446 L<http://api.weather2020.com/> - international, signup required
447  
448 Overview of Open Data
449  
450 L<https://index.okfn.org/place/de/weather/>
451 L<https://index.okfn.org/place/us/weather/>
452 L<https://index.okfn.org/place/lv/weather/>
453 L<https://index.okfn.org/place/cy/weather/>
454  
455 Cyprus forecast
456  
457 L<http://www.moa.gov.cy/moa/ms/ms.nsf/DMLforecast_general_gr/DMLforecast_general_gr?opendocument>
458  
459 =head2 Icons
460  
461 L<https://github.com/zagortenay333/Tempestacons>
462  
463 L<https://thenounproject.com/search/?q=weather>
464  
465 L<https://undraw.co/search>
466  
467 L<https://coreui.io/icons/>
468  
469 =cut
470  
471 3 1;
472 =head1 REPOSITORY
473  
474 The public repository of this module is
475 L<https://github.com/Corion/weather-mosmix>.
476  
477 =head1 SUPPORT
478  
479 The public support forum of this module is L<https://perlmonks.org/>.
480  
481 =head1 BUG TRACKER
482  
483 Please report bugs in this module via the RT CPAN bug queue at
484 L<https://rt.cpan.org/Public/Dist/Display.html?Name=Weather-MOSMIX>
485 or via mail to L<www-Weather-MOSMIX@rt.cpan.org|mailto:Weather-MOSMIX@rt.cpan.org>.
486  
487 =head1 AUTHOR
488  
489 Max Maischein C<corion@cpan.org>
490  
491 =head1 COPYRIGHT (c)
492  
493 Copyright 2019-2020 by Max Maischein C<corion@cpan.org>.
494  
495 =head1 LICENSE
496  
497 This module is released under the same terms as Perl itself.
498  
499 =cut
« blib/lib/Weather/MOSMIX/Weathercodes.pm ↑ Summary blib/lib/Weather/MOSMIX/Reader.pm »