aranet-cli 0.2.0

Command-line interface for Aranet environmental sensors
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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
//! Keyboard input handling for the TUI.
//!
//! This module provides key mapping and action handling for the terminal
//! user interface. It translates keyboard events into high-level actions
//! and applies those actions to the application state.
//!
//! # Key Bindings
//!
//! | Key       | Action            |
//! |-----------|-------------------|
//! | `q`       | Quit              |
//! | `s`       | Scan              |
//! | `r`       | Refresh           |
//! | `c`       | Connect           |
//! | `d`       | Disconnect        |
//! | `y`       | Sync history      |
//! | `↓` / `j` | Select next       |
//! | `↑` / `k` | Select previous   |
//! | `Tab` / `l` | Next tab        |
//! | `BackTab` / `h` | Previous tab |
//! | `?`       | Toggle help       |
//! | `D`       | Do Not Disturb    |
//! | `F`       | Toggle export fmt |

use std::time::Duration;

use crossterm::event::{KeyCode, MouseButton, MouseEvent, MouseEventKind};
use tokio::sync::mpsc;

use super::app::{App, ConnectionStatus, HistoryFilter, PendingAction, Tab, Theme};
use super::messages::Command;

/// User actions that can be triggered by keyboard input.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
    /// Quit the application.
    Quit,
    /// Start scanning for devices.
    Scan,
    /// Refresh readings for all connected devices.
    Refresh,
    /// Connect to the currently selected device.
    Connect,
    /// Connect to all devices.
    ConnectAll,
    /// Disconnect from the currently selected device.
    Disconnect,
    /// Sync history from the currently selected device.
    SyncHistory,
    /// Select the next item in the list.
    SelectNext,
    /// Select the previous item in the list.
    SelectPrevious,
    /// Switch to the next tab.
    NextTab,
    /// Switch to the previous tab.
    PreviousTab,
    /// Toggle the help overlay.
    ToggleHelp,
    /// Toggle data logging.
    ToggleLogging,
    /// Toggle terminal bell for alerts.
    ToggleBell,
    /// Dismiss current alert.
    DismissAlert,
    /// Scroll history up.
    ScrollUp,
    /// Scroll history down.
    ScrollDown,
    /// Set history filter.
    SetHistoryFilter(HistoryFilter),
    /// Increase threshold value.
    IncreaseThreshold,
    /// Decrease threshold value.
    DecreaseThreshold,
    /// Change setting value (in Settings tab).
    ChangeSetting,
    /// Export history to CSV file.
    ExportHistory,
    /// Toggle alert history view.
    ToggleAlertHistory,
    /// Cycle device filter.
    CycleDeviceFilter,
    /// Toggle sidebar visibility.
    ToggleSidebar,
    /// Toggle sidebar width.
    ToggleSidebarWidth,
    /// Mouse click at coordinates.
    MouseClick { x: u16, y: u16 },
    /// Confirm pending action.
    Confirm,
    /// Cancel pending action.
    Cancel,
    /// Toggle full-screen chart view.
    ToggleChart,
    /// Start editing device alias.
    EditAlias,
    /// Input character for text input.
    TextInput(char),
    /// Backspace for text input.
    TextBackspace,
    /// Submit text input.
    TextSubmit,
    /// Cancel text input.
    TextCancel,
    /// Toggle sticky alerts.
    ToggleStickyAlerts,
    /// Toggle comparison view.
    ToggleComparison,
    /// Cycle comparison device forward.
    NextComparisonDevice,
    /// Cycle comparison device backward.
    PrevComparisonDevice,
    /// Show error details popup.
    ShowErrorDetails,
    /// Toggle theme.
    ToggleTheme,
    /// Toggle temperature on chart.
    ToggleChartTemp,
    /// Toggle humidity on chart.
    ToggleChartHumidity,
    /// Toggle Bluetooth range.
    ToggleBleRange,
    /// Toggle Smart Home mode.
    ToggleSmartHome,
    /// Toggle Do Not Disturb mode.
    ToggleDoNotDisturb,
    /// Toggle export format (CSV/JSON).
    ToggleExportFormat,
    /// No action (unrecognized key).
    None,
}

