Template sensor not working - works in HA web UI

Not really sure what’s going on. I have this template sensor:

3d_printer_power:
  friendly_name: '3D Printer Power'
  value_template: '{{ states.switch["3d_printer"].attributes.power_consumption | float }}'
  unit_of_measurement: 'W'

Based on this switch:

Which gives this:

image

However, using said template in the web UI works as expected:

What am I missing here?

Home Assistant inspects the template sensor’s value_template and attempts to identify the entities it should monitor. When any one of those identified entities changes its state, Home Assistant evaluates the template sensor’s value_template.

If it fails to identify any entities, it will evaluate the value_template only once, at startup. No further evaluation of the template sensor will occur until the next restart.

It may be possible that Home Assistant is unable to determine that it must monitor switch.3d_printer. I suggest you try the following variation:

3d_printer_power:
  friendly_name: '3D Printer Power'
  value_template: "{{ state_attr('switch.3d_printer', 'power_consumption') | float }}"
  unit_of_measurement: 'W'

If it still fails to work, then explicitly indicate the entity to be monitored:

3d_printer_power:
  friendly_name: '3D Printer Power'
  entity_id: switch.3d_printer
  value_template: "{{ state_attr('switch.3d_printer', 'power_consumption') | float }}"
  unit_of_measurement: 'W'
1 Like

Your first suggestion worked, thanks!

I’m not 100% clear though why my code didn’t, especially since it evaluated in the web UI. You mentioned that it’s only evaluated once during startup but even with a value in that attribute I still got an unknown which mean it wasn’t actually read. There was a value in that attribute during startup so I don’t know what I got the unknown.

I get the fact that it may not update, I’m just curious why it never gave anything.

Thanks again!