#templates-archived

1 messages · Page 131 of 1

mighty ledge
#

So if you want all of yesterday, you’d start at midnight 2 days ago and end at midnight today

#

When you use end now, your saying that the end of the dataset should be right this second

edgy umbra
#

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.

ivory delta
#

Why would you want a month to start on a Monday? That would be quite rare...

edgy umbra
#

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.

ivory delta
#

What's wrong with the 'today' sensor you have now?

edgy umbra
#

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.

ivory delta
#

ends at the time I made the sensor
What? 🤔

edgy umbra
#

Ok I did miss understood it I gues. 😁

ivory delta
#

Forget the config. Does it do what you want?

edgy umbra
#

I think it do’s but I’m not sure if it start and ends at the hours I want. 🙂

ivory delta
#

Go check if it works. There's no point asking people to solve problems that don't exist.

edgy umbra
#

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. 🙂

ivory delta
#

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...

edgy umbra
#

Ok that’s clear enough, thanks for your time. 🙂

peak juniper
#

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

ivory delta
#

however, I want to ADD to the value every time.
What do you mean?

peak juniper
#

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:

  1. 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)
  2. 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

ivory delta
#

Oh... you're nesting templates. You can't have templates within templates.

peak juniper
#

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?

ivory delta
#

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.

peak juniper
#

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

ivory delta
#

You were close. You just needed to nest things properly.

teal leaf
#

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

ivory delta
#

And the likely answer is: no

teal leaf
marble jackal
#

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?

pastel moon
#

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/

inner mesa
#

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

marble jackal
#

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') }}"
pastel moon
#

Thanks guys! I have probably copy/pasted something and got it where it does not belong. Second one in conditions from now on then 🙂

marble jackal
#

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']
        }}
pastel moon
#

Thanks, but I think I will use the 2nd style. I sometimes over-complicate stuff sometimes... Simple is better where possible 🙂

marble jackal
#

thanks!

mighty ledge
#

Strings are iterable so check not string too

marble jackal
#

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!

mighty ledge
#

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

pastel moon
finite stump
#

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

mighty ledge
mighty ledge
#

everything under the hood is utc

#

the timestamp is not incorrect

finite stump
mighty ledge
#

what are you trying to do? You typically don't need to convert anything unless you're trying to perform math

mighty ledge
finite stump
mighty ledge
#

as I said, the likely hood of you needing to convert it is low

#

so please. Say what you are using the timestamp for.

finite stump
finite stump
mighty ledge
#
  1. You should never use states.xxx.xxx. It's not safe during startup. Use expand.
  2. You don't need to loop. Use filters, like selectattr and map.
  3. convert to a timestamp then to local
finite stump
mighty ledge
#

check the template in developer tools

#

don't need to reboot either unless you're using the new template integration

mighty ledge
finite stump
silent barnBOT
mighty ledge
# silent barn

The template I provided should work out of the box without alteration.

#

are you aware that last changed will change upon restart?

finite stump
# mighty ledge The template I provided should work out of the box without alteration.

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

mighty ledge
finite stump
#

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 }}

mighty ledge
#

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.

finite stump
#

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

mighty ledge
#

why are you using last_changed there

#

is last_changed the state?

finite stump
#

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

finite stump
#

want to know when the last change occured in house

mighty ledge
#

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

finite stump
#

in the sensor section actually....

mighty ledge
#

Ok, so then it's not binary

#

binary sensor is on/off

finite stump
#

well it is, but i am wrong

#

it's a knx sensor sending a binary

#

put the template in the sensor section although

mighty ledge
#

so you're saying 'sensor.home_last_presence' is binary?

finite stump
#

no i guess i will put it in the binary_sensor section

mighty ledge
#

No!

#

It's not binary.

#

but you're setting the state to a local timestamp

finite stump
#

ok now following you

mighty ledge
#

I can tell

#

sensor.home_last_presence's state is a local timestamp, correct?

#

the answer is yes or no

finite stump
#

yes

mighty ledge
#

Ok, so then why aren't you getting the state in your notification

finite stump
#

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

mighty ledge
#

how do you get a state from an entity_id?

#

spoiler: You're already using it

finite stump
#

let me try one sec

mighty ledge
#

hint2: You're even using it in the same notification template...

finite stump
#

ok .state

#

uff works

#

🙂

#

Thanks for beeing educational 🙂

mighty ledge
#

fyi, you should switch thoes to states('sensor.xxx') instead of using states.xxx.state

#

np

finite stump
#

ok will try that immediately too

finite stump
pastel moon
#

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...

