weathervane 0.9.1

Weather data, air quality, and alerts from public APIs. Fetches, parses, and returns clean Rust types.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Air quality data and AQI categories for US and European standards.

use serde::{Deserialize, Serialize};

use crate::air_quality_aqicn::fetch_headline_aqi;
use crate::client::http_client;
use crate::error::Result;
use crate::geo::{detect_region, Region};

/// AQI standard based on geographic region.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AqiStandard {
    /// US EPA AQI. Scale 0-500, used everywhere outside Europe.
    Us,
    /// European AQI. Scale 0-100+, used within Europe.
    European,
}

/// Which provider supplied the headline AQI.
///
/// Recorded at fetch time by [`fetch_air_quality`]; consumers use it for
/// source attribution without re-deriving the selection logic.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum AqiSource {
    /// World Air Quality Index Project (aqicn.org), US EPA scale.
    Aqicn,
    /// Open-Meteo (the default; used for Europe, no token, or aqicn fallback).
    #[default]
    OpenMeteo,
}

/// US EPA AQI category.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum UsAqiCategory {
    /// AQI 0-50.
    Good,
    /// AQI 51-100.
    Moderate,
    /// AQI 101-150. Active children and adults with respiratory issues should limit outdoor exertion.
    UnhealthySensitive,
    /// AQI 151-200.
    Unhealthy,
    /// AQI 201-300.
    VeryUnhealthy,
    /// AQI 301+.
    Hazardous,
}

impl UsAqiCategory {
    /// Maps a US AQI value to its category.
    pub fn from_aqi(aqi: i32) -> Self {
        match aqi {
            0..=50 => Self::Good,
            51..=100 => Self::Moderate,
            101..=150 => Self::UnhealthySensitive,
            151..=200 => Self::Unhealthy,
            201..=300 => Self::VeryUnhealthy,
            _ => Self::Hazardous,
        }
    }
}

/// European AQI category.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum EuAqiCategory {
    /// AQI 0-20.
    Good,
    /// AQI 21-40.
    Fair,
    /// AQI 41-60.
    Moderate,
    /// AQI 61-80.
    Poor,
    /// AQI 81-100.
    VeryPoor,
    /// AQI 101+.
    ExtremelyPoor,
}

impl EuAqiCategory {
    /// Maps a European AQI value to its category.
    pub fn from_aqi(aqi: i32) -> Self {
        match aqi {
            0..=20 => Self::Good,
            21..=40 => Self::Fair,
            41..=60 => Self::Moderate,
            61..=80 => Self::Poor,
            81..=100 => Self::VeryPoor,
            _ => Self::ExtremelyPoor,
        }
    }
}

/// AQI category, region-specific.
/// Frontend matches on this to produce translated descriptions.
///
/// Wire form is adjacent-tagged (the one documented exception to the
/// serde-defaults baseline): `{"standard": "Us", "level": "Good"}`.
/// The tag disambiguates levels like `Good`/`Moderate` that exist in both
/// scales, so deserialization is exact.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "standard", content = "level")]
pub enum AqiCategory {
    /// US EPA category. Returned for all non-European locations.
    Us(UsAqiCategory),
    /// European category. Returned when coordinates fall within Europe.
    Eu(EuAqiCategory),
}

/// Current air quality data.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AirQualityData {
    /// AQI value. Scale depends on the standard (US 0-500, EU 0-100+).
    pub aqi: i32,
    /// Categorized severity for display. Also carries which standard applies;
    /// see [`AirQualityData::standard()`].
    pub category: AqiCategory,
    /// Fine particulate matter (micrograms per cubic meter).
    pub pm2_5: f32,
    /// Coarse particulate matter (micrograms per cubic meter).
    pub pm10: f32,
    /// Ground-level ozone (micrograms per cubic meter).
    pub ozone: f32,
    /// NO2 concentration (micrograms per cubic meter).
    pub nitrogen_dioxide: f32,
    /// CO concentration (micrograms per cubic meter).
    pub carbon_monoxide: f32,
    /// Which provider supplied the headline AQI. Defaults to OpenMeteo for
    /// wire back-compat with payloads serialized before this field existed.
    #[serde(default)]
    pub aqi_source: AqiSource,
}

impl AirQualityData {
    /// Which AQI standard applies, derived from the category variant.
    pub fn standard(&self) -> AqiStandard {
        match self.category {
            AqiCategory::Us(_) => AqiStandard::Us,
            AqiCategory::Eu(_) => AqiStandard::European,
        }
    }
}

