Add Sensor to Template.yaml

Hi,
I am trying to move a sensor from my sensors.yaml to the template.yaml.
There was already one sensor in the template.yaml, which was working fine.
After adding the second sensor, the first one does not work anymore.
Sorry, I am always struggling with Yaml.

Where did I go wrong?

- sensor:
    - name: "pv power numeric"
      state: "{{ states('sensor.inverter_instant_power') | float(0) }}"
      unit_of_measurement: "kWh"
      
    - name: "gasmeter"
      state: '{{ states("sensor.gas_delivered_raw") | regex_findall_index("\((\d*\.?\d*)\)$") }}'
      friendly_name: gasmeter
      unit_of_measurement: "m³"
      icon_template: mdi:fire
      device_class: gas

No friendly_name on modern format template sensors, and it’s icon not icon_template. There should be errors in the logs for this.

You can create these sensors in the UI, under Helpers. No YAML problems there…

Also, your first sensor is pointless — it’s just a copy of sensor.inverter_instant_power. States are always strings, so running it through float here does nothing.

Hi Troon,
Thanks for your help, that fixed my problem indeed.
About the first sensor, it reads my solar inverter. The inverter sleeps at night, that gave me an error on my dashboard. With this sensor, now the value is 0 at night. Or am I incorrect?

Could you help me out one more time?

I would like to add this to my template

sensor:
  - platform: template
    sensors:
      thermostat1_temperature:
        entity_id: climate.thermostat1
        value_template: "{{ state_attr('climate.thermostat1', 'temperature') }}"
        friendly_name: "Thermostat1 Temperature"

I found the example in the forum, but I am not sure how to correctly use it in the new template.

1 Like

Ah yes, your inverter “copy” does make sense then.

Rather than fiddling with YAML, use the UI to create a template sensor: look for Helpers.

Use a state template of

{{ state_attr('climate.thermostat1', 'temperature') }}

The UI is now very good for template sensors, provided you don’t need to set any attributes.

Just an addition:
If you want a friendly name, you can do it like this:

    - unique_id: "gasmeter_unique_id"
      state: '{{ states("sensor.gas_delivered_raw") | regex_findall_index("\((\d*\.?\d*)\)$") }}'
      attributes:
        friendly_name: gasmeter
      unit_of_measurement: "m³"
      icon: mdi:fire
      device_class: gas

(I think i remember this only works if you done have name:, so if you do it that way, you have to search the sensor in the developer tools and rename it.)