Files
nixos-configs/hosts/pinwheel/modules/power/default.nix
Alexander Heldt f15701f426 Apply nixfmt
2024-09-02 21:55:41 +02:00

115 lines
3.0 KiB
Nix

{
pkgs,
lib,
config,
...
}:
let
enabled = config.mod.power.enable;
lowbat = config.mod.lowbat;
in
{
options = {
mod.power = {
enable = lib.mkEnableOption "enable power module";
};
mod.lowbat = {
enable = lib.mkEnableOption "enable low battery manager";
battery = lib.mkOption {
default = "BAT0";
description = "Battery to monitor";
};
notifyCapacity = lib.mkOption {
default = 15;
description = "Notify low battery at this level";
};
suspendCapacity = lib.mkOption {
default = 10;
description = "Warn at this level and then suspend if power is not plugged in";
};
};
};
config = {
services = lib.mkIf enabled {
upower = {
enable = true;
};
tlp = {
enable = true;
settings = {
START_CHARGE_THRESH_BAT0 = 75;
STOP_CHARGE_THRESH_BAT0 = 80;
};
};
};
systemd.user = lib.mkIf lowbat.enable {
timers = {
"monitor-low-battery" = {
unitConfig = {
Description = "monitors battery level and suspends computer if battery is low";
};
timerConfig = {
Unit = "monitor-low-battery.service";
OnCalendar = "*-*-* *:00/15:00"; # Every 15 minutes
Persistent = true;
};
wantedBy = [ "timers.target" ];
};
};
services = {
"monitor-low-battery" = {
unitConfig = {
Description = "monitors battery level and suspends computer if battery is low";
};
serviceConfig = {
Type = "exec";
};
path = [
pkgs.coreutils # For `cat`
pkgs.libnotify
pkgs.swaylock
];
script =
let
pause-music = "${pkgs.playerctl}/bin/playerctl -p spotify pause";
in
''
BATTERY_CAPACITY=$(cat /sys/class/power_supply/${lowbat.battery}/capacity)
BATTERY_STATUS=$(cat /sys/class/power_supply/${lowbat.battery}/status)
echo "Battery capacity: $BATTERY_CAPACITY"
echo "Battery status: $BATTERY_STATUS"
if [[ $BATTERY_CAPACITY -le ${builtins.toString lowbat.notifyCapacity} && $BATTERY_STATUS = "Discharging" ]]; then
notify-send --expire-time=0 --urgency=critical "Battery Low"
fi
if [[ $BATTERY_CAPACITY -le ${builtins.toString lowbat.suspendCapacity} && $BATTERY_STATUS = "Discharging" ]]; then
notify-send --expire-time=0 --urgency=critical "Battery Critically Low" "Suspending in 60 seconds if power is not plugged in"
sleep 60s
BATTERY_STATUS=$(cat /sys/class/power_supply/${lowbat.battery}/status)
if [[ $BATTERY_STATUS = "Discharging" ]]; then
${pause-music}; ${pkgs.swaylock}/bin/swaylock -f; systemctl suspend
fi
fi
'';
};
};
};
};
}