RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
Battery: estimate remaining time from the measured drain
oxydizerf99aebcdda6c
diff --git a/src/Taskbar.zig b/src/Taskbar.zigindex f1ddd98..55f2ea4 100644--- a/src/Taskbar.zig+++ b/src/Taskbar.zig@@ -326,7 +326,7 @@ pub fn destroy(bar: *Taskbar) void {gpa.destroy(bar);}-/// Takes a fresh `battery.read` snapshot; only a change requests a frame.+/// Takes the power policy's fresh battery state; only a change requests a frame.pub fn applyBattery(bar: *Taskbar, next: battery.State) void {bar.server.updateBatteryWarning(next);if (std.meta.eql(next, bar.battery_state)) return;diff --git a/src/session/power_policy.zig b/src/session/power_policy.zigindex 3d76c35..9c8b258 100644--- a/src/session/power_policy.zig+++ b/src/session/power_policy.zig@@ -5,6 +5,7 @@ const wl = @import("wayland").server.wl;const Server = @import("../Server.zig");const Output = @import("../Output.zig");const battery = @import("../taskbar/battery.zig");+const BatteryRate = @import("../taskbar/battery_rate.zig");const cfg = @import("config").power;const Profile = @import("../power_profiles.zig").Profile;const Self = @This();@@ -12,6 +13,7 @@ const Self = @This();server: ?*Server = null,timer: ?*wl.EventSource = null,state: battery.State = .{},+rate: BatteryRate = .{},source: ?cfg.Source = null,effective: cfg.Profile = .{},initialized: bool = false,@@ -69,10 +71,25 @@ pub fn refresh(self: *Self) void {if (charge.writable and !self.charge_limit.writable) self.charge_requested = null;const changed = !std.meta.eql(self.charge_limit, charge);self.charge_limit = charge;- self.update(battery.read(server.io, @import("../main.zig").gpa));+ if (battery.scan(server.io, @import("../main.zig").gpa)) |snapshot| self.update(self.estimate(snapshot));if (changed) self.refreshSettings();}+/// A snapshot's state with the remaining time measured over recent snapshots+/// instead of one reading of the firmware's present rate.+fn estimate(self: *Self, snapshot: battery.Snapshot) battery.State {+ var state = snapshot.state();+ if (snapshot.count == 1 and snapshot.driver_time) {+ self.rate.reset();+ return state;+ }+ var ts: std.posix.timespec = undefined;+ if (std.posix.errno(std.posix.system.clock_gettime(@import("platform").system.boot_clock, &ts)) != .SUCCESS) return state;+ const t = @as(f64, @floatFromInt(ts.sec)) + @as(f64, @floatFromInt(ts.nsec)) / std.time.ns_per_s;+ state.remaining_minutes = self.rate.feed(t, snapshot.level(), BatteryRate.directionOf(state)) orelse state.remaining_minutes;+ return state;+}+pub fn update(self: *Self, state: battery.State) void {const server = self.server orelse return;if (!state.valid) return;diff --git a/src/taskbar/battery.zig b/src/taskbar/battery.zigindex a6d7f00..aa67b5c 100644--- a/src/taskbar/battery.zig+++ b/src/taskbar/battery.zig@@ -6,6 +6,8 @@//! Kernel power_supply uevents (plug, unplug, charge state) trigger an//! immediate read; capacity and time estimates are re-read on the session power policy's//! minute tick, because many firmwares never announce percentage changes.+//! A snapshot's own time is one instantaneous reading; the power policy+//! replaces it with `battery_rate`'s estimate over recent snapshots.const i18n = @import("i18n");const std = @import("std");@@ -61,6 +63,34 @@ pub const Warning = struct {}};+/// How full the system's batteries are, in the units the driver reports:+/// micro-Wh with a micro-W rate, or micro-Ah with a micro-A rate.+pub const Level = struct {+ pub const Unit = enum { energy, charge };++ unit: Unit,+ now: f64,+ full: ?f64,+ /// The firmware's present rate; null when missing or zero.+ rate: ?f64,++ pub fn parse(contents: []const u8) ?Level {+ if (number(contents, "POWER_SUPPLY_ENERGY_NOW")) |now| return .{+ .unit = .energy,+ .now = now,+ .full = number(contents, "POWER_SUPPLY_ENERGY_FULL"),+ .rate = rateValue(contents, "POWER_SUPPLY_POWER_NOW"),+ };+ if (number(contents, "POWER_SUPPLY_CHARGE_NOW")) |now| return .{+ .unit = .charge,+ .now = now,+ .full = number(contents, "POWER_SUPPLY_CHARGE_FULL"),+ .rate = rateValue(contents, "POWER_SUPPLY_CURRENT_NOW"),+ };+ return null;+ }+};+fn field(contents: []const u8, key: []const u8) ?[]const u8 {var lines = std.mem.tokenizeScalar(u8, contents, '\n');while (lines.next()) |line| {@@ -85,6 +115,10 @@ pub const Snapshot = struct {energy_count: u32 = 0,cycles: ?u32 = null,remaining_minutes: ?u32 = null,+ /// A pack reported its own time (fuel gauges average it themselves).+ driver_time: bool = false,+ level_sum: ?Level = null,+ level_ok: bool = true,pub fn add(self: *Snapshot, contents: []const u8) void {const kind = field(contents, "POWER_SUPPLY_TYPE") orelse return;@@ -107,6 +141,8 @@ pub const Snapshot = struct {self.sum += percent;self.count += 1;self.remaining_minutes = estimateMinutes(contents);+ if (driverMinutes(contents) != null) self.driver_time = true;+ self.addLevel(contents);if (std.mem.eql(u8, field(contents, "POWER_SUPPLY_STATUS") orelse "", "Charging")) self.charging = true;if (std.mem.eql(u8, field(contents, "POWER_SUPPLY_STATUS") orelse "", "Discharging")) self.discharging = true;if (std.mem.eql(u8, field(contents, "POWER_SUPPLY_STATUS") orelse "", "Full")) self.full_count += 1;@@ -132,6 +168,32 @@ pub const Snapshot = struct {self.cycles = std.fmt.parseInt(u32, field(contents, "POWER_SUPPLY_CYCLE_COUNT") orelse "", 10) catch null;}+ fn addLevel(self: *Snapshot, contents: []const u8) void {+ const reading = Level.parse(contents) orelse {+ self.level_ok = false;+ return;+ };+ const sum = self.level_sum orelse {+ self.level_sum = reading;+ return;+ };+ if (sum.unit != reading.unit) {+ self.level_ok = false;+ return;+ }+ self.level_sum = .{+ .unit = sum.unit,+ .now = sum.now + reading.now,+ .full = if (sum.full != null and reading.full != null) sum.full.? + reading.full.? else null,+ .rate = if (sum.rate != null and reading.rate != null) sum.rate.? + reading.rate.? else null,+ };+ }++ /// The level of every system battery together, when they share units.+ pub fn level(self: Snapshot) ?Level {+ return if (self.level_ok) self.level_sum else null;+ }+pub fn state(self: Snapshot) State {return .{.valid = true,@@ -158,28 +220,43 @@ fn number(contents: []const u8, key: []const u8) ?f64 {return @floatFromInt(value);}-// Driver times are seconds; capacity/rate pairs are micro-Wh/micro-W or-// micro-Ah/micro-A. Keep pairs in the same units, with no voltage guesswork.-fn estimateMinutes(contents: []const u8) ?u32 {+/// Some drivers sign the present rate (negative while discharging).+fn rateValue(contents: []const u8, key: []const u8) ?f64 {+ const value = std.fmt.parseInt(i64, field(contents, key) orelse return null, 10) catch return null;+ if (value == 0) return null;+ return @floatFromInt(@abs(value));+}++fn driverMinutes(contents: []const u8) ?u32 {const status = field(contents, "POWER_SUPPLY_STATUS") orelse return null;- const charging = std.mem.eql(u8, status, "Charging");- if (!charging and !std.mem.eql(u8, status, "Discharging")) return null;- const time_keys = if (charging)+ const time_keys = if (std.mem.eql(u8, status, "Charging"))[_][]const u8{ "POWER_SUPPLY_TIME_TO_FULL_NOW", "POWER_SUPPLY_TIME_TO_FULL_AVG" }+ else if (std.mem.eql(u8, status, "Discharging"))+ [_][]const u8{ "POWER_SUPPLY_TIME_TO_EMPTY_NOW", "POWER_SUPPLY_TIME_TO_EMPTY_AVG" }else- [_][]const u8{ "POWER_SUPPLY_TIME_TO_EMPTY_NOW", "POWER_SUPPLY_TIME_TO_EMPTY_AVG" };+ return null;for (time_keys) |key| {if (number(contents, key)) |seconds| {if (minutesFromHours(seconds / 3600)) |minutes| return minutes;}}+ return null;+}++// Driver times are seconds; capacity/rate pairs are micro-Wh/micro-W or+// micro-Ah/micro-A. Keep pairs in the same units, with no voltage guesswork.+fn estimateMinutes(contents: []const u8) ?u32 {+ const status = field(contents, "POWER_SUPPLY_STATUS") orelse return null;+ const charging = std.mem.eql(u8, status, "Charging");+ if (!charging and !std.mem.eql(u8, status, "Discharging")) return null;+ if (driverMinutes(contents)) |minutes| return minutes;const pairs = [_][3][]const u8{.{ "POWER_SUPPLY_ENERGY_NOW", "POWER_SUPPLY_ENERGY_FULL", "POWER_SUPPLY_POWER_NOW" },.{ "POWER_SUPPLY_CHARGE_NOW", "POWER_SUPPLY_CHARGE_FULL", "POWER_SUPPLY_CURRENT_NOW" },};for (pairs) |keys| {const now = number(contents, keys[0]) orelse continue;- const rate = number(contents, keys[2]) orelse continue;+ const rate = rateValue(contents, keys[2]) orelse continue;if (rate <= 0) continue;const remaining = if (charging) (number(contents, keys[1]) orelse continue) - now else now;if (minutesFromHours(remaining / rate)) |minutes| return minutes;@@ -187,19 +264,19 @@ fn estimateMinutes(contents: []const u8) ?u32 {return null;}-fn minutesFromHours(hours: f64) ?u32 {+pub fn minutesFromHours(hours: f64) ?u32 {// Reject missing/invalid rates and avoid overflowing on broken firmware.const minutes = @ceil(hours * 60);if (!std.math.isFinite(minutes) or minutes <= 0 or minutes > std.math.maxInt(u32)) return null;return @intFromFloat(minutes);}-pub fn read(io: std.Io, allocator: std.mem.Allocator) State {- var dir = std.Io.Dir.cwd().openDir(io, "/sys/class/power_supply", .{ .iterate = true }) catch return .{};+pub fn scan(io: std.Io, allocator: std.mem.Allocator) ?Snapshot {+ var dir = std.Io.Dir.cwd().openDir(io, "/sys/class/power_supply", .{ .iterate = true }) catch return null;defer dir.close(io);var snapshot: Snapshot = .{};var it = dir.iterate();- while (it.next(io) catch return .{}) |entry| {+ while (it.next(io) catch return null) |entry| {var path_buf: [512]u8 = undefined;// A HID peripheral battery's uevent can send a synchronous GET_REPORT// to the device; `scope` is static, so check it before reading that.@@ -209,11 +286,11 @@ pub fn read(io: std.Io, allocator: std.mem.Allocator) State {if (std.mem.eql(u8, std.mem.trimEnd(u8, scope, "\n"), "Device")) continue;} else |_| {}const path = std.fmt.bufPrint(&path_buf, "{s}/uevent", .{entry.name}) catch continue;- const contents = dir.readFileAlloc(io, path, allocator, .limited(16384)) catch return .{};+ const contents = dir.readFileAlloc(io, path, allocator, .limited(16384)) catch return null;defer allocator.free(contents);snapshot.add(contents);}- return snapshot.state();+ return snapshot;}pub const openUeventSocket = @import("platform").power_supply.openUeventSocket;@@ -222,4 +299,5 @@ pub const isSystemPowerSupplyUevent = @import("platform").power_supply.isSystemPtest {_ = @import("battery_tests.zig");+ _ = @import("battery_rate.zig");}diff --git a/src/taskbar/battery_rate.zig b/src/taskbar/battery_rate.zignew file mode 100644index 0000000..49f3c87--- /dev/null+++ b/src/taskbar/battery_rate.zig@@ -0,0 +1,121 @@+//! Remaining time from how fast the battery's level actually moves.+//!+//! The firmware's present rate (`POWER_NOW`, `CURRENT_NOW`) is a short-window+//! value. One reading per minute tick lands wherever the load happens to be,+//! and on a bursty desktop that is often an idle gap: level / rate then+//! promises hours a real session never gets (and level / rate over a noisy+//! rate skews long even when the gaps are random). The level itself+//! integrates every burst, so the slope of recent readings is the real drain.+//! The reported rate, averaged as power rather than as time, covers the first+//! minutes after a plug change and firmware whose level moves in coarse steps.+const std = @import("std");+const battery = @import("battery.zig");+const Self = @This();++/// Readings older than this no longer shape the estimate.+pub const window_s: f64 = 15 * 60;+/// A longer gap between readings (suspend, an inactive session) starts over:+/// the level barely moves while suspended, which would read as a tiny drain.+pub const max_gap_s: f64 = 3 * 60;+/// The slope needs this much history and this many level changes before it+/// is trusted; a level that moves in 1 % steps needs a few of them.+pub const min_span_s: f64 = 4 * 60;+pub const min_changes: u32 = 3;+const capacity = 64;++pub const Direction = enum { charging, discharging };++const Sample = struct { t: f64, now: f64, rate: ?f64 };++samples: [capacity]Sample = undefined,+len: usize = 0,+direction: ?Direction = null,+unit: ?battery.Level.Unit = null,++pub fn reset(self: *Self) void {+ self.* = .{};+}++pub fn directionOf(state: battery.State) ?Direction {+ if (state.charging) return .charging;+ if (state.discharging) return .discharging;+ return null;+}++/// Records a reading taken at `t` seconds on the boot clock and returns the+/// minutes until empty (discharging) or full (charging), or null when the+/// battery is neither or the level cannot say.+pub fn feed(self: *Self, t: f64, level: ?battery.Level, dir: ?Direction) ?u32 {+ const reading = level orelse return self.clear();+ const d = dir orelse return self.clear();+ if (self.len > 0) {+ const last = self.samples[self.len - 1];+ if (self.direction != d or self.unit != reading.unit or t < last.t or t - last.t > max_gap_s) self.reset();+ }+ self.direction = d;+ self.unit = reading.unit;+ var keep: usize = 0;+ while (keep < self.len and t - self.samples[keep].t > window_s) keep += 1;+ if (self.len - keep == capacity) keep += 1;+ std.mem.copyForwards(Sample, self.samples[0 .. self.len - keep], self.samples[keep..self.len]);+ self.len -= keep;+ self.samples[self.len] = .{ .t = t, .now = reading.now, .rate = reading.rate };+ self.len += 1;++ const rate = self.observedRate() orelse self.reportedRate() orelse return null;+ const remaining = switch (d) {+ .discharging => reading.now,+ .charging => (reading.full orelse return null) - reading.now,+ };+ if (remaining <= 0) return null;+ return battery.minutesFromHours(remaining / rate);+}++fn clear(self: *Self) ?u32 {+ self.reset();+ return null;+}++/// Least-squares slope of the level over the window, per hour, positive in+/// the direction of travel.+fn observedRate(self: *const Self) ?f64 {+ const samples = self.samples[0..self.len];+ if (samples.len < 2 or samples[samples.len - 1].t - samples[0].t < min_span_s) return null;+ var changes: u32 = 0;+ for (samples[1..], samples[0 .. samples.len - 1]) |b, a| {+ if (b.now != a.now) changes += 1;+ }+ if (changes < min_changes) return null;+ const n: f64 = @floatFromInt(samples.len);+ var mean_t: f64 = 0;+ var mean_level: f64 = 0;+ for (samples) |s| {+ mean_t += s.t / n;+ mean_level += s.now / n;+ }+ var cov: f64 = 0;+ var variance: f64 = 0;+ for (samples) |s| {+ cov += (s.t - mean_t) * (s.now - mean_level);+ variance += (s.t - mean_t) * (s.t - mean_t);+ }+ if (variance <= 0) return null;+ const per_hour = cov / variance * 3600;+ const travel = if (self.direction == .discharging) -per_hour else per_hour;+ return if (travel > 0 and std.math.isFinite(travel)) travel else null;+}++/// Mean of the firmware's present rates over the window.+fn reportedRate(self: *const Self) ?f64 {+ var sum: f64 = 0;+ var count: f64 = 0;+ for (self.samples[0..self.len]) |s| if (s.rate) |r| {+ sum += r;+ count += 1;+ };+ return if (count > 0 and sum > 0) sum / count else null;+}++test {+ _ = @import("battery_rate_tests.zig");+}diff --git a/src/taskbar/battery_rate_tests.zig b/src/taskbar/battery_rate_tests.zignew file mode 100644index 0000000..cbe24d7--- /dev/null+++ b/src/taskbar/battery_rate_tests.zig@@ -0,0 +1,74 @@+const std = @import("std");+const battery = @import("battery.zig");+const Estimator = @import("battery_rate.zig");++fn level(wh: f64, watts: ?f64) battery.Level {+ return .{ .unit = .energy, .now = wh * 1_000_000, .full = 60_000_000, .rate = if (watts) |w| w * 1_000_000 else null };+}++test "a level draining faster than the sampled rate wins once it has history" {+ // 12 W real drain, but every minute tick catches an idle 4 W reading.+ var e: Estimator = .{};+ var minutes: ?u32 = null;+ for (0..6) |i| {+ const t: f64 = 1000 + @as(f64, @floatFromInt(i)) * 60;+ minutes = e.feed(t, level(40 - 0.2 * @as(f64, @floatFromInt(i)), 4), .discharging);+ // The first minutes have only the reported rate: 40 Wh / 4 W.+ if (i == 0) try std.testing.expectEqual(@as(?u32, 600), minutes);+ }+ // 39 Wh left at 12 W: 195 min.+ try std.testing.expect(minutes.? >= 195 and minutes.? <= 196);+}++test "reported rates average as power, not as time" {+ var e: Estimator = .{};+ _ = e.feed(0, level(40, 4), .discharging);+ // Level unchanged (coarse firmware), rates 4 W and 16 W: 40 Wh / 10 W.+ try std.testing.expectEqual(@as(?u32, 240), e.feed(60, level(40, 16), .discharging));+}++test "coarse level steps wait for enough changes before the slope counts" {+ var e: Estimator = .{};+ var minutes: ?u32 = null;+ // 1 % steps of 0.6 Wh every 3 min (12 W), firmware rate claims 6 W.+ for (0..10) |i| {+ const step: f64 = @floatFromInt(i / 3);+ minutes = e.feed(@as(f64, @floatFromInt(i)) * 60, level(30 - 0.6 * step, 6), .discharging);+ if (i == 5) try std.testing.expect(minutes.? > 250);+ }+ try std.testing.expect(minutes.? < 170);+}++test "a gap, a direction change or a missing level starts over" {+ var e: Estimator = .{};+ for (0..6) |i| _ = e.feed(@as(f64, @floatFromInt(i)) * 60, level(40 - 0.2 * @as(f64, @floatFromInt(i)), 4), .discharging);+ // After suspend only the new reading's rate counts.+ try std.testing.expectEqual(@as(?u32, 585), e.feed(3600, level(39, 4), .discharging));+ // Charging needs the room left to full: 21 Wh at 30 W.+ try std.testing.expectEqual(@as(?u32, 42), e.feed(3660, level(39, 30), .charging));+ try std.testing.expectEqual(@as(?u32, null), e.feed(3720, level(39, 30), null));+ try std.testing.expectEqual(@as(usize, 0), e.len);+ try std.testing.expectEqual(@as(?u32, null), e.feed(3780, null, .discharging));+ try std.testing.expectEqual(@as(?u32, null), e.feed(3840, level(39, null), .discharging));+}++test "old readings leave the window and the buffer never overflows" {+ var e: Estimator = .{};+ for (0..200) |i| _ = e.feed(@as(f64, @floatFromInt(i)) * 10, level(50 - 0.01 * @as(f64, @floatFromInt(i)), 3.6), .discharging);+ try std.testing.expect(e.len <= 64);+ try std.testing.expect(e.samples[e.len - 1].t - e.samples[0].t <= Estimator.window_s);+}++test "snapshot levels sum packs with the same units and drop mixed ones" {+ var s: battery.Snapshot = .{};+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=50\nPOWER_SUPPLY_STATUS=Discharging\nPOWER_SUPPLY_ENERGY_NOW=20000000\nPOWER_SUPPLY_ENERGY_FULL=40000000\nPOWER_SUPPLY_POWER_NOW=5000000\n");+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=50\nPOWER_SUPPLY_STATUS=Discharging\nPOWER_SUPPLY_ENERGY_NOW=10000000\nPOWER_SUPPLY_ENERGY_FULL=20000000\nPOWER_SUPPLY_POWER_NOW=1000000\n");+ try std.testing.expectEqual(@as(?battery.Level, .{ .unit = .energy, .now = 30_000_000, .full = 60_000_000, .rate = 6_000_000 }), s.level());+ try std.testing.expect(!s.driver_time);+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=50\nPOWER_SUPPLY_CHARGE_NOW=1000000\n");+ try std.testing.expectEqual(@as(?battery.Level, null), s.level());+ s = .{};+ s.add("POWER_SUPPLY_TYPE=Battery\nPOWER_SUPPLY_CAPACITY=50\nPOWER_SUPPLY_STATUS=Discharging\nPOWER_SUPPLY_CHARGE_NOW=2000000\nPOWER_SUPPLY_CURRENT_NOW=-1000000\nPOWER_SUPPLY_TIME_TO_EMPTY_NOW=3600\n");+ try std.testing.expectEqual(@as(?battery.Level, .{ .unit = .charge, .now = 2_000_000, .full = null, .rate = 1_000_000 }), s.level());+ try std.testing.expect(s.driver_time);+}