From c75ab728a38ede1540a83aad307fefdb23fbabba Mon Sep 17 00:00:00 2001 From: sinanmohd Date: Fri, 30 Aug 2024 11:57:06 +0530 Subject: home/wayland/swayidle: suspend idle system on battery --- home/wayland/modules/sway/swayidle.nix | 51 ++++++++++++++++++++++++++++++++-- 1 file changed, 48 insertions(+), 3 deletions(-) diff --git a/home/wayland/modules/sway/swayidle.nix b/home/wayland/modules/sway/swayidle.nix index 1aa16c5..abb3a10 100644 --- a/home/wayland/modules/sway/swayidle.nix +++ b/home/wayland/modules/sway/swayidle.nix @@ -2,14 +2,51 @@ swaylock = lib.getExe config.programs.swaylock.package; brightnessctl = lib.getExe pkgs.brightnessctl; swaymsg = "${pkgs.sway}/bin/swaymsg"; + + minute = 60; # seconds + suspend_timeout = minute * 60; + suspend_on_battery = pkgs.writeShellApplication { + name = "suspend_on_battery"; + runtimeInputs = with pkgs; [ gnugrep systemd sudo coreutils ]; + text = let + sudo = "/run/wrappers/bin/sudo"; + in '' + is_discharging() { + grep -qFx \ + 'POWER_SUPPLY_STATUS=Discharging' \ + /sys/class/power_supply/*/uevent + } + + was_charging=false + while true; do + if is_discharging; then + if [ $was_charging = true ]; then + sleep ${builtins.toString suspend_timeout} + fi + + if is_discharging; then + ${sudo} systemctl suspend-then-hibernate + fi + fi + + was_charging=true + sleep 10 + done + ''; + }; in { + systemd.user.services.suspend_on_battery = { + Unit.Description = "Suspend on battery"; + Service.ExecStart = lib.getExe suspend_on_battery; + }; + services.swayidle = { enable = true; systemdTarget = "sway-session.target"; timeouts = [ { - timeout = 250; + timeout = minute * 4; command = "${brightnessctl} --save; " + "${brightnessctl} set 10%-"; @@ -17,12 +54,12 @@ in { } { - timeout = 300; + timeout = minute * 5; command = swaylock; } { - timeout = 600; + timeout = minute * 10; command = "${swaymsg} --type command 'output * dpms off'; " + "${brightnessctl} -c leds -d platform::kbd_backlight --save; " @@ -31,6 +68,14 @@ in { "${brightnessctl} -c leds -d platform::kbd_backlight --restore; " + "${swaymsg} --type command 'output * dpms on'"; } + + { + timeout = suspend_timeout; + command = + "${pkgs.systemd}/bin/systemctl --user start suspend_on_battery"; + resumeCommand = + "${pkgs.systemd}/bin/systemctl --user stop suspend_on_battery"; + } ]; }; } -- cgit v1.2.3