#templates-archived

1 messages · Page 75 of 1

inner mesa
#

and that

mighty ledge
#

well... no I think he wants to show C - H

inner mesa
#

I was simply telling you to add quotes in teh first place, and you went with something completely different

mighty ledge
#

so used to that mistake, immediately assumed wanted to subtract

edgy umbra
#

The second one is just a working example, still want to use the first one i posted.

inner mesa
#

then just add quotes around the entity_id

#

simple

edgy umbra
#

This is still not working.

#
          {% if status == "heating" %}
            Hallo;
          {% endif %}```
inner mesa
#

the problem isn't the template

edgy umbra
#

K going to try there

inner mesa
unique turret
#

How would I go abouts adding an else statement showing off when lights are off?

{{ ((state_attr('light.room', 'brightness') / 2.55) | round(0) ~ '%') if is_state('light.room', 'on') }}

frail dagger
#

Wrap it in either a {% if %} or use {{ iif() }} around it.

unique turret
#

I think the same thing can be achieved using else as well?

frail dagger
#

Hold on. Let me get to my PC. Trying to do this mobile sucks. lol

#

Ok... now I can actually see what you're doing... lol (yeah, that didn't work like I thought it would)

haughty breach
#
{{ ((state_attr('light.room', 'brightness') / 2.55) | round(0) | string ~ '%') if is_state('light.room', 'on') else 'off'}}
unique turret
frail dagger
#

Thanks @haughty breach

haughty breach
#

For iif it would be :

{{ iif(is_state('light.room', 'on'), ((state_attr('light.room', 'brightness') / 2.55) | round(0) | string ~ '%'), 'off')}}
marble jackal
#

Alternative

{{ (state_attr('light.room', 'brightness') | default(0, true) / 2.55) | round(0) | default('off', true) }}
#

Although that will also return off when the brightness is set to 1

#

Alternative which avoids that

{{ state_attr('light.room', 'brightness') | multiply(1/2.55, 'off') | round(0, default='off') }}
sacred sparrow
#

In HA dashboard this shows as "Away" {{ states('person.esperance') | title }} but when I put it in a template it says Not_home. Is there a way I can make it show what the dashboard is showing instead of the state?

lofty mason
#

state_translated('person.esperance') should do it.

slate fossil
#

Trying to wrap my head around something. is_state is really just a "condensed" method (function?) of using states(xx.yy) == whatever. state_attr is basically the same concept but with an attribute. And then the same goes for iif; it "condenses" an if statement. They'll all perform their respective tasks but the is_state, state_attr, and iif are a bit easier to read. (I'm slowly starting to understand conditional (ternary) operators; the above examples took me a moment to grasp.)

marble jackal
#

For iif there is also a difference. Both the part for true and false will be rendered. So this can lead to errors.
Example:

{% set x = 'some.entity' %}
{{ iif( x | has_value, x | float * 3, 0) }}
{% set x = 'some.entity' %}
{{ x | float * 3 if x | has_value else 0 }}
#

The first one will give an error when some.entity is unavailable, the second one won't

hexed galleon
#

Quick one that I can't seem to find the answer on - Is it possible to reference a list index of a filter function, not a variable? Found the first function.

#

Template for context: {{ ['media_player.plex_plexamp_neutron_linux','media_player.plex_plexamp_neutron'] | expand | selectattr('state','in',['idle','playing']) | sort(attribute='last_changed',reverse=True) | map(attribute='entity_id') | list }}

slate fossil
#

TheFes I think I gotcha. So for better error handling (when it is needed), states('some.entity') and if (instead of iif) would be a better way to go. (While working on something else, I just noticed there's is_state_attr available, too.)

cloud night
#

Hiiii
So I'm trying to set up an automation based on the result of a template which looks if there are a set of strings in the 'condition' attribute of my weather integration.
I have this:
{{ state_attr('weather.my_location_hourly_forecast', 'forecast')[0:5] | map(attribute='condition') | list | select('equalto', 'clear') | list }}
Which lists off the entries that have 'clear' as a condition, but I need something equivalent to
select('equalto', 'clear' or 'sunny' or 'partlycloudy')
IE I need to have multiple arguments to all produce a result in the list. Any suggestions?

tame axle
#

Approximate RGB value in a template

marble jackal
marble jackal
#

You should use the service call and then use the service response

#

And to answer your actual question, you can use select('in', ['clear', 'sunny', 'partlycloudy'])

dry sierra
#

I'm trying to write a condition template, and I want to check if two datetime objects are more than 5 minutes apart

#

I've got this so far:
{{ utcnow() - states.sensor.niro_ev_19_data.last_updated }}

#

I'm struggling to get the "more than 5 minutes" part though

#

{{ ( utcnow() - states.sensor.niro_ev_19_data.last_updated).total_seconds() > 300 }}
!!

#

OK, I think that does it ☝️

marble jackal
dry sierra
#

If I post
{{ now() - utcnow() }}
in the the Developer Tools > Templates tab I see
-1 day, 23:59:59.999959

#

I expected that to be closer to 0

mighty ledge
dry sierra
#

Or is that a strange serialization saying "negative one day plus 23 hours 59 minutes..."

#

OK, thanks!

#

Sorry, another confusion...

{{ strptime('2024-05-05T09:09:45+00:00', '%Y-%m-%dT%H:%M+00:00') }}
gives
ValueError: Template error: strptime got invalid input '2024-05-05T09:09:45+00:00' when rendering template 'strptime test {{ strptime('2024-05-05T09:09:45+00:00', '%Y-%m-%dT%H:%M+00:00') }}

#

But my template looks like a good match to me :/

inner mesa
#

{{ '2024-05-05T09:09:45+00:00'|as_datetime }}

mighty ledge
#

what rob said, but your format was not correct

#

you're missing seconds

#

if you want to create a datetime object for today at 9:45, use today_at. {{ today_at('9:45') }}

#

@dry sierra ^

dry sierra
#

Thx both - my input string had no seconds, but the as_datetime filter looks easiest - I had tried datetime as a filter, seen it fail and got lost in strptime

cloud night
cloud night
#

Thanks!

sick ice
#
      - condition: and
        conditions:
          - condition: template
            value_template: "{{ trigger.to_state.context.id != none }}"
            alias: context.id not = none
          - condition: template
            value_template: "{{ trigger.to_state.context.user_id == none }}"
            alias: context_user.id = none
          - condition: template
            value_template: "{{ trigger.to_state.context.parent_id == none }}"
            alias: context_parent.id = none
        alias: Test if triggered from a physical wall button press

I'm using the trigger contexts to automate from physical button presses and have just noticed that if I turn a light group (helper) on or off, it registers as a physical button press. Does anyone know how I could filter these out. Is this a bug?

jovial pilot
#

Working on a template that notifies us for the undone chores and then clears the chores without altering the list. Code in the thread

sick ice
languid fern
#

Is it possible to create custom device/entities out of scripts? I have a vent fan that is controlled with IR and have 3 separate scripts to control it. One toggles on and off and the other two are scripts to trigger power up/down. Can I create a custom device/entity, so that when it is opened it contains all the buttons and states I expect to see as you do in other devices "more-info" cards?

lyric comet
jade patio
#

Does anyone know how i can use card_mod to modify the new tables group headers? I am open to other solutions as well that dont envolve card_mod

#

I know the css tag for it is group-header, i added this into my theme:
skynet_theme_v2: card-mod-theme: skynet_theme_v2 card-mod-view: | .group-header { font-weight: 800; font-size: 18px; color: #FFC10A; }

jade patio
vast iris
#

How can I use a template to define how often a button is pressed? It seems that isn't easy possible without a lot of helpers?!
so my template returns a number like 1 or 12 - and I want to push a button 1 or 12 times ...

mighty ledge
#

this will most likely be an automation

#

you need to set a datetime the first time something is pressed, and if you press the button again within a time window, it increments a counter

#

outside the time window, it goes back to 1

#

2 helpers (input_datetime, counter), 1 automation

#

1 template (in the automation)

vast iris
#

so I have a script which is trggered by a cronjob - so every 10 min. My template returns 2 - so I planned to use while count thing and just use the template. But I guess that's not working. So I do need a helper counter?

mighty ledge
#

yes, you need a counter

#

you can attempt to do this all in a single template sensor, but it would be a pita

vast iris
#

hmm I see. I tried to avoid that, since my script already got like 30... but fine

mighty ledge
#

just make a separate automation

#

exactly how I described

#

it does not need to be in your script at all

#

the counter is the entity you use

#

for conditions etc

vast iris
#

right ... I'll try that. Thank you

plucky bison
#

Hello there, I asked this question in the #automations-archived and I was send here to ask. So what I want: I need to detect who (I want user name of the account) did the last change in the HVAC mode. I want to use it in scenario, where I will send notification to the last person that changed the mode. I wasnt able to find anything online 🤷

mighty ledge
#

That will only work if the adjustment is made via the HA ui

#

If that's what you want, you'd need an automation as a base bfore I can give pointers on the template needed to make that happen.

#

or we could just go straight to a script.

lilac anchor
#

having some trouble with making a "sensor" which is reporting uptime in "s" to display in HH:MM:SS. i'm able to add the sensor to a dashboard but when i try to just check the value of the sensor via Developer Tools, the sensor is coming back as "'sensor' is undefined"

https://imgur.com/a/oeTgXIL

inner pagoda
#

if i want to make a template sensor that reports a color (for example, RGB values or XY chromaticity coordinates), does anyone have an idea on how i could report the "state" which consists of a list of several numbers? Or should i do something like split it into multiple numeric sensors, one for each value? (so i'd have separate sensors for color_x and color_y)

lofty mason
#

I really don't think you want uptime sensors to count in seconds, that's just going to thrash your state machine infinitely forever

fallen charm
#

where is it getting the color from?

lofty mason
#

just make it a datetime when it boots, and you can display the relative time since then

lofty mason
#

hm I'm not familiar enough with espresense to say I guess

inner pagoda
#

@fallen charm in this case it's calculated in the template sensor, but i guess the same issue would also apply if someone had a color sensor connected to an esp32 or someting

fallen charm
#

calculated from what?

lofty mason
#

for sensor is undefined it is complaining that you need to put quotes around the sensor name (also use states and not state_attr)

#

for HH:MM:SS display a sensor must be device_class: duration

inner pagoda
#

@fallen charm sun elevation; i found some math that i wanted to try that might let me figure out a color that approximates the color of the sky :)

fallen charm
#

ok. the easy answer is that you could put it into a color format that is a single number, with the easiest but least differentiated being RGB hex

inner pagoda
#

got to that point, then started wondering how to actually report a color that other things could consume, e.g. an automation to set a light. I'd prefer to report xy chromaticity.

fallen charm
#

you're converting to it though anyway, so you could just move the math to where you're using it

#

if you need two numbers to be reported separately, you can do something silly with math and then undo it at the end point, or you can output it in two variables

inner pagoda
#

hmm, so two separate numeric sensors then would probably be easiest. or i suppose I could have the state be some combined representation then put the more useful split values in attributes.

fallen charm
#

or if you want to play with attributes, you could have it do all of the conversions and output them all into attributes

lilac anchor
inner pagoda
#

well, i guess i'll try it with attributes. still need to figure out if i can simplify this calculation enough that it's maintainable as a template; i might end up wanting to turn it into an actual integration instead :)

lilac anchor
#

i might just disable that sensor and just rely on "connected" or not

ember iron
#

Hi, i try to multiply a entity with a helper to get a price in euro as output.
My ha config is splittet into folders, this means i have a sensor folder with .yaml files inside for waste_collection (working fine with different .yaml files).
I have an template folder with a .yaml file for garbage_collect (working fine too).
I added those 2 files in my configuration.yaml with those 2 lines. sensor: !include_dir_list sensor / template: !include_dir_list template. (Seems working).
Now i try to add the following. Now i tried to add a new sensor in my sensor folder.
sensor:

  • platform: template
    sum_of_entities:
    friendly_name: "Daily_Strom_Export_in_Euro"
    unit_of_measurement: "€" # Ersetze "Einheit" durch die entsprechende Einheit
    value_template: "{{ (states('sensor.growatt_today_s_grid_export') | float * states('input_number.aktueller_strompreis_export') | float) | round(2) }}"
    My goal was to get a number as a result.
    When i add this sensor as a new .yaml, and try to check the output in developer tools i get "Konfigurationswarnungen
    Platform error 'sensor' from integration 'daily_export_price' - Integration 'daily_export_price' not found." while i search for "daily_strom" i get no output. Does anyone have an idea ?
    Thank you in advance.
analog mulch
# inner pagoda if i want to make a template sensor that reports a *color* (for example, RGB val...

You can make a template sensor — you trigger off whatever you use as a source, eg solar elevation, in the action part you can perform your calculation and save it into variables. Then you save those variables into the attributes of the sensor. These do not have to be a number, but can even be a dictionary or a list. But… if you are trying to do lights that track the temperature of the light, and get warm at night, check of the adaptive lighting HAVS integration

inner pagoda
#

yeah, i already use adaptive lighting; i want to do something a bit trickier where some lights are based on ambient sky (shadow) light and others on direct sunlight :)

analog mulch
#

Depending on whether the sun is on that side of the house? Interesting…

inner pagoda
#

well, just depending on sun elevation. i haven't considered direction yet, but that could be neat too :)

#

for the sun direct light i'm just using a color temperature, which is fine as a sensor since it's a single number.

analog mulch
#

But adaptive lighting basically computes the temperature curve on the basis of the elevation, at least in the default settings, doesn’t it?

inner pagoda
#

not directly; you set a min and max color temp, and it fades between those based on time of day (so noon is always max color temp regardless of the sun's actual elevation)

#

it does by default use the sun position to determine sunrise, sunset, and solar noon times.

analog mulch
inner pagoda
#

heh. yeah; "blue hour" twilight simulation based on scattered light is a whole other thing :)

#

(in many cases for indoor lighting you wouldn't actually want to simulate that)

analog mulch
#

Are you building a matrix with a fake sky?

inner pagoda
#

nah, i just have a few light strips that i wanted to use to cast an ambient-ish light onto a white ceiling.

#

no idea if it's a good idea or not, but it seems like it could be neat looking

plain magnetBOT
#

@rare karma I converted your message into a file since it's above 15 lines :+1:

spark flicker
#

I have a helper with my cats dates of birth how do I create a sensor to show their age on my dashboard?

turbid crystal
#

Urgh... Message malformed: Expected a dictionary @ data['action'][0]['choose'][2]['conditions'][0]
This means so the first item under action (-> choose) and the third item under choose (so the third - conditions: ...
I can't see how that is different to the others though 😕
https://pastebin.com/57AVh9w2
ARGH, figured it out, it was the indentation of the default keyword... no idea why that would be ['choose'][2] if it counts all options that would be 7, or if it's conditions as one [0] then it should be [1] 🤷‍♂️

cosmic hamlet
#

Can i find out what room a device is in based on the device_id?

haughty breach
#

{{ area_name(device_id) }}

quasi frost
#

i need a template wich indicates if a value of a sensor is greater then a value of a helper. If the value of the sensor is greater, the value of the helper should be refreshed with the value of the Sensor. How can i arange this?

fossil venture
#

That is an automation. Template trigger "{{ states('sensor.foo')|float(0) > states('input_number.bar')|float }}" and in the action use the input number set value service with this for the value "{{ states('sensor.foo') }}"

#

You could also just use a numeric state trigger. It will take the input number entity_id in the above option. However that trigger will not monitor the input number for changes like the template trigger will. So if you change the input number to be below the sensor then only the template trigger will fire immediately. The numeric state trigger will wait until there is a change in the sensor.

quasi frost
#

alright, so i took your example and change the Sensor and input to this: {{ states('sensor.solar_erzeugung_absolut)|float(0) > states('input_number.solar_peak')|float }}

#

is this correct

fossil venture
#

You missed a quote at the end of the sensor.

sacred sparrow
#

I have a sensor that shows the pm2.5 level but I want to make a template sensor that shows the AQI using this: https://cms.iqair.com/sites/default/files/inline-images/AQI-Chart_US.jpg
What would be the easiest way to do something like this:
pm2.5 of 0 is 0 AQI
pm2.5 of 6 is 25 AQI
pm2.5 of 12 is 50 AQI
but all the increments in between that are in that chart?

#

I already have something similar for the text:

        {% set pm25 = states('sensor.view_plus_pm25') | float %}
        {% if pm25 < 12 %}
          Good
        {% elif pm25 < 35.4 %}
          Moderate
        {% elif pm25 < 55.4 %}
          Poor
        {% elif pm25 < 150.4 %}
          Very Poor
        {% elif pm25 < 250.4 %}
          Severe
        {% else %}
          Hazardous
        {% endif %}```
