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
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
//! Configuration file management.

use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

/// Configuration file structure
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Config {
    /// Default device address
    #[serde(default)]
    pub device: Option<String>,

    /// Default output format
    #[serde(default)]
    pub format: Option<String>,

    /// Disable colored output
    #[serde(default)]
    pub no_color: bool,

    /// Use Fahrenheit for temperature
    #[serde(default)]
    pub fahrenheit: bool,

    /// Use inHg for pressure (instead of hPa)
    #[serde(default)]
    pub inhg: bool,

    /// Use Bq/m³ for radon (instead of pCi/L)
    #[serde(default)]
    pub bq: bool,

    /// Connection timeout in seconds
    #[serde(default)]
    pub timeout: Option<u64>,

    /// Device aliases (friendly name -> device address)
    #[serde(default)]
    pub aliases: HashMap<String, String>,

    /// Last successfully connected device (auto-updated)
    #[serde(default)]
    pub last_device: Option<String>,

    /// Name of the last connected device (for display)
    #[serde(default)]
    pub last_device_name: Option<String>,

    /// Behavior settings for unified data architecture
    #[serde(default)]
    pub behavior: BehaviorConfig,

    /// GUI-specific settings
    #[serde(default)]
    pub gui: GuiConfig,
}

/// GUI-specific configuration settings.
///
/// Controls appearance and behavior of the native GUI application.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GuiConfig {
    /// Theme preference: "dark", "light", or "system"
    #[serde(default = "default_theme")]
    pub theme: String,

    /// Show colored tray icon for elevated CO2 levels.
    /// When false, always uses native template icon (auto dark/light).
    /// When true, shows colored icons (yellow/orange/red) for elevated CO2.
    #[serde(default = "default_true")]
    pub colored_tray_icon: bool,

    /// Enable desktop notifications for CO2 threshold alerts.
    #[serde(default = "default_true")]
    pub notifications_enabled: bool,

    /// Play sound with desktop notifications.
    #[serde(default = "default_true")]
    pub notification_sound: bool,

    /// Start the application minimized to system tray.
    #[serde(default)]
    pub start_minimized: bool,

    /// Minimize to tray instead of quitting when closing window.
    #[serde(default = "default_true")]
    pub close_to_tray: bool,

    /// Temperature unit preference: "celsius" or "fahrenheit".
    /// Used when device settings are not available.
    #[serde(default = "default_celsius")]
    pub temperature_unit: String,

    /// Pressure unit preference: "hpa" or "inhg".
    /// Used for pressure display.
    #[serde(default = "default_hpa")]
    pub pressure_unit: String,

    /// Whether the sidebar is collapsed.
    #[serde(default)]
    pub sidebar_collapsed: bool,

    /// Enable compact mode for denser layout on smaller screens.
    #[serde(default)]
    pub compact_mode: bool,

    /// Remembered window width.
    #[serde(default)]
    pub window_width: Option<f32>,

    /// Remembered window height.
    #[serde(default)]
    pub window_height: Option<f32>,

    /// Remembered window X position.
    #[serde(default)]
    pub window_x: Option<f32>,

    /// Remembered window Y position.
    #[serde(default)]
    pub window_y: Option<f32>,

    /// CO2 warning threshold in ppm (yellow/amber indicator).
    #[serde(default = "default_co2_warning")]
    pub co2_warning_threshold: u16,

    /// CO2 danger threshold in ppm (red indicator).
    #[serde(default = "default_co2_danger")]
    pub co2_danger_threshold: u16,

    /// Radon warning threshold in Bq/m³.
    #[serde(default = "default_radon_warning")]
    pub radon_warning_threshold: u32,

    /// Radon danger threshold in Bq/m³.
    #[serde(default = "default_radon_danger")]
    pub radon_danger_threshold: u32,

    /// Default export format: "csv" or "json".
    #[serde(default = "default_export_format")]
    pub default_export_format: String,

    /// Custom export directory path. Empty string means use default (Downloads).
    #[serde(default)]
    pub export_directory: String,

    /// URL for the aranet-service REST API.
    /// Default: "http://localhost:8080"
    #[serde(default = "default_service_url")]
    pub service_url: String,

    /// Optional API key for authenticated aranet-service deployments.
    #[serde(default)]
    pub service_api_key: Option<String>,

    /// Show CO2 readings in dashboard.
    #[serde(default = "default_true")]
    pub show_co2: bool,

    /// Show temperature readings in dashboard.
    #[serde(default = "default_true")]
    pub show_temperature: bool,

    /// Show humidity readings in dashboard.
    #[serde(default = "default_true")]
    pub show_humidity: bool,

    /// Show pressure readings in dashboard.
    #[serde(default = "default_true")]
    pub show_pressure: bool,

    /// Do Not Disturb mode - suppress all notifications.
    #[serde(default)]
    pub do_not_disturb: bool,
}

