///| Linux provider for the `battery` capability (and the battery fields of `system`): reads /// /sys/class/power_supply. Every battery the machine has counts together (a laptop with two /// packs shows one charge). Modules never see these paths. ///| Where power supplies are read from; tests point it at a fake tree. let power_supply_root : Ref[String] = { val: "/sys/class/power_supply" } ///| Read batteries from `dir` instead of /sys/class/power_supply (tests: a fake power supply). pub fn set_power_supply_root(dir : String) -> Unit { power_supply_root.val = dir absent_since.val = None } ///| When the last look found no battery (monotonic ms). A machine without one (most desktops) /// would otherwise try all eight names every second, for nothing. let absent_since : Ref[UInt64?] = { val: None } ///| How long "no battery" is believed before looking again (a battery plugged into a running /// machine shows up within this). const ABSENT_RECHECK_MS : UInt64 = 30000UL ///| `read_battery` of the configured tree for the once-a-second samplers: without a battery it /// only looks again every 30 s. fn read_battery_polled() -> BatteryInfo { let now = @sys.monotonic_ms() match absent_since.val { Some(t) if now - t < ABSENT_RECHECK_MS => return no_battery _ => () } let b = read_battery() absent_since.val = if b.state == 0 && b.percent < 0 { Some(now) } else { None } b } ///| Names Linux gives batteries (ACPI, Apple, Qualcomm/ARM fuel gauges). The tree is not listed: /// a lookup of each name keeps this to plain file reads, which every host serves. let battery_names : Array[String] = [ "BAT0", "BAT1", "BAT2", "BATT", "BATC", "CMB0", "CMB1", "battery", "bq27411-0", "qcom-battery", "bms", "max170xx_battery", "axp20x-battery", "rk817-battery", ] ///| The `battery.status` record: state is the `charge-state` index (0 none, 1 discharging, /// 2 charging, 3 full, 4 not charging). #derive(Eq, Debug) pub(all) struct BatteryInfo { percent : Int state : Int secs_left : Int } ///| let no_battery : BatteryInfo = { percent: -1, state: 0, secs_left: 0 } ///| One battery's numbers, in µWh/µW (energy_*, power_now) or µAh/µA (charge_*, current_now). priv struct Pack { capacity : Int status : String now : Int64 full : Int64 rate : Int64 } ///| fn sysfs_text(path : String) -> String { @utf8.decode_lossy(@sys.read_proc_bytes(path)).trim(chars=" \n").to_string() } ///| A sysfs number ("-1234" allowed), or -1 when the file is missing or empty. fn sysfs_num(path : String) -> Int64 { let s = sysfs_text(path) if s.length() == 0 { return -1L } if s.has_prefix("-") { -parse_i64(s[1:].to_string()) } else { parse_i64(s) } } ///| fn read_pack(base : String) -> Pack? { let cap = sysfs_text(base + "/capacity") if cap.length() == 0 { return None } let ty = sysfs_text(base + "/type") // A mouse or headset battery (scope Device) is not the machine's. if (ty.length() > 0 && ty != "Battery") || sysfs_text(base + "/scope") == "Device" { return None } let energy = sysfs_num(base + "/energy_now") >= 0L let (n, f, r) = if energy { ("energy_now", "energy_full", "power_now") } else { ("charge_now", "charge_full", "current_now") } let rate = sysfs_num(base + "/" + r) Some({ capacity: parse_i64(cap).to_int(), status: sysfs_text(base + "/status"), now: sysfs_num(base + "/" + n), full: sysfs_num(base + "/" + f), // Some firmware reports discharge as a negative rate. rate: if rate < 0L { -rate } else { rate }, }) } ///| The machine's batteries under `root`, summed: percent from the energy left over the energy /// when full (each pack's capacity if they don't say), state, and the seconds left at the current /// rate (0 when the firmware doesn't report one). Without a battery: percent -1, state 0. pub fn read_battery(root? : String = power_supply_root.val) -> BatteryInfo { let packs : Array[Pack] = [] for name in battery_names { match read_pack(root + "/" + name) { Some(p) => packs.push(p) None => () } } if packs.length() == 0 { return no_battery } let mut now = 0L let mut full = 0L let mut rate = 0L let mut cap_sum = 0 let mut sized = true let mut discharging = false let mut charging = false let mut all_full = true for p in packs { cap_sum = cap_sum + p.capacity if p.now < 0L || p.full <= 0L { sized = false } else { now = now + p.now full = full + p.full } if p.rate > 0L { rate = rate + p.rate } match p.status { "Discharging" => discharging = true "Charging" => charging = true _ => () } if p.status != "Full" && p.capacity < 100 { all_full = false } } let percent = if sized { ((now * 100L + full / 2L) / full).to_int() } else { cap_sum / packs.length() } let percent = if percent < 0 { 0 } else if percent > 100 { 100 } else { percent } let state = if discharging { 1 } else if charging { 2 } else if all_full { 3 } else { 4 } let secs = if !sized || rate <= 0L { 0 } else if state == 1 { (now * 3600L / rate).to_int() } else if state == 2 { let left = full - now if left > 0L { (left * 3600L / rate).to_int() } else { 0 } } else { 0 } { percent, state, secs_left: secs } } ///| Samples the battery about once a second for the `battery` capability. The discharge rate /// jumps with load, so time left follows a running average of it rather than each sample. pub(all) struct BatteryMeter { mut last_secs : Int mut last_state : Int /// Average seconds left, scaled by the latest reading's energy (0: none yet). mut avg_secs : Int mut cur : BatteryInfo } ///| pub fn BatteryMeter::new() -> BatteryMeter { { last_secs: -1, last_state: -1, avg_secs: 0, cur: no_battery } } ///| Feed one reading: the time left is averaged (a quarter of each new sample) while the state /// holds, and starts over when it changes (plugged in, unplugged). pub fn BatteryMeter::feed(self : BatteryMeter, b : BatteryInfo) -> Unit { if b.state != self.last_state || b.secs_left <= 0 || self.avg_secs <= 0 { self.avg_secs = b.secs_left } else { self.avg_secs = (self.avg_secs * 3 + b.secs_left) / 4 } self.last_state = b.state self.cur = { ..b, secs_left: self.avg_secs } } ///| Re-read if a wall-clock second passed since the last call; cheap otherwise. pub fn BatteryMeter::refresh(self : BatteryMeter) -> BatteryInfo { let now = wall_secs() if now != self.last_secs { self.last_secs = now self.feed(read_battery_polled()) } self.cur }