#templates-archived
1 messages · Page 66 of 1
sequence:
- service: notify.alexa_media_kitchen
metadata: {}
data:
message: Your next Recycling and Food Bin Collection is Wednesday
title: Next waste collection
target: media_player.kitchen
data:
type: tts
mode: single
icon: mdi:recycle```
if you put your code into either code blocks using like this, looks prettier
I also have a sensor called 'Next Waste Collection' which downloads the correct info. How can I get the text generated by the sensor into the message?
two of these `
Like so? 🙂
Like that?
even better
Now, onto my question 🤣
I thought (naively) amending the following to message: sensor.next_waste_collection would read out the string of that sensor. But alas, is just literally reads the line of text.
How can I make the message read out the line of text returned by the sensor I created?
Nevermind, I figured it out myself. It should read
{{ states('sensor.next_waste_collection') }}```
@wraith spade I converted your message into a file since it's above 15 lines :+1:
for that we would need to know what's in the blueprint
I would like to count how many persons who are in the group.smurf_drivers are home. This doesn't seem to work:
{{expand('group.smurf_drivers')|select('is_state','home')|count}}
if you expand the group, you will get the full state objects
either use:
{{ state_attr('group.smurf_drivers', 'entity_id') | select('is_state', 'home') | list | count }}
or:
{{ expand('group.smurf_drivers') | selectattr('state', 'eq', 'home') | list | count }}
Well, I could come up with some other variations on that which will also work, but I think those are the 2 most logical options
Do smurfs drive?
Smurf is our impossibly blue car
ok i see it -- groups have the list of entity_id's as an attribute
The main point was that the is_state test takes entity_id, not state objects
https://www.youtube.com/watch?v=9kEIPMQYV_U we had this commercial years ago in the Netherlands when the rules how to give priority to bicycles changed. So at least they seem to ride bicycles and mopeds.
yes, which makes this also a possible variant:
{{ expand('group.smurf_drivers') | map(attribute='entity_id') | select('is_state', 'home') | list | count }}
only during excessive complexity story time hour
too bad is_state isn't added as a filter, then you could do:
{{ state_attr('group.smurf_drivers', 'entity_id') | map('is_state', 'home') | sum }}
Hi, I need help adding multiple lights to this code. This is used in a template card to change the icon color once the light entity which is specified for this card is on but I would like the icon to show when any light for that room is on. I’m using template cards for the card that’s seen on the dashboard but when you click the cards within that room are light cards. How do I tell this icon to also respond to the other light cards in that room? Thanks.
{% if is_state('light.office_hue_group_1, ‘light.office_hue_group_2','on') %}
orange
{% endif %}
{% if ['light.office_hue_group_1', ‘light.office_hue_group_2']|select('is_state', 'on')|list|length > 0 %}
orange
{% endif %}
Oh great 😊 thank you Rob, I’ll try this
sorry, fixed
good morning, i created a few template helpers to grab attribute data from an entity. basically making the attributes their own entities so i can use the data in grafana
i seem to have an issue with the new helpers 'falling asleep' and not reporting data periodically. i'll look at my grafana dashboard and one or both of the template helper sensors are not reporting, when i goto the helper it looks like the last time it updated is hours ago, which leads me to believe it has some kind of timeout or lack of persistance
is this something that is common with template helpers? is there some way i can prevent the helper templates from 'falling asleep'?
This apparently isn’t working
grafana is polling all entities every 5 minutes so there shouldn't be an issue from grafana side
it will return true if any of the lights is on
so, it will result in 'orange' if that's true
It works if I have 1 entity like this…
{% if is_state('light.office_hue_group_1,'on') %}
orange
{% endif %}
they don't "fall asleep". they update when their consittuent parts update
You can verify that in HA
you'll need to explain how it doesn't work
Doesn’t change the icon at all using that code
This works
it will do exactly what I described
any of those lights are on, it will evaluate to "orange"
you can debug in
-> Templates
I’ll try that
oh, you need to add "if" to the first line
no
is there some way i can set them to update at a regular interval?
{% if ['light.back_door_infrared', 'light.back_porch']|select('is_state', 'on')|list|length > 0 %}
orange
{% endif %}
You can add a time_pattern trigger to the template sensors. But you shouldn't need to
as I mentioned, they will update when the entities they reference update
you can confirm that in HA
the only exceptions are when your template starts with states, where it will only evaluate every minute or states.domain, where it updates every second
TemplateSyntaxError: unexpected char '‘' at 35
{{ state_attr('sensor.servername_storage_c', 'UsedSpacePercentage') }}
that's the template sensor, does that mean it starts with states?
I copied it into my instance and it's fine
you'll need to debug it
Ok
no, it does not
Is there a possibility to force the "secondary" attribute in a mushroom template card to show a blank value (space), such that the card is not vertically shortened?
that's a #frontend-archived question
evening. how do you (in effect) join lists of entities? for example, how do i template to get a list of all light entities which are not in the living room area?
{{ states.light | map(attribute='entity_id') | reject('in', area_entities('living_room')) | list }}
That would do that, without the need to join lists
nice thanks
hi, pulling my hair out here with a blueprint automation which uses template conditions. i've read through and i'm sure things are correct but clearly they are not. and because its using a template as condition its seemingly impossible to troubleshoot it using trace.
the trace shows the result
yes and the result isnt what I want. i was hoping it would tell me which aspect is causing it
post the blueprint
or break up the template into separate variables in the variable section
or test the template in the template editor
there's multiple ways to test this
i tried to use the template editor but its not as simple as pasting it in there. i couldnt work it out
(couldnt work out how to declare the variables/inputs in there
well, you're shooting yourself in the foot
you're creating variables with the name time_to
in the variable section, and then you're trying to overwrite that in the condition
can't do that.
variables set in variables are set in stone.
outside that, you're using a ton of strings to compare times instead of datetimes
do the input_datetime helpers actually exist? or are the intentions to pull the time input into the blueprint selector?
Yeah, based on what I see, I think you have a misconception on what the blueprint selectors are doing. You seem to have a helper conveniently named after each selector, which is not how selectors work.
current time is pulled in with now() the time_to and time_from are there are a part of the condition to determine whether to run or not
lux_entity: lux_value: and ilum_entity are all optional, so the value for these is possible to be undefined/blank.
what i need the conditions to trigger on are as follows:
if time_use: is ON then ONLY consider the time aspects to trigger the automation actions.
if time_use: is off, then consider the time and all other conditions too, but effectively only trigger if one of the other conditions are true AND it is within the time frame specified.
the other conditions are ilum_entity and lux_entity and sun elevation. which should be all considered (if they exist as defined values)
oh and if the time_to and time_from are default values 00:00:00 then dont bother caring about time at all.
it all made sense in my head and now i'm trying to explain it and i'm getting myself in a tizzy 😦
i've not done this before (templates) and its getting a bit overwhelming
did you create this entity in the UI via the helper menu? input_datetime.time_to Yes or No.
or are you assuming that it's coming from this?
time_to:
name: 'Timeslot to'
description: 'Automation only activates before this time'
default:
selector:
time:
that's not how selectors work
ok
selectors do not create entities
this is grabbing an entities state states('input_datetime.time_to')
which does not exist for you
hmm ok back to the drawing board then
change your variable section to this
variables:
target_brightness: !input 'target_brightness'
target_color_temp: !input 'target_color_temp'
time_from: !input time_from
time_to: !input time_to
use_time: !input use_time
elevation_shift: !input elevation_shift
lux_value: !input lux_value
that will get all the values from your selectors so you can use them
then your template will be
actually, you need to add variables for all selectors that you made
can't i just refer to the !inputs directly instead of creating the variable?
aren't they themselves variables
If you want to use them in a template, they do
right ok
give me a moment
what is the light binary sensor doing
that doesn't make sense
it'll have a value of on or off
is that a flag to say "Use the lux entity?"
Yeah, I don't get that part at all, that doesn't make senes
You're trying to treat it like anumber. I'm going to remove it and just use the lux entity.
ok so i have a few light sensors... some which are normal ones which report the lux value , so those are to be used in the input for ilum_entity and value
and i have a few on esp devices which dont register the voltage/etc but they have a pot on them and will report on/off based on if a certain brightness is achieved (based on the pot adjustment)
so the automation allows for using one or the other and ignores the other in the conditions
does that make sense?
thank you thats really kind of you.
does that do what my orignal one was supposed to do? i can see you've very much simplified the conditions aspect. its just because with my weirdly specific list of conditions originally it seems that that condition wouldnt do all that? or is that all done elsewhere?
Well your logic was all over the place, I cleaned up the intentions and the code
lol yeah the logic in the code was, yes. ok thanks let me give it a test
gah why does raw.github always take ages to refresh after you make changes 😐
doesnt appear to be working still trace doesnt give much info
Stopped because of unknown reason "null" at 30 January 2024 at 22:18:56 (runtime: 0.00 seconds)
look in the logs, and check the outputs of each variable in the variable tab on the trace
fwiw the automation i'm testing it with has elevation shift set to -10 time from 01:00:00 , time to 23:00:00 .. tried with and without use_time on or off
the homeassistant.log logs
Sorry, I'm not going to play guess work, typical HA debugging is to figure out exactly what's wrong by looking at the returned variables and logs
i'm looking
how would one find the returned variables if they're not in the trace page?...
looking through the logs and its a huge mess of stuff which is above my paygrade. things are all over the place and i can't tell whats relavent and what isnt
just post the errors
raise ValueError(
ValueError: Sensor sensor.unavailable_entities has device class 'None', state class 'None' unit 'entities' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: '' (<class 'str'>)
2024-01-30 22:11:09.461 ERROR (MainThread) [homeassistant.util.yaml.loader] while scanning a simple key
in "<unicode string>", line 62, column 1:... thing
^
could not find expected ':'
in "<unicode string>", line 63, column 17:
target_light:
^
is one... but its immediately preceeded by a traceback
well the arrow is pointing to the underscore
unless that's not the full error, I can't tell because it looks like you truncated the full error
thats just one of the things which looks like it might be relavent... there are some stuff all over that mentions ValueError: could not convert string to float: ''
is the full error the traceback?
yes
try to run the automation from a known point in your logs as well
don't just guess
look at your logs, note the time, run the automation, grab relevant lines that point to things in the automation
ok
look, thanks for helping, I'm getting it in the ear from the wife now so i have to knock this on the head for now and i'll continue looking at it in the morning. really do appriciate the help and time
unless lounge_motion_lights is one of the automations
ok, where is test_none coming from? That's not something I added
did you change anything in the blueprint?
nope
if you did, post the blueprint here
just pasted it as it
is
check my link earlier for my github.. thats what its using, which is your code
unless its something mentioned in another blueprint i use ... is there a way of searching for it... is it an entity or something i've searched entities and dev states but nothing like tha
hi, is this correct please?
{{ (monthly_total_usage / 24) | round(1) | replace("."," κόμμα ") }}
Looks like you're trying to treat a floating point number as a string
yes, because Nabu Casa TTS for greek is crap
What does it say in
-> Templates?
it does work indeed
Then
I only asked for the parenthesis
You asked if it was correct
yes
maybe it needs another parenthesis ?
because it is correct . i get what i need
after I divide with 24 I close this to a parenthesis and then round and then replace ? is it correct lke this ?
I wouldn't have expected replace() to work on a number, but 🤷. The parentheses are fine
i use it very much with TTS
because Text to speech engine of nabu casa doesn't pronounce the comma correct.
so I always do a replace from 6.2. to 6 κόμμα 2
(it's greek)
so the tts engine read it properly
It's..uh..all Greek to me
@inner mesa sorry can’t seem to get this to work, my other code works but not this
{% if ['light.office_hue_group_1', ‘light.office_hue_group_2']|select('is_state', 'on')|list|length > 0 %}
orange
{% endif %}
Put it in
-> Templates
I did, if I remove the second group entity it works so it may be the separation between the 2?
Can’t seem to include the 2 entities without an error
Ok, I copied and paste what you sent sorry. I’m new to yaml
Yes
it's fine
Ok
not what you have above
Sorry I was using this, the first you sent
morning, I'm still trying to get this ruddy blueprint to work but i'm just seeing in my logs
2024-01-31 10:27:00.285 ERROR (MainThread) [homeassistant.components.automation.lounge_motion_lights] Error rendering variables: TypeError: test_none() takes 1 positional argument but 2 were given
(for every automation using this blueprint when it is triggered)
there is nothing in the blueprint or anywhere that I can see which mentions anything relating to test_none ... very very baffled
https://raw.githubusercontent.com/thefunkygibbon/homeassistant/main/motionlight.yaml <--- the blueprint
Good morning guys all good? 🙂
Is there anyone who can help me build a "Your next meeting is in X minutes/hours" template?
This is what I have so far 😄
`{% set t =
strptime('states.calendar.ical_work_calendar.attributes.start_time', '%a %b
%d %H:%M:%S %Z%z %Y') %}
{{ t.hour }} {{ t.minute }}`
Although it is giving me an error
Error rendering data template: ValueError: Template error: strptime got invalid input 'states.calendar.ical_work_calendar.attributes.start_time' when rendering template '{% set t = strptime('states.calendar.ical_work_calendar.attributes.start_time', '%a %b %d %H:%M:%S %Z%z %Y') %} {{ t.hour }} {{ t.minute }}' but no default was specified
The start_time attribute is: start_time: 2024-01-31 13:00:00
Why not just install easy_time from HACS and use the macro in there?
Yes. Should appear in a HACS, you might need to make sure HACS is in experimental mode to see templates, I can not remember.
BTW: It is recommended to use the state_attr() function to get attributes these days, I understand.
thanks for that, i will keep it in mind
The one thing I can spot from the blueprint is that you are giving the variables lux_check and ilum_check a set value of off and still use them in the condition part. Both need to be either true to pass the condition.
yeah i have just seen that, and i also just found what was causing the error, ( but it still doesnt explain test_none being mentioned ?!)
Good morning all, i would like to create a sensor that shows me Current W Usage, all i got is a sensor that is showing me my Total kWh usage with its value being 51545.0195, this value updates every 10s. My idea was to somehow store the previous value and do a calculation "new value - old value". Any idea how to achieve this?
there is something wrong with the formatting on my condition here... can anyone suggest what it could be?
value_template: >
{% if use_time %} # If the use_time switch is on
{{ within_time_use }} # Only consider the time range
{% else %} # If the use_time switch is off
{{ within_time_range and (time_range_not_set or ilum_check or lux_check or sun_elevation_below_shift) }} # Consider all conditions
{% endif %}
logs say Error handling message: while scanning for the next token found character '%' that cannot start any token in "<unicode string>" but i'm struggling to understand what it means as everywhere i read says i should have the % in there
Comments in templates must be enclosed like this {# comment here #}
ahhhh ok let me change that then 🙂
so like this ?
{% if use_time %} {# If the use_time switch is on #}
i guess i can just remove the comments tbh
I did it! Thanks for the info of the template of EasyTime, its a life saver 😄
That still shouldn't produce an error. That should treat them as passing values.
As tom said, don't use comments at all in jinja unless you use comment lines. That's why I removed them
got ya 🙂
So, you didn't copy my full blueprint
that's why it's failling
you only copied the variables
I altered everything
the within_time variable covers the use of not using time or using time
{{ not use_time or time_from | today_at < now() < time_to | today_at }}
if use_time is false, then that statement will return true and it won't compare times
if use_time is true, then the portion before the or statement will return false, forcing that to check the second statement
so your changes to your value_template in the condtion and the addition of within_time_use is pointless
because it's handled by the within_time function
To debug, run an automation from this blueprint (give me a second) to see what the variables are.
@last basin ^
Post the variables on the variable page, then we can continue.
@marble jackal
#templates-archived message
have a look . you will remember it. It was you point me to keep the condition ...
I meant this condition
#templates-archived message
yes, you asked me to keep the original condition ...now you said to remove it again
Actually this
#templates-archived message
anyway, because the automation works flawlessly I will keep it as it is . I changed parallel to queued
After that your added the state to the trigger, based on my advice. That was not correct and my post you linked was an advice to go back to this
#templates-archived message
I don't think what you have now will work as flawlessly as you think it does, but you seem to have made many changes now, so I don't know what your current full automation is
You only share small bits every time, so that makes it hard to see the full picture
That automation and its condition logic are not the same as talked about earlier, also the condition is still redundant as by definition of a state trigger; the from and to states are always different.
@lofty mason I just wanted to thank you for all of your help last weekend!! I was able to set everything up and used 3 template sensors for the attributes, and everything works flawlessly!!
But I guess it will work with the mode queued with lesser precision though by ditching the confidence parameter
@fickle sand are you talking to me ?
yes
Bas honestly it is exactly the same as the first place.
I just enhanced it with a random function for each person (instead of saying the same thing)
the condition is intact and the trigger it's the same (i just added more faces - but they all end to FROM : frontdoor_camera2
You removed the whole condition checking on a match. It's completely different from the code I linked to above
dont worry about it
You've forgot it
two messages bellow you said to me:
"I would say you should have kept your original trigger"
And after that, you expressed your concern about the changing confidence without a state change #templates-archived message so TheFes and I suggested to stick with Petro's trigger and condition so it wouldn't be more complex than it should be
fair enough
thank you very much for your time!
I will stick with queued mode for now and get back to you with some feedback
Cross postedish question from the #automations-archived channel, I am looking at making an automation that is generic so it can apply to multiple devices of the same exact type but have complex logic that is checking multiple entities on this single device? For instance, I have some of the 3rd reality smart night lights and I basically want to say for each night light, if motion is detected & the lux on the specific device motion was triggered on, then turn on the light for that specific device. What is the best way to get entities or properties of a device?
Is there a more efficient way to do this for instance,
{{
states[device_entities(device_id(trigger.entity_id))
| select('search', 'light') | list | first].state == "on"
}}
I feel like I am doing this multiple times in an automation and would like to ideally avoid repeating it many times
If you have a trigger for each device you can pick up the entity and the device from the trigger data. Then use that to build the entity IDs in a variables section.
@lament dust if you want to switch off lights that are ON, then you can try with expand. You just need to create a group of the lights
I've use it for years
Its not that simple because they are night lights. I only want to switch one on at a time and I only want it to be switched on based on if its dark(lux is 1), and motion is detected etc..
So basically the logic is as follows:
- If motion is detected on any of X night lights
- Check if the lux is low
- Turn on that specific light only
check if the illuminance is 1 or not lol
nope, i mean from the same sensor ? or another sensor just for lux ?
what am saying, is these night lights , got also motion sensor and lux ??
Yes they are one device but 3 different entities
I think I got it mostly working now:
variables:
occupancy_entity_id: trigger.entity_id
light_entity_id: >-
{{states[device_entities(device_id(trigger.entity_id)) | select('search',
'light') | list | first].entity_id }}
illuminance_entity_id: >-
{{states[device_entities(device_id(trigger.entity_id)) | select('search',
'illuminance') | list | first].entity_id }}
ok
Out of interest I think you can simplfy the selects a little:
{{device_entities(device_id(trigger.entity_id))
| list | select('search', 'light') | first }}
You even don't need the list filter
Oh, and you might want to use match instead of search to avoid finding an entity with light in the object_id instead of the domain
And/or use 'light.'
or just do ^light
I always forget about match and just use search w/ leading/trailing indicators
^ = starts with $ = endswith
^light or light$
Yeah, I know. I normally do that myself
Just got reminded about match the other day, that's why I proposed it now 😅
Cool thanks everyone just tweaked it further
where can i add this time_pattern trigger? my attribute entity templates seem to have fallen asleep again
that or where do i check in HA that the entities they reference have updated?
well poor term then, but they aren't displaying in grafana again
Focus on HA first
You can see the last_changed and last_updated timestamps there
OK the entity referenced i clicked on it and it says
last changed yesterday
last updated 9 minutes ago
so the 'parent' entity seems to be updated..
oh there we go.. the attribute entity says:
last changed: 20 hours ago
last updated: 20 hours ago
last_changed means the state of the entity changed
last_updated means any of the attributes changed
ya i assume the last updated is the issue? that should be 'polling' or updating at a much more regular interval than almost a full day, no?
oh... given what you said there maybe not..
If there is no change, the timestamps don't change as well
So if the state of your source entity changes, but this doesn't render into a new state or attribute value, there is no update of these timestamps
hmm maybe its how im trying to pull the data into grafana then?
because its clearly there in HA, just seems to drop off at some point on my granafa dashboard
Possibly, I don't use Grafana, but this issue does ring a faint bell
I think I've seen something similar before
You could add an attribute in your template sensor with something like {{ range(1000000) | random }}
That should give you at least a last_updated timestamp everytime it renders the templates
Not sure if it would help for Grafana though
If your 'falling asleep' is that it doesn't continuously update for the same value, that's just how HA works
You can probably hack it as TheFes suggested
i think all of my grafana calls to HA are time series with a mean grouping, maybe because there isn't enough calls over a certain amount of time it just stops displaying the data because it doesn't have enough?
You would need to add a trigger, too
maybe that isn't explaining it properly... but i really don't understand it all myself which is why im asking for help... so ty in advance as well
SELECT mean("value") FROM "autogen"."%" WHERE ("entity_id"::tag = 'ParentEntity_AttributeEntity') AND $timeFilter GROUP BY time($__interval) fill(null)
ParentEntity_AttributeEntity are changed from what they actually are in HA
err. this may be the wrong chat for troubleshooting grafana query sorry
If it used a selection from the database that could indeed be the cause. If it doesn't change, nothing is written to the database
i can start with this, where would i add it, right to the state template code I'm using?
It should be an attribute of the sensor
i tried chaning it to 'last' instead of mean, didn't provide any different output in grafana dashboard
This topic seems to be about the same issue https://community.home-assistant.io/t/influxdb-to-store-data-in-intervals/270896?u=thefes
So i have tried to use the Derivative Helper but the Values seem to be Off, i can see a increase of about 10W in 10sec which should be 3600 Watt current usage in an hour. Anybody that has done something similar?
ahhh, thank you. this line here sounds promising
update_now: "{{ (now().minute / 5) | round(0) }}"
Gets updated every 5 minutes ( at 03, 08, 13, … due to the rounding), using now() only updates every minute.
i'll play around with that once i find the attribute code location
Unless you are using the legacy format, then you have to look at the bottom of that page
So my Electricity Meter does only deliver the Counter total kWh every 10s via a sensor. I would like to make a sensor that shows me current watt usage in my Home. I got an answer using the Derivative Helper but i cant figure out how to configure this to achieve my goal. It sounds so easy but yet i fail 😄
https://github.com/maxi1134/Home-Assistant-Config/blob/master/includes/template.yaml#L87
I'm trying to improve this sensor who relies heavily on Elifs.
Any suggestion is welcomed to make it more readable and maintanable
Hello. I'm trying to calculate the average temperature for the next 24h.
The purpose of this is that I want to modify the temperature of my gas heater based on this avg temperature.
I tried this, but gives me the average for the next 24 days I guess. Or at least it's trying to.
{{ state_attr('weather.forecast_home', 'forecast')[:24]
| map(attribute='temperature') | average | round(1) }}
I don't know how to access hourly instead of daily. Any ideas?
You need a weather integration which provides an hourly forecast
But using that attribute won't work on long term, it will be gone in two months
The default weather forecast have a hourly forecast. Can't I use that one?
Any recommendations on this?
Yes, use a trigger based template sensor and the weather.get_forecasts service call
There is an example in the docs
TheFes, any tipps on my case?
Thanks!
I can only say use to use the derivative sensor. #integrations-archived can help setting that up
Alright, then ill try that. Thank you!
I’m experiencing an issue with showing temperature from nspanels the way they are set in devices. In devices settings, I changed the default to showing 1 digit after the point (27.1 instead of 27.14621).
If I point to the temp entity using the mushroom chips card or sensor cards they show temp the way I want but when using the template cards (using the code), they display temperature the default way. How can I fix this? Is this an issue with the mushroom cards? This code pulls the temp the default way and not the way the entity shows. Puzzling thing is the code uses the entity id so not sure why this is happening.
{{ states('sensor.nspanel_livingroom_temperature') }}
I’m using the “secondary” field on my mushroom cards
The actual state still has the decimals, your setting is just applied in the GUI.
You can use
{{ states('sensor.nspanel_livingroom_temperature', rounded=True) }}
Or
{{ states('sensor.nspanel_livingroom_temperature', with_unit=True) }}
That will apply the rounding and add the unit of measurement
@marble jackal thank you so much, helpful as always
I would like a binary switch to turn on when a value of a device is above 5, and turn off when the value of the device is below 1, but only when the binary switch is already on - these are power usages in W. Is a threshold helper a good way to accomplish this, or is this something I should do with a template.
template binary sensor that uses those as triggers
So that I understand: use a template to set it, then I can use it in an automation?
template:
- trigger:
- id: 'on'
platform: numeric_state
entity_id: xxxxxxx
above: 5
- id: 'off'
platform: numeric_state
entity_id: xxxxxxx
below: 1
binary_sensor:
- name: blah
unique_id: 89124u32jlkjlfajoeijsef
state: >
{% if trigger.id == 'on' %}
{{ trigger.id }}
{% elif if trigger.id == 'off' and this.state == 'on' %}
{{ trigger.id }}
{% else %}
{{ this.state }}
{% endif %}
Thanks!
turn off when the value of the device is below 1, but only when the binary switch is already on
I don't get it, the alternative is that it isoff. I don't see the harm in turning it off when it is already off
Especially when the trigger based template sensor like above is used, as that will restore the state, so it will not be unavailable
or am I missing something
Doesn't sound like your missing anything. I just have a way of overcomplicating things. 😇
but what would you like the binary sensor to be if the source sensor is unavailable?
I actually don't care, as long as it isn't on. I intend to use this to send a notification when the binary_sensor turns off. i.e. washing machine is done
okay, and is your actual goal to avoid getting notifications after a restart of HA?
Yes. The notification only makes sense if it went from running to completed
use this in your automation:
trigger:
- platform: numeric_state
entity_id: xxxxxxx
below: 1
for:
minutes: 1
condition:
- condition: template
value_template: "{{ trigger.from_state.state | is_number }}"
no need for that binary sensor
Thank you for your help!
it will trigger as soon as your power value goes below 1 for 1 minute
and it will check if the previous value was a number
That's great, and clean!
why would this state the wrong day {% set datum = states('sensor.afvalwijzer_next_date') %} {% from 'easy_time.jinja' import month, weekday %} {{weekday(datum) ~' '~ as_timestamp(datum)|timestamp_custom('%d') ~ ' '~ month(as_datetime(datum).month)}} 'donderdag' while tomorrow clearly is friday...
or a bit cleaner
this does work, but is so complex...```{% set next = 'sensor.afvalwijzer_next_date' %}
{% set dagnummer = as_datetime(states(next)).strftime('%w')%}
{% from 'easy_time.jinja' import weekday %}
{% set dag = weekday(dagnummer|int) %}
{{dag}}
{{weekday(states(next))}}```
this should do it.... {% set datum = states('sensor.afvalwijzer_next_date') %} {% set stamp = datum|as_timestamp %} {% from 'easy_time.jinja' import month, weekday %} {% set dag =weekday(stamp|timestamp_custom('%w')|int) %} {% set datum = stamp|timestamp_custom('%-d') %} {% set maand = month(stamp|timestamp_custom('%m')) %} {{dag}} {{datum}} {{maand}}
or {% set next = 'sensor.afvalwijzer_next_date' %} {% set date = as_datetime(states(next)) %} {% from 'easy_time.jinja' import month, weekday %} {% set dag = weekday(date.strftime('%w')|int) %} {% set datum = date.day %} {% set maand = month(date.month) %} {{dag}} {{datum}} {{maand}}. hmm more invlved than I would have hoped for
weekday macro is 1 based.
check out the docs
for easy_time
also %w is week number, not weekday.
scratch that, wrong on that. But %w is 0 based, not 1 based.
so just add 1
I had forgotten I needed to int that 0 number
also, weekday from easytime only accepts numbers, not states from entities
Didn’t I write a FR on that ?
Yeah, but I haven't added it
So much going on I forgot sorry
I moved to new house and now I'm getting an error when the call service of the telegram send photo should be sent to me with a snap of the aquarium camera, have no idea why it's happening..
service: telegram_bot.send_photo
data:
authentication: digest
file: /config/www/tmp/snapshot_aquarium_sub.jpg
caption: " {% if values.error %} 🐟 ❌ The fishes have not been fed at {{ values.timestamp }} ❌ {% else %} 🐟 The fishes have been fed {{ values.value }} portions at {{ values.timestamp }}. {% endif %}"
The error:
Error running action
Error rendering data template: UndefinedError: 'values' is undefined
where does "values" come from?
that's my sensors.yaml
http://pastie.org/p/5fvyuOeytm6dckb9TI28Fi
binary_sensors.yaml
http://pastie.org/p/5xUlMjScnfXqxGmvvJAXhk
TheFes helped me a lot with those templates, it worked before I moved out here, now I'm getting an error on the telegram message part
Nothing there is showing how values is created
Your template throwing he error is in the caption of your send_photo
value is part of the switch.hfjh_v2_eadb_fish_tank_2 attributes.
no it's not
model: hfjh.fishbowl.v2
lan_ip: 10.0.0.142
entity_class: MiotSwitchEntity
miot_type: urn:miot-spec-v2:device:fish-tank:0000A0A2:hfjh-v2:2
fish_tank.on: true
fish_tank.water_pump: true
fish_tank.pump_flux: 100
function.ledboard_color: 0
state_updater: cloud
event.4.1: {"timestamp":1706808612,"value":[{"piid":16,"value":"2024,2,1,19,30,0,2"}]}
sub_entities: fish_tank-2.water_pump-2, function-4.ledboard_time_switch-8, function-4.feed_time_switch-11, function-4.key_switch-14, fish_tank-2.pump_flux-3, function-4.ledboard_color-5, function-4.ledboard_model-2, function-4.set_feed_single-1, fish_tank-2
device_class: switch
icon: mdi:fishbowl
friendly_name: Desgeo C series smart fish tank Fish Tank
supported_features: 0
and if it is, we need to see it
inside event.4.1.
right, but that's not being set anywhere
the template is getting values
it's not declared anywhere
Is that service call in an automation?
I can send the whole automation if needed
it's needed
it's in the variables section
so how did it worked before
you'd have to view the trace, it seems that it's erroring and not creating the variable.
either way, the error seems impossible if the automation is actually running
because it is declared
are you copying and pasting that template into the service caller and testing it?
Probably just hit 'run'
I did hit run then this error shows up
Yep
yeah, that's not going to work
it needs to run from a trigger
if you just want to test the actions separately, you should just make that a script.
wait i will send the traces
no need
the issue is that you're clicking run
when you click run, it only runs the actions, nothing else
if you want to be able to click run, then you should make the variable section and the actions into a script. Then you can just click run on the script.
I also thought that it needed to be trigger_variables at that level
I clicked run after the automation failed just to make sure it wasn't the camera fault
well the error you're pulling is only from the run
I'm not sure how much more I or rob can say this
if youre having a different problem, you need to post the different problem. The error you're getting is from you clicking run.
Triggered by the state of switch.hfjh_v2_eadb_fish_tank_2 at February 1, 2024 at 7:30:20 PM
Check if the switch didn't go from or to unavailable
Check if the values are correct
Call a service 'Camera: Take snapshot' on Aquarium Fluent
Stopped because an error was encountered at February 1, 2024 at 7:30:30 PM (runtime: 10.04 seconds)
That's the automation traces, before i clicked on Run
well we need the error at February 1, 2024 at 7:30:30 PM
and if it's Error rendering data template: UndefinedError: 'values' is undefined then you're looking the wrong error
How can I get to this error via Traces?
it's in your logs
whenever you see this Stopped because an error was encountered at February 1, 2024 at 7:30:30 PM (runtime: 10.04 seconds) that means there's an exception/error in your logs
Fish Fed Telegram Notification triggered by state of Last Fish Feed changed to February 1, 2024 at 7:30 PM
7:30:20 PM - 1 hour ago - Traces
Feeding is required changed to February 3, 2024 at 10:30 PM triggered by state of Last Fish Feed changed to February 1, 2024 at 7:30 PM
7:30:20 PM - 1 hour ago
Last Fish Feed changed to February 1, 2024 at 7:30 PM
7:30:20 PM - 1 hour ago
That's all I have on logs related to the fish tank today.
ofir
please, look in your homeassistant.log file
you've been here long enough to know what the logs are
those are not the logs
there you go
http://pastie.org/p/5Nd9SMoE04Afqp9zpqx5xl
thanks for helping me btw
Your error is unrelated tot he template, the automation timed out creating the snapshot
What can cause that?
an issue with the integration or an issue with the connection to the camera
ok, thanks!
Hi, i have a question regarding date and timestamp templating. When i use this piece of code the day (timestamp_custom("%A %d.%m.%Y") is displayed in english but my language settings are german. Any idea why the day is nevertheless displayed in english?
Templates aren't translated
Perhaps this would help: https://github.com/Petro31/easy-time-jinja
https://www.youtube.com/watch?v=KjbpXiA-u2I
I found this which seemed to do the trick. there is an automation command to force and entity to refresh. seems to be updating my parent entity the attribute template is attached too.. but not the attribute template itself
only seems to update 'last updated' though, not 'last changed' which would make sense as teh value is relative static i don't expect it to change very much as it is % used on a backup drive
Update entity will not update parent entities
Thx, i will try it.
it just updates the entity in question
what language?
german
Yep, it's supported
hmm i have 2 entities, each of them has an attribute that i mapped to a helper template
i added all 4 entities to an update entity automation that runs every 30 minutes
the 'parent's both have 'last updated' update every 30 minutes
but the attribute do not update
im calling them parents because i don't know what else to call them
alias: "Refresh C: and D:"
description: ""
trigger:
- platform: time_pattern
minutes: "30"
condition: []
action: - service: homeassistant.update_entity
target:
entity_id:
- sensor.parent1- sensor.parent2
- sensor.attributetemplate1
- sensor.attributetemplate2
data: {}
mode: single
- sensor.parent2
Ah ok, just a miss comm then. 👍
Is there a way to make a templated rest_command that will take a number directly?
Yes, the command itself can be a template
How would I specify that?
You can template the url or the payload
so just "http://URL/{{ data }}" ?
Yeah and you’d need to pass the data variable in the data section of your service call
You might want to use a different variable name so you don’t get confused
would that go in the target?
No, in data
so If im making a button, I have a tap action:
tap_action:
action: call-service
service: rest_command.command
target: {}
Where would I add my parameter?
In the field called data, you are omitting it. It’s literally called data. I’m not mixing my words up here.
Thank you, I got it to work now
Can this IP address be rendered in a template? The ones shown in the device page. https://i.imgur.com/9DLRJ6X.png
@bronze horizon Is it also the name of the device?
Hi. Maybe I am overthinking, but wanted to check. If I specify a datetime string with no timezone, will HA understand it as one in local time if I use "as_local". The dates are in the past, so in principle there could have been some change of DST with respect to the current time etc. If not, is there some way of taking care of this?
Hi! I'm making a sensor to represent the status of my standing desk and to use it as a input sensor for a history_stats sensor. The yaml seems to be working on developer tools, but then i don't know why is not showing on the entities page (I have saved and restarted HA VM). Code is:
desk_standing_status:
friendly_name: Desk sitting status
value_template: >
{% if states('sensor.desk_2995_height') | float < 0.9 %}
Sitting
{% elif states('sensor.desk_2995_height') | float > 0.9 and states('sensor.desk_2995_height') | float <= 1.15 %}
Standing
{% elif states('sensor.desk_2995_height') | float > 1.15 %}
Walking
{% endif %}
(full yaml in https://pastebin.com/uU6Avw1C) Any clue what I'm doing wrong?
is that in configuration.yaml?
yes
so you aren't using sensor: !include sensor.yaml?
no I don't
Ok then, the entity will appear in developer tools -> states page
I should move it to there some day 🤣
if you already have a sensor section, that would be the reason it's not showing up
TheSlowFes
its showing up on there @mighty ledge
and also on the dashboard
I just had to wait 🤯
Thanks guys
Hi all, QQ. I have a sensor for my car which is displaying the correct odometer reading, but the wrong units. (A bug in a depreciated integration). Can I use REPLACE on the sensor to change the text from km to mi?
This is all I have on my entity card at present
name: Mileage ```
is the unit in the state itself, or in the unit_of_measurement attribute?
It's in the state itself
if it's in the state you either need to use a custom card which allows you to overwrite the state in the card
or create a template sensor which does it in the state of the template sensor
but if it is indeed in the state itself, you can use replace to do that
Great, thanks! How? 😂
I tried this, but don't know where to put it in the yaml
{{states('sensor.tmbbr8nxx_odometer') | replace("km", "mi")}}
create a template helper in Settings > Devices & Services > Helpers
and use that for the template
no YAML requred
that will create a new sensor
which you can use in your card
Is there some way I can load the weather.get_forecasts service's response variable into a variable I could then play with in the template editor?
there's no communication between the Services and Templates tabs, so you'd need to make the service call and then copy the response into the Templates tab when assigning to a variable
How would I set up a template helper that returns the amount of time since a certain entity switched from false to true?
Is there a way in jinja from within a loop to increase the size of the loop itself?
As in add additional items to the loop
Or are you stuck with what ever is in your loop list at the time the loop starts.
{% for dolphin in ocean %}
{{ something something }}
{% endfor %}
In this example being stuck with whatever is in ocean at the start of the loop.
This will give you the timestamp of when the sensor changed from false to true:
template:
- trigger:
- platform: state
entity_id:
- binary_sensor.my_sensor
from:
- 'off'
to:
- 'on'
sensor:
- name: "Sensor Turned On Timestamp"
unique_id: e80380db-5261-457e-bd92-1b63381fcd49
device_class: timestamp
state: "{{ now() }}"
Some front end cards will display this timestamp in a relative format that is easy to read (e.g. "two minutes ago"). If you want something more specific you can use a template card and format it however you desire
You can use a namespace:
{% set ns = namespace(ocean=[1,2,3,4,5,6]) %}
{% for dolphin in ns.ocean %}
{% set ns.ocean = ns.ocean + [dolphin -1] if dolphin is even else ns.ocean %}
{% endfor %}
{{ ns.ocean }}
Just be careful you're not creating an infinite loop 🙃
Interesting. Good to know.
I dont know whats wrong with my template (im pretty new to ha)
as you can see in the screenshot the validation is just loading into eternity and never stops.
I also cant restart home assistant because of the following error:
" argument of type ‘NoneType’ is not iterable " .
This only takes place while i tried it with my custom template light i wanted to create. Can anyone tell me whats wrong with my template ligtht?
Here is the code: https://dpaste.org/D0cnu
If i remove the template there is no error at all and everything works fine.
Everything under treppenlicht: needs to be indented. Where did you add this i.e. which file?
So should i just move it 2 spaces to the right?
at first i had it in configuration.yaml but then i changed it and added it in a lights.yaml file so my conf file would't be so full and i simply added light: !include lights.yaml in my configuration file
Then you need to remove the top light:.
Okay it looks like this now http://pastie.org/p/7IuxVNNoh2vCFaVzhOETsj
what exactly has to be indented?
It worked thank you really much!
I've setup local calendar and several automations that are triggered with some pir sensors.
When this happens, I get events with duration of 24 hours and then, if events > 0, I conditionally execute a TTS action which announce this events.
It's pretty simple and it covers me almost 100%.
But sometimes, with some very important events, if I don't trigger a PIR in time, I won't get an announcement.
And this might be a problem some times.
So I was wondering what is the best way to get a trigger before a calendar event occur ??
I've found a template that creates a sensor which gives the remaining minutes before an event occurs.
{{((state_attr('calendar.school', 'start_time') |as_timestamp|int - now()|as_timestamp|int)/60)|int}}
But is this the right thing to do? How to address it when you have multiple calendars?
Please don't crosspost
am sorry TheFes, didn't mean it. I just did it because i didn't know where is the right to post it,
I just deleted it from automations
not sure if i m in the right channel for this question but here i go: i have a sensor that gives out a kWh i want to create a new sensors out of this that resets every month to 0 but the original sensors sometimes goes to 0 for a short time and the nback to its original state. I do not need to have its value x2 then how can i do this? when i create a nutsmeter out if it that resets every month it adds up the value after what its at when it got to 0 for a short time....
@final trellis what is exactly your goal here. An announcement x minutes before a calendar event? You can use a calendar trigger for that
would you pls provide an example?
platform: calendar
event: start
offset: "-1:30:0"
entity_id: calendar.work_days
Although I don't know why you could not have simply used the automation editor and done that yourself.
Jane_t, I obviously read an old post which was saying that this was not possible.
based on your recommendation I created the following automation which works
https://dpaste.org/ro0jK
thank you for that! My only problem is that if stataments inside message are not considered
would you please take a moment and have a look?
is it because you can't put it on an IF statement ??
agenda['calendar.school'].events | count > 0
That template condition will always render true when the automation triggers
As it triggers one hour before the start of a calendar entry, there will always be a calendar which has an event
always? wil render when there are events on calendar.school. not always
I revise the code, but still doesn't work properly
it played only the school events. although there were events for calendar.makis, these events didn't TTS
Check your automation trace. Most probably they both worked, but are issues with microseconds after each other, so first one started, but got overridden by the second one
I would combine them in one TTS message
i did but if statement is not working
see preious post
this is the reason I tried to change it
and also can the trigger combined to one?
trigger:
- platform: calendar
event: start
offset: "-1:00:0"
entity_id: calendar.school
- platform: calendar
event: start
offset: "-1:00:0"
entity_id: calendar.eleni
- platform: calendar
event: start
offset: "-1:00:0"
entity_id: calendar.makis
I meant like this https://dpaste.org/V9Po7
TheFes, I said that this didn't work for me.
The if stamenets inside the TTS message was not consided
it played all three calendars, even though for calendar.eleni was no events
(but it anounced the name)
lines 42,49 and 59 didn't worked
can the if statement work like this ??
You might need to debug it a bit, I copied and pasted it on mobile
I mean with agenda['calendar.school'].events
Use the service call in developer tools > service. Then convert the output to json using https://onlineyamltools.com/convert-yaml-to-json
Create a variable called agenda in devtools > templates using the json, and then test and tinker your TTS output message until you have what you want
{% set agenda = <json output> %}
oh ok
this is great!! Today I knew something I didn't know
thank you for that +1
also my code is working as expected +1
so why TTS engine plays only the first part ???
I think it has to do with the trigger
they all triggered the same time and this confuse it
That template you now used was my proposal for the combined one right?
To have it all in one TTS message
No, you have mode: single so the other triggers won't do anything
Besides logging a warning that the automation didn't trigger because it was already running
correct, but I still can't figure out why the template shows what is right and what I want and the TTS engige doesn't play it
Check the automation trace, it will tell you what it did
found it!!
some extra spacing ...didn't let the code to be executed
thank you. about nabu casa cloud.say, does anyone know if there is a pause like alexa when you tts ??
That's something for #integrations-archived
I just saw the notification. Thanks, I will enjoy it ☕
your welcome
https://i.imgur.com/CawumtA.png
I could use some help. I'm trying to pull today's precipitation chance (see imgur image above) from weather.home . I have pulled attributes before but this one has a bunch of values listed each for the next five days. How can I pull just the value for today's percipitation chance using jinja (I will eventually need to do this in js but jinja call for now is fine).
https://pastebin.com/ZT727yZT
^^^^ full sensor attributes for reference
@bronze prawn The forecast is a list, take the first item from the list and then the precipitation chance
state_attr('weather.home', 'forecast')[0].precipitation_probability
Do note that this attribute will be removed in a few months, you will have to use the service call to retrieve the data then
Thanks for this. Oh yeah, I did see that as upcoming but until now, I had no need to think much of it. I'll take a look
how do I find out the integration name to use in auto-entities and integration_entities?
seems brute force guessing has worked today
I always go to Settings > System > Repairs > 3 dot menu > integration start up times
that is amazing
tyvm
Hi all, probably a trivially simple question, how would go about calculating an average value of another sensor, though not taking into consideration values of the sensor when another binary sensor is switched ON.
More specifically, I'd like to calculate an hourly/monthly/yearly efficiency of my forced air ventilation system. My efficiency sensor goes to 0 however, when the bypass is switched on, so this would invalidate any sensible average.
I could probably indicate mathematically that the average should be non-zero average
But I was hoping to include a more mechanistic approach and use state of other sensors to inform the calculations of the average
This would be a super useful skill to have for me since I foresee using it in other templates as well.
Help will be greatly appreciated!
Hi I'm trying to write a template that lists all my plants that need watering.
I have the following so far
{% for plant in states.plant | selectattr('attributes.moisture_status', 'match', 'Low') %}
{{- plant.name }} 💧{% if 'low' in plant.attributes.conductivity_status %}💩{% endif -%} {% if not loop.last %}, {% endif -%}
{% endfor %}
But how would I go about grouping by area?
You could create a template sensor which uses your source sensor for the state, and has an availability based on the binary sensor.
From that sensor you can use a statistics sensor to calculate he average
I'll sit down to it and probably come back with questions. Thank you for the idea!
How can I access the value of an attribute ? I tried this:
'{{ states("climate.thermostat_esstisch.attributes.temperature") }}'
but it returns always 'unknown'
I couldn't post pictures here (don't know why), here is a screenshot:
https://i.ibb.co/WBVF8Z7/Screenshot-2024-02-04-143409.png
state_attr('device_tracker.paulus', 'battery')will return the value of the attribute or None if it doesn’t exist.
@sharp night I converted your message into a file since it's above 15 lines :+1:
Trying to setup a template for a weather station reporting it's battery status. I found this template sensor that seems to evaluate properly in the Template developer tools section, though it shows as "unknown". Upon further checking it looks like it's interpreting my battery voltage as a string:
ValueError: could not convert string to float: '# calculate percent from the voltage # clamp the output to a 0-100% range 100'
The unit of measurement is mv for the source sensor in the template.
Your "comments" aren't comments since they're outside the template
They are strings w/ the actual value 100 appended on the end
🤦
thats what i get for blind copy/paste
Comments in Jinja must be surrounded by {# #}
yeah, dumb mistake. i was just happy someone had already figured it out so i did the copypasta without even thinking about it. 🙂
There is a super great blueprint for that btw
Could use some of what it did https://community.home-assistant.io/t/plant-moisture-notification/369425
I'm not using the built in plant integration as that one lacks areas, but if you have a link I will certainly check it out 😀
Dunno if that would help. What are you using? I'm using plants.yaml with friendly names in customize.yaml
I think I found a way to do what I need, but haven't had time to put it to a test yet 😀 the function areas() and area_entities() should do the trick.
I figured that would at least help you figure out the rest
If you get a working template let me know. What are you using instead of plants.yaml?
Having looked into it, I know I am pedantic, though was wondering if there is a more elegant approach.
More specifically, I have the original ventilation efficiency, which is 0 when the bypass is open and 'something' then bypass is closed.
To use your approach, I need to first pull it's state and match it against the bypass being open of closed to draw 'non-zero' efficiency.
Then this would have another set of statistics platform sensors for the last hour/day/year created.
Is there really no way to use statistics platform-like sensor inside a template?
- name: Effective ventilation energy efficiency
unique_id: recu_energy_efficiency
icon: mdi:percent
unit_of_measurement: "%"
state: >
{{ states('sensor.recu_energy_efficiency') | float }}
availability: >
{{ is_state('binary_sensor.ventilation_bypass', 'off') }}
Going from this into drawing an hourly/daily/yearly average:
usind something like:
start: "{{ now().replace(hour=24).replace(minute=0).replace(second=0) }}"
end: "{{ now() }}"
Am I overcomplicating it for the sake of having one entity vs. 2-3?
There is actually also a bit of an additional problem, which is that the statistics platform only allow max age so the monthly sensor would be the last 30 or so days and not a sensor for the month of march, june, etc.
So i im getting the total kWh value from my Power Box but i cant add it to my Energy tab, i Guess because i does not have the state energy class.
i tried adding this in my YAML but in it does not show my change in the developer tools. What did i do wrong?
homeassistant:
customize:
sensor.tasmota_sml_total_in:
unit_of_measurement: "kWh"
device_class: energy
state_class: total_increasing
last_reset: 1970-01-01T00:00:00+00:00
This is not related to #templates-archived
Could you point me in the right direction? Sorry i did not see any more fitting Channel
#energy-archived can probably help
Thank you
Does anyone have any ideas?
Hello. How can I round this to the 1 decimal point? ```{% if is_state("climate.master_bedroom_ac", "cool") -%}
{{ states('sensor.master_bedroom_ac_9_1d') }} - kWh.
{%- else -%}
- kWh.
{%- endif %}```
Add |float|round(1)
thank you
@undone jungle I converted your message into a file since it's above 15 lines :+1:
In other words, if left the way it is, the sensor will produce a result when the 'switch.hot_water` is on, but will produce a value of the main gas meter and not a separate meter that increases by only the delta of main gas meter value from the point the switch got activated.
I am sure there is a cool way of computing it, though I've not been succesful in finding it.
use a trigger based template sensor.
Might need some debugging though
- trigger:
- platform: state
entity_id: sensor.gas_meter_count
from: null
sensor:
- name: Water heating gas energy consumption
unique_id: water_heating_gas_energy_consumption
icon: tc:dew-point-alternative
unit_of_measurement: "kWh"
device_class: energy
state_class: total_increasing
state: >
{% 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) %}
{{ this.state | float + to | float - previous }}
{% else %}
{{ this.state }}
{% endif %}
attributes:
previous: >
{% set from = trigger.from_state.state %}
{{ from | float if from | is_number else this.attributes.previous }}
hey there, i need help using a template. I have no knowledge about template... 🙂
I want to make speak output on alexa device depending from the room where i am:
I already have the room tracking working. I write the actual room inside of a text helper: input_text.p_raumerkennung_input_sprachausgabe
Now i want to use the notify function to make speak output on alexa device. The alexa device is depending of the room.
How can i build that?
'trigger' is undefined - I'll have to debug
It should be placed under template:
any ideas?
don't start asking for responses within 10 minutes after placing your question
ok 🙂
what will be the state of that input_text?
you can probably do something like this:
{% set alexa_mapping =
{
'room_1': 'media_player.alexa_room_1',
'room_2': 'media_player.alexa_room_2',
'room_3': 'media_player.alexa_room_3',
}
%}
{{ alexa_mapping[states('input_text.p_raumerkennung_input_sprachausgabe')] }}
https://i.imgur.com/oExx2q2.png not sure what I am doing wrong. It's complaining the trigger being undefined.
the state of input text will be variable. I want to use this input always if i want to make speak output on alexa device. Bit i have another state called "input_text.p_raumerkennung_aktiver_raum" this will be my trigger of the room
content of input_text.p_raumerkennung_aktiver_raum can be multiple rooms. For example Wohnzimmer, Flur, Schlafzimmer ect..
what i actually have as my tmeplate is:
trigger:
- platform: state
entity_id: input_text.p_raumerkennung_input_sprachausgabe
from:
to:
service: notify.alexa_media_schafzimmer
data:
message: {{ states('input_text.p_raumerkennung_input_sprachausgabe') }}
yes, so you need te define them all in that mapping
I guess you want to template the service call then, so notify.alexa_media_schafzimmer
i am right that this template already should trigger a speak output at the alex davice?
does the room always match the last part of the notify service?
no it doesnt
you can't test this in devtools > templates as it relies on the trigger data
you won't have it there
unless you define it
like:
OK, I knew there was something to it.
{% set trigger = dict(from_state=dict(state='100'), to_state=dict(state='110')) %}
i am not sure how to go on
It may be a whack-am-all... 'this' is undefined
you need to do the same thing there
okay, you want to tempalte the service call right?
yes
{% set trigger = dict(from_state=dict(state='100'), to_state=dict(state='110')) %}
{% set this = dict(state='5') %}
this looks like it works, but i dont become a speak output if i change the input value
and it should right?
trigger:
- platform: state
entity_id: input_text.p_raumerkennung_input_sprachausgabe
from: null
action:
- variables:
alexa_mapping:
Schlafzimmer: notify.alexa_media_schafzimmer
Flur: notify.alexa_media_1234qw45
Wohnzimmer: notify.alexa_media_asdf556
- repeat:
for_each: "{{ states('input_text.p_raumerkennung_aktiver_raum').split(', ') }}"
sequence:
- service: "{{ alexa_mapping[repeat.item] }}"
data:
message: "{{ states('input_text.p_raumerkennung_input_sprachausgabe') }}"
sorry, had the wrong input_text
nice! Looks good, but the input eich de3vice should be make output is also a text helper. Its called "input_text.p_raumerkennung_aktiver_raum" Should this helper be used as "trigger" on wich room speka output will be make?
i got the output 'repeat' is undefined
how are you testing?
in the template editor
you can't test it there
on the upper right o got a red notification
run the automation by changing the input text
where do you see that now?
yes, I just explained you can't test this template in devtools > templates
you need to test the automation itself
and check the automation trace if ti worked
It relies on a variable created in the repeat loop
i am not sure if i understand you correct. There is actually no automation for the speak autput. Shouldnt the template do the output? I only have the input text helper and in your template example this helper is used correct?
in the step below, it splits the state of your active room input text into parts, based on the comma. So it will create a list of all the rooms in that input text
for_each: "{{ states('input_text.p_raumerkennung_aktiver_raum').split(', ') }}"
then it will do a notify service call for each of those rooms
this post: #templates-archived message is an automation, with a trigger and an action sequence
meant to send out the notifications to the speakers when the input_text for the message changes
I based that, on what you provided here: #templates-archived message
Did you change the data?
no
I provided gibberish notify services
you need to change it to the correct one per room, I have no clue what your notifcy services are
Also, everything is case sensitive, so the rooms have to be exactly like they are in your input_text
yes, i tested with the room Büro
What do you have now, as automation?
the value of input_text.p_raumerkennung_aktiver_raum isd actually Büro
trigger:
- platform: state
entity_id: input_text.p_raumerkennung_input_sprachausgabe
from: null
action:
- variables:
alexa_mapping:
Büro: notify.alexa_media_schafzimmer
Flur: notify.alexa_media_1234qw45
Wohnzimmer: notify.alexa_media_asdf556
- repeat:
for_each: "{{ states('input_text.p_raumerkennung_aktiver_raum').split(', ') }}"
sequence:
- service: "{{ alexa_mapping[repeat.item] }}"
data:
message: "{{ states('input_text.p_raumerkennung_input_sprachausgabe') }}"
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
please do that
if you have that, it should send a TTS message to notify.alexa_media_schafzimmer
which probably doesn't work, as I see there is an l missing
The whole idea of that alexa_mapping is to mach the rooms with the right notify service
git that
so you need to change that
you have this: Büro: notify.alexa_media_schafzimmer
is that correct?
so i removed the other "options"
trigger:
- platform: state
entity_id: input_text.p_raumerkennung_input_sprachausgabe
from: null
action:
- variables:
alexa_mapping:
Büro: notify.alexa_media_schafzimmer
- repeat:
for_each: "{{ states('input_text.p_raumerkennung_aktiver_raum').split(', ') }}"
sequence:
- service: "{{ alexa_mapping[repeat.item] }}"
data:
message: "{{ states('input_text.p_raumerkennung_input_sprachausgabe') }}"
correct
without the l?
okay
but it is correct
so, you have this as an automation now
what happens when you change the input text? does the automatin get triggered?
where can i see if the autmation got triggered?
does the template generate a automation?
i am very nwe in HA, i used Iobrooker before..
The code above IS an automation
IS?
you should create an automation with that code
ahhh
thy for your patience... 😉
Yes, its triggering
i didnt know that i need to make a automation out of a template... 😉
now its working 🙂
i didnt know that 🙂
in an automation, or in a template sensor, or in a script
as you were providing a trigger and a service call, I assumed you were creating an automation
as i wrote, i came from the iobroker, and my thinking about automation is poisened 🙂
so looks good at all, i will know fill the alexa devices...
its working now, thank you very much! @marble jackal
For the moment, I've transferred it into my templates file and corrected some indents, but outside of that left it the way you've constructed it.
Will see how it fares for my regular boiler kicking in.
Will report later today. Thank you again for the assistance!!
Hey y'all, anyone able to help me with a template binary sensor which so I can do the following: Can I set a time condition in an alert? So that the notification will happen only during certain times even though the boolean is turned on?
The alert itself is already setup, just not the part about in only sending the notification during certain times
go to Devices & Settings > Helpers and create a template helper with the type binary sensor.
Then paste this template in the respective field (adjust where needed)
{% set start = '09:00' %}
{% set end = '22:00' %}
{% set input_boolean = 'input_boolean.alert_washing_machine' %}
{{ is_state(input_boolean, 'on') and today_at(start) < now() < today_at(end) }}
Could you explain the logic behind this so I understand how it works? I'm sure it'll work, just trying to learn how exactly 😄
And the alert itself stays the same? As for the automation that turns the boolean on?
no, in the alert you use the newly created binary sensor instead of the input_boolean
in the automation you still turn the input boolean on
not sure what to explain about the template, the first 3 lines set some variables so it is more easy for you to know what to change
the last line outputs true or false, if it is true your binary sensor will be on, otherwise it will be off
Hello
I have a sensor that I am turning into a template sensor to correct for inaccurate readings (it's a humidity sensor and I'm adding a constant as a calibration correction)
sometimes the sensor gives a 0 value and thus the template sensor returns just the calibration value which makes my graphs ugly
Is there a good way to filter out zero values of the sensor so that the template sensor is undefined or ignored or something so it doesn't show the incorrect value?
It seems that people haven't had success with trying to use the availability_template to ignore spurious values
- sensor:
- name: "Livingroom Humidity C"
unit_of_measurement: "%"
state: "{{ (states('sensor.ble_sensor_livingroom_humidity') |float(0) + states('input_number.livingroom_humidity_correction')|float(0)) | round(2) }}"
```
can I use 'unknown'?
{{ 'unknown' if x == 0 else x|float(0) }}
template:
- sensor:
- name: "Livingroom Humidity C"
unit_of_measurement: "%"
state: "{{ (states('sensor.ble_sensor_livingroom_humidity') |float + states('input_number.livingroom_humidity_correction')|float) | round(2) }}"
availability: "{{ states('sensor.ble_sensor_livingroom_humidity') | is_number }}"
when sensor.ble_sensor_livingroom_humidity is not a number, it will go unavailable
okay, so unavailable should prevent the value from being recorded? I read somewhere in the forums that availability wasn't preventing values from being recorded
it's an infrequent error so I'll have to test it for a while to see what happens
it will still be recorded as unavailable in the database
but it won't affect your calculations
great! thanks for the help
np
@rare schooner I converted your message into a file since it's above 15 lines :+1:
Can't nest ' in ', just use " for the outer
@marble jackal that is definitely not what was expected:
https://i.imgur.com/4fDvNCt.png
It seems like it's taking the original sensor state and not the delta
I've even tried setting the state to 0 assuming it was a momentary fluke, but it immediately returned to the state of the input sensor:
https://i.imgur.com/qmBNJaG.png
@undone jungle I converted your message into a file since it's above 15 lines :+1:
Here is the sensor (inside a templates.yaml file).
The input sensor state https://i.imgur.com/xJfFjl5.png , though mind the fact it's in m3 and not kWh (which is 11.474 multiplied).
Any assistance would be greatly appreciated!
Just imported the binary sensor and changed it in the alert.yaml, tested it and it works as intentioned. Thanks for your help!
ah, I know why that is, it already had a state from your old config
I also spotted a mistake on my end
I on the other hand realized the conversion from m3 to kWh is gone from this template, so will have to modify to add it.
- trigger:
- platform: state
entity_id: sensor.gas_meter_count
from: null
sensor:
- name: Water heating gas energy consumption
unique_id: water_heating_gas_energy_consumption_new_version
icon: tc:dew-point-alternative
unit_of_measurement: "kWh"
device_class: energy
state_class: total_increasing
state: >
{% 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 }}
{% else %}
{{ this.state }}
{% endif %}
attributes:
previous: >
{% set from = trigger.from_state.state %}
{{ from | float if from | is_number else this.attributes.previous }}
make sure it has a new unique_id (I changed it above)
The gas meter count is in m3 and it must be converted by multiplication of 11.474
and the default in the float filter was missing
that really makes it a lot more complicated
state: >
{% set watergas = states('sensor.gas_meter_count') | float %}
{% if is_state('switch.shelly_hot_water', 'on') %}
{{ (( watergas * 11.474) | round(2)) }}
{% else %}
None
{% endif %}
That was my original way of going about it.
yeah, I was overthinking it
I'd have to produce the output in m3 and then feed this sensor into another for conversion.
Do you have an idea for something halfway between mine and yours?
EDIT: I see you've edited just now
okay, adjusted above
Shouldn't this be bracketed to have the addition before the multiplication?
{{ this.state | float(0) + delta * 11.474 }}
no
Won't this.state be still in m3 while delta won't.
OK, sorry, I may be missing the logical step somewhere.
that will start at 0 after creating, and will adding the deltas as soon as it starts working
so it will be a sum of deltas, which are all in kWh
Is there a way to get rid of what is under the current unique_id already, and start over?
I'd prefer having the unique_id the same - or at least this is how I had them until now
the unique id is just somehting in the backend
it can be a randomly generated uuid if you want
Sorry - OCD...
the name will determine the entity_id
But I will know... lol 🫣
delete the config
reboot
remove the entity entirely
reboot
create it again
that might work 🙂
OK, OCD cured by laziness....
story of my life
Isn't it for all of us. It's just where we draw the line is what differentiates us....
Logger: homeassistant.config
Source: config.py:596
First occurred: 16:44:48 (2 occurrences)
Last logged: 16:45:16
Invalid config for 'template' at templates.yaml, line 108: invalid template (TemplateSyntaxError: expected token 'end of statement block', got 'integer') for dictionary value 'sensor->0->state', got "{% set to = trigger.to_state.state %} {% set from = trigger.from_state.state %} {% if to | is_number and is_state('switch.shelly_hot_water', 'on') %}\n {% set previous = this.get('attributes', {}).get('previous', from | float) %}\n {% set delta = to | float 0 previous %}\n {{ this.state | float(0) + delta * 11.474 }}\n{% else %}\n {{ this.state }}\n{% endif %}\n"
I can't seem to locate how I've messed it up.
not sure what went wrong there
corrected it in my post above, should have been this:
{% set delta = to | float - previous %}
the default was not needed, as we already determined it was a number
you can round it if you want
DISREGARD
I could round it with a float(0) to zero decimals / CORRECTED BELOW
float(0) doesn't round. It uses the default 0, if the value isn't numerical
decimal(0)
round(0) 😉
Not my day....
Spoilers!
How do I round a number? decimal(0)
Thank you all!
it's not a bad guess tbh
state: >
{% 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(2) }}
{% else %}
{{ this.state | round(2) }}
{% endif %}
attributes:
previous: >
{% set from = trigger.from_state.state %}
{{ from | float if from | is_number else this.attributes.previous }}
Why would it produce 4.474860000003757 ?
isn't the pipe after both the states enough to round it to 2 decimals?
I guess I am missing a parenthesis somewhere to make this work?
{{ (this.state | float + delta * 11.474) | round(2) }}
parethesis, exponents, multiplication - division, addition - subtraction
I've tried it while you were typing and didn't work
it works
OK, it must change state to take effect!
gotta reload, make sure you didn't override your sig figs if you have a unique_id
I've reloaded the template_entities, but it didn't take effect until the state updated.
Once again, thank you for everyone's assistance!!
Hi folks! Is there any way to set an attribute of an entity? I know that state_attr(sensor.entity_id, 'current_temperature') is for reading an attribute. I could not find something for writing a value (in my case a float value) to an attribute.
You use service calls to actually do things
You can't modify the state or the attributes directly
Whatever is providing that entity should provide a way to change it, if it makes sense to do so
The solution is an automation who calls a script which returns namespace variable and then I use a service call? In the namespace would be several entitites btw
My point was that you use a service call. how you get there depends on your specific situation
ok
my problem is that I can create a namespace var and return it, but I cannot wrap my head around how the part of doing the service call with zero to a handful of records from the namespace is done.
I'm only getting bits and pieces of what you're actually doing, but if your goal with the template is to output a set of interesting entities, then you use that as a target for a service call
@undone jungle I converted your message into a file since it's above 15 lines :+1:
there are a few issues in that code
as I think was pointed out, {{ this.state | float + delta * 11.474 | round(2) }} is rounding 11.474
and {{ this.state | round(2) }} is trying to round a string, which may work if they convert it to a float for you 🤷
round will actually do that
But the round filter is not needed there, the whole idea is that it will return the existing state, which should already be rounded to two decimals (if parenthesis would have been used)
Hello gang, a typical novice question.
I have filled an INPUT_DATETIME helper . I want to only print hours and minutes. How can this be done?
does it have a date or just a time?
It was set with the following JINJA2
{{ now().timestamp()|int + states('input_number.washing_expected_runtime')|int }}
Okee, in settings -> helpers it says Type: "date and/or time"
It was the 3rd option "Date and time"
then... {{ (states('input_datetime.whatever')|as_datetime|as_local).strftime('%H:%M') }}
Yes. This works. Thank you very much.
Im not really sue if this falls into automations or templates, but I am trying to filter a sensor updates to an average .For conext, I have a distance sensor that updates ever 0.5 seconds and I want to take the average of the last say 5 seconds and use that as the actual distance
It seems the filter for average can only do this by minutes and hours though not seconds
hey, could use some guidance if anyone have any pointers it would be much appreciated.
i got this sensor that i want to shorten, its length and text varies
whats the best way to remove everything after the fourth "/"
/random/random/random/example/random/
{{ '/random/random/random/example/random/'.split('/')[:4] | join('/') }}
thanks! you the man
is there a way to take something that after a reset goes to 30% and then as it fills up goes to 100%, is there a way to make 30% be the new 0?
i can't do this on the device
and idc if i end up getting a different entity doing this
Hello everyone, I would like to finally bring my Luke Roberts lamp into HA The lamp can only be switched by rest without an app. I have the lamp so far that I can switch it on and off via restswitch, only with the brightness I stand on the spot what I have to enter behind Brightness: because a value is required. Ultimately, this should be a light template. Thank you very much. Here is the Rest_command code
url: https://cloud.luke-roberts.com/api/v1/lamps/by_serial_number/1901ZH/command
method: put
headers:
authorization: "Bearer XXX"
accept: "application/json"
payload: '{"brightness" : "??? "}'
content_type: 'application/json' ```
Are you asking what to use for ??? ? You can just use something like {{ brightness }} and then in the call to it, pass that value in as data
Yes, that was exactly my question, because I have the command with it for the time being in order to be able to process it in the template light. So does it have to work like this? Wow, I should have thought of that myself 😦
payload: `{{ brightness }}`
Hey there... I am trying to build a wokrtime counter. I want to Trigger a bolean Switch helper. If the helper is in the Templates should Count my working time. I found some example and configured IT to my conditions. I added this Code as a helper/Templates/binaray helper. But nothing Happen when try to Trigger.
'''
sensor:
- platform: history_stats
name: Living Room Main Light On Current Month
entity_id: input_boolean.nebenjob_arbeiten_aktiv
state: "on"
type: time
start: '{{ now().replace(day=1, hour=0, minute=0, second=0) }}'
end: "{{ now() }}"
'''
I also tryed state true, because its a bolean Switch helper i guessed the state should BE true instead of on. But both are Not working. Can someone Help me?
What are you hoping to get from that? I just copied exactly that definition into my config, changed the entity to a switch that I use regularly, and it created a sensor with a sane value
- platform: history_stats
name: Living Room Main Light On Current Month
entity_id: switch.office_desk_lamp
state: "on"
type: time
start: '{{ now().replace(day=1, hour=0, minute=0, second=0) }}'
end: "{{ now() }}"
The Sensor should Count the passed time between in and off
that doesn't make sense
you're counting the duration the sensor is on, or the duration the sensor is off
over the given time frame
if you count both, it's just going to be whatever your time frame is
Of course IT should.only Count when the Switch is on. I dont need to Count my free time 🙂
Ok, that's what Rob and your configuration will do
Also remember the history_stats do not update all the time, so you need to wait awhile to see them update.
it has a polling rate
but the word trigger is sort of meaningless, are you talking about it changing state or triggering an automation?
I mean changing the state of the bolean Switch helper to on
the history stats will only update once a minute
Should state "on" or "true" Trigger the Sensor?
Ok, so the Switch must be longer on then one Minute?
I note that it defaults to a unit_of_measurement of 'h', so maybe that's the problem?
Do you maybe know a better Option to Count working time?
I mean "better" in a easyer way f.e.
after your work day, it'll show whatever you worked that day, it doesn't need to be instant. If you want instant feedback when you get to work, use the input_boolean
History stats is the easiest way to track time a sensor has been on
And IT would BE okay for me
Alright, so again the question about what should BE the correct Trigger state. "on" or "true"?
"on"
Alright, i will Check it now again.
exactly like rob and your configuration
I switched on more then 2 minutes before. But nothing Changes in the Template Details. Shouldnt IT be displayed?
what do you mean "It be displayed"
the entity should instantly show up
if it's not showing up, you're not putting it in the correct spot
It will have a state directly after startup too. Then it will update once a minute.
So there's 2 things you could be doing wrong.
- You're assuming reload yaml will reload this integration. It will not if you just added it for the first time. Reload only works after you add an integration for the first time & restart.
- You're putting it in the wrong spot in configuration.yaml. Either you've duplicated the sensor section or you've put it outside the sensor section.
I'm guessing you sorted it out?
Correct 🙂
Do i need to add the Code to the yaml? I thought i Just need to make a new helper/Template?
the code is yaml
it's the history stats integration
it has nothing to do with tempaltes other than it uses some templates in it's configuration
Did you paste that into the template helper in the UI? If yes, that's your problem. That's only for the template integration.
ah ok, i still struggeling to get in touch with the different meanings
i just went from iobroker to ha
so, sorry for that
yes, but its very confusing to understand that fast
i added the code to the configurationyaml.
Now i get this information:
Platform error 'switch' from integration 'history_stats' - No module named 'homeassistant.components.history_stats.switch'
i am guessing the history data integration is missing? is that the problem?
yes, i found it also
the reset occus based on the start time
@lethal bison I converted your message into a file since it's above 15 lines :+1:
from my tests, looks like a no. HA removes the string after the variable. I think I need to move the quotation to after the string, at least
You also need to define your variables BEFORE you use them.
so for clarity, "before" means at a higher yaml level, not physicaly above?
I only mention this because the visual editor places the variables block at the bottom of the automation
This seems to work:
action:
- service: script.utility_notification
data:
name: "{{ trigger.id }}"
emojis: "{{ chosen_emojis }}"
variables:
chosen_emojis: |
{% if 'dryer' in trigger.id %} 👕👖♨️
{% elif 'washingmachine' in trigger.id %} 👚👕
{% elif 'dishwasher' in trigger.id %} 🍽🍳
{% endif %}
With that, you're putting it at a higher/larger scope
Before, you were setting the variable at a later step in the action. They are processed in order
I get it, because the action: is processed as a list
the variables section is processed after the trigger, before the conditions are checked
you can already use them in conditions
@worn dust I converted your message into a file since it's above 15 lines :+1:
possibly type conversion? What does traces show?
also, I don't have the data to back this up, but I've never liked using the hash values for device_id. Try using the entity_id for the thermostat instead (if you only have one, you could also use entity_id: all)
I converted the Visual to YAML and that's what it had. Would I just change id to entity_id and can then list the name?
also not sure how to pull up traces, I'm brand new to HA, sorry
sadly this didnt working, i try via developer Tools to Set 80 at the data line but I wont work