From 35e165b801a910f588e074f318d6739fd57f968e Mon Sep 17 00:00:00 2001 From: Syed Daanish Date: Thu, 9 Jul 2026 18:46:21 +0100 Subject: [PATCH] Add hinernation on low battery feature --- home/battery/default.nix | 49 ++++++++++++++++++++++++---------------- 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/home/battery/default.nix b/home/battery/default.nix index 20d9589..235a9d9 100644 --- a/home/battery/default.nix +++ b/home/battery/default.nix @@ -1,46 +1,55 @@ { config, pkgs, ... }: let - batteryNotify = pkgs.writeShellScript "battery-notify" '' + battery = pkgs.writeShellScript "battery" '' BAT="/sys/class/power_supply/BAT1" LEVEL=$(cat "$BAT/capacity") STATUS=$(cat "$BAT/status") - if [ "$STATUS" = "Discharging" ] && [ "$LEVEL" -lt 20 ]; then - ${pkgs.dunst}/bin/dunstify \ - -r 9991 \ - -t 0 \ - -u critical \ - "Battery Low" \ - "Battery is at ''${LEVEL}%" - else - ${pkgs.dunst}/bin/dunstify \ - -C 9991 2>/dev/null || true + has_notifications() { + ${pkgs.dbus}/bin/busctl --user status org.freedesktop.Notifications >/dev/null 2>&1 + } + + if [ "$STATUS" = "Discharging" ] && [ "$LEVEL" -lt 3 ]; then + ${pkgs.systemd}/bin/systemctl hibernate + exit 0 + fi + + if has_notifications; then + if [ "$STATUS" = "Discharging" ] && [ "$LEVEL" -lt 20 ]; then + ${pkgs.dunst}/bin/dunstify \ + -r 9991 \ + -t 0 \ + -u critical \ + "Battery Low" \ + "Battery is at ''${LEVEL}%" + else + ${pkgs.dunst}/bin/dunstify \ + -C 9991 2>/dev/null || true + fi fi ''; in { - systemd.user.services.battery-notify = { + systemd.user.services.battery = { Unit = { - Description = "Low battery notification"; - After = [ "dunst.service" ]; - Requires = [ "dunst.service" ]; + Description = "Battery management"; }; Service = { Type = "oneshot"; - ExecStart = batteryNotify; + ExecStart = battery; }; }; - systemd.user.timers.battery-notify = { + systemd.user.timers.battery = { Unit = { - Description = "Check battery level every 20 seconds"; + Description = "Check battery level every 15 seconds"; }; Timer = { - OnBootSec = "20s"; - OnUnitActiveSec = "20s"; + OnBootSec = "15s"; + OnUnitActiveSec = "15s"; }; Install = {