/// Fetches air quality data.
///
/// Pollutant concentrations (pm2_5, pm10, etc) always come from Open-Meteo so
/// the µg/m³ contract on [`AirQualityData`] stays honest. The headline `aqi`
/// field uses the World Air Quality Index Project (aqicn.org) when a token is
/// provided and the coordinates are outside Europe. Europe stays on Open-Meteo
/// so the [`AqiStandard::European`] category mapping is preserved.
///
/// Free aqicn tokens are issued at <https://aqicn.org/data-platform/token/>.
/// Pass `None` to skip aqicn entirely.
///
/// If aqicn is selected but unreachable, returns invalid data, or the token
/// is rejected, the call falls back to Open-Meteo's AQI without surfacing an
/// error.
pub async fn fetch_air_quality(
    latitude: f64,
    longitude: f64,
    aqicn_token: Option<&str>,
) -> Result<AirQualityData> {
    let url = format!(
        "https://air-quality-api.open-meteo.com/v1/air-quality?latitude={}&longitude={}&current=us_aqi,european_aqi,pm2_5,pm10,ozone,nitrogen_dioxide,carbon_monoxide&timezone=auto",
        latitude, longitude
    );

    let response = http_client()?.get(&url).send().await?.error_for_status()?;
    let data: AirQualityResponse = response.json().await?;

    let region = detect_region(latitude, longitude);

    // Try aqicn for the headline AQI when a token is present and we're not
    // in Europe. Europe keeps Open-Meteo so the EU scale and category mapping
    // are preserved.
    let aqicn_aqi = match (aqicn_token, region) {
        (Some(token), r) if r != Region::Europe => {
            fetch_headline_aqi(latitude, longitude, token).await
        }
        _ => None,
    };

    let (aqi, category, aqi_source) = resolve_headline_aqi(&data, region, aqicn_aqi);

    Ok(AirQualityData {
        aqi,
        category,
        pm2_5: data.current.pm2_5.unwrap_or(0.0),
        pm10: data.current.pm10.unwrap_or(0.0),
        ozone: data.current.ozone.unwrap_or(0.0),
        nitrogen_dioxide: data.current.nitrogen_dioxide.unwrap_or(0.0),
        carbon_monoxide: data.current.carbon_monoxide.unwrap_or(0.0),
        aqi_source,
    })
}

/// Resolves the headline `(aqi, category, aqi_source)` tuple: aqicn (US scale)
/// when present, else Open-Meteo on the region-appropriate scale. Lives in its
/// own function so the headline-AQI resolution can be unit-tested without a
/// live network.
fn resolve_headline_aqi(
    response: &AirQualityResponse,
    region: Region,
    aqicn_aqi: Option<i32>,
) -> (i32, AqiCategory, AqiSource) {
    if let Some(val) = aqicn_aqi {
        (
            val,
            AqiCategory::Us(UsAqiCategory::from_aqi(val)),
            AqiSource::Aqicn,
        )
    } else if region == Region::Europe {
        let val = response.current.european_aqi.unwrap_or_else(|| {
            tracing::warn!("European AQI missing from API response, defaulting to 0");
            0
        });
        (
            val,
            AqiCategory::Eu(EuAqiCategory::from_aqi(val)),
            AqiSource::OpenMeteo,
        )
    } else {
        let val = response.current.us_aqi.unwrap_or_else(|| {
            tracing::warn!("US AQI missing from API response, defaulting to 0");
            0
        });
        (
            val,
            AqiCategory::Us(UsAqiCategory::from_aqi(val)),
            AqiSource::OpenMeteo,
        )
    }
}

/// Open-Meteo Air Quality API response.
#[derive(Debug, Deserialize)]
struct AirQualityResponse {
    current: AirQualityCurrentData,
}

#[derive(Debug, Deserialize)]
struct AirQualityCurrentData {
    us_aqi: Option<i32>,
    european_aqi: Option<i32>,
    pm2_5: Option<f32>,
    pm10: Option<f32>,
    ozone: Option<f32>,
    nitrogen_dioxide: Option<f32>,
    carbon_monoxide: Option<f32>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn aqi_source_defaults_to_open_meteo() {
        assert_eq!(AqiSource::default(), AqiSource::OpenMeteo);
    }

    // --- resolve_headline_aqi branches ---

