weatherstat/src/weather.rs

80 lines
2.1 KiB
Rust

use futures_util::future::TryFutureExt;
use serde::Deserialize;
use std::env;
#[derive(Debug, Deserialize)]
struct APIResponseWeather {
main: String,
description: String,
}
#[derive(Debug, Deserialize)]
struct APIResponseMain {
temp: f32,
temp_min: f32,
temp_max: f32,
feels_like: f32,
humidity: u32,
pressure: u32,
}
#[derive(Debug, Deserialize)]
struct APIResponse {
weather: Vec<APIResponseWeather>,
main: APIResponseMain,
}
#[derive(Debug)]
pub enum WeatherSummary {
Thunderstorm(i32, i32),
Clouds(i32, i32),
Snow(i32, i32),
Rain(i32, i32),
Drizzle(i32, i32),
Clear(i32, i32),
Atmospheric(i32, i32),
}
impl From<APIResponse> for WeatherSummary {
fn from(resp: APIResponse) -> Self {
let temp_min = resp.main.temp_min as i32;
let temp_max = resp.main.temp_max as i32;
match resp.weather[0].main.as_ref() {
"Thunderstorm" => Self::Thunderstorm(temp_min, temp_max),
"Clouds" => Self::Clouds(temp_min, temp_max),
"Snow" => Self::Snow(temp_min, temp_max),
"Rain" => Self::Rain(temp_min, temp_max),
"Drizzle" => Self::Drizzle(temp_min, temp_max),
"Clear" => Self::Clear(temp_min, temp_max),
"Atmosphere" => Self::Atmospheric(temp_min, temp_max),
_ => panic!("unrecognized weather type"),
}
}
}
pub async fn get_summary(loc: &str) -> Result<WeatherSummary, String> {
let url = format!(
"https://api.openweathermap.org/data/2.5/weather?q={}&appid={}&units=metric",
loc,
env::var("OPEN_WEATHERMAP_API_KEY").expect("could not load OPEN_WEATHERMAP_API_KEY")
);
let resp = reqwest::get(&url).map_err(|e| e.to_string()).await?;
//println!("{}", resp.text().map_err(|e| e.to_string()).await?);
if !resp.status().is_success() {
return Err(format!("Weather API response: {}", resp.status()).into());
}
let api_response = resp
.json::<APIResponse>()
.map_err(|e| e.to_string())
.await?;
println!("Got API resp: {:?}", api_response);
Ok(api_response.into())
}