#templates-archived
1 messages ยท Page 146 of 1
I mean, I think my sensors all have the word temperature in them
{{ states.sensor|selectattr('attributes.unit_of_measurement', 'eq', 'ยฐF')|map(attribute='entity_id')|list }}
works for me
thank you
the list includes one sensor I don't want - my phone battery temp. Can I just get rid of that sensor all together? I don't really ever care (at least for now)
you can disable the entity
right, thank you Rob C
ah, of course I have a calibration template for all my temp sensors so it won't work afterall. Will need to define the list the original way.
"calibration template"?
you can generate the list as long as there's something to match on
yes, I created a template sensor for each physical sensor with an offset so they all show same temp when in same place
just matched it to thermostat display temp since i can't change that
so I have sensor.sonoff_TH01_1_temperature and sensor.guest_bedroom_temp the latter being the calibrated temp
i don't think it's called a claibration template but it is a template for "calibration"
offset is prob a better word
And you can still create a list from them
is it posible to split the template config files in to 2, one template.yaml file and a dir list?
Configuration.yaml
template: !include templates.yaml
template split: !include_dir_list ./entities/templates
You can try it
looking to build an automation that fires is the outside temperature is below x
To do that, I'm thinking that I need to somehow grab the current outdoor temperature and turn it into a template sensor
not necessarily. why?
just being below a certain temperature isn't a singular time, so isn't a trigger
Let me recap - I'd like to have a binary sensor for is_below_freezing
that's just a template binary sensor
I'm trying to build an automation that tells me to turn on my roof heat cables if the temperature is below freezing
Right.
so I guess my question is - how do I get the current outdoor temperature in such situations, googling for such things just takes me to climate which is more to do with HVAC ...which is not really what I'm after
I DID find this: https://www.home-assistant.io/integrations/weather.template/
where are you getting it from?
uh, right now just the default which I think is....hold on
presumably you have the information somewhere in HA?
i just have the integration setup and it shows a pretty card in lovelace, I'm not actually doing anything with the data so I've never had to interact with it
Right, so I can get weather.home
and the temperature is an attribute?
do you want to start with a template binary_sensor for that?
yeah, probably.
or do you just want an automation that triggers when the temperature drops below 32?
or freezing
i want an automation that triggers when the temperature drops below freezing, but having a binary sensor to encapsulate that seemed like a neater solution than a magic number of "32" randomly in there
not necessarily - you'll have that number somewhere, and if you don't plan to use that template binary_sensor anywhere else, it's not that helpful
anyway
{{ state_attr('weather.home', 'temperature')|float < 32 }}
Gotcha, thanks
I mean - I was thinking having the ability to interrogate a sensor as to whether it is or is not freezing might be helpful but i dont know
๐
I should point out that Fahrenheit is not my chosen unit of measurement but hey ho
Now you're talking!
๐
Anyway, I use Fahrenheit because:
- I live in America
- My wife is American
- This means that all our thermostats etc. need to be in Fahrenheit
- Therefore, having HomeAssistant use the same units as the stuff it's controlling makes it less of a headache
but that does mean that "oh, 32 = freezing" isn't where my brain would typically go - so having a way to attach semantic meaning to that is nice ๐
oh and by the way - that thing I was doing earlier with scenes, automations and timers worked a treat so thanks!
I'm trying to convert from legacy to modern template sensors, but I can't figure out how to write my files. I have splitted my configuration so that I have one sensor per file, so one of my sensors is like
ยดยดยด
platform: template
air_conditioner_running:
friendly_name: "Varmepumpe kjรธrer"
value_template: "{{ states('sensor.power_air_conditioner') | float(0) > 10 }}"
ยดยดยด
How do I write this in the "modern configuration syntax"?
I have tried
platform: template
sensor:
- name: air_conditioner_running
state: "{{ states('sensor.power_air_conditioner') | float(0) > 10 }}"
But HA is complaining...
Invalid config for [sensor.template]: [sensor] is an invalid option for [sensor.template]. Check: sensor.template->sensor. (See ?, line ?).
The new modern template sensors don't fall under the sensor integration, but under the template integration.
So you can't place them in sensor.yaml.
You will have to place them directly in configuration.yaml, or create a template.yaml file and include that one.
But all of this is not a template question, but something for #integrations-archived ๐ So please continue there
Thanks, I just read that in the docs, I had missed it... I will try, and continue in integrations if I still don't get it ๐
Hi all, is there a way how to get current automation last_triggered value not knowing its entity id? Something like we can do with triggers? - trigger.entity_id
The reason I need this is, that am writing blueprint and I need to turn off the switch by variable time after the automation was triggered last time.
this is a usable state object for templates
so this.attributes.last_triggered should be my solution right?
yes
Awesome guys, appreciate your help, thank you!
But, it will not be the current trigger time, it will be the previous trigger
last_triggered will only be changed after the conditions are checked, and when they are True
yes, that's actually what I need. I bear in mind this. ๐
hello everyone, is it possible to have a sensor that makes me the list of calendar events?
With templates, you can do pretty much anything. A template that does what your asking wonโt be cookie cutter, youโll have to make it
Hi all, I am looking to do a template that looks to see if a value is between two numbers
{{ 10 < states('sensor.mysensor')|int < 99 }}
i an just looking for the syntax to combine them, JS example:
if (sensro >10 && sensor is > 2)
``state: >
{% if 10 < states('sensor.mysensor') | int < 99 %}
middle
{% elseif 100 < states('sensor.mysensor') | int < 299 %}
high
{% endif %}```
`
Like that?
should work. you can test that in
> templates
note that without an else you're going to get an empty return if it doesn't hit either of those paths
I got that, I was just concerned with the if - esleif
Is there a way to do string substitution in jinja? I have a door sensor who's states are on/off and I would like to substitute them with open/closed in my template. Thanks in advance.
You can, but if it is a binary_sensor you can change the device_class to door or window and it will show open or closed on your dashboard
It will also change the icon accordingly
@marble jackal many thanks Iโll look into that.
@marble jackal unfortunately the device_class route doesn't work for my needs, any idea how I would do it in a template script?
Device class translates it on the dashboard, not in the backend. How does this not work for your needs?
@mighty ledge I have a door(s) sensor automation which sends a notification on state change. message is {{ trigger.from_state.name }} is {{ trigger.to_state.state }}
I would like to substitute the on/off states with open/closed.
{{ trigger.from_state.name }} is {{ 'open' if trigger.to_state.state == 'on' else 'closed' }}
Will be even more simple in 2022.2
{{ trigger.to_state.state == 'on' | iif('open', 'closed') }}
That replaces the if/else
Ninja edit ๐
Niiice ๐
is there a way to get "b" returned from this? from_state: ['a', 'b', 'c'], to_state ['a', 'c'] basically a pattern to"get the item from the list that "dropped out" - a diff of sorts
yeah, it's nice, but not sure if its 'much' simpler.```
- service: >
script.alarm_arm_{{is_state('group.family','home')|iif('night','away')}}
script.alarm_arm_{{'night' if is_state('group.family','home') else 'away'}}
or even: value_template: > {{(value_json.state.daylight == True)|iif('on','off')}} {{'on' if value_json.state.daylight == True else 'off'}}. guess its more a matter of preference? Used to those ternaries in JS, a translation to Jinja might indeed be more straightforward now. nice indeed.
I'm running a shell_command and passing a parameter to it:
service: shell_command.test
data_template:
foo: '{{ states(''sensor.bedroom_illuminance'')|float * 20|int }}'
In the command I then just reference it as {{ foo }} as a param to the command I'm trying to run.
That template in dev tools shows as an int, however, inside the shell command it seems to be evaluating to a float because the command I'm passing to is erroring out saying something like 90.0 is not valid input. Do I need to convert it to an int with something like {{ foo|int }} again?
Kinda seems to be the case, but that almost seems like a bug? I'm specifying the number to be an int in my template and then using that value in the command and it seems to be a float there
You're casting 20 as an int
Hi guys
if you have a sensor made up of, let's say, 3 entities, is it possible to know which entity triggered the last change?
No
You could test them all, I guess. Put them all in the trigger and test the from_state against the to_state. But that's brute force
Or just look at trigger.entity_id. Was making it too hard
I could add an attribute to the sensor with the entity id that has the highest timestamp?
last changed timestamp
Just do what I suggested. Add them all to the trigger and look at trigger.entity_id
How can I sum the sensor which gives daily power production sensor to make a total energy sensor? I could have used utility sensor but the issue is that this particular daily sensor resets at mid night. Any ideas
Statistics or Integration/Riemann Sum
the issue that i find with statistic is the sample size which can be infinity for this case. I dont know how riemann would work for this. Could do explain?
It integrates power over time to make energy
yes but how can I do with my thing
I don't think a 'daily power sensor' makes sense, though
Did you read the doc page?
Anyway, maybe it will help, maybe not. Just a thought
Yes so why is it showing up as a float?
Ah I see. I'd have to wrap that basically in parens and then cast it
Hi all,
in tasmota you can adjust the KwH reading by a command in terminal "EnergyReset<x>"
i have a shelly installed with original firmware but require the KwH reading to adjust to match my energy supply meter.
i did manage to in developer tools/template place this code in which netted a result of 407.358
{{ states('sensor.energy_company_power_kwh' ) }}
i would like to adjust this reading by 1200 to display a reading of 1607.358
{{ states('sensor.energy_company_power_kwh' ) | float(default=0) + 1200 }} will work to get what you want
Be aware that this will be shortly just 1200 at startup, because the sensor won't be available, and the float filter will then default to 0. As soon as the sensor is loaded it will show the correct result.
Hi all,
why would,
state: "{{ (states ('binary_sensor.x')) or (states ('binary_sensor.y')) }}"
not evaluate to true if either binary sensors x or y is true? Am i missing something?
thanks, I'll give it a go
i have a timezone set in HA, and i am running HA in HA blue.
done the code as @marble jackal worked great, {{ states('sensor.energy_company_power_kwh' ) | float(default=0) + 1200 }} but I'm struggling to add it to my code below is part of my configuration.yaml
sensor 1:
- platform: integration
source: sensor.suppliers_energy_power
name: 'Energy Company Power kWH'
unit_prefix: k
round: 3
utility_meter:
daily_energy:
name: "OVO Energy Daily Kwh"
source: sensor.energy_company_power_kwh
You need to create a template sensor https://www.home-assistant.io/integrations/template/
I'll give it a try
Because states are strings (and "on" or "off" for binary sensors). This will work
{{ is_state('binary_sensor.x', 'on') or is_state('binary_sensor.y', 'on') }}
Thank you; that makes sense.
thanks, I searched the forum, but I only found templates that give me back the total of events
right, that's why I said you'll have to make the template
how do i add which sensor has been opened in the notify.notify ?
https://pastebin.ubuntu.com/p/JdhBqJgFF4/
{id} ?
Presumably with this, but you'd need to look at the event. Most things like this are easier with state triggers
as you added trigger id's you can use:
title: "{{ trigger.id }} al langere tijd open !"
Indeed. Forgot that could just be a word that you could use directly
It's possible to create a custom sensor and add them to a already existing device?
I like to extend device from a integration with aggregated (interpretations of the device data.
No, you can not add template sensors to a device
hi, I have a rest switch that was on when the laptop suddenly restarted
and now the HA won't see the switch entity at all
tried resetting rest services, tried restarting HA, even restarting the laptop again, but it won't appear. Checked config, the entry is still there but it seems it just won't load it
troubleshooting 101: Check logs first.
No route to resource/endpoint: http://192.168.100.16:5000/setSta
did the IP address change?
can you access that from the browser on your computer?
basically, this is a networking issue as HA doesn't see the endpoint
I cant but Im not certain I could before either. From the browser I mean.
I can however trigger the switch from the phone app of the device
typically rest endpoints just contain Json
so it clearly connects
yes but that's your phone
is your phone on your network or on the cell network?
is your ha using the same network as your phone?
i'm getting an empty value where a string is expected with this Template variable warning: 'mappingproxy object' has no attribute 'player_list' when rendering '{{ trigger.to_state.attributes.player_list|reject("in", trigger.from_state.attributes.player_list|default([]))|list|first }} online' i know it's a lot to unpack, but when the to_state attribute is "['player_one']" and the from state attribute is absent, the from state should default() to an empty list, and the reject filter should give me ['player_one']|first --> 'player_one' -- instead i'm getting '' and a the warning
and does the phone actually use rest to access the sensor or does it have a built in api
either way, look towards your network
not certain on that. It's a plug with a dedicated app
tenda
thing is, I pinged it from the HA terminal
so I know for a fact the server can reach it
yes, you can ping it all day, but can it access that port?
good point
pinging != checking connectivity on the port 5000
The warning will still occur even though the default is happening
it's impossible to ping a port
anything that says otherwise is "faking it out"
ok. it's resulting in a blank string though (or object than can't be cast to a string)
which is odd because it's working as expected in the template debugger:
{% set fromstate = {} %}
{% set tostate = {"value": ['c']} %}
{{ tostate.value|reject("in",
fromstate.value|default([]))|list|first }}
results in "c"
well no matter what, first will error on an empty list
Personally, I'd refactor your code to check to see if the attribute exists
it's a dictionary, so you could also just use get
ah. i can do that, i thought the default filter protected me though
and get supports a default?
I reset the switch, reconnected it and now HA sees it too, thanks for your assistance!
dont know why I didnt start with that, in retrospect
you should try to see if you can connect to the endpoint in a browser
just for shits and giggles
first() should always work because it's operating on the reject diff, which should always have at least 1 item in the list
not in the instance that 2 state is empty
to_state*
ah sorry, to_state will never be empty at this point because i've conditioned that out in prior code.
figured it out - get helped for sure (Thanks petro), but i also asked for "player_list" instead of "players_list" (typo) which made the to_state HAVE an empty list, haha
Hello. Hoping someone can point me in the right direction. I have an automation already configured in automations.yaml. I'm wanting to add a condition to only run it if the day is a specific day of the year. Example if the date is "01/01" (Regardless of year). How would I go about doing this?
{{ now().day ~ now().month }}
so...{{ now().day == whateverday and now().month == whatevermonth }}
hey all. I'm trying to figure out how to output a timestamp and thought someone might have a relatively easy way to do this.
Currently an automation that is set to run based on a condition that occurs every 2 weeks, based on the week number.
{{(as_timestamp(now())|timestamp_custom ('%U') | int % 4) == 2}} which would output a true/false.
I'm trying to figure out how to output a timestamp now based on the week number. For instance, every Saturday of a certain week number of the year. Not sure why I'm coming up short.....
@inner mesa Thanks! How would I enter that as a condition though? I'm new, so I apologize ๐ฆ I assume that would be the data, but what would the condition be?
a template condition
condition: template
value_template: "{{ now().day == whateverday and now().month == whatevermonth }}"
Ok. So in my Configuration.yaml, I need to add the template correct?
in the automation you said you had
Oh! Ok. Sorry, I was thinking I had to create the template in configuration.yaml first. But I guess I not ๐ Sorry!
np
see the second example for a shorthand version: https://www.home-assistant.io/docs/automation/condition/
you could use that too
One more question.. Would I put in the whateverday and whatevermonth value in quotes or no because it's an int?
Perfect! That's what I was thinking ๐ Thanks again!!!
Ok, one more queston.. If I have multiple conditions and I want it on everyday BUT "01/01"? I tried != on both month and day, but this didn't work because it is equal to 1 for the month...
๐ Ok. SO like this:
value_template: "{{ not(now().day == whateverday and now().month == whatevermonth) }}"
Yes, but with a space after not
Perfect! THANKS SO MUCH!!!
Is there an easy way to condition a time between say 8pm and 8am the following day without doing some sort of datetime witchcraft?
I thought of another solution could have an input boolean with an automation that turns it on/off at a certain time which bypasses this but seems like extra hassle to get working
Yes, because time conditions don't work the same way sunset/sunrise conditions do:
Time condition windows can span across the midnight threshold if both after and before keys are used. In the example above, the condition window is from 3pm to 2am.
im messing with a template that i found elsewhere on the internet and i think i understand except for 1 part
value_template: >-
{% if states.calendar.columbus_blue_jackets.attributes.start_time %}
{{((as_timestamp(states.calendar.columbus_blue_jackets.attributes.start_time) - as_timestamp(now())) / 60) | int }}
{%- else -%}
0
{%- endif %}
what is the {% if states.calendar.columbus_blue_jackets.attributes.start_time %} of this sensor really doing??
it's a wordy way of getting the value of the start_time attribute
the right way to do it is state_attr('calendar.columbus_blue_jackets', 'start_time')
I don't know why people do it the other way. I think they're all copying random stuff from forums and reddit
it's the same thing
or should i do {% state_attr('calendar.columbus_blue_jackets', 'start_time') %}
that probably won't return a boolean, so wouldn't make sense
oh, I guess it's checking if it's blank?
gotcha. i dont understand the {% portion as of yet lol
yeah because it can be blank if nothing scheduled
so then it just shows 0
I wouldn't count on that working reliably, but if it does, it could be rewritten like this:
{{ ((as_timestamp(states.calendar.columbus_blue_jackets.attributes.start_time) - as_timestamp(now())) / 60) | int if state_attr('calendar.columbus_blue_jackets', 'start_time') else 0 }}
but the point is that the test needs to return a boolean
i mean that template in developer seems to return the same value as mine currently
i guess i dont understand what the if is doing
it seems to me this is all you would really need?
{{ ((as_timestamp(states.calendar.columbus_blue_jackets.attributes.start_time) - as_timestamp(now())) / 60) | int }}
that probably won't give you 0 if the start_time attribute is blank
it'll more likely cause as_timestamp() to fail and maybe giving a warning, and then fail to do the subtraction
im going to try it with a calendar sensor that doesnt have a scheduled game
better to guard against unexpected values than to accept and deal with random results
the value of as_timestamp("") (a blank string) could change at any time because it doesn't make sense
yeah when i did {{ states.calendar.michigan_wolverines }} theres no start time attribute
because nothings scheduled
so when i do {{ ((as_timestamp(states.calendar.michigan_wolverines.attributes.start_time) - as_timestamp(now())) / 60) | int }} i get a TypeError: unsupported operand type(s) for -: 'NoneType' and 'float' which is what i think you were referring to
that wasn't a valid test
I guess if you dig around the state object. But the easier way to do it is to look at the attributes in
-> States
Yes, exactly
yeah so {{ ((as_timestamp(states.calendar.michigan_wolverines.attributes.start_time) - as_timestamp(now())) / 60) | int if state_attr('calendar.michigan_wolverines', 'start_time') else 0 }} makes it return a 0 like you said
I know some stuff ๐
im trying to learn it
but yes you do lol
i hate just copying shit. i wanna know why lol
that is a good strategy
I was just copying your initial example above, and the better way to do that is:
{{ ((as_timestamp(state_attr('calendar.michigan_wolverines', 'start_time')) - as_timestamp(now())) / 60) | int if state_attr('calendar.michigan_wolverines', 'start_time') else 0 }}
yeah i changed it to that. i was just trying to understand why the if state_attr part was needed
see the warning box: https://www.home-assistant.io/docs/configuration/templating/#states
cool beans.
alright i got another one for you then.
i made a sensor template and added this to my config.yaml
{{ state_attr('calendar.columbus_blue_jackets' , 'start_time') }}
and it returns the time correctly but in a 24hr format.
this as_timestamp(states('sensor.time_of_next_bluejackets_game')) | timestamp_custom('%I:%M %p') correctly converted it to a 12 hour format but im confused at how to put it toghether now lol
hmm might of figured it out.
change the config.yaml to
{{ as_timestamp(state_attr('calendar.columbus_blue_jackets' , 'start_time')) | timestamp_custom('%I:%M %p') }}
hmm that gave me the correct time now but lost the date
got it. i didnt know what the variables were for it but i guess its %b/%d/%Y
there's a link in the link I posted earlier:
Supports the standard Python time formatting options.
I looked through that template page and didnโt see it but thereโs a bunch of information on that page lol
Looking through the documentation, I see that Templates says to use ```template:
- sensor:
etc....```
and that
- platform: template
etc....```
is legacy/deprecated/ not recommended
But in History Stats, the config example is in the legacy format of
```sensor:
-platform: history_stats```
Is there a "modern" version of the history stats sensor config, or is the legacy-looking version the modern?
no, templates were just pulled out to their own section
great, thanks
@hollow girder posted a code wall, it is moved here --> https://hastebin.com/abuvunotes
I can call this script with action: true or false... but if I use on or off it converts to string! Can I make any check that on or off are assumed as true and false in the script?
because on/yes/true should all map to true
I did {% if action|string|lower == 'true' or action|string|lower == 'on' %} but this is very ugly... any alternative?
when you call it, don't wrap on or off in quotes. That converts on or off to a string.
something: on # This will resolve True
something: off # This will resolve False
something: 'on' # This will resolve 'on'
something: 'off' # This will resolve 'off'
Umm, so I'm trying to create a template from my philips hue motion sensor to have a virtual motion sensor that shows if there has been motion within 5 minutes. Basically I was thinking of just having a template sensor mirror the occupancy that I get from hue sensor and add a delay_off to handle the 5 minute thing. I'm not getting it working and I think I may have misunderstood something on how the HA works.
I have this in my configuration.yaml, but the sensor it produces just says "Unavailable"
template:
- binary_sensor:
- name: "Olkkari Liike"
state: >
'{{ state(binary_sensor.liike_olkkari_occupancy) }}'
unique_id: template_olkkari_motion
device_class: motion
delay_off:
minutes: 5
What am I fumbling here?
thats what i did... but when I go and see the script debug, the on is 'on'
post the service call that you used and show the trace for that service call
you don't have quotes around your entity_id, and you have quotes around your multiline template. Check out the pins to distinguish between jinja and yaml.
ok, give me a second
@hollow girder posted a code wall, it is moved here --> https://hastebin.com/exepipaviz
this is the service... Now I have it with the if like that because I need to have this working..
no this is the script... the problem is in the script
yes... the caller on the develop test
Thanks, tried fixing:
template:
- binary_sensor:
- name: "Olkkari Liike"
state: "{{ state('binary_sensor.liike_olkkari_occupancy') }}"
unique_id: template_olkkari_motion
device_class: motion
delay_off:
minutes: 5
but it's still Unavailable after first becoming clear on boot, then changing
I need to change the script to make the problem... the if that I have is correcting the bug
i changed to
title: >
{% if action == true %}
turn_on
{% else %}
turn_off
{% endif %}
Oh, states( not state(
you don't need that, just if action
now I'll call it with ON
service: script.android_bluetooth
data:
target: diogo
action: on
that's identical to what you had before
@hollow girder posted a code wall, it is moved here --> https://hastebin.com/ojikatohef
the result... it assumed the else...
if I do just if action it allways does on... because Strinf(on) is assumed as exists
dude, that's not your problem.
yaml no matter what will take on and translate it to true
and off will translate to false
I know... but it's not doing that translations... as least not here
wrapping in quotes will keep it a string. You're doing something else, possibly the fact that your variables match your incoming information
incoming variables cannot be overwritten by variables in your variable section
i'm doing the call without the '
also, you should use variables to actually see what's coming through
can't I use the variables to set defaults if nothis is passed?
ex:
alias: "Android Bluetooth"
fields:
target:
description: Target Name
example: <<name>>
action:
description: Action on Bluetooth
example: on
variables:
target_result: "{{ target | default("") }}"
action_result: "{{ action | default(True) }}"
sequence:
- service: script.android_message_relay
data:
target: "{{ target_result|lower }}"
message: command_bluetooth
title: turn_o{{ 'n' if action_result else 'ff' }}
then use the variables section to see what's actually being supplied to the script, and you'll see the output as well because you're providing it to your internal variables.
I call with on and works, because action_result exists, if I call it with off it does the on also... same problem.... It's not converting off to false.. instead is passing off as sting... making the it trigger, and not the else
@hollow girder posted a code wall, it is moved here --> https://hastebin.com/nurapoxuya
look at action result
and this was the call
service: script.android_bluetooth
data:
target: diogo
action: off
I'm only doing this tests in the service test tab... can it be that? a "problem/bug" in the service tester tab?
I'll create a automation to test it out
I have no idea if the service tester properly validates the yaml
that is the problem..
All that is done in the UI is convrted to string
so it converted to 'on' in the UI... and off to 'off'
also if I do a automation on the UI I can't use the on/off...
I tried to do a automation in the yaml with off and it worked... the same automation created in the UI is converted to 'off' and gives the problem...
so the problem is in the UI...
don't know if this is a bug or not... but made me walk in circles for some time and wast my time and yours...
tks @mighty ledge
also if I create a automation with the service call with off... and I save it... when I go back in, the off is converted to 'off'
Hi everyone, this is my first second post here. Iโve been looking for answers on the forum, ha documentation, YouTubeโฆ but I feel like I must be missing a core concept, as Iโm not finding what I am looking for.
My goal is to have a record of every time my basement sump pump turns on, and for how long it was on each time. My basement sump pump is connected to a Sonoff S31 with power monitoring. When the sump pump turns on, it uses about 300W to run the pump and turns off when there is no more water in the sump basin. I want to use the power reading from the S31 as the trigger for my automation.
I used the Dishwasher example here in the HA docs to create the binary sensor template in my extended configuration.yaml: https://www.home-assistant.io/integrations/template/
My code now: https://www.codepile.net/pile/8ZOwe7ZE
This example appears to have logic built in, but I didnโt have any luck using it. I'd like help with fixing the logic, and or a review of the binary sensor I created to ensure that I'm barking up the right tree. Any guidance would be greatly appreciated in how I can accomplish my goal.
{{ states('sensor.s31_03_sump_pump_energy_power')|float > 0 }}
``` that's all you need
You can test in
-> Templates
Ah okay, I see what you mean. I put that code into the Dev Tools > Templates and I can see that it is currently reading false (as the pump is not running)
So I just need to clean up that line, ok
I'll give that a shot, thank you ๐
That seems to have worked. Thanks again!
All bets are off with the automation editor. Same goes for the service tester if you aren't using it in yaml mode. Chances are, it'll adjust things too if it's in yaml mode as it probably uses the same code as the automation editor. At your skill level, you should just be using yaml anyways.
Tks for the help. I only use yaml in the vscode. I was testing the scripts before creating the automation, and noticed this! Tks for all your help and time
@halcyon condor posted a code wall, it is moved here --> https://hastebin.com/qepeqikize
im trying to read a rest api (json) and use value_template
but it gives Unknown and an error in the logs:
Template variable error: 'value_json' is undefined when rendering '{{ value_json.data.0.status.online }}'
however, if i save part of the json output in Developer Tools -> Template, then this template just works
what can i do / try?
configuration here: https://hastebin.com/qepeqikize
Your value is most likely not json
According to https://jsonlint.com/ as well..
I am getting template warnings on my logs regularly. Does anyone know how I find out where it's coming from?
Template variable warning: 'dict object' has no attribute 'cluster_id' when rendering '{{ trigger.event.data.cluster_id }}'
Template variable warning: 'dict object' has no attribute 'endpoint_id' when rendering '{{ trigger.event.data.endpoint_id }}'
Template variable warning: 'dict object' has no attribute 'args' when rendering '{{ trigger.event.data.args }}'```
Probably and automation, template sensor or blueprint which uses these templates. ๐
I will take a look but do you know what it is saying? What should i look for?
@granite steppe posted a code wall, it is moved here --> https://hastebin.com/hurecunuru
You should look for these templates which are throwing these warnings. So eg {{ trigger.event.data.command }}
These are templates which are used on a event trigger, and then taking some data out of that event.
If there is no event trigger (for example if you trigger it manually, or by another trigger type) it can not find the data, and will throw an warning
Thanks. i dont think i am using any templates in automations. The only was are in the config file - the one above (https://hastebin.com/hurecunuru) and
sensors:
robovac_battery:
friendly_name: "Robovac Battery"
unique_id: "robovac_battery"
unit_of_measurement: '%'
value_template: "{{ state_attr('vacuum.robovac', 'battery_level') }}"
Somewhere this template is used, otherwise it won't appear in your logs ๐
Its annoying it doesn't tell me where
So i am looking for a trigger thats using event data? Sorry, i don't understand that ^^^
is this an event trigger?
- event: start
platform: homeassistant
Here's my automations... https://pastebin.com/bnt9aUcm
Trying to figure out how to create a new sensor using only a part of an attribute from another sensor.
I am able to create the new sensor and have it pull the attribute I want but I am struggling to workout how to have it only pull the part that I want.
This is the attribute data that my sensor has but I only want the time and not the date
start_time: 2022-01-13 14:15:00
Here what I have for my sensor so far
tottenham_event_day_start:
friendly_name: "tottenham event start"
value_template: "{{ state_attr('calendar.tottenham_hotspur_fc', 'start_time') }}"
There is probably a way better way of doing this that all you wizards use
Thanks
Then something else is wrong, Are you sure that error is produced when you reload the rest sensor or restart HA?
Yeah i tried a curl command and i get some warning from the api. So curl gives a different response (html) than the same url in browser (json)
Warning about misuse or something
Maybe its a headers thing?
No clue without seeing the errors, and I would have to google the error anyways
I mean how the browser gives correct output and curl a different output. But its not ha related then :)
@median mason posted a code wall, it is moved here --> https://hastebin.com/veloqaqace
I have a sensor that outputs my nuc's uptime as follows:
sensor.intel_nuc5i3_system_uptime >> 01:16:43:28
I am calculating the uptime as a time like this
{% set d, h, m, s = states('sensor.intel_nuc5i3_system_uptime').split(':') | map('int') %}
{{ as_datetime(states('sensor.date_time_iso')) - timedelta(days=d, hours=h, minutes=m, seconds=s)}}
output to template editor: 2022-01-11 20:12:31
But I get an error for this and get the value 'unknown'
sensor.template_intel_nuc5i3_uptime rendered timestamp without timezone: 2022-01-11 20:12:31
How can I add a timezone to my template?
Just use now(), it is timezone aware
{% set d, h, m, s = ('01:16:43:28').split(':') | map('int') %}
{{ now() - timedelta(days=d, hours=h, minutes=m, seconds=s) }}
Or utcnow() if you want the utc time.
coming from #automations-archived message please have a look if/why my template in https://community.home-assistant.io/t/automation-wont-trigger-conditions-maybe-wrong/357288/13 would be reason for the condition not the pass?
I'm using a template to gather all problematic states of all plants. How can I remove a specific state like battery from the loop?
{%- for plant_id in state_attr('group.all_plants','entity_id') -%}
{%- if is_state(plant_id, 'problem') -%}
{%- set problems.plants = problems.plants ~ state_attr(plant_id, 'friendly_name') ~ ': ' ~ state_attr(plant_id, 'problem') ~ ', ' -%}
{%- endif -%}
{%- endfor -%}
You don't need a for loop for this
Oh wait, what do you expect as output? A dictionary?
@heady cedar posted a code wall, it is moved here --> https://hastebin.com/owiximaxip
Pff, 18 lines ๐
That does not answer my question. Could you give me an example of how you would imagine the result of your template as shown above
Should string which looks like this: Petunia: Too much water, Roses: Not red enough, Violets: Need water
And you don't want to include those plants with battery in the the problem attribute
fixed it by passing headers, user-agent
correct! Right now this is the value Aloe: battery unavailable, conductivity low, Bogenhanf: moisture low, battery unavailable, conductivity low, Gรผnther: battery unavailable
i hate it but:
{% for thing in expand('group.living_room') %}
{% set ns.things = ns.things + ["%s: %s"|format(thing.name, thing.state)] %}
{% endfor %}
{{ ', '.join(ns.things) }}```
oh, adding extra filters, sec
I was just about to post this:
{% set plants = state_attr('group.all_plants','entity_id') %}
{% set problem_plants = expand(plants) | selectattr('state', 'eq', 'problem') | rejectattr('attributes.problem', 'search', 'battery') | map(attribute='entity_id') | list %}
{% set ns = namespace(info=[]) %}
{% for entity in expand(problem_plants) %}
{% set ns.info = ns.info + [ entity.attributes.friendly_name ~ ': ' ~ entity.attributes.problem ]
%}
{% endfor %}
{{ ns.info | join(', ') }}
{% set ns = namespace(things = []) %}
{% for thing in things %}
{% set ns.things = ns.things + ["%s: %s"|format(thing.name, thing.state)] %}
{% endfor %}
{{ ', '.join(ns.things) }}```
thanks ๐
just keep messing with your filter on things in my example
But I now see that that won't work though
expand() is a wonderful thing
you should split the problems mentions in problem, then remove the battery ones, and then join them again
you can just expand plants
without your state_attr
expand explodes groups (Not light groups)
Well, you could try this @heady cedar
{% set problem_plants = expand('group.all_plants') | selectattr('state', 'eq', 'problem') | map(attribute='entity_id') | list %}
{% set ns = namespace(info=[]) %}
{% for entity in expand(problem_plants) %}
{% set ns.info = ns.info + [ entity.attributes.friendly_name ~ ': ' ~ entity.attributes.problem.split(', ') | reject('search', 'battery') | join(', ') ]
%}
{% endfor %}
{{ ns.info | join(', ') }}
And thanks @mighty ledge!
That looks nearly perfect but is now it shows also plants where "battery" is the only problem :/
Aloe: conductivity low, Bogenhanf: moisture low, conductivity low, Gรผnther:
Yes, I just thought of that myself
@heady cedar This should work
{% set problem_plants = expand('group.all_plants') | selectattr('state', 'eq', 'problem') | map(attribute='entity_id') | list %}
{% set ns = namespace(info=[]) %}
{% for entity in expand(problem_plants) %}
{% set problems = entity.attributes.problem.split(', ') | reject('search', 'battery') | list %}
{% if problems %}
{% set ns.info = ns.info + [ entity.attributes.friendly_name ~ ': ' ~ problems | join(', ') ] %}
{% endif %}
{% endfor %}
{{ ns.info | join(', ') }}
Corrected to better version
so i fyou want a more memory efficient one...
Awesome! Thank you so much!
{% set ns = namespace(info=[]) %}
{% for entity in expand('group.all_plants') | selectattr('state', 'eq', 'problem') %}
{% set problems = entity.attributes.problem.split(', ') | reject('search', 'battery') | list %}
{% if problems %}
{% set ns.info = ns.info + [ entity.attributes.friendly_name ~ ': ' ~ problems | join(', ') ] %}
{% endif %}
{% endfor %}
{{ ns.info | join(', ') }}
Ah, yes, I see what I'm doing wrong, or at least inefficient
for loops work on generators
if you cast things to list, it forces the generator to resolve everything
where a for loop will use the generator properly, especially if you are filtering things
Thanks again ๐
np
It always feels good when the problems of one are not solved in 10 seconds ๐
Thanks to all! ๐
sorry if this is the wrong thread...Please can anyone help me with my cover/sensor template. The yaml that i have added now lets me to control my mqtt shade from lovelace where i couldnt before and i had to add a template sensor so that i could view the position in lovelace too. I know it is missing something though because i cant set the shade to a specific position in node red and when the shade is fully open or shut it doesn't display "open" or "closed". As i am new to coding i can't work out what im missing, probably the value_template has something to do with it but atm i hav commented it out because it doesn't seem to do anything as it currently is written. see here https://pastebin.com/DdEP8ciK
Well, let me thank you first for using a code sharing site. But this code is completely messed up, and if it would be like this in your config you would not have a cover or sensor at all.
Could you try again using on of these sites:
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://hastebin.com/ (sometimes may not allow you to save)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
But as far as I can see, it seems and #integrations-archived topic, so share your correct code there ๐
thanks, I'll repost there and use one of your sugested code share sites ๐
@small rock posted a code wall, it is moved here --> https://hastebin.com/uruxohobeq
I can't see what I'm missing with:
https://hastebin.com/uruxohobeq
[state_class] is an invalid option for [sensor.template]. Check: sensor.template->sensors->current_energy->state_class. (See ?, line ?). but in the docs 'https://www.home-assistant.io/integrations/template/' it's optional
Appreciate the help!
You've mixed up the old and new template formats
state_class is only supported in the new format
Where could I find the new template formats?
In the docs you pointed to
I figured it out
Not that what you posted is what's described in the section at the end:
Legacy Sensor configuration format
instead of platform I need to use template:
Oh, I think i have found it. The only blueprint i use is that https://community.home-assistant.io/t/zha-ikea-tradfri-shortcut-button-debounced/265921 and this seems to include those strings
Seems to be the culprit indeed.
@obsidian lintel posted a code wall, it is moved here --> https://hastebin.com/vakagenadi
Was trying to make a lock toggle
Doesnt work
action: call-service
service: |
[[[
return (lock.digital_door_lock.state === 'locked') ? 'lock.unlock' : 'lock.lock';
]]]
service_data:
entity_id: lock.digital_door_lock
Anyone can help?
you aren't accessing the state object properly
also, your entity for the button card is what you're using, so just use entity.state instead
yah, makes sense, I haven't touched that stuff in that long
I'm trying to write JSON to a file using the file notification integration. Shouldn't something like this work?
server: notify.writefile
data:
message: >-
{{ {"key": "{{states('sensor.blah')}}",
"key2": "value"}|to_json }}
It only works if I add a char or something before or after the double curly brackets. but obviously that produces invalid json
remove the inside {{ }}
I mentioned this in #automations-archived , but server: should be service:
also, that
and this works fine for a persistent_message:
also remove the " " you have around the inside {{ }}
set_test:
sequence:
service: persistent_notification.create
data:
message: >-
{ "key": "{{ states('weather.wf_udp') }}", "key2": "value" }
{ "key": "cloudy", "key2": "value" }
message needs to be a string
Yeah the server thing is my bad, typing on the phone, probs autocorrect.
I tried without the double curly brackets and |to_json, same thing. I get a "template value should be a string for dictionary" error
hey. i got a silly problem. I have a bunch of humidity and temperature sensors that has been added automatically by mqtt (using espresense). I want to round(1) the values without creating a new template sensor. I tried to customize the sensor with value_template but it doesn't work. any suggestions?
manually configure them instead of using discovery
Here's the exact yaml I am trying: https://paste.debian.net/plainh/3af09cd3
that's not going to work
{ trigger template use
your whole template needs to return the string
{{ }} on the outside, that's the only way.
you can attempt to do it the other way, but then you have to use either {% raw %} {%endraw %} or escape them
๐ฆ ok
So I tried that as well, with and without |to_json, same error. That only worked when I added a random char outside of the double curlies
I'm guessing you did something wrong when you had it inside the {{ }}
post that version please.
Works: https://paste.debian.net/plainh/73f9a591
Does not work: https://paste.debian.net/plainh/b33472e0
both of those are wrong though
you have templates in templates
that's what I said earlier when I said remove the inside "" and {{}}
{{ {"current_condition": [{"temp_C": state_attr('weather.home_hourly', 'temperature'),
"weatherCode": "320"}], "weather": [{"mintempC": states_attr('weather.home','forecast')[0].templow,
"maxtempC": states_attr('weather.home','forecast')[0].temperature}],
"nearest_area": [{"areaName": [{"value": "XXXX"}],"country": [{"value": "XX"}]}]} |tojson }}
However that still might get resolved as an object in message
Yeah same thing
then you have to provide a string unfortunately
what are you trying to do?
I know this is your current hurdle, but what's the overall goal
I'm trying to write a JSON file in /config/www with the weather data to grab from a Sonoff NSPanel flashed with tasmota
(I agree, end goal is always useful :)
use curl to write to a file with a command line script
Curling from where?
from the command line
Yes but what url?
What url would I curl? I need to build this JSON file from home assistant states
Polling weather APIs with straight curl is non trivial (API tokens etc), while I already have all this data at my disposal
just the path to the file, it doesn't have to be a url
But I need to create this file, that's the problem I have
that should create the file
he wants the sonoff panel to grab the file (with curl)
Yes, I need home assistant to create a JSON file in /config/www, and subsequently the NSPanel will curl that file to obtain currently weather data.
yes, and you can create a file with curl, can you not?
No?... Curl is an http/ftp client
oh, you mean he should curl the api for the state and put the output into a file? would work ofc
-o outputs though
But like I said, querying weather APIs is non trivial (API tokens are all) while there's a perfectly working and maintained integration that does that already
It's been like 5 years since I've needed to curl anything, so I could be wrong
I'm just trying to get it so you can create the file
you can use command_line to run ANY command
You can have curl output the result of an http call to a file of course, but I don't have a url to query
that will create a file
curl your homeassistant api
will get you the state and you can format it how you want
essentially the same as your notify with template
Seems so convoluted when a simple template should just work. Works fine in the dev tool template thingy
you have restrictions imposed by the method you are using
your output must be a string
that's it
you can't use what you're trying to use
you're welcome to beat that dead horse, but I doubt it will be fruitful
no matter what, that template will resolve to an object if you're trying to write an object and the validation doesn't like that
so you have to get around that validation by enforcing that it's a string, (you already did that with your X before the output)
or use somehting else to output the same template
which you can do with command_line
does that make sense now?
so, you're outputting the same shit, jsut a different method
That was helpful thanks. Still not working though because shell_command refuses to have a : in it. Using > works as far as the config is concerned but the resulting service doesn't do anything :/
Ended up writing a bash script that formats the JSON and writes the file and I call that with the state templates as parameters. I know have my tasmotized NSPanel reporting the weather from home assistant data ๐
I just had an epiphany
I know it's a few hours late... but this would work with your file method...
Epiphany was last week... ๐คช
gimme a sec to write it out
Sure :)
service: notify.write_weather_hourly
data: >
{% set out = {'current_condition': [{'temp_C': state_attr('weather.home_hourly', 'temperature'),'weatherCode': '320'}], 'weather': [{'mintempC': states_attr('weather.home','forecast')[0].templow,
'maxtempC': states_attr('weather.home','forecast')[0].temperature}],
'nearest_area': [{'areaName': [{'value': 'XXXX'}],'country': [{'value': 'XX'}]}] | tojson %}
{{ {'message':out} }}
that get's around the validation on message
hello friends. I have a question. I have an event data here and would like to know if someone could help me to make a trigger
@olive moth posted a code wall, it is moved here --> https://hastebin.com/kebisucaqa
In fact I need "CardNo": "879076c8", as a trigger. This card number is my rfid from my doorbell. I have 3 badgesso this "CardNo": "879076c8", will change for each badge
now my question is: how to create a template trigger with this event data...
Evening Guys and Girls, could someone help me convert this to the "modern configuration" outlined here https://www.home-assistant.io/integrations/template/ please, I can't figure it out. I'm using an RF bridge, but I want to take advantage of the auto_off and delay off features. Thank you.
- platform: mqtt
name: "motion_livingroom"
state_topic: "tele/RF_Bridge/RESULT"
payload_on: "E664DE"
payload_off: "E664DEOff"
qos: 0
device_class: motion
value_template: "{{ value_json.RfReceived.Data }}"
my approach for my question is:
@olive moth posted a code wall, it is moved here --> https://hastebin.com/tisasukoza
Hi ๐
If I have an array, say from nordpool with tomorrow's value, end and start-time, is there a way to find the n consecutive lowest hours?
So if I want the three lowest hours (say 2-5am, not 1, 3 and 5am), how would I go about that?
Hi I hope someone can help me with a sort of concept question, Im new to the system and YAML and am trying to understand if there is a way to create a template that is referenced by a number of different devices/entities etc and whether you can add a custom attribute to that template? Or if that is even the right approach.
This won't work, you'll end up with an empty service call if another card is scanned. Use a template condition with {{ trigger.event.data.Data.CardNo in ["8804c91e", "879076c8"] }} or add the card numbers to the event trigger like this:
trigger:
- platform: event
event_type: dahua_vto
event_data:
Code: AccessControl
Data:
CardNo:
- "8804c91e"
- "879076c8"
@marble jackal neat thanks will tr this
Approach to what? Rather than asking about what you think is the solution to your problem, actually describe the problem you want to solve.
The XY problem is asking about your attempted solution rather than your actual problem.
This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.
The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.
This is probably beyond the limited capability of jinja templating and you might have to consider a python script instead. Also your requirements are not well defined. In this example, which is the lowest consecutive group of three values [1,1,1,1,1,1]?
Hi Sorry I don't really have a problem as such, I am trying to get my head around what good architecture/design config looks like really. Sorry if I was incorrect in using this chat.
I'll try my best to answer your questions then, easy one first, you can add custom attributes to any entity using customize. I'm not sure what you mean by this though: "if there is a way to create a template that is referenced by a number of different devices/entities etc " your template sensor states and attributes are available to anything that can use them.
Hi there, how would I reference the 'pictureUrl' state attribute?
camera.doorbell
inherited:
state:
pictureUrl: https:// <some URL>
I've tried the following but to no avail.
{{ state_attr('camera.doorbell', 'pictureUrl') }}
{{ state_attr('camera.doorbell', 'inherited.state.pictureUrl') }}
What happens if you enter this in
> TEMPLATES
{{ state_attr('camera.doorbell', 'pictureUrl') }}
Oh wait, i see.
This probably works {{ state_attr('camera.doorbell', 'inherited').state.pictureUrl }}
But check that first in 
{{ state_attr('camera.doorbell', 'inherited').state.pictureUrl }}
This worked - @marble jackal you're awesome, thanks so much.
hey, does anybody have any idea how I can debug configuration load paths and order? I'm really lost with why my template binary sensor is not showing up in the states and I'm pretty sure there is something wrong with how I use !include_dir_merge_list
even though I basically copied and pasted documentation examples
not really
if you're using !include_dir_merge_list wrong, you'd see errors in your logs
if you have 2 template sections, the second one will overwrite the first
how about you just post what you have and the contents of the file that are not showing up
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://dpaste.org/ (you guessed it, select YAML)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
there are 2 examples (first is working, having issues with the other one)
let me add that state template is also correct as it shows correct value in the template tool
yup
what is really annoying is that configuration checker shows that everything is ok
No need to surround your template in quotes if you use > though
well, looks like removing quotes helped
yep, confirmed, Thank You! Anyway, this is what you get changing configuration on Friday ๐
i think this would be a templating question. i have a sensor that shows off and on but i wanna make it when its "off" show "armed" and when its "on" show "activated" on my lovelace dashboard? how would i do this.
the entity id is binary_sensor.dome_battery_powered_z_wave_plus_enabled_mousetrap_general_purpose
the entitiy id is binary_sensor.dome_battery_powered_z_wave_plus_enabled_mousetrap_general_purpose
You can often do this with a device_class, but I don't see an appropriate one for this. You'd either need to create a template sensor to transform the state name or use a card that lets you do it there
the template itself is simple:
{{ 'activated' if is_state('binary_sensor.dome_battery_powered_z_wave_plus_enabled_mousetrap_general_purpose', 'on') else 'armed' }}
i was reading through the documentation of templating and definitely didnt come across that yet lol
that made it super easy
is_state() is documented here: https://www.home-assistant.io/docs/configuration/templating/#states
the if/else syntax is like Python
Thanks for your reply. In an attempt to further speciy: https://dpaste.org/ogT4/raw - this is a nordpool (power prices per kwh, start and end) output I've filtered out. In this case, it is sorted by value, but that means that the lowest values could be spread throughout the timespan of the day. What I would like to do is find the lowest consecutive time period (based on an input number, let's say 3) which will give me the cheapest time to perform an action such as charging my car.
thanks a bunch man. it looks to work beautifully
Anyone happen to have some guidance on HVAC controls?
In particular, I have one that is working fine (MQTT)
I need to include the option of heat source - gas or heat pump. Is there a particular entity I should use? I know I can use an input_select, but I would prefer to have it as an optoin in the climate entity
i have fan mode and regular modes defined
Hello! Would someone be able to advise if this is possible? I have a helper dropdown called house_state, this holds two values, daytime and nighttime. I also have two input_numbers daytime_brightness and nighttime_brightness.
Is there a way to write a template string that would substitute hardcoded value"daytime" or "nighttime"_brightness and replace it with whatever the current state of house_state so it dynamically is either daytime_brightness or nightttime_brightness?
This is my current code:
brightness_pct: '{{ states(''input_number.daytime_brightness'') | int }}'
yes, there's an example just above your question in this channel
any idea why this automation does not work ?
@olive moth posted a code wall, it is moved here --> https://hastebin.com/xorovodapi
this is my event:
@olive moth posted a code wall, it is moved here --> https://hastebin.com/ugecunuyer
your event data CardNo in your trigger has a list but the event is only a single item
you can't do that
remove CardNo and add that check as a condition. or have 2 triggers, each with each CardNo
i have three badges .. thats why i want either one of them.. or do i have to make three triggers?
3 triggers or a condition checking the 3 values
thre triggers seems easier ๐
let me test
how would that look like?
CardNo:
- a71e12c9
- 879076c8
this part
like t his
{
"event_type": "dahua_vto",
"data": {
"Action": "Pulse",
"Code": "AccessControl",
"Data": {
"CardNo": "879076c8",
"CardType": null,
......
so like this
that's your event...
@olive moth posted a code wall, it is moved here --> https://hastebin.com/hajuxegave
the code will trigger an automation like open the door
why don't you try it out
will do ๐
Thanks, I am not sure exactly what one you are referring to, perhaps I need to reword my question. This is what i tried without success, perhaps it shows better what i am trying to do:
brightness_pct: {{ states('input_number.{{states(input_select.house_state)}}_brightness') | int }}
brightness_pct: {{ states('input_number.' ~ states('input_select.house_state') ~ '_brightness') | int }}
Ah! Thanks, what does the ~ represent, is that like a concat?
Thanks alot
Hello, I want to modify the state of a scene with a boolean but I don't see how to do it.
Do you have an example please?
Scenes don't have a state other than Scening
I thank you @inner mesa for your answer.
So how can I do that I can activate an automation group. The goal is to activate them by pressing a button and deactivating it when needed.
That's a group, not a scene
Groups allow the user to combine multiple entities into one.
You can turn groups on and off, and that state is applied to the entities it contains
Don't know if the question belongs here but is it possible to template a tap_action that uses a service?
This works but i have no idea how it will work with a service action...
action: |
[[[
if (entity.attributes.alarm == "remote locking jammed bolt") {
return "more-info"
}
return "toggle"
]]]```
Depends on the card you're using. That's #frontend-archived
My robot vacuum has the sensor sensor.vacuum_last_clean_end which is a timestamp of when it last ran, e.g. 2022-01-13T11:27:37+00:00.
Can anyone help me with an expression that is true if the timestamp of that sensor is over 24 hours ago?
EDIT: This seems to work:
{{ now()|as_timestamp|int - states('sensor.vacuum_last_clean_end')|as_timestamp|int > 24*3600 }}
you could also use {{ states('sensor.vacuum_last_clean_end')|as_datetime + timedelta(days=1) < now() }}
or something like that
Nice! Looks better
Or this
{{ (now() - as_datetime(states('sensor.vacuum_last_clean_end'))).days > 0 }}
Nice
Another question: My Android app reports the "Next Alarm" sensor which has an attribute Local Time: Mon Jan 17 06:00:00 GMT+01:00 2022.
How can I format this into e.g. Monday Jan 17th 6:00am?
Alternatively, maybe it is easier to achieve the same by converting the Time in Milliseconds: 1642395600000 attribute?
Or the state itself, as it is a normal datetime
True, but the state reports the time as UTC, so wouldn't I have to account for my local time zone (and DST) in the template in that case?
Use as_local
{{ as_local(as_datetime(states('sensor.pixel_5_next_alarm'))).strftime('%A %b %e %I:%M%p') }}
This will give AM/PM (so uppercase). %P should return lowercase am/pm but for some reason it is not working for me in the template checker
The timestamp will also be in UTC time btw
My example returns Saturday Jan 15 06:30AM for me now
It's a bit of a workaround, but this returns Saturday Jan 15 06:30am
{% set next_alarm = as_local(as_datetime(states('sensor.pixel_5_next_alarm'))) %}
{{ next_alarm.strftime('%A %b %e %I:%M') ~ next_alarm.strftime('%p') | lower }}
Beautiful! Thanks a lot
I see you actually wanted 17th. I don't see that in the docs.
Me neither. No big deal
I have that here https://github.com/skalavala/mysmarthome/tree/master/jinja_helpers#21-date-format---using-st-nd-rd-th @grim obsidian @marble jackal
Nice one
Any suggestion how to start troubleshooting a template error that I think cropped up after an upgrade?
"Template variable error: 'None' has no attribute 'attributes' when rendering '{{ states.sensor.weather_station_report.attributes.list[0].lastData["tempf"] }}'"
(I get a bunch from all the templates with this particular JSON)
For a start see and heed the warning here: https://www.home-assistant.io/docs/configuration/templating/#states
{{ state_attr('sensor.weather_station_report', 'list')[0].lastData["tempf"] }}
K. I barely remember the details of all this, so it's gonna take a while to remember WTF all this is for
but thanks
I think new folks always manage to find some cave drawings with states.xxx.xxx.state and such at first, and then it lives on in their config forever
sensor.buffalo
When I started for some reason using states.xxx.xxx.state did seem more "logical" to me.
Hi everyone. Need some suggestions, please. I have a power sensor that sends a cumulative pulse data for hourly and daily pulses. But I have issues with it rebooting at random times and hence starting to count pulses from scratch.
https://ibb.co/1nxNFcq
Just wondering if its possible to somehow sum the max hourly values, so that I can plot total daily ones?
You can get a rolling "last hour" total using the statistics sensor integration https://www.home-assistant.io/integrations/statistics/ If you want a "per clock hour" reading you are probably going to have to fix your sensor so you can use the utility meter. What are you using to count the pulses?
I try to use the Template Alarm Control Panel but It's not clear how the code inputted by the user can be used inside the disarm and arm_* actions.
The example in the documentation shows code taken by secrets file.
ble puck.js
hey guys! is it possibly to have more than one value_template state? i tried to do this: value_template: "{{ is_state('media_player.playstation_4', 'idle', 'playing') }}" but that is not working... i would like to be "on" when im playing and when its idle
yes, like this:
value_template: "{{ states('media_player.playstation_4') in ['idle', 'playing'] }}"
thanks a lot man :)
Hey all - having some small issues with my garage door cover. I used the basic template from the HA website and it works, but only the stop/close_cover states. The Open cover is not available (grayed out). My position template is: position_template: "{{ states('binary_sensor.garage_door_state') }}" Shelly 1 with reed switch.
Here's the rest of the cover code (just to the open_cover part). The icon state is working fine
garage_door:
device_class: garage
friendly_name: "Garage Door"
position_template: "{{ states('binary_sensor.garage_door_state') }}"
open_cover:
- condition: state
entity_id: binary_sensor.garage_door_state
state: "off"
- service: switch.toggle
target:
entity_id: switch.garage_door```
value_template template (optional)
Defines a template to get the state of the cover. Valid output values from the template are open, opening, closing and closed which are directly mapped to the corresponding states. In addition, true is valid as a synonym to open and false as a synonym to closed. If both a value_template and a position_template are specified, only opening and closing are set from the value_template.
binary_sensor always reports on or off
perhaps: position_template: "{{ is_state('binary_sensor.garage_door_state', 'on') }}" or the opposite
Iโll try that. I had that logic somewhere else but removed it - canโt remember where I had it now. I completely removed the position template line and it worked - but only until a entity refresh
Seems that my sensor is getting inconsistent readings which is complicating things. That code worked and the door is opening/closing and the proper arrow is highlighted to open, but the icon is not changing reliably. I'll have to double check my mounting - thanks!
OK I'm having a hard time converting an old template line to use state_attr() - getting errors with all the different tweaks
value_template: '{{ states.sensor.weather_station_report.attributes.list[0].lastData["humidityin"] }}'
how should I be rewriting that with state_attr()?
maybe I should rephrase that: I'm trying to extract various values in a json dict (lastData) several levels down. I used to do it with the line above but that stopped working when I upgraded HA last week.
value_template: "{{ state_attr('sensor.weather_station_report', 'list')[0].lastData['humidityin'] }}"
updating HA wouldn't have caused that not work, so you'll need to dig into that a bit further
hm, yeah - looks like it's actually not finding jsonrest in my custom components any more.
@still dune posted a code wall, it is moved here --> https://hastebin.com/ayavibisaf
actions: >
{%- for entity in room_entities -%}
- action: 'autoroom_{{ entity }}'
title: '{{ state_attr(entity, 'friendly_name') }}'
{%- endfor %}
becomes
actions: |-
- action: 'autoroom_light.wohnzimmer_dimmer'
title: 'Wohnzimmer Dimmer'
I need the template working without '|-' behind actions. It wont work with '|-' behind actions.
Can someone help me please
You can't template both keys and values like that. Only values
I am trying to read this JSON in RESTful, but it doesn't seem to work. It is Google Sheet API
{
"range": "'Sheet 2022'!A10:B13",
"majorDimension": "ROWS",
"values": [
[
"Tuesday",
"1/11"
],
[
"Wednesday",
"1/12"
]
]
}
{{ states.sensor.sheet_2022.values }} doesn't show any value
This is the state of the sensor
{ "range": "'Sheet 2022'!A10:B13", "majorDimension": "ROWS", "values": [ [ "Tuesday", "1/11" ], [], [ "Wednesday", "1/12" ] ]}
You should parse that in the REST sensor itself
Otherwise you can use this, but it's not optimal
I am using Rest: in config YAML with adjustable timeout since it took a min to get the API to response
I tried value_template: "{{ value_json.values }}" but this show up instead <built-in method values of dict object at 0x7f95d16500>
Thank you very much. It works now
do we have a template PRESS button yet?
Looks like it will be in 2022.2: https://github.com/home-assistant/core/pull/61908
wooo. thanks. i need it, unless there is a way to make a select list work like that
the thing with select list is if you try to do the thing "again" that's already selected, nothing happens
maybe i'm just not setting the select list state right (if that's even possible)
You can create a script which does an action based on the selected option, and place that on the dashboard
It will show RUN instead of PRESS though
Is there a way to make it working?
I'm trying to figure out how to know if an input number was last updated within the last 5 minutes.
"{{ ( as_timestamp(now(),0) - as_timestamp(state.last_updated('input_number.daniels_temperature'),as_timestamp(now(),0)) ) > 300 }}"
I get this error when testing this in the template editor
UndefinedError: 'state' is undefined
I use a similar template that works.
"{{ ( as_timestamp(now(),0) - as_timestamp(state_attr('automation.winter_3_zones_correction_revised', 'last_triggered'),as_timestamp(now(),0)) ) > 25 }}"
That's pretty weird syntax
'state' is indeed undefined there and you appear to be calling last_updated as a function?
{{ (now() - states.input_number.daniels_temperature.last_updated).seconds > 300 }}
No juggling with timestamps needed at all
I see thank you
I want to search for a specific word in a entitiy list in a template.. if word is present in any of entity names in the list, then I do something.. but I can't do like "'word' in list" as I could if it was just a string.. doesn't matter if the word is present one or several times within the entity names, just if it's present or not present
use search
like this?
{{ ['foobar', 'barblah', 'foo']|select('search', 'bar')|list }}
-> [ "foobar", "barblah" ]
you don't mention what "do something" entails, but hopefully that's a start
probably a stupid question.. list here: {% set magnetsensorer = (expand('group.varme_magnet_sensorliste') | selectattr('state','eq','on')| map(attribute = 'entity_id') | list) %}
I then just want to verify if a specific word is present within the entity id's in that list
then do this:
{% set magnetsensorer = (expand('group.varme_magnet_sensorliste') | selectattr('entity_id', 'search', 'whatever')|selectattr('state','eq','on')| map(attribute = 'entity_id') | list) %}
Am I missing something? Why would these two render to "None"? 1: {{ state_attr('light.pool_controller_relay_1','last_updated')|as_timestamp }} 2: {{ state_attr('light.pool_controller_relay_1','last_changed')|as_timestamp }}
because neither is an attribute
if you look at
-> States, you won't see them in the attributes column
on the other hand:
1: {{ states.light.pool_controller_relay_1.last_updated|as_timestamp }}
2: {{ states.light.pool_controller_relay_1.last_changed|as_timestamp }}
I'm trying to make a template sensor that depends calculating two states with different update intervals. However, I only want to trigger the template sensor update when a specific one changes, as the computed value will be inaccurate if the sensor with the faster update time triggers an update but the slower one hasn't updated. How should I do this?
use a trigger in a template sensor
Ahhh right, thanks!
I was looking at a way to make states() call not become a dependency heh
Hi ๐! Is it possible to use trigger/event based templates directly as value_template for a template light entity somehow? Or would this need an intermediate template sensor?
Explain exactly what you want in your template light template.
Id like to do something like this https://www.home-assistant.io/integrations/template/#turning-an-event-into-a-binary-sensor (TURNING AN EVENT INTO A BINARY SENSOR) for a light entity's state and brightness.
Here is the full scope of the question: https://community.home-assistant.io/t/help-request-switching-different-lights-based-on-value-in-an-event/380780
So basically I'm asking if the template_light can hold its state by itself or if it needs another entities state_attr()
so I have one of the new dual dials of tuyas, that in mqtt exposes toggle, brightness step up and down (got these working fine) but trying to figure out how to use the color temp step up and down option to control either color or light temperature
You can use this service call to increase color_temp
- service: light.turn_on
target:
entity_id: light.your_light
data:
color_temp: >
{% set light = 'light.your_light' %}
{% set step = 10 %}
{{ [ state_attr(light, 'max_mireds'), state_attr(light, 'color_temp') + step ] | min }}
And this to decrease:
- service: light.turn_on
target:
entity_id: light.your_light
data:
color_temp: >
{% set light = 'light.your_light' %}
{% set step = 10 %}
{{ [ state_attr(light, 'min_mireds'), state_attr(light, 'color_temp') - step ] | max }}
Change light.your_light and the step number to accommodate your needs
thanks worked ๐
You will get errors in your log if you turn the dial when the light is off, as the color_temp attribute is not present then. So it only works when the light is on.
You could add a condition to your automation so it only works when the light is on, or you could add a light.turn_on service call without additional service data before this action
its not a issue as the dial only does the temp if your pushing in why rotating
okay
I'm trying to make a template mqtt-sensor and the topic I'm subscribed to has nested arrays, eg: topic = {"wifi_sta":{connected: true}}, how do I reach the value that says "true"?
Right now I'm trying: value_template: "{{ value_json.connected }}" but it returns "unknown".
I realize this is very basic, but I'm honestly not finding a simple enough answer for my brain via google. ๐
Solved it! Seems I just had to add a dot inbetween, so: value_template: "{{ value_json.wifi_sta.connected }}"
anyway that I can put an input_select into this
background: center / cover no-repeat fixed url('/local/testbg.jpeg')
So that I can change BG through a selector?
If that fields accepts templates.
that field does not accept templates
I believe you can template the background with a dropdown using card-mod
Any examples? Im a noob
If you're a noob, I'd just settle with keeping the background associated with the current theme. Card-mod is not for noobs and it can be extremely difficult, this being one of those difficult cases.
I guess your first test can be installing HACS and card mod, if you get that far, ask in #frontend-archived
Thanks
hi. i am not a friend with regex and the gang. somebody can help me solve this sensor as for now is unavailable
Missing a period in the regex - regex_findall_index("\*valoare de\* ([0-9.]+) lei") }}
Ty. I will try
same result ๐ฆ
if I look in body values i have something strange before value: =C3=AEn valoare de <strong>70.00</stron= g> lei<br>
Hey everyone,
so I already tried this by myself and already searched but couldn't find a similar solution, so I hope you guys can help me.
So heres my problem: I am working from home and im curious how much Energy I am using while I'm working (so I can calculate how much the energy costs me per year). I do have a Shelly Plug S connected to the desk where I work on and a sensor which determines if I'm currently working. The problem is that I also use the same desk (with Monitors and speakers) for gaming and my private projects. As far as I understood I can only create a template energy sensor which always increases without a way to stop the power increasing based on a condition. But I'm looking for a solution to increase a template energy sensor only while im working. Is this somehow possible?
Use https://regex101.com/ to debug your regex
Hi. I'm trying to update my template to set a default value but struggling to get it to work. Can anyone help? Template is {{ "ยฃ%.2f"|format(float(states.sensor.daily_electricity.state)*0.1852+0.2508) }}
Figured it out - "ยฃ%.2f"|format(float(states.sensor.daily_electricity.state,0)*0.1852+0.2508) }}
What would be the best way to store a "collection" of something? I'm looking for some data structures I can append to, pop/push, etc. Not sure if this is possible
This doesn't necessarily relate to templates so many it's not the right place to ask
There don't seem to be helpers that would accomplish this either. The closest one would be the dropdown but that seems to have a static list of items
I think the easiest way to do that is by storing, retrieving, and manipulating the data via an MQTT broker
but what you're doing sounds like something more suited to PyScript or AppDaemon or external to HA
you could do it through attributes of a template sensor
Yeah was thinking attributes and maybe that wouldn't be a bad idea. Although, I'm using it as storage and not really as a sensor. So on HA restart I believe all those values would be lost?
I have an xbox status sensor that has a value of "Last seen 2h ago: Call of Duty" I would like to create a new sensor from this one that only keeps "Call of Duty" I think I need to use regex_replace and I tried but 2h obviously changes depending on how long ago you stopped playing, so it can be 3h or even 3d. I'm not sure how to do that. This is what I have so far:
- platform: template
sensors:
xxxpaul_xbox_gameplayed:
friendly_name: xxxpaul's Game played
value_template: >
{{ states('sensor.xxxpaul_status') | regex_replace(find="Last seen *h ago:", replace='') }}
Would anyone be able to help?
Still pretty inexperienced with MQTT so I'd have to get the basics down but I'll check that out
{{ "Last seen 2h ago: Call of Duty".split(': ')[1] }}
Actually it looks like you can dynamically set values of an input select. Glad I had this conversation before finding that out lol
So {{ states('sensor.chezpaul_status').split(': ')[1] }} ?
Test it in the tester
I can only guess
Pin #1
how do you write "if value of a state contains a certain value"? Same example as before, if the value is :Last seen 2h ago: Call of Duty then can how do I write, {% if states('sensor.xxxpaul_status') contains "last seen" %}
then
{{ bla bla bla }}
in
{% if "last seen" in states('sensor.xxxpaul_status') %}
depending on what "bla bla bla" really is, you can usually do something like:
{{ 'foo' if 'last seen' in states('sensor.xxxpaul_status') else 'bar' }}
Thanks. Will try
this doesn't seem to work
{%- if "Last seen" in state('sensor.chezpaul_status') -%}
{{ states('sensor.chezpaul_status').split(': ')[1] }}
{%- else %}
{{states('sensor.chezpaul_status') | regex_replace(find="Classic Edition", replace='') }}
{%- endif %}
should it be in_state instead of in state
nope
it gives this error:
UndefinedError: 'state' is undefined
Found my stupid mistake
lif "Last seen" in states with an s
i'm looking for a little help with a template running in an automation.. i am looking to turn lights in a group to 10% if they are off or below 10%. I currently have this for those that are below 10% but couldn't seem to crack how to include also lights that may be off
How to put text sensor value into automation?
A little bit more information would help ๐
data: {{ states('input_text.tv_prompt_text') }}```
Doesn't work, i did it wrong somehow
you probably need:
service: notify.tv
data:
message: "{{ states('input_text.tv_prompt_text') }}"
So you need to specify that you want to send a message instead of just providing data, and you need to wrap your template in quotes (and use other quotes than you do inside your template)
I Got to learn it eventually
hey TheFes thanks for your help yesterday when finished do you think I can bug you with something else (same dial but for living room) to cycle through the imported hue scenes in home assistant ๐
Don't ask to ask, just ask your question. Then people can answer when they're around.
When you do ask a question, try to provide as much background detail as possible. Ask yourself these questions first so that others don't have to:
- What version of the Home Assistant are you running? (remember, last isn't a version)
- What exactly are you trying to do that won't work?
- Is the problem uniform or erratic?
- What's the exact error message?
- When did it arise?
- What exactly don't you "get"?
- Can you share sample code, ideally with line errors where the error occurs?
Just looking for help in trying to get a dial with up and down values to change between some of the listed scenes in home assistant, so rotating one way to change scenes that way and rotation to change in reverse
not looking to include all the scenes just specified ones.
@marble jackal it still doesn't work, it says "message malformed wrong entity id or UUID for dictionary value" . More than less. Isn't it about that text sensor is a 'helper' ?
Entity exists, and it's name is copypasted
Wait, maybe I figured it out
Thank you
@silent vector posted a code wall, it is moved here --> https://hastebin.com/edozeqidol
I didn't know it was too big to post and it would be converted. Whoops.
I am trying to setup an action condition. The action condition is an OR that either 2 thermostats gap between set temperature and current temperature is less than 1. In other words 0. Then the action as I won't know which actually is less than 1 has to be a template. If I didn't use an OR then it's possible the first is false and the second is true but the first being false stops the remaining actions. This would be a climate set temperature value template. But it returns an error. The template is in the hastebin above.
remove the double curly brackets here: {% if "{{ (state_attr('climate.daniel_s', 'current_temperature') - (state_attr('climate.daniel_s','temperature')|float(0))) }}" < 1 and "{{ (state_attr('climate.master_bedroom', 'current_temperature') - (state_attr('climate.master_bedroom','temperature')|float(0))) }}" < 1 %}
Like this {% if ( (state_attr('climate.daniel_s', 'current_temperature') - (state_attr('climate.daniel_s','temperature')|float(0))) ) < 1 and ( (state_attr('climate.master_bedroom', 'current_temperature') - (state_attr('climate.master_bedroom','temperature')|float(0))) ) < 1 %}
Thank you that doesn't turn up an error now. Does the action side look properly formatted? As in is it proper the way I have it setup below the conditional template
'{{ (state_attr("climate.master_bedroom", "temperature")|int) - 2 }}' '{{ (state_attr("climate.daniel_s", "temperature")|int) - 2 }}'
just bumping this up if anyone knows how to approach this. i tried to add in to the template to include those in the group whose state was off but it didn't seem to work. Do i need to have another template under the first that generates entities, or can i add it in together?
If this is a template for a condition, it should return True or False
It will not do that now
Trying to add the action side the way I formatted it above returns an error.
TemplateSyntaxError: Expected an expression, got 'end of statement block'
You did not add a statement to the {% elif %}
But what are you trying to do here, it's still unclear to me
I thought I did? I have 3 zone heating/cooling. I have an automation to avoid all 3 running at the same time. I prioritize 1 zone and shut the other 2 off if they are all running at the same time. Then when the priority zone turns off these 2 reset. I also have a thermostat that only keeps a 1 degree gap rather than the typical 2. So I have to force a 2 degree threshold. Turns on at 64 and turns off at 66 for example. There's a chance when I restore the temperature that it was already at 66. If it was it will mess up the threshold automation as it's now above what it was. That's why if the gap is 0 then if it's the same temperature as the set temperature -2 to keep the schedule.
{% if ( (state_attr('climate.daniel_s', 'current_temperature') -
(state_attr('climate.daniel_s','temperature')|float(0))) ) < 1 and ( (state_attr('climate.master_bedroom', 'current_temperature') -
(state_attr('climate.master_bedroom','temperature')|float(0))) ) < 1 %}
{% elif %} ( (state_attr('climate.daniel_s', 'current_temperature') -
(state_attr('climate.daniel_s','temperature')|float(0))) ) < 1 %}
'{{ (state_attr("climate.daniel_s", "temperature")|int) - 2 }}'
{% else %} ( (state_attr('climate.master_bedroom', 'current_temperature') -
(state_attr('climate.master_bedroom','temperature')|float(0))) ) < 1 %}
'{{ (state_attr("climate.master_bedroom", "temperature")|int) - 2 }}'
{% endif %}
'{{ expand(''group.hall'') | selectattr(''domain'', ''eq'', ''light'') | selectattr(''state'', ''eq'', ''on'') | selectattr(''attributes.brightness'', ''lt'', 26) | list + expand(''group.hall'') | selectattr(''domain'', ''eq'', ''light'') | selectattr(''state'', ''eq'', ''off'') | list }}'
ah
Okay, but what do you expect this template to return? It seems you want it to return a value based on the temperature (temp -2)
so if i'm understanding this, it's going to list the entities expanded from the first conditions ('on less than 26'), then add to that list the remaining entities ('off')
yes, and no need to join them, lists are accepted
Yes I want it to return a value. It will be apart of the HVAC set temperature. That's going to be the value.
I guess I would also need a template for entity though? Or no I could select both thermostats as entities and the temperature value is the template?
it adds the two lists together to one list
Yes, it might be better if you share the complete automation.
btw in the template you shared thel last time, there is nothing to show anymore if the first if statement is True, and the second if statement (the elif) still does not have a statement. You need something which will return true or false there
The automation is huge. Maybe I can add it to the hastebin.
https://hastebin.com/edozeqidol. That doesn't work I'll dm you the yaml
I think you mean to do this:
{% if ( (state_attr('climate.daniel_s', 'current_temperature') - (state_attr('climate.daniel_s','temperature')|float(0))) ) < 1 and ( (state_attr('climate.master_bedroom', 'current_temperature') -
(state_attr('climate.master_bedroom','temperature')|float(0))) ) < 1 %}
{% elif ( (state_attr('climate.daniel_s', 'current_temperature') - (state_attr('climate.daniel_s','temperature')|float(0))) ) < 1 %}
{{ (state_attr("climate.daniel_s", "temperature")|int) - 2 }}
{% elif ( (state_attr('climate.master_bedroom', 'current_temperature') - (state_attr('climate.master_bedroom','temperature')|float(0))) ) < 1 %}
{{ (state_attr("climate.master_bedroom", "temperature")|int) - 2 }}'
{% endif %}
Your expression needs to be between the {% and %} of the elif
And you also added a statement to the else, which will not work. Either just use {% else %} or use {% elif foo == bar %}
You're right I missed that on the elif and else. Sounds good I wasn't sure how that should be. Will the value it returns work?
There is still nothing to return for the first statement in the code from my post
You had someting like '{{ (state_attr("climate.master_bedroom", "temperature")|int) - 2 }}' '{{ (state_attr("climate.daniel_s", "temperature")|int) - 2 }}' there, but that will return two values, and that will not work in your service call
Yeah that's what I wanted. How would I adjust 2 different entities?
Would I do after the "Or"
2 separate service calls? Using these templates and just do 1 thermostat per call?
If you want to adjust two entities, with also two different values, you need 2 service calls
Sounds good that makes sense now. 2 service calls. And use this template format. But of course with only 1 thermostat per template to return a single value.
correct
If it's false what will the value be? Meaning if it's not. < 1
That would not change the temperature right? It would just stop and evaluate the next service call?
How do I make it go to the next service call if it's false?
Create a choose and only perform the service call if the change is needed would be a way
Create a choose inside of a sequence? This has to come after the temperature was adjusted earlier in the sequence. Meaning the temperature will be adjusted in the action but one it's adjusted I want to check to see if they are < 1 then make a final adjustment.
- choose:
- conditions:
- determine somehow if master bedroom needs to change
sequence:
- change the tempperature of master bedroom
- choose:
- conditions:
- determine somehow if daniel's bedroom needs to change
sequence:
- change the tempperature of daniel's bedroom
Well the issue is that would trigger when the automation didn't run previously.
Making the thermostat turn off before it's supposed to potentially. If there was an attribute for when the automation was executed that could work but there's Only a triggered attribute. It will trigger for each thermostat and may not actually execute anything so that's not going to work as a condition. For example I just had the automation run and it worked but there's a miniscule chance the thermostat was about to shut off before this automation is executed and it will on reset restore the temperature to the temperature it was previously at but it also matches the current temperature therefore messing up the 2 degree threshold as it's not higher than it was supposed to be if that makes sense. It might make more sense if you see the automation yaml I sent in your dms
I realized I could just call a script from the action and use choose there and the templates.
@sour canopy posted a code wall, it is moved here --> https://hastebin.com/ujowelojoz
Hey guys, I want to turn on/off a template switch and make that based on a different entity_id. It comes down to this:
https://pastebin.com/EBY8cVYd
But I can't get it to work. Any idea how I can set the condition of a specific entity ID with this
Just list all entities in the trigger, and use {{ trigger.entity_id }} to get the one which triggered the automation
Please don't use the dm and use the public channels, use a code sharing site if you want to send a large piece of code
Please use a code share site to share code or logs, for example:
- https://www.codepile.net/ (select YAML as the language)
- https://paste.debian.net/ (select YAML as the language)
- https://dpaste.org/ (you guessed it, select YAML)
Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.
Got it. Can a script execute 2 separate choose options at a time or can it only execute 1? Meaning if both options should be actioned as they are True will it execute both or only 1?
If you use separate choose blocks like I did in my example, it will execute both, if the conditions for both are true
If you put them in one choose, it will only execute the first one that is true
Sounds good I didn't know that was possible.
It's explained here https://www.home-assistant.io/docs/scripts/#choose-a-group-of-actions
Yes, but if is triggering it then it's not working
- platform: state entity_id: sensor.sonoff_nspanel1_zolder_light_details_id
The idea is that I long press a button on the Nextion panel, which opens a details page with info about the light. So I want to set the on/off state on that page. Which is triggered by sensor.sonoff_nspanel1_zolder_light_details_id which knows that that button has been pressed
Is sensor.sonoff_nspanel1_zolder_light_details_id the actual name of the entity?
And if so, what would be an example of the state of this entity?
Yes. If I press one of the light buttons it sets this entity_id to button_1 or button_7 etc.
But that is custom made, so I can change it if needed
okay, no that's fine
I was also thinking about setting that sensor to the entity_id value, that's possible too
so, assume it is button_7, what should your template return?
should it check if the entity matching that button is on?
Exactly
I want to toggle the light with that button. So if the entity is ON, it should turn off, if it is OFF it should turn on
{{ is_state('light.your_light', 'on' }}
I had this: {{ is_state('group.staande_lamp_woonkamer', 'on') }}
But giving errors. Let me have a look what it said
I had it like this, which is causing errors: https://pastebin.com/SNBLJk8y
define errors
Damn, I think I found it. Template was fine but target entity_id was wrong. Sorry sorry
I'll check better next time ๐ฉ
Okay, thanks!
But if you would enter the entity instead of button_on you could really simplify it
You could simply use {{ is_state(states('sensor.sonoff_nspanel1_zolder_light_details_id') , 'on') }}
Hmm, yeah. I'm gonna try to rewrite, that makes all my automations for that specific page much better
Thanks mate!
The reason I went for button_1 etc. instead of entity_id is because that didn't work with this. Because the value of a sensor couldn't be used for entity_id
- service: homeassistant.toggle target: entity_id: | {% set state = states('sensor.sonoff_nspanel1_zolder_light_details_id') | trim %} {% if 'button_1' in state %} group.staande_lamp_woonkamer {% elif 'button_2' in state %} light.houten_lamp_woonkamer {% endif %}
But if you have a smart idea how to use the value of the sensor as entity_id for service call, then I can re-write everything
Something like this works fine for me:```yaml
service: light.toggle
target:
entity_id: "{{ states('input_text.test') }}"
hey i'm getting an error on this
you are missing a step in your template, I also missed it
I didn't want to temper with it too much because of the double single quotes ๐
lol what do you mean?
i removed the last line from yours (adding the 'off' entity) but still didn't work
should they be " instead?
at least you can use it in the template checker then
But the main problem was that you should map the entity_id's
{% set low = expand('group.hall') | selectattr('domain', 'eq', 'light') | selectattr('state', 'eq', 'on') | selectattr('attributes.brightness', 'lt', 26) | map(attribute='entity_id') | list %}
{% set off = expand('group.hall') | selectattr('domain', 'eq', 'light') | selectattr('state', 'eq', 'off') | map(attribute='entity_id') | list %}
{{ low + off }}
| map(attribute='entity_id') was missing
ah ok! man every time i think i understand this i get more confused lol
If you want to use the template above, you need to do it like this (example using target)
target:
entity_id: >
{% set low = expand('group.hall') | selectattr('domain', 'eq', 'light') | selectattr('state', 'eq', 'on') | selectattr('attributes.brightness', 'lt', 26) | map(attribute='entity_id') | list %}
{% set off = expand('group.hall') | selectattr('domain', 'eq', 'light') | selectattr('state', 'eq', 'off') | map(attribute='entity_id') | list %}
{{ low + off }}
I'm doing the same as before, but now I've split it in two parts, to make it more readable
and I've added the missing filter (| map(attribute='entity_id'))
Okay. I re-wrote almost everything, but one thing is still missing and that's the brightness value sending back to the screen. It was like this: https://pastebin.com/6NdTzbuq
How to calculate the brightness of a templated entity_id? ๐
If it's not a light, it doesn't probably have brightness
hmmm vscode isn't passing this..
I understand. But there are 3 light entities inside the pastebin
ah okay, I understand your question now. But the same as for the state, {{ state_attr(states('sensor.sonoff_nspanel1_zolder_light_details_id'), 'brightness') }}
You might want to check if it is a light first though
Excellent, thanks. This helps a lot!
How did you use it? What is the complete service call? And did you notice the > after entity_id:?
yes i did. trying it in dev tools now because vscode was throwing all kinds of comments about missing commas and bad indentation but it looked ok to me
from dev tools i get: UndefinedError: 'mappingproxy object' has no attribute 'brightness'
**if i run the automation i get those errors like before in the trace
**Error: Template rendered invalid entity IDs: [<template TemplateState(<state light.above_store=on; supported_color_modes=['brightness'], color_mode=brightness, brightness=8, friendly_name=Above Store, supported_features=32 @ 2022-01-18T17:49:49.903238+08:00>)>, <template TemplateState(<state light.dining_room=on; supported_color_modes=['brightness'], color_mode=brightness, brightness=8, friendly_name=Dining Room, supported_features=32 @ 2022-01-18T17:49:49.898966+08:00>)>, <template TemplateState(<state light.entry_1=on; supported_color_modes=['brightness'], color_mode=brightness, brightness=8, friendly_name=Entry 1, supported_features=32 @ 2022-01-18T17:49:47.557094+08:00>)>, <template TemplateState(<state light.living_2=on; supported_color_modes=['brightness'], color_mode=brightness, brightness=8, friendly_name=Living 2, supported_features=32 @ 2022-01-18T17:49:47.555413+08:00>)>, <template TemplateState(<state light.study_area=on; supported_color_modes=['brightness'], color_mode=brightness, brightness=8, friendly_name=Study area, supported_features=32 @ 2022-01-18T17:49:49.891817+08:00>)>]
this is the call i placed in dev tools:
- service: light.turn_on target: entity_id: > {% set low = expand('group.hall') | selectattr('domain', 'eq', 'light') | selectattr('attributes.brightness', 'lt', 26) | map(attribute='entity_id') | list %} {% set off = expand('group.hall') | selectattr('domain', 'eq', 'light') | selectattr('state', 'eq', 'off') | map(attribute='entity_id') | list %} {{ low + off }} data: brightness_pct: '10' transition: '5'
hey @marble jackal sorry i got this working! not sure what was wrong before but i messed around in the template checker and got it implemented. thanks for your help!
Looking at the error you did not reload automations yet
and I added | selectattr('state', 'eq', 'on') to my templates. But I think you copied them before I did that the first time
Hi, I'm trying to extract the value of action_user on this topic "zigbee2mqtt/DoorlockAvant"
Here's what I get on the topic when I unlock the door(used mosquitto_sub): "{"action":"unlock","action_source":0,"action_source_name":"keypad","action_user":6,"auto_relock_time":0,"battery":96,"linkquality":63,"lock_state":"unlocked","state":"UNLOCK","voltage":5700}"
sensor:
- platform: mqtt
name: "User 6 FrontDoor"
state_topic: "zigbee2mqtt/DoorlockAvant"
json_attributes_topic: "zigbee2mqtt/DoorlockAvant"
value_template: "{{ value_json.action_user == '6' }}"
The sensor always return false when I unlock the door, have an idea why or what I missed ?
I have a card with my ikea led lamp. It automatically adds a slider for brightness, but this lamp also has color_temp (cold-warm) how can I add another slider to the card?
action_user is a number not a string, remove the quotes around 6
Hi, I am trying to use the cover template but I get the following error while adding code to my YAML file: "[covers] is an invalid option for [cover.templte]. Did you mean [discovery]?" Does someone knows how to fix this?
omg, you are right, it works! Thanks a lot, I can't believe how much time I've lost trying multiple things What should I read to understand those kind of thing ? quote/no quote on strings/bool/number etc.. ?
There aren't any quotes around the 6 in the json, so that indicates it's not a string, but a number
That also applies to booleans. true is a boolean, "true" is a string
Oh, finally it doesn't work.. the state seems to change for a fraction of second and return to false.. It's really weird. I looks like the doorlock send a message to the topic with the action_user and immediately send another one with the current state of the lock and it's like this message always overwrite any trigger or template I try to make
A quick question... Are packages still good to use, or should we start migrating and stop using packages? I ask this because of the fact that the new sensor template not being compatible with package.
How do you set a template value if a certain condition is met? For example Im just checking the app_name attribute of a media player and want it to say something other than "unknown" if the state attribute isnt present
Right now I've got just
value_template: "{{ state_attr('media_player.backyard_tv_chromecast', 'app_name')}}"
I want it to just say "None" instead of "unknown"
Do a if
value_template: >
{% if is_state('media_player.tv','unknown') %}
None
{% else %}
{{ states('media_player.tv') }}
{% endif %}
if im checking specifically for the app_name attribute shouldnt it be
value_template: >
{% if is_state_attr('media_player.backyard_tv_chromecast', 'app_name', 'unknown') %}
None
{% else %}
{{ state_attr('media_player.backyard_tv_chromecast', 'app_name') }}
{% endif %}```
?
This returns the app name if something is playing but it still comes out as "unknown" when theres nothing playing
hm- I suppose because the attribute isnt actually 'unknown'- it just doesnt exist
{{state_attr('media_player.backyard_tv_chromecast', 'app_name')}} returns null as a dict, but {{is_state_attr('media_player.backyard_tv_chromecast', 'app_name', null)}} returns false ๐ค
Ok I got it working- but for anything except "None" as a string. Lmao wtf
This returns null as a dict
{% if states.media_player.backyard_tv_chromecast.attributes.app_name %}
{{ state_attr('media_player.backyard_tv_chromecast', 'app_name') }}
{% else %}
{{ 'None' }}
{% endif %}```
While this (which is just replacing "None" with "Nothing" returns "Nothing" as a string.
```yml
{% if states.media_player.backyard_tv_chromecast.attributes.app_name %}
{{ state_attr('media_player.backyard_tv_chromecast', 'app_name') }}
{% else %}
{{ 'Nothing' }}
{% endif %}```
I don't understand that behaviour
Yes, 'None' is a special word
odd
It's a Python keyword that means null/no value