/// Map a key code to an action.
///
/// # Arguments
///
/// * `key` - The key code from a keyboard event
/// * `editing_text` - Whether the user is currently editing text input
/// * `has_pending_confirmation` - Whether there is a pending confirmation dialog
///
/// # Returns
///
/// The corresponding action for the key, or [`Action::None`] if the key
/// is not mapped to any action.
pub fn handle_key(key: KeyCode, editing_text: bool, has_pending_confirmation: bool) -> Action {
    // If editing text, handle text input specially
    if editing_text {
        return match key {
            KeyCode::Enter => Action::TextSubmit,
            KeyCode::Esc => Action::TextCancel,
            KeyCode::Backspace => Action::TextBackspace,
            KeyCode::Char(c) => Action::TextInput(c),
            _ => Action::None,
        };
    }

    // When a confirmation dialog is active, only handle Y/N keys
    if has_pending_confirmation {
        return match key {
            KeyCode::Char('y') | KeyCode::Char('Y') => Action::Confirm,
            KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => Action::Cancel,
            _ => Action::None,
        };
    }

    match key {
        KeyCode::Char('q') => Action::Quit,
        KeyCode::Char('s') => Action::Scan,
        KeyCode::Char('r') => Action::Refresh,
        KeyCode::Char('c') => Action::Connect,
        KeyCode::Char('C') => Action::ConnectAll,
        KeyCode::Char('d') => Action::Disconnect,
        KeyCode::Char('S') | KeyCode::Char('y') => Action::SyncHistory,
        KeyCode::Down | KeyCode::Char('j') => Action::SelectNext,
        KeyCode::Up | KeyCode::Char('k') => Action::SelectPrevious,
        KeyCode::Tab | KeyCode::Char('l') => Action::NextTab,
        KeyCode::BackTab | KeyCode::Char('h') => Action::PreviousTab,
        KeyCode::Char('?') => Action::ToggleHelp,
        KeyCode::Char('L') => Action::ToggleLogging,
        KeyCode::Char('b') => Action::ToggleBell,
        KeyCode::Char('n') => Action::EditAlias,
        KeyCode::Esc => Action::DismissAlert,
        KeyCode::PageUp => Action::ScrollUp,
        KeyCode::PageDown => Action::ScrollDown,
        KeyCode::Char('0') => Action::SetHistoryFilter(HistoryFilter::All),
        KeyCode::Char('1') => Action::SetHistoryFilter(HistoryFilter::Today),
        KeyCode::Char('2') => Action::SetHistoryFilter(HistoryFilter::Last24Hours),
        KeyCode::Char('3') => Action::SetHistoryFilter(HistoryFilter::Last7Days),
        KeyCode::Char('4') => Action::SetHistoryFilter(HistoryFilter::Last30Days),
        KeyCode::Char('+') | KeyCode::Char('=') => Action::IncreaseThreshold,
        KeyCode::Char('-') | KeyCode::Char('_') => Action::DecreaseThreshold,
        KeyCode::Enter => Action::ChangeSetting,
        KeyCode::Char('e') => Action::ExportHistory,
        KeyCode::Char('a') => Action::ToggleAlertHistory,
        KeyCode::Char('f') => Action::CycleDeviceFilter,
        KeyCode::Char('[') => Action::ToggleSidebar,
        KeyCode::Char(']') => Action::ToggleSidebarWidth,
        KeyCode::Char('g') => Action::ToggleChart,
        KeyCode::Char('A') => Action::ToggleStickyAlerts,
        KeyCode::Char('v') => Action::ToggleComparison,
        KeyCode::Char('<') => Action::PrevComparisonDevice,
        KeyCode::Char('>') => Action::NextComparisonDevice,
        KeyCode::Char('E') => Action::ShowErrorDetails,
        KeyCode::Char('t') => Action::ToggleTheme,
        KeyCode::Char('T') => Action::ToggleChartTemp,
        KeyCode::Char('H') => Action::ToggleChartHumidity,
        KeyCode::Char('B') => Action::ToggleBleRange,
        KeyCode::Char('I') => Action::ToggleSmartHome,
        KeyCode::Char('D') => Action::ToggleDoNotDisturb,
        KeyCode::Char('F') => Action::ToggleExportFormat,
        _ => Action::None,
    }
}

/// Handle mouse events and return corresponding action.
///
/// # Arguments
///
/// * `event` - The mouse event from crossterm
///
/// # Returns
///
/// The corresponding action for the mouse event, or [`Action::None`] if the event
/// is not mapped to any action.
pub fn handle_mouse(event: MouseEvent) -> Action {
    match event.kind {
        MouseEventKind::Down(MouseButton::Left) => Action::MouseClick {
            x: event.column,
            y: event.row,
        },
        _ => Action::None,
    }
}

