55 lines
1.6 KiB
Rust

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
/// System and location information
///
/// Contains country, sunrise/sunset times, and internal API parameters.
#[derive(Debug, Clone, Deserialize, Serialize, Default, PartialEq)]
pub struct Sys {
/// Internal parameter
#[serde(default)]
pub r#type: Option<u8>,
/// Internal parameter
#[serde(default)]
pub id: Option<u32>,
/// Country code (ISO 3166-1 alpha-2, e.g. "GB", "JP")
#[serde(default)]
pub country: Option<String>,
/// Sunrise time (UTC Unix timestamp)
#[serde(with = "chrono::serde::ts_seconds_option")]
pub sunrise: Option<DateTime<Utc>>,
/// Sunset time (UTC Unix timestamp)
#[serde(with = "chrono::serde::ts_seconds_option")]
pub sunset: Option<DateTime<Utc>>,
/// Internal parameter (often used for error messages)
#[serde(default)]
pub message: Option<f64>,
}
impl Sys {
/// Returns true if it's currently daytime at the location
///
/// Compares current UTC time with sunrise and sunset times.
#[must_use]
pub fn is_daytime(&self) -> Option<bool> {
let now = Utc::now();
match (self.sunrise, self.sunset) {
(Some(sunrise), Some(sunset)) => Some(now >= sunrise && now <= sunset),
_ => None,
}
}
/// Returns the duration of daylight (sunset - sunrise)
///
/// Returns `None` if either sunrise or sunset data is missing.
#[must_use]
pub fn daylight_duration(&self) -> Option<chrono::Duration> {
Some(self.sunset? - self.sunrise?)
}
}