nixos-configuration/modules/esphome/default.nix
2025-05-27 15:10:20 +02:00

100 lines
2.8 KiB
Nix

{ lib
, pkgs
, config
, ...
}:
let
cfg = config.jalr.esphome;
esphomeParams =
if config.services.esphome.enableUnixSocket
then "--socket /run/esphome/esphome.sock"
else "--address ${config.services.esphome.address} --port ${toString config.services.esphome.port}";
in
{
options.jalr.esphome = with lib; with lib.types; {
enable = mkEnableOption "ESPHome";
port = mkOption {
description = "TCP port for esphome dashboard.";
type = port;
};
configDir = mkOption {
type = path;
description = "Location of the device configuration";
};
secretsFile = mkOption {
type = path;
description = "Location of the secrets file";
};
};
config = lib.mkIf cfg.enable {
services.esphome = {
enable = true;
address = "127.0.0.1";
inherit (cfg) port;
package = pkgs.esphome;
};
systemd.services.esphome = {
environment = {
"PLATFORMIO_CORE_DIR" = lib.mkForce "/var/cache/esphome/.platformio";
};
serviceConfig = {
BindReadOnlyPaths = [
"/nix/store"
"%d/secrets.yaml:/run/esphome/config/secrets.yaml"
"/etc/resolv.conf"
"/etc/ssl"
"/etc/static/ssl"
];
TemporaryFileSystem = [
"/var/lib"
];
ExecPaths = [
"-+/var/cache/esphome/.platformio/packages/"
];
DeviceAllow = [
"char-ttyACM rw"
"char-ttyAMA rw"
"char-ttyUSB rw"
];
ExecStartPre = [
(pkgs.writeShellScript "esphome-exec-start-pre" ''
if ! [ -d "$CACHE_DIRECTORY/.platformio/packages" ]; then
mkdir -p "$CACHE_DIRECTORY/.platformio/packages"
exit 1
fi
mkdir -p "$CACHE_DIRECTORY/.esphome"
for linked in \
.esphome \
.gitignore
do
ln -s "$CACHE_DIRECTORY/$linked" "/run/esphome/config/$linked"
done
${pkgs.rsync}/bin/rsync \
-a \
--delete \
--checksum \
--exclude secrets.yaml \
--exclude=.esphome \
--exclude=.platformio \
--exclude=.gitignore \
'${cfg.configDir}/' /run/esphome/config/
'')
];
ExecStart = lib.mkForce "${config.services.esphome.package}/bin/esphome dashboard ${esphomeParams} /run/esphome/config";
LoadCredential = "secrets.yaml:${cfg.secretsFile}";
PrivateTmp = true;
RootDirectory = "%t/esphome/chroot";
RuntimeDirectory = [
"esphome/chroot"
"esphome/config"
];
StateDirectory = lib.mkForce [ ];
CacheDirectory = "esphome";
SupplementaryGroups = [ "dialout" ];
WorkingDirectory = lib.mkForce "/run/esphome/config";
};
};
};
}