#templates-archived
1 messages · Page 122 of 1
Why wouldn’t you make that output json and use a normal rest sensor?
that's a good question
what do you have in the house that he would use?
yeah, probably because it's a time
I'd assume google home only accepts specific sensors
I know alexa only allows temperature and humidity sensors
Can you run voice commands in google home?
In alexa, I can create a routine and then trigger off that routine with a TTS response
Did that work? I'm curious now. I always thought the only sensors that could be exposed to google were ones with a device class of temp or humidity
That's what it says in the doc anyway (https://www.home-assistant.io/integrations/google_assistant/#available-domains). But then again it also doesn't list binary sensor as supported and it sounds like you got that to work so perhaps the list needs an update
you can but its not as fun as it sounds. I set it up at one point, you can make a bot using DialogFlow. And I did get it all working but once I realized I was going to have to start every conversation with "Hey Google, talk to Home Assistant", wait for it to move into that mode and then start conversing I was like nope, not for me lol
I think for that particular use case it might be easier to expose a script to google, tie it to a routine that listens for that phrase and then have the script call the tts_say action to get google to speak the value of the sensor
I think that works right? I don't really use tts_say much but I know its pretty popular
meanwhile.. #voice-assistants-archived exists
Is there any "sensor" allowing calculate and show measured value increase per some period of time?
Let's say I have sensors which shows "working time since start", now I would like to see "working time in last 60 seconds"
Displayed as (for example) "3 units/minute"
@cinder geyser integration integration
Integrations integrate Home Assistant with devices or services, or provide functionality within Home Assistant. Add-ons provide additional software or services, which an integration could possibility integrate with. Add-ons are for Home Assistant OS and Supervised only, other install methods can install software other ways.
Bot pulls from sitemap. It is not hard coded.
Is this the place to ask about a 'shell_command' in a 'service-call' ? I am struggling with the infamous quotation marks problem passing data.
Whats the best way of creating a sensor that will give me the seconds since midnight? So at 8AM it should show 28800 and every day at midnight it should start the count again so it should go from go from 86400 back to 1.
Is it possible to use if-statements in the "params" part of a script?
Is it possible that the fan speed template isn't working like documented, or is it me ? When I add the line percentage_template: "{{ state_attr('light.bodemwarmtewisselaar_2', 'brightness_pct') }}" it gives me an error : Invalid config for [fan.template]: [percentage_template] is an invalid option for [fan.template] without this line everything works fine.
what are you trying to do with this sensor?
You can use jinja inside variables. I'm not sure what you mean by params. You have an example of what you're talking about?
what version of HA are you running?
@mighty ledge I am running 2021.1.5 on a ARM kubernetes cluster from docker image "homeassistant/home-assistant" stable
@mighty ledge You asked the right question. I changed the tag to latest and did a helm upgrade on my HA container. Now it runs the latest version and the template is working ! My bad. Thanks a lot for taking your time to help me with this. Br N.
That’s an old version, the new fan template came put in 2021.3
@tawny valve posted a code wall, it is moved here --> https://paste.ubuntu.com/p/R9g6jDZQhP/
Why does the platform: mqtt show up as 2 lightning icons off/on while the platform: rest shows up as sliding switch? Which configuration determines the icon? thanks
https://imgur.com/a/ls3yaCZ i have an image of the 2 here
how to pick up the latest file name from a directory?
I am trying to use it to calculate other stuff
I am using the following to store the snapshot from the camera. But I also want to send it to mobile phone as a notify. Since I do want to keep a timestamp of the files - for easy search in future. How can I get the file name which is stored by the below and use it in notify? One way is to get the latest file from the directory - looking for the template for the same - service: camera.snapshot target: entity_id: camera.entrance data: filename: '/share/img_store/snapshot_{{ now().strftime("%Y%m%d-%H%M%S") }}.jpg'
what other stuff, when does the other stuff need to be calculated?
Please give more than a vague answer, because what you are looking for is not entirely possible.
make filename a variable in your automation then use it in both the filename field and your notification message field.
something like this? But wouldn't the name in the variable change since the name will change due to the exact time indicated ``` variables:
filename_image: '/share/img_store/snapshot_{{ now().strftime("%Y%m%d-%H%M%S") }}.jpg'
action:
- service: camera.snapshot
target:
entity_id: camera.entrance
data:
filename: "{{ filename_image }}"```
Just checked - it works - thanks. Somehow I was under the impression that when the automation will be executed the file name will change
I want a template sensor for the soconds of the day from midnight because then I can use it with influxdb and grafana to calculate an estimated value form a rest sensor that only gives me the last 24h - so basically when its 16:00 I want to divide the rest sensor number by 24h (in seconds) and multiply it by 16h (in seconds)
Is it possible to do math in the below field, like this?
- platform: numeric_state
entity_id: sensor.temperature_living_room
below: "{{ states('input_number.temperature_max') | float * 0.9 }}"
for:
minutes: 5```
Doesn't seem to work.
Best you can get is a sensor that updates each minute
{{ (now() - now().replace(hour=0, minute=0, second=0, microsecond=0)).seconds }}
No, just use a template trigger.
nice thanks - one minute is good enough fro what I am trying to do
So something like this?
value_template: "{% if ( states( 'sensor.temperature_living_room' ) | float) <
( states( 'input_number.temperature_max' ) | float * 0.9 ) %}true
{% endif %}"
for:
minutes: 5```
Can I actually use `for:` in a template like that?
Ah, so just:
platform: template
value_template: "{{ (states('sensor.temperature_living_room') | float) >
( states('input_number.temperature_max') | float * 0.9 ) }}"
for:
minutes: 5```
yep
but indent the second line of the template or don't use a carriage return
Also, you don't need the ()
value_template: "{{ states('sensor.temperature_living_room') | float > states('input_number.temperature_max') | float * 0.9 }}"
Thanks!
trying to iterate a group to catch turned on lights. Can't figure it out since expand function seems no working as described here https://www.home-assistant.io/docs/configuration/templating/#working-with-groups
This code put in template
{% for light in expand("light.desk_lamp", "light.bigroom_main") %}
{{ states(light) }}
{% endfor %}
generates this error
AttributeError: 'TemplateState' object has no attribute 'lower'
Any ideas?
you're mixing a bunch of things there that don't work the way you think they do
if you want to loop like that do
{% for light in ["light.desk_lamp", "light.bigroom_main"] %}
what do you mean?
This code
{% for light in expand("group.alexa") %}
{{ states(light) }}
{% endfor %}
also gives this error. Are those examples in the docs wrong?
expand will still work if you just want to get the state out
{% for light in expand("light.desk_lamp", "light.bigroom_main") %}
{{ light.state }}
{% endfor %}
yes, I can see that. So, how to get light "name"?
light.name
what he said
great, thanks! So, back to the examples here https://www.home-assistant.io/docs/configuration/templating/#working-with-groups Does that work for you?
yes, because expand gives state objects not string object names, right?
yep
I have thermostat, that use room temp to display. I have been able to find the floortemp using rest-api. Is it possible to change the "sensor" that the thermostate use for actual temp?
not unless you use the generic thermostat integration
@inner mesa How do I check that?. The thermostat is through the deconz intergration. And show up as an climate.thermostat_x
"no", then
ok, I thought that the device config was store, and was editable.
you might be able to use generic_thermostat as a base to combine the various things you want, some based on your existing thermostat and some based on some other sensor, but you can't just do what you want without more work
Ok, could be worth looking into 🧐
Anyway to make a sensor which displays last known value instead of ‘unavailable’?
I was thinking something like this but a sensor can't seem to reference itself: {% if states('sensor.encore_noire_V1') == "unavailable" % {{states('sensor.encore_noire_V2')}} {% else %} {{states('sensor.encore_noire_V1')}} {% endif %}
I want to automate the on/off times for each light in an area for every day of the week. I created date/time helpers for each light each day of the week (that's a lot but I don't think there's a way around it). I now have to create an automation for each light to turn on/off based on the helpers
is there a way I can create one for each day of the week or do I need to create one for each light each day of the week?
I guess I need a template that uses as a trigger the date/time helper that contains the name of the day
this is what it looks like right now
You can do circular references, it'll just warn you.
thank you so much
no clue if it works
you don't need 'day conditions' with that automation because it's handled by the templates.
I'll test it and report back
even if at the same time I'm looking into SimpleScheduler add-on
there's also schedy or whatever it's called
{{ now().strftime("%B") }} Displays the month name in English. is there a way so it gets displayed in my native language? HA is set to that language
it should be locale dependent
I don't think language is set for the internals
How to create weather template for climacell?
Best regards
Hmm, seems like it isn't. I'm very bad at making templates, is there an easy way to translate the month value?
it should already be. these are the placeholders: https://support.sendwithus.com/jinja/jinja_time/#datetime-format
but you can create your own mapping if needed
there's an example here: https://community.home-assistant.io/t/convert-date-and-time-template/99328/18
the point is that you get the month as an index and index into your own array of translated values
Yea i've looked at this, sadly it doesn't translate, no idea why
I will take a look at that, thanks!
@fierce hornet as I said before, it's not translated in the internals. Never has been.
There are threads on the forum that cover this exact question
has exactly what you're looking for
How would one go about creating a template sensor that shows the maximum value of a sensor over the last 24 hours?
- platform: template
Windspeed_max:
value_template: "{{ state_attr('sensor.wupws_windspeed_stats_mean', 'max_value') }}"
Windspeed_min:
value_template: "{{ state_attr('sensor.wupws_windspeed_stats_mean', 'min_value') }}"
- platform: statistics
entity_id: sensor.wupws_windspeed
name: Windspeed Average
sampling_size: 288
I've got this far, but i think it might be terribly wrong. (288 as the sensor updates every five minutes.)
@glacial matrix
no need for templates
nevermind, i see you're using it
what's the problem, that should work fine
you might be off by 5 minutes, but you could double the sample size and add max age to 24 hours
I wasn't sure i had got the setup right with template. i didnt realise i could just use statistics.
well the result is the mean, but if you want max you'll need those templates you created
i just realized that your template yaml is wrong too
- platform: template
sensors:
windspeed_max:
value_template: "{{ }}"
you're missing sensors, and you capitalized the field name
windspeed_min_24h:
value_template: "{{ state_attr('sensor.wupws_windspeed_stats_mean', 'min_value') }}"
- platform: statistics
name: "Windspeed Stats - 24 hours"
entity_id: sensor.wupws_windspeed
sampling_size: 600
max_age:
hours: 24
So what name would i give the template sensor to pick up the windspeed stats? I assume it should be "windspeed_stats_-_24_hours"
it's best if you start up and find out what the entity_id is
remove the template sensors then add them in once you have the entity_id
just restarting HA now.
Great, That seems to be working. I think I realised i didnt need the min and the max, average and max makes more sense. Min might be 0. lol
my 24hour max is showing as 0, but my 1 week, and 30 days is showing as 6. The second two make sense as this only started recording today.
https://pastebin.ubuntu.com/p/77JrjcmDCy/
🏀🏀🏀🏀🏀🏀. Just seen my mistake! might help if it is set to look at the max value, not the min value!
folks , how can I use {{ trigger.above }} or {{ trigger.below }} in the choose option, without specifying a value?
for example: I'd like my sentence to be like ' if {{ trigger.above }} was used to trigger the automation (no matter was the value), do this '
and NOT this --> {{ trigger.above == 5 }}
I don't think you can
it's a pretty simple test to say {{ trigger.to_state.state|float > trigger.above|float }}, though. As far as I can tell, trigger.above is just repeating the threshold you provided and not telling you that that's what triggered it
could be wrong, didn't know that those variables existed until you mentioned them
typically in a situation like that, you'd just want 2 automations. Otherwise what @inner mesa will work.
Hey all, I have this template {{state_attr('calendar.2021_fia_formula_one_world_championship_race_calendar', 'message')|title}} that gives Formula 1 Gulf Air Bahrain Grand Prix 2021 - Practice 1. If I want to make two sensors, one with everything before the '-' and one with everything after, how would I go about that? I've tried |split(' - ') but get "TemplateAssertionError: no filter named 'split'".
The only stuff I've found on the forums seems to have the old states.sensor.state syntax.
{% set title = "Formula 1 Gulf Air Bahrain Grand Prix 2021 - Practice 1" %}
{{ title.split(' - ') }}
[
"Formula 1 Gulf Air Bahrain Grand Prix 2021",
"Practice 1"
]
So it does have to be handled by two lines. Interesting. Thank you!
probably not
I just did it that way to test
Same result: {{ "Formula 1 Gulf Air Bahrain Grand Prix 2021 - Practice 1".split(' - ') }}
the point is that it's a method of a string and not a filter
Hmm. Interesting, works just fine, but if I want to apply filters afterward, it does some weird formatting stuff.
I'll dig in more. Thanks.
np
Can someone explain why in the doc https://www.home-assistant.io/docs/configuration/state_object/ the state objects are like state.state , state.name and etc...
But we use states.light.hall.state in the templates.
Is it state or states? I got confused
‘states’ is the collection of all state objects. Each one has a ‘state’, which is the state that you’d see in
-> States
I guess more correctly, ‘states’ is a collection of platforms (like ‘light’), which is in turn a collection of objects. Each object has the definition in the link.
states contain domains contain states (entities)
Hi I have two sensors with date, how can I make a sensor with a subtraction result?
Hi all, new HA user here. I have a temperature sensors which I wanted to add offsets to and found from the forums that people add templates and copied that like this:
"{{ ( states('sensor.etupiha_temperature')|float - 0.7 ) | round(1) }}"
And it basicly works fine. Only problem is that I have a automation that restarts HA at 4am and the template is getting the "offset" (-0.7 in this case) value before sensors come back up and it messes up with my beatiful graphs 😄 anyway,could I make it ignore values after restart or smt like that? Althou I used to restart because I lost some sensors, but dont use those anymore, so maybe I should restart HA so often..
Hello, Im having an error in my logs Error while executing automation automation.sync_volume_google_home_downstairs: Error rendering data template: TypeError: '>' not supported between instances of 'NoneType' and 'float'
this is my automation https://paste.ubuntu.com/p/gnbwfHrQ4p/
is it because parsing to float or something else?
``` is evaluating to `None` you cannot use gt/lt with `None`
that means that my entity is off or unavailabkle, and for that reason volume_level attribute is None?
Hi everyone, may I get some help with a template sensor ? I've been struggling with it for a few days without result...I'm almost at what I want to achieve, minus an irritating detail ^^
- platform: template
sensors:
feeder_trigger:
unique_id: feederTrigger
friendly_name: 'Dernier déclenchement'
value_template: >
Il y a {{ relative_time(states.automation.nourrir_le_poisson.attributes.last_triggered) | replace('hours', 'Heures') | replace('minutes', 'Minutes') | replace('seconds', 'Secondes') }}```
sorry, paste has destroyed indentation
This is my sensor, and this is how I display it in a card :
https://ibb.co/BtpkhdS
(the one in the middle)
The problem is that even if I run the automation, the relative time displayed never updates...
Any clue on what I'm doing wrong ?
Ah well in fact it gets updated when I run the automation, but then the value always stays the same. Meaning it displays 0 seconds, and even if I refresh the page 10 minutes later, it still displays 0 seconds. How can I force it to be updated let's say every minute for example ?
Just add now() to your template, doesn’t matter where
in the value_template ?
Yep
Sorry but I'm getting an invalid config...I think I don't understand what you mean by "doesn't matter where"
{% set foo = now() %}
I feel stupid but I really dont understand what you want me to do and where...
Okay I think I have found, let's see if it works ^^
Yes it works !! many thanks @dreamy sinew and @mighty ledge for the tips, really appreciated !
hey can I get some help with a template I had for finding the lowest forecasted pressure in OWM? it was working but apparently the format got changed from datetime to str for some reason and now it doesn't work due to the data types being different. is there some way to convert it back to datetime?:
{% set start = now() %}
{% set end = start + timedelta(hours=48) %}
{{ state_attr('weather.openweathermap', 'forecast') | selectattr('datetime', '>=', start) | selectattr('datetime','<=', end) | map(attribute='pressure') | list | min }}
gives: TypeError: '>=' not supported between instances of 'str' and 'datetime.datetime'
probably need to convert those start and end values to strings via strftime
would >= & <= work on it in str format?
comparing a string to a string yes
yes but will the string comparison of datetimes be valid? trying to think about the format
as long as you match the format correctly it'll work
ok thanks. separate question: i kinda want to change this template up. instead of just finding the lowest value i think i want to set up two separate templates - 1) template that gives the difference between the highest val in 48hrs and the lowest val after that point in 48hrs; and 2) template that gives difference between the lowest val in 48hrs and the highest val before that point
no idea how i'd set either of those up though
have one sensor be the list
have the others pull what they need from that list
pressure_list:
{% set end = start + timedelta(hours=48) %}
{{ state_attr('weather.openweathermap', 'forecast') | selectattr('datetime', '>=', start) | selectattr('datetime','<=', end) | map(attribute='pressure') | list }}```
pressure_min: `{{ states('sensor.pressure_list')|list|min }}`
pressure_max: `{{ states('sensor.pressure_list|list|max }}`
pressure_delta: `{{ states('sensor.pressure_max')|float - states('sensor.pressure_min')|float }}`
that would give me max-min, but i want max-min(values after max) & max(values before min) - min
maybe there'd be a way to subset pressure_list into something like pressure_list_after_max & pressure_list_before_min
@zealous drum posted a code wall, it is moved here --> https://paste.ubuntu.com/p/78FRNXR22R/
ugh, it wasn't really that big of a wall. 😕
the question was hoping someone can help me with a simple package I'm trying to build. I'm just trying to have the binary sensor icon be consistent. First I wanted it to be icon A or B depending if the binary sensor was on or off, but it kept throwing a loop warning. Next I tried to customize and just maintain a static icon. Every time I change state, it reverts back to the default icon... Here is what I've tried so far.
I am completely new to HA, and I've had great success so far. most things just work, which is freaking amazing. Now I want to add an automation for my bug zappers. They're controlled by a z-wave paddle switch. I understand how to do an automation for "turn them on at sunset -0:30:00" and 'turn them off at sunset +6:00:00" - but I want to add a condition for the 'on' automation - only turn on between date x and y - I was told to use a template - can someone explain?
depends on how complicated you want to make it. Here's a relevant thread: https://community.home-assistant.io/t/automation-during-date-range/133814/42
something like "between month x and y" is pretty simple, but you can add more to it and be more precise
can somebody tell me why this isn't rounding?
{{ ("5292913"| float) /125000 |round(1)}}
Does anyone know how i check multiple statements in one line. Does this work within home assistant templates? so like this:
{%- if (datum == gftafval or datum == restafval or datum == papierafval) -%}
true
{%- endif %}
I would like to make a trigger check if one of the following is true and then trigger an automation. I have set the right variables and datetimes. i only need to know how to check multiple statements
the template section in
is great for testing templates
so it is or to use multiple
@grim flicker if they are simple types (int, str, float, bool) you can simply do
{{ datum in [gftafval, restafval, papierafval] }}
gotta use quotes for string checks
ok thanks will check that
This must be very simple so sorry in advance. I am trying to extract sensor values from mqtt json payload, the same topic can contain multiple value pairs but it rarely contains all in the same topic. I'm using value_template to check if the variable is defined and if it is extract the value for display. The challenge I have is that even if the variable is not defined the sensor itself assumes a zero value and overwrites any previous reading. Is there a way to stop processing the sensor as soon as I find the variable is not defined?
From the post above by @inner mesa I can get a general sense of a template. Can anyone point me to a 'step by step' overview (hand holding) of how a template gets created/edited, then how it is referred to by a trigger or condition or whatever?
there are lots of examples right in that thread
@gusty nimbus posted a code wall, it is moved here --> https://paste.ubuntu.com/p/kncTDJf9xJ/
hey i have a problem with my 'template thing'
i have an file.yaml loaded with code:
in that url of hassbot
when the input_boolean.droogkastgevult is on it should switch the automation on and if the boolean is off it should switch off
I don't get any error and it doesn't work
Did i do something wrong
Many thanks on advance
i found another way to do it tx anyway
I found a solution of sorts. When the the variable is not defined I capture as part of an if-else statement and give the sensor it's own value. I found this https://community.home-assistant.io/t/mqtt-sensor-template-how-to-hold-value-until-next-correct-value-arrives/37096
Is it possible to have 2 states in this template somehhow? :
"{{ not is_state('media_player.jbl_vardagsrum', 'playing, paused') }}"
playing or paused
that did not work 😛
{{ states("media_player.jbl_vardagsrum") not in ("playing", "paused") }}
is there a function similar to relative_time but that works with future dates? I am trying to figure out how many days until event
You can use this, just reverse the first line https://community.home-assistant.io/t/uptime-no-longer-working/256600/64
{{relative_time(now() - timedelta(seconds=as_timestamp(f) - as_timestamp(now()))) }} f being your future date. It creates a date in the past with the same delta than you future date
hey guys, I'm trying to build a discomode for my light, right now I'm pretty stuck, it seems I'm not completely understanding how to use the "data_template:" especcially the part with the ">" or ">-" behind it. Where can I find what these sign mean to learn how to execute my template without a syntax error? 🙂
of course I tried to google, but without a name it's super hard to find something
> means multiline template and you don't need to wrap the template in quotes. - removes the leading whitespace in your template. The - is mostly meaningless because all leading and trailing whitespace is trimmed with how we process templates. These characters are yaml characters, so when googling, google yaml notation without including HA or the word templates.
Hi!
I have a question about blinds in HA, i have blinds that are connected via telldus live, but they show up as lights in HA, is there some way to change the unit from light to blinds?
Is it possible to parse json from a mqtt message in the template editor?
Not really sure what this question means. If you put this in:
{% set parsed = {
"hello": "I'm JSON"
} %}
{{ parsed }}
Then it says the output is a dict implying that it has parsed the pasted in JSON into a python Dictionary, is that what you want?
Is there a template to get the name of your home assistant installation?
the one we set at the top of /config/core
you have to make a template cover
no
can i pull data directly from mqtt and how?
im trying to save a message to a file, only 1 message
ahh ty @inner mesa , the gui is causing issues like usual
Hey, folks. I'm trying to change the look of a lovelace card when a particular event has been trigger for more than, say, 5 mins. I have card-mod loaded and working, but I think I need a template to activate the change. I've read through the templating docs, but I'm not sure where to start. Is there an example I can look at to get started?
How about this for a more narrow question - can I find the time an entity state changed in a template? I should be able to do some math with that.
thank you, I forgot, that YAML is a think outside of ha and templates
entity_id for heater switch, must be a toggle device. - does this mean I need to create a template switch to toggle the entity on and off? and if so, how do I toggle something that's power options are either heat and off or cool and off?
switches:
bedroom_aircon:
value_template: "{{ is_state_attr('climate.master_bedroom_aircon', 'hvac_modes', 'cool') }}"
turn_on:
service: script.bedroom_ac
turn_off:
service: climate.turn_off
target:
entity_id: climate.master_bedroom_aircon```
is what I came up with but doesn't seem to work
I'm trying to convert a value I get as sensor to string. I currently have template_value: '{{ value != 2 }}' which converts it to bool.
Trying to go further to a string, I tried the {% if ... %} {% else %} style, and both C and python style ternary expression.
That switch will only be on if the state of the climate device is 'cool'.
ah so the device already has to be on cool?
how would i get it to toggle from off to cool and vice versa?
That's how you wrote the value_template, which is what determines the state, so yes.
wow i am retarded
if you want cool when turning on, then your turn_on service must turn it to cool
you would have a good laugh if you looked at my yaml no doubt haha
what's your question
How to go from bool to string in value_template. Because the various if constructs I tried lead to errors
The turn on service is a script to turn it to cool as I don’t know how I’d write the yaml for just turning it on within the template. Will that not work?
Why do you need a string? What are the errors you getting?
turn_on list is a list of services and doesn't use a template
so really should be service: climate.turn_on target: entity_id: climate.bedroom_ac
switches:
bedroom_aircon:
value_template: "{{ is_state_attr('climate.master_bedroom_aircon', 'hvac_modes', 'cool') }}"
turn_on:
service: climate.turn_on
target:
entity_id: climate.master_bedroom_aircon
turn_off:
service: climate.turn_off
target:
entity_id: climate.master_bedroom_aircon```
Looking better? Or have I still stuffed up `value_template`?
check out all the climate services that set the hvac_mode
Because I want it to be a string in the automaticlaly handled overview thingy
2021-03-26 12:28:51 ERROR (MainThread) [homeassistant.config] Invalid config for [sensor.snmp]: invalid template (TemplateSyntaxError: unexpected '%') for dictionary value @ data['value_template']. Got '{{ {% if value != 2 %} Connected {% else %} Disconnected {% endif %} }}'. (See /home/homeassistant/.homeassistant/configuration.yaml, line 16). Please check the docs at https://www.home-assistant.io/integrations/snmp
The others looked similar. Just with the other syntax in there that I tried
target:
entity_id: climate.master_bedroom_aircon
hvac_modes: cool
fan_modes: medium
like that?
this is all the state attributes for the main entity
ugh that isn't gonna work
ok there is a service service: climate.set_hvac_mode
but if I call that, it does not turn it on
actually, it does 🙂
now i am getting somewhere
how do I create a fan template that controls low/mid/high fan modes on a climate entity?
Ahh, the {{ }} around the entire thing were the issue. Leaving them away fixes it. That wasn't too hard
so strange - now the switch will not turn off the AC
value_template: "{{ is_state_attr('climate.office_aircon', 'hvac_modes', 'cool') }}"
turn_on:
service: climate.set_hvac_mode
data:
hvac_mode: cool
target:
entity_id: climate.office_aircon
turn_off:
service: climate.turn_off
data: {}
target:
entity_id: climate.office_aircon```
set the hvac_mode to off
@obsidian delta posted a code wall, it is moved here --> https://paste.ubuntu.com/p/7Fqh3RPTtr/
Template line indicators do not go inside template line indicators. {% %} means the contents does not return a value {{ }} means the contents do return a value.
{{ {% %} }} is never valid. {% {{ }} %} is never valid. Any permutation of that is also invalid. You'll only ever have these side by side... {{ }} {% %} {{ }} {% %} etc.
I would really welcome a pointer - how to achieve a break between each line... tried everything.
grrr.... still no good....
value_template: "{{ is_state_attr('climate.office_aircon', 'hvac_modes', 'cool') }}"
turn_on:
service: climate.set_hvac_mode
data:
hvac_mode: cool
target:
entity_id: climate.office_aircon
turn_off:
service: climate.set_hvac_mode
data:
hvac_mode: 'off'
target:
entity_id: climate.office_aircon```
it looks right to me
it must be something to do with value_template: "{{ is_state_attr('climate.office_aircon', 'hvac_modes', 'cool') }}" no?
actually i have an idea...
does the attribute hvac_modes change state to cool or does another attribute do that?
or does the main state?
hvac_modes does both cool and off
no, that's not the question
i thought i figured it out but no, still broken
does hvac_modes get set to cool?
ah yes it does
ugh.... haha....
take a screenshot of the entity in the devtools states page
and post it here
well nevermind, I have an exmaple
hvac_modes: heat_cool, heat, dry, fan_only, cool, off
ok, is that 'cool'?
let me turn it on again 🙂
no, its heat_cool, heat, dry, fan_only, cool, off
just changed from off to cool in the Filter states column
ok, so the state changes from off to cool, so what would that template look like?
value_template: "{{ is_state_attr('climate.office_aircon', 'hvac_modes', 'cool') }}"
turn_on:
service: climate.set_hvac_mode
data:
hvac_mode: cool
target:
entity_id: climate.office_aircon```
https://www.home-assistant.io/docs/configuration/templating/#states see the methods here
nope
see the link
reading now
first, do you know what method you are using right now?
yep.... the one that doesn't work 😉
yes, but what is it
I want to see where you sit with templates
and this will tell me
so, which method are you using?
an is_state
close, you're using is_state_attr
or an is_state_attr
is_state I would think
ok, and if you wanted to check an attribute which one would you use?
is_state_attr no?
aight, so modify the template and post it here
the state is cool but the state attr is heat_cool, heat, dry, fan_only, cool, off
well, hvac_modes attribute is heat_cool, heat, dry, fan_only, cool, off
ah yes
aight, so try to alter the template
I would think
value_template: "{{ is_state('climate.office_aircon', 'cool') }}"
turn_on:
service: climate.set_hvac_mode
data:
hvac_mode: cool
target:
entity_id: climate.office_aircon
turn_off:
service: climate.set_hvac_mode
data:
hvac_mode: 'off'
target:
entity_id: climate.office_aircon```
would do it
That looks good
nice
thank you so much 🙂
np
I have actually learnt something
that was the goal 😉
🥣 not just spoon fed
now just to wait for my new temp sensors and zzh to arrive and I can finally get this working properly, fingers crossed...
I want an entity to be the result of three things. Calendar start time + waze travel time + 20 minutes.
How can I get a thing that is the result of that math?
I tried "{{ state_attr('calendar.xxcalendarnamexx', 'start_time') + state_attr('sensor.waze_travel_time_5','duration') + 20}}"
Not it doesn't appear to be logging a number
what are the actual values of start time and duration?
There’s a few posts on the forum with solutions to this answer
I've googled around and can't see to get the syntax right to find it
Do you have a link to one by chance?
here's the thread I was thinking of https://community.home-assistant.io/t/automation-based-on-traffic-and-train-delay-waze-travel-time-sensor-viaggiatreno/72673
Need help building a template that determines if the time from a sensor is before noon the next day (or current day if it's before noon).
The sensor outputs as: 2021-03-27T12:07:00.000Z OR Time in Milliseconds
Can someone help me with cover template? I am stuck. i got the template working so i could open_cover and close_cover, but the state dosen't work, i am trying to change my blinds that show as light.gardin_kok, and have set brightness_pct: "{{ position }}" but still it won't work
Hey, I'm doing and if, else if, else if, thing for a weather provider, so, basically, I want it to use my own sensors for wind and rain, but if it isn't raining or windy, I want it to pull it from another weather provider. So, I'm doing this:
condition_template: >
{% if states('sensor.estacion_meterologica_ratio_de_lluvia') > 3 %}
pouring
{% elif states('sensor.estacion_meterologica_ratio_de_lluvia') > 0 %}
rainy
{% elif states('sensor.estacion_meterologica_velocidad_del_viento') > 19 %}
windy
{% else %}
{{ states('sensor.aemet_condition') }}
{% endif %}
But for some reason, I can't get it to work
If I do this, it totally works:
condition_template: "{{ states('sensor.aemet_condition') }}"
where is "condition_template" valid?
In the "Template Weather Provider"
Like this?
condition_template: >
{% if states('sensor.estacion_meterologica_ratio_de_lluvia')|float > 3 %}
pouring
{% elif states('sensor.estacion_meterologica_ratio_de_lluvia')|float > 0 %}
rainy
{% elif states('sensor.estacion_meterologica_velocidad_del_viento')|float > 19 %}
windy
{% else %}
{{ states('sensor.aemet_condition')|float }}
{% endif %}
Oh sorry, I pasted the float there
It works!
Thank you
you don't need a float on that last one, it wont' do anything
but you're going to be returning a number instead of windy, rainy, or pouring
Also your order of operation is wrong
er, nevermind, it's a separate sensor
agreed on the last one. should just stay a string
It isn't working
just removing |float from the else clause won't break it
perhaps you did something else
I already did?
what isn't working? and how?
The weather provider loads, but it shows "Unknown"
that could mean that your sensors aren't reporting good data. Does it work in the template dev tool?
Yeah
And the sensor reports "clear-night" so it should work
And all of the other sensors work
If I change the wind one to "> 0" it's shows windy
ok. I don't use that particular integration, so if it works in the dev tools, I don't know what could be wrong. Unless it's initially getting bad data at start, the sensors update, but the weather template doesn't see the chagne
Hang on
I just found what wasn't working
It's a bug
clear-night doesen't work in template weather provider
If I just do condition_template: clear-night
It doesen't work
If I do condition_template: sunny then it works!
it probably needs to be quoted
I have this code which gives false but it should be true. i guess the round(0) isnt doing what it should. Can someone tell me how i write it the right way?
{{ is_state('input_number.jaloezien_in_procenten'| round(0), states('sensor.brel_motor_links_positie')) }}
input_number.jaloezien_in_procenten gives the value 0.0 and sensor.brel_motor_links_positie the value 0
So thats why i want to round the first one
This code is giving me the value 0 so i guess in an is_state i need to write it differently?
{{ states('input_number.jaloezien_in_procenten') | round(0) }}
You can't use is_state that way. It is expecting an entity for the first parameter
so i could use it for the second part
An easier way would be if a input_number helper wouldnt comunicatie 0.0 but just 0 Its pretty annoying that you cant tell in home assistant that it has to use round numbers. Especially when you set the increment step to 1.
By the way this {{ is_state(('sensor.brel_motor_links_positie'), states('input_number.jaloezien_in_procenten')| round(0)) }} isnt working as well
Does anyone have an idea how to fix this in a condition?
I noticed some weird behavior in the weather template when using the forecast template. When using {{ states.weather.openweathermap.attributes.forecast }} which generates a list things work alright but when using {{ states.weather.buienradar.attributes.forecast }} which generates a string a error occurs in the log and the weather(templated) entity doesn't work. Is this a fault in the weather_template integration or in the buienradar integration?
i gave up.... I made a sensor that first rounds the input_number and use that in a template
All you need is this {{ states('sensor.brel_motor_links_positie')|int == states('input_number.jaloezien_in_procenten')|int }}
if i have this trigger:
- platform: device
domain: mqtt
device_id: ab8e6b8f333ee21c47bf8070b5d96d8a
type: action
subtype: on-press
what should i put on:
- choose:
- conditions:
- condition: template
value_template: "{{ trigger.?????? == 'on-press' }}"
to make it work?
If you change it to an event trigger, then you should be able to use trigger.event_data ==
hmm not sure i can do that with zigbee2mqtt
but let me try
yah no dice can use event on that
so only remains to listen on topics
So... MQTT triggers? 🤯 https://www.home-assistant.io/docs/automation/trigger/#mqtt-trigger
@ivory delta yah that works and choose works also with them
but
i was trying to do it the recommended way 🙂
Via MQTT device trigger (recommended)
What's recommended depends on what you're trying to do. And I still have no idea what you're even trying to achieve here... your trigger already narrows down the device action to an 'on-press' subtype. What's the condition supposed to do?
let me put up something for you to see what i want to do
one moment
ok this is a working automation https://pastebin.com/43jDDENL
if you look at the commented triggers
i need the choose template conditions for the commented triggers
but that doesnt work i think
I'm not reading through 300 lines. Explain what you're trying to do.
take as example only first commented trigger
how do i make that:
- choose:
- conditions:
Ok... so you want to have X different triggers and then use a choose:... use MQTT triggers 🤷♂️
It doesn't matter if the one person that wrote the z2m docs says that device triggers are recommended. You need to think about the different available tools and pick the right tool for each task.
De rien
ha you are french 😄
Hi there!
I have this
- choose:
- conditions: >
{{ is_state('sensor.utendors_lysstyrke' | float, < 600) and
is_state('input_boolean.in_bed', 'off') }}
... but it´s totally wrong.
The conditions should be like:
(if state_of_sensor is below xxx) and
is_state('input_boolean.in_bed', 'off')
I ended up doing this, thus conditions will not apply untill tomorrow when it´s not dark outside
action:
- choose:
- conditions:
- condition: numeric_state
entity_id: sensor.utendors_lysstyrke
below: 800
- "{{ is_state('input_boolean.in_bed', 'off') }}"
That is an incorrect use of is_state. You don't need any templates this can all be done with standard numeric_state and state conditions.
So my last lines of code would be correct, then?
You still don't need a template. Use a state condition for the last condition.
- conditions:
- condition: numeric_state
entity_id: sensor.utendors_lysstyrke
below: 800
- condition: state
entity_id: input_boolean.in_bed
to: 'off'
state: 'off' would be it, right?
Correct!
Thanks"
I never found several condition: tests in the documentation for the choose: actions, though 🙂
Standard condition rules apply, see the condition syntax doc page.
FYI to do it all in one template would have been: {{ states('sensor.utendors_lysstyrke') | float < 600 and is_state('input_boolean.in_bed', 'off') }}
I tried this at first, but did not succeed
No you didn't. Look closely. There is no is_state for the first part of the template.
Also there were other issues that I just edited out.
you got it! It evaluates correct in the template editor here 😉 Thank you
Hi! I am using a template to convert my light.gardin_kontoret to cover.gardin_kontoret
I did succed to get this working so it now show up as a cover instead of a light, but the problem now is the script can't see the position, so if i change the "brightness" witch is the position in the UI, it works great, but if an automation change the position, ex rolls it down - it won't change and appears as up in the UI, here is my script code
position_cover:
sequence:
- service: light.turn_on
data:
brightness: "{{(float(position)*2.55)|int}}"
entity_id: light.gardin_kontor
Thanks!
How do I create a trigger from a sensor entity that's triggered when its value drops by 2ºC?
e.g. I want to turn on a climate entity when bedroom temp drops
I would use a state trigger for any change and a condition template that subtracts the to_state from the from_state and compares against 2
Or...the other way around
That just checks for changes that are 2 degrees at once. You’d need a more complicated solution if you want to measure over time or pick some other reference
You need a position template
That service is correct, but that's not what generates the position state for the cover.
Alright, i am pretty new with this and trying to learn every day, i don't quite know what you mean or how to do it, but this is the last part of my cover template from config.yaml
set_cover_position:
service: script.position_cover
data:
variables:
position: "{{position}}"
Good morning everyone!
I am using the github integration to monitor a few repos. Among the data, there is an attribute, latest_release_tag. Can I use some template to identify if there has come a new version? For example, the HA core repo has a latest_release_tag of 2021.3.4 at the moment. I'd like to trigger an automation if there is a newer version available.
I know that HA has an internal fuction for this, but I am using this with other repos. HA is just an example in this case.
How would one nest the state of a device in a template? For example: (yes the indenting is wrong)
https://pastebin.com/Sx8uEMPX
It's currently read out by tts.cloud_say as if it was text, but I would like to report the actual value 🤷🏼♂️
Would this work?
condition:
- condition: template
value_template: |-
{% if states(trigger.from_state)|int - states(trigger.to_state)|int >= 2 %} true {% endif %}
Take a look at the docs, you need a position template. It's literally called position_template. You keep focusing on the set_cover_position service, that was fine the first time you did it.
Just use the updater integration
https://www.home-assistant.io/docs/backend/updater/
https://www.home-assistant.io/integrations/updater/
second link
Yeah, I know, but for the versions of other stuff I am tracking.... 🙂
temperature is not the actual value?
{{ trigger.from_state.state | int - trigger.to_state.state | int >= 2 }}
however, your trigger needs to be a state trigger.
The state of that entity is ‘heating’, the set temperature is an attribute of the entity
@magic pike Ok so what do you want, the temperature or the state?
You can use the same concept. A state trigger can also take an attribute, and your condition template can compare the attributes
I understand, the only thing i don't quite understand is the sensor part, since my cover is imported as a light, the brightness is the position, but how do i tell home assistant that my position_template is the brightness? The only thing i find in the docs is that it's taking that value from sensor. but i don't have any sensor. Or am i just dumb and missing something?'
You have to adjust the template to extract the brightness as the position
basically you'll be inverting this equation
{{(float(position)*2.55)|int}}
but instead of using the position variable you'll be pulling the brightness from your light
thanks for your answers, but i understand i am too much a newbie to understand how to get this working properly
well do you understand how to solve for position from a brightness value?
hint: this is 8th grade math, or at least it was taught to me in year 8.
y = x * 2.55, how do you invert this to have x = ?
getting the brightness requires you to use the state_attr method
No, 8th grade was to long ago and i wasn't paying so much attention at the math classes unfortunately.
Yeah i manage to get the brightness with the state_attr by using the following
{% if states.light.gardin_kontor %}
{{ state_attr('light.gardin_kontor', 'brightness') }}
{% else %}
??
{% endif %}
But i don't really know how to get from here
well, you got the brightness correctly but the rest isn't needed. All you're trying to do is convert 0 - 255 brightness to 0 - 100 percentage.
y = x * 255 inverted is x = y / 255. Very simple math. Where x = percentage and y = brightness. So... if state_attr('light.gardin_kontor', 'brightness') gets your brightness and the equation is brighness / 255... then what would you have as a template?
are you there?
yeah sorry
so what do you think the template should be for just the equation?
state_attr('light.gardin_kontor', 'brightness') returns the brightness. And the equation is brightness / 255
{{ brightness / 255 *100}} ?
yep, but what goes in the place of the word brightness?
hint: You already figured that part out
Sorry since English isn't my foreign language i have to think twice for everything you write, so my brain is working like an 56k modem atm, hang tight
do you mean something like this? {{ position/ 255 *100}}
state_attr
yep, so if the equation is brightness /255 * 100... what goes in the place of the word brightness?
i am so stuck
you've given the answer like 3 times but you aren't combining it
no i get lost in your words
just look at the equations ignore my words
haha
brightness / 255 * 100
state_attr('light.gardin_kontor', 'brightness') returns the brightness
combine them!
I'm not sure what you're doing to overthink this. Here's the answer
state_attr('light.gardin_kontor', 'brightness') / 255 * 100
see how simple that was?
easy for you to say 🙄
all said and done, your position_template would be:
position_template: "{{ state_attr('light.gardin_kontor', 'brightness') / 255 * 100 }}"
told you i were a newbie 🍴
yes but I told you to replace the word brightness
I'm not sure how else that could have been conveyed
you had the equation. You had the way to get brightness, you just needed to combine "getting the brightness" and the "equation"
Is there a need to supply an integer for the position?
i don't think so, floats and int's resolve to a number in the template resolution
yeah well i know, but since i was lost in the words my brain was freezing, and i just started with this type of coding 3 days ago, so i don't really get the hang of it yet. But i really appreciate you time and effort trying to make my brain figure this out
you´r
ugh... as it turns out, my shutter dc tells different values everytime it goes to a up or down position, so if it's up it can sometime tell 255, and sometime 90, 150 etc.. so guess i am back at the beginning
Hi guys, i need change value, when my binary sensor is ON set in template value 2050, when is off set nothing or zero.
`#Boiler Changer when is ON State to 2050 kWh
- platform: template
sensors:
binary_sensor.boiler_state:
friendly_name: "Boiler 2050 kWh"
unit_of_measurement: "kWh"
value_template: "{%if states.binary_sensor.boiler_state.state == 'on'}2050{% elif states.binary_sensor.boiler_state.state == 'off'}0{% endif %}"`
where is the problem in the code ? thx
I don't understand you, write me exactly how you think, thank you @inner mesa
#Boiler Changer when is ON State to 2050 kWh
- platform: template
sensors:
binary_sensor.boiler_state:
friendly_name: "Boiler 2050 kWh"
unit_of_measurement: "kWh"
value_template: "{%if states.binary_sensor.boiler_state.state == 'on'%}2050{% elif states.binary_sensor.boiler_state.state == 'off'%}0{% endif %}"
and, you should use is_state('binary_sensor.boiler_state', 'on'), for instance
you hadn't terminated your {% with %}
clear?
no im go try this is_state('binary_sensor.boiler_state', 'on'),
understand the bit about %}?
no
look at the difference between yours and mine
you have {%if states.binary_sensor.boiler_state.state == 'on'}
I have {%if states.binary_sensor.boiler_state.state == 'on'%}
Hi, I am trying to get a template sensor to work. I have this code:
{{states.group.grocy|expand|selectattr('state', 'eq', '0')|list|count|int }}
It works great, and give the correct result when i test it in template editor, but when i try to validate the config, i get an error saying that there is no filter named expand
Can anyone see what I am doing wrong? Don't get why it is working fine in the template editor, but not when i try to validate the config
Would need to see the template sensor definition, but you replace that with expand(‘group.xxx’)
Thanks RobC! Using expand() worked
Got a template question 🙂
timeout: "00:01:00"```
Will this turn something off if the binary sensor is inactive for one minute?
This is the sample from the documentation btw, just trying to figure out which parts I need to alter
that just waits, it does not perform actions
If the sensor is triggered again, will that reset it?
Trying to make a sensor light that will turn on, then after 2 minutes of no activity, will turn the light off
use a wait_for_trigger with a default
Ah yep, cheers 🙂
- wait_for_trigger:
- platform: state
entity_id: binary_sensor.hallway_sensor_motion
to: 'off'
for: 120 ```
I’m guessing that would do it in my case, with a call service light.turn_off following it?
Hmm doesn’t seem to be
Ok - for: needs -minutes after it 😂
Is something like this possible? Can I use a pipe as an OR statement?
value_template: "{{ trigger.event.data.entity_id.startswith('switch.|light.') }}"```
not like that. This says you can provide a tuple:
Markup.startswith(prefix[, start[, end]]) → bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.
{{ "bar".startswith(("foo", "bar")) }} -> True
{{ "foo".startswith(("foo", "bar")) }} -> True
{{ "blah".startswith(("foo", "bar")) }} -> False
Thank you!
Am I doing something wrong in the first line here? I can't get it to work.
value_template: >
{% set last_triggered = (expand(trigger.event.data.entity_id) | first).attributes.last_triggered %}
{{ (as_timestamp(now()) - as_timestamp(last_triggered)) | int > 1 }} ```
If I hard code the entity id instead of trigger.event.data.entity_id, it works as I intend
I think expand() returns a list
Or a generator
Oh, you have |first
Do you see the entity_id in the event from
-> Events?
last_triggered attribute is only on automations, i doubt your trigger is using an automation entity_id
or script
@grim obsidian posted a code wall, it is moved here --> https://paste.ubuntu.com/p/xCNQCt7K7x/
thats going to fire on every state change
you'll get errors for evey item that doesn't have an automation.turn_on_<xxxx>
Right. Could I use something like domain: switch in the trigger?
just make an if statement to check if the automation exists
{% set automation = expand('automation.turn_on_' ~ triggered_by) | first %}
{% if automation %}
...
{% endif %}
Good idea.
what are you trying to do... this seems over complicated
I'm sure it is. Basically what I want to accomplish is if a light/switch/any device is turned on/off by anything other than an automation (i.e physically, voice command, Lovelace), it will stop that device from being controlled automatically.
# and if it was turned on manually (not by an automation),
# it will override that device's automation and "lock" it in its' new state.```
is this specifically for motion sensors? How are you going to enable the automation again?
also, there's a context attached to every state object. You can build a simple auotmation and check the context against an automation id or user id
Depends on the automation, but generally I'm thinking of resetting all overrides once a day, e.g. when exiting sleep mode
well, as someone who's been doing this for years, i'd suggest against all this as it ultimately doesn't work the way you might want
I personally moved to other actions to disable things, and only specific things
like double tap on a light switch, etc
and then double tap to start back up
I appreciate the advice. I'm definitely considering the fact that I'm a bit too deep down the rabbit hole right now.
at this point in time, I only have 3 automations with a 'cancel'
and that's automated door lighting when I open a door
light stays on for 2 minutes and shuts off. Sometimes I want to keep the light on. So double tap to cancel the turn off
thats what I mean by 'specific'
because the automation still runs, but you can just cancel that one specific event
You're probably right. This is the entire thing, and it actually seems to be working, but it also scares me a little bit:
https://pastebin.ubuntu.com/p/p8VMM2x3GN/
If I have a question about how to configure a Zigbee Switch to i.e turn on and off a light, then it's in here, and not in Zigbee channel, right? 🙂
Hi, there! I have this template in a script, and there is no other option for an {% else %} clause. Will it still be valid. Is there other methods i would rather use to trigger the scipt only if binary_sensor.dark_inside is true/on?
goodmorning:
alias: God morgen
sequence:
- service: input_boolean.turn_off
data:
entity_id: input_boolean.in_bed
- service: >
{% if is_state('binary_sensor.dark_inside', 'on') %}
script.lys_grunnbelysning_on
{% endif %}
Use a state condition above the second service call.
If the state is false, the execution for the rest of the script is haltet, right?
Correct. So you may have to move it to the end of the sequence.
I sure do 🙂
BTW how is the state conditoin put in a script? I always struggle remembering this....
- service: condition... ??
Found it 😉
Like this: ```
- service: some.other_service
- condition: state
entity_id: binary_sensor.dark_inside
state: 'on' - service: script.lys_grunnbelysning
- condition: state
entity_id: binary_sensor.dark_inside
state: "on"
Yep 👍
Yes
Hmmm. had an error checking, and it passed when using double quote.
Nice to be certain I can use both
Should make no difference.
There's a style standard for documentation that calls for double quotes but that is a recommendation for documentation. Single quotes should still work.
I´ve ended up using single qoutes inside tamplates and for variables, but double outside the entire template
Yep, that's the style standard but the other way round does work.
quotes are only needed for on/off because they translate to true/false with all the yaml interpreters. Outside that, you don't need quotes unless you're single line templating
So here's something I'm wondering. I've built some venetian blind motors off of a NodeMCU that's working over MQTT. If I set it to positionCommand = 20, the blinds will be closed down, and if I set them to 0 they are closed up. 10 is open. Is there a way to set the covers in HA to when it's told to be open it sets to 10 by default and closed at 20, but allow some adjustments if I want to adjust them with the slats up if desired?
Hey!
I am trying to make a template to change the attribute on lovelace UI, for now it shows my cat is "Gone" and "Home" but i wan't it to show "Ute" and "Inne"
But i can't really figure it out, this is what i have to get the attribute from the sensor..
How i try to change it back and forth it only shows "Ute"
{% if is_state_attr('binary_sensor.pet_doris', 'where', 'inside') %} Inne {% else %} Ute {% endif %}
nevermind... changed 'inside' to 'Inside' and wops it works 🙄
You can do it all on one line if you like: {{ Inne if is_state_attr('binary_sensor.pet_doris', 'where', 'Inside') else Ute }}
I have a question about rest and templates, is this the right room? 🙂
Yes
So i'm trying to retreive data from a JSON file but i keep staring blind on that little code. Everything seems to be working'ish, but the sensor wont pick data from the JSON attributes. I need a push in the right direction...
using this tool: https://jsonpathfinder.com/ to get the right path. My corona_dashboard does retreive information from the JSON, however it wont get put through to the sensor.
Remove x. X is your sensor.
Though I still don't think the path is correct. There's a values missing as well.
See and this. remains to be the question...its the wall that i keep running up to
I believe the path checks out, seeing as the JSON gets picked up by the tool and i derive all paths from that location
So at the moment this line underneath gives me the information in the 'corona dashboard'
json_attributes:
- vaccine_administered_planned
state_attr('sensor.corona_dashboard', 'vaccine_administered_planned').values[0].doses
Or maybe state_attr('sensor.corona_dashboard', 'values')[0].doses
That's for your first template sensor.
omw
One error:
can not read a block mapping entry; a multiline key may not be an implicit key at line 153, column 24:
friendly_name: "Vaccine Administered"
^
need to see the whole thing
your spacing is wrong and you need to mix your quotes
Double quotes outside the template.
you can see from teh color coding on the sharing site
Or value_template: "{{ 'running' if is_state('<your_sensor>', 1) else 'stopped' }}"
Ok, somethings changed now
Vaccines administred state_attr('sensor.corona_dashboard', 'values')[0].doses persons <-- this is at the suffix location now in the column
Have you checked the template in the developer tools template editor?
Well, if i load the code in there it says: UndefinedError: 'value_json' is undefined
but im affraid i get lost even further when i go there...just because thats the part that seems to be right
but i cant say that with full confidence
{% set value_json = {"your": "json", "payload": "here"} %}
where do i put that?
in the template tester
ok
You should not have value_json in the template you are testing. Test this one: ```
{{ state_attr('sensor.corona_dashboard', 'vaccine_administered_planned').values[0].doses }}
same output; This template does not listen for any events and will not update automatically.
And this one: ```
{{ state_attr('sensor.corona_dashboard', 'values')[0].doses }}
Look i really appriciate you guys helping out
Ok last one brings back this; UndefinedError: None has no element 0
Can you link to a screenshot of the sensor.corona_dashboard attributes in the developer tools states menu?
max 15 lines right? I could paste it here if thats allowed
vaccine_administered_planned:
values:
- doses: 514015
date_start_unix: 1616976000
date_end_unix: 1617494400
date_of_insertion_unix: 1617062400
last_value:
doses: 514015
date_start_unix: 1616976000
date_end_unix: 1617494400
date_of_insertion_unix: 1617062400
friendly_name: corona dashboard
Hi there, i want to create a binary template sensor for my media player to only show true if its playing and the content type is video.
- platform: template sensors: apple_tv_state: friendly_name: A movie is playing. value_template: {{ is_state('media_player.living_room_apple_tv', 'playing') and is_state((state_attr('media_player.living_room_apple_tv', 'media_content_type'), 'video')}}
you need to quote the template
not sure what's going on with this bit: is_state((state_attr('media_player.living_room_apple_tv', 'media_content_type'), 'video')
that part is supposed to get the state of the "media_content_type"
This is already working
- platform: template
sensors:
apple_tv_state:
friendly_name: A movie is playing.
value_template: {{ is_state('media_player.living_room_apple_tv', 'playing')}}
a "state" is a technical term that describes the current state of an entity. not just a string comparison
you need to quote the template
value_template: "{{ is_state('media_player.living_room_apple_tv', 'playing')}}"
Now i also want to include the media_conent_type
media_content_type: video
media_duration: 7108
media_position: 4712
media_position_updated_at: '2021-03-30T20:05:45.416502+00:00'
media_title: The Bourne Identity
app_id: com.netflix.Netflix
app_name: Netflix
friendly_name: Living Room Apple TV
entity_picture: >-
/api/media_player_proxy/media_player.living_room_apple_tv?token=d146e96ae4c7aa874ccb0fb30da17dec4804be82c528bf4e332c18f47dc7949e&cache=com.apple.avkit.207.d9ed8e7b
supported_features: 317363
i used the template under developer tools to very it and the first part works?
it will, but the YAML parser will probably choke on it
ahh ok thx
I'll add them
the "playing" state is not an attribute if i got it right?
correct, it's the state
ahh ok, that was a bit confusing
each entity has a state and (optionally) a set of attributes
so this should work
` - platform: template
sensors:
apple_tv_state:
friendly_name: A movie is playing.
value_template: "{{ is_state('media_player.living_room_apple_tv', 'playing')
and is_state_attr('media_player.living_room_apple_tv', 'media_content_type', video) }}"
`
'video'
meci
sorta. if you can fit it all on one line, then yes. Otherwise, you need to use a multi-line template like this:
- platform: template
sensors:
apple_tv_state:
friendly_name: A movie is playing.
value_template: >-
{{ is_state('media_player.living_room_apple_tv', 'playing') and
is_state_attr('media_player.living_room_apple_tv', 'media_content_type', 'video') }}
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://paste.ubuntu.com/ or https://www.hastebin.com/.
FYI quoting works with multiline templates like he has it as well
just unnecessary
it's just not readable
what does that mean?
don't worry about it 😉 Just go with @inner mesa's suggestion
It was just some info for him
for future support
Basically there's 2 ways to use multiline templates. With quotes, on the first line and last line. Or with >, >-, |, |- and the template on the next line(s).
I'm having an issue where i can't get a "History" graph to show a bar chart
- platform: file
name: "Speedtest Download"
file_path: "external/speedtest.csv"
value_template: >
{{ ((value.split(',')[7]|replace('"','')|float)/125000) | round(2) }}
Here's one of the sensors. It reads from a csv file
in customize.yaml, I'm doing this:
unit_of_measurement: Mbps
in entry customizations, I see the Mbps unit of measurement.
I only read this file daily - does it need to wait for the next reading to come in to switch over to a sensor with units?
Maybe answered my own question - I created a new sensor like this one with units and it came in as a continuous measure. So, I'll just put the units in here and wait.
yes, you need to add unit_of_measurement to have it display a graph
and yes, if it still has some old data with it, or that's considerably different, it can confuse it and you need to either flush it out by pruning the database or just wait it out
or creating a new sensor, as you did
Nice, thanks for the reply. How does one prune the database?
depends on the database you're using, but: https://www.home-assistant.io/integrations/recorder/#services
Anyone got a way to pass color_xy into a template light, or how to get a color_xy out of of one? Looks like it only supports color_hsl but my light only supports color_xy 😦
How do I get a dict of a dict? So far I've got
{{ states.media_player.shield_tv.attributes.adb_response }}
Which outputs another dict. I'd like to add .wake_lock_size
ok - I've found the formula to convert between them, but it's rather complex - is there a recommended way/integration that will allow me to add either a js or python function into jinja?
What does return adb_response? You may be interested in https://www.home-assistant.io/docs/configuration/templating/#tofrom-json
python script, but the the result can only be set on a helper. You can create sensors, but they don't persist on startup so there will be periods of time where the device doesn't exist. Your best option is to use an input text or input number to store the value and create a template sensor off that.
I'm actually trying to create a template light - but the light only supports xy_color and template light only supports rgb 😦
will look into helpers more to see if that will help me
the function I thought worked only seems to work for the set of test-data I used - more randomized values fail 😢
Sometimes a few of my sensors report a value that is obviously wrong - like after a restart before Z-wave is up to date.
I know there is a function that can handle that - but I can't find it. Tips?
It may be that your template sensors using |float or |int are evaluating to 0 when the referenced sensor is unavailable. Using a test in the template or an availability template can rectify this.
Ah! Not the solution I had in mind, but thanks! I'll begin with looking in to that.
Is it possible to add an AND condition in a template that checks the history of a value for e.g. in the last 5min and defaults to true if the set state has been active?
yea but you have to code it out. Much easier to just use a yaml and condition
adb_response returns:
{
"screen_on": true,
"awake": true,
"audio_state": "paused",
"wake_lock_size": 4,
"current_app": "com.hulu.livingroomplus",
"media_session_state": 2,
"audio_output_device": "hdmi",
"is_volume_muted": false,
"volume": 15,
"running_apps": [
"com.android.systemui",
"com.nvidia.blakepairing"
],
"hdmi_input": null
}
@eager veldt posted a code wall, it is moved here --> https://paste.ubuntu.com/p/cr9YwjJ5Y7/
guru's, does this look right?
friendly_name: "Family Status"
value_template: >-
{{ is_state('person.damien', 'home')
or is_state('person.olia', 'home') }}
Home
{ else }
Away
{ endif }```
for a sensor if family is home or away
No
plz help
remind me what the diff between { } {{ }} and {% %} is?
i knew it was gonna be bad 😄
You should review the templating docs
yeah there wasn't an example of using an 'or' in there that I could see
Where is your if?
If/else/endif
‘Or’ is just ‘or’
friendly_name: "Family Status"
value_template: >-
{% if is_state('person.damien', 'home')
or is_state('person.olia', 'home') %}
Home
{% else %}
Away
{% endif %}```
I think this may actually work
coming back with a result type: string of
friendly_name: "Family Status"
value_template: >-
Away```
Looks better
Convention would have the results (Home / Away) indented one more space. But that's just cosmetic.
Hi, i cannot seem to figure out how to check if something is = to a number, as an example this doesnt work "{% if '{{ my_test_json.temperature }}' == 25 %}"
that line won't work on its own
oh, you're mixing things together
note in jinja {% %} are logic statements and {{ }} are output statements. You do not mix them together in the same line
{% if my_test_json.temperature == 25 %}
or {{ my_test_json.temperature == 25 }}
Hang on, that might of worked. Thanks!
ok thank you.
think i'm asking in the right place for this one, but essentially i've got a command line sensor which does a bit of logic on the curl return to set the value - i'd like to set some more sensors using the response that i'm getting back but it's not as simple as assigning a json value to an attribute, it's more like setting the attributes based on a few operations done on the json response. Can this be done? I'm basically trying to set multiple attributes without having to poll the endpoint multiple times.
That cannot be done with command line, however it looks like a rest endpoint and that can be done with the rest integration
alright, i'll look into that. There was a reason i didn't start with rest... can't remember what it is now though!
Hi
Maybe this is something very obvious but I'm no programmer so forgive me my ignorance - I've tried googling and reading through the documentation but can't find any examples of the correct way to do this so I came here to ask.
The documentation says you should use {{ states('device_tracker.paulus') }} instead of {{ states.device_tracker.paulus.state }} but I can't find any way to get state.last_updated field using the states(... method. What's the correct way of doing this?
What I'd like to do is replace this:
value_template: "{{ ((as_timestamp(now()) - as_timestamp(states.sensor.outdoor_temperature.last_changed)) / 60) | round(0) }}"
with the suggested format.
states.sensor.outdoor_temperature.last_changed is the format to be avoided.
(expand('sensor.outdoor_temperature') | first).last_changed
but it'll have the same problem as states.sensor.outdoor_temperature.last_changed, so it doesn't matter which route you go if you need last_changed
Thank you guys. I actually stumbled upon that post but apparently didn't read it properly. I'll keep it the way it is then.
Can you guys help me with json_attributes_template? trying to extract "Power" "Voltage" and "Current" with their respective units ( W, V, A)
I'd like the attributes to be like:
Power 52 W
Voltage 123 V
Current 3 A
https://paste.ubuntu.com/p/73TrmsW2z2/
Unfortunately the mqtt integration does not have very powerful attribute gathering options. You can grab all the attributes under ENERGY or one.
what is | tojson for in a template?
It's to covert a string to json there are some examples here https://www.home-assistant.io/docs/configuration/templating/#tofrom-json
Does anyone know how to create custom helpers for jinja template?
I have to create a custom helper, exemple
{{ my_custom_helper() }}
But I don't want to use macro
Does anyone know where I can get some help setting up my spotify?
anyone here an expert on using custom button card template
i got lot of these light entity if i can move some of the stuff into a template it would be great
I have a bunch of nested templates
this is a #frontend-archived question, though
no need to be an expert, just follow the instructions for the card
i have a warning message that annoys me and wnat to stop that. entity_id is deprecated and should be removed. i said ok..... i checked my sensors...i got some places where can be easy to remove like template example, but how to remove from statistics?
Do not remove it from the statistics sensors. That is a required option and is not generating the warnings. For the template sensor with the date sensor entity id you can either use the new triggered sensors option in the current beta release or add {% set update = states('sensor.date') %} to your template after removing the entity id. This does nothing to the rest of the template but as the date sensor is now in the template the template will be monitored for changes to the date sensor and the whole template will be updated when it changes.
If I remember correctly, last_changed isn't an attribute, it is a.. property? Which would be why state_attr("domain.entity", "last_changed") won't work, but states.domain.entity.last_changedwill.
According to https://www.home-assistant.io/docs/configuration/state_object/, it is strongly advised to use the states(), is_state(), state_attr() and is_state_attr() as much as possible, to avoid errors and error message when the entity isn’t ready yet (e.g., during Home Assistant startup).
Is there a better template for what I now use states.domain.entity.last_changed for?
nop
Darn
That should not be causing issues though.
{% set item = expand('sensor.xxx') | first %}
{% if item %}
{{ item.last_changed }}
{% endif %}
set goes inside value_template
value_template: >
{% set update = states('sensor.date') %}
{{ states.automation | list | length }}
or
value_template: "{% set update = states('sensor.date') %}{{ states.automation | list | length }}"
still i have to figure where is single bracket or double by myself to not trouble with silly questions
just use multiline templates and you don't have to think about it
thank you
Does cover.set_position not accept templates, or am I just being silly and messing up a simple thing? 🙂
Basically.. This is what i WANT to do... But HA doesn't like it.
Sigh.. I was stoopid. Sorry..
position: >
{{ state_attr('cover.etage_rullgardin_hoger_fonster','current_position') }}
hi, I have some 2 code door sensors but I want to have an idea when the battery dies. There is no battery state advice with the sensors so it has been suggested by a friend in automations thhat a template could be used to monitor last activity. Can anyone suggest how this could be achieved please?
Scroll up a little: #templates-archived message
OK thanks I'll try this. Thanks
What is the correct way to use true/false in jinja templates? Is it true/false, True/False, TRUE/FALSE, TrUE/FaLsE?
True/False
though i don't think its super picky
the first three could work
but the 2nd will definitely work (python)
All lowercase has been working but with the beta attributes template warnings I am trying to make sure to eliminate things. Thanks
And that is the error I am getting
Template variable warning: TRUE is undefined
ahh ok, trying to use it like a var then
Hi, I'm looking for some help in passing a float in order to assign a random color to an led bulb. The following is throwing an error saying that a float is expected in the hs_color values.
service: light.turn_on
data:
hs_color: ["{{ range(360)|random }}", 100]
transition: 1
Try this ```
service: light.turn_on
data:
hs_color: >
[{{ range(360)|random }}, 100]
transition: 1
Thanks @fossil venture , the error I now get is: Failed to call service light/turn_on. None for dictionary value @ data['hs_color']
Do I need to consider a sensor named random first?
How about: ```
hs_color: >
{% set h = range(360)|random %}
{{ [ h, 100 ] }}
Same error with that, Failed to call service light/turn_on. None for dictionary value @ data['hs_color']
Do I need to add this to the configuration.yaml for the random function to work?
sensor:
- platform: random
No
It's a built in function of the template engine.
Try it in the template editor.
I'm trying this from the Dev Tools > Services tab in HA, which template editor should I go to?
Right next to services 🙂
😄
this is the output, service: light.turn_on
data:
hs_color: >
[184, 100]
transition: 1
looks like an extra line break is in there
data:
hs_color: >-
[202, 100]
transition: 1
It worked!!
Thanks so much!
So does the Dev Tools > Services use a different "compiler" than the actual automation engine?
I believe that it's more YAML vs. Jinja. The template editor interprets Jinja, and the line continuation and whitespace chomping is a function of YAML
I see
But can dev tools services interpret jinja?
That would be the issue then. HomeAuto's original template should work irl.
Yeah he was testing it in services.
This is my first non-visual template, so I'm just getting started. I was running into other issues with the IRL template and decided to go to the DevTools to troubleshoot to save a few clicks with each test. Lesson learned 🙂
made more confusing by the fact that some integrations do accept templates in services, like persistent_notification
but I digress..
Wish granted. Home Assistant 2021.4
ooh, easter egg
Hi guys, can someone help me to build a template for an event_type triggered = true? I need something like that "If event.event_type.call_service (domain=cover, service=set_cover_position, service_data=entity_id=cover.my_room_cover) triggered then true
Is that going to be used as an automation trigger?
Yes i want to use it. At the moment it looks like this:
trigger:
- platform: event
event_type: call_service
event_data:
domain: cover
service: set_cover_position
service_data:
entity_id: cover.my_room_cover
this works but my trigger should be if this call service is Not called with my_room_cover. Thats why i try templating
So first knock off the entity ID and you have a trigger that knows set_cover_position was called for some cover:
trigger:
- platform: event
event_type: call_service
event_data:
domain: cover
service: set_cover_position```
Then your condition will check which entity ID was inside the event. The template would be something like: {{ trigger.event.data.entity_id == 'some_id' }}
Tweak the logic in the template as needed but that's the general approach I'd suggest.
Wow thank you mono for that fast answer! sounds good to me, i will try that. And to say that it is not triggered with some ID {{ trigger.event.data.entity_id != 'some_id' }}?
Exactly
mono how can i paste code in the chat like you did :)?
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://paste.ubuntu.com/ or https://www.hastebin.com/.
Like that ☝️
If you want the colours, you can also specify the language after the first backticks, then make sure to add a new line.
Thank you! The solution was:
{{ trigger.event.data.service_data.entity_id == 'cover.my_room_cover' }}
@neat pivot posted a code wall, it is moved here --> https://paste.ubuntu.com/p/ktth8PjcBk/
{{ trigger.event.data.service_data.entity_id == 'cover.my_room_cover' and is_state('switch.down_8','on') }} can't figure out the problem 🥲
Don't capitalise the to state, also it is 'state' not 'to'. https://paste.ubuntu.com/p/Xn3dSCcvvD/ and finally the conditions are AND by default, no need to specify that.
@neat pivot posted a code wall, it is moved here --> https://paste.ubuntu.com/p/KYHM9DF5DX/
Easy with the code walls 😉
@neat pivot Rule #6: 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://paste.ubuntu.com/.
sry 😓 did you see my last ubuntu paste?
I saw. I don't know the answer, so I'll let someone else help 😄
There are no templates in that. It's a question for #automations-archived
Can somone tell me if I am missing something obvious here?!
data:
master: >
{{ states('input_text.sonos_group_master') }}
entity_id: media_player.sonos_lounge
Results in the following:
Failed to call service sonos/join. Entity ID {{ states('input_text.sonos_group_master') }} is an invalid entity ID for dictionary value @ data['master']
In the template editor, {{ states('input_text.sonos_group_master') }} correctly shows a valid entity ID of another sonos media player.
Are you testing the service call in the Dev Tools?
@idle gyro ☝️
If so, templates don't work there
Until...2021.4 🎉
Lmao.....was that copy pasta Rob?
Nope, a celebratory response
So, should this work in
-> Services in 2021.4? It doesn't for me in the beta, while just the string does:
service: homeassistant.turn_on
data:
entity_id: {{ 'switch.fr_table_lamp' }}
Quotes?
i have a simple(ish) one time need. I just want a "days to go" counter to a big house move, so was thinking I could create a template sensor for that, but am having trouble getting it to surface in HA. It reports "Unavailable" on lovelace dash, but when tested in the devtools template section it reports back it's value correctly. Thoughts?
{{as_timestamp('2021-05-04T06:00:00+10:00') - as_timestamp(now()) }}
actually, I figured part out - the problem is me not reloading the template sensor from config ! 😐
Now I can't get the sensor to pass config check
it passes in file editor, but not server controls
sensors:
daystomove:
value_template: {{(as_timestamp('2021-05-04T06:00:00+10:00'))-(as_timestamp(now()))}}
friendly_name: 'Days until we move'
reports Error loading /config/configuration.yaml: invalid key: "OrderedDict([("(as_timestamp('2021-05-04T06:00:00+10:00'))-(as_timestamp(now()))", None)])" in "/config/configuration.yaml", line 82, column 0
hmm, broke it up and think I have it working now. All cool 🙂
How can I retrieve all (with filter)the attributes of a entity? I meant something like this - {{state_attr('sensor.bus_stop1','%_tracked_%')}} Where there are bunch of attributes which has tracked in their attr name
goodmorning from Germany! Following a template, first line returns True (not equal) but having the two logic check seperately seems to return the same string.
Please help me before I got mad!
{{(strptime(state_attr('calendar.feiertage_feiertage', 'start_time'), '%Y-%m-%d')) != (strptime((strptime(states('sensor.date'), '%Y-%m-%d') + timedelta(days=1)), '%Y-%m-%d'))}} {{ (strptime(state_attr('calendar.feiertage_feiertage', 'start_time'), '%Y-%m-%d')) }} {{ strptime(strptime(states('sensor.date'), '%Y-%m-%d') + timedelta(days=1), '%Y-%m-%d') }}
For test purposes It's the same with:
{{(strptime('2021-04-05 00:00:00', '%Y-%m-%d')) != (strptime((strptime(states('sensor.date'), '%Y-%m-%d') + timedelta(days=1)), '%Y-%m-%d'))}} {{(strptime('2021-04-05 00:00:00', '%Y-%m-%d')) }} {{strptime(strptime(states('sensor.date'), '%Y-%m-%d') + timedelta(days=1), '%Y-%m-%d') }}
So I found what is wrong but don't know why. state_attr('calendar.feiertage_feiertage', 'start_time') returns: 2021-04-05 00:00:00 and sensor.date returns 2021-04-04 that doesn't contain time.
If I remove time from the first one everything works as it should. But if it has the time the check isn't any more false
so here's what is working for me:
{{(strptime(state_attr('calendar.feiertage_feiertage', 'start_time'), '%Y-%m-%d 00:00:00')) != (strptime((strptime(states('sensor.date'), '%Y-%m-%d') + timedelta(days=1)), '%Y-%m-%d'))}} {{ (strptime(state_attr('calendar.feiertage_feiertage', 'start_time'), '%Y-%m-%d')) }} {{ strptime(strptime(states('sensor.date'), '%Y-%m-%d') + timedelta(days=1), '%Y-%m-%d') }}
sensor.date does what it says, returns a date only. If you want a sensor that returns a date and time then configure a date_time sensor here https://www.home-assistant.io/integrations/time_date/
It will considerably simplify your template.
Either that or use now() instead of sensor.date_time
I know that, but as I wrote this line {{ (strptime(state_attr('calendar.feiertage_feiertage', 'start_time'), '%Y-%m-%d')) }} returns exactly the same string as this line {{ strptime(strptime(states('sensor.date'), '%Y-%m-%d') + timedelta(days=1), '%Y-%m-%d') }} but when you check them with != you have true
that can't be used since it's a binary_sensor 😉
Yeah it can. Try this and see if it returns true/false {{ state_attr('calendar.feiertage_feiertage', 'start_time') == now() }} the only issue is that now() contains milliseconds and your calendar may not. Which is why {{ state_attr('calendar.feiertage_feiertage', 'start_time') == states('sensor.date_time') }} may be better.
The problem is I want only to get the date from the calendar start time and check if it is tomorrow. Forgive me if I am wrong but I think I've failed using now() in a binary_sensor template since it is in configuration.yaml (that would only check at the load of it and not on any changes of date). So neither of these suggestions could help me
or is it a more efficient way to get only the date from calendar (skipping time) and check it if it is tomorrow?
I want simply now if it is a workday tomorrow according to my "holidays" calendar
(checking also my "vacation", "illness" calendars 😛 )
Add 24 hours or 1 day to now using the timedelta and compare that to your start time
Only compare the date strings
I already mentioned that now() can't be used
Why
it is a template for a binary_sensor in configuration.yaml
Ok that changes nothing
have you used now() in configuration.yaml?
Yes you can use now anywhere in a value_template inside the sensor section
I think i did it and failed... but i can be wrong.
You are wrong... you did something else wrong and are correlating it to using now
Ok thank you for the info!
value_template: “{{ as_timestamp(now() + timedelta(days=1)) | timestamp_custom(....) in state_attr(‘entity_id’, ‘start_time’) }}”
You’ll have to replace .... with the format that’s in your start time for a date and change entity_id to your entity_id
On mobile so you may have to remove typos
For the format, %Y is year, %m is month and %d is day. So if the date in starttime is year-month-day, the format would be ‘%Y-%m-%d’
I will try it! thank you very much for your time 🙂
how can I drop the time and check only the date? the time is irrelevant and could cause problems if it isn't always 00:00:00 according to your template
The code checks if only the date is inside the timestamp so you dont have to drop it
that's lovely!
thank you a lot!
now i saw the "in"
it checks if it is in the string
very clever!
yeah
last question is it wrong to use or for multiple state_attr after in?
value_template: “{{ as_timestamp(now() + timedelta(days=1)) | timestamp_custom(....) in (state_attr(‘entity_id’, ‘start_time’) or state_attr(‘entity_id2’, ‘start_time’) or state_attr(‘entity_id3’, ‘start_time’)) }}”
Yes, it’s not correct. Set the date string to a variable and compare the variable in each starttime with ors between
beautiful! thanks!
I have a template sensor set up that calculates the difference between two sensor values. These to values only have one decimal, but the template sensor more often than not outputs values with like ten decimals (like .9999999999999999999991 or .000000000000000000000000003). How is this possible?
Without seeing your template, you're just asking people to guess.
I'm getting a yaml error (parsing a block mapping) when trying to use a sensor template in config, and I really can't tell why:
sensor:
- platform: template
sensors:
washer_door_lock:
Pretty sure I'm following the right syntax and spacing
Your snippet doesn't show a template... 🤔
the template's further down, and wasn't part of the error
The error will also likely tell you the position of the error. You need to give the full error message.
looks like it was maybe a badly pasted tab from someone else's snippet (which is weird considering i copied from their config file)
Quite likely. That message is saying your YAML is poorly formatted. But since you say it's nothing to do with the template, you want #integrations-archived
You can’t mix tabs and spaces
It didn't look like i was. Atom was showing spaces for everything, and it was copied direct from another config file 🤷♂️
Hmm, template doesn't seem to like the entity from zigbee, for example {{ states.binary_sensor.0x00124b0022ff6569_contact.last_changed }} returns TemplateSyntaxError: expected token 'end of print statement', got 'x00124b0022ff6569_contact' - i could change the entity id but out of curiosity wondering why it fails, works otherwise fine as a sensor and stuff?
Testing on Developer tools template tab, as per regular workflow i ensure there first the stuff works before i put it into configs..
seems like you have something else in the template dev tool that's causing that
this works fine for me: {{ states.binary_sensor.aarlo_motion_back_door.last_changed }}
hmm, let me clean it up, it works fine for me on "regularly" named binary sensor, not with those zigbee address-named
did you exclude them from recorder:?
it works fine for a selection of entities here, but I have no Zigbee stuff
nope, no exclusions of any kind, they are visible on logbook just fine and i am trying to get their last_changed timestamp (which is properly shown on the states-tab
hmm, maybe that naming is broken. I think that object names need to start with a letter
that's what the error message is complaining about - the leading '0'
Now that i started to think it, sounds plausible, however that's the very default after a device is added to zigbee, it only have address as a name and it works for HA but suppose it causes issues to some subfunctions
try using states['binary_sensor.0x00124b0022ff6569_contact'].last_changed
It’s the number
That seems to work, thanks. Timestamp is off by 3 hours, maybe by design (ie. gtm time) but that can be ignored for now.
Yeah so it seems, no problem with that, thanks. I've got some issues renaming the z2m provided devices but that's not for template
If manually configured add a unique_id
Added few door sensors to z2m, gave them friendly name (Frontdoor, Backdoor) in there but did not select the "Update Home Assistant entity ID" - results in devices named by friendly name (Frontdoor, Backdoor) from z2m but sensor names are crafted from ieee address . {{ state_attr('binary_sensor.0x00124b0022ff6569_contact', 'friendly_name') }} -> Backdoor contact
Thanks all for your assistance! Progress and learning, i'll move rest to the proper channel should i fail to fix the renaming
I have a hopefully simple question for someone to answer, if I have a template like this that grabs the current value of a sensor how do I grab the value that it was previously set to? {{states.sensor.plant_sensor_5_moisture.state }}
I have some humidity (moisture) sensors in my plants, i'm hoping to create a template to inform me of when the plants have been watered then take a timestamp. My thought was to compare the value of the previous state with the current to see if it increased. i.e the plant was at 10% humidity then jumped to 30% so it must have been watered, then save a timestamp.
this would typically be done through an integration that triggers on a state change, where you have access to the "from" and "to" states
what you're describing is an automation, not a template
an automation that uses a template, perhaps
Hmm OK, i'm hoping to find some similar example as this is a new concept to me.
you can review the example at the bottom here: https://www.home-assistant.io/docs/automation/templating/
sounds like you'd want a trigger that triggers on any state change for your sensor, a condition that checks the from and to states to see if they meet your criteria, and an action that does something when they do
Thanks @inner mesa, taking a look at this now.
Hi everyone waveslight_smile Trying to create an automation that triggers when current hour on the clock matches an integration's sensor attribute that annoyingly only outputs numeric state between 00-23
Any ideas on ways to go about this? Thanks!
*Sorry for the double post, wasn't quite sure where best to ask 🙂