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
730
731
732
733
//! CLI argument definitions using clap.

use std::path::PathBuf;

use clap::{Args, Parser, Subcommand, ValueEnum};

/// Output format for commands
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, ValueEnum)]
pub enum OutputFormat {
    #[default]
    Text,
    Json,
    Csv,
}

/// Output format for cached summary reports.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, ValueEnum)]
pub enum ReportFormat {
    #[default]
    Text,
    Json,
}

/// Visual styling mode for output
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, ValueEnum)]
pub enum StyleMode {
    /// Standard styling with colors
    Minimal,
    /// Rich styling with tables, icons, and full formatting (default)
    #[default]
    Rich,
    /// Plain text with no decorations (for scripting)
    Plain,
}

/// Reusable device connection arguments
#[derive(Debug, Clone, Args)]
pub struct DeviceArgs {
    /// Device address (MAC address or UUID), or use ARANET_DEVICE env var
    #[arg(short, long, env = "ARANET_DEVICE")]
    pub device: Option<String>,

    /// Connection timeout in seconds
    #[arg(short = 'T', long)]
    pub timeout: Option<u64>,
}

/// Device arguments that support multiple devices
#[derive(Debug, Clone, Args)]
pub struct MultiDeviceArgs {
    /// Device address(es) - can be specified multiple times, or comma-separated
    #[arg(short, long, value_delimiter = ',', env = "ARANET_DEVICE")]
    pub device: Vec<String>,

    /// Connection timeout in seconds (per device)
    #[arg(short = 'T', long)]
    pub timeout: Option<u64>,
}

/// Reusable output format arguments
#[derive(Debug, Clone, Args)]
pub struct OutputArgs {
    /// Output format
    #[arg(short, long, value_enum)]
    pub format: Option<OutputFormat>,

    /// Use Fahrenheit for temperature display (overrides --celsius and config)
    #[arg(long, conflicts_with = "celsius")]
    pub fahrenheit: bool,

    /// Use Celsius for temperature display (default, overrides config)
    #[arg(long, conflicts_with = "fahrenheit")]
    pub celsius: bool,

    /// Use Bq/m³ for radon (SI units, overrides --pci and config)
    #[arg(long, conflicts_with = "pci")]
    pub bq: bool,

    /// Use pCi/L for radon (default US units, overrides config)
    #[arg(long, conflicts_with = "bq")]
    pub pci: bool,

    /// Use inHg for pressure display (overrides --hpa and config)
    #[arg(long, conflicts_with = "hpa")]
    pub inhg: bool,

    /// Use hPa for pressure display (default, overrides config)
    #[arg(long, conflicts_with = "inhg")]
    pub hpa: bool,

    /// Omit header row in CSV output (useful for appending)
    #[arg(long)]
    pub no_header: bool,
}

impl OutputArgs {
    /// Resolve fahrenheit setting: explicit flags override config
    pub fn resolve_fahrenheit(&self, config_fahrenheit: bool) -> bool {
        if self.fahrenheit {
            true
        } else if self.celsius {
            false
        } else {
            config_fahrenheit
        }
    }

    /// Resolve bq setting: explicit flags override config
    /// (Currently config doesn't have bq, but this future-proofs it)
    pub fn resolve_bq(&self, config_bq: bool) -> bool {
        if self.bq {
            true
        } else if self.pci {
            false
        } else {
            config_bq
        }
    }

    /// Resolve inhg setting: explicit flags override config
    pub fn resolve_inhg(&self, config_inhg: bool) -> bool {
        if self.inhg {
            true
        } else if self.hpa {
            false
        } else {
            config_inhg
        }
    }
}

/// Output/unit arguments for cached summary reports.
#[derive(Debug, Clone, Args, Default)]
pub struct ReportOutputArgs {
    /// Use Fahrenheit for temperature display (overrides --celsius and config)
    #[arg(long, conflicts_with = "celsius")]
    pub fahrenheit: bool,

    /// Use Celsius for temperature display (default, overrides config)
    #[arg(long, conflicts_with = "fahrenheit")]
    pub celsius: bool,

    /// Use inHg for pressure display (overrides --hpa and config)
    #[arg(long, conflicts_with = "hpa")]
    pub inhg: bool,

    /// Use hPa for pressure display (default, overrides config)
    #[arg(long, conflicts_with = "inhg")]
    pub hpa: bool,

    /// Display radon in Bq/m³ (default, overrides config)
    #[arg(long, conflicts_with = "pci")]
    pub bq: bool,

