@@ -0,0 +1,98 @@
1+{ config, lib, pkgs, ... }:
2+
3+with lib;
4+
5+let
6+ cfg = config.services.zigbee2mqtt;
7+
8+ configJSON = pkgs.writeText "configuration.json"
9+ (builtins.toJSON (recursiveUpdate defaultConfig cfg.config));
10+ configFile = pkgs.runCommand "configuration.yaml" { preferLocalBuild = true; } ''
11+ ${pkgs.remarshal}/bin/json2yaml -i ${configJSON} -o $out
12+ '';
13+
14+ # the default config contains all required settings,
15+ # so the service starts up without crashing.
16+ defaultConfig = {
17+ homeassistant = false;
18+ permit_join = false;
19+ mqtt = {
20+ base_topic = "zigbee2mqtt";
21+ server = "mqtt://localhost:1883";
22+ };
23+ serial.port = "/dev/ttyACM0";
24+ # put device configuration into separate file because configuration.yaml
25+ # is copied from the store on startup
26+ devices = "devices.yaml";
27+ };
28+in
29+{
30+ meta.maintainers = with maintainers; [ sweber ];
31+
32+ options.services.zigbee2mqtt = {
33+ enable = mkEnableOption "enable zigbee2mqtt service";
34+
35+ package = mkOption {
36+ description = "Zigbee2mqtt package to use";
37+ default = pkgs.zigbee2mqtt.override {
38+ dataDir = cfg.dataDir;
39+ };
40+ defaultText = "pkgs.zigbee2mqtt";
41+ type = types.package;
42+ };
43+
44+ dataDir = mkOption {
45+ description = "Zigbee2mqtt data directory";
46+ default = "/var/lib/zigbee2mqtt";
47+ type = types.path;
48+ };
49+
50+ config = mkOption {
51+ default = {};
52+ type = with types; nullOr attrs;
53+ example = literalExample ''
54+ {
55+ homeassistant = config.services.home-assistant.enable;
56+ permit_join = true;
57+ serial = {
58+ port = "/dev/ttyACM1";
59+ };
60+ }
61+ '';
62+ description = ''
63+ Your <filename>configuration.yaml</filename> as a Nix attribute set.
64+ '';
65+ };
66+ };
67+
68+ config = mkIf (cfg.enable) {
69+ systemd.services.zigbee2mqtt = {
70+ description = "Zigbee2mqtt Service";
71+ wantedBy = [ "multi-user.target" ];
72+ after = [ "network.target" ];
73+ serviceConfig = {
74+ ExecStart = "${cfg.package}/bin/zigbee2mqtt";
75+ User = "zigbee2mqtt";
76+ WorkingDirectory = cfg.dataDir;
77+ Restart = "on-failure";
78+ ProtectSystem = "strict";
79+ ReadWritePaths = cfg.dataDir;
80+ PrivateTmp = true;
81+ RemoveIPC = true;
82+ };
83+ preStart = ''
84+ cp --no-preserve=mode ${configFile} "${cfg.dataDir}/configuration.yaml"
85+ '';
86+ };
87+
88+ users.users.zigbee2mqtt = {
89+ home = cfg.dataDir;
90+ createHome = true;
91+ group = "zigbee2mqtt";
92+ extraGroups = [ "dialout" ];
93+ uid = config.ids.uids.zigbee2mqtt;
94+ };
95+
96+ users.groups.zigbee2mqtt.gid = config.ids.gids.zigbee2mqtt;
97+ };
98+}