mighty ledge
pastel moon
mighty ledge
#

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') }}
pastel moon
#

Yes, will do. I have added it in most places I do this, but not this one yet, obviously... 🙂 Thanks!

mighty ledge
#

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') }}
pastel moon
#

I simply set it in the var declaration as time_on: "{{ time_on | default('00:02:00') }}"

mighty ledge
#

that also works

#

you'll have to use a different var name though

#

in your template

#

you can't replace input variables using variables

pastel moon
#

Yes, I did change those to avoid conflict, Thanks for your help! Much to learn (and remember) 🙂

marble jackal
#

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 🙂

dreamy sinew
#

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 ^

marble jackal
#

Thanks a lot, I will give it a try 🙂

mighty ledge
#
set entities = state_attr('group.xyz','entity_id') | select('in', entity_list) | list
dreamy sinew
#

wouldn't that check to see if the full set is in the list?

mighty ledge
#

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

dreamy sinew
#

he wants the group names of groups that contain entities in a list

mighty ledge
#

ah, so I am

dreamy sinew
#

so sadly still need loops

mighty ledge
#

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

dreamy sinew
#

yeah, expand() "helps" too much here and jumps straight to the entities

mighty ledge
#

interesting situation

#

would be nice for a recursive flag

#

expand(.... , recursive=False)

dreamy sinew
#

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

mighty ledge
#

reverse it with search

#

well, no, you're right

#

you know about the new search/match?

dreamy sinew
#

that's another limitation that annoys me 😛

mighty ledge
#

they are new tests

#

only for HA

dreamy sinew
#

yeah, i've used them a couple of times. regex is generally "slow" though so i try to avoid it

mighty ledge
#

still won't work, but very useful

dreamy sinew
#

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?"

mighty ledge
#

Ya

#

I went through my templates thinking I would need to use them

#

but turns out I don't have any templates that complex

dreamy sinew
#

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

mighty ledge
#

so it was a "oh hey, lets delete that"

dreamy sinew
#

heh that'll do it

final parcel
#

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.

ivory delta
#

Does it always follow the same structure? The brackets and percentage are always there, and there's always a number in there?

inner mesa
final parcel
#

will check the strucutre

#

Where can I find the documetnattion for split function pls? I am maybe really blind.

ivory delta
#

It's Python.

final parcel
#

Thanks RobC!

#

oh! I searched for Jinja

inner mesa
#

applying a regex would be easy, but I don't think you can do that in Jinja

ivory delta
#

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.

inner mesa
#

Jinja uses Python data types, and you get the methods on those types for free

final parcel
#

Thank you guys!

final parcel
#

Do you know what is minimum scan interval of sensors and if it can be below 1 sec ?

inner mesa
#

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?)

wicked smelt
#

- 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?

dreamy sinew
#

probably but why?

wicked smelt
#

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

lost wyvern
#
- 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.

thorny snow
#

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) }}"
inner mesa
#

add a unit_of_measurement: xxx

thorny snow
#

where do i add that?

inner mesa
#

that's a template sensor definition, right?

thorny snow
#

yeah

thorny snow
#

oh okay, goes on its own line within the sensor

#

will give it a go 😄

silent barnBOT
lost wyvern
#

Oops. Adjusting my question.

silent barnBOT
#

@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.

median mason
#

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?

inner mesa
#

10 days from now, or from that uptime sensor?

final parcel
final parcel
#

I will move it to the PI in future after I figure it how i can do so

lost wyvern
dreamy sinew
#

with a simple test in the template tester it is working for me

lost wyvern
#

It worked for me too, but not with the json_attributes / trying to define multiple sensors

dreamy sinew
#

that's not something i've really messed with so i'm not sure

median mason
# inner mesa 10 days from now, or from that uptime sensor?

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

dreamy sinew
#

what is the output of sensor.time_date ?

median mason
dreamy sinew
#

{{states('sensor.time_date')}}

#

the literal output

median mason
dreamy sinew
#

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

median mason
silent barnBOT
dreamy sinew
#

then you can do as_timestamp(states('sensor.date_time_iso')) + timedelta(days=10)

lost wyvern
#

Is there a faster way to reload my REST sensor entity/template than restarting HA core?

inner mesa
#

the REST sensor is its own integration, so unless there's an entry in configuration -> Server Controls, no. I don't have one to confirm

mighty ledge
#

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

inner mesa
#

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

mighty ledge
#

🤷‍♂️

#

I would assume the service

#

but I made a custom integration that has a reload service and it's not showing up

inner mesa
#

