krikey
(krikey)
April 17, 2024, 2:48pm
1
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?
123
(Taras)
April 17, 2024, 2:58pm
2
The template is invalid.
It nests a template within a template.
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?
krikey
(krikey)
April 17, 2024, 5:32pm
3
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.
krikey
(krikey)
April 17, 2024, 5:35pm
4
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)) }}
123
(Taras)
April 17, 2024, 6:15pm
5
For future reference, don’t post Jinja2 templates containing pseudo code that looks exactly like Jinja2.
1 Like