    /// Display radon in pCi/L (overrides --bq and config)
    #[arg(long, conflicts_with = "bq")]
    pub pci: bool,
}

impl ReportOutputArgs {
    /// Resolve fahrenheit setting: explicit flags override config.
    pub fn resolve_fahrenheit(&self, config_fahrenheit: bool) -> bool {
        if self.fahrenheit {
            true
        } else if self.celsius {
            false
        } else {
            config_fahrenheit
        }
    }

    /// Resolve inhg setting: explicit flags override config.
    pub fn resolve_inhg(&self, config_inhg: bool) -> bool {
        if self.inhg {
            true
        } else if self.hpa {
            false
        } else {
            config_inhg
        }
    }

    /// Resolve bq setting: explicit flags override config.
    pub fn resolve_bq(&self, config_bq: bool) -> bool {
        if self.bq {
            true
        } else if self.pci {
            false
        } else {
            config_bq
        }
    }
}

#[derive(Parser)]
#[command(name = "aranet")]
#[command(
    author,
    version,
    about = "CLI for Aranet environmental sensors",
    long_about = "CLI for Aranet environmental sensors\n\nMade with ❤️ by Cameron Rye\nhttps://rye.dev"
)]
pub struct Cli {
    /// Enable verbose output
    #[arg(short, long, global = true)]
    pub verbose: bool,

    /// Suppress non-essential output
    #[arg(short, long, global = true)]
    pub quiet: bool,

    /// Output as JSON (shorthand for --format json)
    #[arg(long, global = true)]
    pub json: bool,

    /// Output compact JSON (no pretty-printing)
    #[arg(long, global = true)]
    pub compact: bool,

    /// Disable colored output
    #[arg(long, global = true)]
    pub no_color: bool,

    /// Visual styling mode (minimal, rich, plain)
    #[arg(
        long,
        global = true,
        value_enum,
        default_value = "rich",
        env = "ARANET_STYLE"
    )]
    pub style: StyleMode,

    /// Write output to file instead of stdout
    #[arg(short, long, global = true)]
    pub output: Option<PathBuf>,

    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand)]
pub enum Commands {
    /// Scan for nearby Aranet devices
    Scan {
        /// Scan timeout in seconds
        #[arg(short, long)]
        timeout: Option<u64>,

        /// Output format
        #[arg(short, long, value_enum)]
        format: Option<OutputFormat>,

        /// Omit header row in CSV output (useful for appending)
        #[arg(long)]
        no_header: bool,

        /// Interactively save aliases for discovered devices
        #[arg(short, long)]
        alias: bool,
    },

    /// Read current sensor values from one or more devices
    Read {
        #[command(flatten)]
        device: MultiDeviceArgs,

        #[command(flatten)]
        output: OutputArgs,

        /// Read from BLE advertisements without connecting (requires Smart Home enabled)
        #[arg(long)]
        passive: bool,
    },

    /// Quick one-line status from a device
    Status {
        #[command(flatten)]
        device: DeviceArgs,

        #[command(flatten)]
        output: OutputArgs,

        /// Super-compact single-line output for scripting
        #[arg(long)]
        brief: bool,
    },

    /// Retrieve historical data from a device
    History {
        #[command(flatten)]
        device: DeviceArgs,

        #[command(flatten)]
        output: OutputArgs,

        /// Number of records to retrieve (0 for all)
        #[arg(short, long, default_value = "0")]
        count: u32,

        /// Filter records since this date/time (RFC3339 or YYYY-MM-DD)
        #[arg(long)]
        since: Option<String>,

        /// Filter records until this date/time (RFC3339 or YYYY-MM-DD)
        #[arg(long)]
        until: Option<String>,

        /// Read from local cache instead of connecting to device
        #[arg(long)]
        cache: bool,
    },

    /// Display device information
    Info {
        #[command(flatten)]
        device: DeviceArgs,

        /// Output format
        #[arg(short, long, value_enum)]
        format: Option<OutputFormat>,

        /// Omit header row in CSV output (useful for appending)
        #[arg(long)]
        no_header: bool,
    },

    /// Configure device settings
    Set {
        #[command(flatten)]
        device: DeviceArgs,

        /// Skip confirmation prompt
        #[arg(long, short = 'f')]
        force: bool,

        #[command(subcommand)]
        setting: DeviceSetting,
    },

