blubat-core 0.4.0

Bluetooth battery model, macOS data sources and polling engine behind the blubat CLI
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
//! The TOML file at `~/.config/blubat/config.toml`.
//!
//! The file is user intent and blubat never writes it. It is also optional:
//! everything here has a built-in default, so a machine with no config file
//! behaves exactly as one whose file repeats the defaults back. What blubat
//! knows about itself, the armed and fired flags and the debounce clocks, is
//! machine state and lives under the state directory instead.
//!
//! Parsing is strict in the other direction: an unknown key, an unknown event
//! name or a duration that does not parse is an error carrying the line it is
//! on, because a typo that silently does nothing is worse than one that says so.

use std::collections::BTreeMap;
use std::fs;
use std::io::ErrorKind;
use std::path::Path;
use std::time::Duration;

use serde::Deserialize;

use crate::address::Address;
use crate::device::Device;
use crate::duration::{Debounce, de_duration, de_optional_duration};
use crate::error::{Error, Result};
use crate::event::Event;
use crate::poll::Tiers;
use crate::theme::Theme;

/// Everything the config file can say.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct Config {
    pub poll: Poll,
    pub notifications: Notifications,
    pub defaults: Defaults,
    pub theme: Theme,
    pub dashboard: Dashboard,
    /// Per device overrides, in file order: the first block a device matches wins.
    #[serde(rename = "device")]
    pub devices: Vec<DeviceRule>,
    #[serde(rename = "hook")]
    pub hooks: Vec<Hook>,
}

impl Config {
    /// Parses config text, rejecting unknown keys and unparseable values.
    pub fn parse(contents: &str) -> Result<Self> {
        toml::from_str(contents).map_err(|error| Error::Format(error.to_string()))
    }

    /// Reads the config file. `Ok(None)` when there is none, which is not an error.
    pub fn read(path: &Path) -> Result<Option<Self>> {
        match fs::read_to_string(path) {
            Ok(contents) => Self::parse(&contents)
                .map(Some)
                .map_err(|error| Error::Format(format!("{}: {error}", path.display()))),
            Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
            Err(source) => Err(Error::Io {
                path: path.to_path_buf(),
                source,
            }),
        }
    }

    /// The config in force: the file's, or the built-in defaults without one.
    pub fn load(path: &Path) -> Result<Self> {
        Self::read(path).map(Option::unwrap_or_default)
    }

    /// The thresholds one device is judged by.
    ///
    /// Most specific first: the first `[[device]]` block the device matches,
    /// then `[defaults]`, then what the device itself advertises, then the
    /// built-in numbers. `advertised` is per key, so a device that publishes a
    /// low threshold but no critical one still takes the built-in critical.
    pub fn thresholds_for(&self, device: &Device, advertised: Advertised) -> Thresholds {
        self.resolve(self.rule_for(device), advertised)
    }

    /// The hooks that run for one event on one device, in file order.
    pub fn hooks_for<'a>(
        &'a self,
        event: Event,
        device: &'a Device,
    ) -> impl Iterator<Item = &'a Hook> {
        self.hooks
            .iter()
            .filter(move |hook| hook.event == event && hook.covers(device))
    }

    /// The `[[device]]` blocks that match nothing in a reading.
    ///
    /// A warning rather than an error: the device may simply be switched off.
    pub fn unmatched(&self, devices: &[Device]) -> Vec<&str> {
        self.devices
            .iter()
            .map(|rule| rule.pattern.as_str())
            .filter(|pattern| !devices.iter().any(|device| device.matches(pattern)))
            .collect()
    }

    /// What is wrong with the file that parsing alone cannot catch.
    ///
    /// Empty for a usable config, which is what `blubat config validate` exits
    /// on. Each entry names the table it came from, since a threshold is only
    /// nonsense in the company of the ones it is ordered against.
    pub fn problems(&self) -> Vec<String> {
        std::iter::once((
            String::from("[defaults]"),
            self.resolve(None, Advertised::NONE),
        ))
        .chain(self.devices.iter().map(|rule| {
            (
                format!("[[device]] match = \"{}\"", rule.pattern),
                self.resolve(Some(rule), Advertised::NONE),
            )
        }))
        .flat_map(|(table, thresholds)| {
            thresholds
                .problems()
                .into_iter()
                .map(move |problem| format!("{table}: {problem}"))
        })
        .chain(
            self.hooks
                .iter()
                .filter(|hook| hook.command.trim().is_empty())
                .map(|hook| format!("[[hook]] event = \"{}\": command is empty", hook.event)),
        )
        .collect()
    }

    /// The first block a device matches, which is the one that overrides.
    fn rule_for(&self, device: &Device) -> Option<&DeviceRule> {
        self.devices
            .iter()
            .find(|rule| device.matches(&rule.pattern))
    }

    fn resolve(&self, rule: Option<&DeviceRule>, advertised: Advertised) -> Thresholds {
        let built_in = Thresholds::BUILT_IN;

        Thresholds {
            low: rule
                .and_then(|rule| rule.low)
                .or(self.defaults.low)
                .or(advertised.low)
                .unwrap_or(built_in.low),
            critical: rule
                .and_then(|rule| rule.critical)
                .or(self.defaults.critical)
                .or(advertised.critical)
                .unwrap_or(built_in.critical),
            high: rule
                .and_then(|rule| rule.high)
                .or(self.defaults.high)
                .unwrap_or(built_in.high),
            rearm_margin: rule
                .and_then(|rule| rule.rearm_margin)
                .or(self.defaults.rearm_margin)
                .unwrap_or(built_in.rearm_margin),
        }
    }
}

