ctucx.git: sdm2mqtt

Publish data from SDM120M meters via MQTT

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
83 
84 
85 
86 
87 
88 
89 
90 
91 
92 
93 
{ options, config, pkgs, lib, ... }:

with lib;

let
  cfg            = config.services.sdm2mqtt;
  settingsFormat = pkgs.formats.json {};
  configFile     = settingsFormat.generate "sdm2mqtt-config.json" cfg.config;

in {

  options = {
    services.sdm2mqtt = with lib; {
      enable = mkEnableOption "sdm2mqtt - Exporter for SDM120M meters to mqtt, written in nim";

      package = mkOption {
        type    = types.package;
        default = pkgs.sdm2mqtt;
      };

      config = mkOption {
        type    = settingsFormat.type;
        default = {};
        example = {};
      };

      environmentFiles = mkOption {
        type = types.listOf types.path;
        default = [];
        example = [ "/run/keys/sdm2mqtt.env" ];
        description = lib.mdDoc ''
          File to load as environment file. Environment variables from this file
          will be interpolated into the config file using envsubst.
          This is useful to avoid putting secrets into the nix store.
        '';
      };

    };
  };


  config = lib.mkIf cfg.enable {

    systemd.services.sdm2mqtt = {
      after           = [ "network-online.target" ];
      wantedBy        = [ "multi-user.target" ];

      environment.CONFIG_PATH  = (
        if cfg.environmentFiles == []
        then configFile
        else "/var/run/sdm2mqtt/config.json"
      );

      serviceConfig = {
        DynamicUser  = true;

        Restart      = "on-failure";
        RestartSec   = 5;

        RuntimeDirectory   = "sdm2mqtt";

        EnvironmentFile = cfg.environmentFiles;

        ExecStart    = "${cfg.package}/bin/sdm2mqtt";
        ExecStartPre = lib.optional (cfg.environmentFiles != []) (pkgs.writeShellScript "sdm2mqtt-preStart" ''
          umask 077
          ${pkgs.envsubst}/bin/envsubst -i "${configFile}" > /var/run/sdm2mqtt/config.json
        '');

        NoNewPrivileges         = true;
        PrivateTmp              = true;

        ProtectSystem           = "strict";
        ProtectKernelLogs       = true;
        ProtectKernelModules    = true;
        ProtectKernelTunables   = true;
        ProtectControlGroups    = true;
        ProtectHome             = true;

        RestrictAddressFamilies = lib.mkDefault "AF_UNIX AF_INET AF_INET6";
        RestrictNamespaces      = true;
        RestrictRealtime        = true;
      
        DevicePolicy            = "closed";
        LockPersonality         = true;

        LimitNPROC              = 1;
      };
    };

  };

}