Giter Club home page Giter Club logo

hass-variables's Introduction

hass-variables

A Home Assistant component to declare and set/update variables (state).

Install

Manualy

Copy variable folder in to your home-assistant custom_components folder

Automaticaly with HACS

In HACS settings, add a custom repository with:

  • URL: https://github.com/rogro82/hass-variables
  • type: integration

Then the variable custom component will be installable through HACS and you will be able to follow the future updates.

Configure

Add the component variable to your configuration and declare the variables you want.

Example configuration

variable:
  countdown_timer:
    value: 30
    attributes:
      friendly_name: 'Countdown'
      icon: mdi:alarm
  countdown_trigger:
    name: Countdown
    value: False
  light_scene:
    value: 'normal'
    attributes:
      previous: ''
    restore: true

A variable 'should' have a value and can optionally have a name and attributes, which can be used to specify additional values but can also be used to set internal attributes like icon, friendly_name etc.

In case you want your variable to restore its value and attributes after restarting you can set restore to true.

Set variables from automations

To update a variables value and/or its attributes you can use the service call variable.set_variable

The following parameters can be used with this service:

  • variable: string (required) The name of the variable to update
  • value: any (optional) New value to set
  • value_template: template (optional) New value to set from a template
  • attributes: dictionary (optional) Attributes to set or update
  • attributes_template: template (optional) Attributes to set or update from a template ( should return a json object )
  • replace_attributes: boolean ( optional ) Replace or merge current attributes (default false = merge)

Example service calls

action:
  - service: variable.set_variable
    data:
      variable: test_timer
      value: 30

action:
  - service: variable.set_variable
    data:
      variable: last_motion
      value: "livingroom"
      attributes_template: >
        {
          "history_1": "{{ variable.state }}",
          "history_2": "{{ variable.attributes.history_1 }}",
          "history_3": "{{ variable.attributes.history_2 }}"
        }

Example timer automation

variable:
  test_timer:
    value: 0
    attributes:
      icon: mdi:alarm

script:
  schedule_test_timer:
    sequence:
      - service: variable.set_variable
        data:
          variable: test_timer
          value: 30
      - service: automation.turn_on
        data:
          entity_id: automation.test_timer_countdown

automation:
  - alias: test_timer_countdown
    initial_state: 'off'
    trigger:
      - platform: time_pattern
        seconds: '/1'
    action:
      - service: variable.set_variable
        data:
          variable: test_timer
          value_template: '{{ [((variable.state | int) - 1), 0] | max }}'

  - alias: test_timer_trigger
    trigger:
      platform: state
      entity_id: variable.test_timer
      to: '0'
    action:
      - service: automation.turn_off
        data:
          entity_id: automation.test_timer_countdown

More examples can be found in the examples folder.

hass-variables's People

Contributors

jpoppe avatar oncleben31 avatar rogro82 avatar tefinger avatar xannor avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hass-variables's Issues

Can't seem to set attributes

Hello,

First thank you very much for your code. Im happily using it.
At first I've used all seperate variable's for a single item, which I now try to put into one variable with different attributes but I can't seem to set them..

When I use the code to set just the state value it works fine. When I add the code (from the examples) to set attributes as well it doesn't work at all (including state)

My code:

- service: variable.set_variable
  data_template:
    variable: monica
    value: "{{ states.vacuum.monica.state }}"
    attributes_template: >
      {
        "cleaned_in_away_mode": 1,
        "cleaned_in_away_mode_finished": 0
      }

Feature Request: variable_template

Is it possible to also use variables as templates.
The purpose would to be to be able to create generic scripts that work for multiple variables. (so without having to create the same script for each variables)
My current workaround is to have one variable with loads of attributes. But it looks cleaner to have them seperated.

Variable - could we have versioning and a .json file?

Love your variable component!!! Thank you!
@rogro82, maybe you have a good reason not to, but is there any chance you could introduce versioning for your releases and create a .json tracking file for adding to custom_updater configuration.
I accidentally noticed that you introduced the new architecture, whereas being compatable with custom_updater would have alerted us immediately. Best! Milster

Use custom Unit_of_measurement with variable

I use the variables to feed data into Home assistant from local sensors and different apis. For example I have a temperature / humidity sensor, which is updating two variables when it gets an update.

However, I want to show the unit in the UI. How can I set a unit of the variable in use?

I have this:
grafik

I want this (shot from other SH system):
grafik

Unable to import add-on from repository

I´m adding repository URL to a new card in hassio/add-on store/Repositories, but the new card adden is not shown. The card shows "unknown" title and I cant´t see the addon. The system log show:

19-09-15 10:08:23 INFO (MainThread) [hassio.store] Load add-ons from store: 60 all - 0 new - 0 remove
19-09-15 10:08:28 INFO (MainThread) [hassio.store.git] Clone add-on https://github.com/rogro82/hass-variables repository
19-09-15 10:08:33 ERROR (MainThread) [hassio.utils.json] Can't read json from /data/addons/git/c6142703/repository.json: [Errno 2] No such file or directory: '/data/addons/git/c6142703/repository.json'
19-09-15 10:08:33 WARNING (MainThread) [hassio.store.data] Can't read repository information from /data/addons/git/c6142703/repository.json
19-09-15 10:08:33 INFO (MainThread) [hassio.store] Load add-ons from store: 60 all - 0 new - 0 remove