mighty ledge
plain magnetBOT
#

@storm thunder I converted your message into a file since it's above 15 lines :+1:

mighty ledge
#

it's a trigger based template sensor, it won't track changes to any entities, so the message is correct

#

this should be your code too btw, you have a few mistakes

template:
  - trigger:
    - platform: state
      entity_id: sensor.luftsensor_temperatur
      not_to:
        - unavailable
        - unknown
    sensor:
    - name: Luftsensor Temperatur Test
      unique_id: 'LuftsensorTempTest'
      unit_of_measurement: '°C'
      device_class: temperature
      state_class: measurement
      state: >-
        {{trigger.to_state.state}}
storm thunder
#

But anyway if this isn't the right way to track a sensor that's not always online, please guide me to the right direction 🥺

marble jackal
#

This should work, but just a guess, you are pasting that entire code in the GUI for a template helper?

mighty ledge
jagged halo
#

Hi ... i have a problem with utility meter after few days.

#
    - name: consumocasa
      unit_of_measurement: 'kWh'
      state_class: total_increasing
      device_class: 'energy'
      state: >- 
          {% set sunp = states('sensor.shelly_em_channel_1_energy')|float(0) %}
          {% set enelp = states('sensor.shelly_em_channel_2_energy')|float(0) %}
          {% set eneld = states('sensor.shelly_em_channel_2_energy_returned')|float(0) %}
          {{sunp + enelp - eneld}}
        #value_template: "{{ (states('sensor.shelly_em_channel_1_energy') | float) + states('sensor.shelly_em_channel_2_energy') | float) - (states('sensor.shelly_em_channel_2_energy_returned') | float)) | round(2) }}"
      availability: "{{ (states('sensor.shelly_em_channel_1_energy') not in ['unknown', 'unavailable', 'none']) and (states('sensor.shelly_em_channel_1_energy') not in ['unknown', 'unavailable', 'none']) }}"```
#

this template sensor measure the total consuption of my house

#

the daily cycle utility meter that work perfectly for several months stop working

plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

mighty ledge
#

@jagged halo ^

marble jackal
#

Don't forget you can edit your post rather than repeatedly posting the same thing.

jagged halo
#

sorry

mighty ledge
#

backtick

#

`

#

not quote

marble jackal
#

and you can copy the backticks from the bot if you can't find them on your keyboard 🙂

jagged halo
#

i have italian keyboard

mighty ledge
#

Alt Gr + '

#

google is your friend

jagged halo
#

the utility meter count only 'sunp'

#

thanks petro ... excuse me

#

until max a week this worked perfectly

#

Anyone can help me?

mighty ledge
#

what's the problem?

#

if it's not adding the other sensors, make sure they are available

#

your template looks fine

#

sensor.shelly_em_channel_2_energy and sensor.shelly_em_channel_2_energy_returned

#

make sure they are not unavailable

jagged halo
#

worked until the last update

mighty ledge
#

that's great, the problem is not the template

#

the problem is those sensors

#

so, please verify they are still working

jagged halo
#

the three sensor are sunp: solar production, enelp: energy from net, eneld: energy to net. The formula is the total energy consumption on my house

#

the sensor are available

mighty ledge
#

Look up those entity_id's in developer tools -> states page

#

Again, the template is fine. The only thing it can be is those entities

#

either a miss-spelled entity_id or the entities are unavailable

#

there were issues with the shelly integration this past release

marble jackal
#

what does it return if you paste the yaml above in developer tools > template?

jagged halo
#

how i can add a screenshot?

plain magnetBOT
#

@jagged halo Please use imgur or other image sharing web sites, and share the link here.

Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.

jagged halo
#

and not the daily cycle of the formula sunp + enelp - eneld.

storm thunder
mighty ledge
#

no, that whole thing goes in configuration.yaml

marble jackal
storm thunder
#

I see. Thank you!

plain magnetBOT
#

@rare karma I converted your message into a file since it's above 15 lines :+1:

#

@rare karma I converted your message into a file since it's above 15 lines :+1:

rare karma
#

Oh come on

mighty ledge
#

stop posting multiple times

#

we can read the bot

rare karma
#

I can’t even edit it

#

Would be better if I’d have some preview, there is no way I can see if the message comes through properly beforehand

mighty ledge
#

you can expand it

rare karma
#

Not on my phone unfortunately

inner mesa
#

You can always use dpaste or some other site

elder moon
#

good morning all. I cannot find the answer to my question online

#

is there a way of checking in the template an area the entity is assigned to?

elder moon
#

(background - i am using Alarmo as my alarm and want to add a snapshot of CCTV to the alarm notifications, but with a lot of different sensors in different rooms of my house which can trigger an alarm its only feasible to detect which camera i want to snapshot using the area)

elder moon
#

thanks!

devout holly
#

Can I manual run a templete?

plain magnetBOT
#

@devout holly I converted your message into a file since it's above 15 lines :+1:

devout holly
#

can above message be deleted?

#

i figured it out

bleak stream
#