fn default_service_url() -> String {
    "http://localhost:8080".to_string()
}

fn default_theme() -> String {
    "dark".to_string()
}

fn default_celsius() -> String {
    "celsius".to_string()
}

fn default_hpa() -> String {
    "hpa".to_string()
}

fn default_co2_warning() -> u16 {
    1000
}

fn default_co2_danger() -> u16 {
    1400
}

fn default_radon_warning() -> u32 {
    100
}

fn default_radon_danger() -> u32 {
    150
}

fn default_export_format() -> String {
    "csv".to_string()
}

impl Default for GuiConfig {
    fn default() -> Self {
        Self {
            theme: default_theme(),
            colored_tray_icon: true,
            notifications_enabled: true,
            notification_sound: true,
            start_minimized: false,
            close_to_tray: true,
            temperature_unit: default_celsius(),
            pressure_unit: default_hpa(),
            sidebar_collapsed: false,
            compact_mode: false,
            window_width: None,
            window_height: None,
            window_x: None,
            window_y: None,
            co2_warning_threshold: default_co2_warning(),
            co2_danger_threshold: default_co2_danger(),
            radon_warning_threshold: default_radon_warning(),
            radon_danger_threshold: default_radon_danger(),
            default_export_format: default_export_format(),
            export_directory: String::new(),
            service_url: default_service_url(),
            service_api_key: None,
            show_co2: true,
            show_temperature: true,
            show_humidity: true,
            show_pressure: true,
            do_not_disturb: false,
        }
    }
}

/// Behavior configuration for unified data architecture.
///
/// Controls automatic connection, sync, and device memory across all tools.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BehaviorConfig {
    /// Auto-connect to known devices on startup (TUI/GUI)
    #[serde(default = "default_true")]
    pub auto_connect: bool,

    /// Auto-sync history on connection
    #[serde(default = "default_true")]
    pub auto_sync: bool,

    /// Remember devices in database after connection
    #[serde(default = "default_true")]
    pub remember_devices: bool,

    /// Load cached data (devices, readings) on startup
    #[serde(default = "default_true")]
    pub load_cache: bool,
}

fn default_true() -> bool {
    true
}

impl Default for BehaviorConfig {
    fn default() -> Self {
        Self {
            auto_connect: true,
            auto_sync: true,
            remember_devices: true,
            load_cache: true,
        }
    }
}

impl Config {
    /// Get the config file path.
    ///
    /// Checks `ARANET_CONFIG_DIR` first, then falls back to the platform config directory.
    pub fn path() -> PathBuf {
        std::env::var_os("ARANET_CONFIG_DIR")
            .map(PathBuf::from)
            .or_else(|| dirs::config_dir().map(|d| d.join("aranet")))
            .unwrap_or_else(|| PathBuf::from("."))
            .join("config.toml")
    }

    /// Load config from the default path.
    ///
    /// Returns an error if the file exists but cannot be read or parsed.
    pub fn load() -> Result<Self> {
        Self::load_from_path(&Self::path())
    }

    /// Load config from the default path, returning defaults when the file is absent.
    ///
    /// Returns an error if the file exists but cannot be read or parsed.
    pub fn load_or_default() -> Result<Self> {
        Self::load_from_path_or_default(&Self::path())
    }

