#templates-archived
1 messages · Page 20 of 1
so instead of hardcoding it, I want to just do:
{%set number = this.attribute.thisname |replace('...','')%}
That's probably more characters than just using the name
But no, I don't know of a way to reference the name of the attribute that you're defining
it would be cool, because now I need to access the attribute before the attribute I currentl defining
but thank you anyway^^
Can anyone help me - Do you see anything wrong with this??
is_weekend_day list: {{ is_state('sensor.day_of_the_week', ['Saturday','Sunday']) }}
is_weekend_day: {{ is_state('sensor.day_of_the_week', 'Sunday') }}
Day of Week: {{ states('sensor.day_of_the_week') }}
I get False, True, 'Sunday' for these 3...
You at least need to surround the template in quotes
But yes, you've made up some syntax there
? - not following. I'm doing this in the developer test area.
If you were to actually use it elsewhere...
Your first statement is using incorrect syntax
I'm attepting to check against a list - according to this documentation - https://www.home-assistant.io/docs/configuration/templating/
is_state compares an entity’s state with a specified state or list of states and returns True or False. is_state('device_tracker.paulus', 'home') will test if the given entity is the specified state. is_state('device_tracker.paulus', ['home', 'work']) will test if the given entity is any of the states in the list.
You can't just stick a list in there
is that documentation wrong? that's what they seem to do.
Really?
I see it listed in the docs too. Interesting.
Fascinating
I mean, it doesn't WORK... but that's what I'm trying to do
I just tried it on a local sensor myself and it does work.
did you try it in the developer test? Wonder why it's not working for me.
works for me too
Yes, I tested this {{ is_state('person.me', ['home','TF']) }} and it worked. It is case sensitive though.
looks like I'm a version behind. Let me update.
never know. 😄 maybe they fixed this exact bug. haha.
Found this in the docs detail: frenck Allow is_state to accept a list of values (#25031)…
I always do: {{ states('sensor.day_of_the_week') in ['Saturday','Sunday'] }}
such a subtle difference. I wonder what the benefit of one vs the other is
Yes - I use this all of the time for lists.
lol:
emontnemery merged 3 commits into dev from is-state-in-list 11 days ago
or if it's just another case of 20 different ways to do the same thing.
Kind of yeah
What's the best approach for animation / flashing icons? Card mod?
well, we all learned something
Counting lights in a group like this
{% set ns = namespace(res=0) %}
{% for lightg in state_attr('light.all_lights', 'entity_id') %}
{% for light in state_attr(lightg, 'entity_id') if is_state(light, 'on') %}
{% set ns.res = ns.res + 1 %} {%endfor%}
{%endfor%} {{ ns.res }}
How to make sure the state is returned as number? beacuse id like to use the result for a <> evaluation
that's quite overcomplicated
{{ expand(state_attr('light.foo', 'entity_id'))|selectattr('state', 'eq', 'on')|list|length }}
Nice! This will result a number?
yes
Template is working fine, i get the number. but when evaluating the result its not working.
what?
Yep, me too! Why was this not listed in the noteworthy changes 🙂
We need a "Only for Template Geeks" section
Is this right:
action:
- if:
- condition: template
value_template: trigger.to_state.state == "on"
- condition: template
Is there a way to have a binary on off sensor to check whether I have an event with a specific name on my calendar for the current day? I have an google calendar that I am subscribed to and I want to check at the beginning of the day (before that event takes place) whether I have it or not. The name has two variations.
If you format it properly
You don't need a template for that. Just a state condition
I think the formatting is right. I guess my query is quotes, {{ etc and if I want trigger.to_state or to_state.state
It is not
Unless the state changes really often a state condition will indeed probably be fine. But there is always a chance that the state has changed again between the trigger and the the if-then
Oh I see. Don’t bother with the trigger variable, just look at the actual entity state instead
My trigger is a schedule so it doesn’t change a lot
I’m using it/else in order to call either switch.turn on or off
An you use templates in the service name ?
Yes
is this a valid template condition? value_template: "{{ media_command == 'pause'}}" obviously media_command is a variable that is set in the automation.
- variables:
media_command: "{{ tags[trigger.event.data.tag_id].media_command }}"
Yes, assuming that the variable has a valid value
I am using it in an automation as part of a choose action. I can watch the event in event monitor and the command is coming as pause so i think that means its valid. I will try to put up what I have on pastebin. Or is a thread better?
What is wrong?
Where do I begin
https://pastebin.com/vKysEM0a is part of the automation.
The problem is the condition seems to not be evaluating properly.
I guess this means something.
while parsing a block collection in "/config/packages/media/rfid_jukebox.yaml", line 47, column 9 expected <block end>, but found '?' in "/config/packages/media/rfid_jukebox.yaml", line 56, column 9
Where is tags defined?
ok ok. Don't kill me yet. It was an extra space.
I looked but sometimes yaml indents when they are a few steps in get confusing.
Its all good now.
tags are defined here:
automation:
variables:
tags:
XX-XX-XX-XX:
Not sure where this question belongs, I'm trying to set up a helper, looks to be exactly what I want ... I can't seem to figure a way to make it "sum" two values with a negative (I'm assuming there's some way to use it to do "difference" right?)
I know I can do it with a template, I just wanted to test out the helper stuff
I should clarify, I mean the "combine the state of various sensors" part
Can someone explain to me how I can put the result of this template into a template sensor? {{ state_attr('sensor.current_electricity_price_all_in', 'prices') | selectattr('from', 'gt', now()) | max(attribute='price') }}
De result of the template:{'from': datetime.datetime(2022, 12, 12, 17, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Amsterdam')), 'till': datetime.datetime(2022, 12, 12, 18, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Amsterdam')), 'price': 0.7424}I want to put the price in the template sensor.
Add ['price']
Or replace max(attribute='price') with map(attribute='price') | max
Is my question on helpers not something that people do, or is there something wrong with my question that is causing people to avoid answering?
Great. Thank you both!
Hello Community, yesterday I did wrote a little code for tracing the position of my vacuum cleaner along the home and I don´t know exactly what happened.. I think there is an issue with the templates on the recent releases (I would report it in the core bug report web) .. by steps. In the Template Editor developer I could SET two variables easily (pos_x and pos_y) and then use those to in the remaining code where I compare those coordinates with this code : '''{% set vac_y = (state_attr("camera.xiaomi_cloud_map_extractor", "vacuum_position")).y%}''' and this can´t be used in the "template sensor". So I had to create two additional sensors for the X and Y values.. of witch states("vac_x") is the above code. Till here okay.. probably.. there is any how an issue as per.. on developer template the states return a sting instead of an integer and the check / validation on the core reload passed generating an "unknown" value of the template of the second sensor (to trouble shoot this it took a while) . What I´m trying to report.. is that there is a huge validation difference between the developer and and core validation.. (of course I wold give more details).. I´m just wander if this is normal "as it should be" or somehow a bug as I suspect.. that we would need to report on the appropriate channels.
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.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.
@tropic pine share all relevant code using one of the websites above
Not only the template, but the full sensor yaml
this is the template editor code:
{% set vac_y = (state_attr("camera.xiaomi_cloud_map_extractor", "vacuum_position")).y%}
{% set vac_x = (state_attr("camera.xiaomi_cloud_map_extractor", "vacuum_position")).x%}
{% if (vac_x > 20191 and vac_x < 23043) and (vac_y > 22475 and vac_y < 24002) -%}
kitchen
{% elif (int(states("sensor.vac_x")) > 20214 and vac_x < 26082) and (vac_y > 23992 and vac_y < 27735) -%}
livingroom
{% elif (vac_x > 26204 and vac_x < 27631) and (vac_y > 22122 and vac_y < 24966) -%}
entrance
{% elif (vac_x > 23710 and vac_x < 26512) and (vac_y > 21954 and vac_y < 23876) -%}
bathroom
{% elif (vac_x > 26190 and vac_x < 30695) and (vac_y > 24474 and vac_y < 27615) -%}
bedroom
{%- endif %}
and this are the sensors (final version):
@tropic pine I converted your message into a file since it's above 15 lines :+1:
@tropic pine I converted your message into a file since it's above 15 lines :+1:
@keen holly I converted your message into a file since it's above 15 lines :+1:
im trying to put that if statement into a sensor whats the trick lol
@keen holly you are nesting templates
and you are using value_template where you should use state
I assume you don't want to have "state: " in the actual state?
- sensor:
- name: Estimated Boiler Runtime
state: >
{% if is_state_attr('climate.office', 'hvac_action', 'heating') and is_state_attr('climate.kitchen', 'hvac_action', 'heating') and is_state_attr('climate.dining_room', 'hvac_action', 'heating') %}
heating
{% else %}
idle
{% endif %}
ya im just trying to get get combined state from all of those sensors so il try that, i didn't know i could just put math after the state
that was the trick thank you so much!
ok so with it like that my if statement is going true anymore
@keen holly I converted your message into a file since it's above 15 lines :+1:
i changed my ands out for ors that was definitely wrong but its still only spitting ut the else, am i breaking any rules in my if statement?
you are back to square one, again nesting templates
and you replaced all my is_state_attr() with state_attr() == 'heating' again
i didnt even see that change lol
basically the only thing you needed to do is replace all and with or in my version
so i cant use the == alright
il hit the man pages yours worked right away
im sure there is a page on how to make if statements, but wasn't finding much for checking them against a string just all floats thank you very much
you can use ==
you can also use state_attr() == 'bla'
but it is advised to use is_state_attr() when possible
ya thats much cleaner
can you set state attributes for a template sensor? or only the main state?
Am I correct to use the template switch for turning my tado heating on and off through an input_boolean?
@solid fox I converted your message into a file since it's above 15 lines :+1:
This ^^ crashed my home assistant and can’t access it for now.
I just want to have a toggle between heating on/off but also if I use the climate card and press there off or on, the toggle should switch with it
that doesn't do what you think it does
That, and it is missing platform: template
and I don't see how it would crash HA
If it’s already in template.yaml does it still need it?
What should be my best approach for the thing I want?
And HA keeps “crashing” or at least unavailable…
define crashing
adding that will not cause a crash. It simply won't reload your template sensors. If you're restarting, HA simply won't start. I.e. No crash
a crash is when HA stops working from a working state without the user doing anything.
The “crash” I experience it trying to change something in config, checking the config and restarting but between config and checking my config it keeps loading. Refreshing browser gives me just an empty screen (no ha screen but just black) keeps trying for around 20min before being back available and still with old config
But anyway, I understand I can’t do the things I want with a template switch, if there is a solution for it, what is it?
It should not be in template.yaml, it belongs under switch
but you should just create an automation, which performs these actions triggered by a state change of that input_boolean
I have that for the state “on” so I should make another one for state “off”? But changes in my climate card do not make changes in the input boolean or should it also need 2 automations?
you can put it in one
the shortest way it to use a template 🙂
trigger:
- platform: state
entity_id: input_boolean.verwarming_winter
action:
- service: climate.set_hvac_mode
data:
entity_id: climate.woonkamer
hvac_mode: "{{ 'auto' if trigger.to_state.state == 'on' else 'off' }}"
well, this is the one to change the climate based on the input_boolean
if you want changes made to the climate entity also reflected in the input_boolean, it's easiest to create a second automation
Okay thank you! I’ll make a group first for both hvac_mode of my badkamer and woonkamer so I can toggle the group.
First gotta get that wrong config changed
you can also ditch the input_boolean completely, and do create a template switch
I have created a dashboard with mushroom and got some sort of banner with a switch called “Wintermodus”. It displays “on” or “off” and should be setting the hvac on or off. For now I have 1 automation to put in on and I use a helper for this.
switch:
- platform: template
switches:
verwarming_winter:
unique_id: template_swicht_climate_woonkamer
value_template: "{{ not is_state_attr('climate.woonkamer', 'hvac_mode', 'off') }}"
turn_on:
- service: climate.set_hvac_mode
data:
entity_id: climate.woonkamer
hvac_mode: auto
turn_off:
- service: climate.set_hvac_mode
data:
entity_id: climate.woonkamer
hvac_mode: "off"
If you use this template switch, the state will match the setting of the climate entity, and toggling it will turn set it to auto or turn it off
Okay wow that’s a great help! Thank you so much! So I keep my helper called “verwarming_winter” and just put this in my config and configure my switch in the dashboard with this
no, you don't need that helper if you use this
Even better! Thanks and sorry for bothering! Kinda lost my way in the docu
this will create switch.verwarming_winter which you can use to toggle the climate entity
Thanks a lot!
so... I hammered google for a bit but now I'm here... I have an mqtt topic that is an array of warnings warnings = ["Cannot Ping e1.31 Channel Data Target 10.0.0.52","FPP Scheduler is disabled"] - I'm trying to set up a value template to be "on" or "true" if the array contains FPP Scheduler is disabled is that something I can do in a value_templaet?
just noticed today.... that y startup script/notification doesnt pronounce the -. in the current temp that is.....```
sequence:
- variables:
temp: >
{{states('sensor.temp_current')}}
- service: script.intercom_message
data:
message_en: >
Good {{states('sensor.part_of_day')}}, Home Assistant is back up and running since
{{now().strftime('%A %d %B %X')}} and it is {{temp}} degrees.
message_nl: >
Goede{{states('sensor.dag_deel')}}, Home Assistant is weer actief sinds
{{states('sensor.dag')}} {{now().strftime('%-d')}} {{states('sensor.maand')}} en buiten is het
{{temp}} graden.
should I fix that in the template somehow? it would say: Maandag 12 December en buiten is het -1.4 graden.
{% set warnings = ["Cannot Ping e1.31 Channel Data Target 10.0.0.52","FPP Scheduler is disabled"] %}
{{ warnings | select('search', 'FPP Scheduler is disabled') | list | count > 0 }}
or, if the item is always exactly that string:
{% set warnings = ["Cannot Ping e1.31 Channel Data Target 10.0.0.52","FPP Scheduler is disabled"] %}
{{ 'FPP Scheduler is disabled' in warnings }}
Thank you!
I'd started down the path of writing for loops 😄
I've seen this before, not sure if it was here.
What you can do:
message_en: >
Good {{states('sensor.part_of_day')}}, Home Assistant is back up and running since
{{now().strftime('%A %d %B %X')}} and it is {{ 'minus ' if temp < 0 }}{{ temp | abs }} degrees.
message_nl: >
Goede{{states('sensor.dag_deel')}}, Home Assistant is weer actief sinds
{{states('sensor.dag')}} {{now().strftime('%-d')}} {{states('sensor.maand')}} en buiten is het
{{ 'min ' if temp < 0 }}{{ temp | abs}} graden.
yep, will do, thx. its just that I was surprised to hear GA almost pause on the minus sign. (was the first freezing restart since a long time.....)
just try this
Guess it freezes on the minus sign 🥁
haha yes, and when I change that to +5 it does say Plus 5
hmm, so it does the the +.. strange
@mental violet I converted your message into a file since it's above 15 lines :+1:
hi, I need a template, that gets 3 lists 'previous_list' and 'should_be_in_list and 'should_not_be_in_list and does the following
if an element is in the should_be_in_list and NOT in previous_list, than add that element to previous_list
if an element is in the should_not_be_in_list and IN previous_list, than delete only that element from the previous_list
otherwise do nothing
I have this code, but it doesnt quite work, when something in the lists changes things get messy.
For convinience you can just put my code into template test area.
@mental violet I converted your message into a file since it's above 15 lines :+1:
What am I doing wrong here?
{{ cal_events.attributes.start_time | timestamp_custom('%Y:%m.%d') }}
I'm trying to set a variable in the action part of an automation using data from the trigger and its not evaluating. how can I test it? I tested in dev tools using the actual device_id not from the trigger and it seems ok.
output without filter is: 2022-12-13 12:30:00
heres what I tried:
action:
- variables:
media_player_entity_id: >-
{% for entity in expand(device_entities(trigger.event.data.device_id))|map(attribute='entity_id')|list %}
{% if is_state_attr(entity, 'friendly_name', 'Media Players') %}
"{{ states(entity) }}"
{% endif %}
{% endfor %}
try to add in as_timestamp
{{ cal_events.attributes.start_time | as_timestamp | timestamp_custom('%Y:%m.%d') }}
you should remove the quotes around "{{ states(entity} }}", and otherwise expand on what "its not evaluating" means
further, you need some sort of default to avoid that whole thing evaluating to nothing and blowing up
Thanks a lot, this works. I was struggling so long lol. Is there a good source for these kind of things or ( https://www.home-assistant.io/docs/configuration/templating/ )?
@inner mesa do you have any help?
no
ok. it was the "... I didn't expand on the not evaluating because it just didn't work. Now it does. I will look into how to do the default for the variable. Hopefully I won't need to come back for that 😉
I tried to come up with something for default:
{% set id = "default" %}
{%- for entity in expand(device_entities("ba27048b2237478aadb9d0af5b630328"))|map(attribute='entity_id')|list -%}
{%- if is_state_attr(entity, 'friendly_name', 'Media Players') -%}
{% set id = states(entity) %}
{{id}} = id <--- for testing only
{%- endif -%}
{% endfor %}
{{id}} <-- what we are looking at
but its not working. this is what i got:
media_player.squeezeplay = id <--- for testing only
default <-- what we are looking at
you need to use a namespace if you're going to be setting a variable within a for loop
the whole thing seems overly complicated, though
you're trying to get the state of the entity that has "Media Players" as its friendly_name?
like, this: expand(device_entities("ba27048b2237478aadb9d0af5b630328"))|map(attribute='entity_id')|list is exactly the same as device_entities("ba27048b2237478aadb9d0af5b630328"), right?
{{ expand(device_entities("ba27048b2237478aadb9d0af5b630328"))|selectattr('attributes.friendly_name', 'eq', 'Media Players')|map(attribute='state')|list|default(['Nothing'], True)|first }}
{{ (should_be_in_list + previous_list | reject('in', should_not_be_in_list) | list) | unique | list }}
Result: ['test1', 'test2', 'test6', 'test5']
Check the pinned posts here
Hate to repost, my question yesterday seems to have gotten lost in the scrolling, but can anyone tell me how to make the helper "sum" take one number from another?
what do you mean
create helper -> combine the state of several sensors -> sum -> ... I want to take one room temperature from another, but I can't figure how to get a negative sign in there
....is this in the GUI?
yes
I can add the two temperatures together just fine. I just can't subtract one from the other no matter what I try.
...ok - can you show me what expression you have?
...oh
yeah i don't think you can do that - i think you need to create a template sensor
i could be wrong though
That combine helper would be really useful with a "difference" function if "sum" can't do it. I tried adding 'negatives' to the entities, but it doesn't seem to recognize the entity then
I know I can do it with a template, was trying to use the "new this version" feature that seemed like it was just the thing
I haven't yet figured out what language the template stuff is written in etc, hence attmepting to avoid it. I'm new to HA
Thanks for the help @tired sandal
Ahh, thanks! I would never have found that without the pointer
can I set the state of an input_number in a template?
no, templates only get
I don't think so..? I am really using device_entities(trigger.event.data.device_id) not the actual deviceid. I want to return the entity_id that has friendly name of 'Media Players' but that belongs to the trigger.event.data.device_id I am basically using an rfid reader to control mediaplayers and which player should be controlled is based on the device that read the card, like the example in the blog at https://www.home-assistant.io/blog/2020/09/15/home-assistant-tags/ , with the difference that instead of a static device based on the scanner there is a select component to decide the entity_id. I couldn't figure out a less complicated way but I am deefinitely interested if there is. And I am not too good at this to really be able to tell if I can do it easier.
Thanks.
They are the same
you probably don't need to expand that now
it returns state objects?
{{ device_entities(trigger.event.data.device_id) | select('is_state_attr', 'friendly_name', 'Media Players') | map('states') | list ...
look at you, using the new features
I didn't add them for my health!
I thought it would be shorter, but then I forgot it was is_state_attr
YMMV
👍
Hey friends! New to HA, and I'm hoping for some help. Hoping it's an easy one. I can't get my input_number to be a box instead of slider. Looked here https://www.home-assistant.io/integrations/input_number/, but I have my default_config set and don't want to mess that up.
i replied in #frontend-archived
@thorn torrent I converted your message into a file since it's above 15 lines :+1:
nevermind, forgot quotes around my template 🤦
i have this template https://hastebin.com/ihacetuqeq.php could someone have a quick look and tell me what im doing wrong here? I want to take all the valve positions and take an average. but only take the value if its available. the error states: TemplateSyntaxError: Encountered unknown tag 'gemiddeld'. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.
i guess within an if i cant use {% , %} but how is it done the right way? {{ , }} obviously dont work either
You can use {% within an if
then im doing something else wrong but i dont know what
yes, you are not using set
for example on lines 9 and 10 you need to use {% set gemiddeld = gemiddeld...
you are now using {% gemiddeld = gemiddeld
{% if (states('number.badkamer_thermostaatkraan_valve_control')|float != 'unavailable') %} you should also remove the float filter here
with it the template will run in error if it is actually unavailable
Or use
{% if states('number.badkamer_thermostaatkraan_valve_control') | is_number %}
Thanks allot! it works like a charm now
didnt know i had to use set every time i thought i only needed it to start a variable
I tried this a few times but I notice some issues and can’t figure out what’s the problem. The switch that it creates keeps turning on. It works when pressing but after some seconds. The switch goes back on (without setting the hvac to auto)
Also an issue that I will figure out is why I won’t work with a simple mushroom button
For the state of the switch it checks if the hvac_mode of the entity is not off. So if the hvac_action is off, the switch will off as well, if the hvac_action is anything else, the switch will be on
So if the action to set the hvac_action to auto is not performed, the switch will indeed toggle back to off
Can I post a video somewhere?
It seems the problem is the service call defined under turn_on. I don't have any climate entities, so I can not test this myself
Can maybe also a problem with my tado
You don't need to post a video, I understand what is happening and just explained you why it is happening
The code should be working so I’ll try and figure out what is wrong with it internally and if it’s my tado. Cause can I input multiple services (also climate.badkamer)?
what happens if you try this in developer tools > services
service: climate.set_hvac_mode
data:
entity_id: climate.woonkamer
hvac_mode: auto
I get: alle beschikbare parameters: hvac_mode
New value of operation mode
Tado/hvac is unresponsive
Oh yeah it’s working just very slowly
Okay no, corrction: it’s working!
Both off and auto
(Also heat) but i don’t use that
but it will toggle back first
then when the entity is updated it will go to the correct state
Okay, so the toggle will switch back to on and after a while goes back to off
yes, as soon as the service call is processed and visible on the climate entity
I see the climate entity switch immediately on my climate card but switch keeps toggling on. Should I put a delay on it? For it to process correctly?
Maybe the service switches a little bit late causing my switch so notice the not is_state_attr to not have changed states
I have the same issues with my switched for turning my tv and pc on. Home assistant updates the states to fast so i turn a swith on the pc turns on but because the pc hasnt yet confirmed its on to ha the switch goes back to off. when i wait until the pc updates its state to ha the switch is turned back on automatically.
^
You can't put a delay on that state template
but if the climate card updates immediately, something is updated immediately
probably the state of the entity, instead of the hvac mode
Imo, HA should make a function (without hassle or yaml) to connect some entities to a switch.
On = …
Off = …
If you have a feature request for the frontend you can open one here, for Home Assistant itself please post on the forum. All other feature requests should be made to the developer of that custom card/component.
Yes indeed. Hvac mode is possible since tado updates late
And also TheFes can I connect both climate.woonkamer and climate.badkamer in the same switch?
Or should I make a group?
you can just add more entities to the service calls
service: climate.set_hvac_mode
data:
entity_id:
- climate.woonkamer
- climate.badkamer
- climate.zolder
hvac_mode: auto
Wouldnt it be easier to just make an input boolean which runs some scripts when its turned on and off?
Yes, that’s what I meant. If you choose the input boolean, you can select one or multiple on/off states/services/scripts
you can add a whole array of actions to the turn_on section
basically the template switch is the same as an input_boolean and an automation
but then combined in one entity
I know but for beginners it’s easier if you can configure 1 input boolean in simplified modus. But that’s off topic. I’ll adjust the data and see if that helps with the switch
if you open one screen with developer tools > states
then search for the entity in the table (climate.woonkamer)
and issue the service call to turn it to auto or off
(on a separate screen, or on your phone)
do you see something changing immediately?
The change happens immediately. And I timed it and the switch turns back on after 3seconds
what exactly changes immediately?
probably not the hvac_mode
so what does change
the state itself?
My climate card has multiple sensors: the hvac mode (auto, heat, off), geolocation mode (home, away) and temp sensor. I can see the hvac mode chance from auto to off when I press the button in dev tools > services
I'd wager that your value_template isn't set up properly
as that's what determines the state in the UI
so the attribute hvac_mode changes immediately when you press the button?
Yes, correct
value_template: "{{ not is_state_attr('climate.woonkamer', 'hvac_mode', 'off') }}"
^
if the attribute changes immediately, that template should change immediately as well.. unless there is something I'm missing here
if you put that template in developer tools > templates, and then change the hvac mode using the service call, does it update then?
i think the correct question here would be. does it change multiple times in a short time
I lost you there sorry
put this {{ not is_state_attr('climate.woonkamer', 'hvac_mode', 'off') }} in devtools > templates and watch the result when you change this hvac
the button should never switch back as long as the state of the attribute isnt changing
its not like off is Off or something right? i have an AC that has some strange attributes with different ways of writing
yes, what is the state of the hvac_mode attribute when it is set to off
and this is case sensitive
The hvac turns to auto and off just the switch reacts weirdly
so, again, what is the state of this attribute (hvac_mode) when you've set it to off
please copy paste it from developer tools > states
or post a screenshot using imgur
its should look something like this: https://photos.app.goo.gl/VfPuViSVHex1Nmzs7
It’s ‘off’
uhm.. there is no hvac_mode attribute in your screenshot @grim flicker
WHAT is off? The state of the climate entity itself, or the attribute?
hvac_modes:
- ‘off’
- auto
- heat
I don't have a climate entity, you need to provide me the information I need
But it’s not hvac modes 🤔
that's not what I need, that is a list of the possible hvac_modes, not the one currently set
Ah
so again, WHAT is changing when you set the hvac_mode
what does that show when you set the hvac_mode to off?
i think the hvac modes as in my screenshot is also always the state of the climate
so it can only be one in that list
It changes to ‘off’
the hvac_action changes to off?
Yes
And I think what’s happening is that my tado can be in auto mode also be ‘heating’
Then use:
value_template: "{{ not is_state_attr('climate.woonkamer', 'hvac_action, 'off') }}"
for the switch
i dont follow this. when you change hvac mode the climate state will change according to the choosen hvac mode. the hvac state is always the hvac_modes chosen attribute.
I’ve changed it and rebooting now
no need to reboot
just go to developer tools > yaml and reload template entities (sjabloonentiteiten if you have your language set to Dutch)
Well, I don't have a climate entity, and I'm asking what is changing when he sets the hvac_mode. Just following what I'm being told here 🙂
if you have switch: configured in your configuration.yaml i dont think you can reload a switch like that
yes you can, everyting under the template integration or using platform: template is a template entity, and will be reloaded when you reload template entities
good to know 🙂
Indeed good to know!
It’s working! 🎉 1 final question I have mushroom with a template card. I use it to replace the switch with the following code: {{ (states(‘switch.wintermodus_2’))}}
But that won’t work
place the yaml code of the entire card here
Please use a code share site to share code or logs, for example:
- http://pastie.org/ (select YAML for the language)
- https://dpaste.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.
Sadly we're not mind readers (any more anyway, not after the last time we tried). Please share the YAML and any errors so we can see what you've done.
grr
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
@solid fox I converted your message into a file since it's above 15 lines :+1:
Sorry! My bad
Always on and not being able to interact
entity: input_boolean.verwarming_winter
you defined that as entity so you are toggling that entity
- type: custom:mushroom-template-card
primary: Winter
secondary: '{{ states(entity) }}'
icon: mdi:snowflake
layout: vertical
icon_color: blue
multiline_secondary: false
entity: switch.wintermodus_2
fill_container: true
tap_action:
action: toggle
hold_action:
action: none
double_tap_action:
action: none
You can refer to the entity you defined there using the variable entity
I misread that
secondary: '{{ states(entity) }}'
It’s fixed
Thank you! My bad just read over it
Was always thinking to just changing the secondary but yep my bad
You’re a life saver @marble jackal thank you for helping!
If coding is not your knowledge it’s great to have some help!
hey, I'm trying to make my smart coffee machine into a template that i can control on the dashboard, with the amount of cups i can set, and such like
Okay, sounds fun!
Any idea how I would get it to display a gauge and suchlike?
displaying cards is something for #frontend-archived
a template entity can just provide data
Ah ok
I need a bit Help, to invert my Shutter
@thorny bolt I converted your message into a file since it's above 15 lines :+1:
This Template ist working, but i need to invert the states Open/Closed/opening/closing too
I hate to have my Shutter at 100% when Open and 0% when closed
why you don't wire the shelly/whatever inverted?
I use an HomeMatic BROLL with RaspberryMatic
When i invert it on the Hardware Side, the Buttons in the Switch are also inverted, and thats what infont want
Hey, i am trying to create template sensors to format data obtained by the nextcloud integration. I have the issue that those values show as XYZ GB GB for the first sensor and XYZ GB MB for the latter one. Any idea what could be wrong?
template:
- sensor:
- name: "NextCloud Free Space (GB)"
unit_of_measurement: "GB"
state: >-
{{ (states('sensor.nextcloud_system_freespace') | filesizeformat(GB)) }}
- name: "NextCloud PHP Upload Max Filesize (MB)"
unit_of_measurement: "MB"
state: >-
{{ (states('sensor.nextcloud_server_php_upload_max_filesize') | filesizeformat(MB)) }}
What's the state of these source sensors?
You mean the last reported value, right? It is 917442527232 for the first and 10737418240 for the latter one without any unit after the value
well, if I try {{ '10737418240' | filesizeformat(MB) }} in developer tools > template, I get UndefinedError: 'MB' is undefined
same with GB btw
Idk, i copied it from the forums and used MB as it seems it is defined. It also does work but it has the double unit suffix
it only accepts true or false and based on that is shows MB or MiB
the unit it shows is based on the input
That is the exaple i based it on:
https://community.home-assistant.io/t/unit-conversion-b-to-gb/334244/2
So unit_of_measurement is actually the input unit?
unit of measurement doesn't make sense here, your ouput is a string, not a number
not sure what that link has to do with it though
It is where i copied the yaml from.
there is nothing regarding to filesizeformat() in that topic
I sent the wrong link 😅 I have now updated it
Well, it's not a good post
if you want the MB just divide your source sensor with1000000
if you want MiB divide it with 1048576
Ohh i think i understand it now ^^
the filter you are using now will output a string, already including the unit of measurement
and based on how high your input is, it will return kB, MB, GB, TB etc
of KiB, MiB, GiB, TiB
This is working now 🙂 I assumed i have to tell it what the input value is (bits, byte, kb, kib, etc.) and also what the format target is. It is actually just assuming Bytes and as you said the function parameter only toggles Bi notation
template:
- sensor:
- name: "NextCloud Free Space"
state: >-
{{ (states('sensor.nextcloud_system_freespace') | filesizeformat(true)) }}
- name: "NextCloud PHP Upload Max Filesize"
state: >-
{{ (states('sensor.nextcloud_server_php_upload_max_filesize') | filesizeformat(true)) }}
yes, but these sensors will now not be usable to create graphs
you can use them on your dashboard though
Yeah that was the main goal. I got to see when i have to bump the storage share plan as all my NC users have unlimited quota.
But what would i have to do to also make them work on graphs? Is this a simple addition or would i need a completely different setup?
Got to admit i am still at the very beginning with HA.
well, then you need to do something like
template:
- sensor:
- name: "NextCloud Free Space"
unit_of_measurement: "GiB"
state: >-
{{ (states('sensor.nextcloud_system_freespace') | float(0) / 1024**3) | round(2) }}
but if your free space becomes less than 50 MiB, it will show 0 GiB as the unit will not change
Ahh so graphs will only work with numeric values?
Seems familiar coming from prometheus 😅
presumably, with a |float in there
Is there a documentation on what casts do exist?
it's a filter, not a cast. And the docs are in the topic
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
Merci, i will have my fun with that 🙂
whoops
Is there a way of knowing what event the zone trigger was triggered by
I would like to make one automation and one notify message setup, only to differentiate the message related to event: leave or enter resulting in two different messages related to enter or leave
message: "{{ trigger.to_state.name }} arrived ZONE at {{now().strftime('%H:%M') }}"
State as in the zone or not?
The state of a person is the zone they're in. Or not_home
I was looking for a way of notifying when entering/leaving this particular zone, as trigging a notify for every zone I have defined is not what I want. You have an example of using
The state of a person is in the zone they're in. Or not_home
It's just a state trigger
states(trigger.entity_id) will return the zone of the person entity triggering this automation
assuming you are using a state trigger on person entities
oh wait just use trigger.to_state.state
There no magic here, just entities and states
🪄
Sure. I can use this, but maybe you guys had som magic to spread on this huge code 🙂
message: >
{% if (trigger.event) == 'leave' %}
{{ trigger.to_state.name }} left {{ trigger.zone.attributes.friendly_name }} kl. {{now().strftime('%H:%M')}}
{% else %}
{{ trigger.to_state.name }} entered {{ trigger.zone.attributes.friendly_name }} kl. {{now().strftime('%H:%M')}}
{% endif %}
at least it might be less repetitive to do something like {{ trigger.to_state.name }} {% if ... %}left{% else %}entered{% endif %} kl.{{etc.}}
but yeah, that doesn't seem bad to me either
I´m using this:
- platform: zone
entity_id:
- person.pal
- person.eva
zone: zone.nordre_krakeroy
event: leave
I would personally use a state trigger
how?
- platform: state
entity_id:
- person.pal
- person.eva
from: "Name of zone"
...a state trigger on the person
I assume you also have a trigger for entering then
without the from you can use it for all zone changes
I sure have an enter trigger in my setup now
well, with from: ~
was hoping to make to code slimmer some how.
Ah, magical coding
Hi, I'm looking for a way to test if an entity belongs to a group. I don't see any in_group attribute or equivalent in the state of my light entities. Thanks.
I think I used something like is_group long time ago but can't make it working.
trigger:
- platform: state
entity_id:
- person.pal
- person.eva
to: ~
variables:
person: "{{ trigger.to_state.name }}"
action: "{{ 'left' if trigger.to_state.state == 'not_home' else 'entered' }}"
zone: "{{ trigger.from_state.state if action == 'left' else trigger.to_state.state }}"
Hey! Thank you, @marble jackal
then you can build your message like {{ person}} {{ action }} {{ zone }} kl. {{now().strftime('%H:%M')}}
So the to: ~ will trigger both ways?
yes, without it it will also trigger on attribute changes
like small updates of coordinates, without you actually changing a zone
I need to have the automation not trigger for all zones, just this single zone, as I have too many zones defined to want me to have it trigger on every enter/leave 🙂
then why bother with templating the zone name?
To have one string both for enter and leave
but it is the same zone, but in one line you are entering it, in the other leaving it
still the same zone every time
what kind of group?
light group
Actually I would like to count number of on lights, without counting the individual bulbs that belong to a light group (which is already counted)
you can get a list of all entities which are in light groups with
{{ states.light | selectattr('attributes.entity_id', 'defined') | map(attribute='attributes.entity_id') | sum(start=[]) | unique | list }}
Then use that to reject them from the list of on lights, right?
yes
Thanks a lot
lights in the lights_in_groups list continue to appear in ns
Is it possible to generate the nice "In X hours" from a datetime string in template? I am using template-entity-row from HACS (I wanted to make it show other things depend on state while still showing the original entity's panel when clicked, so a template sensor won't work) which doesn't support format parameter. I tried relative_time(as_local(as_datetime(states("sensor.octoprint_estimated_finish_time")))) but seems like it doesn't work.
Ask chat gpt for help. Works 8/10 times if you ask the right questions
then ask it to fix it if it's wrong
Is there a way to set multiple inline variables based on a input templated variable?
I'm not sure what you're looking for
So I have a light template, for my coffee machine, and I need to get it so I can set the number of cups using a script
you'll need to break that down a bit more. What exactly are you setting?
a light template (template light?) wouldn't obviously have anything to do with an espresso machine or setting a number of cups
Well, i figured it's the only thing that has a gauge that somewhat makes sense for that purpose
It has a coffee machine icon so my partner knows its for a coffee machine, but it's easier then a light
It sounds like you're talking about a card on your dashboard, not a template
The template being the math?
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
That
On the developer console my math works, but when I put it in a script, it doesn't
Sadly we're not mind readers (any more anyway, not after the last time we tried). Please share the YAML and any errors so we can see what you've done.
this might be a long shot, but I need some serious help here... trying to figure out the optimal inside temp to prevent Mold. We have the Mold indicator integration, https://github.com/home-assistant/core/blob/dev/homeassistant/components/mold_indicator/sensor.py but that returns a percentage. Could we somehow template the ideal temp out of that given the current given humidity inside and outside temp?
the integrtion provides attributes for Dewpoint and Estimated critical temp, but as far as I can see, this is not what I am looking for. What I want is a sensor calculating the required inside temp to get the mold indicator show no mold will happen (not sure what percentage that would be really), so I guess below 50%?
Hmm...if you can find a regression equation that relates mould growth to humidity and temp, you could plug in the values and math it out.
Eg. mould growth rate = c + a * temp + b * humidity + ...
If you have a target growth rate, you plug in the numbers and work out the value of temp.
yeah, I am not sure that is even possible (a lot of documents online simply state you need to ventilate, or not have your home cool down.....) but was hoping to find the calculation required for that inside this integration. I cant even find the mentioned MAGNUS_K2/3 values documented anywhere
If I get
Invalid config for [template]: not a valid value for dictionary value @ data['event']. Got None. (See ?, line ?).
is it wanted behavior to get only ? and not any further helping information? I found the root cause manually, but wonder, why no further information are provided.
And would it be possible to include this in config check as it gave no errors where studio code server showed the problem.
It was a wrong (copy&paste problem) event-value in platform: homeassistant`
@ornate storm I converted your message into a file since it's above 15 lines :+1:
What are you asking here? Event is only for an event trigger IIRC
So if you're asking about the error, that's a generic error produced from the configuration loading that comes from voluptuous (the library that validates our yaml). There's only so much information we can get from the raised exception. So that error is saying that it expects items inside event
so the homeassistant trigger requires the event key. When it's not provided, voluptuous populates that key with None and raises the error.
Both of these will return the same error
- platform: homeassistant
- platform: homeassistant
event:
- platform: homeassistant
event: None
well, all 3 of those...
trigger-template
yeah, ignore my first comment, read the rest
basically, we cant get more information from the voluptuous library as it truncates everything, and when things are included it loses the placement in the file and what file it's reading from.
@ornate storm you can use this.state to get the previous state. Keep in mind that a restart wipes that out so you have to have a backup if this is not defined.
{{ this.state if this is defined else 22 }}
Also, you have to use that syntax, you cannot use iif
because of the order of operation that needs to occur
A trigger based template sensor restores it, bit you will still lose it if it's already triggered before the state is restored
Did so. Understood. Here it was a value, but not a supported one. So not blank nor None. And vsc shows the root-cause of course (wrong, not supported value), so I hoped, that the parser can/will check such things (eventually) as well.
So
for conditions in trigger based sensors to avoid that
VSCode uses the schema IIRC or they have a completely separate schema built into itself
so, it's not a 1-1 case
I know that HA and the VSCode addon get out of sync on a regular basis
so it's definitely using something else
The difference is that it also doesn't combine things into 1 large config object, which is ultimately the problem for voluptuous as that wipes out the file, line, & column numbers
True. Was only a wish to get more help, as I only found the problem by chance with the help of vsc. Without line number or more error text, I would have been hard. But ok. It is as it is. Understood. Thx for the explanations.
I think the only way we could solve that is if we rewrite the config parser to not include things and treat each section as it's own file. Or override the thing competely
IIRC it combines things prior to checking the schema
I'd have to go through the code again
I'm looking to get the HH and the MM value from an input_select which has several time options, such as 07:45. I want to input this in a input_datetime, and suppose I have to strip the 07 and set is as hour and 45 as minute in the input_datetime. I already have an automation set up that does this, but how can I extract those values from the input_select?
today_at('{{ states(input_select.alarm_hours) | int(07) }}:{{ states(input_select.alarm_minutes) | int(30) }}')
Or similar
The whole action would probably be something like this:
action:
- service: input_datetime.set_datetime
data:
datetime: "today_at('{{ states(input_select.alarm_hours) | int(07) }}:{{ states(input_select.alarm_minutes) | int(30) }}')"
target:
entity_id: input_datetime.alarm_clock
Though you may want to just use a time datetime
Thank you, I will try to get this to work. To be able to understand this better in the future, I'm trying to understand what it does. Could you please help me with that? I understand the following:
This action calls the service set_datetime from input_datetime. That data it uses is what follows. That's where I don't really understand anymore. What is today_at used for, and what do int(07) and int (30) do? Looking at the documentation it seems that this influences the base, or is that incorrect?
It then sends this to the alarm_clock entity.
So | int parses the input to an integer, and the (07) or 30 are "sensible defaults" in case there isn't a number there to read
today_at() is a template function, so the whole thing needs to be in curly brackets
datetime: "{{ today_at(states('input_select.alarm_hours')~':'~states('input_select.alarm_minutes'))}}"
As you are creating a string anyway, there is no need for an int filter
Though if you had an empty option you wouldn't want that in there, it would cause weird problems
If the input select only has sensible options there is no need for a default
Indeed
Thanks a lot! How would I be able to test this in the Template dev tools? I assume this is because i am not specifying from which entity to read this data from, how do I do that?
just paste that into the template dev tools and it'll spit out the result
If I do that, with the changes of TheFes, it gives me ValueError: could not convert str to datetime: 'unknown:unknown'
then you didn't give it the correct entity_ids
you have to have those input_selects
I only have one input_select, which is input_select.smartsleep_set, with a value of HH:MM
Sorry if I didn't explain that correctly
then it would just be {{ today_at(states('input_select.smartsleep_set')) }}
That indeed gives me the full details of the entity, but I would like to split this. The SmartSleep integration uses
number.smartsleep_alarm0_hours and
number.smartsleep_alarm0_minutes to set the alarm, so I would like to get the HH:MM from input_select.smartsleep_set and then send the HH to alarm_hours and the MM to alarm_minutes
Ah, so the other way around
Just split the string on : and index the components?
{{ today_at(states('input_select.smartsleep_set')).hour }}
that would also work
{% set hour, minute = states('input_select.smartsleep_set').split(':') | map('int') | list %}
{{ hour }}
{{ minute }}
Thanks a lot, this works! It surprises me that it "knows" that this input_select is in an hour:minute format without telling it.
Well...if you use today_at, it converts the string into a time which then has hours and minutes. If you use the string splitting, it really doesn't know that the string is a time, but it doesn't need to know so long as you can extract the info you want.
Ah, that explains, thanks!
@thorny snow I converted your message into a file since it's above 15 lines :+1:
@thorny snow you copied hours twice and you aren't setting minutes
Wow, damn, that's stupid
Thanks!
Still not working unfortunately, the trace in the automation is saying this:
expected float for dictionary value @ data['value']
What exactly are the options available in your input_select?
06:30, 07:30, 08:30 for now.
Share your latest automation yaml?
share taht full error, not paraphrased please
I'm about to go off to bed - good luck squashing this bug! But also, do consider to use an input_datetime storing a time only rather than input_select, as the former will be more flexible.
@thorny snow I converted your message into a file since it's above 15 lines :+1:
Thanks a lot for all your help. I know datetime would be a lot more flexible, but I want the time to be set by saying it to Google Assistant, and that only supports input_selects
dude
you're still using hour twice
the error should also say what it's getting
e.g. expected float for dictionary value at data[value] but got; ksjdflkja
and i'm 100% sure it's .hour not hours
Sorry - pasted the wrong YAML. Already had changed it to minutes. But the hour instead of hours indeed was the problem!
That would be clear if you paste the template in
-> Templates
I'm now trying to rebuild things a bit and send it through an input_datetime (so I can also manually change it). This YAML works in the Templates section of dev tools and shows 6:30 as a value, but gives the following error in traces:
Triggered manually at December 14, 2022, 17:03:52
Input datetime: Set SmartSleep Time
Stopped because an error was encountered at December 14, 2022, 17:03:52 (runtime: 0.01 seconds)
must contain at least one of date, time, datetime, timestamp.
service: input_datetime.set_datetime target: entity_id: input_datetime.smartsleep data: value: '{{ today_at(states(''input_select.smartsleep_set'')) }}'
The step details also provide me with a valid timestamp:
Executed: December 14, 2022, 17:03:52 Result: params: domain: input_datetime service: set_datetime service_data: value: '2022-12-14 06:30:00+01:00' entity_id: - input_datetime.smartsleep target: entity_id: - input_datetime.smartsleep running_script: false limit: 10
does input_datetime.set_datetime except value in it's data?
ahh alright - thanks!
so this would do it right?
{% if is_state('binary_sensor.livingroom_door_sensor_contact', 'on') and utcnow().timestamp() - states.binary_sensor.livingroom_door_sensor_contact.last_changed.timestamp() > 90 %}
17
{% elif is_state('binary_sensor.livingroom_presence_group', 'on') and utcnow().timestamp() - states.binary_sensor.livingroom_presence_group.last_changed.timestamp() > 270 %}
24
{% elif is_state('binary_sensor.livingroom_presence_group', 'off') and utcnow().timestamp() - states.binary_sensor.livingroom_presence_group.last_changed.timestamp() > 570 %}
19
{% else %}
{{ this.state if this is defined else 5 }}
{% endif %}
That seems to be the problem. I've changed it to time, but now it parses the whole timestamp which is not accepted
Invalid time specified: 2022-12-14 07:45:00+01:00 for dictionary value @ data['time']
*not timestamp btw, but the full date and time
ok, so if you have a full date and time, do you think it goes in datetime, date, time or timestamp?
looks good
Hahaha omg, time to take some rest. Thanks so much all!
I have this two rest sensor
- platform: rest
resource: http://klima-basement.subraum.c3pb.de/json
name: Klima Basement Temperatur
value_template: "{{ value_json.temp }}" - platform: rest
resource: http://klima-basement.subraum.c3pb.de/json
name: Klima Basement Luftfeuchtigkeit
value_template: "{{ value_json.humidity }}"
how can i combine this two into one "virtual device" with 2 entities?
In short: you can't.
Long version: if you create an MQTT device and add those entities to it (so it all has to be published via MQTT), you can. But there's not much/any gain.
Hey all, is there a way to display the last time an entity was in a specific state?
(I've outsourced most of the templating work to chatcgt, but he kept just giving me a template to show when an entity last changed)
no, but you can create a template sensor to keep track of that
or write an SQL sensor
What's the difference between a template and a template sensor?
templates are Jinja expressions. Template sensors use a template to represent their state and other components
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
Interesting thank you. I don't really use many templates, I didn't realise how deep this got
Hi, anyone that can help me create a sensor that shows total cost of a device? I have a sensor for total kWh used for the device, and i have a sensor that gives me my current $/kWh
You can multiply them them in a template sensor
{{ states('sensor.energy') | float * states ('sensor.price') | float }}
What should state_class, unit_of_measurement and device_class be set to?
state_class: measurement, unit_of_measurement: "$" (this one was obvious right) and no device_class: monetary
as my sensor.energy already have a value, the total cost of the device is incorrect, as it multiplies with the current $/kWh price. Any ideas how to fix that?
Maybe, if you can explain more clearly what the result should be then
i wanna know the electricity cost of a device
yes, per what? day, month, lifetime? That information is currently missing
Lifetime, and i wanna be able to make graphs that show the cost per hour for a day
Well, lifetime is what you have right now
if you want data per hour or day you need to create a utility meter out of the sensor
which will give you the hourly/daily/whatever consumtpion
and then create additional template sensors to multiply the price with those sensors
is there a way to make this "or" instead of "and":
{{ expand(['sensor.echo_beam_next_timer', 'sensor.echo_dot_next_timer', 'sensor.echo_show_next_timer', 'sensor.echo_spot_next_timer'])|selectattr('state', 'in', ['unavailable', 'unknown'])|list|length == 0 }}```
right now if one is unavailable or unknown it shows as false
Use rejectattr instead of selectattr and then use > 0 instead of == 0
perfect thank you 🙂
How do you get day of the week for a date time ?
you'll have to expand on your question. What entity? What attribute on the entity? And what's the result of the entity/attribute
sensor entity is waste bin colletion day. value is like "2022-12-23". i want to be able to have a card saying bin collection is today, tomorrow, saturday, sunday monday etc.
easy to filter that into a datetime but i expected to find a filter for day of the week
i guess i could use timestamp_custom
{{ states('sensor.waste_this_collection') | as_datetime | as_timestamp | timestamp_custom('%A') }}
seems to do it
{{ (states('sensor.waste_this_collection') | as_datetime).strftime('%A') }}
No need to convert it to a datetime and then to a timestamp
Hello, I try to create a new sensor to copy the value of an existing one "pluie_today" the goal will be to copy its value at 11:59 pm. my code is the following
template:
- trigger:
- platform: time_pattern
This will update every night
hours: 21
minutes: 01
sensor:
copie la valeur de précipitation du jour
- name: "pluie_hier"
state: '{{ sensor.pluie_today | float }}'
- platform: time_pattern
For the moment I'm not able to find my new sensor "pluie_hier" to display it with a gauge, do you know what is wrong ?
thank you for your help
state: '{{ states("sensor.pluie_today") | float }}'
I assume you canged the trigger to test it
You could also use a time trigger instead of time pattern
- trigger:
- platform: time
at: "21:21"
It works ! thank you TheFes !
Hi guys
need help with script.....
I want a script first testing some conditions before the run a sequence
So you want to start here probably: https://www.home-assistant.io/docs/scripts#test-a-condition
Yes I already read
but seems we can't do something like
- if:
- condition:
condition: and
conditions:
- condition: "{{ states('input_select.routeur_marche_forcee_sortie') == 'Sortie 2 (Géothermie)' }}"
- condition: "{{ states('binary_sensor.geothermie_fan_on') == 'on' }}"
- then:
sequence:```
maybe I am wrong ...
- conditions are AND by default (i.e. all must be true for the actions to run) so you don't need the
andcondition. - check your syntax for the
if_thenaction. You've got an extra-beforethen, and you don't need the- condition:underif:
all good advice, but it's also missing the initial sequence:, and it would be better to use is_state() to check the state, rather than ==
expand(integration_entities('mqtt')) | selectattr('domain', 'eq', 'sensor') | selectattr('state', 'eq', 'unavailable') as a start of your template
Managed this {{ expand(integration_entities('mqtt')) | selectattr('state', 'in', ['unavailable'])| map(attribute='name' ) | join('\n ') | default('none', True) }} but it gives me the (obviously) all of the sensors and i’m after the devices really, is there any way to only show devices that has an unavailible sensor attached to it?
{{ expand(integration_entities('mqtt')) | selectattr('state', 'in', ['unavailable']) | map(attribute='entity_id') | map('device_attr', 'name') | unique | select() | join('\n') | default('none', true) }}
@rose scroll thx
Is there a way to add variables to a dashboard configuration? For instance I have one dashboard that sums all my temperatures in mini-graph-cards of the house. All those graphs use the same hours_to_show and points_per_hour, but whenever I want to change them, I have to change each one by itself. I'd much rather define one variable on top that affects all of those.
how would I do that in yaml?
only variables are input helpers, input_number for example. you can hide the entities once you've created them so they don't appear in the UI
I have a sensor showing the timestamp of my next alarm. Id like to test if this is tomorrow. I can compare these 2```
{{states('sensor.next_alarm_timestamp')|int(default=0)|timestamp_custom('%d')}}
{{(now()+ timedelta( days = 1 )).day }}``` Is that the shortest? I do think it jumps the month/year correctly?
it will jump months/years
just realized I have to |int the last one again:```
{{ (now() + timedelta( days = 1 )).day ==
states('sensor.next_alarm_timestamp')|int(default=0)|timestamp_custom('%d')|int}}
yep, that's true
{{ states.scene | expand }} outputs a list of objects like this one <template TemplateState(<state scene.hall_bright=unknown; group_name=Hall, group_type=room, name=Bright, speed=0.6031746031746031, brightness=100.0, is_dynamic=False, friendly_name=Hall Bright @ 2022-12-15T17:46:26.918385+00:00>)>
how can i filter the list on group_name
i.e iterate all scenes in a given area
ok i think i have managed to do it, but I expect i'm about to be shown how it could be improved a lot
{{ states.scene | expand | selectattr('attributes.group_name','defined') | selectattr('attributes.group_name','==','Hall') | map(attribute='entity_id') | list}}
you don't have to use expand here
states.scene will already have the expanded state objects
sorry, I don't understand the question and end goal here
ah you can use [] to access
what i am working towards is having a button which can cycle through scenes in a room each press. mainly as a learning excercise.
without having to hard-code the list of scenes in the automation logic
so this gets the name of the entity with index=1
{{ (states.scene | selectattr('attributes.group_name','defined') | selectattr('attributes.group_name','==','Living room') | map(attribute='entity_id') | list)[1]}}
so now i can increment an input_number, roll it back to zero if it's past the scene count for a room, then get the name of the scene to activate based on the input_number value.
thanks, i will look at that. but i think working through and figuring it out yourself is very helpful for learning.
How do i get the last word of a entity value.
how would I go about implementing this? tried like this, and it wont show any graph:
entities:
- sensor.sensor_temperature
hours_to_show: {{ states('input_number.temperaturedashboard_hours_to_show') }}
points_per_hour: 2
type: custom:mini-graph-card
I confirmed the template works in dev-tools
do you mean an entity's state?
might be that that card doesn't support templates for values
oh no, so then there would be no solution for my problem. thats a bummer
Yes
{{ (states('<entity id>') | default).split(' ') | last }}
There is a hacs solution card_templater that may help...it does not always but I have a few working examples
Well, the problem with scenes is they are not on or active
so you need to use a helper for that, like an input_select or an input_boolean. But that makes it a bit tricky to have it dynamically like you want to do
i appreciate that, but for my use case that's fine. i'm happy to just activate them in a cycle. the video you link to (i've not watched it yet but i will) rightly points out that this is emulating something that hue can do.
i understand i'll need to use a helper to track the cycle state
if it supports templates, you need to put the template between quotes
hours_to_show: "{{ states('input_number.temperaturedashboard_hours_to_show') }}"
yes, but your dynamic approach makes that a bit more difficult
what yo could do is create an automation which populates an input_select with the result of your template above
and then in each scene add an action to set the input_select to the option belonging to the scene
does it though? in the script, i'd increment the input helper then check if it's >= count of entities in my template list, if so then set to 0
which input_helper do you want to use here?
@still plank I converted your message into a file since it's above 15 lines :+1:
but not with a hard coded count, instead i'd use the length of the list from above
ah okay, that could work, you don't need an if then though
don't I ?
action:
- variables:
list_lenght: 3 # user your template here
- select: input_number.set_value
target:
entity_id: input_number.test_number
data:
value: "{{ (states('input_number.test_number') | int + 1) % list_lenght }}"
and you don't need to escape your quotes in your templates, just use double quotes outside the template and single quotes inside the template
i actually did that example in the UI editor then switched to the yaml tab; it was that process that did the escaping
understand your suggestion, looks good
i do wish there were some support for static variables in automations. it seems messy to need an input helper for this, when i wold never want to use it elsewhere.
@urban shard I converted your message into a file since it's above 15 lines :+1:
@urban shard I converted your message into a file since it's above 15 lines :+1:
Jesus...
stop posting it, I can see it
I'm sorry... That just looks terrible in a 'file'
and you are not seeing an icon because you are mixing jinja with javascript
icon: >
{% if states("switch.nachtlampje_socket_1") == "on" -%}
mdi:account
{%- else -%}
mdi:account
{%- endif %}
Hmm okay okay! These kind of examples I've been seeing a lot when I'm searching for an answer online
or even better, use {% if is_state("switch.nachtlampje_socket_1", "on") -%}
that's because a lot of cards use javascript templates, but mushroom uses jinja
Oh gosh... So what would be the best solution in this case?
you can also use:
icon: "{{ 'mdi:account' if is_state('switch.nachtlampje_socket_1', 'on') else 'mid:account' }}"
the only solution (when using a Mushroom template card) is to use jinja
and I would use the last one I just posted, as it is a nice short single line template
Didnt you mean
icon: "{{ 'mdi:account' if is_state('switch.nachtlampje_socket_1', 'on') else 'mid:account' }}"
yes sorry
I usually use single quotes inside my templates, but I copy pasted what you used
No probs haha, but that also gives me no icons
this should give you mdi:account when in all cases
type: horizontal-stack
cards:
- type: custom:mushroom-entity-card
entity: switch.nachtlampje_socket_1
layout: vertical
name: Nachtlampje R
icon_color: light-blue
hold_action:
action: none
double_tap_action:
action: none
icon: "{{ 'mdi:account' if is_state('switch.nachtlampje_socket_1', 'on') else 'mdi:account' }}"
does the template work in developer tools > template?
it works for me
oh wait, you are using a mushroom-entity-card
yes I am
you can only use templates in a mushroom-template-card
type: horizontal-stack
cards:
- type: custom:mushroom-template-card
entity: switch.nachtlampje_socket_1
layout: vertical
primary: Nachtlampje R
icon_color: light-blue
hold_action:
action: none
double_tap_action:
action: none
icon: "{{ 'mdi:account' if is_state(entity, 'on') else 'mdi:account' }}"
Ah yes that fixes it all!
and in Secondary Information how will i show the entity state?
I assume you want it in Dutch?
Nope haha I like to have everything in english
type: horizontal-stack
cards:
- type: custom:mushroom-template-card
entity: switch.nachtlampje_socket_1
layout: vertical
primary: Nachtlampje R
secondary: "{{ states(entity) | title }}"
icon_color: light-blue
hold_action:
action: none
double_tap_action:
action: none
icon: "{{ 'mdi:account' if is_state(entity, 'on') else 'mdi:account' }}"
Nachtlampje doesn't look very English to me 😛
Haha that is true indeed, I'm currently revamping my whole home assistant setup. I added that a long time ago in Tuya and never changed the name.
what does the | title do? So I can understand in the future?
It changes the first character of every word to uppercase
so it will show On instead of on
Aaah okay okay makes sense!
I did take a look at your Github configuration. Looks pretty neat if I say so myself!
Thanks
Can I discuss your setup a tiny bit in this channel?
if it relates to templates 😛
Let's move to #general-archived 😄
I'm stuck. It's probably very simpel but how do I add 2 values into one? (100+100 = 200)? '{{ value_json.CIH + value_json.CIL }}' this does not work :p
Error? Otherwise... maybe they're strings?
{{ value_json.CIH | float + value_json.CIL | float }}
Hi Everyone. what would be the best way to achieve the following:
I have some RGB lights and a switch (using KNX) that has a little RGB indicator. I can send the RGB indicator a RGB value, and only accepts 0,0,0 to turn off. How can I create an automation that mirrors the colour of the light, and if the light is off, send a value of 0,0,0 to the indicator?
an if-then in your automation which sends 0,0,0 if the light is off (using a state condition) and {{ state_attr('light.your_light', 'rgb_color') | join(',') }} if it is not off
Is there any tutorial available for the basics of Jinja? The documentation starts too difficult for me, is there any way to get into that a bit easier?
This is how I got started with Jinja in HA. https://youtu.be/GnW0mLt2YLg
Thanks, will take a look at that 🙂
given a dictionary like this: {% set translations = ({"RECYCLING":"Green bin","REFUSE": "Black bin"}) %}
if i have a sensor whos value is a list of one of more of RECYCLING etc, how can i transform that into a list of the translations?
just show us the output of the sensor so we don't have to decipher what you're saying.
it's the attributes: they look like thispickup_types: REFUSE
area_name: SouthNorfolkUK
device_class: date
friendly_name: Next pickup
in this example there is just one, but it's a list
{{ state_attr('sensor.waste_this_collection', 'pickup_types') }} shows ['RECYCLING']
ok
so what do you want from that, just recycling?
does the list have more than one? If yes, do you want all of them?
i want ultimately to craft a message like, "put out the black bin, and green bin"
{% set dict1 = {'A': 'Z', 'B': 'Y', 'C':'X'} %}
{% set list1 = ['A', 'B', 'C'] %}
{% set ns = namespace(list2 = []) %}
{% for i in list1 %}
{% set ns.list2 = ns.list2 + [dict1[i]] %}
{% endfor %}
{{ ns.list2 }}
i was thinking of transformaing the values in the list
and then iterating it
but perhaps that's ass about face
and i just need to iterate the list and convert the values in the iteration
if it's just 2 then you can simply do
no it could be between 1 and 4
{{ state_attr('sensor.waste_this_collection', 'pickup_types') | join(' and ') | replace('RECYCLING', 'Green bin') | replace('REFUSE', 'Black bin') }}
if it's more than 2 then....
Unfortunately Jinja can't do something like [dict1[i] for i in list1]
{% set items = state_attr('sensor.waste_this_collection', 'pickup_types') %}
{% set phrase = items[:-1] | join(', ') ~ ', and ' ~ items[-1] if items | count > 2 else items | join(' and ') %}
{{ phrase | replace('RECYCLING', 'Green bin') | replace('REFUSE', 'Black bin') | replace('xxx', 'xxx') | replace('yyy', 'yyy') }}
you don't really need to iterate when you have a small amount of 'translations' as you call them
just write the phrase and replace the strings
you can also just regex_replace
if you're dead set on generators
or just replace
Ok, thank you
generators look like
{% set items = state_attr('sensor.waste_this_collection', 'pickup_types') %}
{% set items = items | map('replace', 'RECYCLING', 'Green bin') | map('replace', 'REFUSE', 'Black bin') | list %}
{{ items[:-1] | join(', ') ~ ', and ' ~ items[-1] if items | count > 2 else items | join(' and ') }}
ok, I have an MQTT rf433 binary_sensor, that should be on/off, but is showing true/false
how do I tell it to be on/off?
binary sensors can only be on/off, if the UI is showing True False, then change the device class. If the backend is showing true/false, it's not a binary sensor, it's a sensor and you'll have to make a template binary sensor from it.
actually, binary sensors have no translated device classes that display true/false, so you don't have a binary_sesnor, you have a sensor
Thanks petro, I see that now.
did you configure it via MQTT or is it discovered?
it was giving 1/0. configured.
show your configuration
- state_topic: "HomeAssistant/rtlsdr/event/234"
name: Replace Outside Battery
device_class: battery
object_id: binary_sensor.rf433_ob001
value_template: "{{ not(value_json.battery_ok) }}"
```
The key element is missing 😉
use
mqtt:
binary_sensor:
- state_topic: "HomeAssistant/rtlsdr/event/234"
name: Replace Outside Battery
device_class: battery
object_id: binary_sensor.rf433_ob001
value_template: "{{ not(value_json.battery_ok) }}"
payload_on: "1"
payload_off: "0"
wait
you're template is modifying things
change your template to "{{ value_json.battery_ok }}"
gewet rid of not?
then swap your payload
The object id shouldn't contain the domain right?
also, that
mqtt:
binary_sensor:
- state_topic: "HomeAssistant/rtlsdr/event/234"
name: Replace Outside Battery
device_class: battery
object_id: rf433_ob001
value_template: "{{ value_json.battery_ok }}"
payload_on: "0"
payload_off: "1"
that's assuming your value_template was correct
if you want it to be on when battery_ok is "1" for example, set payload_on to "1"
you can also just omit the payloads and make your template...
mqtt:
binary_sensor:
- state_topic: "HomeAssistant/rtlsdr/event/234"
name: Replace Outside Battery
device_class: battery
object_id: rf433_ob001
value_template: "{{ "OFF" if value_json.battery_ok else "ON" }}"
mind blown. thats so easy
Invalid config for [mqtt]: [payload_on] is an invalid option for [mqtt]. Check: mqtt->mqtt->sensor->2->payload_on. (See /config/configuration.yaml, line 29).
mqtt:
sensor: !include 433mhz.yaml
line 29/30
it's not a sensor 😉
yep
it needs to be in a separate mqtt section
mqtt:
sensor: ...
binary_sensor:
- state_topic: "HomeAssistant/rtlsdr/event/234"
name: Replace Outside Battery
device_class: battery
object_id: rf433_ob001
value_template: "{{ "OFF" if value_json.battery_ok else "ON" }}"
np
I'm trying to display light % in lovelace. What am I doing wrong? In Secondary Info {{ states_attr('light.gus_light', 'brightness') }} works, but {{ states_attr('light.gus_light', 'brightness_pct') }} does not
And so why wouldn't it have it? It seems you can reference brightness_pct as per some of the documentation
like why would it have the attribute brightness but not brightness_pct?
take your brightness * 100 / 255 to get brightness %
Look on your entity, I think you’re confusing attributes with service call parameters
Developer tools -> states page will show you the attributes that exist on your light.
Make sure to turn it on first, it will not show much if it's off
Hi all, is there a reason why the template cover doesn't have a "stopped" status? It can only be Closed or Open, but what if it is stopped in the middle? This makes it unusable because the Open status only allows to close it and the Closed status only allows to open. If it is stopped in the middle both command should be available. Is any improvement planned on this?
Hmm my blinds report % closed/open, @vernal juniper
Can you share the yaml code please?
service: cover.open_cover
target:
entity_id: cover.all_covers
Or
service: cover.close_cover
target:
entity_id: cover.all_covers
Good morning, I created a template in which I'd like to add up all sensor values but I do not know how to convert each sensor value from 'str' to 'int': {{ states.sensor | selectattr('entity_id', 'search', 'adults') | map(attribute='state') | sum() }}
This is my current list: ['2', '2', '2', '0', '0', '2', '2', '1', '2', '2', '0', '0', '2', '0', '2', '0', '0', '0', '2', '2', '0', '1', '2', '2', '2', '0'] sum() of course does not work on strings.
|map('float')
And it works! Thanks a million!
Hello. Following the example on the tado integration page, I would like to make an automation that changes my tado temp sensor's value depending on an extermal temp sensor. The action part, which I need to use the yaml editor for instead of UI editor, gives me this error: Message malformed: template value should be a string for dictionary value @ data['action'][0]['data']
Here the snippet of code:
- service: tado.set_climate_temperature_offset
target:
entity_id: climate.wohnzimmer
data:
offset: >
{% set tado_temp = states('sensor.thermostat_wohnzimmer_hk_current_temperature')|float(20) %}
{% set room_temp = states('sensor.wohnzimmer_temperature')|float(20) %
{% set current_offset = state_attr('climate.wohnzimmer', 'offset_celsius') %}
{{ (-(tado_temp - room_temp) + current_offset)|round(1) }}```
I read that a while back the UI yaml editor was the problem. Not sure if this is fixed, is my code faulty or is it a bug?
The second example on the bottom of this page: https://www.home-assistant.io/integrations/tado/#service-tadoset_climate_temperature_offset
Heya! So I got this code:
https://paste.debian.net/1264366/
But I would like to change the values inside that code via input number. Is that possible?
Can I somehow replace the "3" after "numberOfSequentialHours" to
"states('input_number.elprisverktyg_antal_timmar')" so I can change it on the go not needing to change the code if I want to try another set of hours?
I copied some templates from a community thread but I think I'm missing something when I split the config into template.yaml. Can someone help me fix it?
This is my entire current template.yaml: http://pastie.org/p/5JO04FrwXZHryAcjQheahP
And this is the errors I'm getting in the log, which seems clearly pointing at the "platform" lines. Just not sure how to fix it.
Invalid config for [template]: [platform] is an invalid option for [template]. Check: template->platform. (See /config/template.yaml, line 0). Invalid config for [template]: [platform] is an invalid option for [template]. Check: template->platform. (See /config/template.yaml, line 11). Invalid config for [template]: [platform] is an invalid option for [template]. Check: template->platform. (See /config/template.yaml, line 19). Invalid config for [template]: [platform] is an invalid option for [template]. Check: template->platform. (See /config/template.yaml, line 28).
Hi there
I have 2 REST sensors that get data from an api. Sensor 1 is setup to update every 30 mins. Is it possible to setup such that sensor 2 updates whenever sensor 1 updates?
Like, is it possible to link sensor 2 to sensor 1?
Well, do exactly what you just said
{%- set numberOfSequentialHours = states('input_number.elprisverktyg_antal_timmar') -%}
You are mixing the old and new format
The old format is belonging to the sensor integration and can't be placed in template.yaml
The top 4 items should be placed under sensor:
aha... I don't know them tbh. But I did what you said, and now the error is different:
Error loading /config/configuration.yaml: while parsing a block mapping
in "/config/template.yaml", line 1, column 1
expected <block end>, but found '-'
in "/config/template.yaml", line 40, column 1
I added:
`sensor:
-
platform: template
sensors:wiser_boiler:
value_template: >-
{%- if states('sensor.wiser_hot_water') == "On" or states('sensor.wiser_heating') == "On" -%}
{{ "On" }}
{%- else -%}
{{ "Off" }}
{% endif %}`
ah or do you mean under sensor inside configuration.yaml instead of inside template.yaml?
I tried that, but then I got the error:
TypeError: unsupported operand type(s) for +: 'int' and 'str'
I typed 3 in the input helper number, but the state is actually 3.0 could that mess things in the code maybe?
You need to convert it to int
I indeed forgot to add that
{%- set numberOfSequentialHours = states('input_number.elprisverktyg_antal_timmar') | int -%}
Correct, it needs to be outside template.yaml
You can create a sensor.yaml
Thank a lot! 🙂
but isn't it better to update them instead to the new recommended way? I'd rather do that and have them all the same.
You can only update the one with platform: template
The others only belong under sensor
how can I update at least that one? How should it look with the new structure?
This is currently the template.yaml http://pastie.org/p/4BZ1igc88dO5EgcKusALC1
I have removed the 3 "old style" ones for now into configuration.yaml
You have several examples in that file you posted
yeah but can't figure it out. Nvm, I will look into that later.
For now, even when moving them into sensor.yaml, it's still giving me the error.
Error loading /config/configuration.yaml: while parsing a block collection in "/config/sensor.yaml", line 1, column 1
This is sensor.yaml now: http://pastie.org/p/6kF6rKd4996OaeQTA5qXhK
I think I fixed it. It was a couple indentations that I messed up
sensor:
- name: Wiser Boiler
state: >-
{%- if states('sensor.wiser_hot_water') == "On" or states('sensor.wiser_heating') == "On" -%}
{{ "On" }}
{%- else -%}
{{ "Off" }}
{% endif %}
That should work as a new format template sensor
Not sure why you are not creating a binary sensor here though
no particular reason. I'm just not able to understand the code yet. I'm just copy pasting what someone else did. That's the struggle. xD
thank you very much
states('sensor.wiser_heating') == "On" not is_state('sensor.wiser_heating', "On")? 😛
Yep, focused on old to new format, didn't really look closely at the template itself
Help with using input_number ‘helper’ in a template condition. Basic problem statement: I defined a input_number.home_monitor_state that can range from 0 to 3 (seems to want to store as float but I really only need integer) and I want to test that state as a condition in an automation before taking some action. I have the latest HA OS, UI, COre, etc and have tried all kinds of variations based on what I read in these help sections but seem to just doing something fundamentally wrong. Keep getting ‘condition did not pass’ when I ‘test’ the template. Here is the snippet in basic form:
http://pastie.org/p/1WX590hQKO8hTRuXJqLJpD
Using dev tools to look at input_number.home_monitor_state presently shows it as 0.0
Yeah, that syntax is weird
value_template: "{{states('input_number.home_monitor_state') | float < 3.0 }}"
or, you can just use a numeric_state condition instead of a template
Thanks - tried your suggestion in the value template and got the same result.
Yes I don’t know how to fix it
The numeric_state condition is what I tried first - the problems I ran into with that is it wants an ‘attribute’ and the attribute did not let me get to the ‘value’ of the input_number. I’ll redo the example that way and post that.
test whatever you have in
-> Templates and debug from there, or just use a numeric_state condition
it does not require an attribute
just don't provide an attribute
Oops
Using numeric_state condition. I still get condition did not pass. No template, no attribute.
Using dev tools to look at input_number.home_monitor_state presently shows it as 0.0
above: 0
it is correct
90% of getting the logic right is just knowing what you want
Agreed.
input number.home_monitor state
0.0
© Home Monitor State
initial: null
editable: true
min: 0
max: 3
step: 1
mode: box
friendly_name: Home Monitor State
Omg, that’s when u cannot see the forest thru the trees. I had tried to simplify the testing when I was using the value template to just test for less than 3.0 - I will go set that state to be 1 or 2 and see what happens. Duh.
Thank-you!
That worked.
What is the template notation to retrieve the "last changed by" information?
e.g. when a light is turned off by the service "light.toggle", under the entity's ( light.schakelaar_toilet_beneden_right ) history tab - logbook header I can see: "turned off triggered by service light.toggle"
I want to differentiate between the button being pushed (no "triggered by" information) and a service call (by an automation).
My use case is a toilet door sensor and light. Door is opened, toggles light.
Currently, when a luser manually turns off the light and then opens the door, the light turns on.
I've already added in a template checking whether it wasn't turned off in the last twenty seconds, but that does not support back to back toilet visits if there's a queue.
You should find last_changed on this page: https://www.home-assistant.io/docs/configuration/templating#states
That only gives me the last change timestamp, not the source of the last change
My apologizes. Maybe someone else can chime in on that.
Thanks for the attempt 🙂
That is in the context. There are lots of threads on this in the forum
And described in the docs for the state object
Thanks RobC, looks like I should be able to figure it out based on this.
Ah December, here to test all my templates again```
- name: "Next Bill Estimate" # monthly bill
icon: "mdi:currency-usd"
unit_of_measurement: "$"
state: >
{% if now().day < 18 %}
{% set remaining_days = 18 - now().day %}
{% else %}
{% set remaining_days = ( now().replace(month=now().month + 1, day=18) - timedelta(days=now().day) ).day %}
{% endif %}
{{ (states('sensor.cumulative_energy_cost')|float(0) + states('sensor.average_daily_cost')|float(0) * remaining_days)|round(2, default = none) }}
This should do it, unless someone has a better way? ```
{% set next_month = now().month + 1 if now().month + 1 < 13 else 1 %}
{% set remaining_days = ( now().replace(month=next_month, day=18) - timedelta(days=now().day) ).day %}
I'm having a weird issue with a template temperature sensor not keeping statistics
It's just taking the temperature from an existing sensor with 2 decimal places and rounding it to 1, and I have two other template sensors doing exactly the same thing and they're both keeping statistics
from template.yaml
@fallow gulch I converted your message into a file since it's above 15 lines :+1:
nursery temperature has no statistics, but kitchen and bedroom do
Add this to them state_class: measurement
that's fixed it, thanks!
Hi. I use a power meter to measure the power of our heat pump. The heat pump is used both for heating and hot water. I want to split out the energy use of those two.
First, I use a template to split the measured power.
state: >
{% if is_state('sensor.prio_43086', 'HEAT') %}
{% set power = states('sensor.power_heatpump_total') %}
{% else %}
{% set power = 0 %}
{% endif %}
{{ power }}
device_class: power
Then I user a Riemann helper to calculate the split energy from the split power.
The numbers don't add up after that. It seems the Riemann helper sees the period with value 0 as one point, and adds it to the sum total. Since power can go to 1kW instantly, that messes up the values considerably.
Should I try to fix it using the template? (I can give more information if you want, but I wanted to keep the question reasonably short).
{% if is_state('binary_sensor.turkontakt', 'on') %} Door is open {% else %} Door is closed {% endif %} }}
Hi. I'd like to put this template as the name on a custom button card. The template works in the developer tools as expected. But how do I add this as the name of the custom button card (or any other card for that matter)?
The card has to support Jinja templates, not many do. I'm not sure about the custom button card, I don't use the myself
Looks like custom button card doesn't support Jinja, but something with Javascript. Thanks for getting me on the right track 🙂
#frontend-archived can help with that
Already found the solution in the custom button card docu:
> [[[ if (states["binary_sensor.turkontakt"].state == 'on') return "Door is open"; else return "Door is closed"; ]]]
Hi. Im trying to change a nan value to 0 with a template sensor. But im getting syntax error. Whats wrong with that?
- name: "Leistung Solar"
unique_id: "leistung_solar"
unit_of_measurement: "W"
state: >
{% if is_state('sensor.inverter_watts', 'nan') %}
{% set output = 0 %}
{% else %}
{% set output = (states('sensor.inverter_watts')|float)|round(3) %}
{% endif %}
{% output %}
Looks just like what I managed to do with my template, few posts above.
Does it work if you replace
{% output %}
with
{{output}}
?
Yes man. That was the error! Thanks 🙂
i have a template sensor like this. the outcome is 44.0 i had hoped with | round (0) to get 44. is there a way to actually round it to a round number. i tried | int but this also gives 44.0 in home assistant is there a way to get 44?
{% set setpoint = states('input_number.otgw_aanvoer_setpoint_y2')|float - ((states('sensor.huidige_temp_vandaag')|float - states('input_number.otgw_buitentemperatuur_x1')|float) * states('sensor.otgw_p_factor')|float)|round(0) %}
{{ setpoint }}
never mind i missed () at the beginning and the end to specify what needs to be rounded. my bad
I want to compare a state of a variable sensor with a value in a variable. This isn't working:
"state: - operator: "template" value: | [[[ return variables.ulm_card_vertical_button_sensor.state == variables.ulm_card_vertical_button_state; ]]]"
What am I doing wrong? In the variable ulm_card_vertical_button_sensor is a sensor defined. When I enter a value instead of a sensor and I use the variable without .state it is working.
That is Javascript for a custom card and belongs in #frontend-archived, but why would you add ".state" to the first part and not the second? Variables don't have a ".state"
this is confusing:
state of a variable sensor
that's not a thing
if you're trying to retrieve the state of an entity, there are many examples in the card docs for how to do that
Given the attribute state in the link. Is it any good at templating that can help me doing the following:
https://pastecode.io/s/yn782zby
- Get the full object that has the value=1.98
- Get the average of all value fields
looks like it's just {{ data|map(attribute='value')|average }} to get the average
and to get a single object with a specific value: {{ data|selectattr('value', 'eq', 2)|list|first }}
Unless he is using a custom integration which creates these entities
I still have no idea what that means
where data is the sensor attribute (the whole list of raw data?)
The average one worked. Great! - the other one I get "UndefinedError: No first item, sequence was empty."
then there wasn't an object with that value
yeah stupid me. I need to be more specific on the decimals. Thank you Learned something new
{{ data|selectattr('value', 'eq', 4)|list }} if you just want the raw list
Oh yeah another thing. Is it possible via the template to access the "energy" values, like how much power cost is this far in the month?
The day and month cost from the energy tab in native home assistant from sources
no sorry
Hi, I'm attempting to integrate my withings scale. I've been through the documentation for this and i was able to connect the scale from the app and get it integrated
I used the template provided in the doc to convert KG to LBS, there are no errors in the config.yaml and i have resstarted HA, but I'm not seeing any effects of using the template...I imagined that i would see additional entities that show the sensors in lbs ..or the values in the entities would display lbs instead of kg...what am i supposed to see by using the template?
what template did you use?
Will it slow down using templates directly in the frontend vs making a template sensor?
presumably you modified it for the appropriate entities?
and checked your config?
yes, no issues
what entities did you look for and can't find?
In the withings integration, I have 34 entities that were all populated upon adding the integration, they all still display as KG and the values are still showing in KG...essentially nothing has changed for me after adding the template
yeah, that hasn't happened
that's why I asked what you were looking for and couldn't find, and you started taliking about the existing entities
those won't change
unless they are being filtered, perhaps?
and you won't see them in the integration page
you've created completely new entities
-> States
they are completely unrelated to the integration
other than using the entities from that integration, of course
got it, ok happy with that, you gave me a clue , that helped, thank you!
What are you guys using for icon color changing based on a value?
NFL Team Score Automation
how would i test if at least two states are true?
{% set wz_1 = is_state('binary_sensor.wz_motion_1', 'on') %}
{% set wz_2 = is_state('binary_sensor.wz_motion_2', 'on') %}
{% set ku = is_state('binary_sensor.ku_motion', 'on') %}
{% set list = [wz_1,wz_2,ku] %}
the template should result true if at least two items off the list are true
thanks alot
Having an issue with the attribute not properly working in my template. Trying to check whether the team_score attribute has changed by 6 or more. It is erroring saying Error: In 'template' condition: UndefinedError: 'homeassistant.core.State object' has no attribute 'attribute'.
trigger:
- platform: state
entity_id:
- sensor.philadelphia_eagles
attribute: team_score
condition:
- condition: state
entity_id: sensor.philadelphia_eagles
state: IN
- condition: template
value_template: '{{ trigger.to_state.attribute.team_score|int(0) - trigger.from_state.attribute.team_score|int(0)
>= 6 }}'
My thread is here: https://discord.com/channels/330944238910963714/1054149570298384384
ahh so just add the "s"?
trigger.to_state.attributes.team_score
yes
follow up how would i say in the notification how many points were scored...it says malformed.
service: notify.mobile_app_iphone_6s
data:
message: Buccaneers Scored {% trigger.to_state.attributes.team_score|int(0) - trigger.from_state.attributes.team_score|int(0) %}
title: NFL
that is in an automation
"Message malformed: template value should be a string for dictionary value @ data['action'][0]['data']"
Your message isn't printing. {% in Jinja evaluates, you need {{ to output.