    #[test]
    fn resolve_headline_aqi_us_region_with_aqicn_returns_aqicn() {
        let json = r#"{"current": {"us_aqi": 42, "european_aqi": null, "pm2_5": null,
            "pm10": null, "ozone": null, "nitrogen_dioxide": null, "carbon_monoxide": null}}"#;
        let data: AirQualityResponse = serde_json::from_str(json).unwrap();
        let result = resolve_headline_aqi(&data, Region::Us, Some(88));
        assert_eq!(
            result,
            (
                88,
                AqiCategory::Us(UsAqiCategory::Moderate),
                AqiSource::Aqicn
            )
        );
    }

    #[test]
    fn resolve_headline_aqi_us_region_without_aqicn_returns_open_meteo_us() {
        let json = r#"{"current": {"us_aqi": 42, "european_aqi": null, "pm2_5": null,
            "pm10": null, "ozone": null, "nitrogen_dioxide": null, "carbon_monoxide": null}}"#;
        let data: AirQualityResponse = serde_json::from_str(json).unwrap();
        let result = resolve_headline_aqi(&data, Region::Us, None);
        assert_eq!(
            result,
            (
                42,
                AqiCategory::Us(UsAqiCategory::Good),
                AqiSource::OpenMeteo
            )
        );
    }

    #[test]
    fn resolve_headline_aqi_us_region_with_missing_us_aqi_defaults_to_zero() {
        let json = r#"{"current": {"us_aqi": null, "european_aqi": null, "pm2_5": null,
            "pm10": null, "ozone": null, "nitrogen_dioxide": null, "carbon_monoxide": null}}"#;
        let data: AirQualityResponse = serde_json::from_str(json).unwrap();
        let result = resolve_headline_aqi(&data, Region::Us, None);
        assert_eq!(
            result,
            (
                0,
                AqiCategory::Us(UsAqiCategory::Good),
                AqiSource::OpenMeteo
            )
        );
    }

    #[test]
    fn resolve_headline_aqi_europe_region_without_aqicn_returns_open_meteo_eu() {
        let json = r#"{"current": {"us_aqi": null, "european_aqi": 25, "pm2_5": null,
            "pm10": null, "ozone": null, "nitrogen_dioxide": null, "carbon_monoxide": null}}"#;
        let data: AirQualityResponse = serde_json::from_str(json).unwrap();
        let result = resolve_headline_aqi(&data, Region::Europe, None);
        assert_eq!(
            result,
            (
                25,
                AqiCategory::Eu(EuAqiCategory::Fair),
                AqiSource::OpenMeteo
            )
        );
    }

    #[test]
    fn resolve_headline_aqi_europe_region_with_missing_european_aqi_defaults_to_zero() {
        let json = r#"{"current": {"us_aqi": null, "european_aqi": null, "pm2_5": null,
            "pm10": null, "ozone": null, "nitrogen_dioxide": null, "carbon_monoxide": null}}"#;
        let data: AirQualityResponse = serde_json::from_str(json).unwrap();
        let result = resolve_headline_aqi(&data, Region::Europe, None);
        assert_eq!(
            result,
            (
                0,
                AqiCategory::Eu(EuAqiCategory::Good),
                AqiSource::OpenMeteo
            )
        );
    }

    #[test]
    fn resolve_headline_aqi_unknown_region_behaves_as_us() {
        let json = r#"{"current": {"us_aqi": 175, "european_aqi": null, "pm2_5": null,
            "pm10": null, "ozone": null, "nitrogen_dioxide": null, "carbon_monoxide": null}}"#;
        let data: AirQualityResponse = serde_json::from_str(json).unwrap();
        let result = resolve_headline_aqi(&data, Region::Unknown, None);
        assert_eq!(
            result,
            (
                175,
                AqiCategory::Us(UsAqiCategory::Unhealthy),
                AqiSource::OpenMeteo
            )
        );
    }

    // --- UsAqiCategory::from_aqi boundaries ---

    #[test]
    fn us_aqi_category_good_at_50() {
        assert_eq!(UsAqiCategory::from_aqi(50), UsAqiCategory::Good);
        assert_eq!(UsAqiCategory::from_aqi(0), UsAqiCategory::Good);
    }

    #[test]
    fn us_aqi_category_moderate_at_51_and_100() {
        assert_eq!(UsAqiCategory::from_aqi(51), UsAqiCategory::Moderate);
        assert_eq!(UsAqiCategory::from_aqi(100), UsAqiCategory::Moderate);
    }

    #[test]
    fn us_aqi_category_unhealthy_sensitive_at_101_and_150() {
        assert_eq!(
            UsAqiCategory::from_aqi(101),
            UsAqiCategory::UnhealthySensitive
        );
        assert_eq!(
            UsAqiCategory::from_aqi(150),
            UsAqiCategory::UnhealthySensitive
        );
    }

    #[test]
    fn us_aqi_category_unhealthy_at_151_and_200() {
        assert_eq!(UsAqiCategory::from_aqi(151), UsAqiCategory::Unhealthy);
        assert_eq!(UsAqiCategory::from_aqi(200), UsAqiCategory::Unhealthy);
    }

    #[test]
    fn us_aqi_category_very_unhealthy_at_201_and_300() {
        assert_eq!(UsAqiCategory::from_aqi(201), UsAqiCategory::VeryUnhealthy);
        assert_eq!(UsAqiCategory::from_aqi(300), UsAqiCategory::VeryUnhealthy);
    }

    #[test]
    fn us_aqi_category_hazardous_at_301_and_above() {
        assert_eq!(UsAqiCategory::from_aqi(301), UsAqiCategory::Hazardous);
        assert_eq!(UsAqiCategory::from_aqi(999), UsAqiCategory::Hazardous);
    }

    // --- EuAqiCategory::from_aqi boundaries ---

    #[test]
    fn eu_aqi_category_good_at_20() {
        assert_eq!(EuAqiCategory::from_aqi(20), EuAqiCategory::Good);
        assert_eq!(EuAqiCategory::from_aqi(0), EuAqiCategory::Good);
    }

    #[test]
    fn eu_aqi_category_fair_at_21_and_40() {
        assert_eq!(EuAqiCategory::from_aqi(21), EuAqiCategory::Fair);
        assert_eq!(EuAqiCategory::from_aqi(40), EuAqiCategory::Fair);
    }

    #[test]
    fn eu_aqi_category_moderate_at_41_and_60() {
        assert_eq!(EuAqiCategory::from_aqi(41), EuAqiCategory::Moderate);
        assert_eq!(EuAqiCategory::from_aqi(60), EuAqiCategory::Moderate);
    }

    #[test]
    fn eu_aqi_category_poor_at_61_and_80() {
        assert_eq!(EuAqiCategory::from_aqi(61), EuAqiCategory::Poor);
        assert_eq!(EuAqiCategory::from_aqi(80), EuAqiCategory::Poor);
    }

    #[test]
    fn eu_aqi_category_very_poor_at_81_and_100() {
        assert_eq!(EuAqiCategory::from_aqi(81), EuAqiCategory::VeryPoor);
        assert_eq!(EuAqiCategory::from_aqi(100), EuAqiCategory::VeryPoor);
    }

    #[test]
    fn eu_aqi_category_extremely_poor_at_101_and_above() {
        assert_eq!(EuAqiCategory::from_aqi(101), EuAqiCategory::ExtremelyPoor);
        assert_eq!(EuAqiCategory::from_aqi(999), EuAqiCategory::ExtremelyPoor);
    }

    // --- AirQualityData::standard() ---

    #[test]
    fn air_quality_data_standard_returns_us_for_us_variant() {
        let data = AirQualityData {
            aqi: 0,
            category: AqiCategory::Us(UsAqiCategory::Good),
            pm2_5: 0.0,
            pm10: 0.0,
            ozone: 0.0,
            nitrogen_dioxide: 0.0,
            carbon_monoxide: 0.0,
            aqi_source: AqiSource::OpenMeteo,
        };
        assert_eq!(data.standard(), AqiStandard::Us);
    }

    #[test]
    fn air_quality_data_standard_returns_european_for_eu_variant() {
        let data = AirQualityData {
            aqi: 0,
            category: AqiCategory::Eu(EuAqiCategory::Good),
            pm2_5: 0.0,
            pm10: 0.0,
            ozone: 0.0,
            nitrogen_dioxide: 0.0,
            carbon_monoxide: 0.0,
            aqi_source: AqiSource::OpenMeteo,
        };
        assert_eq!(data.standard(), AqiStandard::European);
    }

    // --- pollutant Option defaults ---

    #[test]
    fn air_quality_response_missing_pollutants_default_to_zero_after_fetch() {
        let json = r#"{"current": {"us_aqi": 42, "european_aqi": null, "pm2_5": null,
            "pm10": null, "ozone": null, "nitrogen_dioxide": null, "carbon_monoxide": null}}"#;
        let data: AirQualityResponse = serde_json::from_str(json).unwrap();
        let (aqi, category, aqi_source) = resolve_headline_aqi(&data, Region::Us, None);
        let built = AirQualityData {
            aqi,
            category,
            pm2_5: data.current.pm2_5.unwrap_or(0.0),
            pm10: data.current.pm10.unwrap_or(0.0),
            ozone: data.current.ozone.unwrap_or(0.0),
            nitrogen_dioxide: data.current.nitrogen_dioxide.unwrap_or(0.0),
            carbon_monoxide: data.current.carbon_monoxide.unwrap_or(0.0),
            aqi_source,
        };
        assert_eq!(built.pm2_5, 0.0);
        assert_eq!(built.pm10, 0.0);
        assert_eq!(built.ozone, 0.0);
        assert_eq!(built.nitrogen_dioxide, 0.0);
        assert_eq!(built.carbon_monoxide, 0.0);
    }
}