Home Assistant

Useful Snippets for HomeAssistant.

Sum Sensor Values

Below is the most concise way I have come up with to sum a bunch of sensor values in a template sensor. It allows for easy updates and minimal chance of error.

To use it, create a group with the sensors you want to sum. Then if you want change float to int if you don’t want float values.

  group:
    sum_entities:
      entities:
        - sensor.sum_one
        - sensor.sum_two
        - sensor.sum_three
  sensor:
    - platform: template
        sensors:
          my_summing_sensor:
            friendly_name: "Sum Entities"
            entity_id:
              - sensor.sensors_to_trigger_updates
            value_template: >-
              {{ expand('sum_entities') | map(attribute='state') | map('float') | sum }}

Count how many people at home

Use this to determine how many people are at home.

  {{ dict((states.person) | groupby('state'))['home'] | count }}

Setup rtl_433 for use with HomeAssistant

Setting up a rtl_433 is useful if you have a bunch of 433MHz sensors and want to communicate with HomeAssistant

Install rtl_433

There are many tutorials on how to install rtl_433 on various distributions but with a RaspberryPi its a simple as the following

sudo apt-get install libtool libusb-1.0-0-dev librtlsdr-dev rtl-sdr build-essential autoconf cmake pkg-config
git clone https://github.com/merbanan/rtl_433
cd rtl_433
mkdir build
cd build
cmake ..
make
sudo make install

Test if it worked by typing sudo rtl_433

Setup Communication with HomeAssistant

Once you have it working, the cleanest way I found to have it communicate with HomeAssistant is via MQTT.

Test using the script below, and be share to ammend the BROKER_IP_ADDRESS, USERNAME and PASSWORD fields to match your MQTT setup.

rtl_433 -q -F 'mqtt://BROKER_IP_ADDRESS:1883,user=USERNAME,pass=PASSWORD,retain=1,events=HomeAssistant/rtlsdr/event[/id],states=HomeAssistant/rtlsdr/state[/id]' -M newmodel

Then Subscribe to the topic in HomeAssistant to check whether its working.

Setup rtl_433 to run as a systemd service

If you want to setup rtl_433 to run on system startup, set it as a systemd service

Create a new service file with nano rtl433.service then add

[Unit]
Description=RTL433 Sensor
After=network.target
[Service]
ExecStart=/usr/local/bin/rtl_433 -q -F 'mqtt://BROKER_IP_ADDRESS:1883,user=USERNAME,pass=PASSWORD,retain=1,events=HomeAssistant/rtlsdr/event[/id],states=HomeAssistant/rtlsdr/state[/id]' -M newmodel
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target

Copy the unit file to /etc/systemd/system and give it permissions:

sudo cp myservice.service /etc/systemd/system/rtl433.service
sudo chmod 644 /etc/systemd/system/rtl433.service

Once you have a unit file, you are ready to test the service:

sudo systemctl start rtl433

Check the status of the service:

sudo systemctl status rtl433

If everything is working OK and you dont see any errors, enable the service.

sudo systemctl enable rtl433