lib/Weather/PurpleAir/API.pm

filter: Statementstmt 12.7% 31 / 243 Branchbran 0.0% 0 / 110 Conditioncond 0.0% 0 / 65 MC/DCmcdc 0.0% 0 / 40 Subroutinesub 33.3% 9 / 27 Podpod 26.3% 5 / 19 totaltotal 8.9% 45 / 504 CC 92 SCAR 56.9
CC
92
Cov
7%
gather_sensors
650.0
guess_best_aqi
650.0
in
110.0
CRAP 297.2
↑ Summary
1 package Weather::PurpleAir::API;
2  
3 ## ABSTRACT: Client for using the purpleair.com air quality sensor API
4  
5 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use v5.10.0; # provides "say" and "state"
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 1 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use File::Valet;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use HTTP::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use Time::HiRes;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 1 ▶use String::Similarity qw(similarity);
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 1 our $VERSION = '0.09';
16  
17 # Litchfield 38887 38888 City of Santa Rosa Laguna Treatment Plant 22961 22962 Geek Orchard 26363 26364
18  
19 =head1 NAME
20  
21 Weather::PurpleAir::API -- Client interface to Purple Air air quality API [DEPRECATED]
22  
23 =head1 SYNOPSIS
24  
25 use Weather::PurpleAir::API;
26 use Data::Dumper;
27  
28 my $api = Weather::PurpleAir::API->new();
29 my @sensors = qw(38887 22961 26363);
30 my $report = $api->report(\@sensors);
31 for my $sensor_name (keys %$report) {
32 print join("\t", ($sensor_name, @{$report->{$sensor_name}})), "\n";
33 }
34  
35 =head1 DESCRIPTION
36  
37 B<IMPORTANT!!> C<Weather::PurpleAir::API> is deprecated! The PurpleAir team turned off their old API, and have set up a totally new API. A re-implementation of C<Weather::PurpleAir::API> for the new API is in progress, and will replace this module (which is now useless).
38  
39 C<Weather::PurpleAir::API> provides a convenient interface to the Purple Air air quality API. It will
40 pull down data for specified sensors, transform them as desired (for instance, converting from raw
41 PM2.5 concentration to USA EPA AQI number, averaging results from dual-sensor nodes, etc) and provide
42 a concise report by sensor name.
43  
44 The Purple Air map of sensors is located at L<https://www.purpleair.com/map>.
45  
46 This module is very much a work in progress and 0.x releases might not be suitable for use.
47  
48 For a simple commandline script wrapping this module, see C<bin/aqi> in this package.
49  
50 Please do not poll sensors too frequently or the Purple Air server might block your IP.
51  
52 =head1 PACKAGE ATTRIBUTES
53  
54 =over 4
55  
56 =item C<$Weather::PurpleAir::API::VERSION> (string)
57  
58 The version number of this package (#.## format).
59  
60 =back
61  
62 =head1 OBJECT ATTRIBUTES
63  
64 =over 4
65  
66 =item C<sensor_hr> (hashref)
67  
68 Keys on sensor ID numbers, maps to sensor names.
69  
70 It is empty until the C<report()> method is called.
71  
72 =item C<name_hr> (hashref)
73  
74 Keys on sensor names, maps to sensor ID numbers.
75  
76 It is empty until the C<report()> method is called.
77  
78 =item C<ok> (string)
79  
80 Indicates status of most recent operation: "OK", "WARNING" or "ERROR".
81  
82 =over 4
83  
84 * "OK" means everything completed as expected.
85  
86 * "WARNING" means everything completed and possibly-useful data was returned, but something suspicious happened.
87  
88 * "ERROR" means something went horribly wrong and the operation was unable to complete.
89  
90 =back
91  
92 =item C<err> (string or arrayref)
93  
94 Set by WARNING and ERROR conditions, describes details of what went wrong.
95  
96 =item C<n_err> (integer)
97  
98 Incremented every time an error occurs.
99  
100 =item C<n_warn> (integer)
101  
102 Incremented every time a warning occurs.
103  
104 =item C<ex> (exception or exception string)
105  
106 Set to $@ when an exception is caught (for instance, when a JSON string does not decode).
107  
108 =item C<js_or> (C<JSON::MaybeXS> object reference)
109  
110 Contains a reference to the JSON decoder object used internally. May be overridden by the user when different behavior is desired. The default instance has parameters C<ascii =E<gt> 1, allow_nonref =E<gt> 1, space_after =E<gt> 1>.
111  
112 =back
113  
114 =head1 METHODS
115  
116 All functionality is available via a C<Weather::PurpleAir::API> object. Start with C<new> and
117 use the resulting object to generate reports. Additional functionality (like finding sensors
118 by name, or finding sensors near locations) will come in future releases.
119  
120 =head2 C<new(%options)>
121  
122 Instantiates and returns a C<Weather::PurpleAir::API> object. Options passed here may be overridden
123 by passing options to methods of the object.
124  
125 All options have hopefully-sane defaults:
126  
127 =over 4
128  
129 =item C<api_url> =E<gt> string
130  
131 Override the URL at which the API is queried. Useful for testing, or if you have your own server.
132  
133 Default is "https://www.purpleair.com/json?show=", to which the sensor ID is appended by the C<sensor_url> method.
134  
135 =item C<average> =E<gt> 0 or 1
136  
137 Averages AQI metrics from a node's sensors instead of returning the AQI metrics from each sensor in a node.
138  
139 Default is 0 (do not average).
140  
141 =item C<d> =E<gt> 0 or 1
142  
143 Activate debugging logic, which will print horribly confusing things to STDOUT. Default is 0 (off).
144  
145 =item C<g> =E<gt> 0 or 1
146  
147 Indicate that reports should include a "GUESSING" entry, providing a pruned average of all results from all sensors. In future releases it might incorporate other heuristics (like using older cached values when bad metrics are detected).
148  
149 The format of this entry is a little different from the sensor entries. Instead of $report->{GUESSING} referring
150 to an array of AQI metrics, it refers to an array containing the guessed gestalt AQI metric and its standard
151 deviation (a measure of statistical skew). The higher the standard deviation, the lower the confidence you
152 should have in the guessed metric.
153  
154 For example:
155  
156 { GUESSING => [123.45, 1.09] } # AQI is 123.45, with high confidence
157 { GUESSING => [123.45, 10.3] } # AQI is 123.45, with somewhat less confidence
158 { GUESSING => [123.45, 67.5] } # AQI is 123.45, with very low confidence!
159  
160 Default is 0 (do not guess).
161  
162 =item C<http_or> =E<gt> HTTP::Tiny object
163  
164 Provide the C<HTTP::Tiny> instance used to query the API. This is useful when you need to customize the query timeout, set a user agent string or specify an https proxy.
165  
166 Default is undef (an C<HTTP::Tiny> object will be instantiated internally).
167  
168 =item C<no_errors> =E<gt> 0 or 1
169  
170 Set this to suppress writing error messages to stderr. Default is 0 (errors will be displayed).
171  
172 =item C<no_warnings> =E<gt> 0 or 1
173  
174 Set this to suppress writing warning messages to stderr. Default is 0 (warnings will be displayed).
175  
176 =item C<now> =E<gt> 0 or 1
177  
178 Normally reports will use the ten-minute average AQI from each sensor. Specify C<now> to use the current AQI instead.
179  
180 Default is 0 (report will use ten-minute average AQI metrics).
181  
182 =item C<prune_threshold> =E<gt> fraction between 0 and 1
183  
184 When the C<g> (GUESSING) option is set, the guessing heuristic may prune more then one high and one low outlier
185 from the sensor data, if doing so will leave sufficient data left over for meaningful averaging. The prune
186 threshold determines how close to an outlier other data points must be, as a fraction of the outlier value, for
187 them to be pruned as well.
188  
189 For instance, if C<prune_threshold> = 0.1 (10%) and the high outlier is 90, then 90 * 0.1 = 9, so data points
190 which are 81 or higher might also be pruned. If C<prune_threshold> = 0.05 (5%) and the high outlier is 90,
191 90 * 0.05 = 4.5, so data points which are 85.5 or higher might be pruned, etc.
192  
193 Default is 0.1 (10%).
194  
195 =item C<q> =E<gt> 0 or 1
196  
197 "C<q>" is for "quiet". Setting this is equivalent to setting C<no_errors> and C<no_warnings>.
198  
199 Default is 0.
200  
201 =item C<raw> =E<gt> 0 or 1
202  
203 When set, C<report> will not convert the API's raw concentration numbers to USA EPA PM2.5 AQI scores (the
204 metric displayed on the Purple Air website map). Part-per-million concentrations of 2.5 micrometer diameter
205 particles will be provided instead.
206  
207 Default is 0 (concentrations will be converted to USA EPA PM2.5 AQI scores).
208  
209 =item C<sensor> =E<gt> ID-number
210  
211 =item C<sensor> =E<gt> [ID-number, ID-number, ...]
212  
213 =item C<sensor> =E<gt> "ID-number ID-number ..."
214  
215 Normally sensor IDs are passed to the C<report> method, but a default sensor or sensors can also be given
216 to C<new> at object instantiation time.
217  
218 Right now C<Weather::PurpleAir::API> can only work with numeric sensor IDs and there isn't a really good
219 way to find the IDs of sensors. If you point a browser at the Purple Air map, some browsers will expose
220 the IDs of specific sensors and others will not.
221  
222 If you download the all-sensors blob (either from the API at L<https://www.purpleair.com/json> or the
223 cached blob at L<http://ciar.org/h/sensors.all.json>) you can pick through the list and find IDs of
224 sensors of interest, which is a pain in the ass.
225  
226 Future releases of C<Weather::PurpleAir::API> will support functions for finding sensors near a location,
227 but this one doesn't, which is one of the reasons it's a 0.x release.
228  
229 Some example sensors and their IDs:
230  
231 25407 Gravenstein School
232 38887 Litchfield
233 22961 City Of Santa Rosa Laguna Treatment Plant
234 26363 Geek Orchard
235  
236 The default is 25407 (Gravenstein School, in Sonoma County, California)
237  
238 =item C<stash_path> =E<gt> path string
239  
240 When a C<stash_path> is provided, C<report> will store a copy of each sensor's JSON blob in the
241 specified directory, under the name C<aqi.$sensor_id.json>.
242  
243 For example, if C<stash_path> = "/tmp" and C<sensor> = 25407, the JSON blob will be stored in file
244 "/tmp/aqi.25407.json".
245  
246 The default is undef (not set, will not stash).
247  
248 =item C<temperature> =E<gt> "C" or "F"
249  
250 Also display the sensor's reported temperature, in either degrees Celsius or Fahrenheit.
251  
252 =item C<v> =E<gt> 0 or 1
253  
254 "C<v>" is for verbosity. When set, the reported-upon sensors (and gestalt guess, when C<g> parameter is
255 set) will be printed to stdout. This is normally set by the C<bin/aqi> utility.
256  
257 Future releases might implement higher verbosity levels.
258  
259 The default is 0 (do not print to stdout).
260  
261 =back
262  
263 =cut
264  
265 1 ▶sub new {
Subroutine new: called CC=3 SCAR=14.2
Pod documented
266 1 my ($class, %opt_hr) = @_;
267 1 my $self = {
268 opt_hr => \%opt_hr,
269 ok => 'OK',
270 ex => undef, # stash caught exceptions here
271 n_err => 0,
272 n_warn => 0,
273 err => '',
274 err_ar => [],
275 js_or => JSON::MaybeXS->new(ascii => 1, allow_nonref => 1, space_after => 1),
276 sensor_hr=> {},
277 name_hr => {},
278 };
279 1 bless ($self, $class);
280  
281 # convert keys of form "some-parameter" to "some_parameter":
282 1 foreach my $k0 (keys %{$self->{opt_hr}}) {
283 0 my $k1 = join('_', split(/-/, $k0));
284 0 ▶ next if ($k0 eq $k1);
Branch: 1 branch
BranchTrueFalseTotal
if $k0 eq $k1 0 0 0
285 0 $self->{opt_hr}->{$k1} = $self->{opt_hr}->{$k0};
286 0 delete $self->{opt_hr}->{$k0};
287 }
288  
289 1 return $self;
290 }
291  
292 0 ▶sub safely_to_json {
Subroutine safely_to_json: not called CC=2 SCAR=17.9
Pod undocumented
293 0 my ($self, $r) = @_;
294 0 my $js = eval { $self->{js_or}->encode($r); };
295 0 ▶ $self->{ex} = $@ unless(defined($js));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $js 0 0 0
296 0 return $js;
297 }
298  
299 0 ▶sub safely_from_json {
Subroutine safely_from_json: not called CC=2 SCAR=17.9
Pod undocumented
300 0 my ($self, $js) = @_;
301 0 my $r = eval { $self->{js_or}->decode($js); };
302 0 ▶ return $r if (defined $r);
Branch: 1 branch
BranchTrueFalseTotal
if defined $r 0 0 0
303 0 $self->{ex} = $@;
304 0 $self->err("JSON decode failed", $@);
305 0 return;
306 }
307  
308 0 ▶sub most_similar {
Subroutine most_similar: not called CC=4 SCAR=30.0
Pod undocumented
309 0 my ($self, $thing, $ar, $opt_hr) = @_;
310 0 my $best_match = '';
311 0 my $best_score = $self->opt('min_score', 0, $opt_hr);
312 0 for my $x (@$ar) {
313 0 my $score = similarity($thing, $x);
314 0 ▶ next unless($score >= $best_score);
Branch: 1 branch
BranchTrueFalseTotal
unless $score >= $best_score 0 0 0
315 0 $best_score = $score;
316 0 $best_match = $x;
317 }
318 0 ▶ return ($best_match, $best_score) if ($self->opt('best_match_and_score', 0, $opt_hr)); # for testing, mostly
Branch: 1 branch
BranchTrueFalseTotal
if $self->opt("best_match_and_score", 0, $opt_hr) 0 0 0
319 0 return $best_match;
320 }
321  
322 0 ▶sub opt {
Subroutine opt: not called CC=5 SCAR=34.0
Pod undocumented
323 0 my ($self, $name, $default_value, $alt_hr) = @_;
324 0 ▶ $alt_hr //= {};
Condition0%0/2
$alt_hr //= {}
l!l
00
MC/DC0%0/1
$alt_hr //= {}
$alt_hr
Truth table0%0/2
A
A= $alt_hr
Aresult
11
00
325 0 ▶ return $self->{opt_hr}->{$name} // $self->{conf_hr}->{$name} // $alt_hr->{$name} // $default_value;
Condition0%0/9
(($self->{"opt_hr"}{$name} // $self->{"conf_hr"}{$name}) // $alt_hr->{$name}) // $default_value
l!l&&r!l&&!r
000
($self->{"opt_hr"}{$name} // $self->{"conf_hr"}{$name}) // $alt_hr->{$name}
l!l&&r!l&&!r
000
$self->{"opt_hr"}{$name} // $self->{"conf_hr"}{$name}
l!l&&r!l&&!r
000
MC/DC0%0/4
(($self->{"opt_hr"}{$name} // $self->{"conf_hr"}{$name}) // $alt_hr->{$name}) // $default_value
$self->{"opt_hr"}{$name} $self->{"conf_hr"}{$name} $alt_hr->{$name} $default_value
Truth table0%0/5
A // B // C // D
A= $self->{"opt_hr"}{$name}B= $self->{"conf_hr"}{$name}C= $alt_hr->{$name}D= $default_value
ABCDresult
1XXX1
01XX1
001X1
00011
00000
326 }
327  
328 # approximates python's "in" operator, because ~~ is unsane:
329 0 ▶sub in {
Subroutine in: not called CC=10 SCAR=47.0
Pod undocumented
330 0 my $v = shift @_;
331 0 ▶ return 0 unless (@_ && defined($_[0]));
Branch: 1 branch
BranchTrueFalseTotal
unless @_ and defined $_[0] 0 0 0
Condition0%0/3
@_ and defined $_[0]
!ll&&!rl&&r
000
MC/DC0%0/2
@_ and defined $_[0]
@_ defined $_[0]
Truth table0%0/3
A and B
A= @_B= defined $_[0]
ABresult
0X0
100
111
332 0 ▶ if (ref($_[0]) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0] eq 'ARRAY') { } 0 0 0
333 0 ▶ foreach my $x (@{$_[0]}) { return 1 if defined($x) && $x eq $v; }
Branch: 1 branch
BranchTrueFalseTotal
if defined $x and $x eq $v 0 0 0
Condition0%0/3
defined $x and $x eq $v
!ll&&!rl&&r
000
MC/DC0%0/2
defined $x and $x eq $v
defined $x $x eq $v
Truth table0%0/3
A and B
A= defined $xB= $x eq $v
ABresult
0X0
100
111
334 } else {
335 0 ▶ foreach my $x (@_) { return 1 if defined($x) && $x eq $v; }
Branch: 1 branch
BranchTrueFalseTotal
if defined $x and $x eq $v 0 0 0
Condition0%0/3
defined $x and $x eq $v
!ll&&!rl&&r
000
MC/DC0%0/2
defined $x and $x eq $v
defined $x $x eq $v
Truth table0%0/3
A and B
A= defined $xB= $x eq $v
ABresult
0X0
100
111
336 }
337 0 return 0;
338 }
339  
340 0 ▶sub ok {
Subroutine ok: not called CC=1 SCAR=6.9
Pod documented
341 0 my $self = shift(@_);
342 0 $self->all_is_well();
343 0 return ('OK', @_);
344 }
345  
346 0 ▶sub err {
Subroutine err: not called CC=3 SCAR=24.8
Pod documented
347 0 my $self = shift(@_);
348 0 $self->{ok} = "ERROR";
349 0 $self->{err} = [@_];
350 0 ▶ $self->shout("ERROR", @_) unless ($self->opt('q') || $self->opt('no_errors'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->opt("q") or $self->opt("no_errors") 0 0 0
Condition0%0/3
$self->opt("q") or $self->opt("no_errors")
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->opt("q") or $self->opt("no_errors")
$self->opt("q") $self->opt("no_errors")
Truth table0%0/3
A or B
A= $self->opt("q")B= $self->opt("no_errors")
ABresult
1X1
011
000
351 0 $self->{n_err}++;
352 0 return ('ERROR', @_);
353 }
354  
355 0 ▶sub warn {
Subroutine warn: not called CC=3 SCAR=24.8
Pod undocumented
356 0 my $self = shift(@_);
357 0 $self->{ok} = "WARNING";
358 0 $self->{err} = [@_];
359 0 ▶ $self->shout("WARNING", @_) unless ($self->opt('q') || $self->opt('no_warnings'));
Branch: 1 branch
BranchTrueFalseTotal
unless $self->opt("q") or $self->opt("no_warnings") 0 0 0
Condition0%0/3
$self->opt("q") or $self->opt("no_warnings")
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->opt("q") or $self->opt("no_warnings")
$self->opt("q") $self->opt("no_warnings")
Truth table0%0/3
A or B
A= $self->opt("q")B= $self->opt("no_warnings")
ABresult
1X1
011
000
360 0 $self->{n_warn}++;
361 0 return ('WARNING', @_);
362 }
363  
364 0 ▶sub shout {
Subroutine shout: not called CC=1 SCAR=6.9
Pod undocumented
365 0 my $self = shift(@_);
366 0 my $msg = join("\t", @_);
367 0 print STDERR $msg, "\n";
368 0 return;
369 }
370  
371 0 ▶sub all_is_well {
Subroutine all_is_well: not called CC=1 SCAR=6.9
Pod undocumented
372 0 my ($self) = @_;
373 0 $self->{ok} = 'OK';
374 0 $self->{ex} = undef;
375 0 $self->{err} = '';
376 0 $self->{err_ar} = [];
377 0 return;
378 }
379  
380 0 ▶sub sensors {
Subroutine sensors: not called CC=4 SCAR=30.0
Pod undocumented
381 0 my ($self, $sensor_string, $opt_hr) = @_;
382 0 ▶ $opt_hr //= {};
Condition0%0/2
$opt_hr //= {}
l!l
00
MC/DC0%0/1
$opt_hr //= {}
$opt_hr
Truth table0%0/2
A
A= $opt_hr
Aresult
11
00
383 0 ▶ my $sensor_list = $sensor_string // $self->opt('s', $self->opt('sensor', 25407, $opt_hr), $opt_hr);
Condition0%0/3
$sensor_string // $self->opt("s", $self->opt("sensor", 25407, $opt_hr), $opt_hr)
l!l&&r!l&&!r
000
MC/DC0%0/2
$sensor_string // $self->opt("s", $self->opt("sensor", 25407, $opt_hr), $opt_hr)
$sensor_string $self->opt("s", $self->opt("sensor", 25407, $opt_hr), $opt_hr)
Truth table0%0/3
A // B
A= $sensor_stringB= $self->opt("s", $self->opt("sensor", 25407, $opt_hr), $opt_hr)
ABresult
1X1
011
000
384 0 ▶ return $sensor_list if (ref $sensor_list eq 'ARRAY');
Branch: 1 branch
BranchTrueFalseTotal
if ref $sensor_list eq "ARRAY" 0 0 0
385 0 return [split(/[^\d]+/, $sensor_list)];
386 }
387  
388 0 ▶sub sensor_url {
Subroutine sensor_url: not called CC=1 SCAR=6.9
Pod undocumented
389 0 my ($self, $sensor_id, $opt_hr) = @_;
390 0 my $api_url = $self->opt('api_url', "https://www.purpleair.com/json?show=", $opt_hr);
391 0 my $url = "$api_url$sensor_id";
392 0 return $url
393 }
394  
395 =head2 C<report()>
396  
397 =head2 C<report([sensor-id, sensor-id, ...])>
398  
399 =head2 C<report([sensor-id, sensor-id, ...], {option =E<gt> value, ...})>
400  
401 =over 4
402  
403 The C<report> method retrieves current data from each specified sensor and returns a hashref with
404 sensor name keys and arrayref values. The values represent the air quality at the sensor's location
405 (where higher values = more gunk in the air). Higher than 50 is bad, lower than 20 is good.
406  
407 If no list of sensor IDs is used, and no list was provided to C<new(sensor =E<gt> ...)> a default of
408 25407 (Gravenstein School) will be used, which probably is not very useful to you.
409  
410 See the notes under C<sensor> in the section for C<new> regarding sensor IDs and how to find them.
411  
412 C<report> optionally accepts a hashref options, which are the same as those documented for C<new>.
413  
414 Returns C<undef> on error and sets the object's C<ok> and C<err> attributes.
415  
416 Returns a hashref as described on success and sets the object's C<ok> and C<err> attributes to "OK" and "" respectively.
417  
418 =back
419  
420 =cut
421  
422 0 ▶sub report {
Subroutine report: not called CC=5 SCAR=34.0
Pod documented
423 0 my ($self, $sensors, $opt_hr) = @_;
424 0 $self->ok();
425 0 ▶ $opt_hr //= $opt_hr;
Condition0%0/3
$opt_hr //= $opt_hr
l!l&&r!l&&!r
000
MC/DC0%0/2
$opt_hr //= $opt_hr
$opt_hr $opt_hr
Truth table0%0/3
A //= B
A= $opt_hrB= $opt_hr
ABresult
1X1
011
000
426  
427 0 my $report_hr = $self->gather_sensors($sensors, $opt_hr);
428
429 0 my ($best_guess_aqi, $guess_deviation) = (0, 0);
430 0 ▶ if ($self->opt('g', 0, $opt_hr)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->opt("g", 0, $opt_hr)) 0 0 0
431 0 ($best_guess_aqi, $guess_deviation) = $self->guess_best_aqi($report_hr, $opt_hr);
432  
433 0 my ($p_best, $p_dev) = ($best_guess_aqi, $guess_deviation);
434 0 ▶ ($p_best, $p_dev) = (int($p_best+0.5), int($p_dev+0.5)) if ($self->opt('i', 0, $opt_hr));
Branch: 1 branch
BranchTrueFalseTotal
if $self->opt("i", 0, $opt_hr) 0 0 0
435
436 0 ▶ print "GUESSING\t$p_best\t$p_dev\n" if($self->opt('v', 0, $opt_hr));
Branch: 1 branch
BranchTrueFalseTotal
if $self->opt("v", 0, $opt_hr) 0 0 0
437 0 $report_hr->{GUESSING} = [$best_guess_aqi];
438 }
439  
440 0 return ($report_hr, $guess_deviation);
441 }
442  
443 =head2 C<concentration_to_epa($concentration)>
444  
445 This method implements the official USA EPA guideline for converting PM2.5
446 concentration to AQI, per
447 L<https://www.airnow.gov/sites/default/files/2020-05/aqi-technical-assistance-document-sept2018.pdf>.
448  
449 The sensors do not report AQI metrics, only raw concentrations, so conversion
450 is necessary. The C<report> method does this automatically (unless the C<raw>
451 option is set).
452  
453 The official equation is a dumb-ass piecewise function of linear interpolations,
454 but nobody ever said government was smart.
455  
456 Takes a PM2.5 concentration as input, returns an AQI metric as output. The EPA
457 guideline asserts that the AQI must be truncated to a whole integer. I leave
458 that as an exercise for the programmer.
459  
460 =cut
461  
462 0 ▶sub concentration_to_epa {
Subroutine concentration_to_epa: not called CC=9 SCAR=45.0
Pod documented
463 0 my ($self, $conc, $opt_hr) = @_;
464 # ref: https://www3.epa.gov/airnow/aqi-technical-assistance-document-sept2018.pdf
465 0 ▶ return $conc if ($conc > 500.0 || $conc < 0.05);
Branch: 1 branch
BranchTrueFalseTotal
if $conc > 500 or $conc < "0.05" 0 0 0
Condition0%0/3
$conc > 500 or $conc < "0.05"
l!l&&r!l&&!r
000
MC/DC0%0/2
$conc > 500 or $conc < "0.05"
$conc > 500 $conc < "0.05"
Truth table0%0/3
A or B
A= $conc > 500B= $conc < "0.05"
ABresult
1X1
011
000
466 0 my ($Ihi, $Ilo, $BPhi, $BPlo);
467 0 ▶ if ($conc <= 12.0) { ($Ihi, $Ilo, $BPhi, $BPlo) = ( 50, 0, 12.0, 0.0); }
Branch: 6 branches
BranchTrueFalseTotal
if ($conc <= 12.0) { } 0 0 0
elsif ($conc <= 35.4) { } 0 0 0
elsif ($conc <= 55.4) { } 0 0 0
elsif ($conc <= 150.4) { } 0 0 0
elsif ($conc <= 250.4) { } 0 0 0
elsif ($conc <= 350.4) { } 0 0 0
468 0 elsif ($conc <= 35.4) { ($Ihi, $Ilo, $BPhi, $BPlo) = (100, 51, 35.4, 12.0); }
469 0 elsif ($conc <= 55.4) { ($Ihi, $Ilo, $BPhi, $BPlo) = (150, 101, 55.4, 35.5); }
470 0 elsif ($conc <= 150.4) { ($Ihi, $Ilo, $BPhi, $BPlo) = (200, 151, 150.4, 55.5); }
471 0 elsif ($conc <= 250.4) { ($Ihi, $Ilo, $BPhi, $BPlo) = (300, 201, 250.4, 150.5); }
472 0 elsif ($conc <= 350.4) { ($Ihi, $Ilo, $BPhi, $BPlo) = (400, 301, 350.4, 250.5); }
473 0 else { ($Ihi, $Ilo, $BPhi, $BPlo) = (500, 401, 500.4, 350.4); }
474 0 my $epa = ($Ihi - $Ilo) * ($conc - $BPlo) / ($BPhi - $BPlo) + $Ilo;
475 0 return $epa;
476 }
477  
478 0 ▶sub gather_sensors {
Subroutine gather_sensors: not called CC=25 SCAR=64.8
Pod undocumented
479 0 my ($self, $sensors, $opt_hr) = @_;
480 0 my $report_hr = {};
481 0 ▶ my $http_or = $self->opt('http_or', undef, $opt_hr) // HTTP::Tiny->new();
Condition0%0/3
$self->opt("http_or", undef, $opt_hr) // "HTTP::Tiny"->new
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->opt("http_or", undef, $opt_hr) // "HTTP::Tiny"->new
$self->opt("http_or", undef, $opt_hr) "HTTP::Tiny"->new
Truth table0%0/3
A // B
A= $self->opt("http_or", undef, $opt_hr)B= "HTTP::Tiny"->new
ABresult
1X1
011
000
482  
483 0 $self->ok();
484 0 ▶ $sensors = $self->sensors($sensors, $opt_hr) unless (defined $sensors && ref $sensors eq "ARRAY");
Branch: 1 branch
BranchTrueFalseTotal
unless defined $sensors and ref $sensors eq "ARRAY" 0 0 0
Condition0%0/3
defined $sensors and ref $sensors eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $sensors and ref $sensors eq "ARRAY"
defined $sensors ref $sensors eq "ARRAY"
Truth table0%0/3
A and B
A= defined $sensorsB= ref $sensors eq "ARRAY"
ABresult
0X0
100
111
485 0 my @temps;
486  
487 0 for my $sensor (@$sensors) {
488 0 my $hr = $self->fetch_aqi($http_or, $sensor, $opt_hr);
489 0 ▶ next unless(defined $hr);
Branch: 1 branch
BranchTrueFalseTotal
unless defined $hr 0 0 0
490  
491 0 my ($name, $aqi_ar) = (undef, []);
492 0 ▶ for my $results_hr (@{$hr->{results} // []}) {
Condition0%0/2
$hr->{"results"} // []
l!l
00
MC/DC0%0/1
$hr->{"results"} // []
$hr->{"results"}
Truth table0%0/2
A
A= $hr->{"results"}
Aresult
11
00
493 0 ▶ $name //= $results_hr->{Label};
Condition0%0/3
$name //= $results_hr->{"Label"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$name //= $results_hr->{"Label"}
$name $results_hr->{"Label"}
Truth table0%0/3
A //= B
A= $nameB= $results_hr->{"Label"}
ABresult
1X1
011
000
494 0 my $aqi = $results_hr->{pm2_5_atm};
495 0 ▶ unless ($self->opt('now', 0, $opt_hr)) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->opt("now", 0, $opt_hr)) 0 0 0
496 0 my $stats_hr = $self->safely_from_json($results_hr->{Stats});
497 0 ▶ if (defined $stats_hr) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $stats_hr) { } 0 0 0
498 0 $aqi = $stats_hr->{v1}; # ten-minute average
499 } else {
500 0 $self->warn("unable to parse ten-minute average, using current value");
501 }
502 }
503
504 0 ▶ $aqi = $self->concentration_to_epa($aqi, $opt_hr) unless ($self->opt('raw', 0, $opt_hr)); # approx conversion from raw concentration to US EPA PM2.5
Branch: 1 branch
BranchTrueFalseTotal
unless $self->opt("raw", 0, $opt_hr) 0 0 0
505 0 ▶ push @{$aqi_ar}, $aqi if (defined $aqi);
Branch: 1 branch
BranchTrueFalseTotal
if defined $aqi 0 0 0
506 0 ▶ push @temps, $results_hr->{temp_f} if (defined $results_hr->{temp_f});
Branch: 1 branch
BranchTrueFalseTotal
if defined $results_hr->{"temp_f"} 0 0 0
507 }
508  
509 0 ▶ $name //= $sensor;
Condition0%0/3
$name //= $sensor
l!l&&r!l&&!r
000
MC/DC0%0/2
$name //= $sensor
$name $sensor
Truth table0%0/3
A //= B
A= $nameB= $sensor
ABresult
1X1
011
000
510 0 $self->{sensor_hr}->{$sensor} = $name;
511 0 $self->{name_hr}->{$name} = $sensor;
512 0 ▶ $report_hr->{$name} = $aqi_ar if (@$aqi_ar > 0);
Branch: 1 branch
BranchTrueFalseTotal
if @$aqi_ar > 0 0 0 0
513  
514 0 my $aqi = $self->aqi_calculate($aqi_ar, $opt_hr);
515 0 my $temp_f = 0;
516 0 $temp_f += $_ for (@temps);
517 0 ▶ $temp_f /= @temps if (@temps);
Branch: 1 branch
BranchTrueFalseTotal
if @temps 0 0 0
518 0 ▶ $temp_f = ($temp_f - 32) * 5 / 9 if (uc($self->opt('temperature', 'F')) eq 'C');
Branch: 1 branch
BranchTrueFalseTotal
if uc $self->opt("temperature", "F") eq "C" 0 0 0
519 0 ▶ $temp_f = int($temp_f + 0.5) if ($self->opt('i'));
Branch: 1 branch
BranchTrueFalseTotal
if $self->opt("i") 0 0 0
520 0 ▶ $report_hr->{temp_f} = $temp_f if ($self->opt('temperature'));
Branch: 1 branch
BranchTrueFalseTotal
if $self->opt("temperature") 0 0 0
521  
522 0 ▶ if ($self->opt('v', 0, $opt_hr) && @$aqi_ar) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->opt("v", 0, $opt_hr) and @$aqi_ar) 0 0 0
Condition0%0/3
$self->opt("v", 0, $opt_hr) and @$aqi_ar
!ll&&!rl&&r
000
MC/DC0%0/2
$self->opt("v", 0, $opt_hr) and @$aqi_ar
$self->opt("v", 0, $opt_hr) @$aqi_ar
Truth table0%0/3
A and B
A= $self->opt("v", 0, $opt_hr)B= @$aqi_ar
ABresult
0X0
100
111
523 0 my @p_aqi = @$aqi;
524 0 ▶ @p_aqi = map { int($_+0.5) } @p_aqi if ($self->opt('i', 0, $opt_hr));
Branch: 1 branch
BranchTrueFalseTotal
if $self->opt("i", 0, $opt_hr) 0 0 0
525 0 ▶ push @p_aqi, $temp_f if ($self->opt('temperature'));
Branch: 1 branch
BranchTrueFalseTotal
if $self->opt("temperature") 0 0 0
526 0 my $s_aqi = join("\t", @p_aqi);
527 0 print "$name\t$s_aqi\n";
528 }
529 }
530  
531 0 return $report_hr;
532 }
533  
534 0 ▶sub fetch_aqi {
Subroutine fetch_aqi: not called CC=3 SCAR=24.8
Pod undocumented
535 0 my ($self, $http_or, $sensor, $opt_hr) = @_;
536 0 my $stash_path = $self->opt('stash_path', undef, $opt_hr);
537 0 my $url = $self->sensor_url($sensor, $opt_hr);
538 0 my $resp = $http_or->get($url);
539 0 my $hr;
540 0 ▶ if ($resp->{success}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($resp->{'success'}) { } 0 0 0
541 0 my $js = $resp->{content};
542 0 ▶ wr_f("$stash_path/aqi.$sensor.json", $js) if (defined $stash_path);
Branch: 1 branch
BranchTrueFalseTotal
if defined $stash_path 0 0 0
543 0 $hr = $self->safely_from_json($js);
544 } else {
545 0 $self->err($resp->{status}, $resp->{reason});
546 }
547 0 return $hr;
548 }
549  
550 0 ▶sub aqi_calculate {
Subroutine aqi_calculate: not called CC=3 SCAR=24.8
Pod undocumented
551 0 my ($self, $aqi_ar, $opt_hr) = @_;
552 0 my $aqi = 0;
553 0 ▶ if ($self->opt('average', 0, $opt_hr)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->opt('average', 0, $opt_hr)) { } 0 0 0
554 0 $aqi += $_ for(@$aqi_ar);
555 0 $aqi /= @$aqi_ar;
556 0 $aqi = [$aqi];
557 } else {
558 0 $aqi = $aqi_ar;
559 }
560 0 return $aqi;
561 }
562  
563 0 ▶sub guess_best_aqi {
Subroutine guess_best_aqi: not called CC=25 SCAR=64.8
Pod undocumented
564 0 my ($self, $report_hr, $opt_hr) = @_;
565 0 my $average = 0;
566 0 my $deviation = 0;
567 0 my $n_values = 0;
568 0 my $n_sensors = keys %$report_hr;
569 0 my %hi = (sensor => undef, result => 0, ppm => 0);
570 0 my %lo = (sensor => undef, result => 0, ppm => 1000000);
571 0 my @v_list; # superfluous, but simplifies stddev logic
572  
573 0 for my $k (keys %$report_hr) {
574 0 my $ar = $report_hr->{$k};
575 0 $n_values += @$ar;
576 0 for my $ix (0..$#$ar) {
577 0 my $ppm = $ar->[$ix];
578 0 $average += $ppm;
579 0 push @v_list, $ppm;
580 0 ▶ %hi = (sensor => $k, result => $ix, ppm => $ppm) if ($ppm > $hi{ppm});
Branch: 1 branch
BranchTrueFalseTotal
if $ppm > $hi{"ppm"} 0 0 0
581 0 ▶ %lo = (sensor => $k, result => $ix, ppm => $ppm) if ($ppm < $lo{ppm});
Branch: 1 branch
BranchTrueFalseTotal
if $ppm < $lo{"ppm"} 0 0 0
582 }
583 }
584  
585 # prune outliers if it will leave us with sufficient data for meaningful results
586 0 my $have_pruned = 0;
587  
588 # first the high reading(s)
589 0 ▶ if ($hi{sensor} && ($n_sensors + $n_values) > 3) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hi{"sensor"} and $n_sensors + $n_values > 3) 0 0 0
Condition0%0/3
$hi{"sensor"} and $n_sensors + $n_values > 3
!ll&&!rl&&r
000
MC/DC0%0/2
$hi{"sensor"} and $n_sensors + $n_values > 3
$hi{"sensor"} $n_sensors + $n_values > 3
Truth table0%0/3
A and B
A= $hi{"sensor"}B= $n_sensors + $n_values > 3
ABresult
0X0
100
111
590 0 ▶ print "DEBUG\tpruning high outliers n_sensors=$n_sensors n_values=$n_values\n" if ($self->opt('d', 0, $opt_hr));
Branch: 1 branch
BranchTrueFalseTotal
if $self->opt("d", 0, $opt_hr) 0 0 0
591 0 my $ar = $report_hr->{$hi{sensor}};
592 0 my $high_ppm = $hi{ppm};
593 0 ▶ if ($n_sensors > 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_sensors > 2) { } 0 0 0
594 # potentially prune out all results from this sensor
595 0 for my $ppm (@$ar) {
596 0 ▶ next unless(abs($ppm - $high_ppm) < $high_ppm * $self->opt('prune_threshold', 0.1, $opt_hr));
Branch: 1 branch
BranchTrueFalseTotal
unless abs $ppm - $high_ppm < $high_ppm * $self->opt("prune_threshold", "0.1", $opt_hr) 0 0 0
597 0 ▶ print "DEBUG\tpruning high value $ppm\n" if ($self->opt('d', 0, $opt_hr));
Branch: 1 branch
BranchTrueFalseTotal
if $self->opt("d", 0, $opt_hr) 0 0 0
598 0 $average -= $ppm;
599 0 $n_values--;
600 0 $have_pruned++;
601 }
602 } else {
603 # just prune the sensor's highest ppm
604 0 ▶ print "DEBUG\tpruning highest value $high_ppm\n" if ($self->opt('d', 0, $opt_hr));
Branch: 1 branch
BranchTrueFalseTotal
if $self->opt("d", 0, $opt_hr) 0 0 0
605 0 $average -= $high_ppm;
606 0 $n_values--;
607 0 $have_pruned++;
608 }
609 }
610  
611 # now the low reading(s)
612 0 ▶ my $prune_threshold = $have_pruned ? 2 : 3;
Branch: 1 branch
BranchTrueFalseTotal
$have_pruned ? : 0 0 0
613 0 ▶ if ($lo{sensor} && ($n_sensors + $n_values) > $prune_threshold) {
Branch: 1 branch
BranchTrueFalseTotal
if ($lo{"sensor"} and $n_sensors + $n_values > $prune_threshold) 0 0 0
Condition0%0/3
$lo{"sensor"} and $n_sensors + $n_values > $prune_threshold
!ll&&!rl&&r
000
MC/DC0%0/2
$lo{"sensor"} and $n_sensors + $n_values > $prune_threshold
$lo{"sensor"} $n_sensors + $n_values > $prune_threshold
Truth table0%0/3
A and B
A= $lo{"sensor"}B= $n_sensors + $n_values > $prune_threshold
ABresult
0X0
100
111
614 0 ▶ print "DEBUG\tpruning low outliers n_sensors=$n_sensors n_values=$n_values\n" if ($self->opt('d', 0, $opt_hr));
Branch: 1 branch
BranchTrueFalseTotal
if $self->opt("d", 0, $opt_hr) 0 0 0
615 0 my $ar = $report_hr->{$lo{sensor}};
616 0 my $low_ppm = $lo{ppm};
617 0 ▶ if ($n_sensors > 2) {
Branch: 1 branch
BranchTrueFalseTotal
if ($n_sensors > 2) { } 0 0 0
618 # potentially prune out all results from this sensor
619 0 for my $ppm (@$ar) {
620 # zzapp -- this might be unfair, since threshold for low ppm is intrinsically of smaller magnitude
621 # maybe use different prune_threshold parameters for high and low?
622 0 ▶ next unless(!$ppm || (abs($ppm - $low_ppm) < $low_ppm * $self->opt('prune_threshold', 0.1, $opt_hr)));
Branch: 1 branch
BranchTrueFalseTotal
unless not $ppm or abs $ppm - $low_ppm < $low_ppm * $self->opt("prune_threshold", "0.1", $opt_hr) 0 0 0
Condition0%0/3
not $ppm or abs $ppm - $low_ppm < $low_ppm * $self->opt("prune_threshold", "0.1", $opt_hr)
l!l&&r!l&&!r
000
MC/DC0%0/2
not $ppm or abs $ppm - $low_ppm < $low_ppm * $self->opt("prune_threshold", "0.1", $opt_hr)
not $ppm abs $ppm - $low_ppm < $low_ppm * $self->opt("prune_threshold", "0.1", $opt_hr)
Truth table0%0/3
not(A) or B
A= not $ppmB= abs $ppm - $low_ppm < $low_ppm * $self->opt("prune_threshold", "0.1", $opt_hr)
ABresult
1X1
011
000
623 0 ▶ print "DEBUG\tpruning low value $ppm\n" if ($self->opt('d', 0, $opt_hr));
Branch: 1 branch
BranchTrueFalseTotal
if $self->opt("d", 0, $opt_hr) 0 0 0
624 0 $average -= $ppm;
625 0 $n_values--;
626 }
627 } else {
628 # just prune the sensor's lowest ppm
629 0 ▶ print "DEBUG\tpruning lowest value $low_ppm\n" if ($self->opt('d', 0, $opt_hr));
Branch: 1 branch
BranchTrueFalseTotal
if $self->opt("d", 0, $opt_hr) 0 0 0
630 0 $average -= $low_ppm;
631 0 $n_values--;
632 }
633 }
634  
635 # calculate the average
636 0 ▶ $n_values ||= 1;
Condition0%0/2
$n_values ||= 1
l!l
00
MC/DC0%0/1
$n_values ||= 1
$n_values
Truth table0%0/2
A
A= $n_values
Aresult
11
00
637 0 $average /= $n_values;
638  
639 # and now the standard deviation
640 # zzapp -- this includes pruned values, and I'm not sure if that's a bug or a feature
641 0 for my $v (@v_list) {
642 0 my $square_diff = ($average - $v) ** 2;
643 0 $deviation += $square_diff;
644 }
645 0 $deviation = ($deviation / @v_list) ** 0.5;
646  
647 0 return ($average, $deviation);
648 }
649  
650 =head1 ABOUT RELIABILITY
651  
652 The sensor readings are not always reliable. A car starting or a person
653 smoking near the sensor can produce a false high reading. Right now the
654 workaround is to specify multiple sensors and use the -g option. Future
655 releases will provide alternative remedies.
656  
657 =head1 AUTHOR
658  
659 TTK Ciar, <ttk[at]ciar[dot]org>
660  
661 =head1 COPYRIGHT AND LICENSE
662  
663 Copyright 2020 by TTK Ciar
664  
665 This library is free software; you can redistribute it and/or modify it under
666 the same terms as Perl itself.
667  
668 =head1 TO DO
669  
670 Write more documentation. Some methods are undocumented.
671  
672 Write more unit tests.
673  
674 Save some state and perform time averaging, perhaps throw out dramatic changes and reuse last known value.
675  
676 Pull down and cache the all-sensors blob, implement relevant operations:
677  
678 =over 4
679  
680 * find sensors by name
681  
682 * find sensors nearest a latitude/longitude, or near another sensor, maybe do some light GIS-fu
683  
684 =back
685  
686 =head1 HISTORY
687  
688 This was originally a throw-away script that just yanked JSON from the API, parsed out the sensor name
689 and first reading's PM2.5 concentration, and printed to stdout.
690  
691 It was quickly apparent that this left something to be desired, so the script was refactored into this
692 module and associated wrapper utility.
693  
694 My friend Matt using the throw-away script made me feel embarrassed at its shortcomings, which provided
695 some of the motivation to do better.
696  
697 =head1 SEE ALSO
698  
699 L<The PurpleAir Website|http://purpleair.com>
700  
701 L<The PurpleAir API FAQ|https://github.com/bomeara/purpleairpy/blob/master/api.md> (stored in more convenient form by purpleairpy project)
702  
703 L<Python API Client|https://github.com/ReagentX/purple_air_api> by ReagentX, providing a different approach to the interface.
704  
705 L<Air Concentration to USA EPA PM2.5 AQI Calculator|https://aqicn.org/calculator/> an unfortunately crude tool corresponding PM2.5 concentration to the AQI metric.
706  
707 L<USA EPA PM2.5 AQI Calculation Guidelines|https://www3.epa.gov/airnow/aqi-technical-assistance-document-sept2018.pdf>
708  
709 =cut
710  
711 1 1;
↑ Summary