#templates-archived
1 messages · Page 75 of 1
well... no I think he wants to show C - H
I was simply telling you to add quotes in teh first place, and you went with something completely different
so used to that mistake, immediately assumed wanted to subtract
The second one is just a working example, still want to use the first one i posted.
K going to try there
That's #frontend-archived
How would I go abouts adding an else statement showing off when lights are off?
{{ ((state_attr('light.room', 'brightness') / 2.55) | round(0) ~ '%') if is_state('light.room', 'on') }}
Wrap it in either a {% if %} or use {{ iif() }} around it.
Something like this?
{% if is_state('light.room', 'off') off }}
I think the same thing can be achieved using else as well?
Hold on. Let me get to my PC. Trying to do this mobile sucks. lol
Ok... now I can actually see what you're doing... lol (yeah, that didn't work like I thought it would)
{{ ((state_attr('light.room', 'brightness') / 2.55) | round(0) | string ~ '%') if is_state('light.room', 'on') else 'off'}}
This one is working great, thank you both 👍
Thanks @haughty breach
For iif it would be :
{{ iif(is_state('light.room', 'on'), ((state_attr('light.room', 'brightness') / 2.55) | round(0) | string ~ '%'), 'off')}}
Alternative
{{ (state_attr('light.room', 'brightness') | default(0, true) / 2.55) | round(0) | default('off', true) }}
Although that will also return off when the brightness is set to 1
Alternative which avoids that
{{ state_attr('light.room', 'brightness') | multiply(1/2.55, 'off') | round(0, default='off') }}
In HA dashboard this shows as "Away" {{ states('person.esperance') | title }} but when I put it in a template it says Not_home. Is there a way I can make it show what the dashboard is showing instead of the state?
state_translated('person.esperance') should do it.
Trying to wrap my head around something. is_state is really just a "condensed" method (function?) of using states(xx.yy) == whatever. state_attr is basically the same concept but with an attribute. And then the same goes for iif; it "condenses" an if statement. They'll all perform their respective tasks but the is_state, state_attr, and iif are a bit easier to read. (I'm slowly starting to understand conditional (ternary) operators; the above examples took me a moment to grasp.)
There are some differences. One thing you need to know is that states('some.entity') will return unknown when an entity doesn't exist, while is_state() will always return false when the entity doesn't exist. So is_state('some.entity', 'unknown') will return false when the entity doesn't exist, and states('some.entity') == 'unknown' will return true.
For iif there is also a difference. Both the part for true and false will be rendered. So this can lead to errors.
Example:
{% set x = 'some.entity' %}
{{ iif( x | has_value, x | float * 3, 0) }}
{% set x = 'some.entity' %}
{{ x | float * 3 if x | has_value else 0 }}
The first one will give an error when some.entity is unavailable, the second one won't
Quick one that I can't seem to find the answer on - Is it possible to reference a list index of a filter function, not a variable? Found the first function.
Template for context: {{ ['media_player.plex_plexamp_neutron_linux','media_player.plex_plexamp_neutron'] | expand | selectattr('state','in',['idle','playing']) | sort(attribute='last_changed',reverse=True) | map(attribute='entity_id') | list }}
TheFes I think I gotcha. So for better error handling (when it is needed), states('some.entity') and if (instead of iif) would be a better way to go. (While working on something else, I just noticed there's is_state_attr available, too.)
Hiiii
So I'm trying to set up an automation based on the result of a template which looks if there are a set of strings in the 'condition' attribute of my weather integration.
I have this:
{{ state_attr('weather.my_location_hourly_forecast', 'forecast')[0:5] | map(attribute='condition') | list | select('equalto', 'clear') | list }}
Which lists off the entries that have 'clear' as a condition, but I need something equivalent to
select('equalto', 'clear' or 'sunny' or 'partlycloudy')
IE I need to have multiple arguments to all produce a result in the list. Any suggestions?
Approximate RGB value in a template
Basically the same thing applies to is_state_attr()
The forecast attribute is depreciated, this doesn't work anymore since 2024.4
You should use the service call and then use the service response
And to answer your actual question, you can use select('in', ['clear', 'sunny', 'partlycloudy'])
I'm trying to write a condition template, and I want to check if two datetime objects are more than 5 minutes apart
I've got this so far:
{{ utcnow() - states.sensor.niro_ev_19_data.last_updated }}
I'm struggling to get the "more than 5 minutes" part though
{{ ( utcnow() - states.sensor.niro_ev_19_data.last_updated).total_seconds() > 300 }}
!!
OK, I think that does it ☝️
Or
{{ now() - states.sensor.niro_ev_19_data.last_updated > timedelta(minutes=5) }}
No need to use utcnow() as both datetimes are timezone aware
If I post
{{ now() - utcnow() }}
in the the Developer Tools > Templates tab I see
-1 day, 23:59:59.999959
I expected that to be closer to 0
uh that's 0.000041 from 0.
Or is that a strange serialization saying "negative one day plus 23 hours 59 minutes..."
OK, thanks!
Sorry, another confusion...
{{ strptime('2024-05-05T09:09:45+00:00', '%Y-%m-%dT%H:%M+00:00') }}
gives
ValueError: Template error: strptime got invalid input '2024-05-05T09:09:45+00:00' when rendering template 'strptime test {{ strptime('2024-05-05T09:09:45+00:00', '%Y-%m-%dT%H:%M+00:00') }}
But my template looks like a good match to me :/
{{ '2024-05-05T09:09:45+00:00'|as_datetime }}
what rob said, but your format was not correct
you're missing seconds
if you want to create a datetime object for today at 9:45, use today_at. {{ today_at('9:45') }}
@dry sierra ^
Thx both - my input string had no seconds, but the as_datetime filter looks easiest - I had tried datetime as a filter, seen it fail and got lost in strptime
Thank you!
My instance isn't up to date, so this should still work but it's good to know it's depricated. I'll get it working just to know I can but I won't rely on it.
Any idea where to find all of the tests you can use in select()? I was looking for quite some time and all I found were a few examples, no exhaustive list
Here's a list of built in tests
https://jinja.palletsprojects.com/en/3.1.x/templates/#list-of-builtin-tests
Tests added in HA can be found in the templating docs
https://www.home-assistant.io/docs/configuration/templating/
Thanks!
- condition: and
conditions:
- condition: template
value_template: "{{ trigger.to_state.context.id != none }}"
alias: context.id not = none
- condition: template
value_template: "{{ trigger.to_state.context.user_id == none }}"
alias: context_user.id = none
- condition: template
value_template: "{{ trigger.to_state.context.parent_id == none }}"
alias: context_parent.id = none
alias: Test if triggered from a physical wall button press
I'm using the trigger contexts to automate from physical button presses and have just noticed that if I turn a light group (helper) on or off, it registers as a physical button press. Does anyone know how I could filter these out. Is this a bug?
Working on a template that notifies us for the undone chores and then clears the chores without altering the list. Code in the thread
Ah I figured it out - the light group included a Z2M light group, which is registered as a physical press when switched.
Is it possible to create custom device/entities out of scripts? I have a vent fan that is controlled with IR and have 3 separate scripts to control it. One toggles on and off and the other two are scripts to trigger power up/down. Can I create a custom device/entity, so that when it is opened it contains all the buttons and states I expect to see as you do in other devices "more-info" cards?
Have you looked at using a Template fan https://www.home-assistant.io/integrations/fan.template/
Does anyone know how i can use card_mod to modify the new tables group headers? I am open to other solutions as well that dont envolve card_mod
I know the css tag for it is group-header, i added this into my theme:
skynet_theme_v2: card-mod-theme: skynet_theme_v2 card-mod-view: | .group-header { font-weight: 800; font-size: 18px; color: #FFC10A; }
you can do that with browser_mod addon, you basically would design what you want to go inside your more-info card on your dash and that's hidden by default, then when you click on your entity it will open that design as a popup. I know not really elegant, but it does work well. Here is a link how to do it: https://github.com/thomasloven/hass-browser_mod/blob/master/documentation/popups.md
this is something for #frontend-archived
How can I use a template to define how often a button is pressed? It seems that isn't easy possible without a lot of helpers?!
so my template returns a number like 1 or 12 - and I want to push a button 1 or 12 times ...
this will most likely be an automation
you need to set a datetime the first time something is pressed, and if you press the button again within a time window, it increments a counter
outside the time window, it goes back to 1
2 helpers (input_datetime, counter), 1 automation
1 template (in the automation)
so I have a script which is trggered by a cronjob - so every 10 min. My template returns 2 - so I planned to use while count thing and just use the template. But I guess that's not working. So I do need a helper counter?
yes, you need a counter
you can attempt to do this all in a single template sensor, but it would be a pita
hmm I see. I tried to avoid that, since my script already got like 30... but fine
just make a separate automation
exactly how I described
it does not need to be in your script at all
the counter is the entity you use
for conditions etc
right ... I'll try that. Thank you
Hello there, I asked this question in the #automations-archived and I was send here to ask. So what I want: I need to detect who (I want user name of the account) did the last change in the HVAC mode. I want to use it in scenario, where I will send notification to the last person that changed the mode. I wasnt able to find anything online 🤷
That will only work if the adjustment is made via the HA ui
If that's what you want, you'd need an automation as a base bfore I can give pointers on the template needed to make that happen.
or we could just go straight to a script.
having some trouble with making a "sensor" which is reporting uptime in "s" to display in HH:MM:SS. i'm able to add the sensor to a dashboard but when i try to just check the value of the sensor via Developer Tools, the sensor is coming back as "'sensor' is undefined"
if i want to make a template sensor that reports a color (for example, RGB values or XY chromaticity coordinates), does anyone have an idea on how i could report the "state" which consists of a list of several numbers? Or should i do something like split it into multiple numeric sensors, one for each value? (so i'd have separate sensors for color_x and color_y)
I really don't think you want uptime sensors to count in seconds, that's just going to thrash your state machine infinitely forever
where is it getting the color from?
just make it a datetime when it boots, and you can display the relative time since then
how would i do that?
hm I'm not familiar enough with espresense to say I guess
@fallen charm in this case it's calculated in the template sensor, but i guess the same issue would also apply if someone had a color sensor connected to an esp32 or someting
calculated from what?
for sensor is undefined it is complaining that you need to put quotes around the sensor name (also use states and not state_attr)
for HH:MM:SS display a sensor must be device_class: duration
@fallen charm sun elevation; i found some math that i wanted to try that might let me figure out a color that approximates the color of the sky :)
ok. the easy answer is that you could put it into a color format that is a single number, with the easiest but least differentiated being RGB hex
got to that point, then started wondering how to actually report a color that other things could consume, e.g. an automation to set a light. I'd prefer to report xy chromaticity.
you're converting to it though anyway, so you could just move the math to where you're using it
if you need two numbers to be reported separately, you can do something silly with math and then undo it at the end point, or you can output it in two variables
hmm, so two separate numeric sensors then would probably be easiest. or i suppose I could have the state be some combined representation then put the more useful split values in attributes.
or if you want to play with attributes, you could have it do all of the conversions and output them all into attributes
would it be simpler to create a timer when "Connectivity" = Connected and then simply display that value?
well, i guess i'll try it with attributes. still need to figure out if i can simplify this calculation enough that it's maintainable as a template; i might end up wanting to turn it into an actual integration instead :)
wayyy above my paygrade. i'm a very basic user 😦
i might just disable that sensor and just rely on "connected" or not
Hi, i try to multiply a entity with a helper to get a price in euro as output.
My ha config is splittet into folders, this means i have a sensor folder with .yaml files inside for waste_collection (working fine with different .yaml files).
I have an template folder with a .yaml file for garbage_collect (working fine too).
I added those 2 files in my configuration.yaml with those 2 lines. sensor: !include_dir_list sensor / template: !include_dir_list template. (Seems working).
Now i try to add the following. Now i tried to add a new sensor in my sensor folder.
sensor:
- platform: template
sum_of_entities:
friendly_name: "Daily_Strom_Export_in_Euro"
unit_of_measurement: "€" # Ersetze "Einheit" durch die entsprechende Einheit
value_template: "{{ (states('sensor.growatt_today_s_grid_export') | float * states('input_number.aktueller_strompreis_export') | float) | round(2) }}"
My goal was to get a number as a result.
When i add this sensor as a new .yaml, and try to check the output in developer tools i get "Konfigurationswarnungen
Platform error 'sensor' from integration 'daily_export_price' - Integration 'daily_export_price' not found." while i search for "daily_strom" i get no output. Does anyone have an idea ?
Thank you in advance.
You can make a template sensor — you trigger off whatever you use as a source, eg solar elevation, in the action part you can perform your calculation and save it into variables. Then you save those variables into the attributes of the sensor. These do not have to be a number, but can even be a dictionary or a list. But… if you are trying to do lights that track the temperature of the light, and get warm at night, check of the adaptive lighting HAVS integration
yeah, i already use adaptive lighting; i want to do something a bit trickier where some lights are based on ambient sky (shadow) light and others on direct sunlight :)
Depending on whether the sun is on that side of the house? Interesting…
well, just depending on sun elevation. i haven't considered direction yet, but that could be neat too :)
for the sun direct light i'm just using a color temperature, which is fine as a sensor since it's a single number.
But adaptive lighting basically computes the temperature curve on the basis of the elevation, at least in the default settings, doesn’t it?
not directly; you set a min and max color temp, and it fades between those based on time of day (so noon is always max color temp regardless of the sun's actual elevation)
it does by default use the sun position to determine sunrise, sunset, and solar noon times.
Oh I see. It just uses the local time. I guess it saturates the temp pretty soon after sunrise. You’ve sent me on a rabbit hole though: https://media.springernature.com/full/springer-static/image/art%3A10.1038%2Fsrep26756/MediaObjects/41598_2016_Article_BFsrep26756_Fig1_HTML.jpg?as=webp
heh. yeah; "blue hour" twilight simulation based on scattered light is a whole other thing :)
(in many cases for indoor lighting you wouldn't actually want to simulate that)
Are you building a matrix with a fake sky?
nah, i just have a few light strips that i wanted to use to cast an ambient-ish light onto a white ceiling.
no idea if it's a good idea or not, but it seems like it could be neat looking
@rare karma I converted your message into a file since it's above 15 lines :+1:
I have a helper with my cats dates of birth how do I create a sensor to show their age on my dashboard?
https://github.com/Petro31/easy-time-jinja is a set of templates that can do that for you to make a sensor.
I use it for my days...
https://github.com/SirGoodenough/Home-Assistant-Config/blob/4624b4abbd571316a131554dd8542a49798fc0e3/templates/sensor/time_s-tmpl.yaml#L15 @spark flicker
Urgh... Message malformed: Expected a dictionary @ data['action'][0]['choose'][2]['conditions'][0]
This means so the first item under action (-> choose) and the third item under choose (so the third - conditions: ...
I can't see how that is different to the others though 😕
https://pastebin.com/57AVh9w2
ARGH, figured it out, it was the indentation of the default keyword... no idea why that would be ['choose'][2] if it counts all options that would be 7, or if it's conditions as one [0] then it should be [1] 🤷♂️
Can i find out what room a device is in based on the device_id?
{{ area_name(device_id) }}
i need a template wich indicates if a value of a sensor is greater then a value of a helper. If the value of the sensor is greater, the value of the helper should be refreshed with the value of the Sensor. How can i arange this?
That is an automation. Template trigger "{{ states('sensor.foo')|float(0) > states('input_number.bar')|float }}" and in the action use the input number set value service with this for the value "{{ states('sensor.foo') }}"
You could also just use a numeric state trigger. It will take the input number entity_id in the above option. However that trigger will not monitor the input number for changes like the template trigger will. So if you change the input number to be below the sensor then only the template trigger will fire immediately. The numeric state trigger will wait until there is a change in the sensor.
alright, so i took your example and change the Sensor and input to this: {{ states('sensor.solar_erzeugung_absolut)|float(0) > states('input_number.solar_peak')|float }}
is this correct
You missed a quote at the end of the sensor.
That's what I proposed 🙂 #automations-archived message
I have a sensor that shows the pm2.5 level but I want to make a template sensor that shows the AQI using this: https://cms.iqair.com/sites/default/files/inline-images/AQI-Chart_US.jpg
What would be the easiest way to do something like this:
pm2.5 of 0 is 0 AQI
pm2.5 of 6 is 25 AQI
pm2.5 of 12 is 50 AQI
but all the increments in between that are in that chart?
I already have something similar for the text:
{% set pm25 = states('sensor.view_plus_pm25') | float %}
{% if pm25 < 12 %}
Good
{% elif pm25 < 35.4 %}
Moderate
{% elif pm25 < 55.4 %}
Poor
{% elif pm25 < 150.4 %}
Very Poor
{% elif pm25 < 250.4 %}
Severe
{% else %}
Hazardous
{% endif %}```
us the compensation integration
@storm thunder I converted your message into a file since it's above 15 lines :+1:
it's a trigger based template sensor, it won't track changes to any entities, so the message is correct
this should be your code too btw, you have a few mistakes
template:
- trigger:
- platform: state
entity_id: sensor.luftsensor_temperatur
not_to:
- unavailable
- unknown
sensor:
- name: Luftsensor Temperatur Test
unique_id: 'LuftsensorTempTest'
unit_of_measurement: '°C'
device_class: temperature
state_class: measurement
state: >-
{{trigger.to_state.state}}
https://community.home-assistant.io/t/use-last-value-instead-of-unknown/614331/5
According to this it 'listens'
But anyway if this isn't the right way to track a sensor that's not always online, please guide me to the right direction 🥺
This should work, but just a guess, you are pasting that entire code in the GUI for a template helper?
I posted the correct code, just copy/paste what I wrote
Hi ... i have a problem with utility meter after few days.
- name: consumocasa
unit_of_measurement: 'kWh'
state_class: total_increasing
device_class: 'energy'
state: >-
{% set sunp = states('sensor.shelly_em_channel_1_energy')|float(0) %}
{% set enelp = states('sensor.shelly_em_channel_2_energy')|float(0) %}
{% set eneld = states('sensor.shelly_em_channel_2_energy_returned')|float(0) %}
{{sunp + enelp - eneld}}
#value_template: "{{ (states('sensor.shelly_em_channel_1_energy') | float) + states('sensor.shelly_em_channel_2_energy') | float) - (states('sensor.shelly_em_channel_2_energy_returned') | float)) | round(2) }}"
availability: "{{ (states('sensor.shelly_em_channel_1_energy') not in ['unknown', 'unavailable', 'none']) and (states('sensor.shelly_em_channel_1_energy') not in ['unknown', 'unavailable', 'none']) }}"```
this template sensor measure the total consuption of my house
the daily cycle utility meter that work perfectly for several months stop working
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.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
@jagged halo ^
Don't forget you can edit your post rather than repeatedly posting the same thing.
sorry
and you can copy the backticks from the bot if you can't find them on your keyboard 🙂
i have italian keyboard
the utility meter count only 'sunp'
thanks petro ... excuse me
until max a week this worked perfectly
Anyone can help me?
what's the problem?
if it's not adding the other sensors, make sure they are available
your template looks fine
sensor.shelly_em_channel_2_energy and sensor.shelly_em_channel_2_energy_returned
make sure they are not unavailable
worked until the last update
that's great, the problem is not the template
the problem is those sensors
so, please verify they are still working
the three sensor are sunp: solar production, enelp: energy from net, eneld: energy to net. The formula is the total energy consumption on my house
the sensor are available
Look up those entity_id's in developer tools -> states page
Again, the template is fine. The only thing it can be is those entities
either a miss-spelled entity_id or the entities are unavailable
there were issues with the shelly integration this past release
what does it return if you paste the yaml above in developer tools > template?
ahhhh
how i can add a screenshot?
@jagged halo Please use imgur or other image sharing web sites, and share the link here.
Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.
the value is correct, but the utility meter with the daily consumption return value that is only the daily sunp
and not the daily cycle of the formula sunp + enelp - eneld.
Yea posted that to Helper -> Template -> Template for a Sensor. Wasn't that right?
no, that whole thing goes in configuration.yaml
trigger based template sensors are not supported through helpers, like Petro mentioned this should be placed in configuration.yaml
I see. Thank you!
@rare karma I converted your message into a file since it's above 15 lines :+1:
@rare karma I converted your message into a file since it's above 15 lines :+1:
Oh come on
I can’t even edit it
Would be better if I’d have some preview, there is no way I can see if the message comes through properly beforehand
you can expand it
Not on my phone unfortunately
You can always use dpaste or some other site
good morning all. I cannot find the answer to my question online
is there a way of checking in the template an area the entity is assigned to?
(background - i am using Alarmo as my alarm and want to add a snapshot of CCTV to the alarm notifications, but with a lot of different sensors in different rooms of my house which can trigger an alarm its only feasible to detect which camera i want to snapshot using the area)
You might find some of this code useful; once you get the area you’ll want to map that to a camera entity
thanks!
Can I manual run a templete?
@devout holly I converted your message into a file since it's above 15 lines :+1:
i'm trying to consolidate my battery notification automations using templates, i hope to call something like {{states.sensor.devicename_internal_battery_level}} in place of hard-coded battery percentages, but that's returning way too much info for my needs.. is there a good way to refine the results further? (i tried simply appending .current_capacity but that didn't do it)
if you want the state of the entity, than {{states('sensor.devicename_internal_battery_level')}}
What you currently have is the state object which has a lot more info.
Hi all, is it possible to add somehow so this template switch always have state off between time 09:00-18:00 ? or is it not possible? 😛
switch:
- platform: template
switches:
motion_lights_on_off_vardagsrum_emby_playing_helper:
friendly_name: Motion Lights On/Off - Vardagsrum - Emby Playing helper
value_template: >
{% if is_state('media_player.emby_shield_tv_valbo', 'playing') and is_state('input_boolean.motion_lights_on_off_vardagsrum', 'on') %}
off
{% elif is_state('media_player.emby_shield_tv_valbo', 'playing') and is_state('input_boolean.motion_lights_on_off_vardagsrum', 'off') %}
off
{% elif is_state('input_boolean.motion_lights_on_off_vardagsrum', 'off') %}
off
{% else %}
on
{% endif %}
turn_on:
turn_off:
You can add another if statement with now().hour comparisons
I don't see how that's useful for a template switch, though
It looks like you just want a template binary_sensor based on what you posted
okey, i will change to that ! 🙂
oh brilliant, thanks!
sry but do u know how to type that line or have one u can copy paste here? i cant code :/ hehe
Why is a binary sensor better? so i learn why :p
You're doing nothing in the turn_on and turn_off parts. It's a switch that doesn't do anything
okok i see 😛
@solemn zodiac I converted your message into a file since it's above 15 lines :+1:
{% set incomplete = [] %}
{% set today = now().strftime('%A') | lower %}
{% set array = states.input_boolean|selectattr('entity_id', 'search', today+"_.*_brendyn")|rejectattr('entity_id', 'search', today+"_.*_chore") |rejectattr('state', 'search', 'off') |map(attribute='entity_id') |list %}
{% for entity in array %}{% set chore = entity+"_chore" %}{% if is_state(chore, 'off') %}{{chore}}{% do incomplete.append(1) %}{% endif %}
{% endfor %}
{{ incomplete[0] }}
input_boolean.thursday_teeth_brendyn_chore
input_boolean.thursday_homework_brendyn_chore
input_boolean.thursday_tidy_brendyn_chore
input_boolean.thursday_laundry_brendyn_chore
input_boolean.thursday_mail_brendyn_chore
Without the set incomplete = []
and the do incomplete .append
and the {%incomplete[0] %}
it produces a list of entities that haven't been checked off.
chore list, essentially.
I'm trying to set a global variable, or just one outside of the for and if loops here.
and set it to a value of anything.
{% set incomplete = chore %} sets it to 6 different variables, which is fine.
but as soon as the if loop exits
the variable resets to undefined.
and if i define it, it's like they're stored independently
i've tried starting with {% set incomplete = '' %}
and at the end, echoing incomplete
but it's just blank
or if i set it to 'pizza'
at the end, it's 'pizza
'
regardless of what it got changed to inside the if statement
was trying what this said here, but no success
Got it I have to use from_json
"{{ (trigger.json | from_json)['status'] }}"
"{{ (trigger.json | from_json).status }}"
Is it possible for a device id to find out the area the device is in?
{{ device_attr('entity_id_or_device_id', 'area_id') }}
great thanks
i know the markdown card doesn't support tap_action natively... but i'm trying to get this card somehow clickable to navigate to another dashboard that is a subview. I could but a HTML hyperlink to the URL of the dashboard but that breaks the ability to go back to the previous dashboard. anyone know of, perhaps, any custom stuff on HACS that might accomplish this?
this is what is in the markdown card, if it matters {% for story in state_attr('sensor.breaking_news','channel').item %} {%- if loop.index == 1 %} <h4>{{story.title}}</h4> <td> <img src="{{ story['media:content']['@url']}}"/> </td> {% endif %} {% endfor %}
does this look right?
- service: squeezebox.call_method
data:
entity_id: media_player.squeezeplay
command: playlist
parameters: |
- loadtracks
- {{trigger.id}}.titlesearch="{{ states('input_text.music_search')}}"
hi! moving from #general-archived . due to a custom integration, i have states coming in as text and not numeric (https://imgur.com/a/yGOKjbY)
would this template work to get it to the actual value?
{{ states('sensor.basement_server_room_primary_water_heater_kw_hours') | replace(" Watts","") | trim | float}}
it does not seem to 🙃
wrong entity 🤦🏻♂️ working!
damn, no way to duplicate a helper in the UI?
Nope
Hey RobC -- lot time no hair pull out
chuckles
I'm migrating HA hosts, and am working on the custom sensor templates to get it working again, and I think there might have been some changes that are impeding me;
- sensor:
- name: blah
state: >```
im assuming is not the way it's done anymore?
although it could be the state template i am using, but I wanted to check top-down
That's the modern format
Thanks Fes, I actually just figured it out ... thanks though
it was in the state template
Ok not sure how to do this. I have 14 calendars I want to condense into one and then use template triggers on the automation that pulls from them (7 chore lists, 7 calendars to reset them and 7 to send notifications). What does that template look like to filter for a calendar event? I've never used templates as triggers for an automation
Hi I have a problem with my my binary sensor template for a system im making before using the if statements to use it my method was working but when I added the if statement it does not update at all
template:
binary_sensor:
- name: "Garage Entry Alarm"
state: >
{% set alarm_system = is_state('input_boolean.house_alarm', 'on') %}
{% set garage_entry = is_state('binary_sensor.garage_entry', 'on') %}
{% if alarm_system and garage_entry %}
Open
{% else %}
Closed
{% endif %}
device_class: door
Binary sensors need a template value of true or false, not Open/Closed. The device class takes care of it. And I'd add a unique ID, so you can change some stuff via the UI.
Use the following template, for example:
template:
binary_sensor:
- name: "Garage Entry Alarm"
state: "{{ is_state('input_boolean.house_alarm', 'on') and is_state('binary_sensor.garage_entry', 'on') }}"
device_class: door
unique_id: someuniquestring
(or yes, on, enable for true and anything else for false)
As everything else (like Open or Closed) are interpreted as false, the binary sensor with your template will always be off.
Small addition, number above 0 will also render it true
Wasn't thinking about numbers 😅
oh ok thanks for the the help
Hey folks; been running up against something and it's confusing me. In the docs for templating, it says that functions like floor_id and area_id "can be used as a filter", but it's not clear how? Is there a quick and easy way to, for example, filter a list of entity_ids by testing which floor they're on? Logically: {{ [entities] | select('floor_id', 'first_floor') }} ?
(yes, I know that syntax doesn't make sense by itself, but it's just to give a sense of what I'm attempting)
assuming [entities] is the result of an expand() or similar; how can I filter it to 'only entities with a specific floor_id()'? There's some syntax trick I'm missing, and the documentation teases me with 'can also be used as a filter' in all sorts of useful places 😉
({{ [entities] | map('floor_id') }} gives me the floor ids of each entity in the list, but obviously that's not useful by itself)
What it means is that you can either use floor_id('light.ceiling') (=function) or 'light.ceiling' | floor_id (=filter)
What you need is to check the entities in your list against the entities in the floor. Unfortunately there is no floor_entities function yet, so you need to work around that
{% set floor = 'living_room' %}
{% set floor_entities = floor_areas(floor) | map('area_entities') | sum(start=[]) %}
{{ your_entity_list | select('in', floor_entities) | list }}
Ah yeah, that's similar to what I'm doing now; just was wondering if there was a potentially cleaner way to do it. Many thanks!
oh... using sum like that is a nice idiom. makes note
Well, I hope there will be a floor_entities function/filter in the 2024.6 release, that will make it easier
then I can use a simple "in" filter yes
"in" test, but yes 🙂
what I really want, of course, is ultimately a "where" filter {{ entities | where('function') }} or {{ entities | where('floor_id', 'eq', 'ground_floor') }} - ie: call the function on each item in the generator/list and filter by result of a function call.
like a combination of map() and select()
So that it matches the syntax used for is_state etc it should be select('is_floor', 'ground_floor')
that would also be cool
Maybe in_area, on_floor, has_label
Hello. How can I change this to have 1 decimal point? ${Number(states['[[humidity]]'].state).toFixed()}%</span>`
nvm i think i figured it out
${Number(states['[[humidity]]'].state).toFixed(1)}%</span>`
if ur still wondering this should do it
Hello. Why isn't this working? I get an error with float:
service: climate.set_temperature metadata: {} data: hvac_mode: cool temperature: {{ float(states('input_number.settemp_klimaanlage_max')) }} target: entity_id: climate.klimaanlage_schlafzimmer_max
templates must have quotes around them
Only this part isn't working. temperature: {{ float(states('input_number.settemp_klimaanlage_max')) }}
I want to make an automation which uses numbers from the input number helper.
I tried it with quotes and it still doesn't work
then update with what you tried and what didn't work about it
When I triy this:
service: climate.set_temperature metadata: {} data: hvac_mode: cool temperature: "{{ float(states("input_number.settemp_klimaanlage_max")) }}" target: entity_id: climate.klimaanlage_schlafzimmer_max
I get this error:
expected float for dictionary value @ data['temperature']. Got None
input_number.settemp_klimaanlage_max is set to 21
With this one I have the same problem:
delay: hours: "{{ float(states("input_number.timer_klimaanlage_max")) }}" minutes: 0 seconds: 0 milliseconds: 0
you can't use double quotes inside double quotes:
"{{ float(states("input_number.settemp_klimaanlage_max")) }}"
either mix single/double, or use a multiline syntax
valid: temperature: "{{ float(states('input_number.settemp_klimaanlage_max')) }}"
also valid:
temperature: >
{{ float(states("input_number.settemp_klimaanlage_max")) }}
Thanks
Any idea why this is not working?
label: "[[[ return helpers.relativeTime(entity.last_changed) ]]]"
-moved-
That sounds like something for #frontend-archived
Wow, not even sure how I ended up in #templates-archived 😂 I thought I was in #general-archived ... Oops
I have made several sensors to sum up my energy costs correct. And the last one I made sum up the total costs for the current hour. I am unsure how to take this a step further so I can display the costs for the current month. Is it possible to use helpers as rieman sum or? anyway, this is the sensor: - sensor: - unique_id: kostnad time med nettleie name: "kostnad time med nettleie" state: > {% set sensor1_value = states('sensor.accumulated_consumption_current_hour_hjemme') | float(0) %} {% set sensor2_value = states('sensor.strompris_med_nettleie') | float(0) %} {{ (sensor1_value * sensor2_value) | round(2) }}
Do you have a fixed energy price?
I have a floating price for electricity, a price for the grid that varies by month and time of day, as well as a price that is fixed but varies by consumption. The last one is fixed by an automation who set the correct amount in an input_number when I go from one level to another one. So what I need to do is to somehow sum up the costs from each hour and sum them in to monthly cost and the hopefully add the last input_number. But first ting to sum up, was going to have a closer look to the ytility meter. EDIT: Made an utility meter to track this, then I made a new sensor where I summed up the costs. Lot of steps, but looks promising.
Hey there, I'm trying to set up a script for my heating system. It has four fields: the climate device, the schedule helper, the numeric helper for the low temperature and the numeric helper for the high temperature. The script calls the climate.set_temperature service and set the temperature to the state of the high temperature helper if the schedule is on, otherwise it should set it to the state of the low temperature helper.
I don't get this to work using fields in a script. In the template editor my ternary condition outputs the right value but when executing the script from an automation the temperature is not set on the climate.
alias: Apply Heating Schedule
sequence:
- service: climate.set_temperature
metadata: {}
data:
temperature: >-
{{ states(high_temperature) if states(schedule) else
states(low_temperature) }}
target:
device_id: "{{ device }}"
mode: single
icon: mdi:heating-coil
fields:
climate:
selector:
device: {}
name: Climate
required: true
schedule:
selector:
entity: {}
name: Schedule
required: true
low_temperature:
selector:
entity: {}
name: Low Temperature
required: true
high_temperature:
selector:
entity: {}
name: High Temperature
required: true
How are you calling the script?
I'm using this code in an automation
action:
- service: script.apply_heating_schedule
metadata: {}
data:
climate: dde7b091df566b25ebe905be81d3265e
schedule: schedule.buro_heating_schedule
low_temperature: input_number.buro_heating_low
high_temperature: input_number.buro_heating_high
Where is 'device' coming from?
I guess from my stupidity
Looks like it's climate
Oh wow, sorry about that, I should have spotted this
It's my first time really using templates and that threw me off. Thank you!
If you set up the Energy Dashboard, there is also a cost sensor. It just increases until you do a restart. But you can use an utility meter on that sensor to get hourly/daily/weekly/monthly/yearly costs
Hey all, i'm hoping this is easier than i'm making it. I'm trying to have an automation when triggered with a calendar event, read the summary of said event on a nest hub
i can have it read a manually typed message, or by doing "{{'trigger.calendar_event.summary'}}" it'll read those literal words
but i don't seem to be able to get it to actually read the summary
@keen spoke Remove the single quotes around your trigger variable
That makes it a string instead of a variable
tried that too but the thing would never fire, finally got this to work just now: ```alias: Dan Alarm Test
trigger:
- platform: state
entity_id: calendar.dan_automation_test
to: "on"
action: - service: tts.speak
data_template:
media_player_entity_id: media_player.nesthub28f4
message: "{{ trigger.to_state.attributes.message }}"
target:
entity_id: tts.home_assistant_cloud
If you were using a state trigger all that time, there is indeed no trigger.calendar variable
no, i wasn't
i was triggering off of a calendar event
i don't have a copy of what my yaml was before i made the change up, but it was suggested by chatgpt and appears to have worked, so for now good enough for me
i really need to dig in and learn more about templating though
I have given up on the Energy Dashboard it is almost useless, hope it will be given som attention in the future. I ended up using a combination of a rieman sum, and a utility meter. It seems like my new sensor now sums up correct.
Hi. Can anyone assist me with my custom mqtt sensor? I am trying to get around the json format sent from esp32 to my mqtt. I have tried to customize this via the "Value_Template" It works fine in the developer tab but not when saving to my configuration yaml. When saving below value_template to sensor in yaml it returns nothing.
From Developer page
{{states("sensor.esp32_garagedoor")}} value_template: "{{ states('sensor.esp32_garagedoor').split(':')[1] | regex_replace('}','') }}" value_template: "{{states("sensor.esp32_garagedoor").split(":")[1] | regex_replace("}","")}}"
Result from Developer page
{"cm":605} value_template: "605" value_template: "605"
From my yaml
mqtt: sensor: - name: "ESP32_Garagedoor" state_topic: "/home/sensors/#" unique_id: 9883815210775802070849
From Ardruino
` StaticJsonDocument<80> doc;
char output[80];
long now = millis();
if (now - lastMsg > 5000) {
lastMsg = now;
float dist = distance;
doc["cm"] = dist;
serializeJson(doc, output);
Serial.println(output);
Serial.println(dist);
client.publish("/home/sensors", output);`
@misty oxide fix your mqtt entity.
mqtt:
sensor:
- name: "ESP32_Garagedoor"
state_topic: "/home/sensors/#"
unique_id: 9883815210775802070849
value_template: "{{ value_json.cm }}"
Thank you, this will help me with future esp projects also! much appreciated 🙂
{% set ns = namespace( average_playing_volume = 0, counter = 0 )%} {%- for player in states.media_player -%}
{% if state_attr(player.entity_id, 'is_volume_muted') == false and is_state(player.entity_id, "playing") and "speakers" in player.entity_id and "following" not in player.entity_id and "home" not in player.entity_id %}
{% set ns.average_playing_volume = ns.average_playing_volume + state_attr(player.entity_id,'volume_level') %}
{% set ns.counter = ns.counter + 1 %}{%- endif -%} {% endfor %} {{ ns.average_playing_volume / ns.counter }}
Any way to optimize this template? I am pulling over 280 entities ( all the media players) currently and it's probably not the most efficient thing to do
yes
{{ states.media_player | selectattr('entity_id', 'search', 'speakers') | rejectattr('entity_id', 'search', 'following|home') | selectattr('state', 'eq', 'playing') | map(attribute='attributes.volume_level') | list | average }}
Hmm. in template sensors, it seems like the this variable isn't available to trigger actions. Am i missing something?
what do you mean "trigger actions"
I think they mean in the action section of a trigger based template sensor
Ah yep
this is only available in the individual entity, if it's even available for trigger based templates
filed that
I'm not sure how that's an issue
you can have more than 1 sensor per trigger
Both the original template and this one will error when no entities match the criteria, but you can add a default to the average filter
so if you have more than 1 sensor in your sensor section, what does this populate with?
sensor 1 or sensor 2?
Yep, it if was 1 to 1, yah, this all day
Thanks!
What if I want to exclude muted speakers?
"if state_attr(player.entity_id, 'is_volume_muted') == false"
This part
{{ states.media_player | selectattr('entity_id', 'search', 'speakers') | rejectattr('entity_id', 'search', 'following|home') | rejectattr('volume_muted', 'search', 'true') | selectattr('state', 'eq', 'playing') | map(attribute='attributes.volume_level') | list | average }}
I try this but get 'homeassistant.helpers.template.TemplateState object' has no attribute 'volume_muted'
rejectattr('attributes.volume_muted', 'eq', True)
{{ states.media_player | selectattr('entity_id', 'search', 'speakers') | rejectattr('entity_id', 'search', 'following|home') | rejectattr('attributes.volume_muted', 'search', True) | selectattr('state', 'eq', 'playing') | map(attribute='attributes.volume_level') | list | average }}
results in TypeError: first argument must be string or compiled pattern
sry, edited
No error but the value is not correct. It seems like the parameter is ignored
mine: {% set ns = namespace( average_playing_volume = 0, counter = 0 )%}
{%- for player in states.media_player -%}
{% if state_attr(player.entity_id, 'is_volume_muted') == false and is_state(player.entity_id, "playing") and "speakers" in player.entity_id and "following" not in player.entity_id and "home" not in player.entity_id %}
{% set ns.average_playing_volume = ns.average_playing_volume + state_attr(player.entity_id,'volume_level') %}
{% set ns.counter = ns.counter + 1 %}
{%- endif -%}
{% endfor %}
{{ ns.average_playing_volume / ns.counter }}
yours: {{ states.media_player | selectattr('entity_id', 'search', 'speakers') | rejectattr('entity_id', 'search', 'following|home') | rejectattr('attributes.volume_muted', 'eq', 'true') | selectattr('state', 'eq', 'playing') | map(attribute='attributes.volume_level') | list | average }}```
mine: 0.3499999940395355
yours: 0.3680456919329507
changing true to false does not change the value neither
Capitalized?
Yes
I tried both False and True.
Same result for both. .3680456919329507
vs .3499999940395355 for mine
{{ states.media_player | selectattr('entity_id', 'search', 'speakers') | rejectattr('entity_id', 'search', 'following|home') | rejectattr('attributes.volume_muted', 'eq', 'true') | selectattr('state', 'eq', 'playing') | map(attribute='attributes.volume_level') | list | average }}
is still using 'true'
mine: {% set ns = namespace( average_playing_volume = 0, counter = 0 )%}
{%- for player in states.media_player -%}
{% if state_attr(player.entity_id, 'is_volume_muted') == false and is_state(player.entity_id, "playing") and "speakers" in player.entity_id and "following" not in player.entity_id and "home" not in player.entity_id %}
{% set ns.average_playing_volume = ns.average_playing_volume + state_attr(player.entity_id,'volume_level') %}
{% set ns.counter = ns.counter + 1 %}
{%- endif -%}
{% endfor %}
{{ ns.average_playing_volume / ns.counter }}
yours: {{ states.media_player | selectattr('entity_id', 'search', 'speakers') | rejectattr('entity_id', 'search', 'following|home') | rejectattr('attributes.volume_muted', 'eq', False) | selectattr('state', 'eq', 'playing') | map(attribute='attributes.volume_level') | list | average }}
i copied/pasted that from your last post
I modified after your request
are you sure volume_muted is the correct attribute name?
Ah.
is_volume_muted
Now it works! Thanks!
I have at least 30+ sensors doing loops on various domains.
Would it be significant performance wise to try convert them all to this kind of templatE?
Or not really that much of a performance hit
it will be faster than what you wrote but it's probably negligible
if you have a slow machine, use the single line template
I don't ATM. But I am planning on moving my HA from a VM to a NUC
Everytime I play with my homelab and there's an issue, HA goes down.
Need to avoid that in the future
@winter forge I converted your message into a file since it's above 15 lines :+1:
is it possible to get historic data like gps coords of the last 6 hours of a person for example?
to bad. I want my phone system to email out my last gps track when i am missing.
why not go overboard and make a sql db,
ah, that makes a lot of sense, I had forgotten about the multiple sensors thing.
Hey folks, hopefully a quick one. Referencing the 'precipitation' attribute of a forecast array with the new method. Is this right? {{ False if forecast_daily[0:2]['precipitation'] > 1 else True }}. Have run the daily forecast as a previous step in this automation and stored it in the forecast_daily variable. Want it to resolve to False if there's > 1mm rain forecast in the next 3 days.
not...quite
{{ state_attr('sensor.pirateweather_daily_forecast', 'forecast')[0:2]|map(attribute='precipitation')|sum > 1 }}
as always, if you're returning "true" or "false", just return the test
Isn't that the old method that no longer works and you need to use the variable assignment from a service call now?
do you mean "if there's > 1mm of rain in a single day over the next three days?" or "is there a total of greater than 1mm of rain in the next 3 days?"
how you get to the forecast doesn't matter
it's the rest of it that does the work
I didn't ask where you got "forecast_daily" and assumed you had a way
I'm just giving you an example that I can test myself
So the forecast_daily is the variable in the automation. It's not a sensor, so I can't use state_attr() right? That's why I was trying to use direct list referencing.
like I said, if it's a list, that's fine. use it
I'm not focusing on how you got the forecast
it doesn't matter
I mean, if you need me to do it
{{ forecast_daily[0:2]|map(attribute='precipitation')|sum > 1 }}
still:
do you mean "if there's > 1mm of rain in a single day over the next three days?" or "is there a total of greater than 1mm of rain in the next 3 days?"
Riiiight, that makes more sense. Sorry for being dense.
what I gave you was the latter
for the former:
{{ forecast_daily[0:2]|map(attribute='precipitation')|select('gt', 1)|list|length > 1 }}
And if the attribute was returned as a str for whatever reason, just cast it as a float before the sum?
Ah right because it's still a list at that stage, can't just | float it. Thanks for the thorough explanation!
im creating a script to help me control my CRT TV via IR.
but it has a quirk where i need to alternate between sending a command and a version of the command +0x800
example, first time i send 0xC, but if I send 0xC again it wont work i need to send 0x80C
how can I achieve this behaviour? do i need to create some sort of global variable? or is there a simpler solution
Hey there, i am using a blue print to send me notifications if movement at the front door was detectet. Now i want to trigger this routine only if the front door is closed. So i want to use a additionally helper (the Windows Sensor on the door) and use this state in my own routine to trigge the new binary helper wich triggers the blue print. My problem is, that i am dont know how to setup the binary template "helper" for that. I need a binary helper to use it in the blueprint as trigger. I got this:
binary_sensor:
- platform: template
sensors:
send_notify_eingang:
value_template:
friendly_name: 'Send Notify Eingang'
device_class: switch```
But i need something for the value template. What should fill in there?
oh sorry, it needs to be a motion sensor.
i added a virtual motion sensor, but i cant manipulate the sensor from a automation. I need this virtual motion sensor to trigger automation in front of the notifiy
So the binary_sensor you're creating should state on when the door sensor reports closed?
template:
- binary_sensor:
- name: 'Send Notify Eingang'
state: "{{is_state('binary_sensor.door_contact','off')}}"
device_class: motion
i knwo what you mean, but it cant be like that. i want to trigger the blueprint to send me the notify by using a autmation for that. In this automation i want to check multiple states. And if the result is true, this automation should chnage the state of the virtual mition sensor
i cant add another condition to the blueprint
Binary sensors are changed by state events, not by user input or service from an automation
ah ok, hmmm, so how can i add another condition to a blueprint wich doesnt support that?
i thought, by using a "virtual" motion sensor.
an input_boolean perhaps
jeah, but the blueprint dont accepts a bolean as input 🙂
or can i change that condition inside of the blueprint?
I don't know, not sure about what blueprint you are talking. It's lacking the details to understand and helping you
i am using this blueprint:
But you can use that state of an input helper to determine the state of a binary sensor, just change the entity to the input boolean in the above example
yes, but i cant use it to trigger the blueprint
the yaml of my blueprint looks like this:
alias: "Eingangsbereich: Bild senden wenn Bewegung erkannt"
description: ""
use_blueprint:
path: vorion/send-camera-snapshot-notification-on-motion.yaml
input:
motion_sensor: binary_sensor.0x00158d00065850d2_occupancy
camera: camera.10_10_10_114
notify_device: ad276a7be8ef9e7cb72d3ef7ac2d3a17
delay: 0
notification_title: Bewegung im Eingangsbereich erkannt!
So with what conditions should it trigger? If motion is detected and front door is closed?
in this example yes
but for me it would be the best to check that by an automation, so that i can arrenge the conditions to what i need
wouldnt it be possible to change the preset of the blueprint from "motion sensor" to "binary sensor" inside of the yaml?
its written here:
domain: automation
input:
motion_sensor:
name: Motion sensor
description: The sensor wich triggers the snapshot creation
selector:
entity:
domain:
- binary_sensor
device_class:
- motion
multiple: false
isnt it possible just to change the input in the blueprint?
Okay, then when all conditions are met you can set an input_boolean to on in that automation and turn it off when the conditions fail
template:
- binary_sensor:
- name: 'Send Notify Eingang'
state: "{{is_state('input_boolean.motion_conditions','on')}}"
device_class: motion
And use this binary sensor in your blueprint, no need to change the blueprint
Of course you can, but it is possible you also need to change the logic within the blueprints templates/actions
i understand, but then i can only arrange the conditions inside of the helper, right? not by using a automation to check all neded conditions?
You handle all conditions inside your automation and set the state of the input_boolean accordingly. The binary_sensor above mirrors the state of the input_boolean
aaaah, think i got it!
i will try
ok, so i made a helper Switch bolean as a trigger, i added the Switch into your code by adding a template helper:
template:
- binary_sensor:
- name: 'Send Notify Eingang'
state: "{{is_state('input_boolean.test_trigger_notify','on')}}"
device_class: motion
correct?
Does it work? than it should be correct.
i would say, its working the half way...
the template sensor indicates the status of the bolean helper, but something is still wrong
and i cant select the template trigger in the blueprint
You somehow misplaced the code. The snippet I posted is meant to be placed directly into configuration.yaml
ah, ok 🙂 i added it as a template helper
whe i add it to the cong.yaml i got this:
Invalid config for 'binary_sensor' at configuration.yaml, line 230: required key 'platform' not provided
i changed the template using one of my examples in my confi.yaml to this:
- platform: template
sensors:
send_notify_eingang_test:
value_template: "{{is_state('input_boolean.test_trigger_notify','on')}}"
friendly_name: 'Send Notify Eingang Test'
device_class: motion
Now its working
This is the legacy format, what I posted is the new supported format
ah ok, do i need to setup something to use the new format?
anyway, i added the 2 additional binary sensor and added the two template sensors and tested themn. its working as i need1 thank you!
Just be mindful of the syntax and that it is used within configuration.yaml under template: , as used by my example, instead of binary_sensor: or sensor. All documentation is also focused on the new format
hi all! did anyone export a list of Zigbee integration list of entities? I've been told to use template to achieve it
HA has a built-in template function for that
https://www.home-assistant.io/docs/configuration/templating/#entities-for-an-integration
legend!
im creating a script to help me control my CRT TV via IR.
but it has a quirk where i need to alternate between sending a command and a version of the command +0x800
example, first time i send 0xC, but if I send 0xC again it wont work i need to send 0x80C
how can I achieve this behaviour? do i need to create some sort of global variable? or is there a simpler solution
@placid patrol I converted your message into a file since it's above 15 lines :+1:
You can pull the source and parse it to the sensors without storing them in a helper.
thank you! It works as expected - is there a way to add a friendly name after a coma?
Edit:
{% for entity in integration_entities('zha') -%} {{ entity }}, {{ state_attr(entity, 'friendly_name') }} {% endfor %}
this sorted my problem.
Good day to everyone here. I need some help with these
https://imgur.com/a/qLD0xLx
you can use the GUI template helper, but then you only need to provide the actual template, and not all the YAML around it
so only {{is_state('input_boolean.test_trigger_notify','on')}}
Thx, @marble jackal i am nownusing the way wich @fickle sand Shows me. That works fine
at least one of these entity_id's doesn't exist, and therefor states('input_number.x') returns unknown which can't be converted to an integer
his quotes are wrong
ah right,single quotes within and outside the template
however, the error message shows it did render the template
and couldn't convert unknown to an integer
Hmmm... try this instead:
data:
duration: "{{int(states('input_number.bedroom_hour',0)}}:{{int(states('input_number.bedroom_min',0)}}:00"
int used as a function in this case, converts whatever is in the helper to an integer, but int also allows for a 'default' value to be used in the event that the value in the helper is invalid or not a number (in the case of it being undefined, for instance)
you can also do that when using int as a filter
data:
duration: "{{ states('input_number.bedroom_hour') | int(0) }}:{{ states('input_number.bedroom_min') | int(0) }}:00"
However, an input_number will never return the state unknown, so therefor I know for sure the entity_id is wrong. Using defaults will only hide that underlying issue
aah i think i had an idea, I'll use a counter entity and increment it, then ill get the counter value and send with +800 if odd and if even send without it.
When using a [[[ return `` ]]] template, is there a way to set a default value if the values are unknown or undefined?
How do I use this variables action?
alias: CCE_IR
sequence:
- variables:
test_var: "2323"
I tried it like this and got this error
Message malformed: expected a dictionary for dictionary value @ data['sequence'][0]['variables']
you need to indent the test_var line
You'll have to elaborate, that looks like JS code which is a #frontend-archived question
alias: CCE_IR
sequence:
- variables:
command_value: "{{ increment_value|int(base=16) + '0xC'|int(base=16) }}"
still didnt work, how odd.
This worked. how weird.
alias: CCE_IR
sequence:
- variables: {
"command_value": "{{ increment_value|int(base=16) + '0xC'|int(base=16) }}"
}
AAAH
Nevermind, I need ANOTHER tab lmao.
Petro, hey again... I didn't realize it was JS until you pointed that out. I'm setting the name of a custom button-card with the contents of the brackets, but currently the output is undefined versus what I would like to have is actually null text
I'll post to frontend if need be
You'll get better help there
'ppreciate it
how do I print an integer as a base 16 string in jinja
Right, you didn't actually indent that line
oh, and also, Petro, the stupid crazy template you and RobC helped me out with?, has made some pretty cool stuff in the last few months
{{ '%x'%283948239482 }}
ah nevermind, if I send the number as a decimal it works too, so no need.
Thanks!
which one is that?
{% set helper.list=helper.list+[entity|replace('media_player.mrp_','input_boolean.mrp_')|replace('_kodi_mini','')] %}{%endfor%}
{% set turned_on=expand(helper.list, 'media_player.mrp_helper')|map(attribute='entity_id') | map('replace', 'media_player.', 'input_boolean.') | list %}
{{ expand(turned_on) | selectattr('state', 'eq', 'on')|sort(attribute='last_updated', reverse=True)|map(attribute='entity_id')|first|default }}
Nice, glad it works
I've been able to do some pretty slick stuff with my light groups and a few other grouped things
so, I wanted to give ya guys a little shout-out
Uh this is a nightmare, i hate handcrafting JSON string in templates. is there a way to put a dictionary into it and then it will internally convert to JSON?
data:
qos: "0"
topic: cmnd/tasmota_466C1F/IRSend
payload: '''{{ '{"Protocol":"RC5","Bits":12,"Data":'+command_value | string+'}' }}'''
enabled: true
| to_json
:O let me try
payload: "{{ dict(Protocol='RC5', Bits=12, Data=command_value | string) | to_json }}"
Is it ok to use recursivity in scripts
Can someone help with this log error when restarting HA? http://pastie.org/p/7goKr8jeHyMPaCkUgxwoYv I believe it's related to a state value not being available during load, but can't recall how to fix it.
Does this look right? im afraid to run it lmao
- if:
- condition: template
value_template: "{{ repeat > 0}}"
then:
- service: script.cce_ir
metadata: {}
data:
repeat: "{{ repeat - 1 }}"
raw_command: "{{ raw_command }}"
repeat_interval_delay: "{{ repeat_interval_delay }}"
COMMAND_KEY: "{{ COMMAND_KEY }}"
Disallowed recursion detected
Oooh cmoon! let me do it
oh nevermind its because I Set it to Queued
Parallel it is then.
That’s almost never needed.
yeah, its part lazyness
I would have to redo how I set the alternating increment of the protocol
Just make the script accept a repeat option
thats what I did. and then if repeat > 0 call the script again with repeat -1.
dirty but works nicely.
I'll rework it later.
Or just use the for each repeat with your service call inside the script you’re calling
I have a template sensor that spits out a name based on whichever of multiple binary sensors trigger to on. usually only one binary sensor triggers on at any given time. I would like to create a template sensor that does the same but weighs it's output based off multiple binary sensors that could be on at the same time but still functions correctly if only one is on. I think this could be done with a ton of and/or's but is there a shorter code way to accomplish this?
thinking i am going to be stuck actually making several smaller template sensors that does the "weigh" aspect and then feeds into a final template sensor that spits out the name
You will need to describe what you want more clearly. Should the new sensor return only one name? What are the criteria for choosing or sorting the list of sensors?
Is there a way to do a if this else with variables? So if (A) then variable (A) else variable (B) without putting a template inside of a template?
Template inside template isn't a thing. What is the context?
Yes, certainly that logic can be used within a template
Basically I want to go if my master switch is on then state my master switch enabled variable, if it isn't then do the master switch disabled variable. I was previously doing this in an automation by creating separate choose options but i want to simplify it if possible
A template can't actually do anything
If you were using choose, you're probably doing things that templates can't do
It's basically a {{ 'enabled' if is_state (input_boolean.master_switch', 'on') else 'disabled' }} but wanting to replace enabled and disabled with a variable option
yes return only one name/result. currently I have a sensor set up that basically just returns the name of a camera that has a person detection binary sensor and that sensor triggers to ON.
detection for specified camera triggers on => template sensor changes state to name of that camera
what I want is to add a secondary detection binary sensor for each camera and to weigh the templates output
the template sensor is used to determine which camera has a snapshot saved which is why I only needs it's output to produce the name of the camera that has detection. I want to add additional binary detection sensors to the mix so each camera could have 2 or 3 and then weigh whichever one that has the most triggered at same time to be set as the template sensors output at that time
I'm kind of thinking I might need to assign each detection source a number and then use math comparison to determine which camera name should be outputed to the state
What kind of variable option? You can put anything there
I have variables that give a random response like ' enabled, active, activated ' etc to give some variation to the text to speech
The variable can only be referenced by {{ }} though right so would that be an issue?
Wrong
Just put the variable name there
Once you're in a template variables will resolve
- variables:
mapping:
binary_sensor.motion_phong_ngoai_t1_occupancy: Phòng Ngoài
binary_sensor.motion_bep_occupancy: Phòng Bếp
binary_sensor.motion_cau_thang_t45_occupancy: Tầng 5
binary_sensor.motion_phong_khach_occupancy: Phòng Khách
message: |-
Có chuyển động {{ mapping[trigger.entity_id] }}
|--> {{ now().strftime('%H:%M:%S %A %d-%b-%Y') }}
a bayesian sensor where you could customize it's output would be nice
So I have an Ikea Fyrtur blind which I'm controlling via my Zigbee Coordinator.
The blind device doesn't have an entity for it's current position but it is reporting it as secondary information.
If I toggle secondary information on the blinds dashboard card or view the device it will show me what position it's in so HA is getting the information.
Is there any way I could make a helper or some entity which exposes what position the blind is in so I can use it for conditions in automations as well as other things?
It was mentioned to me that a "template" might be able to do this for me so I'll have a poke around with those but any other advice would be welcome
for conditions in automations you don't need a separate entity
you can refer to an attribute as wel
condition: numeric_state
entity_id: cover.some_blind
attribute: current_position
above: 50
make sure to not use quotes around the value here, as the attribute will report an integer, and not a string. If you use the GUI, it will add them automatically and you need to remove them in YAML mode
that's not an issue for numeric_state, only for state
Yeah, you're right, I rewrote the condition when I realized numeric state made more sense
hi all, im trying to modify this to say if an item is present in the to-do then list the title (or summary) of the item
{%- for task_entity in task_entities %}
Upcoming tasks for today on list "{{ state_attr(task_entity, 'friendly_name') }}":
{%- set tasks = tasks_responses[task_entities[loop.index0]] %}
{%- for task in tasks['items'] %}
{%- if 'due' in task and now().date() == as_datetime(task.due, "2222-11-11").date() %}
- {{task['summary']}}
{%- endif %}
{%- endfor %}
{%- endfor %}
and if no item is present, then no task should be completed
@floral steeple I converted your message into a file since it's above 15 lines :+1:
{{ tasks_responses.items() | selectattr('0', 'in', task_entities) | map(attribute='1') | sum(start=[]) | selectattr('due', 'defined') | selectattr('due', 'eq', now().date() | string) | list }}
that will just be 1 giant list
ahh, ok I think it would be good to have it distinguised by todo lists, so I made this, and it seems to work except:
{%- for task_entity in task_entities %}
Upcoming tasks for today on list "{{ state_attr(task_entity, 'friendly_name') }}":
{%- set tasks = tasks_responses[task_entities[loop.index0]] %}
{%- for task in tasks['items'] %}
{%- if 'due' in task and now().date() == as_datetime(task.due, "2222-11-11").date() %}
- Tasks with due dates today are: {{task['summary']}}
{%- else %}
- Tasks with no due dates are: {{task['summary']}}
{%- endif %}
{%- endfor %}
{%- endfor %}
sometims there is a list with NO tasks, like this:
todo.work_to_do:
items: []
how can I say that is there is no task, then just say "no task(s) for this list"
guess it would "no items"
Well, your output isn't matching what you you said you wanted above
i know, sorry im all over the place lol
but essentially, I want to take care of 3 scenarios
- items with due dates
- items with no due dates
- lists with no items
How do i iterate over/list all services (and by extension all services that start with notify. in particular)
kinda like this output #templates-archived message
that output has the 3 scenarios
{%- for task_entity in task_entities %}
Upcoming tasks for today on list "{{ state_attr(task_entity, 'friendly_name') }}":
{%- for task in tasks_responses[task_entity] | selectattr('due', 'defined') | selectattr('due', 'eq', now().date() | string) | map(attribute='summary') | list or ['No Tasks'] %}
- {{ task }}
{%- endfor %}
Upcoming tasks with no due date:
{%- for task in tasks_responses[task_entity] | selectattr('due', 'undefined') | map(attribute='summary') | list or ['No Tasks'] %}
- {{ task }}
{%- endfor %}
{%- endfor %}
thanks, that output of your code above gave this:
# Tasks Lists:
Upcoming tasks for today on list "Anto's list":
- No Tasks
-
Upcoming tasks for today on list "General to-do":
- No Tasks
-
Upcoming tasks for today on list "Work to-do":
- No Tasks
-
Only thing is, its only looking for tasks that have a due date, and not listing the tasks without a due date At the moment, there are things on my to-do list with no due dates, but the output does not show that.
its strange, your code is written like it should work
by the way, where is that extra hypen coming from?
I'd have to see what {{ tasks_responses[task_entity] | selectattr('due', 'defined') | selectattr('due', 'eq', now().date() | string) | map(attribute='summary') | list }} outputs
nm
i see issue
{%- for task_entity in task_entities %}
Upcoming tasks for today on list "{{ state_attr(task_entity, 'friendly_name') }}":
{%- for task in tasks_responses[task_entity]['items'] | selectattr('due', 'defined') | selectattr('due', 'eq', now().date() | string) | map(attribute='summary') | list or ['No Tasks'] %}
- {{ task }}
{%- endfor %}
Upcoming tasks with no due date:
{%- for task in tasks_responses[task_entity]['items'] | selectattr('due', 'undefined') | map(attribute='summary') | list or ['No Tasks'] %}
- {{ task }}
{%- endfor %}
{%- endfor %}
hm, let me check i get this error now Error: TypeError: 'builtin_function_or_method' object is not iterable
here's the blueprint link, if you're intereed in see the entire thing:
https://gist.github.com/Anto79-ops/92537f9f3ff07e079fd640256718feb4
something about missed comma
change .items to ['items']
@floral steeple I converted your message into a file since it's above 15 lines :+1:
and the LLM said this
As for your tasks, you have a few items on your "General to-do" list
without specific due dates: ambient oxygen sensor, find water leak, and home
depot wire covers. Make sure to tackle these tasks at your convenience.
thanks!
Hello, I'm trying to make a script that has a field to enter a light entity, then it publishes a MQTT payload using the light as a target
but I can't use the field value directly in the mqtt like
data:
topic: zigbee2mqtt/{{ light_entity_id }}/set
payload: "{\"state\": \"ON\"}"
enabled: true```
since it will return the value like "light.bedroom_lamp", and it should only be "bedroom_lamp"
I tired to replace the field key with
{{ "{{light_entity_id}}" | replace("light.", "") }}
to remove the "light." but it doesn't work, I also tried defining a variable
test: "{{light_entity_id}} | replace("light.", "")"
and then using the variable in MQTT, but HA won't accept the variable
service: mqtt.publish
data:
topic: zigbee2mqtt/{{ light_entity_id.split('.')[1] }}/set
payload: "{\"state\": \"ON\"}"
enabled: true
you were nesting templates, that doesn't work
this will also work (which was what you were trying to achieve)
service: mqtt.publish
data:
topic: zigbee2mqtt/{{ light_entity_id | replace('light.', '') }}/set
payload: "{\"state\": \"ON\"}"
enabled: true
ooooooh
sorry for the ping
no worries
the desire to nest templates is strong
and what if the field returned an RGB value?
Your attempte here (in the variables) also wouldn't work because you were using double quotes inside and outside the template
depends on what you want to do with it
use it in the payload
data:
topic: zigbee2mqtt/{{ light_entity_id | replace('light.', '') }}/set
payload: "{\"color\":{\"r\":255,\"g\":0,\"b\":0}}"
enabled: true
just surround the whole thing with single-quotes
then you don't need any of the escaping
I think you can even proivde it as a yaml dict
service: mqtt.publish
data:
topic: zigbee2mqtt/{{ light_entity_id | replace('light.', '') }}/set
payload:
color:
r: 255
g: 0
b: 0
enabled: true
now you are using vocabulary that is beyond my level
I've seen so many people construct JSON for it that it makes me think you have to
Error "value should be a string for dictionary value @ data['payload']. Got None"
okay
then an alternative couls also be:
payload: "{{ dict(color=dict(r=255, g=0, b=0)) | to_json }}"
just one more typo...
I don't even know how will the retuned field value of the RGB look like
how can I see?
In mine? Not seeing it.. 😅
crap: paylaod
but, anyway, this will also work:
payload: '{ "color": {"r":255, "g":0, "b":0}}'
data:
topic: zigbee2mqtt/{{ light_entity_id | replace('light.', '') }}/set
payload: "{{color}}"
enabled: true```
will become
```service: publish
service_data:
topic: zigbee2mqtt/right_wall_lamp_hallway/set
payload:
- 251
- 0
- 255```
which doesn't work
fixed it
data:
topic: zigbee2mqtt/{{ light_entity_id | replace('light.', '') }}/set
payload: '{ "color": {"r":"{{color[0]}}", "g":"{{color[1]}}", "b":"{{color[2]}}"}}'
enabled: true
hi guys, what was the template to only have an automation trigger if its' set triggers were actioned by the user?
in the case of an input boolean, for example
What are you trying to achieve? 🤔
this
{{ trigger.from_state.last_changed_by == 'user' }}
found it in the mean time ^^
Otherwise, have a condition with a value_template
{{trigger.to_state.context.user_id is not none}}
For any user logged into HA, otherwise, specify the username of who triggered it.
That would be able to catch it as it happens, versus retroactively after it has happened.
@flint jewel I converted your message into a file since it's above 15 lines :+1:
That’s made up gibberish
is it? it seemed to work though
No such attribute exists
I have not tested it enough so cannot tell for certain
ok then what is the correct form for this
Looks like chat gpt made up crap
There is nothing for this
You have pull the user id from context and then compare it to your list of persons
I changed 'user' to 'chris' if that helps
Nope
You have to pull the user id from the trigger context (if it even exists) like the Kirb posted. Then you need to extract the proper person from the list of people by the user id you found.
Always best to protect for when you have more! You might end up creating users for other add-ons etc
hmm that's true
thanks guys
hey guys! im trying to create an automation for my Google nest.
Its read with elevellabs a message from meteoalarm. one of the attributes from the meteoalarm sensor is
"awareness_level: 2; yellow; Moderate"
and the other one
"awareness_type: 3; Thunderstorm"
for the level attribute:
how can i change it so it says only says "Yellow". The best thing is it translate automatical in to german "Gelb"
for the type attribute
how can i change it so it says only says "Thunderstorm". The best thing is it translate automatical in to german "gewitter"
current script:
service: tts.speak
data:
cache: true
media_player_entity_id: media_player.nestspeaker
options:
voice: Adam
stability: 1
similarity: 1
style: 0.3
use_speaker_boost: "true"
model: eleven_multilingual_v1
optimize_streaming_latency: 3
message: Von MeteoAlarm. {{ state_attr('binary_sensor.meteoalarm', 'event') }}. {{ state_attr('binary_sensor.meteoalarm', 'description') }}. {{ state_attr('binary_sensor.meteoalarm', 'instruction') }}.
target:
entity_id: tts.elevenlabs_tts
What is the output of my proposed solution in #automations-archived if you put that in developer tools > templates
full output of the sensor
@timber pewter I converted your message into a file since it's above 15 lines :+1:
Which part returns awareness_level: 2; yellow; Moderate
what do u mean?
ah i see
Von MeteoAlarm. {{ state_attr('binary_sensor.meteoalarm', 'event') }}. {{ state_attr('binary_sensor.meteoalarm', 'description') }}. {{ state_attr('binary_sensor.meteoalarm', 'instruction') }}. {{ state_attr('binary_sensor.meteoalarm', 'awareness_level') }}. {{ state_attr('binary_sensor.meteoalarm', 'awareness_type') }}```
Which of those parts returns that specific piece of text
Gewitterwarnung```
```{{ state_attr('binary_sensor.meteoalarm', 'description') }}
Gewitter mit Sturmböen sind zu erwarten.```
```{{ state_attr('binary_sensor.meteoalarm', 'instruction') }}
VORSICHT bei Aktivitäten im Freien, Gewitter sind möglich. Achtung an
exponierten Stellen, wie auf Bergen und freien Flächen sowie im Wald.```
```{{ state_attr('binary_sensor.meteoalarm', 'awareness_level') }}
2; yellow; Moderate```
```{{ state_attr('binary_sensor.meteoalarm', 'awareness_type') }}
3; Thunderstorm```
idk how to sparate that and translate it
Ah, I had the wrong part
Use
{{ state_attr('binary_sensor.meteoalarm', 'awareness_type').split(';')[1] }}
That should return yellow
And
{{ state_attr('binary_sensor.meteoalarm', 'awareness_type').split(';')[1] }}
Only manually by providing all options and then a German translation
Got it to work! just added the following template to configuration file:
@timber pewter I converted your message into a file since it's above 15 lines :+1:
{% set user = states.person | selectattr('attributes.user_id', 'eq', trigger.to_state.context.user_id) | list | first | default %}
{{ user and user.name == 'frank' }}
wow. thanks!
What’s the purpose of default with no arguments in this context?
Prevent errors
The first filter will return an error when the list is empty
The default filter will prevent that error and let it return an empty string (if I'm not mistaken, it could be none)
Ok I’m seeing that now. Was testing and apparently there is a difference between:
{{ [] | first }}
compared to
{% set my_list = [] %}
{{ my_list | first }}
Which I still don’t understand
what difference?
they both produce the same error...
Maybe you're referring to the error being raised in the UI?
if you check the logs, the error is produced for both, but {{ [] | first }} does not raise the error to the UI
which is most likely a bug
You’re right, there’s an error in the logs, just nothing shown in the template editor UI
Thanks
Apologies for re-posting - I think this originally got lost previously as it got converted to a file.
Hi all - looking for some help on handling the response from weather.get_forecasts. Been doing a fair bit of googling, but couldn't find enough for me to figure it out!
Its fairly simple, I understand how to list the full dict response using {{forecast.items()}}, but I'm looking to actually dive into the dict and pull out the first day's 'condition' and 'temperature', for example
Current sequence:
sequence:
- service: weather.get_forecasts
metadata: {}
data:
type: daily
target:
entity_id: weather.home
response_variable: forecast
- service: notify.xx
data:
message: >
{{forecast.items()}}
@flint jewel I converted your message into a file since it's above 15 lines :+1:
{{ forecast[0].temperature }} and so on
I'm quite new to HA and could really use some help with my template file.
I have google calendar integration and I want to set a binary sensor to on/off depending on whether a calendar event for the particular calendar exists for today. I want it to update periodically in line with the 15m of google calendar integration.
I have this template.yaml but the first two sensors for this are showing as unavailable.
I've spent hours banging my head against a wall and just don't know what the problem is
http://pastie.org/p/6OV1Ozr2bYO30lf01nega9
You need to remove the - before binary_sensor:
You're basically creating a new sensor that isn't related to the trigger
I'm both happy and upset that all my time of frustration was caused by that 😂 so once I fix that am I safe to assume that what I've actually written will do what I've requested?
And given that I will want binary_sensors that are not reliant on that trigger, is it still normal procedure to continue to nest them under with - name
By definition, you're not nesting them when you add -
You're creating new independent list items
I don't use calendars, but I guess so
Sorry maybe bad terminology, I mean placing them within the same binary_trigger: area
|count() can be just |count
If you want additional sensors unrelated to the trigger, they should be peer list items
What I mean't for nested is whether its normal practice to put all binary_triggers below those ones I have rather than some syntax like:
` - trigger:
binary_sensor:
- name: "You have an event today"
- name: "Someone has a birthday today"
- binary_sensor:
- name: "washing machine"`
Still trying to get my ahead around the syntax
It's fine
Brill thanks for your help, very appreciated!
This is what I thought but:
Error rendering data template: UndefinedError: dict object has no element 0
So I tried this as I assumed the response likely contains another "forecast" before (confusing that I named the response variable the same as a value in the dict...)
forecast.forecast[0].temperature
But no luck there either
it's forecast['weather.home'].forecast[0]
indeed, that's what I get trying to read code on my phone
ahah brilliant, got it - an expansion on that: {{ forecast["weather.home"].forecast[0].condition }} is what works for me
Now if my "weather.home" is an input variable, I should safely be able to replace that too right?
weather.home is the entity you used for the service call
you can use it on multiple enitites in one go
Previously I had asked for help and got this to work:
{{ state_attr('sensor.double_take_officetable1', 'matches') | selectattr('name', 'eq', 'mike') | selectattr('match', 'eq', True) | list | count > 0 }}
Now, this works as a trigger for one camera, but I have multiple cameras. How would I be able to list those cameras in the trigger without having 10 different entries, or is that the best/only way?
hello friends, a question, as far as i know the temperature displayed for a zone (in dashboard) is randomly picked from any temp sensors assigned to that area? but if i remove all but one i can get the one i want to show up, this is no problem
thing is, my fridge temp sensor is offset/uncalibrated, has no calibration feature, so i made a helper that lets me offset a number, with a slider, this lets me adjust a value for that entity
i then created had this template sensor in sensors.yaml (i assume to use the {} syntax to calculate):
- platform: template sensors: Fridge_Temp_Adjusted: friendly_name: "Fridge Temp" unit_of_measurement: "°C" value_template: "{{ states('sensor.kyl_temperature') | float - states('input_number.kyl_offset') | float }}"
which then gives me the correct temperature for my fridge, and it seems to work.
But im stuck at getting it to be the displayed temp on the picture entity card for that area
i have tried adding:
attributes: room: "Kitchen"
as well as:
attribute_templates: room: "Kitchen"
ignore the indents, its proper in yaml
let me know if this is the wrong channel/server
and feel free to ping if you have any ideas 💌
Are you referring to the "Area Card"?
sorry, yes
id post some pics, but i see theres no image perms
but not needed i think
i just got a zigbee display temp sensor, it works amazingly, displays on my bedroom area card, but my offset entity fridge temp isnt a "sensor" but a template sensor, cant seem to find how to assign an area, in the forums it was mentioned its not possible, but that changed, but i got stuck there
Add a unique_id to your sensor so that you can modify it in the UI and add it to an area
@warm burrow ^
You are using the legacy format, you may also want to convert to the new template sensor format (which goes under the main key template: as opposed to sensor:)
I'm struggling with a template sensor. All family members are defined as a "Person" in HA and are tracked through various devices. I want to display their location but change they way it is being displayed: "not_home" with "Away" and "home" with "Home and everything else ie if there is a zone defined it should show that. What I have done is working except for the "else" part - it should simply show the value of the person.xxx entity but all I get is "unknown":
- platform: template
sensors:
manueltracker:
friendly_name: "ManuelTracker"
value_template: >-
{% if is_state('person.manuel', 'not_home') %}
Away
{% elif is_state('person.manuel', 'home') %}
Home
{% else %}
"{{ person.manuel }}"
{% endif %}
I must be missing something simple here!
@flint pagoda 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.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
also note you can simply use {{ state_translated('person.manuel') }}
great many thanks that did the trick!
How can you check in javascript if the day is today and if not show yesterday or 2 days ago etc.
Previously I had asked for help and got this to work:
{{ state_attr('sensor.double_take_officetable1', 'matches') | selectattr('name', 'eq', 'mike') | selectattr('match', 'eq', True) | list | count > 0 }}
Now, this works as a trigger for one camera, but I have multiple cameras. How would I be able to list those cameras in the trigger without having 10 different entries, or is that the best/only way?
{{ states.sensor | selectattr('attributes.matches', 'defined') | map('attributes.matches') | sum(start=[]) | selectattr('name', 'eq', 'mike') | selectattr('match', 'eq', True) | list | count > 0 }}
Does this work?
What am I doing wrong. Trying to have template sensors that measure bed if we are charging our phones after a certain time (to add more sensors and smarts later) but these don't show up 😦
@summer arch I converted your message into a file since it's above 15 lines :+1:
I tested the templates in dev tools, but now trying to add the triggers to configuration.yaml and it doesn't seem to work
template: !include_dir_merge_list templates/
I have multiple files for templates for organisation
I have that for sensor: but when doing binary_sensor: I get bad indentation of a mapping entry
Because your indentation is wrong
no wait, the trigger isn't - trigger:
Do you need to mask true and false to on and off?
No
I guess the triggers aren't working then 🤷
I guess, your binary_sensor part is still formatted wrong
Ok? And how's that? Or are you intentionally omitting helpful information?
No. You should have a look at the docs. Sensors and binary sensors are not in the list of triggers.
Like the example of the docs I linked.
Given my message here I clearly read docs and corrected as per docs
To which I got an indentation error
To which you hilariously pointed out is because there's an error in my indentation
However, the realisation was then that the trigger was infact formatted incorrectly
Of which, it is still not working
How is your YAML looking like right now?
@glass fjord I converted your message into a file since it's above 15 lines :+1:
@tawny coral I converted your message into a file since it's above 15 lines :+1:
@glass fjord I converted your message into a file since it's above 15 lines :+1:
can anybody figure out why the following template only listens for the first two entities:
{{ is_state('binary_sensor.staff_entrance_is_dark', 'off') and is_state('binary_sensor.smoking_area_is_dark', 'on') and is_state('binary_sensor.staff_entrance_motion', 'off') and is_state('binary_sensor.staff_entrance_person_detected', 'off') }}
Probably because the 2nd entity is off
but the following is listening to all entities as expected:
{{ is_state('binary_sensor.charging_room_is_dark', 'off') and is_state('binary_sensor.charging_room_motion', 'off') and is_state('binary_sensor.key_room_motion', 'off') and is_state('binary_sensor.key_room_person_detected', 'off') }}
No need to check for the other ones then
hi everybody; i've successfully added a template helper using the HA UI (offset to a temperature sensor) but I'm not able to use the added helper as an entity. what am I doing wrong?
Hi, I want to know how I can add a JSON from a link and then Home Assistant actualize this information every hour or every half an hour. Thank you.
I guess you're talking about this: https://www.home-assistant.io/integrations/sensor.rest/
Thank you a lot
On https://www.home-assistant.io/docs/configuration/templating/, it often says "can be used as a filter", but I fail to use the correct syntax 🙈 My assumption was that something like this would work, but it doesn't: {{ integration_entities("tapo_control") | select("match", "switch\..*privacy$") | list | area_entities("aussen") }}
I get the error TypeError: area_entities() takes 2 positional arguments but 3 were given, so apparently the three entities returned by | list are passed as the arguments.
Any hints on where I can find docs on what it means that these things can be used as a filter?
You can only apply filters on a list trhough map
i.e. | map('area_entities', 'aussen')
and afterward, you're going to get a list of lists
if you want a single list, you'll have to add them together
{{ integration_entities("tapo_control") | select("match", "switch\..*privacy$") | map('area_entities', 'aussen') | list | sum(start=[]) }}
edit: unique isn't needed
In this case I don't understand why you would use area_entities there.
When it says can be used as a filter it means you can either do
arrea_entities('aussen') (used as function) or 'aussen' | area_entities.
However, in both cases it needs an area name or area id as input. Not an entity_id.
What are you trying to achieve @quartz fulcrum
The template Petro gave will work like this
{{ integration_entities("tapo_control") | select("match", "switch\..*privacy$") | map('area_id') | map('area_entities') | list | sum(start=[]) }}
oops forgot the area_id in between
is the reject the best way to diff to lists? we cant use - like we can use + between lists, but the reject requires one to know which list contains most items.```
{% set group_list = states.light
|selectattr('attributes.is_hue_group','defined')
|selectattr('attributes.is_hue_group','eq',true)
|map(attribute='entity_id')|list %}
{{group_list|reject('in',label_entities('hue_groep'))|list}}
{{label_entities('hue_groep')|reject('in',group_list)|list}}```
the first results in the correct diff, the second returns [].... which is correct ofc. But I simply want to find the difference between them without caring about either length. (group_list contains all groups , label_entities contains only a subset)
It doesn't work, this code. I'm trying to get a JSON from the link and get the longitude and longitude of the ISS, but it doesn't work. Could you help me, please? Thank you.
rest:
- resource: http://api.open-notify.org/iss-now.json
sensors:
- name: 'ISS longitude'
value_template: "{{ value_json.iss_position.longitude | float}}"
- name: 'ISS latitude'
value_template: "{{ value_json.iss_position.latitude | float}}"
Are you aware there's an ISS integration that already handles this?
Yes, I am aware I'm just playing around with JSON on Home Assistant.
I, however, want to have the direct access to the information such that I can utilize JSON on Home Assistant. Can you help me? My entities are not showing up. Thanks!
is it sensor: not sensors: ?
https://www.home-assistant.io/integrations/rest#sensor
otherwise looks correct
if that's the issue there should have been a message in your log about it
thx, wasnt aware of that. however, it results in the same albeit in {} and not being a list. It still needs to know the order, and for that, the content of the 2 lists.
Cast the set to a list again using | list
yes, I am aware how to make that into a list again, but thats not my quest. my hope is to find a way to use 2 lists, and find thd difference between them without having to know the number of items in the list (to know which to substract from the other). As you can see in the screenshot, the reject itself works just fine, but only when the correct order is used (btw, that is also required using the set() python method)
seems all of these techniques have that same limitation: https://www.geeksforgeeks.org/python-difference-two-lists/
this seems to work, but it feels really hacky: {% if group_list|length >= label_list|length %} {{group_list|reject('in',label_list)|unique|list}} {% else %} {{label_list|reject('in',group_list)|unique|list}} {% endif %}
doesnt work either.... it doesn pick all the unique items from both lists..
to find the differences in 2 lists, you need to do both, and add them together
{% set a = [ 'a', 'b', 'c', 'e' ] %}
{% set b = [ 'a', 'b', 'c', 'f' ] %}
{{ (set(a) - set(b)) | list + (set(b) - set(a)) | list }}
Result: ['e', 'f']
thanks, yes that works nicely.
and yet (somehow this has eveolved quickly...) I dont think it is the same as the 'difference'. The above is the lis of unique items for both lists. argh, I need to rethink this.
no, I do believe this is working as I had hoped for. Its a bit convoluted, (seems a very common operation, would have expected a more direct function() for it) but it does what I need right now. thanks again (also Petro)
moving a few more templates away from {{states.domain}}, would there be any benefit at all to use the integration_entities version here:```
{{states['light']
|map(attribute='entity_id')
|select('in',integration_entities('homekit_controller'))
|select('has_value')|list|count}}
{{expand(integration_entities('homekit_controller'))
|selectattr('domain','eq','light')
|map(attribute='entity_id')
|select('has_value')|list|count}}```
seems more narrowed down to begin with selecting only a sub set of states, but then requiring them to be expanded is less efficient ?
The first one is throttled to one update per second
right, I didnt even think about that aspect, and was thinking more in terms of required internal operations, or memory usage.
whats remarkable now, when entering the states. template it indicates to only listen to state changes of those particular light entities. I always believed states. templates listen to all state changes, and that being the main reason to avoid those.
the expand template above listens to all homekit entities, and those are way more!
How can I use templates or variables to make piper speak? Like have it say 'It is now 20 degrees outside'? It uses sort of a webcall with message=word+word+word (no spaces).
Hi, i got an sensor on my balcony door that i want to know how long since its been open/triggered by announcing it with TTS, how would i do that? Something like «It was last triggered (mins) ago» not sure how i put it in HA to make it work
2nd one is 'lighter', which is why the first is throttled but the second is not.
you're starting with a defined small list, vrs all lights. The defined small list will always win. I.e. avoid states.light and use integration_entities as the base
#voice-assistants-archived can help
how are you triggering it to say that? You can simply use {{ relative_time(states.binary_sensor.xyz.last_changed) }} to get a friendly relative time
My plan was kinda making it as a script and putting that script into google home app making it a routine so my activationfunction would be «when i say» and when google hears it it will trigger the script if that makes sense
Yep, then that's what you'd need for it to say 15 minutes
Okey nais, not too familiar with templates, do i need to change binary_sensor to what my sensor is called?
yes
Eh... no
They want to use templates in a TTS service call
data:
media_content_id: >-
media-source://tts/tts.piper?message=Beweging+aan+de+voordeur&language=nl_BE&voice=nl_BE-nathalie-medium
media_content_type: provider
``` is where they're starting from
I'm guessing you have insider info on this? I did not gather that at all from their question
Yeah ,they posted a lot more in #automations-archived - but why bother actually sharing that here?
No point in making it easy for us to help after all
What kind of template would i need to make an automation if someone presses a botton it will send the current time as a notification to phone?
depends on what format you want the time in
what u mean? like 3PM?
There's many different ways to represent time
military time, US time, whatever you can dream up
e.g. I use 9:22 AM
i guess i want CET ?
that's a timezone...
military time is would be 22:10 for 10:10 PM.
do you want seconds? do you not want seconds?
ok, then {{ now().strftime("%H:%M") }}
Ah it works thank u very much
is there any way to add a timer to the following helper template. so it only activates if all statements are true for 1 minute:
{{ is_state('device_tracker.lmr', 'not_home') and is_state('device_tracker.waffle_shop_3', 'home') and is_state('device_tracker.log_flume_photos_3', 'home') and is_state('device_tracker.casablanca_2', 'home') and is_state('device_tracker.safe_room_2', 'home') and is_state('device_tracker.safe_room_3', 'home') }}
Maybe you want delay_on, but you'll have to add that in yaml instead of as a helper template.
https://www.home-assistant.io/integrations/template/#delay_on
that sounds like what I want but not sure what you mean in the second half of your sentance
Template sensors can be added either in yaml in your configuration.yaml, or by adding a helper in the UI.
The helper menu in the UI does not have delay_on as an option, so you'll have to go the yaml route.
it has a template option though
Yes, it can add some templates, but it has more limited/simplified options
UGHGHGHHH
that suckss
I have 25 completed helpers in the UI i now need to put into the yaml
does this look right?
- platform: template
sensors:
custom_condition:
value_template: "{{ is_state('device_tracker.lmr', 'not_home') and is_state('device_tracker.waffle_shop_3', 'home') and is_state('device_tracker.log_flume_photos_3', 'home') and is_state('device_tracker.casablanca_2', 'home') and is_state('device_tracker.safe_room_2', 'home') and is_state('device_tracker.safe_room_3', 'home') }}"
delay_on: 00:01:00```
for yaml
I'm not that good with yaml syntax
I'm not sure where delay_on should go
oh i guess it probably needs a more descriptive name aswell
- platform: template
sensors:
custom_condition:
value_template: "{{ is_state('device_tracker.lmr', 'not_home') and is_state('device_tracker.waffle_shop_3', 'home') and is_state('device_tracker.log_flume_photos_3', 'home') and is_state('device_tracker.casablanca_2', 'home') and is_state('device_tracker.safe_room_2', 'home') and is_state('device_tracker.safe_room_3', 'home') }}"
delay_on: 00:01:00```
no
follow the docs and the examples in the docs
I also recommend using the new template configuration, not the legacy template integration
Does this look any better?
- lmr_network_power_is_off:
- name: "Custom Condition"
state: >
{{ is_state('device_tracker.lmr', 'not_home') and
is_state('device_tracker.waffle_shop_3', 'home') and
is_state('device_tracker.log_flume_photos_3', 'home') and
is_state('device_tracker.casablanca_2', 'home') and
is_state('device_tracker.safe_room_2', 'home') and
is_state('device_tracker.safe_room_3', 'home') }}
delay_on: 00:01:00
- binary_sensor:
- name: lmr_network_power_is_off
state: >
{{ is_state('device_tracker.lmr', 'not_home') and
is_state('device_tracker.waffle_shop_3', 'home') and
is_state('device_tracker.log_flume_photos_3', 'home') and
is_state('device_tracker.casablanca_2', 'home') and
is_state('device_tracker.safe_room_2', 'home') and
is_state('device_tracker.safe_room_3', 'home') }}
delay_on: 00:01:00```
hows that?
That looks good
Awesome thanks!
each additional sensor, you don't need the template: line
and if they are all binary sensors, you can just list them all under
template:
- binary_sensor:
e.g.
template:
- binary_sensor:
- name: lmr_network_power_is_off
....
- name: lmr_network_power_is_off2
what about delay_on could i put that under - binary_sensor: or template: once instead of each sensor?
nope, you'll need it on each one
- binary_sensor:
- name: lmr_network_power_is_off
....
- name: lmr_network_power_is_off2
delay_on: 00:01:00```
oh okay
if i wanted to change the friendly name is this looking good?
- binary_sensor:
- name: lmr_network_power_is_off
attributes:
friendly_name: lmr & nms
....
- name: lmr_network_power_is_off2
delay_on: 00:01:00```
just change the name
I didn't think I can put an ampersand in
sure you can
it's not the entity_id or object_id
it is the friendly name of the entity
it will get slugified to determine the entity_id
Oh so i dont even need all the underscores?
nope
Oh okay thanks 🙂
if you give your sensor a unique_id you can even change the name and entity_id in the GUI
Hey I am trying to implement a template condition check, that makes sure that the automation hasn't been run in the past 6 hours (excluding the current run). I came up with the following https://dpaste.org/GW2Pp , but this seems to fail on the condition with:
Error: In 'and' (item 5 of 5): In 'template' condition: ValueError: Template error: as_timestamp got invalid input 'None' when rendering template '{% set last_triggered = as_timestamp(state_attr('automation.main_event_automation', 'last_triggered')) %} {% set current_time = as_timestamp(now()) %} {{ (current_time - last_triggered) > 180 and (current_time - last_triggered) < 21600 }}' but no default was specified
What can I do to get this work with the templated condition?
I think had a similar problem. I used a script with with a delay on the end of it in single mode (this means it wont run again within the 'delay' time). maybe that could work for you?
The automation could run the script.
Just an idea there could be a better solution or it might not work in your case im not sure.
you probably used this condition on a new automation, which didn't trigger before
so the easiest solution is to use a default 🙂
- condition: template
value_template: >-
{% set last_triggered = as_timestamp(state_attr('automation.main_event_automation','last_triggered'), default=0) %}
{% set current_time = as_timestamp(now()) %}
{{ (current_time - last_triggered) > 180 and (current_time - last_triggered) < 21600 }}
the autoamation you are using this condition in, is not the same one as mentioned in the condition right?
Unfortunately, the condition has triggered before.
I do have a default set though, with "send a notification to my phone"
But, this had run a few days prior to just send notifications to make sure it worked without this template condition
well, according to your error state_attr('automation.main_event_automation','last_triggered') returned none which it will if 1) the automation doesn't exist or 2) it hasn't triggered yet
So I guess at that point, is it easier to just use a counter and reset it once a day? 🤔
I mean, I am interested in learning this but for a single person home assistant situation, it seems easier. 😄
What are you exactly trying to achieve?
You have automation A, and you only want that to trigger if automation B triggered somewhere between 3 minutes and 6 hours earlier
I have Automation A, and I want it to trigger if Automation A has not run in the past 6 hours.
But because of that flow, it would always fail, so I added a if > 2 or 3 minutes, and < 6 hours
for "this automation has not run in the past 6 hours", add this as a template condition in the conditions section (called "and if" in the UI):
{{ now() - this.attributes.last_triggered | default(0 | as_datetime, true) >= timedelta(hours=6) }}
I had these helper template sensors in the UI set as problem sensors but I had to use the configuration.yaml to add a delay so they no longer use the UI but how can I set these as problems using the configuration.yaml?
- binary_sensor:
- name: Lakeside Network Power is Off or Radar Hit
state: >
{{ is_state('device_tracker.lmr', 'not_home') and is_state('device_tracker.waffle_shop_3', 'home') and is_state('device_tracker.log_flume_photos_3', 'home') and is_state('device_tracker.casablanca_2', 'home') and is_state('device_tracker.safe_room_2', 'home') and is_state('device_tracker.safe_room_3', 'home') }}
delay_on: 00:01:00
- binary_sensor:
- name: Valhalla Network Power is Off
state: >
{{ (is_state('device_tracker.casablanca_2', 'not_home') and is_state('device_tracker.safe_room_2', 'home') and is_state('device_tracker.safe_room_3', 'home')) or (is_state('device_tracker.casablanca', 'not_home') and is_state('device_tracker.main_office_2', 'home') and is_state('device_tracker.safe_room_2', 'home') and is_state('device_tracker.safe_room_3', 'home')) }}
delay_on: 00:01:00
- binary_sensor:
- name: Log Flume Photos Network Power is Off
state: >
{{ is_state('device_tracker.log_flume_photos_3', 'not_home') and is_state('device_tracker.casablanca_2', 'home') and is_state('device_tracker.safe_room_2', 'home') and is_state('device_tracker.safe_room_3', 'home') }}
delay_on: 00:01:00
add device_class: problem
would that go under name?
How can I use this
selectattr('attributes.rgb_color', 'defined') |
With
{{ [area_id('binary_sensor.group_office_motion_occupancy')] | map('area_entities') |
sum(start=[]) | select('search',
'^light\.') | unique | list }}
I tried inbetween every argument
@rich moss I converted your message into a file since it's above 15 lines :+1:
sweet that worked
I was told to ask here for some help with a template that will allow me to create a trigger for automations that triggers every 10 days
¬_¬
Try this template
{{ now().timestamp() / 60 / 60 // 24 % 10 == 0 }}
I ended up trying this:
{{ (now().timestamp() / 86400) | int % 10 == 0 }}
kind of hard to validate if it works though :)
That will do the exact same thing
You can validate it by adding days.
{{ (now() + timedelta(days=1)).timestamp() // 86400 % 10 == 0 }}
Try different numbers of days until you convince yourself it works every 10th day
thank you for the help :)
Edited
I'm also seeing if I can use a local calendar for the same result
That would work too
{{ trigger.calendar_event.summary == 'event summary' }}
using this as a condition
sensible?
hm didn't work!
That looks like it should work as long as the text matches what you put as the event title. I haven’t played with calendars so I only know what I’ve read in the docs
Yeah I found an example of someone using it this way too, but I just put in a test event, with the same event title, and didn't get anything to trigger
alias: Litter Reminder Calendar
description: ""
trigger:
- platform: calendar
event: start
entity_id: calendar.reminders
condition:
- condition: template
value_template: "{{ trigger.calendar_event.summary == 'Clean Litter' }}"
For troubleshooting purposes, remove (or disable) the condition. Then get it to trigger. Then look at the trace and see what is in the trigger variable
hm interesting, it didn't trigger even without the condition
Any trigger has to transition from false to true. So if the event is already happening and then you create the automation it won’t trigger
I set the event 2 minutes from current time
OK that should work
I'm seeing everyone sharing snippets that look exactly the same as mine!
very confused here
The folks in #automations-archived probably know better than I do. I know templates and most things in automations I just never deal with calendars. So I’m just throwing darts
Np
I'm trying to work out how to make a template work.
I want to see what the weather max temp will be today
{{state_attr('weather.home','temperature') }}degrees
But it says what it is now.
I assume I just can't work out the way to ask for "max temp"
Thanks
Do you have an entity that contains the max temp in an attribute?
Assuming you do not, you need to call the weather.get_forecasts service to got the forecasts.
https://www.home-assistant.io/integrations/weather/#service-weatherget_forecasts
Then you can use a template to work through the returned data to extract the max temp
It was working before the change.
But now i am thinking as there isn't a max temp I need a helper to make a service ?
Hi, Is there any way to see the mins aswell with template when its gone over an hour since device was last triggered? Currently it only says last triggered an hour ago. I want it in a TTS
What's your current template?
{{ relative_time(states.input_boolean.toggle.last_changed) }}
{{ time_since(states.input_boolean.toggle.last_changed, precision=2) }}
Ah damn nice thank you
Is there a faster way for default value if an item is not in a list than this?
{% if 'foo' in var_icon_array %}
{{ var_icon_array['foo'] }}
{% else %}
bar
{% endif %}
So directly e.g. define a default in the list?
{{ var_icon_array.foo | default(bar) }}
{{ var_icon_array.get('foo', 'bar') }}
but var_icon_array is incorreclty named because that's not an array it's a dictionary
I'd rename that variable, otherwise you'll confuse people who will attempt to help you. Arrays cannot use ['key'] or .get('key') or .key
those are exclusive to dictionaries
{{device_id('binary_sensor.assistsatmasterbath_assist_in_progress')}}
I know this will give me device_id, but I have device_id and would like entity_id from it. How do I do the reverse of the example I'm showing?
device_entities
I'm trying to write a template. I have this bit:
{{ (expand('binary_sensor.conflict_group') | selectattr('state', 'eq', 'on') | list) }}
And it mostly works. For example, right now I get the output:
[<template TemplateState(<state binary_sensor.garage_door_conflict=on; device_class=problem, friendly_name=Garage door conflict @ 2024-05-22T07:55:25.700079-05:00>)>]
What can I do to filter this so that it only provides the first entry in the list in the case where the list has multiple entries?
| first
and you'll probably want a | default after for when it doesn't have any items in the list
Simplifying a bit:
selectattr('state', 'eq', 'on') | list ) %}
{{ entity.entity_id }}
{% endfor %}``` works fine, ```{% for entity in (expand('binary_sensor.conflict_group') |
selectattr('state', 'eq', 'on') | list | first) %}
{{ entity.entity_id }}
{% endfor %}``` results in key error
right because you pulled the first item from the list... it's now not a list
so you can't iterate it
So how can I only do any work on the first item that appears in the list?
set it to a variable, then use the variable
{% set a = expand('binary_sensor.conflict_group') | selectattr('state', 'eq', 'on') | list | first | default %}
{% if a %}
{{ a.entity_id }}
{% endif %}
That works. Thanks!
👋🏻 i'm trying to use an automation to get a string entry for the specific day of the week (and use set_text to set that day of the week entry as the value for another entity. but i'm very much struggling 😬
i setup an input_text with the state as an array ['a', 'b', 'c', 'd', 'e', 'f', 'g'].
- is that the right way to 'represent' an array?
- what would the YAML look like to get the value that represents the day of the week integer (e.g., day of week 0 should get 'a')?
@fiery umbra I converted your message into a file since it's above 15 lines :+1:
So I can select, for example, my light bulb, and every time the state changes, it will change the JSON @arctic sorrel
{"bedroom_light":"On", "bedroom_light_brightness":30, "tv_bedroom":"on"}
Context: #general-archived message
Use an automation triggered by the state change.