summaryrefslogtreecommitdiffstats
path: root/krebs/3modules/power-action.nix
diff options
context:
space:
mode:
authortv <tv@krebsco.de>2016-08-02 20:58:42 +0200
committertv <tv@krebsco.de>2016-08-02 20:58:42 +0200
commite6aef09ad41cd55d716b8ee276ebd774b95d8ecb (patch)
tree6d8d5cce976f3843ab196367e82fec56f0798838 /krebs/3modules/power-action.nix
parent0928cc03a6191640c66c9122159994855527faef (diff)
parentb197949ab83ee3ee87b5774e0fc7c8d0123a6708 (diff)
Merge remote-tracking branch 'gum/master'
Diffstat (limited to 'krebs/3modules/power-action.nix')
-rw-r--r--krebs/3modules/power-action.nix92
1 files changed, 92 insertions, 0 deletions
diff --git a/krebs/3modules/power-action.nix b/krebs/3modules/power-action.nix
new file mode 100644
index 000000000..bb5b3e521
--- /dev/null
+++ b/krebs/3modules/power-action.nix
@@ -0,0 +1,92 @@
+{ config, lib, pkgs, ... }:
+
+with config.krebs.lib;
+
+let
+ cfg = config.krebs.power-action;
+
+ out = {
+ options.krebs.power-action = api;
+ config = lib.mkIf cfg.enable imp;
+ };
+
+ api = {
+ enable = mkEnableOption "power-action";
+ battery = mkOption {
+ type = types.str;
+ default = "BAT0";
+ };
+ user = mkOption {
+ type = types.string;
+ default = "power-action";
+ };
+ startAt = mkOption {
+ type = types.str;
+ default = "*:0/1";
+ };
+ plans = mkOption {
+ type = with types; attrsOf (submodule {
+ options = {
+ charging = mkOption {
+ type = nullOr bool;
+ default = null;
+ description = ''
+ check for charging status.
+ null = don't care
+ true = only if system is charging or unknown
+ false = only if system is discharging
+ '';
+ };
+ upperLimit = mkOption {
+ type = int;
+ };
+ lowerLimit = mkOption {
+ type = int;
+ };
+ action = mkOption {
+ type = path;
+ };
+ };
+ });
+ };
+ };
+
+ imp = {
+ systemd.services.power-action = {
+ serviceConfig = rec {
+ ExecStart = startScript;
+ User = cfg.user;
+ };
+ startAt = cfg.startAt;
+ };
+ };
+
+ startScript = pkgs.writeDash "power-action" ''
+ set -euf
+
+ power="$(${powerlvl})"
+ state="$(${state})"
+ ${concatStringsSep "\n" (mapAttrsToList writeRule cfg.plans)}
+ '';
+ charging_check = plan:
+ if (plan.charging == null) then "" else
+ if plan.charging
+ then ''&& [ "$state" = "true" ]''
+ else ''&& ! [ "$state" = "true" ]''
+ ;
+
+ writeRule = _: plan:
+ "if [ $power -ge ${toString plan.lowerLimit} ] && [ $power -le ${toString plan.upperLimit} ] ${charging_check plan}; then ${plan.action}; fi";
+
+ powerlvl = pkgs.writeDash "powerlvl" ''
+ cat /sys/class/power_supply/${cfg.battery}/capacity
+ '';
+
+ state = pkgs.writeDash "state" ''
+ if [ "$(cat /sys/class/power_supply/${cfg.battery}/status)" = "Discharging" ]
+ then echo "false"
+ else echo "true"
+ fi
+ '';
+
+in out