Git Product home page Git Product logo

home-assistant-variables's Introduction

home-assistant-variables

The var component is a Home Assistant integration for declaring and setting generic variable entities. Variables can be set manually using the var.set service or they can be set using templates or SQL queries which will be run automatically whenever a specified event fires. The var component depends on the recorder component for up-to-date SQL queries and uses the same database setting.

Buy Me A Coffee

Table of Contents

Installation

MANUAL INSTALLATION

  1. Download the latest release.
  2. Unpack the release and copy the custom_components/var directory into the custom_components directory of your Home Assistant installation.
  3. Add a var entry to your configuration.yaml.
  4. Restart Home Assistant.

INSTALLATION VIA HACS

  1. Ensure that HACS is installed.
  2. Search for and install the "Variable" integration.
  3. Add a var entry to your configuration.yaml.
  4. Restart Home Assistant.

Configuration

To add a variable, include it under the var component in your configuration.yaml. The following example adds two variable entities, x and y:

# Example configuration.yaml entry
var:
  x:
    friendly_name: 'X'
    initial_value: 0
    icon: mdi:bug
  y:
    friendly_name: 'Y'
    initial_value: 'Sleeping'
    entity_picture: '/local/sleep.png'

CONFIGURATION VARIABLES

var (map) (Required)

  • unique_id (string)(Optional) Unique identifier for VAR entity, to enable overriding settings from within the UI, such as the entity name or room. Use with care, and only if explicitly required!

  • friendly_name (string)(Optional) Name to use in the frontend.

  • friendly_name_template (template)(Optional) Defines a template for the name to be used in the frontend (this overrides friendly_name).

    Note: friendly_name_template is evaluated every time an update is triggered for the variable (i.e., via tracked_entity_id, tracked_event_type, or var.update). To pass a template to be evaluated once by var.set, use the friendly_name parameter in a data_template.

  • initial_value (match_all)(Optional) Initial value when Home Assistant starts.

  • value_template (template)(Optional) Defines a template for the value (this overrides initial_value).

    Note: value_template is evaluated every time an update is triggered for the variable (i.e., via tracked_entity_id, tracked_event_type, or var.update). To pass a template to be evaluated once by var.set, use the value parameter in a data_template.

  • attributes (map)(Optional) Dictionary of attributes equivalent to that of HomeAssistant template sensor attributes.

    Similar to value_template, attributes are evaluated on every update.

  • tracked_entity_id (string | list)(Optional) A list of entity IDs so the variable reacts to state changes of these entities.

  • tracked_event_type (string | list)(Optional) A list of event types so the variable reacts to these events firing.

  • query (string)(Optional) An SQL QUERY string, should return 1 result at most.

  • column (string)(Optional) The SQL COLUMN to select from the result of the SQL QUERY.

  • restore (boolean)(Optional) Restores the value of the variable whenever Home Assistant is restarted.

    Default value: true

  • force_update (boolean)(Optional) Trigger a state change event every time the value of the variable is updated, even if the value hasn't changed. If false, state change events will only be triggered by distinct changes in value.

    Default value: false

  • unit_of_measurement (string)(Optional) Defines the units of measurement of the variable, if any. This will also influence the graphical presentation in the history visualization as a continuous value. Variables with missing unit_of_measurement are shown as discrete values.

    Default value: None

  • icon (string)(Optional) Icon to display for the component.

  • icon_template (template)(Optional) Defines a template for the icon to be used in the frontend (this overrides icon).

    Note: icon_template is evaluated every time an update is triggered for the variable (i.e., via tracked_entity_id, tracked_event_type, or var.update). To pass a template to be evaluated once by var.set, use the icon parameter in a data_template.

  • entity_picture (string)(Optional) Picture to display for the component.

  • entity_picture_template (template)(Optional) Defines a template for the entity_picture to be used in the frontend (this overrides entity_picture).

    Note: entity_picture_template is evaluated every time an update is triggered for the variable (i.e., via tracked_entity_id, tracked_event_type, or var.update). To pass a template to be evaluated once by var.set, use the entity_picture parameter in a data_template.

Services

var.set

The set service can be used to set the state or attributes of the variable entity from an automation or a script. All config parameters can also be set using var.set.

PARAMETERS

  • entity_id (string | list)(Required) A list of var entity IDs to be set by the service.
  • friendly_name (string)(Optional)
  • friendly_name_template (template)(Optional)
  • value (match_all)(Optional)
  • value_template (template)(Optional)
  • attributes (map)(Optional)
  • tracked_entity_id (string | list)(Optional)
  • tracked_event_type (string | list)(Optional)
  • query (string)(Optional)
  • column (string)(Optional)
  • restore (boolean)(Optional)
  • force_update (boolean)(Optional)
  • unit_of_measurement (string)(Optional)
  • icon (string)(Optional)
  • icon_template (template)(Optional)
  • entity_picture (string)(Optional)
  • entity_picture_template (template)(Optional)

EXAMPLE

This example sets up an automation that resets the values of the variables at midnight.

