Using hass_variable

I have been trying to use hass_variable to save start and end energy values for my dishwasher so that I can calculate costs of cycles within an automation. .

So far, I have yet to populate a variable successfully

One of these variables is:

dishwasher_start_energy:
  value: 0
  attributes:
      icon: mdi:power-on

I am testing with a script with the following code in an action:

service: variable.set_variable
data:
  variable: dishwasher_start_energy
  value_template: '{{ states(''sensor.kitchen_kettle_plug_localbytes_5_energy_today'') | float}}'

The value of the sensor.kitchen_kettle_plug_localbytes_5_energy_today is 0.076 (kwh)

I ran it and the trace resulted in the following:

Executed: 4 September 2022, 12:38:42
Result:
params:
  domain: variable
  service: set_variable
  service_data:
    variable: dishwasher_start_energy
    value_template: 0.076
  target: {}
running_script: false
limit: 10

So it does seem to have recognised the 0.076 value but the dishwasher_start_energy variable remains at the value 0.

I have tried the statement without the “float” and also using “value” instead of “value_template” but the result is the same i.e.no update to the value. I am struggling and need help.

Update: I have found the following error in the log:

wait() got an unexpected keyword argument 'loop'

I guess that is a python type error but no idea what to do.

@stain3565
In looking at your code I see a couple things that need fixed.

dishwasher_start_energy:
  value: 0
  attributes:
      icon: mdi:power-on
  1. Here, the 4th line is indented by 2 extra spaces. This may not cause your script to fail, but YAML is VERY particular about indentation, so pay close attention to this.
value_template: '{{ states(''sensor.kitchen_kettle_plug_localbytes_5_energy_today'') | float}}'
  1. Here the ‘double single quotes’ is again, just bad form. Try this instead:
value_template: "{{ states('sensor.kitchen_kettle_plug_localbytes_5_energy_today') | float}}"

or this:

value_template: >-
  {{ states('sensor.kitchen_kettle_plug_localbytes_5_energy_today') | float}}

The second way does not require the outermost quotes and can clean up readability.

3 And finally, the correct syntax to set a variable is:

  - service: variable.set_variable
    data:
      variable: v_ha_db_size
      value: "{{ states('sensor.home_assistant_v2_db_size')|float(default=0) }}"

value_template: is not the correct way to set a variable.
use value: instead

Hope this helps.

Thanks.

Admittedly, i had just abandoned this variable method and had used the input_number type instead. Althoigh not complete yet (ie final cost formula yet to set up using the wh rather than kwh value, so i am dealing in integers, and my tarriff - will hunt around to see if it is anything more than a multiplication), the integer values for the number of wh used seems correct so think i will stick wth this.