/// How often each tier reads, and how long a silence lasts before it is stale.
#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct Poll {
    /// The tick while the dashboard or a foreground command runs.
    #[serde(deserialize_with = "de_duration")]
    pub foreground_interval: Duration,
    /// The tick under launchd, slower because nothing is watching.
    #[serde(deserialize_with = "de_duration")]
    pub daemon_interval: Duration,
    /// The slow tier's own interval, cached in between.
    #[serde(deserialize_with = "de_duration")]
    pub profiler_interval: Duration,
    /// How long `system_profiler` may take before blubat gives up on the call.
    ///
    /// Generous on purpose: the call costs about 150ms here and scales with how
    /// many devices have ever been paired, so this is a ceiling on a wedged
    /// call rather than a budget for a slow one.
    #[serde(deserialize_with = "de_duration")]
    pub profiler_timeout: Duration,
    /// A device silent for this long is stale.
    #[serde(deserialize_with = "de_duration")]
    pub stale_after: Duration,
}

impl Default for Poll {
    fn default() -> Self {
        Self {
            foreground_interval: Duration::from_secs(30),
            daemon_interval: Duration::from_secs(120),
            profiler_interval: Duration::from_secs(300),
            profiler_timeout: Tiers::default().timeout,
            stale_after: Duration::from_secs(600),
        }
    }
}

impl Poll {
    /// The two tier intervals for the daemon.
    ///
    /// The dashboard builds its own in `tui`, since it polls faster than any
    /// other caller while nothing in the file has asked otherwise.
    pub fn daemon_tiers(&self) -> Tiers {
        Tiers {
            fast: self.daemon_interval,
            slow: self.profiler_interval,
            timeout: self.profiler_timeout,
        }
    }
}

/// Which events raise a desktop banner, and what it sounds like.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct Notifications {
    pub low: bool,
    pub critical: bool,
    /// The "safe to unplug" banner.
    pub charged: bool,
    /// Covers connect and disconnect together, which flap as a pair.
    pub connect: bool,
    pub stale: bool,
    /// A macOS sound name, as `osascript` names them.
    pub sound: String,
}

impl Default for Notifications {
    /// Battery events on, link events off: connect and disconnect are noisy.
    fn default() -> Self {
        Self {
            low: true,
            critical: true,
            charged: true,
            connect: false,
            stale: true,
            sound: "Glass".to_string(),
        }
    }
}

impl Notifications {
    /// Whether this event is one the user wants a banner for.
    pub fn enabled(&self, event: Event) -> bool {
        match event {
            Event::LowBattery => self.low,
            Event::CriticalBattery => self.critical,
            Event::Charged => self.charged,
            Event::Connected | Event::Disconnected => self.connect,
            Event::Stale => self.stale,
        }
    }
}