I think I´m doing samething wrong. Can you help me?

Thenk you.

Issue with setting larger data

I am trying to set a string of around 1500 characters to a variable and I am getting an error saying "State max length is 255 characters". How do I save larger strings to variables.

How to remove form HA

Latest HA now claims to have own variables inegration. I wanted to experiment but HA keeps warning that an untested custom component variables is used. Please advise how to (might be temporary) remove custom component variables. Thanks
Martin

Making a variable of a string, from an api?

Trying to do something like this:

sensor 2:

Would this component be able to do something like this? I need to set a variable to a string from the youtube api, then call it in the curl post.

This allows me to pull the video id of the newest video on a channel then play it directly on my tv.

Not working anymore with 0.115.0

The Variable Component is not working any longer, with the 0.115.0 Update. It's throwing out this Error:

2020-09-17 21:24:23 ERROR (MainThread) [homeassistant.components.automation.last_motion] Last Motion: Error executing script. Unexpected error for call_service at pos 1: Error rendering data template: UndefinedError: 'variable' is undefined
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 285, in async_render
    return compiled.render(kwargs).strip()
  File "/usr/local/lib/python3.8/site-packages/jinja2/environment.py", line 1090, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.8/site-packages/jinja2/environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "/usr/local/lib/python3.8/site-packages/jinja2/_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "<template>", line 2, in top-level template code
  File "/usr/local/lib/python3.8/site-packages/jinja2/sandbox.py", line 407, in getattr
    value = getattr(obj, attribute)