/// Handle navigation actions: tab switching, scrolling, item selection, mouse clicks.
fn apply_navigation_action(app: &mut App, action: Action) -> Option<Command> {
    match action {
        Action::SelectNext => {
            if app.active_tab == Tab::Settings {
                app.select_next_setting();
            } else {
                app.select_next_device();
            }
            None
        }
        Action::SelectPrevious => {
            if app.active_tab == Tab::Settings {
                app.select_previous_setting();
            } else {
                app.select_previous_device();
            }
            None
        }
        Action::NextTab => {
            app.active_tab = match app.active_tab {
                Tab::Dashboard => Tab::History,
                Tab::History => Tab::Settings,
                Tab::Settings => Tab::Service,
                Tab::Service => Tab::Dashboard,
            };
            None
        }
        Action::PreviousTab => {
            app.active_tab = match app.active_tab {
                Tab::Dashboard => Tab::Service,
                Tab::History => Tab::Dashboard,
                Tab::Settings => Tab::History,
                Tab::Service => Tab::Settings,
            };
            None
        }
        Action::ScrollUp => {
            if app.active_tab == Tab::History {
                app.scroll_history_up();
            }
            None
        }
        Action::ScrollDown => {
            if app.active_tab == Tab::History {
                app.scroll_history_down();
            }
            None
        }
        Action::SetHistoryFilter(filter) => {
            if app.active_tab == Tab::History {
                app.set_history_filter(filter);
            }
            None
        }
        Action::MouseClick { x, y } => {
            // Tab bar is at y=1-3, clicking on a tab switches to it
            if (1..=3).contains(&y) {
                // Simple tab detection based on x position
                if x < 15 {
                    app.active_tab = Tab::Dashboard;
                } else if x < 30 {
                    app.active_tab = Tab::History;
                } else if x < 45 {
                    app.active_tab = Tab::Settings;
                } else if x < 60 {
                    app.active_tab = Tab::Service;
                }
            }
            // Device list is in the left sidebar (x < ~25, y > 4)
            else if x < 25 && y > 4 {
                let device_row = (y as usize).saturating_sub(5);
                app.select_filtered_row(device_row);
            }
            None
        }
        _ => None,
    }
}

/// Handle device actions: connect, disconnect, scan, refresh, sync, confirm/cancel.
fn apply_device_action(app: &mut App, action: Action) -> Option<Command> {
    match action {
        Action::Scan => Some(Command::Scan {
            duration: Duration::from_secs(5),
        }),
        Action::Refresh => {
            if app.active_tab == Tab::Service {
                Some(Command::RefreshServiceStatus)
            } else {
                Some(Command::RefreshAll)
            }
        }
        Action::Connect => app.selected_device().map(|device| Command::Connect {
            device_id: device.id.clone(),
        }),
        Action::ConnectAll => {
            let first_disconnected = app
                .devices
                .iter()
                .find(|d| matches!(d.status, ConnectionStatus::Disconnected))
                .map(|d| d.id.clone());
            let count = app
                .devices
                .iter()
                .filter(|d| matches!(d.status, ConnectionStatus::Disconnected))
                .count();

            if let Some(device_id) = first_disconnected {
                app.push_status_message(format!("Connecting... ({} remaining)", count));
                return Some(Command::Connect { device_id });
            } else {
                app.push_status_message("All devices already connected".to_string());
            }
            None
        }
        Action::Disconnect => {
            if let Some(device) = app.selected_device()
                && matches!(device.status, ConnectionStatus::Connected)
            {
                let action = PendingAction::Disconnect {
                    device_id: device.id.clone(),
                    device_name: device.name.clone().unwrap_or_else(|| device.id.clone()),
                };
                app.request_confirmation(action);
            }
            None
        }
        Action::SyncHistory => app.selected_device().map(|device| Command::SyncHistory {
            device_id: device.id.clone(),
        }),
        Action::Confirm => {
            if app.pending_confirmation.is_some() {
                return app.confirm_action();
            }
            None
        }
        Action::Cancel => {
            if app.pending_confirmation.is_some() {
                app.cancel_confirmation();
            }
            None
        }
        Action::EditAlias => {
            app.start_alias_edit();
            None
        }
        Action::TextInput(c) => {
            if app.editing_alias {
                app.alias_input_char(c);
            }
            None
        }
        Action::TextBackspace => {
            if app.editing_alias {
                app.alias_input_backspace();
            }
            None
        }
        Action::TextSubmit => {
            if app.editing_alias {
                app.save_alias();
            }
            None
        }
        Action::TextCancel => {
            if app.editing_alias {
                app.cancel_alias_edit();
            }
            None
        }
        Action::ExportHistory => {
            if let Some(path) = app.export_history() {
                app.push_status_message(format!("Exported to {}", path));
            } else {
                app.push_status_message("No history to export".to_string());
            }
            None
        }
        Action::CycleDeviceFilter => {
            app.cycle_device_filter();
            None
        }
        _ => None,
    }
}

