stockholm/krebs/3modules/power-action.nix

92 lines
2.1 KiB
Nix
Raw Normal View History

2016-06-16 20:42:14 +00:00
{ config, lib, pkgs, ... }:
with lib;
2016-06-16 20:42:14 +00:00
let
2016-07-26 19:36:47 +00:00
cfg = config.krebs.power-action;
2016-06-16 20:42:14 +00:00
out = {
2016-07-26 19:36:47 +00:00
options.krebs.power-action = api;
config = lib.mkIf cfg.enable imp;
2016-06-16 20:42:14 +00:00
};
api = {
enable = mkEnableOption "power-action";
battery = mkOption {
type = types.str;
default = "BAT0";
};
2016-06-16 20:42:14 +00:00
user = mkOption {
type = types.string;
default = "power-action";
2016-06-16 20:42:14 +00:00
};
startAt = mkOption {
type = types.str;
default = "*:0/1";
};
plans = mkOption {
type = with types; attrsOf (submodule {
options = {
2016-06-18 19:51:45 +00:00
charging = mkOption {
type = nullOr bool;
default = null;
description = ''
check for charging status.
null = don't care
2016-08-02 12:59:58 +00:00
true = only if system is charging or unknown
2016-06-18 19:51:45 +00:00
false = only if system is discharging
'';
};
2016-06-16 20:42:14 +00:00
upperLimit = mkOption {
type = int;
};
lowerLimit = mkOption {
type = int;
};
action = mkOption {
type = path;
};
};
});
};
};
imp = {
systemd.services.power-action = {
serviceConfig = rec {
ExecStart = startScript;
User = cfg.user;
2016-06-16 20:42:14 +00:00
};
startAt = cfg.startAt;
};
};
startScript = pkgs.writeDash "power-action" ''
2016-06-18 19:51:45 +00:00
set -euf
2016-06-16 20:42:14 +00:00
power="$(${powerlvl})"
2016-06-18 19:51:45 +00:00
state="$(${state})"
2016-06-16 20:42:14 +00:00
${concatStringsSep "\n" (mapAttrsToList writeRule cfg.plans)}
'';
2016-06-18 19:51:45 +00:00
charging_check = plan:
if (plan.charging == null) then "" else
if plan.charging
then ''&& [ "$state" = "true" ]''
else ''&& ! [ "$state" = "true" ]''
;
2016-06-16 20:42:14 +00:00
writeRule = _: plan:
2016-06-18 19:51:45 +00:00
"if [ $power -ge ${toString plan.lowerLimit} ] && [ $power -le ${toString plan.upperLimit} ] ${charging_check plan}; then ${plan.action}; fi";
2016-06-16 20:42:14 +00:00
powerlvl = pkgs.writeDash "powerlvl" ''
cat /sys/class/power_supply/${cfg.battery}/capacity
2016-06-16 20:42:14 +00:00
'';
2016-06-18 19:51:45 +00:00
state = pkgs.writeDash "state" ''
if [ "$(cat /sys/class/power_supply/${cfg.battery}/status)" = "Discharging" ]
2016-06-28 15:39:03 +00:00
then echo "false"
else echo "true"
2016-06-18 19:51:45 +00:00
fi
'';
2016-06-16 20:42:14 +00:00
in out