    /// Continuously monitor a device
    Watch {
        #[command(flatten)]
        device: DeviceArgs,

        #[command(flatten)]
        output: OutputArgs,

        /// Polling interval in seconds
        #[arg(short, long, default_value = "60")]
        interval: u64,

        /// Number of readings to take before exiting (0 for unlimited)
        #[arg(short = 'n', long, default_value = "0")]
        count: u32,

        /// Watch from BLE advertisements without connecting (requires Smart Home enabled)
        #[arg(long)]
        passive: bool,
    },

    /// Manage configuration
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },

    /// Manage device aliases (friendly names)
    Alias {
        #[command(subcommand)]
        action: AliasSubcommand,
    },

    /// Generate shell completions
    Completions {
        /// Shell to generate completions for
        #[arg(value_enum)]
        shell: clap_complete::Shell,
    },

    /// Run BLE diagnostics and permission checks
    Doctor,

    /// Show common usage examples
    Examples,

    /// Sync device history to local database
    Sync {
        #[command(flatten)]
        device: DeviceArgs,

        /// Output format
        #[arg(short, long, value_enum)]
        format: Option<OutputFormat>,

        /// Force full sync (re-download all history)
        #[arg(long)]
        full: bool,

        /// Sync all known devices from the database
        #[arg(long, conflicts_with = "device")]
        all: bool,
    },

    /// Query cached data from local database
    Cache {
        #[command(subcommand)]
        action: CacheAction,
    },

    /// Generate summary report from cached data
    Report {
        /// Device address or alias (uses the configured or remembered device when omitted)
        #[arg(short, long)]
        device: Option<String>,

        /// Generate reports for all cached devices
        #[arg(long, conflicts_with = "device")]
        all: bool,

        /// Report period
        #[arg(short, long, value_enum, default_value = "daily")]
        period: ReportPeriod,

        /// Output format
        #[arg(short, long, value_enum)]
        format: Option<ReportFormat>,

        #[command(flatten)]
        output: ReportOutputArgs,
    },

    /// Start the HTTP API server
    Server {
        /// Path to the aranet-service configuration file
        #[arg(short, long)]
        config: Option<std::path::PathBuf>,

        /// Bind address (overrides server.toml)
        #[arg(short, long)]
        bind: Option<String>,

        /// Database path (overrides server.toml)
        #[arg(long)]
        database: Option<std::path::PathBuf>,

        /// Disable background collector (API only mode)
        #[arg(long)]
        no_collector: bool,

        /// Run as a background daemon (detach from terminal)
        #[arg(long)]
        daemon: bool,
    },

    /// Launch interactive terminal dashboard
    #[cfg(feature = "tui")]
    Tui,

    /// Launch native desktop GUI
    #[cfg(feature = "gui")]
    Gui,
}

/// Report time period
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, ValueEnum)]
pub enum ReportPeriod {
    /// Last 24 hours
    #[default]
    Daily,
    /// Last 7 days
    Weekly,
    /// Last 30 days
    Monthly,
}

/// Cache subcommands for querying local database
#[derive(Debug, Clone, Subcommand)]
pub enum CacheAction {
    /// List cached devices
    Devices,

    /// Show cache statistics
    Stats {
        /// Device address to show stats for (optional)
        #[arg(short, long)]
        device: Option<String>,
    },

    /// Query cached history
    History {
        /// Device address (required)
        #[arg(short, long)]
        device: String,

        /// Number of records to show (0 for all)
        #[arg(short, long, default_value = "100")]
        count: u32,

        /// Filter records since this date/time
        #[arg(long)]
        since: Option<String>,

        /// Filter records until this date/time
        #[arg(long)]
        until: Option<String>,

        #[command(flatten)]
        output: OutputArgs,
    },

    /// Show aggregate statistics (min/max/avg) for cached history
    Aggregate {
        /// Device address (required)
        #[arg(short, long)]
        device: String,

        /// Filter records since this date/time
        #[arg(long)]
        since: Option<String>,

        /// Filter records until this date/time
        #[arg(long)]
        until: Option<String>,

        /// Output format
        #[arg(short, long, value_enum, default_value = "text")]
        format: OutputFormat,
    },

    /// Export cached history to file
    Export {
        /// Device address (required)
        #[arg(short, long)]
        device: String,

        /// Output format
        #[arg(short, long, value_enum, default_value = "csv")]
        format: ExportFormat,

        /// Output file path (uses stdout if not specified)
        #[arg(short, long)]
        output: Option<std::path::PathBuf>,

        /// Filter records since this date/time
        #[arg(long)]
        since: Option<String>,

        /// Filter records until this date/time
        #[arg(long)]
        until: Option<String>,
    },