I figured that it was just for Core integrations, but evidently not

mighty ledge
#

Oh wait, it does

#

so, all you need is to subscribe to the reload service and it'll show up

inner mesa
#

cool

mighty ledge
#

so, if it can, it'll be in that area

inner mesa
#

I don't maintain anything with a YAML config, but good to know

mighty ledge
#

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

inner mesa
#

so this?

#
    hass.services.async_register(
        domain=DOMAIN, service=SERVICE_RELOAD, service_func=async_reload_config_entries
    )
mighty ledge
#

No, that's for the non-yaml

#

lemme find it

inner mesa
#

ah, indeed

mighty ledge
#
    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

median mason
mighty ledge
#

he meant as_datetime

median mason
# mighty ledge 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!

mighty ledge
#

days=10 is what you should have

#

if you have uptime in seconds or something do seconds=

median mason
#

output of sensor.intel_nuc5i3_system_uptime is 10:05:39:32.

mighty ledge
#

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) }}
median mason
mighty ledge
#

then change it to .split

median mason
# mighty ledge 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

lost wyvern
median mason
#

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

median mason
#

thanks, just added device_class: timestamp and it's exactly what I wanted now.

bright quarry
#
  - 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?
lost wyvern
#

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.

thorny snow
#

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

marble jackal
#

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

marble jackal
#

I found I could use .index but there could be cases where my search value is not in the list

mighty ledge
marble jackal
#

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

dreamy sinew
#

|first

#

will always return the first one

#

nvm i like that workaround

wintry needle
#

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.

silent barnBOT
inner mesa
#

What’s wrong?

supple sparrow
finite stump
supple sparrow
#

These filters are a very powerful thing

finite stump
#

yes, build one to get the max actual temp in my house from all sensors, luckily managed to get that one to work

#

brb

dreamy sinew
#

max() is a thing

marble jackal
tepid agate
#

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

fossil venture
#

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"
finite stump
# dreamy sinew `max()` is a thing

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 }}

tepid agate
#

ah, ok so i did do it right, but messed up calling the service i think

finite stump
#

but it works

fossil venture
finite stump
dreamy sinew
#

drop that last set and just put it in the output line

marble jackal
#

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)

dreamy sinew
#

yup, handled that in the thread

finite stump
naive wagon
# inner mesa What’s wrong?

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.

inner mesa
#

You can test your template in devtools -> Templates

marble jackal
#

Ah, threads.. still need to get used to that :)

finite stump
dreamy sinew
#

yeah, that one is pretty great

trail estuary
#

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....

inner mesa
#

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') %}

trail estuary
#

Let me try....

inner mesa
#

{{ "foo-bar".startswith("foo") and "foo-bar".endswith("bar") }}

#

true

trail estuary
#

Yeah, that makes sense! Thanks! 🙏
I seem to often know where I wanna end up (good in itself) but not how to get there.... 😊

trail estuary
#

Is there a way I can template a timestamp that always is one second into the current day?

inner mesa
#

{{ now().replace(hour=0, minute=0, second=1) }}

#

as a timestamp: {{ as_timestamp(now().replace(hour=0, minute=0, second=1))|int }}

trail estuary
#

Let me see if this actually works.... 🙂

#

Is only the last template actually a timestamp?

inner mesa
#

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

trail estuary
#

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... 😉

inner mesa
#

what's not working about it?

trail estuary
#

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.

inner mesa
#

you don't have state_class: measurement

trail estuary
#

No I don't!!

#

🤦‍♂️

#

And then it was bliss! 🙂

#

Thanks for all the help! 😉

frigid marsh
#

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 }}

inner mesa
#

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 }}

frigid marsh
low blaze
#

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

inner mesa
#

Yes, they’re all separate

unreal merlin
#

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

ivory delta
#

You'd expand the group to get at the individual entities. Search the history of this channel for examples.

unreal merlin
#

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

ivory delta
#

You don't... you'd use a template trigger...

unreal merlin
#

oic, cool, thanks mono

trail estuary
wet lodge
#

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?

inner mesa
#

what are you getting in devtools -> Templates?

wet lodge
#

It works fine there.... Gives me the expected 00:00:00.

inner mesa
#

so what's wrong?

#

I can't pick out the issue if you only provide the part that's working 🙂

wet lodge
marble jackal
#

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

floral blaze
#

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!

ivory delta
#

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.

floral blaze
#

ill head over there

inner mesa
wet lodge
#

Thanks. I’ll give that a try.

hollow girder
#

is it possible to do somting like.

{% for a in states.area %}
  {{a}}
{% endfor %}

