#templates-archived
1 messages · Page 155 of 1
haha nice
Well depends, if you only need these times, you don't need the attributes at all
as I said, time is the only variable that changes, the route # and destination will be the same each time, so why pull them
- platform: rest
name: Bus Times
resource: https://transperth.maxrumsey.xyz/api/v1/busTimes?stop_number=18418
value_template: >
{%- set buses = value_json.buses %}
{{ buses | map(attribute='time') | join(', ') if iif(buses) else 'no buses' }}
or:
- platform: rest
name: Bus Times
resource: https://transperth.maxrumsey.xyz/api/v1/busTimes?stop_number=18418
value_template: >
{%- set buses = value_json.get('buses', []) %}
{{ iif(buses, buses | map(attribute='time') | join(', '), 'no buses') }}
Tried your first piece of code and it pulled the last 2 stop times for the night
Perfect, thanks!
last one is most error proof
OK, will use that instead
Worked like a charm, and updates every 30 seconds. Thanks again.
No problem
here's a tricky one. i need a wait_for_template that works with now()
{{ trigger.to_state.state == now().strftime("%Y-%m-%dT%H:%M:%S-04:00") }}
wait... maybe i'm a dummy
i thought it was failing because the wait template doesn't 'tick' for anything but entities. it's not going to check every second, for instance
yeah even if i change the trigger.to_State to the sensor.state, it's still a static value, which doesn't change
so the question is: how do i have a wait trigger fire when the current time equals a static time?
maybe need an actual sensor for comparison? https://www.home-assistant.io/integrations/time_date/
from your question, do you need a wait trigger? would a template trigger work? value_template: "{{ states('sensor.time') == '00:00' }}"
template trigger is fine, but it sounds like i still need a sensor that updates every second reporting the time
i can't use now()
why
It would be evaluated once per minute
hmm, not accurate enough. going to try the date_time sensor integration... does that update every second?
you want it to evaluate every second??
... it's not ideal i know.
but Alexa Media Player timers don't give me much of a choice
all they do is set the timestamp when the alarm will go off. there is NO state change on the thing when the alarm is actually ringing
You could make an automation that updates an input_datetime with the timestamp and use a time trigger for the main automation
maybe pastebin your script/automation so people can see what you're trying to do
the whole automation is basically this {{ states("sensor.library_dot_next_timer") == now().strftime("%Y-%m-%dT%H:%M:%S-04:00") }}
the main trigger on the automation is the # of timers on the device going from 0 to 1
Ok. Is the frequency check there faster?
There is no frequency check. It will just trigger at whatever time the input_datetime is at
And the trigger will update itself whenever the input_datetime is changed
or use an event on sensor.library_dot_next_timer both ideas would work
hmm ok. thanks 🙂
ok now i need help getting a valid timstamp out of alexa's format: 2022-03-29T18:39:54-04:00
i think it's iso..
oh hey. as_timestamp for that string just works. nice.
Hey Fes thanks for helping out. I have a question. How is {% set buses = value_json.get('buses', []) %} different from {{ set buses = value_json.buses}}?
It provides a default if buses doesn’t exist
It’s the python dictionary way of supplying a default
Same as value_json.buses | default([])
hey all just starting messing with UI lovelace Minimalist. I believe I got everything installed. but trying to configure a card as a test and always seem to be getting template is missing error?
Button-card template 'card_graph' is missing!
use lovalace normal 😜
there's 3 templates there that might work
says it's legacy, so good luck. I did a search
actually says card_graph should work and 3 variables/entities , dunno legacy stuff why not use the UI that's intended
#frontend-archived is the place for questions about your Dashboard
{{ states('sensor.nas_throughput_upload')|float < 50 }} how do I make it when the state is under 50 for 20 minutes? in a wait template
I'm trying to program an ofset for my Aqara humity sensor. I've tried the template below (both with single ' and double " ) and I can't get it to work 😦
Any tips?
- platform: template
sensors:
humidity_sensor_offset:
value_template: '{{ states('sensor.temperature_sensor_humidity') | float + 1}}'
friendly_name: 'humidity'
I would say your quote marks need to be differentiated. Try outermost double quotes and single quotes inside the outermost quotes.
Ok, so basically 2 sets, single inside, double outside
Could you write it out for me, do I'm sure I get it right?
"{{ states('sensor.xxx') | float + 1 }}"
Should consider also setting a default value for float, in case the state is not a number.
I tried exactly this (double qoutes outside, single around the sensor) and it didn't work
You can see why I am so confused
Try putting that jinja into Developer Tools > Template. What error do you get?
counting domain entities light, that should not be groups, so contain attributes 'entity_id' or contain attribute 'lights' (for the Hue groups), I cant get the reject filter right. {{states.light |rejectattr('lights')|rejectattr('entity_id')|list|count}} 'lights' does nothing, and 'entity_id' filter them all 😉
wait, this is is I believe:{{states.light |rejectattr('attributes.lights') |rejectattr('attributes.entity_id')|list|count}} .....
and yet there's this Warning:```Template variable warning: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'lights' when rendering '{{states.light
|rejectattr('attributes.lights')
|rejectattr('attributes.entity_id')|map(attribute= 'name')|list|count}}'
It will also give you this warning if you put it in developer tools, because the are lights without those attributes
It's only a warning though, the template will do what it should
If you really don't want warnings in your log, you can use a namespace and a for loop.
|rejectattr('attributes.lights', 'defined')
Aaaah, that's the magic trick! 🪄 Probably well documented in the Jinja docs
No it does not, I was only warned about it because of my log tail card 😉
btw:```
2022-03-30 13:19:45 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'lights' when rendering '{{states.light
|rejectattr('attributes.lights')
|rejectattr('attributes.entity_id','defined')|map(attribute= 'name')|list|count}}
{{states.light
|rejectattr('attributes.lights')
|rejectattr('attributes.entity_id','defined')|map(attribute= 'entity_id')|list}}'
and yet the result is perfect....
o wait... my bad, forgot the 'lights'... nvm me
It will show in the log, not in the page of the template editor
o,. yes. ofc, thats why I noticed. I dont have these configured yet in the backend sensors. Waiting for the merger of this fix tomorrow: https://github.com/home-assistant/core/issues/68836 🚀
Warnings don't show up in the template editor, only errors
warnings -> logs, errors -> template editor & logs
it's pretty annoying tbh
yeah, that s why I always have a second window of the same instance open with the logviewer addon
dont know that, is that also a HA addon?
no, it's a windows software that tracks rolling logs
like baretail, but more customizability and not 7899852834 years old
found it https://github.com/zarunbal/LogExpert. must admit I never looked for something like that on a Mac, having the logviewer available.
btw, now that you're here, might I ask you to check https://community.home-assistant.io/t/can-we-prevent-error-initializing-trigger-in-automation/406118 for a second. The issue is fixed already, but Id love to understand why happened what happened.
Whenever you need to run anything, always search "Open Source alternative for XYZ", just realize it won't be as feature rich as the alternative. And it might be a bitch to install, but it's free.
No clue, I'd have to look into the code to see what changed
it's just that the entities weren't created by that integration(now back up and running) and because of that, the automation couldn't be set up. I guess it would happen with any non-existing trigger entity_id? I would have hoped some condition (is not none) to prevent that, but apparently not
{{states.sensor.not_exist}} returns 'null' in dev tools, and in States, no column is populated at all. This time, there's nothing in the logs either....
because the states machine has guards against that
if you add .state at the end, you'd get an error
right. and {{states('sensor.not_exist')}} renders 'unknown' ofc, so maybe I can add that to the conditions
trigger.to_state.state not in ['unknown,'unavailable']
the reason you're getting the error is because of the order you're doing things
order of operations matter
your first condition should be:
{{trigger.to_state is not none and
trigger.from_state is not none and
trigger.to_state.state != trigger.from_state.state}}
not the second
and functions and or functions in code resolve left to right, and if in a list, first to last
For and, every statement must resolve true. As soon as something resolves false, it bails out with False
for or, any statement must resolve true, as soon as something resolves true, it bails out with true
this is true for every single language that exists
and it's true for home assistant conditions
I understand that yes. the reason I put the is_number() first was that seemed the quickest and shortest test available to see if the input was valid. And tbh, It cant have passed that, so why would the automation considered the rest at all? Put differently, why would it make a difference in this case? Not a number? halt.
That's what's probably producing the error
you're accessing the trigger object first in that
unsafely
objects also resolve left to right
trigger.x.y
trigger resolves first, then x, then y
ok, well, Ive adjusted all automations. just for testing purposes will create a new one with a non existing trigger entity, and the same conditions to see what gives at automation reload.
nope, that order wasnt the reason, I get the same warning for 2 new automations on a non existing entity, both with my original order, and the changed order in your instruction
Then it's beyond your control
Error initializing 'Marijn bijna thuis tester 2' trigger: In 'numeric_state' condition: unknown entity sensor.here_marijn_huis. Meaning there is some check in place before the actual conditions are processed, and we can not influence that
crosspost...
I didn't realize you're getting the error on reload, I thought you were getting it during execution
yet this feels like an issue. Ill post it as such in the tracker so to see what the dev team says
it's not an issue
your entity should exist
otherwise the automation is doing nothing
This is why things like that 'set state' python script are work arounds and shouldn't be used
just to be clear, this was of a faulting core integration, not one of my Python contraptions....
But I guess you're right, the warning does exactly what it should do, warn us for an invalid / unknown entity... back to templates 😉 thanks!
Yes, but if you use that python script and it doesn't create the entity and you reload the automations without the entities existing, thats a you problem, not a core problem
as said, it was this https://github.com/home-assistant/core/issues/68661 and it was fixed in todays dev nightly
Hi everyone,
Does anyone know a way, or a guide to control what entities are displayed on a lovelace using templates?
I'm trying to avoid extra bloat using automations to control helpers, or creating extra entities in the config.
For Example:
I have my son's bedroom light, I know I can use
{% if now().strftime('%T') > strptime('20:30:00', '%T') %}
to compare now to 8:30pm.
But I'm not sure how to then say only show the entity on the card if now>8:30pm
#frontend-archived would probably suggest some solutions, first of which is the conditional card and not far behind being custom:state-switch. Both would require you to put your template into a template sensor then use the state to determine whether a card displays or not.
Why do you want to avoid more helpers? In this case, I think the helper could save you a lot of copy pasta, as you can control the display of multiple cards based on one helper's state, rather than having to reproduce the template logic in every card.
Well my ultimate goal was to create a lovelace that is frequent tasks.
Usually around 8:30 my son needs to go to bed, so only display the button when his light is on in that window
Usually shortly after the tv turns on, so only display the tv if it's off in that window
exc exc
I've got my automations of course, but sometimes I still want a "yes proceed"
I was trying to avoid bloating the system and possibly confusing myself with countless helpers
I looked at the conditional card, but it seems to only allow control based on entity state
I'll do more research into custom state-switch though
Is it possible with a fan template to get fan speed not as a percentage in UI? I have a 7 speed fan, and would like to see 1, 2, 3, 4, ... instead of 14, 29, etc..
I haven't done that myself but have you seen this? Seems like it should help with what you're looking for
https://www.home-assistant.io/integrations/fan.template/
@tired kindle I saw that, and tried a few things with it, but couldn't seem to get it to do what I wanted.
{{ now() > today_at("20:30") }}
As for only showing the card, turn that into a binary sensor and use the conditional card or the filter card based on the binary_sensors state.
You can use preset_modes for that.
seems like from docs preset_modes is not for fan speed and not sure I see how one maps the value of preset mode to speed
it is for fan speed, it's for whatever you want it to be
that's how you'll get a dropdown with 7 speeds
I guess I'm not looking for a drop down, but to just display speed in a different means than as percentage
Heh the template fan is quite finicky. I would advise to leave the speed in the fan entity in terms of percentage, then handle the conversion to numbered speeds in the frontend with some multiplication in a template.
Or would you consider graphically representing the speed? I use custom:slider-button-card to display the fan speed percentage as a bar chart. It is quite neat and intuitive!
I'm using https://github.com/thomasloven/lovelace-slider-entity-row to show the speed. I just want it the UI to show 1, 2, 3.. 7 as that makes more sense for the Fans I have than 0, 14, 29, 43, 57, 71, 86, 100. So looking for how I might do the conversion in the frontend as you mention.
You can make a template number that has a 1-7 range
is there an example or some docs you can point at that would show how I associate the template number and fan speed?
The template will be very similar to what I linked above
here's an example template number, however you wouldn't be templating min and max https://community.home-assistant.io/t/extra-keys-not-allowed-data-min/353838/12
and it's missing the set_number action list.
which would be a service call that uses value to set the value of your fan with a fan.set_percentage service call
In that example how do you reference the value of openevse_pilot in set_value?
that example is showing you the yaml, you do not want to use the code
you want to use the code from the previous example
this
template = jinja tempate, i.e. the code
not the yaml
read pin 3 to figure out the differences between jinja/templates and Yaml
@mighty ledge sorry, I'm now confused by the references. Which example should I be looking at?
they both have relevant information
the 2nd example is showing you the yaml for an template number. The 1st example has the templates that you can use and alter for your template number.
template number is the integration.
templates, as in this channel, refer to jinja templates
which are not to be confused with the template integrations
which is what you're doing
read pin #3 on this channel to understand the differences between templates & yaml (template integration)
then combine the 2nd examples yaml (template integration for number), with code cherry picked from the 1st example (the template/jinja code)
Can you repost to the link to the 1st example
here
Hey
I want to round my values in weather forecast
show_forecast: true
type: weather-forecast
entity: weather.home
secondary_info_attribute: humidity
``` how do I see the attributes to control
I see that https://www.home-assistant.io/dashboards/weather-forecast/ does not have forecast_template for instance https://community.home-assistant.io/t/rounding-forecast-with-weather-integration-met-no/351847/2
you can't use templates in the frontend without custom cards
There really isn't a way to format the numbers in that card. You'd have to make something custom or use a custom card.
I went from this:
to this:
{% if value > -20 and value < 125 %}
{{ value }}
{% else %}
{{ states('sensor.patio_temperature') }}
{% endif %}
and now all states are unknown...
what did I do wrong??
The sensor it came from looked like this:
- platform: mqtt
name: "Patio Temperature"
state_topic: "/rtl_433/1/temperature_F"
unit_of_measurement: 'F'
value_template: "{{ [value|round(1)|float, 125.0]|min }}"
don't change your tempalte, just add a filter integration on that. Otherwise you'll be running into self referencing issues.
create yet ANOTHER sensor?
well, do you want a working sensor or do you want to chase templating errors for hours?
If that first one is a template sensor, I'd just remove it for the filter sensor
yes, then use the filter sensor
and they end up being 125F which is still nonsensical when it's 50F outside
sensor:
- platform: filter
entity_id: your_mqtt_entity_id
filters:
- filter: range
lower_bound: -20
upper_bound: 125
no template, just yaml
that might not be what you want, but you can use the outlier filter instead
to ensure that there aren't any crazy temperature jumps from erroneous readings
I feel like I'm so close with:
template:
- number:
- name: "Kumar Fan Speed"
unique_id: kumar_speed
state: "{{ (( (state_attr('fan.office_fan', 'percentage')) / state_attr('fan.office_fan', 'percentage_step'))) | round | int}}"
min: 0
max: 7
step: 1
set_value:
service: fan.set_percentage
target:
entity_id: fan.office_fan
data:
percentage: "{{ states('number.kumar_fan_speed') * 14.28 | int }}"
I get:
Ok, so I end up with ```
sensor:
- platform: mqtt
name: "Patio Temperature"
state_topic: "/rtl_433/1/temperature_F"
unit_of_measurement: 'F' - platform: filter
entity_id: sensor.patio_temperature
filters:- filter: range
lower_bound: -20
upper_bound: 125
- filter: range
[homeassistant.helpers.script.kumar_fan_speed] Kumar Fan Speed: Error executing script. Invalid data for call_service at pos 1: expected int for dictionary value @ data['percentage']
keep in mind that 150 will truncate it to 125, where you may want to just remove the 150 all together and keep the previous result. I.e. outlier filter
Your set value should be using the variable value
I was basing it off your previous comment
I have no idea why you'd apply a filter to a temperature
but you're trying to do it
Thanks!!!!
Ok, so when you get 240F, your filter will be 125, is that what you want?
I'm pretty sure the answer is no
no, that's the same result as the original template
which is why you'll probably want outlier
i just want to ignore value from out of bounds and use the previous
np
- platform: mqtt
name: "Patio Temperature"
state_topic: "/rtl_433/1/temperature_F"
unit_of_measurement: 'F'
- platform: filter
entity_id: sensor.patio_temperature
filters:
- filter: outlier
window_size: 5
radius: 10.0
ok, given the above, I am looking at the last 5 states (minutes in my polling case) and alllowing the F to change 10F within that time?
that will replace the outlier - removed value with an average of the last 5 values
oh, it keeps the outlier instead of removing it?
"The Outlier filter (outlier) is a basic Band-pass filter, as it cuts out any value outside a specific range."
it replaces the removed value with an average of your window size
continue reading the paragraph
"The included Outlier filter will discard any value beyond a band centered on the median of the previous values, replacing it with the median value of the previous values. If inside the band, the current state is returned."
reading is fundamental
personally, i'd just keep the window_size to 1
I am trying to read and undertand 😄
you aren't going to have a 10 degree change
yes
couldn't the temperature crawl outside the window if its replaced with a median?
I mean it is possible to change 10F in 5 minutes
rain, etc....
and if the returned values are constantly outside the window at that point, replacing with the mean as the temp continues to drop will result in mean values, not actual
so what's the fix, increase the radius?
the weather is crazy here sometimes
what if the last 5 readings are outside the window
you think your temperature is going to change 10F over 1 minute?
no, over 5
ok then....
Thank you Petro, I'll see how it performs.
Is there somewhere in the docs that mentions to use of value variable?
{{ media_players | first if media_players | length > 0 else none }}
i'm guessing first selects the first in the list here. Is there any documentation on this anywhere?
@next flax posted a code wall, it is moved here --> https://hastebin.com/ipihiwomuw
@next flax posted a code wall, it is moved here --> https://hastebin.com/xicufokeca
That's an inline if statement. Documentation on that would be in jinja because that's just something that jinja does
ah so it's shorthand for loop.first ?
it's "If the there are media players, choose the first media player, otherwise choose none"
got it thanks
guys any ideas why I'm getting Unexpected scalar at node end YAML here : {{ states('sensor.anniversary_saule_days_old')|int /7 |int | round(0, "floor",default)}}
https://jinja.palletsprojects.com/en/3.0.x/templates/#jinja-filters.round round() takes only 3 params, value, precision and method, so your param "default" seems out of place.
I was hoping this would work for displaying state via the icon for a motion sensor in a picture-glance Lovelace card.
- entity: binary_sensor.cam_terrasse_ost_motion
name: Motion Sensor
icon: |
[[[
if is_states('binary_sensor.cam_terrasse_motion', 'on')
return mdi:motion-sensor;
else
return mdi:motion-sensor-off;
endif
]]]
This setup show no icon, removing the icon: section reveals the icon, but it is static, not state dependant. What am i missing here?
I don't see anything in the docs that says that it supports a template there
Also, you have a mix of jinja and JavaScript in there, so it wouldn't work as is if it did
Same syntax works for label: in a custom:button-card, so I was just testing
Any suggestions how I can make the motion icon change eg. color in the picture-glance Lovelace card?
You should actually provide a default: {{ 'test' | round(3, default='no number') }} returns no number as expected
@rose scroll default works fine, but only with a default provided 🙂
This also works {{ 'test' | round(3, 'floor', 'no number') }}
it works in developer tools template, but configuration fails on validation.
I see, good to know!
What is the full yaml?
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://dpaste.org/ (you guessed it, select YAML)
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.
You still do not provide what the default is. you have only default, this should be default=something
- platform: template
sensors:
baby_weeks:
friendly_name: "Baby Weeks Old"
value_template: "{{ states('sensor.anniversary_saule_days_old')|int /7 |int | round(0, 'floor')}}"
availability_template: "{{ states('sensor.anniversary_saule_days_old') | is_number }}"
icon_template: mdi:baby
If you add availability_template like this, there is no need for default. And you need to differentiate the quotes inside your template and outside it (double quotes outside, single quotes inside, or the other way round)
The quotes were your main issue
{{ 'test' | round(3, 'floor', default) }} this will just return nothing (as there is no default provided)
OGM, thanks alot! I wouldn't guest that is the problem, will need to dig in a bit deeper how and why it`s working like that.
That was not the main problem, the problem is that you used double quotes around your template, but also around "floor"
This will break the template like this {{ states('sensor.anniversary_saule_days_old')|int /7 |int | round(0, // floor // )}}
if you add default without providing what the default is, the default will be none
So if i change doubles to single quotes and remote default, it should work?
add the availability_template like I did in my code above. This will ensure the source sensor ('sensor.anniversary_saule_days_old') is providing a number, and thus removes the need for the default
If it is not providing a number (eg unavailable which is probably the case just after a reboot) the template sensor will also be unavailable
BTW congratulations with the baby 🙂
Thanks :), yes after reboot it when unavailable for a bit, and now its displays whole number, it didn't round it, I used your example any thoughts?
@vast juniper you did rount it, by using round(0, "floor") I took that from your code
oh wait
it didn't round, that's because you should it only rounds 7 now
BTW, I guess int will be fine here, as your are using floor, so: "{{ ( states('sensor.anniversary_saule_days_old') | int / 7 ) | int }}"
int and round(0, 'floor') have the same result
But brackets around the total formula are needed if you want to round the formula result. Filters are applied first in the order of operations
Is the second "int" filter required ?
Yes, because he wants it rounded down to 0 decimals. Without it it would return a float.
got it thanks, I'm still learning 👍
Thanks alot for your help, this templating is above my current understanding 😩
hang in there buddy, you'll get it, i'm still understanding...The help is pretty good round here
It's quite basic though. What you need to know is that the state of an entity is always a string. So text. An integer is a number without decimals (eg 5), a floating point number is a number with decimals (eg 5,7)
| int converts something to an integer (if possible) and | float to a floating point number.
| is used for filters, and filters are always applied first (from left to right if more are entered)
I will play with it more when time permits, 🤣 and surely will come back for guidance 😉
Hey Fes, feel like taking a look at this one ? https://community.home-assistant.io/t/parsing-kodi-json-array-results-in-to-yaml-ha/363715 🙂
what's not working with it?
Did you follow Petros advice to add a unique id and follow the automation trace?
This is your service data (from the example you provided) scrap that
method: Playlist.Add
item:
- episodeid: plid
playlistid: 1
entity_id: media_player.lhtpc
He did not. Also, I don't see any events in the zip that show a Playlist.GetItems
Oh you are right, I was looking at the call_method
wait
I see it
it's shittily formatted
@tepid onyx I see why it's not working. The get is returning a list, are you expecting it to play the first item in the list?
I was also thinking the problem might be that
well also, his set is not correct
unless i'm missing something
the plid is not passed to anything
I guess he tries to do that here, but forgot to format it as template
kodi_set_playlist_test:
alias: "kodi set playlist test"
sequence:
- service: kodi.call_method
data_template:
method: Playlist.Add
item:
- episodeid: plid
playlistid: 1
entity_id: "{{ entity_to }}"
there's even an event that bitches about it being invalid
Event 24 fired 10:46 AM
"message": "Invalid params."
Should probably be - episodeid: "{{ plid }}"
I would assume so
Guess he needs to crate a list with a dict like episodeid: id per item. I know how to do that with a for loop an namespace, but I kinda expect it can be done without
I feel like we are missing another automation
I vaguely remember posting something about passing through a custom event
and this post does not have it
from this list:
items:
- id: 7625
label: The Madness of King Zøg
type: episode
- id: 7608
label: Stairway to Hell
type: episode
But maybe I'm missing that information you vaguely remember 🙂
As far as I can see, this needs to become:
- service: kodi.call_method
data_template:
method: Playlist.Add
item:
- episodeid: 7625
- episodeid: 7608
playlistid: 1
entity_id: "{{ entity_to }}"
how so? Are you looking at the code?
no, I can not read python, and don't have kodi to test it 🙂
ah okay
I would assume you can only add 1 thing
the an counted repeat 🙂
He's quite silent know while we are discussing his issue 🙂
But, he's still missing his piece of the puzzle
in the other automation he was trying to move things from 1 item to 1 of 2 others, with it 'guessing' the player
and the get / set actions do not pass extra data, meaning he'll need to use an event send and a wait for trigger in order to keep the context
in a single automation
like I set up in that other automation.
didn't bother looking at the other post, will do now
@tepid onyx do you mind giving some more insight in the actual issue? 😛
And if this is what you want, you can try this: https://www.codepile.net/pile/nZmn8aDJ
But I guess that needs some work on the entity_to variable, because this will be the same entity as from which the data is coming 🙂
sorry had dinner, let me catch up
yes im trying to grab a whole play list from one kodi box and add it to another kodi box
instead of one item, the json returns a bunch
I was able to add multiple items using playlist add statically but couldn't retrieve them in to a yaml list
petro solved the issue in the other post with the entity_to variable the only problem I have now is getting the json items in to a yaml list
let me check that codepile code.
BTW, you can just put the sequence from that script in the automation itself, no need to call a script here
Unless it can fail on one of the items in the list, then you could call the script once per item and run them in sequence
I added a version where it is all combined in the automation
ok thanks, let me take a look...midnight again woop
That won't work
It's setting the playlist on where it got the playlist from
It needs the interim event
yes, I know, that's why I said the entity_to variable needs work
but I think that is handled in the other forum topic
But I saw that one was solved, so I guess he needs to combine the two now
well the other thread was about files
TLDR 😅
yeah, the other thread is about playing a single file and playing it on another device
this one is about playing a playlist on another device
same shit, different data set
if it was me, i'd make an automation that handles both
I don't have a kodi either
Don't know how many kodi instances he has, but I guess, two, so he could use "{{ 'media_player.kodi_1' if trigger.event.data.entity_id == 'media_player.kodi_2' else 'media_player.kodi_2' }}"
he has 3
Oh
which is his problem
he wants buttons that take the currently playing XYZ and push them to one or the other without creating all these automations with the events
Ah
Just use a shared library then 😛
That was the reason I started to use Emby, I couldn't get the MySQL database working. Now I just use Emby
target:
entity_id: "{{ ['media_player.kodi_1', 'media_player.kodi_2', 'media_player.kodi_3'] | reject('eq', trigger.event.data.entity_id) | list }}"
But I guess a safeguard is also needed to don't let the automation trigger on the changes caused by the automation 🙂
he want's it to target a media player of his choosing
so, there was that aspect. You can see it in the other automation
the problem is that the event doesn't pass it, so it needs to be in a single automation with a wait so that the context is kept
Generate template for APEX Chart generator.
Guess I should have read the whole thing then 🙂
Hi. I want to create a template for a condition where the automation is only triggered under the condition that two sensors (IPs) do not match. I used the following template, but whether or not they match, the template always outputs true:
{{ not is_state('sensor.oneplus8_public_ip_address', 'sensor.fritz_box_7530_external_ip') }}
Where did I mess up?
Only run automation when IP of OnePlues does not match IP of FritzBox
I think you want:
{{ not is_state('sensor.oneplus8_public_ip_address', states('sensor.fritz_box_7530_external_ip')) }}
or, a little easier to read:
{{ states('sensor.oneplus8_public_ip_address') != states('sensor.fritz_box_7530_external_ip') }}
it's an attribute for an automation, if that's what you're looking for
so you can get the value just like any attribute
so you want to know the most recent last_triggered date/time of all your PIR sensors?
that should be straightforward with a template
but "last triggered" isn't a thing for sensors. you would want "last_changed"
{{ states.binary_sensor.aarlo_motion_back_door.last_changed }}
Hey Pros, what would be the correct way to add an input number (percentage_side_blinds) into my payload message, replacing the value (50 in this example)?
payload: '{ "lift": 50 }'
would the following be correct?
payload: '{ "lift": {{percentage_side_blinds}} }'
What do you mean exactly? I'm trying to have a slider to put a restful command (value between 0-100) to the api.
payload: '{ "lift": 50 }'
This works and now I'm trying to replace the value with an input number so I can use an automation that triggers on the input number to send the command.
in the automation action data the input_number state will be added
been looking at this topic: https://community.home-assistant.io/t/rest-api-with-ui-slider-not-working/282034/6
I mean that this is not the way to get the state of an entity:
would the following be correct?
payload: '{ "lift": {{percentage_side_blinds}} }'
And I pointed you to an example
Don't get me wrong, it's very much appreciated. I don't know much about templates.
How come this works for the person in the example?
payload: '{"staircase":{"segment-delay-ms": {{ wipe_speed }},"on-time-s": {{ aan_tijd }}}}'
wipe_speed and aan_tijd are input numbers
I'm trying to figure out your example to come up with one that works for me.
To start, you're not using the whole entity_id. It starts with input_number.
Second, you need to use states('input_number.whatever')
I suggest looking through https://www.home-assistant.io/docs/configuration/templating/#states
In that case I'm looking at
payload: '{ "lift": {{states('input_number.percentage_side_blinds')}}}'
You probably also need to use payload_tenplate:
payload_template: '{ "lift": {{states('input_number.percentage_side_blinds')}}}'
Am I going in the right direction?
Is is possible to create sensors, automations, scripts using jinja macros (much like what one can do in lovelace using #lovelace_gen) ? I have a number of each type that are nearly identical except for certain elements that i'd like to parameterize. I'm getting a validation error. input_text: {% macro triggered(zonename, dest) -%} {{zonename}}_triggered_{{dest}}_alert_ids: name: {{zonename}} Triggered Weather Alert IDs - UI initial: None {%- endmacro }
payload_template: '{ "lift": {{states('input_number.percentage_side_blinds')}} }'
Sorry for the spam but the code above is giving me the correct value in developer-tools > Template, but is not accepted in configuration.yaml, any idea what went wrong?
payload_template: "{{ {'lift': states('input_number.percentage_side_blinds')} }}"
oh, you had that problem too
i was just generating the entirety of the dict inside the template and happened to fix your quotes at the same time
I wonder if you may also need to cast the value to int ? payload_template: "{{ {'lift': states('input_number.percentage_side_blinds') | int(0)} }}"
Likely not in the JSON. Since states('xxx') will just return 5 and not "5", it will be interpreted by the receiver as a number. The whole payload_template is a string
Haha I would like this ability too to not have to exhaustively manually define each entity but rather dynamically generate them, something like pythonic list comprehension, or something akin to an array. But haven't found a viable option. If anyone knows of a way, would be greatly interested!
This, but with payload: because payload_template: is not accepted in a restful command.
I'm getting '{ 'lift': 64 }' as result though and I need '{ "lift": 64 }' as result for it to work.
Hey guys, are we allowed to use templates in service call buttons?
Mine keep resetting from:
type: button
tap_action:
action: call-service
service: zwave_js.set_lock_usercode
service_data:
code_slot: {{states.input_number.code_slot | int | string}}
usercode: {{states.input_number.pin | int | string}}
target:
entity_id:
- lock.assure_key_free_lever_touchscreen
- lock.touchscreen_deadbolt_z_wave_plus
- lock.touchscreen_deadbolt_z_wave_plus_2
name: Set Code
icon: mdi:lock-alert
@tired lily posted a code wall, it is moved here --> https://hastebin.com/isiyehodom
type: button
tap_action:
action: call-service
service: zwave_js.set_lock_usercode
service_data:
code_slot:
'[object Object]': null
usercode: '[object Object]'
target:
entity_id:
- lock.assure_key_free_lever_touchscreen
- lock.touchscreen_deadbolt_z_wave_plus
- lock.touchscreen_deadbolt_z_wave_plus_2
name: Set Code
icon: mdi:lock-alert
for some reason the template just gets reset. I'd fire an event, but the option to do so doesn't seem to be here anymore
@tired lily you missed the '' in your first post
And: no
type: button
tap_action:
action: call-service
service: zwave_js.set_lock_usercode
service_data:
code_slot: "{{states(''input_number.code_slot'') | int }}"
usercode: "{{states(''input_number.pin'') | int }}"
target:
entity_id:
- lock.assure_key_free_lever_touchscreen
- lock.touchscreen_deadbolt_z_wave_plus
- lock.touchscreen_deadbolt_z_wave_plus_2
name: Set Code
icon: mdi:lock-alert
You're right, the formatting is a bit new to me I must admit!
No it didn't, I tried it in the template section and receive back the correct value, but not too sure how to implement it here
Not surprised. Call a script and do it there
It seems to work when called via script, which is great. Thanks for the tip Rob!
Almost none of the standard cards support templates
Guess Markdown is the example
Hi, does anyone know a way to create a template sensor that adds up each inputNumber with the name: temperature_*
?
{{ states.input_number | selectattr('object_id', 'search', 'temperature_') | map(attribute='state') | select('is_number') | map('float') | sum }}
thank you so much 😄
looking at it now petro thakns
you around petro.:
It's returning the same error: Error rendering variables: TypeError: 'builtin_function_or_method' object is not iterable
did you see the response on the forums
I sure did, i've implemented it but it's bombing out with that error.
the new code you put in the last - service: kodi.call_method with the for loop seems to be causing the issue but i'm not sure how to debug that
that's new to me
I need to see the full error and the trace variables
it's best to respond on the forums
ok
when you respond, reply to my post, not the whole thread
that way I'll get notificaitons for it
include the trace, the variables in the trace and the error
ok i'll do that.
it's the wait trigger timing out
I included the event trace, how do I include variables in the trace?
oh right the automation trace where you said put an id: in the automation
fukn 1 am again
Hi, can I trigger an automation, whenever an input_boolean is changed from on to off with a shared name?
like:
if inputboolean.temperature_bath
or inputboolean.temperature_door
or inputboolean.temperature_floor
turns from off to on?
but I dont wanna hard code it. Is that possible with a tenplate?
guys, I'm trying to wrap my head around how all this templating works, I want to extract numeric value from sensor that displace the date. I need only month from date "2022-02-04" to be display as integer. "{{ (state_attr('sensor.anniversary_saule_days_old', 'date'))}}"
value_template: "{{ is_state('inputboolean.temperature_bath', 'on') or is_state( inputboolean.temperature_door', 'on or is_state( inputboolean.temperature_floor', 'on'')}}"
Can a split help with your question on the date spektus. eg https://community.home-assistant.io/t/split-a-value-from-a-sensor/7057
'{{ value.split("-")[2] }}'
"{{ (state_attr('sensor.anniversary_saule_days_old.split("-")[2])', 'date'))}}"
it results "none"
oh you would have to run the split on the final string ,does this work
"{{ state_attr('sensor.anniversary_saule_days_old, date').split("-")[2] }}"
ie the output from state_attr should be your date string "2022-02-04" and its on that you would try the split?
@vast juniper yeah that I know. But there will be more added down the line so I dont want to create for each new device a new rule.
Can I just compact it in a filter rule?
I'm new at this I only know this way 🙂
spektus, this should convert the date to a string if its not already in string format, otherwise the split wont work.
'{{ (state_attr('sensor.anniversary_saule_days_old, date')|string).split("-")[2] }}'
@mental violet I'm not an expert but also interested in something like you are trying to achieve. Is it that you want to trigger on something like sensors that match a certain pattern, and over time, even if more sensors get added matching that pattern, you want to trigger on them.
If true, I'd love to get something like this working also. Is there some template you need to write to first find all sensors that have a certain string in their name, in a loop maybe?
it's fairly straightforward if you do it like this:
trigger:
platform: event
event_type: state_changed
condition:
- condition: template
value_template: "{{ trigger.event.data.entity_id is match('input_boolean.temperature') and trigger.event.data.new_state.state == 'on' }}"
Nice, I spent the last hour coming up some crazy loop and then saw your simple value_template and 'match', nice.
I've done it before 🙂
I like that
where do i find a specific doco page of all these jinja functions like match, first, last etc
Jinja Template Designer Documentation
For more examples and samples, visit see this page.
and Jinja is its own thing that's used elsewhere, so you can Google for things
thanks mate... I was looking for more specific, for e.g. Petro the genius fires out all these fixes examples with ternary condtionals etc which I get from older languages (or I can comprehend) but some of the other stuff I can't find which is why I'm asking for specific references. It just blows my mind, i'm not there yet. I want to learn it!@!
like first I understand the concept but where is the doco?!@!
Those are they
yeh they and this
I go back to work and reuse what i've learnt some of the guys look at me like I've invented fire but I'd like to increase my rate and commit it to memory...Just frustrated. Yeah I probably work in a shit shop 🙂
But if i learn then I whinge less here 🍭
You could add the state to the trigger
trigger:
platform: event
event_type: state_changed
event_data:
new_state:
state: "on"
condition:
- condition: template
value_template: "{{ trigger.event.data.entity_id is match('input_boolean.temperature') }}"
I am familiar with yaml and Jinja, but am struggling with where and how templating is to be used.
This template in dev options works fine:
{% set domain = 'light' %}
{% set entities = states[domain] | map(attribute='entity_id') | list %}
{% for entity in entities %}
- {{ entity }}: off
{% endfor %}
But when I try to use it in a scene, I get an error:
2022-04-02 09:38:23 ERROR (MainThread) [homeassistant.config] Invalid config for [scene]: expected dict for dictionary value @ data['states'][0]['entities']. Got None. (See /config/scenes.yaml, line 0). Please check the docs at https://www.home-assistant.io/integrations/scene
Meaning the data source is not available there. Docos for templating mention "limited templates" for "triggers", and docos for scenes don't mention templating at all..
Can someone provide some basic guidance here on what docos I failed to read? Or is this all tribal knowledge for now? I don't mind updating documentation
Keep in mind that I have no idea if scenes are even appropriate to be used here... My idea was to have "turn off all lights" button on the lovelace UI, and potentially as something I can trigger with a physical button, too
I don’t think you can template scenes
But what you want to do can easily be done with a script or automation
And either an input_boolean as a switch or something lovelace related from #frontend-archived
Thank you, that's a good pointer right there. I'll go google some more
I think I don't need the input boolean at all for this, as it's a declarative change across many devices, but reading up on input_boolean was useful. Thanks!
You said you wanted turn off all lights button on the lovelace ui. Anyway, depending on what you are doing, setting up groups in the ui is in the current beta, due for release on Wed. Might be something you can use.
With groups, you have to list entities though, I don’t think you can template them either.
The key thing here is for it to be dynamic - without me manually enumerating each light
Are you trying to only turn off lights that are on?
Doesn't matter - if I want to turn off all lights, why would I care if some were on or off 🙂
All lights without manually typing them out
dynamic as in <something> (script/automation/whatever) figures out at the time of me hitting that switch what the lights are
I will also take advice in a form of "you are thinking about this completely wrong, try this, instead" 😄
So then you basically want to loop through the light domain and set a group
There is an example loop in the template editor and group.set is a service
But depends on how dynamic you want it. You could just make a group once and be done with it.
Ah, no - that's why I want the dynamic part - so I don't have to re-execute this
That’s what I thought
Then again - I might be a bit nitpicky here... I'm not going to have 1000s of lights
This is very good to know, thank you
Also, I guess the Areas feature can also be used if I properly set up all devices
Really depends on your use case 😉
I'm trying to discover my use case, which is the hardest part 🙂
I don't have a clear idea (yet) on how I want to use HA
Get something working. 4 years later and my stuff still changes on the regular ☺️
Just use this in script, no template needed (this was broken, but has been fixed)
service: light.turn_off
target:
entity_id: all
I decided on having this:
- Define a
input_buttoncalledall_lights_off - Through the UI, create an automation that will trigger off that "button" state - call service / Lights off / all (all has to be typed in as an entity, though...)
- Add the
all_lights_offbutton to lovelace
I like the script approach, too. less moving parts
seems inefficient, If you want to do it that way just add all your lights to a groups.yaml file and use that without the input_boolean, Or do what TheFes said 3 line script...
Morning all, Could someone tell me if on the correct lines of template to calculate cost in £ please.
{{ (states('sensor.washing_machine_energy_today') | float ) * (states('input_number.electric_per_kwh') | float) }}
energy_today is measued in kWh
electric_per kWh is recorded in p i.e. (29.4) so i guess i just need to divide the answer by 100?
{{ (states('sensor.washing_machine_energy_today') | float ) * (states('input_number.electric_per_kwh') | float) / 100}}
i think i jyst need to round it to two figures.
Make sure to use parentheses then, to ensure you're not just rounding 100
Hi Guys, I'd like read the power values of my solar system which are exposed via json. Could someone please help me to extract only the actual value in W?
{"address":"_sum/EssActivePower","type":"INTEGER","accessMode":"RO","text":"AC-side power of Energy Storage System. Includes excess DC-PV production for hybrid inverters. Negative values for charge; positive for discharge","unit":"W","value":1210}
This is the returned json when I setup the sensor like this:
- platform: rest
name: EssActivePower
resource: http://x:user@192.168.178.25/rest/channel/_sum/EssActivePower
put it in a post in the ha forum and format it
Looks like {{ value_json.value }} should work
I'll check one sec.
awesome, it worked. Thx!
I assumed that the template would be
Morning all, Could someone tell me if on the correct lines of template to calculate cost in £ please.
{{ (states('sensor.washing_machine_energy_today') | float ) * (states('input_number.electric_per_kwh') | float) / 100 | round(2)}}
How do I then get the sensor unit in front of the value? I.e. £0.11 rather than 0.11 £?
The unit of measurement is always shown behind the value
You could add it to the template itself
{{ '£ ' ~ ((states('sensor.washing_machine_energy_today') | float ) * (states('input_number.electric_per_kwh') | float) / 100) | round(2) }}
You're also rounding the integer
But then it will be string and not a number
thanks, i'm not sure what you mean by i'm rounding the integer, is this better?
{{ (states('sensor.washing_machine_energy_today')|float * states('input_number.electric_per_kwh')|float)|round(2) /100}}
Just what toml said. I don't see an issue with that one
so it is, sorry. was looking at it on my phone on the go. Thank you.
Hello,
I need a template that finds all inputnumber.temperature_ variables (I got that part). But I also have inputboolean.temperature_ that share the same name with the numbers. So my template should add up every inputnumber with temperature_ in name while their inputboolean counterpart is true/on.
So for example:
input_number.temperature_bath + input_number.tempature_kitchen while input_boolean.temperature_bath == on and input_boolean.temperature_kitchen == on and input_boolean.temperature_bedroom == off
perhaps this will help:
{% set entities = states.binary_sensor|selectattr('object_id', 'search', 'occupancy')|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|list|replace('binary_', '')|replace('_occupancy', '_temperature') %}
{{ states.sensor|selectattr('entity_id', 'in', entities)|map(attribute='state')|select('is_number')|map('float')|sum }}
with modifications for your specific needs
NICE really really cool thanks 😄
it should be simpler, but I found a bug that makes it more complicated. could only be in the beta
you can try this for the second line and see if it works for you:
{{ expand(entities)|map(attribute='state')|select('is_number')|map('float')|sum }}
so a platform: group template {{state_attr('binary_sensor.active_devices','entity_id')}} results in a [ ] list, while an 'old style' group template {{state_attr('group.indoor_temp_sensors','entity_id')}} results in a (list) and needs |list...
seems no issue, but wondering if thats per design.
Noticed that as well, btw the () list is called a tuple, in case you want to dig into it further.
The template editor shows them as a list though, if it is the only result, which can be confusing
yeah, I just used the same wording, to accent the style of template was indentical. its not only confusing, it's quite inconsistent.
@acoustic trail posted a code wall, it is moved here --> https://hastebin.com/vuvuzigitu
Hi due to changes in defaults ie float at the moment will return 0 if the value isn't valid I was changing floats to be float(0) this seems to be effective in getting rid of the warning in most integrations i used | float but this sensor broke https://www.codepile.net/pile/6xlg51DE and after a few days i noticed it had stopped updating reverting it started working again. I would like to understand why.
Anyone able to successfully pull data from thingspeak? Here's my code - I can't seem to get field1, I just get a string consisting of the date and time....https://www.toptal.com/developers/hastebin/vuvuzigitu
If I would have a list with dicts like this [ { 'where': 'basket', 'what': [ 'apples', 'bananas' ] }, { 'where': 'fridge', 'what': [ 'grapes', 'pears' ] } ] called fruit, can I somehow take out the whats and combine them in a list?
I can do {{ fruit | map(attribute='what') }} but then, how to create one list out of this selector
{{ fruit|map(attribute='what')|list|sum(start=[]) }}
like that?
['apples', 'bananas', 'grapes', 'pears']
Let me check that, but looks good.
I came up with this, but yours looks better
{% set fruit = [ { 'where': 'basket', 'what': [ 'apples', 'bananas' ] }, { 'where': 'fridge', 'what': [ 'grapes', 'pears' ] } ] %}
{{ (fruit | map(attribute='what') | map('join', ',') | join(',')).split(',') }}
But while reading the docs on what start does, I realized this is even better:
{{ fruit | sum(attribute='what', start=[]) }}
Why no cherries in the fruit bowl?
nice, I didn't realize that it could also pull out an attribute
Not the right season yet
This works as well {{ fruit | sum('what', []) }}
Hi there!
How do I go about setting a input Boolean equal to the state of a light?
I'm trying to capture the state of a light when an automation is trigger.
I have an input Boolean named "input_boolean.garagelightstateondooropen".
I have a light called "switch.garage_light".
I dont know the correct syntax... But my thought is something like this:
{% {'input_boolean.garagelightstateondooropen' = 'switch.garage_light'}%}
I would want to also do this to restore the state of the light when a different automation is triggered.
{% {'switch.garage_light'='input_boolean.garagelightstateondooropen' }%}
Cheers!
You use the service for input_boolean
Templates don't do anything to the HA state machine. They just provide output that can be used somewhere in HA
But if you want to toggle an input_boolean to match the state of a light, you can use this:
trigger:
- platform: state
entity_id: switch.garage_light
to: ~
action:
- service: input_boolean.turn_{{ trigger.to_state.stae }}
target:
entity_id: input_boolean.garagelightstateondooropen
hi, I search for a template, that does the following:
I have 2 batterylevels (A and B) and 2 devicetracker. (From me and my gf)
The batterylevel is only important, if I or my gf is at home.
The template should be on, if: A(while A.devicetracker == home) < 80 OR B(while B.devicetracker == home) < 70 and should be off, if: A(while A.devicetracker == home) >= 90 AND B(while B.devicetracker == home) >= 85
I had many if states, but now every time both our phones get charged over the threshold a loop occurs.
What if battery level A is 85 and battery level B is 75? Then they don't fit on and off
ah yes, so if one of the batterylevels fall under the 80/70 threshhold the template should be on until both batterylevels are over the 90/85 threshhold and then turn off until one of them falls under the 80/70 threshold
i did this, because I feared if I only make it: be on if >85 and be off =<84 then the template (and therfore my switch) would be like on/off/on/off after 1% charge /discharge
how can I put 2 entitie ids in a variable?
{% entites =+ deviceid 2 %}
{{entities}}``` output: ```['deviceid 1' , 'deviceid 2']```
oh wow ok thanks you
sorry, pressed enter too soon
{% set entities = [ 'device_id1' ] %}
{% set entiteis = entities + [ 'device_id2' ]
{{ entities }}
As far as I know the =+ notation doesn't work in jinja
But you can add lists to lists
Is there anyway i could craete a mediaplayer that uses everything from the Apple TV media player i already have except for the volume, that would be my sonos beam?
thank you^^
universal media player: https://www.home-assistant.io/integrations/universal/
But that would be someting for #integrations-archived
is there a similar filter to replace that just adds a string?
Could you give an example?
|replace(homeentities,homeentities+'_battery_level') I tried this, but that just changes the array to a string and adds battery_level behind that... 😦['sensor.test2', 'sensor.test1']_battery_level
Hmm, you can if you loop through them, not sure if there is an easier way:
{%- set ns = namespace(battery=[]) %}
{%- for tracker in homeentities %}
{%- set ns.battery = ns.battery + [ tracker + '_battery_level' ] %}
{%- endfor %}
{{ ns.battery }}
yes. and with the test for 'home': {%- set ns = namespace(battery=[]) %} {% for d in states.device_tracker if d.state == 'home' %} {% set ns.battery = ns.battery + [d.entity_id~'_battery_level'] %} {% endfor %} {{ns.battery}} The allenentities you use in your test is not needed. you already select the device_tracker domain, so just leave that out.
thinking this might need an extra test, to see if the actual entity exists
BTW, this will result in device_tracker.something_battery_level so I think you also neet to replace device_tracker with sensor
{%- set ns = namespace(battery=[]) %}
{% for d in states.device_tracker
if d.state == 'home' %}
{% set ns.battery = ns.battery + [(d.entity_id~'_battery_level')|replace('device_tracker','sensor')] %}
{% endfor %}
{{ns.battery}}
you could use:
{%- set ns = namespace(battery=[]) %}
{% for d in states.device_tracker | selectattr('state', 'eq', 'home') %}
{% set ns.battery = ns.battery + [ 'sensor.' ~ d.object_id ~ '_battery_level' ] %}
{% endfor %}
{{ns.battery}}
or that 😉 (much better)
maybe this: {%- set ns = namespace(battery=[]) %} {% for d in states.device_tracker %} {% set id = 'sensor.' ~ d.object_id ~ '_battery_level' %} {% if d.state == 'home' and states(id) not in ['unknown','unavailable'] %} {% set ns.battery = ns.battery + [id] %} {% endif %} {% endfor %} {{ns.battery}} or TheFes's format: {%- set ns = namespace(battery=[]) %} {% for d in states.device_tracker| selectattr('state', 'eq', 'home') %} {% set id = 'sensor.' ~ d.object_id ~ '_battery_level' %} {% if states(id) not in ['unknown','unavailable'] %} {% set ns.battery = ns.battery + [id] %} {% endif %} {% endfor %} {{ns.battery}}
The ~ (read as "tilde") operator is used to join operands as strings. It converts neighboring operands into strings and concatenates them.
and you have to declare it first if it's part of an array
that fixed an issue. nice
or:
{%- set ns = namespace(battery=[]) %}
{%- for d in states.device_tracker| selectattr('state', 'eq', 'home') %}
{%- set id = 'sensor.' ~ d.object_id ~ '_battery_level' %}
{%- if id in states.sensor | map(attribute='entity_id') %}
{%- set ns.battery = ns.battery + [id] %}
{%- endif %}
{%- endfor %}
{{ ns.battery }}
If you want to optimize that for speed. Make a list outside the loop to look at. Otherwise the states function is actually more optimized
Ah right
states.sensor | map(attribute='entity_id') will iterate the collection every entity
that's typically bad
yo petro
currently in the template devtool and i get the TemplateSyntaxError: unexpected char '\\' at 2327
@tepid onyx I just replied on the trhead
really I was going to give up and go with a rest temple
The player.add or whatever the call is, is missing required information
{%- set ns = namespace(battery=[]) %}
{%- for d in states.device_tracker| selectattr('state', 'eq', 'home') %}
{%- set ns.battery = ns.battery + [ 'sensor.' ~ d.object_id ~ '_battery_level' ] %}
{%- endfor %}
{{ ns.battery | select('in', states.sensor | map(attribute='entity_id') | list) | list }}
Like this?
ok thank you Petro
That'll still have the same problem
it has to be on a separate line
{%- set ns = namespace(battery=[]) %}
{%- for d in states.device_tracker| selectattr('state', 'eq', 'home') %}
{%- set ns.battery = ns.battery + [ 'sensor.' ~ d.object_id ~ '_battery_level' ] %}
{%- endfor %}
{%- set sensors = states.sensor | map(attribute='entity_id') | list %}
{{ ns.battery | select('in', sensors) | list }}
{% set filter = states.sensor | ... %}
{{ ns.battery | select('in', filter) ...
yes
although, I think I might be mistaken with that
your 1 liner might work
I'd have to see the debugging
how does one do that? see a trace of a template?
select is a method, so it's probably resolved once before getting placed into select
I've changed my mind. this will work.
Hehe, okay! Good to know
morning fog
Time for coffee ☕
Exciting
It requires you to debug into the actual code
I.e. you probably won't understand how to do it unless you set up a dev environment and learn the development process
..... thanks for the compliment 🙂
It's no easy feat, so it's not meant to be an insult
if you haven't setup a dev environment before, it's very hard
that's before even using the debugging ability
I know!
then, once you're there, you need to understand the objects and code flow (the stack trace)
ok, so well just keep asking you 😉
im going for a smoke
{{ service_calls | selectattr('entity_id', 'defined') | map(attribute='entity_id') | list }} can I check somehow if the entity id is provided as a string or as a list? If it is a list I want to sum them, if it is a string I want to create a list
list == is iterable, dict == is mapping, keep in mind a string is iterable. So to check explicitly for a list... is iterable and is not mapping and is not string
okay, but nobody will provide a dict when they enter entity_id's in a service call right?
hahahaha, never trust users
.. let me check
users will always find a way to break what you did
hehe
So this will do I guess
{% set e_s = service_calls | selectattr('entity_id', 'defined') | map(attribute='entity_id') | reject('mapping') | select('string') | list %}
{% set e_l = service_calls | selectattr('entity_id', 'defined') | map(attribute='entity_id') | reject('mapping') | reject('string') | select('iterable') | sum(start=[]) %}
{% set e = e_s + e_l %}
And then add data.entity_id and target.entity_id.. So many ways to enter an entity_id to a service call 😛
where is service_calls coming from?
Well, from a script call, in which it is possible to provide actions (using the action selector)
It's for my Google Home Resume script, I let them provide the service calls in the script call, so I can determine which entities are the target, so which need to resume afterwards
The script performs the actions later on, using a repeat (and I take out the service calls out of the provided actions, because service calls have template support on service, data and target)
Now I think of it, the entities I should only take out those provided in data and target als the others ones are not used in the repeat
when you provide 1 item without it being a list, does the configuration accept that?
if yes, that would be a mapping
I will do some tests, but thanks!
I had a lot of for loops to this before, this is much better
This works:
{% set service_calls = [
{
"alias": "Send TTS message",
"service": "meida_player.media_play",
"entity_id": "media_player.woonkamer_mini ",
}
] %}
{% set e_s = service_calls | selectattr('entity_id', 'defined') | map(attribute='entity_id') | reject('mapping') | select('string') | list %}
Isn't this what you just said? 1 item without it being a list?
yes but how is this being passed?
to the script
home assistant did this "smart" thing where service calls don't require a -
action:
service: ....
is the same as
action:
- service: ...
top is a dict, bottom is a list
if that isn't possible for whatever you're creating, don't worry about it
fyi | select('string') effectively rejects mapping, so the | reject('mapping') isn't needed
Ah, that's what you mean, I'll give that a test
hoping someone can help me, I'm trying to figure out why a single light entity would be counted as two when using a state sensor to display number of lights on.
If the light is on, it shows 2. If I turn it off, it shows 0. There is only one light.desk entity so I'm very confused
I'm just using {{ states.light | selectattr('state','eq','on') | list | count }}
I think it is in a group actually, does that see the group as an additional entity?
is it a light group?
yeah it is
A light group is also a light entity, so it will be listed under states.light
{{ states.light | rejectattr('attributes.entity_id', 'defined') | selectattr('state','eq','on') | list | count }} should remove the group
Unless that has been added in 2022.4
{{ states.light | selectattr('state','eq','on') | map(attribute='entity_id') | list }} will at leas show you which lights were included in your count
I've added this to the check for service calls
{% set action = [ action ] if action is mapping else action %}
{{ action | selectattr('service', 'defined') | list }}
Yeah that works
could have use iif 🙂 iif(action is mapping,[ action ], action)
or in one line {{ iif(action is mapping,[ action ], action) | selectattr('service', 'defined') | list }}
guys,
on home assistant website, i read that this
{{ states.sensor.formula_one_sensor.attributes.next_race.Circuit.circuitName }}
is not the right way to do this, but how to get this value the right way??
{{state_attr('sensor.formula_one_sensor', ??)}}
{{ state_attr('sensor.formule_one_sensor', 'next_race').Circuit.circuitName }}
Sorry 'bout that
no problem it's working now
@astral ginkgo posted a code wall, it is moved here --> https://hastebin.com/ucusinoras
@astral ginkgo posted a code wall, it is moved here --> https://hastebin.com/losinozelo
Can someone help out? 🙂
Where do you want to use this template?
I want to use this in a markdown card 🙂
What is it that you actually want to display. What would be an example of the text? In Dutch would be fine
I want to display all the energy cost components in a detailed way, preferably in a table, column 1 will contain the name and column 2 the price
I am able to format the table, that's no problem
But I am having issues with iterating in an interation
{% for kost in energie.elektriciteit.kosten %} {% for kost_detail in kost %} {{ kost_detail }} {% endfor %} {% endfor %}
i thought this would be correct, but unfortunately it's not
What would you expect to get as result of your template? It's still not clear to me what you want to achieve
I will try to explain it differently
So we have the following array:
{%
set array = {
"colors": {
"blue":"1",
"red":"2",
},
"animals": {
"dog":"1",
"cat":"2",
},
}
%}
If I want to list all possible options, I use this code:
{% for test in array %} {{ test }} {% endfor %}
the result I get is:
`colors
animals`
what I want as a result is:
`blue
red
dog
cat`
@astral ginkgo posted a code wall, it is moved here --> https://hastebin.com/givofuwoto
but that doesn't work either 🙂
{% set ns = namespace(values=[]) %}
{% for d in array %}
{% set ns.values = ns.values + array[d].keys() | list %}
{% endfor %}
{{ ns.values }}
returns [ "blue", "red", "dog", "cat" ]
that works, thanks
Now I am trying to make it work for my original template
And that isn't working 😦
@astral ginkgo posted a code wall, it is moved here --> https://hastebin.com/imuruwuvup
fixed it!
{% set ns = namespace(values=[]) %}
{% for d in energie.elektriciteit.kosten %}
{% set ns.values = ns.values + energie.elektriciteit.kosten[d].keys() | list %}
{% endfor %}
{{ ns.values }}
thank you so much! :d
Please stop posting code walls
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://dpaste.org/ (you guessed it, select YAML)
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.
And use code formatting for smaller posts containing code
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://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).
Ok will do
@dense stream posted a code wall, it is moved here --> https://hastebin.com/muhomedipi
specific error for that code it "TypeError: can only concatenate list (not "str") to list"
You need [item], but it's still not going to do what you want. You need to use a namespace and do {% ns.newList = ns.newList + [item] %}
awesome that worked thanks!
What would a template look like that randomly pick one of about 20 strings and changes it every 30 seconds?
The first part is a simple list and |random. The second is an automation or template sensor.
- trigger:
platform: time_pattern
seconds: "/30"
sensor:
- name: random_string
state: >-
{% set strings = ["foo", "bar", "blah"] %}
{{ strings|random }}
hey,
iam trying to get a list of all my entities with the device class "motion" i tried this but it throws me an error
{{states.binary_sensor|selectattr('device_class','motion')}}
okay states.binary_sensor does not make sense ....
So I tried this and it doesn't show anything in the card now for that
Currently {{ states.light | rejectattr('attributes.entity_id', 'light.other')
| selectattr('state','eq','on') | list | count }} lights are on.```
light.other is the light group that that light was in
Hello! I am having some issues with ESPHome and pulling some existing entity values via Yaml, any chance someone can help?
never mind, think I fixed it!
I want to get a baniry sensor that will give me a result from a bunch of vector algebra of the sun position and variables describing the window (binary sensor to see if the sun is outside of the window, but checking if window is not covered by e.g. a balcony). The algebra I can handle, but doing this in jinja2 seems a little inefficient. Is there an alternative approach?
a python script, but it'll have it's own problems @ startup if you're creating a sensor. Templates are easily the best option, as they are fast and update on state changes.
is there some neat way of writing a long template that just brute-forcing it?
I don't know what you mean
if you have the calculation, it's probably an easy template
I can help if that's what you're asking...
I mean that I will have to define lots of variables, functions for scalar products, I guess trigonometry is there in jinja2 and wrap everhyitng in {%%}. and code server doesn't seem to be able to do parenthesis checking or entity_id lookup inside templates, so my code's always very buggy
entity_id lookups are supported in the template editor of HA itself
> Templates
It immediately shows if the template can be rendered and the result
syntax highlighting is a bit better in VSCode though (with the HA configuration extension) and you can also optionally do bracket highlighting there
entity_id lookup in templates in VSCode would be nice though
yeah, I like having the whole thing in vscode. But point taken than I should just do the template in the editor -- i usually play around there and then move it to vs
I also usually just do it in VSCode, but also because I usually have a lot of variables defined somewhere else in my scripts, or even coming from other scripts, which doesn't make it easy to have a working template in the template editor
And the entity_id autocomplete is new since 2022.3, so I'm kinda used to having to enter them myself
I just write everything in the editor and then paste it in vscode after I add the proper spacing with SHIFT + ALT + Drag
if you share your code, I can help you with the buggyness
shift+alt+drag?
Oh, I use CTRL + [ and CTRL + ]
amazing!
Hi all, I need your help to understand how is working templates... Could you please tell me what's the main difference between templates and inputs that we can create in HA (automation/entry...) ?
I also tried to understand the example on the website of HA : https://pastebin.com/F2kyZ7zs
I can create it, import it on my lovelace card, but if I click on it, the button goes back to off after about 3 seconds: I don't understand this behaviour.
Thanks for your help.
This is the actual template part in that code {{ is_state_attr('switch.blind_toggle', 'sensor_state', 'on') }
there is more explanation in the pinned posts on this channel
Maybe have a look at this: https://community.home-assistant.io/t/psa-template-and-yaml/348967
Ok I will check them.
I'm sorry, I don't understand your answer. I already tried to delete the "value_template" line but I still have this behaviour...
Your value template is incorrect and that's what determines the state of your switch. So you click the button in the interface, it assumes it's turning on, the value template then executes the code and shut's itself off because the code is wrong.
If your value_template was correct, you wouldn't see the behavior.
Ok 👍 . Thanks for your explanation. I will test it later. 👍
If I delete the "value_template" line, It works fine, but I have two different buttons (two lightning).
very confused, the message portion with templating works fine in the developer tools but i get an error when trying to save the script that "Message malformed: extra keys not allowed @ data['test_script']"
https://pastebin.com/FAMPeN1i
That's correct, petro didn't say you should remove it, but it should contain a correct template
You've put an empty service call on line 30
i did yes, that has been removed but was not what was causing the issue 🙂
Well the term message in the error message does not necessarily refer to the message in the notify service call
So don't pin on that. You can replace it with just a simple string like "test" and see if that resolves the error. If not, it's caused by something else
What is the code now?
was a stupid issue......
i added a name at the top but was testing by pasting into the visual editor
i.e. at the top was the name of the script where as it should have just been the alias
have these for my Hue tap switches: state: > {% if state_attr('sensor.auditorium_tap_switch','last_triggered') is not none %} {{trigger.event.data.subtype}} {% else %} Not yet tapped {% endif %} attributes: time_fired: > {{as_timestamp(trigger.event.time_fired)|timestamp_custom()}} last_triggered: > {{trigger.event.time_fired.isoformat()}}
starting up with Unknown. which is expected. However, If I click the first time, it shows 'Not yet tapped' for state. Seems 1 step behind.?
I get a value (=0.03) in the template editor for following:
{{states('sensor.switch_01_current')}}
But I get an error when I try to compare:
{% if {{states('sensor.switch_01_current')}} | float > 0 %}
Appliance running
{% else %}
Appliance not running
{% endif %}
TemplateSyntaxError: expected token ':', got '}'
Any idea what may be wrong with the comparison syntax above?
Awesome!! Thanks!
Is this will be working assuming climate.radiator_obyvak has attribute current_temperature which I previous status want to store in sensor "Radiator obyvak - posledni teplota please? This is template for platform template which will be in config.yaml "```- trigger:
- platform: state
entity_id:- climate.radiator_obyvak
sensor: - name: "Radiátor obývák - poslední teplota"
state: '{{ trigger.from_state.attributes.current_heating_setpoint }}'```
- climate.radiator_obyvak
So I have this but it does not give me previous state but current. Ie if heating setpoint is set to 21 and I set it now to 0 the sensor should give me 21 but gives me 0. Why so pls?
It triggers on all changes
You should change the trigger so it only triggers on the change of that specific attribute
- platform: state
entity_id: climate.radiator_obyvak
attribute: current_heating_setpoint
oh, or I can simply use scenes ... which came up to my mind now....
In that case I can also use scene variable name
Many roads to Rome
can I load attributes from scene entities?
Unfortunatelly I will need that sensor :/
Well, change the trigger then :)
Hey folks, I am just starting to learn how to work with templates. I wanted to test a simple template. (If spot 1 or 2 on send message {{ trigger.id }} is on). That works I get that message only thing that confuses me is that istead of the id "Spot1" or "spot2" it shows 0 and 1 like "0 is on" Can someone tell me how I get him to take the correct ids? Or is it possible to make him spill out friendly names?
trigger.id is correct, but what id you actually put in the id field for your trigger?
it has the entity id and device id
You probably either want {{ trigger.entity_id }} or you need to provide a trigger id ( that's what {{ trigger.id }} refers to).
ah ok thanks I will try that
Thank you very much!
Solved my problem 😄 thaks
dears, why does this do not want to work? ```
service: climate.set_temperature
data:
temperature: sensor.radiator_obyvak_posledni_nastavena_teplota
target:
entity_id: climate.radiator_obyvak
Because you need to use a template and not direct reference to the entity
okay.Thank you! 🙂
But I do not know why this for example works without template ```platform: numeric_state
entity_id: climate.radiator_obyvak
attribute: current_temperature
above: sensor.0x00158d0003f0d48a_temperature
because that's designed to work without needing a template
okay 🙂 guys thank you! 🙂
HI Guys,
I would like to create an entity for e.g. my water meter where I manually update the value on my Dashboard. I have been looking at Input Number, I I don't think this is what I am looking for. It should behave like a utility meter, just with me beeing the "input sensor". Any hints / directions on where to look?
The goal is to already collect some data until I have a automated solution. But having an update like once a week is still a lot better than not having it at all...
You can create an utility meter out of your input_number
Hello, I am trying to get a notification if one of my plantsensors detects low water. I get how I could use a Template but every plant has a different min_water value. Is there a way to work around this (without studdying rocketscience preferably)
Is there maby a way to get the alias or something? Sometimes my ids are very long and techy
You can use {{ state_attr(trigger.entity_id, 'friendly_name') }} for the friendly name
Or provide an id to the trigger and use that
Perfecti will try that is there a documentation where these comands come frome? I couldnt finde those. Or are they in your head?
Check the pinned posts of this channel
{{ state_attr(trigger.entity_id, 'friendly_name') }} seems to not do the trick. But I will read up on that thanks
Should work, but not if you run the automation from Configuration > Automations, as there is no trigger then
I think I need a break of fresh air... well that was dumb XD
Later I will get back on the topic of getting the plant sensor values int templates
how do i pull open_sensors: null attribute from alarm sensor for in a actionable notifications tried {{open_sensors}} but doesnt work ?
lots of examples here: https://www.home-assistant.io/docs/configuration/templating/#states
but I don't know what you mean by this:
pull open_sensors: null attribute
if you mean "display the attribute", then {{ state_attr('alarm_control_panel.something', 'open_sensors') }}
the null there is confusing
yes when one door or windows is opened it says which door/window , null = nothing open
ty
yes it now displays the binary_sensor which is opened , can i attr more from open_sensors like friendly name ?
if it outputs an entity_id, then yes
is its output when triggering from frontdoor {'binary_sensor.frontdoor_contact':'open'} like to clean it up
to only display frontdoor
some test code;
{% set attr = {"binary_sensor.office_motion_sensor": "open"} %}
{{ expand(attr.keys())|map(attribute='attributes.friendly_name')|join(', ') }}
-> Office Motion Sensor
can i set a wildcard for .office_motion_sensor ? * ?
you said that the attribute contains the sensors that you care about. what would a wildcard do?
well alarmo open_sensors attribute has multiple sensors which can populate it ?
that's just test code that you need to modify for your needs
I showed you how to get the attribute, then a way to take the attributes and extract the friendly name for each and display it as a comma-separated list
all the pieces are there
trying to trigger an automation every minute... what's the best way to accomplish this?
tried triggering on a template of {{ now() }}
how do i achieve the following
i have sensor attribute "today" its a fixed format with 24 values per day. comma separated. first value is for 00:00 next value is for 01:00 etc.
i want to create a template sensor that gives me the average value out of the three next hours from the attribute value.
Sensor attribute value: 0.6, 0.3, 0.3, 0.3, 0.3, 0.7, 2.1, 2.3, 2.3, 2.1, 1.3, 1, 1, 1, 0.9, 1, 1, 1.6, 2.1, 2.3, 2.2, 1.7, 1.4, 0.8
{% set values = [0.6, 0.3, 0.3, 0.3, 0.3, 0.7, 2.1, 2.3, 2.3, 2.1, 1.3, 1, 1, 1, 0.9, 1, 1, 1.6, 2.1, 2.3, 2.2, 1.7, 1.4, 0.8] %}
{% set hour = now().hour %}
{{ values[hour:hour+3]|sum/3 }}
there are definitely corner cases and maybe off-by-one errors left as an exercise to the reader
cool, thanks, ill give it a go
the values are not static, meaning they are state attributes and will change every 24h. So, i need first grab the state attributes then do the calculation. i realise it will be some error around midnight, but this is fine for now. i can add the tomorrow value later.
sensor.cost attribute today: x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x,x
HI Guys,
I did ask this here earlier today.
I would like to create an entity for e.g. my water meter where I manually update the value on my Dashboard. I have been looking at Input Number, I I don't think this is what I am looking for. It should behave like a utility meter, just with me beeing the "input sensor". Any hints / directions on where to look?
The goal is to already collect some data until I have a automated solution. But having an update like once a week is still a lot better than not having it at all...
TheFes suggested I use an input number within the utility meter. My problem is now:
The input number requires a min and a max value. That seems wrong for my purpose. What do you think?
…and more important: Utility meter does only accept a sensor as source no input_number. So this does not work.
@tribal prairie how about using the File sensor? https://www.home-assistant.io/integrations/file#sensor
append your meter reading to that file when you collect it and the sensor will pick it up and record in the database with the timestamp. set it up with the proper units and you can use it w/ the energy dashboard etc
@fossil totem That is interesting. I would prefer having a way to use an input filed in the app to populate the sensor. But this is an interesting way. I am just wondering on how to get the readings into the file with as little effort as possible now.
Thanks!
I'm trying to display everyone that is home in one sensor with some nice formatting. With a lot of help here a few weeks ago I managed to get this working:
{% for person in expand('input_boolean.luukaanwezig', 'input_boolean.rensaanwezig', 'input_boolean.joostaanwezig', 'input_boolean.arjanaanwezig', 'input_boolean.jennyaanwezig')| selectattr('state','eq','on') | sort(reverse=true, attribute="name") %}
{%- if loop.first %}{% elif loop.last %} en {% else %}, {% endif -%}
{{ person.name }}
{%- endfor %}```
Unfortunately it doesn't work as intended when everyone is away. It just remembers the last person that was home. How can I add something to this so it display "none" or something like that.
Probably not the best template but it does the job
Hmm why use input_booleans to track person presence, as opposed to device trackers or the actual person entity? Those also take states on and off only.
But anyway, I would suggest to first simplify your code for testing purposes. Can you remove all but 2 of the input_booleans, then manually set them to off in Dev Tools > States, then see what this template returns in Dev Tools > Templates?
Yea I'm experimenting with it myself right now. Not figured it out yet
I use booleans so I can manually enable and disable them for testing purposes. The booleans get enbabled/disabled by a group state. That group contains multiple device_tracker entities for each person.
maybe wrap the whole thing in an if statement, with one big or condition
if at least one of them is home, then do the template you have above, if not, some other text you want when nobody is home.
also i'm confused by the if loop.first followed immediately by an else clause. feels like a rudandant statement maybe?
Honestly, I have no idea😅 My templating skills aren't very good, someone else made most of this for me.
Yea that should work, but there is an easier way I think. Like just checking if the output is empty
If that's possible
I'm thinking whether the problem is with how the states of your input_booleans are set, rather than with the template logic itself. The template seems legit from first glance, but I don't have TheFes's Jinja Fu spider sense 😂 😂
Template currently works fine, but when using it in a sensor it "remembers" the last person when no one is home. Don't know what's the problem with the booleans, also works fine and the state gets changed by Node-Red. I do this with quite a lot of sensors.
So when all input_booleans are off and you put the template into Dev Tools > Template, what is the output?
Good day folks. I use a input_select to store the state of my washing machine. Values are either empty, running or full. The state changes based on a few sensors on the machine. An automation monitors an zwave plug then sets it to "running" when a certain wattage is hit. Once that wattage drops for a period of time an automation sets it to "full". Then when a door sensor detects the door being opened for 15 seconds, an automation sets the value to "empty". On my lovelace (dashboard), I have an Entity card, which I'd like the icon to change based on the state of the input_select. But, I can't figure out how to make it do that.
I've looked at a select template, but that requires an action...but I don't want an action to occur when it changes. Am I missing an option somewhere?
Here's how I do that:
{%- set peopleHome = states.person | selectattr('state', 'eq', 'home') | map(attribute='name') | list -%}
{%- set peopleNumber = peopleHome |length -%}
{%- if peopleNumber == 0 %}
Nobody is home!
{%- elif peopleNumber == 1 %}
{{ peopleHome[0] }} is home!
{% else %}
{{ peopleHome[:-1] | join (', ')~' and '~peopleHome[-1] }} are home!
{%- endif %}
{{ now().timestamp() | timestamp_custom('%a %-I:%M %p') }}```
I use that as a template widget for my Android watch.
I would suggest to use 3 conditional cards based on the state of the input_select to display a different card per state. Or if you dabble in custom components, you can use one custom:state-switch card to achieve the same thing.
Or you can use a custom:button-card with the icon changing based on the state of your input_select, using a template.
Interesting. hadn't thought of that method. I'll also take a look at that card as an option.
Thank you!
Hello. I need some help changing a template. I have tried various combinations with no success. I need to change the variable room["climate"] to variables.climate. This is a template from dwains which im trying to use in a different project. Any help would be great. https://www.codepile.net/pile/Rd0DJEd8
This is supposed to go inside a custom button card.
Hello
ok I have figured out its this that doesnt work. The is defined check doesnt let the card load. Am I doing something wrong? I cant even get this test to work. https://www.codepile.net/pile/xYA0MDGB
{% if states.media_player.some_name.state is defined %}
if it exists actions
{% else %}
if it doesn't actions
{% endif %}
It's a bit of a work around, but you can create a template sensor out of the input_number, then use the template sensor for the utility_meter
I have MQTT lights, but if I group a large amount together i get an issue of only some doing what they are meant to when I change them. Adding a delay works for simple on off commands or a pre determined value "blue" "red" etc but is there a way that I can use the colour wheel / temperature / brightness and then "send" that information through to all the lights one by one?
I know the plan is to move a lot to the UI. Does that mean templates will be done away with or will they be possible to do from the UI where you would create the name for example in the UI and just drop in the template and it would format for you rather than doing it in the configuration or templates yaml?
That's good thank you.
Wow, that looks & works great! I've modified it to work with my input_booleans😁 Thanks!!
Is it safe/possible to refer to the state of the sensor itself in the template defining the sensor? I am trying to add a condition in the template in a trigger-based sensor and return the value unchanged if it fails to pass.
That should be fine
Hey guys,
Is delay_on still valid? I'm getting errors
https://www.toptal.com/developers/hastebin/anigowikot.yaml
This is in "Sensors"
I want to know how long a sensor (binary_sensor.test) was in the state off. With history_stats I was able to create an entity that shows the cumulated off-state for today, but not how long the current off time is (i.e. since last state change). I just want to have a time like "binary_sensor.test has been off since 2 hours" which resets with the next on/off toggle.
The templates I have found in the forums always use some complicated set of actions, triggers etc. - right now I have the binary sensor with its attached state. The data all seems in the logbook already, so i pretty much want to display the time from the last entry from the logbook
I use something similar, see if this works
It's never been supported for a sensor. Perhaps you want a binary_sensor?
unfortunately I don't have that attribute .last_changed
Your indentation is also incorrect there: https://www.home-assistant.io/integrations/template/#legacy-binary-sensor-configuration-format
I have a fun jinja coding challenge! I want the average temperature of occupied rooms based on motion within the last n minutes. Any smart way to do this without a ton of if statements?
Thanks, so I put the following under binary sensor
It's working fine without delay. But when I put the delay HA gives me the following
Invalid config for [binary_sensor.template]: [off_delay] is an invalid option for [binary_sensor.template]. Check: binary_sensor.template->sensors->testsensor->off_delay. (See ?, line ?).
https://www.toptal.com/developers/hastebin/ibitubunik.yaml
I've been trying to get this to work for the last 2 hours lol
Would be great if you can put something together for me to test out, please 🙂
your indentation is still off. please see the examples in the docs
Got it, this now is the working version
I solved this by using history stats for each area's motion devices to get a ratio of time in the last 30 minutes each area was occupied, and used those % as weights in a weighted average temperature. This is better since walking into a room for a second won't impact the average very much
Rest Sensor Templating issues.
when I do a curl, with the api key it works. (from a different box on same network)
curl -X 'GET' 'http://thisismyipaddress/api/meal-plans/today' -H 'accept: application/json' -H 'Authorization: Bearer myapikeygoeshere
it spits out all of the expected JSON
@willow rapids posted a code wall, it is moved here --> https://hastebin.com/axamohuhar
It's delay_off not off_delay
Any thoughts on 255 char of sensor.rest_command limitation?
It's a thing
should this still work correctly as documented here: https://docs.mealie.io/documentation/community-guide/home-assistant/ ?
if I follow it to the letter I'm getting ''' homeassistant.exceptions.TemplateError: UndefinedError: 'value_json' is undefined '''
probably isn't returning JSON, or is just failing
instead of using localhost use your IP address of your homeassistant server. Is your secrets.yaml setup correctly, have you put the Bearer token directly in the yaml code instead of using !secrets like the URL example says
newb question: i'd like to customize the device_class of multiple binary sensors based on an attribute shared by the devices. i know that i can do this in customize.yaml for each specific entity. just wondering if there is a way to do this with less toil. i thought maybe templates could be used.
I've used the IP as well as localhost and for the bearer I tried it both ways also.
Ok. If I remove the template it exceeds the 255 characters. So I feel it is necessary, just need assistance on the wording.
Hi guys. A very simple question, but I cant seem to get my head around template sensor rounding. I have a water meter that reports in m3. I want to display liters that were used daily, but without any decimals. I now have this sensor: https://www.codepile.net/pile/JQBARag7. How do I get rid of the decimal?
Try round(0) or, if it returns the same number of decimal places all the time, string indexing. Eg. "(xxx.000 | string)[:-4]" will give you "xxx"
by use of | round(0), but make sure to add parenthesis around the formula, otherwise you are only rounding 1000. Filters are applied first in the order of operations.
as round also automatically cast the value to a float, you could also use | round(3) instead of | float in this case
how do I set the entity_ID using a template? It always seem to be name, but the name I want to be a friendly name and I can't seem to be able to set a friendly name using the "new" format (compared to legacy) https://www.home-assistant.io/integrations/template/
I tried setting the unique_id but it doesn't seem to have any impact on entity id
The unique_id is as an identifier by HA itself, it has no influence on the entity_id (unless you con't provide a name). However if an unique_id is provided, you can change the enitity_id by editing the entity in the GUI
If you omit the name the entity_id will be sensor.template_{{ unique_id }}
ah! very interesting. I would really love to be able to set more entity_id's. This seems to be a thing all over the system that entity_id is something I set later via the UI. Maybe I should go ahead and omit the name and set that later then to get "clean" entity_Ids
with my wait template
{{ is_state('input_boolean.office_status', 'off') or is_state('input_select.home_status', 'off') }}
how can I make it to wait for the OFF state to be off for 2 minutes before moving on with the automation?
the OFF state of input_boolean.office_status anyway - the other can stay is it is
so technically wait until input_boolean.office_status is off for 2 minutes
The following template is still not doing what I want to achieve:
{{ 'Deutschlandfunk' in states('media_player.sonos_kuche.media_channel') }}
What I actually want to do: I want to check whether the device (media_player.sonos_kuche) is playing a certain channel (Deutschlandfunk).
The issue is that the channel name is not fixed and can be extended by whatever is currently playing, e.g. ("Deutschlandfunk" or "Deutschlandfunk - Nachrichten").
So, I cannot simply check the content but need to workaround to use a template.
Sadly, this seems to not work yet, as I get:
Result:
result: false
entities:
- media_player.sonos_kuche.media_channel
even though the channel is indeed "Deutschlandfunk".
I think the mixing of entity and state is probably wrong. But I do not know how to fix it. I simply do not understand the documentation.
Any idea what I'm doing wrong?
If I check
{{ 'Deutschlandfunk' in states('media_player.sonos_kuche.media_channel') }}
in the template tab, I do get a "false".
But if I check media_player.sonos_kuche in the states tab, it says:
media_channel: Deutschlandfunk
Just did some testing:
{{ (state_attr('media_player.sonos_kleines_bad', 'media_channel')) in 'Deutschlandfunk' }} returns "true"
{{ 'Deutschlandfunk' in states('media_player.sonos_kleines_bad') }} returns "false"
{{ 'Deutschlandfunk' in states('media_player.sonos_kleines_bad.media_channel') }} returns "false"
Essentially, I would like
{{ (state_attr('media_player.sonos_kleines_bad', 'media_channel')) in 'Deutschlandf*' }}
or
{{ (state_attr('media_player.sonos_kleines_bad', 'media_channel')) in 'Deutschlandf.*' }}
(or something similar) to return "true".
I really don't get it.
very good hint! I now omitted the name from my templates and I am lot happier because I can create clean entity_ids as well as unique_ids.
Can I attach a template-entity to a device? I.e. I have an existing device (e.g. binary sensor with on/off & battery) - can I add a templated entity to that device? Would I use groups for that?
Nope, you can not add entities to device
Is it possible to have multiple riemann sums in your config file? I’ve double and triple checked but my 2nd integral is not working
Yes it is.
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://dpaste.org/ (you guessed it, select YAML)
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.
Share your config in #integrations-archived . This has nothing to do with templates.
Somewhere halfway the first sector. I've made 1 file for both tempate and config but got it configured seperatly in HA
I'm experimenting with writing down a time something triggered into a sensor. This below never seems to trigger -- the state is always unknown. Any idea why?
- trigger:
- platform: state
entity_id: input_boolean.test_switch
from: "off"
to: "on"
sensor:
- name: Kids Pani Hana Arrival Time
icon: mdi:baby-bottle
unique_id: "woutmpo4utmp384tmp348ytpmj3984yt"
state_class: measurement
device_class: date
state: "{{ now() - timedelta(hours=1) }}"
of course. a typo. thanks!
ok, so I've edited the stupid typo in the timedelta, but it still doesn't trigger when I flip the test_switch
I get this in the log
"sensor.kids_pani_hana_arrival_time rendered invalid date 2022-04-08 15:23:46.702796+02:00"
I thought I was supposed to supply a datetime object to the state if the device_class is a date?
You should use device_class: timestamp. device_class: date only expects the date YYYY-MM-DD
Thanks, that works now!
Is there a device_class for a sensor which would contain a time duration? I want to keep track of the time that someone was present during the day and not sure if I should return seconds, which I could then convert/display in hours or I should just fix my unit of time and track hours>
Device class is not required, you could just leave it empty. But they are listed here https://www.home-assistant.io/integrations/sensor/#device-class
And sorry to spam: can I give a trigger_based a trigger id and then do an if test for it inside the template?
Yep
Does someone know what is going wrong here? I've a template sensor that displays the volume of my Sonos One speaker. Using a very simple {{ state_attr('media_player.one', 'volume_level') | float * 100}}. In state developer tools the volume shows as 0.28. But the template dev tools & the sensor shows 28.000000000004 for some reason
Ahh okay, I'll do that. Thanks!
Maybe I'm forgetting something but when adding a simple | round(1) to the end of my template nothing changes?
What are parens? English isn't my first language😅 and where?
That did the trick, thanks!
Is it possibe somehow to remove a key from a dict in jinja?
So loop through all keys and build a new dict but ignore the ones I don't want
Or with a filter
Let me think about that 🙂
Assume I have:
{% set example = { 'a': 1, 'b': 2, 'c': 3 } %}
How would I remove example.a then?