var:
  daily_diaper_count:
    friendly_name: "Daily Diaper Count"
    initial_value: 0
    icon: mdi:toilet
  daily_bottle_feed_volume_formula:
    friendly_name: "Daily Formula Intake"
    initial_value: 0
    unit_of_measurement: 'ounces'
    icon: mdi:baby-bottle-outline

automation:
  - alias: "Reset Baby Counters"
    trigger:
      - platform: time
        at: '00:00:00'
    action:
      - service: var.set
        data:
          entity_id:
            - var.daily_diaper_count
            - var.daily_bottle_feed_volume_formula
          value: 0
          icon: mdi:null

var.update

The update service can be used to force the variable entity to update from an automation or a script.

PARAMETERS

  • entity_id (string | list)(Required) A list of var entity IDs to be updated by the service.

EXAMPLE

This example sets up an automation that updates the variable every 5 minutes.

var:
  temp_sensor_battery:
    friendly_name: "Temp Sensor Battery"
    value_template: "{{ state.attr('sensor.temperature', 'battery') }}"

automation:
  - alias: "Update Temp Sensor Battery Var Every 5 Minutes"
    trigger:
      - platform: time_pattern
        minutes: '/5'
    action:
      - service: var.update
        data:
          entity_id: var.temp_sensor_battery

Note: The homeassistant.update_entity service can be used more generally to update any entity, including var entities.

Automatic Updates

UPDATING USING TRACKED ENTITIES

A variable can be set to update whenever the state of an entity changes. This example counts the number of times the state changes for input_boolean.foo and input_boolean.bar.

var:
  toggle_count:
    friendly_name: "Toggle Count"
    initial_value: 0
    value_template: "{{ (states('var.toggle_count') | int) + 1 }}"
    tracked_entity_id:
      - input_boolean.foo
      - input_boolean.bar

UPDATING USING TRACKED EVENT TYPES

A variable can be set to update whenever an event fires. This example multiplies variables y and z whenever my_custom_event fires.

var:
  x:
    friendly_name: 'yz'
    value_template: "{{ (states('var.y') | int) * ( states('var.z') | int) }}"
    tracked_event_type: my_custom_event
    attributes:
      y: "{{ states('var.y') }}"
      z: "{{ states('var.z') }}"

Templates

The var component shares features with the template sensor. Many of a variable's attributes can be set using templates.

SELECTING ENTITY/VALUE USING TEMPLATES

Templates can be used with the variable set service to select the entity_id and to set any of the attributes of a variable entity. This example shows entity_id and value being selected via template.

automation:
  - alias: "Handle Bottle Feed Event"
    trigger:
      platform: event
      event_type: bottle_feed_event
    action:
      service: var.set
      data_template:
        entity_id: >-
          {% if trigger.event.data.contents == 'milk' %}
            var.daily_bottle_feed_volume_milk
          {% elif trigger.event.data.contents == 'formula' %}
            var.daily_bottle_feed_volume_formula
          {% endif %}
        value: >-
          {% if trigger.event.data.contents == 'milk' %}
            {{ (states('var.daily_bottle_feed_volume_milk') | int) + (trigger.event.data.volume | int) }}
          {% elif trigger.event.data.contents == 'formula' %}
            {{ (states('var.daily_bottle_feed_volume_formula') | int) + (trigger.event.data.volume | int) }}
          {% endif %}
        attributes: >-
          last_feed_volume: "{{ trigger.event.data.volume }}"

DYNAMIC VARIABLE UPDATES USING TEMPLATES

This example shows how the value, and other attributes of the variable, can be set to update automatically based on the state of another entity. Template values will be updated whenever the state changes for any of the tracked entities listed below tracked_entity_id.

var:
  waldo_location_status:
    friendly_name: "Waldo Location Status"
    value_template: >-
      {% if states('device_tracker.waldo_phone_wifi') == 'home' and states('device_tracker.waldo_phone_bluetooth') == 'home' %}
        Home
      {% else %}
        Unknown
      {% endif %}
    entity_picture_template: >-
      {% if states('var.waldo_location_status') == 'Home' %}
        /local/home.jpg
      {% else %}
        /local/question_mark.jpg
      {% endif %}
    tracked_entity_id:
      - device_tracker.waldo_phone_wifi
      - device_tracker.waldo_phone_bluetooth
      - var.waldo_location_status

SQL Queries

The var component also shares features with the SQL sensor. When a variable updates, it will run the SQL query against the Home Assistant database updating the variable with the value of the query.

DYNAMIC VARIABLE UPDATES USING AN SQL QUERY

This example shows how the value, and other attributes of the variable, can be set to update automatically based on an SQL query. Template values will be updated whenever the state changes for any of the tracked entities listed below tracked_entity_id or when any event fires with the same event type as any of the event types listed below tracked_event_type.

var:
  todays_diaper_count:
    friendly_name: "Today's Diaper Count"
    icon: mdi:toilet
    query: "SELECT COUNT(*) AS diaper_count FROM events WHERE event_type = 'diaper_event' AND time_fired BETWEEN DATETIME('now', 'start of day') AND DATETIME('now');"
    column: 'diaper_count'
    tracked_event_type: diaper_event

FILTERING EVENT DATA USING AN SQL QUERY

