use std::io::{self, Write};
use std::path::PathBuf;
use blubat_core::{Config, Paths, Snapshot, Timestamp};
use crate::effects::Effects;
use crate::hooks::Outcome;
use crate::notify::{Desktop, Notifier};
use crate::{Failure, lock};
use super::watches::Watches;
struct Resident {
effects: Effects,
watches: Watches,
notifier: Box<dyn Notifier>,
directory: PathBuf,
}
pub fn serve(paths: &Paths) -> Result<(), Failure> {
let Some(_running) = lock::take(&paths.daemon_lock()).map_err(Failure::Error)? else {
return Err(Failure::Error(
"a blubat daemon is already running".to_string(),
));
};
let (config, unreadable) = load(paths);
let (effects, stale_state) = Effects::live(paths, report);
let mut resident = resident(paths, effects, Box::new(Desktop));
let mut out = io::stdout();
for problem in [unreadable, stale_state].into_iter().flatten() {
log(&mut out, &problem);
}
log(
&mut out,
&format!(
"watching every {:?}, logging to {}",
config.poll.daemon_interval,
paths.log_file().display()
),
);
for reading in blubat_core::poll(config.poll.daemon_tiers()) {
for line in resident.tick(&reading, &config) {
log(&mut out, &line);
}
}
let stopped = "the poller stopped delivering readings";
log(&mut out, stopped);
Err(Failure::Error(stopped.to_string()))
}
fn resident(paths: &Paths, effects: Effects, notifier: Box<dyn Notifier>) -> Resident {
let dashboard = paths.tui_lock();
Resident {
effects: effects.deferring_to(move || lock::held(&dashboard)),
watches: Watches::default(),
notifier,
directory: paths.watch_dir(),
}
}
impl Resident {
fn tick(&mut self, reading: &Snapshot, config: &Config) -> Vec<String> {
let mut lines = self.effects.observe(reading, config).problems;
lines.extend(self.watches.adopt(&self.directory));
lines.extend(self.watches.settle(
reading,
&config.notifications.sound,
reading.read_at,
self.notifier.as_ref(),
));
lines
}
}
fn load(paths: &Paths) -> (Config, Option<String>) {
Config::load(paths.config_file()).map_or_else(
|error| (Config::default(), Some(error.to_string())),
|config| (config, None),
)
}
fn report(outcome: Outcome) {
if outcome.went_wrong() {
eprintln!("{}", stamped(Timestamp::now(), &outcome.to_string()));
} else {
println!("{}", stamped(Timestamp::now(), &outcome.to_string()));
}
}
fn stamped(now: Timestamp, message: &str) -> String {
format!("{now} {message}")
}
fn log(out: &mut impl Write, message: &str) {
let _ = writeln!(out, "{}", stamped(Timestamp::now(), message));
}
#[cfg(test)]
mod tests {
use std::fs;
use std::sync::Arc;
use blubat_core::{
Address, AdvertisedThresholds, ChargeState, Device, Engine, Levels, Source, Watch,
};
use crate::hooks::fake::Recorder as StartedHooks;
use crate::notify::fake::Recorder as PostedBanners;
use crate::scratch::Scratch;
use super::*;
const TRACKPAD: &str = "Paul\u{2019}s Magic Trackpad";
const READ_AT: i64 = 1_785_643_199;
fn reading(level: Option<u8>, second: i64) -> Snapshot {
let read_at = Timestamp::from_unix(READ_AT + second);
Snapshot {
read_at,
devices: vec![Device {
address: Address::parse("30-82-16-f2-24-90").expect("valid address"),
name: TRACKPAD.to_string(),
kind: None,
transport: None,
levels: Levels {
main: level,
..Levels::default()
},
charge: ChargeState::Discharging,
source: Source::IoKit,
connected: true,
read_at,
}],
degraded: false,
warnings: Vec::new(),
}
}
fn resident(scratch: &Scratch) -> (Resident, Arc<PostedBanners>, Arc<StartedHooks>) {
let paths = scratch.paths();
let banners = Arc::new(PostedBanners::new());
let hooks = Arc::new(StartedHooks::new());
let effects = Effects::new(
&paths,
Engine::default(),
AdvertisedThresholds::new(),
Box::new(Arc::clone(&banners)),
Box::new(Arc::clone(&hooks)),
);
(
super::resident(&paths, effects, Box::new(Arc::clone(&banners))),
banners,
hooks,
)
}
fn config() -> Config {
Config::parse("[[hook]]\nevent = \"low_battery\"\ncommand = \"nag\"\n").expect("parses")
}
fn owner(scratch: &Scratch) -> Effects {
Effects::new(
&scratch.paths(),
Engine::default(),
AdvertisedThresholds::new(),
Box::new(Arc::new(PostedBanners::new())),
Box::new(Arc::new(StartedHooks::new())),
)
}
fn dashboard(scratch: &Scratch) -> lock::Held {
lock::take(&scratch.paths().tui_lock())
.expect("a lock")
.expect("nobody else holding it")
}
#[test]
fn a_crossing_reaches_the_banner_and_the_hook_with_no_terminal_attached() {
let scratch = Scratch::new();
let (mut resident, banners, hooks) = resident(&scratch);
let config = config();
resident.tick(&reading(Some(50), 0), &config);
resident.tick(&reading(Some(19), 1), &config);
assert_eq!(banners.posted().len(), 1);
assert_eq!(banners.posted()[0].body, "Battery low at 19%");
assert_eq!(hooks.commands(), ["nag"]);
}
#[test]
fn a_dashboard_holding_the_lock_takes_the_banners_and_the_hooks() {
let scratch = Scratch::new();
let (mut resident, banners, hooks) = resident(&scratch);
let config = config();
let open = dashboard(&scratch);
resident.tick(&reading(Some(50), 0), &config);
resident.tick(&reading(Some(19), 1), &config);
assert!(banners.posted().is_empty(), "{:?}", banners.posted());
assert!(hooks.commands().is_empty(), "{:?}", hooks.commands());
assert!(
!scratch.paths().state_file().exists(),
"the dashboard owns the state file while it owns the events"
);
drop(open);
}
#[test]
fn a_lock_left_by_a_dashboard_that_was_killed_does_not_silence_the_daemon() {
let scratch = Scratch::new();
let (mut resident, banners, _) = resident(&scratch);
let config = config();
let lock = scratch.paths().tui_lock();
fs::create_dir_all(lock.parent().expect("a parent")).expect("a state directory");
fs::write(&lock, "2147483646\n").expect("a lock file left behind");
resident.tick(&reading(Some(50), 0), &config);
resident.tick(&reading(Some(19), 1), &config);
assert_eq!(
banners.posted().len(),
1,
"nothing is holding the lock the file was written for"
);
}
#[test]
fn the_dashboard_closing_hands_the_side_effects_back() {
let scratch = Scratch::new();
let (mut resident, banners, _) = resident(&scratch);
let config = config();
let mut open_elsewhere = owner(&scratch);
let open = dashboard(&scratch);
open_elsewhere.observe(&reading(Some(50), 0), &config);
resident.tick(&reading(Some(50), 0), &config);
drop(open);
resident.tick(&reading(Some(19), 1), &config);
assert_eq!(banners.posted().len(), 1);
assert_eq!(banners.posted()[0].body, "Battery low at 19%");
}
#[test]
fn a_watch_handed_over_is_taken_up_and_notified_on_the_poll_it_is_met() {
let scratch = Scratch::new();
let (mut resident, banners, _) = resident(&scratch);
let config = Config::default();
Watch::new("trackpad", 90, None)
.write(&scratch.paths().watch_dir())
.expect("a registered watch");
let adopted = resident.tick(&reading(Some(50), 0), &config);
let met = resident.tick(&reading(Some(95), 1), &config);
assert_eq!(adopted, ["watching `trackpad` for 90%"]);
assert_eq!(met, [format!("{TRACKPAD} reached 95%")]);
assert_eq!(banners.posted().len(), 1);
assert_eq!(
banners.posted()[0].body,
format!("{TRACKPAD} is at 95%, safe to unplug.")
);
}
#[test]
fn a_watch_is_settled_whether_or_not_a_dashboard_owns_the_banners() {
let scratch = Scratch::new();
let (mut resident, banners, _) = resident(&scratch);
let config = Config::default();
let directory = scratch.paths().watch_dir();
Watch::new("trackpad", 90, None)
.write(&directory)
.expect("a registered watch");
let open = dashboard(&scratch);
let settled = resident.tick(&reading(Some(95), 0), &config);
assert_eq!(
settled,
[
"watching `trackpad` for 90%".to_string(),
format!("{TRACKPAD} reached 95%")
]
);
assert_eq!(banners.posted().len(), 1);
assert_eq!(
fs::read_dir(&directory).expect("a watch directory").count(),
0,
"and the file is consumed rather than left behind"
);
drop(open);
}
#[test]
fn a_stamped_line_carries_the_moment_it_was_written() {
assert_eq!(
stamped(Timestamp::from_unix(READ_AT), "watching every 120s"),
"2026-08-02T03:59:59Z watching every 120s"
);
}
}