1use 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 "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 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
539fn 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
556fn 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 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 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}