This example shows how to use an SQL query to filter events based on their event_data. In the example, diaper_event contains an event_data entry called type that is either wet, dirty, or both.

var:
  todays_wet_diaper_count:
    friendly_name: "Today's Wet Diaper Count"
    icon: mdi:water
    query: "SELECT COUNT(*) AS diaper_count FROM events WHERE event_type = 'diaper_event' AND JSON_EXTRACT(event_data, '$.type') LIKE '%wet%' AND time_fired BETWEEN DATETIME('now', 'start of day') AND DATETIME('now');"
    column: 'diaper_count'
    tracked_event_type: diaper_event

USING AN SQL QUERY IN A TEMPLATE

The result of a variable's SQL query can also be used within templates. This example computes the average formula volume over the past week and adds it to the variable z. In this example, bottle_event contains an event_data entry called volume that contains the volume of formula.

var:
  avg_formula_plus_z:
    friendly_name: "Average Formula Plus z"
    value_template: "{{ ( avg_formula | float) + ( states('var.z') | float) }}"
    query: "SELECT COALESCE(SUM(CAST(JSON_EXTRACT(event_data, '$.volume') AS FLOAT))/7.0, 0) AS avg_formula FROM events WHERE event_type = 'bottle_event' AND time_fired BETWEEN DATETIME('now', 'start of day', '-7 days') AND DATETIME('now', 'start of day');"
    column: 'avg_formula'
    tracked_event_type: bottle_event

SCENES

You may set the values of variables with scenes:

- name: My Scene
  entities:
    var.my_var: 'New Value'

Lovelace UI

Variables can be displayed in the Lovelace frontend like other entities.

cards:
  - type: entities
    title: "Baby Variables"
    entities:
      - entity: var.daily_diaper_count
      - entity: var.daily_bottle_feed_volume_milk
      - entity: var.daily_bottle_feed_volume_formula

Setting a unit_of_measurement will prompt Home Assistant to display a two dimensional graph in its history panel and history-graph card.

cards:
  - type: history-graph
    title: "Baby Plots"
    hours_to_show: 24
    entities:
      - entity: var.daily_bottle_feed_volume_milk
      - entity: var.daily_bottle_feed_volume_formula

Tip: Using a unit of ' ' can be useful if you want to group unit-less variables together in a single 2D graph.

Reload

Variable configuration can be reloaded without restarting HA using the YAML tab on the Developer Tools page. When the var component is loaded an option will be added to the YAML configuration reloading section named Variables. Clicking this option will reload all var configuration.

Note: the component is only loaded by HA at startup when configuration is defined for the component. This means that if the var component is installed and HA is restarted without var configuration the reload option is not available yet. You have to add some configuration first and restart HA again before the reload option becomes available.

Why?

I assembled this component for a few reasons:

  • It was tedious to create a corresponding separate template sensor for each entity in the UI.
  • I wanted a single general-purpose component, with a generic name, that could be used to store, update, and display values using templates.
  • I didn't like using named UI components to store first-class data (e.g. input_text).
  • I wanted to be able to work with data directly from the home assistant database (especially custom events) without having to create and flip-flop between a bunch of different entities.
  • I wanted a custom component that I could extend with more features in the future.

Useful Links

home-assistant-variables's People

Contributors

danielbrunt57 avatar inusasha avatar ludeeus avatar mvsjes2 avatar robomagus avatar snarky-snark 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

home-assistant-variables's Issues

Timeout Errors when var service call from AppDaemon

Iny ideas why sometimes i get this kind of errors in AD?

2020-03-09 15:57:45.081046 WARNING salon_purifier_controller: Unexpected error in worker for App salon_purifier_controller:
2020-03-09 15:57:45.084617 WARNING salon_purifier_controller: Worker Ags: {'id': '8d0e0ec0d347422bbfc1afaf9b35bca7', 'name': 'salon_purifier_controller', 'objectid': 'ec664cb8795848d4a4a094193f677744', 'type': 'scheduler', 'function': <bound method SalonPurifierController.reset_trigger_variable of <salon_purifier_controller.SalonPurifierController object at 0x7f814f3490>>, 'pin_app': True, 'pin_thread': 7, 'kwargs': {'pin': True, '__thread_id': 'thread-7'}}
2020-03-09 15:57:45.088877 WARNING salon_purifier_controller: ------------------------------------------------------------
2020-03-09 15:57:45.112356 WARNING salon_purifier_controller: Traceback (most recent call last):
  File "/usr/lib/python3.8/site-packages/appdaemon/threading.py", line 766, in worker
    funcref(self.AD.sched.sanitize_timer_kwargs(app, args["kwargs"]))
  File "/config/appdaemon/apps/salon_purifier_controller.py", line 141, in reset_trigger_variable
    self.call_service('var/set', entity_id = self.trigger_entity, value = 'off')
  File "/usr/lib/python3.8/site-packages/appdaemon/utils.py", line 191, in inner_sync_wrapper
    f = run_coroutine_threadsafe(self, coro(self, *args, **kwargs))
  File "/usr/lib/python3.8/site-packages/appdaemon/utils.py", line 285, in run_coroutine_threadsafe
    result = future.result(self.AD.internal_function_timeout)
  File "/usr/lib/python3.8/concurrent/futures/_base.py", line 441, in result
    raise TimeoutError()