    /// Load config from an explicit path.
    pub fn load_from_path(path: &Path) -> Result<Self> {
        let content = fs::read_to_string(path)
            .with_context(|| format!("Failed to read config file: {}", path.display()))?;
        toml::from_str(&content)
            .with_context(|| format!("Failed to parse config file: {}", path.display()))
    }

    /// Load config from an explicit path, returning defaults when the file is absent.
    pub fn load_from_path_or_default(path: &Path) -> Result<Self> {
        if !path.exists() {
            return Ok(Self::default());
        }

        Self::load_from_path(path)
    }

    /// Load config from the default path, logging a warning and falling back to defaults on error.
    ///
    /// This helper is for non-fatal UI paths that should remain usable while still surfacing
    /// broken config files in the logs.
    pub fn load_or_default_logged() -> Self {
        match Self::load_or_default() {
            Ok(config) => config,
            Err(err) => {
                tracing::warn!("Failed to load config file: {err:#}");
                Self::default()
            }
        }
    }

    /// Save config to file
    pub fn save(&self) -> Result<()> {
        let path = Self::path();
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).with_context(|| {
                format!("Failed to create config directory: {}", parent.display())
            })?;
        }
        let content = toml::to_string_pretty(self).context("Failed to serialize config")?;
        fs::write(&path, content)
            .with_context(|| format!("Failed to write config: {}", path.display()))?;
        Ok(())
    }
}

/// Resolve multiple devices, applying alias resolution to each.
/// Returns an empty Vec if no devices are specified.
pub fn resolve_devices(devices: Vec<String>, config: &Config) -> Vec<String> {
    devices
        .into_iter()
        .map(|d| resolve_alias(&d, config))
        .collect()
}

/// Resolve an alias to its device address, or return the original if not an alias.
pub fn resolve_alias(device: &str, config: &Config) -> String {
    config
        .aliases
        .get(device)
        .cloned()
        .unwrap_or_else(|| device.to_string())
}

/// Resolve an alias and return information about the resolution.
/// Returns (resolved_address, was_alias, original_alias_name).
pub fn resolve_alias_with_info(device: &str, config: &Config) -> (String, bool, Option<String>) {
    if let Some(address) = config.aliases.get(device) {
        (address.clone(), true, Some(device.to_string()))
    } else {
        (device.to_string(), false, None)
    }
}

/// Print alias resolution feedback if the user is not in quiet mode.
/// Call this after resolving an alias to inform the user which device was selected.
pub fn print_alias_feedback(original: &str, resolved: &str, quiet: bool) {
    if !quiet && original != resolved {
        eprintln!("Using device '{}' -> {}", original, resolved);
    }
}

/// Print device source feedback (e.g., "Using last connected device: ...").
pub fn print_device_source_feedback(device: &str, source: Option<&str>, quiet: bool) {
    if quiet {
        return;
    }
    match source {
        Some("default") => eprintln!("Using default device: {}", device),
        Some("last") => eprintln!("Using last connected device: {}", device),
        Some("store") => eprintln!("Using known device from database: {}", device),
        _ => {}
    }
}

/// Update the last connected device in config.
/// This is called after a successful connection.
pub fn update_last_device(identifier: &str, name: Option<&str>) -> Result<()> {
    let mut config = Config::load_or_default()?;
    config.last_device = Some(identifier.to_string());
    config.last_device_name = name.map(|n| n.to_string());
    config.save()
}

/// Get info about whether we're using a fallback device.
/// Returns (device_identifier, fallback_source) where fallback_source is:
/// - None if device was explicitly provided
/// - Some("default") if using default device
/// - Some("last") if using last connected device
/// - Some("store") if using known device from database
pub fn get_device_source(
    device: Option<&str>,
    config: &Config,
) -> (Option<String>, Option<&'static str>) {
    if let Some(d) = device {
        (Some(resolve_alias(d, config)), None)
    } else if let Some(d) = &config.device {
        (Some(d.clone()), Some("default"))
    } else if let Some(d) = &config.last_device {
        (Some(d.clone()), Some("last"))
    } else if config.behavior.load_cache {
        // Try to get a known device from the store
        if let Some(d) = get_first_known_device() {
            (Some(d), Some("store"))
        } else {
            (None, None)
        }
    } else {
        (None, None)
    }
}

