#templates-archived
1 messages · Page 131 of 1
When you use end now, your saying that the end of the dataset should be right this second
Is there any change you can edit my template that it starts for the week and month at monday 00:00 and for the day starts at 00:00 and ends at 24:00. 🙂
So I can understand it a little bit better because for now I’m not sure what you means.
Why would you want a month to start on a Monday? That would be quite rare...
Yeah that was a stupid thing to ask. 🙂
I mean to start the day at 00:00 and ends at 24:00 so I have a full 24h history. And for the week/month start at the first day 00:00 and ends the last day 24:00.
What's wrong with the 'today' sensor you have now?
I think like petro says it ends at the time I made the sensor if I understand it right? And I want to end today at 24:00.
ends at the time I made the sensor
What? 🤔
Ok I did miss understood it I gues. 😁
Forget the config. Does it do what you want?
I think it do’s but I’m not sure if it start and ends at the hours I want. 🙂
Go check if it works. There's no point asking people to solve problems that don't exist.
I know but I’m just asking what that ends now means. Do it means it ends the history recording at the time I made the sensor or at the day 24:00 I made it. 🙂
It will never end recording because now keeps changing.
In fact, it isn't even 'recording'. That sensor surfaces existing data from your DB in another form.
If you tell it to give you everything from 14 days ago to 7 days ago, that will always be one week. It's just a different selection of data points depending on what day it is today...
Ok that’s clear enough, thanks for your time. 🙂
anyone able to help me create with a templating issue? I have successfully created a value template based on two other sensor values so that I can save values to a certain variable depending on the month and year
- service: var.set
data_template:
entity_id: >-
var.strava_run_distance_{{(states.sensor.year.state)}}_{{(states.sensor.month.state) }}
this works by essentially making the entity_id in to "var.strava_run_distance_2021_august"
I have tested this by running the automation with a value of:
value: "{{ (states.var.strava_last_run.state|int) }}"
which successfully sets the value at 4
however, I want to ADD to the value every time. I have other automations that do this but this is the first time I've used a template like the one above to decide the entity_id and I'm hitting some roadblocks while trying to figure it out
however, I want to ADD to the value every time.
What do you mean?
This is what I currently have to increment my "this month" variable by the last run value
- service: var.set
data:
entity_id: var.strava_runs_thismonth
value_template: "{{ ((states.var.strava_runs_thismonth.state|float) + (states.var.strava_last_run.state|float))|round (2) }}"
but that's a simple variable that I have defined
but I can't quite figure out the syntax to essentially have:
var.strava_run_distance_{{(states.sensor.year.state)}}_{{(states.sensor.month.state) }} + (states.var.strava_last_run.state|float))|round (2)
value_template: "{{ ((states.var.strava_run_distance_{{(states.sensor.year.state)}}_{{(states.sensor.month.state)) }}) + (states.var.strava_last_run.state|float))|round (2) }}"
this returns the error TemplateSyntaxError: expected token ')', got '{'
so what I essentially want to do is:
- Every time I record a run, ADD the km from the new run to the current value for "km run this month" (I have this and it works fine)
- Every time I record a run, ADD the km from the new run to the current value for "km run in August" (this is what I can't figure out)
Any help would be greatly appreciated 🙂 this my first time playing around with a value template that is defined by other entity values
Sounds like you just have a formatting error somewhere. Test that same template in Dev Tools > Templates and tweak it until it works.
Oh... you're nesting templates. You can't have templates within templates.
ok, thanks 🙂 will keep tweaking
ah I see! That's what I was worried about and what seemed to be causing the concerns
is there any way around that? I had considered maybe saving the templated name as a sensor or input_text but I'm not quite sure if that will work either?
There are a few issues with your approach. First, always use the states() function to access state values. Second, you need to build the variable name up in pieces like this before finally getting the value of the sensor whose name you just built:
states('var.strava_run_distance_' ~ states('sensor.year') ~ '_' ~ states('sensor.month'))
From there, do the math to add the other sensor's value to it.
thanks @ivory delta I'll have a look down that route then
- service: var.set
data_template:
entity_id: >-
var.strava_run_distance_{{(states.sensor.year.state)}}_{{(states.sensor.month.state) }}
value: "{{ ((states('var.strava_run_distance_' ~ states('sensor.year') ~ '_' ~ states('sensor.month'))|float) + (states.var.strava_last_run.state|float)) | round (2)}}"
works like a mothatrucking charm
thank you so much!
I would never have got there without the ~~~ stuff
You were close. You just needed to nest things properly.
Hello! Is it possible to create multiple mqtt sensors based on topic. For example:
office/sensorX
{
"temperature": 23.20,
"humidity": 43.70
}
where X is a number that can vary any-time
I'm not sure how that has anything to do with templates. Sensors are an #integrations-archived thing.
And the likely answer is: no
i'll go to #integrations-archived then, thanks for helping ^^
I'm working on a script which has some variables which can be entered when you run it. This can be one or multiple entity id's. For the script to properly work, this needs to be a list.
Now it could be that the input is already a list, but it could also be that the input is a comma separated string. Is there a way to determine if a variable is already a list, so I can convert it to a list when it is not?
While checking some stuff I noticed I have got two different syntax for conditions. One of them just having a '>' and no double-ticks. What is the difference, if any? https://paste.ubuntu.com/p/SWhGrFNBTM/
The second makes sense and the first does not
I suspect that you’re looking for: the first is a single multi line template and the second is a list of 2 template conditions (in shorthand format)
But the first is incorrect because it returns two values and won’t evaluate to a single boolean
The 2nd one works like having two seperate template conditions. And should both evaluate to true for the process to contintue. It would be the same as this:
- conditions:
- conditiion: template
value_template: "{{ states('sensor.period_of_day') in ['night'] }}"
- condtion: template
value_template: "{{ is_state('switch.tv_telldus1', 'on') }}"
Thanks guys! I have probably copy/pasted something and got it where it does not belong. Second one in conditions from now on then 🙂
The first could work if you combine them with and
- conditions: >
{{
trigger.id == "tv"
and states('sensor.period_of_day') in ['night']
}}
Which is the shorthand notation of:
- conditions:
- condition: template
value_template: >
{{
trigger.id == "tv"
and states('sensor.period_of_day') in ['night']
}}
Thanks, but I think I will use the 2nd style. I sometimes over-complicate stuff sometimes... Simple is better where possible 🙂
Use is iterable
thanks!
Strings are iterable so check not string too
ah, okay.. I was just going to say that both of these returned True
{% set player = 'media_player.google_home1, media_player.google_home2' %}
{{ player is iterable }}
{% set player2 = [ 'media_player.google_home1', 'media_player.google_home2' ] %}
{{ player2 is iterable }}
is string or not string seems to work. Thanks!
This seems to do what I want, thanks again Petro!
https://paste.ubuntu.com/p/Q7347Z2HNC/
np, fyi to be robustly search for a list and only a list... value is iterable and value is not mapping and value is not string
it's a pita, but that will only find lists.
you're luckily searching for a string or a list so you can safely just find a string
however, if you want to find a list vs a dictionary, you'd need the above statement
I need to estimate/show a time in the future, and came up with this. https://paste.ubuntu.com/p/Ms4W8DWv7j/ It feels messy and hope there perhaps is an easier way?
Hi, did anyone have the same issue that timestamps are incorrect in templates while correct in all other instances: message: Last presence: {{states.sensor.home_last_presence.last_changed}} gives me message: Last presence: 2021-08-02 11:08:39.108935+00:00. Might be an UTC issue as I'm 2 hours off UTC time. No clue where to start with this one. When I check the last triggered in the dev panel, the time is correct
{% set time_on = as_datetime(now().date() ~ ' ' ~ '00:02:00') %}
{{ time_on + timedelta(minutes=2) }}
That's utc
everything under the hood is utc
the timestamp is not incorrect
ok never had this issue, will look how to convert the template timestamp. great tip
what are you trying to do? You typically don't need to convert anything unless you're trying to perform math
Thanks! Much cleaner 😄
just realize the output will now contain the date. If you want it to just be a time, you need to use timestamp_custom
the issue is I made a template showing the last triggered presence detector, and that one shows the utc time (no idea why) instead of the utc+2 time. therefore i have to convert that one
Ok, but you're still describing what you think you need to do, not what your goal is
as I said, the likely hood of you needing to convert it is low
so please. Say what you are using the timestamp for.
to send me a notification about the last presence, i don't want a notification with all individual sensor timestamps, only the last one triggered. Made this template: https://hastebin.com/nepesitoji.yaml
and that gives me utc time now when i call it with: Last indoor motion: {{states.sensor.home_last_presence.last_changed}}
{%- set sensors = expand('binary_sensor.prasenz_eg_flur2', 'binary_sensor.prasenz_1s_duschzimmer', 'binary_sensor.prasenz_eg_wc', 'binary_sensor.prasenz_1s_badezimmer', 'binary_sensor.prasenz_1s_flur', 'binary_sensor.prasenz_kg_flur') %}
{% set last_changed = sensors | map(attribute='last_changed') | list | max %}
{{ as_timestamp(last_changed) | timestamp_local }}
- You should never use states.xxx.xxx. It's not safe during startup. Use expand.
- You don't need to loop. Use filters, like selectattr and map.
- convert to a timestamp then to local
@mighty ledge amazing tips!, rebooting already with the improvements
check the template in developer tools
don't need to reboot either unless you're using the new template integration
5/7. Perfect score.
you can reload templates using the reload button or template.reload service
Thanks, did it, rebooting again, there was still a timestamp issue. checking where it comes from. was correctly showing +2 ,but when i called the .last_changed state it was incorrect. will see if the reboot helped
@finite stump posted a code wall, it is moved here --> https://paste.ubuntu.com/p/HmXGVb5fGC/
The template I provided should work out of the box without alteration.
are you aware that last changed will change upon restart?
that's the one i use, maybe i am missing something but the template {{states.sensor.home_last_presence}} returns <template TemplateState(<state sensor.home_last_presence=2021-08-02 13:52:07; friendly_name=Last Presence Indoor, device_class=timestamp @ 2021-08-02T13:52:28.523906+02:00>)> and {{states.sensor.home_last_presence.last_changed}} returns UTC : 2021-08-02 11:52:28.523906+00:00
yes... but what does my template return?
that's your template - platform: template sensors: home_last_presence: friendly_name: Last Presence Indoor device_class: timestamp value_template: >- {%- set sensors = expand('binary_sensor.prasenz_eg_flur2', 'binary_sensor.prasenz_1s_duschzimmer', 'binary_sensor.prasenz_eg_wc', 'binary_sensor.prasenz_1s_badezimmer', 'binary_sensor.prasenz_1s_flur', 'binary_sensor.prasenz_kg_flur') %} {% set last_changed = sensors | map(attribute='last_changed') | list | max %} {{ as_timestamp(last_changed) | timestamp_local }}
if you use device_class: timestamp you don't need to care. You said you were using this for a notification
which you would need to convert it
so which is it?
are you using this in the UI or are you using this for a notification
The UI naturally converts things and device_class: timestamp does the conversion for you.
service: notify.homeassitant data: message: >- Last motion in carport at {{states.sensor.eingang_last_presence.state}} Last indoor motion: {{states.sensor.home_last_presence.last_changed}} End
this is my notification
to have a clean notification, avoiding this basically: message: Last presence: <template TemplateState(<state sensor.home_last_presence=2021-08-02 13:52:07; friendly_name=Last Presence Indoor, device_class=timestamp @ 2021-08-02T13:52:28.523906+02:00>)> detected by 2021-08-02 13:52:07
state is binary
want to know when the last change occured in house
so you put that template that I provided into a device_class: timestamp sensor in the binary_sensor section?
I'm trying to lead you to water here because you're making simple mistakes
in the sensor section actually....
well it is, but i am wrong
it's a knx sensor sending a binary
put the template in the sensor section although
so you're saying 'sensor.home_last_presence' is binary?
no i guess i will put it in the binary_sensor section
ok now following you
I can tell
sensor.home_last_presence's state is a local timestamp, correct?
the answer is yes or no
yes
Ok, so then why aren't you getting the state in your notification
For this
initially used {{states.sensor.home_last_presence}}for my notification, but wanted to get the timestamp only for the notification
not the entire <template TemplateState(<state sensor.home_last_presence=2021-08-02 13:52:07; friendly_name=Last Presence Indoor, device_class=timestamp @ 2021-08-02T13:52:28.523906+02:00>)> output, therefore went the -last_changed route
and then I was stuck
let me try one sec
hint2: You're even using it in the same notification template...
fyi, you should switch thoes to states('sensor.xxx') instead of using states.xxx.state
np
ok will try that immediately too
great, all working perfectly. will now try to display the sensor which changed last. Will try to work it out myself. Thanks again
I though I could adapt this. My aim is to add time to now() formatted as 00:00:00. The time I'd like to add is a string in the same format. This is what I have now: {% set time_on = as_datetime(now().date() ~ ' ' ~ '00:02:00')%} {% set min = time_on.minute %} {{ as_timestamp(now() + timedelta(minutes=min)) | timestamp_custom('%H:%M:%S') }}
It works like this in DevTools, but when added to the script it will not. I have tried to replace the latter part of the 1st line '00:02:00' with the string variable, but cannot work it out...
replace '00:02:00' with whatever variable name you are passing to the script.
Sorry. I did try that, but triggered the script without a default... 😦 It works nicely when fed a variable!
then supply a default in your teemplate
{% set time_on = as_datetime(now().date() ~ ' ' ~ my_var | default("00:00:00") %}
{% set min = time_on.minute %}
{{ as_timestamp(now() + timedelta(minutes=min)) | timestamp_custom('%H:%M:%S') }}
Yes, will do. I have added it in most places I do this, but not this one yet, obviously... 🙂 Thanks!
or if you want 1 minute from now....
{% set time_on = as_datetime(now().date() ~ ' ' ~ my_var | default(as_timestamp(now)|timestamp_custom('%H:%M:%S')) %}
{% set min = time_on.minute %}
{{ as_timestamp(now() + timedelta(minutes=min)) | timestamp_custom('%H:%M:%S') }}
I simply set it in the var declaration as time_on: "{{ time_on | default('00:02:00') }}"
that also works
you'll have to use a different var name though
in your template
you can't replace input variables using variables
Yes, I did change those to avoid conflict, Thanks for your help! Much to learn (and remember) 🙂
I need a bit more help with a template.
I have a list with some enitity_id's in it (entity_id_list). I also have a list with some groups in it (group_list). I want to create a new list with all the groups which have one or more of those enitity_id's in them.
If I would only have one entity_id, I can create a for loop to check all the groups. However, I now have also mutliple entity_ids, so I thought I had to nest the for loops.
I tried this:
{% for i in range(0, (entity_id_list | count) - 1) %}
{% for a in range(0, (group_list | count) - 1) %}
{{ group_list[a] if entity_id_list[i] in state_attr(group_list[a], 'entity_id') }}
{% endfor %}
{% endfor %}
But that only gives a result if my entity_id_list contains all entities of a group. But I want to know the group even if one of the entities is listed.
What am I doing wrong here? And if I know that, how can I create a list out of the result 🙂
few things. so {{}} are print statements, they will always output. 2nd: you can't update things that are out of a loop from inside a loop, you need to use a namespace() accomplish that
here is what i worked out:
"light.ge_14294_inwall_smart_dimmer_level",
"binary_sensor.master_bedroom_occupancy"
] %}
{% set groups = ["group.master_suite", "group.living_room"] %}
{% set ns = namespace(groups = []) %}
{% for group in groups %}
{% for entity in state_attr(group, 'entity_id') if entity in entity_list %}
{% set ns.groups = ns.groups + [group] %}
{% endfor %}
{% endfor %}
{{ ns.groups }}```
@marble jackal ^
Thanks a lot, I will give it a try 🙂
why even bother with namespaces when you can use select or reject
set entities = state_attr('group.xyz','entity_id') | select('in', entity_list) | list
wouldn't that check to see if the full set is in the list?
no that will filter the entity_id from the group down to only things inside the entity_list
unless i'm reading his requrementents wrong
he wants the group names of groups that contain entities in a list
ah, so I am
so sadly still need loops
well, you could still just use selectattr in that case
but you can't use expand
so, I get why the loop is being used
yeah, expand() "helps" too much here and jumps straight to the entities
interesting situation
would be nice for a recursive flag
expand(.... , recursive=False)
that could be cool
so just tried this:
{{ groups|selectattr('attributes.entity_id', 'in', entity_list)|list }}``` and it didn't like it
since it checks the whole thing
reverse it with search
well, no, you're right
you know about the new search/match?
that's another limitation that annoys me 😛
yeah, i've used them a couple of times. regex is generally "slow" though so i try to avoid it
still won't work, but very useful
lol
the regex tests will be awesome for substring matching. "hey, i have entities with x in the name, how do i do <stuff> with them?"
Ya
I went through my templates thinking I would need to use them
but turns out I don't have any templates that complex
lol
or you did the "do i actually need to do it this way" test and realized you didn't and went with a better route
i treat regex like i treat for loops. "If you think you need this, you're probably wrong"
though the above example is why i say "probably" because sometimes you do need it
I realized the only place I used it was on my corona virus tracking sensor which I removed because I don't look at it
so it was a "oh hey, lets delete that"
heh that'll do it
Hi Guys, anybody great at spliting the values out of sensors by templating? I have "Front Left: Playback 42597 [65%] [on]" and need to get only the value without percentages from first brackets.
Does it always follow the same structure? The brackets and percentage are always there, and there's always a number in there?
{{ "Front Left: Playback 42597 [65%] [on]".split('[')[1][:-3] }}
will check the strucutre
Where can I find the documetnattion for split function pls? I am maybe really blind.
It's Python.
applying a regex would be easy, but I don't think you can do that in Jinja
The stuff that works on arrays/numbers/strings is usually Python. The stuff that does filters (|) is usually Jinja. Some things are a little vague.
Jinja uses Python data types, and you get the methods on those types for free
Thank you guys!
Do you know what is minimum scan interval of sensors and if it can be below 1 sec ?
this is an #integrations-archived question, but it's based on a Python timedelta, and they can have higher precision: Syntax : datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
I wouldn't recommend a super-fast scan_interval because it will affect overall system perf, especially if you're also triggering on changes (and if not, what's the point?)
- service: persistent_notification.create data: title: Test random light message: > {% set random_light = ["light.kjokken", "light.vindfang", "light.dimmer_stue", "light.lampe_stue", "light.dimmer_hovedsoverom", "light.dimmer_2etg_gang", "light.dimmer_kine", "light.dimmer_hanna"]|random %} {{ random_light }} - delay: 00:00:10 - service: persistent_notification.create data: title: Test random light message: Light off {{ random_light }}
Is it possible to do something like this?
probably but why?
We're often at our cabin, and then I would fake our presence by turning on two random lights, and then turn them off again around midnight
- platform: rest
resource: https://services.surfline.com/kbyg/regions/forecasts/conditions?spotId=5842041f4e65fad6a7708b8d&days=1
method: GET
name: "Surfline"
value_template: '{{ (value_json.data.conditions[0].observation) }}'
scan_interval: 60
Getting a state of "unknown" on this rest sensor (first time making a custom sensor) but when I manually curl the endpoint it works fine. Trying to make a sensor for displaying data from Surfline.
When trying it out in developer tools > Template, it works fine
Welp. Nvm. Restarted HA Core and it works now.
hello helpful friends, i am new to templates. do you know how i can append a unit (kWh) to the numerical value in this template?
state: "{{ (states('sensor.power_none_123_1min') | float / 1000) | round(2) }}"
add a unit_of_measurement: xxx
where do i add that?
that's a template sensor definition, right?
yeah
@lost wyvern posted a code wall, it is moved here --> https://paste.ubuntu.com/p/tZVvKq6vQ8/
Oops. Adjusting my question.
it worked, thanks Rob
@lost wyvern posted a code wall, it is moved here --> https://paste.ubuntu.com/p/kxgypDry4X/
@lost wyvern Rule #6: Please do not post codewalls (text longer than 15 lines) - use sites such as https://paste.ubuntu.com/ (just not Pastebin).
Please take the time now to review all of the rules and references in #rules.
my windows machine's uptime sensor has output like this: 10:04:20:14. how can i convert to timestamp? i tried
{{ strptime(states('sensor.intel_nuc5i3_system_uptime'), '%j:%H:%M:%S')}}
but its not working.
edit: maybe it is working. the output is: 1900-01-10 04:22:17
that means it start counting from 1900/01/01.
but i want 10 days from now. how can i do that?
10 days from now, or from that uptime sensor?
I want to have led strip W2812 connected to wemos d1 mini with esphome to act as volume level indicator - I set the command line sensor according which the led strip will light its leds
I would connect the strip to the PI if I have the knowledge how to code it. Thru esphome it is feassible for me i think.
I will move it to the PI in future after I figure it how i can do so
API Endpoint JSON: https://hastebin.com/miqijudife.json (https://services.surfline.com/kbyg/regions/forecasts/conditions?spotId=5842041f4e65fad6a7708b8d&days=1)
Template: https://hastebin.com/uyijoxozas.yaml
Why am I unable to retrieve the data located at value_json.data.conditions[0].am?
with a simple test in the template tester it is working for me
It worked for me too, but not with the json_attributes / trying to define multiple sensors
that's not something i've really messed with so i'm not sure
i need a date that is 10 days before now.
i managed to calculate this
{{ as_timestamp(strptime(states("sensor.time_date"), "%H:%M, %Y-%m-%d")) -
as_timestamp(strptime(states('sensor.intel_nuc5i3_system_uptime'), '%j:%H:%M:%S')) - 2208988800}}
this represents when the windows machine was restarted. but how can i get back as date and hours?
2208988800 is 1900/01/01
what is the output of sensor.time_date ?
current time
21:11, 2021-08-02
what display option are you using? and why did you chose it?
if you use date_time_iso you don't have to do any formatting
how can i use that, can you give me one example?
then you can do as_timestamp(states('sensor.date_time_iso')) + timedelta(days=10)
Is there a faster way to reload my REST sensor entity/template than restarting HA core?
the REST sensor is its own integration, so unless there's an entry in
-> Server Controls, no. I don't have one to confirm
It should have one, it's super easy to add in code now
but it'll be a service
check the developer tools -> services tab and look for a rest reload service
if it exists, it'll only be for the old style integration
what does it take to get it to show up in Config->Server Controls? I see some non-general integrations adding items there, like for my ISY994
🤷♂️
I would assume the service
but I made a custom integration that has a reload service and it's not showing up
I figured that it was just for Core integrations, but evidently not
Oh wait, it does
so, all you need is to subscribe to the reload service and it'll show up
cool
so, if it can, it'll be in that area
I don't maintain anything with a YAML config, but good to know
it's a TIL situation for sure
I only added it to my integration because I was writing it as I went
ain't nobody got time to restart
so this?
hass.services.async_register(
domain=DOMAIN, service=SERVICE_RELOAD, service_func=async_reload_config_entries
)
ah, indeed
await async_setup_reload_service(hass, DOMAIN, PLATFORMS)
it's stupid simple
but I'm not sure if it works with complex data structures like the list of templates that the new template sensors use
i get this error TypeError: unsupported operand type(s) for +: 'float' and 'datetime.timedelta'
he meant as_datetime
now it works....what should I write instead of days=10? timedelta(as_timestamp(strptime(states('sensor.intel_nuc5i3_system_uptime'), '%j:%H:%M:%S')) + 2208988800) gives me wrong days!
days=10 is what you should have
if you have uptime in seconds or something do seconds=
output of sensor.intel_nuc5i3_system_uptime is 10:05:39:32.
there's no timedelta conversion
so do the math yourself
or use that to set each item
{% 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) }}
thanks for the code, but i got this error
invalid template (TemplateAssertionError: No filter named 'split'.)
then change it to .split
it's working now. thanks a lot. i made a sensor now with following code
- platform: template
sensors:
nuc5i3_uptime:
friendly_name: "Intel Nuc Uptime"
value_template: "{% 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) }}"
but the device class is not timestamp. is there any way i can convert to timestamp
Update on my issue: When I do {{ states.sensor.surfline.attributes }} in the Developer Tools > Template I get nothing (empty string), but when I do {{ states.sensor.surfline }} I get
None
None```
the reason i am asking is, when i use sensor.uptime (system uptime, device_class: timestamp) as entity, in lovelace it is shown as 'X' days ago/ 'Y' weeks ago. but the output of my NUC's uptime is not like that. entity shows in lovelace as date and time
thanks, just added device_class: timestamp and it's exactly what I wanted now.
- platform: template
sensors:
time_since_most_recent:
value_template: >-
{{ states.input_text.lastusedss.last_updated.strftime('%Y-%m-%dT%H:%M:%S') }}Z
device_class: timestamp```
i have this sensor that displays in lovelace as ex; `1 hour ago` depending on when an `input_text` was last modified. unfortunately when my HAS restarts, it changes to the system uptime, ex; `1 minute ago`. why might this be?
Okay, I finally got my Surfline REST sensor working. I ditched the am/pm etc JSON attributes and just opted for a single data attribute which I go and manually grab what I need.
Now, next question, how can I add a "Dropdown" selector to display different rest sensors on the same card. Use case is this:
I want to check the wave height for multiple locations, each location requiring a separate API call/resource URL. I only want one card for this, though. So I will select the dropdown and pick "37th Street", which will display the wave height data for 37 St. Select 61st and it shows for 61st, etc.
Hi, I am trying to call the notify.mobile_app service and have it include the current date in the following format: 8/2/2021 in the message title. I can't seem to get the date to appear
What would be a way I could do that?
Nevermind, figured it out with now().strftime
Question. Let's say I have a list with the following data ['foo', 'bar', 'yolo' ]
Is it possible to get the list index number of one of these values. So e.g. bar would return 1
I found I could use .index but there could be cases where my search value is not in the list
If it’s not in the list the result will be -1 pretty sure… unless that’s c#
It will return a error, but I found a work around (example found on stackoverflow)
{{ansible_play_hosts.index('not exists') if 'not exists' in ansible_play_hosts else 999 }}
without the check it will return an error like ValueError: 'not exists' is not in list
Wondering if anyone can help me with something? I'm trying to create a boolean check basically with multiple door sensors. When the doors are shut the boolean is true, and if 1 or all doors are open the boolean is false. I'm doing this by making a sensor such as below but I'm struggling to get it working.
@wintry needle posted a code wall, it is moved here --> https://paste.ubuntu.com/p/fWCkrbwhGz/
What’s wrong?
Did you find | sort(reverse=True, attribute='last_changed') | first (not tested, but likely to help) yet?
not yet, did some tries but failed, slowing to start noting how these templates work with my basic python knowledge. will give it a shot
These filters are a very powerful thing
yes, build one to get the max actual temp in my house from all sensors, luckily managed to get that one to work
brb
max() is a thing
Just FYI, this is why I was asking my template questions 🙂 https://community.home-assistant.io/t/script-to-resume-radio-tunein-and-spotify-after-tts-on-google-home-speakers/326634
so ive been st to work out how to use variables - trying to create a variable called message where the asterisks are.
rest_command: text: url: "http://192.168.178.12/" method: post content_type: "application/x-www-form-urlencoded" payload: "alignment=center&speedslider=100&devicemode=text&input1=**********"
apologies if this is super simple, but haven't been able to figure it out from the documentation
payload: "alignment=center&speedslider=100&devicemode=text&input1={{ message }}"
pass it to your command like this: ```
- service: rest_command.text
data:
message: "your message here"
I am sure I could make it more compact and elegant {%set temps = states("sensor.temperatur_kg_flur")|int, states("sensor.temperatur_1s_bad")|int, states("sensor.temperatur_1s_duschzimmer")|int, states("sensor.temperatur_1s_elternschlafzimmern")|int, states('sensor.temperatur_1s_flur') | int, states('sensor.temperatur_1s_xxx_zimmer') |int, states('sensor.temperatur_1s_xxx_zimmer') | int, states('sensor.temperatur_eg_wohnraum') |int %} {{ temps | max }}
ah, ok so i did do it right, but messed up calling the service i think
but it works
Well there is this https://www.home-assistant.io/integrations/min_max/
cheers for the help
works like this, thanks {%- set sensors = expand('binary_sensor.prasenz_eg_flur2', 'binary_sensor.prasenz_1s_duschzimmer', 'binary_sensor.prasenz_eg_wc', 'binary_sensor.prasenz_1s_badezimmer', 'binary_sensor.prasenz_1s_flur', 'binary_sensor.prasenz_kg_flur') %} {% set last_changed = sensors | sort(reverse=True, attribute='last_changed') | first %} {{ last_changed }}
drop that last set and just put it in the output line
You can add those sensors in a group (eg group.temperature_sensors) and use expand('group.temperature_sensors')
That also makes it easy to add and remove sensors without having to make changes to your script(s)
yup, handled that in the thread
thanks @dreamy sinew helped me out
If you're replying to Owner I posted it on the wrong account.
It doesn't work basically, there is no errors in the config but when I change the front door to open / closed the sensor doesn't change at all. The single front door sensor does work though.
You can test your template in
-> Templates
Ah, threads.. still need to get used to that :)
the .format() filter is indeed useful, could shorten a few other templates!
yeah, that one is pretty great
Can this be changed to have an AND operator?
{% if s.object_id.endswith('daily_consumption') %}
I am looking to filter based on both the beginning and ending of the entity_id....
changed or just adding and "and"?
I would expect something like this to work:
{% if s.object_id.endswith('daily_consumption') and s.object_id.startswith('foo') %}
Let me try....
Yeah, that makes sense! Thanks! 🙏
I seem to often know where I wanna end up (good in itself) but not how to get there.... 😊
Is there a way I can template a timestamp that always is one second into the current day?
{{ now().replace(hour=0, minute=0, second=1) }}
as a timestamp: {{ as_timestamp(now().replace(hour=0, minute=0, second=1))|int }}
Let me see if this actually works.... 🙂
Is only the last template actually a timestamp?
you can try it
the "as_timestamp()" is the clue 🙂
I have no idea what you're doing, so I'm just giving you the building blocks so you can solve whatever problem you have
Yeah, I was just asking... The first temaplte you gave me was what i was after, and you referred to the second one "as a timestamp". Just trying understand the difference...
I am trying to create a template sensor that is compatible with a certain new panel coming tomorrow... 😉
This is what I currently have, and it is not working... 😄
https://paste.ubuntu.com/p/bTfp7fWznw/
what's not working about it?
It is not showing up as a candidate for device consumption in the panel... I think all the requirements are in place, not sure anymore what could be wrong.
you don't have state_class: measurement
I would like to return a boolean depending on the numeric value of a sensor similar to this, so I can insert in on the conditional card in lovelace, but I can't seem to make the int work. Should return True or false for something similar to :
{{ states('sensor.u_s_air_quality_index') > 80 }}
you say that you can't make "int" work, but I don't see it there at all
{{ states('sensor.u_s_air_quality_index')|int > 80 }}
Ooofff, I must have tried this like 10 times and messed up the parentheses... Thanks! I'm going to use this a lot going forward.
if you use a {% set variablename = states....... %} its ok to reuse variables names in other templates right?
(not to share data, but checking it won't cause any issues if I reuse the naming schemes)
set offset being used in 9 template sensors for example
Yes, they’re all separate
Howdy 🙂
what's the trick for templating automation/trigger/entity_id? there was something like having to use data somehow if brain serves, but I just can't find it 😄
context: I'd like use sensor states from a group to trigger automation, so what I'd like to do is to expose all the entity_ids from that group with a template
You'd expand the group to get at the individual entities. Search the history of this channel for examples.
oh that part is OK, how do I add that as my trigger?
trigger:
- platform: state
data_template:
entity_id: "{{ ...
but this doesn't seem to be OK
You don't... you'd use a template trigger...
But that's a topic for #automations-archived
oic, cool, thanks mono
Moved to #energy-archived
HI folks. I'm usually pretty good about reading the release notes, but something in there must have escaped me. I have a few template sensors that look like this and are all now failing to render:
https://pastebin.ubuntu.com/p/wGcg7j9KTn/
Can someone point me in the direction of a fix?
what are you getting in
-> Templates?
It works fine there.... Gives me the expected 00:00:00.
so what's wrong?
I can't pick out the issue if you only provide the part that's working 🙂
The sensor value shows up as "unknown" in Home Assistant and I get the following error in the logs when it tries to update:
https://pastebin.ubuntu.com/p/3D9Xvh744V/
I'm trying to debug a script using a counted loop in which I use the repeat.index. Can I somehow define repeat.index in de template editor? If I just do {% set repeat.index = 2 %} it tells me TemplateRuntimeError: cannot assign attribute on non-namespace object
Hey guys, im blind on this one; i want to implement a button-card with a template. I've added the template in my frontlace raw config (on top). But i still get the message; Button-card template 'standard' is missing!
Not just blind but also lost. You want #frontend-archived for cards. And even when they use 'templates', they're usually JavaScript templates - this channel's for Jinja.
ill head over there
you should use is_state('sensor.kitchen_next_timer', 'unavailable') rather than the test you have, but we'd need to see the actual sensor definition for anything else. I suspect that the sensor state is sometimes "None" and not just "unavailable"
Thanks. I’ll give that a try.
is it possible to do somting like.
{% for a in states.area %}
{{a}}
{% endfor %}
loop by all the areas?
No, because areas aren’t states and area isn’t an attribute of an entity
I don’t think there’s useful area support in templates
Sill no good.... At this point, I'm wondering if it's just an HA bug. As I said, it works fine vie the Developer Tools.
Unless I missed it, you still haven’t shared your sensor definition. Like I said, sharing the part that works isn’t that helpful
Tks for the help
Good point. I thought the issue was in the part I posted, but I also have a template for the friendly name and that actually seems to be the part that's failing. Now that I've narrowed it down, I have some more investigation to do. I'll be back if I need more help.
Thanks for pointing me in the right direction.
np. If you can stick the template in
-> Templates and it works, then the problem is either elsewhere or simply timing
Looks like it may be timing.
I use conditions like this to avoid similar issues:
condition:
- "{{ trigger.from_state is not none and trigger.to_state is not none }}"
- "{{ 'unavailable' not in [trigger.to_state.state, trigger.from_state.state] }}"
Here's what I have for the friendly name template:
https://pastebin.ubuntu.com/p/dqg96m4Gq4/
It worked fine before upgrading to the latest version of Hone Assistant and works fine in the Developer Tools. So, I'm assuming it's a timing issue on startup. Any suggestions?
that's still not the whole thing
and you probably have exactly the same problem I mentioned above, and gave you examples to avoid it
if you sensor is "none", it will barf
Forgive me... I'm a bit of a newb with templates. I'm not sure how conditions fit in with template sensors.
Here's the full definition of the sensor:
https://pastebin.ubuntu.com/p/jXynhS4kGJ/
they're just an example of how I'm guarding against uninitialized states
adapt as needed
something like this: https://pastebin.ubuntu.com/p/2nDQVnkKQK/
@wet lodge
I'll see what I can do with that. Thanks!
the main point is that you want to guard against "none" and don't try to poke into it unless it has a valid value
I've tried a couple variations of your example:
https://pastebin.ubuntu.com/p/QWrqzx4qQQ/
Neither works. But if I comment out the else clause, the sensor initializes properly (though, of course, it doesn't do what I want it to).
So, it seems like it's slipping through the none / unavailable check and choking on something in the else clause. What's weird, though, is that it worked fine before upgrading and, even still, each variation I've tried works fine in the Developer Tools.
your second one isn't checking the values in friendly_name_template, so it's no better than what you had
in the first, I had a typo in the value_template
sensor.kitcen_next_timer->sensor.kitchen_next_timer
The most important thing is that you understand what I'm trying to do. Your "second" variation makes me think that you haven't grasped it yet.
and that you check that your entity names are correct - I'm just playing with your code and can't test it
@wet lodge
That error doesn’t actually exist in my config. It was just a typo I made when posting my code. So, the code in my config is correct and still doesn’t work.
In any case, you may be right about the fact that I still don’t grasp it. I’ll keep working on it…. Thanks for your help!
@wet lodge 'NoneType' object is not callable means that you are calling some function that is not a function. Not an expert, but it looks like the only calls you're making are to split on some objects. Maybe one of the objects does not have a split function but has a split attribute that is not a function. Which one? Why? That's where your debugging comes in, and where the techniques showed by @inner mesa are useful. Make sure that something is "ok" on every step.
calling split on objects would not produce 'NoneType' object is not callable
it would produce a NameError or KeyError
NoneType is not callable would be if an object is set to None and you attempt to call it. i.e. set foo = none, foo()
FYI that error is a python error and it's not associated with your syntax. It's saying that _async_update is None and it's not callable. I'm not sure why self._async_update is returning none. You should do a config check and see what errors that produces.
No errors in my config.
what does the state_attr('sensor.kitchen_next_timer', 'sorted_active') attribute look like
If there are no active timers (as there would be on startup, it returns a list that only outputs [].
If there are active timers, it looks something like this:
https://pastebin.ubuntu.com/p/KD4y6hXqmT/
Template wizards - how would you create a template sensor to show the one latest updated value of either sensor X or sensor Y? Ie the template sensor is equal to X or Y, depending on which was last updated. Thanks!
I got some help from the folks here when I first built the template for the friendly name (help = someone basically wrote it for me) and I remember that we discovered the output was oddly formatted - a constraint of the Alexa Media Player custom component.
based on that data, I have no idea how your template ever worked.
it's not a string. The template editor is claiming it's a string because the value is JSON. However, it is an object. I.e. you should be searching it like it's an object.
If it helps any, I added the formatting myself for readability. In any case, it did work perfectly until upgrading to 2021.8.0.
I would start with something like {{ (expand("sensor.x","sensor.y") | sort(attribute="last_updated",reverse=true) | first ).name }} if you want the name as a string. No error checking in there, though.
Hey everyone, I'm trying to create a template sensor which subtracts two values, all far so good, but I want to have a condition around it to basically not show any negative values. So a value > 0, it should just return the actual value, otherwise it should return 0, I already created this, but it doesn't work 🙃 :
value_template: >
{%- if '%0.2f' | format(states.sensor.power_consumption.state | float -
states.sensor.power_production.state | float) < 0 -%}
{{ 0 }}
{%- else -%}
{{ '%0.2f' | format(states.sensor.power_consumption.state | float -
states.sensor.power_production.state | float) }}
{%- endif -%}
{% set value = states(sensor.power_consumption)|float - states(sensor.power_production)|float %}
{{ value|round(2) if value > 0 else 0 }}
@rare karma
Thanks! Just tried it but I'm still getting unavailable as state
did you reload templates?
Yes
.share your template definition
Please use https://paste.ubuntu.com/ to share code or logs. Please don't use Pastebin, since it can randomly add spaces to the main view.
- platform: template sensors: grid_consumption_tarif_1_kw: value_template: > {% set value = states(sensor.power_consumption)|float - states(sensor.power_production)|float %} {{ value|round(2) if value > 0 else 0 }} unit_of_measurement: "kW" friendly_name: Grid Consumption Tarif 1 (kW)
Yes it works! 🙂 Thanks!!
Thanks! ...I’m looking for the state of X or Y rather than the name of X or Y… how would that look? Just .state instead of .name?
i posted this in the automations channel, but was encouraged to try here instead... i'm trying to make a POST request to an API after an NFC tag is scanned. the post request should include the tag id that was scanned. can anyone help me complete the automation? here is the full description of what i have so far:
you need to get that tag id from the event and pass it in to your rest_command service call
action:
- service: rest_command.tag_scan_request
data:
tag_id: '{{ template for tag id here }}'
under
> Events you can start listening to your tag_scanned event and see what data you get from it when it fires
why dont you try it
@dreamy sinew "you need to get that tag id from the event and pass it in to your rest_command service call"
that's the part i'm not sure how to accomplish:
tag_id: '{{ template for tag id here }}'
would it be tag_id: '{{ trigger.event.data.tag_id }}'. that doesn't seem to work
no idea. it would depend on what you actually get when that event fires
do the testing steps i suggested
this is what's shown when i listen to the tag_scanned event:
{
"event_type": "tag_scanned",
"data": {
"tag_id": "1f4f6134-0179-42ff-8e01-ec798bbfdc6d",
"device_id": "67781e32d0764951bb0473397a435a17"
},
"origin": "LOCAL",
"time_fired": "2021-08-05T17:27:15.872087+00:00",
"context": {
...
}
}
first: test the service call with that tag_id populated manually
under developer-tools/service i enter the service and the tag_id as the service data. when i click the Call Service button, nothing happens. am i supposed to see any sort of feedback?
if your rest command is set up correctly it should have made that call
i guess it must not be setup correctly then, since i don't see anything in my API logs for an incoming request, and i don't see any sort of indicator in the service call screen to let me know anything happened. no really sure where to go from here. would there be some sort of logs where i can see if the rest call had an error or anything like that?
the homeassistant.log should
ok, it turns out that i needed to set content_type: 'application/json; charset=utf-8' on the rest_command. not sure what the default content_type is, but setting it to json allowed it to properly go through
thanks for the help @dreamy sinew ! i definitely learned a lot while troubleshooting this
Thanks so much! Works a treat
How do I sum the values from this: {% for payment in state_attr('sensor.something', 'payments') %} {{- payment.amount }} {% endfor %}
probably a combination of filters to get down to the actual values
Before trying to come up with fancy solutions, check the built-in filters.
state_attr(...)|map(attribute='amount')|sum
not sure how that would handle unknown though
Just using | sum gave TypeError: 'float' object is not iterable
because you only have a single number, not a list of numbers
Do it one step at a time. What's the result of {{ state_attr(...)|map(attribute='payments') }}?
Right
that error says you are still doing stuff other than what i pasted 😉
Ah, not payments 😄
Yeah, what you pasted seems to work. 🙂
it'll crash if you ever get "unknown" for that state_attr() call but should work most of the time
Even simpler... you can use |sum(attribute="something") per https://jinja.palletsprojects.com/en/3.0.x/templates/#jinja-filters.sum
I have sensor showing all entities with state unavailable or unknown :
{{ states | selectattr("state", "in", ["unavailable", "unknown"]) | map(attribute="entity_id") | list | join(", ") }}
That works fine, but now I would really like to use the new device template function to show the device name of the entities instead of the entity id.
It was easy to do it for a single entity: {{ device_entities(device_id("binary_sensor.altandorr")) }}
But is it possble to do it in a list? Preferably any device name only show up once in the list, but that may be next step. Any tips?
device_id(entity_id) returns the device ID for a given entity ID. Can also be used as a filter
Use it as a filter against the list you're already returning.
I guess that's the correct terminology for what I want, yes.
I know about "learn a man to fish", but I can't spend that much time on learning something I only need for a very specific thing in Home Assistant, so I'd appreciate an example to get going, thanks.
but you have an example yourself... you just need to take those 2 templates and combine them.
I tried, but haven't succeeded so far
and what have you tried?
I tried by inserting the new template like this {{ states | selectattr("state", "in", ["unavailable", "unknown"]) | device_attr(device_id('map(attribute="entity_id")'), "name") | list | join(", ") }}, but I don't get the syntax, so it was mostly a wild guess
well, see if you spent time learning what the selectattr and map can do, you wouldn't be in this situation
that whole teach a man to fish really comes in handy with templates instead of being a copy/paste monkey
you have to iterate through the entities using states | selectattr
Well, you are absolutely correct, but I can't spend that much time on this nice to have thing.
So thanks, but without an actual solution, I don't think I'll solve it.
have you ever iterated through anything?
spoiler: I've helped you in the past and the answer is yes
Let's say I often solve things by being a copy/paste monkey. So I may have, but I probably didn't know about it.
well, you've used a for loop, so this is nothing new and it's very basic.
I guess you'll have to keep asking, because you've been here a long time and this is something you should be able to do by now.
i'll give you a hint:
{% for x in <ILL LET YOU FILL THIS OUT %}
{% endfor %}
Thanks, I'll give a try some night.
Is there a way to get the name of the area to which the entity is assigned?
For example, sensor.1234_temperature belongs to the device X which is assigned to area Kitchen. How to get the name Kitchen using a template?
2021.8.2 supposedly brings package support for top level integration template: but I can not get it to work. see https://community.home-assistant.io/t/template-in-package-still-not-possible-or-user-error/327541 Did I make a mistake?
How do i add the values of two sensors together? I have this but it just results in the value of '+'
tautulli_count_direct_play_and_direct_stream: friendly_name: 'Direct Play and Direct Stream Count' value_template: '{{ states.sensor.tautulli.attributes.direct_plays }} + {{ states.sensor.tautulli.attributes.direct_streams }}'
Put it in one template: {{ states.sensor.tautulli.attributes.direct_plays + states.sensor.tautulli.attributes.direct_streams }}
Better would be{{ state_attr('sensor.tautulli', 'direct_plays') + state_attr('sensor.tautulli', 'direct_streams') }}
Depending on the attribute you might need to convert them to a number using | int or | float
Getting an error message on the second part of what you wrote
expected <block end>, but found '<scalar>'
I don't have these sensors of course, but this works for me (result is 0) {{ state_attr('sensor.tautulli', 'direct_plays')|int + state_attr('sensor.tautulli', 'direct_streams')|int }}
How does the entire template look?
That is the entire template
If it's complaining about blocks vs scalars, that's a problem with your YAML rather than with the template. You either haven't correnctly surrounded your template with quotes or you're trying to use a multiline template without telling the YAML to expect multiple lines.
ok then i'm missunderstanding something. my code right now looks like this:
tautulli_count_direct_play_and_direct_stream: friendly_name: 'Direct Play and Direct Stream Count' value_template: '{{ state_attr('sensor.tautulli', 'direct_plays')|int + state_attr('sensor.tautulli', 'direct_streams')|int }}'
Given your first example had singles quotes around it and TheFes' suggestion has single quotes within it... you need to mix your quotes.
Thx @ivory delta, i got the code to compile by removing the inner qoutes but the result is NaN and not 0 so something seems wrong anyways.
You need the inner quotes. You need the outer quotes. They can't be the same style.
If you have a template like this, HA will stop at the second quote and the rest of the line will be gibberish:
value_template: '{{ state_attr('sensor.tautulli', 'direct_plays') }}'
start ^ end ^
^...............wtf?................^
Aha. So how do I solve that?
value_template: "{{ state_attr('sensor.tautulli', 'direct_plays') }}"
start ^ end ^```
you need to mix your quotes
So use " at start and beginning?
Remember computers take things literally. You and I both know what you meant with the quotes... but the computer just tries to match the first pair it finds.
Yeah I mean it's obvious when you show it like that. I'll try with ".
yeah but the programer in me should have realized that
Eh, don't feel bad. I'm a dev too and I still make stupid mistakes. The good news is that I'm down to only a dozen stupid mistakes per day now.
How do I avoid floating point errors when using decimals i.e. {{ 0.1694 | float / 100 }} gives me 0.16949999999999998
Round the number to the desired number of decimal places as your last operation.
You can't avoid floating point math, you have to make the output sane.
Thanks
When dividing I should use ceil as the round method right? as the float will always be less than actual value
I don't know about 'always'. There are times where the floating point values can be bigger than the original.
Use whatever gives the values you expect.
with {{ 0.1694 | float / 100 }} I would at least expect something close to 0.001694 and not something really close to the original value
I assumed that was just a mistake in their hand typed example.
looking at the template guide I have to nest if statements to get stuff like if sensor1=on and sensor2=off, is this true?
anyone know how to expand an attribute on a state
I wish to loop through an attribute that is an array on a state and filter out some of them
Is it an array or just an array-like structure (like a comma-separated list)?
Then it doesn't need 'expanding', just work with it. There are Jinja filters for, well, filtering.
There are many examples of that
The various select/reject ones, depending on what you want to do.
Many
ok yeah for loop seems to just work
Here’s an example of grabbing the first one: <#automations-archived message>
how could I create a simulated 4.8kw battery that 'charges' with excess solar energy in HA?
basically to work out if a battery would be worth it using against live data
That... doesn't sound like a template question.
so why would this work:
{{ forecast }}
{% endfor %}
{{state_attr('weather.kbed_daynight', 'forecast') | selectattr('daytime', 'true') }}```
If you're trying to do something with the new energy feature, you want #energy-archived
why would the for loop work but not the one outside for loop
the last line there produces an error
What error?
<generator object select_or_reject at 0x7f881bcf0dd0>
That's not an error. That's a generator object... you need to do something with it. In this case, pass it to the | list filter.
ah that works thanks
I didnt know energy existed, thanks
Think of generators like a 'list in progress'. If you want the human readable format, you have to explicitly call list.
ok kind of like an enumerator object in code
Exactly, which is why for x in y worked.
for the selectattr thing is there any way to get the first one always even if it fails the selectattr
so could I get the first result of the array and then use the check on all the subsequent ones
Not in the same expression
No? Not even with | default?
could I join them back up into a single list
{{state_attr('weather.kbed_daynight', 'forecast') | selectattr('daytime', 'true') | list | default(state_attr('weather.kbed_daynight', 'forecast')[0]) }} or something like it
You could repeat the expression with [0] and [1:]
Ah, my idea won't work against an empty array 😢
yeah that doesn't work
I could make it separate statements but I need to then add them back together
Try this:
{{ list or state_attr('weather.kbed_daynight', 'forecast')[0] }}```
Should work against an empty array, I think.
You can make it a one-liner but it'd be a looooong line.
Probably shouldn’t call it list
the or doesn't work
Does it give an error?
no it just doesn't show the first item
I want to always have the first item
regardless of daytime thing
You need another expression
then for all others after first item I check daytime
{{ [4,5,6] or [1,2,3] }} yields [4,5,6]```
So the 'or' works.
well yes but I am looking for this
Do whatever you want to get a 'default' last, but the 'or' works.
[1,2,4]```
Ok, so it's this: #templates-archived message
Stitch them together. Grab the first, them perform your filter on the remainder.
Assign the generator to a variable and do that
how would I stitch them together
With a +
Once you grab the first, it’s probably stripped off and you can just proceed to filter the list normally
The magic of generators
{% set myweather = state_attr('weather.kbed_daynight', 'forecast')[1:] | selectattr('daytime', 'true') | list %}
{{ state_attr('weather.kbed_daynight', 'forecast')[0] | list + myweather }}
this does not appear to work
the first item is not added
I turned the first item into a list and then tried to add it to myweather
Does the first part of the expression work? Return the first item?
myweather returns a valid list
ok
so the first part {{ state_attr('weather.kbed_daynight', 'forecast')[0] | list }} is broken
Yeah, you can't get it to turn an item into a list with that filter. It only works one way - generator to list.
that worked I think
{{ [state_attr('weather.kbed_daynight', 'forecast')[0]] + myweather }}```
appears to work
how to check if the all lights in array turned on?
I want to have a logic, on button press, if all 7 lights are turned on, then turn off all except first light. If the first light only turned on, then turn on second. If first and the second turned on, then turn on third, and so on
Hi guys! Quick question. Is creating a sensor template the only way to use an attribute in the frontend?
Or can I do something like this: weather.mytown.temperature to retrieve the temperature attribute from weather.mytown?
There's about 902347802985092384 posts on the forum with a solution that hasn't changed in 3 years
you can't use templates in the frontend unless you use a custom card that allows you to extract a template. Also, some cards allow you to enter the attribute you want to display. So, there are ways to display attributes, but it depends on what card you're using.
This is my question posted on community forum..I am looking to avoid multiple if else statements if possible
What have you tried?
my response is in the thread
Thabks @mighty ledge ! It works like a charm!
I'll mark it as the solution then
@charred dagger - Earlier this year, you raised https://github.com/home-assistant/core/pull/45090 to expose Area information in Templates. That PR went stale and nothing seemed to come from it. Did you have any other discussions that shut that request down? I have a number of automations that could be simplified with access to this information. Given the recent addition of Device info in the templating engine, I'm wondering if we can drum up interest in exposing this other area of 'hidden' data?
How did you manage to ping me withing 30 seconds of me first getting back to my computer after three days away?
It's those hidden cameras.
lol....not intentional!
I haven't looked at that for a while, but I think I heard about something like it when I listened to the last podcast. Something about Devices in templates or something. So maybe parts of it has been added to 21.8 already?
I'm not keeping up at the moment
Devices were just exposed in 21.8....it's just Areas that remain hidden.
At least a lot of the work should be done then. Areas are pretty much exactly the same thing as devices as far as entities are concerned - but twice.
As a workaround, you can always set custom attributes on things instead of assigning them to areas, then something like this works:
{{ states | selectattr('attributes.room', 'equalto', 'study') | map(attribute='name') | join(',')}}
Hopefully gives you a way to achieve whatever you think any future area functions might expose.
Yes, I do do some of that today, it just seems inefficient to duplicate area/location data. It should really be a 'single source' attribute.
Agreed. And one day, hopefully more work will be done with Areas. Like Thomas said, I would imagine there's a lot of overlap with the Devices work that just released, so it shouldn't be a huge thing to add Area functions... but it still depends on someone taking the time to write the code for it.
Good to hear that it is similarly architected. If there wasn't an explicit reason why the old PR never advanced, maybe we can get some support for this.
@ornate ruin , as developer of the Device templates, do you have any thoughts on the feasibility of extending templates to Areas as well?
People are going to love being tagged 🤔
Not a bad idea. It would be pretty easy to use the device templates code as a reference to add this if someone is interested in contributing. And re: the tag it would’ve been more annoying if it was buried, which happens way too often
Thank you for the feedback! Glad the tag wasn’t offensive, it wasn’t intended that way. As you mentioned, I was afraid the direct question might otherwise get buried.
Hi All. I have searched and searched for this so hoping somebody can assist. I'm looking to create a template that returns the date and time a person was last at home. I tried using last_changed/last_updated but these get reset when HA restarts.
If you want that information to survive a restart, you'll probably want to save the values to an input helper.
hi , after adding additional sensors to that are using a rest API i am starting to get a NaN state
this is a manual line in the config file . works fine with 3 sensors for that rest API but after that its starts to radomly produce the NaN
Template variable error: 'dict object' has no attribute 'channel' when rendering '{{ (value_json.channel.last_values|from_json).field3.value|round()|float }}'
Do those fields exist in the response?
yes it works fine until i start to add more than 3 sensors for that api platform
It sounds like the response is different
it might be to do with the number of request per minute
with the restfull api can you set the refresh intervals
Run a curl test and see
curl test? .. 🙂
okay will do
its very odd , but i do think it has to do with the requests per channel per minute
Hi, I have this trigger to go off when having been true for 15 mins, https://paste.ubuntu.com/p/xXDgcZqNrS/. Problem is, it doesn't always fire. I then immediately after I notice check it in DevTools, and so far it has always evaluated to true... Perhaps this template is too elaborate? Thoughts?
it is overly complicated. Stuff like this doesn't need to be that complicated: states('weather.home') in ['cloudy']
it would work, it's just weird
you have a lot of unnecessary parentheses
something like this:
value_template: >-
{% set mapping = {"sunny": 40, "partlycloudy": 75, "cloudy": 65, "rainy": 65} %}
{{ states('sensor.avg_illumination')|int < mapping[states('weather.home')] and states('sensor.period_of_day') != 'morning' and is_state('input_boolean.luxcontrol', 'on') }}
something like that, at least
Yes, I guess I confused it a bit. Your example looks really good, will try it out! Thanks! 🙂
The only reason that it wouldn't trigger is if it momentarily became false. You could write an automation to catch that
maybe the lux level moves around
Yes, I suspect that is what happens really. I have actually tried writing such automation, but triggered it on same lux template... Better would be as a timer triggered when last change of state?
just use the same template with no for: and create a persistent_notification when it changes state
I will try it out. The mapping above is really interesting too, will make more use of that. Thanks for the help! 🙂
it's a dict
When using a trigger with value_template like this```
trigger:
- platform: template
value_template: >-
{% set mapping = {"sunny": 40, "partlycloudy": 75, "cloudy": 65, "rainy": 65} %}
{{ states('sensor.avg_illumination')|int < mapping[states('weather.home')]
and states('sensor.period_of_day') != 'morning'
and is_state('input_boolean.luxcontrol', 'on') }}
It returns `true`, but is it somehow possible to also read out what actually set it off? The individual parameters? Or will that need another automation/script to catch?
You would have to break it down a little bit. Perhaps move your mapping to a template sensor, and then in your automation use a numeric state trigger, moving your "and" stuff to conditions... assuming that's ok with your logic. You may have to create other triggers when those states change value, just to be sure you catch every case.
Hi, I'm trying to template a MQTT cover's tilt integer output to one of two string values for a RF code transmitter
`
- platform: mqtt
name: "Livingroom blinds"
command_topic: cmnd/rf_bridge/RfRaw
tilt_command_topic: cmnd/rf_bridge/RfRaw
qos: 0
retain: true
optimistic: true
tilt_optimistic: true
payload_open: AAA8060501B32E051155
payload_close: AAB037063012CA05D2015402DA00E61E50581A3A3A3A3A3A3A3B2B2A3B2B2A3A3B2B2A3A3B2C3B2B2B2C3C3C3A3A3A3B2A3B2A3B2A3B2A3B2A3B55
payload_stop: AAA8060501B32E055555
tilt_min: 0
tilt_max: 100
tilt_command_template: >-
{% if state_attr(entity_id, "current_tilt_position") | float > 50 %}
AAA8060501B32E055555
{% else %}
AAA8060501B32E051155
{% endif %}
`
I'd expect that requesting a tilt value in the range of 0..100 would get me either of the two strings output, depending on whether it was above or below 50.
but the integer is just passed onto the RF transmitter, not the code string that I need
Am I missing something with templating an int to a string for a command topic here?
What does that template give in Dev Tools > Templates?
Either of the two "AAA...." strings, as expected
one thing I've never understood, is the ">" ">-" or "|-" after the colon on the _template: line
is there a difference in intepreting those?
They're to do with multiline content. Explanation here: https://yaml-multiline.info/
I don't see anything unusual about your config. The template itself seems fine - maybe someone in #integrations-archived knows more about the MQTT Cover integration itself.
Ah, I see. Well, atm this will need a bigger restructuring (which will happen eventually) and I will keep this as a note until then, thanks! 🙂
Thanks @ivory delta for the sanity check, I'll keep digging
I get an error after adding a condition to this automation. Says mapping values are not allowed. While I understand what it says, is this really right? https://paste.ubuntu.com/p/fSfcqRzqWg/
What's the full error message?
Error loading /config/configuration.yaml: mapping values are not allowed here in "/config/automations/common/lux_low.yaml", line 28, column 19
line 28 corresponds to the added condition
Ok. That's not a problem with your template, nor with the 'mapping' variable you set in there.
That's basic YAML formatting problems.
.yaml
Bot's sleeping 😢
Thank you. I do have issues with learning all syntaxes, but will keep trying... 👍
Hi, I remembered that I cant ass for entitiy_id: an template object like this
so my question is how to do this in this or similar way?
I want to catch the entitiy_id from my trigger, and that entitiy_id to turn off
I obviously was wrong. It works 🙂
If in doubt, try it. If still in doubt, read the docs.
Could someone help with this, config check says its fine but it generates an error in log
`template:
-
sensor:
name: 'Home Storage Battery'
unit_of_measurement: 'W'
state: >
{% if (sensor.battery_daily > 0.48) %}
{% set discharge = states('sensor.grid_import') | float %}
{% else %}
{% set discharge = 0 %}
{% if (sensor.battery_daily = 4.8) %}
{% set charge = 0 %}
{% else %}
{% set charge = states('sensor.energy_export') | float %}{{ ((charge - discharge)) | round(1) }} `
What is the error?
Replace your = with == I'm your if checks
= is for assignment
== is for "is equal to"
And... sensor.battery_daily? Use the states function.
You know it exists, you're using it in other parts of the same template.
Thanks
I'm sorry I don't understand
{% if (sensor.battery_daily > 0.48) %}
states('sensor.grid_import')
One of those is a valid way of getting the current state of an entity. The other is not.
Don't you need to close the if with endif as well?
Probably... but they still haven't shared the error, so no point wasting too much energy on them.
The error has gone now I've fixed the syntax
@lime grove posted a code wall, it is moved here --> https://paste.ubuntu.com/p/2XrZGXCj8D/
but sensor.home_storage_battery no longer contains data
i just see unavailable now in lovelace
So your template is still wrong. Test it in Dev Tools > Templates, and adjust it until it gives what you want.
{{ states('sensor.{{ states('sensor.user') }}') }}
Returns the following error:
TemplateSyntaxError: expected token ',', got 'sensor'
What am I doing wrong?
You’re nesting templates
that's not a thing
{{ states('sensor.' ~ states('sensor.user')) }}
May I know where this is mentioned in the docs?
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find the docs at https://www.home-assistant.io/docs/automation/templating/ - and don't forget rule #1! Please use https://www.hastebin.com/ or https://paste.ubuntu.com/ to share code or logs
No, the tilde notation.
+ seems to do the same als ~ (at least in this case). What is the difference?
~ concatenates numbers too. + adds numbers and generates an error if you try to concatenate numbers and strings.
~ treats both objects to strings before concatenating them.
Hi, I'm using a custom card to control a cover and I need to read an attribute value of the cover itself to call the service set_cover_position. The name of the attribute is "core:Memorized1PositionState". Everything else in this custom button card works (open and close and sliderservice) but when I call this service it gives the error: " expected int for dictionary value @thorny snowta['position'] ".
Could someone help with this problem?
var pos = entity.attributes[attrname];
Thanks! that worked
are the new style template sensors not appropriate for some uses?
I was having a strange issue which has been rectified by switching back to the value template one
bascially feeding a wattage to the sensor, then into an integration sensor and finally a utility_meter, clicking on the sensor just showed it as a history graph rather than a graph
and it was causing issues with utility meter recording incorrect data
you didn't specify a unit_of_measurement. What's funny is that the old method feeds data directly into the new configuration. So, you're still using the same code.
or you didn't specify a device_class
i did specify a unit of measurement but admittedly not a device class
History graphs only work off unit_of_measurement. If that’s not specified and a unit less value gets into the database, you’ll run into issues.
If they ever show up as text instead of a graph, you started the sensor at some point without unit_of_measurement or device_class
This is the case for all sensors, not just templates
Ah
Is that valid? I mean i know it's not but idk what is not valid about this
template:
- sensor:
friendly_name: "Server Cost"
unit_of_measurement: "PLN"
value_template: "{ { (states('sensor.server') | float * 0.6 | round(2) } }"
you're rounding 0.6, to start
it might not like all the spaces
value_template: "{{ (states('sensor.server') | float * 0.6) | round(2) }}"
you also had an unmatched paren
that was probably it, and just a typo
i don't even see what's not matched
it's still not happy
put it in
-> Templates
I am more confused
about?
whatcha mean by the hammer emote
look on your screen and hit that icon
yeah it doesn't even show up in devtools tho
what doesn't show up?
Am i that stupid or idk
then no need
I'm looking at the example "current week" at https://www.home-assistant.io/integrations/history_stats/ and want to change it to current month
end: "{{ now().replace(hour=0, minute=0, second=0) }}"
duration:
days: 30
At least that is my guess
ah
Invalid config for [template]: expected a dictionary @ data['sensor'][0]. Got 's' extra keys not allowed @ data['friendly_name']. Got 'Server Cost' extra keys not allowed @ data['unit_of_measurement']. Got 'PLN' extra keys not allowed @ data['value_template']. Got "{{ (states('sensor.server') | float * 0.6) | round(2) }}". (See /config/configuration.yaml, line 52).```
right
it's from the shelly integration
or are you asking me about something completly different
that's not correct
check the docs
see the example here: https://www.home-assistant.io/integrations/template/#state-based-template-sensors
dis better? https://ptero.co/ixaqogusej.cpp
you have some weird hybrid between the old and new formats, and still some issues
no, see the example again
Here is my history stats: https://www.hastebin.com/ugokojudes.yaml
there are at least 10 different examples and yet none of them seam to fit what i want to achieve... thus i went ahead and asked here
the very first one
compare:
template:
- sensor:
- name: "Average temperature"
unit_of_measurement: "°C"
state: >
{% set bedroom = states('sensor.bedroom_temperature') | float %}
{% set kitchen = states('sensor.kitchen_temperature') | float %}
{{ ((bedroom + kitchen) / 2) | round(1) }}
{% set bedroom = states('sensor.bedroom_temperature') | float %}
{% set kitchen = states('sensor.kitchen_temperature') | float %}
{{ ((bedroom + kitchen) / 2) | round(1) }}```
what is all this
doesn't look like this:
template:
- sensor:
name: "Server Cost"
unit_of_measurement: "PLN"
state: "{{ (states('sensor.server') | float * 0.6) | round(2) }}"
like I said, only a few lines
you mean that i am missing a single dash
and indentation
and just a general lack of attention to detail
YAML requires that attention
I hope that my formatter takes care of that
Last week i ran it as first day of the week. Tonight i changed it to a static date as start and i thought it worked but now i see that it didn't update all day
sorry for being a js programmer who doesn't care about indents cuz i just save and it's done
if you don't pay attention to it, learn it, and understand it, you're going to have a bad time
ah. i just had to restart HA
i tried with a reload of history stats entities. Thank you @inner mesa
forecast:
- detailed_description: ''
temperature: 86
How do I get at the inner temperature?
I am trying {{ state_attr('weather.kntu_hourly', 'forecast.[0].temperature') }}
I'm guessing from your fragment, but state_attr("foo.bar", "forecast")[0].temperature
that was a bit a of a mess 🙂
consider what you're doing there, in sequence - 1) extract attribute 2) grab first element in the list, 3) extract the value of the key you care about
or i'll get pissed at myself and the fact that i can't make it work ending up giving up on the solution so I kindly ask. Can you just tell me the solution instead of making me struggle to understand how someone out there made this configuration file integrate into the python backed? As much as i love this platform i do hate some of the solutions. Because by all means all other sensors have it formatted
- type: id
stuff
and apparently in template its different for whatever reason....
sigh
sorry kinda hate not getting straight answers
ok 🤷
It makes sense like that Rob, thanks!
so thanks for all the help. Did find that typo....
Hi all, I was hoping for some help with how to format a counter automation. (ie when I get a notification, I want to increase or decrease the counter set value) I haven’t been able to find detailed information on this subject. Any help would be appreciated. Thanks
More of an #automations-archived thing
I am using rest platform to collect some data from an api, but I need to refresh my token sometimes. I've created a own sensor for the token. But i cant get it to work.
- platform: rest
resource: https://api.xxxxxxxxxxxxx
name: ElectricVehicleCharger
scan_interval: 60
value_template: '1' #Avoid 255 err msg
headers:
authorization: !secret tibber_header
#authorization: "{{ states_attr('sensor.ElectricVehicleCharger_token', 'accessToken' }}"
I would like to use the comment out line, but it just throws me an error. How could I solve this? thanks
What error?
You can't template headers
How would i create a temperature sensor that displayes the average of several other sensors. If i just add the temperatures together and divide by number of sensors that wouldn't work if one or more sensors were offline right? Is there a way to fix that?
Use this integration instead of a template: https://www.home-assistant.io/integrations/min_max/
awesome i'll try it! Thx
how would i use it if one of my "sennsors" is a aircon and not a temp-sensor?
You would have to create a template sensor from the climate attribute.
alright! thanks!
I thought the same, but if he has to create a template sensor for that attribute, he can also just calculate the average in a template sensor right 🙂
Just because I'm also trying to make use of templates more and more, I came up with this to get the average and make sure unavailable or other unwanted states are not used in the average
{% set sensors = [1, 2.3, 3.5, 'test', 4.7] %}
{% set ns = namespace(avg_list = []) %}
{% for sensor in sensors %}
{% set ns.avg_list = ns.avg_list + [ sensor ] | list if sensor is number else ns.avg_list %}
{% endfor %}
{{ (ns.avg_list | sum / ns.avg_list | count) | round(2) }}
I guess the upside is that if the aircon goes down or something the minmax sensor won't use that value? If i do it manually and one sensor goes down the values will be wweird
replace the values in the list to define sensors with the sensors you want to use (so e.g. [ states('sensor.something'), state_attr('sensor.foo', 'bar'), states('sensor.yolo') ])
But is there any upside to using yours @marble jackal rather than the built in minmax?
Not really, but I thought as you will have to create a template sensor anyway for the attribute, why not use a template sensor for the calculation itself 🙂
Especially if you want to use more attributes, as you would have to create a template sensor for each of them
Makes sense
i have this in a template sensor:
{% set sensors = [
states('sensor.living_room_temperature')|float,
states('sensor.office_temperature')|float,
states('sensor.thermostat_temperature')|float
]
%}
{{(sensors|sum / sensors|reject("eq", 0.0)|list|length)|round(1)}}```
could go further and make a group out of them though
{{ (sensors|sum / sensors|reject("eq", 0.0)|list|length)|round(1) }}```
but since you need the attribute of something you couldn't use that trick so just list them out in the first example
add state_attr('climate.whatever', 'whatever')|float
But that gives an error for the sensors in my example, because I have the string 'test' in my list (to test how to exclude results like 'unavailable')
you need to map everything to a float
yes, I just had the lightbulb moment
which will change "test" to 0.0
yep, that was the 2nd part I did not understand, and then suddenly did 🙂
{% set sensors = []|map('float') %}
you'll have to do that anyway since anything coming out of states() will be a string
yep, there were a lot of lightbulbs above my head all of the sudden 😉
haha
only thing is that there could be a sensor which is already 0.0, which you might want to include in your average
But if the temperature of on of the rooms in your home is 0.0 degrees, you will have bigger problems probably
{% set sensors = [states(), state_attr()]|reject('in', ['unavailable', 'unknown'])|map('float')|list %}
most likely
which is why i didn't bother
lots of ways to skin that cat
Had another small lightbulb moment (something else I learned today)
This also works:
{% set sensors = [
'1' | float('no number'),
'2.3' | float('no number'),
'3.5' | float('no number'),
'test' | float('no number'),
'4.7' | float('no number')
] | reject('eq', 'no number') | list
%}
{{ (sensors | sum / sensors | count) | round(1) }}
posted in #automations-archived already, but this seems more template related:
i'm trying to use a variables dict with integer keys, but it seems they're always treated as strings
i have an event that sends an integer payload, and that payload never matches with:
variables:
codes:
1398067: button_1_on
and ```yaml
condition:
- "{{ trigger.event.data.code in codes }}"
is there a way to debug the typing in the automation?
maybe try |float(-1) and |reject('lt', 0)
its probably always a string for yaml reasons.
i've tried to concatenate the event data with an empty string, or pass it through a |string filter, but no luck
i'm also assuming this is the problem, which it may not be
e.g., this doesn't help:
condition: >
{{ (trigger.event.data.code in codes) or
(trigger.event.data.code|string in codes) }}
for context, here's the event data as shown in the automation trace:
trigger:
platform: event
event:
event_type: esphome.rf_code_received
data:
code: '1398076'
{{ code in codes or '{}'.format(code) in codes }}``` maybe?
oh, you're going the wrong direction then
code|int in codes
oh weird, casting to int makes it pass the condition
good call
yay, that fixed it 🎉
condition: "{{ trigger.event.data.code|int in codes }}"
action:
- variables:
code: "{{ codes[trigger.event.data.code|int] }}"```
it's confusing as the variable dict in the trace quoted the keys which implied to me they would be strings
well the int converts it to a int from a string
yes, but this seemed backwards to me. from the automation trace output:
codes:
'1398067': button_1_on
vs the declaration:
variables:
codes:
1398067: button_1_on
whenever you create yaml, typing is preserved. If you use an int anywhere, it will be an int in yaml.
that's why we have to quote things in order to keep them strings
I asked a question in #frontend-archived yesterday regarding calculating time until the next (set time) trigger of an automation. I am currently trying to do just that in a template, using {% set time_remaining = as_timestamp(next_sunrise) - as_timestamp(now()) %}. This gives me the correct value in seconds, however I would like to display this as hours and minutes, how does one do this?
You can do something like this: https://community.home-assistant.io/t/convert-seconds-to-days-hours-minutes/23152/18?u=mono
Ah great, thanks!
Read the full thread to understand what they're doing, that's only a part of the solution.
But basically, lots of math.
here's an out of the box solution, just change the calc in up_time
https://community.home-assistant.io/t/uptime-no-longer-working/256600/64
goes up to weeks
would it be possible to as_datetime() both of those and then get a timedelta object out of them?
yah, just change the up_time line to
{%- set up_time = (now() - as_datetime(states('sensor.hassio_drifttid_dagar'))).seconds %}
unless you really want the timedelta
I'm sure it could have been done easier with a time delta, I think it didn't exist in templates when I made that
yeah, that and as_datetime() are both new
but this on my system:
{{ as_datetime(states.sun.sun.attributes.next_rising) - now() }} -> ```14:17:29.194920
yeah, it just wouldn't handle weeks but it would probably shrink it down.
it would count it in days
just depends on how pretty you want it
so the only benefit that my template provides is that you can delete a line and it will treat that as the 'highest number'
there's also |relative_time but that only works for things in the past
like, if I delete days and hours then replace the denominator with 1, you'll get endless hours and everything else will be formatted correcdtly
which is kinda annoying
ya
and it's not translated
which is dumb
that template is an 'all in one' kinda template
I just copy/paste it now when I need it
It does have 1 bug that I'm too lazy to fix
but you'll only reach it when you get to years
ah, looks like it only does a days difference
{{ now() + timedelta(days=2000) - as_datetime(state_attr('sun.sun', 'next_rising')) }} -> ```1999 days, 10:48:08.038924
anyway. fun diversion
days in a year can be too arbitrary sometimes so it makes sense that the computers just go "f-it"
This works perfectly for my usecase, however I would like to display the end result as xx:xx:xx.
I have changed it to:
phrase('', 60*60, 24),
phrase('', 60),
phrase('', 1, 60)
] | select('!=','') | list %}
Next sundown:
{{ values | join(':') }}
Which shows: xx :xx :xx, any idea what is wrong?
If that's all you want you should just use the timedelta that @dreamy sinew posted
You mean this one right?
{{ now() + timedelta(days=2000) - as_datetime(state_attr('sun.sun', 'next_rising')) }}
now() - as_datetime(state_attr('sun.sun', 'next_setting'))
{%- set up_time = (now() - as_datetime(state_attr('sun.sun', 'next_setting'))).seconds %}
{%- macro phrase(name, divisor, mod=None) %}
{%- set value = ((up_time // divisor) % (mod if mod else divisor)) | int %}
{{- '{}{}'.format(value, name) if value | int > 0 else '' }}
{%- endmacro %}
{%- set values = [
phrase('', 60*60, 24),
phrase('', 60),
phrase('', 1, 60)
] | select('!=','') | list %}
{{ values | join(':') }}
if you really want to use what I wrote
I would prefer the shortest one, so I am trying this:
{{ now() - as_datetime(state_attr('automation.sundown_for_zeus', 'last_triggered')) }}
But that throws:
TypeError: argument 1 must be str, not datetime.datetime
because it's already a datetime
remove the as_datetime
but that will error if you restart
so you could also just do | string between the last 2 ))
{% set next_setting = as_datetime(state_attr('sun.sun', 'next_setting')) %}
{{ meow - next_setting if next_setting > meow else 'its in the past' }}```
😄
Doesn't next setting change to tomorrow?
since that attr is already a datetime just drop the as_datetime() from it
on restart it populates with a string tho
lame
yup
Yes that works, but I had to put now() at the end. Now the outcome of {{ as_datetime(state_attr('automation.sundown_for_zeus', 'last_triggered') | string) - now() + timedelta(days=1) }} = 9:38:59.094569. Can I remove anything after the seconds?
split on the period and select the first item
Btw, I know my calculation is funny to say the least, but it works hehe
- sensor:
- name: "light"
state: >
{% if is_state('light.canvas_fa77', 'off') %} not_bright {% elif state_attr('light.canvas_fa77', 'rgb_color')[0],[255],[0] %} test {% elif state_attr('light.canvas_fa77', 'rgb_color')[255],[0],[0] %} bright {% else %} off {% endif %} ```
something something Schrödinger’s cat
got it now like that got no errors but the colors dont work, when itz off it says not_bright but when i make it red or blue or green itz always test
Almost there I think: UndefinedError: 'datetime.timedelta object' has no attribute 'replace'
put it on now()
put it on both
now and the as_datetime
TypeError: 'microseconds' is an invalid keyword argument for replace(). I should to it like now().replace(microseconds=0) right?
it might be microsecond without the s
Ah haha
it's one or the other
Yes that's absolutely perfect! Thanks so much
You too @dreamy sinew!
Also, keep in mind... You'll be some microseconds off.. so is it really the correct sunset time?
i'm just screwing with you
hmm, can you round a datetime? 🤔
Well it shows when the lights for my pet reptile turn on/off, both he and I don't mind about microseconds 😄
Maybe not when he's cold. When he's warmer, he'll think faster.
Even when he is warm he is surprisingly slow (it's a bearded dragon)
{% elif state_attr('light.canvas_fa77', 'rgb_color')[255, 0, 0] %} bright ist this hte right format in that case for the rgb values?
I don't know what that is
looks like you're trying to dereference the attribute in some weird, broken way 🙂
presumably you're trying to compare the attribute to that list?
What is the value of {{ state_attr('light.canvas_fa77', 'rgb_color') }}?
basicly i want that when my light canvas turns to rgb 255,0,0 that then the template switch to bright
Turns out I am not done 😄
This is the end result: {% set next_sunrise = as_datetime(state_attr('automation.sundown_for_zeus', 'last_triggered').replace(microsecond=0) | string) - now().replace(microsecond=0) + timedelta(days=1) %}
That shows the seconds always as 00. Can I remove the seconds from the outcome?
Ok but... #templates-archived message
the value is the color in rgb format, or what you mean ?
Share the value.