Home Assistant

From NixOS Wiki
Revision as of 16:20, 4 August 2022 by imported>Mweinelt (→‎Declarative configuration)

Home Assistant is an open source home automation software that puts local control and privacy first. Powered by a worldwide community of tinkerers and DIY enthusiasts.

Installation methods

Upstream has defined several installation methods which they are willing to support. The NixOS module is not one of them. When you find a problem you can still report it upstream, if you are certain that the issue is relevant to upstream supported installation methods as well. If not, or if in doubt, please open an isssue on the nixpkgs issue tracker or visit the NixOS Home-Automation (#nixos-homeautomation:lossy.network) Matrix room.

Upstream supported

Virtual machine

You could run your Home Assistant in a virtual machine, with your NixOS host providing the hypervisor.

TODO: add example configuration

OCI container

You could run your Home Assistant in any kind of container runtime

Example Configuration

Adding the following to your `configuration.nix` will bring up home-assistant listening on `:8123` on the host interface.

{  
  virtualisation.oci-containers = {
    backend = "podman";
    containers.homeassistant = {
      volumes = [ "home-assistant:/config" ];
      environment.TZ = "Europe/Berlin";
      image = "ghcr.io/home-assistant/home-assistant:stable"; # Warning: if the tag does not change, the image will not be updated
      extraOptions = [ 
        "--network=host" 
        "--device=/dev/ttyACM0:/dev/ttyACM0"  # Example, change this to match your own hardware
      ];
    };
  };
}

NixOS Module

You could run home-assistant using the NixOS module system at services-home-assistant. As of 2021-11-28 we have roughly 70% of component dependencies packaged. There are two major ways of running home-assistant using the module system.

Declarative configuration

Set up your home-assistant by configuring the services.home-assistant.config attribute set as if it were your home-assistant YAML configuration. The module parses the root and platforms level to automatically discover integrations used and will add their dependencies to your home-assistant package.

The following is a minimal starting configuration, that has all the dependencies that are required to complete the initial configuration flow, that creates your first user.

{
  services.home-assistant = {
    enable = true;
    extraComponents = [
      # Components required to complete the onboarding
      "met"
      "radio_browser"
    ];
    config = {
      # Includes dependencies for a basic setup
      # https://www.home-assistant.io/integrations/default_config/
      default_config = {};
    };
  };
}
First start

On your first start you may see multiple ModuleNotFoundError in Home Assistants journal log. These are dependencies required to set up devices Home Assistant already found on the network.

The appropriate component to load can be looked up in the component-packages.nix file, that gets auto-generated as part of the packaging process.

For example we can map the following error to

 ModuleNotFoundError: No module named 'aioesphomeapi'

the esphome module quite easily.

{
  version = "2022.8.0";
  components = {
    [...]
    "esphome" = ps: with ps; [
      aioesphomeapi
      aiohttp-cors
      ifaddr
      zeroconf
    ];
    [...]

Using components without YAML configuration

When a component has no YAML configuration its dependencies can in theory be installed by mentioning the component name in services.home-assistant.config.wled = {};. This is deprecated, since Home Assistant will usually complain about the config having been migrated into the graphical user interface.

In recent versions of the home-assistant this use case has become more prominent and therefore received a more straightforward implementation, that also ensures that the component is still provided by Home Assistant.

{
  services.home-assistant.extraComponents = [
    "wled"
  ];
}

Making additional python packages available

We control the dependencies we pass into the Home Assistant python environment through module options that make the dependencies available, when their relative component was declaratively mentioned.

For other use cases like PostgreSQL support in the recorder component or the use of custom components, we provide an option to inject arbitrary dependencies from nixpkgs available python package set.

{
  services.home-assistant.extraPackages = python3Packages: with python3Packages; [
    # recorder postgresql support
    psycopg2

    # miele@home
    flatdict
    (callPackage ./pymiele.nix)
  ];
}

Using custom components

We currently do not provide a way to declaratively manage custom components through the NixOS module. There is an open PR with an implementation, that still requires further work and discussion to make it a good solution.

Until then custom components can be installed to /var/lib/hass/custom_components/ as is the customary for Home Assistant.


Using custom lovelace modules

The support for custom lovelace modules is planned, same as for custom components.

Until then lovelace modules can be installed to /var/lib/hass/www/, which uses Home Assistants internal webserver to serve files below /local/ on your installation. This webserver will not follow symlinks, which we will allow in the future by applying a patch, which will be reasonable safe to do because of all the hardening options we apply by default. The patch in the question is part of the PR above:

Reusing existing YAML configuration

The module also supports passing it an existing configuration, however that comes with certain drawbacks. For example we cannot automatically detect the components, that your configuration requires. In that scenario you will need to resolve dependencies manually using the packages extraComponents parameter. Also you will be unable to reuse configuration values between parts of your NixOS configuration. A barebones setup to get you started may look like this:

{
  services.home-assistant = {
    enable = true;
    # Pass the path to the directory where your configuration.yaml
    # resides, /var/lib/hass might be a good location.
    configDir = /var/lib/hass;
    # Override the package to handle dependency management manually
    package = (pkgs.home-assistant.override {
      # https://github.com/NixOS/nixpkgs/blob/master/pkgs/servers/home-assistant/component-packages.nix
      extraComponents = [
        "default_config"
        "esphome"
        "met"
      ];
      extraPackages = py: with py; [
        # Are you using a database server for your recorder?
        # https://www.home-assistant.io/integrations/recorder/
        #mysqlclient
        #psycopg2

      ];
    }).overrideAttrs (oldAttrs: {
      # Don't run package tests, they take a long time
      doInstallCheck = false;
    });
  };
}

You may find the following script helpful. It looks up missing dependencies from the home-assistant.service systemd unit journal: https://gist.github.com/AngryAnt/74c047a2b8438517c822ffdd9663aa57

Running a recent version using an overlay

Home Assistant is a fast-paced open source project, that currently features one major release every month, and a handful of minor ones in between. Firmwares and API endpoints tend to change from time to time, so Home Assistant and its bindings need to keep up to keep things work. The version we provide at the branch off is just a snapshot in time, and does not receive any updates, because there would just be too many dependencies to backport. But with NixOS it is still possible to use the version in nixpkgs/unstable by creating an overlay and using the module from nixos-unstable.

let
  # Track NixOS unstable via nix-channel, or replace it with something like niv at your own discretion
  # nix-channel --add http://nixos.org/channels/nixos-unstable nixos-unstable
  unstable = import <nixos-unstable> {};
in
{
  nixpkgs.overlays = [
    (self: super: {
      inherit (unstable) home-assistant;
    })
  ];

  disabledModules = [
    "services/home-automation/home-assistant.nix"
  ];

  imports = [
    <nixos-unstable/nixos/modules/services/home-automation/home-assistant.nix>
  ];
}

Snippets

Reverse Proxying with nginx

If you run a public Home Assistant instance it is a good idea to enable SSL/TLS. The following configuration generates a certificate using letsencrypt:

  services.home-assistant.config.http = {
    server_host = "::1";
    trusted_proxies = [ "::1" ];
    use_x_forwarded_for = true;
  };

  services.nginx = {
    recommendedProxySettings = true;
    virtualHosts."home.example.com" = {
      forceSSL = true;
      enableACME = true;
      extraConfig = ''
        proxy_buffering off;
      '';
      locations."/" = {
        proxyPass = "http://[::1]:8123";
        proxyWebsockets = true;
      };
    };
  };

Using PostgreSQL

Home Assistant supports PostgreSQL as a database backend for, among other things, its logger and history components. It's a lot more scalable and typically provides faster response times than the SQLite database, that is used by default.

Remember to make backups of your database, for Home Assistant is becoming more and more stateful and has moved away from a completely declarative YAML configuration for new and core components.

Also note that when overridding the package you may want to disable install checks as they tend to take a long time to complete.

  services.home-assistant = {
    package = (pkgs.home-assistant.override {
      extraPackages = py: with py; [ psycopg2 ];
    }).overrideAttrs (oldAttrs: {
      doInstallCheck = false;
    });
    config.recorder.db_url = "postgresql://@/hass";
  };

  services.postgresql = {
    enable = true;
    ensureDatabases = [ "hass" ];
    ensureUsers = [{
      name = "hass";
      ensurePermissions = {
        "DATABASE hass" = "ALL PRIVILEGES";
      };
    }];
  };

Add custom lovelace modules

There are many useful and pretty lovelace components out there that you might want to integrate into your dashboards. Some of them are packaged up inside NUR repositories.

Usually you would install these into /var/lib/hass/www, but that comes with issues on NixOS, as their internal webserver does not follow symlinks. You could then think about exposing that directory over your webserver, but you'll notice that your webserver user has no permissions to enter the home assistant users state directory, which is due to proper hardening on the home-assistant.service.

let
  # https://nur.nix-community.org/repos/mweinelt/
  nur = import (builtins.fetchTarball "https://github.com/mweinelt/nur-packages/archive/master.tar.gz") {};

  mkLovelaceModule = name: {
    # https://www.home-assistant.io/lovelace/dashboards-and-views/#resources
    url = "/local/${name}.js?${nur.hassLovelaceModules."${name}".version}";
    type = "module";
  };
in {
  # Install lovelace components into temporary directory that can be
  # served by nginx.
  systemd.tmpfiles.rules = [
    "d /run/hass 0700 nginx nginx"
    "L+ /run/hass/mini-graph-card.js - - - - ${nur.hassLovelaceModules.mini-graph-card}/mini-graph-card-bundle.js"
    "L+ /run/hass/mini-media-player.js - - - - ${nur.hassLovelaceModules.mini-media-player}/mini-media-player-bundle.js"
    "L+ /run/hass/multiple-entity-row.js - - - - ${nur.hassLovelaceModules.multiple-entity-row}/multiple-entity-row.js"
  ];

  # Instruct home-assistant to load these resources in the lovelace frontend
  services.home-assistant.config.lovelace = {
    resources = [
      (mkLovelaceModule "mini-graph-card") # https://github.com/kalkih/mini-graph-card
      (mkLovelaceModule "mini-media-player") # https://github.com/kalkih/mini-media-player
      (mkLovelaceModule "multiple-entity-row") # https://github.com/benct/lovelace-multiple-entity-row
    ];
  };

  services.nginx.virtualHosts."home.example.com" = {
    locations."/local/" = {
      alias = "/run/hass/";
    };
  };
}

Add custom components

In order to install a custom component, you have to place it in /var/lib/hass/custom_components. This can be achieved using systemd tmpfiles like so (for sonoff custom component):

  systemd.tmpfiles.rules = [
    "C /var/lib/hass/custom_components/sonoff - - - - ${sources.sonoff-lan}/custom_components/sonoff"
    "Z /var/lib/hass/custom_components 770 hass hass - -"
  ];

Combine declarative and UI defined automations

You can also declaratively define your automations while still being able to define them in Home Assistant UI. Automations defined in UI are stored in /var/lib/hass/automations.yaml. If you are not planning on using UI defined automations, then you can define them under services.home-assistant.config.automation, otherwise split them into services.home-assistant.config."automation manual" and services.home-assistant.config."automation ui", like so:

  services.home-assistant.config =
  {
    "automation manual" = [
      {
        alias = "living room plug off";
        trigger = {
          platform = "time";
          at = "22:00";
        };
        action = {
          type = "turn_off";
          device_id = "someID"; #Inspect yaml of automation created in UI
          entity_id = "switch.living_room_plug";
          domain = "switch";
        };
      }
    "automation ui" = "!include automations.yaml";
 }

Combine declarative and UI defined scenes

Scenes are configured the same way automations(described above) are.

services.home-assistant.config."scene manual" = []
services.home-assistant.config."scene ui" = "!include scenes.yaml";

Example configurations

- Mic92's config

Misc

Run Home Assistant from GitHub repository

When developing Home Assistant for some test dependencies additional libraries are needed. A nix-shell expression for this is available here.