Cannot create a new template sensor for my net electricity price

Hi,

I’m struggling to create a new template sensor to get the net cost to date of my electricity using the Octopus API. I’ve attached a copy of the code added to the configuration.yaml file with the unique IDs removed.

template:

  • sensor:
    • name: “Net Electricity Usage”
      unit_of_measurement: ‘GBP’
      state: >
      {{states(‘sensor.electricity_{{ID}}current_accumulative_cost’) | float - states('sensor.octopus_energy_electricity{{ID}}_current_standing_charge’) | float}}

When adding this to a dashboard after restarting HAOS it simply displays “Unavailable” as the value.

I have other sensors defined in the template: section which seem to be working ok. Why isn’t this one?

The template is invalid.

  1. It nests a template within a template.

  2. It references an undefined variable named ID.

The following fixes the invalid use of nested templates.

state: >
  {{ states('sensor.electricity_' ~ ID ~ 'current_accumulative_cost') | float(0) - 
    states('sensor.octopus_energy_electricity' ~ ID ~ '_current_standing_charge') | float(0) }}

However, it doesn’t fix the undefined variable named ID. What is this variable? Is your posted example just a fragment of the actual Template Sensor configuration?

I realised that I was using an incorrect sensor name and so the subtraction could not happen. Here’s a working version of the code:

template:
  - sensor:
     - name: "net electricity cost"
       unit_of_measurement: 'GBP'  # Assuming the cost is in GBP, adjust as necessary
      state: >
          {{ (states('sensor.octopus_energy_electricity_{{ID}}_current_accumulative_cost') | float(default=0)) - (states('sensor.octopus_energy_electricity_{{ID}}_current_standing_charge') | float(default=0)) }}

where {{ID}} is my unique reference for my supply.

perhaps I shouldn’t use {{ID}} to denote that this is a value I don’t wish to share, so for completeness below is a revised copy

template:
  - sensor:
    - name: "net electricity cost"
      unit_of_measurement: 'GBP'  # Assuming the cost is in GBP, adjust as necessary
      state: >
          {{ (states('sensor.octopus_energy_electricity_UNIQUEID_current_accumulative_cost') | float(default=0)) - (states('sensor.octopus_energy_electricity_UNIQUEID_current_standing_charge') | float(default=0)) }}

For future reference, don’t post Jinja2 templates containing pseudo code that looks exactly like Jinja2.

1 Like