/// Handle settings actions: threshold adjustments, interval changes, service control.
fn apply_settings_action(app: &mut App, action: Action) -> Option<Command> {
    match action {
        Action::IncreaseThreshold => {
            if app.active_tab == Tab::Settings {
                match app.selected_setting {
                    1 => app.increase_co2_threshold(),
                    2 => app.increase_radon_threshold(),
                    _ => {}
                }
                app.push_status_message(format!(
                    "CO2: {} ppm, Radon: {} Bq/m³",
                    app.co2_alert_threshold, app.radon_alert_threshold
                ));
            }
            None
        }
        Action::DecreaseThreshold => {
            if app.active_tab == Tab::Settings {
                match app.selected_setting {
                    1 => app.decrease_co2_threshold(),
                    2 => app.decrease_radon_threshold(),
                    _ => {}
                }
                app.push_status_message(format!(
                    "CO2: {} ppm, Radon: {} Bq/m³",
                    app.co2_alert_threshold, app.radon_alert_threshold
                ));
            }
            None
        }
        Action::ChangeSetting => {
            if app.active_tab == Tab::Service {
                if let Some(ref status) = app.service_status {
                    if status.reachable {
                        if status.collector_running {
                            return Some(Command::StopServiceCollector);
                        } else {
                            return Some(Command::StartServiceCollector);
                        }
                    } else {
                        app.push_status_message("Service not reachable".to_string());
                    }
                } else {
                    app.push_status_message(
                        "Service status unknown - press 'r' to refresh".to_string(),
                    );
                }
                None
            } else if app.active_tab == Tab::Settings && app.selected_setting == 0 {
                if let Some((device_id, new_interval)) = app.cycle_interval() {
                    return Some(Command::SetInterval {
                        device_id,
                        interval_secs: new_interval,
                    });
                }
                None
            } else {
                None
            }
        }
        Action::ToggleLogging => {
            app.toggle_logging();
            None
        }
        Action::ToggleBell => {
            app.bell_enabled = !app.bell_enabled;
            app.push_status_message(format!(
                "Bell notifications {}",
                if app.bell_enabled {
                    "enabled"
                } else {
                    "disabled"
                }
            ));
            None
        }
        Action::ToggleAlertHistory => {
            app.toggle_alert_history();
            None
        }
        Action::ToggleStickyAlerts => {
            app.toggle_sticky_alerts();
            None
        }
        Action::ToggleBleRange => {
            app.toggle_ble_range();
            None
        }
        Action::ToggleSmartHome => {
            app.toggle_smart_home();
            None
        }
        Action::ToggleDoNotDisturb => {
            app.toggle_do_not_disturb();
            None
        }
        Action::ToggleExportFormat => {
            app.toggle_export_format();
            None
        }
        _ => None,
    }
}