    /// Delete old data from the cache
    Prune {
        /// Delete records older than this duration (e.g., "90d", "6m", "1y")
        #[arg(long, value_name = "DURATION")]
        older_than: String,

        /// Only prune history records (keep readings)
        #[arg(long)]
        history_only: bool,

        /// Skip confirmation prompt
        #[arg(long, short = 'f')]
        force: bool,

        /// Also run VACUUM to reclaim disk space
        #[arg(long)]
        vacuum: bool,
    },

    /// Show database path and info
    Info,

    /// Import history from a CSV or JSON file
    Import {
        /// Input format
        #[arg(short, long, value_enum, default_value = "csv")]
        format: ExportFormat,

        /// Input file path (uses stdin if not specified)
        #[arg(short, long)]
        input: Option<std::path::PathBuf>,
    },
}

/// Export format options
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum ExportFormat {
    /// Comma-separated values
    Csv,
    /// JavaScript Object Notation
    Json,
}

/// Alias subcommands
#[derive(Debug, Clone, Subcommand)]
pub enum AliasSubcommand {
    /// List all device aliases
    List,

    /// Set a device alias
    Set {
        /// Friendly name for the device (e.g., "living-room", "office")
        name: String,

        /// Device address (MAC address or UUID)
        address: String,
    },

    /// Remove a device alias
    #[command(alias = "rm")]
    Remove {
        /// Alias name to remove
        name: String,
    },
}

/// Device settings that can be configured
#[derive(Debug, Clone, Subcommand)]
pub enum DeviceSetting {
    /// Set measurement interval
    Interval {
        /// Interval in minutes (valid: 1, 2, 5, 10)
        #[arg(value_parser = parse_interval)]
        minutes: u8,
    },

    /// Set Bluetooth range
    Range {
        /// Range setting
        #[arg(value_enum)]
        range: BluetoothRangeSetting,
    },

    /// Enable or disable Smart Home integration
    SmartHome {
        /// Enable Smart Home mode
        #[arg(value_parser = parse_bool_arg)]
        enabled: bool,
    },
}

/// Bluetooth range setting values
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum BluetoothRangeSetting {
    /// Standard range (lower power consumption)
    Standard,
    /// Extended range (higher power consumption)
    Extended,
}

/// Parse interval value with validation
fn parse_interval(s: &str) -> Result<u8, String> {
    let minutes: u8 = s
        .parse()
        .map_err(|_| format!("'{}' is not a valid number", s))?;
    match minutes {
        1 | 2 | 5 | 10 => Ok(minutes),
        _ => Err(format!(
            "Invalid interval '{}'. Valid values: 1, 2, 5, 10 minutes",
            minutes
        )),
    }
}

/// Parse boolean argument with flexible input
fn parse_bool_arg(s: &str) -> Result<bool, String> {
    match s.to_lowercase().as_str() {
        "true" | "yes" | "on" | "1" | "enable" | "enabled" => Ok(true),
        "false" | "no" | "off" | "0" | "disable" | "disabled" => Ok(false),
        _ => Err(format!(
            "Invalid boolean value '{}'. Use: true/false, yes/no, on/off, 1/0",
            s
        )),
    }
}

/// Configuration keys
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum ConfigKey {
    /// Default device address
    Device,
    /// Default output format
    Format,
    /// Default connection timeout in seconds
    Timeout,
    /// Disable colored output
    NoColor,
    /// Use Fahrenheit for temperature
    Fahrenheit,
    /// Use inHg for pressure (instead of hPa)
    Inhg,
    /// Use Bq/m³ for radon (instead of pCi/L)
    Bq,
}

/// Configuration subcommands
#[derive(Subcommand)]
pub enum ConfigAction {
    /// Show current configuration
    Show,

    /// Get a configuration value
    Get {
        /// Configuration key
        #[arg(value_enum)]
        key: ConfigKey,
    },

    /// Set a configuration value
    Set {
        /// Configuration key
        #[arg(value_enum)]
        key: ConfigKey,
        /// Configuration value
        value: String,
    },

    /// Unset (remove) a configuration value
    Unset {
        /// Configuration key to remove
        #[arg(value_enum)]
        key: ConfigKey,
    },

    /// Show configuration file path
    Path,

    /// Initialize default configuration
    Init,
}