loop by all the areas?

inner mesa
#

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

wet lodge
#

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.

inner mesa
#

Unless I missed it, you still haven’t shared your sensor definition. Like I said, sharing the part that works isn’t that helpful

wet lodge
#

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.

inner mesa
#

np. If you can stick the template in devtools -> Templates and it works, then the problem is either elsewhere or simply timing

wet lodge
#

Looks like it may be timing.

inner mesa
#

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] }}"
wet lodge
#

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?

inner mesa
#

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

wet lodge
inner mesa
#

they're just an example of how I'm guarding against uninitialized states

#

adapt as needed

#

@wet lodge

wet lodge
#

I'll see what I can do with that. Thanks!

inner mesa
#

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

wet lodge
#

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.

inner mesa
#

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

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!

supple sparrow
#

@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.

mighty ledge
#

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()

mighty ledge
wet lodge
#

No errors in my config.

mighty ledge
wet lodge
rocky vector
#

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!

wet lodge
mighty ledge
#

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.

wet lodge
#

If it helps any, I added the formatting myself for readability. In any case, it did work perfectly until upgrading to 2021.8.0.

supple sparrow
rare karma
#

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 -%}

dreamy sinew
#
{% set value = states(sensor.power_consumption)|float - states(sensor.power_production)|float %}
{{ value|round(2) if value > 0 else 0 }}
#

@rare karma

rare karma
#

Thanks! Just tried it but I'm still getting unavailable as state

dreamy sinew
#

did you reload templates?

rare karma
#

Yes

dreamy sinew
#

.share your template definition

silent barnBOT
#

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.

rare karma
#

- 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)

dreamy sinew
#

oops, wrap both the entity_ids in ''

#

... states('sensor...ption')|float ...

rare karma
#

Yes it works! 🙂 Thanks!!

rocky vector
unkempt bolt
#

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:

https://paste.ubuntu.com/p/gXvgD5PrQ4/

dreamy sinew
#

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 devtools > Events you can start listening to your tag_scanned event and see what data you get from it when it fires

unkempt bolt
#

@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

dreamy sinew
#

no idea. it would depend on what you actually get when that event fires

#

do the testing steps i suggested

unkempt bolt
#

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": {
        ...
    }
}
dreamy sinew
#

first: test the service call with that tag_id populated manually

unkempt bolt
#

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?

dreamy sinew
#

if your rest command is set up correctly it should have made that call

unkempt bolt
#

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?

dreamy sinew
#

the homeassistant.log should

unkempt bolt
#

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

distant plover
#

How do I sum the values from this: {% for payment in state_attr('sensor.something', 'payments') %} {{- payment.amount }} {% endfor %}

dreamy sinew
#

probably a combination of filters to get down to the actual values

ivory delta
#

Before trying to come up with fancy solutions, check the built-in filters.

dreamy sinew
#

state_attr(...)|map(attribute='amount')|sum

#

not sure how that would handle unknown though

distant plover
#

Just using | sum gave TypeError: 'float' object is not iterable

dreamy sinew
#

because you only have a single number, not a list of numbers

ivory delta
#

Do it one step at a time. What's the result of {{ state_attr(...)|map(attribute='payments') }}?

distant plover
#

Right

dreamy sinew
#

that error says you are still doing stuff other than what i pasted 😉

ivory delta
#

Ah, not payments 😄

distant plover
#

Yeah, what you pasted seems to work. 🙂

dreamy sinew
#

it'll crash if you ever get "unknown" for that state_attr() call but should work most of the time

supple sparrow
waxen rune
#

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?

ivory delta
#

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.

waxen rune
#

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.

mighty ledge
waxen rune
#

I tried, but haven't succeeded so far

mighty ledge
#

and what have you tried?

waxen rune
#

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

mighty ledge
#

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

waxen rune
#

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.

mighty ledge
#

have you ever iterated through anything?

#

spoiler: I've helped you in the past and the answer is yes

waxen rune
#

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.

mighty ledge
#

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 %}
waxen rune
#

Thanks, I'll give a try some night.

frank tulip
#

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?

floral shuttle
half pendant
#

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 }}'

marble jackal
#

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

half pendant
marble jackal
#

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 }}

half pendant
ivory delta
#

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.

half pendant
#

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 }}'

ivory delta
#

Given your first example had singles quotes around it and TheFes' suggestion has single quotes within it... you need to mix your quotes.

half pendant
#

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.

ivory delta
#

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?................^
half pendant
#

Aha. So how do I solve that?