/// Handle view/display actions: theme, help, sidebar, chart, comparison, errors.
fn apply_view_action(app: &mut App, action: Action) -> Option<Command> {
    match action {
        Action::ToggleHelp => {
            app.show_help = !app.show_help;
            None
        }
        Action::DismissAlert => {
            if app.show_help {
                app.show_help = false;
            } else if app.show_error_details {
                app.show_error_details = false;
            } else if let Some(device) = app.selected_device() {
                let device_id = device.id.clone();
                app.dismiss_alert(&device_id);
            }
            None
        }
        Action::ToggleSidebar => {
            app.toggle_sidebar();
            app.push_status_message(
                if app.show_sidebar {
                    "Sidebar shown"
                } else {
                    "Sidebar hidden"
                }
                .to_string(),
            );
            None
        }
        Action::ToggleSidebarWidth => {
            app.toggle_sidebar_width();
            app.push_status_message(format!("Sidebar width: {}", app.sidebar_width));
            None
        }
        Action::ToggleChart => {
            app.toggle_fullscreen_chart();
            None
        }
        Action::ToggleComparison => {
            app.toggle_comparison();
            None
        }
        Action::NextComparisonDevice => {
            app.cycle_comparison_device(true);
            None
        }
        Action::PrevComparisonDevice => {
            app.cycle_comparison_device(false);
            None
        }
        Action::ShowErrorDetails => {
            app.toggle_error_details();
            None
        }
        Action::ToggleTheme => {
            app.toggle_theme();
            let theme_name = match app.theme {
                Theme::Dark => "dark",
                Theme::Light => "light",
            };
            app.push_status_message(format!("Theme: {}", theme_name));
            None
        }
        Action::ToggleChartTemp => {
            app.toggle_chart_metric(App::METRIC_TEMP);
            let status = if app.chart_shows(App::METRIC_TEMP) {
                "shown"
            } else {
                "hidden"
            };
            app.push_status_message(format!("Temperature on chart: {}", status));
            None
        }
        Action::ToggleChartHumidity => {
            app.toggle_chart_metric(App::METRIC_HUMIDITY);
            let status = if app.chart_shows(App::METRIC_HUMIDITY) {
                "shown"
            } else {
                "hidden"
            };
            app.push_status_message(format!("Humidity on chart: {}", status));
            None
        }
        _ => None,
    }
}

/// Apply an action to the application state.
///
/// This function handles both UI-only actions (which modify app state directly)
/// and command actions (which return a command to be sent to the background worker).
/// Actions are dispatched to focused handler functions by category:
/// navigation, device, settings, and view actions.
///
/// # Arguments
///
/// * `app` - Mutable reference to the application state
/// * `action` - The action to apply
/// * `_command_tx` - Channel for sending commands (used for reference, actual sending done by caller)
///
/// # Returns
///
/// `Some(Command)` if an async command should be sent to the background worker,
/// `None` if the action was handled entirely within the UI.
pub fn apply_action(
    app: &mut App,
    action: Action,
    _command_tx: &mpsc::Sender<Command>,
) -> Option<Command> {
    match action {
        Action::Quit => {
            app.should_quit = true;
            None
        }
        Action::None => None,

        // Navigation: tab switching, scrolling, item selection, mouse clicks
        Action::SelectNext
        | Action::SelectPrevious
        | Action::NextTab
        | Action::PreviousTab
        | Action::ScrollUp
        | Action::ScrollDown
        | Action::SetHistoryFilter(_)
        | Action::MouseClick { .. } => apply_navigation_action(app, action),

        // Device: scan, connect, disconnect, sync, confirm/cancel, alias, export, filter
        Action::Scan
        | Action::Refresh
        | Action::Connect
        | Action::ConnectAll
        | Action::Disconnect
        | Action::SyncHistory
        | Action::Confirm
        | Action::Cancel
        | Action::EditAlias
        | Action::TextInput(_)
        | Action::TextBackspace
        | Action::TextSubmit
        | Action::TextCancel
        | Action::ExportHistory
        | Action::CycleDeviceFilter => apply_device_action(app, action),

        // Settings: thresholds, intervals, toggles for logging/bell/alerts/BLE/smart home
        Action::IncreaseThreshold
        | Action::DecreaseThreshold
        | Action::ChangeSetting
        | Action::ToggleLogging
        | Action::ToggleBell
        | Action::ToggleAlertHistory
        | Action::ToggleStickyAlerts
        | Action::ToggleBleRange
        | Action::ToggleSmartHome
        | Action::ToggleDoNotDisturb
        | Action::ToggleExportFormat => apply_settings_action(app, action),

        // View: theme, help, sidebar, chart, comparison, error details
        Action::ToggleHelp
        | Action::DismissAlert
        | Action::ToggleSidebar
        | Action::ToggleSidebarWidth
        | Action::ToggleChart
        | Action::ToggleComparison
        | Action::NextComparisonDevice
        | Action::PrevComparisonDevice
        | Action::ShowErrorDetails
        | Action::ToggleTheme
        | Action::ToggleChartTemp
        | Action::ToggleChartHumidity => apply_view_action(app, action),
    }
}