weathr 1.0.0

A terminal-based ASCII weather application with animated scenes driven by real-time weather data
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
mod animation;
mod config;
mod render;
mod scene;
mod weather;

use animation::{
    birds::BirdSystem, chimney::ChimneySmoke, clouds::CloudSystem, fireflies::FireflySystem,
    leaves::FallingLeaves, moon::MoonSystem, raindrops::RaindropSystem, snow::SnowSystem,
    stars::StarSystem, sunny::SunnyAnimation, thunderstorm::ThunderstormSystem,
    AnimationController,
};
use clap::Parser;
use config::Config;
use crossterm::event::{self, Event, KeyCode, KeyModifiers};
use render::TerminalRenderer;
use scene::WorldScene;
use std::io;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::mpsc;
use weather::{
    OpenMeteoProvider, RainIntensity, SnowIntensity, WeatherClient, WeatherCondition, WeatherData,
    WeatherLocation, WeatherUnits,
};

const REFRESH_INTERVAL: Duration = Duration::from_secs(300);
const FRAME_DELAY: Duration = Duration::from_millis(500);
const TARGET_FPS: u64 = 30;
const FRAME_DURATION: Duration = Duration::from_millis(1000 / TARGET_FPS);

#[derive(Parser)]
#[command(version, about = "Terminal-based ASCII weather application", long_about = None)]
struct Cli {
    #[arg(
        short,
        long,
        value_name = "CONDITION",
        help = "Simulate weather condition (clear, rain, drizzle, snow, etc.)"
    )]
    simulate: Option<String>,

    #[arg(
        short,
        long,
        help = "Simulate night time (for testing moon, stars, fireflies)"
    )]
    night: bool,

    #[arg(short, long, help = "Enable falling autumn leaves")]
    leaves: bool,
}

#[tokio::main]
async fn main() -> io::Result<()> {
    let cli = Cli::parse();

    let config = match Config::load() {
        Ok(config) => config,
        Err(e) => {
            eprintln!("Error loading config: {}", e);
            eprintln!("\nContinuing with default location (Berlin: 52.52°N, 13.41°E)");
            eprintln!("\nTo customize, create a config file at:");
            eprintln!("  $XDG_CONFIG_HOME/weathr/config.toml");
            eprintln!("  or ~/.config/weathr/config.toml");
            eprintln!("\nExample config.toml:");
            eprintln!("  [location]");
            eprintln!("  latitude = 52.52");
            eprintln!("  longitude = 13.41");
            eprintln!();
            Config::default()
        }
    };

    let mut renderer = TerminalRenderer::new()?;
    renderer.init()?;

    let result = run_app(&config, &mut renderer, cli.simulate, cli.night, cli.leaves).await;

    renderer.cleanup()?;

    result
}