ivory delta
#
value_template: "{{ state_attr('sensor.tautulli', 'direct_plays') }}"
          start ^                                               end ^```
#

you need to mix your quotes

half pendant
#

So use " at start and beginning?

ivory delta
#

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.

half pendant
#

Yeah I mean it's obvious when you show it like that. I'll try with ".

ivory delta
#

It's only obvious once you know 😄

#

We all made the same mistakes in the beginning.

half pendant
#

yeah but the programer in me should have realized that

ivory delta
#

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.

winged dirge
#

How do I avoid floating point errors when using decimals i.e. {{ 0.1694 | float / 100 }} gives me 0.16949999999999998

ivory delta
#

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.

winged dirge
#

Thanks

#

When dividing I should use ceil as the round method right? as the float will always be less than actual value

ivory delta
#

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.

marble jackal
#

with {{ 0.1694 | float / 100 }} I would at least expect something close to 0.001694 and not something really close to the original value

ivory delta
#

I assumed that was just a mistake in their hand typed example.

unborn glade
#

looking at the template guide I have to nest if statements to get stuff like if sensor1=on and sensor2=off, is this true?

ivory delta
#

Not nested, chained.

#

Something along the lines of {{ a == 'on' and b == 'off' }}

prisma valley
#

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

ivory delta
#

Is it an array or just an array-like structure (like a comma-separated list)?

prisma valley
#

it is an array

#

its a forecast on a weather entity

ivory delta
#

Then it doesn't need 'expanding', just work with it. There are Jinja filters for, well, filtering.

inner mesa
#

There are many examples of that

ivory delta
#

The various select/reject ones, depending on what you want to do.

inner mesa
#

Many

prisma valley
#

ok yeah for loop seems to just work

ivory delta
#

You don't want a loop... you want filters.

inner mesa
lime grove
#

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

ivory delta
#

That... doesn't sound like a template question.

prisma valley
#

so why would this work:

 {{ forecast }}
{% endfor %}
{{state_attr('weather.kbed_daynight', 'forecast') | selectattr('daytime', 'true') }}```
ivory delta
#

If you're trying to do something with the new energy feature, you want #energy-archived

prisma valley
#

why would the for loop work but not the one outside for loop

#

the last line there produces an error

ivory delta
#

What error?

prisma valley
#

<generator object select_or_reject at 0x7f881bcf0dd0>

ivory delta
#

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.

prisma valley
#

ah that works thanks

lime grove
ivory delta
#

Think of generators like a 'list in progress'. If you want the human readable format, you have to explicitly call list.

prisma valley
#

ok kind of like an enumerator object in code

ivory delta
#

Exactly, which is why for x in y worked.

prisma valley
#

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

inner mesa
#

Not in the same expression

ivory delta
#

No? Not even with | default?

prisma valley
#

could I join them back up into a single list

ivory delta
#

{{state_attr('weather.kbed_daynight', 'forecast') | selectattr('daytime', 'true') | list | default(state_attr('weather.kbed_daynight', 'forecast')[0]) }} or something like it

inner mesa
#

You could repeat the expression with [0] and [1:]

ivory delta
#

Ah, my idea won't work against an empty array 😢

prisma valley
#

yeah that doesn't work

#

I could make it separate statements but I need to then add them back together

ivory delta
#

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.

inner mesa
#

Probably shouldn’t call it list

prisma valley
#

the or doesn't work

ivory delta
#

Does it give an error?

prisma valley
#

no it just doesn't show the first item

#

I want to always have the first item

#

regardless of daytime thing

inner mesa
#

You need another expression

prisma valley
#

then for all others after first item I check daytime

ivory delta
#
{{ [4,5,6] or [1,2,3] }} yields [4,5,6]```
So the 'or' works.
prisma valley
#

well yes but I am looking for this

ivory delta
#

Do whatever you want to get a 'default' last, but the 'or' works.

prisma valley
#
[1,2,4]```
ivory delta
#

Stitch them together. Grab the first, them perform your filter on the remainder.

inner mesa
#

Assign the generator to a variable and do that

prisma valley
#

how would I stitch them together

ivory delta
#

With a +

inner mesa
#

Once you grab the first, it’s probably stripped off and you can just proceed to filter the list normally

#

The magic of generators

