#templates-archived
1 messages ยท Page 166 of 1
if your interested in sorted listing those in the frontend, you can also let the frontend do the work for you in an auto-entities filter. filter: template: > {% set threshold = states('input_number.battery_alert_level')|float(0) %} {% for s in expand('group.battery_sensors_auto') if s.state|float(0) < threshold %} {{s.entity_id}} {%- endfor %} sort: method: state numeric: true
that auto group is nothing more than an automation creating that at startup: action: service: group.set data: object_id: battery_sensors_auto entities: > {{states.sensor|selectattr('attributes.device_class','eq','battery') |map(attribute='entity_id')|list}} so if you wish, you could also use that in the filter
btw, seems that automation does not error without the | selectattr('attributes.device_class', 'defined') though the template editor does
Had a 2nd look, now using one for loop
{%- set threshold = 30 -%}
{%- set ns = namespace(states=[], format=[]) -%}
{%- for state in states.sensor
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'battery')
| selectattr('state', 'is_number') -%}
{%- if state.state | int < threshold -%}
{% set name = state.name | replace(' battery', '') | replace(' Battery', '') %}
{% set state = state.state | int %}
{% set ns.states = ns.states + [dict(name = name, state = state)] %}
{% set index = (ns.states | sort(attribute='name') | sort(attribute='state') | map(attribute='name') | list).index(name) %}
{% set ns.format = ns.format[:index] + [name ~ ': ' ~ state ~'%'] + ns.format[index:] %}
{%- endif -%}
{%- endfor -%}
{{ ns.format | join(', ') }}
The battery entities with the same state are also sorted by name
- trigger:
- platform: time
at: '05:00:00'
- platform: numeric_state
entity_id: sensor.outside_home_thermometer_temperature
below: sensor.outside_min_temp
sensor:
- name: "Outside Min Temp"
unit_of_measurement: "ยฐC"
device_class: temperature
availability: "{{ not is_state('sensor.outside_home_thermometer_temperature', 'unavailable') or is_state('sensor.outside_home_thermometer_temperature', 'unknown') }}"
state: '{{ states(''sensor.outside_home_thermometer_temperature'') }}'
``` at 5am it registered the temp at 13.9 which is fine but then at 6:23am sensor.outside_home_thermometer_temperature went to 11.3 but my sensor did not change the state to 11.3
I see no reason why it didn't work. Unfortunately there is no such thing as a trace for the trigger based template sensors, so there is not much I can do further
You could replicate it in an automation using an input_number, so at least you can see if it triggers when it should
okay thanks - I'll give that a go ๐
would the trigger in the automation be:
platform: numeric_state
entity_id: sensor.outside_home_thermometer_temperature
below: '{{ states('input_number.outside_min_temp') }}'```
no just below: input_number.outside_min_temp
no error anymore ๐
geez... the error was in the action part
hehe
is this still the best way to get the number of minutes of uptime? {{((now().timestamp()-as_timestamp(states('sensor.uptime')))/60)|int}}
tried the today_as() (which I still have not used...) but didnt see the correct use for it in this case
in fact, I only need this to set a condition in certain automations to not fire unless minutes is >1
For that specific use case I would use {{ (now() - as_datetime(states('sensor.uptime'))).seconds > 60 }}
nice yes. thx!
that would translate to a dedicated uptime minutes sensor like: {{ ((now() - as_datetime(states('sensor.uptime'))).seconds/60)|int }} and then allow me to do: condition: condition: numeric_state entity_id: sensor.ha_uptime_minutes above: 1
Yes, that should work
although that will only be true after 2 minutes, as 1 is not above: 1
I stole from here a while ago and have:
{{ ( now() - states('sensor.uptime')|as_datetime ).seconds }}
as a template sensor
I believe this also works:
{{ (( now() - states('sensor.uptime')|as_datetime ).seconds / 60) | round }}
(at least it does in my template editor)
Hey guys, I'm experiencing and odd issue with a bayesian sensor. It seems to turn off for the the tiniest milisecond, when a "state" platform observation turns off, even though the sensor itself is way above the treshold probability:
https://i.imgur.com/jDXfvqj.png
Even though it's only off for an insurmountable short time, it still triggers whatever follows in my automation to turn off accordingly. Any ideas?
- platform: "bayesian"
name: bathroom_is_occupied
prior: 0.06
probability_threshold: 0.35
observations:- platform: "state"
entity_id: binary_sensor.samjin_motion_b26e1201_ias_zone
to_state: "on"
prob_given_true: 0.99 - platform: "numeric_state"
entity_id: "sensor.bathroom_movement"
prob_given_true: 0.92
above: 0
- platform: "state"
Both the observations above are enough to stay above the probability threshold, and they are active at the same time, but when the "state" observation with the ias_zone turns off, it still triggers the entire sensor to turn off for this infinitesimally short amount of time
is there any way to get {{(states('input_text.discord_family_channel')) | string }} to return a string if the text is numerical?
Well, it already is a string, and you're casting it to a string
But in developer tools it's showing giving "result type: number"
And the automation doesn't work because it says it wants a string for the target attribute
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
My guess is that you didn't surround the template in quotes
hmm. That seems to have solved it. I'd tried with and without quotes, so I'm not sure what else I had wrong in previous testing. It works now. (without the | string as well.
I figured it out I think:
state: "{{ states('sensor.outside_home_thermometer_temperature') }}" instead of
state: '{{ states(''sensor.outside_home_thermometer_temperature'') }}'
hello!
{{ state_attr('light.kantoor', 'brightness' ) / 2.55 if is_state('light.kantoor', 'on') else 'Off' }}%
{{ states("sensor.temperatuur_kantoor_temperature") }} ยฐC
Output:
Result type: string
100.0%
26.57 ยฐC
how do i trim the string of the 100.0%
And the% stays there if its off -.-
{{ (state_attr('light.kantoor', 'brightness' ) / 2.55) | int ~ '%' if is_state('light.kantoor', 'on') else 'Off' }}
thanks! Gonna try to understand this!
Might be better to change | int to | round(0)
~ concatenates the parts on both sides as strings
done ๐
anyone can link me to a good guide about templating, specifically i have like 7 rooms requiring motion detection (conditions and triggers). I would rather not write up / gui input all the same conditions and triggers (other than the sensor entity obviously)
referring to automations
Thanks! I'll take a look at this
{{ now() > (states.binary_sensor.garage_motion_sensor.last_changed + timedelta(minutes=3)) }}
why does that throw an error in the condition tester? It says "template value should be a string ... got None"
see first pinned message
Looking for a simple option to show lights on at the moment, p.s im totaly new so im using only ui and no yaml at the moment
it's a simple template
{{ states.light|selectattr('state', 'eq', 'on')|map(attribute='name')|list }}
ok how where to enter it and how to use it ? like i understand that i have to replace the entity_id with my entity id but thats all ๐
what are you trying to do with it?
im trying to make a dashboard and on top of it i will have a chip who shows couple things that are open
yep its the mushroom thing
anyway, you're talking about a #frontend-archived topic now
and I have no experience with the mushroom card suite
oh ok, ill just try my luck there then ๐
a variant of the template I provided above is the starting point
- platform: time
at: "05:00:00"
- platform: state
entity_id: sensor.outside_home_thermometer_temperature
- condition: numeric_state
entity_id: sensor.outside_home_thermometer_temperature
below: sensor.outside_min_temp
sensor:
- name: "Outside Min Temp"
unit_of_measurement: "ยฐC"
device_class: temperature
availability: "{{ not is_state('sensor.outside_home_thermometer_temperature', 'unavailable') or not is_state('sensor.outside_home_thermometer_temperature', 'unknown') }}"
state: "{{ states('sensor.outside_home_thermometer_temperature') }}"
is it possible to have conditions? like above
no
first, conditions don't belong in the trigger, and second, you cannot use conditions in template sensors
is there another way?
Thanks ๐
haha I like your request better
- trigger:
- platform: time
at: "05:00:00"
- platform: state
entity_id: sensor.outside_home_thermometer_temperature
sensor:
- name: "Outside Min Temp"
unit_of_measurement: "ยฐC"
device_class: temperature
availability: "{{ not is_state('sensor.outside_home_thermometer_temperature', 'unavailable') or not is_state('sensor.outside_home_thermometer_temperature', 'unknown') }}"
state: "{{ iif (states('sensor.outside_home_thermometer_temperature') < states('sensor.outside_min_temp'), states('sensor.outside_home_thermometer_temperature'), states('sensor.outside_min_temp')) }}"
I'm having problems with my value template when a key contains a - character. What should my value template look like? https://pastebin.com/HDAH8MuZ
{{ temp_json["acpitz-acpi-0"].temp1.temp1_input }}
how can I make this trigger at 05:00:00 regardless if sensor.outside_home_thermometer_temperature is less than sensor.outside_min_temp
I just want it to do
state: "{{ states('sensor.outside_home_thermometer_temperature') }} "
at 05:00:00 but every other time
state: "{{ iif (states('sensor.outside_home_thermometer_temperature') < states('sensor.outside_min_temp'), states('sensor.outside_home_thermometer_temperature'), states('sensor.outside_min_temp')) }}"
Add trigger ids and use those in yourstate template
I've never used trigger ID's before - where should I start?
I'd love to see some examples ๐
well I have in automations with CHOOSE but not for template sensors
The idea is the same, but now you use them in your if statement
state: "{{ iif (trigger.id == 'whale' or states('sensor.outside_home_thermometer_temperature') < states('sensor.outside_min_temp'), states('sensor.outside_home_thermometer_temperature'), states('sensor.outside_min_temp')) }}"
- trigger:
- platform: time
at: "05:00:00"
id: whale
ahh so I only need a trigger id on one of them
Change whale in both places to something to like
You only need to identify that one
- trigger:
- platform: time
at: "05:00:00"
id: 5am
- platform: state
entity_id: sensor.outside_home_thermometer_temperature
sensor:
- name: "Outside Min Temp"
unit_of_measurement: "ยฐC"
device_class: temperature
availability: "{{ not is_state('sensor.outside_home_thermometer_temperature', 'unavailable') or not is_state('sensor.outside_home_thermometer_temperature', 'unknown') }}"
state: "{{ iif (trigger.id == '5am' or states('sensor.outside_home_thermometer_temperature') < states('sensor.outside_min_temp'), states('sensor.outside_home_thermometer_temperature'), states('sensor.outside_min_temp')) }}"```
where in that does it tell it to do "states('sensor.outside_home_thermometer_temperature')" when its 5am?
Yes, but you can simplify your availability template to "{{ states('your.sensor') | is_number }}"
At 5:00 that trigger will be the one triggering, so trigger.id == '5am' will be true
So it will pick that option of the iif
helping out in https://community.home-assistant.io/t/detection-how-long-someone-is-in-a-zone/434382/3 but wondering what the answer to my efficiency question. is... is this the quickest: {{(now() - states.person.xxx.last_changed).total_seconds()|timestamp_custom('%X') }} ?
(now() - states.person.xxx.last_changed) = already a timedelta
(now() - states.person.xxx.last_changed).strftime('%X')
no need to juggle with things
oh wait
that doesn't work with timedelta's ๐ฆ
good morning Frenck
that might be it actually, not sure if it can be made simpler
You can use seconds instead of total_seconds()
No?
seconds is limited to max a day
while total_seconds() is the whole timedelta represented as seconds
when doing conversions like these, I would say one should use total_seconds()
thx for confirming.
1 more detail please. I expanded it with a test to do: {% set zones = states.zone|map(attribute='name')|list %} {% set id = 'marijn' %} {% if states('person.'~id) in zones or is_state('person.' ~id,'home') %} to check if person is in a zone. In my config, 'home' is not the name of my zone home so I added that extra line. would have hoped something like states('person.'~id) in [zones,'home'] would be possible, but that doesnt work. Can that be done differently?
so, either be in the list zones or in 'home'
hi all. im trying to create an input boolean for summer or winter. i want to use it for a conditional card in lovelace. whats the best approach to define a period based on month of year?
maybe i should use something else and not a boolean for this?
create a template binary
yes, define any relevant period for you in the template, check if it is now, on, true, and use that in the conditional card as entity
thx so much ! @floral shuttle , do you perhaps have an example yaml you can share to get me started?
- unique_id: wintertijd_binary
name: Wintertijd
picture: /local/season/winter.png
state: >
{{now().timetuple().tm_isdst == 0}}
- unique_id: christmas_time
name: Christmas time
state: >
{% set today = now().day %} {% set month = now().month %}
{{month == 12 and today >= 24 or month == 1 and today <= 2}}
I have these even as trigger based templates, because with that their updating it limited to the trigger you define (and not per each minute). As such they go under:```
template:
-
trigger:
- platform: time_pattern
hours: 0
minutes: 0 - platform: homeassistant
event: start - platform: event
event_type: event_template_reloaded
binary_sensor:
- platform: time_pattern
cool thats very helpful! thx @floral shuttle !
Is it possible to crate a sensor that automatically includes all sensors of a specific type? I want a simple sensor that tells me if any of my Twitch channels goes live, and don't want to add them manually to a list (because I will forget to add them to both places).
that would probably be possible yes. What did you try and didnt work out?
in (zones + ['home'])
sweet! thank you very much!
can rewrite: {{trigger.to_state.state in ['home','not_home'] or trigger.from_state.state in ['home','not_home'] or trigger.to_state.state in zones or trigger.from_state.state in zones}} at least to {{trigger.to_state.state in (zones,['home','not_home']) or trigger.from_state.state in (zones,['home','not_home'])}}
maybe even:{% set location = (zones,['home','not_home']) %} {{trigger.to_state.state in location or {{trigger.from_state.state in location }} ?
need to test if I need to quote the (zones,['home','not_home']) in the set location line.
or, maybe this would even be easier: {% set location = states.zone|map(attribute='name')|list + ['home','not_home'] %} {{trigger.to_state.state in location or trigger.from_state.state in location}}
I would go for that one indeed
I could use a hand
template:
- sensor:
- name: combined_power_usage_kwh
unit_of_measurement: kWh
device_class: energy
state_class: total_increasing
attributes:
reject_this_sensor: >-
{{ 'true' }}
state: >-
{% set pwr = states.sensor
| rejectattr('state','in',['unknown','unavailable'])
| selectattr('attributes.unit_of_measurement', 'defined')
| selectattr('attributes.unit_of_measurement', 'eq', 'kWh')
| map(attribute='state') | map('float') | list %}
{{ pwr | sum }}
I try to put every energy sensor I have and will have in a template.
Current implementation has just one downside, it includes itself
An idea how I can get around it? Tried rejectattr('attributes.reject_this_sensor', 'eq', 'true') but that will let the template fail
Why not rejectattr('name', 'eq', 'combined_power_usage_kwh') ?
because I did'nt crossed my mind ๐
Start simple ๐
tryed to, but used entety_id instead of name or | rejectattr('friendly_name','eq','combined_power_usage_kwh') ๐คฆโโ๏ธ Noice that it can be so easy
yaaay Works! thanks โค๏ธ
rejectattr('name', 'eq', this.name) will always work, even if you change the name of the entity
As friendly_name is an attribute, you need to use atrributes.friendly_name
This fails because the state template is rendered before the attribute templates are, so the attribute does not exist yet
Great!, very much appreciated!
does anyone happen to have a template to filter all the attributes of a particular entity? I had something like that around but it got lost over time
What do you exactly mean here? Filter all the attributes?
well, more like list all, to have a reference for jinja
states.your.entity.attributes.items()
Got a pointer for me where you found this.name, I guess there is a hell lot more
The release notes, but it is also in the template docs https://www.home-assistant.io/integrations/template/#self-referencing
ouch.. they gotten a whole lot longer since I checked them the last time ๐ Thanks a ton, this should give me good options to brake stuff
uh, so new! ahead of times
Hello all, I am FAR from a programmer so be gentle with me, having an issue or potential issue with some 433mhz door switches, most on doors, one on a cover(garage door). When i edit my configuration.yaml file in Studio Code Server, I see errors. As of now, they still work but I'm assuming it's part of a planned breaking change so I'm trying to get a jump on it. The error says, String does not match the pattern of "DEPRECIATED" I've tried everything I can think of and can see on the templating help areas, MQTT binary sensors etc. Will try to screen shot or paste some code
@deft sail posted a code wall, it is moved here --> https://hastebin.com/umipakohur
- trigger:
- platform: time
at: "05:00:00"
id: 5am
- platform: state
entity_id: sensor.outside_home_thermometer_temperature
sensor:
- name: "Outside Min Temp"
unit_of_measurement: "ยฐC"
device_class: temperature
availability: "{{ states('sensor.outside_home_thermometer_temperature') | is_number }}"
state: "{{ iif (trigger.id == '5am' or states('sensor.outside_home_thermometer_temperature') < states('sensor.outside_min_temp'), states('sensor.outside_home_thermometer_temperature'), states('sensor.outside_min_temp')) }}"
My lowest temp today was 8.2 but this template now shows 10 which was the temp a few minutes ago - I am not sure how that happened as 8.2 < 10.
it triggered at 5am perfectly and was 9.6 - then at 6:58 the temp dropped to 8.2 and the template above set the sensor to 8.2 but then at 10:04am the temp went to 10am and the template sensor changed it state to 10 even though it should have just stayed 8.2?
You are doing a string comparison, and "10" < "8.2" is true, because 1 is lower as 8
Convert the values to floats in your comparison
state: "{{ iif (trigger.id == '5am' or states('sensor.outside_home_thermometer_temperature') | float < states('sensor.outside_min_temp') | float, states('sensor.outside_home_thermometer_temperature'), states('sensor.outside_min_temp')) }}"
@sacred sparrow
ah that makes sense - thank you ๐
I think I've bothered you with this template sensor for 3-4 days now - I really appreciate it
No problem
Check out the breaking changes for MQTT this month.
selecting all domain group entities works with {{states.group|map(attribute ='entity_id')|list}} Trying to do that with the integration_entities like {{expand(integration_entities('group'))|selectattr('domain','eq','group')|list}} doesnt..
I need to select the domain because otherwise it adds all other domains obviously
{{integration_entities('group')|select('search','group')|list}} feels like a hack..and it doesnt result in a correct list of groups, if the string is in the object_id.
how should I adapt the integration_entities template to only show domain group entities?
The group integration covers all domains
Thatโs why you have to filter the domain after
sure, I understand that, it just doesnt work.. the result is []
yes, because the group integration doesn't supply group entities
the integration entities only work with new integrations. The old group entities fall under 'not showing up' under integration entities as they aren't set up using config flow.
hmm, if I do plain {{integration_entities('group')}} I get my group entities of domain group, with all other domains
yes they are yaml groups, but still show in the integration_entities. My hope was to only show those. My believe was they need a unique_id (which they all have) to show
and heck, I tried it with domain light {{expand(integration_entities('group'))|selectattr('domain','eq','light') |map(attribute='entity_id')|list}} and this results in a list of all light entities. So, not integration_entities('group') at all ..
whats even more remarkable: there's not a single grouped light in that listing!
so it does find the grouped light groups created via the UI, and effectively expands those to a list of single lights. It cant however return all grouped light groups?
ah, then the problem is that group entities are expanded into their sub entities
Apparently they fixed how entities were added into config entries. For a long time, yaml entities did not "show their integration" under the hood
I wrongly assumed that was the issue
Yeah well, itโs a mixed thing currently so I wrote up https://github.com/home-assistant/core/issues/74058 and hope to get this fixed
there's nothing to fix though
expand always recurses into groups and expands them
just do expand on a single group entity
you'll see the ending result does not contain the group
@floral shuttle
by design
Yes thatโs what this boils down to: if you want a list of domain group entities, you need to use the states.group format
I still would love to understand why the integration_entities() on its own does show the yaml groups but we can not not filter those
because it's a list of entity_id's
and when you expand a group, the group entities are expanded....
it's not 'integration_state_objects', it's 'integration_entities'
Hehe that would be nice though
i.e. you get a list of strings, that are the entity_id's
I have this template:
{% set new_level = trigger.to_state.attributes.brightness|int %}
{% if 0 < new_level < 10 %}
10
{% elif 80 < new_level < 100 %}
150
{% else %}
{{ new_level }}
{% endif %}
The first part (between 0 and 10) works, but the high end does not. The target entity is set to levels higher than 150...
What am I doing wrong?
@thorny snow Not sure what the trigger is and what the target is. Are they the same light?
But if you set the trigger entity to any brightness other then 1 - 9 or 81 - 99 , it will just use the brightness of the trigger entity, so this can go up to 255
Hello everyone, I need some help with parsing an MQTT string from a motion sensor. Basically, I have a PIR sensor that replies in MQTT.
I want to set it up as a binary sensor so I added the following
name: Wemos passive infrared motion sensor
state_topic: "tele/Wemos_D1_V3.0_Test_bench/SENSOR"
value_template: '{{ value_json.Switch7 }}' ```
to my binary_sensor.yaml
Thanks! I figured it out... I thought that the trigger used brightness (1-255) but it used brightness percent... All good now! ๐
Problem is, the reply I get is ACTION:ON or ACTION:OFF, which can't work as a binary sensor
how can I get it to only reply with switch7 and on or off, so the binary will work?
the full MQTT string from tasmota is "stat/Wemos_D1_V3.0_Test_bench/RESULT = {"Switch7":{"Action":"OFF"}}"
value_json.Switch7.Action
ok, thank you
I think I tried that, but got an error. Maybe I did something else wrong then
Than worked, thank you.
Can I just keep piling on the variables after the dot, if I have even longer strings?
Will something like "value_json.Switch7.Action.Result.Data.Whatever" work if the string is this long?
You're indexing into a dict
If that's the data structure, yes.
It's important to understand what that's doing
Yeah, I'm trying to understand the documentation, I just though it only accepted one variable after the dot, for some reason.
Thank you for the explanation
{% set value_json = {"Switch7":{"Action":{"Result":{"Data":{"Whatever":7}}}}} %}
{{ value_json.Switch7.Action.Result.Data.Whatever }}
-> 7
you can test this in
-> Templates
Is there a means of getting last_value from an entity in templating?
Faking a cover and only have contact sensor on the top and bottom.
My idea is to do something like (in psuedocode):
{% if last_state was open %}
opening
{% elseif last_state was closed %}
closing
{% endif %}
Not like that, but you can with a trigger in an automation or template sensor
trigger.from_state.state
I'll go that route, cheers mate!
Thanks, and I did, and for a minute I thought I had something but no such luck. I guess I can't find any examples close enough to anything I have to get things working. I listen to the top tele/Tasmota_RF2/# and when I open my door switch, I see the message {
"Time": "2022-06-27T21:49:52",
"RfReceived": {
"Sync": 14070,
"Low": 470,
"High": 1400,
"Data": "6E3E0A",
"RfKey": "None"
}
}, but U'm lost on how to get the rest working. I guess if all else fails I can wimp out and order a bunch of zigbee door swiches, but I liked the $3 mqtt switches and up till now they worked fine. Actually they still do but not for long I guess
Hello! I get an error and I would like which integrations is from. I don't have a template with this value query.
2022-06-28 10:12:56 ERROR (MainThread) [homeassistant.helpers.template] Template variable error: 'float object' has no attribute 'temp' when rendering '{{value_json["temp"].value}}'
Any tipps how to debug this?
Going a little crazy trying to configure something that should be simple. I have a button and clicking on it is calling a script, I want to include some arguments when I call the script to be used as variables inside the script.
action: call-service
service: script.start_music
data:
myMessage: The light is on!
Script
service: system_log.write
data:
message: '{{ myMessage }}'
But myMessage always evaluates to empty, I've tried sending the data via the variables format as well as the format posted above, which appears to be correct according to the documentation
you should read the docs instead of making assumptions ๐
action: call-service
service: script.start_music
service_data:
myMessage: The light is on!
data isn't valid for tap_action, service_data is.
Hold the phone on that
data might be valid now
depends on the version you are running
What assumption sorry?
Ah, I'm on 2022.6.6 I believe. I didn't see anything specific to tap_action, perhaps that is the problem
the assumption of data being a valid key
doesn't matter, looks like it's now valid
that must have changed in one of the last 2 versions
it's always been service_data and it always bites everyone in the ass
anyways, if that's not your problem, it's the capital M in myMessage
also, it could be your script because your script isn't a valid script, but it is a valid service call. Is that your entire script?
No just a snippet of the script - the script does run fine until the point that myMessage is required.
Are these keys case insensitive? re: your comment on the capital M
That's odd, though I'm not a python developer so not too sure.
I can confirm that service_data does work, with the key myMessage
so you'd have to change both your tap action and your script to have mymessage
ok
you're on 2022.6.6 for sure?
This was the documentation I read up on: https://www.home-assistant.io/integrations/script/#passing-variables-to-scripts
Which doesn't mention service_data unfortunately - perhaps why it is catching people up
you need to read the tap-action documentation
for the UI
core-2022.6.6 Yep
tap-action is not the same as a script action
Ah I didn't know that - perhaps we can add a note in the script documentation to mention the difference when calling from the UI and link to that perhaps
Got it
You're welcome to suggest an edit
Done, thanks for the help
np
are you 100% sure you're on 2022.6.6 and data did not work and service_data did work?
the version I copied above I took directly from my settings page, I just updated from 2022.4.x about a week ago. And yes as soon as I tweaked it to use service_data then I saw that the message showed in the logs. I cleared the log and ran a second test to be sure and then changed back to data and another test showed it stopped working then
๐คท
sounds like you found a bug then
are you willing to write up an issue on the frontend for this?
Hmmm, that would be odd. I can look into it further in the morning
I think you have enough info
Yeah, first I will do some looking around - I may step through the frontend code.
write the issue up here -> https://github.com/home-assistant/frontend/issues
I'm not particularly familiar with the code base but here's an opportunity to get to know the frontend
FYI, service_data was changed to data in 2022.6.x
Interesting - do you know where the change was centrered? Was this a change in the backend as well, or just how the frontend works with it
Just keep in mind scripts are wierd in the backend
if you call a script with variables using the script.turn_on service call, you need to provide the data like this:
service: script.turn_on
target:
entity_id: script.xyz
data:
variables:
myvariable: xxx
where as, if you call it via the script itself, you do not
service: script.xyz
data:
myvariable: xxx
Yes I gave that a good go while I was debugging earlier trying to find the right format
so, if you want to, you can add the following tap actions to your testing
action: call-service
service: script.xyz
data:
variables:
myvariable: xxx
action: call-service
service: script.turn_on
data:
entity_id: script.xyz
variables:
myvariable: xxx
OK - got it. It was me being new to custom components. I had written this in YAML and not considered how this may get configured via the YAML. I was using a custom component that I did not update, so it must have been expecting service_data before the update. I hadn't thought to look at what I was actually configuring in the end
I'd naively looked at the data payload as just a dynamic object but I guess it was validating or parsing it and obviously not happy with data
I have learned my lesson there I suppose
well custom stuff is the wild wild west and they typically don't use the built-ins from HA
which means they need to keep it up with HA instead of utilizing HA updates
what's the custom element?
mushroom-entity card
ah, i'd just write up an issue with that
they probably don't know about it
it's been service_data for 5 years at this point
Actually it looks like I just need to update it which I will do
Hey Petro, I know thefes helped me with this but not sure if you could help explain why after 20:00 next start is 05:30 when it should be 00:00. I assume it's something to do with 00:00. Next start works correctlt for all other times. Right now it's 08:11 and next start is 15:00
https://dpaste.org/zCF4W
It's because of the default I used
Oh you are here lol.
Your data didn't have a start at midnight, that was only added because the day starts then
So I made the default pick the 2nd item in the list instead of the 1st
{{ (hours[index + 1] | default(hours[1]))[0] }}
There
If you change hours[1] to hours[0] it will start at midnight
{{ (hours[index + 1] | default(hours[0]))[1] }}?
The default itself is still needed, because [index + 1] will fall if the current time is the in the last time block
Makes sense. So a having a 12am is a must if I am to change this {{ (hours[index + 1] | default(hours[1]))[0] }} to selecting the first number?
{{ (hours[index + 1] | default(hours[0]))[1] }} is that correct?
Yes, correct
Sounds good thank you as always. I'll note that and use that.
๐
I missed that! Thanks for pointing it out
I had no clue it was changed until I went and looked at the docs
It wasn't covered in the RN
It was annoying, so I'm all for the change
yep
trying to smarten up some templates I was wondering if we have the means to make this shorter:```
{% set x = ['unavailable','unknown'] %}
{{trigger.to_state.state not in x and trigger.from_state.state not in x
this is a bit tricky, because we still need to use things like trigger.event.data.service_data.message I guess, and, most users using custom:button-card will start to get confused, as that still uses the 'old' way of calling the service_data iirc
event data never contains the word service_data unless you set that up an event that way..
i mean: trigger: platform: event event_type: call_service event_data: domain: persistent_notification service: create action: service: notify.system data: message: > {% set message = trigger.event.data.service_data.message %} etcetc
Yes, but that's the call_service event
sure. I just did a service_data full config search and this came up ๐
right but that's not changing
so its a 'replace here, but not there' thingy
and has nothing to do with the frontends tap action
you think it would be more readable if it was replaced?
no!
so it would be trigger.event.data.data.message?
tbh, I didnt mind the service_data at all, as it was very clear what it stands for.
still, getting back to frontend services on buttons: it would be good if custom cards would adopt the same
Hey peoples..
I have 5 entities that have an attribute (MAC adress)
I'd like to create a template sensor for each that changes value depending what the attribute's state is.
I know how to do this with a large if-elseif structure, but I was wondering if any of you wizards knew a cleaner way to achieve this ?
it would be even easier if instead of: tap_action: action: call-service service: input_boolean.toggle service_data: entity_id: input_boolean.dst or now: tap_action: action: call-service service: input_boolean.toggle data: entity_id: input_boolean.dst we could do: tap_action: action: call-service service: input_boolean.toggle entity_id: input_boolean.dst but I believe we even need a target: there now. Or is that only backend. yes. o well
If each attribute maps cleanly to a state for your template sensor, just use a dictionary:
{% set sensor_state = {attribute_state1: sensor_state1, attribute_state2: sensor_state2..., attribhte_state5: sensor_state5}
{{ sensor_state[state_attr('entity.id', 'attribute')] }}
Fill in the blanks appropriately.
thanks !!! ๐
that doesn't work, you can't define a dictionary without using strings
try it, you'll see it produces an UndefinedError: 'attribute_state1' is undefined
Ah.. ๐โโ๏ธ
just put single quotes around attribute_state1, like this 'attribute_state1'
Yup that's what I meant. Petro's right!
perfect ๐
My weather sensor shows 3 states (Min, max and current temp) in the UI on dashboard. is there a way to make a template sensor that does the same?
{% set lights = expand(area_entities('my_area')) %}
{{ lights | selectattr('state', 'eq', 'on') | list | count > 0 }}
How can I filter out any entities that aren't lights in this expression?
Nevermind got it ๐
selectattr("domain", "eq", "light") did the job
You can define attribute in your template sensor : https://www.home-assistant.io/integrations/template/#attributes
if i have a sensor which result type is "number", how can i compare that?
my sensor has the value "136".
this here (correctly) returns "true"
{{ states("sensor.lumi_lumi_sensor_motion_aq2_d0a28e07_illuminance") < "150"}}```
however this here also (and its false) returns "true"
{{ states("sensor.lumi_lumi_sensor_motion_aq2_d0a28e07_illuminance") < '50'}}
you need to make a 'number' of that illuminance state, because currently it is a 'string' and you can not compare a string to a number. Right now you make a string out of the number and you're comparing 2 strings ๐
state: >
{{states('sensor.mean_outdoor_lux')|float(0) <
states('input_number.outdoor_low_lux')|float(0)}}```
so in you're case: {{states("sensor.lumi_lumi_sensor_motion_aq2_d0a28e07_illuminance")|float(0) < 50}}
thank you @floral shuttle . i tried with | float as well as | int, but somehow didnt use it correctly. - thanks for clarifying and your time ๐
trying to make humidity/temperature sensor to work on homekit
how? ๐
thank in advance
It's selecting the second time now for all times lol. Not sure why. I'm using
{{ (hours[index + 1] | default(hours[0]))[1] }} just as you said.
@lyric gazelle posted a code wall, it is moved here --> https://hastebin.com/xetecabexi
Hello,
I have never got around to learning to do my own templates, i have always reversed other peoples work, but not i am a bit stuck and wondering if anyone would have any tips for me.
I have setup a scraping to pull the current price from my profile at my energy company.
And i get the value back (but also contaning the price/kWh)
This is what i am getting though the API of the scraping tool and what i am "trying" to do with HA.
https://www.toptal.com/developers/hastebin/toviqatuze.less
Anyone got any suggestions, it would be greatly appriciated!
Cheers
so you're asking how to split that value and take out the kr/kWh bit?
@floral shuttle Yes, just getting the numbers out ๐
you do that with the split function, find it in the template docs and see if you can make it
use {{value_json[0].selection5.split(' kr/kWh ')[0]}} and see what happens
Thanks @floral shuttle , just to make sure ( you are refering to the Jinja docs right? )
what that does, it splits the value at the string between quotation marks, and next selects the first ([0]) item
Cool, thanks, rebooting HA now
why?
Loading the changes to the rest sensor?
Or did i miss something?
you can reload rest sensors in the Yaml dev tools, or by hitting 'c' (for the quickbar)and select rest
LOL! Cheers, missed that aswell ๐คฆโโ๏ธ
i feel this is probably pretty simple, but i'm trying to build a template filter that includes both a device state and a device class (All open doors / windows). Can anyone help? This obviously doesn't work as thing.* is from the state class
{% for thing in states %}
{% if thing.state == "on" and thing.device_class == "door" %}
{{ thing.entity_id}}
{% endif %}
{% endfor %}
I've seen examples where folks manage a group of devices so they only have to expand the group and filter on the attribute. Was hoping to keep this dynamic.
IE "{{ expand('group.doors_windows')|selectattr('state','eq','on')|list|count }}"
Thanks @floral shuttle it comes back with "unknown" unfortenetly, but i can try and read a bit of the docs also
add |selectattr('attributes.device_class','defined') |selectattr('attributes.device_class','eq','door')
Like this?
{% for thing in states %}
{% if thing.state == "on" | selectattr('attributes.device_class','defined')
|selectattr('attributes.device_class','eq','door') %}
{{ thing.entity_id}}
{% endif %}
{% endfor %}
did you test it?
yeah, nothing atm. validating my zigbee sensor is open
but why not use the {{ expand('group.doors_windows')|selectattr('state','eq','on')|list|count }} you posted ?
group.doors_windows isn't built in is it?
I thought you had that..
ah, nope, sorry, that was the example I found online
the use states
actually I wonder if i could build a dynamic object of entity IDs that are in state open and then filter on device_class attribute
{{states
|selectattr('attributes.device_class','defined')
|selectattr('attributes.device_class','eq','door')
|selectattr('state','eq','off')
|map(attribute='entity_id')|list}}```
needed off, because all of my doors are closed ๐
awesome. thank you!! ๐
you know you can have auto-entities do this for you, if you only need it in the frontend?
@rain crescent posted a code wall, it is moved here --> https://hastebin.com/esiqahafoz
huh, cool bot.
ah, guessing you mean I could use the include: filed with auto-entities instead of the template: one?
no, but seeing what you have in the auto-entities is my exact suggestion, I wonder why you asked in the first place ?
just put your suggestion into it. the template that I had in before was the one I pasted to start.
It works as expected. Thank you!
Please donโt abuse it, share your code via code sharing sites
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
a ok,. And I meant if you dont need it in the backend, you can do it all in the frontend
saves you another template sensor
ahh, so no need to create a template group, just have the auto-entities filter it directly.
yup, got it. Thank you again!
That should not happen.. so it always returns 5:30? Could you share the entire config
It returned 06:30 when it should have been 05:30 and right now 19:00 when it should be 15:00
Ah, that's because the last part should be [0]
You are now taking out the end time of the next block
You should use {{ (hours[index + 1] | default(hours[0]))[0] }} if 00:00 is valid as next_start, otherwise {{ (hours[index + 1] | default(hours[1]))[0] }}
I see. I'm trying to add this condition to the schedule we worked on and I can't seem to get it right. https://dpaste.org/YMphg
In the last elif statement I'm trying to say, if the thermostat is equal to 'climate.daniel_s' and the time is after 20:00 or before 06:00 and one of 2 things is occuring. Either the temperature before next start is above 65 or the current temperature of master bedroom is less than or equal to 62 then +3. It worked before I added the above 65 part. It didn't isolate the thermostat and increased another thermostats temperature lol. I also tried using a set Boolean and that didn't work either oddly.
Well, you use a variable next_start in that template, but you do not define it anywhere
It's defined. I'm updating the dpaste
Couldn't update heres the entire script, all variables 'not defined' are passed from the automation. Something is up with my elif that's all. https://dpaste.org/0XrOz
check the typing in that .split filter, I think I had a few spaces in there, this should be it:{{value.split(' kr/kWh')[0]}} when testing on {% set value = '0.98 kr/kWh' %}
Maybe add some brackets {% elif thermostat == 'climate.daniel_s' and (state_attr('climate.master_bedroom', 'current_temperature') <= 62 or (thermostat == 'climate.daniel_s' and temp | select('>', 65) | list | count > 0)) and (now() >= today_at('20:00') or now() <= today_at('06:00')) %}
Don't know if I put them in the right place now, but this seemed logical to me
It worked. I tested changing the time to make it true right now and a different thermostat. I was wondering what the (now() was for instead of now() what does that do? These brackets break it up and make it do?
pedmas
or my dear aunt sally blah blah blah
Oh my lol the pemdas again. To control how home assistant reads it even without doing math use that?
parenthesis, exponents, division, multiplication, addition, subtraction
that's a method/function
I see. Didn't realize that pemdas applied to that as well.
Going to take note of that.
filters/functions, parenthesis, exponents, division, multiplaction, addition, subtraction, equal signs
Makes sense.
Good to know.
I will lol before I come back here with another issue only to have you popup again and say pemdas for probably the 3rd time now or peppridge farm remembers pemdas
Is there a way to create a group dynamically using a wildcard in the entity_id name. For example, on startup create a group called securitylights, and add all entities with the name starting light.security* to it? I received a recommendation to ask here to assist with how such a template will look, to use with group.set.
Yes, sure
Using the group.set service call, and a template
{{ states.light | selectattr('entity_id', 'match', '^light.security') | map(attribute='entity_id') | list }}
Thank you!
I'm sure I'm missing something obvious, but I get these errors pop up in the logs from time to time:
Template error: float got invalid input 'unknown' when rendering template
{{ float(states('sensor.switchbot_lounge_curtain') | default(0)) }}'but no default was specified
The thing is, I do have a default specified?
I suspect that 'default' just checks for None or similar.
The better way to do it is with states()|float(0)
Cool, I'll give that a shot, thanks ๐
Point is that 'unknown' is a perfectly good value for default()
Yes, which is annoying but understandable.
I've always wondered whats the difference between:
"{{ states('remote.hu01_lounge') == 'off' }}"
and
"{{ is_state_attr('remote.hu01_lounge', 'off' }}"
or is it just another way to write it? is there some point to having an is_state ?
they're quite different ๐
perhaps you meant:
"{{ is_state('remote.hu01_lounge', 'off' }}", in which case they're nearly or completely the same
oops yes, not is_state_attr I mean't is_state
from the docs:
It is strongly advised to use the states(), is_state(), state_attr() and is_state_attr() as much as possible, to avoid errors and error message when the entity isnโt ready yet (e.g., during Home Assistant startup).
yah I saw that but is there any other differences I wonder. It's just OCD and coding semantics for me but I am curious. I use both interchangeably but it's always been a question for later
Just to keep twisting the knife, the docs say: "It is strongly advised to use the states(), is_state()," which is both. I think that refers to the old format like states.something.attributes.someattr for e.g.
Well, is_state won't throw an error when it's not available yet, which is pretty nice
neither will states() ?
True. I was thinking of states.blabla.thingy.whatsit which of course will
is_state has a subtle difference where none is explicitly built into the check. Meaning, it will always be false if the entity doesnโt exist. Where as states() will return none of it doesnโt exist. If youโre checking for a valid state, it doesnโt matter what youโre using. If youโre checking for none, do not use is_state
is_state(โฆ, none) will be false where states(โฆ) == none will be true.
Technically you shouldnโt use == none anyways
Anyways, super subtle differences
Hey can someone help? I@ trying to change this input select of my air purifier into a light switch so I can control itโs with a slider:
trigger:
- platform: state
entity_id: select.kids_sensible_pure_light
action:
- service: switch.turn_on
data_template:
entity_id: >
{% if is_state('select.kids_sensible_pure_light', 'on') %}
switch.on
{% elif is_state('select.kids_sensible_pure_light', 'dim') %}
switch.dim
{% elif is_state('select.kids_sensible_pure_light', 'off') %}
switch.off
{% endif %}```
Your spacing is horribly off for yaml
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
Ok Iโll try to fix that. I did get example from here : https://community.home-assistant.io/t/how-can-i-set-the-entity-id-with-an-input-select/22032/4
I ran it through the YAML editor then reposted into configuration.yaml file but still got these errors:
Integration error: action - Integration 'action' not found. Integration error: entity_id - Integration 'entity_id' not found. Integration error: data_template - Integration 'data_template' not found. Integration error: alias - Integration 'alias' not found. Integration error: trigger - Integration 'trigger' not found.
that just indicates that your indentation is still "horribly off"
Hey, does anybody know how I can template a electricity meter sensor? I have the current usage of my home: 130 W and I want ja meter that shows 1 kWh after aprox. 8 hours. The "utility meter" shows 2 kW after 30 minutes. Don't know what that means ๐
Use the Riemann Sum integral which is available under Helpers to create a sensor which converts power (W) to evergy (kWh)
@marble jackal thank you that is looking promising. now how can i get this sensor into the energy dashboard?
as "Grid Consumption"
Yes, but the right channel for follow up questions on that would be #energy-archived
thanks petro for explaining that. always on the money.
so i was confused about the new bool() function. believed it to be a boolean tester. But it seems to be more of a translator really
I now wonder where we can use that optimally. just tried to use is as 'availability template' replacement in my mqtt sensors on a value. (replacing value_template: > {{value if value in ['on','off'] else none}}but there it re-states the on/off to true/false rendering all of my sensors unknown...```
- unique_id: amp_left_auditorium_state_binary
state_topic: '70:B3:D5:6F:31:F2/powerswitch-zwave/c5745b57/state'
name: Amp left Auditorium state
<<: &binary
payload_on: 'on'
payload_off: 'off'
device_class: power
value_template: >
{{value|bool(none)}}
and it that sense it is truly different from eg the is_number() ```
value_template: >
{% set maximum = 2400 %}
{{ [ value | round(2), maximum] | min if value | is_number and value | float >= 0 else none }}
the filter isn't called is_bool so i'm not sure why you thought it would behave the same way
it's like float or int
yes, I guess that was my misunderstanding. probably because I had been looking for such a test and wish was father of the thought (Dutch saying...) Still. it's not completely like float and int either, because bool changes/translates the outputs state and not type? (unless they're true/false already)
no, its exactly like float or int
it changes a string to a boolean
boolean is always true/false, nothing else
it translates on, off, true, false strings to True or False
probably because I had been looking for such a tes
I've thought about adding a is_boolean filter/function for templates
right! so I should be doing: {{value if value is boolean else none}}
yep, but you can't use that as a filter
maybe I've heard you thinking that
is for some reason is not a valid test for selectattr, select, etc
well, in that case the is_boolean() would be most welcome still
cant post in an image but the value is boolean doesnt work as expected, returning null, both in the mqtt config, and in template editor (Result type: dict) using: {% set value = 'off' %} {{value if value is boolean else none}}
I have a Zigbee light strip for which I have created 4 scenes. I also have a Zigbee button (Sonoff SNZB-01) that I was to configure to cycle through those 4 scenes. The state of these scenes gets updated with a date/time string, instead of on/off. I haven't been able to fingure out how to create this list of scenes and have each button click active the next scene in the list. I was thinking a template could do this, but I'm not having much luck. Might anyone have an idea how to do this?
I believe the template editor returns null for none
yes, but it should have returned True...
Ah, right
{% set value = "off" %}
{{ value if value | bool('no boolean') is boolean else none }}
You actually need the new filter here
yep that works!
however, it is a bit unexpected we need that to be able to test the is boolean...
replacing {{value if value in ['on','off'] else none}}
That's the test you were doing
Well the string "off" is not a boolean
but off is and {{off is boolean}} still returns False
btw, have changed all of my binary_sensors to you suggestion and confirm that is working as it should
hmm. so, cut it short, first I need to 'translate' it to a boolean with |bool, and than test if that is boolean, else it renders null
yep see that now. interesting
There aren't many reserved words
guess in ['on','off'] already proved that, being a string in a list, and not a boolean perse/at all
thx, til
is boolean are built in's for jinja. It does not do what is_number filter does. This is why I keep saying that we need the is_boolean
is boolean literally checks to see if a value is a boolean object
'off' or 'on' are strings, so is boolean will return false
Hi. Is there a way to create a data dict in template ("missing" append() method for dict)? The below doesn't work, tried to write it down as python-like syntax ๐ -> TemplateSyntaxError: expected token 'end of statement block', got '['
(the goal is to use that data dict in next service call)
{% set nm = namespace() %} {% set nm.data = {} %} {%- for key in [ key1, key2, key3] %} {%- set nm.data[ key] = 'value' %} {%- endif %} {% endfor %} {{nm.data}}'
{% set nm = namespace(data={}) %}
{% for key in ['key1', 'key2', 'key3'] %}
{% set nm.data = dict(nm.data, **{key: "value"}) %}
{% endfor %}
{{ nm.data }}
->
{
"key1": "value",
"key2": "value",
"key3": "value"
}
aside from the namespace syntax, this is the magic:
{% set nm.data = dict(nm.data, **{key: "value"}) %}
Thanks.
It seems this 'unpack' operator do the trick. I have to check how and why. Never seen/used this in Python.
the most common usage in Python is with an argument list including **kwargs (keyword arguments)
Example 3: Creating dictionary using iterables
The keys and values can be passed to dict() in form of iterables like lists or tuples to form a dictionary and keyword arguments can also be passed to dict().
Syntax:
class dict(iterable, **kwarg)
I confess that I have that bit of code in a note that I can refer back to
So this is why it has added new key/value, not replacing.
I understand it, but would have trouble coming up with it from scratch
Yep. Sometimes it is better to have it somewhere to not reinvent the wheel :-).
You can also use it to change a value in a dict:
{% set test = {
"key1": "value",
"key2": "value",
"key3": "value"
} %}
{% set test = dict(test, **{"key2": "new value"}) %}
{{ test }}
This 'magic' will be very, very useful to prepare data dict in one template pass. .
{
"key1": "value",
"key2": "new value",
"key3": "value"
}
Yes. This is how I understand this syntax. Just never needed this in Python, so wasn't 'ready' to be used in templates.
This 'update' scenario is also very usable. Thanks for recalling this.
It looks it works like a charm ...
sequence: - variables: loggers: >- {% set nm = namespace(data={}) %} {%- for object in states.input_select %} {%- if object.entity_id | regex_search('^input_select.logger_.+') %} {%- set logger = object.entity_id.split('_')[2].upper() %} {%- set level = states( object.entity_id) %} {%- set nm.data = dict( nm.data, **{logger: level}) %} {%- endif %} {% endfor %} {{nm.data}} - service: logger.set_level data: "{{loggers}}"
I have a set of helpers to set log_levels on-the-fly and needed script to restore logger levels after restart.
{ "LIGHTS": "info", "MANUAL": "debug", "MOTION": "info", "OTHERS": "debug", "STATUS": "debug" }
BTW, have you 'kind of' reusable library methods for common sensor parsing/listing/selection or using specific, dedicated templates in scripts/automations? Just wondering if is good practice to have a common, reusable script (or templates macro) for 'selection sensors by regex match' in this case or leave it as is as template evaluated variable.
Please don't share images of text, if someone wants to suggest a correction, they will have to type it all over
.share the code using a code sharing website
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
keep in mind, you can't use spaces for the keys with that method
if you want to use spaces...
{%- set nm.data = dict.from_keys(nm.data.items() | list + [(logger, level)]) %}
I'm trying to use a template to trigger an automation an hour before high noon.
It works as intended when testing using the Template editor, but does not trigger when in an automation.
Creating just a single line without the constants also works as intended.
Are setting values the way I am not supported for Automation triggers, or could there be something else wrong?
(I'm aware of the strategy of creating a helper to use as a constant, but I prefer the idea of everything being together -hence my current attempts)
{% set hours_to_offset = -1 %}
{% set hour_in_sec = 3600 %}
{% set time_offset = hour_in_sec * hours_to_offset %}{{ (as_timestamp(state_attr('sun.sun','next_noon')) + time_offset) | timestamp_custom('%R',true) == states('sensor.time') }}
{{ state_attr('sun.sun','next_noon') | as_datetime | as_local - timedelta(hours=1) == today_at(states('sensor.time')) }}
You are right! Thanks for the reminder!
Hello! ๐ Iโm having a hard time setting up a binary sensor around a zha_event. According to this topic, it should now be possible : https://community.home-assistant.io/t/wth-dont-we-have-event-binary-sensors/219658/21 but when trying it, it only displays unavailable. I verified the template documentation but I should be fine according to it. Is my template wrongly formulated according to the event? Hereโs the configuration : https://dpaste.org/vozGE and an image for reference : https://i.ibb.co/FVSR8Q5/Binary-sensor.png
Some fun tools I wasn't aware of. Thank you
you're telling home assistant it's never available with availability: false
Doesn't something like this need an auto_off? How will it ever turn off after it has been turned on otherwise?
how can i join variables as string into a new variable?
{% set jaar = (now().year) %}
{% set maand = (now().month) %}
{% set gecorrigeerde_tijd = dag-maand-jaar %}```
That last one does a match calc instead of making it a string. but donno the syntax...
quoting doesnt work... forum searched but not found
You are right. Basically I want to wrap the ZHA event of a doorbell sensor into a binary sensor to debounce it.
Just use strftime for this
th'eres a bajillion forum examples of that and what you're asking fuzzy
if you justr want to join the ints and get a string back instead, just use ~ instead of -
does that suite my needs? I have a time object only. {{strptime(starttijd_regen, "%H:%M")}}gives me 1900-01-01 as well. So i want to add current date
A quick reference for Python's strftime formatting directives.
{{ now().strftime('%D-%M-%Y') }}
I changed it to this : https://dpaste.org/oMBHa unfortunately it wont trigger or show available.
If you don't want the leading zeros, check the link petro sent
ill have a tinker with that!
remove args: [] and params: {} from your trigger too
aslo, add a - before trigger:
- trigger:
keep trigger in with binary_sensor though
template:
- trigger:
- platform: event
event_type: zha_event
event_data:
device_ieee: 00:08:89:00:01:d9:df:f2
unique_id: 00:08:89:00:01:d9:df:f2:18:0x0006
device_id: 7d98ffa3028511eb9091ab77437cf133
endpoint_id: 18
cluster_id: 6
command: on
binary_sensor:
- name: Sonnette
state: "true"
device_class: sound
auto_off: 4
oh
I see another
wrap on in quotes 'on'
template:
- trigger:
- platform: event
event_type: zha_event
event_data:
device_ieee: 00:08:89:00:01:d9:df:f2
unique_id: 00:08:89:00:01:d9:df:f2:18:0x0006
device_id: 7d98ffa3028511eb9091ab77437cf133
endpoint_id: 18
cluster_id: 6
command: 'on'
binary_sensor:
- name: Sonnette
state: "true"
device_class: sound
auto_off: 4
The state is still unknown with : https://dpaste.org/FYfba . ๐ฆ Let me try it it still.
still confusing. I have a time string which i have parsed to a time with {{ strptime(starttijd_regen, "%H:%M")}}
Now i need to ADD current date only, since i have the time already. This to get rid of 1900-01-01
{{ now().strftime('%d-%m-%Y') }} gives me a date but how to add both to a timeobject..
going to as_timestamp and add both?
Yay it works! ๐ Strange that it shows unavailable at first. Once it sees the event, the binary sensor show available.
Use today_at
@mighty ledge I'm impressed with what you shared earlier and have tweaked some other projects using what I've learned.
I'm curious if there's a sexier way to do either of these:
This checks my google calendar to see if I have a work event today
{{ as_timestamp(state_attr('calendar.work_calendar','start_time')) | timestamp_custom('%F', true) == states('sensor.date')
This checks my google calendar to see if I have a work event on the day that is in 9 hours (This runs when I go to bed, and so effectively checks if I will be working when I wake up, even if it's checking after midnight)
{{ as_timestamp(state_attr('calendar.work_calendar', 'start_time')) | timestamp_custom('%F', true) == (as_timestamp(now()) + (9 * 3600)) | timestamp_custom('%F', true) }}
PS: I hope I don't sound like I'm asking you to do my work for me, and I'm sorry if it does. I really want to learn. You don't owe me anything โค๏ธ
You can use a timedelta to explicitly add 9 hours by the way instead of multiplying by 3600 ๐
But, you should probably look at the today_at('9am') filter, that might be a lot easier to work with ๐
E.g.
{% set start_time = state_attr('calendar.france', 'start_time') | as_timestamp %}
{{ start_time == today_at(start_time| timestamp_custom('%X', true)) }}
I appreciate the example.
Syntax is often a struggle for me.
I had to switch out your calendar to one that I have, but I think it's easy enough to swap it back
For sure.
I'm excited to tinker with this more soon
Also, if you're sharing a short template like that, you can put three ` on a line with py after them, your example, and then another line with three more backticks for better formatting. (py being python, yaml being yaml, etc.)
Though in general, it's best to use a code sharing site ๐
#Learning
Good to know.
Thank you ๐
No problem. I've stolen plenty from Petro myself ๐
After all, automation is all about not having to do the thing yourself ๐
How do I check to see if an entity exists
States.domain.object_id returns a dict null but how can I check for that
{{ states.sensor.xxx is none }} appears to work
I got there by using {{ states.sensor.xxx }}
ahh, none without quotes, gotcha. tried null and 'none'
Anything with quotes is a string
In this context no way to use spaces in keys, but thanks a lot for pointing this out Petro, it can help in other cases.
{{ (state_attr('calendar.work_calendar','start_time') | as_datetime | as_local).date() == now().date() }}
Can you do an include in a templates file? To modularize the file by breaking out groups of related templates? Would that still work using reload templates and how would that be done?
I don't think you can do that. There is an include function in jinja, but I could not get it working in devtools
I meant in the file itself. I should have said in the template sensors file my mistake. I'm referring to inside of a templates.yaml
You can use YAML anchors
Also I created a start time on the schedule we worked on the start is a string. How would I make a template that checks If the time now is 5 minutes or greater than start. For example the output of start may be start: '05:00'. What's the format for using a yaml anchor?
Perfect, that worked. That would allow me to say in English (include this file 'schedules.yaml' of templates)?
You can only use anchors in the same yaml file
I remember a video on Dr zzz channel with Frenck where he said he broke out his automations file into various sub files but I wasn't sure if that could be done with templates and still be reloadable.
I use one file per automation myself
That same thing can't be done in templates? Put 5 template sensors into a file? Then include that file in the templates file so that it's read as 1 file?
I also have (mostly) all my template sensors in separate files
But 5 in one file would also work
Yes that's exactly what I'm looking for. How would I do that? My file is getting full of related templates that could easily be separated for sanity.
Example from my own config where I've put 3 templates for trash collection in one file https://github.com/TheFes/HA-configuration/blob/main/include/template/sensor/trash_formatted_date.yaml
template:ย !include_dir_listย /config/include/template/
That is the line used to include the folder
You put that line in the main templates.yaml?
No, you could place it in configuration.yaml. I don't have a templates.yaml
But I've gone quite far in splitting the configuration,
I understand now. That points to a directory that includes all files within that directory and this can be reloaded from UI still?
Yes
Awesome thank you.
Thank you. This is exactly what I hoped for.
I've even been able to manage adding an offset much cleaner now with this.
{{ (state_attr('calendar.work_calendar','start_time') | as_datetime | as_local).date() == (now() + timedelta(hours=9)).date() }}
{%- if days_until <= 1 %}
{{ ['Vandaag', 'Morgen'][days_until] }}
...
That's genius.
So it picks "today" or "tomorrow" automatically? unless I've massively misunderstood and forgotten all my dutch ๐
I'm tinkering with now() in an attempt to use it as an automation trigger.
{{ now() }} reports back with a 6 digit decimal, which isn't suitable for a trigger.
Is there a way to remove those decimals?
I'm aware of sensor.time, which may very well be the best solution (and so my question may be silly), but I'm more asking to improve my understanding of these systems.
{{ now().replace(microsecond=0) }}
you can change the other components, too: hour, minute, second
Correct
I can't believe I didn't think of doing that. You're a genius
Super cool!
Thank you
Replace is a function I've never seen in any documentation. Do you happen to know where I can learn more?
Is it a python thing?
https://docs.python.org/3/library/datetime.html#datetime.datetime.replace
Answering my own question (I think)
yes, Jinja uses Python data types and you can use Python methods on them
Can Jinga use Python data types in the same way Arduino can use C++ functionality?
Not identical, but built off the other and some added tools
I have no idea how Arduino uses C++ functionality. The reality is that Jinja uses Python data types
What's wrong with this snippet as a Template Sensor? - sensor: - name: "Freezer1 Temp" unique_id: "freezer1_temp_id" state: {{ states(sensor.freezer_temp_1) | float * 2.0 }}
Gives me an error: Error loading /config/configuration.yaml: invalid key: "OrderedDict([('states(sensor.freezer_temp_1) | float * 2.0', None)])" in "/config/configuration.yaml", line 70, column 0
the indentation is pretty hard to make out ๐
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
I'll put it in a pastebin.
but the main issue is that you need to surround your template in quotes
rule #1 of templates
you also need to surround the entity_id in quotes
state: "{{ states('sensor.freezer_temp_1') | float * 2.0 }}"
Thanks! That was the problem. The quotes on both the state and the entity_id.
i think i need a template trigger... "when all lights downstairs in zone A and B are off"
Zones don't typically have lights
Did you mean 'area'?
sorry yes!
its late ๐
a group wont help. thats a toggle ofcouse... i need a sensor maybe then
There's a template function to return the entities in an area
You don't need any of those things
ok. thx. ill go look for it then
{% set entities = area_entities('Family Room') + area_entities('Kitchen') %}
{{ entities|select('match', 'light.')|expand|selectattr('state', 'eq', 'on')|list|length == 0 }}
ooof nice!
i was searching the forum, but im not sure what i was looking for hehe
i understand whats written but i still cant make up the syntax
its like understanding german but not able to speak it(im dutch)
so in my case is going to be list|length = 0
sorry, yeah. But you need == 0
np. thx for the help!
exactly what i need ๐
gonna be a reminder which doors/windows are open at bedtime
one more question... can i set a variable in a trigger template?
trigger: all lights in living and kitchen are off
condition: after 10pm
action: notify mobile
i copy paste a lot of stuff around between automations. but this kind of trigger is new to me
that doesn't require you to set a variable
well it does add both areas together
you can use that template anywhere, so if that's your question, then yes, you can set a variable like that in any template anywhere
{{ (area_entities('woonkamer') + area_entities('keuken'))|select('match', 'light.')|expand|selectattr('state', 'eq', 'on')|list|length == 0 }}```
you can make it harder to read, yes
i put that variable between brackets and it worked...
you didn't need to do that
well im a novice pushing code around as a hobby
then I think it's all the more important that the things you write are easy to read and understand
true that
split stuff for ez reading
ill try to paste your solution into the trigger template and test it out
it works in develop tools. but it throws an error as automation trigger
you did something wrong
im sure i did
platform: template
value_template: >-
{% set entities = area_entities('woonkamer') + area_entities('keuken') %}
{{ entities|select('match', 'light.')|expand|selectattr('state', 'eq', 'on')|list|length == 0 }}
what is the error?
i only changer the trigger so it must be there. lemme see
Message malformed: invalid template (TemplateAssertionError: No filter named 'expand'.) for dictionary value @ data['value_template']
that's weird
you can try this:
platform: template
value_template: >-
{% set entities = area_entities('woonkamer') + area_entities('keuken') %}
{{ expand(entities|select('match', 'light.'))|selectattr('state', 'eq', 'on')|list|length == 0 }}
or, just create a template binary_sensor with that and use it in a state trigger
well it saved the automation
lemme check!
bingo!
i turned off all lights and got the notify
just need to add the condition now
great thank you!
interesting:
hass_globals = [
"closest",
"distance",
"expand",
"is_state",
"is_state_attr",
"state_attr",
"states",
"utcnow",
"now",
"device_attr",
"is_device_attr",
"device_id",
]
hass_filters = ["closest", "expand", "device_id"]
for glob in hass_globals:
self.globals[glob] = unsupported(glob)
for filt in hass_filters:
self.filters[filt] = unsupported(filt)
looks like it should have disallowed the function, too
hey, a noob question, how do i find out, what capabilities a devices has, and what kind of stuff i can expose as sensors
for example i currently have a tecking SP22 smart plug, and it's been added on localTuya, and i would like to expose it's sensor, power consumption, voltage
i found this random sample tuya_g4_current_consumption: friendly_name: "balcony consumption" unit_of_measurement: 'W' value_template: "{{ states.switch.balcony_socket.attributes.current_consumption }}"
is there a way to get the entire list of attributes listed that this device has?
that's an #integrations-archived question, not releated to templates
are you asking about how to access things that are already exposed via attributes?
that's not what it sounded like from your first statement
well because i do not know how to phrase it
- Look in
-> States and see if it already exposes what you want. If not, 2) go to
-> Devices, find your device, and see if there are entities that aren't enabled and do have what you want
- If neither is what you want, ask in #integrations-archived
templates only allow you to access things that already exist
yes yes, this is what i was looking for, states
and if lets say an attribute does not show up, and i need to get back to integrations to expose it, where should i look to see what entities are possible to expose?
- go to
-> Devices, find your device, and see if there are entities that aren't enabled and do have what you want
- If neither is what you want, ask in integrations
alright, probably it gets boring after a while having the same old questions asked
thanks for your time
after they've been answered, yes ๐
Why does this binary sensor template always become true exactly one minute **after **the on time, instead of at the on time? ```
state: >
{% set t_now = now().strftime("%H:%M") %}
{% set t_on = states('input_datetime.upstairs_ac_am_on_time') %}
{% set t_off = states('input_datetime.upstairs_ac_am_off_time') %}
{{ t_on <= t_now <= t_off }}
What if you do this:
state: >
{% set t_now = now() %}
{% set t_on = today_at(states('input_datetime.upstairs_ac_am_on_time')) %}
{% set t_off = today_at(states('input_datetime.upstairs_ac_am_off_time')) %}
{{ t_on <= t_now <= t_off }}
That does seem to have made a difference. I wonder why?
I guess it has probably something to do with now() being rendered once per minute, and that it doesn't rely on whole minutes now, but I also can't really put a finger on it
I am trying to track the last changed of the HVAC action attribute. I assume this would be the way to go about it because I don't think it would work doing this {{ state_attr(thermostat, 'hvac_action').last_updated }}
https://dpaste.org/1wtzU
However I can't get the attribute in the template sensor to work.
last_changed is not an attribute
Attributes don't have a last_changed object, only the entity itself
If you want to track that of a specific attribute, you need to create a template sensor out of that attribute
Yes so I made a template sensor out of the attribute to track that to obtain that but I don't think I'm doing it right.
It's in the dpaste
This works {{ states.sensor.daniels_hvac_action_last_changed.last_changed }} but it would more efficient for this to be achieved within the template sensor itself so it can be true/false. I wasn't sure if you can do this.state in the manner I'm doing it
What does the attribute return now?
Null
TemplateError('UndefinedError: 'str object' has no attribute 'last_changed'') while processing template 'Template("{{ now() - timedelta(minutes = 5) > this.state.last_changed }}")' for attribute 'last_changed' in entity 'sensor.daniels_hvac_action_last_changed'
Hey, all, hopefull everyone is doing well so far today ๐ so im back with new problems and questions ๐ Today im trying to optimize and simplify some of my basic GUI automations, is there a way to simplify these two automations and to create one out of them ?
https://dpaste.org/enZFP
You need this.last_changed
It worked. Thank you.
Like this: https://dpaste.org/mCGRE ?
from a quick look seems to be ok, im like realy new, and it super hard here so huge thanks for Youre time !
id is like the state of the service in that case ? like Id on, that means the service ( smart plug ) gets triggered, right ?
I added ids to the trigger, and I use those in the service call
You can use anything for the trigger id, but in this way you can use them directly
Do note the automation only works if it is triggered by the state of the sensor now, you can not run actions manually as there is no trigger id then
ok, the last sentence i understood ๐ from the first one i took screenshot ๐
I have another one ( Of course.. ), this one is about light in storage room, i would like to merge both of them and add the lux thing, so that if its light enough, the light wouldn't turn on at all, im not just jet sure whats the lux number i have to use since i haven't found a way to measure it for now so lets say 50 lux ๐
and what im doing for now, if i get the idea, im just copy pasting, and editing the automations i get here, like i got the dehumidifier automation, i managed to get another one for other room out of it, simple, but still progress ๐
This is odd, if I run this in template editor it's True {{ hvac_action_last_changed }} and if I do {{ hvac_action_last_changed == 'True' }} it's false and if I do {{ hvac_action_last_changed == 'true' }} it's also false. This is a variable I set what it's equal to in the template editor which is a sensor for context. That's how I just used {{ hvac_action_last_changed }} to get the output.
Not sure why you want to do this though
I'm using it as part of the schedule script to modify the temperature under certain conditions so knowing the thermostat is idle or cooling for example and it has been for x minutes is the goal.
Okay, but why use variable == true when you can simply use variable
Because the variable can be false and I want it to be true in this statement. oh I get it now the result will be true in itself. Otherwise false and that's the same thing as variable == false if it's false and same as variable == true if it's true because it's a boolean
Yes makes sense now. I didn't think of that.
hello guys & gals!
I'm trying to refresh my dashboards and use Minimalist UI, but i'm stuck trying to use an if/else statement for a card title. Anyone got any insights on how i could accomplish this:
ulm_card_script_title: > {% if is_state('input_number.lr_fan_state', 0) | int %} Fan Off {% elif is_state('input_number.lr_fan_state', 1) | int %} Fan Low {% elif is_state('input_number.lr_fan_state', 2) | int %} Fan Medium {% else %} Fan High {% endif %}
as is, it prints the everything as a string and doesn't parse it
the | int that you've added to each condition doesn't do anything
In any case, it seems like this is more of a #frontend-archived question. Most cards don't support templates at all
Trying to create a script to increase the a/c unit's target temperature by 1, but I get a "malformed" error. I followed a solution that's about 3 yrs old - doesn't appear to work, but I'm pretty sure I've messed this up somehow. Can someone help?
Thanks. I'll keep digging
Yeah that was one of the errors.
So many things wrong with that script, the correct should be: https://dpaste.org/zRFBR
I have a template sensor which returns True or False if the calendar event exists today or not.
Currently, there are no calendar events in the future (a fairly common occurrence), and returns a null value of dict type
From the Template editor:
{{ state_attr('calendar.my_calendar','start_time') }}
null```
(I think) I'd like my code to either validate if the value of the calendar is a datetime object and proceed in determining the result, or conversely return false if the calendar is in a null state.
I think I got it
The line I was looking for was
{% if state_attr('calendar.work','start_time') == None %}
None -captital N, no quotes
I need some help with Regex,
How would I get the first 6 digits of the number from this whole string
Phone Number: 87654321
I would just do this:
{{ "Phone Number: 87654321".split(': ')[1][:6] }}
I cant use split here because there is also
Name: Astogems
Phone Number:
Address:
and 87654321 can be any value
.Phone Number: (.)\n
.*Phone Number: (.*)\n
I managed to think of this but I cannot get the first 6 digit
I was expecting this to work, but I can't get capture to work:
{{ "Phone Number: 87654321"|regex_replace('.*: (\d{6}).*', '$1') }}
Tricky one eh
you can still use split():
{{ "Name: Astogems
Phone Number: 12345678
Address: 123456789".split("Number: ")[1][:6] }}
-> 123456
Yeah but the Name could also be RobC
Its err
Generated from Google Calendar
.*Phone Number: ([0-9]{6})
it doesn't matter what the name is. You mean "Phone Number: " isn't constant?
The value of Phone Number isnt constant
I'm not relying on that
The value of everything isnt constant
are you still saying that what I have above won't work?
It would work is my friends name is Astogems but his name could be RobC or maybe John
it doesn't matter. you're looking for the phone number, right?
nothing in that search string has anything about the name
Oh my god hahaha I didnt notice, I apologise
Yup, exactly im only looking at the values after Number:
However would this work with a context such as
Full Name: John
Last Name: Smith
Phone Number: 87654321
Address: 123 Apple Street
Postal Code: 123456
Got it Thanks a lot
Hello
I can not for the life of me figure out why this template is not working
- name: Pegasus Array Available
where: '"path" =~ /.*user0/ AND "host" =~ /^Pegasus$/'
measurement: '"disk"'
unit_of_measurement: bytes
field: '"free"'
database: telegraf
group_function: last
value_template: '{{ states.sensor.pegasus_array_available | multiply(0.0000000000001) }}'
``` Any suggestions?
this does it as well with a regex:
{{ "Name: Astogems
Phone Number: 12345678
Address: 123456789"|regex_findall_index('.*: (\d{6}).*')}}
as does this (apparently \1 references a capture group):
{{ "Phone Number: 87654321"|regex_replace('.*: (\d{6}).*', '\\1') }}
Yes, you're referencing the state object and not the state itself, and then you're not turning it into a number
value_template: "{{ states('sensor.pegasus_array_available')|float | multiply(0.0000000000001) }}"
Oh, alright. Thank you!
well now I get this error https://questionable.link/5AJHRFQA1
ok
ohh. so can single quotations just not be used for this?
it just has to be parseable, and using the same type of quotes makes it impossible to parse
that makes sense. thanks!
Thanks!
Where should I go to ask questions about Restful Commands
Thanks!
Is there a method with template to differentiate between a normal light, and a light group?
A light group will have an entity_id attribute
Will something like this work? I'm still very green with jinja, but trying to learn```
{{ states.light | rejectattr('entity_id') | map(attribute='entity_id') | list }}
Thx - I spend a lot of time there. The above seem to filter all the entities. What I have so far is```
{{ states.light | rejectattr('entity_id', 'match', '^light.browser*') | rejectattr('entity_id', 'match', '^light.*doorbell_flash') | rejectattr('entity_id', 'match', '^light.*control_screen') | map(attribute='entity_id') | list }}
The above filters out unwanted lights - This template is used with group.set to create a group dynamically.
{{ states.light|selectattr('attributes.entity_id', 'defined')|map(attribute='entity_id')|list }}
Thank you - I really appreciate the help. This community is awesome!
Is it possible to stick a template sensor to a area? I
As long as you give it a unique_id
I've got another head scratcher... with this template, when I try and adjust the position of my blinds, I get an error that "position is undefined" https://dpaste.org/XN80B
I tried but it will not show in the area card. When I go into the area the sensor show, but it will not get displayed ๐ฆ
when I add one, I get the same error: https://dpaste.org/k38mw
I also get the same error if I use optimistic: true
Can someone point me in the right direction here?
Trying to set a helper value == my fan's current speed
service: input_number.set_value
target:
entity_id: input_number.dallasfanspeed
data:
value: '{{states(''fan.dallas_bedroom_ceiling_fan'', ''percentage'')}}'
you're using the wrong function, assuming that "percentage" is an attribute
value: "{{ state_attr('fan.dallas_bedroom_ceiling_fan', 'percentage') }}"
Cool, that action seems to work
But apparently my overall automation is broke
Thanks much
still not sure what I'm doing wrong where even with a position_template I get an error https://dpaste.org/k38mw
the subtraction of 100 would put you outside of the defined range (0-100%)
even if I remove the math, it is still undefined
what does the call to the script look like?
cover.bedroom_large_right: Set position to 62
can you share?
not sure how... the template is exposed as a device via homekit and I'm dragging a slider in home kit which I think is calling the set position
sounds like maybe HomeKit isn't passing the position value to the script when triggered that way. Maybe an input_number in HA exposed to HomeKit that would trigger the automation in HA using the value from the input number to set the position
Hey jinja ninjas, is there a simpler way of achieving what I'm doing here? Taking timestamp for now and timestamp for last changed of a sensor to get how many hours since last update as a value_template:
{{ ((as_timestamp(now()) - as_timestamp(states.binary_sensor.front_door_contact.last_changed))/3600) | float | round(0)}}
Any idea why this is resulting in
Message malformed: template value should be a string for dictionary value @ data['action'][1]['data']
can i set an attribute of an entity for development purposes? im testing a rain sensor but its not gonna rain soon lol
or should i overwrite the value manually
Yes, in
-> States
with {% set ..... % }
To test an automation there's three stages you can follow. Testing the action, the condition and action, and the whole automation:
- Use Configuration -> Automations to find the automation and then push Run Actions. If this fails your problem is in the
action:section, and details should be found in your log file - Use Developer tools -> Services and call
automation.triggeron the automation withskip_condition: false. If the first passes but this fails then the problem is in yourcondition:block - Use Developer tools -> States to find the trigger entity, click the name, then change the state (at the top) to something that'll trigger the automation before pushing Set State. If this fails then the problem is with your
trigger:section, or the automation is turned off (you can check that in Developer tools -> States).
You can also see this section in the docs and with HA 2021.4 onwards debug automations.
Fixed thank you
{{ ((now() - states.binary_sensor.front_door_contact.last_changed).total_seconds() / 3600) | round(0) }}
Hey! I want to check if the state of a sensor is above a certain value at a given time every hour. Is that possible?
For example a binary sensor that is true if the state of the sensor is above 3.5 and the minutes of the current hour is more than 40.
{{ now().minute > 40 and states('sensor.whale') > 3.5 }}
Something like this?
If I understand that correctly, YES!
That should do it!
I get this: TypeError: '>' not supported between instances of 'str' and 'float'
all states are strings
so it's correct
{{ now().minute > 40 and states('sensor.whale')|float > 3.5 }}
Not sure why, but I had to modify it to make it render properly....
{{ (now().minute | float >= 40) and (states('sensor.hourly_consumption_meter')|float > 3.5) }}
the parens may have been required, but now().minute should already be a float or int
Let me try that... Just for fun! ๐
{{ now().minute is integer }} -> True
{{ (now().minute >= 40) and (states('sensor.hourly_consumption_meter')|float > 3.2) }} also works great! ๐
Any idea how I can have a variable result, pull a corresponding list? For example away_selector output could be one of 3 lists for example if it's daniel_away then the goal is to simultaneously pull that list daniel_away to use on line 28. Initially I had away_selector above the lists so I thought I needed to move it below them but that didn't work. I was trying to avoid more logic and something efficient. I'm assuming I'll have to use a different strategy for this and not use the same list names as the output for away_selector but I figured it was worth trying.
https://dpaste.org/Q354x
but the object_ids are already the names of the lists? It seems like that's how you tie those two things together
I just realized that yes, the only difference is adding _away to the zone object IDs and doing a single replace
Whoops, I feel kinda stupid I forgot that float filter.
Any idea how I can tie them together? Because the zone object Id needs _away added to it. So it's not 1 for 1.
I have this group entity and I want to dynamically add all entities that come from a specific integration. How can I do that?
group:
ignored_unavailable_entities:
entities:
- light.some_light
- ...
- <all entities from specific integration>
So remove the string when you index? I'm not really sure what exactly you're trying to solve. From what I can tell, you have a bunch of lists and you want to choose one of them based on a string?
I don't know if this is helpful, but it works:
- id: test
alias: test
variables:
lists:
mylist_1:
- "foo"
- "bar"
mylist_2:
- "blah"
- "floop"
trigger:
- platform: state
entity_id:
- input_boolean.test1
- input_boolean.test2
action:
service: persistent_notification.create
data:
message: "{{ lists['mylist_' ~ trigger.to_state.object_id.replace('test', '')] }}"
@silent vector
Use group.set with integration_entities() https://www.home-assistant.io/docs/configuration/templating/#integrations
Could you by any chance give a minimal YAML example?
On how to combine manual addition of entities to the group with the templated ones?
- service: group.set
data:
object_id: zwave_js_group
entities: "{{ integration_entities('zwave_js') }}"
If you want to add more entities to an existing group, you should create a new group instead based on the original group and the new entities
So if I add a group to a group, does the nested group automatically expand?
I don't know
I suspect no, since you can have groups of groups
a group is just an entity, after all
So maybe I should just use a template group that gets the integration's entities to which I add the "manual" entities within the template, if that is possible
the only way to create such a group is what I showed above
and you can add whatever you want
Oh, but I don't understand how I can practically do this with using the service :/
just like I showed you
I mean I could create an automation that just invokes this service constantly
that's working code
yes, you would need to run that either at startup, or periodically
Alright. Thank you.
There's probably a good reason for this, but it seems a little weird there are no template groups, like what you can do with e.g. sensors.
the devs have moved away from group.* groups and encourage domain-specific groups now. I don't know if there's a good technical reason that they couldn't support template definitions, but maybe it's just a feature request
One last question, is the parameter of integration_entities() the name of the integration as seen in the integration column of the entities table?
I'm just going off the documentation: https://www.home-assistant.io/docs/configuration/templating/#integrations. Feel free to experiment
I have 3 different lists. I tied their names to match the object Id as close as possible. The zone object Id though will not match. person.daniel becomes daniel and I would need to add _away and then for the state change it's fine as is. daniel_away from the boolean matches the list
did you review my proposal?
it chooses a list from the set of variables based on the object_id of the triggering entity, modified to remove a part of the name
I saw it, I was answering the first post, I'm just confused how I would implement in this in my use case.
I think I understand it now. Thank you
I couldn't figure out how to impleme what you sent given my objectids aren't the same structure as what your example was. I'm attempting at line 7 to use what you had to pull the correct list but it's not working. https://dpaste.org/pDMXv
Yeah, that doesn't look like what I gave you
You need an index and you're providing a comma-separated list and you're not stripping the part of the string as we discussed
I'm a little stuck on how to make what you sent work. Can you show how I would do that with my lists?
You have this:
entity_id: '{{ lists[away_selector | list | join('','')] }}'
I gave you this:
message: "{{ lists['mylist_' ~ trigger.to_state.object_id.replace('test', '')] }}"
note how I assemble the name of the list and use it as an index to choose the right list
you're creating a comma-separated list and not doing any string manipulation
So swap mylist_ with away_selector? I know but that's what I'm stuck on because I'm trying to align it with the Entity IDs.
that's what my example does
it takes the entity_id that triggers, such as input_boolean.test2, and uses a part of it to build the name of the list to use
you're already doing some of it in your away_selector variable
Every entity id has a different name before _ though. daniel_away , all_away. That's the part I'm stuck on. Your example was test2 strip test and select mylist_2 essentially.
doesn't away_selector already have the name of the list you want?
It does
That's what I was stuck on
it's just that
Perfect thank you.
So im trying my luck out here, I get the idea, I know what I need, but I just can do such an automation in my day 3/4 on YAML and doing it in the UI with like 5 automations isnโt the best way, so im trying my luck here ๐ looking for a template to do the following, if the iRobot Script isnโt working, when a movement is detected and the Brightness is below 50 lux turn on the light, if there has been no movement for 20 sec, and the robot script isnโt running, turn off the light
iRobot script: irobot_with_automatic_lights
Light entity: switch.0x54ef4410003b3633
Movement detection entity: binary_sensor.motion_sensor_storage_room_occupancy
Brightness Entity: sensor.motion_sensor_storage_room_illuminance_lux
thats pretty simple really, don't see a need for templates
movement = trigger, brightness value = condition, script = condition
i get the idea, my problem is code writing, thats why im asking for the template...
Hello, I looking for a long time and cant find solution. I trying new template system because, old templates doesn't support "state_class: measurent".
template: #Missing property "platform"
- sensor:
- name: "switches_power_consumption"
unit_of_measurement: "kWh"
device_class: energy
.
.
.
and getting error:
Invalid config for [sensor]: required key not provided @ data['platform']. Got None. (See /config/configuration.yaml, line 13).
I will be very happy for any kind of help or information
thanks ๐
What version of HA are you using?
8.2
That's not a version
Home Assistant Core 2022.6.7
Home Assistant Supervisor 2022.05.3
Home Assistant OS 8.2
Where did you put that? Seems like you put it in sensors.yaml or similar, when it belongs in configuration.yaml
I ussed include in configuration,yaml
sensor: !include sensors.yaml
Right, it doesn't go in there
okey, thank you very much I didnt expect include doesnt work for this
It's not that. It's that it sounds like you put the code above into sensors.yaml, where it doesn't belong
It's not the include that's the problem, but that you put it in the sensor: section
okey, witch section is right for this code, I feel bad, because it's work but its in configuration.yaml and thats doesnt feel right
@steep tulip posted a code wall, it is moved here --> https://hastebin.com/axujerebid
It belongs in configuration.yaml.
@quaint crystal posted a code wall, it is moved here --> https://hastebin.com/xolopohixe
struggling to understand how this error is occurring:
a template reads "undefined when rendering" in the logs, but it works fine in the developer tool window
a basic {{ state_attr('weather.home_hourly','temperature') }}
sensor shows as "Unknown" in the Ui, and logs show Template variable error: 'weather' is undefined, but it does template correctly in the developer tools section. Matches state I see as well for my weather entity
That error indicates that you're using the wrong quotes
It's interpreting 'weather' as a variable, as well as temperature
interesting, the docs show using single quotes in the examples https://www.home-assistant.io/docs/configuration/templating/#devices
ahhh whey copying my yaml over onto the server the single quote were removed. doh! thanks a ton
Can I ask for a second set of eyes on this... I'm sure I'm missing something and/or doing something stupid, or both?
- platform: template
switches:
heat_required:
value_template: {{ is_state_attr('climate.bedroom_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.ensuite_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.ruby_bedroom_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.guest_room_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.living_room_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.sitting_room_thermostat', 'hvac_action', 'heating' ) }}
Error: The system cannot restart because the configuration is not valid: Error loading /config/configuration.yaml: while parsing a flow mapping in "/config/configuration.yaml", line 177, column 26 expected ',' or '}', but got '<scalar>' in "/config/configuration.yaml", line 177, column 97
Works successfully in the developer tools
Thank-you all... I was missing the quotes at the start of the value_templates ๐
And then of course I want this as a sensor not a switch ๐
You have to quote your template
or:
switch:
- platform: template
switches:
heat_required:
value_template: >-
{{ is_state_attr('climate.bedroom_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.ensuite_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.ruby_bedroom_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.guest_room_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.living_room_thermostat', 'hvac_action', 'heating' ) or is_state_attr('climate.sitting_room_thermostat', 'hvac_action', 'heating' ) }}
Based on the posts he added, he already found out ๐
๐ I answered too fast :-p
- wait_template: '{{ states("vacuum.staubi") == "docked" }}'
continue_on_timeout: true
timeout: '12000'
i was hoping this is two hours, looks like its not. does someone know what the value/metrix here is exactly? 120 did also not work for me before.
@buoyant sapphire This is 200 minutes. The timeout is in seconds, so 2 hours is 7200 (there are 60 seconds in a minute, not 100)
But such a long timeout will be risky, as it will be cancelled by an automation reload (also when you edit another automation in the GUI, and save it) or a reboot of HA
And you can rewrite your template to: '{{ is_state("vacuum.staubi", "docked") }}'
@bronze tide
condition: template
value_template: "{{ is_state('binary_sensor.whale', 'on') or (is_state('binary_sensor.whale', 'off') and (now() - states.binary_sensor.whale.last_changed).seconds < 60) }}"
Thanks a lot! Somehow I prefer this solurion...
hey, is anyone able to explain how i get my successfully created template sensor to be added to my recorder so it records the data and shows up in my statistics page?
Did you set a specific configuration for recorder?
And did you set a state class for you sensor?
Is it possible to limit a template from rendering? I have this template that takes the current electric consumption, divides it by now().minute and multiplies it with 60. For the first 10 minutes or so, the estimations this calculation does have huge errors. Can I have the template render only after 10 minutes into the hour? Other ways to filter the huge errors/variations?
Hi Everyone, I am hoping I can get an idea on how to approach what I assume has been done, but I cannot find anything so far, likely wording. I have a energy monitoring smart outlet running Tasmota on a dumb โ coffee maker. I am hoping to have a badge on my main page showing if the Coffee is brewing or heating. Brewing is easy, as power is over 700W. The challenge is with the warming state as the heating element only comes on every minute or so, so power drops to 1W like the phantom draw.
What I am trying to use is something like condition in rules "for 5 min", so I can say if power is below 2W for 5 min then it's "Off". I will happily share the results if nobody has posted this.
Thanks in advance!! For context I am running Core 2022.6.7.
url: "https://api.ttlock.com/v3/keyboardPwd/add"
method: POST
content_type: "application/x-www-form-urlencoded"
payload: "clientId=971e80f12xxx3b914fc6b0551b4&accessToken=c014bb77xxxxxx1287c478b&lockId=48xx23&keyboardPwd=456123&keyboardPwdName=Test2&startDate=1656979200000&endDate=1656997200000&addType=2&date={{as_timestamp(now())}}"```
I created a Rest Command, it work if I just input the date= parameter with the Epoch current time
But when I use a template, it does not work
Is there a problem with my code formatting?