#templates-archived
1 messages ยท Page 1 of 1 (latest)
state_attr('weather.met_no_nowcast_buskogen', 'forecast')[0].precipitation
Thank you, do you know if there is way to store those into a template helper, or better a template variable that resolves based on a boolean set
Put it in a template sensor attribute (not the state)
What are you looking for? There IS a path...check jsonpathfinder.com
How can you get when the sun will rise im trying The sun will rise at {{ (now()-as_timestamp(state_attr("sun.sun", "next_rising")) | timestamp_local).hour()}}. But i dont think I understand how this works
Sounds like you're looking for "how long until sunrise"
Number of hours until the next sunrise: {{ (state_attr('sun.sun', 'next_rising')|as_datetime - now()).total_seconds()//3600 }}
Hey guys, just going to copy my thread from #automations-archived, is anyone able to offer some guidance on this?
https://discord.com/channels/330944238910963714/1000076444434694395
yea, is | casting stuff to a data type?
In that case it is. It's invoking a Jinja filter
HA seems to have a default state that climate entities are set to when they turn on.
I am trying to create a switch that will turn on my heat pump to the most recent state it was in (except off)
I've created a template sensor which does this effectively
value_template: |-
{%
if states('climate.office_heatpump') != 'off'
and states('climate.office_heatpump') != 'unknown'
%}
{{ states('climate.office_heatpump') }}
{% else %}
{{ states('sensor.office_heatpump_last_state') }} <- this exists so the state doesn't go blank when the heatpump is off
{% endif %}
I've created a script which effectively uses this sensor to turn on the heatpump to the latest state
toggling this script directly works as intended
alias: 'Heatpump Turn On: Office'
sequence:
- service: climate.set_hvac_mode
data:
hvac_mode: '{{ states(''sensor.office_heatpump_last_state'') }}'
target:
entity_id: climate.office_heatpump
mode: restart
icon: mdi:thermostat-auto
@civic cargo posted a code wall, it is moved here --> https://hastebin.com/bilajuteza
Here's all my code and description in one place since I'm misbehaving
https://www.toptal.com/developers/hastebin/afepoyiyoy.yaml
Why doesn't the switch work
The sensor and the script work independently
The switch isn't playing ball and I'm not sure why
I think you can kind of do that but believe you need to put it under the state in template sensor
- binary_sensor:
- name: "Has Unavailable States"
state: "{{ states | selectattr('state', 'in', ['unavailable', 'unknown', 'none']) | list | count }}"```
like that. But Ill let someone else confirm.
I'm not familiar with selectattr, but I'm doing some investiagting.
Thanks for the guidance.
- sensor:
- name: Vacuum Map Numbers
{"input_boolean.kitchen_d_vacuum": 21, "input_boolean.family_room_d_vacuum":19,
"input_boolean.dining_room_d_vacuum":17, "input_boolean.dining_room_d_vacuum":16,
"input_boolean.downstairs_bedroom_d_vacuum":23, "input_boolean.downstairs_bathroom_d_vac>
"input_boolean.washing_room_d_vacuum":18 }```
like this? Because that didnt seem to work
@simple edge Thanks for the insight, my guy
Got it going
Not like that, more like a couple of post below:
rejected by hassbot. that's sad
Can't see what's wrong on mobile, even on the second try
is that last bit all one line?
Should be, but it wasn't, pasting it on dpaste helped
Corrected:
template:
- sensor:
- name: Vacuum Map Numbers
state: "{{ 'ok' }}"
attributes:
map_numbers: >
{{ {"input_boolean.kitchen_d_vacuum": 21, "input_boolean.family_room_d_vacuum":19, "input_boolean.dining_room_d_vacuum":17, "input_boolean.dining_room_d_vacuum":16, "input_boolean.downstairs_bedroom_d_vacuum":23, "input_boolean.washing_room_d_vacuum":18 } }}
Not sure what he wants to do with this, could be a classic ๐ฅ
The XY problem is asking about your attempted solution rather than your actual problem.
This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.
The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.
Hey guys, I'm still looking for some help with setting up a temperature slider.
What I'm trying to do at the moment, is set up a temperature slider (or something equivalent), that then sends the correct up and down commands to my IR controlled Air con unit.
The unit control is all handled through harmony, and I have the scripts set up in HA to send these commands, but I cant for the life of me figure out how to hook those commands into some kind of temp setter. I have created an input number, and I can trigger things to happen when it changes, but i cant figure out how to do the correct commands (correct number of up or down commands to reach the new set temp)
I think this should be possible, but im not sure how to go about it. Any help would be appreciated! Thanks!
Np my dude
Curious what does mean, just wondering
how can I best compare temperatures from sensor.weather.external, temperature (attribute) with sensor.temp.internal (no attribute)? Not sure how to mix that
those aren't entity_ids
it doesn't really matter whether they're states or attributes
hmm
I have used state_attr for attributes but not for states
see that link
will do, thanks
i'm trying to calculate the energy cost of an individual device per day, i have a sensor (sensor.electricty_price) which is my cost of electricity per kwh and another sensor which is the daily usage using utility_meter.
I figured it would be something as simple as multiplying the two numbers together but that's giving completely the wrong sum
{{ ((states.sensor.electricity_price.state | float) * (states.sensor.pow1_usage.state | float)) }}
oh wait i think one is kWh and one is Wh
Hey folks, I've been playing in 'Developer Tools/Templates' and created a template I'd like to display on a card. How can I do this? My template is at https://www.toptal.com/developers/hastebin/aloriyawim.java
a markdown card?
make a template sensor out of it and then use any card that displays an entity state?
ok .. so I need to turn it into a template sensor, then display it
Thanks Rob, I'll give it a whirl
you could also simplify the template like this:
{% set strings = ['Standby', 'VENT Low', 'VENT Med', 'VENT High', 'VENT Turbo', 'RECIRC Low', 'RECIRC Med', 'RECIRC High'] %}
{% set state = states('sensor.hrv_state')|int(0) %}
{{ 'unknown --- sensor.hrv_state' if state not in range(2,10) else strings[state - 2] }}
Thanks again Rob, I tried the markdown card and it worked. Now I'm trying to turn it into a template sensor...
to reload the template sensors, I should be using the 'Developer Tools/YAML/YAML configuration reloading/template entities'...right?
Yes
Ok... I got the template sensor working now and I'm 2 for 2 tonight!!
onto your suggestion for the template....
Made a small fix
that's 3 for 3!!! Thanks Rob!
Just want to check my understanding on something: If I used i = sensors | map('bool', false) it would take the list sensors and look for the boolean value of the items in the list then output a boolean list with the default option being false?
I would think, yes
Depends on what 'sensors' actually is
If it's a list of the names of sensors, no. If it's a list of the state of a bunch of sensors, yes
Yeah, i is a list of the state of the sensors achieved by set i = expand('binary_sensor.digit2_a', 'binary_sensor.digit2_b', 'binary_sensor.digit2_e', 'binary_sensor.digit2_f', 'binary_sensor.digit2_g') | map(attribute='state'). There is a whole bunch more to the code block and I'm trying to break it down little by little so I can wrap my head around it.
On that, is the expand() function a Home Assistant specific function? I could only find a reference to it in the HA docs but not the jinja docs.
The link is what led me to it ๐. I had spent a good amount of time looking through the jinja docs losing hope. Just wanted to check I hadn't missed it somewhere over there. Thanks.
I was saying that the question you were asking could be a solution for a problem that could be solved in a different, more easy way
Hmm how would it be solve easier?
That requires you to explain the actual problem you are trying to solve, instead of the solution. So how are these numbers related to the input_boolean entities?
I created a vacuum interface, that I can select a bunch of rooms to vacuum at a time and these are tracked by those boolean. Unfortunately these rooms inside these vacuum are not map normal they have a random room ID. I need to create a list of room id's that are based on what switches are toggled on when clicking a single clean room button
I kind of used your code as a way to store and easily update values later on
Okay, if that works fine ๐๐ผ
I would love to learn if there is a better way
You're not on the Dutch Discord now ๐
oeps..
How must I create a sensor in HA in correct YAML:
`{% set data = "20;47;Cresta;ID=3601;TEMP=00cf;HUM=09;BAT=LOW;" %}
{% set ns=namespace(fields={}) %}
{% set fields = data.split(';') %}
{% if fields[2] == "Cresta" %}
{% for item in data.split(';') %}
{% if '=' in item %}
{% set keys=item.split('=') %}
{% set ns.fields = dict(ns.fields.items(), **{keys[0]: keys[1]}) %}
{% endif %}
{% endfor %}
{% endif %}
{{ ns.fields|to_json }}`
I have these MQTT sensor:
mqtt: sensor: - name: Cresta #{% set data = "20;47;Cresta;ID=3601;TEMP=00cf;HUM=09;BAT=LOW;" %} state_topic: "/ESP00/msg" value_template: "{{% set ns=namespace(fields={}) %} {% set fields = data.split(';') %} {% if fields[2] == "Cresta" %} {% for item in data.split(';') %} {% if '=' in item %} {% set keys=item.split('=') %} {% set ns.fields = dict(ns.fields.items(), **{keys[0]: keys[1]}) %} {% endif %} {% endfor %} {% endif %} {{ ns.fields|to_json }}}"
But it's not accepted.. I need a multiline format I think... Any help with this would be nice (I tried to add | allready, didn't work)
Please don't post text walls here, rules are a bit more strict
[Rule #6](#rules message): Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.
Please take the time now to review all of the rules and references in #rules.
For sharing code or logs use https://dpaste.org/ (pick YAML for the language) or https://www.codepile.net/ (pick YAML for the language).
that helps a lot...
@dark sparrow It was not intended as help, just explaining the rules here
For multi line format use:
value_template: >
{% set whatever %}
{% set even more %}
{{ foo }}
You also need to check how you can refer to the state_topic. In the examples this is normally value_json but your payload is not json. I'm not completely sure how to refer to it, but I don't think data will be valid
And you added an additional { and } to the template which shouldn't be there
Do I need to define value_json? When adding a mqtt sensor i get the values in HA but also a lot of error in logs saying " 'value_json' is undefined when rendering". The payload is: {"temperature":"30.00" } and value_template: "{{ value_json.temperature }}" is used in configuration.yaml.
value_json is the data you get in the state topic
I guess you need to prevent errors like that using the availability templates
availability_template: "{{ value_json is defined }}" might do the trick
But I'm not an expert on MQTT sensors
Thank you! Will try!
Well, the fault in the log are still there and the sensordata is being read. Will try to google some more.
Are you sure the log messages are not old? Did you clear the logs?
But does is have 30 as it's state?
Right now it sends random data between 0 and 50 every second. I added the sensor to a guage on dashboard and it shows values between 0 and 50 every second.
Hi do you know why this doesnt work?
entity_id: '{{input_boolean}}'
state: 'on'```
as in it wont let me save giving me Message malformed: Entity {{input_boolean}} is neither a valid entity ID nor a valid UUID for dictionary value @ data['sequence'][2]['if'][0]['entity_id']
It a variable passed in to the script
Interesting, but this works above it
data: {}
target:
entity_id: '{{ input_boolean }}'```
You cannot provide a template there. If you want to use variables in a condition like that, you need to use a template condition
value_template: '{{is_state(input_boolean,''off'')}}'```
ahhhh im sorry, it just abnormal to me
but this didnt work
assuming that input_boolean is the name of an actual input_boolean.xxxx entity, I would replace the '' with "
if by "didn't work", you mean this: #automations-archived message
then...
| selectattr('state', 'eq', 'on') | list| count)| str, "0")}}```
how would i do something like this?
like what?
{{ states.input_boolean | selectattr('entity_id', 'search', '_d_vacuum') | selectattr('state', 'eq', 'on') | list| count == 0 }}?
just guessing from the mess ๐
hi, how dangerous is the mode "restart" ? my automation checks if the outdoor temp is lower then the indoor. If its below HA sends a notification after them he waits 12hrs again until sunset goes down.
Ahhh I do need to explain more, so im looking for a way to check if all booleans are false, This is way i found online states.input_boolean | select('search', '_d_vacuum') | selectattr('state', 'eq', 'on') | list| count
which give me all of vacuum boolean that are on, but when I put
{{ states.input_boolean | selectattr('entity_id', 'search', '_d_vacuum') | selectattr('state', 'eq', 'on') | list| count == 0 }} (yea i changed it to yours because you somehow from my mess got what I wanted)
into a conditional template like so >
value_template: >
{{ states.input_boolean | selectattr('entity_id', 'search', '_d_vacuum') |
selectattr('state', 'eq', 'on') | list| count == 0 }}```
But give me back
`template value should be a string for dictionary value @ data['value_template']. Got None`
not sure why?
I mean, like
check temp lower then 79
if not, restart
now you're back to this: #templates-archived message
I dont think restart is the way to go, probably a if then instead
that's not what mode: restart does
yea your right, if I save it worked, my bad
@vast rapids posted a code wall, it is moved here --> https://hastebin.com/igotojiluj
i share my code here before I screw everything up
https://hastebin.com/igotojiluj
thx bot
[Rule #6](#rules message): Please do not post codewalls (text longer than 15 lines) - use sites such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
Please take the time now to review all of the rules and references in #rules.
well, it will fight the delay
the delay means nothing with mode: restart
again, "dangerous"?
hm I've set the delay to 12hrs bc to wait to the next sunset and send it once a day
I think you have the right code, but remove the delay. The trigger will tell it when to fire and will only happen once a day being passive otherwise. mode is not going to impact unless the trigger are close together and the script run that long. An example would be checking if a light is on wait 20s and text the phone. Say the light changes in 10s. You might want to put it to restart so it only text you the light was turned off. Since it will stop in the middle of the 20s to text the phone the light would be on and wait another 20s to tell you that the light is off.
- platform: sun event: sunset offset: minutes: -10 this only run 1 a day
Why the delay? It doesn't have any function here
Oh sorry, should have read everything
My complexity radar is going off, so this may be a bad idea to pursue as a programming challenge, but I'm curious so I'm going to ask anyway.
I've have created a sensor which remembers the last state the heat pump was running in, so it can be turned on back to the same state.
(There is some added complexity to make an educated guess if the sensor has no data, which occurs after Home Assistant is restarted)
See code below -it's working as intended:
https://www.toptal.com/developers/hastebin/osizubujaw.php
My questions are:
- How would I write one chunk of code to be usable for all 3 heat pumps I own?
As it is now, I have 3 identical blocks, except the entities being referenced are changed.
This rejects complexity which is very good. - Would it become significantly more complex to make a change like this?
How many more elements would I need to create and reference to make that happen, or is this something that can be done fairly simply?
What I'm imagineing sounds simple to explain, but I don't know what tools I'd need to implement it.
Why not store the state whenever it changes with an input_text or similar?
And use a template to set the name with the entity_id being a input_text.{{heat_pump_id}}_state or similar?
That sounds about right. I'll look into that.
Thanks!
Bonus, you can skip all the recalculating when HA restarts
Oooo
Are those values persistent after a restart?
That's rad
Yup, they are. Unless you set a default in which case it will revert to that.
Hello, what did I do wrong here?
value_template:
{{ state_attr('weather.dwd_weather', 'temperature')|float(0) > states('sensor.temperatur_10'|float(0)) }}
getting a AttributeError: 'int' object has no attribute 'lower'
I do get valid numbers for each on their own
ahhh, I see. thank you very much. got it
hi, short question, when i run this automation (and according script): https://dpaste.org/VEsKc
i get this error:
Error: Stream already recording to /media/12:23:40-24.07.2022.mp4!
looking at the trace confirms, that the filename have not been updated with the second iteration:
https://dpaste.org/34jOE
so why {{ now().strftime("%H:%M:%S-%d.%m.%Y") }} have not been evaluated in every iteration of the loop, or what am i misunderstanding here ? thx!
now() is only evaluated once per minute
oh, ok wow thanks
is ther a documentation to this ?
and is there an alternatvie which is evaluated with a shorter cooldown ?
I don't see it mentioned here, but you can believe me on my word :)
https://www.home-assistant.io/docs/configuration/templating/#time
You could add repeat.index to your filename to make it unique
i do believe your words ... i was just wondering if i overlooked something
โบ๏ธ
oh, it seems that i am facing another issue as well ... i assume that there is not more than one stream at a time allwoed from a camera
because now the file names di differ thanks to your recommendation with reperat.index but on the second iteration it still says Stream already recording to /media/13:00:08-24.07.2022_r1.mp4!
do you have an idea how to record contiguously from a camera entity with the service camera.record and save it to clips, one after another ?
That would be a question for #cameras-archived or #integrations-archived I guess
is anyone running a dynamic weather template or integration? Ideally, I'd like to see the current weather based off of the location of my phone. If it helps, I use the iOS companion app...
Hi guys! Is there a way to get number of seconds since HA was restarted? I would need that for a comparison in a condition. Normally I want to wait 15 minutes, but when restarted, and conditions are right, I want it to pass. This is what I would need to compare it against {{ (((as_timestamp(now()) - (as_timestamp(states.sensor.weather.last_changed))) | int) > (60 * 15)) }}
something like homeassistant.restart.last_changed? or is there a better way to do this please?
That is perfect, thanks @inner mesa !
I would like to create a new sensor that depends on two others. New sensor state = if sensor a=true then state 1, if sensor b=true then state 2, if a+b true = state 3. is this something that can / should be done through a template? if yes, what would be my approach?
It's most easy to start with state 3, then you don't need to check if the state of the other sensor is false
and sensor states are unlikely to be "true"
For the other states
yeah they are on and off, that is correct
Ah, you changed it ๐๐ผ
it's a different scenario than yesterday and I just used true as an example to illustrate my goal but thanks for spotting it
it would still be a value_template, correct?
Depends on where you use the template
Oh wait, it was a new sensor, if you use the legacy template format it is value_template
but not sure if that's the best place
And what you just posted is the legacy format
yes, a new sensor, relying on two existing ones
it's the only format I know so far I guess, as I do have many value_template sensors in my config
Well, they are still valid
I have 3000 lines of value_templates
so I do hope they stay valid for a while
so should I start with something different then?
thanks, will try to come up with a first draft
template:
- sensor:
- name: fenster_buero
state:
{% if binary_sensor.buro_2_auf == 'on' and binary_sensor.buro_2_kipp == 'on' %} 'Fenster zu'
{% endif %}
my first try, it says "missed comma between flow collection entries"
more like this?
template:
- sensor:
- name: fenster_buero
state:
{% if states('binary_sensor.buro_2_auf') == 'on' and states(binary_sensor.buro_2_kipp') == 'on' %} Fenster zu
{% endif %}
You quoted the sensor name in the first one, but not the second
yeah missed the entry one, fixed
It's better, but a) you should use is_state(), b) you need >- to introduce a multi line template
and iif() for a more concise statement
and I should prefer this over the == ?
I will have three different states, so this would not apply here, would it?
If I understood the question correctly he needs two elifs
yeah those will come, you suggested to start with one though
From the current state I can see that he attached two door/window sensors to a window to detect how it is opened
my windows has two different "open" positions and one closed
Yes, because your elifs will be easier if you already checked for this one
yes, more or less (they are builtin, not attached)
But normally they are on when open, so both off them being off would mean the window is closed
yeah I agree mine are a bit weird, they are "on" in the closed position coming from "magnets are connected=1" etc
- name: fenster_buero
state: >
{% if is_state('binary_sensor.buro_2_auf', 'on') and is_state('binary_sensor.buro_2_kipp', 'on') == 'on' %} Fenster zu
{% elif is_state('binary_sensor.buro_2_auf', 'on') and is_state('binary_sensor.buro_2_kipp', 'off') == 'on' %} Fenster gekippt
{% elif is_state('binary_sensor.buro_2_auf', 'off') and is_state('binary_sensor.buro_2_kipp', 'off') == 'on' %} Fenster auf
{% endif %}
like this?
good night and thanks for your help!
Remove the == 'on' in every statement
oh yes
makes sense
thanks
well, I don't want to keep you away from your sleep ๐
And putting this one first was to avoid the check for off, it is not needed as you already know they are not both on
don't think I understand
Binary sensors have two states on or off
agreed
You already check in your first statement if they are both on
agreed
If that results in false, it will move to the next statement
agreed
If you check for a sensor being on then, and that is true, you know the other must be off
As you already know they are not both on
ahhh, I see what you mean, thank you
That is why I suggested to start with that one
that's smart, thank you
Now I'm really off to bed
enjoy!
holy wow it works!
so, now I have a few of these and would like to count how many windows are in each state. what would be the best approach todo this?
binary_sensor:
- name: "pir1"
state_topic: "tele/B_Kitchen/MotionBedroom/SENSOR"
value_template: "{{value_json.MotionBedroom.Occupancy}}"
payload_on: "1"
payload_off: "0"
availability:
- topic: "tele/B_Kitchen/LWT"
payload_available: "online"
payload_not_available: "offline"
qos: 0
device_class: motion
can anyone tell me why this won't work ?
MQT: tele/B_Kitchen/MotionBedroom/SENSOR = {"MotionBedroom":{"Device":"0x7184","Name":"MotionBedroom","Illuminance":81,"Occupancy":1,"Endpoint":1,"LinkQuality":24}}
turns out on 1 and 0 don't need quotations
Try removing the quotes around payload_on and payload_off?
yes!
is there a way to auto discovery entitties in my sonoff zigbee bridge just through mqtt ?(without ZHA)
{{ states.sensor | selectattr('state', 'eq', 'Fenster zu') | list | count }}
How would I go about creating a key:value set of entities and their states? I can create a list of the entities using integration_entities() but I'm struggling to find a way to transform that in to key:value pairs. I've considered using map() but I don't think that is going to produce the end result I'm after as I think, if I understand it correctly, it just produces a list of the requested attributes. I also looked at dictsort() but, again if I understand it correctly, it will only sort a set of key:value pairs, not create one.
I then though items() might be the go but that hasn't worked out either.
you need a for loop for that, with a namespace
do you want this (example using media players):
media_player.living_room: playing
media_player.bedroom: paused
or this:
- entity_id: media_player.living_room
state: playing
- entity_id: media_player.bedroom
state: paused
Hmm... I think I am after option A. Ultimately I want the template to return the key from the list that has a particular value.
you might be better of with option 2 then, you could do somethingl like {{ template_result | selectattr('state', 'eq', 'paused') | map(attribute='entity_id') | list }}
which would return media_player.bedroom in the example above
You can do the same with option 1, but the template would be more complicated
I think your example is pretty close to where I'm headed. I'll play around a bit in the Dev Tool and try and sus it out. Thanks.
You know how to work with namespaces and for loops?
Not really. I think I understand how a for loop works but I don't get what you mean by namespaces.
{{ p | selectattr('state', 'eq', 'Open') | map(attribute='entity_id') | list}}```
results in `UndefinedError: 'str object' has no attribute 'state'`
you need to expand p
you are only intereted in those with state Open?
you don't need the complete overview with all input_selects and their states, like above?
{% set p = integration_entities('input_select') %}
{{ expand(p) | selectattr('state', 'eq', 'Open') | map(attribute='entity_id') | list}}
Well, each input_select will have 3 states I want to monitor for.
I have 15 roller shutters I want to control for Open, Shut and Partial. I am trying to avoid the need for 45 separate automation's and figured I could compress it down to 3 by using a template to pass the id of the shutter that called for it.
Jumping back to your example of selectattr('state', 'eq', 'paused') how did you know to use 'eq' in there? I can't find that kind of information in the jinja2 template docs.
you can also use '=='
So I do I know what can be used in the position? Is there a list somewhere?
but the tests you can use in select() or selectattr() are mentioned here https://jinja.palletsprojects.com/en/3.0.x/templates/#list-of-builtin-tests
Ah.... of course ๐คฏ
@mighty ledge I just had a look at these tests, do you by any chance know why this {{ [ 3, true, '3' ] | select('number') | list }} also returns true in the result.
The same when I use select('is_number') instead of number. In that case it also includes '3' (as expected)
select('boolean') works as expected and returns only true
thank you
this will still be a template sensor, correct?
- name: anzahl_fenster_zu
state: {{ states.sensor | selectattr('state', 'eq', 'Fenster zu') | list | count }}
tryng this as template sensor, doesn't seem to be complete yet as the sensor below this one is now getting errors
ah it works with a linebreak in between
thank you
You need to put quotes around your template if you use single line notation
hah that explains it, thank you
and you don't need to lowercase and underscore your name
thanks again
You can use Anzahl fenster zu, it will determine the friendly name of the sensor
and HA will lowercase and underscore it to use as entity_id
if you add a unique_id you can change it yourself in the GUI
ah nice, thank you
you are great ๐
I do have template covers that have status of the cover and open/close etc. commands. since those are attached to the same windows that I am checking for opening state, what is the best practice to group those together? I would prefer to have a window entity with cover status, control and opening state of the window (not cover). is this possible?
If you want control of the covers, you need to have a cover entity, I don't think you can add the window state to that
I see, so the best practice would be to align them close on the dashboard?
That'll be something for #frontend-archived but I would say a vertical-stack, or maybe custom:vertical-stack-in-card if you don't want borders between the cards
got it, just wanted to check if there is another approach. thank you
I'm getting
Error: dictionary update sequence element #0 has length 1; 2 is required
I googled and it may be related to target? I am trying to use a single service call to do everything. The second (hard coded Boolean) will be removed soon.
Target will default to target: {} if it is not a service call of set Boolean or switch.turn_on/off. I tested calling a service from developer tools such as calling a script with
service: script
data: {}
target: {}
And it worked.
https://dpaste.org/sg6vF
I'm also having a funky issue where my condition is evaluating to false when it should be true and I tested it in the template editor. The
liights variable should be true when the trigger entity id is either of the 2 and in template editor it is. The entire condition evaluates without errors I tested piece by piece and all together. For some reason it evaluates to false every time for either trigger.
target_condition: |
{{ {entity_id: target_data } }}
entity_id needs to be quoted here, as it is not a variable
Yep I just did that. When I noticed it said undefined.
Same trigger as before and now I get
Error: Template rendered invalid entity IDs: "{}"
I was expecting that
You need to put your service call in an if-then
- if: "{{ iif(target_data) }}"
then:
- your current service call
And an else for if it's not?
or just add it to the condition
{{ iif(target_data) and (lights or switch or event_lights or event_switch) }}
why did you put the condition in a variable, and not directly in the value template of the conditon?
Seems a bit redundant this way
Just to keep it clean, and not have a ton at the top. How would it work to add that to the condition? I'm trying to understand how it would stop the issue while still allowing the rest of the service calls to work?
yes, I was about to mention that
the if-then is better then. the else is optional, you can leave it empty
btw, you better default target_data to [] instead of {}
as entity_id expects a list, not a dict
The condition works with the exception of the light variable. It keeps failing. Still trying to understand it because the calls are script, switch or boolean. So if I condition the call itself to having target_data then wouldn't it mess it up if it doesn't? Going to try [] now
this indicates it tried to do this:
target:
entity_id: {}
which will be the case if target_data results in {}
service: script.off_daniels_bathroom_lights
data: {}
target: {}
I was trying to do this which works when calling it from developer tools. I think I need to condition target_condition to not appear and be '' unless it has to appear
That also will not work, your service call expects data there
you should only perform the service call when all data for the service call is available, hence the if-then I proposed
I also don't fully understand the need for target_condition here
- if: "{{ iif(target_data) }}"
then:
- service: '{{ service }}'
data: {}
target:
entity_id: '{{ target_data }}'
or even simpler
- if: "{{ target_entity in ['switch.daniels_bathroom_fan_switch','input_boolean.daniels_bathroom_fan_automation_running'] }}"
then:
- service: '{{ service }}'
data: {}
target:
entity_id: '{{ target_entity }}'
then you don't need the target_data variable
I just realized. I am setting {} as default but it will not be read that way because I am using target_condition and in it's current form it won't even read {} properly as it reads entity_id: {} the goal would be for that line to just '' when it's not needed. I am trying to key the entity_id. The purpose of setting {}```` to default was so that it would be `target: {}` when it was not needed. But it's not going to do that the way I have it setup. If I could set that to `target: {}` and then when needed bring in `entity_id: x it would work? I was leveraging an automation Petro helped me with a while back where he variablized the key.
https://dpaste.org/w550O
I was trying to do all of this in a single service call. The service_data variable is what he used
Making everything a variable
this condition will also run in error when the trigger is your event trigger or the home assistant start trigger:
- condition: template
value_template: >-
{{ trigger.entity_id == 'sensor.daniels_bathroom_fan_off' and
trigger.to_state.state == 'True' }}
The way you set it up, it ends in what I posted above, not what you just posted
#templates-archived message
I see it's not possible to do this
{{ {iif(target_data != '','entity_id:',''): target_data } }}
``` Without a `:`
I'll use if-then Any idea why the lights variable in the condition is not working
The fact that the GUI completely messed up your templates also doesn't help
Yes I really hate that with a passion.
but I kinda see why you need an empty target: now, you also have a script as service, which is perfectly valid with an empty target
Simple solution, don't use the GUI
Yes that's what I was aiming for. Just use an empty target when it's not needed. Then I wouldn't need if-then and just a single service. But it doesn't appear possible to make the key just not be there. As soon as entity_id is there it messes it up.
you can replace this:
target_data: >-
"{{ iif(target_entity in
['switch.daniels_bathroom_fan_switch','input_boolean.daniels_bathroom_fan_automation_running'],target_entity,'{}')
}}"
target_condition: |
{{ {entity_id: target_data } }}
service: script.off_daniels_bathroom_lights
data: {}
target:
entity_id: []
Worked hm
with:
target_condition: |
{{ {'entity_id': target_entity } if target_entity in ['switch.daniels_bathroom_fan_switch','input_boolean.daniels_bathroom_fan_automation_running'] else {} }}
that also works because an empty list is a valid target
an empty dict is not
It worked!!!!!
What you did ^
Now the question is why is the light variable broken in the condition or something messed up but isn't because I validated the entire thing in the template editor.
This one:?
lights_script: >-
{% if (now() >= today_at('05:50') and now() <= today_at('18:30')) %}
script.morning_daniels_bathroom_lights {% elif (now() >= today_at('18:30')
or now() <= today_at('05:50')) %} script.night_daniels_bathroom_lights {%
endif %}
This
condition: >-
{% set lights = trigger.entity_id in
['binary_sensor.daniels_bathroom_presence_detector','binary_sensor.daniels_bathroom_motion_sensor_1_home_security_motion_detection']
and lights_status != set_lights %} {% set switch = trigger.platform ==
'event' and trigger.event.data.command == 'Away' and switch_status !=
set_switch %} {% set event_lights = trigger.platform == 'event' and
trigger.event.event_type == 'automation_reloaded' or trigger.event ==
'start' and states('binary_sensor.daniels_bathroom_presence_detector') ==
'off' and lights_status == 'on' %} {% set event_switch = trigger.platform ==
'event' and trigger.event.event_type == 'automation_reloaded' or
trigger.event == 'start' and states('sensor.daniels_bathroom_fan_off') ==
'True' %} {{ lights or switch or event_lights or event_switch }}
GUI makes this look awful.
Not working as In when the trigger is one of those sensors it's not working. It's failing. When the trigger is one of those sensors and I can visually see the variables light_status and set_lights are not equal it should pass. It isn't.
I tested it with this. How do you set a trigger.entity_id or trigger.platform variable in template editor? I remember you showing me once but I didn't take note of it. I have to remove the . or it doesn't work.
https://dpaste.org/brOWq
Then I just asked for {{ lights }} and it was true.
{% set trigger = { 'entity_id': 'binary_sensor.daniels_bathroom_presence_detector', 'platform': 'state' } %}
Perfect that will be much easier to test these big templates now
you can also just open the trace, and copy the entire trigger json from there
Bug in the app as I couldn't download trace for some reason. It kept crashing. Had to open a Browser
I didn't need the trace, it was just a tip to copy the trigger object from the trace to
> template
Hello, I have a weird one. Template sensor is derived from the state of an input number. This sensor has worked for several months. Today it is unavailable despite the input number still being populated. Not sure how to even troubleshoot this one as it should just work. The template sensor is:
template:
- sensor:
- name: "Electricity Demand Max"
unique_id: electricity_demand_max_sensor
unit_of_measurement: kWh
state: >
{{ states('input_number.electricity_demand_max') |float(0) }}
and {{ states('input_number.electricity_demand_max') |float(0) }} in the template editor returns 1.422 as expected where as {{ states('sensor.electricity_demand_max') is unavailable. Is it possible the template sensor has become unavailable because the input number has been static for a couple of weeks?
Oh I see
even if the source input_number would be unavailble it should return 0
are you sure it didn't create a 2nd version (sensor.electricity_demand_max_2)
I'm trying to list entities from a group:
this works using jinja filters:
{{ expand(state_attr('group.alllights', 'entity_id')) | rejectattr('entity_id', 'in', ['light.li08_bedside_lamp_01', 'light.li09_bedside_lamp_02']) | map(attribute='entity_id') | list }}
But I can't seem to get a for loop to work:
`{% for x in expand('group.alllights') | rejectattr('entity_id', 'in', ['light.li08_bedside_lamp_01', 'light.li09_bedside_lamp_02']) | map(attribute='entity_id') -%}
- {{ x }}
{% endfor %}`
What am I doing wrong
The for looop work in the yaml template editor but when trying to use it with e.g. light.turn_on it throws an error in the "Dev Tools | services"
@tepid onyx why do you want a loop? The first one creates a perfectly valid list for you to use in your service call
I'm using the first one but I haven't used for loops for ages now I can't get it to work...
having a brain fart what am I missing
you don't have to use the loop
why do you want to use it?
- service: light.turn_off
target:
entity_id: >
{{ expand(state_attr('group.alllights', 'entity_id')) | rejectattr('entity_id', 'in', ['light.li08_bedside_lamp_01', 'light.li09_bedside_lamp_02']) | map(attribute='entity_id') | list }}
Thanks, I found a sneaky bracket that had snuck into my config weeks ago but perhaps I had not restarted until today. removing that resolved several related issues.
yes I know I don't have to. But I can't remember how to do it with a for loop. I want to know why it's not working
because HA will do whitespace control, and put them all in one line:
- light.1 - light.2 - light.3
that's not valid
you need to provide a list like this if you want to use a template [ 'light.1', 'light.2', 'light.3' ] which is what the first template does
I don't understand why you are making it so hard for yourself
If you want to use a loop, you need to use a namespace, and add the values to that
{% set ns = namespace(lights=[]) %}
{% for x in expand('group.alllights') | rejectattr('entity_id', 'in', ['light.li08_bedside_lamp_01', 'light.li09_bedside_lamp_02']) | map(attribute='entity_id') -%}
{% set ns.lights = ns.lights + [ x ] %}
{% endfor %}
{{ ns.lights }}
Which will give the exact same result as your first template
Is there a easy way to change the day in dutch? Now it prints Monday 25/07 instead of Maandag 25/07
"{{ now().strftime('%A %d/%m') }}"
I'm creating a combined weather entity, which combines the forecast of multiple weather entities
any advice to make this more efficient? https://dpaste.org/t3Vrm
lemme take a look
so
first thing I notice is taht you do this
{% set datetimes = (expand(entities) | map(attribute='attributes.forecast')| list)| sum(start=[]) | map(attribute='datetime') | unique | sort | list %}
pretty sure sort is already a list
if it's a generator, you'd just want to declare that in the for line
otherwise, I think it looks good
okay, thanks
well, whats the iif doing for iif(pp)?
seems odd to me
i don't use iff
so, if you're just turning into true/false, you can optimize that by just doing if pp, and emtpy list in an if statement is essentially false.
Ah yeah, that's all that's doing. So just remove the iif() around the pp, no point
changed the last line in the for loop to {% set ns.forecast = ns.forecast + [ dict(f.items() | list | selectattr('1')) ] %} to remove the none items from the dicts (if there is only one weather entity left which eg doesn't provide wind_speed)
and removed the iif()
yeah i usually do that part differently
whenever i'm adding dynamic things, I'll use namespace and add items to alist
but it ends up being moreif statements
What would a combined weather entity allow you to do differently? As in what are the use cases, sounds interesting. Also pretty cool to see 2 legends working together!!
I think he just want's to know what each one is saying and get a 'crowd sourced' result using a bunch of weather entitites
I especially want to always have a temperature and forecast and such available
I may have some use for something like this to clean up what I do with pulling in weather data. Definitely interested in seeing the final yaml if possible @marble jackal and the template for the sensor.weather_entities
So if I combine 3, I think 1 of them should be available ๐
Yep That's what I'm thinking I end up having to have a bunch of extra code to ensure there's at least something working. By doing a bunch of "or".
the template sensor is basically only there to have a list of entities excluding the combined weather entities themselves, so the data of the combined weather entity is not included in itself
I see. Very interesting. Always something to learn. I always thought about combining weather data but didn't know how or if it was possible. But anything is possible it seems with Jinja.
Thank you!.. hm invalid response?
yeah, I get the same
but I copied it directly from my browser screen
you can navigate to it from the link in my profile ๐
Yep i found it. Thanks again.
@winged coral posted a code wall, it is moved here --> https://hastebin.com/juvecasomu
Hi guys I'm having some trouble with a rest sensor and templating the resulting values. Currently I get one sensor Salah times where the value is string with all the timings' json, and Fajr, Dhuhr, Asr, Maghrib and Isha templated entities just show up as unknown. How would I change my config (linked below) so that the individual times are populated and I suppose get rid of the overarching Salah Times catch all entity?
I think you might actually need the RESTful integration, instead of your current approach: https://www.home-assistant.io/integrations/rest/
Are you sure the Salah times sensor actually has the ID of sensor.json_time? It seems unlikely
if you don't want to change much, you have to add json attributes to your rest sensor. You're assuming it's creating the attributes for you, but it's not.
so, just add json_attributes_path: $.data.timings
Why is the first one not working - If I understand the docs correctly, the first syntax is better to use if values are not available during boot etc.```
{{ state_attr('cover.left_garage_door', 'last_updated') }}
{{ states.cover.left_garage_door.last_updated }}
it's not an attribute
it's a property of the state object
there's no alternative to the second one
Thank you for explaining - much appreciated! Everyday I learn a little more... ๐
Hi, I think templates are the right tool for my task but I need some help understanding time-based rules. I have a computed temperature difference between 2 other values already, called deltatemp. I want to cycle a zigbee on or off based upon tolerance of the deltatemp but want to 'dampen' it over time with this logic:
deltaT > 1.5 for 120seconds = ON
deltaT < -0.5 for 120seconds = OFF
any ideas?
I need some sort of rolling time evaluation and I can't quite wrap my head around it (i'm a python guy)
Why not two numeric triggers and call the zigbee cycle in the actions?
Are alternatively, perhaps two binary template sensors for the below and above values and use that as triggers. state on for x minutes/seconds
Thanks @mighty ledge @silent seal needed a combination of both to get it working:
humm, possibly...
how do I cast these to times?
am I right in thinking it would be using https://www.home-assistant.io/docs/configuration/templating/#states-examples ? I'm just not sure as to the syntax and how it applies to my config
that's unlikely to work ๐
since states are strings, and you've made the number 1.5 a string, too
it returns false
comparing a string with a string when you want a numeric comparison is unlikely to be what you want
yes
what does it have to do with a "time value calculation"?
it's a calculation for a custom cooling unit (think refrigerator) and I'd like it to not cycle too frequently, so if it passes that threshold for say 2mintes, then cycles off
that just sounds like a numeric_state trigger: https://www.home-assistant.io/docs/automation/trigger/#numeric-state-trigger
I will look into, thanks much!!!
I'm not I understand this portion, "and fires if the value is changing from above to below or from below to above the given threshold" The example uses 17 and 25 as 'above' and 'below' values
it triggers when it crosses one of the thresholds that you established
yes
ok
I see
so the logic for this automation example would be turn on switch when above value and turn off switch when below? or is that not stated explicitly in this example?
if you want that, you should use two triggers to differentiate the two different events
specifying both above and below is providing a range that will cause a trigger when the value transitions into that range
np, so one to turn on, with only above and another to turn off when below?
yes
awesome, ty
I'm trying to use a sensor attribute as a url for an attachment but I can't get the correct format to show the picture in the notification
attachment: url: "${states['sensor.overseerr_movie_requests'].attributes.last_request_poster}"
that looks like Javascript
I tried so many combination
this channel is for Jinja templates
Is it possible to show the link in jinja to work with the attachment url?
something like url: {{ states.sensor.overseerr_movie_requests.attributes.last_request_username }}
The sensor attribute is returning an URL which show an image, I'm using that to be shown in the notification data
But i'll keep digging
thanks tho
Hey @inner mesa like this?
@rain grove posted a code wall, it is moved here --> https://hastebin.com/kahevizolo
that's not similar to what you had above
you want to trigger if the sensor value becomes exactly -1 and stays there?
I pointed you to a numeric_state trigger and you've used a state trigger, rarely a good choice for a value crossing a threshold
{% set q = expand(p) | selectattr('state', 'eq', 'Open') | map(attribute='entity_id') | list %}
{{ t[0] }}```
Works fine so long as one of my `input_select`'s is displaying `Open` but, obviously, if none of them are then the list is empty which leads to `UndefinedError: list object has no element 0`.
What can I do avoid this error? I was thinking of defining the q first with a single entry in the list and then appending the list with the above template thereby ensuring the list always has an element but I realise this wont work as I'll then want to call t[1] which will just give me the same error except for element 1.
I think I solved it. I thought I'd try defined() and it works okay.
{% set q = expand(p) | selectattr('state', 'eq', 'Open') | map(attribute='entity_id') | list %}
{% if q[0] is defined %}
{{ q[0] }}
{% endif %}```
You could also use {{ q[0] | default() }}
That is probably the better option. Thanks.
Anyone know why on automation reloaded and the presence detector is on which needs to be off to be true in the service variable it keeps evaluating to true.
https://dpaste.org/9AGDh
It probably reads if (platform = event AND event = reload) OR (event = start AND presence = off). Add some parentheses where you want them instead.
I tried. Adding it around the and ( presence = 'off' ) but it didn't work.
{% elif trigger.platform == 'event' and trigger.event.event_type == 'automation_reloaded' or trigger.event ==
'start' and (states('binary_sensor.daniels_bathroom_presence_detector') == 'off') %}
You'd want if platform = event AND (event = reload OR event = start) AND presence = off, I guess.
Do you understand why?
The first method would be true if the platform was even and the even was reload. But it would also be true if the event was start (regardless of platform) and presence was off.
Those parentheses don't actually make any difference.
Yes I remember Petro schooling me on pemdas (order of operations). After being schooled a few times lol I usually get it right figuring out where to add parenthesis just not this time.
You can replace states('binary_sensor.daniels_bathroom_presence_detector') == 'off' with `is_state('binary_sensor.daniels_bathroom_presence_detector', 'off')' by the way. That adds some protection against errors in some cases.
Which errors would it cause?
The order of boolean operations (and/or) is always weird. And can also vary from language to language. I always put parentheses just to be sure.
In your case states( likely won't cause any problems, but in some cases if the entity doesn't exist you'll get weird errors. It's good to just get into the practice of using is_stateIMO.
Hm that's interesting. I never saw that but it's good to know. I just thought it was about preference to use either one. Not that one had a graceful fail vs the other not having it.
The problem with an == check is if the types do not match, then it throws a wobbly. And if your entity is unavailable, then the type is a string regardless of what else it may have been before.
Interesting thank you for the explanation
Though usually states are strings, but attributes may not be, hence is_state_attr also being a nice function.
all states are strings, attributes can be a native type
I was pointed here to request assistance with cleaning up this template trigger. Currently it is working, but I understand this can be done more streamline. I would appreciate assistance on how to do this better that I can apply it in future ideas too.```
trigger:
- platform: template
value_template: >-
{% set t = now() %} # To make it update every minute
{{ (states | selectattr('entity_id','in',
state_attr('light.group_outside_security_lights','entity_id')) |
selectattr('state','eq','off') | list | count) >= 0 }}
Iโd start by looking at this: https://www.home-assistant.io/integrations/template/#trigger-based-template-binary-sensors-buttons-numbers-selects-and-sensors
The time pattern should help you automatically update every minute ๐
I'm trying to steer clear of adding a "helper" entity and using a template directly in the trigger
I read that you added the now() to have it evaluate every minute, but that makes no sense, it will already update on state changes
Thatโs why I suggested the time pattern trigger to update every minute, if thatโs what you actually need/want
I thought so too, but when turning off one of the lights I would have expected it to re-evaluate and turn the light back on, which it does not do
trigger:
- platform: template
value_template: >-
{{ expand('light.group_outside_security_lights') |
selectattr('state','eq','off') | list | count >= 0 }}
The template does not do actions
Not sure I'm following...
This could work and use the template as a condition, e.g count on < count members. But this will still only evaluate every minute or so. Ideally would be to have it react instantly when someone turns off one of the lights
Let me quickly change to this and see if it works...
Thx - Will go through this quickly... brb
Groups are what you want. Take a look at how template sensors work and update usually, and then look through the triggers for more info ๐
Thank you - I think I have an okay understanding of those two. What I'm still getting my head around is the whole iterating through groups etc... I'm forcing myself to familiarise myself with jinja
In case you want it to update on state changes of all group members, this will work
trigger:
- platform: template
value_template: >
{% set entities = state_attr('light.group_outside_security_lights', 'entity_id') %}
{{ expand(entities) |
selectattr('state','eq','off') | list | count >= 0 }}
The good news about Jinja, is itโs very similar to many other templating languagesโTwig, Blade, Liquid, etc.
However, it will not trigger again if a second light turns off
@marble jackal You are the man! I removed the '=' and the forgotten bracket after count and it is wokring a charm now!```
- platform: template
value_template: >-
{{ expand('light.group_outside_security_lights') |
selectattr('state','eq','off') | list | count > 0 }}
The delay in your version was caused because your were irritating over the entire states object, and that is only done once a minute
I'm very rusted in that department - haven't really touched anything in that realm for over a decade. But its fun and frustrating to do it again ๐
states.domain is limited to once per 10 seconds
If I'm correct ๐
At least both are limited
Awesome! So just to make sure I grasp this, if I iterate over states, HA will throttle this to once per minute
Nevermind - saw you just answered this ๐
The fun part is good. The Jinja docs are good, as is the template editor. And of course, you can always come in here with an example and a description of what youโre trying to do for some help.
I absolutely love the template editor - Spend a lot of time there trying to figure stuff out. And as always the help here has been overwhelming - I dont think it gets said enough, the HA community is brilliant and the help here invaluable. ๐
Agreed, so many helpful folks, so many ideas to steal, the limit is the time in which to implement the ideas, and the cash to spend on the cool gadgets ๐
All true, I keep a "to-do" list on Google keep of ideas to implement. Lack of time is traded off against sleep, unfortunately the last one is the biggest hurdle, not to mention the maintenance as these gadgets age/breaks... ๐ That said, I have been building on my instance for a few years building it up, and I'm very very close to having everything I need on HA - Only a few lights & PIRs left HW wise...
Fingers crossed - I'm still running on a RPi and it is coping...
I just hope you have backups off the device, and preferably arenโt running on an SD card. If not, I recommend your next projects are: backups get copied elsewhere ASAP, and then get it booting off an SSD.
In case you are interested. https://imgur.com/TrWNjNF
https://imgur.com/fRyjraU
Backups local & cloud. And I am indeed still using an SD Card ๐ But I did address it, sort of, I store all data on an USB 3.0 Drive, and the SD card has been configured to minimise the R/W cycles to almost zero. They also get replaced once a year, needed or not. This policy came into place after the first one went belly up on me
Hi! I'm trying an automation sending a message if the outside temp is less than 1 degree below inside temp. I am using temp reading from the ventilation unit which is updating values precise and often. I used a binary sensor evaluating temperatures which then triggers the automation which sends notification. It makes me nuts as it is going "the wrong way": If it's hot, it states Off... I just want to understand why
- platform: template
sensors:
outdoor_temp:
device_class: heat
friendly_name: Auรentemperatur
value_template: "{{(states.sensor.vallox_outdoor_air.state) | float > (((states.sensor.vallox_extract_air.state) | float )-1 )}}"
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. Here's an example
Don't forget you can edit your post rather than repeatedly posting the same thing.
For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).
You should use states() instead of states.entity_id.state, see the warning here https://www.home-assistant.io/docs/configuration/templating/#states
Great, thanks, I'll do that. However, I am mainly adding entities with dropdown menu of file editor. Is there a way that this directly adds "correctly" with states()?
If youโre typing in the template editor (where itโs easy to test your automation), it definitely auto completes
When working with templates, don't forget:
- You can test them in Developer tools -> Templates
But if it shows on when it should show off and the other way round, I would suggest to change > into < ๐
Absolutely! However I'm just starting and I like to understand what happens so this is my try. However, I never stepped over the template editor. Can it also be used to save templates or only live testing?
Itโs only for testing, you save them by putting them in the place you need them (automation/script actions, template sensors, etc.)
Itโs also useful for debugging
Paste the following code into the Template Builder in Developer Tools to list all sensors and their names:
{%- set domains = [states.sensor] %}
{{ \"Entity ID\".ljust(50) }} {{ \"Entity Name\" }}
{%- for domain in domains %}
{% for item in domain %}
{{ item.entity_id.ljust(50) }} {{ item.name }}
{%- endfor %}
{%- endfor %}
Things like that can be really useful when youโre poking around looking for information.
Perfect. Another help-yourself tool. Thanks a lot ๐ ๐
HA is a lot of DIY. But if you can show what youโve tried then it inspires other users, and makes it a lot easier to help you.
Don't get me wrong. I really love HA, it's great how easy it to create even complex automations. But when it comes to some lines of code I am just at the beginning of a huge and steep learning curve :-D simple double checking tools are great then.
Youโll get there.
And if youโre ever worried about something youโre doing, do a backup first, download it to another device, and then just do it anyway
Worst thing that can happen is you end up restoring the backup you made just before you changed it all.
I have lots of files floating around with bits of old snippets in that I was trying out as a way to help myself in the future. Though, my HA config is in git as well which is the next step up ๐
@inner mesa thanks for your help yesterday, it all works! https://i.imgur.com/Ywx6mbX.png
That's great!
Hey all, got sent here from #automations-archived / #general-archived the problem here would be im having a hard time and huge mess creating it all, ang got said that there is way to much stuff involved like to much booleans, so someone here would be able to help -> So, im at work for at least two hours boolean on, i leave work ( zone ) , booolean is on, send notification, boolean is of, second boolean of leaving work is on, i arrive closer to home ( zone ) , second boolean is on, send notification turn secoind boolean off, i arive at home, noone is home, send notification
this and like another 5-7 automations like this
i think im getting alergic to links with docs ๐ but ill try to understand this one ๐
so its a trigger, like in automations the first part in GUI ?
You should always start by reading the docs and trying things. It's much easier to help someone who says "I am trying to do X, I tried to do this with Y <link to code>, but I'm struggling with Z/it's not working in this particular scenario"
That one is indeed a trigger, very similar to the automations in the GUI.
But there are also template sensors and template binary sensors.
my problem with docs is im understanding like 5% of the stuff there, and thats on a good day, the it's been written, its just unusable for me, i got only that its a trigger, thats all...
Try reading the whole page, and looking at the examples. You can copy the template parts and put them in the developer tools and see what they output.
https://www.home-assistant.io/docs/configuration/templating/ This page is an introduction to templating
the simples way here would be wait for trigger, super easy and really doable in GUI only it doesn't work when im working on HA ...
This is an advanced feature of Home Assistant. Youโll need a basic understanding of:
Home Assistant architecture, especially states.
The State object.
You'll need that for automations in the long run too ๐
and thats where it ends, first two sentences
Easier to get started now, even if all you understand is that a boolean or binary state can be on and off right now.
i've wrote it here like dozen times, its like i have to learn everything in HA just to make a automation and it all in the robotic text of docs, impossible in my case...
p.s. nothing against people who help here !!!!!! ๐ i get it, i have to know each and everything in HA and YAML and so on.
You definitely need to start reading the documentation and googling the terms you don't understand. The HA docs have a search feature which is very helpful, as are the links in the docs and the sidebar.
Both the Home Assistant Architecture and the state object link you to their own pages there to read through.
went back to #general-archived im just done here for today, but still thanks for trying
{% set q = expand(p) | map(attribute='friendly_name') | list %}
{{ q }}```
returns
```[Undefined, Undefined, Undefined]```
Is `friendly_name` not considered an attribute?
it's an attribute, but not that kind of attribute ๐
๐ of course.
{% set p = integration_entities('input_select') %}
{% set q = expand(p) | map(attribute='attributes.friendly_name') | list %}
{{ q }}
and that's easier written like this:
{{ states.input_select | map(attribute='attributes.friendly_name') | list }}
and even easier:
{{ states.input_select | map(attribute='name') | list }}
which will use "name" if it's defined, and friendly_name if not
(I think)
Is "name" the full name of the entity, ie input.select.kitchen_shutters? Or would it just return kitchen_shutters?
Because it just returns the friendly_name when trying in the Dev Tools.
Additionally, what is considered an "attribute" in the first example?
@inner mesa Can I buy you a (virtual) coffee or beer or something? You have been very helpful with all my question and I'd like to thank you somehow.
no coffee or beer needed, happy to help. Thanks for the offer, thoguh
Is "name" the full name of the entity, ie input.select.kitchen_shutters? Or would it just return kitchen_shutters?
neither. input_select.kitchen_shutters is an entity_id and kitchen_shutters is the object_id, which is the part of the entity_id after the "."
the name and friendly_name are things that you assign
Got you.
"attribute" in that statement means "property of a state object"
<that last part is more complicated that I made it sound>
I think I get it though. So by using map(attribute='attributes.friendly_name') I'm passing the dict key of "attributes" of which I want to extract the "friendly_name"
The attribute I want to map is "attributes" and from that I want to extract the friendly_name.
Am I close to understanding?
I think they actually generate the entire set of "attributes.xxx" for each key in the dict and make those available as "attributes" for the purpose of Jinja, rather than it being a general purpose way to index into dicts
but I haven't looked into the implementation
for instance, I don't know if map(attribute='attributes.foo.bar') is valid
I'm now puzzled by how attributes work in Jinja (at least as implemented by HA). Take these statements:
{% set data={'foo':{'bar': 'blah'}} %}
{{ data.foo }}
{{ data['foo'] }}
{{ data|attr('foo') }}
The second and third lines both return what I would expect: {'bar': 'blah'}
The third returns UndefinedError: 'dict object' has no attribute 'foo'
I guess it's because it's an "item" and not an "attribute"? https://jinja.palletsprojects.com/en/3.1.x/templates/#notes-on-subscriptions
Huh, that's unexpected for me too
jinja-filters.attr(obj: Any, name: str) โ Union[jinja2.runtime.Undefined, Any]
Get an attribute of an object. foo|attr("bar") works like foo.bar just that always an attribute is returned and items are not looked up.
Yes, that's what I'd expect. I'll grant I'm a PHP dev and especially thanks to MongoDB am very used to "abuse the code, it'll return what I want", but I really would expect the last one to work
the terminology in the Jinja docs is pretty loose and doesn't usually make a distinction:
You can use a dot (.) to access attributes of a variable in addition to the standard Python getitem โsubscriptโ syntax ([]).
I think I've run into something like this before with the attr where I was trying to get something and HA wasn't working the way the jinja docs said it should
it doesn't look like I can create attributes in my own data structures, just items
then they talk about "elements":
You can mess around with the variables in templates provided they are passed in by the application. Variables may have attributes or elements on them you can access too. What attributes a variable has depends heavily on the application providing that variable.
How odd. It reminds me of whenever I want to create an array, and I have to wrap it in a dictionary first ๐คช
then there's this:
{{ data.items()|selectattr('0', 'eq', 'foo')|map(attribute='1')|first }}
-> {'bar': 'blah'}
I think it's 1am talking, that seems somewhat nonsensical
pretty sure I learned it from petro. It's quite magical
I mean, I understand how it works
but it looks like the only way that I can "create" attributes from my own data structure for use with those functions
But a good chunk of my brain is saying "that seems wrong"
is there a template equivalent of "for:" trigger option?
basically i want to make a wait_template, where the automation will not only wait for a couple of states to be off, but stay in this state for a longer bit of time
Yes, use the last_changed object of the entity
But it might be easier to group all the entities, and use the state of the group
It will be off when all members are off
You can then use a state condition on the group and use for:
Oh, wait, not in a wait_template
But at least it makes your template easier, as you only have to take one entity into account
ahhh, ok this is a good idea but not as universal as ive been hoping for - ive got a couple of automations where i would like to add motion sensing and this last_changed should work fine for those, but ive been hoping for a solution which i could also use for numeric states (so wind speed is lower than... for on hour)
No, that won't work. You can only get that working using a template binary sensor
Which is on when your numeric state is below ...
hmm not good
ok maybe i will try to do the numeric_state thing without the "for:" thing, but instead will do some kind of hysteresis by increasing the number
also just for the record i think that "wait for trigger" could work if i would only be waiting for one numeric_state
hmmm hold on...
recently HA added an option to use a template as a trigger?
Not recently, the template trigger had been a thing for as long as I know
ahh, dont mind me, i doesnt seem to be possible to use "for:" with template triggers either, at least not through UI
However, the caveat with it a trigger is that it will only will if it changes from false to true.
No, you can't use for: with template triggers, also not in YAML
Only with state, and numeric state
Oh and device
the thing is that those weather sensors often give random, odd readings and thats what i want to avoid here
This is the first time you mention weather sensors, what are you trying to achieve here
The XY problem is asking about your attempted solution rather than your actual problem.
This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.
The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.
Oh wait, wind_speed, missed that
Really your only solution here is too create a binary sensor which is on if the wind speed is below your threshold
You can then use that both for triggers and conditions
There is a threshold helper (integration) which can do exactly that. You can set it up in the UI under helpers or in YAML
Ah, okay, the template binary sensor is not the only option ๐
It is not, the threshold is just different way to do it ๐
It's basically a template binary sensor with special fields so you don't have to use Jinja
Yeah, wasn't aware it existed (should have known though)
Hey there, im really trugling with a telegram template.
im trying to include a maps location with cordinates and a message in one.
it only send the maps link but dosent attached the message
There's nothing wrong with your templates. Perhaps that is how the Telegram send location service works. You could ask in #integrations-archived
okay strange. because map is sending finde trougt, but no msg ๐ฆ
why aren't you creating a notifier
when notifying someone you should be using the notify service
hi, im not sure if im in the right section but can someone help me with my configuration.yaml
i made a sensor to detect when my phone is connected via bluetooth to a certain mac address.
the sensor works fine everytime, i can see it in my dashboard. the only issue is its getting flagged as an invalid config, And i dont understand why because its working like i said.
this is the error
Configuration invalid!
Integration error: phone_connected_to_PC_Speaker - Integration 'phone_connected_to_PC_Speaker' not found.
Integration error: value_template - Integration 'value_template' not found.
Integration error: friendly_name - Integration 'friendly_name' not found.
Invalid config for [binary_sensor]: required key not provided @ data['platform']. Got None. (See /config/configuration.yaml, line 83).
@scarlet berry posted a code wall, it is moved here --> https://hastebin.com/ikiloniwum
The yaml isn't correct
compare it to your binary_sensor someone_home
does it look remotely similar?
lol no i was just looking at that....i think you can tell i copy and past my code...im just confused as to why it works
because the last 3 lines are correct for the new template style
these 4 lines are doing nothing and shouldn't be in your config:
- sensors:
phone_connected_to_PC_Speaker:
friendly_name: "Phone Connected To PC Speaker"
value_template: ### Phone Connected To PC Speaker ###
ok that fixed it....thanks soo much.
hi guys!
@shrewd epoch posted a code wall, it is moved here --> https://hastebin.com/axezutoluy
looksl ike your entity_id is wrong for sensor.humidifiersb
hum
oh
which would make the entity_id sensor.humidifiersb
also, you should be using state_attr
'{{ states.sensor.humidifiersb.attributes["humidity"] }}'and so on then?
instead of states.xxx.yyy.attributes
'{{ state_attr("sensor.humidifiersb", "humidity") }}'
whats the differance?
the first one is just if the module got different sensors and not just attributes right?
and the last one if the sensors just got attributes and no more sensors
state_attr is safer and will not cause errors on startup
oh ok
do you know how i can make all these sensors and build a devices of them inside Home assistant, is that even possible?
and btw it worked, thanks you sir!
That's not currently possible
Oh, would be a cool feature
I don't think it'll get added. It's been up as a discussion before
oh ok, just for templates would be helpful to merge some sensors to a device
trying to get the delta between a certain input_datetime variable and todays date. not sure what im doing, but maybe someone can help me:
#this one results in "1", while the input is todays date (-> expected would be 0)
{{ (as_timestamp(states("input_datetime.staubilastrunwohnzimmer")) - as_timestamp(now().date()) ) | timestamp_custom("%j")| int }}
#this one results in "364", while the input is yesterday (-> expected would be 1)
{{ (as_timestamp(states("input_datetime.staubilastrunflur")) - as_timestamp(now().date()) ) | timestamp_custom("%j")| int }}
#this one results in "363", while the input is the day before yesterday (-> expected would be 2)
{{ (as_timestamp(states("input_datetime.staubilastruneingang")) - as_timestamp(now().date()) ) | timestamp_custom("%j")| int }}
you want the number of days?
yes sir
๐
Take the highest value now() and subtract the lower value from it, instead of the other way round
tried that and failed. that gave me very funky results. but let me try again.
{{ (now() - states('input_datetime.date_test')|as_datetime|as_local).total_seconds()//86400 }}
thank you very much
This also works for the number of complete days
{{ (now() - states('input_datetime.date_test')|as_datetime|as_local).days }}
nice
ye even better. tyvm
I can never remember what you can easily get from a timedelta, and I'm often disappointed
Hehe
it apparently supports "days" and "seconds", but not "minutes" or "hours", for instance
Hi - I was wondering if anyone here knows how to change the color mode on a light template?
Hi, is this the right channel to post a question about templated sensors?
Sure
I am trying to get create a binary sensor that changes states depending on time and some input_datetime entities.
So far I managed this:
- trigger:
- platform: time
at: input_datetime.aqua_fim_fotoperiodo
id: 'off'
- platform: time
at: input_datetime.aqua_inicio_fotoperiodo
id: 'on'
- platform: homeassistant
event: start
id: 'off'
binary_sensor:
- name: "fotoperiodo_aquario"
state: "{{ trigger.id }}"```
it works for the 2 time events but i want it to be "correct" when homeassistant starts... so I am trying to write a rule that sets the id if the time homeassistant start is after "input_datetime.aqua_inicio_fotoperiodo" and before "input_datetime.aqua_fim_fotoperiodo"
Ok
the logic should be
id is on if
(input_datetime.aqua_fim_fotoperiodo > input_datetime.aqua_inicio_fotoperiodo and now > input_datetime.aqua_inicio_fotoperiodo and now < input_datetime.aqua_fim_fotoperiodo) or
(input_datetime.aqua_fim_fotoperiodo < input_datetime.aqua_inicio_fotoperiodo and (now > input_datetime.aqua_inicio_fotoperiodo or now < input_datetime.aqua_fim_fotoperiodo))
else if is off
but I can`t figure out how to compare 'now' to the input_datetime entities
So you can write almost exactly that
You need to convert the input_datetime state to an actual local datetime with |as_datetime|as_local
And compare with now()
issue is that my input_datetime only has time (no date)...
should be okay if you use now().time()
iif( input_datetime.aqua_fim_fotoperiodo > input_datetime.aqua_inicio_fotoperiodo and now().time() > input_datetime.aqua_inicio_fotoperiodo | as_datetime | as_local ...
``` ?
ok, maybe not
you need to reference the states as per https://www.home-assistant.io/docs/configuration/templating/#states
this may be helpful:
{{ (today_at(states('input_datetime.date_test'))|as_local).time() > now().time() }}
that's an input_datetime with only the time
@last mesa posted a code wall, it is moved here --> https://hastebin.com/isapegufas
Thanks RobC! I got it working with the following code:
{% set var_now = now().time() %}
{% set var_finish = (today_at(states('input_datetime.aqua_fim_fotoperiodo'))|as_local).time() %}
{% set var_start = (today_at(states('input_datetime.aqua_inicio_fotoperiodo'))|as_local).time() %}
{% set var_after_start = var_now > var_start %}
{% set var_before_finish = var_now < var_finish %}
{% set var_and = var_after_start and var_before_finish %}
{% set var_or = var_after_start or var_before_finish %}
{% set var_start_before_finish = states('input_datetime.aqua_fim_fotoperiodo') > states('input_datetime.aqua_inicio_fotoperiodo') %}
{{ ((var_start_before_finish and var_and) or ((not var_start_before_finish) and var_or)) | iif('on','off') }}
I will leave it here if someone needs something similar.
BTW, this is doing a string comparison, which may not work the way you expect:
{% set var_start_before_finish = states('input_datetime.aqua_fim_fotoperiodo') > states('input_datetime.aqua_inicio_fotoperiodo') %}
ideally, you would do something similar to what you did earlier to convert the time string into a real datetime and then do the comparison @last mesa
as long as the times are zero-filled and in 24-hour mode, you will probably be okay, though
How can i delete the "SPACE" that is when my sensor updates ?
Code: + ' / ' "https://www.mysite.com/?api=1&query=" + states('sensor.testname') }}
Output: / https://www.mysite.com/?api=1&query=firststate, secondhere
betwen firststate, and secondhere it inserts a space betwen.
and makes my link invalid.
.share the entire template
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as 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.
Are the spaces included in the state of your entity?
You can always use | replace(' ','')
Is it possible to make a template trigger than will wait for another trigger within 10 seconds or timeout
if another trigger happens turn on.
The purpose is i am using an fp1 and tracking zha events (approach,leave) to turn on/off a light. It works well but sometimes it will fire a leave event just because i moved back a little bit not that i got up and walked away.
It usually retriggers within 10 seconds. the purpose of this would be to turn on if that happens as i would use that as a condition.
i could just use wait for trigger in the automation but i am trying to use a single service call with various capabilities for efficiency.
Maybe using trigger ids and last_updated. You can also store the trigger_id and last trigger datetime in attributes, and use that
How would I do that? Storing the trigger IDs and last trigger datetime
Something like:
template:
- trigger:
- id: "foo"
- id: "bar"
sensor:
- name: Your sensor
state: "{{ your template }}"
attributes:
trigger_id: "{{ trigger.id }}"
triggered: "{{ now().isoformat() }}"
Thank you.
You can refer to them using this.attributes.trigger_id which will be at the time of the trigger, so before they are rendered again
So it will contain the previous trigger
And trigger time
Spacing is off but something like this right?
https://dpaste.org/qjBfW
Something like that yes
In the state refer to it using this.attributes.trigger_id == 'retrigger' and triggered < 10 seconds? Not sure how to format the time
With the code you posted above the trigger_id will either be approach or leave
I will change that. It will be leave first. Then check if approach is fired in less than 10 seconds. If not turn on.
Something like this.atrributes.trigger_id == 'leave' and (now() - as_datetime(this.attributes.triggered)).total_seconds() < 10
How would that check for if approach is fired then do nothing as in stay (false/off) or if approach is not fired turn on/true
You can add trigger.id == 'approach'
this.atrributes.trigger_id == 'leave' and (now() - as_datetime(this.attributes.triggered)).total_seconds() < 10 and trigger.id == 'approach'?
Yes
Perfect thank you.
Hey, working on kinda huge automation here but need some help with templates, the main idea is, if a Light is on for longer than 10min while a window is opened, if itโs 1h before sunset, send a notification about the exact room light is on, that itโs on too long while the window is open. ( The living room light has been on while the living room window is open, donโt be that lazy ) So I kinda need some help on the template part of it.
And I can do it in GUI for each room for each window and each light separately but Iโm sure someone here could help / share if he has something like this already done ๐ Iโm pretty basic in YAML ๐ Oh and using my names instead of friendly namesโฆ in the link are some light entities and some mappings hopefully that helps here ๐
https://dpaste.org/O5GmC
https://dpaste.org/fPULD and this is the automation for one window and one light in one room ๐ if that helps, as i've said, i can just repeat this like around 20 times with all possible cases but im sure there is a way to do it a bit more organised ๐
I'm getting this
Template variable error: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'atrributes' when rendering '{{ this.atrributes.trigger_id == 'leave' and (now() - as_datetime(this.attributes.triggered)).total_seconds() < 10 and trigger.id == 'approach' }}'
Error rendering state template for sensor.bedroom_presence_detector_condition: UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'atrributes'
Here's the code
https://dpaste.org/x1RkH
Ah, right, change it to this.get('attributes', {}).get('trigger_id')
Which part should be changed?
@shrewd epoch posted a code wall, it is moved here --> https://hastebin.com/ralotenufu
this.attributes.trigger_id to what I just posted
And the same for the other attribute
Please remove that code wall from your post
Yeah why itโs not autoremoved ? ;D
Where is the extra ')' needed?
Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected '}', expected ')') for dictionary value @ data['sensor'][0]['state']. Got "{{ this.get('attributes', {}).get('trigger_id') == 'leave' and (now() - as_datetime(this.get('attributes', {}).get('triggered')).total_seconds() < 10 and trigger.id == 'approach' }}".
(now() - as_datetime(this.get('attributes', {}).get('triggered')).total_seconds() < 10
After triggered, there should be 3 there
No more errors but it doesn't appear to be doing what I expected. As in it's not becoming true.
If event leave is fired and within 10 seconds event approach is fired it should become true. It didn't do that. It's staying false.
friendly_name: Bedroom Presence Detector Condition
trigger_id: approach
triggered: '2022-07-28T08:38:24.404193-04:00'
.share the entire sensor yaml
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language)
- https://www.codepile.net/ (select YAML as 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.
You did not replace this part with the new version this.atrributes.trigger_id
Unfortunately there is no trace here, what you can do is break the template in 3 parts and put that in 3 attributes so you can see on which part it falls
Anyone know what gives me the error of:
Configuration validation
Validate your configuration if you recently made some changes to it and want to make sure that it is all valid.
Configuration invalid!
Platform error humidifier.template - No module named 'homeassistant.components.template.humidifier'```
https://pastebin.com/81zwAjVa
Thanks guys!
On leave and approach it doesn't change from this.
https://dpaste.org/aOWCw
leave: false
time: false
approach: true
I had the command for the event messed up.
It's meant to be 'Away' not 'Leave'. How do I make this auto turn off? It did go to true.
Just add auto turn off and give it a few seconds?
Correct
Perfect thank you.
Any ideas about this one ? ๐ #templates-archived message
Finished product
binary_sensor:
- platform: template
sensors:
campainha_zigbee:
friendly_name: "Campainha"
value_template: "{{ state_attr('sensor.0x00124b002241ad4d_action', 'action') in ['single', 'double', 'long'] }}"
I assume the light and the window have to be in the same room?
If so, I would add them in areas, eg an area named Bedroom
Yes the idea is they are in the same room ๐
so far ive got the automation to work and it worked ๐ so the idea works ๐
never done anything like that
like i have rooms and they are in the right room / area ๐
Then create your variables like this:
variables:
mapping:
Bedroom:
light: light.bedroom
sensor: binary_sensor.window_bedroom
You use areas in HA?
You can set them in the GUI
Yep i have areas ๐ so the right sensor is in the right area already ๐
And the light as well?
yep
Okay, I quickly draft something based on my mapping example above
didn't understood what You've meant but take You're time ๐
and why use areas ? is the way i have it in that one automation that bad ? it would be just was easier to correct it later on, when i need it ๐
just asking ๐ i've had something similar where you've helped and it works like a charm !!!! ๐
Is this what you needed?
ill have to test it since im not that good with yaml to get it just from code ๐
but i will definitely give a feedback here ๐
I assume all of this is in your sensor.yaml? The part starting on line 49 doesn't belong in sensor.yaml
It belongs in configuration.yaml
And do you use a custom component for that, because I don't see it mentioned here as template entity
https://www.home-assistant.io/integrations/template/
so, does this look correct ? https://dpaste.org/NxNJV
sorry for the holdup, You're welcome to check #general-archived my HA was such a buggy mess ๐
When using map(attribute=*) what do I replace the * with to return the "entity", eg I want the return to be something like input_select.alpha or counter.number?
Found the answer whilst looking into some other issue on the forums. Turns out it's map(attribute='entity_id') which I swear I tried already ๐คทโโ๏ธ
you're mapping a state object, whose fields are described here: https://www.home-assistant.io/docs/configuration/state_object/
Thanks, that is the exact information I was looking for earlier (but will be very useful in the future ๐).
my value is {34AB9527089500000005010100328F}
value_template: >
{% if "{{value[2]}}" == "4" %}
1
{% else %}
{{value[2]}}
{% endif %}
it should be 1 right ? but why it show 4
What have I missed ?
current: 1972 current_consumption: 414.3 voltage: 208 friendly_name: Smart Plug
hi guys, how do i add this state attributes into sensor entity? from integration local tuya
You nested templates
i'm sorry. i don't understant. i am new user. Can you advise me how I need to fix it?
you started a template with {% and then put {{ }} in the middle
{{ 1 if value[2] == '4' else value[2] }}
No, I wasn't aware that there could be multiple sensors in the room.
You need to add the full entity ids to the variable, so including binary_sensor
And then this should be your template in the if:
- condition: template
value_template: >
{% set sensors = mapping[area] %}
{{ expand(sensors) | selectattr('state','eq','on') | list | count > 0 }}
And you might want to add your sunset condition you had in your own automation
mqtt:
sensor:
- name: "BBB"
state_topic: "/response/app/34AB95270895/#"
unit_of_measurement: "C"
value_template: {{ 1 if value[2] == '4' else value[2] }}
it show error
missed comma between flow collection entries at line 125, column 37:
value_template: {{ 1 if value[2] == '4' else value[2] }}
^
thank you so much. It's already working
Is there some way of getting a template sensor to be registered as related to a particular device, so that it appears on the deviceโs UI page? Eg I calculate energy for a device using a template and would like that to appear together with the other entities related to the device
Eg you see that HA picks up the automations using the deviceโs entities and puts them on the page
Nope
๐ Thanks!
Hi, now have couple shifts to do but after couple days Iโm back on trying so Iโll update my progress then here ๐
I have a templates.yaml file but not matter what I do i cannot move this template from my config to it without breaking something. ```sensor:
- platform: template
sensors:
vapor_deficit:
friendly_name: 'vpd in kilo pascals'
value_template: >-
{% set T = ((states('sensor.greenhousemotion_air_temperature') | float) - 32) * 5/9 %}
{% set RH = states('sensor.greenhousemotion_humidity')|float %}
{% set SVP = 0.61078 * e ** (17.2694 * T / (T + 238.3)) %}
{% set VPD = ((100-RH) / 100) * SVP %}
{{-VPD | round(2) -}}
unit_of_measurement: 'kPa'```
- name: vapor_deficit:
value_template: >-
{% set T = ((states('sensor.greenhousemotion_air_temperature') | float) - 32) * 5/9 %}
{% set RH = states('sensor.greenhousemotion_humidity')|float %}
{% set SVP = 0.61078 * e ** (17.2694 * T / (T + 238.3)) %}
{% set VPD = ((100-RH) / 100) * SVP %}
{{-VPD | round(2) -}}
unit_of_measurement: 'kPa'```
first post is correct, second post is not
second post is... a mixture of wrong code for both the new and old style
- sensor:
- name: vapor_deficit
state: >-
{% set T = ((states('sensor.greenhousemotion_air_temperature') | float) - 32) * 5/9 %}
{% set RH = states('sensor.greenhousemotion_humidity')|float %}
{% set SVP = 0.61078 * e ** (17.2694 * T / (T + 238.3)) %}
{% set VPD = ((100-RH) / 100) * SVP %}
{{-VPD | round(2) -}}
unit_of_measurement: 'kPa'
thank you thank you! i see what needed to be changed now. an hour staring a trying to get this to work. thank you!
Is there an easy way to pick the defined value from one of two columns, from a list of entities?
I currently have
{{ expand('binary_sensor.lounge_door_sensor_occupancy', 'binary_sensor.lounge_sofa_sensor_occupancy') | selectattr('attributes.occupancy', 'defined') | map(attribute='attributes.occupancy') | list | max }}
but now need to add attributes.presence as a fallback for any sensors where attributes.occupancy is undefined
Not that I'm aware of. You'd need to generate separate lists and combine them
Ok, I'll explain briefly my goal, maybe someone can point me toward the best solution. I have just installed a flow meter with ESP32 and I am fetching values for instant water flow (in litres). I'm trying to calculate how much water (in litres) has been used last time a water flow has been detected, and keep that value somewhere (in a sensor?) so I can use it in an automation if it reaches more than a certain threshold. Example: water flow for more than 3 minutes, it's probably someone having a shower, I want to use that data to calculate volume (in litres) x cost of electricity to heat 1 litre of water, then call a service and send a message to a Google Home in my bathroom telling how much that shower cost.
it can be done, but there's no easy way. Jinja is built in a way that doesn't allow you to dynamically change things, so it's a pain in the ass when you need to do those things
Use the integration... integration
it calculates the area under the curve, which is the value you're looking for.
Petro, do you know why I'm getting
list index out of range
On the set variables at the first for each and probably I will get the same error on the second for each as it is nearly identical
https://dpaste.org/bRtV8
I actually got lucky, the state of the sensor worked, and then I did same approach using the state of the sensor and comparing it to 'on' to reproduce the true/false of the occupancy
I now have flawless motion/mmWave combo sensors ๐
I think I just need to change the thermostat variable to
Can I have a little more details please?
Take a look at the integration integration
it will calculate x/time stuff for you
Ok fine! I'll read from there! Thank you Petro
if you're struggling setting that up, just head over to #integrations-archived , also, after you set up the integration integration, you can use the item in utility_meter integration to get stats over different time ranges
basically, you don't need a template
@mighty ledge, about the Integral method to select, I couldn't decide which. In the documentation it mentions that "In case you expect that your source sensor will provide several subsequent values that are equal, you should opt for the left method to get accurate readings.".
In my case, when water starts to flow I want to calculate volume in litres until flow stops. I want to keep track of those different events and especially those when water flow for more than 3 or 4 minutes as this probably mean it's a shower happening.
what your asking for isn't possible. You have to get creative for a calculation like that.
Yesss... That's why I'm baffled into overthinking this for the last 24h.... I will have to dig further into this... There must be a way, I just haven't found it yet.... When water flows, I have the debit in L/min. When flow goes from 0 L/min to any value above this, I know it's a starting point to count, but I don't know how to use that as a trigger to count and I don't know where to calculate this... That's my challenge here....
Well, that's where the integration integration comes into play. It'll give you the area under the curve for the past X minutes. If you use that as the threshold, you got what you want.
using left will ignore the long pauses where the water isn't flowing.
๐คทโโ๏ธ
but programmatically turning that calc on or off is not possible. So, maybe you are over thinking it.
area under curve = total amount over x time.
Do you know where I should discuss this challenge as it does not seem to be appropriate in #templates-archived
see this comment
Ok, I'll head over there and see if I can get some help thinking about this. Thanks Petro for your help so far. ๐
are you just trying to get the total volume of water?
if that's the case, just set up energy meter with your water set as gas
as that handles gas and electric, but not liquid, but liquid is basically represented the same way as gas is. Volume/time
I want total volume of water after flow is detected and then stops.
Because I want to use that value when it is above 3-4 minutes, then make a background calculation with a Template so I can call a service to TTS how much that shower cost
I know it's crazy, but that's a funny project I'll share in a school webinar and it pushes the limit of what can smart homes can do to help become aware of water consumption
You aren't going to be able to get that without getting the information from the database
and it will only work for the last shower.
That's fine for me. I can live with it working only for the last shower
that will require a template, and it will require a properly formatted sql query
The webinar will be presented to 5000-10000 students this fall 2022 and winter 2023
I will present the backstory behind it and mention the struggles to achieve the goal toward it. I hope it will raise interest into smart home and community of builder for the future
Are you going to show how you did it?
Exactly
because it won't be friendly for non-coders.
I'm a Ph.D. in education, I'll find a way to make it friendly to show how it has been done
ok, by all means then, it would be an SQL sensor with a query and a value_template that summates the last shower volume. Then you'd make another template that just uses the last total volume multiplied by the $ per liter
Then @mighty ledge, you will certainly get credit for pointing me in the right direction.
You might need 2 datetimes
or 1
basically, you'd have to set the datetime via an automation when the flow starts
then use that datetime in the SQL query. Possibly set a datetime when the flow stops as well
then grab all the states between the 2 datetimes
sum them
I see the path toward the goal now, but I need to make sure I get the starting point correctly. Now that my flow meter is set, I must work in automation to set a datetime? Is that the next step?
Yea, I'd say so
if your flow sensor is literally 0, you could just do an automation that looks at any numerical change going above 0.
maybe a template sensor to help with that if you really want
template:
- binary_sensor:
- name: Waterflow on
state: "{{ states('sensor.xyz') | float(0) > 0 }}"
the automation would be...
- alias: Set On/Off Datetime
trigger:
- id: 'on'
platform: state
entity_id: binary_sensor.waterflow_on
from: 'off'
to: 'on'
- id: 'off'
platform: state
entity_id: binary_sensor.waterflow_on
from: 'on'
to: 'off'
action:
- service: input_datetime.set
target:
entity_id: input_datetime.{{ 'last_shower_start' if trigger.id == 'on' else 'last_shower_end' }}
just make 2 input datetimes: last_shower_start, last_shower_end
then you have the SQL query
You are amazing, I'll try it out right now. I'm so thankful Petro ๐
or you could do it slightly differently
where your sql sensor just summates everything from a starting timestamp
and then when the binary_sensor goes off, you send the notification.
that might be easier
template sensor are created in configuration.yaml ? Correct?
yep
I'm not sure you can do this with SQL either
as the query doesn't allow for variable times
So, you might have to attempt to sum itself with another template sensor.
I confirm, the binary sensor works flawlessly. It turns ON when water flows. I tested it
Should I test the automation you suggested now?
@mighty ledge, in the suggested automation, you are pointing to last_shower_start and last_shower_end. Should I create these entities?
yeah, you could make those sensors but we might have to approach this a different way
try it with this template sensor.
- sensor:
- name: Last Shower Summation
state: >
{% if states('binary_sensor.waterflow_on') %}
{{ this.state | float(0) + states('sensor.xyz') if this.state is defined else 0 }}
{% else %}
off
{% endif %}
I'll add it in configuration.yaml
sorry wait a sec
Ok
On this line: {{ this.state | float(0) + states('sensor.xyz') }}
the sensor.xyz should be pointing toward which sensor?
- alias:
- platform: state
entity_id: sensor.last_shower_summation
to: 'off'
condition:
- condition: template
value_template: "{{ trigger.from_state is defined and trigger.from_state.state | is_number }}"
action:
- event: event_shower_ended
event_data:
volume: "{{ trigger.from_state.state | float }}"
then, make a template sensor that calculates the cost....
- trigger:
- platform: event
event_type: event_shower_ended
sensor:
- name: Shower Cost
state: "{{ trigger.event.data.volume * 0.01 }}"
unit_of_measurement: $
Cost is 0,01 $ / litre. I double-checked with local Power Facility here in Quebec/Canada
Yeah, so basically how this works is you have a sensor that adds a state to the previous state everytime the shower is on
don't restart during this time, as you'll lose the data
but you'll have a cost of the last shower
Don't mean to barge in on this bit but hoping someone can help me understand. I've got a sensor that outputs a value similar to "2022-07-30T07:22:40+10:00". How would I go about removing everything except the time "07:22:40"
make a template sensor
template:
- sensor:
- name: Friendly Time
state: "{{ (states('sensor.xyz') | as_datetime).strftime('%H:%M:%S') }}"
Thanks very much.
so to recap @flint wing
this should be in configuration.yaml
template:
- binary_sensor:
- name: Waterflow on
state: "{{ states('sensor.xyz') | float(0) > 0 }}"
- sensor:
- name: Last Shower Summation
state: >
{% if states('binary_sensor.waterflow_on') %}
{{ this.state | float(0) + states('sensor.xyz') if this.state is defined else 0 }}
{% else %}
off
{% endif %}
- trigger:
- platform: event
event_type: event_shower_ended
sensor:
- name: Shower Cost
state: "{{ trigger.event.data.volume * 0.01 }}"
unit_of_measurement: $
with this automation
- alias:
- platform: state
entity_id: sensor.last_shower_summation
to: 'off'
condition:
- condition: template
value_template: "{{ trigger.from_state is defined and trigger.from_state.state | is_number }}"
action:
- event: event_shower_ended
event_data:
volume: "{{ trigger.from_state.state | float }}"
@mighty ledge, I just want to make sure I followup since you are a fast template-guru ๐
- I created the binary_sensor for Waterflow on
- I need to create a template sensor for Last Shower Summation
- I need to create automation with - alias: - platform: state entity_id: sensor.last_shower_summation
- I need to make a template sensor that calculates the cost
Is that the correct order?
Guess .time() would also work for @abstract sapphire as the source sensor doesn't output microseconds
@mighty ledge, that for recap, it answers my last comment
template:
- sensor:
- name: Friendly Time
state: "{{ (states('sensor.xyz') | as_datetime).time() }}"
I guess you could simplify it down
to this
template:
- sensor:
- name: Last Shower Summation
state: >
{% set current_liters = states('sensor.xyz') | float(0) %}
{% if current_liters > 0 %}
{{ this.state | float(0) + current_liters if this.state is defined else 0 }}
{% else %}
off
{% endif %}
- trigger:
- platform: event
event_type: event_shower_ended
sensor:
- name: Shower Cost
state: "{{ trigger.event.data.volume * 0.01 }}"
unit_of_measurement: $
Looks good but I went with strftime as I wanted to remove the seconds. Thanks anyway.
@mighty ledge, and when you write sensor.xyz, I guess you are referring to my sensor that calculate water flow, is that correct?
And as a reminder, water flow below 3 minutes have few chance of being a shower.
that requirement will force you to change your template last_shower summation
you'd have to set the trigger as a template, but then keep in mind, that you'll loose all data between 0 and 3 minutes
That wouldn't be an issue since these data won't be needed. To have a realistic shower trigger it needs to start calculating at a minimum shower duration which I suppose being 3 minutes
Then I guess the automation that would be at the end, I mean the call service to shout out the cost of the shower could use the last shower duration? It would not call service TTS to unless above 3 minutes?
you could add an automation that sets the input_datetime for the start of the shower.
The final automation could use last shower duration and send call service TTS to a GoogleHome in bathroom. TTS would say "Based on your shower duration, this shower cost X dollars".
right, but as it stands you don't have the duration
you only have the summation
so to get the duration, you'd need to calculate the duration
aka, you need the start time
Then I just need to trigger call service to TTS beyond a certain threshold summation
is the flow rate constant?
Kind of.... It will vary slightly if other people use water in house
And also depending on time of the day because if many neighbors use water, it ends up affecting flow
Yes, my flow meter if for my entire house. But I will install a dedicated flow meter for hot water tank very soon
I was starting to get into the programmation and calculation but your help has pushed me weeks ahead because I don't come anywhere near your knowledge of templating and coding. That's why I'm trying to keep up the pace.
well, either way, you can set the start and end time datetimes with that other automation
and then you can make a sensor that calculates the difference
and when the difference is greater than x, you can send the notification
keep in mind that the value might be negative at times because you're in the middle of a shower that hasn't ended. And you might run into issues where you have to wait for the value to be calculated by putting a 20 second wait in your notification automation
Yes, I understand what you mean. If time is beyond 3 minutes, automation should have to wait for calculation to be made
Alright I've got the templating I want setup but for some reason it's not adding a space between the two IF statement values. Eg it will show "sun will rise at xx.There is a 0% chance..." without a space between the two statements. If I put any other character there it will show but spaces don't.
{%- if now() < (states('sensor.astronomical_sunrise_time_0') | as_datetime) -%}The sun will rise around {{ (states('sensor.astronomical_sunrise_time_0') | as_datetime).strftime('%H%M') }}.
{%- if now() > today_at("05:00") -%} There is a {{ states('sensor.rain_chance_0') }}% chance of rain today.
{%- endif %}{%- endif %}
Oh and please tell me if I can clean that up. Looks messy as all hell in my eyes but don't know.
Without creating template sensors.
Use quotes?