/// The `[defaults]` table: thresholds for every device that has no block.
///
/// Every key is optional so an unset one can fall through to what the device
/// advertises, which a filled-in default would silently shadow.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct Defaults {
    pub low: Option<u8>,
    pub critical: Option<u8>,
    pub high: Option<u8>,
    pub rearm_margin: Option<u8>,
}

/// One `[[device]]` block: a match and the keys it overrides.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct DeviceRule {
    /// Case insensitive substring, tested against the name and the address.
    #[serde(rename = "match")]
    pub pattern: String,
    pub low: Option<u8>,
    pub critical: Option<u8>,
    pub high: Option<u8>,
    pub rearm_margin: Option<u8>,
}

/// One `[[hook]]` block: a command, the event that runs it, and its limits.
#[derive(Clone, Debug, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Hook {
    pub event: Event,
    /// A shell command line, run with the `BLUBAT_*` variables set.
    pub command: String,
    /// Optional device filter, matched as `--device` is.
    #[serde(rename = "match")]
    pub pattern: Option<String>,
    pub debounce: Option<Debounce>,
    #[serde(default, deserialize_with = "de_optional_duration")]
    pub timeout: Option<Duration>,
}

impl Hook {
    /// Whether this hook covers a device, which an unfiltered hook always does.
    pub fn covers(&self, device: &Device) -> bool {
        self.pattern
            .as_deref()
            .is_none_or(|pattern| device.matches(pattern))
    }
}

/// What the dashboard hides and how it sorts.
#[derive(Clone, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(default, deny_unknown_fields)]
pub struct Dashboard {
    /// Matches for devices the dashboard leaves out, which `h` maintains and
    /// which are the only thing blubat ever writes back into the file.
    pub hidden: Vec<String>,
    pub sort: Sort,
}

/// The order the dashboard lists devices in.
#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum Sort {
    #[default]
    Level,
    Name,
    LastSeen,
}

/// The thresholds a device's own IOKit node publishes, where it has them.
///
/// Apple's numbers sit between the config file and the built-in defaults: they
/// describe the device rather than the user, so anything written wins over them.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Advertised {
    pub low: Option<u8>,
    pub critical: Option<u8>,
}

impl Advertised {
    /// A device that publishes no thresholds of its own.
    pub const NONE: Self = Self {
        low: None,
        critical: None,
    };
}

/// What every device advertises about itself, keyed by address.
///
/// Reading the registry is a separate pass from a poll, so the event engine
/// takes one of these as an input and a test hands one in without a registry.
pub type AdvertisedThresholds = BTreeMap<Address, Advertised>;

/// The thresholds in force for one device, with every key answered.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Thresholds {
    pub low: u8,
    pub critical: u8,
    /// The level that raises `charged`.
    pub high: u8,
    /// Points of recovery required before a fired event re-arms.
    pub rearm_margin: u8,
}

impl Thresholds {
    /// What blubat uses when neither the config nor the device says otherwise.
    pub const BUILT_IN: Self = Self {
        low: 20,
        critical: 10,
        high: 100,
        rearm_margin: 1,
    };

    /// The orderings and the ranges a usable set of thresholds has to hold.
    ///
    /// A threshold above 100 parses but can never be crossed, since no battery
    /// reports more, so it silences its event rather than configuring it.
    fn problems(self) -> Vec<String> {
        [
            (self.low >= self.high)
                .then(|| format!("low ({}) must be below high ({})", self.low, self.high)),
            (self.critical > self.low).then(|| {
                format!(
                    "critical ({}) must not be above low ({})",
                    self.critical, self.low
                )
            }),
        ]
        .into_iter()
        .flatten()
        .chain(
            [
                ("low", self.low),
                ("critical", self.critical),
                ("high", self.high),
                ("rearm_margin", self.rearm_margin),
            ]
            .into_iter()
            .filter(|(_, value)| *value > 100)
            .map(|(key, value)| format!("{key} ({value}) must be a percentage of 100 or less")),
        )
        .collect()
    }
}

impl Default for Thresholds {
    fn default() -> Self {
        Self::BUILT_IN
    }
}

#[cfg(test)]
mod tests {
    use crate::address::Address;
    use crate::device::{ChargeState, Levels, Source};
    use crate::timestamp::Timestamp;

    use super::*;