prisma valley
#
{% 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

inner mesa
#

Does the first part of the expression work? Return the first item?

prisma valley
#

myweather returns a valid list

#

ok

#

so the first part {{ state_attr('weather.kbed_daynight', 'forecast')[0] | list }} is broken

inner mesa
#

Try [] around it

#

Rather than a list filter

ivory delta
#

Yeah, you can't get it to turn an item into a list with that filter. It only works one way - generator to list.

prisma valley
#

that worked I think

#
{{ [state_attr('weather.kbed_daynight', 'forecast')[0]] + myweather }}```
#

appears to work

sonic nimbus
#

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

main steppe
#

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?

mighty ledge
sonic nimbus
#

Yeah I found it. Thanks

#

But I have other problem

mighty ledge
sonic nimbus
#

This is my question posted on community forum..I am looking to avoid multiple if else statements if possible

ivory delta
#

What have you tried?

sonic nimbus
#

Thabks @mighty ledge ! It works like a charm!

mighty ledge
#

I'll mark it as the solution then

stuck grail
#

@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?

charred dagger
#

How did you manage to ping me withing 30 seconds of me first getting back to my computer after three days away?

ivory delta
#

It's those hidden cameras.

stuck grail
#

lol....not intentional!

charred dagger
#

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

stuck grail
#

Devices were just exposed in 21.8....it's just Areas that remain hidden.

charred dagger
#

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.

ivory delta
#

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.

stuck grail
#

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.

ivory delta
#

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.

stuck grail
#

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?

ivory delta
#

People are going to love being tagged 🤔

ornate ruin
#

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

stuck grail
#

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.

tired frost
#

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.

ivory delta
#

If you want that information to survive a restart, you'll probably want to save the values to an input helper.

candid iron
#

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 }}'

inner mesa
#

Do those fields exist in the response?

candid iron
#

yes it works fine until i start to add more than 3 sensors for that api platform

inner mesa
#

It sounds like the response is different

candid iron
#

it might be to do with the number of request per minute

#

with the restfull api can you set the refresh intervals

inner mesa
#

Run a curl test and see

candid iron
#

curl test? .. 🙂

inner mesa
#

curl is a command line utility

#

You could Google how to use it

candid iron
#

okay will do

#

its very odd , but i do think it has to do with the requests per channel per minute

pastel moon
#

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?

inner mesa
#

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

pastel moon
#

Yes, I guess I confused it a bit. Your example looks really good, will try it out! Thanks! 🙂

inner mesa
#

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

pastel moon
#

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?

inner mesa
#

just use the same template with no for: and create a persistent_notification when it changes state

pastel moon
#

I will try it out. The mapping above is really interesting too, will make more use of that. Thanks for the help! 🙂

inner mesa
#

it's a dict

pastel moon
#

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?
supple sparrow
atomic dust
#

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?

ivory delta
#

What does that template give in Dev Tools > Templates?

atomic dust
#

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?

ivory delta
#

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.

pastel moon
atomic dust
pastel moon
ivory delta
#

What's the full error message?

pastel moon
#

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

ivory delta
#

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 😢

#

YAML is the mark up language used by Home Assistant, consistent indenting (two spaces per level) is key. Here is a primer, and this explains multi-line templates. For validating YAML see YAML Lint.

pastel moon
#

Thank you. I do have issues with learning all syntaxes, but will keep trying... 👍

sonic nimbus
#

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

sonic nimbus
#

I obviously was wrong. It works 🙂

ivory delta
#

If in doubt, try it. If still in doubt, read the docs.

lime grove
#

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) }}   `
    
dreamy sinew
#

What is the error?

#

Replace your = with == I'm your if checks

#

= is for assignment
== is for "is equal to"

ivory delta
#

And... sensor.battery_daily? Use the states function.

#

You know it exists, you're using it in other parts of the same template.

lime grove
ivory delta
#

{% 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.

waxen rune
#

Don't you need to close the if with endif as well?

ivory delta
#

Probably... but they still haven't shared the error, so no point wasting too much energy on them.

lime grove
#

The error has gone now I've fixed the syntax

silent barnBOT
lime grove
#

but sensor.home_storage_battery no longer contains data

#

i just see unavailable now in lovelace

ivory delta
#

So your template is still wrong. Test it in Dev Tools > Templates, and adjust it until it gives what you want.

lime grove
#

I think I've fixed it

#

using Dev Tools, so thanks

unreal salmon
#

{{ states('sensor.{{ states('sensor.user') }}') }}

Returns the following error:
TemplateSyntaxError: expected token ',', got 'sensor'

What am I doing wrong?

inner mesa
#

You’re nesting templates

#

that's not a thing

#

{{ states('sensor.' ~ states('sensor.user')) }}

unreal salmon
inner mesa
#

Not to nest templates?

#

It’s just the way jinja works. You’re already in a template

silent barnBOT
inner mesa
#

It’s probably more correct to say you don’t nest expressions

unreal salmon
marble jackal
#

+ seems to do the same als ~ (at least in this case). What is the difference?

fossil venture
#

~ concatenates numbers too. + adds numbers and generates an error if you try to concatenate numbers and strings.

mighty ledge
#

~ treats both objects to strings before concatenating them.

vernal jasper
#

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?

mighty ledge
vernal jasper
#

Thanks! that worked

lime grove
#

are the new style template sensors not appropriate for some uses?

lime grove
#

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

mighty ledge
#

or you didn't specify a device_class

lime grove
#

i did specify a unit of measurement but admittedly not a device class

mighty ledge
#

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

lime grove
#

Ah

vital comet
#

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) } }"
inner mesa
#

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

