# ¶ Adding custom sensors to Home Assistant

Sometimes you need custom sensors for bespoke automations or uncommon devices. These need to be added manually to a file on the persistent storage, so it survives reboots and updates of the COFY-box.

# ¶ Adding a custom sensor

In this demo we will add a statistics sensor averaging the total power consumption over a 5-minute interval, useful for controlling immersion heaters.

## ¶ 1. Finding the sensor IDs

You first need to find the entity IDs of the sensors/states which you want to forward (these will be our 'ingredients'). There are several ways to find these.

1. Go to `Settings`> `Devices and services`> `Devices`. Open the device and click on the sensor. A pop-up should appear displaying the entity ID, e.g. `sensor.utility_meter_total_active_power`.
2. Alternatively, go to `Developer tools`> `States`. Locate the required entity ID(s) in this list.

## ¶ 2. Adding the custom sensor

1. Go to the device through the balena cloud. Open a terminal to the `homeassistant` service.
2. Type in `cd /config/.storage/user` and enter. Next, type in `vi sensor.yaml`and enter. A vi editor opens.

> The file might be empty, in which case you can proceed to the next step. If not, you need to use your keyboard arrow keys to navigate the cursor to the very last character. You can also type in `G` followed by `$`, e.g. if it is a very long file.

3. In the vi editor, press the `i` key on your keyboard. In the bottom left corner, you will see an `I` appearing, meaning the vi editor is in `insert` mode.

> If your cursor is still highlighting the last character of previously existing text, press the right arrow on your keyboard and enter to add a new line.

4. You can now add your custom sensor. E.g. in this demo we want to add the following statistics sensor:

      - platform: statistics
        name: "5min active power"
        unique_id: sensor.utility_meter_mean_power
        entity_id: sensor.utility_meter_total_active_power
        state_characteristic: mean
        max_age:
          minutes: 5

Copy the above code for the custom sensor. Right-click in the vi editor and select `Paste`. This copies the content from the source file into the editor.
5. Press the `Esc` key on your keyboard a few times. Now type `:w` and press Enter. Next, type `:q` and enter. This saves (writes) and closes (quits) the file.

> If you have made a mistake, pressing `Esc` a few times followed by `:q!` quits the file without saving.

6. In Home Assistant, navigate to `Developer Tools`. In the tab `YAML`, click on `Check configuration`. This should yield the message `Configuration will not prevent Home Assistant from starting!`. If you have made a mistake in the sensor definition, this will show you where the mistake is.
7. If the configuration is valid, press `Restart`, confirm, and wait until Home Assistant is fully started again. The custom sensor will then be available (you can check in `Developer tools`> `States`).