blib/lib/Weather/OWM.pm

filter: Statementstmt 100% 138 / 138 Branchbran 96.2% 77 / 80 Conditioncond 96.6% 57 / 59 MC/DCmcdc 91.1% 31 / 34 Subroutinesub 100% 25 / 25 Podpod 100% 11 / 11 totaltotal 97.6% 339 / 347 CC 66 SCAR 19.7
CC
66
Cov
98%
one_call_response
15.0
get_history_response
13.0
_preprocess_params
8.0
CRAP 7.2
↑ Summary
1 package Weather::OWM;
2  
3 3 ▶use 5.008;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 3 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 3 ▶use parent 'Weather::API::Base';
Subroutine BEGIN: called CC=1 SCAR=0.0
10 3 ▶use Weather::API::Base qw(:all);
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 =head1 NAME
13  
14 Weather::OWM - Perl client for the OpenWeatherMap (OWM) API
15  
16 =cut
17  
18 3 our $VERSION = '0.2';
19  
20 =head1 SYNOPSIS
21  
22 use Weather::OWM;
23 use v5.10;
24  
25 my $owm = Weather::OWM->new(key => 'Your API key');
26  
27 ### Using the free endpoints of the "classic" Weather API 2.5:
28
29 # Get current weather for the Stonehenge area using coordinates...
30 my %re = $owm->get_weather(lat => 51.18, lon => -1.83);
31  
32 # ...and print temperature, humidity, wind speed
33 say "$re{main}->{temp}C $re{main}->{humidity}% $re{wind}->{speed}m/s"
34 unless $re{error};
35  
36 # Get 3h/5d forecast for London, UK...
37 %re = $owm->get_weather(product => 'forecast', loc => 'London,UK');
38  
39 # ...and print the temperature for every three hours over the next 5 days
40 say scalar(localtime($_->{dt}))." $_->{main}->{temp}C" for @{$re{list}};
41  
42 ### Using the newer One Call 3.0 API:
43  
44 # Get current weather and min/h/day forecast for Punxsutawney, PA...
45 %re = $owm->one_call(city => 'Punxsutawney,PA,US', units => 'imperial');
46  
47 # ...print current temperature, humidity, wind speed...
48 say "$re{current}->{temp}F $re{current}->{humidity}% $re{current}->{wind_speed}mph"
49 unless $re{error};
50
51 # ...and print the temperature for every hour over the next 2 days
52 say "$_->{temp}F" for @{$re{hourly}};
53  
54 ### Using the History API 2.5:
55  
56 # Get the historical weather for the first 72 hours of 2023 at Greenwich, UK...
57 my %report = $owm->get_history(
58 product => 'hourly',
59 loc => 'Greenwich,UK',
60 start => '2023-01-01 00:00:00',
61 cnt => '72'
62 );
63  
64 # ...and print the temperatures next to the date/time
65 say scalar(localtime($_->{dt}))." $_->{main}->{temp}C" for @{$re{list}};
66  
67 ### Using the Geocoder API:
68  
69 # Fetch Portland, Maine from the Geocoder API...
70 my @locations = $owm->geo(city => 'Portland,ME,US');
71  
72 # ...and print the latitude,longitude
73 say "$locations[0]->{lat},$locations[0]->{lon}";
74  
75 # Get the top 5 cities named "Portland" in the US...
76 @locations = $owm->geo(city => 'Portland,US', limit=>5);
77  
78 # ...and print their state and coordinates.
79 say "$_->{state} $_->{lat},$_->{lon}" for @locations;
80  
81 # Perform reverse geocoding of coordinates 51.51 North, 0.12 West...
82 @locations = $owm->geo(lat=>51.51, lon=>-0.12);
83  
84 # ...and print the location name, country
85 say "$locations[0]->{name}, $locations[0]->{country}";
86  
87 =head1 DESCRIPTION
88  
89 L<Weather::OWM> is a lightweight Perl client supporting most OpenWeatherMap (OWM) APIs,
90 including the latest One Call v3.0.
91  
92 There is an easy-to-use object oriented interface that can return the data in hashes.
93 There are virtually no dependencies, except L<LWP::UserAgent> for the requests, and
94 optionally L<JSON> or L<XML::Simple> if you want to decode JSON (most common) or XML data.
95  
96 Current OWM API support:
97  
98 =over 4
99  
100 =item * OneCall API 3.0 for current weather, forecast and weather history.
101  
102 =item * Weather API 2.5 including free (current weather, 3h/5d forecast) and paid forecasts.
103  
104 =item * Historical APIs 2.5 (history, statistical, accumulated).
105  
106 =item * Geocoding API 1.0 for direct/reverse geocoding.
107  
108 =back
109  
110 Please see L<the official OWM website|https://openweathermap.org/api> for extensive
111 documentation. Note that even the free APIs require L<registering|https://home.openweathermap.org/users/sign_up>
112 for an API key.
113  
114 This module belongs to a family of weather modules (along with L<Weather::Astro7Timer>
115 and L<Weather::WeatherKit>) created to serve the apps L<Xasteria|https://astro.ecuadors.net/xasteria/>
116 and L<Polar Scope Align|https://astro.ecuadors.net/polar-scope-align/>, but if your
117 service requires some extra functionality, feel free to contact the author about adding it.
118  
119 =head1 CONSTRUCTOR
120  
121 =head2 C<new>
122  
123 my $owm = Weather::OWM->new(
124 key => $api_key, #required
125 timeout => $timeout_sec?,
126 agent => $user_agent_string?,
127 ua => $lwp_ua?,
128 lang => $lang?,
129 units => $units?,
130 error => $die_or_return?,
131 debug => $debug?,
132 scheme => $url_scheme?
133 );
134  
135 Creates a Weather::OWM object.
136  
137 Required parameters:
138  
139 =over 4
140  
141 =item * C<key> : The API key is required for both free and paid APIs. For the former,
142 you can L<sign up|https://home.openweathermap.org/users/sign_up> for a free account.
143  
144 =back
145  
146 Optional parameters:
147  
148 =over 4
149  
150 =item * C<timeout> : Timeout for requests in secs. Default: C<30>.
151  
152 =item * C<agent> : Customize the user agent string.
153  
154 =item * C<ua> : Pass your own L<LWP::UserAgent> to customise further. Will override C<agent>.
155  
156 =item * C<lang> : Set language (two letter language code) for requests. You can override per API call. Default: C<en>.
157  
158 =item * C<units> : Set units (standard, metric, imperial). You can override per API call. Default: C<metric>. Available options:
159  
160 =over 4
161  
162 =item * C<standard> : Temperature in Kelvin. Wind speed in metres/sec.
163  
164 =item * C<metric> : Temperature in Celsius. Wind speed in metres/sec.
165  
166 =item * C<imperial> : Temperature in Fahrenheit. Wind speed in mph.
167  
168 =back
169  
170 =item * C<error> : If there is an error response with the main methods, you have the options to C<die> or C<return> it. You can override per API call. Default: C<return>.
171  
172 =item * C<debug> : If debug mode is enabled, API URLs accessed are printed in STDERR. Default: C<false>.
173  
174 =item * C<scheme> : You can use C<http> as an option if you have trouble building https support for LWP in your system. Default: C<https>.
175  
176 =back
177  
178 =head1 MAIN METHODS
179  
180 The main methods will return a string containing the JSON (or XML etc where specified),
181 except in the array context (C<< my %hash = $owm->method >>), where L<JSON> (or similar)
182 will be used to conveniently decode it to a Perl hash.
183  
184 If the request is not successful, by default an C<ERROR: status_line> will be returned
185 in scalar context or C<(error => HTTP::Response)> in array context.
186 If the constructor was set with an C<error> equal to C<die>, then it will die throwing
187 the C<< HTTP::Response->status_line >>.
188  
189 For custom error handling, see the alternative methods.
190  
191 =head2 C<one_call>
192  
193 One Call 3.0 API
194  
195 my $report = $owm->one_call(
196 product => $product, # Can be: forecast, historical, daily
197 lat => $lat, # Required unless city/zip specified
198 lon => $lon, # Required unless city/zip specified
199 city => $city?, # City,country (via Geocoder API)
200 zip => $zip?, # Zip/postcode,country (via Geocoder API)
201 date => $date?, # Date or unix timestamp: required for daily/historical
202 );
203  
204 my %report = $owm->one_call( ... );
205  
206 Fetches a One Call API v3.0 response for the desired location. The One Call API
207 offers 3 products, which differ in some options as listed below. C<lang>, C<error>
208 and C<units> options specified in the constructor can be overridden on each call.
209  
210 For an explanation to the returned data, refer to the L<official API documentation|https://openweathermap.org/api/one-call-3>.
211  
212 Parameters common to all products:
213  
214 =over 4
215  
216  
217 =item * C<lat> : Latitude (-90 to 90). South is negative.
218  
219 =item * C<lon> : Longitude (-180 to 180). West is negative.
220  
221 Latitude/Longitude are normally required.
222 As a convenience, you can specify a city name or a zip/post code instead:
223  
224 =item * C<city> : Expects C<city name,country code> or C<city name,state code,US>,
225 where C<country code> is ISO 3166.
226  
227 =item * C<zip> : Expects C<zip/post code,country code>, where C<country code> is ISO 3166.
228  
229 Note that to avoid issues with ambiguity of city names etc you can use the
230 Geocoder API manually.
231  
232 =back
233  
234 =head4 One Call API products
235  
236 Three call types/products to use listed below, along with any custom parameters they support.
237 If no product is specified, C<forecast> is used.
238  
239 =over 4
240  
241 =item * C<forecast> : B<Current weather and forecasts>: Provides a minute forecast for 1 hour, hourly for 48 hours and daily for 8 days.
242 Optional parameter:
243  
244 =over 4
245  
246 =item * C<exclude> : Exclude data from the API response (to reduce size). It expects a comma-delimited list with any combination of the possible values:
247 C<current>,C<minutely>,C<hourly>,C<daily>,C<alerts>
248  
249 =back
250  
251 =item * C<historical> : B<Weather data for any timestamp>: 40+ year historical archive and 4 days ahead forecast.
252 Required parameter:
253  
254 =over 4
255  
256 =item * C<date> : Unix timestamp for start of the data. Data is available from 1979-01-01.
257 For convenience, C<date> can be specified instead in iso format C<YYYY-MM-DD HH:mm:ss>
258 for your local time (or C<YYYY-MM-DD HH:mm:ssZ> for UTC).
259  
260 =back
261  
262 =item * C<daily> : B<Daily aggregation>: 40+ year weather archive and 1.5 years ahead forecast.
263 Required parameter:
264  
265 =over 4
266  
267 =item * C<date> : Date of request in the format C<YYYY-MM-DD>.
268 For convenience, the timestamp/date formats of the C<historical> product can be used (will be truncated to just the plain date).
269  
270 =back
271  
272 =back
273  
274 =head2 C<get_weather>
275  
276 Weather API 2.5
277  
278 my $report = $owm->get_weather(
279 product => $product, # Can be: current, forecast, hourly, daily, climate
280 lat => $lat, # Required unless loc/zip/city_id specified
281 lon => $lon, # Required unless loc/zip/city_id specified
282 loc => $location?, # Named location (deprecated)
283 zip => $zip?, # Zip/postcode (deprecated)
284 city_id => $city_id?, # city_id (deprecated)
285 mode => $mode?, # output mode - default: json
286 );
287  
288 my %report = $owm->get_weather( ... );
289  
290 Fetches a weather API v2.5 response for the desired location. The weather API has
291 several products available (some free, others requiring paid subscription), some have
292 special arguments as listed below. C<lang>, C<error> and C<units> options specified
293 in the constructor can be overridden on each call.
294  
295 For an explanation to the returned data, refer to the L<official API documentation|https://openweathermap.org/api>
296 or see below in the products list the links for each endpoint.
297  
298 Parameters common to all products:
299  
300 =over 4
301
302 =item * C<lat> : Latitude (-90 to 90). South is negative. Required unless loc/zip/city_id specified.
303  
304 =item * C<lon> : Longitude (-180 to 180). West is negative. Required unless loc/zip/city_id specified.
305  
306 =item * C<loc> : Deprecated (lat/lon recommended - see Geocoder API). Location given either as a C<city name>
307 or C<city name,country code> or C<city name,state code,US>.
308  
309 =item * C<zip> : Deprecated (lat/lon recommended - see Geocoder API). Expects C<zip/post code> (US) or C<zip/post code,country code>.
310  
311 =item * C<city_id> : Deprecated (lat/lon recommended - see Geocoder API). City id from list L<here|https://bulk.openweathermap.org/sample/city.list.json.gz>.
312  
313 =item * C<mode> : Output mode. Default is json C<json>, C<xml> is the supported alternative (unless otherwise specified).
314  
315 =back
316  
317 =head4 API products
318  
319 There are several API endpoints which are selected via C<product> (two of them accessible with a free key).
320 They are listed below, along with any custom parameters they support. If no product is provided, C<current> is used.
321  
322 =over 4
323  
324 =item * C<current> : B<Current Weather Data> (free product). For response details see L<official API doc|https://openweathermap.org/current>.
325  
326 =over 4
327  
328 =item * C<mode> : C<xml> and C<html> are supported as alternatives. (Optional)
329  
330 =back
331  
332 =item * C<forecast> : B<5 Day / 3 Hour Forecast> (free product). For response details see L<official API doc|https://openweathermap.org/forecast5>.
333  
334 =over 4
335  
336 =item * C<cnt> : Limit the number of timestamps returned. (Optional)
337  
338 =back
339  
340 =item * C<hourly> : B<Hourly Forecast (4 days)>. For response details see L<official API doc|https://openweathermap.org/api/hourly-forecast>.
341  
342 =over 4
343  
344 =item * C<cnt> : Limit the number of timestamps returned. (Optional)
345  
346 =back
347  
348 =item * C<daily> : B<Daily Forecast (16 days)>. For response details see L<official API doc|https://openweathermap.org/forecast16>.
349  
350 =over 4
351  
352 =item * C<cnt> : Number of days (1 to 16) to be returned. (Optional)
353  
354 =back
355  
356 =item * C<climate> : B<Climatic Forecast (30 days)>. For response details see L<official API doc|https://openweathermap.org/api/forecast30>.
357  
358 =over 4
359  
360 =item * C<cnt> : Number of days (1 to 30) to be returned. (Optional)
361  
362 =back
363  
364 =back
365  
366 =head2 C<get_history>
367  
368 History API 2.5
369  
370 my $report = $owm->get_history(
371 product => $product, # Can be: hourly, year, month, day, temp, precip
372 lat => $lat, # Required unless loc/zip/city_id specified
373 lon => $lon, # Required unless loc/zip/city_id specified
374 loc => $location?, # Named location (deprecated)
375 zip => $zip?, # Zip/postcode (deprecated)
376 city_id => $city_id?, # city_id (deprecated)
377 );
378  
379 my %report = $owm->get_history( ... );
380  
381 Fetches a historical weather API v2.5 response for the desired location. The weather API has
382 several products available, some have special arguments as listed below. C<lang>, C<error>
383 and C<units> options specified in the constructor can be overridden on each call.
384  
385 For an explanation to the returned data, refer to the L<official API documentation|https://openweathermap.org/api>
386 or see below in the products list the links for each endpoint.
387  
388 Parameters common to all products:
389  
390 =over 4
391
392 =item * C<lat> : Latitude (-90 to 90). South is negative. Required unless loc/zip/city_id specified.
393  
394 =item * C<lon> : Longitude (-180 to 180). West is negative. Required unless loc/zip/city_id specified.
395  
396 =item * C<loc> : Deprecated (lat/lon recommended - see Geocoder API). Location given either as a C<city name>
397 or C<city name,country code> or C<city name,state code,US>.
398  
399 =item * C<zip> : Deprecated (lat/lon recommended - see Geocoder API). Expects C<zip/post code> (US) or C<zip/post code,country code>.
400  
401 =item * C<city_id> : Deprecated (lat/lon recommended - see Geocoder API). City id from list L<here|https://bulk.openweathermap.org/sample/city.list.json.gz>.
402  
403 =back
404  
405 =head4 API products
406  
407 There are several API endpoints which are selected via C<product>.
408 They are listed below, along with any custom parameters they support.
409 If none is specified, C<hourly> is used.
410  
411 =over 4
412  
413 =item * C<hourly> : B<Hourly Historical Data>. For response details see L<official API doc|https://openweathermap.org/history>.
414 Parameters:
415  
416 =over 4
417  
418 =item * C<start> : (required) Start date. Unix timestamp (or iso date).
419  
420 =item * C<end> : (required unless C<cnt> specified) End date. Unix timestamp (or iso date).
421  
422 =item * C<cnt> : (required unless C<end> specified) Number of timestamps returned (used instead of C<end>).
423  
424 =back
425  
426 =item * C<year> : B<Statistical Climate Data: Yearly aggregation>. Returns statistical climate indicators for the entire year. For response details see L<official API doc|https://openweathermap.org/api/statistics-api>.
427  
428 =item * C<month> : B<Statistical Climate Data: Monthly aggregation>. Returns statistical climate indicators for a specific month of the year. For response details see L<official API doc|https://openweathermap.org/api/statistics-api>.
429 Parameters:
430  
431 =over 4
432  
433 =item * C<month> : (required) Specify the month (1-12) for which to return statistical climate data.
434  
435 =back
436  
437 =item * C<day> : B<Statistical Climate Data: Day aggregation>. Returns statistical climate indicators for a specific month of the year. For response details see L<official API doc|https://openweathermap.org/api/statistics-api>.
438 Parameters:
439  
440 =over 4
441  
442 =item * C<month> : (required) Specify the month (1-12) for which to return statistical climate data.
443  
444 =item * C<day> : (required) Specify the day (1-31) of the month for which to return statistical climate data.
445  
446 =back
447  
448 =item * C<temp> : B<Accumulated temperature>: The sum, counted in degrees (Kelvin), by which the actual air temperature rises above or falls below a threshold level during the chosen time period. For response details see L<official API doc|https://openweathermap.org/api/accumulated-parameters>.
449 Parameters:
450  
451 =over 4
452  
453 =item * C<start> : (required) Start date. Unix timestamp (or iso date).
454  
455 =item * C<end> : (required) End date. Unix timestamp (or iso date).
456  
457 =item * C<threshold> : All values smaller than indicated value are not taken into account.
458  
459 =back
460  
461 =item * C<precip> : B<Accumulated precipitation>: The sum, counted in millimetres, of daily precipitation during the chosen time period. For response details see L<official API doc|https://openweathermap.org/api/accumulated-parameters>.
462 Parameters:
463  
464 =over 4
465  
466 =item * C<start> : (required) Start date. Unix timestamp (or iso date).
467  
468 =item * C<end> : (required) End date. Unix timestamp (or iso date).
469  
470 =back
471  
472 =back
473  
474 =head2 C<geo>
475  
476 Geocoding API 1.0
477  
478 # Direct geocoding
479  
480 my $locations = $owm->geo(
481 city => $city?, # City,country. Required if zip not specified.
482 zip => $zip?, # Zip/postcode,country. Required if city not specified.
483 limit => $limit # Limit number of results.
484 );
485  
486 my @locations = $owm->geo( ... );
487  
488 my ($lat, $lon) = ($locations[0]->{lat},$locations[0]->{lon});
489  
490 # Reverse geocoding
491  
492 my $locations = $owm->geo(
493 lat => $lat, # Latitude.
494 lon => $lon, # Longitude
495 limit => $limit # Limit number of results.
496 );
497  
498 my @locations = $owm->geo( ... );
499  
500 my ($name, $country) = ($locations[0]->{name},$locations[0]->{country});
501  
502 # Checking for error with default error handling behaviour
503 warn "Error" if @locations && $locations[0] eq 'error';
504 warn "No results" if !@locations;
505  
506 Will return a list of named locations with their central coordinates (lat/lon) that
507 match the request. The request can include either city or zip/postcode (geocoding),
508 or latitude/longitude (reverse geocoding).
509  
510 All the OWM APIs work with coordinates, which are unambiguous. As a convenience,
511 the 2.5 API accepted city names or zip codes. This is now deprecated and you are
512 advised to use the geocoding to get the latitude/longitude of the desired location.
513 The Weather::OWM C<one_call> method also accepts city or zip as a convenience,
514 the top result of from the Geocoding API is used. You may want to use this API
515 directly yourself as well to verify the location is as intended.
516  
517 For an explanation to the returned data, refer to the L<official API documentation|https://openweathermap.org/api/geocoding-api>.
518  
519 Due to the data returned being an array, for the default error mode (C<return>),
520 on error a size-2 array will be returned: C<('error', HTTP::Response)>. Alternatives
521 are using the C<geo_response> function, or passing an C<error=>'die'> parameter
522 and using C<try/catch>.
523  
524 Common parameters:
525  
526 =over 4
527  
528 =item * C<limit> : Limit the number of location results from 1 to 5. Currently, the API
529 default seems to be set to 1. Note that both direct and reverse geocoding can produce
530 more than one result (either different cities with the same name, of a location belonging
531 to different administrative units (e.g. city vs local municipality).
532  
533 =back
534  
535 Geocoding parameters:
536  
537 =over 4
538  
539 =item * C<city> : Expects C<city name>, C<city name,country code> or C<city name,state code,US>,
540 where C<country code> is ISO 3166. If the C<country code> is skipped, the result
541 may be ambiguous if there are similarly named/sized cities in different countries.
542  
543 =item * C<zip> : Expects C<zip/post code,country code>, where C<country code> is ISO 3166.
544  
545 =back
546  
547 Reverse geocoding parameters:
548  
549 =over 4
550  
551 =item * C<lat> : Latitude.
552  
553 =item * C<lon> : Longitude.
554  
555 =back
556  
557 =head1 ALTERNATIVE METHODS
558  
559 The main methods handle the HTTP response errors with a C<die> that throws the status line.
560 There are alternative methods you can use that work exactly the same, except you
561 get the full L<HTTP::Response> object from the API endpoint, so that you can do
562 the error handling yourself.
563  
564 =head2 C<one_call_response>
565  
566 my $response = $owm->one_call_response(
567 %args
568 );
569  
570 Alternative to C<one_call> (same parameters).
571  
572 =head2 C<get_weather_response>
573  
574 my $response = $owm->get_weather_response(
575 %args
576 );
577  
578 Alternative to C<get_weather> (same parameters).
579  
580 =head2 C<get_history_response>
581  
582 my $response = $owm->get_history_response(
583 %args
584 );
585  
586 Alternative to C<get_history> (same parameters).
587  
588 =head2 C<geo_response>
589  
590 my $response = $owm->geo_response(
591 %args
592 );
593  
594 Alternative to C<geo> (same parameters).
595  
596 =head1 HELPER METHODS
597  
598 =head2 C<icon_url>
599  
600 my $url = $owm->icon_url($icon, $small?);
601  
602 The APIs may return an C<icon> key which corresponds to a specific icon. The URL
603 to the 100x100 icon (png with transparent background) is provided by this function,
604 unless you pass C<$small> in which case you get the URL to the 50x50 icon.
605  
606 =head2 C<icon_data>
607  
608 my $data = $owm->icon_data($icon, $small?);
609  
610 Similar to L<icon_url> above, but downloads the png data (undef on error).
611  
612 =head1 HELPER FUNCTIONS FROM Weather::API::Base
613  
614 The parent class L<Weather::API::Base> contains some useful functions:
615  
616 use Weather::API::Base qw(:all);
617  
618 # Get time in YYYY-MM-DD HH:mm:ss format, local time zone from a unix timestamp
619 my $datetime = ts_to_date(time());
620  
621 # Convert 30 degrees Celsius to Fahrenheit
622 my $result = convert_units('C', 'F', 30);
623  
624 See the doc for that module for more details.
625  
626 =cut
627  
628 3 my $geocache;
629  
630 10 ▶sub new {
Subroutine new: called CC=2 SCAR=6.9
Pod documented
631 10 my ($class, %args) = @_;
632  
633 10 ▶ croak("key required ") unless $args{key};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"key"} 1 9 10
634  
635 9 my $self = $class->SUPER::new(lang => 'en', %args);
636 8 $self->{key} = $args{key};
637  
638 8 return $self;
639 }
640  
641 13 ▶sub one_call {
Subroutine one_call: called CC=1 SCAR=0.0
Pod documented
642 13 my $self = shift;
643 13 return $self->_get(wantarray, 'one_call', @_);
644 }
645  
646 7 ▶sub get_weather {
Subroutine get_weather: called CC=1 SCAR=0.0
Pod documented
647 7 my $self = shift;
648 7 return $self->_get(wantarray, 'weather', @_);
649 }
650  
651 10 ▶sub get_history {
Subroutine get_history: called CC=1 SCAR=0.0
Pod documented
652 10 my $self = shift;
653 10 return $self->_get(wantarray, 'history', @_);
654 }
655  
656 10 ▶sub geo {
Subroutine geo: called CC=1 SCAR=0.0
Pod documented
657 10 my $self = shift;
658 10 return $self->_get(wantarray, 'geo', @_);
659 }
660  
661 14 ▶sub one_call_response {
Subroutine one_call_response: called CC=15 SCAR=27.1
Pod documented
662 14 my $self = shift;
663 14 my %args = $self->_preprocess_params('one_call', @_);
664  
665 14 ▶ $args{product} = '' if !$args{product} || $args{product} eq 'forecast';
Branch: 1 branch
BranchTrueFalseTotal
if not $args{"product"} or $args{"product"} eq "forecast" 6 8 14
Condition100%3/3
not $args{"product"} or $args{"product"} eq "forecast"
l!l&&r!l&&!r
518
MC/DC100%2/2
not $args{"product"} or $args{"product"} eq "forecast"
not $args{"product"} $args{"product"} eq "forecast"
Truth table100%3/3
not(A) or B
A= not $args{"product"}B= $args{"product"} eq "forecast"
ABresult
1X1
011
000
666  
667 croak("product has to be 'forecast', 'historical' or 'daily'")
668 14 ▶ if $args{product} && $args{product} ne 'historical' && $args{product} ne 'daily';
Branch: 1 branch
BranchTrueFalseTotal
if $args{"product"} and $args{"product"} ne "historical" and $args{"product"} ne "daily" 1 13 14
Condition100%6/6
$args{"product"} and $args{"product"} ne "historical" and $args{"product"} ne "daily"
!ll&&!rl&&r
941
$args{"product"} and $args{"product"} ne "historical"
!ll&&!rl&&r
635
MC/DC100%3/3
$args{"product"} and $args{"product"} ne "historical" and $args{"product"} ne "daily"
$args{"product"} $args{"product"} ne "historical" $args{"product"} ne "daily"
Truth table100%4/4
A and B and C
A= $args{"product"}B= $args{"product"} ne "historical"C= $args{"product"} ne "daily"
ABCresult
0XX0
10X0
1100
1111
669  
670 13 $self->_geocode(\%args);
671  
672 11 Weather::API::Base::_verify_lat_lon(\%args);
673  
674 9 ▶ if ($args{product}) { # Not forecast
Branch: 1 branch
BranchTrueFalseTotal
if ($args{"product"}) 7 2 9
675 croak("date expected")
676 7 ▶ unless $args{date};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"date"} 1 6 7
677  
678 6 ▶ if ($args{product} eq 'daily') {
Branch: 2 branches
BranchTrueFalseTotal
if ($args{'product'} eq 'daily') { } 3 3 6
elsif ($args{'product'} eq 'historical') { } 3 0 3
679 $args{date} = ts_to_date($args{date})
680 3 ▶ if $args{date} =~ /^\d+$/;
Branch: 1 branch
BranchTrueFalseTotal
if $args{"date"} =~ /^\d+$/ 1 2 3
681  
682 3 ▶ if ($args{date} =~ /^(\d{4}-\d{2}-\d{2})/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($args{'date'} =~ /^(\d{4}-\d{2}-\d{2})/) { } 2 1 3
683 2 $args{date} = $1;
684 } else {
685 1 croak("date expected in the format YYYY-MM-DD");
686 }
687 croak("date of at least 1979-01-02 expected")
688 2 ▶ unless $args{date} ge "1979-01-02";
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"date"} ge "1979-01-02" 1 1 2
689 } elsif ($args{product} eq 'historical') {
690 $args{date} = datetime_to_ts($args{date})
691 3 ▶ unless $args{date} =~ /^\d+$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"date"} =~ /^\d+$/ 2 1 3
692  
693 croak("dt / date of at least 1979-01-01 expected")
694 2 ▶ unless $args{date} >= 283999530;
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"date"} >= 283999530 1 1 2
695 1 $args{dt} = delete $args{date};
696 }
697 }
698  
699 4 return $self->_get_ua($self->_onecall_url(%args));
700 }
701  
702 8 ▶sub get_weather_response {
Subroutine get_weather_response: called CC=4 SCAR=13.9
Pod documented
703 8 my $self = shift;
704 8 my %args = $self->_preprocess_params('weather', @_);
705  
706 Weather::API::Base::_verify_lat_lon(\%args)
707 8 ▶ unless $args{q} || $args{zip} || $args{city_id};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"q"} or $args{"zip"} or $args{"city_id"} 3 5 8
Condition100%6/6
$args{"q"} or $args{"zip"} or $args{"city_id"}
l!l&&r!l&&!r
413
$args{"q"} or $args{"zip"}
l!l&&r!l&&!r
134
MC/DC100%3/3
$args{"q"} or $args{"zip"} or $args{"city_id"}
$args{"q"} $args{"zip"} $args{"city_id"}
Truth table100%4/4
A or B or C
A= $args{"q"}B= $args{"zip"}C= $args{"city_id"}
ABCresult
1XX1
01X1
0011
0000
708  
709 8 return $self->_get_ua($self->_weather_url(%args));
710 }
711  
712 11 ▶sub get_history_response {
Subroutine get_history_response: called CC=13 SCAR=25.6
Pod documented
713 11 my $self = shift;
714 11 my %args = $self->_preprocess_params('history', @_);
715  
716 11 ▶ $args{product} ||= 'hourly';
Condition100%2/2
$args{"product"} ||= "hourly"
l!l
83
MC/DC100%1/1
$args{"product"} ||= "hourly"
$args{"product"}
Truth table100%2/2
A
A= $args{"product"}
Aresult
11
00
717  
718 Weather::API::Base::_verify_lat_lon(\%args)
719 11 ▶ unless $args{q} || $args{zip} || $args{city_id};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"q"} or $args{"zip"} or $args{"city_id"} 3 8 11
Condition100%6/6
$args{"q"} or $args{"zip"} or $args{"city_id"}
l!l&&r!l&&!r
443
$args{"q"} or $args{"zip"}
l!l&&r!l&&!r
317
MC/DC100%3/3
$args{"q"} or $args{"zip"} or $args{"city_id"}
$args{"q"} $args{"zip"} $args{"city_id"}
Truth table100%4/4
A or B or C
A= $args{"q"}B= $args{"zip"}C= $args{"city_id"}
ABCresult
1XX1
01X1
0011
0000
720  
721 11 my %req = (
722 hourly => ['start'],
723 month => ['month'],
724 day => [qw/month day/],
725 temp => [qw/start end/],
726 precip => [qw/start end/],
727 );
728  
729 11 my $req = $req{$args{product}};
730  
731 11 foreach (@$req) {
732 12 ▶ croak("$_ is expected") unless $args{$_};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{$_} 1 11 12
733 }
734 croak("end or cnt is expected")
735 10 ▶ if $args{product} eq 'hourly' && !$args{end} && !$args{cnt};
Branch: 1 branch
BranchTrueFalseTotal
if $args{"product"} eq "hourly" and not $args{"end"} and not $args{"cnt"} 1 9 10
Condition100%6/6
$args{"product"} eq "hourly" and not $args{"end"} and not $args{"cnt"}
!ll&&!rl&&r
721
$args{"product"} eq "hourly" and not $args{"end"}
!ll&&!rl&&r
613
MC/DC100%3/3
$args{"product"} eq "hourly" and not $args{"end"} and not $args{"cnt"}
$args{"product"} eq "hourly" not $args{"end"} not $args{"cnt"}
Truth table100%4/4
A and not(B) and not(C)
A= $args{"product"} eq "hourly"B= not $args{"end"}C= not $args{"cnt"}
ABCresult
0XX0
10X0
1100
1111
736  
737 9 foreach (qw/start end/) {
738 18 ▶ next unless $args{$_};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{$_} 10 8 18
739 $args{$_} = datetime_to_ts($args{$_})
740 8 ▶ unless $args{$_} =~ /^\d+$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $args{$_} =~ /^\d+$/ 4 4 8
741 }
742  
743 9 return $self->_get_ua($self->_history_url(%args));
744 }
745  
746 10 ▶sub geo_response {
Subroutine geo_response: called CC=5 SCAR=16.1
Pod documented
747 10 my $self = shift;
748 10 my %args = $self->_preprocess_params('geo', @_);
749  
750 10 ▶ if (defined $args{lat} && defined $args{lon}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $args{'lat'} and defined $args{'lon'}) { } 1 9 10
Condition100%3/3
defined $args{"lat"} and defined $args{"lon"}
!ll&&!rl&&r
811
MC/DC100%2/2
defined $args{"lat"} and defined $args{"lon"}
defined $args{"lat"} defined $args{"lon"}
Truth table100%3/3
A and B
A= defined $args{"lat"}B= defined $args{"lon"}
ABresult
0X0
100
111
751 1 Weather::API::Base::_verify_lat_lon(\%args);
752 } else {
753 croak("either both lat & lon, or either of city or zip parameters expected")
754 9 ▶ unless $args{city} || $args{zip};
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"city"} or $args{"zip"} 3 6 9
Condition100%3/3
$args{"city"} or $args{"zip"}
l!l&&r!l&&!r
513
MC/DC100%2/2
$args{"city"} or $args{"zip"}
$args{"city"} $args{"zip"}
Truth table100%3/3
A or B
A= $args{"city"}B= $args{"zip"}
ABresult
1X1
011
000
755 }
756  
757 7 return $self->_get_ua($self->_geo_url(%args));
758 }
759  
760 5 ▶sub icon_url {
Subroutine icon_url: called CC=3 SCAR=11.0
Pod documented
761 5 my $self = shift;
762 5 my $icon = shift;
763 5 my $sm = shift;
764  
765 5 ▶ return unless $icon;
Branch: 1 branch
BranchTrueFalseTotal
unless $icon 2 3 5
766  
767 3 ▶ $icon .= '@2x' unless $sm;
Branch: 1 branch
BranchTrueFalseTotal
unless $sm 2 1 3
768 3 return $self->{scheme} . "://openweathermap.org/img/wn/$icon.png";
769 }
770  
771 2 ▶sub icon_data {
Subroutine icon_data: called CC=3 SCAR=11.0
Pod documented
772 2 my $self = shift;
773 2 my $url = $self->icon_url(@_);
774  
775 2 ▶ if ($url) {
Branch: 1 branch
BranchTrueFalseTotal
if ($url) 1 1 2
776 1 my $res = $self->_get_ua($url);
777 1 ▶ return $res->content if $res->is_success;
Branch: 1 branch
BranchTrueFalseTotal
if $res->is_success 1 0 1
778 }
779  
780 1 return;
781 }
782  
783 43 ▶sub _preprocess_params {
Subroutine _preprocess_params: called CC=8 SCAR=20.8
784 43 my $self = shift;
785 43 my $api = shift;
786 43 my %args = @_;
787  
788 43 $args{q} = delete($args{loc});
789 43 ▶ if ($api eq 'one_call' || $api eq 'weather') {
Branch: 1 branch
BranchTrueFalseTotal
if ($api eq "one_call" or $api eq "weather") 22 21 43
Condition100%3/3
$api eq "one_call" or $api eq "weather"
l!l&&r!l&&!r
14821
MC/DC100%2/2
$api eq "one_call" or $api eq "weather"
$api eq "one_call" $api eq "weather"
Truth table100%3/3
A or B
A= $api eq "one_call"B= $api eq "weather"
ABresult
1X1
011
000
790 22 ▶ $args{$_} //= $self->{$_} for qw/lang units/;
Condition66%2/3
$args{$_} //= $self->{$_}
l!l&&r!l&&!r
8360
MC/DC0%0/2
$args{$_} //= $self->{$_}
$args{$_} $self->{$_}
Truth table66%2/3
A //= B
A= $args{$_}B= $self->{$_}
ABresult
1X1
011
000
791 22 ▶ delete $args{units} if $args{units} eq 'standard';
Branch: 1 branch
BranchTrueFalseTotal
if $args{"units"} eq "standard" 6 16 22
792 22 ▶ delete $args{lang} if $args{lang} && $args{lang} eq 'en';
Branch: 1 branch
BranchTrueFalseTotal
if $args{"lang"} and $args{"lang"} eq "en" 20 2 22
Condition100%3/3
$args{"lang"} and $args{"lang"} eq "en"
!ll&&!rl&&r
1120
MC/DC100%2/2
$args{"lang"} and $args{"lang"} eq "en"
$args{"lang"} $args{"lang"} eq "en"
Truth table100%3/3
A and B
A= $args{"lang"}B= $args{"lang"} eq "en"
ABresult
0X0
100
111
793 }
794 43 $args{appid} = $self->{key};
795  
796 43 return %args;
797 }
798  
799 40 ▶sub _get {
Subroutine _get: called CC=5 SCAR=16.1
800 40 my $self = shift;
801 40 my $wantarray = shift;
802 40 my $api = shift;
803 40 my %args = @_;
804  
805 40 ▶ $self->{output} = $args{mode} || 'json';
Condition100%2/2
$args{'mode'} || 'json'
l!l
238
MC/DC100%1/1
$args{'mode'} || 'json'
$args{'mode'}
Truth table100%2/2
A
A= $args{'mode'}
Aresult
11
00
806  
807 40 ▶ my $resp =
Branch: 3 branches
BranchTrueFalseTotal
$api eq 'one_call' ? : 13 27 40
$api eq 'weather' ? : 7 20 27
$api eq 'history' ? : 10 10 20
808 $api eq 'one_call' ? $self->one_call_response(%args)
809 : $api eq 'weather' ? $self->get_weather_response(%args)
810 : $api eq 'history' ? $self->get_history_response(%args)
811 : $self->geo_response(%args);
812  
813 23 return $self->_get_output($resp, $wantarray);
814 }
815  
816 13 ▶sub _geocode {
Subroutine _geocode: called CC=5 SCAR=16.1
817 13 my $self = shift;
818 13 my $args = shift;
819 13 ▶ return if defined $args->{lat} && defined $args->{lon};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{"lat"} and defined $args->{"lon"} 6 7 13
Condition100%3/3
defined $args->{"lat"} and defined $args->{"lon"}
!ll&&!rl&&r
616
MC/DC100%2/2
defined $args->{"lat"} and defined $args->{"lon"}
defined $args->{"lat"} defined $args->{"lon"}
Truth table100%3/3
A and B
A= defined $args->{"lat"}B= defined $args->{"lon"}
ABresult
0X0
100
111
820  
821 7 my @location = $self->geo(city => $args->{city}, zip => $args->{zip}, limit => 1);
822 5 ▶ croak("requested location not found") unless @location;
Branch: 1 branch
BranchTrueFalseTotal
unless @location 0 5 5
823 5 $args->{$_} = $location[0]->{$_} for qw/lat lon/;
824 }
825  
826 8 ▶sub _weather_url {
Subroutine _weather_url: called CC=5 SCAR=16.1
827 8 my $self = shift;
828 8 my %args = @_;
829 8 ▶ my $prod = delete $args{product} || 'current';
Condition100%2/2
delete $args{'product'} || 'current'
l!l
71
MC/DC100%1/1
delete $args{'product'} || 'current'
delete $args{'product'}
Truth table100%2/2
A
A= delete $args{'product'}
Aresult
11
00
830 8 my %products = (
831 current => 'weather',
832 forecast => 'forecast',
833 hourly => 'forecast/hourly',
834 daily => 'forecast/daily',
835 climate => 'forecast/climate',
836 );
837 8 my $sub = 'api';
838 8 ▶ $sub = 'pro' if $prod eq 'hourly' || $prod eq 'climate';
Branch: 1 branch
BranchTrueFalseTotal
if $prod eq "hourly" or $prod eq "climate" 3 5 8
Condition100%3/3
$prod eq "hourly" or $prod eq "climate"
l!l&&r!l&&!r
215
MC/DC100%2/2
$prod eq "hourly" or $prod eq "climate"
$prod eq "hourly" $prod eq "climate"
Truth table100%3/3
A or B
A= $prod eq "hourly"B= $prod eq "climate"
ABresult
1X1
011
000
839 croak('valid products: '.join(", ", keys %products))
840 8 ▶ unless $products{$prod};
Branch: 1 branch
BranchTrueFalseTotal
unless $products{$prod} 1 7 8
841  
842 7 return "$sub.openweathermap.org/data/2.5/$products{$prod}?" . _join_args(\%args);
843 }
844  
845 9 ▶sub _history_url {
Subroutine _history_url: called CC=3 SCAR=11.0
846 9 my $self = shift;
847 9 my %args = @_;
848 9 my $prod = delete $args{product};
849 9 my %products = (
850 hourly => 'history/city',
851 year => 'aggregated/year',
852 month => 'aggregated/month',
853 day => 'aggregated/day',
854 temp => 'history/accumulated_temperature',
855 precip => 'history/accumulated_precipitation',
856 );
857  
858 9 ▶ $args{type} = 'hour' if $prod eq 'hourly';
Branch: 1 branch
BranchTrueFalseTotal
if $prod eq "hourly" 3 6 9
859  
860 croak('valid products: '.join(", ", keys %products))
861 9 ▶ unless $products{$prod};
Branch: 1 branch
BranchTrueFalseTotal
unless $products{$prod} 1 8 9
862  
863 8 return "history.openweathermap.org/data/2.5/$products{$prod}?" . _join_args(\%args);
864 }
865  
866 4 ▶sub _onecall_url {
Subroutine _onecall_url: called CC=4 SCAR=13.9
867 4 my $self = shift;
868 4 my %args = @_;
869 4 ▶ my $prod = delete $args{product} || '';
Condition100%2/2
delete $args{'product'} || ''
l!l
22
MC/DC100%1/1
delete $args{'product'} || ''
delete $args{'product'}
Truth table100%2/2
A
A= delete $args{'product'}
Aresult
11
00
870 4 ▶ $prod = '/timemachine' if $prod eq 'historical';
Branch: 1 branch
BranchTrueFalseTotal
if $prod eq "historical" 1 3 4
871 4 ▶ $prod = '/day_summary' if $prod eq 'daily';
Branch: 1 branch
BranchTrueFalseTotal
if $prod eq "daily" 1 3 4
872  
873 4 return "api.openweathermap.org/data/3.0/onecall$prod?" . _join_args(\%args);
874 }
875  
876 7 ▶sub _geo_url {
Subroutine _geo_url: called CC=3 SCAR=11.0
877 7 my $self = shift;
878 7 my %args = @_;
879  
880 return "api.openweathermap.org/geo/1.0/reverse?" . _join_args(\%args)
881 7 ▶ if defined $args{lat} && defined $args{lon};
Branch: 1 branch
BranchTrueFalseTotal
if defined $args{"lat"} and defined $args{"lon"} 1 6 7
Condition66%2/3
defined $args{"lat"} and defined $args{"lon"}
!ll&&!rl&&r
601
MC/DC50%1/2
defined $args{"lat"} and defined $args{"lon"}
defined $args{"lat"} defined $args{"lon"}
Truth table66%2/3
A and B
A= defined $args{"lat"}B= defined $args{"lon"}
ABresult
0X0
100
111
882  
883 6 $args{q} = delete $args{city};
884 6 return "api.openweathermap.org/geo/1.0/direct?" . _join_args(\%args);
885 }
886  
887 26 ▶sub _join_args {
Subroutine _join_args: called CC=2 SCAR=6.9
888 26 my $args = shift;
889 26 ▶ return join "&", map {defined $args->{$_} ? "$_=$args->{$_}" : ()} keys %$args;
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{$_} ? : 92 21 113
890 }
891  
892 =head1 PERL WEATHER MODULES
893  
894 A quick listing of Perl modules for current weather and forecasts from various sources:
895  
896 =head2 OpenWeatherMap
897  
898 OpenWeatherMap uses various weather sources combined with their own ML and offers
899 a couple of free endpoints (the v2.5 current weather and 5d/3h forecast) with generous
900 request limits. Their newer One Call 3.0 API also offers some free usage (1000 calls/day)
901 and the cost is per call above that. If you want access to history APIs, extended
902 hourly forecasts etc, there are monthly subscriptions. If you want to access an API
903 that is missing from L<Weather::OWM>, feel free to ask the author.
904  
905 Note that there is an older L<Weather::OpenWeatherMap> module, but it is no longer
906 maintained and only supports the old (v2.5) Weather API. I looked into updating it
907 for my purposes, but it was more complex (returns objects, so a new object definition
908 is required per API endpoint added etc) and with more dependencies (including L<Moo>),
909 than what I wanted for such a module.
910  
911 =head2 Apple WeatherKit
912  
913 An alternative source for multi-source forecasts is Apple's WeatherKit (based on
914 the old Dark Sky weather API). It offers 500k calls/day for free, but requires a
915 paid Apple developer account. You can use L<Weather::WeatherKit>, which is very
916 similar to this module (same author).
917  
918 =head2 7Timer!
919  
920 If you are interested in astronomy/stargazing the 7Timer! weather forecast might be
921 useful. It uses the standard NOAA forecast, but calculates astronomical seeing and
922 transparency. It is completely free and can be accessed with L<Weather::Astro7Timer>,
923 which is another very similar to this module (same author).
924  
925 =head2 YR.no
926  
927 Finally, the Norwegian Meteorological Institute offers the free YR.no service, which
928 can be accessed via L<Weather::YR>, although I am not affiliated and have not tested
929 that module.
930  
931 =head1 AUTHOR
932  
933 Dimitrios Kechagias, C<< <dkechag at cpan.org> >>
934  
935 =head1 BUGS
936  
937 Please report any bugs or feature requests on L<GitHub|https://github.com/dkechag/Weather-OWM>.
938  
939 =head1 GIT
940  
941 L<https://github.com/dkechag/Weather-OWM>
942  
943 =head1 LICENSE AND COPYRIGHT
944  
945 This software is copyright (c) 2024 by Dimitrios Kechagias.
946  
947 This is free software; you can redistribute it and/or modify it under
948 the same terms as the Perl 5 programming language system itself.
949  
950 =cut
951  
952 3 1;
↑ Summary