    /// The sample configuration the PRD documents, which is the shape blubat
    /// promises to read.
    const SAMPLE: &str = r##"
[poll]
foreground_interval = "30s"
daemon_interval     = "120s"
profiler_interval   = "5m"
profiler_timeout    = "15s"
stale_after         = "10m"

[notifications]
low      = true
critical = true
charged  = true
connect  = false
sound    = "Glass"

[defaults]
low        = 20
critical   = 10
high       = 100
rearm_margin = 1

[theme]
scheme = "dark"
accent   = "#39c5cf"
critical = "#f47067"
low      = "#c69026"
ok       = "#57ab5a"

[dashboard]
hidden = ["MX Master"]
sort   = "level"

[[device]]
match = "trackpad"
low   = 20
high  = 100

[[device]]
match = "Soundcore"
low   = 25
high  = 90
rearm_margin = 5

[[device]]
match = "MX Keys"
low   = 15

[[hook]]
event    = "low_battery"
command  = "~/.config/blubat/hooks/nag.sh"
debounce = "30m"

[[hook]]
event    = "charged"
command  = "osascript -e 'display notification'"
debounce = "once"

[[hook]]
event    = "disconnected"
match    = "AirPods"
command  = "~/bin/pause-music"
timeout  = "10s"
"##;

    fn device(name: &str, address: &str) -> Device {
        Device {
            address: Address::parse(address).expect("valid address"),
            name: name.to_string(),
            kind: None,
            transport: None,
            levels: Levels {
                main: Some(50),
                ..Levels::default()
            },
            charge: ChargeState::Unknown,
            source: Source::IoKit,
            connected: true,
            read_at: Timestamp::from_unix(0),
        }
    }

    fn trackpad() -> Device {
        device("Paul\u{2019}s Magic Trackpad", "30-82-16-f2-24-90")
    }

    #[test]
    fn the_documented_sample_parses_into_every_table() {
        let config = Config::parse(SAMPLE).expect("the sample parses");

        assert_eq!(config.poll.profiler_interval, Duration::from_secs(300));
        assert_eq!(config.poll.profiler_timeout, Duration::from_secs(15));
        assert_eq!(config.poll.stale_after, Duration::from_secs(600));
        assert_eq!(config.notifications.sound, "Glass");
        assert!(!config.notifications.connect);
        assert_eq!(config.defaults.low, Some(20));
        assert_eq!(config.dashboard.hidden, ["MX Master"]);
        assert_eq!(config.dashboard.sort, Sort::Level);
        assert_eq!(config.devices.len(), 3);
        assert_eq!(config.hooks.len(), 3);
        assert_eq!(config.hooks[0].event, Event::LowBattery);
        assert_eq!(
            config.hooks[0].debounce,
            Some(Debounce::Window(Duration::from_secs(1_800)))
        );
        assert_eq!(config.hooks[1].debounce, Some(Debounce::Once));
        assert_eq!(config.hooks[2].pattern.as_deref(), Some("AirPods"));
        assert_eq!(config.hooks[2].timeout, Some(Duration::from_secs(10)));
        assert!(config.problems().is_empty(), "{:?}", config.problems());
    }

    #[test]
    fn an_empty_file_is_the_built_in_defaults() {
        assert_eq!(Config::parse("").expect("parses"), Config::default());
        assert_eq!(
            Config::default().thresholds_for(&trackpad(), Advertised::NONE),
            Thresholds::BUILT_IN
        );
    }

    #[test]
    fn defaults_apply_to_a_device_with_no_block_of_its_own() {
        let config = Config::parse("[defaults]\nlow = 30\nrearm_margin = 4\n").expect("parses");

        let thresholds = config.thresholds_for(&trackpad(), Advertised::NONE);

        assert_eq!(thresholds.low, 30);
        assert_eq!(thresholds.rearm_margin, 4);
        assert_eq!(
            thresholds.critical,
            Thresholds::BUILT_IN.critical,
            "an unset key stays built in"
        );
        assert_eq!(thresholds.high, Thresholds::BUILT_IN.high);
    }

    #[test]
    fn a_block_matched_by_name_overrides_the_defaults() {
        let config = Config::parse(SAMPLE).expect("parses");

        let earbuds = config.thresholds_for(
            &device("Soundcore Liberty 3 Pro", "aa-bb-cc-00-00-0a"),
            Advertised::NONE,
        );

        assert_eq!(earbuds.low, 25);
        assert_eq!(earbuds.high, 90);
        assert_eq!(earbuds.rearm_margin, 5);
        assert_eq!(earbuds.critical, 10, "unset in the block, set in defaults");
    }

