Custom component to declare/set variables

It seems that after upgrading HA to 0.84.2 (and applying the latest hass-variables fix), variables with "restore": true don’t preserve their state after HA restart anymore. I have opened a new bug: https://github.com/rogro82/hass-variables/issues/11.

Hi i just upgraded to 0.84.2 and updated the variable.py. Still getting errors.

2018-12-16 11:58:36 ERROR (MainThread) [homeassistant.loader] Error loading custom_components.variable. Make sure all dependencies are installed

Traceback (most recent call last):

File "/usr/src/app/homeassistant/loader.py", line 92, in get_component

module = importlib.import_module(path)

File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module

return _bootstrap._gcd_import(name[level:], package, level)

File "<frozen importlib._bootstrap>", line 994, in _gcd_import

File "<frozen importlib._bootstrap>", line 971, in _find_and_load

File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked

File "<frozen importlib._bootstrap>", line 665, in _load_unlocked

File "<frozen importlib._bootstrap_external>", line 678, in exec_module

File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed

File "/config/custom_components/variable.py", line 14, in <module>

from homeassistant.helpers.restore_state import async_get_last_state

ImportError: cannot import name 'async_get_last_state'

2018-12-16 11:58:36 ERROR (MainThread) [homeassistant.loader] Unable to find component variable

Any help please…

I have the same problem. Hope having a solution soon

Have a look here

1 Like

Are you sure you updated to the latest variable.py correctly because your log shows an import from the previous version:

File "/config/custom_components/variable.py", line 14, in <module>
from homeassistant.helpers.restore_state import async_get_last_state
ImportError: cannot import name 'async_get_last_state'

Line 14 should be:

Thank you

Hi there, when I tried to install the custom component HA complains on startup:

2018-12-20 15:43:36 ERROR (MainThread) [homeassistant.loader] Error loading custom_components.variable. Make sure all dependencies are installed
Traceback (most recent call last):
File “/home/homeassistant/.pyenv/versions/3.6.3/envs/homeassistant-3.6.3/lib/python3.6/site-packages/homeassistant/loader.py”, line 92, in get_component
module = importlib.import_module(path)
File “/home/homeassistant/.pyenv/versions/3.6.3/lib/python3.6/importlib/init.py”, line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File “”, line 994, in _gcd_import
File “”, line 971, in _find_and_load
File “”, line 955, in _find_and_load_unlocked
File “”, line 665, in _load_unlocked
File “”, line 678, in exec_module
File “”, line 219, in _call_with_frames_removed
File “/home/homeassistant/.homeassistant/custom_components/variable.py”, line 14, in
from homeassistant.helpers.restore_state import RestoreEntity
ImportError: cannot import name ‘RestoreEntity’

Do I need to install the dependency?

You need to run 0.84.x for the latest version of this component.

Ah thanks… that solved my problem! :wink:

Just pushed an update to github which should fix this issue.

HI @rogro82

would you care to make this card ‘trackable’ by the custom_component updater card please? https://github.com/custom-cards/tracker-card

would make updating you CC so much more comfortable .

thanks for considering

2 Likes

could it be that the restore state functionality of the Variable component is somehow compromised lately?

On each restart my variables lose their history, while I have enabled restore:

variable:
  solar_angle_outside_light:
    value: 'Not set'
    restore: true
    attributes:
      icon: mdi:format-rotate-90
      name: 'Solar angle'

  virtual_light_outside_light:
    value: 'Not set'
    restore: true
    attributes:
      icon: mdi:brightness-5
      name: 'Virtual light'

I did move from the default recorder to MariaDB lately but still have variable included in the domains in recorder,yaml. HA 84.3

Do you use the latest version of hass-variables? This issue has been fixed already - see https://github.com/rogro82/hass-variables/issues/11 .

yes I have dl’d that version, and think (…) it worked al right.
Unfortunately this component hasn’t got a version number in the file, and can’t be tracked by the updater card, but I’ve secured it manually

Is there a way to pass multiple values to this? For example, if I wanted to use the attributes (I use the motion example, works fine and I understand it’s “rolling” the values forward, so to speak) to hold device_tracker information? I’m not really clear on how I can do this with attribute template with perhaps value template? IE:

        attributes_template: >
            {
              "latitude": "{{ ??? }}",
              "longitude": "{{ ??? }}"
            }

Not sure how to populate this using states.attributes.device_tracker.attributes.latitude/longitude (for example.)

