all repos — dotfiles @ ef4e054f609a65e639255b16addda1c1ad656ec4

my *nix dotfiles

nix/services/suspend.nix (view raw)

 1{ config, lib, pkgs, ... }:
 2
 3with lib;
 4let
 5  cfg = config.services.batteryNotifier;
 6in
 7{
 8  options = {
 9    services.batteryNotifier = {
10      enable = mkOption {
11        default = false;
12        description = ''
13          Whether to enable battery notifier.
14        '';
15      };
16      device = mkOption {
17        default = "BAT0";
18        description = ''
19          Device to monitor.
20        '';
21      };
22      notifyCapacity = mkOption {
23        default = 10;
24        description = ''
25          Battery level at which a notification shall be sent.
26        '';
27      };
28      suspendCapacity = mkOption {
29        default = 5;
30        description = ''
31          Battery level at which a suspend unless connected shall be sent.
32        '';
33      };
34    };
35  };
36
37  config = mkIf cfg.enable {
38    systemd.user.timers."lowbatt" = {
39      description = "check battery level";
40      timerConfig.OnBootSec = "5m";
41      timerConfig.OnUnitInactiveSec = "5m";
42      timerConfig.Unit = "lowbatt.service";
43      wantedBy = [ "timers.target" ];
44    };
45    systemd.user.services."lowbatt" = {
46      description = "battery level notifier";
47      serviceConfig.PassEnvironment = "DISPLAY";
48      script = ''
49        export battery_capacity=$(${pkgs.coreutils}/bin/cat /sys/class/power_supply/${cfg.device}/capacity)
50        export battery_status=$(${pkgs.coreutils}/bin/cat /sys/class/power_supply/${cfg.device}/status)
51        if [[ $battery_capacity -le ${builtins.toString cfg.notifyCapacity} && $battery_status = "Discharging" ]]; then
52            ${pkgs.libnotify}/bin/notify-send --urgency=critical --hint=int:transient:1 --icon=battery_empty "Battery Low: $battery_capacity%"
53        fi
54        if [[ $battery_capacity -le ${builtins.toString cfg.suspendCapacity} && $battery_status = "Discharging" ]]; then
55            ${pkgs.libnotify}/bin/notify-send --urgency=critical --hint=int:transient:1 --icon=battery_empty "Battery Critically Low: $battery_capacity%"
56            sleep 60s
57            battery_status=$(${pkgs.coreutils}/bin/cat /sys/class/power_supply/${cfg.device}/status)
58            if [[ $battery_status = "Discharging" ]]; then
59                systemctl suspend
60            fi
61        fi
62      '';
63    };
64  };
65}