Custom component to declare/set variables

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:

  times_motion_cam2_zone4_triggered:
    value: 0
    attributes:
      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

Alberto

Hi!

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

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

    • service: variable.set_variable
      data:
      variable: estado_tempe

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

Thank you for time and work.

This custom component is just what I need. However, I can’t get it to work. I created a “custom_components” folder in my configuration directory (/home/homeassistant/.homeassistant/custom_components) and placed the variable.py file there. I then added a simple variable component declarion to the configuration file. After restarting HA, I get:

Component not found: variable
5:39 PM components/__init__.py (ERROR)

Is that the correct configuration of your file? I’m running HA version 0.66.1

Thanks in advance for the help.

dont put the py file directly in custom_components. Create a subdirectory within custom_components called variable and put the py file in that

I have tried that as well. Here is what I have:

pi@hassbian:/home/homeassistant/.homeassistant/custom_components/variable $ ll
total 8
-rw-r--r-- 1 homeassistant homeassistant 6907 Apr 29 13:05 variable.py

Is HA sensitive to the permissions?

I get this error too, even though I put variable.py in a subfolder

\\HASSIO\config\custom_components\variable\variable.py

I am unable to get it to work with hass.io version 0.68.0 on raspbery pi.
I have other custom components that are working.
This is the error I get when I click on [check config] in hass.io

Configuration invalid
Component not found: variable

Here is my configuration.yaml file

variable:
  last_motion:
    value: 'Unknown'
    restore: true
    attributes:
      icon: mdi:map-marker
      name: "Last Motion"

Thanks for any assistance you can give.

Hello,

I also tried to get it to work. My solution was to NOT put it into a seperate Subfolder.

config\custom_components\variable.py

After that, the configured variables are visible.

I’m playing with Hass.io 0.68.1

Greetings
Sven

1 Like

It’s working me for in a NOT separate folder now too. I’m sure i tried that before but maybe hassio didn’t restart when i thought it had.

Hello ,Thank you.

Can these defined variables be used and written to from a bash shell script being executed using the shell component. Specifically I have 3 variables being created by the shell script and I want to make them available to HA.
Thanks, Ynot

I’m using a little python script with the API to populate variables at runtime.
After the variables.yaml has changed, watcher triggers the script, and the variables in HA are updated, if ‘restore: true’ is not set.
Maybe you can use it.

import yaml
import requests

config_file = '/home/homeassi/.homeassistant/variables.yaml'
url = 'http://localhost:8123/api/states/variable.'
headers = {'x-ha-access': 'your_password', 'content-type': 'application/json'}

def read_variables_yaml():
    with open(config_file, 'r') as stream:
        try:
            config = yaml.load(stream)
        except yaml.YAMLError as exc:
            print(exc)
    return config

json = read_variables_yaml()

errors = ''
for v in json:
    variable = v
    state = json[v]['value']
    restore = json[v]['restore']

    if not restore:
        if 'attributes' in json[v]:
            attributes = str(json[v]['attributes'])
            data = '{"state": "' + str(state) + '", "attributes": ' + attributes + '}'
        else:
            data = '{"state": "' + str(state) + '"}'
        data = data.replace("'",'"')
        #print(variable, data)

        r = requests.post(url+variable, data=data, headers=headers)
        if r.status_code != 200 and r.status_code != 201:
            errors = errors + 'ERROR:' + variable + ' - ' + str(r.status_code)

if errors != '':
    print(errors)

The watcher job:

job1:
  label: Watch variables
  watch: /home/homeassi/.homeassistant/variables.yaml
  exclude: []
  events: ['modify']
  options: []
  recursive: false
  command: python3 /home/homeassi/scripts/variables_set.py
2 Likes

Thanks a lot for this nice component. I played a lot with it around and used it in different ways.

Now, I want to use it to store three values coming in via MQTT, but this seems not working!
Here is what I tried: define a variable in configuration.yaml

variable:
  lightlevelvalue:
    value: 0

Then in automations.yaml

  - alias: newlight
    trigger:
      - platform: mqtt
        topic: WeatherStation/light
    action:
      - service: variable.set_variable
        data:
          variable: lightlevelvalue
          value_template: '{{ (variable.state | int) + 1 }}'

This is working pretty well, but as soon as I want to update the variable with a value from my light sensor it fails. What happens is, that the variable just lists the string “{{ states.sensor.weatherstation_light_level.state | int }}’”. Code looks like this:

  - alias: newlight
    trigger:
      - platform: mqtt
        topic: WeatherStation/light
    action:
      - service: variable.set_variable
        data:
          variable: lightlevelvalue
          value_template: '{{ states.sensor.weatherstation_light_level.state | int }}'

I tried several variants of the value statement without success e.g.:

  • sensor.weatherstation_light_level
  • states.sensor.weatherstation_light_level
  • sensor.weatherstation_light_level.valve

Is it possible, that you can’t reach the sensor values from this point?

This here is the sensor:


Any comment or hint is welcome.

Cheers

Have you tried it with data_template ?

   action:
      - service: variable.set_variable
        data_template:
          variable: lightlevelvalue
          value_template: '{{ states.sensor.weatherstation_light_level.state | int }}'

Thank you sooooo much, VDRainer!!! This was the trick. Works perfectly now.

Thanks for the variable component :smile:. Is it possible to use a variable in the delay option? So lets say I have a numeric value of 2000 that I want to use in an automation to delay it for 2000 miliseconds. And if I change the variable to 3000 the automation will have a delay of 3000 miliseconds.

Thanks!

Set your variable to be a delay in seconds
I use a random delay for my holiday lights
- delay: "{{range(0,1200+1)|random|timestamp_custom('%X',false)}}"

It can be easily adjusted to be a variable instead:

  - delay: "{{variable.test_timer|timestamp_custom('%X',false)}}"

Thanks for the quick reply, when I try your delay with my own variable it says: delay template: UndefinedError: ‘variable’ is undefined. Do you know why?

EDIT: got him, when I use: - delay: "{{states.variable.test_var.state|timestamp_custom('%X',false)}}" it is working fine!

EDIT2: the random on in delay is nice…but when I use 2 variables to replace the 0 and 1200 in range(0,1200) with 2 variables it is not working. Do you have an idea on that one? :slight_smile:

Did you install/define the variable package as per original post?

@lolouk44 the component itself was working fine, after some trial and error I got it working! Thanks for your help, appreciate it :slight_smile: