Custom component to declare/set variables

@rogro82, since 0.62.0 i’m getting errors:

2018-01-27 09:16:20 ERROR (MainThread) [homeassistant.core] Error executing service <ServiceCall variable.set_variable: value_template=<homeassistant.helpers.template.Template object at 0x7fe70c6d6b38>, variable=wz_couch_timer>
Traceback (most recent call last):
  File "/srv/homeassi/lib/python3.5/site-packages/homeassistant/", line 1010, in _event_to_service_call
    yield from service_handler.func(service_call)
  File "/home/homeassi/.homeassistant/custom_components/", line 88, in async_set_variable_service
    entity = component.entities[entity_id]
TypeError: 'itertools.chain' object is not subscriptable

I think it depends on a Breaking Change in 0.62.0

Custom component devs only: EntityComponent.add_entity(entity) and EntityComponent.async_add_entity(entity) have been removed. Use EntityComponent.add_entities([entity]) and EntityComponent.async_add_entities([entity]) instead. (@balloob - #11691) (breaking change)

This has indeed be impacted. Update line 88:


entity = component.entities[entity_id]


entity = component.get_entity(entity_id)

Yeah! Works again!
Thanks for the fast fix.


Updated the git repo

Hi @rogro82,

I’ve finally got round to playing with your great custom component :slight_smile:

I’m on Win 10 - HA 62.0, latest github repo and I get the following error for my motion detector variable…

e[31m2018-02-07 03:21:16 ERROR (MainThread) [homeassistant.core] Error doing job: Task exception was never retrievede[0m
Traceback (most recent call last):
  File "C:\Users\MyPc\AppData\Local\Programs\Python\Python36\lib\asyncio\", line 180, in _step
    result = coro.send(None)
  File "C:\Users\MyPc\AppData\Roaming\.homeassistant\custom_components\", line 180, in async_set_variable
    attributes = json.loads(attributes_template.async_render({ 'variable': current_state }))
  File "C:\Users\MyPc\AppData\Local\Programs\Python\Python36\lib\json\", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Users\MyPc\AppData\Local\Programs\Python\Python36\lib\json\", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\MyPc\AppData\Local\Programs\Python\Python36\lib\json\", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 5 column 3 (char 67)e[0m  

Basically I’m using the motion code from …

Hi @rogro82 - I solved most all my issues I was having getting event states and history working. Thread is here: Trying to configure motion history

Only thing that’s not working at the moment is the graph.


What would be some things to look at to get the graph working?

Edit: Problem solved and it solved for all of my graph issues throughout.

I was seeing sql errors like below in the homeassistant logs:
sqlite3.DatabaseError: database disk image is malformed

They included messages about recorder and other things. My Logbook and History has not been working either.

After searching, it appears that this is caused by a corrupt home-assistant_v2.db file. The recomendation was to delete it and let HASS recreate one.

Since doing so, ALL graphs work - including state history and my Logbook and History are working as well!

Thank you.

I did something like this a while ago, I call it input_label - it is basically a placeholder, you can put anything you want in it and use it as a variable.

Below link is where I use the input_label component… It significantly simplified the overall code.

… need help :frowning:
I’m working with a state machine but it dosn’t run… The goal is to increment light_color ad every click from 0 to 8 and rollover so I can use a different color ad every touch v.0.63.3 on RPI3
this is part of my configuration.yaml


value: 0
restore: true

in automation section

  • alias: Toggle dining lamps
    platform: event
    event_type: click
    entity_id: binary_sensor.switch_158d0001bd1d6e
    click_type: single
    • service: light.toggle
      entity_id: light.Dining_Room_right
      transition: 3
    • service: light.toggle
      entity_id: light.Dining_Room
      transition: 3
    • service: variable.set_variable
      variable: light_color
      value_template: >
      {% if variable.state == 8 %}
      ‘{{ variable.state = 0 }}’
      {% else %}
      ‘{{ (variable.state | int) + 1 }}’
      {% endif %}
    • service: persistent_notification.create
      message: “{{ now().strftime(’%Y-%m-%d %H:%M’) }} stato {{ states.variable.light_color.state }}”
      title: “Custom subject”

tnks for helping

This is great! If i want to store sensor values, do i have to create an automation for every sensor i want stored? And I noticed that the icon does not restore to the last icon. it goes back to the icon from the original variable file.

This custom component looks useful but I can’t see the difference with a template sensor. Can anyone explain that?

I have weather forecast tts on chromecast in the morning. And also i sometimes stream web radio over that same chromecast. So i use this component to save current web radio state (off or some station) before weather forecast kicks in. After forecast ends if web radio was streaming before i restore to saved radio station.

Hi, a little off topic I’m afraid but how do you setup that tts stream to the Chromecast?

Weather forecast or web radio?

Weather forecast :slight_smile:

Like this :smiley:

- service: tts.google_say
    entity_id: media_player.chromecastaudio0667
    message: "Right now it's {{states.sensor.dark_sky_summary.state}}. Current temperature is {{states.sensor.dark_sky_temperature.state | round(0)}}. Feels like {{states.sensor.dark_sky_apparent_temperature.state | round()}}. Today will be {{ states.sensor.dark_sky_hourly_summary.state }} With minimum temperature of {{states.sensor.dark_sky_daily_low_temperature.state | round(0)}} and maximum temperature  {{states.sensor.dark_sky_daily_high_temperature.state | round(0)}}. {{ ['Have a nice day.', 'Godspeed.', 'May the force be with you.', 'Live long and prosper.', 'Today is going to be a great day! I can feel it!.', 'See you later, alligator.', 'See you soon.'] | random}}"

I previously had your component working great, but then I borked my system and had to reinstall a backup, now I am getting the following:

2018-03-16 07:16:26 ERROR (MainThread) [homeassistant.loader] Error loading custom_components.variable. Make sure all dependencies are installed
Traceback (most recent call last):
File “/usr/local/lib/python3.4/dist-packages/homeassistant/”, line 141, in get_component
module = importlib.import_module(path)
File “/usr/lib/python3.4/importlib/”, line 109, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File “”, line 2254, in _gcd_import
File “”, line 2237, in _find_and_load
File “”, line 2226, in _find_and_load_unlocked
File “”, line 1200, in _load_unlocked
File “”, line 1129, in _exec
File “”, line 1471, in exec_module
File “”, line 321, in _call_with_frames_removed
File “/home/pi/.homeassistant/custom_components/”, line 11, in
from homeassistant.loader import bind_hass
ImportError: cannot import name ‘bind_hass’

Any idea as to what dependencies I am missing that would be causing this error?

@rogro82: Your custom component looks very useful but I can’t see the difference with a template sensor. Can you please explain that to me?

For the first time since using variables, the values aren’t restoring for me after a reboot today.

The only change I made was to add a fourth variable to my configuration.yaml, which was this one:

    value: 0
      friendly_name: 'Times Camera Two Zone 4 Triggered'
      icon: mdi:cctv
    restore: true

The variables work as perfectly as ever. I’ve done several reboots over the last few days with no issue, but today the values aren’t surviving a reboot or a restart.

Here’s my grafana stats for two of them showing no problems after many issue-free restarts & reboots. I reset the values at midnight.

I’m on the latest version of the code, and on Hass 0.66.1

Anyone else seeing this?

Hello everyone,

I try to use variables, without sucess. i’m using hassbian. And what I want is:
-Write a value from another component, (sensor, counter, etc…) in a variable.
-Create an automation to do the write with a trigger. Without scripts.
-Restart homeautomation or the raspberry pi without loosing the values.

Until now I could only do that with input_number, and in slider type, in box type the value ins’t stored.

The idea is:
-The automation is trigger by a MQTT topic change.
-The condition is that the current time is bigger, by 2 seconds, that the oldTime (a variable).
-the action is:
-Increment total_gas (a variable) by 0.01
-Set oldTime with current time.

I have already this automation working with input_number, but I would like to chang’t to variable.
Could someone help.

Thank you best regards



This is my first post. I have write a little example.

  • alias: test_tempe_interior
    • platform: template
      value_template: "{%- if states(‘sensor.mijia_bt_hygrothermograph_temperature’) != ‘unavailable’ -%}$

    • service: variable.set_variable
      variable: estado_tempe

      value_template: ‘{{ [((states.sensor.mijia_bt_hygrothermograph_temperature.state))] }}’

Thank you for time and work.