concurrent.futures._base.TimeoutError

Feature request: 'force_update' as an option?

Hello,

I've now transferred all 100+ of my variables over to this component, thank you!

I was wondering if it was possible to add a 'force_update' option, as is available on a few other components? I have a number of sensors that I need the value to update the chart for, regardless of if the value has changed, or not...

Initialization failed

I have a new home assistant installation running on Ubuntu 20.04. The version is 0.113.0. I installed the variable integration using HACS and that seems to have been successful. However, when I restart home assistant to complete the installation, the log shows the following error:

2020-07-27 08:24:04 ERROR (MainThread) [homeassistant.setup] Setup failed for var: Integration failed to initialize.

There is no other information. The log does show:

2020-07-27 08:24:01 WARNING (MainThread) [homeassistant.loader] You are using a custom integration for var which has not been tested by Home Assistant. This component might cause stability problems, be sure to disable it if you experience issues with Home Assistant.

Where can I look for more information on what the failure is? My logger component setup looks like this:

logger:
  default: info
  logs:
    homeassistant.core: info

Is the var.set service exposed as an API endpoint?

(I couldn't figure out where to ask this question. If I'm not doing this right, please advise)

Enjoying this var component , but am not clear if I can call it from a bash script. Would it be exposed under:
https://MY-HA/api/services/varset

What a NOOB.

     https://MY-HA/api/services/var/set

Sorry.
Gene

Initial_value not being picked up?

I used the initial_value in configuration.yaml and my understanding is upon startup this is supposed to set the variable to the value you specified. Does not appear to do this; instead sets at 0 or 1?