    #[test]
    fn a_block_matched_by_address_overrides_the_defaults() {
        let config =
            Config::parse("[defaults]\nlow = 20\n\n[[device]]\nmatch = \"de-df-38\"\nlow = 15\n")
                .expect("parses");
        let keys = device("MX Keys", "de-df-38-f0-46-9b");

        assert_eq!(config.thresholds_for(&keys, Advertised::NONE).low, 15);
        assert_eq!(
            config.thresholds_for(&trackpad(), Advertised::NONE).low,
            20,
            "another device keeps the defaults"
        );
    }

    #[test]
    fn the_first_matching_block_wins() {
        let config = Config::parse(
            "[[device]]\nmatch = \"trackpad\"\nlow = 25\n\n[[device]]\nmatch = \"magic\"\nlow = 35\n",
        )
        .expect("parses");

        assert_eq!(config.thresholds_for(&trackpad(), Advertised::NONE).low, 25);
    }

    #[test]
    fn what_a_device_advertises_sits_under_the_config_and_over_the_built_ins() {
        let advertised = Advertised {
            low: Some(18),
            critical: Some(6),
        };
        let silent = Config::default();
        let written = Config::parse("[defaults]\nlow = 30\n").expect("parses");

        assert_eq!(
            silent.thresholds_for(&trackpad(), advertised).low,
            18,
            "nothing written, so the device's own number stands"
        );
        assert_eq!(silent.thresholds_for(&trackpad(), advertised).critical, 6);
        assert_eq!(
            written.thresholds_for(&trackpad(), advertised).low,
            30,
            "the file wins over the device"
        );
        assert_eq!(
            written.thresholds_for(&trackpad(), advertised).critical,
            6,
            "per key, so an unwritten key still takes the device's"
        );
        assert_eq!(
            silent.thresholds_for(&trackpad(), Advertised::NONE).low,
            Thresholds::BUILT_IN.low
        );
    }

    #[test]
    fn a_missing_file_is_the_built_in_config_and_a_missing_directory_too() {
        let absent = std::env::temp_dir()
            .join(format!("blubat-absent-{}", std::process::id()))
            .join("config.toml");

        assert!(!absent.exists(), "{absent:?} was never written");
        assert_eq!(Config::read(&absent).expect("not an error"), None);
        assert_eq!(
            Config::load(&absent).expect("not an error"),
            Config::default()
        );
    }

    #[test]
    fn a_threshold_no_battery_could_reach_is_reported_rather_than_accepted() {
        let unreachable = Config::parse("[defaults]\nlow = 150\nhigh = 200\nrearm_margin = 120\n")
            .expect("parses");

        let problems = unreachable.problems();

        assert_eq!(
            problems,
            [
                "[defaults]: low (150) must be a percentage of 100 or less",
                "[defaults]: high (200) must be a percentage of 100 or less",
                "[defaults]: rearm_margin (120) must be a percentage of 100 or less",
            ],
            "{problems:?}"
        );
        assert!(
            Config::parse("[defaults]\nlow = 100\nhigh = 100\nrearm_margin = 100\n")
                .expect("parses")
                .problems()
                .iter()
                .all(|problem| !problem.contains("percentage of 100")),
            "100 is a level a battery reports"
        );
    }

    #[test]
    fn a_malformed_file_is_rejected_with_the_line_it_is_on() {
        let error = Config::parse("[defaults]\nlow = 20\ncritical = \"ten\"\n")
            .expect_err("a string threshold is not a number");

        let message = error.to_string();
        assert!(message.contains("line 3"), "{message}");
        assert!(matches!(error, Error::Format(_)));
    }

