How to create template sensor from binary sensor?

My goals is to measure gas usage. I don’t have a smart P1 meter, but I do have an OTGW device which provides binary sensors for flame, heating and hot water. I would like to use these as an indication for my gas usage, even though they don’t give exact measurements.

I tried this template sensor.

  - name:                   "tmpl_otgw_flame"
    unique_id:              "tmpl_otgw_flame"
    device_class:           gas
    unit_of_measurement:    m³
    state_class:            total_increasing
    state:                  "{{ states('binary_sensor.otgw_flame') | multiply(1.0) }}"

An then I want to use this in a utility meter:

utility_meter:
  util_otgw_flame:
    source: sensor.tmpl_otgw_flame

Home Assistant gives no errors, but the template sensors stay in the ‘unavailable’ state.
And the utility meters stay zero.
What is wrong?

Have you tested your template in developer tools?

No, I hadn’t. Good advice though. I should start using that.

Anyway. I gives this error:

ValueError: Template error: multiply got invalid input 'on' when rendering template '{{ states('binary_sensor.otgw_flame') | multiply(1.0) }}

Makes sense. The values of the binary sensor are ‘on’ or ‘off’ instead of 0 or 1.
How could I get this right? maybe some kind of if/else structure?

You can’t multiply a binary_sensor — you’re asking HA to do 'off' × 1.0. Try:

    state: "{{ 1 if is_state('binary_sensor.otgw_flame', 'on') else 0 }}"
2 Likes