vital comet
#

i don't even see what's not matched

inner mesa
#

"{ { (s

#

where's the matching one?

vital comet
#

it's still not happy

inner mesa
#

put it in devtools -> Templates

vital comet
#

I am more confused

inner mesa
#

about?

vital comet
#

whatcha mean by the hammer emote

inner mesa
#

look on your screen and hit that icon

vital comet
#

yeah it doesn't even show up in devtools tho

inner mesa
#

what doesn't show up?

vital comet
#

Am i that stupid or idk

inner mesa
#

click "Template"

#

paste your template somewhere there, see what it says

vital comet
#

can't post an image

#

but it's happy

inner mesa
#

then no need

reef onyx
vital comet
#
end: "{{ now().replace(hour=0, minute=0, second=0) }}"
duration:
  days: 30

At least that is my guess

inner mesa
#

{{ now().replace(day=1, hour=0, minute=0, second=0) }}

#

use that as the start

reef onyx
#

ah

vital comet
#
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

inner mesa
#

your formatting is messed up

#

share your sensor config

vital comet
#

it's from the shelly integration

#

or are you asking me about something completly different

inner mesa
#

the template sensor that it's complaining about

#

the one that's producing the error

vital comet
inner mesa
#

that's not correct

#

check the docs

vital comet
inner mesa
#

you have some weird hybrid between the old and new formats, and still some issues

#

no, see the example again

vital comet
#

how about this

inner mesa
#

you really need to walk through the example carefully

#

it's only a few lines

reef onyx
vital comet
#

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

inner mesa
#

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) }}
vital comet
#
          {% set bedroom = states('sensor.bedroom_temperature') | float %}
          {% set kitchen = states('sensor.kitchen_temperature') | float %}

          {{ ((bedroom + kitchen) / 2) | round(1) }}```
#

what is all this

inner mesa
#

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

vital comet
#

you mean that i am missing a single dash

inner mesa
#

and indentation

#

and just a general lack of attention to detail

#

YAML requires that attention

vital comet
#

I hope that my formatter takes care of that

reef onyx
#

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

vital comet
#

sorry for being a js programmer who doesn't care about indents cuz i just save and it's done

inner mesa
#

if you don't pay attention to it, learn it, and understand it, you're going to have a bad time

reef onyx
#

ah. i just had to restart HA

#

i tried with a reload of history stats entities. Thank you @inner mesa

thorny snow
#
forecast:
  - detailed_description: ''
    temperature: 86
#

How do I get at the inner temperature?

#

I am trying {{ state_attr('weather.kntu_hourly', 'forecast.[0].temperature') }}

inner mesa
#

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

vital comet
# inner mesa if you don't pay attention to it, learn it, and understand it, you're going to h...

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....

inner mesa
#

sigh

vital comet
#

sorry kinda hate not getting straight answers

inner mesa
#

ok 🤷

thorny snow
#

It makes sense like that Rob, thanks!

vital comet
#

so thanks for all the help. Did find that typo....

vast thistle
#

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

dreamy sinew
wicked smelt
#

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

inner mesa
#

What error?

half pendant
#

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?

fossil venture
half pendant
#

awesome i'll try it! Thx

#

how would i use it if one of my "sennsors" is a aircon and not a temp-sensor?

fossil venture
#

You would have to create a template sensor from the climate attribute.

half pendant
#

alright! thanks!

marble jackal
#

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 🙂

marble jackal
#

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) }}
half pendant
#

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

marble jackal
#

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') ])

half pendant
#

But is there any upside to using yours @marble jackal rather than the built in minmax?

marble jackal
#

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

half pendant
#

Makes sense

dreamy sinew
#

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

marble jackal
#

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')

dreamy sinew
#

you need to map everything to a float

marble jackal
#

yes, I just had the lightbulb moment

dreamy sinew
#

which will change "test" to 0.0

marble jackal
#

yep, that was the 2nd part I did not understand, and then suddenly did 🙂

dreamy sinew
#

{% set sensors = []|map('float') %}

#

you'll have to do that anyway since anything coming out of states() will be a string

marble jackal
#

yep, there were a lot of lightbulbs above my head all of the sudden 😉

dreamy sinew
#

haha

marble jackal
#

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

dreamy sinew
#

{% 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

marble jackal
#

as always 🙂

#

Thanks for the lesson 🙂

marble jackal
#

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) }}
marble needle
#

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?

dreamy sinew
dreamy sinew
marble needle
#

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'
dreamy sinew
#
{{ code in codes or '{}'.format(code) in codes }}``` maybe?
#