EDIT: Solved it. Now to make it more template-ish as I do passing entity-id to the python script.

  chris_gps:
    value: 'Unknown'
    restore: false
    attributes:
      latitude: 0
      longitude: 0
  trigger:
    - platform: state
      entity_id: device_tracker.homeassistant_chris
  action:
    - service: python_script.calc_gps_coords
      data_template:
        entity_id: '{{ trigger.entity_id }}'
        zone_entity: 'None'
        zone_data: 'None'
    - service: variable.set_variable
      data:
        variable: chris_gps
        attributes_template: >
            {
              "latitude": "{{ states.device_tracker.homeassistant_chris.attributes.latitude }}",
              "longitude": "{{ states.device_tracker.homeassistant_chris.attributes.longitude }}"
            }
1 Like

@rogro82 is it possible to manipulate variables from python script? I keep running into a roadblock (which I’ve googled around) that at first was due to using direct assignment, ie:

foo = foo # object does not support item or slice assignment
foo += foo

Which I thought I solved but now I’m running into an issue trying to use hass.states.set() which produces this error:

Line 72: Augmented assignment of object items and slices is not allowed.

Hi,

Just wanted to share that I used this to track my daily rainfall. Since my oregon scientific pcr800 rain gauge only track cumulative rain from last reset as a standard. Perhaps it of use for someone else. replace “sensor.rain_total” with your own cumulative rain sensor.

configuration.yaml

  • platform: template
    sensors:
    rain_daily:
    value_template: ‘{%- if not (is_state(“sensor.rain_total”,“unknown”) or is_state(“variable.rain_cum_prior”,“unknown”) )-%} {{ ((states.sensor.rain_total.state | float) - (states.variable.rain_cum_prior.state | float)) | max (0) | round(1) }} {%- endif -%}’
    friendly_name: ‘Rain Today’
    unit_of_measurement: ‘mm’

variable:
rain_cum_prior:
value: ‘unknown’

rain_daily_autmation.yaml

alias: ‘record cumulative rain to midnight’
trigger:
- platform: time
at: “00:00:01”
action:
- service: variable.set_variable
data:
variable: rain_cum_prior
value_template: ‘{{states.sensor.rain_total.state}}’

1 Like

This script adds 1 to the variable corresponding to the minute, and then check if it is equal to 60, if true assign zero the variable.
This work for me.

xxx_sc_exalarmeduplo2_alarm1_on_minute_schedule:       
  sequence:
    - service: variable.set_variable
      data:
        variable: xxx_vb_exalarmeduplo2_alarm1_on_minute_schedule
        value_template: "{{ (variable.state | int) + 1 }}"

    - service: persistent_notification.create
      data_template:
        message: "{{ states.variable.xxx_vb_exalarmeduplo2_alarm1_on_minute_schedule.state  }}"
        title: "Minute test"
        
    - condition: state
      entity_id: variable.xxx_vb_exalarmeduplo2_alarm1_on_minute_schedule
      state: '60'
      
    - service: variable.set_variable
      data:
        variable: xxx_vb_exalarmeduplo2_alarm1_on_minute_schedule
        value_template: "0"

I am restructuring my configuration to make it more manageable and run into this issue with variables:
When I put variables directly below the variable: line, properly indented and all, it works fine.

But what I want to do is:
variable: !include_dir_list ../variables

And then have separate files for each variable in the mentioned directory, for example, in …/variables sits a file named house_state.yaml with these contents:

house_state:
  value: 'Unknown'
  restore: true
  attributes:
    icon: mdi:home-heart
    name: 'House status'

The error I see in the build log is then:

Testing configuration at /builds/[redacted]/hass-config/.
Failed config
  homeassistant.packages.variable.variable: 
    - Package variable setup failed. Component variable cannot be merged. Expected a dict.
    - variable: ?
        - house_state: [source /builds/[redacted]/hass-config/./components/packages/../variables/house_state.yaml:4]
            attributes: [source /builds/[redacted]/hass-config/./components/packages/../variables/house_state.yaml:7]
              icon: mdi:home-heart
              name: Huis status
            restore: True
            value: Unknown

Not sure what that error means? Does the variable component not support the !include directives, or am I missing something here?

Using packages with variable here too. No dash in front of variable.

##########################################################################################
# Variables
##########################################################################################

variable:
  solar_angle_outside_light:
    value: 'Not set'
    restore: true
    attributes:
      icon: mdi:format-rotate-90
      name: 'Solar angle'

using

homeasistant:
  packages: !include_dir_named packages