#templates-archived
1 messages ยท Page 33 of 1
This is a perfect case for default=0
But you don't have to use 0, you can use anything
I think 0 makes sense here
In this case it does
Cool. Think I have it set up. Underlying sensor doesn't update often so I'll have to wait to see how it goes. Thanks Fes!
Gotta say, you're one of the most helpful people on here!
You're welcome! And thanks
Seems like after I reload the config for the trigger it gets set to "unknown"
This is the state template: {{ this.state|int(0) + 1 }}
I guess changing the config of the sensor can cause that
I have another template trigger sensor that seems to survive reloads fine, though it's an event trigger
But it's still the same concept I would think. Don't see anything in the docs that say it isn't persisted, but I can't actually find docs for this specifically I don't think. These are the docs for triggers as they apply to automations
Though most of the concepts are the same
What do you mean with this
Reload the config of the trigger
I'm saying when I do reload the config it gets set to unknown. Although I did slightly cheat which is maybe why this is happening. I set the state in dev tools since the underlying trigger doesn't happen often. Just wanted to set the initial value
I've always been a little confused how setting it this way differs from when it's set normally. I'm wondering now if setting it in dev tools doesn't have to get picked up by the recorder? So maybe when it's reloaded it isn't able to get the previous state?
So basically what I did from the start was 1) create the sensor config 2) reload my template sensors so it was picked up into HA 3) go into dev tools and set it to an initial value of 4) reload the template sensor config again and then it gets set back to "unknown"
I wonder if I update the underlying sensor in dev tools that makes a difference...
That worked!
I've actually been trying to think of a way to make another sensor and I think a trigger is the way to go
I want to estimate the amount of water left in my robot vacuum's tank. I have an estimate on the rate at which is uses water based on cleaning area
And then I need to have it reset after I refill the tank
{{now() - states('sensor.saugroboter_og_cleaning_history') | as_datetime | as_local}}
How can I change that to full days? I get 2 days, 20:20:39.063150 but want it to show 3 days since the date are 3 days apart
What do you want it to show if the difference is only one hour?
{{ (now() - states('sensor.saugroboter_og_cleaning_history') | as_datetime | as_local).total_seconds() }} will give you the number of seconds
You can divide that by 60 * 60 * 24 to get the number of days
You can then decide how to round that
is there any way to find out if a trigger was used for shutdown? I have a smart diffuser that shuts off when it runs out of water. I would like to set up a notification to refill water. ie, when a shutdown occurs via google, from HA do not send a notification, if a shutdown occurs without a trigger, send a notification.
You can check probably check the context. If it has a user_id, it was issued by a user
THX. How to check the context? If I make an automation with {{trigger}} message, it shows (for example light) this: {'id': '0', 'idx': '0', 'alias': None, 'platform': 'state', 'entity_id': 'light.office_table_light', 'from_state': <state light.office_table_light=on; supported_color_modes=[], color_mode=onoff, mode=normal, dynamics=none, friendly_name=Office table light, supported_features=LightEntityFeature.0 @ 2023-03-18T09:30:03.619754+01:00>, 'to_state': <state light.office_table_light=off; supported_color_modes=[], mode=normal, dynamics=none, friendly_name=Office table light, supported_features=LightEntityFeature.0 @ 2023-03-18T09:30:27.536371+01:00>, 'for': None, 'attribute': None, 'description': 'state of light.office_table_light'}
Trigger was deconz switch
Hello,
I have a sensor with this template:
{{negativ_tallies|round(2)}} ```
but it has a lot of holes in the history tap and I dont know why. The data of february is completly gone and in march there is no data from 1. of march until 12. of march. But since 12 of march the history is correct.
Hi i wanted to chek with you guys if this templating is ok:
custom_message: >
{% "Please, close bedroom wardrobe." if trigger.id == 'Bedroom' else "Please, close office wardrobe." %}
Based on my trigger id in the trigger section, I want to send different message.
custom_message: >-
{% if trigger.id == 'Bedroom'%}
{{"Please, close bedroom wardrobe."}}
{%else%}
{{"Please, close office wardrobe."}}
{%endif%}
this is how I learned that. This should be fine.
You need to use {{ and }} with those one line if statements
If you only output a string, you don't need {{ and }} and quotes
custom_message: >-
{% if trigger.id == 'Bedroom' %}
Please, close bedroom wardrobe.
{% else %}
Please, close office wardrobe.
{% endif %}
custom_message: >
{{ "Please, close bedroom wardrobe." if trigger.id == 'Bedroom' else "Please, close office wardrobe." }}
Thanks! I prefer more one liner than to have multiple lines
Try the same trigger in an automation and have a look at the trace
Is there no way to just subtract the actual date and ignore the time? So for example if it is 18.03.2023 10:00 minus 15.03.2023 15:00 it should be 3 even though it hasn't been 72h
You can subtract just the dates
{{ ((now().date() - (states('sensor.saugroboter_og_cleaning_history') | as_datetime | as_local).date()).total_seconds() / (60 * 60 * 24)) | int }}
Ty I'll take a look ๐
{{ (now().date() - (states('sensor.saugroboter_og_cleaning_history') | as_datetime).date()).days }}
Simplified version
Wow yea I'm dumb, thanks
what is the "default" restful sensor template? There are only examples with costum value templates on https://www.home-assistant.io/integrations/sensor.rest/ and I'm building my own sensor
whatever the call returns
May I use the state (text) in a text helper as device name in an automation? Tried the following which does not work: entity_id: "{{ states('input_text.tht_phone') | string }}"
state is already a string, you do not have the pipe it
What's the current state of that input_text, because besides the unneeded string filter, this should work fine
And if that entity_id key part of a service call? If so, is it placed either under target: or data:?
Current state: THT S23
planned to be use in below and other places (to avoid changing multiple automations, scripts etc when chaning a phone (or other devices)platform: zone entity_id: "{{ states('input_text.tht_phone') | string }}" zone: zone.home event: enter id: THT Arrive Sorry, disregard, can see I miss something more now when editing the old one in yaml..
That's not an entity_id
And you can't use templates in a zone trigger
entity_id: device_tracker.{{ states('input_text.tht_phone')}}
zone: zone.home
event: enter
id: THT Arrive```
Did spot the S23 got an underscore in the name which is missing in my input text
This one should then be correct but throws the same error even though my input text now is "tht_s23" and the enity line is: entity_id: device_tracker.{{ states('input_text.tht_phone')}}
I can see that my new phone already have several automations.... Is there a "bug" here introduced by the fact that when transfering data from old to new phone as all those automations is written for my old phone.. and the app when moved somewhat believes it is my old phone........ (Not related to the above thought but an interresting discovery as the S20 is the device mentioned in all the automations under my S23 phone.
That should indeed give a complete entity_id, but you still can't use templates there
You need to use a template trigger
But what is your goal here
Your automations are not stored on your phone, they are stored on your HA server. If you change phones, that will not affect your automations
I want to have one place to enter an ID to avoid chaning xx number of automations and scripts every time I change a mobile or other devices for me and the rest of the family. This to get locations, send alerts, control the home based on location etc. I is quote cumbersome to edit all this to change a device
So automations referring to your old phone, will still refer to your old phone
Then use a template trigger
Or smart use of templates in variables
I know, but why do I have several automations on my new phones device page in HA? All the automations there is made long time ago for my old phone. If I open an automation from my new phones device page I can see the automations mention my old phone.
trigger:
- platform: template
value_template: "{{ is_state('device_tracker.' ~ states('input_text.tht_phone'), 'home') }}"
Perfect, thanks that is for triggers only I guess and I can use my above device id for notifications etc if I understand correct?
You mean entity_id right?
yes sorry
As long as templates are allowed you can use your input text for the entity_id
I assume this happens due to the samsung "migration" / transfer data from phone to phone process
Probably, but it's not related to templates, so maybe #integrations-archived or #android-archived would be a better place to ask
If pickup_start: '2023-03-19T16:00:00Z' is today, i would like to output the string 'today', If its tomorrow, then 'tomorrow', else just the date. any smart syntax available?
inching closer.....
{% set today = now() | as_timestamp | timestamp_custom('%d-%m-%Y') | string %}
{% set tomorrow = (now() + timedelta(days=1)) | as_timestamp | timestamp_custom('%d-%m-%Y') | string %}
{% if pickup == today %}
vandaag
{%elif pickup == tomorrow %}
morgen
{%else %}
{{pickup}}
{%endif%}```
bingo
{% set pickup = state_attr('sensor.bla', 'pickup_start') | as_datetime %}
{% if now().date() == pickup.date() %}
vandaag
{% elif (now() + timedelta(days=1)).date() == pickup.date() %}
morgen
{% else %}
{{ pickup.strftime('%d-%m-%Y') }}
{% endif %}
@acoustic arch
That's how I would do it
Thank you. Thats wat more compact ๐๐ฝ
I would like to ask one more question. Would it be difficult to create a similar one for this sensor that would monitor the value every day at 0:00 and add it up? During the month it would increase and then at the end of the month the resulting value would be plotted on the graph?
Thank you.
for plotting graphs you need a unit_of_measurement. And if you want to display data longer than what you store in recorder (default is 10 days), you need to make sure it ends up in the long term statistics
do you want something similar as the energy dashboard shows?
@rich quarry I converted your message into a file since it's above 15 lines :+1:
I have this template perl {% set people = [] %} {% for person in expand('group.trackers_all_people') %} {% set input_boolean = 'input_boolean.' + person.entity_id.split('.')[1] + '_longer_away' %} {% if person.state == 'not_home' and not is_state(input_boolean, 'on') %} {% set people = people + [person] %} {{people|length}} {% endif %} {% endfor %} {{people|length}} {% if people|length == 1 %} {{ people[0].name }} is not home. {% elif people|length > 1 %} {{ people|map(attribute='name')|join(' and ') }} are not home. {% endif %} but for some reason the {{people|length}} inside the for loop is 1 and outside the for loop its 0 What could be causing this?
removed some empty lines so its easier to read
You need to use a namespace to be able to store data from the loop and access it outside the loop
How does one do that?
with some additional improvements:
{% set ns = namespace(people = []) %}
{% for person in expand('group.trackers_all_people') %}
{% set input_boolean = 'input_boolean.' + person.object_id + '_longer_away' %}
{% if person.state == 'not_home' and not is_state(input_boolean, 'on') %}
{% set ns.people = ns.people + [person] %}
{% endif %}
{% endfor %}
{{ ns.people|map(attribute='name')|join(' and ') }} {{ 'are' if ns.people|length > 1 else 'is' }} not home.
btw, if you only need the names, I would only store those in the list
so ns.people = ns.people + [person.name]
what name do you use for the code blocks? i mean the yaml for example
py
ah oki
it looks better than jinja ๐
I have two flavors of the same thing that I'm playing with. The problem comes if the system resets or the YAML is reloaded, it messes with any automations that having a time in state calculation. I need to get the prior state.
https://paste.ubuntu.com/p/MwnMc2xNkn/
You know that the state of zone.home indicates how many person entities are in that zone right?
Man this universal media player is driving me crazy
I have a n LG and an Apple TV (connected to a pair of homepod minis) that i'm trying to group up into one device. The problem is that even if i use a different input than the Apple TV the entity still picks the Apple TV as the active child and displayes the media info from it. Also if i raise the volume on the apple tv controls (which control the entire tv volume through earc) it doesn't reflect in the entity
Also if i use the Mushroom Media player card and the mini-media-player with the same entity and raise the volume in one of them the volume does not change in the other.
@half pendant I converted your message into a file since it's above 15 lines :+1:
just use the custom integration template media player
universal media player is a half attempt at a template media player without templates
that makes a bunch of assumptions based on how you configured it
if you want 100% control, custom template media player
https://github.com/Sennevds/media_player.template this one? I think I tried that one in the past as well
i looked at that one but since it wasn't maintained anymore i figured it wasn't a good way to go
it's still maintained
the owner has made no mention of it being 'not maintained'
seems like he's just not adding feature requests
yeah but he's merging changes other people provide
Maybe he doesn't understand what maintained means
it's the same for custom button card
people are listing it as 'not maintained' but romrider does make fixes to make it work
https://github.com/Sennevds/media_player.template/issues/33 seems he thinks the integration is obsolete
seems I had an issue with current_volume_template https://github.com/Sennevds/media_player.template/issues/31
I'll give it another try, maybe I can close the issue afterward ๐
entity: sensor.tgtg_plus_amersfoort_magic_box
tap_action:
action: url
url_path: '{{state_attr(''sensor.tgtg_plus_amersfoort_magic_box'', ''item_url'') }}'
although its a full https: url,clicking this takes me to domain.com/{{blabla}
so url_path is not template-able?
Probably not, depends on what mushroom card docs say
good question. didnt try regular card yet ๐
as far as I know you can't template tap_action in any card
just noticed that {{now().weekday()}} {{as_timestamp(now())|timestamp_custom('%w')}} don't return the same number... is there a reason HA template extension doesnt not comply with timestamp jinja on this single occurence.
noticed because we need to do: {% set dagen = ['Maandag','Dinsdag','Woensdag','Donderdag','Vrijdag', 'Zaterdag','Zondag'] %} {% set dag = dagen[now().weekday() ] %} {{dag}} and {% set dagen = ['Zondag','Maandag','Dinsdag','Woensdag','Donderdag','Vrijdag', 'Zaterdag'] %} {% set dag = timestamp|timestamp_custom('%w') %} {{dag[dagen]}}. where timestamp is defined earlier obviously
regular business in custom;button-card..
Hey... I have Two strings of Dates "March 20, 2023 at 01:40:50" is there a easy template route to make a date diff?
strptime to convert to datetime objects, then subtract
https://strftime.org/ %w has the week starting at Sunday (so Sunday = 0). weekday() has the week starting on Monday
ValueError: Template error: strptime got invalid input 'March 20, 2023 at 01:40:50' when rendering template '{%set dat1 = strptime("March 20, 2023 at 01:40:50", "%d/%m/%Y %H:%M:%S") %}' but no default was specified
ok Got it...
exactly. is a bit odd they are not in sync
https://docs.python.org/3/library/datetime.html#datetime.date.weekday although, according to the python docs I was reading with my noseweekday() should start at Sunday as well
weekday() starts with Monday according to the python docs
yeah I see that now, so the one format follows strftime, and the other format follows python rules
yes. .weekday() is a python function
guess that shows the origin of python ๐
{{ states.sensor | selectattr('entity_id', 'search', 'tgtg') | rejectattr('state', 'eq', '0') | map(attribute='entity_id') | list | count }} beschikbaar
Now im counting entities which state are not 0. How can i actually add all the values of the states which are numbers?
{{ states.sensor | selectattr('entity_id', 'search', 'tgtg') | map(attribute='state') | map('float', 0) | list | sum }}`
yey! that looks great
I have an entity sensor.tgtg_boxes which already seems to be a combination of all my favorites
what do you mean by that?
that the state of the entity sensor.tgtg_boxes seems to be the sum of all available boxes
which also means your template will double that result
lolz
im always hesitant to make a yaml out of this kind of stuff. I tend to just code in a card
anyway, you can also do this:
{{ integration_entities('tgtg') | map('states') | map('float', 0) | sum }}
thats something new. handy
ill stick to this. Its nice to have it in my system to copy from ๐
mine doesn't have to iterate over all your sensors, but only over those from the tgtg integration
and isn't throttled
you mean save cpu cycles?
templates containing states.domain are throttled so they don't update on any state change of a sensor
ill make a cheat sheet somehere, to save handy stuff. I tend to come back asking almost the same question, but slightly off. ๐
BTW, you could also just create a sensor group in the helper section
then you don't need to do any code
manually adding all tgtg entities?
I don't know how many you have
15ish
okay, then I 'd stick to the template ๐
dunno. just added all local interesting shops
maybe i get freaked out at the amount of notifications and delete some
and coding is a learncurve, gets me further on the long run
I found why I had the sensor.tgtg_boxes. It's for my notification automation. And the state is the number of active boxes
https://github.com/TheFes/HA-configuration/blob/main/include/integrations/packages/tgtg_notificaton.yaml
thx ill have a look.
looks like your notification is ever present if >0, and clears at 0?
at least, once the trigger sensor updates
It updates when the number available boxes updates
so you can swipe it away, and it repopulates once one is found?
You can swipe it away, but ti will be back if there's an updat (so eg when the number of available boxes changes from 5 to 4)
But I only have 2 boxes, so it's not that annoying
you could add a button on the notification to ignore the box
How can i combine these 2?
value_template: "{{ states('sensor.envoy_122249105550_today_s_energy_production') | float / 1000 }}"
value_template: "{{ '%.2f'%(states('sensor.electric_voltage_l1') | float) | float }}"
I wanted the value template to round up numbers
One is in watts, the other in voltage. What is there to combine?
You need amps to convert voltage to watts
W = V * A
sorry, its now WH and im trying to make it KW, that works but i also want to round it up
the second template i send is one i found online
You're just trying to round?
you can use | round(2, 'ceil') to round to 2 digits and always round up
convert to kwh and round
i will try it outz thanks
you can't convert it to w to KWH in a template
you have to use the integration integration to convert w to wh or kwh
my bad i mean kw
W to KW and round it
so i devide it by 1000
so do you know templates at all or are you just copying and pasting? thefes provided a solution above
i did some before and im trying to learn it.
to go from w t kw, you need to multiply by 1000
i tough 1kw = 1000w
envoy_122249105550_today_s_energy_production sounds like thats an energy sensor not power either
yes, but you said w to kw...
so if 1000w is 1 kw... then you need to multiply your w by 1000
you right my bad
so is envoy_122249105550_today_s_energy_production actually a watt sensor?
I'm asking so many questions because you're making this hard by constantly changing what you want
it would be easier if you just shared exactly what you're trying to do with the entities you're trying to use
im sorry its also confusing for me
evony today energy is in Wh, i want it KWh and i want it rounded.
Take the first template from your own post, and add the round filter I provided earlier
Make sure to wrap your formula in brackets, otherwise you'll end up rounding only 1000
Hi, over MQTT I have many integrations. Currently, everything is in one file. Can I separate these different integrations (switches, sensors...) into multiple files, so that each file describes one integration and for this integration a set of switches and sensors?
thanks
Yes, something similar as the energy dashboard would be great.
I'll try to explain it one more time. I calculate the daily balance of the household in finances. So I have unit_of_measurement. So now I have a calculated daily balance (sensor.home_costs) every day. Every day at 0:00 I save this sensor to sensor.status_at_midnight. Now I would like a sensor that will add up these daily statistics gradually for an entire month. So, for example, on the fifteenth day of the month, I will see the total for 15 days. At the end of the month, I write this final value in the graph and get the total financial balance for the given month.
Is it clear what I want to achieve?
I would just use s utility_meter for the monthly total
Ok, I'll look at the utility_meter. Thank you for the advice.
I am looking to find a way of reporting "this sensor was the highest value this month" or even a top 3
I've seen the min/max sensor but that only seems to report the value
I want something that says "You were in these 3 zones the most this month" or "these 3 appliances used the most electricity this month"
any thoughts?
Hello,
I have a few sensors that, everytime I restart HA they go unknown. But many other sensors I coded like them have normal behaviour.
They look like this:
https://cdn.discordapp.com/attachments/307124763707310080/1087523505454710804/image.png
Does anyone has an idea how I can make them behave normal?
hello everyone
I would love some help as this is my first time asking so sorry if its in the wrong channel
I'm trying to setup pihole with custom duration to auto turn on could someone help explain this to me pelase
cheers
Not whiteout the code for these sensors
Many of them are coded like this:{%if (states('sensor.legro_monatliche_einnahmen') != "unavailable") and (states('sensor.legro_monatliche_einnahmen') != "unknown") and (states('sensor.legro_monatliche_einnahmen') != "none") and (states('sensor.legro_monatliche_ausgaben') != "unavailable") and (states('sensor.legro_monatliche_ausgaben') != "unknown") and (states('sensor.legro_monatliche_ausgaben') != "none")%} {% set value = states('sensor.legro_monatliche_einnahmen')|float - states('sensor.legro_monatliche_ausgaben')|float%} {{value |round(2)}} {%else%} 0 {% endif %}
Instead of making the sensor return 0 when something is unavailable is there any other way of return the data before that happened?
the entire yaml config of the sensor
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
@mental violet you can really simplify your template. And I would advice to use an availability template instead of setting the value to 0 if your source sensors are not available
state: "{{ (states('sensor.legro_monatliche_einnahmen') | float - states('sensor.legro_monatliche_ausgaben') | float) round(2) }}"
availability: "{{ states('sensor.legro_monatliche_einnahmen') | is_number and states('sensor.legro_monatliche_ausgaben') | is_number }}"
hi i am trying to split the date (year, month, day) in a seperate number
i got this, but i dont know what i have to type in for the second and the third value (after that "|")
{{ (states('sensor.date'))[1:-1].split('-') | map('float') |first }}
you don't have to use sensor.date for that
how can i do it otherwise?
just use {{ now().year }} {{ now().month }} and {{ now().day }}
Oh ok nice
but in this case? (it could be that i am getting to this problem a second time, without "sensor.date" as my entity?
top accually answer your question, you need to convert it to a list, and take the second item
{{ (states('sensor.date')[1:-1].split('-') | map('float') | list)[1] }}
why do you have the [1:-1]?
รคhm :D i dont know, my template is a big copy of different google searches :D
okay, that takes of the first and last character of the date string, so if the date is "2023-03-21" it will result in "023-03-2"
i made a template sensor for my electricity tarif
how can i now use this to calculate the costs?
- platform: template
sensors:
your_tarif:
friendly_name: "My Tarif"
unit_of_measurement: "CHF"
value_template: >
{% set tariff = { "HT": 25, "LT": 19 } %}
{% if (now().weekday() < 5 and (7 <= now().hour <= 20)) or (now().weekday() == 5 and (7 <= now().hour <= 7)) %}
{{ tariff.HT }}
{% else %}
{{ tariff.LT }}
{% endif %}
this is in the configuration.yaml
What's CHF?
swiss franc
changed it to:
- platform: template
sensors:
your_tarif:
friendly_name: My Tarif
unit_of_measurement: CHF/kWh
value_template: >
{% set tariff = { "HT": 0.2366, "LT": 0.1935 } %}
{% if (now().weekday() < 5 and (7 <= now().hour <= 20)) or (now().weekday() == 5 and (7 <= now().hour <= 7)) %}
{{ tariff.HT }}
{% else %}
{{ tariff.LT }}
{% endif %}````
seems like i solved it
- sensor:
- name: "Strompreis"
unit_of_measurement: "CHF/kWh"
state: >
{% set tariff = { "HT1": 0.2366, "LT1": 0.1935 } %}
{% if (now().weekday() < 5 and (7 <= now().hour <= 20)) or (now().weekday() == 5 and (7 <= now().hour <= 7)) %}
{{ tariff.HT }}
{% else %}
{{ tariff.LT }}
{% endif %}```
but i don't know what the difference is between this 2. they both show up and it seems they change the values as expected
anyone can eli5?
The first is the legacy format (now discouraged) and the second is the new format
Both are described in the docs for template sensors
i deleted the legacy out of the configuration.yaml and did a reboot. the sensor is stil showing up
why?
Is it possible to have a binary sensor that shows as false, rather than off and if so, how do I configure that? Right now my binary sensor (from the template) has the on/off states...
no, a binary_sensor can be on, off, unavailable, or unknown
you can create a template sensor and have it report whatever you want
Thanks!
Hey can somebody help me with my template. I have an input boolean with all and my scenes and want to activate a scene if i press an button. if i press the button again the next scene in the list shut be turned on. This is my code. Thanks for your help. https://dpaste.org/2GMdt
you're missing a bunch of indentation
proper indentation is critical for YAML
you also have two data sections?
not really sure what you're doing there
I guess you're missing the service call for the second bit where you're trying to set the input_select, but you can replace all of that with simply this:
- service: input_select.select_next
entity_id: input_select.scene_switch
Thanks, can you help me again, i think i made it. But i get an error: https://dpaste.org/a0evA
you still have broken/no indentation
what do you mean?
I'm not sure where you're putting that
you have two service calls
this part:
service: scene.turn_on
data:
entity_id: "{{states ('input_select.scene_switch')}}"
note that "entity_id: ..." isn't indented
the error tells me that this is all part of some much larger thing:
Message malformed: template value is None for dictionary value @ data['action'][3]['choose'][0]['sequence'][0]['choose'][0]['sequence'][0]['default'][2]['choose'][0]['sequence'][1]['data']
I am trying to put this in an blueprint for an button press left in an blueprint for my ikea stryrabar controller
This is my full automation: https://dpaste.org/UEXx4
so you need to fix your indentation
- service: scene.turn_on
data:
entity_id: "{{states ('input_select.scene_switch')}}"
and get rid of the "null". I don't know what that's doing there
How do I fix that? I put the "null" away but I still get this message: Message malformed: not a valid value for dictionary value @ data['action'][1]['entity_id']
I gave you the code
you saw the message?
it assumes, of course, that the state of that input_select is a valid entity_id
yes I saw the message, but what is diffrent then mine ?
sorry man
if you don't pay attention to detail, you're going to have a bad time with YAML
english is not my first language
oh oke
i did not know what indentation was, but thanks
Thanks man, it worked. But when i switch through the scenes and a scene with less brigtness of the lights comes on the lights dont dim down
Hi all. Im all new to templates ๐ I got some serious good help from Tom in the forum but im a little stuck (and a littel confused) ๐ https://community.home-assistant.io/t/i-think-i-need-to-combine-my-wavin-air-humidity-data/547834/6 Will somebody help me a little closer to my goal? ๐
not sure if templates or integrations, but im trying to use the file integration and a value template and it doesnt seem to be working right. it's showing a value of unknown.
this is whats in my config.yaml
- platform: file
file_path: /config/person.json
name: device_trackers
value_template: "{{value_json.data.items[0].device_trackers}}"
...
homeassistant:
allowlist_external_dirs:
- "/config"```
and this is whats in the file im trying to use
https://hastebin.com/share/eziposumol.json
anyone know whats going on here
not sure what you are confused about, do you not know where to put conditions?
Yea im really not sure how to build the condition with the template ๐
And im not sure how the trigger is working ๐
im getting this error in the logs: Template variable error: 'value_json' is undefined when rendering '{{value_json.data.items[0].device_trackers}}'
Well you ahve to come up with the automation, that condition is just for an automation
That means you have the wrong file path or the information in the file is not json
Yea. So the trigger is like "Dont turn off light in bathroom"
that's not a trigger
a trigger is something that will start the automation
like the light turning on
Ah sorry no that is a Action ๐
as far as both i and jsonlint.com can tell, it's a valid json
additionally, it works fine in dev tools template if i do it that way
then your path is wrong to your file
Yea okay so i need that to be "10 % higher humidity in bathroom" ๐
then you can use that template in a template trigger
is there anything else it could be, the path is definitely right
there's only 2 things it can be with that error. The JSON is not JSON, or the file is not located where you think it is
there's nothing else that could be the problem
Ouh then you lost me ๐
it's stating that value_json can't be resolved, meaning it wasn't able to make json out of the value from the file
and the only 2 things that mean that are: Not json, or it has nothing to read because it's the wrong file
Have you made an automation before?
if yes, then you've made a trigger
all you need to do is select template trigger when adding the trigger and put that template into it
Yea i made a automation - turn off light when plex is playing ๐ But this is way more complicatet for me ๐
well then its gotta be something wrong with the json. heres what it looks like https://hastebin.com/share/eziposumol.json and this config.yaml
- platform: file
file_path: /config/person.json
name: device_trackers
value_template: "{{value_json.data.items[0].device_trackers}}"```
im not sure knowledgable with this but it looks fine to me, so im not sure what the issue is
But im so confused what template i should use now ๐ I got this:
template:
- sensor:
- name: "Average humidity"
unit_of_measurement: "%"
device_class: humidity
state: >
{{ ( state_attr('climate.alrum', 'current_humidity')|float(0) +
state_attr('climate.kontor', 'current_humidity')|float(0) +
state_attr('climate.bryggers', 'current_humidity')|float(0) ) / 3 }}
availability: >
{{ ( state_attr('climate.alrum', 'current_humidity')|is_number and
state_attr('climate.kontor', 'current_humidity')|is_number and
state_attr('climate.bryggers', 'current_humidity')|is_number ) }}
- name: "Average humidity"
why are you concerned with that template?
that's in the past, that should already be in your system
this is all you care about now
{{ state_attr('climate.alrum', 'current_humidity')|float(0) <= 1.1 * states('sensor.average_humidity')|float(0) }}
what's the name of the file and where is it located in your system?
But that dosent seem right to me. i need the average for all the 3 rooms "alrum, konto and bryggers" ๐
person.json and its located in /config/person.json
I dont think it is in my system. I have not made this template ๐
if i make the template {value} it shows the values as }
which doesnt make sense as far as i can tell?
then that should be working, if the path is correct try just using the template {{ value[:5] }} and the sensor should have a state of { "v
If that doesn't have that state, then you have the wrong file. If it does, then it's not JSON.
then what are you waiting for? Add it to configuration.yaml
How do i do that? ๐
You have to gain access to your files somehow
either through one of the addons that allows you to edit files, SSH, or Samba Share
Ahh so i need to access the files in my HA setup (Unraid) ? ๐
A container but i think it is Core ๐
you set up a docker container running home assisstant?
Yeap ๐
that requires writing and running code
I'm not trying to be an ass here, but if you can do that but can't edit a text file, you're going to have a really bad time with that install method
Ahhh okay ๐ i use the web gui when making automations ๐
My configuration.yaml is like this:
Configure a default setup of Home Assistant (frontend, api, etc)
default_config:
Text to speech
tts:
- platform: google_translate
group: !include groups.yaml
automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml
ok, so add what tom wrote to you into that file at the bottom and you'll have that sensor for use.
So this? ๐
template:
- sensor:
- name: "Average humidity"
unit_of_measurement: "%"
device_class: humidity
state: >
{{ ( state_attr('climate.alrum', 'current_humidity')|float(0) +
state_attr('climate.kontor', 'current_humidity')|float(0) +
state_attr('climate.bryggers', 'current_humidity')|float(0) ) / 3 }}
availability: >
{{ ( state_attr('climate.alrum', 'current_humidity')|is_number and
state_attr('climate.kontor', 'current_humidity')|is_number and
state_attr('climate.bryggers', 'current_humidity')|is_number ) }}
- name: "Average humidity"
Okay cool. I give it a try ๐
"The system cannot restart because the configuration is not valid: Error loading /config/configuration.yaml: while scanning for the next token found character '\t' that cannot start any token in "/config/configuration.yaml", line 26, column 1"
๐ฆ
Ahh
Got a empty line ๐
So now how can i check that it worked? ๐
If you restarted it will show up in developer tools states page
Itโll also show up for use in automations when using entity_id fields
It will not work for a device trigger, so donโt use that. It wonโt show up for any device things
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.
Ah okay. But i can see it now. very nice! Thanks! But the the trigger i dont think is right ๐ Becurse it is the light in the bathroom that i dont want to turn off then then humidity is 10 % higher there ๐
Is this not more correct? ๐
condition:
- condition: template
value_template: "{{ state_attr('climate.bathroom', 'current_humidity')|float(0) <= 1.1 * states('sensor.average_humidity')|float(0) }}"
Sry, driving
That is fine ๐
i figured out the issue, the integration only reads the last line of a file
Use the rest int
@mighty ledge when you have time will you ping me? ๐
I'm not sure if this is the right channel, but I started using this configuration to pull data from my Hayward Aqua Connect on the local network: https://github.com/amscanne/aqua-connect-local It's working great, but the only issue I have is that it makes my logbook extremely noisy because of the way the interface works. The page the restful integration looking at simply changes it's return value every few seconds to cycle through the different bits of information. This causes pool_panel to drop a new logbook entry every time the page changes. I only care about the information the templates are pulling, not the change of the pool panel. Is there a way to put this in "quiet" mode or something similar? I looked at the restful integration docs, but didn't see anything.
Hi, it's there a helper in HA that can allow me to calculate total consumption from a rate like L/h?
Utility meter comes to mind
is there a way to check if a string is in a txt file(maybe 4000 lines)? and what is the maximum length allowed in attributes ?
im feeling a bit dumb rn, i feel like this should work but im getting the error UndefinedError: builtin_function_or_method object has no element 0 and im not sure how to fix it ive spent hours on this lol
template here https://hastebin.com/share/liyunidiko.kotlin
items is a function, so you need to use
{{ value.data['items'][0].device_trackers }}
hi
im trying to round down or up but i cant get it to work.
i can only seem to round down or up the decimals i want to round to nearest 10
looked here but i can figure it out
this is my string
{{ states('sensor.kit_motion_01_battery') | round | int (0, 'floor')}}%
what am i mising ?
You are adding floor to the int filter
but | round(0, 'floor') basically does the same as | int
but how do i get 60, 70, 80 and not 65, 74, 82 ? the original value is 65,4 and that gets to be 65 or 66 but i want it to be 60
tysm
is it possible to use a template in a trigger/platform the way you can in a service
i mean something like this
entity_id:
{{ '- sensor.'~(states('sensor.devicetrackers')|replace('[','')|replace(']','')|replace('\'','')).split (', ')[0]|replace ('device_tracker.','')~'_bluetooth_connection'}}```
if it works, this should be showing this ```platform: state
entity_id:
- sensor.pixel_4a_bluetooth_connection```
but im not sure if theres another syntax or if this is just straight up not possible
{{ states() | round(-1, 'floor') }}
ahh genius ๐ why can i find that info in the https://jinja.palletsprojects.com/en/latest/templates/#jinja-filters.round ๐ฆ
thank you soo much
so that would make -2 round down 10's if i have like 110 it would be 100
how would i use a template trigger for this, since its trigger based off whether the value is different from before. i can think of making a template sensor with the old value delayed by a second, is there an easier way?
It actually gives this example, the only thing it doesn't mention is that you can use a negative precision
{{ 42.55|round(1, 'floor') }}
-> 42.5
yes ๐ that is what i ment it dont say and i'm not smart enough to just try ๐
This just looks like a really complicated way to get an entity id
it is
because the entity id can change
its basically a complicated way to never have to update the automation for when the entity id changes
So please explain what you are trying to achieve here
What is in that sensor.devicetrackers
a list of active device trackers/ha mobile app instances, basically
so when the list changes rather than updating a bunch of automations, im trying to get them to read from the file when necessary
I would start with putting that list in an attribute of that sensor, so it's actually a list and not a string
That will make working with it a lot easier
im using the command line integration which doesnt seem to support templates for attributes
otherwise i would
What is the code for that sensor?
And you could always create a template sensor out of it ๐
- platform: command_line
name: devicetrackers
command: cat /config/.storage/person
value_template: "{{ ((value_json['data']['items']| selectattr('name', 'equalto', 'jack5mikemotown') | first)['device_trackers'])}}"```
true perhaps this is the way to go
Are those all the device trackers linked to your person entity?
yeah
it would be cool if the info were exposed as a sensor, but such is life, i suppose
hmm almost there now it gives a value of 60.0 not 60 how do i get rid of the decimal ?
and this time i tried different -1 ,-2, -01, -10 but no ๐ฆ
Good morning everyone. I have a problem configuring 2 invites teeth that I can't go on I have two thermostats in the living area and in the sleeping area I can't insert them both in Home Assistant. in attached the link with the syntax that gives me error, thanks https://pastebin.com/ZFQS0PNy
Two entity
Add | int
i have {% set batterylevel = states('sensor.kit_motion_01_battery') | int| round(-1, 'floor') %}
i get mdi:battery-60.0
whole code is
{% set batterylevel = states('sensor.kit_motion_01_battery') | int| round(-1, 'floor') %}
{% if batterylevel == 100 %}
mdi:battery
{% else %}
mdi:battery-{{batterylevel}}
{% endif %}
You can create attributes in a command line sensor so it seems https://www.home-assistant.io/integrations/sensor.command_line/#json_attributes
Wrong order, first round, then int
The result of round is a float
{%set batterylevel = states('sensor.kit_motion_01_battery') | round | int(-1, 'floor') %}
gives this mdi:battery-66
๐ฆ
No, now your are adding the settings for the round filter to the int filter
this example just lists attributes. i tried using a template sensor and it errored out when setting up the integration. just doing an attribute entry put most of the thing there. not sure if im just doing it wrong? but it doesnt seem to work the way i need```sensor:
- platform: command_line
name: JSON time
json_attributes:- date
- milliseconds_since_epoch
command: "python3 /home/pi/.homeassistant/scripts/datetime.py"
value_template: "{{ value_json.time }}"```
ok got it ! ๐ {%set batterylevel = states('sensor.kit_motion_01_battery') | round (-1, 'floor') |int %}
wuhuu
I'm currently not able to test it myself as I'm on mobile
What is the current state of your sensor
['device_tracker.pixel_4a', 'device_tracker.pixel_6a']
Okay, and what do you want to do with that?
ive got it all fine for the actions where i use it, but for the triggers, in the specific example above, id like it to trigger if the bluetooth state of any device in that list changes
What do you mean with the Bluetooth state? Is that just the state of the entity?
iirc yeah, when the state of the entity changes, which i believe is no of bluetotoh devices connected
So the state is either home or not_home
no its bluletooth connections so its 0, 1, 2, etc.
That doesn't make sensor for a device_tracker
?
You have two device trackers here, how can the state be 0 or 1 or 2
thats why im doing this
{{(states('sensor.devicetrackers')[0]|replace ('device_tracker.','')~'_bluetooth_connection')}}
to replace device_tracker with sensor and bluetooth_connection
So that was my question here, on which you responded with the state of the entity
oh
sorry i misunsderstood the question
no its not the state of the sensor.devicetrackers entity
But back to the start, what are you trying to achieve, why do you want to trigger when for any of the device trackers associated to your person entity the number of active BT connections changes?
in this instance, i want to trigger a manual location check on the device
Okay, I would create a template sensor out of your command line sensor with an attribute to show the active BT connections per device tracker
You can then use a state trigger on that attribute for your trigger
one last question today
why is this not working ? i dont get any colors on the icons in mushroom template card
{% set batterylevel = states('binary_sensor.kit_motion_01_battery_low') | int %}
{% if batterylevel > 60 %}
green
{% elif batterylevel > 20 %}
orange
{% else %}
red
{% endif %}
nevermind ! i got the wrong entity ๐ฆ
For next time, please format your code
To format your text as code, enter three backticks on the first line, press Shift+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.
yep sorry
hi, wondering if anyone can help explain (rather new to all this):
i'm trying to set up a fan entity. i notice this has a service called 'oscillate'. how can i call this service? for example, in configuration.yaml there are properties 'turn_off' and 'turn_on' which i can define how to execute. There is a 'set_oscillating' property but not 'oscillate'
This is not related to this channel, but something for #integrations-archived .
ic thanks
I habe question about the template sensor switch
Basically here is my issue
I want to track if a server is online, and i can send requests to HA to set the template to on
However, i'd like it automatically to go to "unavailable" after there are no updates for 10minutes.
Is that even possible?
The server can be on, off or the way i update could fail so unavailable, i.e. could be on, could be off
How can i solve this?
Home assistant cannot request the server state directly, it has to be updated via api
Ping me with reply
thanks ill try that
Template sensors can be updated based on triggers. Triggers have the ability to see if there hasn't been an update for 10 minutes. So you can make a template sensor that represents the state of the switch. Then use that sensor in a template switch's value_template.
hello, I tried the utility meter. I inserted a sensor which is worth 15 EUR. But the utility meter showed me a value of -15 EUR. Why is it representing the value to me as negative? I have a positive value on the sensor.
Thank you.
is your energy negative?
will check it out, thanks
Hey guys - i'm using the Torque app and have a latitude sensor and longitude sensor (plus Altitude)
How can I combine both (or all three) on a map to track where I parked my car?
you have to make a template sensor with latitude and longitude attributes
Then attach that to a person
Would I create a person called "MyCar" if i wanted to track that?
Downside of using a person entity for your car is that zone.home will have state 1 if you're not at home, but your car is (maybe you left by foot or bike)
yeah
if you're trying to track your cars position on a map
is that a binary sensor or sensor? I've been assuming (i know) that binary sensors were on/off or true/false - binary options. A sensor would be variable, so since GPS coordinates would be variable, it's a sensor?
reason I ask is the template sensor that includes GPS coordinates is a binary sensor
those go into the attributes
sensor
Hi all, I have a sensor that reports water flow in L/h. I'd like to create a total consumption sensor from this. Is there something I can use for this? Utility meter does not seem to work for this
also, I suspect if I wanted the sensor to report by the minute, I would have to involve some math template to get consumption= ((rate L/h)*3600 s)
You'd need to convert it to m3 for use in the energy dashboards
Oh, nope, it supports L
ahh yes, so indeed, I have to convert it to L
its not, because its a rate, L/h. when water flows, a number is shown, when water stops flowing, it goes to 0
How does this look for the sensor with lat/long attributes? https://hastebin.com/share/asagiwitur.yaml
then you would want a Riemann sum sensor
Rienmann goes from x to X/time
derivative goes from x/time to x
oh, that's right
I'm not sure if it would work in that case tho
๐คทโโ๏ธ
college was so long ago
yes, exactly, I'm stumped on this one also...I'll have to just make a template sensor, I don't think any of the helpers (in the UI at least) would apply here
I use an ESP8266-based pulse meter that initially reports a rate, but I multiply that by the time period to convert to (roughly) instantaneous usage, and then I use a statistics sensor
This is my ESPHome sensor:
sensor:
- platform: pulse_counter
pin: 12
name: "Water Usage"
update_interval: 10s
force_update: true
unit_of_measurement: 'gal'
filters:
# reports in pulses/min, so divide by 6 and by 64 pulses per gallon
multiply: 0.0026041667
I expect that to give me gallons used in the last 10s
and this is my statistics sensor based on that:
- platform: statistics
entity_id: sensor.water_usage
name: "Water Usage Stats"
state_characteristic: total
# 10s sampling, so 6*60*24 points
sampling_size: 8640
max_age:
days: 1
are you using OCR to get those numbers?
or is this a legit sensor
it's a pulse meter on my water softener
I tapped off the existing connector and fed it into an ESP8266
with a level shifter
it was a fun project
thanks, Rob I can work with your setup, its basically the same, except mine is L/h
I also have a utilty_meter that gives roughly the same value as the statistics sensor:
utility_meter:
water_utility:
source: sensor.water_usage
name: Water Usage Today
unique_id: water_usage
cycle: daily
delta_values: true
This is my watermeter ๐
It counts every time some dial rotates, which indicates 1 liter water
I was just going to get an OCR camera but i'd need to put a flash light on it to keep the meter's value shown
it doesn't have power connected to it, so it uses solar power to power the lcd screen
amazing to see what everyone has for water meters....this mine, a meter plus valve....its z-wave....i
oh, I can't share images....but i'm working with Al Calzone to get it fully functional in z-wave js
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.
oh thats kinda cool
I was planning to DIY something like that until I figured out how to get the data from my water softener
it works well... its supposed to detect leaks down to 0.1 L/h and tell you and it shuts off the valve if certain thresholds are met ....low, medium and high flow rates...also tells me the temperature of the water if its too high or low. Its still needs some tinkering for zwave-js...so I would not call it fully compatible just yet.
https://github.com/zwave-js/node-zwave-js/discussions/4902
Any idea how I might run a template that chooses the highest value of five of my sensors without doing five "check if this sensor is great than this and this and this"
like I want to see the top 3 zones i've spent time in, etc
[ 1, 2, 3 ] | max will return 3
so you just gotta get the values from the 5 sensors, put them in a list, then get the max value with | max
wow, that sounds much simpler than I'd imagined, thanks - will try that out now
what about if I want to find out 2nd place or 3rd place?
if you want the entity_id that gave you the max value... then that's another story
oh yes haha that is what I want
I don't want the max value, I want to find out what is giving the max value
so if sensor.blahblah is giving 5 and the others are giving 3 I want to know which sensor that is
rather than just get "5"
I'm sorry - i've tried a few variations but for some reason I can't seem to get HA to show the attributes I'm looking for?
template:
- sensor:
- name: focus
state: "{{ state_attr('sensor.focus_GPS', 'carlocation') }}"
attributes:
latitude: "{{ state_attr('sensor.vehicle_gps_latitude', 'carcoordinateLatitude'}}"
longitude: "{{ state_attr('sensor.vehicle_gps_longitude', 'carcoordinateLongitude'}}"
- name: focus
{{ expand('sensor.1', 'sensor.2') | sort(attribute='state') | map(attribute='entity_id') | list }}
then item 1 will be either the lowest or highest, can't remember
either way, first item [0], second item [1]... last item[-1] second to last item [-2]
etc
great - that makes sense. Will have a play around with it
they most likely aren't attributes, it's just the main state states('sensor.vehicle_gps_latitude')
any chance to invert the list (e.g. if the lowest value is listed first)?
my point is, it doesn't matter because you can work from either side of the list
but it does have a reverse flag you can supply to it
sort(attribute='state', reverse=True)
oh yes, so you're saying -1 will return the last item, ok that makes sense
I will try that, and try the reverse if necessary
that definitely sets me on the right track
just keep in mind that it may not work because it's comparing strings
But if the states are numbers, it will not sort then correct. As it will sort strings
Slowpoke
looking at the template editor, it seems to produce a list that makes sense
ah you're saying the reverse thing won't work?
if your sensors all have the same significant figures, it will work
i.e. if they are all numbers that range from 0 to 9.9999
however, if you have a number that's 10... it will sort them... 1, 10, 2... 9
and what about 99.9999?
oh bugger yeah
that's going to be annoying. Currently the highest value is below 10 but I imagine it will go above that
is there a way to account for that?
it's moving left to right on the string
so 2 is higher than 10, always
because 2 is the first character in the string
if you want to treat them like numbers, you'll have to convert the values to numbers but you'll lose access to the entity_id
you can use namespace to store them as a key value pair
Referring to Amcrest integration. I set up below automation for my AD410 doorbell. However it never gets triggered. What did I do wrong?
`- id: '1679408824655'
alias: Doorbell ring
description: ''
trigger:
- platform: event
event_type: amcrest
event_data:
event: "CallNoAnswered"
payload:
action: "Start"
condition: []
action:`
Oh sry.
so the sensors are created from utility meter sensors, are they still stored as strings?
what is a namespace / key value pair?
all states in HA are strings
namespace and storing the entity_id and numerical value as you iterate the list of entities
{% set ns = namespace(items=[]) %}
{% for s in expand(...) %}
{% set ns.items = ns.items + [ {'entity_id': s.entity_id, 'state': s.state | float(0) } ] %}
{% endfor %}
{{ ns.items | sort(attribute='state') }}
wow
I really appreciate this by the way
but I do feel like I've now gone a little out of my depth
ok, I seem to have got something out of that
[
{
"entity_id": "sensor.x",
"state": 0
},
{
"entity_id": "sensor.y",
"state": 1.5
},
{
"entity_id": "sensor.z",
"state": 3.48
}
]
so if this is one sensor, how do extract these bits to a notification to say "This month, sensor.z was the highest with 3.48" ?
I was referring to myself
also, sorry, but am I putting the above in a template sensor? it doesn't seem to have the same result
I thought that it was faster on your screen than mine
I even refreshed the page
States are always strings, do if you use this as the state of a template sensor it won't be a list with dicts anymore
So either store it in an attribute, or select the highest one from that list and use that for the state
{% set ns = namespace(items=[]) %}
{% for s in expand(...) %}
{% set ns.items = ns.items + [ {'entity_id': s.entity_id, 'state': s.state | float(0) } ] %}
{% endfor %}
{% set items = ns.items | sort(attribute='state') %}
This month {{ items[0].entity_id }} was the highest with {{ items[0].state }}
Or do just that, maybe with a reverse in the sort, or by selecting the last item if you want the highest
Yeah I can't remember if it's ascending or descending
you can reverse the list with what I posted above reverse=True
I based that on this
awesome
this is looking great
just 2 small things and it's perfect
and btw, i appreciate your input and help with this
hope it's not too frustrating - your help is invaluable to me here ๐
- can I store the sensor's "friendly_name" instead of entity_id?
- template editor works great but where am I putting this in my yaml to bring it as a proper sensor in to home assistant?
Use s.name instead of s.entity_id to get the name
You might want to rename the key a well then to avoid confusion
So basically anywhere where it states entity_id you can replace that with name
And how do you want to use this? On your dashboard? In a TTS message? In a notification?
in a notification
I already have a flex-table-card which sorts the entities and show's which is top, etc.
hello I tried the utility meter I
but I want a notification to go out each month with:
- x with 2 hours
- z with 3 hours
so it can be a sensor value that I call ?
Or just use the template for the notification message
oh that's not a bad idea haha
thanks again - I really appreciate all the efforts to help
truly it's taken me ages trying to work out how to do this
I would appreciate a pointer. Is there documentation on how to create a template that will check something like: If HallMotionSensor is on and within 60 seconds, kitchen motion sensor is on and then 90 seconds, a socket is turned on: do something. I'm not comfortable enough yet to write this from scratch without drawing from documentation. Thanks.
that woould be an automation
Yes. But one of the triggers of the automation would be a template to check for motion sensors changing state in a specific order within an interval.
that can all be done with wait for trigger in an automation
A quick look at forum posts relating to WaitForTrigger shows that it would require that I use it in conjunction with a timer. This means I need to start a timeer on each motion sensor. Is there no way of checking if other sensors were set to on within a set time with a template? I would very much rather not use a timeer. in conjunction with WaitForTrigger. It becomes very messy.
No? just use a for trigger
Thanks. I'll give this a shot.
Hoping someone can help me out getting my head around this garage door opener template/cover thingo...
Is it possible to a regex replace on a list? I tried but it only replaced the first item.
{% set t = ['binary_sensor.foo_e','binary_sensor.foo_eee'] %}
{{ t | regex_replace('^.*?\\.','') }}
is there a way to have relative_time use abbreviations like "mins" instead of "minutes"?
For anyone else running into this because of space constraints with a tiny ESPHome screen you can do it locally inside ESPHome. Won't help if you need this done inside homeassistant but maybe a template sensor (or just template if your use case supports it) that does a string op on the output?
As it returns a string, you can replace it {{ relative_time(now()-timedelta(minutes=5)) | replace('minutes', 'mins') }}
Hi all...
What am i missing here?
I have a helper to change the text in "input_text:text". But i cant broadcast it?
service: google_assistant_sdk.send_text_command
data:
command: Broadcast "{{input_text.text}}"
you have to get the state out with the states method
How can I do that?
Can you pls guide me? (Iยดm kind of new to this)
This is probably going to be a bit advanced for you then. I'd recommend watching some videos that explain concepts like functions and methods, then templating will make a LOT more sense.
Figured it out.
Changed it to :
command: Broadcast {{ states('input_text.text') }}
Now it works. ๐
Is it possible to a regex replace on a list? I tried but it only replaced the first item.
{% set t = ['binary_sensor.foo_e','binary_sensor.foo_eee'] %}
{{ t | regex_replace('^.*?\\.','') }}
Dan, you should spend some time learning where filters can be used
and the difference between a filter, a function, and a test
and where all of them can be used
like in functions like map, select, etc
e.g.
I will get to reading
I'm just suggesting this because you keep coming here with similar questions and if you understood these principles, you wouldn't have any of them
I'm learning each time and learning from reading too on multiple sites lol. When I think of something I'm not sure if it's possible I come here. I almost came here to ask how to get keys from dicts when you have the value but then I found a thread from 2018 where you and someone else provided examples to do that.
I came here a lot more back during the summer lol
I am getting an error in my config.yaml and it's stopping all of my automations from working. I can't figure it out.
Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected '}', expected ')') for dictionary value @ data['binary_sensor'][3]['state']. Got "{{(state_attr('binary_sensor.lumi_lumi_motion_ac02_iaszone')}}". (See /config/configuration.yaml, line 33).
template:
binary_sensor:
- name: "basement_motion_notdetected"
delay_off: "00:00:10"
state: "{{(state_attr('sensor.lumi_lumi_motion_ac02_iaszone')}}"
You've got an extra parenthesis at the beginning
"{{(state_attr('sensor.lumi_lumi _motion_ac02_iaszon e')}}"
^
also doesn't a state_attr need an attribute for the 2nd parameter?
It looks like turning a sensor value into a binary sensor here is the attempt?
Probably, which is weird because it looks like it's a Zigbee sensor which should already have a binary sensor entity
The parentheses was it.
I was doing the sensor to get the delay off. Couldn't find another good way to do that.
Hey just a quick question can i use tempalting when adding ui elements ? (rough example with mushroom chips card)
type: custom:mushroom-chips-card
chips:
{% for light in lights %}
- type: light
entity: light.tradfri_2
{% endfor %}
I have a question about how template sensors work, and when they are updated. Let's say I have a template sensor that derives its value partially from a number helper.
In an automation, I will first change the number helper, and then I'll use the template sensor. Does the sensor update when the number helper changes, or when it's 'accessed' by the automation?
No, thatโs not possible
Template entities update when references sensors update unless it uses a trigger. Home assistant is asynchronous. If you update the helper entity, the template will update after. However because home assistant is asynchronous, you won't know which will occur first (the template sensor or when it's accessed).
Thanks. But I think that does help me even if it's asynchronous (if I understood correctly).
I'm working on an automation to determine when to run my washing machine, and prefer to use a template sensor to set a datetime than to have the whole template in each automation that needs it.
Hello I think this is the right chat, I currently show my Sonos system in a media player card on my dashboard. I want to hide the Sonos media player card when the Sonos entity is playing โTVโ and then display another card with media controls for the tv on it. How would I go about functionality the design I can sort myself thank you in advance ๐
I think you need to ask in #frontend-archived, or just look for conditional card
will do thanks
I'm experimenting with creating a few template sensors for power monitoring, and I'd like to compare to a sensors previous state.
How can I call this data ?
I've tried states('sensor.xxxxxxxx.from_state.state') but that doesnt work ..
internet and even chatgpt is not helping either ๐
right, you can't do that
the straightforward way is to use a trigger-based template sensor with a state trigger and use this in a template https://www.home-assistant.io/docs/automation/templating/
there's an example on that page
Does this work for other zones as well?
how to check state of list entities
EX: {% if ([sensor.1,sensor.2,sensor.3,sensor.4] is on ) %} True {% else %} False {% endif %}
Thanks
Yes, all zones use the number of person entities in it as their state
Do you want all of them to be on, or at least one
i want use for template conditions
check one of the entities if on will be True
So it should return true is at least one of those sensors is on
yep
{{ [ 'sensor.foo', 'sensor.banana', 'sensor.petunia' ] | select('is_state', 'on') | list | count > 0 }}
many thanks
if I want my rest sensor value_template to evaluate to the first one in this list, can I only do that using the verbose date in that template like - unique_id: solar_forecast_estimate_watt_hours_day name: Solar Forecast estimate watt hours day value_template: > {{value_json.watt_hours_day[now().strftime('%Y-%m-%d')]}} ? I had hoped to do smth like {{value_json.watt_hours_day[0]}} but that renders 'unknown'
this works: {{state_attr('sensor.solar_forecast_estimate_watt_hours_day','watt_hours_day')|first}} its not a list, its a dict...
this doesnt work though ```
value_template: >
{{value_json.watt_hours_day|first}}
value_template: >
{{value_json.watt_hours_day.items() | list | first }}
ok, have one remaining poll.... let me try that, thx! (too bad we need to reload the rest sensor for that, would nt this be a mere template reload (the resource doesn't change, only the template on that resource, and there is no other way of testing those paths is there?
heck, too late... and now all of my other rest sensors are empty too....
just use the json returned from the API in devtools > templates until you have your templates right
{% set value_json = whatever %}
{{value_json.watt_hours_day.items() | list | first }}
o yes, that helps! need to add the extra 'result' there, but other than that, this nis the result of that template, type list: [ "2023-03-23", 9643 ]
what do you want it to return?
sorry, I need the value, so 9643. but checking that output, I now see its lists yesterday and today, so, Id need the todays date, being in this format {{now().strftime('%Y-%m-%d')}}. Let me try to add that to the template, instead of |first
yes, {{value_json.result.watt_hours_day[now().strftime('%Y-%m-%d')] }} returns the value correctly in the temoplate editor! Woinder why the rest sensor didnt though....
this should do it: - unique_id: solar_forecast_estimate_watt_hours_day name: Solar Forecast estimate watt hours day value_template: > {% set today = now().strftime('%Y-%m-%d') %} {{value_json.result.watt_hours_day[today]}} json_attributes_path: "$.result" json_attributes: - watt_hours_day
thx!
on updating these sensors (rest and its template sensors) and mitigating the rate limit: I believe the best method is setting an update interval 86400 and next, automate the update each our while the sun is up. give or take. that should prevent exceeding the set limit of 12
this should also work if you always want the value of the first item
{{value_json.watt_hours_day.values() | list | first }}
yes it does now. didn't use those constructions (values() or items() ) in my templates yet, so still a bit new territory for me. #TIL...
have another question on the updating, but that would be #automations-archived so hopping over now ๐ thanks Martijn
no problem!
How often do template trigger binary sensors evaluate their state if I use a template? Such as one template trigger binary sensor becoming on if another template trigger binary sensor hasn't also triggered? If it did then it doesn't turn on.
But that only works if it's constantly evaluating and not a one time evaluation at the time of the trigger.
If the template contains the states object with no domain reference, it's throttled to at most 1 update per minute. If the states.<domain> object is used, the template is throttled to at most 1 update per second. If neither are used, the template will update when the entities inside them update. Using now() in a template will cause an update to occur on the minute. If you use a trigger for the template entity, the template will only update when the trigger is fired.
Would now() cause it to update every minute even when using a template trigger or not at all?
I'm trying to create 2 template triggers for zone events. When someone enters a specific zone however I don't want it to turn on if the other also just entered that zone between x time.
Ex. Foo enters x zone between 06:00 and 09:00 and bar also entered then the state doesn't turn on. Only when foo enters and bar didn't enter. The reason I wonder about evaluations is sometimes zone updates could be delayed a few seconds. One phone may send it sooner than the other.
No, if you use a trigger, the trigger is the only thing that will trigger it.
Any thoughts on how to accomplish what I'm trying to achieve? If it's possible at all?
if you want it to update on the minute as well, add a trigger that does that
you can assign a trigger id that can be referenced in the template
right, so now ready for some manipulating ๐ please consider this value_json. If I want to have the max I can do
{{ value_json.result.watts.values()|max}}
a simple test in devtools > template would have confirmed that that results in 1836 which is indeed the hightest value
but now I want it to be todays day only, so need to select: {% set today = now().isoformat() %} first
{{ (value_json.result.watts.items() | list | sort(attribute='1', reverse=True) | first | default(("Unknown",0)))[0] }}
that gets you the max
what he had also works ๐
if you want to get only todays max...
what helps in selecting today is that it is already in the right timezone ๐
sure, I have that ๐
How would I do something like this? I am not sure how to reference the second trigger if it didn't occur yet.
{{ (value_json.result.watts.items() | list | rejectattr('0', '<', now().isoformat()) | sort(attribute='1', reverse=True) | first | default(("Unknown",0)))[0] }}
but if you want from midnight today...
{{ (value_json.result.watts.items() | list | rejectattr('0', '<', today_at().isoformat()) | sort(attribute='1', reverse=True) | first | default(("Unknown",0)))[0] }}
keep in mind that gives you the time, not the value
if you want the value, change the last [0] to [1]
yes, was doing that now...
remove the second - trigger:, only remove that line, nothing else.
but its not the highest.....
I would do this:
{{ value_json.result.watts.items() | selectattr('0', '<', (today_at() + timedelta(days=1)).isoformat()) | map(attribute='1') | max }}
it returns 1752
Whoops forgot about that. That would have been 2 separate template triggers not 1 entity.
which is listed here: so ther are at least 2 higher values
I was trying to keep it a KVP because of the inevitable "I want the time too"
Ah wait... I missed that it includes today an yesterday, I thought it had today and tomorrow
How do I get the state of the template trigger to be on if the second trigger bar_enter didn't occur at or around the same time as the first foo_enter?
now I also understand the filter petro used ๐
assign a trigger id to each trigger.
I did that part. But how does the template know which came first?
then perform logic based on the current state and the trigger that occured
the current state will be this.state
I am not sure it remains like that during the day. I believe at some point it changes that, thats why I need the actual date in there
so does the tempalte I provided work?
well, you can both reject yesterday and tomorrow to be sure
something like this in a 1 liner ๐
{{ value_json.result.watts.items() | rejectattr('0', '<', today_at().isoformat()) | rejectattr('0', '>=', (today_at() + timedelta(days=1)).isoformat()) | map(attribute='1') | max }}
If bar entered the zone first this should be false?
"{{ iif(trigger.id == 'foo_enter' and (now() >= today_at('06:00') and now() <= today_at('09:00')) and this.state != 'on','true','false') }}"
{% set midnight = today_at() %}
{% set tomorrow = midnight + timedelta(days=1) %}
{% set data = value_json.result.watts.items() | rejectattr('0', '<=', midnight.isoformat()) | rejectattr('0', '>=', tomorrow .isoformat()) | sort(attribute='1', reverse=True) %}
{{ (data | first | default(("Unknown",0)))[0] }}
but data in this regard will be a list of sorted times and values.
so you can use it however you want
yeah sure
if that was to me: no it doesnt actually, as postes above, it doesnt select the highest value..
the last one works
this does
this one as well ๐
this give me the time, and changing to [1] indeed yields the highest value correctly
Right, again, I kept it as a KVP so that you could get the time from it if you want
knowing you, your next question will be "How do I get the time"
so that you can trigger off it
or have it as an attribute
or whatever you want
If you just want the max, then you can map the value early on and skip a bunch of the template w/ sorting (what thefes posted)
nono, I love that. thx! Was just checking why the other template rendered the incorrect value
Personally, I would write an if for each trigger ID with it's own logic
ofc, the next improvement would be to select the best period, and not the highest value per point in time only. Give or take: the best providing 2 consecutive hours. But that might be stretching it for now... considering this already a forecast, I suppose some timing like tht is already incorporated in the data
Well yeah because If one takes just a second or too longer to send a zone update it wouldn't work. The idea is did both devices arrive in the zone at around the same time? If they did do nothing otherwise if only foo arrived in the zone between that time frame then it's true.
{% set in_window = today_at('06:00') <= now() <= today_at('09:00') %}
{% if trigger.id == 'a' %}
{{ in_window and this.state != 'xyz' }}
{% elif trigger.id == 'b' %}
..
{% endif %}
something like that
You're going to have a bad time with that
that's a condition
not a trigger
i.e. automation, not template entity
so, I recommend going with an automation that turns on/off an input_boolean
and if you want it as a binary_sensor, abstract that into a template binary_sensor
Good idea thank you.
are trhere any objections to use: {% set today = now().replace(minute=0).replace(second=0).replace(microsecond=0).isoformat() %} and next in the template select 'today' using | selectattr('0', 'eq', today)? it would only skip the first and last items, but since they never contain the highest value anyways, that would hurt
o wait, there are.... I now see that renders that same erratic 1752!
right, ofc. sorry
I don't see how that's erratic
1752 is the highest if you go from your current time
because it isnt the highest value
it's 12:36 or 13:36 where you are, correct?
12:36
12:36
ok, 11 is before that
so it selects the now...
btw, I guess it's shorter to do today_at().replace(hour=now().hour)
or today_at(now().strftime('%H:00'))
hmm, still dont understand why this yields perfectly | rejectattr('0', '<=', midnight.isoformat()) | rejectattr('0', '>=', tomorrow .isoformat()) , or this|selectattr('0','search','2023-03-24'), while my previous attempt above 'today' was incorrect
you are not replacing the hours here, so it will return today as today at 12:00
which will leave out the result of 11:00, which is the highest one
this {% set today = now().replace(minute=0).replace(second=0).replace(microsecond=0).isoformat() %} returns "2023-03-24T12:00:00+01:00"
and with: {% set today = now().strftime('%Y-%d-%m') %} which is 2023-24-03, andn using |selectattr('0','search',today) the template evaluates to 0.... because its unknown and the default kicks in
full template: {% set today = now().strftime('%Y-%d-%m') %} {% set data = value_json.result.watts.items() |selectattr('0','search',today) | sort(attribute='1', reverse=True) %} {{ (data | first | default(("Unknown",0)))[1] }}
thats because you should switch the month and day
........
first month, then day, longest period first
o dear o dear o dear... ๐ฌ
now it works.... thx Petro and Martijn. ,much appreciated! as ever
How do I check if a string starts with a specific value in a template?
{{ "test".startswith("test") }}
maybe a final touch: using the last actual template line like this {{ (data | first | default(("Unknown",0))) }} give s the KVP. if I would like to display that in the frontend as state like 1836 W om 11 uur how would I have to go about doing that. Or, Id only use the value as state, but maybe a secondary line in a template-entity-row.
Thanks!
{% set peak = (data | first | default(("Unknown",0))) %}
{{ peak[1] }} W om {{ as_datetime(peak[0]).strftime('%-H') }} uur
Hi again, I have the following event
event_type: rfxtrx_event
data:
values:
Command: Group off
Now I try to check if Command by using {{ trigger.event.data.values.Command == 'Group off' }} but it does not work? what am I missing? (I tried to cast it to a string using |string but that didn't work.
looks like values is a dict now i just need to find how i get a value from it
perfect!
After trial and error the following did the trick trigger.event.data['values'].Command
.values is a dictionary function, that's why you can't use it as a .values
values and items need to be ['values'] or ['items']
yea I figured that out after much pain ๐
the error in your logs should have pointed you to accessing that
I'd wager it would say something like NameError, values function doesn't have 'command' blah blah
ugh... so Ive got this {% set data = value_json.result.watt_hours_day.items() | list | sort(attribute='1', reverse=True) %} {% set peak = (data | first | default(("Unknown",0))) %} {{ peak[1] }} W op {{ as_datetime(peak[0]).strftime('%-d-%-m') }}working now as template based on the direct rest sensor data. However, I vcan notdo that on the attribute of the sensor, with```
{% set attr =
state_attr('sensor.solar_forecast_estimate_watt_hours_day','watt_hours_day') %}
{% set peak = (attr | first | default(("Unknown",0))) %}
{{ peak[1] }} W op {{ as_datetime(peak[0]).strftime('%-d-%-m') }}```
the {{attr}} returns Attr: {'2023-03-24': 6115, '2023-03-25': 9795} and not [('2023-03-24', 12224), ('2023-03-23', 9643)]. I did test to fake a list surrouding the set with [], but that wont go..
this being the result of the rest sensor data:```
{
"result": {
"watt_hours_day": {
"2023-03-23": 9643,
"2023-03-24": 12224
}
}
}```
also, if I add |list to the set, it transforms the output to a useless Attr: ['2023-03-24', '2023-03-25'] and loses the KVP
Trying to figure out how to add a condition to an automation checking if the automation hasn't been run in a specified time frame (example "since 2 seconds") but i'm not sure how to write it. I figured it should be something like {{ this.state.last_triggered != 2 seconds }} but that obviously isn't it. Any tips?
you need to apply .items() on the attribute
to convert the dict to a list of kvp tuples
try condition: - > {{now() - this.attributes.last_triggered > timedelta(minutes=5) if this.attributes.last_triggered is not none else true}}
magic! and as said, still new to those dicts.... changed it to {% set attr = state_attr('sensor.solar_forecast_estimate_watt_hours_day','watt_hours_day').items() %} {% set peak = (attr |max| default(("Unknown",0))) %} {{ peak[1] }} W op {{ as_datetime(peak[0]).strftime('%-d-%-m') }} to give me a meanigful secondary line. Show state as current, secondary the highest of the 2 listed days. so very useful
This worked but not the way i wanted. I realized i need the inverse. If the automation doesn't run again in the next x seconds then send the notification
see:
looking into the future can only be dine with a wait_template probably, and you can set a default action what should happen if that passes
How would that look like?
other than the template, that would really be an #automations-archived job though
yeah. they sent me here ๐
If "automation x or y hasn't run in z seconds" do this
or If triggerID x or y hasn't been triggered could work as well
Hi everyone! I'm looking to have a template that goes through all of my calendars with a for state in states.calendar, and only return calendars that have an event for that day. And if so, return the message attribute for that calendar. I can get the message attribute to show, no problem, but am unsure how to test whether that event happens today or not.
{% set tomorrow = (today_at() + timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S') %}
{{ states.calendar | selectattr('attributes.start_time', 'defined') | selectattr('attributes.start_time', '<', tomorrow) | map(attribute='attributes.message') | list }}
This will give you a list with all message values for the events today
@marble jackal Holy cow. That's amazing. I really wish I could wrap my head around templates. Is there a way to show the calendar that the message came from if it returned anything?
Where do you want to use this? On a dashboard?
Planning on using it as a daily briefing where TTS would say something along the lines of "The house calendar has an event today called cleaning" where house is the name of the calendar and cleaning is the message.
Okay
Something like this?
{% set tomorrow = (today_at() + timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S') %}
{% set ns = namespace(cal=[]) %}
{% for c in states.calendar | selectattr('attributes.start_time', 'defined') | selectattr('attributes.start_time', '<', tomorrow) %}
{% set ns.cal = ns.cal + [ c.name ~ ' has an event called: ' ~ c.attributes.message ] %}
{% endfor %}
{{ ns.cal[:-1] | join(', ') ~ ' and ' ~ ns.cal[-1] if ns.cal | count > 2 else ns.cal | join(' and ') }}
You can try it in developer tools > template
If you change the number of days in the first line, you will see more events
That definitely gets me close enough where I can tweak from there.
Where can I find documentation on namespace? That's the first time I've seen that used.
@marble jackal Tweaked it to:
{% set tomorrow = (today_at() + timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S') %}
{% set ns = namespace(cal=[]) %}
{% for c in states.calendar | selectattr('attributes.start_time', 'defined') | selectattr('attributes.start_time', '<', tomorrow) %}
{% set ns.cal = ns.cal + [ 'the calendar named ' ~ c.name ~ ' has an event called: ' ~ c.attributes.message ] %}
{% endfor %}
{{ ns.cal[:-1] | join(', ') ~ ' and ' ~ ns.cal[-1] if ns.cal | count > 2 else ns.cal | join(' and ') }}
So that it says "the calendar named" before each item.
Normally the data in the for loop is not available outside the loop. So that's where the namespace comes in
If I want it to say "today" at the very end of the text, do I add that after join(' and ')?
So the calendar named X has an event called: Y and the calendar named Q has an event called: P today
So only today at the end of the total message
Correct.
{{ (ns.cal[:-1] | join(', ') ~ ' and ' ~ ns.cal[-1] if ns.cal | count > 2 else ns.cal | join(' and ')) ~ ' today' if ns.cal }}
I was close. Thanks so much again!
afternoon all!
I have a question with splitting yaml configs (include_dir_merge_list) and the trigger based templated sensors.... first time Im trying to use the trigger/template/sensor ๐ฑ
Up to now when I created template based sensors I would start with:
- platform: template
but I see the trigger/template/sensor complains and the tutorials show:
template:
Is that equivalent? Any kind soul to guide me? thanks!
platform: template is used for the legacy format which falls under the sensor integration
The new format is an integration of its own
@marble jackal Ahh I see.. so I should be using the template: to include all my templates in its own section in the configuration file...
Yes
k will dig deeper.. thanks @marble jackal that was one of the step I wasnt fully in sync on... old timer, legacy habits ๐
surprise, surprise, that worked! @marble jackal thanks again
hello, I have this timestamp value from a forecast integration.
2023-03-25T11:00:00+00:00
Is there any way I could convert it to some usable data so I can display it in grafana dashboard? Cause I can't use it like this ๐ฆ
@bronze dirge I converted your message into a file since it's above 15 lines :+1:
I got UndefinedError: 'volume' is undefined
@bronze dirge That's because you are using double quotes inside and outside your template, which will cause an error
After you fix that, this code will also give errors when the media player was off, because the volume level attribute will not exist then.
So in the last step you will try to set the volume_level to none
Can you do a nested for each in automations? Meaning a for each inside of a for each? And still access the repeat.item for both?
I am trying to loop over a list of entities. Then loop over another list 4 times.
https://dpaste.org/4kM0a
Loop over target_switches then loop over switch entities and do something along the lines of this. The challenge is sensor would need to come from the first for each. Then item from the current nested for each. There is probably a better cleaner way of doing this. I'm trying to avoid creating a massive dict with those 4 switch_entities.
The end result is a number.set_value service call per switch_entity
https://dpaste.org/xQonG
This is a UI/template question, I started out asking in #frontend-archived in the hopes that this was the right place, but I don't think so, so I've come here:
I found this article: https://cyan-automation.medium.com/using-a-template-to-change-a-sensors-icon-in-home-assistant-41766a959ddf that describes how to use templating to change an icon.
I have a basic, default "Light Card" that I'd like to change the icon for under certain circumstances. Do I simply click the Show Code Editor button on the card then replace the icon: mdi:lightbulb line at the bottom with the icon_template: >- code bit from the bottom of that linked article to look at the sensors I want and the icons I want?
Is it really that simple or am I missing something entirely?
I tried that and when I have icon_template: >- in the YAML editor, I get the standard icon no matter what state the input_boolean is that I'm looking at. Also, it changes icon_template: >- to icon_template: |- when I save it and it tells me that "Key 'icon_template' is no expected or not supported by the visual editor", which I can deal with.
If I use icon: with the template there, I get no icon at all, just the text string displayed in the visual editor.
Obviously, I'm missing some important details. Can someone help me out please?
I pasted the template code into the template editor in
and it toggles exactly as I'd expect it to, so maybe it's not a template issue after all...
The link you shared describes creating a template sensor for that
Did you actually do that, as you are only sharing the code for the icon
Well, no, I didn't. Looking at it, I thought I could directly check the value of the input_boolean. Do I need to go the whole 9 yards and create the template sensor to make this work?
Do I need to edit that directly into configuration.yaml, or is there now a GUI editor that might be preferred?
OK, I see where it has to be manually edited. No problem, I can do that.
Hello guys,
could you please help me with that:
- name: "name_minuten"
state: "{{ state_attr('sensor.name', 'time') }}"```
the attribute "time" of "name" gives me back 0:30, but i need 30
i'm fine with the removal of "0:" or the calculation
And what if the current state is 2:30
2:30: yes, that could become a issue in future
under specified: what do you mean?
split(':')[1]: where do i have to put this?
Between time') and }}?
I believe I've now successfully created the template. How do I use that to change the icon in the light card in the UI?
looks good for me.
.split(':')[1] works fine.
@marble jackal and @inner mesa thank you very much!
Hereโs and example that I use in another card for dynamic icon: https://dpaste.org/ORM4Q
You need to use the template entity instead of the original entity.
So if you really want different icons for on and off you should either create a template light, or use a card which supports templates for the icon
Thanks. That is, essentially, what I'd tried. I guess the real root of the problem is that...
I need to find & use a different light card.
I guess this needs to head back to #frontend-archived since that's where my problem really seems to exist. Thanks all.
@sterile condor I converted your message into a file since it's above 15 lines :+1:
Is there any kind soul knowing how to fix that, please?
You need to surround the template in quotes
@sterile condor I converted your message into a file since it's above 15 lines :+1:
No idea why, but that hyphen is double. I used area_id: "{{ area_names }}"
how did you call the script?
Like this:
service: script.lights_toggle_previous_scene
data:
area_names:
- studio
- camera
that doesn't match with what you posted above, there you don't have camera
this is my latest try, I've got a list of area_names, so there could be any number
I'm trying to provide the whole list into the params of the light.turn_off service
so, what is the result with this latest try
Result:
params:
domain: light
service: turn_off
service_data:
transition: 3
area_id:
- - studio
- camera
target:
area_id:
- - studio
- camera
okay, it seems to put the input a new list
but I can't see why it does that. Maybe because it's past my bedtime...
If I figure it out while I'm sleeping I'll let you know in the morning
- service: light.turn_off
data:
transition: 3
target:
area_id: >
{{ area_names|list }}
this is my last try, same result as above
thanks ๐
goodnight
oh... if I use entity_id with the other list I compute, it works:
- service: light.turn_off
target:
entity_id: >
{{ entity_ids | list }}
params:
domain: light
service: turn_off
service_data:
transition: 3
entity_id:
- light.studio_1
- light.studio_2
- light.camera_1
- light.camera_2
it seems like it had to do with the area_id specifically... thanks anyway ๐
forgot to guard my template of solar forecast against now() being not availble in the dict after 19 hours (now, will be later when the season advances) , so figured I need to check whether now is in there. {% set nu = now().replace(minute=0, second=0 , microsecond=0).isoformat() %} {% set watts = state_attr('sensor.solar_forecast_estimate_watts','watts')%} {% set data = watts.items() %} {% if nu in watts %} {{ (data|selectattr('0','eq',nu)|first|default('Unknown',0))[0] }} {% else %} No production estimated {% endif %} would that be ok? COuld probably also check sun state being above_horizon, but for the sake of manipulating these KVP, what should I do ?
btw, this is what I have now {% set nu = now().replace(minute=0, second=0,microsecond=0).isoformat() %} {% set data = state_attr('sensor.solar_forecast_estimate_watts','watts').items() %} {{(data|selectattr('0','eq',nu)|first|default('Unknown',0))[1]}} and it renders a silly n, which I don't understand, other than the list being empty, phrased more correctly: UndefinedError: No first item, sequence was empty.
The n seems to be the 2nd character of Unknown
There was already a default provided in case there is no data
Ah, I see what happens
You need to put an extra pair of brackets around 'Unknown', 0
I expect petro added that as a default kvp in case nothing was reported, but now it uses only 'Unknown' as the default
The 'Unknown' part is the default for the timestamp, the 0 part is the default for the Watt value
So it does work if you do this
{{ (data | selectattr('0', 'eq', nu) | first | default(('Unknown',0)))[1] }}
BTWwhydoyoualwaysremovethespaces,itreallydecreasesreadability
how can this be... ```
{{is_state('binary_sensor.wintertijd','on')}}
{{now().timetuple().tm_isdst == 0}}
the binary has the timetuple() template as template...
Probably hours: 0 in the trigger โฆ.
If it's trigger based it will update at midnight
And last time it triggered it was not dst
Yep. Iโve moved those to the hourly trigger section now. Had forgotten about that.
this one is still having a detail issue though```
next: >
{%- set ns = namespace(previous = 3,spring=none,fall=none) %}
{%- set today = strptime(states('sensor.date'),'%Y-%m-%d').astimezone().replace(hour=ns.previous) %}
{%- for i in range(365) %}
{%- set day = (today + timedelta(days=i)).astimezone() %}
{%- if ns.previous - day.hour == -1 %}
{%- set ns.spring = today + timedelta(days=i) %}
{%- elif ns.previous - day.hour == 1 %}
{%- set ns.fall = today + timedelta(days=i) %}
{%- endif %}
{%- set ns.previous = day.hour %}
{%- endfor %}
{%- set next = [ns.spring, ns.fall]|min %}
{%- set phrase = 'verliezen een uur' if next == ns.spring else 'krijgen een uur extra' %}
{%- set clock = 'vooruit' if next == ns.spring else 'terug' %}
it still sees next as todays
where I would have wished, after the actual change it moved that to the next change of fall
wait, this fell of that paste: {"spring": "{{ns.spring.isoformat()}}", "fall": "{{ns.fall.isoformat()}}", "event": "{{next.isoformat()}}", "days_to_event":{{(next-today).days}}, "phrase": "{{phrase}}", "clock":"{{clock}}"}
next: >
{"spring": "2023-03-26T03:00:00+01:00",
"fall": "2023-10-29T03:00:00+01:00",
"event": "2023-03-26T03:00:00+01:00",
"days_to_event":0,
"phrase": "verliezen een uur",
"clock":"vooruit"}``` is the current output
Any ideas why the automation editor doesn't like the regex_findall_index but the template editor takes it? As soon as I remove that the automation editor turns blue. Put it back and it's red.. I have used this exact regex_findall_index before.
entity_id: "number.{{ (sensor.split('_presence')[:1] | join('') if 'presence' in sensor else sensor.split('_illuminance')[:1] | join('')) | regex_findall_index('\.([^\.]+)$') + '_' + item }}"
yes, the binary is solved because of the trigger. but the bigger template is still off... probably because it is following date change, where I am looking to change it to update hourly after the dst change at 3 o clock. posted in community for easy reference https://community.home-assistant.io/t/with-dst-daylight-savings-time-tomorrow-i-wrote-a-script-to-notify-me/289865/43
@floral shuttle no trigger for this one?
It will not update minutely, as it doesn't use now()
What I mean is if you enter the template in dev tools you will see what happens. Next still shows today, even after it has already happened
This partially solves it
{%- set next = [ns.spring, ns.fall] | reject('<', now()) | min %}
It will still show ns.spring as today, but it will ignore it for next
Btw, you can replace strptime(states('sensor.date'),'%Y-%m-%d') with today_at()
Thx! Will test when I get home ๐ appreciated
@sonic ember I converted your message into a file since it's above 15 lines :+1:
hours.value should be a float? and so is my input number. What am I doing wrong here?
@gleaming schooner I converted your message into a file since it's above 15 lines :+1:
Sorry for the long message.
I'm trying to add a condition like below:
condition: state
entity_id: "{{ trigger.entity_id }}"
state: "on"
within the repeat loop, but trigger.entity_id is not considerd to be valid within the condition (even though it's valid within the service
mqtt:
switch:
name: "Garage Door"
state_topic: "garage/door/status"
command_topic: "garage/door/set"
payload_on: "open"
payload_off: "close"
retain: true
icon: mdi:garage-open
value_template: "{{ is_state('switch.street_rele_l1', 'on') }}"
I have a switch switch.street_rele_l1, and I need to create a virtual switch that will remember its status. In this configuration, the switch isn't workin
How can I solve this problem?
Do you already have values for tomorrow?
Yes I do.
But I think I found the error a few seconds ago... It will work again tomorrow...
- start: '2023-03-26T03:00:00+02:00'
end: '2023-03-26T03:00:00+02:00'
value: null
It's probably just because of the missing hour today (is my guess)
I found at least one solution:
`action:
- repeat:
count: 4
sequence:
- condition: template
value_template: "{{ trigger.to_state.state == states[trigger.entity_id].state }}"
- service_template: switch.turn_{{trigger.to_state.state}}
enabled: true
target:
entity_id: "{{ trigger.entity_id }}"
- delay: 2
enabled: true`
What this does is that it only repeats if my lates configuration of the switch is the same as the loop is repeating for. This is to protect the loop from me switching on and off to fast
What are you trying to do here? Why are to turning an entity to the state it justed turned to
๐ The RF 433 is just one-way, and sometimes the device misses
And service_template is depreciated for 3 years now. You can just use service
Thanks
You can check for a numeric value
?
I was clearly not replying to you, as I'm doing a direct reply to a post of another user
Sorry. Discord is still a bit new to me ๐
How would I do that? (I'm assuming 6 months from now I'll have the same issue otherwise)
replace this even: {{today_at()}} {{strptime(states('sensor.date'),'%Y-%m-%d').astimezone()}}
{%- for hours in today if hours.values | is_number -%}
though replacing that in the temoplate changes the tz details:```
2023-03-26 00:00:00+01:00
2023-03-26 00:00:00+01:00
2023-03-26 03:00:00+01:00
2023-03-26 03:00:00+02:00```
being the output of:```
{{today_at()}}
{{strptime(states('sensor.date'),'%Y-%m-%d').astimezone()}}
{{strptime(states('sensor.date'),'%Y-%m-%d').astimezone().replace(hour=3) }}
{{today_at().replace(hour=3) }}
adding the astimezone there fixes that: {{today_at().astimezone().replace(hour=3) }}