i'm trying to consolidate my battery notification automations using templates, i hope to call something like {{states.sensor.devicename_internal_battery_level}} in place of hard-coded battery percentages, but that's returning way too much info for my needs.. is there a good way to refine the results further? (i tried simply appending .current_capacity but that didn't do it)

lofty mason
silver pewter
#

Hi all, is it possible to add somehow so this template switch always have state off between time 09:00-18:00 ? or is it not possible? 😛

switch:
  - platform: template
    switches:
      motion_lights_on_off_vardagsrum_emby_playing_helper:
        friendly_name: Motion Lights On/Off - Vardagsrum - Emby Playing helper
        value_template: >
          {% if is_state('media_player.emby_shield_tv_valbo', 'playing') and is_state('input_boolean.motion_lights_on_off_vardagsrum', 'on') %}
            off
          {% elif is_state('media_player.emby_shield_tv_valbo', 'playing') and is_state('input_boolean.motion_lights_on_off_vardagsrum', 'off') %}
            off
          {% elif is_state('input_boolean.motion_lights_on_off_vardagsrum', 'off') %}
            off
          {% else %}
            on
          {% endif %}
        turn_on:
        turn_off:
lofty mason
inner mesa
#

I don't see how that's useful for a template switch, though

#

It looks like you just want a template binary_sensor based on what you posted

silver pewter
silver pewter
silver pewter
inner mesa
#

You're doing nothing in the turn_on and turn_off parts. It's a switch that doesn't do anything

silver pewter
#

okok i see 😛

plain magnetBOT
#

@solemn zodiac I converted your message into a file since it's above 15 lines :+1:

uneven pendant
#
{% set incomplete = [] %}
{% set today = now().strftime('%A') | lower %}
{% set array = states.input_boolean|selectattr('entity_id', 'search', today+"_.*_brendyn")|rejectattr('entity_id', 'search', today+"_.*_chore") |rejectattr('state', 'search', 'off') |map(attribute='entity_id') |list %}
  {% for entity in array %}{% set chore = entity+"_chore" %}{% if is_state(chore, 'off') %}{{chore}}{% do incomplete.append(1) %}{% endif %}
{% endfor %}
{{ incomplete[0] }}
#
input_boolean.thursday_teeth_brendyn_chore
input_boolean.thursday_homework_brendyn_chore
input_boolean.thursday_tidy_brendyn_chore
input_boolean.thursday_laundry_brendyn_chore
input_boolean.thursday_mail_brendyn_chore
#

Without the set incomplete = []

#

and the do incomplete .append

#

and the {%incomplete[0] %}

#

it produces a list of entities that haven't been checked off.

#

chore list, essentially.

#

I'm trying to set a global variable, or just one outside of the for and if loops here.

#

and set it to a value of anything.

#

{% set incomplete = chore %} sets it to 6 different variables, which is fine.

#

but as soon as the if loop exits

#

the variable resets to undefined.

#

and if i define it, it's like they're stored independently

#

i've tried starting with {% set incomplete = '' %}

#

and at the end, echoing incomplete

#

but it's just blank

#

or if i set it to 'pizza'

#

at the end, it's 'pizza

#

'

#

regardless of what it got changed to inside the if statement

#

was trying what this said here, but no success

inner mesa
#

you need to use a namespace

uneven pendant
#

will try

#

try

solemn zodiac
uneven pendant
#

that worked.

#

Thanks rob

cosmic hamlet
#

Is it possible for a device id to find out the area the device is in?

mighty ledge
#
{{ device_attr('entity_id_or_device_id', 'area_id') }}
cosmic hamlet
#

great thanks

candid pewter
#

i know the markdown card doesn't support tap_action natively... but i'm trying to get this card somehow clickable to navigate to another dashboard that is a subview. I could but a HTML hyperlink to the URL of the dashboard but that breaks the ability to go back to the previous dashboard. anyone know of, perhaps, any custom stuff on HACS that might accomplish this?

#

this is what is in the markdown card, if it matters {% for story in state_attr('sensor.breaking_news','channel').item %} {%- if loop.index == 1 %} <h4>{{story.title}}</h4> <td> <img src="{{ story['media:content']['@url']}}"/> </td> {% endif %} {% endfor %}

slow vine
#

does this look right?

      - service: squeezebox.call_method
        data:
          entity_id: media_player.squeezeplay
          command: playlist
          parameters: |
            - loadtracks
            - {{trigger.id}}.titlesearch="{{ states('input_text.music_search')}}"
tropic charm
#

hi! moving from #general-archived . due to a custom integration, i have states coming in as text and not numeric (https://imgur.com/a/yGOKjbY)

would this template work to get it to the actual value?
{{ states('sensor.basement_server_room_primary_water_heater_kw_hours') | replace(" Watts","") | trim | float}}

#

it does not seem to 🙃

#

wrong entity 🤦🏻‍♂️ working!

#

damn, no way to duplicate a helper in the UI?

languid pendant
#

Hey RobC -- lot time no hair pull out

#

chuckles

#

I'm migrating HA hosts, and am working on the custom sensor templates to get it working again, and I think there might have been some changes that are impeding me;

#
  - sensor:
      - name: blah
        state: >```
im assuming is not the way it's done anymore?
#

although it could be the state template i am using, but I wanted to check top-down

marble jackal
#

That's the modern format

languid pendant
#

Thanks Fes, I actually just figured it out ... thanks though

#

it was in the state template

jovial pilot
#

Ok not sure how to do this. I have 14 calendars I want to condense into one and then use template triggers on the automation that pulls from them (7 chore lists, 7 calendars to reset them and 7 to send notifications). What does that template look like to filter for a calendar event? I've never used templates as triggers for an automation

digital stump
#

Hi I have a problem with my my binary sensor template for a system im making before using the if statements to use it my method was working but when I added the if statement it does not update at all

template:
  binary_sensor:
    - name: "Garage Entry Alarm"
      state: >
        {% set alarm_system = is_state('input_boolean.house_alarm', 'on') %}
        {% set garage_entry = is_state('binary_sensor.garage_entry', 'on') %}

        {% if alarm_system and garage_entry %} 
        Open
        {% else %}
        Closed
        {% endif %}
      device_class: door
marsh cairn
#

Binary sensors need a template value of true or false, not Open/Closed. The device class takes care of it. And I'd add a unique ID, so you can change some stuff via the UI.
Use the following template, for example:

template:
  binary_sensor:
    - name: "Garage Entry Alarm"
      state: "{{ is_state('input_boolean.house_alarm', 'on') and is_state('binary_sensor.garage_entry', 'on') }}"
      device_class: door
      unique_id: someuniquestring
#

(or yes, on, enable for true and anything else for false)

#

As everything else (like Open or Closed) are interpreted as false, the binary sensor with your template will always be off.

marble jackal
#

Small addition, number above 0 will also render it true

marsh cairn
#

Wasn't thinking about numbers 😅

digital stump
#

oh ok thanks for the the help

harsh hawk
#

Hey folks; been running up against something and it's confusing me. In the docs for templating, it says that functions like floor_id and area_id "can be used as a filter", but it's not clear how? Is there a quick and easy way to, for example, filter a list of entity_ids by testing which floor they're on? Logically: {{ [entities] | select('floor_id', 'first_floor') }} ?

harsh hawk
#

assuming [entities] is the result of an expand() or similar; how can I filter it to 'only entities with a specific floor_id()'? There's some syntax trick I'm missing, and the documentation teases me with 'can also be used as a filter' in all sorts of useful places 😉

harsh hawk
#

({{ [entities] | map('floor_id') }} gives me the floor ids of each entity in the list, but obviously that's not useful by itself)

marble jackal
# harsh hawk Hey folks; been running up against something and it's confusing me. In the docs ...

What it means is that you can either use floor_id('light.ceiling') (=function) or 'light.ceiling' | floor_id (=filter)

What you need is to check the entities in your list against the entities in the floor. Unfortunately there is no floor_entities function yet, so you need to work around that

{% set floor = 'living_room' %}
{% set floor_entities = floor_areas(floor) | map('area_entities') | sum(start=[]) %}
{{ your_entity_list | select('in', floor_entities) | list }}
harsh hawk
#

Ah yeah, that's similar to what I'm doing now; just was wondering if there was a potentially cleaner way to do it. Many thanks!

#

oh... using sum like that is a nice idiom. makes note

marble jackal
#

Well, I hope there will be a floor_entities function/filter in the 2024.6 release, that will make it easier

harsh hawk
#

then I can use a simple "in" filter yes

marble jackal
#

"in" test, but yes 🙂

harsh hawk
#

what I really want, of course, is ultimately a "where" filter {{ entities | where('function') }} or {{ entities | where('floor_id', 'eq', 'ground_floor') }} - ie: call the function on each item in the generator/list and filter by result of a function call.

#

like a combination of map() and select()

haughty breach
#

So that it matches the syntax used for is_state etc it should be select('is_floor', 'ground_floor')

marble jackal
#

It would indeed be possible to add tests for that

#

is_area, is_floor, is_label

harsh hawk
#

that would also be cool

marble jackal
#

Maybe in_area, on_floor, has_label

grim geyser
#

Hello. How can I change this to have 1 decimal point? ${Number(states['[[humidity]]'].state).toFixed()}%</span>`

#

nvm i think i figured it out

sharp bronze
mellow patrol
#

Hello. Why isn't this working? I get an error with float:
service: climate.set_temperature metadata: {} data: hvac_mode: cool temperature: {{ float(states('input_number.settemp_klimaanlage_max')) }} target: entity_id: climate.klimaanlage_schlafzimmer_max

lofty mason
mellow patrol
#

Only this part isn't working. temperature: {{ float(states('input_number.settemp_klimaanlage_max')) }}
I want to make an automation which uses numbers from the input number helper.

#

I tried it with quotes and it still doesn't work

lofty mason
mellow patrol
#

When I triy this:
service: climate.set_temperature metadata: {} data: hvac_mode: cool temperature: "{{ float(states("input_number.settemp_klimaanlage_max")) }}" target: entity_id: climate.klimaanlage_schlafzimmer_max
I get this error:
expected float for dictionary value @ data['temperature']. Got None

#

input_number.settemp_klimaanlage_max is set to 21

#

With this one I have the same problem:
delay: hours: "{{ float(states("input_number.timer_klimaanlage_max")) }}" minutes: 0 seconds: 0 milliseconds: 0

lofty mason
#

you can't use double quotes inside double quotes:
"{{ float(states("input_number.settemp_klimaanlage_max")) }}"

#

either mix single/double, or use a multiline syntax

#

valid: temperature: "{{ float(states('input_number.settemp_klimaanlage_max')) }}"

#

also valid:

 temperature: >
   {{ float(states("input_number.settemp_klimaanlage_max")) }}
mellow patrol
#

Thanks

edgy umbra
#

Any idea why this is not working?

#

label: "[[[ return helpers.relativeTime(entity.last_changed) ]]]"

inner mesa
#

that's not Jinja

river tinsel
#

-moved-

marble jackal
river tinsel
steel swift
#

I have made several sensors to sum up my energy costs correct. And the last one I made sum up the total costs for the current hour. I am unsure how to take this a step further so I can display the costs for the current month. Is it possible to use helpers as rieman sum or? anyway, this is the sensor: - sensor: - unique_id: kostnad time med nettleie name: "kostnad time med nettleie" state: > {% set sensor1_value = states('sensor.accumulated_consumption_current_hour_hjemme') | float(0) %} {% set sensor2_value = states('sensor.strompris_med_nettleie') | float(0) %} {{ (sensor1_value * sensor2_value) | round(2) }}

marble jackal
#

Do you have a fixed energy price?

steel swift
#

I have a floating price for electricity, a price for the grid that varies by month and time of day, as well as a price that is fixed but varies by consumption. The last one is fixed by an automation who set the correct amount in an input_number when I go from one level to another one. So what I need to do is to somehow sum up the costs from each hour and sum them in to monthly cost and the hopefully add the last input_number. But first ting to sum up, was going to have a closer look to the ytility meter. EDIT: Made an utility meter to track this, then I made a new sensor where I summed up the costs. Lot of steps, but looks promising.

random steeple
#

Hey there, I'm trying to set up a script for my heating system. It has four fields: the climate device, the schedule helper, the numeric helper for the low temperature and the numeric helper for the high temperature. The script calls the climate.set_temperature service and set the temperature to the state of the high temperature helper if the schedule is on, otherwise it should set it to the state of the low temperature helper.
I don't get this to work using fields in a script. In the template editor my ternary condition outputs the right value but when executing the script from an automation the temperature is not set on the climate.

alias: Apply Heating Schedule
sequence:
  - service: climate.set_temperature
    metadata: {}
    data:
      temperature: >-
        {{ states(high_temperature) if states(schedule) else
        states(low_temperature) }}
    target:
      device_id: "{{ device }}"
mode: single
icon: mdi:heating-coil
fields:
  climate:
    selector:
      device: {}
    name: Climate
    required: true
  schedule:
    selector:
      entity: {}
    name: Schedule
    required: true
  low_temperature:
    selector:
      entity: {}
    name: Low Temperature
    required: true
  high_temperature:
    selector:
      entity: {}
    name: High Temperature
    required: true
inner mesa
#

How are you calling the script?

random steeple
#

I'm using this code in an automation

action:
  - service: script.apply_heating_schedule
    metadata: {}
    data:
      climate: dde7b091df566b25ebe905be81d3265e
      schedule: schedule.buro_heating_schedule
      low_temperature: input_number.buro_heating_low
      high_temperature: input_number.buro_heating_high
inner mesa
#

Where is 'device' coming from?

random steeple
#

I guess from my stupidity

inner mesa
#

Looks like it's climate

random steeple
#

Oh wow, sorry about that, I should have spotted this

#

It's my first time really using templates and that threw me off. Thank you!

marble jackal
keen spoke
#

Hey all, i'm hoping this is easier than i'm making it. I'm trying to have an automation when triggered with a calendar event, read the summary of said event on a nest hub

#

i can have it read a manually typed message, or by doing "{{'trigger.calendar_event.summary'}}" it'll read those literal words

#

but i don't seem to be able to get it to actually read the summary

marble jackal
#

@keen spoke Remove the single quotes around your trigger variable

#

That makes it a string instead of a variable

keen spoke
#

tried that too but the thing would never fire, finally got this to work just now: ```alias: Dan Alarm Test
trigger:

  • platform: state
    entity_id: calendar.dan_automation_test
    to: "on"
    action:
  • service: tts.speak
    data_template:
    media_player_entity_id: media_player.nesthub28f4
    message: "{{ trigger.to_state.attributes.message }}"
    target:
    entity_id: tts.home_assistant_cloud
marble jackal
#

If you were using a state trigger all that time, there is indeed no trigger.calendar variable

keen spoke
#

no, i wasn't

#

i was triggering off of a calendar event

#

i don't have a copy of what my yaml was before i made the change up, but it was suggested by chatgpt and appears to have worked, so for now good enough for me

#

i really need to dig in and learn more about templating though

steel swift
misty oxide
#

Hi. Can anyone assist me with my custom mqtt sensor? I am trying to get around the json format sent from esp32 to my mqtt. I have tried to customize this via the "Value_Template" It works fine in the developer tab but not when saving to my configuration yaml. When saving below value_template to sensor in yaml it returns nothing.

From Developer page
{{states("sensor.esp32_garagedoor")}} value_template: "{{ states('sensor.esp32_garagedoor').split(':')[1] | regex_replace('}','') }}" value_template: "{{states("sensor.esp32_garagedoor").split(":")[1] | regex_replace("}","")}}"

Result from Developer page
{"cm":605} value_template: "605" value_template: "605"

From my yaml
mqtt: sensor: - name: "ESP32_Garagedoor" state_topic: "/home/sensors/#" unique_id: 9883815210775802070849

From Ardruino
` StaticJsonDocument<80> doc;
char output[80];

long now = millis();
if (now - lastMsg > 5000) {
lastMsg = now;
float dist = distance;
doc["cm"] = dist;

serializeJson(doc, output);


Serial.println(output);
Serial.println(dist);
client.publish("/home/sensors", output);`
mighty ledge
#

@misty oxide fix your mqtt entity.

mqtt:
  sensor:
    - name: "ESP32_Garagedoor"
      state_topic: "/home/sensors/#"
      unique_id: 9883815210775802070849
      value_template: "{{ value_json.cm }}"
misty oxide
winter forge
#

  {% set ns = namespace( average_playing_volume = 0, counter = 0 )%} {%- for player in states.media_player -%}
  {% if state_attr(player.entity_id, 'is_volume_muted') == false and is_state(player.entity_id, "playing") and "speakers" in player.entity_id and "following" not in player.entity_id and "home" not in player.entity_id  %}
  {% set ns.average_playing_volume = ns.average_playing_volume + state_attr(player.entity_id,'volume_level') %}
  {% set ns.counter = ns.counter + 1 %}{%- endif -%} {% endfor %} {{ ns.average_playing_volume / ns.counter }}

Any way to optimize this template? I am pulling over 280 entities ( all the media players) currently and it's probably not the most efficient thing to do

mighty ledge
#

yes

#
{{ states.media_player | selectattr('entity_id', 'search', 'speakers') | rejectattr('entity_id', 'search', 'following|home') | selectattr('state', 'eq', 'playing') | map(attribute='attributes.volume_level') | list | average }}
inner pagoda
#

Hmm. in template sensors, it seems like the this variable isn't available to trigger actions. Am i missing something?

mighty ledge
#

what do you mean "trigger actions"

marble jackal
#

I think they mean in the action section of a trigger based template sensor

mighty ledge
#

Ah yep

inner mesa
mighty ledge
#

this is only available in the individual entity, if it's even available for trigger based templates

inner mesa
#

filed that

mighty ledge
#

I'm not sure how that's an issue

inner mesa
#

;shrug:

#

I expect it to work

mighty ledge
#

you can have more than 1 sensor per trigger

marble jackal
# mighty ledge yes

Both the original template and this one will error when no entities match the criteria, but you can add a default to the average filter

mighty ledge
#

so if you have more than 1 sensor in your sensor section, what does this populate with?

#

sensor 1 or sensor 2?

inner mesa
#

well, that's true

#

that would be a problem

mighty ledge
#

Yep, it if was 1 to 1, yah, this all day

winter forge
#

What if I want to exclude muted speakers?

#

"if state_attr(player.entity_id, 'is_volume_muted') == false"

This part

#

{{ states.media_player | selectattr('entity_id', 'search', 'speakers') | rejectattr('entity_id', 'search', 'following|home') | rejectattr('volume_muted', 'search', 'true') | selectattr('state', 'eq', 'playing') | map(attribute='attributes.volume_level') | list | average }}

I try this but get 'homeassistant.helpers.template.TemplateState object' has no attribute 'volume_muted'

mighty ledge
#

rejectattr('attributes.volume_muted', 'eq', True)

winter forge
#

{{ states.media_player | selectattr('entity_id', 'search', 'speakers') | rejectattr('entity_id', 'search', 'following|home') | rejectattr('attributes.volume_muted', 'search', True) | selectattr('state', 'eq', 'playing') | map(attribute='attributes.volume_level') | list | average }}

results in TypeError: first argument must be string or compiled pattern

mighty ledge
#

sry, edited

winter forge
#

No error but the value is not correct. It seems like the parameter is ignored

#
   mine:        {% set ns = namespace( average_playing_volume = 0, counter = 0 )%}
          {%- for player in states.media_player -%}
            {% if state_attr(player.entity_id, 'is_volume_muted') == false and is_state(player.entity_id, "playing") and "speakers" in player.entity_id and "following" not in player.entity_id and "home" not in player.entity_id  %}
            {% set ns.average_playing_volume = ns.average_playing_volume + state_attr(player.entity_id,'volume_level') %}
            {% set ns.counter = ns.counter + 1 %}
          {%- endif -%}
          {% endfor %}
          {{ ns.average_playing_volume / ns.counter }}
          
yours: {{ states.media_player | selectattr('entity_id', 'search', 'speakers') | rejectattr('entity_id', 'search', 'following|home') | rejectattr('attributes.volume_muted', 'eq', 'true') | selectattr('state', 'eq', 'playing') | map(attribute='attributes.volume_level') | list | average }}```
#

mine: 0.3499999940395355

yours: 0.3680456919329507

#

changing true to false does not change the value neither

mighty ledge
#

you still have 'true' in quotes, look at mine again

#

'true' -> True

winter forge
#

Capitalized?

mighty ledge
#

Yes

winter forge
#

I tried both False and True.

Same result for both. .3680456919329507
vs .3499999940395355 for mine

mighty ledge
#

{{ states.media_player | selectattr('entity_id', 'search', 'speakers') | rejectattr('entity_id', 'search', 'following|home') | rejectattr('attributes.volume_muted', 'eq', 'true') | selectattr('state', 'eq', 'playing') | map(attribute='attributes.volume_level') | list | average }}

#

is still using 'true'

winter forge
#

   mine:        {% set ns = namespace( average_playing_volume = 0, counter = 0 )%}
          {%- for player in states.media_player -%}
            {% if state_attr(player.entity_id, 'is_volume_muted') == false and is_state(player.entity_id, "playing") and "speakers" in player.entity_id and "following" not in player.entity_id and "home" not in player.entity_id  %}
            {% set ns.average_playing_volume = ns.average_playing_volume + state_attr(player.entity_id,'volume_level') %}
            {% set ns.counter = ns.counter + 1 %}
          {%- endif -%}
          {% endfor %}
          {{ ns.average_playing_volume / ns.counter }}
          
yours: {{ states.media_player | selectattr('entity_id', 'search', 'speakers') | rejectattr('entity_id', 'search', 'following|home') | rejectattr('attributes.volume_muted', 'eq', False) | selectattr('state', 'eq', 'playing') | map(attribute='attributes.volume_level') | list | average }}
mighty ledge
#

i copied/pasted that from your last post

winter forge
#

I modified after your request

mighty ledge
#

are you sure volume_muted is the correct attribute name?

winter forge
#

Ah.

#

is_volume_muted

#

Now it works! Thanks!

#

I have at least 30+ sensors doing loops on various domains.

Would it be significant performance wise to try convert them all to this kind of templatE?

#

Or not really that much of a performance hit

mighty ledge
#

it will be faster than what you wrote but it's probably negligible

#

if you have a slow machine, use the single line template

winter forge
#

I don't ATM. But I am planning on moving my HA from a VM to a NUC

#

Everytime I play with my homelab and there's an issue, HA goes down.

Need to avoid that in the future

plain magnetBOT
#

@winter forge I converted your message into a file since it's above 15 lines :+1:

cosmic hamlet
#

is it possible to get historic data like gps coords of the last 6 hours of a person for example?

inner mesa
#

no

#

templates have no access to historical data

cosmic hamlet
#

to bad. I want my phone system to email out my last gps track when i am missing.

#

why not go overboard and make a sql db,

inner pagoda
hexed galleon
#

Hey folks, hopefully a quick one. Referencing the 'precipitation' attribute of a forecast array with the new method. Is this right? {{ False if forecast_daily[0:2]['precipitation'] > 1 else True }}. Have run the daily forecast as a previous step in this automation and stored it in the forecast_daily variable. Want it to resolve to False if there's > 1mm rain forecast in the next 3 days.

inner mesa
#

not...quite

#

{{ state_attr('sensor.pirateweather_daily_forecast', 'forecast')[0:2]|map(attribute='precipitation')|sum > 1 }}

#

as always, if you're returning "true" or "false", just return the test

hexed galleon
#

Isn't that the old method that no longer works and you need to use the variable assignment from a service call now?

inner mesa
#

do you mean "if there's > 1mm of rain in a single day over the next three days?" or "is there a total of greater than 1mm of rain in the next 3 days?"

#

how you get to the forecast doesn't matter

#

it's the rest of it that does the work

#

I didn't ask where you got "forecast_daily" and assumed you had a way

#

I'm just giving you an example that I can test myself

hexed galleon
#

So the forecast_daily is the variable in the automation. It's not a sensor, so I can't use state_attr() right? That's why I was trying to use direct list referencing.

inner mesa
#

like I said, if it's a list, that's fine. use it

#

I'm not focusing on how you got the forecast

#

it doesn't matter

#

I mean, if you need me to do it

#

{{ forecast_daily[0:2]|map(attribute='precipitation')|sum > 1 }}

#

still:

do you mean "if there's > 1mm of rain in a single day over the next three days?" or "is there a total of greater than 1mm of rain in the next 3 days?"

hexed galleon
#

Riiiight, that makes more sense. Sorry for being dense.

inner mesa
#

what I gave you was the latter

#

for the former:
{{ forecast_daily[0:2]|map(attribute='precipitation')|select('gt', 1)|list|length > 1 }}

hexed galleon
#

And if the attribute was returned as a str for whatever reason, just cast it as a float before the sum?

inner mesa
#

it isn't

#

but yes

#

"cast" meaning map('float')

hexed galleon
#

Ah right because it's still a list at that stage, can't just | float it. Thanks for the thorough explanation!

indigo haven
#

im creating a script to help me control my CRT TV via IR.

but it has a quirk where i need to alternate between sending a command and a version of the command +0x800

example, first time i send 0xC, but if I send 0xC again it wont work i need to send 0x80C

#

how can I achieve this behaviour? do i need to create some sort of global variable? or is there a simpler solution

quasi frost
#

Hey there, i am using a blue print to send me notifications if movement at the front door was detectet. Now i want to trigger this routine only if the front door is closed. So i want to use a additionally helper (the Windows Sensor on the door) and use this state in my own routine to trigge the new binary helper wich triggers the blue print. My problem is, that i am dont know how to setup the binary template "helper" for that. I need a binary helper to use it in the blueprint as trigger. I got this:

binary_sensor:    
- platform: template
      sensors:
        send_notify_eingang:
          value_template: 
          friendly_name: 'Send Notify Eingang'
          device_class: switch```

But i need something for the value template. What should fill in there?
#

oh sorry, it needs to be a motion sensor.

quasi frost
#

i added a virtual motion sensor, but i cant manipulate the sensor from a automation. I need this virtual motion sensor to trigger automation in front of the notifiy

fickle sand
#
template:
  - binary_sensor:
      - name: 'Send Notify Eingang'
        state: "{{is_state('binary_sensor.door_contact','off')}}"
        device_class: motion
quasi frost
#

i cant add another condition to the blueprint

fickle sand
#

Binary sensors are changed by state events, not by user input or service from an automation

quasi frost
#

ah ok, hmmm, so how can i add another condition to a blueprint wich doesnt support that?

#

i thought, by using a "virtual" motion sensor.

fickle sand
#

an input_boolean perhaps

quasi frost
#

jeah, but the blueprint dont accepts a bolean as input 🙂

#

or can i change that condition inside of the blueprint?

fickle sand
#

I don't know, not sure about what blueprint you are talking. It's lacking the details to understand and helping you

fickle sand
#

But you can use that state of an input helper to determine the state of a binary sensor, just change the entity to the input boolean in the above example

quasi frost
#

yes, but i cant use it to trigger the blueprint

#

the yaml of my blueprint looks like this:

alias: "Eingangsbereich: Bild senden wenn Bewegung erkannt"
description: ""
use_blueprint:
  path: vorion/send-camera-snapshot-notification-on-motion.yaml
  input:
    motion_sensor: binary_sensor.0x00158d00065850d2_occupancy
    camera: camera.10_10_10_114
    notify_device: ad276a7be8ef9e7cb72d3ef7ac2d3a17
    delay: 0
    notification_title: Bewegung im Eingangsbereich erkannt!
fickle sand
#

So with what conditions should it trigger? If motion is detected and front door is closed?

quasi frost
#

in this example yes

#

but for me it would be the best to check that by an automation, so that i can arrenge the conditions to what i need

#

wouldnt it be possible to change the preset of the blueprint from "motion sensor" to "binary sensor" inside of the yaml?

#

its written here:

  domain: automation
  input:
    motion_sensor:
      name: Motion sensor
      description: The sensor wich triggers the snapshot creation
      selector:
        entity:
          domain:
          - binary_sensor
          device_class:
          - motion
          multiple: false
#

isnt it possible just to change the input in the blueprint?

fickle sand
#

Okay, then when all conditions are met you can set an input_boolean to on in that automation and turn it off when the conditions fail

template:
  - binary_sensor:
      - name: 'Send Notify Eingang'
        state: "{{is_state('input_boolean.motion_conditions','on')}}"
        device_class: motion

And use this binary sensor in your blueprint, no need to change the blueprint

fickle sand
quasi frost
fickle sand
#

You handle all conditions inside your automation and set the state of the input_boolean accordingly. The binary_sensor above mirrors the state of the input_boolean

quasi frost
#

aaaah, think i got it!

#

i will try

#

ok, so i made a helper Switch bolean as a trigger, i added the Switch into your code by adding a template helper:
template:

- binary_sensor:
     - name: 'Send Notify Eingang'
       state: "{{is_state('input_boolean.test_trigger_notify','on')}}"
       device_class: motion

correct?

fickle sand
#

Does it work? than it should be correct.

quasi frost
#

i would say, its working the half way...

#

the template sensor indicates the status of the bolean helper, but something is still wrong

#

and i cant select the template trigger in the blueprint

fickle sand
#

You somehow misplaced the code. The snippet I posted is meant to be placed directly into configuration.yaml

quasi frost
#

ah, ok 🙂 i added it as a template helper

#

whe i add it to the cong.yaml i got this:
Invalid config for 'binary_sensor' at configuration.yaml, line 230: required key 'platform' not provided

#

i changed the template using one of my examples in my confi.yaml to this:

    - platform: template
      sensors:
        send_notify_eingang_test:
          value_template: "{{is_state('input_boolean.test_trigger_notify','on')}}"
          friendly_name: 'Send Notify Eingang Test'
          device_class: motion

Now its working

fickle sand
quasi frost
#

ah ok, do i need to setup something to use the new format?

#

anyway, i added the 2 additional binary sensor and added the two template sensors and tested themn. its working as i need1 thank you!

fickle sand
cyan moth
#

hi all! did anyone export a list of Zigbee integration list of entities? I've been told to use template to achieve it

cyan moth
#

legend!

indigo haven
#

im creating a script to help me control my CRT TV via IR.

but it has a quirk where i need to alternate between sending a command and a version of the command +0x800

example, first time i send 0xC, but if I send 0xC again it wont work i need to send 0x80C

how can I achieve this behaviour? do i need to create some sort of global variable? or is there a simpler solution

plain magnetBOT
#

@placid patrol I converted your message into a file since it's above 15 lines :+1:

marsh cairn
#

You can pull the source and parse it to the sensors without storing them in a helper.

plain magnetBOT
cyan moth
wooden valley
marble jackal
#

so only {{is_state('input_boolean.test_trigger_notify','on')}}

quasi frost
#

Thx, @marble jackal i am nownusing the way wich @fickle sand Shows me. That works fine

marble jackal
mighty ledge
#

his quotes are wrong

marble jackal
#

ah right,single quotes within and outside the template

#

however, the error message shows it did render the template

#

and couldn't convert unknown to an integer

open hound
#

int used as a function in this case, converts whatever is in the helper to an integer, but int also allows for a 'default' value to be used in the event that the value in the helper is invalid or not a number (in the case of it being undefined, for instance)

marble jackal
#

you can also do that when using int as a filter

data:
  duration: "{{ states('input_number.bedroom_hour') | int(0) }}:{{ states('input_number.bedroom_min') | int(0) }}:00"

However, an input_number will never return the state unknown, so therefor I know for sure the entity_id is wrong. Using defaults will only hide that underlying issue

indigo haven
languid pendant
#

When using a [[[ return `` ]]] template, is there a way to set a default value if the values are unknown or undefined?

indigo haven
#

How do I use this variables action?

alias: CCE_IR
sequence:
  - variables:
    test_var: "2323"
#

I tried it like this and got this error

Message malformed: expected a dictionary for dictionary value @ data['sequence'][0]['variables']

inner mesa
#

you need to indent the test_var line

indigo haven
#

aa

#

thanks

mighty ledge
indigo haven
#

This worked. how weird.

alias: CCE_IR
sequence:
  - variables: {
  "command_value": "{{ increment_value|int(base=16) + '0xC'|int(base=16) }}"
  }
#

AAAH

#

Nevermind, I need ANOTHER tab lmao.

languid pendant
languid pendant
mighty ledge
#

You'll get better help there

languid pendant
#

'ppreciate it

indigo haven
#

how do I print an integer as a base 16 string in jinja

inner mesa
languid pendant
#

oh, and also, Petro, the stupid crazy template you and RobC helped me out with?, has made some pretty cool stuff in the last few months

mighty ledge
indigo haven
indigo haven
languid pendant
#
{% set helper.list=helper.list+[entity|replace('media_player.mrp_','input_boolean.mrp_')|replace('_kodi_mini','')] %}{%endfor%}
{% set turned_on=expand(helper.list, 'media_player.mrp_helper')|map(attribute='entity_id') | map('replace', 'media_player.', 'input_boolean.') | list %}
{{ expand(turned_on) | selectattr('state', 'eq', 'on')|sort(attribute='last_updated', reverse=True)|map(attribute='entity_id')|first|default }}
mighty ledge
#

Nice, glad it works

languid pendant
#

I've been able to do some pretty slick stuff with my light groups and a few other grouped things

#

so, I wanted to give ya guys a little shout-out

indigo haven
#

Uh this is a nightmare, i hate handcrafting JSON string in templates. is there a way to put a dictionary into it and then it will internally convert to JSON?

data:
  qos: "0"
  topic: cmnd/tasmota_466C1F/IRSend
  payload: '''{{ '{"Protocol":"RC5","Bits":12,"Data":'+command_value | string+'}' }}'''
enabled: true
mighty ledge
#

| to_json

indigo haven
#

:O let me try

mighty ledge
#
payload: "{{ dict(Protocol='RC5', Bits=12, Data=command_value | string) | to_json }}"
indigo haven
#

IT WORKS

#

ITs alivee!!!!

#

Thanks a lot!

indigo haven
#

Is it ok to use recursivity in scripts

wary yew
indigo haven
#

Does this look right? im afraid to run it lmao

  - if:
    - condition: template
      value_template: "{{ repeat > 0}}"
    then:
      - service: script.cce_ir
        metadata: {}
        data:
          repeat: "{{ repeat - 1 }}"
          raw_command: "{{ raw_command }}"
          repeat_interval_delay: "{{ repeat_interval_delay }}"
          COMMAND_KEY: "{{ COMMAND_KEY }}"
#

Disallowed recursion detected

Oooh cmoon! let me do it

#

oh nevermind its because I Set it to Queued

#

Parallel it is then.

mighty ledge
indigo haven
#

yeah, its part lazyness

#

I would have to redo how I set the alternating increment of the protocol

mighty ledge
#

Just make the script accept a repeat option

indigo haven
mighty ledge
#

Or just use the for each repeat with your service call inside the script you’re calling

bitter atlas
#

I have a template sensor that spits out a name based on whichever of multiple binary sensors trigger to on. usually only one binary sensor triggers on at any given time. I would like to create a template sensor that does the same but weighs it's output based off multiple binary sensors that could be on at the same time but still functions correctly if only one is on. I think this could be done with a ton of and/or's but is there a shorter code way to accomplish this?

#

thinking i am going to be stuck actually making several smaller template sensors that does the "weigh" aspect and then feeds into a final template sensor that spits out the name

haughty breach
#

You will need to describe what you want more clearly. Should the new sensor return only one name? What are the criteria for choosing or sorting the list of sensors?

naive swan
#

Is there a way to do a if this else with variables? So if (A) then variable (A) else variable (B) without putting a template inside of a template?

inner mesa
#

Template inside template isn't a thing. What is the context?

#

Yes, certainly that logic can be used within a template

naive swan
inner mesa
#

A template can't actually do anything

#

If you were using choose, you're probably doing things that templates can't do

naive swan
#

It's basically a {{ 'enabled' if is_state (input_boolean.master_switch', 'on') else 'disabled' }} but wanting to replace enabled and disabled with a variable option

bitter atlas
#

the template sensor is used to determine which camera has a snapshot saved which is why I only needs it's output to produce the name of the camera that has detection. I want to add additional binary detection sensors to the mix so each camera could have 2 or 3 and then weigh whichever one that has the most triggered at same time to be set as the template sensors output at that time

#

I'm kind of thinking I might need to assign each detection source a number and then use math comparison to determine which camera name should be outputed to the state

inner mesa
naive swan
inner mesa
#

You can put anything there

#

You just chose a string

#

If you have a variable, use it

naive swan
#

The variable can only be referenced by {{ }} though right so would that be an issue?

inner mesa
#

Wrong

#

Just put the variable name there

#

Once you're in a template variables will resolve

crimson lichen
#
  • variables:
    mapping:
    binary_sensor.motion_phong_ngoai_t1_occupancy: Phòng Ngoài
    binary_sensor.motion_bep_occupancy: Phòng Bếp
    binary_sensor.motion_cau_thang_t45_occupancy: Tầng 5
    binary_sensor.motion_phong_khach_occupancy: Phòng Khách
    message: |-
    Có chuyển động {{ mapping[trigger.entity_id] }}
    |--> {{ now().strftime('%H:%M:%S %A %d-%b-%Y') }}
bitter atlas
#

a bayesian sensor where you could customize it's output would be nice

wild vapor
#

So I have an Ikea Fyrtur blind which I'm controlling via my Zigbee Coordinator.
The blind device doesn't have an entity for it's current position but it is reporting it as secondary information.
If I toggle secondary information on the blinds dashboard card or view the device it will show me what position it's in so HA is getting the information.
Is there any way I could make a helper or some entity which exposes what position the blind is in so I can use it for conditions in automations as well as other things?
It was mentioned to me that a "template" might be able to do this for me so I'll have a poke around with those but any other advice would be welcome

marble jackal
#

for conditions in automations you don't need a separate entity

#

you can refer to an attribute as wel

#
condition: numeric_state
entity_id: cover.some_blind
attribute: current_position
above: 50
#

make sure to not use quotes around the value here, as the attribute will report an integer, and not a string. If you use the GUI, it will add them automatically and you need to remove them in YAML mode

lofty mason
marble jackal
floral steeple
#

hi all, im trying to modify this to say if an item is present in the to-do then list the title (or summary) of the item

 {%- for task_entity in task_entities %}
      Upcoming tasks for today on list "{{ state_attr(task_entity, 'friendly_name') }}":
      {%- set tasks = tasks_responses[task_entities[loop.index0]] %}
      {%- for task in tasks['items'] %}
      {%- if 'due' in task and now().date() == as_datetime(task.due, "2222-11-11").date() %}
      - {{task['summary']}}
      {%- endif %}
      {%- endfor %}
    {%- endfor %}

and if no item is present, then no task should be completed

plain magnetBOT
#

@floral steeple I converted your message into a file since it's above 15 lines :+1:

mighty ledge
#
{{ tasks_responses.items() | selectattr('0', 'in', task_entities) | map(attribute='1') | sum(start=[]) | selectattr('due', 'defined') | selectattr('due', 'eq', now().date() | string) | list }}
#

that will just be 1 giant list

floral steeple
#

ahh, ok I think it would be good to have it distinguised by todo lists, so I made this, and it seems to work except:


    {%- for task_entity in task_entities %}
      Upcoming tasks for today on list "{{ state_attr(task_entity, 'friendly_name') }}":
      {%- set tasks = tasks_responses[task_entities[loop.index0]] %}
      {%- for task in tasks['items'] %}
      {%- if 'due' in task and now().date() == as_datetime(task.due, "2222-11-11").date() %}
      - Tasks with due dates today are: {{task['summary']}}
      {%- else %}
      - Tasks with no due dates are: {{task['summary']}}
      {%- endif %}
      {%- endfor %}
    {%- endfor %}

sometims there is a list with NO tasks, like this:

#
todo.work_to_do:
  items: []
#

how can I say that is there is no task, then just say "no task(s) for this list"

#

guess it would "no items"

mighty ledge
#

Well, your output isn't matching what you you said you wanted above

floral steeple
#

i know, sorry im all over the place lol

#

but essentially, I want to take care of 3 scenarios

  1. items with due dates
  2. items with no due dates
  3. lists with no items
spice current
#

How do i iterate over/list all services (and by extension all services that start with notify. in particular)

floral steeple
#

that output has the 3 scenarios

mighty ledge
#
    {%- for task_entity in task_entities %}
      Upcoming tasks for today on list "{{ state_attr(task_entity, 'friendly_name') }}":
      {%- for task in tasks_responses[task_entity] | selectattr('due', 'defined') | selectattr('due', 'eq', now().date() | string) | map(attribute='summary') | list or ['No Tasks'] %}
      - {{ task }}
      {%- endfor %}
      Upcoming tasks with no due date:
      {%- for task in tasks_responses[task_entity] | selectattr('due', 'undefined') | map(attribute='summary') | list or ['No Tasks'] %}
      - {{ task }}
      {%- endfor %}
    {%- endfor %}
floral steeple
#

thanks, that output of your code above gave this:

   # Tasks Lists:
        Upcoming tasks for today on list "Anto's list":
        - No Tasks
        - 
        Upcoming tasks for today on list "General to-do":
        - No Tasks
        - 
        Upcoming tasks for today on list "Work to-do":
        - No Tasks
        - 

Only thing is, its only looking for tasks that have a due date, and not listing the tasks without a due date At the moment, there are things on my to-do list with no due dates, but the output does not show that.

#

its strange, your code is written like it should work

#

by the way, where is that extra hypen coming from?

mighty ledge
#

I'd have to see what {{ tasks_responses[task_entity] | selectattr('due', 'defined') | selectattr('due', 'eq', now().date() | string) | map(attribute='summary') | list }} outputs

#

nm

#

i see issue

#
    {%- for task_entity in task_entities %}
      Upcoming tasks for today on list "{{ state_attr(task_entity, 'friendly_name') }}":
      {%- for task in tasks_responses[task_entity]['items'] | selectattr('due', 'defined') | selectattr('due', 'eq', now().date() | string) | map(attribute='summary') | list or ['No Tasks'] %}
      - {{ task }}
      {%- endfor %}
      Upcoming tasks with no due date:
      {%- for task in tasks_responses[task_entity]['items'] | selectattr('due', 'undefined') | map(attribute='summary') | list or ['No Tasks'] %}
      - {{ task }}
      {%- endfor %}
    {%- endfor %}
floral steeple
#

hm, let me check i get this error now Error: TypeError: 'builtin_function_or_method' object is not iterable

#

something about missed comma

mighty ledge
#

change .items to ['items']

plain magnetBOT
#

@floral steeple I converted your message into a file since it's above 15 lines :+1:

floral steeple
#

and the LLM said this

      As for your tasks, you have a few items on your "General to-do" list
      without specific due dates: ambient oxygen sensor, find water leak, and home
      depot wire covers. Make sure to tackle these tasks at your convenience.
#

thanks!

heavy minnow
#

Hello, I'm trying to make a script that has a field to enter a light entity, then it publishes a MQTT payload using the light as a target

but I can't use the field value directly in the mqtt like

data:
  topic: zigbee2mqtt/{{ light_entity_id }}/set
  payload: "{\"state\": \"ON\"}"
enabled: true```

since it will return the value like "light.bedroom_lamp", and it should only be "bedroom_lamp"
#

I tired to replace the field key with
{{ "{{light_entity_id}}" | replace("light.", "") }}
to remove the "light." but it doesn't work, I also tried defining a variable

  test: "{{light_entity_id}} | replace("light.", "")" 

and then using the variable in MQTT, but HA won't accept the variable

marble jackal
#
service: mqtt.publish
data:
  topic: zigbee2mqtt/{{ light_entity_id.split('.')[1] }}/set
  payload: "{\"state\": \"ON\"}"
enabled: true
#

you were nesting templates, that doesn't work

marble jackal
#

this will also work (which was what you were trying to achieve)

service: mqtt.publish
data:
  topic: zigbee2mqtt/{{ light_entity_id | replace('light.', '') }}/set
  payload: "{\"state\": \"ON\"}"
enabled: true
marble jackal
#

no worries

inner mesa
#

the desire to nest templates is strong

heavy minnow
#

and what if the field returned an RGB value?

marble jackal
marble jackal
heavy minnow
inner mesa
#

just surround the whole thing with single-quotes

#

then you don't need any of the escaping

marble jackal
#

I think you can even proivde it as a yaml dict

#
service: mqtt.publish
data:
  topic: zigbee2mqtt/{{ light_entity_id | replace('light.', '') }}/set
  payload:
    color:
      r: 255
      g: 0
      b: 0
enabled: true
heavy minnow
marble jackal
#

see above 🙂

#

but I'm not completely sure about that

inner mesa
#

I've seen so many people construct JSON for it that it makes me think you have to

heavy minnow
#

Error "value should be a string for dictionary value @ data['payload']. Got None"

marble jackal
#

okay

#

then an alternative couls also be:

payload: "{{ dict(color=dict(r=255, g=0, b=0)) | to_json }}"
heavy minnow
#

😂

#

I'm amazed at my ignorance

inner mesa
#

just one more typo...

heavy minnow
#

I don't even know how will the retuned field value of the RGB look like

#

how can I see?

marble jackal
#

crap: paylaod

#

but, anyway, this will also work:

payload: '{ "color": {"r":255, "g":0, "b":0}}'
heavy minnow
#
data:
  topic: zigbee2mqtt/{{ light_entity_id | replace('light.', '') }}/set
  payload: "{{color}}"
enabled: true```

will become

```service: publish
  service_data:
    topic: zigbee2mqtt/right_wall_lamp_hallway/set
    payload:
      - 251
      - 0
      - 255```
which doesn't work
#

fixed it

data:
  topic: zigbee2mqtt/{{ light_entity_id | replace('light.', '') }}/set
  payload: '{ "color": {"r":"{{color[0]}}", "g":"{{color[1]}}", "b":"{{color[2]}}"}}' 
enabled: true
stuck remnant
#

hi guys, what was the template to only have an automation trigger if its' set triggers were actioned by the user?

#

in the case of an input boolean, for example

open hound
stuck remnant
#

this
{{ trigger.from_state.last_changed_by == 'user' }}

#

found it in the mean time ^^

open hound
#

Otherwise, have a condition with a value_template

{{trigger.to_state.context.user_id is not none}}

For any user logged into HA, otherwise, specify the username of who triggered it.

#

That would be able to catch it as it happens, versus retroactively after it has happened.

plain magnetBOT
#

@flint jewel I converted your message into a file since it's above 15 lines :+1:

mighty ledge
stuck remnant
#

is it? it seemed to work though

mighty ledge
#

No such attribute exists

stuck remnant
#

I have not tested it enough so cannot tell for certain

#

ok then what is the correct form for this

mighty ledge
#

Looks like chat gpt made up crap

#

There is nothing for this

#

You have pull the user id from context and then compare it to your list of persons

stuck remnant
#

I changed 'user' to 'chris' if that helps

mighty ledge
#

Nope

#

You have to pull the user id from the trigger context (if it even exists) like the Kirb posted. Then you need to extract the proper person from the list of people by the user id you found.

stuck remnant
#

ah ok now I get it

#

what if I just have the one user?

flint jewel
#

Always best to protect for when you have more! You might end up creating users for other add-ons etc

stuck remnant
#

hmm that's true

timber pewter
#

hey guys! im trying to create an automation for my Google nest.
Its read with elevellabs a message from meteoalarm. one of the attributes from the meteoalarm sensor is
"awareness_level: 2; yellow; Moderate"
and the other one
"awareness_type: 3; Thunderstorm"

for the level attribute:
how can i change it so it says only says "Yellow". The best thing is it translate automatical in to german "Gelb"

for the type attribute
how can i change it so it says only says "Thunderstorm". The best thing is it translate automatical in to german "gewitter"
current script:

#
service: tts.speak
data:
  cache: true
  media_player_entity_id: media_player.nestspeaker
  options:
    voice: Adam
    stability: 1
    similarity: 1
    style: 0.3
    use_speaker_boost: "true"
    model: eleven_multilingual_v1
    optimize_streaming_latency: 3
  message: Von MeteoAlarm. {{ state_attr('binary_sensor.meteoalarm', 'event') }}. {{ state_attr('binary_sensor.meteoalarm', 'description') }}. {{ state_attr('binary_sensor.meteoalarm', 'instruction') }}.
target:
  entity_id: tts.elevenlabs_tts
marble jackal
#

What is the output of my proposed solution in #automations-archived if you put that in developer tools > templates

timber pewter
#

full output of the sensor

plain magnetBOT
#

@timber pewter I converted your message into a file since it's above 15 lines :+1:

marble jackal
#

Which part returns awareness_level: 2; yellow; Moderate

timber pewter
#

ah i see

#
Von MeteoAlarm. {{ state_attr('binary_sensor.meteoalarm', 'event') }}. {{ state_attr('binary_sensor.meteoalarm', 'description') }}. {{ state_attr('binary_sensor.meteoalarm', 'instruction') }}. {{ state_attr('binary_sensor.meteoalarm', 'awareness_level') }}. {{ state_attr('binary_sensor.meteoalarm', 'awareness_type') }}```
marble jackal
#

Which of those parts returns that specific piece of text

timber pewter
#
Gewitterwarnung```
```{{ state_attr('binary_sensor.meteoalarm', 'description') }}
Gewitter mit Sturmböen sind zu erwarten.```
```{{ state_attr('binary_sensor.meteoalarm', 'instruction') }}
VORSICHT bei Aktivitäten im Freien, Gewitter sind möglich. Achtung an
  exponierten Stellen, wie auf Bergen und freien Flächen sowie im Wald.```
```{{ state_attr('binary_sensor.meteoalarm', 'awareness_level') }}
2; yellow; Moderate```
```{{ state_attr('binary_sensor.meteoalarm', 'awareness_type') }}
3; Thunderstorm```
#

idk how to sparate that and translate it

marble jackal
#

Use
{{ state_attr('binary_sensor.meteoalarm', 'awareness_type').split(';')[1] }}

#

That should return yellow

#

And
{{ state_attr('binary_sensor.meteoalarm', 'awareness_type').split(';')[1] }}

timber pewter
#

that work! great!

#

is it possible to translate them to german?

marble jackal
#

Only manually by providing all options and then a German translation

timber pewter
#

Got it to work! just added the following template to configuration file:

plain magnetBOT
#

@timber pewter I converted your message into a file since it's above 15 lines :+1:

mighty ledge
# stuck remnant thanks guys
{% set user = states.person | selectattr('attributes.user_id', 'eq', trigger.to_state.context.user_id) | list | first | default %}
{{ user and user.name == 'frank' }}
stuck remnant
#

wow. thanks!

lucid thicket
marble jackal
#

Prevent errors

#

The first filter will return an error when the list is empty

#

The default filter will prevent that error and let it return an empty string (if I'm not mistaken, it could be none)

lucid thicket
#

Ok I’m seeing that now. Was testing and apparently there is a difference between:

{{ [] | first }}

compared to

{% set my_list = [] %}
{{ my_list | first }}
#

Which I still don’t understand

mighty ledge
#

what difference?

#

they both produce the same error...

#

Maybe you're referring to the error being raised in the UI?

#

if you check the logs, the error is produced for both, but {{ [] | first }} does not raise the error to the UI

#

which is most likely a bug

lucid thicket
#

You’re right, there’s an error in the logs, just nothing shown in the template editor UI

#

Thanks

flint jewel
#

Apologies for re-posting - I think this originally got lost previously as it got converted to a file.

Hi all - looking for some help on handling the response from weather.get_forecasts. Been doing a fair bit of googling, but couldn't find enough for me to figure it out!

Its fairly simple, I understand how to list the full dict response using {{forecast.items()}}, but I'm looking to actually dive into the dict and pull out the first day's 'condition' and 'temperature', for example

#

Current sequence:

sequence:
  - service: weather.get_forecasts
    metadata: {}
    data:
      type: daily
    target:
      entity_id: weather.home
    response_variable: forecast
  - service: notify.xx
    data:
      message: >
        {{forecast.items()}}
plain magnetBOT
#

@flint jewel I converted your message into a file since it's above 15 lines :+1:

inner mesa
#

{{ forecast[0].temperature }} and so on

valid grotto
#

I'm quite new to HA and could really use some help with my template file.

I have google calendar integration and I want to set a binary sensor to on/off depending on whether a calendar event for the particular calendar exists for today. I want it to update periodically in line with the 15m of google calendar integration.

I have this template.yaml but the first two sensors for this are showing as unavailable.

I've spent hours banging my head against a wall and just don't know what the problem is
http://pastie.org/p/6OV1Ozr2bYO30lf01nega9

inner mesa
#

You need to remove the - before binary_sensor:

#

You're basically creating a new sensor that isn't related to the trigger

valid grotto
#

I'm both happy and upset that all my time of frustration was caused by that 😂 so once I fix that am I safe to assume that what I've actually written will do what I've requested?

#

And given that I will want binary_sensors that are not reliant on that trigger, is it still normal procedure to continue to nest them under with - name

inner mesa
#

By definition, you're not nesting them when you add -

#

You're creating new independent list items

#

I don't use calendars, but I guess so

valid grotto
#

Sorry maybe bad terminology, I mean placing them within the same binary_trigger: area

inner mesa
#

|count() can be just |count

#

If you want additional sensors unrelated to the trigger, they should be peer list items

valid grotto
#

What I mean't for nested is whether its normal practice to put all binary_triggers below those ones I have rather than some syntax like:

` - trigger:
binary_sensor:
- name: "You have an event today"

  - name: "Someone has a birthday today"
  • binary_sensor:
    • name: "washing machine"`
#

Still trying to get my ahead around the syntax

inner mesa
#

It's fine

valid grotto
#

Brill thanks for your help, very appreciated!

flint jewel
# inner mesa `{{ forecast[0].temperature }}` and so on

This is what I thought but:
Error rendering data template: UndefinedError: dict object has no element 0
So I tried this as I assumed the response likely contains another "forecast" before (confusing that I named the response variable the same as a value in the dict...)
forecast.forecast[0].temperature
But no luck there either

marble jackal
#

it's forecast['weather.home'].forecast[0]

inner mesa
#

indeed, that's what I get trying to read code on my phone

flint jewel
#

ahah brilliant, got it - an expansion on that: {{ forecast["weather.home"].forecast[0].condition }} is what works for me
Now if my "weather.home" is an input variable, I should safely be able to replace that too right?

marble jackal
#

weather.home is the entity you used for the service call

#

you can use it on multiple enitites in one go

thorny snow
#

Previously I had asked for help and got this to work:

{{ state_attr('sensor.double_take_officetable1', 'matches') | selectattr('name', 'eq', 'mike') | selectattr('match', 'eq', True) | list | count > 0 }}

Now, this works as a trigger for one camera, but I have multiple cameras. How would I be able to list those cameras in the trigger without having 10 different entries, or is that the best/only way?

warm burrow
#

hello friends, a question, as far as i know the temperature displayed for a zone (in dashboard) is randomly picked from any temp sensors assigned to that area? but if i remove all but one i can get the one i want to show up, this is no problem

thing is, my fridge temp sensor is offset/uncalibrated, has no calibration feature, so i made a helper that lets me offset a number, with a slider, this lets me adjust a value for that entity

i then created had this template sensor in sensors.yaml (i assume to use the {} syntax to calculate):

- platform: template sensors: Fridge_Temp_Adjusted: friendly_name: "Fridge Temp" unit_of_measurement: "°C" value_template: "{{ states('sensor.kyl_temperature') | float - states('input_number.kyl_offset') | float }}"

which then gives me the correct temperature for my fridge, and it seems to work.

But im stuck at getting it to be the displayed temp on the picture entity card for that area

#

i have tried adding:
attributes: room: "Kitchen"
as well as:
attribute_templates: room: "Kitchen"

#

ignore the indents, its proper in yaml

#

let me know if this is the wrong channel/server

#

and feel free to ping if you have any ideas 💌

lofty mason
warm burrow
#

sorry, yes

#

id post some pics, but i see theres no image perms

#

but not needed i think

#

i just got a zigbee display temp sensor, it works amazingly, displays on my bedroom area card, but my offset entity fridge temp isnt a "sensor" but a template sensor, cant seem to find how to assign an area, in the forums it was mentioned its not possible, but that changed, but i got stuck there

lucid thicket
#

Add a unique_id to your sensor so that you can modify it in the UI and add it to an area

#

@warm burrow ^

#

You are using the legacy format, you may also want to convert to the new template sensor format (which goes under the main key template: as opposed to sensor:)

flint pagoda
#

I'm struggling with a template sensor. All family members are defined as a "Person" in HA and are tracked through various devices. I want to display their location but change they way it is being displayed: "not_home" with "Away" and "home" with "Home and everything else ie if there is a zone defined it should show that. What I have done is working except for the "else" part - it should simply show the value of the person.xxx entity but all I get is "unknown":

#
  • platform: template
    sensors:
    manueltracker:
    friendly_name: "ManuelTracker"
    value_template: >-
    {% if is_state('person.manuel', 'not_home') %}
    Away
    {% elif is_state('person.manuel', 'home') %}
    Home
    {% else %}
    "{{ person.manuel }}"
    {% endif %}
#

I must be missing something simple here!

plain magnetBOT
#

@flint pagoda To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

marble jackal
#

also note you can simply use {{ state_translated('person.manuel') }}

flint pagoda
edgy umbra
#

How can you check in javascript if the day is today and if not show yesterday or 2 days ago etc.

mighty ledge
#

You have to code that out yourself

#

That’s also not a template question

thorny snow
#

Previously I had asked for help and got this to work:

{{ state_attr('sensor.double_take_officetable1', 'matches') | selectattr('name', 'eq', 'mike') | selectattr('match', 'eq', True) | list | count > 0 }}

Now, this works as a trigger for one camera, but I have multiple cameras. How would I be able to list those cameras in the trigger without having 10 different entries, or is that the best/only way?

marble jackal
#
{{ states.sensor | selectattr('attributes.matches', 'defined') | map('attributes.matches') | sum(start=[]) | selectattr('name', 'eq', 'mike') | selectattr('match', 'eq', True) | list | count > 0 }}

Does this work?

summer arch
#

What am I doing wrong. Trying to have template sensors that measure bed if we are charging our phones after a certain time (to add more sensors and smarts later) but these don't show up 😦

plain magnetBOT
#

@summer arch I converted your message into a file since it's above 15 lines :+1:

summer arch
#

I tested the templates in dev tools, but now trying to add the triggers to configuration.yaml and it doesn't seem to work

marsh cairn
#

Your binary sensor is formatted wrong

#

(Assuming you put that all under template:)

summer arch
#

I have multiple files for templates for organisation

summer arch
marsh cairn
#

Because your indentation is wrong

summer arch
#

no wait, the trigger isn't - trigger:

#

Do you need to mask true and false to on and off?

marsh cairn
#

No

summer arch
#

I guess the triggers aren't working then 🤷

marsh cairn
#

I guess, your binary_sensor part is still formatted wrong

summer arch
#

Ok? And how's that? Or are you intentionally omitting helpful information?

marsh cairn
#

No. You should have a look at the docs. Sensors and binary sensors are not in the list of triggers.

#

Like the example of the docs I linked.

summer arch
summer arch
summer arch
summer arch
summer arch
marsh cairn
#

How is your YAML looking like right now?

plain magnetBOT
#

@glass fjord I converted your message into a file since it's above 15 lines :+1:

#

@tawny coral I converted your message into a file since it's above 15 lines :+1:

plain magnetBOT
#

@glass fjord I converted your message into a file since it's above 15 lines :+1:

rich moss
#

can anybody figure out why the following template only listens for the first two entities:
{{ is_state('binary_sensor.staff_entrance_is_dark', 'off') and is_state('binary_sensor.smoking_area_is_dark', 'on') and is_state('binary_sensor.staff_entrance_motion', 'off') and is_state('binary_sensor.staff_entrance_person_detected', 'off') }}

marble jackal
#

Probably because the 2nd entity is off

rich moss
#

but the following is listening to all entities as expected:
{{ is_state('binary_sensor.charging_room_is_dark', 'off') and is_state('binary_sensor.charging_room_motion', 'off') and is_state('binary_sensor.key_room_motion', 'off') and is_state('binary_sensor.key_room_person_detected', 'off') }}

marble jackal
#

No need to check for the other ones then

rich moss
#

oh

#

smart

#

thank you ive been pulling my hair out

near sail
#

hi everybody; i've successfully added a template helper using the HA UI (offset to a temperature sensor) but I'm not able to use the added helper as an entity. what am I doing wrong?

barren pecan
#

Hi, I want to know how I can add a JSON from a link and then Home Assistant actualize this information every hour or every half an hour. Thank you.

inner mesa
quartz fulcrum
#

On https://www.home-assistant.io/docs/configuration/templating/, it often says "can be used as a filter", but I fail to use the correct syntax 🙈 My assumption was that something like this would work, but it doesn't: {{ integration_entities("tapo_control") | select("match", "switch\..*privacy$") | list | area_entities("aussen") }}

I get the error TypeError: area_entities() takes 2 positional arguments but 3 were given, so apparently the three entities returned by | list are passed as the arguments.

Any hints on where I can find docs on what it means that these things can be used as a filter?

mighty ledge
#

i.e. | map('area_entities', 'aussen')

#

and afterward, you're going to get a list of lists

#

if you want a single list, you'll have to add them together

#
{{ integration_entities("tapo_control") | select("match", "switch\..*privacy$") | map('area_entities', 'aussen') | list | sum(start=[]) }}
#

edit: unique isn't needed

marble jackal
#

In this case I don't understand why you would use area_entities there.

When it says can be used as a filter it means you can either do
arrea_entities('aussen') (used as function) or 'aussen' | area_entities.

However, in both cases it needs an area name or area id as input. Not an entity_id.

What are you trying to achieve @quartz fulcrum

The template Petro gave will work like this

{{ integration_entities("tapo_control") | select("match", "switch\..*privacy$") | map('area_id') | map('area_entities') | list | sum(start=[]) }}
mighty ledge
#

oops forgot the area_id in between

floral shuttle
#

is the reject the best way to diff to lists? we cant use - like we can use + between lists, but the reject requires one to know which list contains most items.```
{% set group_list = states.light
|selectattr('attributes.is_hue_group','defined')
|selectattr('attributes.is_hue_group','eq',true)
|map(attribute='entity_id')|list %}

{{group_list|reject('in',label_entities('hue_groep'))|list}}

{{label_entities('hue_groep')|reject('in',group_list)|list}}```

#

the first results in the correct diff, the second returns [].... which is correct ofc. But I simply want to find the difference between them without caring about either length. (group_list contains all groups , label_entities contains only a subset)

mighty ledge
#

Use set

#

set(a)-set(b)

barren pecan
#

It doesn't work, this code. I'm trying to get a JSON from the link and get the longitude and longitude of the ISS, but it doesn't work. Could you help me, please? Thank you.

rest:
  - resource: http://api.open-notify.org/iss-now.json
    sensors:
      - name: 'ISS longitude'
        value_template: "{{ value_json.iss_position.longitude | float}}"

      - name: 'ISS latitude'
        value_template: "{{ value_json.iss_position.latitude | float}}"
lofty mason
plain magnetBOT
barren pecan
#

I, however, want to have the direct access to the information such that I can utilize JSON on Home Assistant. Can you help me? My entities are not showing up. Thanks!

lofty mason
#

otherwise looks correct

#

if that's the issue there should have been a message in your log about it

floral shuttle
# mighty ledge set(a)-set(b)

thx, wasnt aware of that. however, it results in the same albeit in {} and not being a list. It still needs to know the order, and for that, the content of the 2 lists.

marble jackal
#

Cast the set to a list again using | list

floral shuttle
#

yes, I am aware how to make that into a list again, but thats not my quest. my hope is to find a way to use 2 lists, and find thd difference between them without having to know the number of items in the list (to know which to substract from the other). As you can see in the screenshot, the reject itself works just fine, but only when the correct order is used (btw, that is also required using the set() python method)

#

this seems to work, but it feels really hacky: {% if group_list|length >= label_list|length %} {{group_list|reject('in',label_list)|unique|list}} {% else %} {{label_list|reject('in',group_list)|unique|list}} {% endif %}

#

doesnt work either.... it doesn pick all the unique items from both lists..

marble jackal
#

to find the differences in 2 lists, you need to do both, and add them together

{% set a = [ 'a', 'b', 'c', 'e' ] %}
{% set b = [ 'a', 'b', 'c', 'f' ] %}

{{ (set(a) - set(b)) | list + (set(b) - set(a)) | list }}
#

Result: ['e', 'f']

floral shuttle
#

thanks, yes that works nicely.

#

and yet (somehow this has eveolved quickly...) I dont think it is the same as the 'difference'. The above is the lis of unique items for both lists. argh, I need to rethink this.

#

no, I do believe this is working as I had hoped for. Its a bit convoluted, (seems a very common operation, would have expected a more direct function() for it) but it does what I need right now. thanks again (also Petro)

floral shuttle
#

moving a few more templates away from {{states.domain}}, would there be any benefit at all to use the integration_entities version here:```
{{states['light']
|map(attribute='entity_id')
|select('in',integration_entities('homekit_controller'))
|select('has_value')|list|count}}

{{expand(integration_entities('homekit_controller'))
|selectattr('domain','eq','light')
|map(attribute='entity_id')
|select('has_value')|list|count}}```

#

seems more narrowed down to begin with selecting only a sub set of states, but then requiring them to be expanded is less efficient ?

marble jackal
#

The first one is throttled to one update per second

floral shuttle
#

right, I didnt even think about that aspect, and was thinking more in terms of required internal operations, or memory usage.

#

whats remarkable now, when entering the states. template it indicates to only listen to state changes of those particular light entities. I always believed states. templates listen to all state changes, and that being the main reason to avoid those.

#

the expand template above listens to all homekit entities, and those are way more!

dreamy badge
#

How can I use templates or variables to make piper speak? Like have it say 'It is now 20 degrees outside'? It uses sort of a webcall with message=word+word+word (no spaces).

hard sundial
#

Hi, i got an sensor on my balcony door that i want to know how long since its been open/triggered by announcing it with TTS, how would i do that? Something like «It was last triggered (mins) ago» not sure how i put it in HA to make it work

mighty ledge
#

you're starting with a defined small list, vrs all lights. The defined small list will always win. I.e. avoid states.light and use integration_entities as the base

mighty ledge
hard sundial
mighty ledge
#

Yep, then that's what you'd need for it to say 15 minutes

hard sundial
#

Okey nais, not too familiar with templates, do i need to change binary_sensor to what my sensor is called?

mighty ledge
#

yes

arctic sorrel
#

They want to use templates in a TTS service call

#
data:
  media_content_id: >-
    media-source://tts/tts.piper?message=Beweging+aan+de+voordeur&language=nl_BE&voice=nl_BE-nathalie-medium
  media_content_type: provider
``` is where they're starting from
mighty ledge
arctic sorrel
#

No point in making it easy for us to help after all

hard sundial
#

What kind of template would i need to make an automation if someone presses a botton it will send the current time as a notification to phone?

mighty ledge
#

depends on what format you want the time in

hard sundial
#

what u mean? like 3PM?

mighty ledge
#

There's many different ways to represent time

#

military time, US time, whatever you can dream up

#

e.g. I use 9:22 AM

hard sundial
#

i guess i want CET ?

mighty ledge
#

that's a timezone...

#

military time is would be 22:10 for 10:10 PM.

#

do you want seconds? do you not want seconds?

hard sundial
#

yes then i want miliary time

#

not seconds

mighty ledge
#

ok, then {{ now().strftime("%H:%M") }}

hard sundial
#

Ah it works thank u very much

rich moss
#

is there any way to add a timer to the following helper template. so it only activates if all statements are true for 1 minute:
{{ is_state('device_tracker.lmr', 'not_home') and is_state('device_tracker.waffle_shop_3', 'home') and is_state('device_tracker.log_flume_photos_3', 'home') and is_state('device_tracker.casablanca_2', 'home') and is_state('device_tracker.safe_room_2', 'home') and is_state('device_tracker.safe_room_3', 'home') }}

lofty mason
rich moss
#

that sounds like what I want but not sure what you mean in the second half of your sentance

lofty mason
#

Template sensors can be added either in yaml in your configuration.yaml, or by adding a helper in the UI.
The helper menu in the UI does not have delay_on as an option, so you'll have to go the yaml route.

rich moss
#

it has a template option though

lofty mason
#

Yes, it can add some templates, but it has more limited/simplified options

rich moss
#

on that page can I add the delay to the template

mighty ledge
#

no, that's what he means by the UI

#

you have to use yaml

rich moss
#

UGHGHGHHH

#

that suckss

#

I have 25 completed helpers in the UI i now need to put into the yaml

#

does this look right?

  - platform: template
    sensors:
      custom_condition:
        value_template: "{{ is_state('device_tracker.lmr', 'not_home') and is_state('device_tracker.waffle_shop_3', 'home') and is_state('device_tracker.log_flume_photos_3', 'home') and is_state('device_tracker.casablanca_2', 'home') and is_state('device_tracker.safe_room_2', 'home') and is_state('device_tracker.safe_room_3', 'home') }}"
        delay_on: 00:01:00```
#

for yaml

#

I'm not that good with yaml syntax

#

I'm not sure where delay_on should go

#

oh i guess it probably needs a more descriptive name aswell

#
  - platform: template
    sensors:
      custom_condition:
        value_template: "{{ is_state('device_tracker.lmr', 'not_home') and is_state('device_tracker.waffle_shop_3', 'home') and is_state('device_tracker.log_flume_photos_3', 'home') and is_state('device_tracker.casablanca_2', 'home') and is_state('device_tracker.safe_room_2', 'home') and is_state('device_tracker.safe_room_3', 'home') }}"
        delay_on: 00:01:00```
mighty ledge
#

no

#

follow the docs and the examples in the docs

#

I also recommend using the new template configuration, not the legacy template integration

rich moss
#

Does this look any better?

  - lmr_network_power_is_off:
      - name: "Custom Condition"
        state: >
          {{ is_state('device_tracker.lmr', 'not_home') and 
             is_state('device_tracker.waffle_shop_3', 'home') and 
             is_state('device_tracker.log_flume_photos_3', 'home') and 
             is_state('device_tracker.casablanca_2', 'home') and 
             is_state('device_tracker.safe_room_2', 'home') and 
             is_state('device_tracker.safe_room_3', 'home') }}
        delay_on: 00:01:00
mighty ledge
#

nope

#
template:
  - binary_sensor:
      - name: ....
rich moss
#
  - binary_sensor:
      - name: lmr_network_power_is_off
        state: >
          {{ is_state('device_tracker.lmr', 'not_home') and 
             is_state('device_tracker.waffle_shop_3', 'home') and 
             is_state('device_tracker.log_flume_photos_3', 'home') and 
             is_state('device_tracker.casablanca_2', 'home') and 
             is_state('device_tracker.safe_room_2', 'home') and 
             is_state('device_tracker.safe_room_3', 'home') }}
        delay_on: 00:01:00```

hows that?
mighty ledge
#

That looks good

rich moss
#

Awesome thanks!

mighty ledge
#

each additional sensor, you don't need the template: line

#

and if they are all binary sensors, you can just list them all under

template:
  - binary_sensor:
#

e.g.

#
template:
  - binary_sensor:
      - name: lmr_network_power_is_off
        ....
      - name: lmr_network_power_is_off2
rich moss
#

what about delay_on could i put that under - binary_sensor: or template: once instead of each sensor?

mighty ledge
#

nope, you'll need it on each one

rich moss
#
  - binary_sensor:
      - name: lmr_network_power_is_off
        ....
      - name: lmr_network_power_is_off2
delay_on: 00:01:00```
#

oh okay

rich moss
#

if i wanted to change the friendly name is this looking good?

  - binary_sensor:
      - name: lmr_network_power_is_off
        attributes:
          friendly_name: lmr & nms
        ....
      - name: lmr_network_power_is_off2
delay_on: 00:01:00```
marble jackal
#

just change the name

rich moss
marble jackal
#

sure you can

#

it's not the entity_id or object_id

#

it is the friendly name of the entity

#

it will get slugified to determine the entity_id

rich moss
#

Oh so i dont even need all the underscores?

marble jackal
#

nope

rich moss
#

Oh okay thanks 🙂

marble jackal
#

if you give your sensor a unique_id you can even change the name and entity_id in the GUI

fallow jetty
#

Hey I am trying to implement a template condition check, that makes sure that the automation hasn't been run in the past 6 hours (excluding the current run). I came up with the following https://dpaste.org/GW2Pp , but this seems to fail on the condition with:

Error: In 'and' (item 5 of 5): In 'template' condition: ValueError: Template error: as_timestamp got invalid input 'None' when rendering template '{% set last_triggered = as_timestamp(state_attr('automation.main_event_automation', 'last_triggered')) %} {% set current_time = as_timestamp(now()) %} {{ (current_time - last_triggered) > 180 and (current_time - last_triggered) < 21600 }}' but no default was specified

What can I do to get this work with the templated condition?

rich moss
#

The automation could run the script.

#

Just an idea there could be a better solution or it might not work in your case im not sure.

marble jackal
#

so the easiest solution is to use a default 🙂

#
          - condition: template
            value_template: >-
              {% set last_triggered = as_timestamp(state_attr('automation.main_event_automation','last_triggered'), default=0) %}
              {% set current_time = as_timestamp(now()) %}
              {{ (current_time - last_triggered) > 180 and (current_time - last_triggered) < 21600 }}
#

the autoamation you are using this condition in, is not the same one as mentioned in the condition right?

fallow jetty
#

Unfortunately, the condition has triggered before.

#

I do have a default set though, with "send a notification to my phone"

#

But, this had run a few days prior to just send notifications to make sure it worked without this template condition

marble jackal
#

well, according to your error state_attr('automation.main_event_automation','last_triggered') returned none which it will if 1) the automation doesn't exist or 2) it hasn't triggered yet

fallow jetty
#

So I guess at that point, is it easier to just use a counter and reset it once a day? 🤔

#

I mean, I am interested in learning this but for a single person home assistant situation, it seems easier. 😄

marble jackal
#

What are you exactly trying to achieve?

#

You have automation A, and you only want that to trigger if automation B triggered somewhere between 3 minutes and 6 hours earlier

fallow jetty
#

I have Automation A, and I want it to trigger if Automation A has not run in the past 6 hours.

#

But because of that flow, it would always fail, so I added a if > 2 or 3 minutes, and < 6 hours

lucid thicket
rich moss
#

I had these helper template sensors in the UI set as problem sensors but I had to use the configuration.yaml to add a delay so they no longer use the UI but how can I set these as problems using the configuration.yaml?

#
  - binary_sensor:
      - name: Lakeside Network Power is Off or Radar Hit
        state: >
          {{ is_state('device_tracker.lmr', 'not_home') and is_state('device_tracker.waffle_shop_3', 'home') and is_state('device_tracker.log_flume_photos_3', 'home') and is_state('device_tracker.casablanca_2', 'home') and is_state('device_tracker.safe_room_2', 'home') and is_state('device_tracker.safe_room_3', 'home') }}
        delay_on: 00:01:00
  - binary_sensor:
      - name: Valhalla Network Power is Off
        state: >
          {{ (is_state('device_tracker.casablanca_2', 'not_home') and is_state('device_tracker.safe_room_2', 'home') and is_state('device_tracker.safe_room_3', 'home')) or (is_state('device_tracker.casablanca', 'not_home') and is_state('device_tracker.main_office_2', 'home') and is_state('device_tracker.safe_room_2', 'home') and is_state('device_tracker.safe_room_3', 'home')) }}
        delay_on: 00:01:00
  - binary_sensor:
      - name: Log Flume Photos Network Power is Off
        state: >
          {{ is_state('device_tracker.log_flume_photos_3', 'not_home') and is_state('device_tracker.casablanca_2', 'home') and is_state('device_tracker.safe_room_2', 'home') and is_state('device_tracker.safe_room_3', 'home') }}
        delay_on: 00:01:00
lofty mason
#

add device_class: problem

rich moss
#

would that go under name?

lofty mason
winter forge
#

How can I use this

selectattr('attributes.rgb_color', 'defined') |

With

{{ [area_id('binary_sensor.group_office_motion_occupancy')] | map('area_entities') |
sum(start=[]) | select('search',
'^light\.') | unique | list }}

I tried inbetween every argument

plain magnetBOT
#

@rich moss I converted your message into a file since it's above 15 lines :+1:

rich moss
#

sweet that worked

crimson fulcrum
#

I was told to ask here for some help with a template that will allow me to create a trigger for automations that triggers every 10 days

#

¬_¬

lucid thicket
crimson fulcrum
#

I ended up trying this:

#

{{ (now().timestamp() / 86400) | int % 10 == 0 }}

#

kind of hard to validate if it works though :)

lucid thicket
#

That will do the exact same thing

#

You can validate it by adding days.
{{ (now() + timedelta(days=1)).timestamp() // 86400 % 10 == 0 }}

#

Try different numbers of days until you convince yourself it works every 10th day

crimson fulcrum
#

thank you for the help :)

lucid thicket
#

Edited

crimson fulcrum
#

I'm also seeing if I can use a local calendar for the same result

lucid thicket
#

That would work too

crimson fulcrum
#

{{ trigger.calendar_event.summary == 'event summary' }}

#

using this as a condition

#

sensible?

#

hm didn't work!

lucid thicket
#

That looks like it should work as long as the text matches what you put as the event title. I haven’t played with calendars so I only know what I’ve read in the docs

crimson fulcrum
#

Yeah I found an example of someone using it this way too, but I just put in a test event, with the same event title, and didn't get anything to trigger

#
alias: Litter Reminder Calendar
description: ""
trigger:
  - platform: calendar
    event: start
    entity_id: calendar.reminders
condition:
  - condition: template
    value_template: "{{ trigger.calendar_event.summary == 'Clean Litter' }}"  
lucid thicket
#

For troubleshooting purposes, remove (or disable) the condition. Then get it to trigger. Then look at the trace and see what is in the trigger variable

crimson fulcrum
#

hm interesting, it didn't trigger even without the condition

lucid thicket
#

Any trigger has to transition from false to true. So if the event is already happening and then you create the automation it won’t trigger

crimson fulcrum
#

I set the event 2 minutes from current time

lucid thicket
#

OK that should work

crimson fulcrum
#

I'm seeing everyone sharing snippets that look exactly the same as mine!

#

very confused here

lucid thicket
#

The folks in #automations-archived probably know better than I do. I know templates and most things in automations I just never deal with calendars. So I’m just throwing darts

crimson fulcrum
#

I'll give them an ask

#

I appreciate all the help all the same

lucid thicket
#

Np

flat cave
#

I'm trying to work out how to make a template work.

I want to see what the weather max temp will be today

{{state_attr('weather.home','temperature') }}degrees

But it says what it is now.

I assume I just can't work out the way to ask for "max temp"

Thanks

lucid thicket
#

Do you have an entity that contains the max temp in an attribute?

flat cave
#

It was working before the change.

But now i am thinking as there isn't a max temp I need a helper to make a service ?

hard sundial
#

Hi, Is there any way to see the mins aswell with template when its gone over an hour since device was last triggered? Currently it only says last triggered an hour ago. I want it in a TTS

marble jackal
#

What's your current template?

hard sundial
#

{{ relative_time(states.input_boolean.toggle.last_changed) }}

marble jackal
#

{{ time_since(states.input_boolean.toggle.last_changed, precision=2) }}

hard sundial
#

Ah damn nice thank you

merry marsh
#

Is there a faster way for default value if an item is not in a list than this?

    {% if 'foo' in var_icon_array %}
        {{ var_icon_array['foo'] }}
    {% else %}
        bar
    {% endif %}

So directly e.g. define a default in the list?

wanton sapphire
mighty ledge
#

but var_icon_array is incorreclty named because that's not an array it's a dictionary

#

I'd rename that variable, otherwise you'll confuse people who will attempt to help you. Arrays cannot use ['key'] or .get('key') or .key

#

those are exclusive to dictionaries

bronze prawn
#

{{device_id('binary_sensor.assistsatmasterbath_assist_in_progress')}}

I know this will give me device_id, but I have device_id and would like entity_id from it. How do I do the reverse of the example I'm showing?

mighty ledge
#

device_entities

hallow plover
#

I'm trying to write a template. I have this bit:
{{ (expand('binary_sensor.conflict_group') | selectattr('state', 'eq', 'on') | list) }}
And it mostly works. For example, right now I get the output:
[<template TemplateState(<state binary_sensor.garage_door_conflict=on; device_class=problem, friendly_name=Garage door conflict @ 2024-05-22T07:55:25.700079-05:00>)>]
What can I do to filter this so that it only provides the first entry in the list in the case where the list has multiple entries?

mighty ledge
#

| first

#

and you'll probably want a | default after for when it doesn't have any items in the list

hallow plover
#

Simplifying a bit:

    selectattr('state', 'eq', 'on') | list ) %}
{{ entity.entity_id }}
{% endfor %}``` works fine, ```{% for entity in (expand('binary_sensor.conflict_group') |
    selectattr('state', 'eq', 'on') | list | first)  %}
{{ entity.entity_id }}
{% endfor %}``` results in key error
mighty ledge
#

right because you pulled the first item from the list... it's now not a list

#

so you can't iterate it

hallow plover
#

So how can I only do any work on the first item that appears in the list?

mighty ledge
#

set it to a variable, then use the variable

#
{% set a = expand('binary_sensor.conflict_group') | selectattr('state', 'eq', 'on') | list | first | default %}
{% if a %}
  {{ a.entity_id }}
{% endif %}
hallow plover
#

That works. Thanks!

tropic charm
#

👋🏻 i'm trying to use an automation to get a string entry for the specific day of the week (and use set_text to set that day of the week entry as the value for another entity. but i'm very much struggling 😬

i setup an input_text with the state as an array ['a', 'b', 'c', 'd', 'e', 'f', 'g'].

  1. is that the right way to 'represent' an array?
  2. what would the YAML look like to get the value that represents the day of the week integer (e.g., day of week 0 should get 'a')?
plain magnetBOT
#

@fiery umbra I converted your message into a file since it's above 15 lines :+1:

unkempt hamlet
#

So I can select, for example, my light bulb, and every time the state changes, it will change the JSON @arctic sorrel

{"bedroom_light":"On", "bedroom_light_brightness":30, "tv_bedroom":"on"}

fiery umbra
unkempt hamlet