/// Get the first known device from the store database.
///
/// Returns the device ID of the most recently connected device in the store,
/// or None if the store is empty or cannot be opened.
fn get_first_known_device() -> Option<String> {
    let store_path = aranet_store::default_db_path();
    let store = aranet_store::Store::open(&store_path).ok()?;
    let devices = store.list_devices().ok()?;
    devices.first().map(|d| d.id.clone())
}

/// Resolve timeout: use provided value, fall back to config, then default.
pub fn resolve_timeout(cmd_timeout: Option<u64>, config: &Config, default: u64) -> u64 {
    cmd_timeout.or(config.timeout).unwrap_or(default)
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn test_resolve_timeout_uses_explicit_value() {
        let config = Config {
            timeout: Some(60),
            ..Default::default()
        };
        let result = resolve_timeout(Some(45), &config, 30);
        assert_eq!(result, 45);
    }

    #[test]
    fn test_resolve_timeout_uses_config_when_missing() {
        let config = Config {
            timeout: Some(60),
            ..Default::default()
        };
        let result = resolve_timeout(None, &config, 30);
        assert_eq!(result, 60);
    }

    #[test]
    fn test_resolve_timeout_uses_default_when_no_config() {
        let config = Config::default();
        let result = resolve_timeout(None, &config, 30);
        assert_eq!(result, 30);
    }

    #[test]
    fn test_behavior_config_defaults_to_true() {
        let behavior = BehaviorConfig::default();
        assert!(behavior.auto_connect);
        assert!(behavior.auto_sync);
        assert!(behavior.remember_devices);
        assert!(behavior.load_cache);
    }

    #[test]
    fn test_config_has_default_behavior() {
        let config = Config::default();
        assert!(config.behavior.auto_connect);
        assert!(config.behavior.auto_sync);
        assert!(config.behavior.remember_devices);
        assert!(config.behavior.load_cache);
    }

    #[test]
    fn test_load_from_path_or_default_returns_default_when_missing() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("missing.toml");

        let config = Config::load_from_path_or_default(&path).unwrap();
        assert!(config.device.is_none());
        assert!(config.aliases.is_empty());
    }

    #[test]
    fn test_load_from_path_reports_parse_errors() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("config.toml");
        fs::write(&path, "device = [").unwrap();

        let err = Config::load_from_path(&path).unwrap_err();
        assert!(err.to_string().contains("Failed to parse config file"));
    }

    #[test]
    fn test_load_from_path_reads_valid_config() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("config.toml");
        fs::write(
            &path,
            r#"
device = "Aranet4 12345"
fahrenheit = true

[aliases]
office = "Aranet4 12345"
"#,
        )
        .unwrap();

        let config = Config::load_from_path(&path).unwrap();
        assert_eq!(config.device.as_deref(), Some("Aranet4 12345"));
        assert!(config.fahrenheit);
        assert_eq!(
            config.aliases.get("office").map(String::as_str),
            Some("Aranet4 12345")
        );
    }

    #[test]
    fn test_behavior_config_serialization() {
        let behavior = BehaviorConfig {
            auto_connect: false,
            auto_sync: true,
            remember_devices: false,
            load_cache: true,
        };
        let toml_str = toml::to_string(&behavior).unwrap();
        assert!(toml_str.contains("auto_connect = false"));
        assert!(toml_str.contains("auto_sync = true"));

        // Deserialize back
        let parsed: BehaviorConfig = toml::from_str(&toml_str).unwrap();
        assert!(!parsed.auto_connect);
        assert!(parsed.auto_sync);
        assert!(!parsed.remember_devices);
        assert!(parsed.load_cache);
    }

    // ========================================================================
    // resolve_alias tests
    // ========================================================================

    #[test]
    fn test_resolve_alias_found() {
        let mut aliases = std::collections::HashMap::new();
        aliases.insert("living-room".to_string(), "AA:BB:CC:DD:EE:FF".to_string());
        aliases.insert("bedroom".to_string(), "11:22:33:44:55:66".to_string());

        let config = Config {
            aliases,
            ..Default::default()
        };

        let result = resolve_alias("living-room", &config);
        assert_eq!(result, "AA:BB:CC:DD:EE:FF");
    }

    #[test]
    fn test_resolve_alias_not_found() {
        let config = Config::default();
        let result = resolve_alias("unknown-alias", &config);
        assert_eq!(result, "unknown-alias");
    }

    #[test]
    fn test_resolve_alias_empty_aliases() {
        let config = Config::default();
        let result = resolve_alias("some-device", &config);
        assert_eq!(result, "some-device");
    }

    #[test]
    fn test_resolve_alias_returns_address_unchanged() {
        let config = Config::default();
        // If you pass an actual address, it should return unchanged
        let result = resolve_alias("AA:BB:CC:DD:EE:FF", &config);
        assert_eq!(result, "AA:BB:CC:DD:EE:FF");
    }

    // ========================================================================
    // resolve_devices tests
    // ========================================================================

    #[test]
    fn test_resolve_devices_empty() {
        let config = Config::default();
        let result = resolve_devices(vec![], &config);
        assert!(result.is_empty());
    }

    #[test]
    fn test_resolve_devices_multiple() {
        let mut aliases = std::collections::HashMap::new();
        aliases.insert("room1".to_string(), "AA:BB:CC:DD:EE:FF".to_string());
        aliases.insert("room2".to_string(), "11:22:33:44:55:66".to_string());

        let config = Config {
            aliases,
            ..Default::default()
        };

        let devices = vec![
            "room1".to_string(),
            "room2".to_string(),
            "direct-address".to_string(),
        ];
        let result = resolve_devices(devices, &config);

        assert_eq!(result.len(), 3);
        assert_eq!(result[0], "AA:BB:CC:DD:EE:FF");
        assert_eq!(result[1], "11:22:33:44:55:66");
        assert_eq!(result[2], "direct-address");
    }

    #[test]
    fn test_resolve_devices_no_aliases() {
        let config = Config::default();
        let devices = vec!["device1".to_string(), "device2".to_string()];
        let result = resolve_devices(devices, &config);

        assert_eq!(result.len(), 2);
        assert_eq!(result[0], "device1");
        assert_eq!(result[1], "device2");
    }

    // ========================================================================
    // get_device_source tests
    // ========================================================================

    #[test]
    fn test_get_device_source_explicit() {
        let config = Config::default();
        let (device, source) = get_device_source(Some("explicit-device"), &config);

        assert_eq!(device, Some("explicit-device".to_string()));
        assert_eq!(source, None); // No fallback source when explicit
    }

    #[test]
    fn test_get_device_source_from_default() {
        let config = Config {
            device: Some("default-device".to_string()),
            ..Default::default()
        };
        let (device, source) = get_device_source(None, &config);

        assert_eq!(device, Some("default-device".to_string()));
        assert_eq!(source, Some("default"));
    }

    #[test]
    fn test_get_device_source_from_last() {
        let config = Config {
            last_device: Some("last-device".to_string()),
            ..Default::default()
        };
        let (device, source) = get_device_source(None, &config);

        assert_eq!(device, Some("last-device".to_string()));
        assert_eq!(source, Some("last"));
    }

    #[test]
    fn test_get_device_source_prefers_default_over_last() {
        let config = Config {
            device: Some("default-device".to_string()),
            last_device: Some("last-device".to_string()),
            ..Default::default()
        };
        let (device, source) = get_device_source(None, &config);

        // Default should take precedence over last
        assert_eq!(device, Some("default-device".to_string()));
        assert_eq!(source, Some("default"));
    }

    #[test]
    fn test_get_device_source_resolves_alias() {
        let mut aliases = std::collections::HashMap::new();
        aliases.insert("my-sensor".to_string(), "AA:BB:CC:DD:EE:FF".to_string());

        let config = Config {
            aliases,
            ..Default::default()
        };
        let (device, source) = get_device_source(Some("my-sensor"), &config);

        assert_eq!(device, Some("AA:BB:CC:DD:EE:FF".to_string()));
        assert_eq!(source, None);
    }
}