Home Assistant 0.108.0b0 breaks the component :-(

Error:

Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/setup.py", line 171, in _async_setup_component
    hass, processed_config
  File "/config/custom_components/var/__init__.py", line 105, in async_setup
    await component.async_setup(config)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 131, in async_setup
    await asyncio.gather(*tasks)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 229, in async_setup_platform
    self.hass, self.config, self.domain, platform_type
  File "/usr/src/homeassistant/homeassistant/setup.py", line 230, in async_prepare_setup_platform
    integration = await loader.async_get_integration(hass, platform_name)
  File "/usr/src/homeassistant/homeassistant/loader.py", line 323, in async_get_integration
    Integration.resolve_from_root, hass, components, domain
  File "/usr/local/lib/python3.7/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/src/homeassistant/homeassistant/loader.py", line 156, in resolve_from_root
    manifest_path = pathlib.Path(base) / domain / "manifest.json"
  File "/usr/local/lib/python3.7/pathlib.py", line 920, in __truediv__
    return self._make_child((key,))
  File "/usr/local/lib/python3.7/pathlib.py", line 699, in _make_child
    drv, root, parts = self._parse_args(args)
  File "/usr/local/lib/python3.7/pathlib.py", line 653, in _parse_args
    a = os.fspath(a)
TypeError: expected str, bytes or os.PathLike object, not NoneType

Error assigning a var to a plant config variable

Hi there,

I am trying to assign the conf variable min_moisture to the value contained in a home-assistant-variables. I already created the variable as:

var:
  tomatoes_min_moisture: 
    initial_value: 20

and then assigned in the plant definition (bringing it as an int):

plant:
  tomatoes:
    sensors:
      moisture: sensor.tomatoes_moisture
      battery: sensor.tomatoes_battery
      temperature: sensor.tomatoes_temperature
      conductivity: sensor.tomatoes_conductivity
      brightness: sensor.tomatoes_light_intensity
    min_moisture: "{{ states('var.tomatoes_min_moisture') | int }}"

but i get the following error:

Invalid config for [plant]: expected int for dictionary value @ data['plant']['tomatoes']['min_moisture']. Got "{{ states('var.tomatoes_min_moisture') | int }}". (See /config/configuration.yaml, line 12).

I would really appreciate any help,

BR

Prevent circular update loops

An infinite update loop can occur if a variable appears in its own value_template and the variable is set to update based on its own state changes. There are use cases where it is useful for a variable to appear in its own value_template. For example,

var:
  toggle_counter:
    initial_value: 0
    value_template: "{{ var.toggle_counter | int + 1 }}"
    tracked_entity_id: input_boolean.foo

In this case, var.toggle_counter is only updated on changes to input_boolean.foo, however, there are situations that warrant listening for the state changes of the variable itself.

In those cases we need to prevent the loop from happening.

A few options to fix this:

  1. Validate input to prevent value_template and tracked_entity_id from both containing the var.
  2. Allow this situation to occur, but don't update a var's self._value if the reason for the update was a state change event for itself.

I'm leaning towards 2 since it allows for other var attributes to be updated whenever the value of the var changes.

Feature Request: Toggle Service

There are some variables that I store as true/false (could also be stored as 1/0 or on/off) and it would be really handy if there was a service call var.toggle that would convert a variable to it's opposite to make the UI for buttons a lot cleaner.

error on startup

I've tested with and without "var:" in configuration.yaml. With it enabled, this error is logged:

2019-08-30 19:30:17 ERROR (MainThread) [homeassistant.core] Error doing job: Task exception was never retrieved
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 223, in async_setup_platform
self.hass, self.config, self.domain, platform_type
File "/usr/src/homeassistant/homeassistant/setup.py", line 227, in async_prepare_setup_platform
integration = await loader.async_get_integration(hass, platform_name)
File "/usr/src/homeassistant/homeassistant/loader.py", line 283, in async_get_integration
Integration.resolve_from_root, hass, components, domain
File "/usr/local/lib/python3.7/concurrent/futures/thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "/usr/src/homeassistant/homeassistant/loader.py", line 154, in resolve_from_root
manifest_path = pathlib.Path(base) / domain / "manifest.json"
File "/usr/local/lib/python3.7/pathlib.py", line 908, in truediv
return self._make_child((key,))
File "/usr/local/lib/python3.7/pathlib.py", line 695, in _make_child
drv, root, parts = self._parse_args(args)
File "/usr/local/lib/python3.7/pathlib.py", line 649, in _parse_args
a = os.fspath(a)
TypeError: expected str, bytes or os.PathLike object, not NoneType

var entities using mySQL do not update with HA v.2021.05.*

Hello,
In the time of writing this text (HA version 2021.05.3) this text, my var config using SQL is not working. The last working version of HA is 2021.4.6. So I downgraded HA and all I need still works perfectly for me.

Please have a look on HA logs below + my HA config data.
Thanks for really great integration!

home-assistant.log

2021-05-13 08:34:03 ERROR (MainThread) [homeassistant.helpers.entity] Update for var.pv_pogoda fails
Traceback (most recent call last):
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 316, in async_update_ha_state
await self.async_device_update()
File "/usr/src/homeassistant/homeassistant/helpers/entity.py", line 524, in async_device_update
raise exc
File "/config/custom_components/var/init.py", line 410, in async_update
_LOGGER.debug("result = %s", res.items())
AttributeError: Could not locate column in row for column 'items'

var definition

pv_moc_avg:
friendly_name: Średnia moc PV #średnia moc
initial_value: 0
icon: mdi:bug
query: |
SELECT entity_id, round(avg(CASE WHEN state > 0 THEN state ELSE 0 END),0) "srednia_moc"
FROM states
WHERE entity_id = "sensor.solarlog_power_ac"
AND convert_tz(last_changed,'utc','poland') >= now() - interval 30 minute
GROUP BY entity_id;
column: "srednia_moc"
unit_of_measurement: W
value_template: >-
{%- if states('sun.sun') == 'above_horizon' -%}
{{ float(value)|round(0) }}
{%else%}
0
{%endif%}

System Health

version core-2021.4.6
installation_type Home Assistant Container
dev false
hassio false
docker true
virtualenv false
python_version 3.8.7
os_name Linux
os_version 5.10.17-v7l+
arch armv7l
timezone Europe/Warsaw
Home Assistant Community Store
GitHub API ok
Github API Calls Remaining 4882
Installed Version 1.12.3
Stage running
Available Repositories 776
Installed Repositories 4
Home Assistant Cloud
logged_in true
subscription_expiration May 20, 2021, 2:00 AM
relayer_connected true
remote_enabled true
remote_connected true
alexa_enabled false
google_enabled true
can_reach_cert_server ok
can_reach_cloud_auth ok
can_reach_cloud ok
Lovelace
dashboards 3
resources 2
views 13
mode storage

Reserved words?

Couldn't set up variables called "Armed" nor "Disarmed". There must be some reserved words that cannot be used??

Restore, only restores state?

Howdy,

I have a number of variables that use icon templates. Upon reboot it appears only the state is restored and the custom icons are lost...? Shouldn't restore reinstate all associated values?

Var.get service?

I currently use Node Red and another variable plugin, this allows me to get the value of a variable via a service (which I do in many NR flows), is this currently achievable?

Ability to store an Array

Would be nice if i could store an Array. Tried to store the value rgb_color of the light component but that doesn't seem to work.

- service: var.set
   data:
     entity_id: var.previous_rgb_color
     value_template: "{{ state_attr('light.hue_play_1', 'rgb_color') }}"

Feature request: store attributes

A few people have requested the ability to store attributes alongside a variable. While a variable can store any kind of object including arrays or dicts, a separate parameter for attributes would allow for attributes to be stored and updated without complicating the logic for getting/setting the variable's value. Additionally, a separate parameter for attributes would remove the need to use a separate variable to store attributes for a another variable.

The approach I am considering is to add a new private attributes attribute to the variable that is a dict with corresponding var.get_attr and var.set_attr services to manipulate the attributes by key.

Attribute templates could then be added to allow for attributes to be updated whenever the variable's value updates. I envision attribute templates to be set via an attributes_template parameter that is a dict that maps attribute names to their templates.

At the moment, I don't have the cycles available to implement this feature properly, but I would happily consider pull requests from interested parties. This should be fairly straightforward to implement, if a bit tedious.

I can't get this to work

in my config I got:
var:
cpos:
friendly_name: 'curtainsposition'
initial_value: 30

in lovelace I got:
type: entities
entities:

  • entity: var.cpos

and it shows:
curtainsposition 0

What am I doing wrong?

How to install in hassio VDI?

If I do not have direct access to the folders in hassio VDI, how else may I install this? HACS also requires direct access to the file system.

Variables

How do I use the variable (0/1) in condition?
trigger:
condition:

  • condition: ???
    action:

Thank you for your response.
OldFedor, retiree.

Can't install v9

Hi there, like your integration, thanks!
But I can't update from v8 to v9. Not with 0.103.0bx and not with 0.103.0 release.

Incompatibility with .108 ?

Get this message

Invalid config
The following integrations and platforms could not be set up:

var
Please check your config.

Add a popup when you click the variable entity in Lovelace to set the value of the variable

Add a popup when you click the variable entity in Lovelace to set the value of the variable

I just assumed this functionality was already built-in, but if it is I couldn't find it. And if it's not in here, it would be extremely helpful. How else can an end-user set the value of a variable?

For example, I've been using a generic thermostat to store variables. When I click on the thermostat in Lovelace, I get this:

image

I can change the "temperature" to change my variable with the up/down arrows. For this project, all you need is a simple textbox and ok/cancel buttons. When the user clicks ok, you call the var.set service and pass in the value of the textbox.

Appdaemon doesn't recognize the var.set service

I am using appdaemon to set some variables using the var component and I can't get it to work.

If I look in the service list in the HA GUI, I see var.set and var.update. However, when I call call_service() with a service parameter of var.set, I get

2020-07-29 20:30:32.030875 WARNING sun: Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/appdaemon/threading.py", line 900, in worker
    funcref(
  File "/home/homeassistant/.appdaemon/apps/sun.py", line 28, in sunset
    self.call_service('var.set', entity_id='variable.sunset', value=localtime)
  File "/usr/local/lib/python3.8/dist-packages/appdaemon/utils.py", line 195, in inner_sync_wrapper
    f = run_coroutine_threadsafe(self, coro(self, *args, **kwargs))
  File "/usr/local/lib/python3.8/dist-packages/appdaemon/utils.py", line 299, in run_coroutine_threadsafe
    result = future.result(self.AD.internal_function_timeout)
  File "/usr/lib/python3.8/concurrent/futures/_base.py", line 439, in result
    return self.__get_result()
  File "/usr/lib/python3.8/concurrent/futures/_base.py", line 388, in __get_result
    raise self._exception
  File "/usr/local/lib/python3.8/dist-packages/appdaemon/adapi.py", line 1568, in call_service
    self._check_service(service)
  File "/usr/local/lib/python3.8/dist-packages/appdaemon/adapi.py", line 1449, in _check_service
    raise ValueError("Invalid Service Name: {}".format(service))
ValueError: Invalid Service Name: var.set

Has anyone verified that appdaemon works with this component?

Issue on HA 0.109

Hello,

I just installed home-assistant-variables 0.9.3 on my HA version 0.109.6.
I just created a test variable on my configuration.yaml :

var:
test:
friendly_name: 'Test'
initial_value: 20
unit_of_measurement: °C

But when I check the config before restarting HA, I have the following error:

Invalid Configuration
Component error: var - cannot import name 'make_entity_service_schema' from 'homeassistant.helpers.config_validation' (/srv/homeassistant/lib/python3.7/site-packages/homeassistant/helpers/config_validation.py)

Can you please help ?
Thanks

DB records into attribute array

It would be nice, when the content of a database table could be selected into an array of arrtibutes in a variable.
It would be also useful to add an optional db_url parameter to be able to use external database.

Like:
DB:

colA colB
cell1 cell2
cell3 cell4

Code:

var:
  db_table_to_attribute_array:
    db_url: db_url
    query: select colA, colB from table

Result:

data:
- colA: cell1
  colB: cell2
- colA: cell3
  colB: cell4

Assign a python result in a var

Hi
I have a simple python script
dt=datetime.now() datej="%02d/%02d/%04d %02d:%02d:%02d" % (dt.day,dt.month,dt.year,dt.hour,dt.minute,dt.second) print(datej)
And I want this print result to be assigned via var.set or var.update from one of my variable...
My variable is defined like
var: datep: friendly_name: 'Date detect move' initial_value: '-' icon: mdi:video
Is it possible ? How to proceed ?
Thanks for your help.

Can't set value template as state.attr

Hi,

I can use the var in an automation with for example:

  • value_template: "{{ states('sensor.heating') }}"
    works, no problem

but if change for
value_template: "{{ state.attr('sensor.heating','temperature') }}"

doesn't work..

maybe you can help?

Thanks,

No 'version' key in the manifest file for custom integration 'var'

At HA startup, the warning message appears:
WARNING (MainThread) [homeassistant.loader] No 'version' key in the manifest file for custom integration 'var'. This will not be allowed in a future version of Home Assistant. Please report this to the maintainer of 'var'

Explanation - please adjust the integration accordingly.

Variables never change from 0

I am a new Home Assistant user. I think Variables is just what I need, so installed v10.0 via HACS.

The definition of the variable in configuration.yaml seems to work because I can display it in LoveLace, and reference them in automations etc - but I can't get the value to change. I have set it with an initial_value, and also have an automation (that is triggering) that is using var.set - still zero.

(edited to format the code correclty)

var:
  pv_output_to_use:
    friendly_name: "PV output to use"
    icon: mdi:bug
    initial_value: 123
    value_template:
       "{{ 234 }}"


automation set_PV_power_in_test_mode:
  alias: "Set PV power in Test Mode"
  trigger:
    platform: template
    value_template: "{{ is_state('input_boolean.test_contactor', 'on') }}"
  condition:
    - condition: template
      value_template: "{{ is_state('input_boolean.test_mode', 'on') }}"  
  action:
    - service: var.set
      data:
        entity_id: pv_output_to_use
        value: 100

var.update fails

I use the var.update service in several automations to update time based variables. The automations have stopped work after updating Variable component to V0.9.1 last night. I try to preform var.update service under developer tools/services and received this message "Failed to call service var/update. mappingproxy() argument must be a mapping, not All" . I uninstalled Variable component, reboot, and reinstalled Variable component. I have attached a screen shot if it helps.

System:
Home Assistant 0.103.0
Ubuntu 18.04.3 LTS
Variable 0.9.1
HACS 0.18.1

For a work around, I have changed my automations to use var.set, force_update. This seems to be working.

Thank you.
Screen Shot 2019-12-12 at 8 59 23 AM

Friendly name

Redefining a friendly name to an existing variable does not change within HA. 'States' still shows the old name. Tried server restart, and reboot. Original Friendly_Name sticks.

Thanks.

record history attributes ?

Hi,
please allow me a question and not raise an issue...
I have been using the other CC for variables https://github.com/rogro82/hass-variables since forever, to record the history of events (like motion). Although it is against the philosophy of Paulus/Balloob, who feels we shouldn't abuse the HA state machine for recording this, it does fill a gap HA doesnt provide.

I was wondering if your variable CC can do the same. If so, I probably would migrate, since you are still developing your CC, and @rogro82 seems to have abandoned ship.

below is the declaration. of a variable, and an automation updating is upon motion:

variable:
  outside_motion:
    value: No motion detected
    restore: true
    attributes:
      icon: mdi:exit-run
      friendly_name: Outside Motion

automation:
  - alias: Update Outside Motion
    id: Update Outside Motion
    trigger:
      platform: state
      entity_id:
        - binary_sensor.backdoor_buiten_sensor_motion
        - binary_sensor.driveway_buiten_sensor_motion
        - binary_sensor.garden_backyard_buiten_sensor_motion
        - etc etc
      to: 'on'
    condition:
      >
        {{trigger.to_state is not none and
          trigger.from_state is not none and
          trigger.to_state.state != trigger.from_state.state}}
    mode: restart
    action:
      - delay:
          seconds: 2
      - service: variable.set_variable
        data:
          variable: outside_motion
          attributes:
            history_1: "{{states('variable.outside_motion')}}"
            history_2: "{{state_attr('variable.outside_motion','history_1')}}"
            history_3: "{{state_attr('variable.outside_motion','history_2')}}"
            history_4: "{{state_attr('variable.outside_motion','history_3')}}"
            history_5: "{{state_attr('variable.outside_motion','history_4')}}"
            history_6: "{{state_attr('variable.outside_motion','history_5')}}"
            history_7: "{{state_attr('variable.outside_motion','history_6')}}"
            history_8: "{{state_attr('variable.outside_motion','history_7')}}"
            history_9: "{{state_attr('variable.outside_motion','history_8')}}"
            history_10: "{{state_attr('variable.outside_motion','history_9')}}"
          value: >
            {{trigger.to_state.name|replace(' buiten sensor motion','')}}:
            {{as_timestamp(trigger.to_state.last_changed)|timestamp_custom('%X')}}

please have a look to see if, and if yes how I could adapt this to your integration?
thanks if you would!

Example how to store and retrieve dictionary

Per another issue posted here, one is supposed to be able to store not just a string but also, for example, a list or a dictionary for value.
I've been trying to do this, but unable to then retrieve it.

I've tried:

  initial_value: "{'value': 0, 'day_value': 0, 'date': -1}"
  initial_value: {'value': 0, 'day_value': 0, 'date': -1}
  initial_value:
    value: 0,
    day_value: 0
    date': -1

{{ states(test).state }}
returns what seems to be a string:
OrderedDict([('value', 0), ('day_value', 0), ('date', -1)])
Trying to retrieve for example date with:
{{ states(test).state.date }}
returns nothing.

Using:
{{ states(test).state['date`] }}
also nothing.

{{ states(test).state[0] }}
Returns: O

{{ states.var.test.state is string }} returns True

So it seems what is being returned is a string and not a dictionary.

What am I doing wrong?

Using variables - new user of Home Assistant - help required please

I need help please.
I am a newbie to Home Assistant so if this method of requesting help is an inappropriate thing to do please accept my apologies.
I am trying to use your variables as data to a service call but I just am not getting the result I need.
I wonder if you could please advise what I’m doing wrong.
I have included two of the service calls in the scripts.yaml. The one in bold tries to use the variables to give the same result as the one not bold.
The "lounge_tv_channel_8 works fine and an 8 is sent to my TV. The "lounge_tv_channel_9" with the variables does not work.
I can see the variables in my overview and they are set to the correct values.
problem.txt
I get the following error in the log
"Logger: homeassistant.helpers.service
Source: helpers/service.py:447
First occurred: 14:24:39 (2 occurrences)
Last logged: 14:45:21

Unable to find referenced entities var.which_remote"

How to store attributes?

Hello,

I'm now on my way to 50 variables and would like to move some of the values to attributes (I use Node Red), is this a possibility? It would GREATLY reduce the number of variables I require.

Thanks in advance.

Error during setup of component var with HA 0.108

The component is unable to be loaded at startup when using HA 0.108 beta.

Error during setup of component var
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/setup.py", line 171, in _async_setup_component
    hass, processed_config
  File "/config/custom_components/var/__init__.py", line 105, in async_setup
    await component.async_setup(config)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 131, in async_setup
    await asyncio.gather(*tasks)
  File "/usr/src/homeassistant/homeassistant/helpers/entity_component.py", line 229, in async_setup_platform
    self.hass, self.config, self.domain, platform_type
  File "/usr/src/homeassistant/homeassistant/setup.py", line 230, in async_prepare_setup_platform
    integration = await loader.async_get_integration(hass, platform_name)
  File "/usr/src/homeassistant/homeassistant/loader.py", line 323, in async_get_integration
    Integration.resolve_from_root, hass, components, domain
  File "/usr/local/lib/python3.7/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/src/homeassistant/homeassistant/loader.py", line 156, in resolve_from_root
    manifest_path = pathlib.Path(base) / domain / "manifest.json"
  File "/usr/local/lib/python3.7/pathlib.py", line 920, in __truediv__
    return self._make_child((key,))
  File "/usr/local/lib/python3.7/pathlib.py", line 699, in _make_child
    drv, root, parts = self._parse_args(args)
  File "/usr/local/lib/python3.7/pathlib.py", line 653, in _parse_args
    a = os.fspath(a)
TypeError: expected str, bytes or os.PathLike object, not NoneType

Question about using secrets in variables

Hi there,

I was wondering if it is possible to secrets as values with this component?

I've tried something like this:

var:
  my_var1:
    value_template: !secret some_password

but when I check the var.my_var1 state via developer tools it contains a value of "unknown" ...

This would be quite useful as then it would be possible to pass/access some secrets from templates via states object.

Variable stored as a string - but need it as a datetime

Hi,
I'm trying to store a datetime variable using your integration.

Unfortunately, it seems to be stored as a string instead of a datetime which make impossible the use of relative_time() function in template.

Variable code:

var:
  last_check_internet_status:
    icon: mdi:router-wireless

Automation code (service part) - I tried both ways:

- service: var.set
    data:
      entity_id: var.last_check_internet_status
      value_template:  "{{ now() }}"
- service: var.set
    data_template:
      entity_id: var.last_check_internet_status
      value: "{{ now() }}"

This template won't work because it's a string, not a datetime object.

{{ relative_time(states('var.last_check_internet_status')) }}

Please let me know if I'm doing something wrong or if you can provide a workaround/improvement to this ?

Thanks

Accept string or list for `tracked_event_type`

For parity with tracked_entity_id, tracked_event_type should accept a string that denotes either a single event type or multiple event types separated by commas.

Examples:

# single event type as string
tracked_event_type: 'foo_event'

# multiple event types as string 
tracked_event_type: 'foo_event,bar_event'

# one or more event types as a list (already supported)
tracked_event_type:
  - 'foo_event'
  - 'bar_event'

Using !include folders

Does this component allow the use of include folders to allow splitting configuration out to separate files? I've tried what I think should work and it appears not, but maybe I'm doing it wrong.

If, in configuration.yaml, I have:

var:

  min_temp_var:
    friendly_name: 'Overnight Minimum'
    icon: mdi:thermometer-low
    tracked_entity_id: sensor.outside_temp
    unit_of_measurement: '°C'
    value_template: >
      {% if float(states('sensor.outside_temp')) < float(states('var.min_temp_var')) %}
      {{float(states('sensor.outside_temp'))}}
      {%- else -%}
      {{float(states('var.min_temp_var'))}}
      {%- endif %}

  max_temp_var:
    friendly_name: 'Daytime Maximum'
    icon: mdi:thermometer-high
    tracked_entity_id: sensor.outside_temp
    unit_of_measurement: '°C'
    value_template: >
      {% if float(states('sensor.outside_temp')) > float(states('var.max_temp_var')) %}
      {{float(states('sensor.outside_temp'))}}
      {%- else -%}
      {{float(states('var.max_temp_var'))}}
      {%- endif %}

It works as expected, but having:

var: !include_dir_merge_list var

in configuration.yaml and adding the code from min_temp_var: onwards (keeping same indentation) to a file called min_max_temp.yaml in a folder 'var' under the folder 'config', I get 'Setup failed for var: Integration failed to initialize.' in the log and a notification of the same.

HomeAssistant 0.103.4 hassio install on RPi3
variable v0.9.2 via HACS

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.