async fn run_app(
    config: &Config,
    renderer: &mut TerminalRenderer,
    simulate_condition: Option<String>,
    simulate_night: bool,
    show_leaves: bool,
) -> io::Result<()> {
    let mut world_scene = WorldScene::new(0, 0); // Will update size later
    let sunny_animation = SunnyAnimation::new();
    let mut animation_controller = AnimationController::new();

    let provider = Arc::new(OpenMeteoProvider::new());
    let weather_client = WeatherClient::new(provider, REFRESH_INTERVAL);

    let location = WeatherLocation {
        latitude: config.location.latitude,
        longitude: config.location.longitude,
        elevation: None,
    };
    let units = WeatherUnits::default();

    let (tx, mut rx) = mpsc::channel(1);

    if simulate_condition.is_none() {
        let client = weather_client.clone();

        tokio::spawn(async move {
            loop {
                let result = client.get_current_weather(&location, &units).await;
                if tx.send(result).await.is_err() {
                    break;
                }
                tokio::time::sleep(REFRESH_INTERVAL).await;
            }
        });
    }

    let mut last_frame_time = Instant::now();
    let mut current_weather = None;
    let mut weather_error: Option<String> = None;
    let mut is_raining = false;
    let mut is_snowing = false;
    let mut is_thunderstorm = false;
    let mut is_cloudy = false;
    let mut is_day = true;

    let mut loading_frame = 0;
    let loading_chars = ['|', '/', '-', '\\'];
    let mut last_loading_update = Instant::now();

    let (term_width, term_height) = renderer.get_size();
    world_scene.update_size(term_width, term_height);
    let mut raindrop_system = RaindropSystem::new(term_width, term_height, RainIntensity::Light);
    let mut snow_system = SnowSystem::new(term_width, term_height, SnowIntensity::Light);
    let mut thunderstorm_system = ThunderstormSystem::new(term_width, term_height);
    let mut cloud_system = CloudSystem::new(term_width, term_height);
    let mut bird_system = BirdSystem::new(term_width, term_height);
    let mut star_system = StarSystem::new(term_width, term_height);
    let mut moon_system = MoonSystem::new(term_width, term_height);
    let mut chimney_smoke = ChimneySmoke::new();
    let mut firefly_system = FireflySystem::new(term_width, term_height);
    let mut falling_leaves = FallingLeaves::new(term_width, term_height);

    if let Some(ref condition_str) = simulate_condition {
        let simulated_condition = parse_weather_condition(condition_str);
        is_thunderstorm = simulated_condition.is_thunderstorm();
        is_snowing = simulated_condition.is_snowing();
        is_raining = simulated_condition.is_raining() && !is_thunderstorm;

        raindrop_system.set_intensity(simulated_condition.rain_intensity());
        snow_system.set_intensity(simulated_condition.snow_intensity());
        is_cloudy = simulated_condition.is_cloudy();

        is_day = !simulate_night;

        current_weather = Some(WeatherData {
            condition: simulated_condition,
            temperature: 20.0,
            apparent_temperature: 19.0,
            humidity: 65.0,
            precipitation: if simulated_condition.is_raining() {
                2.5
            } else {
                0.0
            },
            wind_speed: 10.0,
            wind_direction: 180.0,
            cloud_cover: 50.0,
            pressure: 1013.0,
            visibility: Some(10000.0),
            is_day: !simulate_night,
            moon_phase: Some(0.5), // Simulated Full Moon
            timestamp: "simulated".to_string(),
        });
    }

    loop {
        if let Ok(result) = rx.try_recv() {
            match result {
                Ok(weather) => {
                    is_thunderstorm = weather.condition.is_thunderstorm();
                    is_snowing = weather.condition.is_snowing();
                    is_raining = weather.condition.is_raining() && !is_thunderstorm;

                    raindrop_system.set_intensity(weather.condition.rain_intensity());
                    snow_system.set_intensity(weather.condition.snow_intensity());
                    is_cloudy = weather.condition.is_cloudy();
                    is_day = weather.is_day;

                    if let Some(phase) = weather.moon_phase {
                        moon_system.set_phase(phase);
                    }

                    current_weather = Some(weather);
                    weather_error = None;
                }
                Err(e) => {
                    weather_error = Some(format!("Error fetching weather: {}", e));
                }
            }
        }

        renderer.update_size()?;
        let (term_width, term_height) = renderer.get_size();
        world_scene.update_size(term_width, term_height);

        renderer.clear()?;

        let condition_text = if let Some(ref weather) = current_weather {
            match weather.condition {
                WeatherCondition::Clear => "Clear",
                WeatherCondition::PartlyCloudy => "Partly Cloudy",
                WeatherCondition::Cloudy => "Cloudy",
                WeatherCondition::Overcast => "Overcast",
                WeatherCondition::Fog => "Fog",
                WeatherCondition::Drizzle => "Drizzle",
                WeatherCondition::Rain => "Rain",
                WeatherCondition::FreezingRain => "Freezing Rain",
                WeatherCondition::Snow => "Snow",
                WeatherCondition::SnowGrains => "Snow Grains",
                WeatherCondition::RainShowers => "Rain Showers",
                WeatherCondition::SnowShowers => "Snow Showers",
                WeatherCondition::Thunderstorm => "Thunderstorm",
                WeatherCondition::ThunderstormHail => "Thunderstorm with Hail",
            }
        } else {
            // Update loading frame
            if last_loading_update.elapsed() >= Duration::from_millis(100) {
                loading_frame = (loading_frame + 1) % loading_chars.len();
                last_loading_update = Instant::now();
            }
            "Loading"
        };

        let weather_info = if let Some(ref error) = weather_error {
            format!(
                "{} | Location: {:.2}°N, {:.2}°E | Press 'q' to quit",
                error, location.latitude, location.longitude
            )
        } else if let Some(ref weather) = current_weather {
            format!(
                "Weather: {} | Temp: {:.1}°C | Location: {:.2}°N, {:.2}°E | Press 'q' to quit",
                condition_text, weather.temperature, location.latitude, location.longitude
            )
        } else {
            format!(
                "Weather: Loading... {} | Location: {:.2}°N, {:.2}°E | Press 'q' to quit",
                loading_chars[loading_frame], location.latitude, location.longitude
            )
        };

        renderer.render_line_colored(2, 1, &weather_info, crossterm::style::Color::Cyan)?;

        if !is_day {
            star_system.update(term_width, term_height);
            star_system.render(renderer)?;
            moon_system.update(term_width, term_height);
            moon_system.render(renderer)?;

            // Fireflies appear on warm, clear nights
            if let Some(ref weather) = current_weather {
                let is_warm = weather.temperature > 15.0;
                let is_clear_night = matches!(
                    weather.condition,
                    WeatherCondition::Clear | WeatherCondition::PartlyCloudy
                );
                if is_warm && is_clear_night && !is_raining && !is_thunderstorm && !is_snowing {
                    firefly_system.update(term_width, term_height);
                    firefly_system.render(renderer)?;
                }
            }
        }

        if is_cloudy || (!is_raining && !is_thunderstorm && !is_snowing) {
            if is_cloudy {
                cloud_system.update(term_width, term_height);
                cloud_system.render(renderer)?;
            }

            if !is_raining && !is_thunderstorm && !is_snowing && is_day {
                bird_system.update(term_width, term_height);
                bird_system.render(renderer)?;
            }
        }

        let show_sun = if is_day {
            if let Some(ref weather) = current_weather {
                matches!(
                    weather.condition,
                    WeatherCondition::Clear | WeatherCondition::PartlyCloudy
                )
            } else {
                false
            }
        } else {
            false
        };

        if show_sun && !is_raining && !is_thunderstorm && !is_snowing {
            let animation_y = if term_height > 20 { 3 } else { 2 };
            animation_controller.render_frame(renderer, &sunny_animation, animation_y)?;
        }

        // Render World Scene (House, Ground, Decorations)
        world_scene.render(renderer)?;

        // Render chimney smoke (turn off when raining/thunderstorm)
        if !is_raining && !is_thunderstorm {
            let ground_height = 8;
            let horizon_y = term_height.saturating_sub(ground_height);
            let house_width = 64;
            let house_height = 13;
            let house_x = (term_width / 2).saturating_sub(house_width / 2);
            let house_y = horizon_y.saturating_sub(house_height);
            let chimney_x = house_x + 10;
            let chimney_y = house_y;
            chimney_smoke.update(chimney_x, chimney_y);
            chimney_smoke.render(renderer)?;
        }

        // Render foreground (rain/thunder)
        // Thunderstorm includes rain + lightning
        if is_thunderstorm {
            // Update and render rain first
            raindrop_system.update(term_width, term_height);
            raindrop_system.render(renderer)?;

            // Then lightning
            thunderstorm_system.update(term_width, term_height);
            thunderstorm_system.render(renderer)?;

            // Check for flash
            if thunderstorm_system.is_flashing() {
                renderer.flash_screen()?;
            }
        } else if is_raining {
            raindrop_system.update(term_width, term_height);
            raindrop_system.render(renderer)?;
        } else if is_snowing {
            snow_system.update(term_width, term_height);
            snow_system.render(renderer)?;
        }

        // Render falling leaves (if enabled)
        if show_leaves && !is_raining && !is_thunderstorm && !is_snowing {
            falling_leaves.update(term_width, term_height);
            falling_leaves.render(renderer)?;
        }

        renderer.flush()?;

        if event::poll(FRAME_DURATION)? {
            if let Event::Key(key_event) = event::read()? {
                match key_event.code {
                    KeyCode::Char('q') | KeyCode::Char('Q') => break,
                    KeyCode::Char('c') if key_event.modifiers.contains(KeyModifiers::CONTROL) => {
                        break
                    }
                    _ => {}
                }
            }
        }

        if !is_raining && !is_thunderstorm && !is_snowing {
            // Update sunny animation frame less frequently
            if last_frame_time.elapsed() >= FRAME_DELAY {
                animation_controller.next_frame(&sunny_animation);
                last_frame_time = Instant::now();
            }
        }
    }

    Ok(())
}

