If you have many smart plugs and are tired of defining energy usage sensors (kWh) from power sensors (W), this article is for you.

This is just one solution that works for me. I hope this helps someone else too.

Prerequisite: pyscript

pyscript allows you to write python scripts for Home Assistant. For example, we can write actions (previously “services”) in python rather than with UI or yaml, and pyscript can do much more. This is very powerful in many situations.

In this article, we use pyscript to auto-generate energy usage sensors.

Install pyscript, and enable allow_all_imports option. This is required to import os package to write yaml files to disk. See this section of the pyscript doc to learn more about import limitations and reasons.

Prerequisite: Home Assistant Packages setup

I think it’s best to organize generated yaml files using Packages. This article assumes you configure packages as follows:

homeassistant:
  packages: !include_dir_merge_named packages/

If you have different setup, please adjust the script below to produce the appropriate yaml format. For example, if you use !include_dir_named instead of !include_dir_merge_named, you need to remove the package name (the first line saying energy_monitoring: in this case) and reduce one indent level.

The script

Place the following script to your pyscript directory under Home Assistant configuration directory:

import os


@time_trigger('shutdown')
@service
def generate_energy_monitoring_yaml():
    """Generate yaml file containing energy monitoring sensors and things"""
    ind = "  "
    # NOTE: you might not need package name ("energy_monitoring") depending on your HASS configuration
    yaml_content = f"energy_monitoring:\n{ind}sensor:\n"
    for s in state.names():
        if not is_watt_sensor(s):
            continue
        sensor_content = f"""
- platform: integration
  source: {s}
  name: {s}_energy_spent
  unit_prefix: k
  round: 2
  max_sub_interval:
    minutes: 5
"""
        lines = sensor_content.splitlines()
        for l in lines:
            yaml_content += f"{ind*2}{l}\n"

    # NOTE: update to the right destination path for your setup
    dest_dir = "/config/packages/autogenerated"
    os.makedirs(dest_dir, exist_ok=True)
    fd = os.open(f"{dest_dir}/energy_monitoring.yaml", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644)
    os.write(fd, yaml_content.encode())
    os.close(fd)


def is_watt_sensor(entity_id: str):
    attr = state.getattr(entity_id)
    if attr is None:
        return False
    if 'device_class' not in attr or attr['device_class'] != 'power':
        return False
    if 'unit_of_measurement' not in attr or attr['unit_of_measurement'] != 'W':
        return False
    return True

I hope the script is self-explanatory. It goes over all states, find entities having device_class of “power” and unit_of_measurement of “W”, then define the corresponding energy usage sensors in the auto-generated yaml file.

The generate_energy_monitoring_yaml function is annotated with @time_trigger('shutdown'), so pyscript will execute this function on HASS shutdown. Also it has @service which registers the function as an action/service to HASS, so you can invoke the action to generate yaml file at will.

Now, call the pyscript.generate_energy_monitoring_yaml from HASS Developer tools or simply restart Home Assistant. Check if the expected energy usage sensors appear. If not, check Settings > System > Logs to see if pyscript is encountering errors. It’s also a good idea to check the generated yaml content using SSH addon of your choice (for example Advanced SSH & Web Terminal).

Once the expected energy usage sensors show up, the next step is to setup the Energy dashboard. See Understanding Home Energy Management and add the energy usage sensors as individual devices, then enjoy your nicely visualized energy usage! :)