feat(power): re-apply battery charge limit on AC state change

The threshold was written boot-only, so a firmware that clears
charge_control_end_threshold on unplug would silently lose the cap
until the next reboot. Add a services.udev rule on the mains adapter
(ATTR{type}=="Mains", vendor-neutral) that restarts the oneshot via
systemctl --no-block on every AC state change. Uses restart (not
try-restart) so it re-applies even if the boot run was inactive.

Eval-verified: rule present when the charge limit is on, absent when
off; downstream-template-system still evaluates.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Bernardo Magri
2026-06-30 21:10:44 +01:00
parent cdfe92a089
commit 9976ea06f5
3 changed files with 29 additions and 9 deletions

View File

@@ -109,8 +109,9 @@
where the hardware exposes a charge threshold
(/sys/class/power_supply/BAT*/charge_control_end_threshold).
null leaves charging at the firmware default. Backend-independent
(a small systemd unit writes the sysfs knob at boot), so it
works under PPD too; needs nomarchy.system.power.laptop.
(a small systemd unit writes the sysfs knob, re-applied on AC
state changes), so it works under PPD too; needs
nomarchy.system.power.laptop.
'';
};
};

View File

@@ -38,10 +38,10 @@ in
# Battery charge limit via sysfs. PPD can't cap charge at all, and
# TLP's own knob only applies under TLP — so a tiny oneshot writes
# the threshold directly, independent of the backend. Boot-time only:
# some firmwares reset the threshold on unplug; revisit with a udev
# hook if that bites. `-` paths that don't exist are skipped, so this
# is a clean no-op on hardware without the control.
# the threshold directly, independent of the backend. Re-applied on
# AC state changes by the udev rule below (some firmwares reset the
# threshold when the charger is unplugged). `[ -w ]` skips paths that
# don't exist, so this is a clean no-op on hardware without the control.
systemd.services.nomarchy-battery-charge-limit = lib.mkIf chargeLimit {
description = "Cap battery charging at ${toString cfg.batteryChargeLimit}%";
wantedBy = [ "multi-user.target" ];
@@ -56,5 +56,16 @@ in
exit 0
'';
};
# Re-apply the threshold whenever the mains adapter changes state: the
# boot oneshot above runs once, but some firmwares clear the limit when
# the charger is unplugged, so it must be re-asserted on the event.
# Matched by ATTR{type}=="Mains" (vendor-neutral — the kernel name
# AC/AC0/ADP1/ACAD varies); --no-block so the RUN+= returns at once
# (systemd kills long-running udev workers); restart (not try-restart)
# so it re-applies even if the boot run was inactive.
services.udev.extraRules = lib.mkIf chargeLimit ''
SUBSYSTEM=="power_supply", ATTR{type}=="Mains", RUN+="${config.systemd.package}/bin/systemctl --no-block restart nomarchy-battery-charge-limit.service"
'';
};
}