i3status_rs/blocks/
weather.rs

1//! Current weather
2//!
3//! This block displays local weather and temperature information. In order to use this block, you
4//! will need access to a supported weather API service. At the time of writing, OpenWeatherMap,
5//! met.no, and the US National Weather Service are supported.
6//!
7//! Configuring this block requires configuring a weather service, which may require API keys and
8//! other parameters.
9//!
10//! If using the `autolocate` feature, set the autolocate update interval such that you do not exceed ipapi.co's free daily limit of 1000 hits. Or use `autolocate_interval = "once"` to only run on initialization.
11//!
12//! # Configuration
13//!
14//! Key | Values | Default
15//! ----|--------|--------
16//! `service` | The configuration of a weather service (see below). | **Required**
17//! `format` | A string to customise the output of this block. See below for available placeholders. Text may need to be escaped, refer to [Escaping Text](#escaping-text). | `" $icon $weather $temp "`
18//! `format_alt` | If set, block will switch between `format` and `format_alt` on every click | `None`
19//! `interval` | Update interval, in seconds. | `600`
20//! `autolocate` | Gets your location using the ipapi.co IP location service (no API key required). If the API call fails then the block will fallback to service specific location config. | `false`
21//! `autolocate_interval` | Update interval for `autolocate` in seconds or "once" | `interval`
22//!
23//! # OpenWeatherMap Options
24//!
25//! To use the service you will need a (free) API key.
26//!
27//! Key | Values | Required | Default
28//! ----|--------|----------|--------
29//! `name` | `openweathermap`. | Yes | None
30//! `api_key` | Your OpenWeatherMap API key. | Yes | None
31//! `coordinates` | GPS latitude longitude coordinates as a tuple, example: `["39.2362","9.3317"]` | Yes* | None
32//! `city_id` | OpenWeatherMap's ID for the city. (Deprecated) | Yes* | None
33//! `place` | OpenWeatherMap 'By {city name},{state code},{country code}' search query. See [here](https://openweathermap.org/api/geocoding-api#direct_name). Consumes an additional API call | Yes* | None
34//! `zip` | OpenWeatherMap 'By {zip code},{country code}' search query. See [here](https://openweathermap.org/api/geocoding-api#direct_zip). Consumes an additional API call | Yes* | None
35//! `units` | Either `"metric"` or `"imperial"`. | No | `"metric"`
36//! `lang` | Language code. See [here](https://openweathermap.org/current#multi). Currently only affects `weather_verbose` key. | No | `"en"`
37//! `forecast_hours` | How many hours should be forecast (must be increments of 3 hours, max 120 hours) | No | 12
38//!
39//! One of `coordinates`, `city_id`, `place`, or `zip` is required. If more than one are supplied, `coordinates` takes precedence over `city_id` which takes precedence over `place` which takes precedence over `zip`.
40//!
41//! The options `api_key`, `city_id`, `place`, `zip`, can be omitted from configuration,
42//! in which case they must be provided in the environment variables
43//! `OPENWEATHERMAP_API_KEY`, `OPENWEATHERMAP_CITY_ID`, `OPENWEATHERMAP_PLACE`, `OPENWEATHERMAP_ZIP`.
44//!
45//! Forecasts are only fetched if forecast_hours > 0 and the format has keys related to forecast.
46//!
47//! # met.no Options
48//!
49//! Key | Values | Required | Default
50//! ----|--------|----------|--------
51//! `name` | `metno`. | Yes | None
52//! `coordinates` | GPS latitude longitude coordinates as a tuple, example: `["39.2362","9.3317"]` | Required if `autolocate = false` | None
53//! `lang` | Language code: `en`, `nn` or `nb` | No | `en`
54//! `altitude` | Meters above sea level of the ground | No | Approximated by server
55//! `forecast_hours` | How many hours should be forecast | No | 12
56//!
57//! Met.no does not support location name, but if autolocate is enabled then autolocate's city value is used.
58//!
59//! # US National Weather Service Options
60//!
61//! Key | Values | Required | Default
62//! ----|--------|----------|--------
63//! `name` | `nws`. | Yes | None
64//! `coordinates` | GPS latitude longitude coordinates as a tuple, example: `["39.2362","9.3317"]` | Required if `autolocate = false` | None
65//! `forecast_hours` | How many hours should be forecast | No | 12
66//! `units` | Either `"metric"` or `"imperial"`. | No | `"metric"`
67//!
68//! Forecasts gather statistics from each hour between now and the `forecast_hours` value, and
69//! provide predicted weather at the set number of hours into the future.
70//!
71//! # Available Format Keys
72//!
73//!  Key                                         | Value                                                                         | Type     | Unit
74//! ---------------------------------------------|-------------------------------------------------------------------------------|----------|-----
75//! `location`                                   | Location name (exact format depends on the service)                           | Text     | -
76//! `icon{,_ffin}`                               | Icon representing the weather                                                 | Icon     | -
77//! `weather{,_ffin}`                            | Textual brief description of the weather, e.g. "Raining"                      | Text     | -
78//! `weather_verbose{,_ffin}`                    | Textual verbose description of the weather, e.g. "overcast clouds"            | Text     | -
79//! `temp{,_{favg,fmin,fmax,ffin}}`              | Temperature                                                                   | Number   | degrees
80//! `apparent{,_{favg,fmin,fmax,ffin}}`          | Australian Apparent Temperature                                               | Number   | degrees
81//! `humidity{,_{favg,fmin,fmax,ffin}}`          | Humidity                                                                      | Number   | %
82//! `wind{,_{favg,fmin,fmax,ffin}}`              | Wind speed                                                                    | Number   | -
83//! `wind_kmh{,_{favg,fmin,fmax,ffin}}`          | Wind speed. The wind speed in km/h                                            | Number   | -
84//! `direction{,_{favg,fmin,fmax,ffin}}`         | Wind direction, e.g. "NE"                                                     | Text     | -
85//! `sunrise`                                    | Time of sunrise                                                               | DateTime | -
86//! `sunset`                                     | Time of sunset                                                                | DateTime | -
87//!
88//! You can use the suffixes noted above to get the following:
89//!
90//! Suffix    | Description
91//! ----------|------------
92//! None      | Current weather
93//! `_favg`   | Average forecast value
94//! `_fmin`   | Minimum forecast value
95//! `_fmax`   | Maximum forecast value
96//! `_ffin`   | Final forecast value
97//!
98//! Action          | Description                               | Default button
99//! ----------------|-------------------------------------------|---------------
100//! `toggle_format` | Toggles between `format` and `format_alt` | Left
101//!
102//! # Examples
103//!
104//! Show detailed weather in San Francisco through the OpenWeatherMap service:
105//!
106//! ```toml
107//! [[block]]
108//! block = "weather"
109//! format = " $icon $weather ($location) $temp, $wind m/s $direction "
110//! format_alt = " $icon_ffin Forecast (9 hour avg) {$temp_favg ({$temp_fmin}-{$temp_fmax})|Unavailable} "
111//! [block.service]
112//! name = "openweathermap"
113//! api_key = "XXX"
114//! city_id = "5398563"
115//! units = "metric"
116//! forecast_hours = 9
117//! ```
118//!
119//! Show sunrise and sunset times in null island
120//!
121//! ```toml
122//! [[block]]
123//! block = "weather"
124//! format = "up $sunrise.datetime(f:'%R') down $sunset.datetime(f:'%R')"
125//! [block.service]
126//! name = "metno"
127//! coordinates = ["0", "0"]
128//! ```
129//!
130//! # Used Icons
131//!
132//! - `weather_sun` (when weather is reported as "Clear" during the day)
133//! - `weather_moon` (when weather is reported as "Clear" at night)
134//! - `weather_clouds` (when weather is reported as "Clouds" during the day)
135//! - `weather_clouds_night` (when weather is reported as "Clouds" at night)
136//! - `weather_fog` (when weather is reported as "Fog" or "Mist" during the day)
137//! - `weather_fog_night` (when weather is reported as "Fog" or "Mist" at night)
138//! - `weather_rain` (when weather is reported as "Rain" or "Drizzle" during the day)
139//! - `weather_rain_night` (when weather is reported as "Rain" or "Drizzle" at night)
140//! - `weather_snow` (when weather is reported as "Snow")
141//! - `weather_thunder` (when weather is reported as "Thunderstorm" during the day)
142//! - `weather_thunder_night` (when weather is reported as "Thunderstorm" at night)
143
144use chrono::{DateTime, Utc};
145use sunrise::{SolarDay, SolarEvent};
146
147use crate::formatting::Format;
148pub(super) use crate::geolocator::IPAddressInfo;
149
150use super::prelude::*;
151
152pub mod met_no;
153pub mod nws;
154pub mod open_weather_map;
155
156#[derive(Deserialize, Debug)]
157#[serde(deny_unknown_fields)]
158pub struct Config {
159    #[serde(default = "default_interval")]
160    pub interval: Seconds,
161    #[serde(default)]
162    pub format: FormatConfig,
163    pub format_alt: Option<FormatConfig>,
164    pub service: WeatherService,
165    #[serde(default)]
166    pub autolocate: bool,
167    pub autolocate_interval: Option<Seconds>,
168}
169
170fn default_interval() -> Seconds {
171    Seconds::new(600)
172}
173
174#[async_trait]
175trait WeatherProvider {
176    async fn get_weather(
177        &self,
178        autolocated_location: Option<&IPAddressInfo>,
179        need_forecast: bool,
180    ) -> Result<WeatherResult>;
181}
182
183#[derive(Deserialize, Debug)]
184#[serde(tag = "name", rename_all = "lowercase")]
185pub enum WeatherService {
186    OpenWeatherMap(open_weather_map::Config),
187    MetNo(met_no::Config),
188    Nws(nws::Config),
189}
190
191#[derive(Clone, Copy, Default)]
192enum WeatherIcon {
193    Clear {
194        is_night: bool,
195    },
196    Clouds {
197        is_night: bool,
198    },
199    Fog {
200        is_night: bool,
201    },
202    Rain {
203        is_night: bool,
204    },
205    Snow,
206    Thunder {
207        is_night: bool,
208    },
209    #[default]
210    Default,
211}
212
213impl WeatherIcon {
214    fn to_icon_str(self) -> &'static str {
215        match self {
216            Self::Clear { is_night: false } => "weather_sun",
217            Self::Clear { is_night: true } => "weather_moon",
218            Self::Clouds { is_night: false } => "weather_clouds",
219            Self::Clouds { is_night: true } => "weather_clouds_night",
220            Self::Fog { is_night: false } => "weather_fog",
221            Self::Fog { is_night: true } => "weather_fog_night",
222            Self::Rain { is_night: false } => "weather_rain",
223            Self::Rain { is_night: true } => "weather_rain_night",
224            Self::Snow => "weather_snow",
225            Self::Thunder { is_night: false } => "weather_thunder",
226            Self::Thunder { is_night: true } => "weather_thunder_night",
227            Self::Default => "weather_default",
228        }
229    }
230}
231
232#[derive(Default)]
233struct WeatherMoment {
234    icon: WeatherIcon,
235    weather: String,
236    weather_verbose: String,
237    temp: f64,
238    apparent: f64,
239    humidity: f64,
240    wind: f64,
241    wind_kmh: f64,
242    wind_direction: Option<f64>,
243}
244
245struct ForecastAggregate {
246    temp: f64,
247    apparent: f64,
248    humidity: f64,
249    wind: f64,
250    wind_kmh: f64,
251    wind_direction: Option<f64>,
252}
253
254struct ForecastAggregateSegment {
255    temp: Option<f64>,
256    apparent: Option<f64>,
257    humidity: Option<f64>,
258    wind: Option<f64>,
259    wind_kmh: Option<f64>,
260    wind_direction: Option<f64>,
261}
262
263struct WeatherResult {
264    location: String,
265    current_weather: WeatherMoment,
266    forecast: Option<Forecast>,
267    sunrise: DateTime<Utc>,
268    sunset: DateTime<Utc>,
269}
270
271impl WeatherResult {
272    fn into_values(self) -> Values {
273        let mut values = map! {
274            "location" => Value::text(self.location),
275            //current_weather
276            "icon" => Value::icon(self.current_weather.icon.to_icon_str()),
277            "temp" => Value::degrees(self.current_weather.temp),
278            "apparent" => Value::degrees(self.current_weather.apparent),
279            "humidity" => Value::percents(self.current_weather.humidity),
280            "weather" => Value::text(self.current_weather.weather),
281            "weather_verbose" => Value::text(self.current_weather.weather_verbose),
282            "wind" => Value::number(self.current_weather.wind),
283            "wind_kmh" => Value::number(self.current_weather.wind_kmh),
284            "direction" => Value::text(convert_wind_direction(self.current_weather.wind_direction).into()),
285            "sunrise" => Value::datetime(self.sunrise, None),
286            "sunset" => Value::datetime(self.sunset, None),
287        };
288
289        if let Some(forecast) = self.forecast {
290            macro_rules! map_forecasts {
291                ({$($suffix: literal => $src: expr),* $(,)?}) => {
292                    map!{ @extend values
293                        $(
294                            concat!("temp_f", $suffix) => Value::degrees($src.temp),
295                            concat!("apparent_f", $suffix) => Value::degrees($src.apparent),
296                            concat!("humidity_f", $suffix) => Value::percents($src.humidity),
297                            concat!("wind_f", $suffix) => Value::number($src.wind),
298                            concat!("wind_kmh_f", $suffix) => Value::number($src.wind_kmh),
299                            concat!("direction_f", $suffix) => Value::text(convert_wind_direction($src.wind_direction).into()),
300                        )*
301                    }
302                };
303            }
304            map_forecasts!({
305                "avg" => forecast.avg,
306                "min" => forecast.min,
307                "max" => forecast.max,
308                "fin" => forecast.fin,
309            });
310
311            map! { @extend values
312                "icon_ffin" => Value::icon(forecast.fin.icon.to_icon_str()),
313                "weather_ffin" => Value::text(forecast.fin.weather.clone()),
314                "weather_verbose_ffin" => Value::text(forecast.fin.weather_verbose.clone()),
315            }
316        }
317
318        values
319    }
320}
321
322struct Forecast {
323    avg: ForecastAggregate,
324    min: ForecastAggregate,
325    max: ForecastAggregate,
326    fin: WeatherMoment,
327}
328
329impl Forecast {
330    fn new(data: &[ForecastAggregateSegment], fin: WeatherMoment) -> Self {
331        let mut temp_avg = 0.0;
332        let mut temp_count = 0.0;
333        let mut apparent_avg = 0.0;
334        let mut apparent_count = 0.0;
335        let mut humidity_avg = 0.0;
336        let mut humidity_count = 0.0;
337        let mut wind_north_avg = 0.0;
338        let mut wind_east_avg = 0.0;
339        let mut wind_kmh_north_avg = 0.0;
340        let mut wind_kmh_east_avg = 0.0;
341        let mut wind_count = 0.0;
342        let mut max = ForecastAggregate {
343            temp: f64::MIN,
344            apparent: f64::MIN,
345            humidity: f64::MIN,
346            wind: f64::MIN,
347            wind_kmh: f64::MIN,
348            wind_direction: None,
349        };
350        let mut min = ForecastAggregate {
351            temp: f64::MAX,
352            apparent: f64::MAX,
353            humidity: f64::MAX,
354            wind: f64::MAX,
355            wind_kmh: f64::MAX,
356            wind_direction: None,
357        };
358        for val in data {
359            if let Some(temp) = val.temp {
360                temp_avg += temp;
361                max.temp = max.temp.max(temp);
362                min.temp = min.temp.min(temp);
363                temp_count += 1.0;
364            }
365            if let Some(apparent) = val.apparent {
366                apparent_avg += apparent;
367                max.apparent = max.apparent.max(apparent);
368                min.apparent = min.apparent.min(apparent);
369                apparent_count += 1.0;
370            }
371            if let Some(humidity) = val.humidity {
372                humidity_avg += humidity;
373                max.humidity = max.humidity.max(humidity);
374                min.humidity = min.humidity.min(humidity);
375                humidity_count += 1.0;
376            }
377
378            if let (Some(wind), Some(wind_kmh)) = (val.wind, val.wind_kmh) {
379                if let Some(degrees) = val.wind_direction {
380                    let (sin, cos) = degrees.to_radians().sin_cos();
381                    wind_north_avg += wind * cos;
382                    wind_east_avg += wind * sin;
383                    wind_kmh_north_avg += wind_kmh * cos;
384                    wind_kmh_east_avg += wind_kmh * sin;
385                    wind_count += 1.0;
386                }
387
388                if wind > max.wind {
389                    max.wind_direction = val.wind_direction;
390                    max.wind = wind;
391                    max.wind_kmh = wind_kmh;
392                }
393
394                if wind < min.wind {
395                    min.wind_direction = val.wind_direction;
396                    min.wind = wind;
397                    min.wind_kmh = wind_kmh;
398                }
399            }
400        }
401
402        temp_avg /= temp_count;
403        humidity_avg /= humidity_count;
404        apparent_avg /= apparent_count;
405
406        // Calculate the wind results separately, discarding invalid wind values
407        let (wind_avg, wind_kmh_avg, wind_direction_avg) = if wind_count == 0.0 {
408            (0.0, 0.0, None)
409        } else {
410            (
411                wind_east_avg.hypot(wind_north_avg) / wind_count,
412                wind_kmh_east_avg.hypot(wind_kmh_north_avg) / wind_count,
413                Some(
414                    wind_east_avg
415                        .atan2(wind_north_avg)
416                        .to_degrees()
417                        .rem_euclid(360.0),
418                ),
419            )
420        };
421
422        let avg = ForecastAggregate {
423            temp: temp_avg,
424            apparent: apparent_avg,
425            humidity: humidity_avg,
426            wind: wind_avg,
427            wind_kmh: wind_kmh_avg,
428            wind_direction: wind_direction_avg,
429        };
430        Self { avg, min, max, fin }
431    }
432}
433
434pub async fn run(config: &Config, api: &CommonApi) -> Result<()> {
435    let mut actions = api.get_actions()?;
436    api.set_default_actions(&[(MouseButton::Left, None, "toggle_format")])?;
437
438    let mut format = config.format.with_default(" $icon $weather $temp ")?;
439    let mut format_alt = match &config.format_alt {
440        Some(f) => Some(f.with_default("")?),
441        None => None,
442    };
443
444    let provider: Box<dyn WeatherProvider + Send + Sync> = match &config.service {
445        WeatherService::MetNo(service_config) => Box::new(met_no::Service::new(service_config)?),
446        WeatherService::OpenWeatherMap(service_config) => {
447            Box::new(open_weather_map::Service::new(config.autolocate, service_config).await?)
448        }
449        WeatherService::Nws(service_config) => {
450            Box::new(nws::Service::new(config.autolocate, service_config).await?)
451        }
452    };
453
454    let autolocate_interval = config.autolocate_interval.unwrap_or(config.interval);
455    let need_forecast = need_forecast(&format, format_alt.as_ref());
456
457    let mut timer = config.interval.timer();
458
459    loop {
460        let location = if config.autolocate {
461            let fetch = || api.find_ip_location(&REQWEST_CLIENT, autolocate_interval.0);
462            Some(fetch.retry(ExponentialBuilder::default()).await?)
463        } else {
464            None
465        };
466
467        let fetch = || provider.get_weather(location.as_ref(), need_forecast);
468        let data = fetch.retry(ExponentialBuilder::default()).await?;
469        let data_values = data.into_values();
470
471        loop {
472            let mut widget = Widget::new().with_format(format.clone());
473            widget.set_values(data_values.clone());
474            api.set_widget(widget)?;
475
476            select! {
477                _ = timer.tick() => break,
478                _ = api.wait_for_update_request() => break,
479                Some(action) = actions.recv() => match action.as_ref() {
480                        "toggle_format" => {
481                            if let Some(ref mut format_alt) = format_alt {
482                                std::mem::swap(format_alt, &mut format);
483                            }
484                        }
485                        _ => (),
486                    }
487            }
488        }
489    }
490}
491
492fn need_forecast(format: &Format, format_alt: Option<&Format>) -> bool {
493    fn has_forecast_key(format: &Format) -> bool {
494        macro_rules! format_suffix {
495            ($($suffix: literal),* $(,)?) => {
496                false
497                $(
498                    || format.contains_key(concat!("temp_f", $suffix))
499                    || format.contains_key(concat!("apparent_f", $suffix))
500                    || format.contains_key(concat!("humidity_f", $suffix))
501                    || format.contains_key(concat!("wind_f", $suffix))
502                    || format.contains_key(concat!("wind_kmh_f", $suffix))
503                    || format.contains_key(concat!("direction_f", $suffix))
504                )*
505            };
506        }
507
508        format_suffix!("avg", "min", "max", "fin")
509            || format.contains_key("icon_ffin")
510            || format.contains_key("weather_ffin")
511            || format.contains_key("weather_verbose_ffin")
512    }
513    has_forecast_key(format) || format_alt.is_some_and(has_forecast_key)
514}
515
516fn calculate_sunrise_sunset(
517    lat: f64,
518    lon: f64,
519    altitude: Option<f64>,
520) -> Result<(DateTime<Utc>, DateTime<Utc>)> {
521    let date = Utc::now().date_naive();
522    let coordinates = sunrise::Coordinates::new(lat, lon).error("Invalid coordinates")?;
523    let solar_day = SolarDay::new(coordinates, date).with_altitude(altitude.unwrap_or_default());
524
525    Ok((
526        solar_day.event_time(SolarEvent::Sunrise),
527        solar_day.event_time(SolarEvent::Sunset),
528    ))
529}
530
531#[derive(Debug, Deserialize, Clone, Copy, PartialEq, Eq, SmartDefault)]
532#[serde(rename_all = "lowercase")]
533enum UnitSystem {
534    #[default]
535    Metric,
536    Imperial,
537}
538
539// Convert wind direction in azimuth degrees to abbreviation names
540fn convert_wind_direction(direction_opt: Option<f64>) -> &'static str {
541    match direction_opt {
542        Some(direction) => match direction.round() as i64 {
543            24..=68 => "NE",
544            69..=113 => "E",
545            114..=158 => "SE",
546            159..=203 => "S",
547            204..=248 => "SW",
548            249..=293 => "W",
549            294..=338 => "NW",
550            _ => "N",
551        },
552        None => "-",
553    }
554}
555
556/// Compute the Australian Apparent Temperature from metric units
557fn australian_apparent_temp(temp: f64, humidity: f64, wind_speed: f64) -> f64 {
558    let exponent = 17.27 * temp / (237.7 + temp);
559    let water_vapor_pressure = humidity * 0.06105 * exponent.exp();
560    temp + 0.33 * water_vapor_pressure - 0.7 * wind_speed - 4.0
561}
562
563#[cfg(test)]
564mod tests {
565    use super::*;
566
567    #[test]
568    fn test_new_forecast_average_wind_speed() {
569        let mut degrees = 0.0;
570        while degrees < 360.0 {
571            let forecast = Forecast::new(
572                &[
573                    ForecastAggregateSegment {
574                        temp: None,
575                        apparent: None,
576                        humidity: None,
577                        wind: Some(1.0),
578                        wind_kmh: Some(3.6),
579                        wind_direction: Some(degrees),
580                    },
581                    ForecastAggregateSegment {
582                        temp: None,
583                        apparent: None,
584                        humidity: None,
585                        wind: Some(2.0),
586                        wind_kmh: Some(7.2),
587                        wind_direction: Some(degrees),
588                    },
589                ],
590                WeatherMoment::default(),
591            );
592            assert!((forecast.avg.wind - 1.5).abs() < 0.1);
593            assert!((forecast.avg.wind_kmh - 5.4).abs() < 0.1);
594            assert!((forecast.avg.wind_direction.unwrap() - degrees).abs() < 0.1);
595
596            degrees += 15.0;
597        }
598    }
599
600    #[test]
601    fn test_new_forecast_average_wind_degrees() {
602        let mut degrees = 0.0;
603        while degrees < 360.0 {
604            let low = degrees - 1.0;
605            let high = degrees + 1.0;
606            let forecast = Forecast::new(
607                &[
608                    ForecastAggregateSegment {
609                        temp: None,
610                        apparent: None,
611                        humidity: None,
612                        wind: Some(1.0),
613                        wind_kmh: Some(3.6),
614                        wind_direction: Some(low),
615                    },
616                    ForecastAggregateSegment {
617                        temp: None,
618                        apparent: None,
619                        humidity: None,
620                        wind: Some(1.0),
621                        wind_kmh: Some(3.6),
622                        wind_direction: Some(high),
623                    },
624                ],
625                WeatherMoment::default(),
626            );
627            // For winds of equal strength the direction should will be the
628            // average of the low and high degrees
629            assert!((forecast.avg.wind_direction.unwrap() - degrees).abs() < 0.1);
630
631            degrees += 15.0;
632        }
633    }
634
635    #[test]
636    fn test_new_forecast_average_wind_speed_and_degrees() {
637        let mut degrees = 0.0;
638        while degrees < 360.0 {
639            let low = degrees - 1.0;
640            let high = degrees + 1.0;
641            let forecast = Forecast::new(
642                &[
643                    ForecastAggregateSegment {
644                        temp: None,
645                        apparent: None,
646                        humidity: None,
647                        wind: Some(1.0),
648                        wind_kmh: Some(3.6),
649                        wind_direction: Some(low),
650                    },
651                    ForecastAggregateSegment {
652                        temp: None,
653                        apparent: None,
654                        humidity: None,
655                        wind: Some(2.0),
656                        wind_kmh: Some(7.2),
657                        wind_direction: Some(high),
658                    },
659                ],
660                WeatherMoment::default(),
661            );
662            // Wind degree will be higher than the centerpoint of the low
663            // and high winds since the high wind is stronger and will be
664            // less than high
665            // (low+high)/2 < average.degrees < high
666            assert!((low + high) / 2.0 < forecast.avg.wind_direction.unwrap());
667            assert!(forecast.avg.wind_direction.unwrap() < high);
668            degrees += 15.0;
669        }
670    }
671}