blib/lib/Weather/Meteo.pm

filter: Statementstmt 99.3% 152 / 153 Branchbran 93.3% 56 / 60 Conditioncond 96.0% 48 / 50 MC/DCmcdc 88.8% 24 / 27 Subroutinesub 100% 19 / 19 Podpod 100% 3 / 3 totaltotal 96.7% 302 / 312 CC 49 SCAR 31.8
CC
49
Cov
97%
weather
39.0
new
8.0
ua
4.0
CRAP 24.2
↑ Summary
1 package Weather::Meteo;
2  
3 12 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 12 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 12 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 12 ▶use CHI;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 12 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 12 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 12 ▶use Object::Configure;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 12 ▶use Params::Get 0.13;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 12 ▶use Params::Validate::Strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 12 ▶use Return::Set;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 12 ▶use Scalar::Util;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 12 ▶use Time::HiRes;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 12 ▶use URI;
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 12 ▶use constant FIRST_YEAR => 1940;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 12 ▶use constant EXPIRES_IN => '1 hour';
Subroutine BEGIN: called CC=1 SCAR=0.0
20 12 ▶use constant MIN_INTERVAL => 0; # default: no rate-limiting delay
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 =head1 NAME
23  
24 Weather::Meteo - Interface to L<https://open-meteo.com> for historical weather data
25  
26 =head1 VERSION
27  
28 Version 0.14
29  
30 =cut
31  
32 12 our $VERSION = '0.14';
33  
34 =head1 SYNOPSIS
35  
36 The C<Weather::Meteo> module provides an interface to the Open-Meteo API for retrieving historical weather data from 1940.
37 It allows users to fetch weather information by specifying latitude, longitude, and a date.
38 The module supports object-oriented usage and allows customization of the HTTP user agent.
39  
40 use Weather::Meteo;
41  
42 my $meteo = Weather::Meteo->new();
43 my $weather = $meteo->weather({ latitude => 0.1, longitude => 0.2, date => '2022-12-25' });
44  
45 =over 4
46  
47 =item * Caching
48  
49 Identical requests are cached (using L<CHI> or a user-supplied caching object),
50 reducing the number of HTTP requests to the API and speeding up repeated queries.
51  
52 This module leverages L<CHI> for caching geocoding responses.
53 When a geocode request is made,
54 a cache key is constructed from the request.
55 If a cached response exists,
56 it is returned immediately,
57 avoiding unnecessary API calls.
58  
59 =item * Rate-Limiting
60  
61 A minimum interval between successive API calls can be enforced to ensure that the API is not overwhelmed and to comply with any request throttling requirements.
62  
63 Rate-limiting is implemented using L<Time::HiRes>.
64 A minimum interval between API
65 calls can be specified via the C<min_interval> parameter in the constructor.
66 Before making an API call,
67 the module checks how much time has elapsed since the
68 last request and,
69 if necessary,
70 sleeps for the remaining time.
71  
72 =back
73  
74 =head1 METHODS
75  
76 =head2 new
77  
78 my $meteo = Weather::Meteo->new();
79 my $ua = LWP::UserAgent->new();
80 $ua->env_proxy(1);
81 $meteo = Weather::Meteo->new(ua => $ua);
82  
83 my $weather = $meteo->weather({ latitude => 51.34, longitude => 1.42, date => '2022-12-25' });
84 my @snowfall = @{$weather->{'hourly'}->{'snowfall'}};
85  
86 print 'Number of cms of snow: ', $snowfall[1], "\n";
87  
88 Creates a new instance. Acceptable options include:
89  
90 =over 4
91  
92 =item * C<cache>
93  
94 A caching object.
95 If not provided,
96 an in-memory cache is created with a default expiration of one hour.
97  
98 =item * C<host>
99  
100 The API host endpoint.
101 Defaults to L<https://archive-api.open-meteo.com>.
102  
103 =item * C<min_interval>
104  
105 Minimum number of seconds to wait between API requests.
106 Defaults to C<0> (no delay).
107 Use this option to enforce rate-limiting.
108  
109 =item * C<ua>
110  
111 An object to use for HTTP requests.
112 If not provided, a default user agent is created.
113  
114 =back
115  
116 The class can be configured at runtime using environments and configuration files,
117 for example,
118 setting C<$ENV{'WEATHER__METEO__carp_on_warn'}> causes warnings to use L<Carp>.
119 For more information about runtime configuration,
120 see L<Object::Configure>.
121  
122 =head3 API specification
123  
124 =head4 Input
125  
126 All parameters are optional.
127 They may be supplied as a hashref or a flat key/value list.
128 When C<$class> is an existing C<Weather::Meteo> object the call clones it,
129 merging any supplied parameters.
130  
131 {
132 ua => { type => 'object', can => 'get', optional => 1 },
133 cache => { type => 'object', optional => 1 },
134 host => { type => 'scalar', optional => 1 },
135 min_interval => { type => 'scalar', optional => 1 },
136 }
137  
138 =head4 Output
139  
140 { type => 'object', isa => 'Weather::Meteo' }
141  
142 =head3 FORMAL SPECIFICATION
143  
144 ___ NEW ___________________________________________________
145 | class? : PACKAGE | Weather::Meteo |
146 | params? : NAME |--> VALUE |
147 |___________________________________________________________|
148 | result! : Weather::Meteo |
149 | |
150 | blessed(result!) = 'Weather::Meteo' |
151 | |
152 | params?.ua? => result!.ua = params?.ua |
153 | ~params?.ua => result!.ua : LWP::UserAgent |
154 | params?.cache? => result!.cache = params?.cache |
155 | ~params?.cache => result!.cache : CHI(Memory, global) |
156 | params?.host? => result!.host = params?.host |
157 | ~params?.host => result!.host = 'archive-api.open-meteo.com' |
158 | params?.min_interval? => result!.min_interval = params?.min_interval |
159 | ~params?.min_interval => result!.min_interval = 0 |
160 | result!.last_request = 0 |
161 |___________________________________________________________|
162 | |
163 | PRE: class? is PACKAGE name or blessed Weather::Meteo |
164 | POST: blessed(result!) = 'Weather::Meteo' |
165 | forall k in params? . result!.k = params?.k |
166 |___________________________________________________________|
167  
168 =cut
169  
170 sub new {
171 205 ▶ my $class = shift;
Subroutine new: called CC=8 SCAR=20.8
Pod documented
172 205 ▶ my $params = Params::Get::get_params(undef, \@_) || {};
Condition100%2/2
Params::Get::get_params(undef, \@_) || {}
l!l
11590
MC/DC100%1/1
Params::Get::get_params(undef, \@_) || {}
Params::Get::get_params(undef, \@_)
Truth table100%2/2
A
A= Params::Get::get_params(undef, \@_)
Aresult
11
00
173  
174 205 ▶ if(!defined($class)) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $class) { } 1 204 205
elsif (builtin::blessed($class)) { } 6 198 204
175 # Weather::Meteo::new() used rather than Weather::Meteo->new()
176 1 $class = __PACKAGE__;
177 } elsif(Scalar::Util::blessed($class)) {
178 # If $class is an object, clone it with new arguments
179 6 return bless { %{$class}, %{$params} }, ref($class);
180 }
181  
182 199 $params = Object::Configure::configure($class, $params);
183  
184 199 my $ua = $params->{ua};
185 199 ▶ if(!defined($ua)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $ua) 172 27 199
186 172 $ua = LWP::UserAgent->new(agent => __PACKAGE__ . "/$VERSION");
187 172 $ua->default_header(accept_encoding => 'gzip,deflate');
188 }
189 199 ▶ my $host = $params->{host} || 'archive-api.open-meteo.com';
Condition100%2/2
$params->{'host'} || 'archive-api.open-meteo.com'
l!l
6193
MC/DC100%1/1
$params->{'host'} || 'archive-api.open-meteo.com'
$params->{'host'}
Truth table100%2/2
A
A= $params->{'host'}
Aresult
11
00
190  
191 # Set up caching (default to an in-memory cache if none provided)
192 199 ▶ my $cache = $params->{cache} || CHI->new(
Condition66%2/3
$params->{'cache'} || 'CHI'->new('driver', 'Memory', 'global', 1, 'expires_in', '1 hour')
l!l&&r!l&&!r
104950
MC/DC0%0/2
$params->{'cache'} || 'CHI'->new('driver', 'Memory', 'global', 1, 'expires_in', '1 hour')
$params->{'cache'} 'CHI'->new('driver', 'Memory', 'global', 1, 'expires_in', '1 hour')
Truth table66%2/3
A || B
A= $params->{'cache'}B= 'CHI'->new('driver', 'Memory', 'global', 1, 'expires_in', '1 hour')
ABresult
1X1
011
000
193 driver => 'Memory',
194 global => 1,
195 expires_in => EXPIRES_IN,
196 );
197  
198 # Set up rate-limiting: minimum interval between requests (in seconds)
199 199 ▶ my $min_interval = $params->{min_interval} || MIN_INTERVAL;
Condition100%2/2
$params->{'min_interval'} || 0
l!l
6193
MC/DC100%1/1
$params->{'min_interval'} || 0
$params->{'min_interval'}
Truth table100%2/2
A
A= $params->{'min_interval'}
Aresult
11
00
200  
201 return bless {
202 min_interval => $min_interval,
203 last_request => 0, # Initialize last_request timestamp
204 199 %{$params},
205 cache => $cache,
206 host => $host,
207 ua => $ua
208 }, $class;
209 }
210  
211 =head2 weather
212  
213 use Geo::Location::Point;
214  
215 my $ramsgate = Geo::Location::Point->new({ latitude => 51.34, longitude => 1.42 });
216 # Print snowfall at 1AM on Christmas morning in Ramsgate
217 $weather = $meteo->weather($ramsgate, '2022-12-25');
218 @snowfall = @{$weather->{'hourly'}->{'snowfall'}};
219  
220 print 'Number of cms of snow: ', $snowfall[1], "\n";
221  
222 use DateTime;
223 my $dt = DateTime->new(year => 2024, month => 2, day => 1);
224 $weather = $meteo->weather({ location => $ramsgate, date => $dt });
225  
226 The date argument can be an ISO-8601 formatted date,
227 or an object that understands the strftime method.
228  
229 Takes an optional argument, tz, containing the time zone.
230 If not given, the module tries to work it out from the given location,
231 for that to work set TIMEZONEDB_KEY to be your API key from L<https://timezonedb.com>.
232 If all else fails, the module falls back to Europe/London.
233  
234 Dates before 1940 return C<undef> silently.
235 Invalid date strings cause a C<carp> and return C<undef>.
236 Missing required arguments or non-numeric coordinates cause a C<croak>.
237  
238 On success returns a hashref containing at minimum the key C<hourly>.
239 Returns C<undef> if the API returns an error, if the JSON cannot be
240 parsed, or if the response contains no C<hourly> key.
241  
242 =head3 API specification
243  
244 =head4 Input
245  
246 Three call forms are accepted.
247  
248 # Form 1 and 2 -- hashref or flat list
249 {
250 latitude => { type => 'scalar' },
251 longitude => { type => 'scalar' },
252 date => { type => 'scalar | object' },
253 tz => { type => 'scalar', optional => 1 },
254 location => { type => 'object', can => 'latitude', optional => 1 },
255 }
256  
257 # Form 3 -- positional: ($location_obj, $date)
258 # $location_obj must respond to latitude() and longitude()
259  
260 =head4 Output
261  
262 { type => 'hashref', min => 1 } # success -- contains 'hourly' key
263 undef # pre-1940 date, bad input, or API error
264  
265 =head3 FORMAL SPECIFICATION
266  
267 ___ WEATHER _______________________________________________
268 | self? : Weather::Meteo |
269 | latitude? : REAL |
270 | longitude? : REAL |
271 | date? : DATE_STRING | strftime_OBJECT |
272 | tz? : STRING (optional, default 'Europe/London')|
273 |____________________________________________________________|
274 | result! : HASHREF | undef |
275 |____________________________________________________________|
276 | |
277 | PRE (~latitude? v ~longitude? v ~date?) |
278 | => croak /Usage: weather\(latitude/ |
279 | |
280 | PRE lat? or lon? not matching /^-?\d+(\.\d+)?$/ |
281 | (after leading-decimal normalisation) |
282 | => croak /Invalid latitude\/longitude format/ |
283 | |
284 | PRE date? blessed ^ date?.can('strftime') |
285 | => date? := date?.strftime('%F') |
286 | PRE date? !~ /^\d{4}-\d{2}-\d{2}$/ |
287 | => croak /Invalid date format. Expected YYYY-MM-DD/ |
288 | |
289 | PRE year(date?) < 1940 |
290 | => result! = undef |
291 | |
292 | POST cache hit for (lat, lon, date, tz) |
293 | => result! = cached_value |
294 | |
295 | POST HTTP error response |
296 | => carp msg ^ result! = undef |
297 | |
298 | POST JSON parse failure |
299 | => carp /Failed to parse JSON response/ ^ result! = undef |
300 | |
301 | POST response.error = true |
302 | => result! = undef |
303 | |
304 | POST ~response.hourly |
305 | => result! = undef |
306 | |
307 | POST otherwise |
308 | => result! = { hourly => HOURLY, daily => DAILY } |
309 | cache.set(key, result!) |
310 |____________________________________________________________|
311  
312 =cut
313  
314 sub weather
315 {
316 176 ▶ my $self = shift;
Subroutine weather: called CC=39 SCAR=36.6
Pod documented
317 176 my $params;
318  
319 176 ▶ if((scalar(@_) == 2) && Scalar::Util::blessed($_[0]) && ($_[0]->can('latitude'))) {
Branch: 1 branch
BranchTrueFalseTotal
if (scalar @_ == 2 and builtin::blessed($_[0]) and $_[0]->can('latitude')) { } 10 166 176
Condition100%6/6
scalar @_ == 2 and builtin::blessed($_[0]) and $_[0]->can("latitude")
!ll&&!rl&&r
165110
scalar @_ == 2 and builtin::blessed($_[0])
!ll&&!rl&&r
164111
MC/DC100%3/3
scalar @_ == 2 and builtin::blessed($_[0]) and $_[0]->can("latitude")
scalar @_ == 2 builtin::blessed($_[0]) $_[0]->can("latitude")
Truth table100%4/4
A and B and C
A= scalar @_ == 2B= builtin::blessed($_[0])C= $_[0]->can("latitude")
ABCresult
0XX0
10X0
1100
1111
320 # Two arguments - a location object and a date
321 10 my $location = $_[0];
322 10 $params->{latitude} = $location->latitude();
323 10 $params->{longitude} = $location->longitude();
324 10 $params->{'date'} = $_[1];
325 10 ▶ if($_[0]->can('tz') && $ENV{'TIMEZONEDB_KEY'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($_[0]->can("tz") and $ENV{"TIMEZONEDB_KEY"}) 2 8 10
Condition100%3/3
$_[0]->can("tz") and $ENV{"TIMEZONEDB_KEY"}
!ll&&!rl&&r
622
MC/DC100%2/2
$_[0]->can("tz") and $ENV{"TIMEZONEDB_KEY"}
$_[0]->can("tz") $ENV{"TIMEZONEDB_KEY"}
Truth table100%3/3
A and B
A= $_[0]->can("tz")B= $ENV{"TIMEZONEDB_KEY"}
ABresult
0X0
100
111
326 2 $params->{'tz'} = $_[0]->tz();
327 }
328 } else {
329 166 $params = Params::Get::get_params(undef, \@_);
330 }
331  
332 174 my $latitude = $params->{latitude};
333 174 my $longitude = $params->{longitude};
334 174 my $location = $params->{'location'};
335 174 my $date = $params->{'date'};
336 174 ▶ my $tz = $params->{'tz'} || 'Europe/London';
Condition100%2/2
$params->{'tz'} || 'Europe/London'
l!l
6168
MC/DC100%1/1
$params->{'tz'} || 'Europe/London'
$params->{'tz'}
Truth table100%2/2
A
A= $params->{'tz'}
Aresult
11
00
337  
338 174 ▶ if((!defined($latitude)) && defined($location) &&
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $latitude and defined $location and builtin::blessed($location) and $location->can("latitude")) 2 172 174
Condition100%9/9
not defined $latitude and defined $location and builtin::blessed($location) and $location->can("latitude")
!ll&&!rl&&r
17112
not defined $latitude and defined $location and builtin::blessed($location)
!ll&&!rl&&r
17013
not defined $latitude and defined $location
!ll&&!rl&&r
16284
MC/DC100%4/4
not defined $latitude and defined $location and builtin::blessed($location) and $location->can("latitude")
not defined $latitude defined $location builtin::blessed($location) $location->can("latitude")
Truth table100%5/5
not(A) and B and C and D
A= not defined $latitudeB= defined $locationC= builtin::blessed($location)D= $location->can("latitude")
ABCDresult
0XXX0
10XX0
110X0
11100
11111
339 Scalar::Util::blessed($location) && $location->can('latitude')) {
340 2 $latitude = $location->latitude();
341 2 $longitude = $location->longitude();
342 }
343 174 ▶ if((!defined($latitude)) || (!defined($longitude)) || (!defined($date))) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $latitude and defined $longitude and defined $date) 7 157 164
Condition100%6/6
defined $latitude and defined $longitude and defined $date
!ll&&!rl&&r
143157
defined $latitude and defined $longitude
!ll&&!rl&&r
104160
MC/DC100%3/3
defined $latitude and defined $longitude and defined $date
defined $latitude defined $longitude defined $date
Truth table100%4/4
A and B and C
A= defined $latitudeB= defined $longitudeC= defined $date
ABCresult
0XX0
10X0
1100
1111
344 17 ▶ if(my $logger = $self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $self->{"logger"}) 17 0 17
345 17 $logger->error('Usage: weather(latitude => $latitude, longitude => $longitude, date => "YYYY-MM-DD")');
346 }
347 17 Carp::croak('Usage: weather(latitude => $latitude, longitude => $longitude, date => "YYYY-MM-DD")');
348 0 return;
349 }
350  
351 # Handle numbers starting with a decimal point
352 157 ▶ if($latitude =~ /^\./) {
Branch: 1 branch
BranchTrueFalseTotal
if ($latitude =~ /^\./) 2 155 157
353 2 $latitude = "0$latitude";
354 }
355 157 ▶ if($latitude =~ /^\-\.(\d+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($latitude =~ /^\-\.(\d+)$/) 1 156 157
356 1 $latitude = "-0.$1";
357 }
358 157 ▶ if($longitude =~ /^\./) {
Branch: 1 branch
BranchTrueFalseTotal
if ($longitude =~ /^\./) 2 155 157
359 2 $longitude = "0$longitude";
360 }
361 157 ▶ if($longitude =~ /^\-\.(\d+)$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($longitude =~ /^\-\.(\d+)$/) 1 156 157
362 1 $longitude = "-0.$1";
363 }
364  
365 157 ▶ if(($latitude !~ /^-?\d+(\.\d+)?$/) || ($longitude !~ /^-?\d+(\.\d+)?$/)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($latitude =~ /^-?\d+(\.\d+)?$/ and $longitude =~ /^-?\d+(\.\d+)?$/) 12 145 157
Condition100%3/3
$latitude =~ /^-?\d+(\.\d+)?$/ and $longitude =~ /^-?\d+(\.\d+)?$/
!ll&&!rl&&r
102145
MC/DC100%2/2
$latitude =~ /^-?\d+(\.\d+)?$/ and $longitude =~ /^-?\d+(\.\d+)?$/
$latitude =~ /^-?\d+(\.\d+)?$/ $longitude =~ /^-?\d+(\.\d+)?$/
Truth table100%3/3
A and B
A= $latitude =~ /^-?\d+(\.\d+)?$/B= $longitude =~ /^-?\d+(\.\d+)?$/
ABresult
0X0
100
111
366 12 ▶ if(my $logger = $self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $self->{"logger"}) 12 0 12
367 12 $logger->error(__PACKAGE__ . ": Invalid latitude/longitude format ($latitude, $longitude)");
368 }
369 12 Carp::croak(__PACKAGE__, ": Invalid latitude/longitude format ($latitude, $longitude)");
370 }
371  
372 145 ▶ if(Scalar::Util::blessed($date) && $date->can('strftime')) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($date) and $date->can('strftime')) { } 5 140 145
elsif ($date =~ /^(\d{4})-/) { } 130 10 140
Condition66%2/3
builtin::blessed($date) and $date->can("strftime")
!ll&&!rl&&r
14005
MC/DC50%1/2
builtin::blessed($date) and $date->can("strftime")
builtin::blessed($date) $date->can("strftime")
Truth table66%2/3
A and B
A= builtin::blessed($date)B= $date->can("strftime")
ABresult
0X0
100
111
373 5 $date = $date->strftime('%F');
374 } elsif($date =~ /^(\d{4})-/) {
375 130 ▶ return if($1 < FIRST_YEAR);
Branch: 1 branch
BranchTrueFalseTotal
if $1 < 1940 6 124 130
376 } else {
377 10 Carp::carp("'$date' is not a valid date");
378 10 return;
379 }
380  
381 129 ▶ unless($date =~ /^\d{4}-\d{2}-\d{2}$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($date =~ /^\d{4}-\d{2}-\d{2}$/) 7 122 129
382 7 ▶ if(my $logger = $self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $self->{"logger"}) 7 0 7
383 7 $logger->error('Invalid date format. Expected YYYY-MM-DD');
384 }
385 7 croak('Invalid date format. Expected YYYY-MM-DD');
386 }
387  
388 122 my $uri = URI->new("https://$self->{host}/v1/archive");
389 122 my %query_parameters = (
390 'latitude' => $latitude,
391 'longitude' => $longitude,
392 'start_date' => $date,
393 'end_date' => $date,
394 'hourly' => 'temperature_2m,rain,snowfall,weathercode',
395 'daily' => 'weathercode,temperature_2m_max,temperature_2m_min,rain_sum,snowfall_sum,precipitation_hours,windspeed_10m_max,windgusts_10m_max',
396 'timezone' => $tz,
397 # https://stackoverflow.com/questions/16086962/how-to-get-a-time-zone-from-a-location-using-latitude-and-longitude-coordinates
398 'windspeed_unit' => 'mph',
399 'precipitation_unit' => 'inch'
400 );
401  
402 122 $uri->query_form(%query_parameters);
403 122 my $url = $uri->as_string();
404  
405 122 $url =~ s/%2C/,/g;
406  
407 # Create a cache key based on the location, date and time zone (might want to use a stronger hash function if needed)
408 122 my $cache_key = "weather:$latitude:$longitude:$date:$tz";
409 122 ▶ if(my $cached = $self->{cache}->get($cache_key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cached = $self->{"cache"}->get($cache_key)) 17 105 122
410 17 return $cached;
411 }
412  
413 # Enforce rate-limiting: ensure at least min_interval seconds between requests
414 105 my $now = time();
415 105 my $elapsed = $now - $self->{last_request};
416 105 ▶ if($elapsed < $self->{min_interval}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($elapsed < $self->{"min_interval"}) 2 103 105
417 2 Time::HiRes::sleep($self->{min_interval} - $elapsed);
418 }
419  
420 105 my $res = $self->{ua}->get($url);
421  
422 # Update last_request timestamp
423 105 $self->{last_request} = time();
424  
425 105 ▶ unless(defined($res) && ref($res) && $res->can('is_error')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $res and ref $res and $res->can("is_error")) 5 98 103
Condition100%6/6
defined $res and ref $res and $res->can("is_error")
!ll&&!rl&&r
5298
defined $res and ref $res
!ll&&!rl&&r
23100
MC/DC100%3/3
defined $res and ref $res and $res->can("is_error")
defined $res ref $res $res->can("is_error")
Truth table100%4/4
A and B and C
A= defined $resB= ref $resC= $res->can("is_error")
ABCresult
0XX0
10X0
1100
1111
426 7 Carp::carp(ref($self) . ': UA->get did not return a valid HTTP response');
427 7 return;
428 }
429  
430 98 ▶ if($res->is_error()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->is_error) 5 93 98
431 5 Carp::carp(ref($self), ": $url API returned error: ", $res->status_line());
432 5 return;
433 }
434 # $res->content_type('text/plain'); # May be needed to decode correctly
435  
436 93 my $rc;
437 93 eval { $rc = JSON::MaybeXS->new()->utf8()->decode($res->decoded_content()) };
438 93 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 7 86 93
439 7 Carp::carp("Failed to parse JSON response: $@");
440 7 return;
441 }
442  
443 86 ▶ if($rc && (ref($rc) eq 'HASH')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rc and ref $rc eq "HASH") 84 2 86
Condition100%3/3
$rc and ref $rc eq "HASH"
!ll&&!rl&&r
1184
MC/DC100%2/2
$rc and ref $rc eq "HASH"
$rc ref $rc eq "HASH"
Truth table100%3/3
A and B
A= $rcB= ref $rc eq "HASH"
ABresult
0X0
100
111
444 84 ▶ if($rc->{'error'}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rc->{"error"}) 3 81 84
445 # TODO: print error code
446 3 return;
447 }
448 81 ▶ if(defined($rc->{'hourly'})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $rc->{"hourly"}) 77 4 81
449 # Cache the result before returning it
450 77 $self->{'cache'}->set($cache_key, $rc);
451  
452 77 return Return::Set::set_return($rc, { type => 'hashref', min => 1 }); # No support for list context, yet
453 }
454 }
455  
456 6 return;
457 }
458  
459 =head2 ua
460  
461 Accessor method to get and set UserAgent object used internally.
462 You can call I<env_proxy> for example, to get the proxy information from
463 environment variables:
464  
465 $meteo->ua()->env_proxy(1);
466  
467 You can also set your own User-Agent object:
468  
469 use LWP::UserAgent::Throttled;
470  
471 my $ua = LWP::UserAgent::Throttled->new();
472 $ua->throttle('open-meteo.com' => 1);
473 $meteo->ua($ua);
474  
475 =head3 API specification
476  
477 =head4 Input
478  
479 When called with no arguments acts as a getter; the input schema is empty.
480 When called with an argument the argument must be an object that responds to C<get>:
481  
482 { ua => { type => 'object', can => 'get' } }
483  
484 =head4 Output
485  
486 { type => 'object', can => 'get' }
487  
488 =head3 FORMAL SPECIFICATION
489  
490 ___ UA ____________________________________________________
491 | self? : Weather::Meteo |
492 | ua? : OBJECT [can 'get'] (optional) |
493 |____________________________________________________________|
494 | result! : OBJECT [can 'get'] |
495 |____________________________________________________________|
496 | |
497 | PRE ua? defined ^ ~ua?.can('get') |
498 | => croak /must be an object that understands the get method/ |
499 | |
500 | POST ua? defined |
501 | => self?.ua = ua? ^ result! = ua? |
502 | |
503 | POST ~ua? |
504 | => result! = self?.ua (no state change) |
505 |____________________________________________________________|
506  
507 =cut
508  
509 sub ua {
510 37 ▶ my $self = shift;
Subroutine ua: called CC=4 SCAR=13.9
Pod documented
511  
512 37 ▶ if (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 20 17 37
513 20 my $params = Params::Validate::Strict::validate_strict({
514 args => Params::Get::get_params('ua', \@_),
515 schema => {
516 ua => {
517 type => 'object',
518 can => 'get'
519 }
520 }
521 });
522 # Reject undef explicitly before it silently corrupts $self->{ua}
523 10 ▶ if(!$params->{ua}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($params->{"ua"}) 1 9 10
524 1 ▶ if(my $logger = $self->{'logger'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $logger = $self->{"logger"}) 1 0 1
525 1 $logger->error('ua() requires a defined value')
526 }
527 1 Carp::croak('ua() requires a defined value')
528 }
529 9 $self->{ua} = $params->{ua};
530 }
531 26 return $self->{ua};
532 }
533  
534 =head1 AUTHOR
535  
536 Nigel Horne, C<< <njh@nigelhorne.com> >>
537  
538 This library is free software; you can redistribute it and/or modify
539 it under the same terms as Perl itself.
540  
541 Lots of thanks to the folks at L<https://open-meteo.com>.
542  
543 =head1 BUGS
544  
545 Please report any bugs or feature requests to C<bug-weather-meteo at rt.cpan.org>,
546 or through the web interface at
547 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Weather-Meteo>.
548 I will be notified, and then you'll
549 automatically be notified of progress on your bug as I make changes.
550  
551 =head1 SEE ALSO
552  
553 =over 4
554  
555 =item * L<Test Dashboard|https://nigelhorne.github.io/Weather-Meteo/coverage/>
556  
557 =item * Open Meteo API: L<https://open-meteo.com/en/docs#api_form>
558  
559 =item * L<Object::Configure>
560  
561 =back
562  
563 =head1 SUPPORT
564  
565 This module is provided as-is without any warranty.
566  
567 You can find documentation for this module with the perldoc command.
568  
569 perldoc Weather::Meteo
570  
571 You can also look for information at:
572  
573 =over 4
574  
575 =item * MetaCPAN
576  
577 L<https://metacpan.org/release/Weather-Meteo>
578  
579 =item * RT: CPAN's request tracker
580  
581 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Weather-Meteo>
582  
583 =item * CPANTS
584  
585 L<http://cpants.cpanauthors.org/dist/Weather-Meteo>
586  
587 =item * CPAN Testers' Matrix
588  
589 L<http://matrix.cpantesters.org/?dist=Weather-Meteo>
590  
591 =item * CPAN Testers Dependencies
592  
593 L<http://deps.cpantesters.org/?module=Weather-Meteo>
594  
595 =back
596  
597 =head1 LICENSE AND COPYRIGHT
598  
599 Copyright 2023-2026 Nigel Horne.
600  
601 Usage is subject to the GPL2 licence terms.
602 If you use it,
603 please let me know.
604  
605 =cut
606  
607 12 1;
↑ Summary