jinja2.exceptions.UndefinedError: 'variable' is undefined

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 138, in async_prepare_call_from_config
    service_data.update(template.render_complex(config[conf], variables))
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 81, in render_complex
    return {
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 82, in <dictcomp>
    render_complex(key, variables): render_complex(item, variables)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 86, in render_complex
    return value.async_render(variables)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 287, in async_render
    raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: UndefinedError: 'variable' is undefined

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 206, in _async_step
    await getattr(
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 385, in _async_call_service_step
    domain, service, service_data = async_prepare_call_from_config(
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 140, in async_prepare_call_from_config
    raise HomeAssistantError(f"Error rendering data template: {ex}") from ex
homeassistant.exceptions.HomeAssistantError: Error rendering data template: UndefinedError: 'variable' is undefined
2020-09-17 21:24:23 ERROR (MainThread) [homeassistant.components.automation.last_motion] While executing automation automation.last_motion
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 285, in async_render
    return compiled.render(kwargs).strip()
  File "/usr/local/lib/python3.8/site-packages/jinja2/environment.py", line 1090, in render
    self.environment.handle_exception()
  File "/usr/local/lib/python3.8/site-packages/jinja2/environment.py", line 832, in handle_exception
    reraise(*rewrite_traceback_stack(source=source))
  File "/usr/local/lib/python3.8/site-packages/jinja2/_compat.py", line 28, in reraise
    raise value.with_traceback(tb)
  File "<template>", line 2, in top-level template code
  File "/usr/local/lib/python3.8/site-packages/jinja2/sandbox.py", line 407, in getattr
    value = getattr(obj, attribute)
jinja2.exceptions.UndefinedError: 'variable' is undefined

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 138, in async_prepare_call_from_config
    service_data.update(template.render_complex(config[conf], variables))
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 81, in render_complex
    return {
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 82, in <dictcomp>
    render_complex(key, variables): render_complex(item, variables)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 86, in render_complex
    return value.async_render(variables)
  File "/usr/src/homeassistant/homeassistant/helpers/template.py", line 287, in async_render
    raise TemplateError(err) from err
homeassistant.exceptions.TemplateError: UndefinedError: 'variable' is undefined

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/automation/__init__.py", line 426, in async_trigger
    await self.action_script.async_run(
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 944, in async_run
    await asyncio.shield(run.async_run())
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 198, in async_run
    await self._async_step(log_exceptions=False)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 206, in _async_step
    await getattr(
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 385, in _async_call_service_step
    domain, service, service_data = async_prepare_call_from_config(
  File "/usr/src/homeassistant/homeassistant/helpers/service.py", line 140, in async_prepare_call_from_config
    raise HomeAssistantError(f"Error rendering data template: {ex}") from ex
homeassistant.exceptions.HomeAssistantError: Error rendering data template: UndefinedError: 'variable' is undefined

And it doesn't have to do with the script/automation because switching back to 0.114.4 is fixing the error and its working just fine. Probably has to do with the new "Variables" component they brought out.

Problem using variable in trigger.

Hello!

I am trying to use a variable in an automation trigger. This is my automation:

- alias: 'Envio de videos de la terraza por Telegram'
  trigger:
    platform: state
    entity_id: variable.incoming_terraza_video
    to: 'true'
  action:
    - service: telegram_bot.send_video
      data_template:
        file: "{{ trigger.event.data.path }}"
        caption: "{{now().strftime('%d/%m/%Y  %H:%M')}}"
    - service: variable.set_variable
      data:
        variable: variable.incoming_terraza_video
        value: 'false'

But I am getting the following error:

Envio de videos de la terraza por Telegram: Error executing script. Unexpected error for call_service at pos 2: Error rendering data template: UndefinedError: 'dict object' has no attribute 'event'

What am I doing wrong?

massive errors in set_variables with attributes

suddenly, I receive these errors:

Logger: homeassistant.components.automation.last_motion
Source: helpers/script.py:1122
Integration: Automatisierung (documentation, issues)
First occurred: 14:34:41 (4 occurrences)
Last logged: 14:36:30

Last motion: Error executing script. Invalid data for call_service at pos 1: template value should be a string for dictionary value @ data['attributes_template']

The code:

    - service: variable.set_variable
      data:
        variable: last_general_motion_detected
        value_template: '{{now().strftime("%H:%M:%S - %d-%m-%Y")}}'
        attributes_template: >
          {
          "location": "{{trigger.to_state.attributes.friendly_name}}"
          }

It worked this morning.
All other service calls producing errors as well.

Version: 0.118.3
Updated two days ago
Hassio

variable.state doesn't work

According to documentation, the following statement should work inside "variable.set_variable" block:

{{ variable.state }}

In fact, it doesn't. I have the following script:

test_variable:
  sequence:
    - service: variable.set_variable
      data_template:
        variable: logitech_input
        value_template: "{{ variable.state | int + 1 }}"

It crashes with the following error in the log:

Error rendering data template: UndefinedError: 'variable' is undefined

{{ states.variable.logitech_input.state }} works fine.

To be honest, I don't think it's a crucial functionality, because states.variable... may be used instead, so possibly it makes sense just to remove it from documentation.

See also #12 .

Thanks!

README.md has outdated installation instructions

Suggest updating the README.md as the installations instructions refer to installing variable.py into custom_components/. But no file with that name exists in your repo now that you've updated the custom component to work with the latest integration method. Ie. service.yaml, etc.

Question: Template inside a variable

Hi All,

Is it possible to do something like this:

adaptive_kelvin:
    value: "{{ states.switch.adaptive_lighting_sensor.attributes.color_temp_kelvin | round(0)}}"
    attributes:
      friendly_name: 'Adaptive Kelvin'
      icon: mdi:theme-light-dark

And use this variable "adaptive_kelvin" into automation? something like this:

- service: light.turn_on
   data:
     entity_id: light.livingroom_all
     brightness_pct: 100
     kelvin: "{{ [variable.adaptive_kelvin] }}"

kind regards,

SQL database growth exponentionaly

Dear All,

I am using variable component to emulate classes (structures) to build sort of an objects and procedures approach within HA automations. Maybe it is not a proper way to do that, but I decided to try it this way with Jinja2. In general, It works pretty good - variables and their attributes -> classes and fields, HA scripts == functions, you can impliment pretty complicated logics without need to go to python. But noticed an unexpected fenomena - my SQL DB grows at unprecedented speed after I lauched my "modules" at full load - all objects are created and functional. I assume it is variable writing the data to DB, but I fail to understand which ones of several houndreds I have. I mannualy excluded most of them from the recorder integration, but I do not see any significant difference as far as database growth is concerned. Is there any way to understand what exactly is "eating" my space? To give you an understanding, I estimate it is 20GB/day and I do not have any cameras in this integration! 20 GB/day of some text data! Apart from that I do not see any load on my system - CPU is ~3%, mem ~ 7%...

Would be really thanksfull for any suggestions how to trace this issue.

variable, attributes_template does not work

Dear All,

I am trying to use variable objects for my project, but the attributes_template do not work for some reason. I made a small example which yelds no result and I fail to understand why:

    detectors_list:
        value: 0
        attributes:
            list: "binary_sensor.dining1"

this I call from developer's tools, services, variable.set_variable with data below

variable: detectors_list
value_template: 2
attributes: >  
  { 
    "list": "{{ variable.attributes.list }}" 
  }

No metter what I try, the attributes do not change. Would anyone give me a hint why?

The error message from the log:

Logger: homeassistant
Source: custom_components/variable/init.py:219
First occurred: 23:57:58 (1 occurrences)
Last logged: 23:57:58

Error doing job: Task exception was never retrieved
Traceback (most recent call last):
File "/config/custom_components/variable/init.py", line 219, in async_set_variable
attributes = json.loads(
File "/usr/local/lib/python3.8/json/init.py", line 341, in loads
raise TypeError(f'the JSON object must be str, bytes or bytearray, '
TypeError: the JSON object must be str, bytes or bytearray, not Wrapper

Works with appdaemon?

I'm wondering whether this integration has been tested with appdaemon. I can't get service calls to variable.set_variable to work. The appdaemon event log shows

2020-09-14 15:00:01.007219 WARNING HASS: Error calling Home Assistant service default/variable/set_variable 2020-09-14 15:00:01.007522 WARNING HASS: Code: 400, error: 400: Bad Request 2020-09-14 15:00:01.009312 WARNING HASS: Error calling Home Assistant service default/variable/set_variable 2020-09-14 15:00:01.009564 WARNING HASS: Code: 400, error: 400: Bad Request

Maybe I'm missing something in the appdaemon configuration but I don't see it. If others have been successful using hass-variables with appdaemon, please let me know.

Integration not found

Today I installed the new core-2021.6.1 on HA. After the reboot I got an error message "variable integration not found". Deinstallation and re-installation via HACS didn't solved the problem. Any idea what I can do?

Update last reading, even if it's the same value?

Hi,

I have some variables which I monitor via Node Red, sometimes I need to take action even if the variable hasn't been changed (but has been updated!). I know some components do this, do you know which lines I need to change to have HA show the last update time, even if it was the same value?

Many thanks in advance...

Native type templates seems to break attributes_template

Since native types for templates was enabled in HA 0.118, most of my automations involving service calls for hass-variables are throwing this error:

voluptuous.error.MultipleInvalid: template value should be a string for dictionary value @ data['attributes_template']

Here's an example of one of the autos that is causing the issue:

      - service: variable.set_variable
        data_template:
          variable: rf_input
          value: >-
            # {% set payload = trigger.payload %}
            # {% set json = payload|from_json %}
            # {% set message = json.message %}
            # {{ message.id }}, {{ message.unit }}, {{ message.state }}
            {{ trigger.payload }}
          attributes_template: >
            {% set payload = trigger.payload %}
            {% set json = payload|from_json %}
            {% set message = json.message %}
            {
              "id": "{{message.id}}",
              "unit": "{{message.unit}}",
              "state": "{{message.state}}"
            }

This all worked fine pre-0.118. Any ideas how to make the yaml multiline string be interpreted as a string?

Getting type mismatches on recent versions

Hi, I think the move to allow more types in hass is causing some problems with the variables component. This automation used to work, but no longer does on .118.4. I'm getting this in the logs:

2020-11-30 10:46:42 DEBUG (MainThread) [homeassistant.core] Bus:Handling <Event automation_triggered[L]: name=DPD state change, entity_id=automation.dpd_state_change, source=state
of sensor.dpd_packages_coming_today>
2020-11-30 10:46:42 DEBUG (MainThread) [homeassistant.core] Bus:Handling <Event state_changed[L]: entity_id=automation.dpd_state_change, old_state=<state automation.dpd_state_chang
e=on; last_triggered=2020-11-25T11:32:13.537553+01:00, mode=single, current=0, id=dpd_state_change, friendly_name=DPD state change @ 2020-11-28T00:18:08.955419+01:00>, new_state=<s
tate automation.dpd_state_change=on; last_triggered=2020-11-30T10:46:42.997153+01:00, mode=single, current=1, id=dpd_state_change, friendly_name=DPD state change @ 2020-11-28T00:18
:08.955419+01:00>>
2020-11-30 10:46:43 INFO (MainThread) [homeassistant.components.automation.dpd_state_change] DPD state change: Running automation actions
2020-11-30 10:46:43 INFO (MainThread) [homeassistant.components.automation.dpd_state_change] DPD state change: Executing step call service
2020-11-30 10:46:43 DEBUG (MainThread) [homeassistant.core] Invalid data for service call variable.set_variable: {'variable': 'dpd_variable', 'attributes_template': {'from': 'NOREP
                                                                                                         ek'}, 'value_template': 'Delivery'}
                                                                                              íme balíÄ
[email protected]', 'date': 'Mon, 30 Nov 2020 10:42:27 +0100', 'subject': 'DPD Kurýr: Dnes Vám doruÄ
2020-11-30 10:46:43 ERROR (MainThread) [homeassistant.components.automation.dpd_state_change] DPD state change: Error executing script. Invalid data for call_service at pos 1: temp
late value should be a string for dictionary value @ data['attributes_template']
2020-11-30 10:46:43 DEBUG (MainThread) [homeassistant.core] Bus:Handling <Event state_changed[L]: entity_id=automation.dpd_state_change, old_state=<state automation.dpd_state_chang
e=on; last_triggered=2020-11-30T10:46:42.997153+01:00, mode=single, current=1, id=dpd_state_change, friendly_name=DPD state change @ 2020-11-28T00:18:08.955419+01:00>, new_state=<s
tate automation.dpd_state_change=on; last_triggered=2020-11-30T10:46:42.997153+01:00, mode=single, current=0, id=dpd_state_change, friendly_name=DPD state change @ 2020-11-28T00:18
:08.955419+01:00>>
2020-11-30 10:46:43 ERROR (MainThread) [homeassistant.components.automation.dpd_state_change] While executing automation automation.dpd_state_change
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/components/automation/__init__.py", line 433, in async_trigger
    await self.action_script.async_run(
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 1010, in async_run
    await asyncio.shield(run.async_run())
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 245, in async_run
    await self._async_step(log_exceptions=False)
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 253, in _async_step
    await getattr(
  File "/usr/src/homeassistant/homeassistant/helpers/script.py", line 460, in _async_call_service_step
    await service_task
  File "/usr/src/homeassistant/homeassistant/core.py", line 1405, in async_call
    processed_data = handler.schema(service_data)
  File "/usr/local/lib/python3.8/site-packages/voluptuous/schema_builder.py", line 272, in __call__
    return self._compiled([], data)
  File "/usr/local/lib/python3.8/site-packages/voluptuous/schema_builder.py", line 594, in validate_dict
    return base_validate(path, iteritems(data), out)
  File "/usr/local/lib/python3.8/site-packages/voluptuous/schema_builder.py", line 432, in validate_mapping
    raise er.MultipleInvalid(errors)
voluptuous.error.MultipleInvalid: template value should be a string for dictionary value @ data['attributes_template']

This is the automation in question:

- id: dpd_state_change
  alias: 'DPD state change'
  initial_state: 'true'
  trigger:
    platform: state
    entity_id: sensor.dpd_packages_coming_today
  condition:
    condition: state
    entity_id: 'sensor.dpd_packages_coming_today'
    state: 'Delivery'
  action:
    service: variable.set_variable
    data:
      variable: dpd_variable
      attributes_template: >
        {
          "from": "{{ state_attr('sensor.dpd_packages_coming_today', 'from') }}",
          "date": "{{ state_attr('sensor.dpd_packages_coming_today', 'date') }}",
          "subject": "{{ state_attr('sensor.dpd_packages_coming_today', 'subject') }}"
        } 
      value_template: "{{ states('sensor.dpd_packages_coming_today')}}"

Can't set value from scene

Hi,

Variable definition:

variable:
 setpoint_temperature_living:
  value: 18
  restore: true
  attributes:
          friendly_name: 'Setpoint Temperature Living'

Scene:

- name: "Climate: sleeping"
  entities:
    variable.setpoint_temperature_living:
      value: 20

When trying to activate this scene, HASS logs:
hass[20221]: #033[33m2018-01-10 19:33:29 WARNING (MainThread) [homeassistant.helpers.state] reproduce_state: Unable to reproduce state <state variable.setpoint_temperature_living=None; value=20 @ 2018-01-10T19:33:16.193756+01:00> (2)#033[0m

Is this not supported?

'version' key needed in the manifest file

hi!

the custom component reports:

2021-03-17 17:33:14 WARNING (MainThread) [homeassistant.loader] No 'version' key in the manifest file for custom integration 'variable'. This will not be allowed in a future version of Home Assistant. Please report this to the maintainer of 'variable'

and that was mentioned in HomeAssistant's release 2021.3 breaking changes. can you please add this?

thanks! :)

TextField IFTTT

Hi,

I want to use variable in Hassio to receive a TextField to IFTTT with an Applet with Google Assistant in Trigger with text ingredient ($).

I write this in Body in IFTTT:

{ "action": "call_service", "service": "var.set", "entity_id": "var.tts_bureau", "tts_bureau": "{{TextField}}" }

And I write this in Automatisation in Hassio:

  • id: '1552841249457'
    alias: Webhook TTS Bureau
    trigger:
    • event_data:
      action: call_service
      entity_id: var.tts_bureau
      service: var.set
      event_type: ifttt_webhook_received
      platform: event
      action:
    • data:
      value_template: '{{ trigger.event.data.tts_bureau }}'
      entity_id: var.tts_bureau
      service: var.set

Why the variable statut is {{ trigger.event.data.tts_bureau }} and not the TextField?
Hassio don't change {{ trigger.event.data.tts_bureau }} to the good TextField...

Thank you for your help

Feature Request: Use entity_id instead of variable

I don't know if this extension is still actively maintained, but I'll write my proposal anyways.

With the current situation the service call to "set_variable" MUST contain the variables entity_id as key 'variable'.

Current Situation:
When calling the service with an entity_id supplied, Home Assistant will throw an error: "extra keys not allowed @ data['entity_id']"

Request:
Remove the required 'variable' from the service data and use entity_id instead.

I looked through the code, but I can't quite seem to understand where to change it to allow the passed entity_id to be used as variable (I have an understanding of coding in general, but sadly I haven't looked into development for Home Assistant yet.)

HA 117 : template value should be a string for dictionary value @ data['attributes_template']

please see community post
https://community.home-assistant.io/t/template-value-should-be-a-string-for-dictionary-value-data-attributes-template/238153

template value should be a string for dictionary value @ data['attributes_template']

how should we rewrite this:

      - service: variable.set_variable
        data:
          variable: last_motion
          attributes_template: >
            {
             "history_1":"{{states('variable.last_motion')}}",
             "history_2":"{{state_attr('variable.last_motion','history_1')}}",
             "history_3":"{{state_attr('variable.last_motion','history_2')}}",
             "history_4":"{{state_attr('variable.last_motion','history_3')}}",
             "history_5":"{{state_attr('variable.last_motion','history_4')}}",
             "history_6":"{{state_attr('variable.last_motion','history_5')}}",
             "history_7":"{{state_attr('variable.last_motion','history_6')}}",
             "history_8":"{{state_attr('variable.last_motion','history_7')}}",
             "history_9":"{{state_attr('variable.last_motion','history_8')}}",
             "history_10":"{{state_attr('variable.last_motion','history_9')}}"
            }
          value: >
            {{trigger.to_state.name|replace(' sensor motion','')}}:
            {{as_timestamp(trigger.from_state.last_changed)|timestamp_custom('%X')}}

or, the CC should be adapted to use correct data type? not sure, so please have a look?
thanks!

How to update via Node Red?

Hi,

Thank you for these excellent component, I've made some variables and would like to update / read them from Node Red, do you know if / how this is possible?

When I search for entities via Node Red it doesn't seem to locate them (all other components with entities seem to work okay...?).

Many thanks in advance,

Mark

can't set variable to value_template using trigger.to_state.attributes.friendly_name

value_template for either

  • trigger.to_state.attributes.friendly_name
  • trigger.to_state.name

Doesn't work.

In the example automation below, the notification will show trigger.to_state.attributes.friendly_name however the variable doesn't get set to trigger.to_state.attributes.friendly_name

- alias: "01 First trigger"
  trigger:
    - platform: state # Door and window
      entity_id: binary_sensor.door_window_sensor_158d0001d63b07, binary_sensor.door_window_sensor_158d0001ef77d8, binary_sensor.door_window_sensor_158d0001fa792d, binary_sensor.door_window_sensor_158d0001a94c35, binary_sensor.door_window_sensor_158d0001f9e2e2, binary_sensor.door_window_sensor_158d0001f38b1f
      from: 'off'
      to: 'on'
    - platform: state # Motion
      entity_id: binary_sensor.motion_sensor_158d0001e57659, binary_sensor.motion_sensor_158d0001e52dee, binary_sensor.motion_sensor_158d0001dc7526
      from: 'off'
      to: 'on'
  action:
    - service: timer.start
      entity_id: timer.alarm_triggered
    - service: variable.set_variable
      data:
        variable: alarm_triggerone
        value_template: '{{ trigger.to_state.attributes.friendly_name }}'
    - service: notify.html5
      data_template:
        message: 'Alarm has been tripped by  {{ trigger.to_state.attributes.friendly_name }}'
      data:
        data:
          tag: 'notification-about-sensor'

Hass-variables and node red

Hello. I've tried to update/change a variables value and/or its attributes in node red with call service nod, but it doesn't work. Node configuration:
Server: Home Assistant
Domain: variable
Service: set_variable
Entity Id: variable.example_123
Data: { "value" : "{{Buterbrod}}"}
And... Debug: "Call-service API error. Error Message: extra keys not allowed @ data['entity_id']"
What should I do to make it work?

Hass 63.1 Break

Hello @rogro82,

Please I have been using your component and its been great until the recent 63.1 update. When I try to update a variable, I get the error

Log Details (ERROR)
Thu Feb 15 2018 09:39:20 GMT+0000 (GMT Standard Time)

Error executing service <ServiceCall variable.set_variable: variable=temp_switch_state, value=1>
Traceback (most recent call last):
  File "/srv/homeassistant/lib/python3.5/site-packages/homeassistant/core.py", line 1010, in _event_to_service_call
    yield from service_handler.func(service_call)
  File "/home/homeassistant/.homeassistant/custom_components/variable.py", line 88, in async_set_variable_service
    entity = component.entities[entity_id]
TypeError: 'itertools.chain' object is not subscriptable

Please can you help with this, as a couple of my automation depends on it.

Kind regards

stopped working in HA 0.85.0

trying to set variable in script

    - service: variable.set_variable
      data:
        variable: varxxx
        attributes_template: >
            {
              "history_1": "{{ variable.state }}",
              "history_2": "{{ variable.attributes.history_1 }}",
              "history_3": "{{ variable.attributes.history_2 }}"
            }
      data_template:
        value: "{{ as_timestamp(now())|timestamp_custom('[%d/%m %H:%M] ') ~ message }}"

got error:

Traceback (most recent call last):
  File ".../homeassistant/.homeassistant/custom_components/variable.py", line 179, in async_set_variable
    attributes = json.loads(attributes_template.async_render({ 'variable': current_state }))
  File "/usr/local/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/usr/local/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python3.6/json/decoder.py", line 355, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Invalid control character at: line 2 column 59 (char 60)

worked before upgrde of HA

Support Hacs

Is it possible to support the new community store that will replace/is replacing the custom updater? This will make your work better available and give users a easy solution to update when things change.

More information:
https://github.com/custom-components/hacs

"Restore" attributes along with state

Is there a way to restore my variables attributes upon reboot? the "restore: True" only seems to restore the state, but I was hoping for a way to restore the attributes I've written to it as well

Stopped working since HASS 0.84

Since latest HASS Release 0.84 this component stopped working. Here is the log:

2018-12-12 19:40:54 ERROR (MainThread) [homeassistant.loader] Error loading custom_components.variable. Make sure all dependencies are installed
Traceback (most recent call last):
  File "/srv/homeassistant/lib/python3.5/site-packages/homeassistant/loader.py", line 92, in get_component
    module = importlib.import_module(path)
  File "/usr/lib/python3.5/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 986, in _gcd_import
  File "<frozen importlib._bootstrap>", line 969, in _find_and_load
  File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 673, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 673, in exec_module
  File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed
  File "/home/pi/.homeassistant/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-12 19:40:54 ERROR (MainThread) [homeassistant.loader] Unable to find component variable
2018-12-12 19:40:54 ERROR (MainThread) [homeassistant.setup] Setup failed for variable: Component not found.

Test variable in automation action condition

Hi,

I try to do a conditional action within an automation based on the (integer) value of a variable. This is the code:
- alias: sensor2 initial_state: 'on' trigger: - platform: state entity_id: binary_sensor.stair2 action: - service: automation.turn_off entity_id: automation.sensor2 - service: automation.turn_on entity_id: automation.sensorTimeout - service: variable.set_variable data: variable: stair_state value_template: '{{ 3 if (variable.state | int) == 1 else 2 }}' - condition: template value_template: '{{ (states.variable.stair_state.state | int) == 3 }}' - service: script.turn_on entity_id: script.stair_up

I'm sure the variable stair_state = 3 but the script 'stair_up' isn't called. What can be wrong?

variable component doesn't work with HA 0.86.3

Hello,

I upgraded my HA from 0.74.2 to 0.84.3. Unfortunately the variable custom component doesn't work anymore, it's not loaded at all. I don't see it as a loaded component in the list.

I tried multiple variable file versions (the old one I used with HA 0.74.2, rogro82's one from 13th Dec and the newest one from 28th Dec) but it doesn't work, too.

Surprisingly there's no message in the log related to this component. Also nothing like "couldn't load component...".

I thought it's something related to my configuration.yaml. If I want to check the configuration.yaml in the "settings" menu, the check never ends and shows no result as long as I have the "variable.py" file stored in the "custom_components" folder. If I remove the variable.py file, the "configuration.yaml" check is done successfully.

Do I do something wrong? I worked with my HA 0.74.2 very well in the past. I didn't change anything except upgrading HA to 0.86.3.

Best regards,
Hirgo

use values for RGB setting

How can I use variables to set gateway RGB color?
What need I write to "rgb_color: [255,255,100]" instead the numbers?
thanks!

Config:
variable:
red_color:
value: 50
green_color:
value: 255
blue_color:
value: 50

Automation:
:
action:
- service: light.turn_on
entity_id: light.gateway_light
data:
brightness: 4
rgb_color: [255,255,100]

Attempt to set variable to body of email fails with core dump

Hi, when I try to set one of the variable attributes to the value of the body of an email from IMAP email sensor, I get the following (traceback at the bottom)

2019-05-14 22:56:07 DEBUG (MainThread) [homeassistant.core] Bus:Handling <Event call_service[L]: domain=variable, service=set_variable, service_data=variable=dpd_variable, value_template=delivery, attributes_template={
  "from": "REDACTED",
  "date": "Tue, 14 May 2019 21:42:10 +0200",
  "subject": "Fwd: DPD Kurýr: Dnes Vám doručíme balíček",
  "body": "---------- Forwarded message ---------
From: <[email protected]>
Date: Wed, Apr 17, 2019 at 8:55 AM
Subject: DPD Kur=C3=BDr: Dnes V=C3=A1m doru=C4=8D=C3=ADme bal=C3=AD=C4=8Dek
To: <REDACTED>


[image: Header image] <https://dpdkuryr.cz/r?Parcel=3D15505908155927>
P=C4=9Bkn=C3=BD den,
V=C3=A1=C5=A1 bal=C3=AD=C4=8Dek =C4=8D. *15505908155927* od SHIPITO C/O MAP=
CARGO

doru=C4=8D=C3=ADme dnes mezi 11:04-12:04.
*Doru=C4=8Dovac=C3=AD adresa: * REDACTED
V aplikaci DPD Kur=C3=BDr si st=C3=A1le m=C5=AF=C5=BEete zm=C4=9Bnit term=
=C3=ADn i m=C3=ADsto
Va=C5=A1e p=C5=99ihla=C5=A1ovac=C3=AD =C3=BAdaje: www.dpdkuryr.cz
<https://dpdkuryr.cz/r?Parcel=3D15505908155927>, osobn=C3=AD k=C3=B3d 8326
Nebo si m=C5=AF=C5=BEete bal=C3=AD=C4=8Dek vyzvednout na n=C4=9Bkter=C3=A9m=
 z na=C5=A1ich v=C3=BDdejn=C3=ADch m=C3=ADst
Pickup!
Tady na V=C3=A1s po=C4=8Dk=C3=A1 7 dn=C3=AD.
P=C5=99ihlaste se do na=C5=A1=C3=AD
aplikace DPD Kur=C3=BDr
<https://dpdkuryr.cz/Home/Parcel?utm_source=3Dnotifikace&utm_medium=3De-mai=
l&utm_content=3Dofd&utm_campaign=3DDPD_Kuryr&Parcel=3D15505908155927>


Vyberte si z t=C3=A9m=C4=9B=C5=99 1 000
v=C3=BDdejn=C3=ADch m=C3=ADst Pickup <https://pickup.dpd.cz>


[image: Chatbot image]
<https://bot.dpd.cz/?utm_source=3Dnotifikace&utm_medium=3Demail>
*Jak jste byli spokojeni s doru=C4=8Den=C3=ADm?*
Budeme r=C3=A1di za Va=C5=A1i zp=C4=9Btnou vazbu. Sta=C4=8D=C3=AD, kdy=C5=
=BE tady
<http://public.dpd.cz/customers/feedback/whitelistpage.aspx?email=3DZ0SYAKO=
GAASFW01GXZbzV09S>
odsouhlas=C3=ADte zasl=C3=A1n=C3=AD kr=C3=A1tk=C3=A9ho dotazn=C3=ADku. D=C4=
=9Bkujeme.

S radost=C3=AD,
Va=C5=A1e DPD

dpd.cz <http://www.dpd.cz>  |  Sledujte n=C3=A1=C5=A1 Facebook
<https://www.facebook.com/dpd.cz>  a  Twitter
<https://twitter.com/dpd_cz?lang=3Dcs>  |  Nej=C4=8Dast=C4=9Bj=C5=A1=C3=AD =
odpov=C4=9Bdi
<http://dorucujemeradost.dpd.cz/kontaktujte-nas?utm_source=3DNotifikace&utm=
_medium=3DLinkZapati&utm_campaign=3DFAQ>
 d=C5=99=C3=ADve,
ne=C5=BE se stihnete zeptat
Toto je automaticky generovan=C3=BD e-mail, proto na n=C4=9Bj pros=C3=ADm n=
eodpov=C3=ADdejte.

[image: Zname zvyky a chovani online nakupujicich]
<https://eshopperbarometer.dpd.com/>


Tento e-mail je urcen pouze pro jeho adresata/adresaty a muze obsahovat
duverne informace, jejichz ochrana muze byt vyzadovana pravnimi predpisy.
Jestlize jste zpravu obdrzel(a) omylem, neprodlene informujte jejiho
odesilatele a tuto zpravu, jeji prilohy a pripadne kopie ihned vymazte.
Jakakoli forma uziti, zverejneni, reprodukce, kopirovani, distribuce a
sireni teto zpravy je v takovem pripade zakazana. DPD CZ s.r.o., neodpovida
za mozne skody zpusobene neuplnym prenosem, moznou modifikaci ci zpozdenim
teto zpravy behem prenosu od odesilatele k adresatovi.
---
This e-mail transmission is intended solely for the ordinary user of the
e-mail address to which it was addressed. It may contain legally privileged
and/or confidential information. If you have received this e-mail in error
or are not an intended recipient please inform the sender with-out delay
and delete this e-mail, attachments and possible copies immediately. The
unauthorised use, disclosure, distribution and/or copying of this e-mail or
any information it contains is prohibited. DPD CZ s.r.o., does not accept
liability for any damage caused by incomplete transmission, possible
modification or delay of this e-mail during the transmission from the
sender to the recipient.
"
}>
2019-05-14 22:56:07 ERROR (MainThread) [homeassistant.core] Error doing job: Task exception was never retrieved
Traceback (most recent call last):
  File "/config/custom_components/variable/__init__.py", line 179, in async_set_variable
    attributes = json.loads(attributes_template.async_render({ 'variable': current_state }))
  File "/usr/local/lib/python3.7/json/__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "/usr/local/lib/python3.7/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python3.7/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Invalid control character at: line 5 column 50 (char 186)
2019-05-14 22:56:07 DEBUG (MainThread) [homeassistant.core] Bus:Handling <Event state_changed[L]: entity_id=automation.dpd_state_change, old_state=<state automation.dpd_state_change=on; last_triggered=None, id=dpd_state_change, friendly_name=DPD state change, hidden=True @ 2019-05-14T22:55:42.905821+02:00>, new_state=<state automation.dpd_state_change=on; last_triggered=2019-05-14T22:56:07.720688+02:00, id=dpd_state_change, friendly_name=DPD state change, hidden=True @ 2019-05-14T22:55:42.905821+02:00>>

Service to reload variables

At the moment, every variable needs to first be added to the configuration.yaml and then home assistant needs to be restarted.

This is pretty annoying, especially if your HA setup takes a while to restart (z-wave network etc.).

It would be useful if component had reload service (similar to the automation or python_script components) that would reload variable configuration.

This looks like it might be the answer to my motion prayers!

I have various PIR sensors dotted about the house, and I've long wanted to have a sensor for the PIR which last reported an ON event. I'm not interested in the OFF events, in fact, I rather want to filter them off! Do you think this might be how to go about this? I'm just not sure how I'd (in one automation) use maybe a template to update the variable? I know how to do it in a number of automations equal to the number of sensors I have, but that isn't very elegant! :-)
thanks for the code!!

Can't read variable in automation conditions.

There is no possible to use variables as a conditions in automation like:

variable:
  heating_off_set_by_automation:
    name: heating_off_set_by_automation
    value: False
automation:
  - alias: turn off
    trigger:
      platform: time
      seconds: '/5'
    condition:
      - condition: template
        value_template: '{{ variables.heating_off_set_by_automation == False }}'
    action:
      - service: switch.turn_on
        entity_id: switch.heating_force_turn_off

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.