#templates-archived
1 messages · Page 67 of 1
@worn dust under target:, change device_id: to entity_id:. When you erase the hash, and start typing "thermostat", it will autocomplete with the available entities under that heading
the traces is showing code that I don't have in my template... this is what my automation has:
alias: Thermostat Automation
description: Set thermostat based on outside temperature
trigger: []
action:
- service: climate.set_temperature
metadata: {}
data:
temperature: |
{% if 60 < 70 %} 68 {% elif 60 > 70 %} 75 {% endif %}
target:
entity_id: climate.thermostat
Oh wait I'm guessing traces shows the last run or something?
@worn dust Correct, you can walk through the last 5 executions, step by step
Awesome knowing that will help a lot, I'll look into it and come back if I run into trouble. Thanks much.
Can anyone help me. Trying to use rest but getting a error: Template variable error: 'value_json' is undefined when rendering '{{ value_json.state }}'
A rest sensor is like this:
- platform: rest
name: "RAID_Data_1"
resource: http://192.168.1.24:1234/data_line1.json
scan_interval: 60
value_template: "{{ value_json.state }}"
json_attributes:
- date
- line
- name
The json looks like this:
{"state":"clean", "date":"06.02.2024 21:11:05", "line":1, "name":"data", "active_devices":"2", "working_devices":"2", "status_devices":"in_sync
in_sync"}
just 2 drives? need to beef up those numbers
hehe, works for me and my home assistant I think 😄
But does anyone know i'm getting this error? The json are correct format?
I've never touched REST sensors, but it seems like the value templates may not be correct. From the provided JSON, all the elements are root-level elements, you may have to set up individual sensors
verify the example json is correct, I don' t think the last in_sync is valid
you are absolutely right. I changed the in_sync line and it worked. Thanks alot!!
Question is there a way to make it so that when a light in a area is on change icon?
that's already built in. "Color Icons Based on State"
You can couple that with the Header Toggle, or create your own custom card
@marble jackal the sensor of your designed worked just fine for two days, and all of a sudden became unavailable, even though the incurrent information is still incrementing just fine. Would you be willing to assist?
@undone jungle I converted your message into a file since it's above 15 lines :+1:
That link doesn't work, but that template shouldn't result in unavailable
If it does, there must be an error in your log
I'll be looking into the logs now
Logger: homeassistant.helpers.sensor
Source: helpers/trigger_template_entity.py:208
First occurred: 17:40:03 (7 occurrences)
Last logged: 17:51:52
Error rendering state template for sensor.water_heating_gas_energy_consumption: ValueError: Template error: round got invalid input 'unknown' when rendering template '{% set to = trigger.to_state.state %} {% set from = trigger.from_state.state %} {% if to | is_number and is_state('switch.shelly_hot_water', 'on') %} {% set previous = this.get('attributes', {}).get('previous', from | float) %} {% set delta = to | float(0) - previous %} {{ (this.state | float + delta * 11.474) | round(3) }} {% else %} {{ this.state | round(3) }} {% endif %}' but no default was specified
Error rendering state template for sensor.water_heating_gas_energy_consumption: ValueError: Template error: round got invalid input 'unavailable' when rendering template '{% set to = trigger.to_state.state %} {% set from = trigger.from_state.state %} {% if to | is_number and is_state('switch.shelly_hot_water', 'on') %} {% set previous = this.get('attributes', {}).get('previous', from | float) %} {% set delta = to | float(0) - previous %} {{ (this.state | float + delta * 11.474) | round(3) }} {% else %} {{ this.state | round(3) }} {% endif %}' but no default was specified
It seems it got tripped up receiving an unknown into a number evaluation.
It failed on the round filter you added in the else part (which wasn't needed anyway)
And your version is also missing the default for the float filter I added in the last version
Is this the latest?
I am not sure in which statement.
The only float(0) I can see matches with mine, or am I wrong?
Should float in this statement also have a 0 default filter? {{ (this.state | float(0) + delta * 11.474) | round(3) }}
Or do you refer to the previous, where the float is produced after it being pulled from the attributes
This would make more sense to have a default, if the attribute previous would get lost at some point.
Yes, because of the initial state of the sensor
And because of the current state of the sensor as well
This should work better
https://dpaste.org/GPX1M
The old data wasn't correct BTW
It was counting double
Trying to template a delay action in a script based on a Duration field but can't find any examples nor getting it anywhere with randomly trying. Is this possible or go back to using a number and template a delay for just "minutes"?
There's an example in the docs: https://www.home-assistant.io/docs/scripts/#wait-for-time-to-pass-delay
myscript:
sequence:
- delay: "{{ delay }}"
...
service: script.myscript
data:
delay: "10:00:00"
most minimum example
script and the service call, calling the script
@dark kindle I converted your message into a file since it's above 15 lines :+1:
(copied the wrong thing, field is named my_duration)
- delay:
seconds: "{{ timedelta(**my_duration).total_seconds() }}"
but then when you call it, you have to use
service: script.myscript
data:
my_duration:
minutes: 5
I am lost a bit in this. You mentioned the float should have the default filter, but your latest sketch is identical to mine in this regard and only adds the not_from: clause
Should I thus add the {{ (this.state | float(0) + delta * 11.474) | round(3) }}
you only need defaults if the code tries to convert a string to a number and it fails
if you account for that with your if statements, you don't need it
so I can't rely on the default in the script, but allow custom values if needed?
I have no idea what you're asking
if you want to use the selector, you must use what a selector provides at all times
when you manually use the script
but its defined with a default duration of 5 minutes - I would expect the script to use that if no data was passed?
but the duration isnt defined if not passed in the data: so i guess not
no, defaults are not passed. Fields and selectors are just for the users sake, they do not actually provide information to the script
I mean, if you use the selector it provides the information. But if you don't, nothing is provided.
Thanks for clarifying the logic of it. This said @marble jackal specifically indicated it needing to be there as one of the causes of the failure, hence my wish to understand why it's not in his updated sketch.
that explains some of my confusion - thanks for clarifying
in the code provided, it's only need for this.state and the from, the to is covered because your if statement checks to see if it's a number.
so add one
Which is what I was trying to understand why he said it's needed but later said he updated the sketch without it. I know I can add it but also was trying to understand if my actions make sense.
he probably just made a clerical error, it's easy to do w/ templates
Yes, I missed that one while thinking about the other changes which are needed
Especially the attribute is changed, I used from_state.state there, but it has to be to_state. state
That will be from_state.state the next time it triggers
I included it to add the right delta if your source sensor has been unavailable
You tell me... 😆
What is 'it' in this sentence?
And finally, would you recommend using the default filter in the {{ (this.state | float(0) + delta * 11.474) | round(3) }} statement, since you've mentioned it being necessary.
OK, so finally the filter is not needed in the to loop since it's tested for number in the if already and I'll add the default to the this.state
@undone jungle I converted your message into a file since it's above 15 lines :+1:
Correct
Hi, I'm trying to create a binary sensor for a button push on my rf doorbell with the following yaml but it doesnt seem to be working, I'm using the UI to set up a helper
event_type: esphome.rf_code_received
event_data:
code: d7aa3
variables:
to_state: on```
Is someone able to point me in the right direction please? The sensor just stays as off
That's a trigger, the template helper expects Jinja code
If you want to create a trigger based template binary sensor, you'll have to do it fully in YAML
Thanks, something like this?
- trigger:
platform: event
event_type: esphome.rf_code_received
event_data:
code: d7aa3
binary_sensor:
- name: Front Door
auto_off: 5
state: "true"```
Yep
Does anyone have pointers at where to read up on how to work with the data in exposed_entities doing Jinja template stuff? Googling doesn't find me any useful dev documentation
What would you like to achieve?
@quasi frost I converted your message into a file since it's above 15 lines :+1:
when i check the configuration yaml i got this message:
Konfigurationswarnungen
Invalid config for 'template' from integration 'sensor' at configuration.yaml, line 86: expected dictionary for dictionary value 'sensors->friendly_name', got 'nicht erfasste Verbraucher'
Invalid config for 'template' from integration 'sensor' at configuration.yaml, line 87: expected dictionary for dictionary value 'sensors->unit_of_measurement', got 'W'
Invalid config for 'template' from integration 'sensor' at configuration.yaml, line 88: expected dictionary for dictionary value 'sensors->value_template', got "{% if (states('sensor.heizungskeller_gesamtleistung')|float - states('sensor.gesamt_leistung_plugs')|float) > 0 %}\n {{ states('sensor.heizungskeller_gesamtleistung')|float - states('sensor.gesamt_leistung_plugs')|float }}\n{% else %}\n {{ 0 }}\n{% endif %}"
Invalid config for 'template' from integration 'sensor' at configuration.yaml, line 94: expected dictionary for dictionary value 'sensors->nicht_erfasste_verbaucher_template', got "{{ [ states('sensor.heizungskeller_gesamtleistung'), states('sensor.gesamt_leistung_plugs') ] | map('is_number') | min }}"
What is wrong?
you haven't provided the object id for the 2nd sensor
# first sensor:
sensors:
power_import:
friendly_name: "Power Import"
# 2nd sensor
sensors:
friendly_name: "nicht erfasste Verbraucher"
@quasi frost see the difference?
just the postion?
Is it possible to template the due date Param for a add new Todo service? I want to set a Todo to empty the vacuum so that my google nest setup tells me as a notification.
If you don't add a date then google doesn't put it on the calendar and the nest won't tell me to do it.
I need to use a template to get the current date and use that as the param
Is that possible?
ah no, the power import
no, the equivalent for power_import: is missing for the 2nd senosr.
BTW, you can put it allunder one platform: template line
- platform: template
sensors:
power_import:
friendly_name: "Power Import"
something_else:
friendly_name: "nicht erfasste Verbraucher"
and you are using the legacy format, I would suggest to start using the modern template sensor format
how does it look like in the modern format?
thx, got it and its working now
you now have it under the sensor integration (possibly in a separate yaml). The new format uses the template ingegration
so it would be something like
template:
- sensor:
- name: "Power Import"
state: >
{{ your template }}
availability: >
{{ your availability tempplate }}
I'm guessing I need to use now() then float the string into yyyy-mm-dd like when it's hardcoded?
you should be able to jsut use now().date()
Looks like it worked
just discovered that {{integration_entities('')}} actually has an output
[ "media_player.panasonic_viera_tv", "remote.panasonic_viera_tv" ], and I cant understand why that is
could it be the only integration that has a non existing id?
seems a bug really?
not really
that just means an integration didn't register itself properly
the function looks at the entity registry
or the device registry, can't remember which
it looks at the entity registry
I also have quite a list there, but for me it's all the HACS update entities
same here
but the code has a fallback
if it can't find a config_entry it falls back to the fallback
it tries to find the entry name from entity_sources which is a function in HA
divid Value Imput sensor
this would be a bug..?
or at least a chance for improvement
it depends
the function has fallbacks and it outputs the fallbacks
so the function is working by design
which means it's not a bug with the function
on that fallback: why does it list these 2 entities?
sorry, but I dont understand that.... If you 2 see all HACS update entities there, how come I dont get these? (using HACS...)
Hello, how to create an sensor, which will copy existing sensor, but only when existing will return value, and not copy, when existing is unavailable?
no matter the reason, it seems useless to show these 2 entities, if (and they are) also properly output when using the actual integration name {{integration_entities('panasonic_viera')}} I just dont get why those would be any fallback at all.
you can create a template sensor for that entity, and use an availability template
see a few posts up #templates-archived message
it defaults to getting a domain
it's literally in the code as "Fallback will grab a domain from entity_sources"
as a comment in the code
this is 100% by design
why are you feeding your template an empty string anyways?
I am not... I always first type the structure and then fill that with relevant data. In dev tools template, not in the UI or so. Doing that, I noticed this unexpected (to me) output.
so the 'getting a domain' is just a random domain.. feels a bit arbitrary, or even funky if you ask me, to output some useless output. even if it is by design.
imagine any of our other templates do that....
seems a default of 'No integration set' would make more sense
no, I'd rather have a useful default
well, you go down that path and then we have to make breaking changes
by all means, make a FR
still not a bug though
as it's clearly the original design of the function noted by the comments in the function
do you have the code link for me please?
odd, I cant find that line in the link perm link, nor in the dev blob https://github.com/home-assistant/core/blob/dev/homeassistant/helpers/template.py
theres this though https://github.com/home-assistant/core/blob/97c6fd0f8d8785fc3dd2b12b73b893496eb5adb2/homeassistant/helpers/template.py#L1266 which is probably the same
would this work for and conditions? I know i could do and in the template, I want to know what happens with this:
- choose:
- conditions: >
"{{ condition1 }}"
"{{ condition2 }}"
sequence:
No, but this would:
- choose:
- conditions:
- "{{ condition1 }}"
- "{{ condition2 }}"
sequence:
I permalinked to the function, not the line that contains the comment
so you can read the whole function
yeah, sorry, didnt want to be a smart ass, I just noticed a difference in those sentences, and figured you might have copied something else. Np.
Isn't the issue that the search allows finding entities based on config entry title, which is not unique and may also be the empty string?
It could be, I didn't fully dive into it
I'm not at home w/ my dev box
There's 2 calls i'm unfamiliar with, it's the entry grabbing portion and the entity_sources portion.
I'm almost sure that's it. @tame niche you added the function, maybe it should not allow searching by the empty string?
Also, the config entry search is a bit meh because it will in a non-deterministic way (at least from the user's point of view) give you entities from one of many possible config entries with a matching title. I think it should either hand back none or all.
if we really want to add it, couldn't we just add if not entry_name:...
Not sure how many people are searching for None though
which does return values for integrations I think, but I might be remembering device_id
huh, what ? I heard my name ?!
hehe
the context is that the integration_entities template function searches by config entry title
in many cases, integrations set the title to the emtpy string, and frontend just shows the integration name, so from the user's point of view it's not clear the config entry has no title
that might actually be the most common case evenprobably not
so, if you call integration_entities with the empty string, the result is the entities of the first config entry without a title
Hi all. Can somebody help me out with this simple template?
`template:
- sensor:
- name: "DA_Wärmepumpe_Temp_Abfall"
unit_of_measurement: "°K"
device_class: "temperature"
state_class: "measurement"
state: "{{ state_attr('climate.luft_wasser_warmepumpe', 'current_temperature') - states('sensor.luft_wasser_warmepumpe_in_water_temperature')}}"`
I want to substract this state attribute with the state. Each on their own seems to work but as a substraction it won't give back a number.
Hope you can help. Thanks.
- name: "DA_Wärmepumpe_Temp_Abfall"
All states are strings so you need to convert them to numbers.
aahhh, thanks a lot, so it needs to be casted
{{ (state_attr('climate.luft_wasser_warmepumpe', 'current_temperature') | float(0)) - (states('sensor.luft_wasser_warmepumpe_in_water_temperature') | float(0)) }}
You might not need to do the attr as those can be numbers, but I tend to cast them just in case.
Thanks a lot. Testing...
works! 😄
Hi, I would like to get current action from entities on my climate group.
This code:
{{ expand('group.group_termostati') | map(attribute='attributes.hvac_action') | list }}
produces this output:
[<HVACAction.IDLE: 'idle'>, <HVACAction.IDLE: 'idle'>, <HVACAction.IDLE: 'idle'>, <HVACAction.OFF: 'off'>]
while instead I was expecting:
[ 'idle', 'idle', 'idle', 'off]
Any way to convert the results in the needed values ?
this works fine for a single entity:
{{ states.climate.termostato_sala.attributes.hvac_action }}
Probably, but single entity works fine is just map() that doesn't
yeah, I can't figure out how to pull out the values
{{ expand('group.group_termostati') | map(attribute='attributes.hvac_action') | map(attribute='value') | list }}
it's an enum, so name gets IDLE and value gets idle from the <HVACAction.IDLE: 'idle'> object
Yeah that’s just how enums work in code
They are weird
Basically what we see in the list is the string representation of the object, but when we access the object, it outputs the value
Thx petro. I would have expected the same result and this took on the wrong road.
{{ expand('group.group_termostati') | map(attribute='attributes.hvac_action') | map(attribute='value') | list }}
works as suggested
Yeah it's a bit odd
but it's the nature of generators
they don't access the object they supply unless they don't have to
which is why we get the string representation of it
definitely an oversite by the dev team, but we can easily work around it
Should be documented for all users to find out easily
Should just be fixed somehow 🙂 The differing behavior and exposing implementation details is suboptimal
Not sure how it could be fixed without completely breaking generators or changing the attributes from enums
and by breaking I mean, making them slower
do template sensors support the usage of an object_id ?
/ can i migrate them from a unique_id to another
What's the relation between object_id and unique_id?
i am not sure
for mqtt the unique_id is just whatever with the object_id being what the ui shows as object id
ie i have something like this for mqtt sensors
name: Outdoor Temperature
object_id: Temperature-Probe-68f6cee342a8 Celsius
unique_id: db68590e-13bb-404b-9846-b13e2329c7d1
but the documentation about template sensors doesnt mention this field
template sensors generate the object ID from the name in the new template style
they generate the object_id from the slug in the old template style
if the name isn't provided in the new template style, they are generated from the unique_id but slap a template_ before the unique_id
TLDR: Template sensors do not have an object_id field like MQTT entities do.
i see
i suppose its safe to touch the unique id field tho? (after the entity already wrote some statistics id like to keep)
i somehow ended up with a stroke writing one of them id like to correct / make into a uuid
name: "shellyem3_485519dc8561_channel_abc_power_consumption"
unique_id: "shellyem3_485519dc8561_channel_abc_powe_consumption"
oh no it seems to use the unique_id as statistics one
.-. i suppose this requires careful db modifications
What are you trying to do?
i would like to fix my unique_id to have either an r in power or replace it with a uuid if that id isnt visible anywhere on the ui
If you’re trying to replace an entity but use the old db. Delete the entity and make sure the new one on instantiation has the same entity id as the only one
You shouldn’t need to worry about the uniqu_id at all
You mean object_id?
i set the name and unique_id both for my template sensors as i started with this setup
but i do like the way how i have it for the mqtt one a bit more
so i thought i could make adjustments
You have to make adjustments from the UI
Or delete the entity and let config_entries recreate it with new info
where do i find this config
just to make sure, if i am deleting a template entity over the frontend it does not remove the statistic does it
yay that seems like it did work
this is way too exiting for me ^^, thanks for your help!
Sorry back to help
No, it shouldn't if you have a unique_id attached to it
the big thing is, don't change the unique_id. There's no reason to once you create something with it
If you don't like the unique_id, then you might be SOL. I've never had to deal with that level of change so I'm not familiar with the process
Although
What you could do....
i did end up commenting out the template, deleting the entity and recreating it with a new unique one
the statistics carried over which is what i care the most about
not sure if there is something that internally uses the unique_id over the frontend that borks now
well history and statistics should use the enitty_id
but so far my dashboards look unsuspicious
so, deleting and recreating should work
what you DON'T want to do, is rename the old then craete the new one with the old name
because that will just carry the history to the new renamed entity
you specifically have to delete the old one
so that it doesn't carry to something else
i am not sure wether or not i like the helper entities when working with templates
it feels like modifying the same stuff in two places, especially if something depends on a riemann sum
waait i just saw there are template helper 😮
Thats like significantly better ^^
ill keep that in mind
for now i just need it for splitting grid supply and return from a shelly
I wrote it down in https://github.com/home-assistant/core/issues/110025
ofc you know Erik, just for the others to share, and linked to the discussion here
@spring pollen I converted your message into a file since it's above 15 lines :+1:
device_class: power was breaking it. Something changed with that maybe, since it worked before? Either way it works now
Device class on sensors is only for numerical template sensors
You should be using a binary sensor with device class power, outputting a result of on or off
I do not know where to start looking...
I use a helper to input_number through a slider, that I use to set the time in active directory when my sons computertime should end. The number is the hour in 24 hour format. That works perfekt. The slider is for me and my wife to easy be able to extend for one hour
But now my son would like to get a heads up 10 min before his computer turns of.
So i got the helper input_number.computertime_stop that equals 19. And I need to get a datetime = "18:50:00" to use in a trigger. Any hints on what to search for or ideas for a template?
I normally set up a template sensor like:
- name: Timer Offset
state: "{{as_datetime(state_attr('timer.timer','finishes_at')) - timedelta(minutes=10)}}"
availability: "{{state_attr('timer.timer','finishes_at') is not none}}"
device_class: timestamp
{{ today_at(states('input_number.computertime_stop')|int|string + ":00") - timedelta(minutes=10) }}
Perfect, I learn something new every day!!!
Anyone had luck creating a dict and referencing it later in the same template?
Specifically with the key being a variable, that seems to be the tricky part
like this?
{% set foo = "bar" %}
{% set mydict = {foo: "blah"} %}
{{ mydict.bar }}
-> blah
{% set foo = "bar" %} {% set mydict = {foo: "blah"} %} {% for name in areas() %} {% set mydict = {name: loop.index} %} {{loop.index}},{{name}} {%endfor %} {{mydict}}
-> {'bar': 'blah'}
So a scoping issue, I'm assuming
yes, you need to use a namespace if you want something in a for loop to be available outside it
this will probably do what you expected:
{% set ns = namespace(mydict={}) %}
{% set foo = "bar" %}
{% set ns.mydict = {foo: "blah"} %}
{% for name in areas() %}
{% set ns.mydict = {name: loop.index} %}
{%endfor %}
{{ns.mydict}}
it's overwriting the initial assignment
Well, that's still farther than I've gotten 🙂
Ha, figured it out.
{% set ns = namespace(mydict={}) %} {% set foo = "bar" %} {% set ns.mydict = {'None': 0} %} {% for name in areas() %} {% set foo = {name: loop.index} %} {% set ns.mydict= dict(ns.mydict.items(), **foo) %} {%endfor %} {{ns.mydict}}
Last comment on this post was the solution
https://community.home-assistant.io/t/how-to-extend-a-dict-in-jinja/408928/8
What error are you getting?
Executed: February 9, 2024 at 11:18:46 AM
Result:
params:
domain: todo
service: add_item
service_data:
item: Empty Vacuum
due_date: '2024-02-09'
entity_id:
- todo.home_assistant_notifications
target:
entity_id:
- todo.home_assistant_notifications
running_script: false
service: todo.add_item
metadata: {}
data:
item: Empty Vacuum
due_date: "{{now().date()}}"
target:
entity_id: todo.home_assistant_notifications
My automation trigger set a Todo task in my google tasks for 8/2/24 instead of 9/2/24
Where did I go wrong
Even hard coding the date is wrong. Looks like bug in google tasks integration?
off-by-one maybe?
Trying to do math with an input_number. For testing, input_number.disco is set to 130
{{ (60000 / int(states.input_number.disco_bpm.state)|round(0)) }} should return 461, but doesn't round - I get 461.53846153846155
You just rounded the state
oh, shit I see it now
fixed, thanks! {{ (60000 / int(states.input_number.disco_bpm.state))|round(0)}}
Yeah but it looks like it's a bug in the Google task integration. I did one to a local Todo and it worked right
is one of these better than the other?
"{{ is_state('input_select.which_room', 'living_room') }}"
"{{ states('input_select.which_room') in ['living_room'] }}"
I prefer the second way because I am using it in other parts of the script with a real list ['living_room', 'den', 'kitchen'] etc...
the equivalent to the second example using is_state is "{{ is_state('input_select.which_room', ['living_room']) }}"
in other words, you can provide a list of possible states there, and I think that's the preferred way
How to add one day to now()?
I want to get tomorrow's date
That did the job thank you.
Looks like the Google task implementation has a off by one bug. Calling add Todo for today sets a Todo for yesterday
Can someone please explain why this template is not entirely correct? I don't want it to be reported if it is within a range.
- sensor:
- name: "house_energy_consumption"
unit_of_measurement: "kWh"
state_class: total_increasing
device_class: energy
# availability_template: "{{ (states('sensor.energy_consumed_tariff_1') | float(0) | round(2)) + (states('sensor.energy_consumed_tariff_2') | float(0) | round(2)) > 11000 }}"
availability: "{{ states('sensor.energy_consumed_tariff_1') | float(0) | round(2) + states('sensor.energy_consumed_tariff_2') | float(0) | round(2) > 11000 }}"
state: >
{% set A = states('sensor.energy_consumed_tariff_1') | float(0) | round(2) %}
{% set B = states('sensor.energy_consumed_tariff_2') | float(0) | round(2) %}
{% if (A + B) > 0 -%}
{{ (A + B) }}
{% else %}
unavailable
{%- endif %}```
availability_template doesn't work. so what did I messed up?
availability_template isn't valid for new template styles
availability does the same thing, so you're using the correct field
why are you rounding the value?
template:
- sensor:
- name: "house_energy_consumption"
unit_of_measurement: "kWh"
state_class: total_increasing
device_class: energy
availability: >
{% set a, b = ['sensor.energy_consumed_tariff_1', 'sensor.energy_consumed_tariff_2'] | map('states') | list %}
{{ a | is_number and b | is_number and a | float + b | float > 11000 }}
state: >
{{ ['sensor.energy_consumed_tariff_1', 'sensor.energy_consumed_tariff_2'] | map('states') | map('float') | sum | round(2) }}
or you can just use the sensor group helper using the Sum option.
without the template
thanks, will try it, and rounding is not necessary, will remove it.
you can use defaults for the float filter in the availability template, and just theck on the sum
{{ ['sensor.energy_consumed_tariff_1', 'sensor.energy_consumed_tariff_2'] | map('states') | map('float', 0) | sum > 11000 }}
wait, unless one of them is above 11000 of course
scrap that 🙂
it's not needed with the availability
unless you're syaing to make that the availability
yeah, it thought this might be a one step approach for the availability, but if one of the sensors is above 11000 you still get unexptected results
no, because the and doesn't make the rest of it evaluate
I meant with only my version
oh ok
There's a number of ways to handle the availability, I always go with the most optimized (if I see it)
optimized for speed that is
that is a really nice thing in your code 'is_number' appreciated that!
you can use is_number as a mapped filter too, but it doesn't help in this case
sry, miss understood what you were saying, coffee hasn't kciked in even though I'm shaking from it
i will look into that for my esphome sensors that is feeding this energy sensor.
haha!
no worries 🙂
#energy-archived can help, this is a #templates-archived channel.
I'm having a data type error that I'm not sure how to solve, but I think I have an idea. I have this template:
- unique_id: solar_forecast_estimate_current_hour
name: Solar forecast current hour
state: >
{% set nu = now().replace(minute=0, second=0 , microsecond=0).isoformat() %}
{% set watts = state_attr('sensor.solar_forecast_estimate_watts','watts')%}
{% set data = watts.items() %}
{{watts[nu] if nu in watts else 'No production estimated'}}
icon: mdi:sun-clock
unit_of_measurement: W
And this is the error I get:
ValueError: Sensor sensor.solar_forecast_current_hour has device class 'None', state class 'None' unit 'W' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'No production estimated' (<class 'str'>)
sensors with a unit_of_meaurement should output a numeric state
No production estimated is not a numeric state
I guess it makes sense, since that's a string, and I want this sensor to have a float.
Exactly. So do I just make it a "0" or just accept an unavailable or?
I actually don't even know why I need a fallback
- unique_id: solar_forecast_estimate_current_hour
name: Solar forecast current hour
state: >
{% set nu = today_at().replace(hour=now().hour).isoformat() %}
{% set watts = state_attr('sensor.solar_forecast_estimate_watts','watts') %}
{{ watts[nu] }}
icon: mdi:sun-clock
unit_of_measurement: W
availability: >
{% set nu = today_at().replace(hour=now().hour).isoformat() %}
{% set watts = state_attr('sensor.solar_forecast_estimate_watts','watts') %}
{{ watts is not none and nu in watts }}
I forget. I must have taken this from another example and changed it for my own needs, and then not removed that part.
It's a while ago
How can I get the zone of the current user? Something like
{{ zone_id('user') }}
Is there a way on a notification to convert a sensor in minutes to a more human friendly text? i.e. sensor = 121 minutes, send 2 hours, 1 minute.
i would liek to avoid creating a helper sensor for this and do it in the notification automation itself
the current user
Do you mean the person who is logged in and looking at some dashboard? That’s going to be a question for #frontend-archived and dependent on the card you use.
The backend has no idea who is looking at any dashboard. But if you want the zone of a specific person, it’s just that person’s state.
{{ states('person.john_doe') }}
Markdown card does support a {{user}} var of the person viewing it. But otherwise in many places a user is not even a relevant concept for a template, it may be running where there is no user.
Probably want to elaborate on where you have this template, and what is the use case.
Maybe something like this:
{% set seconds = states('sensor.minutes_until_something') | float * 60 %}
{% set years = seconds // 3153600 %}
{% set days = seconds % 3153600 // 86400 %}
{% set hours = seconds % 86400 // 3600 %}
{% set minutes = seconds % 3600 // 60 %}
{{ '%dy ' % years if years else '' }}{{ '%dd ' % days if days else '' }}{{ '%dh ' % hours if hours else '' }}{{ '%dm' % minutes }}
Modify to your liking
any way to avoid all the new lines that makes?
so replace {% with {%- ?
There is a macro by TheFes if you want something much more powerful that’s fairly simple to use
I mean like this
Hello, {{user}}!l
I want to replace john_doe with the user variable, but have no idea how
*sorry for ping i was too sleepy to realize
A post on the general forum reminded me I need to strip out all my Weather reporting as for no reason I could understand the Forecast stuff is being removed from the Weather Entity, before I do I just wanted to check there is no way to pull a service response in a Jinja Macro, with out having to change all the automations and scripts which use it. Has anyone got around this at all? My current thought is to use MQTT to get the response and put it in a MQTT sensor every half hour or so.
@lyric comet You can put them in a template sensor without the use of MQTT. Trigger based template sensors support an action section, and variables created there are carried over to the sensor section
There's an example in the docs https://www.home-assistant.io/integrations/weather#examples
Hi, want to check my understanding of self referencing
- unique_id: phone_wifi_status
state: "{{ is_state('sensor.sensor.phone_wifi_connection', 'TP-Link_5DF8') }}"
delay_off:
minutes: 2
device_class: presence
icon: |
{% if is_state('this', 'on')%}
mdi:wifi-check
{% else %}
mdi:wifi-cancel
{% endif %}
The usage of this will just self reference this sensor
The question is: where do you want to use that code? If you want to use it in the frontend (on a dashboard) then see karwosts reply: #templates-archived message
If you put quotes around it, this will be the string 'this', not the variable this
So remove the quotes.
Then.. this is the full state object, to use it in that template, you need to use this.entity_id
you could also use this.state == 'on'
icon: "{{ 'mdi:wifi-check' if this.state == 'on' else 'mdi:wifi-cancel' }}"
new question, is there a reason multi line state call wouldn't work?
state: |
{% set grant_home = (is_state('device_tracker.grants_phone', 'home') or is_state('binary_sensor.template_grant_phone_wifi_status', 'home')) %}
{% set holly_home = (is_state('binary_sensor.template_holly_phone_wifi_status', 'home')) %}
"{{ grant_home or holly_home }}"
remove the quotes around the template which does the output
Why no quotes? I use them on the other templates for wifi status
Multiline templates without quotes, single-line templates with quotes
state: "{{ true }}"
state: >
{{ false }}
my bad. will ask in #frontend-archived
anyone know how to turn this into a REST sensor ?
{"message":"ok","data":{"id":716,"ping":6.49,"download":202.3896,"upload":186.52,"server_id":41001,"server_host":"drt-speedtest-b.voiped.eu:8080","server_name":"Voiped Telecom","url":"https:\/\/www.speedtest.net\/result\/c\/ea5c16d5-6633-491a-82da-1b23f2c64ec3","scheduled":false,"failed":false,"created_at":"2024-02-10T14:20:43.000000+01:00","updated_at":"2024-02-10T14:20:43.000000+01:00"}}
tried this but no output :
rest:
- scan_interval: 60
resource: http://192.168.188.46:8844/api/speedtest/latest
sensor:
- name: "Downloadx"
value_template: "{{ value_json.download }}"
Looks like you want {{ value_json.data.download }}
ah ty
can i give them an icon as well ? and should i put them in a device_class ?
sensor:
- name: "DownloadX"
value_template: "{{ value_json.data.download }}"
- name: "UploadX"
value_template: "{{ value_json.data.upload }}"
- name: "PingX"
value_template: "{{ value_json.data.ping }}"
I am currently writing a script to enqueue an album based on the current track playing extracting the information from the media_content_id. I can use urlencode() to build the new format, but I need to decode the media content id, but urldecode() does not exist when I try to use it. Is there an equivalent or a work around please. I know I could just do spaces but I am bound to come across some ampersands or similar.
Is there any way to use a template as a condition for the conditional card?
not directly. you can create a template sensor or binary_sensor and use that, or use this instead: https://github.com/thomasloven/lovelace-state-switch
Hi. I am looking to setup a cast notification for when some tasks finish.
I put on the washing machine and vacuum while I am out, I come home and want the cast to tell me "while you were out the washing machine and vacuum finished". What is the easiest way to handle this? What if only one finishes while I am out?
I thought maybe a template sensor with a list of notifications? Which I can then set and get from various automations to result in
"Hi, while you were out [] and [] and... Finished their tasks"
Figured templates would be the place to help
I imagine I would need to have a trigger sensor and then pull some information from the trigger event (entity name probably) then add that entity name to the list. However when I need print out the string I will need to clear the sensor
Also how would I programatically build the string? I know individually how to for loop and set variables but not how to append strings etc
set string = "Hi, while you were out list[0]"
for list[1] to list.end
string += ", and list[i]"
string += " finished"
return string
I took a stab but absolutely no clue
@summer arch I converted your message into a file since it's above 15 lines :+1:
2024-02-11 15:41:01.555 WARNING (MainThread) [homeassistant.components.sensor.helpers] sensor.completed_tasks rendered invalid timestamp: ['entity_id', 'state', 'attributes', 'last_changed', 'last_updated', 'context', Undefined]
@summer arch I converted your message into a file since it's above 15 lines :+1:
I want to get a list of lights that are on in an area. I get it to work, but one of the light are a helper that combines two lights into one. I can't get it to show up. Why?
This gives me the list i want. But the helper isn't showing:
{{ expand(states.light) | selectattr('entity_id', 'in', area_entities('Vardagsrummet')) | map(attribute='entity_id') |list }}
This gives me a list of all entities in an Area, but the helper is still not showing!
{{ expand(states) | selectattr('entity_id', 'in', area_entities('Vardagsrummet')) | map(attribute='entity_id') |list }}
You're trying to use that as the state?
States are limited to 255 characters. The logs would show that
I am typing this in the developer tools if that is what you are asking.
I'd guess the lighting group made from the helper ui
{{ expand(states.light) | selectattr('entity_id', 'in', area_entities('Vardagsrummet')) | map(attribute='entity_id') |list }}
Gives me this list:
['light.vardagsrummet_vitrinskapet', 'light.vardagsrummet_fonstret_2', 'light.vardagsrummet_fonstret_1', 'light.vardagsrummet_taklampan', 'light.vardagsrummet_golvlampan', 'light.vardagsrummet_pa_tv_banken']
I have combined 'light.vardagsrummet_fonstret_2', 'light.vardagsrummet_fonstret_1' to one light with a helper, i think it is called lightgroup. This is named 'light.vardagsrummet_fonstret'
You can't use a template just anywhere
Testing in developer tools
What is wrong? What did you expect?
'light.vardagsrummet_fonstret' should be in the list
It's a weird way to do that
{{ area_entities('Vardagsrummet')|seiect('is_state', 'on')|list}}
But it sounds like the helper simply isn't in the area
You could verify that
Just lights:
{{ area_entities('Vardagsrummet')|select('match', 'light.')|seiect('is_state', 'on')|list}}
This works!
Strange that my first code isnt showing the helper at all?
Tried in a different area where there is another helper with the same result.
I don't know. They should be the same
I am not that experienced but this feel like a bug to me
Mine is much more efficient
Yes I will use this
BTW, states and states.light are both already collections of state objects, so calling expand() on them doesn't make sense
I don't know what that's actually doing for you, but perhaps that's not doing what you expect 🤷
I just googled and found this and modified it. I suppose it was wrong
Lots of garbage out there
Yes, but I may have been missunderstanding and modifed the code to the wrong usecase
Hi. I am looking to setup a cast
Made a thread so that all my intermediate answers to myself don't get lost while waiting for help
Hi guys I am having problem with my home assistant I want to use 1 input of impulse sensor for multiple outputs cause I need impulses and water flow L/minute but when I am using -platform: template sensors: I get error message --> [sensors] is an invalid option for [sensor.template]. Please check the indentation. Does anyone know how to solve this ?
We might be able to if you would post your YAML
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language, and consider picking a longer expiry)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
@marble jackal u mean whole config
what ever is broken, no one knows what you have written so no one knows why it is broken, except you
Using one of the links above
here is link
I am finding answer almost for 2 days
so you are my last chance
@marble jackal thx for help
You are placing the sensor config for an Home Assistant template sensor in an ESPHome config
That won't work
Furthermore, ESPHome doesn't support Jinja
so is there any way I can use same pin like GPIO13 multiple times
I want to get Water flow pulses and second gauge I need for L/minute
@marble jackal
do you know how to do it
Ask in #diy-archived or on the ESPHome discord
https://discord.com/invite/sKqfcnjw
Hey,
is there a way to loop through all entities with a certain device_class?
I want to get a list with all humidity sensors with humidity higher than a certain value
Something like this?
{% set sensors = states.sensor
| selectattr('attributes.device_class', 'defined')
| selectattr('attributes.device_class', 'eq', 'humidity')
| map(attribute='entity_id')
| list
%}
{%for sensor in sensors%}
{{sensor}}
{% endfor %}
BTW You could also add a select() to filter down to the ones over the value.
You need a namespace and a for loop for that, as states are strings, and you'll get unwanted results if you do a string comparison
Thanks TheFes. I thing I normally filter for ON/OFF so not a problem, but you are of course correct as aways, sorry.
Does anyone here know if it's possible to dynamically change groups using the new group integration? The old integration group.group_of_things had a service call that allowed changing of group members but it seems the new group integration light.group_of_things doesn't seem to have the same functionality
No. Unrelated to #templates-archived
yes but people here in templates know lots of things I shall ask in integrations
It will still be no
I have been x'd
Posting in a random channel because you think there are smart people there is...weird and wrong
well I'd like to make a template that dynamically selects lights as members of a group depending on device state and time of day and then have an automation that acts on that group
since I'm just adjusting light properties, I wonder if I can just dynamically modify an input_text of entity_ids and pass that to the light.turn_on service call
So I trying to get my Google home to respond based of a sensor value but I don't understand and have hard time figure it out I have a script that is this ```service: tts.google_en_com
data:
message: blodsockret är {{states('sensor.last_glucose_level_mmol')}}.
cache: false
But I don't get it to run
You need to quote templates
service: tts.google_en_com
data:
message: "blodsockret är {{states('sensor.last_glucose_level_mmol')}}."
cache: false
Not that one
Also, check your log for errors or warnings
You only need to quote it if the {{ is at the beginning to avoid it looking like a dict
Ah, interesting
Still, the log will help here
Probably ||the lack of a media player target||
And 'don't get it to run' is void of any detail
Of course I forgot the media player target
Ok got this and the script runs without any error ```service: tts.speak
: {}
entity_id: tts.bs
data:
media_player_entity_id: media_player.kok
cache: true
message: >-
service: tts.google_en_com data: message: blodsockret är
{{states('sensor.last_glucose_level_mmol')}}. cache: false
that looks badly formatted
Well got it working now so I'm happy 🙂 now I'm just wondering if I'm able to take the sensor value and divide it or is it not possible to do math calculations?
If you covert the state to a float with |float(0) you can perform math on it
So if I want to devide it by 10?
Do that
I realise I want to make a helper because I need to use it in my dashboard
But I can't grab my head around it how to do it
math is done the same pretty much everywhere
there are also docs in teh topic
here
{{ states('sensor.last_glucose_level_mmol')|float(0)/10 }}
Dear all, how would I go about updating the icon_template variable to the new schema?
- name: "Charging time remaining"
unique_id: "x5_xdrive50e_custom_charging_time_remaining_formatted"
state: >
{% if is_state('sensor.x5_xdrive50e_charging_end_time', 'Unknown') %}
{{ '' }}
{% else %}
{{ states('sensor.x5_xdrive50e_charging_time_remaining') | int | timestamp_custom('%H:%M', false) }}
{% endif %}
icon_template: >-
{% if is_state('sensor.x5_xdrive50e_charging_end_time', 'Unknown') %}
mdi:clock-outline
{% else %}
mdi:clock-end
{% endif %}
icon_template doesn't seem to be support as it used to, anymore.
From the docs: https://www.home-assistant.io/integrations/template/#icon
I've looked through but failed to find it. Now I see there was even an example
Thank you and sorry for a simple solution I could have found myself.
Didn't use the right keywords...
@inner mesa thank you, now I just need to figure out how to take down some decimals
|round(2)
{{ states('sensor.last_glucose_level_mmol')|float(0)/10|round(2) }} is that correct?
You need to add parentheses around what you're rounding
Is there anyway to respond to the Google home you ask or do it need to be a fixed media player
https://i.imgur.com/P0ni2TO.png
How would I test if the time variable is in the future, vs. past+now?
@undone jungle I converted your message into a file since it's above 15 lines :+1:
I'd like to expand the first statement to include situations when the variable for charging end has passed, since the integration doesn't nullify the sensor when the charging is done.
Technically what is already in the if should suffice, but I am not 100% if there is some delay in the charging status updating, while the time sensor is already changing.
I have made a work around by using routines and ambient sounds.
The question triggers a routine which activates a script and starts playing an ambient sound (like white noise).
In HA you can then see which player is playing the ambient sound, and target the response to that player
That sounds advance and vill take a while to get a response then
But rly cool
I got some great help the other day, thanks. But now I end up with an other problem.
I have a slider where I set the hour when my sons computer will turn off. At normal schooldays that is 21:00, but friday and saterday it's 23:00:
And my son wants a 5 min heads up from Google Display. And I set up an automation that worked during the week.
The template I use to get the correct time is
{{ today_at(states('input_number.computer_time_stop')|int|string + ":00") - timedelta(minutes=5) }}
But this friday I extended his time to 24:00 and that's the same as 00:00. But computers do not think 24:00 exist.
I thought if I could subtract 1 hour and add 55 minutes and delete the timedelta part. But I can't figure it out...
Anyone has a good idea?
23:59?
The "problem" is that the slider is from 1 to 24, so that's the value I have to work with
But correct 23:59:59...
Why not use a time helper rather than a number helper.
I need the number 1 to 24 to send to Microsoft ActiveDirectory that I use to change his logonhours.
And it's easy on the phone to use slider to extend the time...
is this the way to use response_variable:
- service: shell_command.my_command
data:
response_variable: my_command_response
- service: input_text.set_value
data:
entity_id: input_text.response
value: "my_command_response: {{ my_command_response['stdout'] }}"
I think it should work but the input text is just blank.
response_variable is not within data
metadata: {}
data:
folder: "{{folder}}"
response_variable: response
I see. I fixed it, but still something is wrong. Its not setting. (it works without the template)
You could do this: '24:50:00' | regex_replace('^24', '00')
@undone jungle I converted your message into a file since it's above 15 lines :+1:
is this new to to logger?:```
Error while processing template: Template<template=({% if states[config.entity] is not none %} {% set id = state_attr(config.entity,'friename').split('hygro')[0] %} {{id}} {% else %} Initialiseren {% endif %}) renders=6>
Error while processing template: Template<template=({% if states[config.entity] is not none %} {% set id = state_attr(config.entity,'friname').split('hygro')[0] %} {{id}} {% else %} Initialiseren {% endif %}) renders=6>
Error while processing template: Template<template=({% if states[config.entity] is not none %} {% set id = state_attr(config.entity,'frname').split('hygro')[0] %} {{id}} {% else %} Initialiseren {% endif %}) renders=6>
Error while processing template: Template<template=({% if states[config.entity] is not none %} {% set id = state_attr(config.entity,'fname').split('hygro')[0] %} {{id}} {% else %} Initialiseren {% endif %}) renders=6>
Error while processing template: Template<template=({% if states[config.entity] is not none %} {% set id = state_attr(config.entity,'name').split('hygro')[0] %} {{id}} {% else %} Initialiseren {% endif %}) renders=6>
check the friendly_name it is parsing, character by character
You don't need to convert everything to a timestamp.
And know that last_changed is reset when you restart HA
state: >
{% set charging_start_time = states.binary_sensor.x5_xdrive50e_charging_status.last_changed %}
{% if is_state('binary_sensor.x5_xdrive50e_charging_status', 'on') and now() > charging_start_time %}
{{ (now() - charging_start_time).total_seconds() | int }}
{% else %}
0
{% endif %}
The problem I am trying to resolve is to determine the start time, while the BMW integration is terrible at timely updates.
Some entities pop in to the next state immediately, some even spam the same information, but others update way way to long to be useful.
- name: "Charging time remaining X5 50e formatted"
unique_id: "x5_xdrive50e_custom_charging_time_remaining_formatted"
state: >
{% if is_state('binary_sensor.x5_xdrive50e_charging_status', 'off') or states('sensor.x5_xdrive50e_charging_end_time') in ("unavailable", "unknown") %}
{{ '' }}
{% else %}
{{ states('sensor.x5_xdrive50e_charging_time_remaining') | int | timestamp_custom('%H:%M', false) }}
{% endif %}
icon: >-
{% if is_state('binary_sensor.x5_xdrive50e_charging_status', 'off') or states('sensor.x5_xdrive50e_charging_end_time') in ("unavailable", "unknown") %}
mdi:clock-outline
{% else %}
mdi:clock-end
{% endif %}
Would it then make sense to use this sensor for formatting the time stamps ?
@leaden swan I converted your message into a file since it's above 15 lines :+1:
How can I add a default to the following template (to account for initial errors when last_triggered is none)? I've tried a number of things I've found in the forum, but none have worked. Thanks! {{ now() - state_attr(this.entity_id, 'last_triggered') > timedelta(hours=3) }}
you can use this.attributes.last_triggered instead of using state_attr(). That attribute will always exist.
It will be none when the automation didn't trigger yet, so I would do this
{% set lt = this.attributes.last_triggered %}
{{ lt is none or now() - lt > timedelta(hours=3) }}
That works... thanks!
Hi all. Trying to create my first custom sensor but doesn't seem to be saving? I've verified that the code works in the template area but when I add the code to configuration.yaml and restart, the new sensor isn't showing in entities. Do I need to do any additional steps? From what I've looked at, I was assuming I wouldn't need to do anything more.
Share the code
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language, and consider picking a longer expiry)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
The sensor's state is definately unknown when away and numerical if present?
I just put exactly that in my config and it works fine:
Yes, confirmed
I don't have those entities, of course
Odd. Not working for me, even after multiple restarts and closing browser window and re-opening
What were the exact steps you took after altering config.yaml?
I already have template entities, so I pasted it in my templates.yaml and reloaded template entities
I suggest looking at the HA logs
should I have a templates.yaml? Because I don't.
you don't need it
ok and probably one more noob question, sorry. where do i find the logs? 'Logbook' doesn't seem to be the right place to look
This would create a binary sensor for presence. Does that work for you?
template:
- binary_sensor:
- name: "Adam Car Presence"
unique_id: 51639777-f8dc-4252-8c8f-b0a255fa220e
device_class: presence
state: "{{ states('sensor.esphome_web_f0c630_ultrasonic_sensor')|is_number }}"
Yeah. just realized that when pasting 🤣
I can't point out what's wrong if you keep fixing it 🙂
-> System -> Logs
I got it working. I needed a full restart rather than just the light yaml restart.
Thanks for your input!
Still learning, so good to know. I'll now know the difference in saying reload and restart. Thanks.
I sure wish that logs like this told you what entity it's rendering when it encountered the error:
2024-02-12 16:14:37.419 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'presence' when rendering '{{ value_json.presence }}'
I know that it's an MQTT discovered entity because I've seen them before, and I know that it's from ESPresence because I just do, and I was able to able to search in MQTT Explorer to find the entity that it's referencing and fix it, but man, it's way too hard
- condition: template
value_template: >-
{{ (now() -
states.device_tracker.dave_location_tracker.last_changed).total_seconds()
> 60 }}
alias: Prevent rapid home/away state changes from causing nuisance door openings
Can someone help me sort this template, it was my attempt to prevent my garage door from opening when we're leaving due to a new quirk where the state changes fromnot_home to home momentarily when we're leaving.
Unfortunately, the above template also prevents the automation from running when it is triggered bydevice_tracker.dave_location_tracker changing from not_home to home.
Is there a way I can get it to return false if there has been a previous state change from home to not_home within the past 60 seconds?
It seems like you just need to fix your trigger: https://www.home-assistant.io/docs/automation/trigger/#holding-a-state-or-attribute
that was my first thought too but adding delay to the garage door opening would be annoying. I haven't yet figured out if the 'bounce' is always immediate or not, hence using atime as high as 60 seconds
from today's logs, the location changed back to home 6 seconds after going to away. even having a 10second hold on the attribute would mean waiting in front of the garage for it to work
oh wait... I see there's more reading to be had. "You can also fire the trigger when the state value changed from a specific state, but hasn’t returned to that state value for the specified time."
trigger:
- platform: state
entity_id:
- device_tracker.dave_location_tracker
from: not_home
to: home
"Please note, that when using from, to and for, only the value of the to option is considered for the time specified."
I'm still not seeing how I can do that from the trigger witout introducing a delay.
seems like you've tackled a similar problem before: https://community.home-assistant.io/t/trigger-automation-if-previous-state-for/451275
Only the coffee rosetta is changed...
maybe this?
{{ trigger.from_state.last_changed > utcnow() - timedelta(seconds=60) }}
did some testing, this seems to work:
{{ trigger.from_state.last_changed < now() - timedelta(seconds=60) }}
Had my sign backwards and not sure that utc is needed.
@terse nymph Do you need the tilted status or would it be sufficient to be an icon? This would be my suggestion with a tilted icon and the status as attribute (just in case)
https://dpaste.org/VF4wM
You can change the window icons, if you prefer the US style windows
Hope I understood it correct 😆 - This one can be grouped with any other door/window sensor and considers the window open, as long as it doesn't have the state closed
I have a binary sensor group with all window sensors. I get a notfication after a specific time on my mobile showing all open windows. The solution behind is template which expands the binary sensor helper group as a list. Problem was that i have also window sensors which are "normal" sensors and not a binary sensor. It was not possible to add them to the binary sensor group, means i was not able to show them in my notification.
In the meantime i was able to solve it. I have created a binary sensor template helper for those window sensors. (open = on / tilted and closed = off) https://dpaste.org/hUWxF
Yeah. Mine does basically the same, just with additional icons and the state as attribute
(and considering tilted as open)
Sorry, i consider tilted also as open like you. I have corrected my previous post.
A bit off-topic - which sensors are you using?
I've seen someone have an entity where it has the count of all lights on in the house. Where do I go to make such entity? I'm new to HA and don't see where to make it at, thank you!
Either in YAML or using a helper template in the UI (go to devices & services and select the “helpers” tab)
Hello everyone,
This is my first template after some searching.
My main objective is to set some valves on or off depending on the temperature (for now).
So i've created a script and I'll create an automation for every room and I'll set the state of that valve equal to the output of this script
My first doubt if I have to cast this variables to be float or is it done automatically.
The second, do you guys know if { value = true } turns a switch on? I can only send off on the developer tool
Template:
alias: "HVAC: Valve control"
variables:
valve_condition: |
{% if set_temperature < real_temperature %}
{% set valve = true %}
{% else %}
{% set valve = false %}
{% endif %}
{{ {'value': valve} }}
sequence:
- stop: End
response_variable: valve_condition
mode: single
icon: mdi:hvac
fields:
set_temperature:
selector:
text: null
name: Set temperature
description: Temperature set on thermostat
real_temperature:
selector:
text: null
name: Real temperature
description: Real room temperature
Sorry guys, any help? I'm really stuck on this
i have an entity that showing how much electricy is drawn and a graph below it. im trying so move the sensor value to the center using card_mod but i can't freaking do it. any ideas?
Seems like you're just asking questions without testing it?
Thanks, im a bit confused right now about every channel 😛
hi, so does restful sensor allow for templating in the payload like:
payload: >
{
"prompt": "magnificent scenery, wide landscape, sharp and crisp background, very beautiful landscape, fantasy, birdview, best quality, masterpiece, ultra high res, dark blue light, photo, photorealistic, wide view, kkw-ph1, professional shot of house, {{ state_attr('weather.forecast_home', 'forecast')[0].condition }} day",
"size": "512x512",
"model": "landscape-photoreal"
}
hey... I am trying to create a template condition for an automation. Currently, I'm able to check if a single condition is true, but how would I change it to: If <sensor> is any of (numbers in a list) then true
Currently have :
{{ states('sensor.openweathermap_weather_code') == '200' }}
This?
{{ states('sensor.openweathermap_weather_code') | int in (200,201,202,210,211,212,221,230,231,232) }}
That would work
I am using this one in my kitchen as i have two section of a window there: https://de.elv.com/homematic-funk-fenster-drehgriffkontakt-hm-sec-rhs-fuer-smart-home-hausautomation-076789?utm_source=google&utm_medium=cpc&utm_campaign=perfmax_shopping_de&refid=Gads&Gads_PerfMax_Shopping&gad_source=1&gclid=Cj0KCQiAw6yuBhDrARIsACf94RVBbz5wgXWnxSS5dzcySg82kVBB9fMx8RPFz-byiC1LQzs8Jxi03KwaAjkHEALw_wcB
@frank geyser here is some template code you can put into the template editor in developer tools. This could be simplified but I tried to keep each step with named variables so it would be a bit more clear what it was doing. You can modify this to fit your needs.
{% set feed_times = ['04:00', '10:00', '14:00', '23:00'] %}
{% set last_triggered = today_at('11:25') - timedelta(days=2) %}
{% set missed_feeds = 0 %}
{% set missed_days = (now().date() - last_triggered.date()).days %}
{% if missed_days %}
{% set missed_feeds_trigger_day = feed_times | map('today_at') | select('gt', today_at(last_triggered.time())) | list | count %}
{% set missed_feeds_whole_days = (missed_days - 1) * feed_times | count %}
{% set missed_feeds = missed_feeds + missed_feeds_trigger_day + missed_feeds_whole_days %}
{% endif %}
{% set missed_feeds_today = feed_times | map('today_at') | reject('gt', now()) | select('gt', last_triggered) | list | count %}
{% set missed_feeds = missed_feeds + missed_feeds_today %}
{{ missed_feeds }}
Oh wow, that's way more help than I was expecting, thanks so much!
I will have a proper dig into this on the weekend - for now I just added a http call out to some healthcheck service that will light my phone up like a christmas tree should the cat not get his biscuits 😛
Sounds good!
would you please tell me why this sensor returnr error ?
- name: "frontdoor Gesture"
unique_id: frontdoor_gestures
state_topic: "gestures/frontdoor_camera2"
value_template: "{{ value_json.gesture }}"
availability:
- topic: "gestures/availability"
json_attributes_topic: "gestures/frontdoor_camera2"
json_attributes_template: "{{ value }}" tojson }}"
Logger: homeassistant.util.yaml.loader
Source: util/yaml/loader.py:270
First occurred: 11:07:06 (5 occurrences)
Last logged: 11:14:08
while parsing a block mapping in "/config/mqtt.yaml", line 195, column 5 expected <block end>, but found '<scalar>' in "/config/mqtt.yaml", line 202, column 45
while parsing a block mapping in "/config/mqtt.yaml", line 195, column 5 expected <block end>, but found '<scalar>' in "/config/mqtt.yaml", line 201, column 45
while parsing a block mapping in "/config/mqtt.yaml", line 193, column 5 expected <block end>, but found '<scalar>' in "/config/mqtt.yaml", line 199, column 45
while parsing a block mapping in "/config/mqtt.yaml", line 193, column 5 expected <block end>, but found '<scalar>' in "/config/mqtt.yaml", line 200, column 45
i found it
json_attributes_template: "{{ value }}" tojson }}"
but what is the correct?
json_attributes_template: "{{ value_json | tojson }}"
????
The last one would at least be a valid Jinja template
But that will turn it into a string
Hi! Can someone help me with this config? Somehow the last_reset doesnt get set in my mqtt sensor entity:
- name: "Zelle 1" state_topic: "venus-home/N/xxx/battery/2/Voltages/Cell1" unique_id: zelle_1 value_template: "{{ value_json.value }}" icon: "mdi:battery" unit_of_measurement: "V" state_class: measurement last_reset_value_template: "1970-01-01T00:00:00+00:00"
Why would you need last_reset ?
On my MQTT sensors, I normally just use:
- name: "Syncback Home Assistant Backups"
unique_id: syncback_home_assistant_backups
state_topic: "syncback/home_assistant_backups/status"
value_template: >
{{ value_json.state }}
json_attributes_topic: "syncback/home_assistant_backups/status"
Which puts all the values from the json into the attributes.
It is clever enough to only put the state value in the state.
Thank you guys! Deleted some if the config items and now it works!
@undone jungle I converted your message into a file since it's above 15 lines :+1:
This sensor returns TypeError: unsupported operand type(s) for -: 'str' and 'datetime.datetime' and I can't seem to locate the issue
@marble jackal assisted in putting it together a few days back, but I am not sure if he's around today.
Ow Hi 😉
The issue is definitely focused around the subtraction of date from date, but not sure what I am doing wrong.
You changed the reference to last_changed to a sensor state
Which is a string instead of a datetime object
What is the state of that sensor?
Use as_datetime on it to convert to a datetime object
It's a string, all entity states are strings
{% set charging_end_time = states('sensor.x5_xdrive50e_charging_end_time') | as_datetime %}
as_datetime as an output filter, correct?
Yes
One down, and last to go, since the output format still doesn't want to agree here:
EDIT: Sensor name changed and was giving issues - NEVERMIND!!
You could use | as_datetime(now()) to prevent errors when the entity is not giving a valid state
Oh wait, you already test on that
You could remove the whole if statement if you do that
Do note you have to be in 2024.2 for that
@undone jungle what is the state of that sensor when that binary sensor is off?
Can someone explain to me why the first one (which is the recommended approach in the docs) returns None, and the second one returns the right value?
{{ state_attr('binary_sensor.kitchen_presence_sensor_presence', 'last_changed') }}
{{ states.binary_sensor.kitchen_presence_sensor_presence.last_changed }}
last_changed isn't an attribute but part of the entity object. The first is a python function to access the attributes, the second accesses the objects directly
got it, thanks. Is there an alternative way then to avoid using the states.binary... since the docs recommend to avoid it?
I think the warning is directed to accessing states and attributes from the entity object not to other parts. But I could be wrong there
You're correct Bas
state_attr() is recommended because it avoids errors when you try to access an attribute which doesn't exist, eg during startup or when an integration fails
But as last_changed is not an attribute, there is no other way to access it
guys, I don't understand :
template:
- sensor:
- name: "HD462 Status"
unique_id: hd462_status
icon: >- # always shows mdi:printer-3d-off
{% if is_state_attr('sensor.hd462', 'print_stats.state', 'printing') %}
mdi:printer-3d
{% else %}
mdi:printer-3d-off
{% endif %}
state: "{{ state_attr('sensor.hd462','print_stats.state') }}" # does not work
# state: "{{ states.sensor.hd462.attributes.print_stats.state }}" # works, but deprecated
NB: hd462 is a rest entity from a klipper 3d printer api json, no issues there, but all values in attributes
Does this work?
state: "{{ state_attr('sensor.hd462','print_stats').state }}"
You can't combine a fixed value of the icon with a template
That will output 2 icons
And your indentation looks off
yup, thank you very much
i don't understand, sorry
so, I can't change the icon from the attibute value ?
Sorry, the comment overflowed to the second line and confused me
You need to fix the state_attr() call as you did above
I see
state_attr('xxx', 'yyy').state == 'printing'
template:
- sensor:
- name: "HD462 Status"
unique_id: hd462_status
icon: >-
{% if state_attr('sensor.hd462','print_stats').state == 'printing' %}
mdi:printer-3d
{% else %}
mdi:printer-3d-off
{% endif %}
state: "{{ state_attr('sensor.hd462','print_stats').state | default('unavailable') }}"
this seems to work as I want
thanks everyone
Same here 😅
so?
Do you mean this pair?
https://i.imgur.com/jFpr2IW.png
https://i.imgur.com/RJN8iKO.png
When charging state is not charging i.e. OFF the times become unknown
There is also a plug related state:
https://i.imgur.com/3I8JWn5.png
May I ask why you ask?
would you please be more specific as i dont understand ?
to_json is used to create a json string
It will not be a dictionary or list or whatever anymore, just a string. So you can't take objects out if it anymore
Because you can really simplify your template then
Do tell 🙂
{% set n = now() %}
{% set charging_end = states('sensor.x5_xdrive50e_charging_end_time') | as_datetime(default=n) %}
{{ (charging_end - n).total_seconds() | int }}
Probably need as_local in there?
I'll think about it, though since it works now and is a bit more robust (if the sensor become strange in their outputs), I may leave it be...
Thank you for another valuable templating lesson though (I'll store it for later) as I have created several other sensors from 'rejected' ideas you've shown me.
I am actually seriously considering adding 2 staggered trigger to this sensor, since I have had an issue today when the chanring_end_time didn't trigger from unknown to date while the state of charging become ON so it was still showing a 0 for both end and elapsed sensors.
#1 trigger would be to check the change of charging sensor state from off to on and then every 5 min for 3 hours as timed trigger, to make sure the end time is updated.
The sensor will not update if just the charging state is the trigger, so it also needs to rely on the end time
The screenshot showed a timezone
Ah, I usually ignore those 🙂
I copied the code of a developer's project
he is saying to integrate the app with home assistant use a mqtt sensor.
mqtt:
sensor:
- name: "Garage Gesture"
unique_id: garage_gestures
state_topic: "gestures/garage"
availability:
- topic: "gestures/availability"
value_template: "{{ value_json.gesture }}"
json_attributes_topic: "gestures/garage"
json_attributes_template: "{{ value }}" tojson }}"
when I test configuration it gives me the following error
So I guess the project is abandoned and the code has changed ....
under mqtt explorer looks like this
https://pasteboard.co/wueGiAK5pBSe.jpg
would you please help me adjust it ?
That last line doesn't make any sense. It has an unmatched quote in the middle, and an unmatched }}. It's broken syntax
οκ. pls see image from mqtt explorer
how can I grab gesture value???
like this?
json_attributes_template: "{{ value_json | tojson }}"
noone?
No
🙂
it seems everybody is busy tonight 🙂
No, just hoping you'd figure it out
@inner mesa please don't hurt me
{{ value_json.gesture }}
I have figure out many more difficult things
am just confused because the programm owner is what it says
great!!! Most of the times, the problem is that we are reading wrong documentation.
if we are lucky and we find the right one, then things are easier
so i have two incoming values coming
can i insert them as attributes to a sensor ??
they are not nested
Clicking the 'Template' link here would have brought you there:
Actually, I see that you already had that in value_template
is this on the link above ?
Why are you trying to put it in an attribute too?
It's the documentation for an MQTT sensor
It's the same value in two places
e.g. if person = makis and gesture = stop then
do i have to create two sensors ? this is what am asking
or can i import as attributes in one sensor ?
just realized that this {{states.light |map(attribute='entity_id') |select('in',integration_entities('homekit_controller')) |select('has_value')|list}} is more restrictive than ``` {{expand(integration_entities('homekit_controller'))
|selectattr('domain','eq','light')
|map(attribute='entity_id')
|select('has_value')|list}}
ever since the expand on the integration entities were possible, I use those in many auto entities cards... thinking those states.xxx templates were costly.
checking the mentioned states these templates 'watches' the version shows all domain entities in the list, even though the output of the template is correct, and identical to the states.light version, but that only lists light entities.
I'm activating a script from the frontend with a tap_action, and also using service_data to specify variables to pass to the script. The script activates but does nothing, the variables still look unset?
Call script with variables from frontend
How do I add spaces in front of the first dash? It's getting stripped {{" - " + ( state_attr('sensor.utilgjengelige_entiteter','entity_id')|join('\n - ')) }}
what are you trying to do?
Create a list of unavailable entities I can copy paste directly into yaml 🙂 So every entity needs about 5 spaces, then a dash and then two spaces in front.
It works for every entity except the first one
why 2 spaces after the dash? and an odd number of spaces before it?
I'm gonna copy it directly into a package.yaml. For it to be indented correctly it needs 2 spaces after dash and 6 before it.
I'm listing ignored unavailable entities
there is no yaml syntax which requires 2 spaces after the dash
Hehe, you're right. I meant 1. 🙂
I was thinking of the usual amount of spaces when indenting
but anyway, the template editor trims strings before it outputs them, if you just add any other text on the first line, and your template on the second line, you will be able to copy it
you could also not include the spaces before it, and copy it in VSCode or File Editor. Select the text block and press tab
That will indent all selected lines
or CTRL+]
that's actually better, it will indent with 2 spaces
The template editor fooled me. Thanks 🙂
the template editor is not fooling you, it is giving you the output as it would if you'd use it in an automation or script or whatever
Ok. I intend to use it as a notification in HA but it looks like - is interpreted as a dot
Since it supports markdown... hmm
I escaped it with \ before the dash. Unfortunately it doesn't include all the spaces it seems. But it's ok, I'll do the tab method in File editor. 🙂
Is there a way to make a template that gets a count of a specific device family for example TP-Link
Do you mean a specific integration?
So without proper knowlegde im building from scratch a gasprice sensor, since DutchGasPrices addon is broken for the time being. Their source is blocking too many api calls.
each sensor outputs like this so far:
{'organization': 'Tango', 'gps': [52.160441, 5.398098], 'address': 'v Randwijcklaan 8', 'town': 'Amersfoort', 'price': 1.919}
Which is well. Not really what i want. I would like the Price as sensor value and the remaining data as attributes...
Any way to rewrite this?
https://dpaste.org/AUkWc
my knowlegde kinda ends here lol
For the number of devices integrated through the TP-Link Smart Home integration:
{% set ns = namespace(dev=[])%}
{% for ent in integration_entities('tplink') %}
{% set ns.dev = ns.dev + [device_id(ent)] %}
{% endfor %}
{{ ns.dev|unique|list|count }}
for my mockupancy scripts I use{{state_attr('light.home_mode_locked_lights_2','entity_id')|random}} but I just noticed this can return a light that is unavailable. Can we reject those unavailables and still use |random?
Hello. I want to get unique items in my list. I saw the filter for unique but just want to check what it does?
[ Washing Machine, Vacuum, Vacuum]
Would this be a list of 2 if list | unique
assuming you quote the items properly, yes
you can test it in
-> Templates
also described here in the Jinja docs: https://jinja.palletsprojects.com/en/3.1.x/templates/#jinja-filters.unique
You could do this:
{%set ns = namespace(a=[])%}
{%for item in state_attr('light.home_mode_locked_lights_2','entity_id')%}
{%if not is_state(item,'unavailable')%}
{%set ns.a = ns.a + [item] %}
{%endif%}
{%endfor%}
{{ns.a | random}}
You could also just select by has_value:
{{state_attr('light.home_mode_locked_lights_2','entity_id')|select('has_value')|list|random}}
right! that is what I was trying to do, but didnt get the syntax right.. works! thx (both of you 😉 )
found a template/automation that seems to sometimes fluke and go crazy:```
Logger: homeassistant.helpers.event
Source: helpers/event.py:296
First occurred: 14:07:35 (20467 occurrences)
Last logged: 14:10:10
Error while dispatching event for automation.count_errors to <Job track state_changed event {'automation.count_errors'} HassJobType.Callback <bound method TrackTemplateResultInfo._refresh of <TrackTemplateResultInfo {Template<template=(:host { color: {% set state = states(config.entity) %} {{'pink' if state == 'on' else 'brown'}}; }) renders=22753>: <RenderInfo Template<template=(:host { color: {% set state = states(config.entity) %} {{'pink' if state == 'on' else 'brown'}}; }) renders=22753> all_states=False all_states_lifecycle=False domains=frozenset() domains_lifecycle=frozenset() entities=frozenset({'automation.count_errors'}) rate_limit=None has_time=False exception=None is_static=False>}>>>```
not sure if this is a template issue or automation...but starting with template. What could be done here?
happening on ```
filter:
include:
- domain: automation
options: {card_mod: !include /config/dashboard/card_mods/binary_state_color.yaml}
maybe try an even simpler template: style: | :host { color: {{'pink' if is_state(config.entity,'on') else 'brown'}}; } and use the is_state() syntax
hi all, so got an automation that has a couple of choose options based on trigger IDs. For one of the trigger IDs, how can I put a condition that it only runs at most once per 30 mins. I know how do this for the entrie automation, but not sure how to do it for a specific trigger in the automation.
- condition: template
value_template: >-
{{(as_timestamp(now()) -
as_timestamp(state_attr("automation.turn_on_lights_open_shades_tts_broadcast",
"last_triggered") | default(0)) | int > 21600 )}}
if don't want to affect other triggers, I would just create a separate automation for it
it's the simplest way to do it
that is true
then just put a delay at the end of that other automation
based on your example, and assuming that's in the action section somewhere, I would expect that template to never be true because it always just triggered
oh good to know, that example is for another automation that I have. Its in the global condition of the automatoin not in the action
global meaning the main condition(s)
if that is right word for it
Got this error sometimes wen sensor climate is unavailable at startup "ERROR (MainThread) [homeassistant.helpers.event] Error while processing template: Template<template=({{ state_attr('climate.vicare_heating', 'room_temperature')|float/ 25}}) renders=2>".
Why do's it say it don't have a default, i think it's available from the template?
sensors:
temp_woonkamer:
unique_id: bf356442-4d88-4f05-8078-3d1e0ed5538d
friendly_name: "Woonkamer temperatuur"
value_template: "{{ state_attr('climate.vicare_heating', 'room_temperature') | float(default=0) }}"
unit_of_measurement: "°C"```
It clearly states which template it uses, and it's not that template
This is the template which is causing the issue, and this template doesn't have a default
{{ state_attr('climate.vicare_heating', 'room_temperature')|float/ 25}}
Well i searched for that template with Studio Code Server and it can’t find that anywhere?
Maybe in a GUI created template helper?
Good catch! It was indeed inside a graphics circle complication for the Apple Watch.
I have a sensor.woonkamer_temperature and trying to make a min and max template sensor. Any one can share and example how to achieve this.
Why not use a Statistics sensor https://www.home-assistant.io/integrations/statistics/
sensor:
- platform: statistics
name: Max temp woonkamer
entity_id: sensor.woonkamer_temperature
state_characteristic: value_max
max_age:
hours: 24
- platform: statistics
name: Min temp woonkamer
entity_id: sensor.woonkamer_temperature
state_characteristic: value_min
max_age:
hours: 24
For example
Thanks allot TheFes!
Btw, i thought that this format is still working but not longer recommended?
This format still works but is no longer recommended. Use modern configuration.
This format is configured as a platform for the binary_sensor integration and not directly under the template integration.```
They are not template sensors, they are Statistics sensors.
That's unrelated to statistics
I wouldn't be surprised if all integrations move away from the platform: syntax eventually, but they're all independent
Oh sorry true, stupid to doubt TheFes 🙂
{{ states.sensor | rejectattr('attributes.device_class', 'undefined') | selectattr('attributes.device_class', 'eq', 'power') | rejectattr('attributes.unit_of_measurement', 'undefined') | rejectattr('state','in', ['undefined','unavailable']) | selectattr('attributes.unit_of_measurement', 'in', ['W', 'kW']) | rejectattr('entity_id', 'search', 'shellyem3') | rejectattr('entity_id', 'search', 'total_power') | rejectattr('entity_id', 'search', 'power_production') | sort(attribute='state', reverse=false) | map(attribute='entity_id') | list() }}
the sort isn't working, any idea what i have done wrong 🙂
trying to sort after which one uses the most power
states are strings, so I suspect it is sorting 1,100,1000,2, etc.
well if it just was that, but i se no sort at all...
Start by removing () after list
no difference for me
@frail hawk I converted your message into a file since it's above 15 lines :+1:
Working fine here (besides that sorting strings doesn't make sense)
Replaced map(attribute='entity_id') with map(attribute='state')
i can se that, but that i can't feed into a card, then there is no names... but trying 🙂
What purpose does sorting serve there?
to get the entity that uses most power on top of the list
am trying todo what he does here https://seanblanchfield.com/2022/05/real-time-device-power-meters-in-home-assistant, just with auto entities instead, so it will automatic pick up all 🙂
but don't think i'm able todo the two items together the way i wanted to 🙂
Try this to check your values
@lyric comet I converted your message into a file since it's above 15 lines :+1:
think i need the bar-card modifies to support the template for the entities input to get it to work 🙂
hmm.... actualy its the config-template-card that does the sorting... ok, need to look more into that then... hmmm... well thanx for the help anyway 🙂
If you just want to view and sort, you could just look at the flex-table-card from hacs if might well give the sorted list.
i'm trying to make a list of automatic genrated entities with power, sorted by what they use... the url i posted higher does it, but i have to add all the enties manual... i wanted not todo that 🙂
but will take a look on that one
auto-entities actually has a sort option
You can sort by state and indicate the state is numeric, so it won't sort them wrong
hmmm need to look into that 🙂 thanx
You actually already have that in your config, you're sorting by name
sort:
method: name
sort: method: state numeric: true reverse: true
that worked 🙂
to bad, that max: ${ Math.max(...vars.map(v => states[v.entity].state))} only works on the config-template-card and not on this way todo it 🙂
In a yaml of a service, how can I include if then of jinja2?
I implement it it works but I can't save the file. After refreshing it;s gone
I'm talking about things like this:
{% if state_attr('light.floor_lamp_left','min_color_temp_kelvin') >= state_attr('light.floor_lamp_left','color_temp_kelvin') -%} Yes {%- else -%} No {%- endif %}
And replace yes and no with some command to set the color temperature
You can not put service calls in a template. You can set a variable at the start of an automation and condition your automation on the value. Services do not have Yaml.
I see, is there a reason behind it?
Yes, that is how Home Assistant works.
Of course as a workaround I can separate the steps and use the if then else outside calling a service. but then I have some duplicate parts
No. You can set the variable then use if with a script or automation variable. Templates are used as the inner level within automations, sensors or scripts.
{{state_attr('light.floor_lamp_left','min_color_temp_kelvin') >= state_attr('light.floor_lamp_left','color_temp_kelvin') }}
I think you need to spend sometime reading up on the concepts of the different building blocks rather than trying to fight against it.
So I should look up automation variable?
Yes, and watch some of the 101 type videos to learn to write automations and scripts. They should always be your starting point.
Thanks I will read on that
Hopefully I can create variable in the automation on the fly and it only persisits while the automation is triggered and running
Otherwise it can be a pain to manually create these and also see them in the entities
variables are local to the automation or script.
that's great 😁
I had this concern since home assistant is definitely not always very intuitive to me
Try watching this for some basics: https://www.youtube.com/watch?v=QlYjuXLRJJg&t=36s
You can template most of the service call, but not the entire YAML
service: "{{ template}}"
target: "{{ template2 }}"
data: "{{ template3 }}"
Where template2 and template3 should return a dict
Basically I tried your template3 part, but it did not save the files.
I can run it on the go. But if I save it and refresh then it's gone
No error messages
Not sure what you mean here,
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language, and consider picking a longer expiry)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
Can you share your automation/script
I suspect there was an error in the automation somewhere so it did not save.
TheFes, any idea why the max template sensor works but the min still shows 0,0.
Because your temp sensor has been 0 in the last 24h?
This is what I meant:
service: light.turn_on target: entity_id: light.floor_lamp_left data: transition: 1 if cond1 color_temp_kelvin: val1 elif cond2 color_temp_kelvin: val2 else color_temp_kelvin: val3 endif
So it's a if else inside the data. And I can run this part with no error, but once it's refreshed it's gone
So what you really mean is a single key with a template as its value
That is not valid YAML
Which is supported and easy
yes it's really just about setting color_temp_kelvin
Well the value of the entity_id: sensor.temp_woonkamer dropped from 20.3 to 20.1 so I thought this will update the min temp sensor?
service: light.turn_on
target:
entity_id: light.floor_lamp_left
data:
transition: 1
color_temp_kelvin: >
{% if something %}
{{ val1 }}
{% elif something_else %}
{{ val2 }}
{% else %]
{{ val3 }}
{% endif %}
The config I posted will give the lowest value of the last 24h. If that is lower than your current value, it will not change state
If it shows 0.0 I would say your temp sensor has had 0.0 as its state in the last 24h
I see, so color_temp_kelvin should be outside?
It is a key and you are tempting the value
I see, makes sense. though I still don't get why the way I wrote it doesn't work
Ah that make sense, thanks again!
You cannot template individual keys like that. You would have to template the entire data section
Just the way it is
All right, thanks
For the template, is there a way to write it in a different grammar/language? I have little jinja2 experience. And for now I find the way to formulate things are quite let's say detailed
No
all right thanks
Been told this is the correct place to ask this ... #general-archived message
I have an issue where my mqtt sensors are not providing the value. They worked fine forever, and the breaking changes didn't seem to point to why mine would break.
Appreciate any help.
Actually you would probably have been better off in #integrations-archived but to save you the hassle of being re-directed again (it is quiet in here), none of those are mqtt binary sensors. And I'm assuming that indentation of your mqtt sensors is a copy/paste mistake? Use MQTT Explorer to see what is being sent to the topics.
You should also remove this for all as it is not needed for power sensors last_reset_value_template:
Thanks Tom, I removed that last_reset_value_template and all is working again. Can't remember the reason that was in there, but all good now, thanks.
@shrewd moat I converted your message into a file since it's above 15 lines :+1:
@shrewd moat I converted your message into a file since it's above 15 lines :+1:
Hey, is it possible to use Template language in yaml config from mushroom chip cards? I put this in but the color doesn't change
icon_color: |
{% if states('sensor.total_lights_count_template')|int > 0 %}
yellow
{% else %}
pink
{% endif %}
how can i convert string to list
eg. "string1,string2,string3"
tried "{{ expand("string1,string2,string3") | list }}"
It works only with the mushroom-template-chip. #frontend-archived can help you further
"string1,string2,string3".split(",") | list
Thanks
ah thanks got it working 🙂
Is e template function available that checks if it starts with a string (MyWiFi), instead of repeating it 3 times like this:
...
{% if (states('sensor.samsung_s24_ultra_wifi_connection') == "MyWiFi") or ((states('sensor.samsung_s24_ultra_wifi_connection') == "MyWiFi - IoT")) or ((states('sensor.samsung_s24_ultra_wifi_connection') == "MyWiFi - Public")) and ((states('sensor.samsung_s24_ultra_public_ip_address') == "123.123.123.123")) %}
...
{% if "MyWiFi" in states('sensor.samsung_s24_ultra_wifi_connection') %}
Thanks!
- string1
- string2
- string3```
That is just a representation of a list, it might be worth explaining how you are trying to use the list.
target:
- string1
- string2
- string3```
If you need to check if it only begins with it you can do either of these options:
states('sensor.samsung_s24_ultra_wifi_connection').startswith('MyWiFi')
states('sensor.samsung_s24_ultra_wifi_connection') | regex_search('^MyWiFi')
I think
data:
target: "{{'string1,string2,string3'.split(',') | list}}"
should work.
will try thanks
Contains or starts with are both sufficient for my use case, thanks for the suggestion!
The list filter is not needed, splitting it will already make it a list
That must be a jinja only thing, split returns a tuple in python
it is, it returns a list in jinja
hmmm, nope python returns a list
when tf did they change that
sometime between python 2.5 and python 3.9
or maybe it's always been a list and I'm miss-remembering?
shout out to @mighty ledge and @marble jackal , I'm running my altered template energy sensors for a week now without any problems! real nice quick help guys!
@unborn bridge I converted your message into a file since it's above 15 lines :+1:
I am trying to do some WaterLeak senson automation; this is all done; however, I want to expose the Valve to HomeKit. In another case, I did this by creating a virtual switch and using a bridge. In those i was setting a default state of the switch to On using the code below. How can set the state of this switch to whatever the state of the valve is.
my_virtual_waterleak_switch:
value_template: "{{ is_state('input_boolean.my_virtual_waterleak_switch', 'on') }}"
turn_on:
service: input_boolean.turn_on
target:
entity_id: input_boolean.my_virtual_waterleak_switch
turn_off:
service: input_boolean.turn_off
target:
entity_id: input_boolean.my_virtual_waterleak_switch
The entiry id is
- platform: device
device_id: 50b3f5370d7547de60161bd7eb3a3759
domain: zwave_js
type: zwave_js.value_updated.value
I'm trying to set up a template to run the weather.get_forecasts service and extract data for use on an ESPHome project. I am having some issues, as I can't get the demo template sensor to show any values. It just says 'unkown'. I can call the service manually and see all the forecast data there. But it doesn't seem to pull into the tempate sensor. I can't test the template (I don't think you can test a template that calls a service?). The template always tells me that the response variable is undefined when I try to use it to set the sensor state when I use the template dev tool. I'm not sure how to figure out what is breaking.
For reference, the demo template sensor I'm trying is the one here: https://www.home-assistant.io/integrations/weather/
goodevening! i got a question regarding rest json sensors:
Its a giant list of gasstations. Each entry has town/price/address/gps_location.
im only interested in my own town Amersfoort. I made it this far: https://dpaste.org/5dSBW
This works. But it only shows the price of the cheapest. I dont fancy making loads of sensors this way, for addresses, gps_locs and prices.
I would like 1 sensor for one gasstation, with town/address/gps as attributes...
im stuck..
so if I understand correctly you just want to add attributes to your sensor?
Correct.
But json_atteibutes don't seem to work because I make a namespace first to sort them(I think)
can't you avoid using the namespace? that way you can indeed use the json_attributes
altough it should work even with namespace. That is used only in the template, right?
This is a little piece of a massive json
Let's just say the town Sneek has 5 gas stations. I want to know the top 3
Price as value, the rest in atteibutes
if you don't mind sharing the resource I can try to help
or is it an api paid service?
no but before its gonna get hammered and start blocking ips i rather keep it to my self for a bit
sure!
i pinged you
as you can see it has loaaads of gas stations
i would like a top3 of the town Amersfoort. Price as value, the rest as attributes.
json_attributes doesnt seem to work with attributes in them
else i could reuse the namespace thingy in there
Based on the information above, you can't really do anything with it in a rest sensor, attributes in a rest sensor need a key
At the moment in trying to dump the json to a file and go from there. A 'regular' sensor can do templated attributes right?
I'm hoping to just repeat my namespace thingy in each attribute and swap .price to .town etc
Yes, but you really don't need a namespace there
I have this template sensor:
{{ expand('binary_sensor.fenster_state') | selectattr('state', eq', 'on')
| map(attribute='name') | list | join (', ') }}
In case there is more than one window open i like to add a and between the list of sensors in my TTS
like window1 is open and window2 is open.
Can somebody help me how to adjust the template?
{{ value_json | selectattr('town', 'equalto', 'Amersfoort') | sort(attribute='price') | map(attribute='price') | first }}
That will give you the lowest price without the need for a for loop and namespace @acoustic arch
What do you want to achieve?
Window 1, window 2 and window 3 are open
or
Window 1 is open, Window 2 is open and window 3 is open
but i would also like price/address etc as attributes. Thats where the pain is atm
I want to achieve your first example a and between the last two sensors without additional text
Each attribute will need it's own template
but rest sensor doesnt allow for template attributes... right?
{% set open = expand('binary_sensor.fenster_state') | selectattr('state', eq', 'on')
| map(attribute='name') | list %}
{{ open[:-1] | join(', ') ~ ' and ' ~ open[-1] is open | count > 2 else open | join(' and ') }} {{ 'are' if open | count > 1 else 'is' }} open
Correct, I thought we were already past that
Thanks a lot, i will test it tomorrow.
- name: cheapest gas
state: "{{ template from my previous post }}"
attributes:
station: "{{ other template }}"
address: "{{ and another template }}"
@acoustic arch each attribute has its own template
In a template sensor
ok sorry for this novice question. But where to i fetch the json from then...
for the rest i understand what you are saying. I made similar sensors like this
thats in your rest
ok ill try in 5min
and paste what i did in dpaste
i pasted attributes for testing only. But they dont show up
(after reloading rest-enitities in dev-tools)
check your log for errors
Invalid config for 'rest' at configuration.yaml, line 104: 'attributes' is an invalid option for 'rest', check: rest->0->sensor->0->attributes, please check the docs at https://www.home-assistant.io/integrations/rest Invalid config for 'rest' at configuration.yaml, line 104: 'state' is an invalid option for 'rest', check: rest->0->sensor->0->state, please check the docs at https://www.home-assistant.io/integrations/rest
as far as i know, templating in rest sensor attributes is not implemented..... (?)
it's not, you have to use json attributes path to point to the object you want to display then use json attributes to output which ones you want
or put the contents of the value_json into an attribute and extract it using template entities
ok but thats something else than the Fes said... i dont think he knew i was fetching with rest i suppose
but can i get a path from the extracted item from the json? or only from the original source
i need the path from:
{{ value_json | selectattr('town', 'equalto', 'Amersfoort') | sort(attribute='price') | map(attribute='price') | first }}
json attributes path is a json path, it's designed to do whatever you tell it to do, it's just like the templates
just different syntax
ok so i need to template the path then
ok one step back. My rest source is a giant list. I need just ONE item, which is the lowest price. So Fes gave me {{ value_json | selectattr('town', 'equalto', 'Amersfoort') | sort(attribute='price') | map(attribute='price') | first }}
Works. i get the lowest price.
Now i need the Adress and Town of that item.
ok then just make 3 separate entities, one for each using that template
but change the mapped attribute
you either need to learn how to use json attributes path, or you need to go via separate sensors, or a single senosr that feeds a template entity
[{"organization":"TinQ","gps":[52.278169,4.513391],"address":"Provincialeweg N206 - 29","town":"Noordwijkerhout","price":1.979},{"organization":"Shell","gps":[51.33081,3.853431],"address":"Serlippensstraat 45","town":"Terneuzen","price":1.939},{"organization":"AVIA","gps":[52.43073,6.54053],"address":"Wierdenseweg 11 (N751)","town":"Daarle","price":1.929}]
lets say they are all in my town Amersfoort. My feeling is that json_path only looks at this original data, not the fetched data from the Fes
that's the whole point of json attribuets path
to filter down to what you want
so, instead of arguing, why not just try the json tester I posted above, take 10 minutes to learn how to use json path
once you filter it down to your town, you can then use json_attributes to get them as attributes
but i need all the data from the cheapest. Not just A gasstation
i can drill down to one no probs.
ah! ok
well there is some new info i didnt know
so i need to lean to write a path expression to first find the item with the lowest value inside town Amersfoort, then list the rest
thats gonna be a fun new hobby🫣
well, the basic is a drill down
thanks for the time so far! much appreciated
but you can also have it do fancy things like sorting and selecting based on names/types
that's about the extent of it's capabilities though
so i need to replicate template_value, but then in json path.... sort of
yes
got it!
it's dumb, but that's how it was originally designed
and then fetching the rest is easy