{ config, lib, pkgs, ... }: with lib; let cfg = config.services.zigbee2mqtt; device = "/dev/ttyACM0"; dataFolder = "/srv/zigbee/data"; zigbeeConfiguration = { # Home Assistant integration (MQTT discovery) homeassistant = false; # homeassistant = true; # allow new devices to join permit_join = cfg.discover; # MQTT settings mqtt = { # MQTT base topic for zigbee2mqtt MQTT messages base_topic = "zigbee2mqtt"; # MQTT server URL server = "mqtt://127.0.0.1:1883"; # MQTT server authentication, uncomment if required: user = "zigbee"; password = cfg.mqttPassword; }; # Serial settings serial = { port = device; # disable LED of CC2531 USB sniffer disable_led = true; }; devices = cfg.devices; } // (lib.optionalAttrs (cfg.networkKey != null) { advanced.network_key = cfg.networkKey; }); configurationYaml = pkgs.writeText "configuration.yml" (builtins.toJSON zigbeeConfiguration); in { options.services.zigbee2mqtt = { enable = mkEnableOption "enable services.zigbee2mqtt"; discover = mkEnableOption "discover new devices"; mqttPassword = mkOption { type = with types; str; description = '' password of the mqtt server. ''; }; networkKey = mkOption { type = with types; nullOr (listOf int); description = '' you own network key, 16 numbers between 0 and 255 see https://www.zigbee2mqtt.io/how_tos/how_to_secure_network.html ''; example = [ 7 3 5 7 9 11 13 15 0 2 4 6 8 11 12 13 ]; }; devices = mkOption { type = with types; attrs; description = '' device definitions. ''; }; }; config = mkIf cfg.enable { # todo : einen eigenen container bauen mit dockerTool : https://nixos.wiki/wiki/Docker virtualisation.docker.enable = true; systemd.services."zigbee2mqtt" = { enable = true; description = "Allows you to use your Zigbee devices without the vendors bridge/gateway."; after = [ "docker.service" ]; requires = [ "docker.service" ]; # todo : udev rule erstellen, die diesen service erst startet, dieses wanted by ist labil wantedBy = [ "home-assistant.service" ]; preStart = '' if [ -f ${dataFolder}/configuration.yaml ] then rm ${dataFolder}/configuration.yaml fi mkdir -p ${dataFolder} cat ${configurationYaml} | ${pkgs.yq}/bin/yq --yaml-output '.' > ${dataFolder}/configuration.yaml ''; restartTriggers = [ configurationYaml ]; script = '' # delete old instance to ensure update ${pkgs.docker}/bin/docker stop zigbee2mqtt || true && ${pkgs.docker}/bin/docker rm -f zigbee2mqtt || true # start instance ${pkgs.docker}/bin/docker run \ --network="host" \ --name zigbee2mqtt \ -v ${dataFolder}:/app/data \ --device=${device} \ koenkk/zigbee2mqtt ''; }; }; }