Updating Template Sensor

I’ve created a pulse sensor with a total, and created a second template sensor that is also going to act as a total - the difference between the two is that they show different values as have different calculations applied to them. So this is in the pulse sensor declaration.

        - sensor.template.publish: 
            id: gas_glow_total_gas_kwh
            state: !lambda 'return id(gas_glow_total_gas_kwh).state+=1;'

And I’m expecting it to update my template sensor:

  - platform: template
    id: gas_glow_total_gas_kwh
    name: '${friendly_name} - Total Gas Used kWh'

But it just returns unknown. In my ‘on_value’ automation every time there is a new pulse, i’m expecting it to get the current state of my template sensor, add one to the value, then return that new nunber to be the new state of that sensor. What part am I getting wrong?

1 Like

I’m trying to do something similar, without success.

I think that sensor.template.publish is only for publishing to binary_sensor, not sensor.

Did you find a solution?

I have found a solution that works for me.

Here’s is the relevant the yaml, in case it helps.

You’ll need a global, a global.set and a template sensor.

  - id: water_used_this_week_global
    type: float
    restore_value: no
    initial_value: '0'

  - globals.set:
    id: water_used_this_week_global
    value: !lambda 'return id(water_used_last_hour).state + id(water_used_this_week_global);'  

  - name: "Water used this week" # From gloabl variable. To HA
    id: water_used_this_week
    platform: template
    unit_of_measurement: "litres"
    accuracy_decimals: 0
    lambda: 'return id(water_used_this_week_global);'

Im not sure I ‘solved’ it but looking at my yaml now I can definitely publish to a regular sensor (rather than binary)

- sensor.template.publish: 
            id: gas_glow_total_gas_kwh
            state: !lambda 'return ((id(pulse_counter)/1000) * 1.02264 * 40) / 3.6;'

I think basically what I was trying to do - publish a sensor state based on a modification to that sensor - isn’t something you can (or could) do so just found a different approach.