oh, you're going the wrong direction then

#

code|int in codes

marble needle
#

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

mighty ledge
marble needle
#

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
mighty ledge
#

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

gritty charm
#

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?

ivory delta
gritty charm
#

Ah great, thanks!

ivory delta
#

Read the full thread to understand what they're doing, that's only a part of the solution.

#

But basically, lots of math.

mighty ledge
#

goes up to weeks

dreamy sinew
#

would it be possible to as_datetime() both of those and then get a timedelta object out of them?

mighty ledge
#

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

dreamy sinew
#

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

mighty ledge
#

yeah, it just wouldn't handle weeks but it would probably shrink it down.

dreamy sinew
#

it would count it in days

mighty ledge
#

split on space, colon, and period

#

map to int

dreamy sinew
#

just depends on how pretty you want it

mighty ledge
#

so the only benefit that my template provides is that you can delete a line and it will treat that as the 'highest number'

dreamy sinew
#

there's also |relative_time but that only works for things in the past

mighty ledge
#

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

dreamy sinew
#

which is kinda annoying

mighty ledge
#

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

dreamy sinew
#

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

mighty ledge
#

makes sense

#

C# does it that way too

dreamy sinew
#

days in a year can be too arbitrary sometimes so it makes sense that the computers just go "f-it"

gritty charm
mighty ledge
gritty charm
mighty ledge
#
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

gritty charm
mighty ledge
#

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 ))

dreamy sinew
#
{% set next_setting = as_datetime(state_attr('sun.sun', 'next_setting')) %}
{{ meow - next_setting if next_setting > meow else 'its in the past' }}```
#

😄

mighty ledge
#

Doesn't next setting change to tomorrow?

dreamy sinew
#

shh

#

(probably)

mighty ledge
#

I don't remember

#

I remember a HUGE discussion about it

dreamy sinew
#

since that attr is already a datetime just drop the as_datetime() from it

mighty ledge
#

on restart it populates with a string tho

dreamy sinew
#

lame

mighty ledge
#

yup

dreamy sinew
#

but then as_datetime() on it would still fail

#

meh, could add handling on it

gritty charm
mighty ledge
#

split on the period and select the first item

gritty charm
#

Btw, I know my calculation is funny to say the least, but it works hehe

mighty ledge
#

or you can .replace(microseconds=0)

#

plenty of crap you can do

cold mica
#
  - 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 %} ```
inner mesa
cold mica
#

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

gritty charm
mighty ledge
#

put it on now()

dreamy sinew
#

put it on both

mighty ledge
#

now and the as_datetime

gritty charm
mighty ledge
#

it might be microsecond without the s

gritty charm
#

Ah haha

mighty ledge
#

it's one or the other

gritty charm
#

You too @dreamy sinew!

mighty ledge
#

Also, keep in mind... You'll be some microseconds off.. so is it really the correct sunset time?

#

i'm just screwing with you

dreamy sinew
#

hmm, can you round a datetime? 🤔

gritty charm
#

Well it shows when the lights for my pet reptile turn on/off, both he and I don't mind about microseconds 😄

ivory delta
#

Maybe not when he's cold. When he's warmer, he'll think faster.

gritty charm
#

Even when he is warm he is surprisingly slow (it's a bearded dragon)

cold mica
#

{% elif state_attr('light.canvas_fa77', 'rgb_color')[255, 0, 0] %} bright ist this hte right format in that case for the rgb values?

inner mesa
#

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?

ivory delta
#

What is the value of {{ state_attr('light.canvas_fa77', 'rgb_color') }}?

cold mica
#

basicly i want that when my light canvas turns to rgb 255,0,0 that then the template switch to bright

gritty charm
#

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?

cold mica
#

the value is the color in rgb format, or what you mean ?

ivory delta
#

Share the value.