fn parse_weather_condition(input: &str) -> WeatherCondition {
    match input.to_lowercase().as_str() {
        "clear" | "sunny" => WeatherCondition::Clear,
        "partly-cloudy" | "partly_cloudy" | "partlycloudy" => WeatherCondition::PartlyCloudy,
        "cloudy" => WeatherCondition::Cloudy,
        "overcast" => WeatherCondition::Overcast,
        "fog" | "foggy" => WeatherCondition::Fog,
        "drizzle" => WeatherCondition::Drizzle,
        "rain" | "rainy" => WeatherCondition::Rain,
        "freezing-rain" | "freezing_rain" | "freezingrain" => WeatherCondition::FreezingRain,
        "snow" | "snowy" => WeatherCondition::Snow,
        "snow-grains" | "snow_grains" | "snowgrains" => WeatherCondition::SnowGrains,
        "rain-showers" | "rain_showers" | "rainshowers" | "showers" => {
            WeatherCondition::RainShowers
        }
        "snow-showers" | "snow_showers" | "snowshowers" => WeatherCondition::SnowShowers,
        "thunderstorm" | "thunder" => WeatherCondition::Thunderstorm,
        "thunderstorm-hail" | "thunderstorm_hail" | "hail" => WeatherCondition::ThunderstormHail,
        _ => {
            eprintln!("Unknown weather condition '{}', defaulting to Clear", input);
            WeatherCondition::Clear
        }
    }
}