    #[test]
    fn every_kind_of_nonsense_in_the_file_is_an_error() {
        for contents in [
            "[defaults]\nlwo = 20\n",
            "[dashbord]\nsort = \"level\"\n",
            "[[device]]\nlow = 20\n",
            "[[hook]]\nevent = \"exploded\"\ncommand = \"true\"\n",
            "[[hook]]\nevent = \"low_battery\"\n",
            "[[hook]]\nevent = \"low_battery\"\ncommand = \"true\"\ndebounce = \"soon\"\n",
            "[[hook]]\nevent = \"low_battery\"\ncommand = \"true\"\ntimeout = \"10 seconds\"\n",
            "[poll]\nstale_after = \"forever\"\n",
            "[poll]\nstale_after = 600\n",
            "[dashboard]\nsort = \"battery\"\n",
            "[theme]\naccent = \"#gggggg\"\n",
            "not toml at all {{",
        ] {
            assert!(
                Config::parse(contents).is_err(),
                "{contents:?} should be rejected"
            );
        }
    }

    #[test]
    fn thresholds_that_cannot_all_hold_are_reported_rather_than_parsed_away() {
        let inverted = Config::parse(
            "[defaults]\nlow = 20\nhigh = 15\n\n[[device]]\nmatch = \"keys\"\ncritical = 40\n",
        )
        .expect("it parses: the problem is what the numbers mean");

        let problems = inverted.problems();

        assert_eq!(problems.len(), 3, "{problems:?}");
        assert!(problems[0].contains("[defaults]"), "{problems:?}");
        assert!(problems[0].contains("low (20) must be below high (15)"));
        assert!(
            problems.iter().any(|problem| problem
                .contains("[[device]] match = \"keys\": critical (40) must not be above low (20)")),
            "{problems:?}"
        );
    }

    #[test]
    fn an_empty_hook_command_is_a_problem() {
        let config =
            Config::parse("[[hook]]\nevent = \"charged\"\ncommand = \"  \"\n").expect("parses");

        assert_eq!(
            config.problems(),
            ["[[hook]] event = \"charged\": command is empty"]
        );
    }

    #[test]
    fn hooks_are_selected_by_event_and_by_their_own_filter() {
        let config = Config::parse(SAMPLE).expect("parses");
        let airpods = device("Paul\u{2019}s AirPods Pro", "74-15-f5-02-8e-38");

        let run: Vec<&str> = config
            .hooks_for(Event::Disconnected, &airpods)
            .map(|hook| hook.command.as_str())
            .collect();
        assert_eq!(run, ["~/bin/pause-music"]);

        assert_eq!(
            config.hooks_for(Event::Disconnected, &trackpad()).count(),
            0,
            "the filter excludes every other device"
        );
        assert_eq!(
            config.hooks_for(Event::LowBattery, &trackpad()).count(),
            1,
            "an unfiltered hook covers every device"
        );
        assert_eq!(config.hooks_for(Event::Stale, &airpods).count(), 0);
    }

    #[test]
    fn a_block_matching_nothing_visible_is_named_so_a_typo_shows_up() {
        let config = Config::parse(SAMPLE).expect("parses");

        assert_eq!(
            config.unmatched(&[trackpad()]),
            ["Soundcore", "MX Keys"],
            "the trackpad block matched, the other two did not"
        );
        assert!(config.unmatched(&[]).len() == 3);
        assert!(Config::default().unmatched(&[]).is_empty());
    }

    #[test]
    fn notifications_answer_for_every_event() {
        let config = Config::default();

        assert!(config.notifications.enabled(Event::LowBattery));
        assert!(config.notifications.enabled(Event::CriticalBattery));
        assert!(config.notifications.enabled(Event::Charged));
        assert!(config.notifications.enabled(Event::Stale));
        assert!(
            !config.notifications.enabled(Event::Connected),
            "link events are off by default"
        );
        assert!(!config.notifications.enabled(Event::Disconnected));

        let noisy =
            Config::parse("[notifications]\nconnect = true\nlow = false\n").expect("parses");
        assert!(noisy.notifications.enabled(Event::Disconnected));
        assert!(!noisy.notifications.enabled(Event::LowBattery));
    }

    #[test]
    fn the_poll_table_hands_the_daemon_its_own_tiers() {
        let poll = Config::parse(SAMPLE).expect("parses").poll;

        assert_eq!(
            poll.daemon_tiers(),
            Tiers {
                fast: Duration::from_secs(120),
                slow: Duration::from_secs(300),
                timeout: Duration::from_secs(15),
            },
            "the slower tick, since nothing is watching the daemon"
        );
    }
}