#templates-archived

1 messages ยท Page 33 of 1

atomic blade
#

That's a good point. So maybe actually a default is fine here

marble jackal
#

This is a perfect case for default=0

#

But you don't have to use 0, you can use anything

atomic blade
#

I think 0 makes sense here

marble jackal
#

In this case it does

atomic blade
#

Gotta say, you're one of the most helpful people on here!

marble jackal
#

You're welcome! And thanks

atomic blade
#

This is the state template: {{ this.state|int(0) + 1 }}

marble jackal
#

I guess changing the config of the sensor can cause that

atomic blade
#

I have another template trigger sensor that seems to survive reloads fine, though it's an event trigger

#

But it's still the same concept I would think. Don't see anything in the docs that say it isn't persisted, but I can't actually find docs for this specifically I don't think. These are the docs for triggers as they apply to automations

#

Though most of the concepts are the same

marble jackal
#

Reload the config of the trigger

atomic blade
#

I'm saying when I do reload the config it gets set to unknown. Although I did slightly cheat which is maybe why this is happening. I set the state in dev tools since the underlying trigger doesn't happen often. Just wanted to set the initial value

#

I've always been a little confused how setting it this way differs from when it's set normally. I'm wondering now if setting it in dev tools doesn't have to get picked up by the recorder? So maybe when it's reloaded it isn't able to get the previous state?

#

So basically what I did from the start was 1) create the sensor config 2) reload my template sensors so it was picked up into HA 3) go into dev tools and set it to an initial value of 4) reload the template sensor config again and then it gets set back to "unknown"

#

I wonder if I update the underlying sensor in dev tools that makes a difference...

#

That worked!

#

I've actually been trying to think of a way to make another sensor and I think a trigger is the way to go

#

I want to estimate the amount of water left in my robot vacuum's tank. I have an estimate on the rate at which is uses water based on cleaning area

#

And then I need to have it reset after I refill the tank

final sun
#

{{now() - states('sensor.saugroboter_og_cleaning_history') | as_datetime | as_local}}

How can I change that to full days? I get 2 days, 20:20:39.063150 but want it to show 3 days since the date are 3 days apart

marble jackal
#

What do you want it to show if the difference is only one hour?

#

{{ (now() - states('sensor.saugroboter_og_cleaning_history') | as_datetime | as_local).total_seconds() }} will give you the number of seconds

#

You can divide that by 60 * 60 * 24 to get the number of days

#

You can then decide how to round that

winter cape
#

is there any way to find out if a trigger was used for shutdown? I have a smart diffuser that shuts off when it runs out of water. I would like to set up a notification to refill water. ie, when a shutdown occurs via google, from HA do not send a notification, if a shutdown occurs without a trigger, send a notification.

marble jackal
#

You can check probably check the context. If it has a user_id, it was issued by a user

winter cape
#

THX. How to check the context? If I make an automation with {{trigger}} message, it shows (for example light) this: {'id': '0', 'idx': '0', 'alias': None, 'platform': 'state', 'entity_id': 'light.office_table_light', 'from_state': <state light.office_table_light=on; supported_color_modes=[], color_mode=onoff, mode=normal, dynamics=none, friendly_name=Office table light, supported_features=LightEntityFeature.0 @ 2023-03-18T09:30:03.619754+01:00>, 'to_state': <state light.office_table_light=off; supported_color_modes=[], mode=normal, dynamics=none, friendly_name=Office table light, supported_features=LightEntityFeature.0 @ 2023-03-18T09:30:27.536371+01:00>, 'for': None, 'attribute': None, 'description': 'state of light.office_table_light'}

#

Trigger was deconz switch

mental violet
#

Hello,
I have a sensor with this template:

{{negativ_tallies|round(2)}} ```
but it has a lot of holes in the history tap and I dont know why. The data of february is completly gone and in march there is no data from 1. of march until 12. of march. But since 12 of march the history is correct.
sonic nimbus
#

Hi i wanted to chek with you guys if this templating is ok:

                custom_message: > 
                  {% "Please, close bedroom wardrobe." if trigger.id == 'Bedroom' else "Please, close office wardrobe." %}

Based on my trigger id in the trigger section, I want to send different message.

mental violet
#
custom_message: >-
  {% if trigger.id == 'Bedroom'%}
    {{"Please, close bedroom wardrobe."}}
  {%else%}
    {{"Please, close office wardrobe."}}
  {%endif%}

this is how I learned that. This should be fine.

marble jackal
marble jackal
#
custom_message: >-
  {% if trigger.id == 'Bedroom' %}
    Please, close bedroom wardrobe.
  {% else %}
    Please, close office wardrobe.
  {% endif %}
marble jackal
sonic nimbus
#

Thanks! I prefer more one liner than to have multiple lines

marble jackal
final sun
marble jackal
#

You can subtract just the dates

#

{{ ((now().date() - (states('sensor.saugroboter_og_cleaning_history') | as_datetime | as_local).date()).total_seconds() / (60 * 60 * 24)) | int }}

final sun
#

Ty I'll take a look ๐Ÿ‘

marble jackal
ashen sequoia
#

Wow yea I'm dumb, thanks

heady cedar
inner mesa
#

whatever the call returns

keen oriole
#

May I use the state (text) in a text helper as device name in an automation? Tried the following which does not work: entity_id: "{{ states('input_text.tht_phone') | string }}"

rare panther
#

state is already a string, you do not have the pipe it

marble jackal
#

And if that entity_id key part of a service call? If so, is it placed either under target: or data:?

keen oriole
#

planned to be use in below and other places (to avoid changing multiple automations, scripts etc when chaning a phone (or other devices)platform: zone entity_id: "{{ states('input_text.tht_phone') | string }}" zone: zone.home event: enter id: THT Arrive Sorry, disregard, can see I miss something more now when editing the old one in yaml..

marble jackal
#

And you can't use templates in a zone trigger

keen oriole
#
entity_id: device_tracker.{{ states('input_text.tht_phone')}}
zone: zone.home
event: enter
id: THT Arrive```
#

Did spot the S23 got an underscore in the name which is missing in my input text

marble jackal
#

It's also missing a domain

#

Like person. or device_tracker.

keen oriole
#

I can see that my new phone already have several automations.... Is there a "bug" here introduced by the fact that when transfering data from old to new phone as all those automations is written for my old phone.. and the app when moved somewhat believes it is my old phone........ (Not related to the above thought but an interresting discovery as the S20 is the device mentioned in all the automations under my S23 phone.

marble jackal
#

You need to use a template trigger

#

But what is your goal here

marble jackal
keen oriole
#

I want to have one place to enter an ID to avoid chaning xx number of automations and scripts every time I change a mobile or other devices for me and the rest of the family. This to get locations, send alerts, control the home based on location etc. I is quote cumbersome to edit all this to change a device

marble jackal
#

So automations referring to your old phone, will still refer to your old phone

marble jackal
#

Or smart use of templates in variables

keen oriole
marble jackal
#
trigger:
  - platform: template
    value_template: "{{ is_state('device_tracker.' ~ states('input_text.tht_phone'), 'home') }}"
keen oriole
marble jackal
#

You mean entity_id right?

keen oriole
#

yes sorry

marble jackal
#

As long as templates are allowed you can use your input text for the entity_id

keen oriole
#

I assume this happens due to the samsung "migration" / transfer data from phone to phone process

marble jackal
acoustic arch
#

If pickup_start: '2023-03-19T16:00:00Z' is today, i would like to output the string 'today', If its tomorrow, then 'tomorrow', else just the date. any smart syntax available?

acoustic arch
#

inching closer.....

#
{% set today = now() | as_timestamp | timestamp_custom('%d-%m-%Y') | string %}
{% set tomorrow = (now() + timedelta(days=1)) | as_timestamp | timestamp_custom('%d-%m-%Y') | string %}

{% if pickup == today %}
  vandaag
{%elif pickup == tomorrow %}
  morgen
{%else %}
  {{pickup}}
{%endif%}```
bingo
marble jackal
#
{% set pickup = state_attr('sensor.bla', 'pickup_start') | as_datetime %}
{% if now().date() == pickup.date() %}
  vandaag
{% elif (now() + timedelta(days=1)).date() == pickup.date() %}
  morgen
{% else %}
  {{ pickup.strftime('%d-%m-%Y') }}
{% endif %}
#

@acoustic arch

#

That's how I would do it

acoustic arch
#

Thank you. Thats wat more compact ๐Ÿ‘๐Ÿฝ

unborn sequoia
#

I would like to ask one more question. Would it be difficult to create a similar one for this sensor that would monitor the value every day at 0:00 and add it up? During the month it would increase and then at the end of the month the resulting value would be plotted on the graph?

Thank you.

marble jackal
#

do you want something similar as the energy dashboard shows?

plain magnetBOT
rich quarry
#

I have this template perl {% set people = [] %} {% for person in expand('group.trackers_all_people') %} {% set input_boolean = 'input_boolean.' + person.entity_id.split('.')[1] + '_longer_away' %} {% if person.state == 'not_home' and not is_state(input_boolean, 'on') %} {% set people = people + [person] %} {{people|length}} {% endif %} {% endfor %} {{people|length}} {% if people|length == 1 %} {{ people[0].name }} is not home. {% elif people|length > 1 %} {{ people|map(attribute='name')|join(' and ') }} are not home. {% endif %} but for some reason the {{people|length}} inside the for loop is 1 and outside the for loop its 0 What could be causing this?

#

removed some empty lines so its easier to read

marble jackal
#

You need to use a namespace to be able to store data from the loop and access it outside the loop

rich quarry
#

How does one do that?

marble jackal
#

with some additional improvements:

{% set ns = namespace(people = []) %}
{% for person in expand('group.trackers_all_people') %}
  {% set input_boolean = 'input_boolean.' + person.object_id + '_longer_away' %}
  {% if person.state == 'not_home' and not is_state(input_boolean, 'on') %}
    {% set ns.people = ns.people + [person] %}
  {% endif %}
{% endfor %}
{{ ns.people|map(attribute='name')|join(' and ') }} {{ 'are' if ns.people|length > 1 else 'is' }} not home.
#

btw, if you only need the names, I would only store those in the list

#

so ns.people = ns.people + [person.name]

rich quarry
#

what name do you use for the code blocks? i mean the yaml for example

marble jackal
#

py

rich quarry
#

ah oki

marble jackal
#

it looks better than jinja ๐Ÿ™‚

young lake
#

I have two flavors of the same thing that I'm playing with. The problem comes if the system resets or the YAML is reloaded, it messes with any automations that having a time in state calculation. I need to get the prior state.
https://paste.ubuntu.com/p/MwnMc2xNkn/

marble jackal
half pendant
#

Man this universal media player is driving me crazy

#

I have a n LG and an Apple TV (connected to a pair of homepod minis) that i'm trying to group up into one device. The problem is that even if i use a different input than the Apple TV the entity still picks the Apple TV as the active child and displayes the media info from it. Also if i raise the volume on the apple tv controls (which control the entire tv volume through earc) it doesn't reflect in the entity

#

Also if i use the Mushroom Media player card and the mini-media-player with the same entity and raise the volume in one of them the volume does not change in the other.

plain magnetBOT
mighty ledge
#

just use the custom integration template media player

#

universal media player is a half attempt at a template media player without templates

#

that makes a bunch of assumptions based on how you configured it

#

if you want 100% control, custom template media player

marble jackal
half pendant
#

i looked at that one but since it wasn't maintained anymore i figured it wasn't a good way to go

mighty ledge
#

it's still maintained

#

the owner has made no mention of it being 'not maintained'

#

seems like he's just not adding feature requests

marble jackal
#

it's indicated there, but it had an update in February 2022

mighty ledge
#

yeah but he's merging changes other people provide

#

Maybe he doesn't understand what maintained means

#

it's the same for custom button card

#

people are listing it as 'not maintained' but romrider does make fixes to make it work

jagged obsidian
#

likely it's a misconfigured shield

#

see commit activity is 0 as well

half pendant
marble jackal
#

I'll give it another try, maybe I can close the issue afterward ๐Ÿ™‚

acoustic arch
#
entity: sensor.tgtg_plus_amersfoort_magic_box
tap_action:
  action: url
  url_path: '{{state_attr(''sensor.tgtg_plus_amersfoort_magic_box'', ''item_url'') }}'

although its a full https: url,clicking this takes me to domain.com/{{blabla}

#

so url_path is not template-able?

mighty ledge
#

Probably not, depends on what mushroom card docs say

acoustic arch
#

good question. didnt try regular card yet ๐Ÿ™‚

marble jackal
#

as far as I know you can't template tap_action in any card

floral shuttle
#

just noticed that {{now().weekday()}} {{as_timestamp(now())|timestamp_custom('%w')}} don't return the same number... is there a reason HA template extension doesnt not comply with timestamp jinja on this single occurence.

#

noticed because we need to do: {% set dagen = ['Maandag','Dinsdag','Woensdag','Donderdag','Vrijdag', 'Zaterdag','Zondag'] %} {% set dag = dagen[now().weekday() ] %} {{dag}} and {% set dagen = ['Zondag','Maandag','Dinsdag','Woensdag','Donderdag','Vrijdag', 'Zaterdag'] %} {% set dag = timestamp|timestamp_custom('%w') %} {{dag[dagen]}}. where timestamp is defined earlier obviously

floral shuttle
grave solstice
#

Hey... I have Two strings of Dates "March 20, 2023 at 01:40:50" is there a easy template route to make a date diff?

lofty mason
marble jackal
grave solstice
floral shuttle
marble jackal
#

weekday() starts with Monday according to the python docs

floral shuttle
#

yeah I see that now, so the one format follows strftime, and the other format follows python rules

marble jackal
#

yes. .weekday() is a python function

floral shuttle
#

guess that shows the origin of python ๐Ÿ˜‰

acoustic arch
#

{{ states.sensor | selectattr('entity_id', 'search', 'tgtg') | rejectattr('state', 'eq', '0') | map(attribute='entity_id') | list | count }} beschikbaar
Now im counting entities which state are not 0. How can i actually add all the values of the states which are numbers?

marble jackal
#
{{ states.sensor | selectattr('entity_id', 'search', 'tgtg') | map(attribute='state') | map('float', 0) | list | sum  }}`
acoustic arch
#

yey! that looks great

marble jackal
#

I have an entity sensor.tgtg_boxes which already seems to be a combination of all my favorites

acoustic arch
#

what do you mean by that?

marble jackal
#

that the state of the entity sensor.tgtg_boxes seems to be the sum of all available boxes

acoustic arch
#

im making a mushroom chip on frontend that counts the amount.

#

ooooo

#

lemme check

marble jackal
#

which also means your template will double that result

acoustic arch
#

i dont have sensor.tgtg_boxes as entity

#

you made it yourself i guess?

marble jackal
#

hehe maybe

#

then I forgot

acoustic arch
#

lolz

#

im always hesitant to make a yaml out of this kind of stuff. I tend to just code in a card

marble jackal
#

anyway, you can also do this:
{{ integration_entities('tgtg') | map('states') | map('float', 0) | sum }}

acoustic arch
marble jackal
#

mine doesn't have to iterate over all your sensors, but only over those from the tgtg integration

#

and isn't throttled

acoustic arch
#

you mean save cpu cycles?

marble jackal
#

templates containing states.domain are throttled so they don't update on any state change of a sensor

acoustic arch
#

ill make a cheat sheet somehere, to save handy stuff. I tend to come back asking almost the same question, but slightly off. ๐Ÿ˜‰

marble jackal
#

BTW, you could also just create a sensor group in the helper section

#

then you don't need to do any code

acoustic arch
#

manually adding all tgtg entities?

marble jackal
#

I don't know how many you have

acoustic arch
#

15ish

marble jackal
#

okay, then I 'd stick to the template ๐Ÿ™‚

acoustic arch
#

dunno. just added all local interesting shops

#

maybe i get freaked out at the amount of notifications and delete some

#

and coding is a learncurve, gets me further on the long run

marble jackal
acoustic arch
#

thx ill have a look.

#

looks like your notification is ever present if >0, and clears at 0?

#

at least, once the trigger sensor updates

marble jackal
#

It updates when the number available boxes updates

acoustic arch
#

so you can swipe it away, and it repopulates once one is found?

marble jackal
#

You can swipe it away, but ti will be back if there's an updat (so eg when the number of available boxes changes from 5 to 4)

#

But I only have 2 boxes, so it's not that annoying

#

you could add a button on the notification to ignore the box

plain ridge
#

How can i combine these 2?

value_template: "{{ states('sensor.envoy_122249105550_today_s_energy_production') | float / 1000 }}"
value_template: "{{ '%.2f'%(states('sensor.electric_voltage_l1') | float) | float }}"
I wanted the value template to round up numbers

acoustic arch
#

One is in watts, the other in voltage. What is there to combine?

mighty ledge
#

W = V * A

plain ridge
#

sorry, its now WH and im trying to make it KW, that works but i also want to round it up

#

the second template i send is one i found online

marble jackal
#

you can use | round(2, 'ceil') to round to 2 digits and always round up

plain ridge
plain ridge
mighty ledge
#

you have to use the integration integration to convert w to wh or kwh

plain magnetBOT
plain ridge
#

W to KW and round it

#

so i devide it by 1000

mighty ledge
#

so do you know templates at all or are you just copying and pasting? thefes provided a solution above

plain ridge
#

i did some before and im trying to learn it.

mighty ledge
#

to go from w t kw, you need to multiply by 1000

plain ridge
#

i tough 1kw = 1000w

mighty ledge
#

envoy_122249105550_today_s_energy_production sounds like thats an energy sensor not power either

mighty ledge
#

so if 1000w is 1 kw... then you need to multiply your w by 1000

plain ridge
#

you right my bad

mighty ledge
#

so is envoy_122249105550_today_s_energy_production actually a watt sensor?

#

I'm asking so many questions because you're making this hard by constantly changing what you want

#

it would be easier if you just shared exactly what you're trying to do with the entities you're trying to use

plain ridge
#

im sorry its also confusing for me

evony today energy is in Wh, i want it KWh and i want it rounded.

marble jackal
#

Make sure to wrap your formula in brackets, otherwise you'll end up rounding only 1000

quiet kite
#

Hi, over MQTT I have many integrations. Currently, everything is in one file. Can I separate these different integrations (switches, sensors...) into multiple files, so that each file describes one integration and for this integration a set of switches and sensors?

buoyant pine
#

yeah, take a look at packages

quiet kite
#

thanks

unborn sequoia
# marble jackal do you want something similar as the energy dashboard shows?

Yes, something similar as the energy dashboard would be great.

I'll try to explain it one more time. I calculate the daily balance of the household in finances. So I have unit_of_measurement. So now I have a calculated daily balance (sensor.home_costs) every day. Every day at 0:00 I save this sensor to sensor.status_at_midnight. Now I would like a sensor that will add up these daily statistics gradually for an entire month. So, for example, on the fifteenth day of the month, I will see the total for 15 days. At the end of the month, I write this final value in the graph and get the total financial balance for the given month.

Is it clear what I want to achieve?

marble jackal
#

I would just use s utility_meter for the monthly total

unborn sequoia
peak juniper
#

I am looking to find a way of reporting "this sensor was the highest value this month" or even a top 3

#

I've seen the min/max sensor but that only seems to report the value

#

I want something that says "You were in these 3 zones the most this month" or "these 3 appliances used the most electricity this month"

#

any thoughts?

mental violet
onyx cypress
#

hello everyone

I would love some help as this is my first time asking so sorry if its in the wrong channel
I'm trying to setup pihole with custom duration to auto turn on could someone help explain this to me pelase

onyx cypress
marble jackal
mental violet
#

Many of them are coded like this:{%if (states('sensor.legro_monatliche_einnahmen') != "unavailable") and (states('sensor.legro_monatliche_einnahmen') != "unknown") and (states('sensor.legro_monatliche_einnahmen') != "none") and (states('sensor.legro_monatliche_ausgaben') != "unavailable") and (states('sensor.legro_monatliche_ausgaben') != "unknown") and (states('sensor.legro_monatliche_ausgaben') != "none")%} {% set value = states('sensor.legro_monatliche_einnahmen')|float - states('sensor.legro_monatliche_ausgaben')|float%} {{value |round(2)}} {%else%} 0 {% endif %}

#

Instead of making the sensor return 0 when something is unavailable is there any other way of return the data before that happened?

marble jackal
#

the entire yaml config of the sensor

plain magnetBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

marble jackal
#

@mental violet you can really simplify your template. And I would advice to use an availability template instead of setting the value to 0 if your source sensors are not available

state: "{{ (states('sensor.legro_monatliche_einnahmen') | float - states('sensor.legro_monatliche_ausgaben') | float) round(2) }}"
availability: "{{ states('sensor.legro_monatliche_einnahmen') | is_number and states('sensor.legro_monatliche_ausgaben') | is_number }}"
maiden magnet
#

hi i am trying to split the date (year, month, day) in a seperate number
i got this, but i dont know what i have to type in for the second and the third value (after that "|")
{{ (states('sensor.date'))[1:-1].split('-') | map('float') |first }}

marble jackal
#

you don't have to use sensor.date for that

maiden magnet
#

how can i do it otherwise?

marble jackal
#

just use {{ now().year }} {{ now().month }} and {{ now().day }}

maiden magnet
#

Oh ok nice

but in this case? (it could be that i am getting to this problem a second time, without "sensor.date" as my entity?

marble jackal
#

top accually answer your question, you need to convert it to a list, and take the second item
{{ (states('sensor.date')[1:-1].split('-') | map('float') | list)[1] }}

#

why do you have the [1:-1]?

maiden magnet
#

รคhm :D i dont know, my template is a big copy of different google searches :D

marble jackal
#

okay, that takes of the first and last character of the date string, so if the date is "2023-03-21" it will result in "023-03-2"

maiden magnet
#

ohhhh

#

hahaha i were very confused, thanks :D

tender summit
#

i made a template sensor for my electricity tarif

#

how can i now use this to calculate the costs?

#
 - platform: template
    sensors:
      your_tarif:
        friendly_name: "My Tarif"
        unit_of_measurement: "CHF"
        value_template: >
          {% set tariff = { "HT": 25, "LT": 19 } %}
          {% if (now().weekday() < 5 and (7 <= now().hour <= 20)) or (now().weekday() == 5 and (7 <= now().hour <= 7)) %}
            {{ tariff.HT }}
          {% else %}
            {{ tariff.LT }}
          {% endif %}

#

this is in the configuration.yaml

mighty ledge
#

What's CHF?

tender summit
#

swiss franc

#

changed it to:

#
  - platform: template
    sensors:
      your_tarif:
        friendly_name: My Tarif
        unit_of_measurement: CHF/kWh
        value_template: >
          {% set tariff = { "HT": 0.2366, "LT": 0.1935 } %}
          {% if (now().weekday() < 5 and (7 <= now().hour <= 20)) or (now().weekday() == 5 and (7 <= now().hour <= 7)) %}
            {{ tariff.HT }}
          {% else %}
            {{ tariff.LT }}
          {% endif %}````
tender summit
#

seems like i solved it

#
  - sensor:
      - name: "Strompreis"
        unit_of_measurement: "CHF/kWh"
        state: >
          {% set tariff = { "HT1": 0.2366, "LT1": 0.1935 } %}
          {% if (now().weekday() < 5 and (7 <= now().hour <= 20)) or (now().weekday() == 5 and (7 <= now().hour <= 7)) %}
            {{ tariff.HT }}
          {% else %}
            {{ tariff.LT }}
          {% endif %}```
#

but i don't know what the difference is between this 2. they both show up and it seems they change the values as expected

#

anyone can eli5?

inner mesa
#

The first is the legacy format (now discouraged) and the second is the new format

#

Both are described in the docs for template sensors

tender summit
#

i deleted the legacy out of the configuration.yaml and did a reboot. the sensor is stil showing up

#

why?

slender laurel
#

Is it possible to have a binary sensor that shows as false, rather than off and if so, how do I configure that? Right now my binary sensor (from the template) has the on/off states...

inner mesa
#

no, a binary_sensor can be on, off, unavailable, or unknown

#

you can create a template sensor and have it report whatever you want

ripe bronze
#

Hey can somebody help me with my template. I have an input boolean with all and my scenes and want to activate a scene if i press an button. if i press the button again the next scene in the list shut be turned on. This is my code. Thanks for your help. https://dpaste.org/2GMdt

inner mesa
#

you're missing a bunch of indentation

#

proper indentation is critical for YAML

#

you also have two data sections?

#

not really sure what you're doing there

#

I guess you're missing the service call for the second bit where you're trying to set the input_select, but you can replace all of that with simply this:

- service: input_select.select_next
  entity_id: input_select.scene_switch
ripe bronze
inner mesa
#

you still have broken/no indentation

ripe bronze
#

what do you mean?

inner mesa
#

I'm not sure where you're putting that

#

you have two service calls

#

this part:

service: scene.turn_on
data:
entity_id: "{{states ('input_select.scene_switch')}}"
#

note that "entity_id: ..." isn't indented

#

the error tells me that this is all part of some much larger thing:
Message malformed: template value is None for dictionary value @ data['action'][3]['choose'][0]['sequence'][0]['choose'][0]['sequence'][0]['default'][2]['choose'][0]['sequence'][1]['data']

ripe bronze
inner mesa
#

so you need to fix your indentation

#
  - service: scene.turn_on
    data:
      entity_id: "{{states ('input_select.scene_switch')}}"
#

and get rid of the "null". I don't know what that's doing there

ripe bronze
inner mesa
#

I gave you the code

#

you saw the message?

#

it assumes, of course, that the state of that input_select is a valid entity_id

ripe bronze
inner mesa
#

dude

#

the indentation

#

the two spaces that you're missing

#

just look at it

ripe bronze
#

sorry man

inner mesa
#

if you don't pay attention to detail, you're going to have a bad time with YAML

ripe bronze
inner mesa
#

it's not a matter of language

#

spaces

#

indentation

ripe bronze
#

i did not know what indentation was, but thanks

ripe bronze
# inner mesa just look at it

Thanks man, it worked. But when i switch through the scenes and a scene with less brigtness of the lights comes on the lights dont dim down

silent reef
orchid oxide
#

not sure if templates or integrations, but im trying to use the file integration and a value template and it doesnt seem to be working right. it's showing a value of unknown.

this is whats in my config.yaml

  - platform: file
    file_path: /config/person.json
    name: device_trackers
    value_template: "{{value_json.data.items[0].device_trackers}}"
...
homeassistant:
  allowlist_external_dirs:
    - "/config"```

and this is whats in the file im trying to use
https://hastebin.com/share/eziposumol.json
#

anyone know whats going on here

mighty ledge
silent reef
orchid oxide
mighty ledge
#

Well you ahve to come up with the automation, that condition is just for an automation

mighty ledge
silent reef
mighty ledge
#

that's not a trigger

#

a trigger is something that will start the automation

#

like the light turning on

silent reef
orchid oxide
#

additionally, it works fine in dev tools template if i do it that way

mighty ledge
silent reef
mighty ledge
#

then you can use that template in a template trigger

orchid oxide
mighty ledge
#

there's only 2 things it can be with that error. The JSON is not JSON, or the file is not located where you think it is

#

there's nothing else that could be the problem

silent reef
mighty ledge
#

it's stating that value_json can't be resolved, meaning it wasn't able to make json out of the value from the file

#

and the only 2 things that mean that are: Not json, or it has nothing to read because it's the wrong file

mighty ledge
#

if yes, then you've made a trigger

#

all you need to do is select template trigger when adding the trigger and put that template into it

silent reef
mighty ledge
#

it's really not

#

add a trigger, select template trigger, paste the template

orchid oxide
silent reef
# mighty ledge it's really not

But im so confused what template i should use now ๐Ÿ˜„ I got this:
template:

  • sensor:
    • name: "Average humidity"
      unit_of_measurement: "%"
      device_class: humidity
      state: >
      {{ ( state_attr('climate.alrum', 'current_humidity')|float(0) +
      state_attr('climate.kontor', 'current_humidity')|float(0) +
      state_attr('climate.bryggers', 'current_humidity')|float(0) ) / 3 }}
      availability: >
      {{ ( state_attr('climate.alrum', 'current_humidity')|is_number and
      state_attr('climate.kontor', 'current_humidity')|is_number and
      state_attr('climate.bryggers', 'current_humidity')|is_number ) }}
mighty ledge
#

why are you concerned with that template?

#

that's in the past, that should already be in your system

#

this is all you care about now

{{ state_attr('climate.alrum', 'current_humidity')|float(0) <= 1.1 * states('sensor.average_humidity')|float(0) }}
mighty ledge
silent reef
orchid oxide
silent reef
orchid oxide
#

which doesnt make sense as far as i can tell?

mighty ledge
#

then that should be working, if the path is correct try just using the template {{ value[:5] }} and the sensor should have a state of { "v
If that doesn't have that state, then you have the wrong file. If it does, then it's not JSON.

mighty ledge
silent reef
mighty ledge
#

You have to gain access to your files somehow

#

either through one of the addons that allows you to edit files, SSH, or Samba Share

silent reef
#

Ahh so i need to access the files in my HA setup (Unraid) ? ๐Ÿ™‚

mighty ledge
#

Are you running HAOS, Core, Container, or Supervised?

#

I'd buess, HAOS

silent reef
#

A container but i think it is Core ๐Ÿ™‚

mighty ledge
#

you set up a docker container running home assisstant?

silent reef
#

Yeap ๐Ÿ™‚

mighty ledge
#

that requires writing and running code

#

I'm not trying to be an ass here, but if you can do that but can't edit a text file, you're going to have a really bad time with that install method

silent reef
#

Ahhh okay ๐Ÿ™‚ i use the web gui when making automations ๐Ÿ™‚

#

My configuration.yaml is like this:

Configure a default setup of Home Assistant (frontend, api, etc)

default_config:

Text to speech

tts:

  • platform: google_translate

group: !include groups.yaml
automation: !include automations.yaml
script: !include scripts.yaml
scene: !include scenes.yaml

mighty ledge
#

ok, so add what tom wrote to you into that file at the bottom and you'll have that sensor for use.

silent reef
#

So this? ๐Ÿ™‚
template:

  • sensor:
    • name: "Average humidity"
      unit_of_measurement: "%"
      device_class: humidity
      state: >
      {{ ( state_attr('climate.alrum', 'current_humidity')|float(0) +
      state_attr('climate.kontor', 'current_humidity')|float(0) +
      state_attr('climate.bryggers', 'current_humidity')|float(0) ) / 3 }}
      availability: >
      {{ ( state_attr('climate.alrum', 'current_humidity')|is_number and
      state_attr('climate.kontor', 'current_humidity')|is_number and
      state_attr('climate.bryggers', 'current_humidity')|is_number ) }}
mighty ledge
#

Yes

#

And youโ€™ll have to restart

#

The container

silent reef
#

Okay cool. I give it a try ๐Ÿ™‚

#

"The system cannot restart because the configuration is not valid: Error loading /config/configuration.yaml: while scanning for the next token found character '\t' that cannot start any token in "/config/configuration.yaml", line 26, column 1"

#

๐Ÿ˜ฆ

#

Ahh

#

Got a empty line ๐Ÿ™‚

#

So now how can i check that it worked? ๐Ÿ™‚

mighty ledge
#

If you restarted it will show up in developer tools states page

#

Itโ€™ll also show up for use in automations when using entity_id fields

#

It will not work for a device trigger, so donโ€™t use that. It wonโ€™t show up for any device things

silent reef
#

YEA! It is there!

#

Why cant i post screenshots? ๐Ÿ™‚

plain magnetBOT
#

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.

silent reef
#

Ah okay. But i can see it now. very nice! Thanks! But the the trigger i dont think is right ๐Ÿ™‚ Becurse it is the light in the bathroom that i dont want to turn off then then humidity is 10 % higher there ๐Ÿ™‚

#

Is this not more correct? ๐Ÿ™‚
condition:

  • condition: template
    value_template: "{{ state_attr('climate.bathroom', 'current_humidity')|float(0) <= 1.1 * states('sensor.average_humidity')|float(0) }}"
mighty ledge
#

Sry, driving

silent reef
#

That is fine ๐Ÿ™‚

orchid oxide
plain magnetBOT
silent reef
#

@mighty ledge when you have time will you ping me? ๐Ÿ™‚

jaunty gull
#

I'm not sure if this is the right channel, but I started using this configuration to pull data from my Hayward Aqua Connect on the local network: https://github.com/amscanne/aqua-connect-local It's working great, but the only issue I have is that it makes my logbook extremely noisy because of the way the interface works. The page the restful integration looking at simply changes it's return value every few seconds to cycle through the different bits of information. This causes pool_panel to drop a new logbook entry every time the page changes. I only care about the information the templates are pulling, not the change of the pool panel. Is there a way to put this in "quiet" mode or something similar? I looked at the restful integration docs, but didn't see anything.

floral steeple
#

Hi, it's there a helper in HA that can allow me to calculate total consumption from a rate like L/h?

#

Utility meter comes to mind

fossil hearth
#

is there a way to check if a string is in a txt file(maybe 4000 lines)? and what is the maximum length allowed in attributes ?

orchid oxide
#

im feeling a bit dumb rn, i feel like this should work but im getting the error UndefinedError: builtin_function_or_method object has no element 0 and im not sure how to fix it ive spent hours on this lol

marble jackal
acoustic tangle
#

hi

#

im trying to round down or up but i cant get it to work.

#

i can only seem to round down or up the decimals i want to round to nearest 10

#

looked here but i can figure it out

#

this is my string

#

{{ states('sensor.kit_motion_01_battery') | round | int (0, 'floor')}}%

#

what am i mising ?

marble jackal
#

You are adding floor to the int filter

#

but | round(0, 'floor') basically does the same as | int

acoustic tangle
#

but how do i get 60, 70, 80 and not 65, 74, 82 ? the original value is 65,4 and that gets to be 65 or 66 but i want it to be 60

orchid oxide
#

is it possible to use a template in a trigger/platform the way you can in a service

#

i mean something like this

entity_id: 
{{ '- sensor.'~(states('sensor.devicetrackers')|replace('[','')|replace(']','')|replace('\'','')).split (', ')[0]|replace ('device_tracker.','')~'_bluetooth_connection'}}```
#

if it works, this should be showing this ```platform: state
entity_id:

  • sensor.pixel_4a_bluetooth_connection```
#

but im not sure if theres another syntax or if this is just straight up not possible

marble jackal
#

This is straight up not possible

#

But you can use a template trigger

marble jackal
acoustic tangle
#

thank you soo much

#

so that would make -2 round down 10's if i have like 110 it would be 100

orchid oxide
#

how would i use a template trigger for this, since its trigger based off whether the value is different from before. i can think of making a template sensor with the old value delayed by a second, is there an easier way?

marble jackal
acoustic tangle
#

yes ๐Ÿ™‚ that is what i ment it dont say and i'm not smart enough to just try ๐Ÿ˜‰

marble jackal
orchid oxide
#

it is

#

because the entity id can change

#

its basically a complicated way to never have to update the automation for when the entity id changes

marble jackal
#

So please explain what you are trying to achieve here

#

What is in that sensor.devicetrackers

orchid oxide
#

a list of active device trackers/ha mobile app instances, basically

#

so when the list changes rather than updating a bunch of automations, im trying to get them to read from the file when necessary

marble jackal
#

I would start with putting that list in an attribute of that sensor, so it's actually a list and not a string

#

That will make working with it a lot easier

orchid oxide
#

im using the command line integration which doesnt seem to support templates for attributes

#

otherwise i would

marble jackal
#

What is the code for that sensor?

#

And you could always create a template sensor out of it ๐Ÿ™‚

orchid oxide
#
  - platform: command_line
    name: devicetrackers
    command: cat /config/.storage/person
    value_template: "{{ ((value_json['data']['items']| selectattr('name', 'equalto', 'jack5mikemotown') | first)['device_trackers'])}}"```
orchid oxide
marble jackal
#

Are those all the device trackers linked to your person entity?

orchid oxide
#

yeah

#

it would be cool if the info were exposed as a sensor, but such is life, i suppose

acoustic tangle
#

hmm almost there now it gives a value of 60.0 not 60 how do i get rid of the decimal ?

#

and this time i tried different -1 ,-2, -01, -10 but no ๐Ÿ˜ฆ

thorny snow
#

Good morning everyone. I have a problem configuring 2 invites teeth that I can't go on I have two thermostats in the living area and in the sleeping area I can't insert them both in Home Assistant. in attached the link with the syntax that gives me error, thanks https://pastebin.com/ZFQS0PNy

#

Two entity

acoustic tangle
#

i have {% set batterylevel = states('sensor.kit_motion_01_battery') | int| round(-1, 'floor') %}

#

i get mdi:battery-60.0

#

whole code is

#

{% set batterylevel = states('sensor.kit_motion_01_battery') | int| round(-1, 'floor') %}
{% if batterylevel == 100 %}
mdi:battery
{% else %}
mdi:battery-{{batterylevel}}
{% endif %}

marble jackal
#

The result of round is a float

acoustic tangle
#

{%set batterylevel = states('sensor.kit_motion_01_battery') | round | int(-1, 'floor') %}
gives this mdi:battery-66

#

๐Ÿ˜ฆ

marble jackal
#

No, now your are adding the settings for the round filter to the int filter

orchid oxide
#

this example just lists attributes. i tried using a template sensor and it errored out when setting up the integration. just doing an attribute entry put most of the thing there. not sure if im just doing it wrong? but it doesnt seem to work the way i need```sensor:

  • platform: command_line
    name: JSON time
    json_attributes:
    • date
    • milliseconds_since_epoch
      command: "python3 /home/pi/.homeassistant/scripts/datetime.py"
      value_template: "{{ value_json.time }}"```
acoustic tangle
#

ok got it ! ๐Ÿ™‚ {%set batterylevel = states('sensor.kit_motion_01_battery') | round (-1, 'floor') |int %}

#

wuhuu

marble jackal
#

What is the current state of your sensor

orchid oxide
#

['device_tracker.pixel_4a', 'device_tracker.pixel_6a']

marble jackal
#

Okay, and what do you want to do with that?

orchid oxide
#

ive got it all fine for the actions where i use it, but for the triggers, in the specific example above, id like it to trigger if the bluetooth state of any device in that list changes

marble jackal
#

What do you mean with the Bluetooth state? Is that just the state of the entity?

orchid oxide
#

iirc yeah, when the state of the entity changes, which i believe is no of bluetotoh devices connected

marble jackal
#

So the state is either home or not_home

orchid oxide
#

no its bluletooth connections so its 0, 1, 2, etc.

marble jackal
#

That doesn't make sensor for a device_tracker

orchid oxide
#

?

marble jackal
orchid oxide
#

thats why im doing this
{{(states('sensor.devicetrackers')[0]|replace ('device_tracker.','')~'_bluetooth_connection')}}

#

to replace device_tracker with sensor and bluetooth_connection

marble jackal
orchid oxide
#

oh

#

sorry i misunsderstood the question

#

no its not the state of the sensor.devicetrackers entity

marble jackal
#

But back to the start, what are you trying to achieve, why do you want to trigger when for any of the device trackers associated to your person entity the number of active BT connections changes?

orchid oxide
#

in this instance, i want to trigger a manual location check on the device

marble jackal
#

Okay, I would create a template sensor out of your command line sensor with an attribute to show the active BT connections per device tracker

#

You can then use a state trigger on that attribute for your trigger

acoustic tangle
#

one last question today

#

why is this not working ? i dont get any colors on the icons in mushroom template card

#

{% set batterylevel = states('binary_sensor.kit_motion_01_battery_low') | int %}
{% if batterylevel > 60 %}
green
{% elif batterylevel > 20 %}
orange
{% else %}
red
{% endif %}

#

nevermind ! i got the wrong entity ๐Ÿ˜ฆ

marble jackal
#

For next time, please format your code

plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Shift+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.

acoustic tangle
#

yep sorry

karmic compass
#

hi, wondering if anyone can help explain (rather new to all this):
i'm trying to set up a fan entity. i notice this has a service called 'oscillate'. how can i call this service? for example, in configuration.yaml there are properties 'turn_off' and 'turn_on' which i can define how to execute. There is a 'set_oscillating' property but not 'oscillate'

marble jackal
inner crest
#

I habe question about the template sensor switch

Basically here is my issue
I want to track if a server is online, and i can send requests to HA to set the template to on

However, i'd like it automatically to go to "unavailable" after there are no updates for 10minutes.

Is that even possible?
The server can be on, off or the way i update could fail so unavailable, i.e. could be on, could be off

How can i solve this?
Home assistant cannot request the server state directly, it has to be updated via api

Ping me with reply

mighty ledge
unborn sequoia
mighty ledge
#

is your energy negative?

next pier
#

Hey guys - i'm using the Torque app and have a latitude sensor and longitude sensor (plus Altitude)

How can I combine both (or all three) on a map to track where I parked my car?

mighty ledge
#

you have to make a template sensor with latitude and longitude attributes

#

Then attach that to a person

next pier
#

Would I create a person called "MyCar" if i wanted to track that?

marble jackal
#

Downside of using a person entity for your car is that zone.home will have state 1 if you're not at home, but your car is (maybe you left by foot or bike)

mighty ledge
#

if you're trying to track your cars position on a map

next pier
#

is that a binary sensor or sensor? I've been assuming (i know) that binary sensors were on/off or true/false - binary options. A sensor would be variable, so since GPS coordinates would be variable, it's a sensor?

#

reason I ask is the template sensor that includes GPS coordinates is a binary sensor

inner mesa
#

those go into the attributes

floral steeple
#

Hi all, I have a sensor that reports water flow in L/h. I'd like to create a total consumption sensor from this. Is there something I can use for this? Utility meter does not seem to work for this

#

also, I suspect if I wanted the sensor to report by the minute, I would have to involve some math template to get consumption= ((rate L/h)*3600 s)

mighty ledge
#

You'd need to convert it to m3 for use in the energy dashboards

#

Oh, nope, it supports L

floral steeple
#

ahh yes, so indeed, I have to convert it to L

mighty ledge
#

I don't think you do

#

unless it's not showing up in the list

floral steeple
#

its not, because its a rate, L/h. when water flows, a number is shown, when water stops flowing, it goes to 0

next pier
inner mesa
mighty ledge
#

derivative goes from x/time to x

inner mesa
#

oh, that's right

mighty ledge
#

I'm not sure if it would work in that case tho

#

๐Ÿคทโ€โ™‚๏ธ

#

college was so long ago

floral steeple
#

yes, exactly, I'm stumped on this one also...I'll have to just make a template sensor, I don't think any of the helpers (in the UI at least) would apply here

inner mesa
#

I use an ESP8266-based pulse meter that initially reports a rate, but I multiply that by the time period to convert to (roughly) instantaneous usage, and then I use a statistics sensor

floral steeple
#

oh cool, yes, this what I need to do

#

can you share your math for that?

inner mesa
#

This is my ESPHome sensor:

sensor:
  - platform: pulse_counter
    pin: 12
    name: "Water Usage"
    update_interval: 10s
    force_update: true
    unit_of_measurement: 'gal'
    filters:
      # reports in pulses/min, so divide by 6 and by 64 pulses per gallon
      multiply: 0.0026041667
#

I expect that to give me gallons used in the last 10s

#

and this is my statistics sensor based on that:

- platform: statistics
  entity_id: sensor.water_usage
  name: "Water Usage Stats"
  state_characteristic: total
  # 10s sampling, so 6*60*24 points
  sampling_size: 8640
  max_age:
    days: 1
mighty ledge
#

or is this a legit sensor

inner mesa
#

it's a pulse meter on my water softener

#

I tapped off the existing connector and fed it into an ESP8266

#

with a level shifter

mighty ledge
#

oh cool

#

i wish i had something like that

#

Working on Blue Iris atm tho

inner mesa
#

it was a fun project

floral steeple
#

thanks, Rob I can work with your setup, its basically the same, except mine is L/h

inner mesa
#

I also have a utilty_meter that gives roughly the same value as the statistics sensor:

utility_meter:
  water_utility:
    source: sensor.water_usage
    name: Water Usage Today
    unique_id: water_usage
    cycle: daily
    delta_values: true
marble jackal
#

This is my watermeter ๐Ÿ™‚

#

It counts every time some dial rotates, which indicates 1 liter water

mighty ledge
#

I was just going to get an OCR camera but i'd need to put a flash light on it to keep the meter's value shown

#

it doesn't have power connected to it, so it uses solar power to power the lcd screen

floral steeple
#

amazing to see what everyone has for water meters....this mine, a meter plus valve....its z-wave....i

#

oh, I can't share images....but i'm working with Al Calzone to get it fully functional in z-wave js

plain magnetBOT
#

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.

floral steeple
mighty ledge
#

oh thats kinda cool

inner mesa
#

I was planning to DIY something like that until I figured out how to get the data from my water softener

floral steeple
#

it works well... its supposed to detect leaks down to 0.1 L/h and tell you and it shuts off the valve if certain thresholds are met ....low, medium and high flow rates...also tells me the temperature of the water if its too high or low. Its still needs some tinkering for zwave-js...so I would not call it fully compatible just yet.
https://github.com/zwave-js/node-zwave-js/discussions/4902

peak juniper
#

Any idea how I might run a template that chooses the highest value of five of my sensors without doing five "check if this sensor is great than this and this and this"

#

like I want to see the top 3 zones i've spent time in, etc

mighty ledge
#

so you just gotta get the values from the 5 sensors, put them in a list, then get the max value with | max

peak juniper
#

wow, that sounds much simpler than I'd imagined, thanks - will try that out now

#

what about if I want to find out 2nd place or 3rd place?

mighty ledge
#

if you want the entity_id that gave you the max value... then that's another story

peak juniper
#

oh yes haha that is what I want

#

I don't want the max value, I want to find out what is giving the max value

#

so if sensor.blahblah is giving 5 and the others are giving 3 I want to know which sensor that is

#

rather than just get "5"

next pier
#

I'm sorry - i've tried a few variations but for some reason I can't seem to get HA to show the attributes I'm looking for?
template:

  • sensor:
    • name: focus
      state: "{{ state_attr('sensor.focus_GPS', 'carlocation') }}"
      attributes:
      latitude: "{{ state_attr('sensor.vehicle_gps_latitude', 'carcoordinateLatitude'}}"
      longitude: "{{ state_attr('sensor.vehicle_gps_longitude', 'carcoordinateLongitude'}}"
mighty ledge
#

then item 1 will be either the lowest or highest, can't remember

#

either way, first item [0], second item [1]... last item[-1] second to last item [-2]

#

etc

peak juniper
#

great - that makes sense. Will have a play around with it

mighty ledge
peak juniper
#

any chance to invert the list (e.g. if the lowest value is listed first)?

mighty ledge
#

my point is, it doesn't matter because you can work from either side of the list

#

but it does have a reverse flag you can supply to it

#

sort(attribute='state', reverse=True)

peak juniper
#

oh yes, so you're saying -1 will return the last item, ok that makes sense

#

I will try that, and try the reverse if necessary

#

that definitely sets me on the right track

mighty ledge
#

just keep in mind that it may not work because it's comparing strings

marble jackal
#

But if the states are numbers, it will not sort then correct. As it will sort strings

#

Slowpoke

mighty ledge
peak juniper
#

looking at the template editor, it seems to produce a list that makes sense

#

ah you're saying the reverse thing won't work?

mighty ledge
#

if your sensors all have the same significant figures, it will work

#

i.e. if they are all numbers that range from 0 to 9.9999

#

however, if you have a number that's 10... it will sort them... 1, 10, 2... 9

peak juniper
#

and what about 99.9999?

#

oh bugger yeah

#

that's going to be annoying. Currently the highest value is below 10 but I imagine it will go above that

#

is there a way to account for that?

mighty ledge
#

it's moving left to right on the string

#

so 2 is higher than 10, always

#

because 2 is the first character in the string

#

if you want to treat them like numbers, you'll have to convert the values to numbers but you'll lose access to the entity_id

#

you can use namespace to store them as a key value pair

bronze dirge
#

Referring to Amcrest integration. I set up below automation for my AD410 doorbell. However it never gets triggered. What did I do wrong?

`- id: '1679408824655'
alias: Doorbell ring
description: ''
trigger:

  • platform: event
    event_type: amcrest
    event_data:
    event: "CallNoAnswered"
    payload:
    action: "Start"
    condition: []
    action:`
bronze dirge
#

Oh sry.

peak juniper
#

what is a namespace / key value pair?

mighty ledge
#

all states in HA are strings

peak juniper
#

ah fair enough

#

so where do we go from here?

mighty ledge
#

namespace and storing the entity_id and numerical value as you iterate the list of entities

#
{% set ns = namespace(items=[]) %}
{% for s in expand(...) %}
  {% set ns.items = ns.items + [ {'entity_id': s.entity_id, 'state': s.state | float(0) } ] %}
{% endfor %}
{{ ns.items | sort(attribute='state') }}
peak juniper
#

wow

#

I really appreciate this by the way

#

but I do feel like I've now gone a little out of my depth

#

ok, I seem to have got something out of that

#
[
  {
    "entity_id": "sensor.x",
    "state": 0
  },
  {
    "entity_id": "sensor.y",
    "state": 1.5
  },
  {
    "entity_id": "sensor.z",
    "state": 3.48
  }
]
#

so if this is one sensor, how do extract these bits to a notification to say "This month, sensor.z was the highest with 3.48" ?

marble jackal
peak juniper
#

also, sorry, but am I putting the above in a template sensor? it doesn't seem to have the same result

mighty ledge
#

I even refreshed the page

marble jackal
#

States are always strings, do if you use this as the state of a template sensor it won't be a list with dicts anymore

#

So either store it in an attribute, or select the highest one from that list and use that for the state

mighty ledge
marble jackal
#

Or do just that, maybe with a reverse in the sort, or by selecting the last item if you want the highest

mighty ledge
#

Yeah I can't remember if it's ascending or descending

#

you can reverse the list with what I posted above reverse=True

marble jackal
peak juniper
#

awesome

#

this is looking great

#

just 2 small things and it's perfect

#

and btw, i appreciate your input and help with this

#

hope it's not too frustrating - your help is invaluable to me here ๐Ÿ™‚

#
  1. can I store the sensor's "friendly_name" instead of entity_id?
#
  1. template editor works great but where am I putting this in my yaml to bring it as a proper sensor in to home assistant?
marble jackal
#

Use s.name instead of s.entity_id to get the name

#

You might want to rename the key a well then to avoid confusion

#

So basically anywhere where it states entity_id you can replace that with name

#

And how do you want to use this? On your dashboard? In a TTS message? In a notification?

peak juniper
#

in a notification

#

I already have a flex-table-card which sorts the entities and show's which is top, etc.

unborn sequoia
#

hello I tried the utility meter I

peak juniper
#

but I want a notification to go out each month with:

  1. x with 2 hours
  2. z with 3 hours
#

so it can be a sensor value that I call ?

marble jackal
#

Or just use the template for the notification message

peak juniper
#

oh that's not a bad idea haha

#

thanks again - I really appreciate all the efforts to help

#

truly it's taken me ages trying to work out how to do this

primal girder
#

I would appreciate a pointer. Is there documentation on how to create a template that will check something like: If HallMotionSensor is on and within 60 seconds, kitchen motion sensor is on and then 90 seconds, a socket is turned on: do something. I'm not comfortable enough yet to write this from scratch without drawing from documentation. Thanks.

mighty ledge
primal girder
mighty ledge
#

that can all be done with wait for trigger in an automation

primal girder
# mighty ledge that can all be done with wait for trigger in an automation

A quick look at forum posts relating to WaitForTrigger shows that it would require that I use it in conjunction with a timer. This means I need to start a timeer on each motion sensor. Is there no way of checking if other sensors were set to on within a set time with a template? I would very much rather not use a timeer. in conjunction with WaitForTrigger. It becomes very messy.

primal girder
vapid night
#

Hoping someone can help me out getting my head around this garage door opener template/cover thingo...

silent vector
#

Is it possible to a regex replace on a list? I tried but it only replaced the first item.

{% set t = ['binary_sensor.foo_e','binary_sensor.foo_eee'] %}
{{ t | regex_replace('^.*?\\.','') }}
median rain
#

is there a way to have relative_time use abbreviations like "mins" instead of "minutes"?

#

For anyone else running into this because of space constraints with a tiny ESPHome screen you can do it locally inside ESPHome. Won't help if you need this done inside homeassistant but maybe a template sensor (or just template if your use case supports it) that does a string op on the output?

marble jackal
grand storm
#

Hi all...
What am i missing here?

I have a helper to change the text in "input_text:text". But i cant broadcast it?

service: google_assistant_sdk.send_text_command
data:
command: Broadcast "{{input_text.text}}"

mighty ledge
#

you have to get the state out with the states method

grand storm
median rain
grand storm
#

Figured it out.
Changed it to :

command: Broadcast {{ states('input_text.text') }}

Now it works. ๐Ÿ™‚

silent vector
#

Is it possible to a regex replace on a list? I tried but it only replaced the first item.

{% set t = ['binary_sensor.foo_e','binary_sensor.foo_eee'] %}
{{ t | regex_replace('^.*?\\.','') }}
mighty ledge
#

and the difference between a filter, a function, and a test

#

and where all of them can be used

#

like in functions like map, select, etc

silent vector
#

I will get to reading

mighty ledge
#

I'm just suggesting this because you keep coming here with similar questions and if you understood these principles, you wouldn't have any of them

silent vector
#

I'm learning each time and learning from reading too on multiple sites lol. When I think of something I'm not sure if it's possible I come here. I almost came here to ask how to get keys from dicts when you have the value but then I found a thread from 2018 where you and someone else provided examples to do that.

#

I came here a lot more back during the summer lol

daring swift
#

I am getting an error in my config.yaml and it's stopping all of my automations from working. I can't figure it out.
Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected '}', expected ')') for dictionary value @ data['binary_sensor'][3]['state']. Got "{{(state_attr('binary_sensor.lumi_lumi_motion_ac02_iaszone')}}". (See /config/configuration.yaml, line 33).
template:
binary_sensor:

  • name: "basement_motion_notdetected"
    delay_off: "00:00:10"
    state: "{{(state_attr('sensor.lumi_lumi_motion_ac02_iaszone')}}"
buoyant pine
#

You've got an extra parenthesis at the beginning

#
"{{(state_attr('sensor.lumi_lumi _motion_ac02_iaszon e')}}"
   ^
spark flame
#

also doesn't a state_attr need an attribute for the 2nd parameter?

buoyant pine
#

Ah yes

#

Just states() if referring to the state of the entity

spark flame
#

It looks like turning a sensor value into a binary sensor here is the attempt?

buoyant pine
#

Probably, which is weird because it looks like it's a Zigbee sensor which should already have a binary sensor entity

daring swift
#

The parentheses was it.

#

I was doing the sensor to get the delay off. Couldn't find another good way to do that.

craggy oasis
#

Hey just a quick question can i use tempalting when adding ui elements ? (rough example with mushroom chips card)

type: custom:mushroom-chips-card
chips:
{% for light in lights %}
  - type: light
    entity: light.tradfri_2
{% endfor %}
sonic ember
#

I have a question about how template sensors work, and when they are updated. Let's say I have a template sensor that derives its value partially from a number helper.
In an automation, I will first change the number helper, and then I'll use the template sensor. Does the sensor update when the number helper changes, or when it's 'accessed' by the automation?

mighty ledge
mighty ledge
sonic ember
sacred ridge
#

Hello I think this is the right chat, I currently show my Sonos system in a media player card on my dashboard. I want to hide the Sonos media player card when the Sonos entity is playing โ€œTVโ€ and then display another card with media controls for the tv on it. How would I go about functionality the design I can sort myself thank you in advance ๐Ÿ™‚

marble jackal
sturdy juniper
#

I'm experimenting with creating a few template sensors for power monitoring, and I'd like to compare to a sensors previous state.
How can I call this data ?
I've tried states('sensor.xxxxxxxx.from_state.state') but that doesnt work ..

#

internet and even chatgpt is not helping either ๐Ÿ˜›

inner mesa
#

right, you can't do that

#

there's an example on that page

young lake
crimson lichen
#

how to check state of list entities
EX: {% if ([sensor.1,sensor.2,sensor.3,sensor.4] is on ) %} True {% else %} False {% endif %}
Thanks

marble jackal
marble jackal
crimson lichen
crimson lichen
marble jackal
#

So it should return true is at least one of those sensors is on

marble jackal
#

{{ [ 'sensor.foo', 'sensor.banana', 'sensor.petunia' ] | select('is_state', 'on') | list | count > 0 }}

floral shuttle
#

if I want my rest sensor value_template to evaluate to the first one in this list, can I only do that using the verbose date in that template like - unique_id: solar_forecast_estimate_watt_hours_day name: Solar Forecast estimate watt hours day value_template: > {{value_json.watt_hours_day[now().strftime('%Y-%m-%d')]}} ? I had hoped to do smth like {{value_json.watt_hours_day[0]}} but that renders 'unknown'

#

this works: {{state_attr('sensor.solar_forecast_estimate_watt_hours_day','watt_hours_day')|first}} its not a list, its a dict...

#

this doesnt work though ```
value_template: >
{{value_json.watt_hours_day|first}}

marble jackal
#
        value_template: >
          {{value_json.watt_hours_day.items() | list | first }}
floral shuttle
#

ok, have one remaining poll.... let me try that, thx! (too bad we need to reload the rest sensor for that, would nt this be a mere template reload (the resource doesn't change, only the template on that resource, and there is no other way of testing those paths is there?

#

heck, too late... and now all of my other rest sensors are empty too....

marble jackal
#

just use the json returned from the API in devtools > templates until you have your templates right

#
{% set value_json = whatever %}
{{value_json.watt_hours_day.items() | list | first }}
floral shuttle
#

o yes, that helps! need to add the extra 'result' there, but other than that, this nis the result of that template, type list: [ "2023-03-23", 9643 ]

marble jackal
#

what do you want it to return?

floral shuttle
#

sorry, I need the value, so 9643. but checking that output, I now see its lists yesterday and today, so, Id need the todays date, being in this format {{now().strftime('%Y-%m-%d')}}. Let me try to add that to the template, instead of |first

#

yes, {{value_json.result.watt_hours_day[now().strftime('%Y-%m-%d')] }} returns the value correctly in the temoplate editor! Woinder why the rest sensor didnt though....

#

this should do it: - unique_id: solar_forecast_estimate_watt_hours_day name: Solar Forecast estimate watt hours day value_template: > {% set today = now().strftime('%Y-%m-%d') %} {{value_json.result.watt_hours_day[today]}} json_attributes_path: "$.result" json_attributes: - watt_hours_day

#

thx!

#

on updating these sensors (rest and its template sensors) and mitigating the rate limit: I believe the best method is setting an update interval 86400 and next, automate the update each our while the sun is up. give or take. that should prevent exceeding the set limit of 12

marble jackal
#

this should also work if you always want the value of the first item
{{value_json.watt_hours_day.values() | list | first }}

floral shuttle
#

yes it does now. didn't use those constructions (values() or items() ) in my templates yet, so still a bit new territory for me. #TIL...

#

have another question on the updating, but that would be #automations-archived so hopping over now ๐Ÿ˜‰ thanks Martijn

marble jackal
#

no problem!

silent vector
#

How often do template trigger binary sensors evaluate their state if I use a template? Such as one template trigger binary sensor becoming on if another template trigger binary sensor hasn't also triggered? If it did then it doesn't turn on.

But that only works if it's constantly evaluating and not a one time evaluation at the time of the trigger.

mighty ledge
# silent vector How often do template trigger binary sensors evaluate their state if I use a tem...

If the template contains the states object with no domain reference, it's throttled to at most 1 update per minute. If the states.<domain> object is used, the template is throttled to at most 1 update per second. If neither are used, the template will update when the entities inside them update. Using now() in a template will cause an update to occur on the minute. If you use a trigger for the template entity, the template will only update when the trigger is fired.

silent vector
#

Would now() cause it to update every minute even when using a template trigger or not at all?

I'm trying to create 2 template triggers for zone events. When someone enters a specific zone however I don't want it to turn on if the other also just entered that zone between x time.

Ex. Foo enters x zone between 06:00 and 09:00 and bar also entered then the state doesn't turn on. Only when foo enters and bar didn't enter. The reason I wonder about evaluations is sometimes zone updates could be delayed a few seconds. One phone may send it sooner than the other.

mighty ledge
silent vector
#

Any thoughts on how to accomplish what I'm trying to achieve? If it's possible at all?

mighty ledge
#

if you want it to update on the minute as well, add a trigger that does that

#

you can assign a trigger id that can be referenced in the template

floral shuttle
#

right, so now ready for some manipulating ๐Ÿ˜‰ please consider this value_json. If I want to have the max I can do

#

{{ value_json.result.watts.values()|max}}

marble jackal
#

a simple test in devtools > template would have confirmed that that results in 1836 which is indeed the hightest value

floral shuttle
#

but now I want it to be todays day only, so need to select: {% set today = now().isoformat() %} first

mighty ledge
#
{{ (value_json.result.watts.items() | list | sort(attribute='1', reverse=True) | first | default(("Unknown",0)))[0] }}
#

that gets you the max

marble jackal
#

what he had also works ๐Ÿ™‚

mighty ledge
#

if you want to get only todays max...

marble jackal
#

what helps in selecting today is that it is already in the right timezone ๐Ÿ™‚

silent vector
#

How would I do something like this? I am not sure how to reference the second trigger if it didn't occur yet.

https://dpaste.org/CQ2XV

mighty ledge
#
{{ (value_json.result.watts.items() | list | rejectattr('0', '<', now().isoformat()) | sort(attribute='1', reverse=True) | first | default(("Unknown",0)))[0] }}
#

but if you want from midnight today...

#
{{ (value_json.result.watts.items() | list | rejectattr('0', '<', today_at().isoformat()) | sort(attribute='1', reverse=True) | first | default(("Unknown",0)))[0] }}
#

keep in mind that gives you the time, not the value

#

if you want the value, change the last [0] to [1]

floral shuttle
#

yes, was doing that now...

mighty ledge
floral shuttle
#

but its not the highest.....

marble jackal
#

I would do this:
{{ value_json.result.watts.items() | selectattr('0', '<', (today_at() + timedelta(days=1)).isoformat()) | map(attribute='1') | max }}

floral shuttle
#

it returns 1752

silent vector
#

Whoops forgot about that. That would have been 2 separate template triggers not 1 entity.

floral shuttle
#

which is listed here: so ther are at least 2 higher values

mighty ledge
marble jackal
#

Ah wait... I missed that it includes today an yesterday, I thought it had today and tomorrow

silent vector
#

How do I get the state of the template trigger to be on if the second trigger bar_enter didn't occur at or around the same time as the first foo_enter?

marble jackal
#

now I also understand the filter petro used ๐Ÿ™‚

mighty ledge
silent vector
#

I did that part. But how does the template know which came first?

mighty ledge
#

then perform logic based on the current state and the trigger that occured

#

the current state will be this.state

floral shuttle
mighty ledge
#

so does the tempalte I provided work?

marble jackal
#

well, you can both reject yesterday and tomorrow to be sure

mighty ledge
#

yeah

#

Iknow you like 1 liners, but I'd personally break it up

marble jackal
#

something like this in a 1 liner ๐Ÿ™‚
{{ value_json.result.watts.items() | rejectattr('0', '<', today_at().isoformat()) | rejectattr('0', '>=', (today_at() + timedelta(days=1)).isoformat()) | map(attribute='1') | max }}

silent vector
#

If bar entered the zone first this should be false?

"{{ iif(trigger.id == 'foo_enter' and (now() >= today_at('06:00') and now() <= today_at('09:00')) and this.state != 'on','true','false') }}"

mighty ledge
#
{% set midnight = today_at() %}
{% set tomorrow = midnight + timedelta(days=1) %}
{% set data = value_json.result.watts.items() | rejectattr('0', '<=', midnight.isoformat()) | rejectattr('0', '>=', tomorrow .isoformat()) | sort(attribute='1', reverse=True) %}
{{ (data | first | default(("Unknown",0)))[0] }}
#

but data in this regard will be a list of sorted times and values.

#

so you can use it however you want

marble jackal
#

yeah sure

floral shuttle
mighty ledge
#

it selects the highest value for today

#

not the highest value

marble jackal
#

the last one works

mighty ledge
#

Not sure how the last one doesn't provide the same info

#

working for me

floral shuttle
mighty ledge
#

Right, again, I kept it as a KVP so that you could get the time from it if you want

#

knowing you, your next question will be "How do I get the time"

#

so that you can trigger off it

#

or have it as an attribute

#

or whatever you want

#

If you just want the max, then you can map the value early on and skip a bunch of the template w/ sorting (what thefes posted)

floral shuttle
#

nono, I love that. thx! Was just checking why the other template rendered the incorrect value

mighty ledge
floral shuttle
#

ofc, the next improvement would be to select the best period, and not the highest value per point in time only. Give or take: the best providing 2 consecutive hours. But that might be stretching it for now... considering this already a forecast, I suppose some timing like tht is already incorporated in the data

silent vector
#

Well yeah because If one takes just a second or too longer to send a zone update it wouldn't work. The idea is did both devices arrive in the zone at around the same time? If they did do nothing otherwise if only foo arrived in the zone between that time frame then it's true.

mighty ledge
#
{% set in_window = today_at('06:00') <= now() <= today_at('09:00') %}
{% if trigger.id == 'a' %}
  {{ in_window and this.state != 'xyz' }}
{% elif trigger.id == 'b' %}
  ..
{% endif %}
#

something like that

mighty ledge
#

that's a condition

#

not a trigger

#

i.e. automation, not template entity

#

so, I recommend going with an automation that turns on/off an input_boolean

#

and if you want it as a binary_sensor, abstract that into a template binary_sensor

silent vector
#

Good idea thank you.

floral shuttle
#

are trhere any objections to use: {% set today = now().replace(minute=0).replace(second=0).replace(microsecond=0).isoformat() %} and next in the template select 'today' using | selectattr('0', 'eq', today)? it would only skip the first and last items, but since they never contain the highest value anyways, that would hurt

#

o wait, there are.... I now see that renders that same erratic 1752!

marble jackal
#

You can do all those replaces in one function

#

.replace(minutes=0, seconds=0)

floral shuttle
#

right, ofc. sorry

mighty ledge
#

1752 is the highest if you go from your current time

floral shuttle
#

because it isnt the highest value

mighty ledge
#

it's 12:36 or 13:36 where you are, correct?

marble jackal
#

12:36

floral shuttle
#

12:36

mighty ledge
#

ok, 11 is before that

floral shuttle
#

so it selects the now...

mighty ledge
#

so...

#

it's removing the 11 value

marble jackal
#

btw, I guess it's shorter to do today_at().replace(hour=now().hour)

#

or today_at(now().strftime('%H:00'))

floral shuttle
#

hmm, still dont understand why this yields perfectly | rejectattr('0', '<=', midnight.isoformat()) | rejectattr('0', '>=', tomorrow .isoformat()) , or this|selectattr('0','search','2023-03-24'), while my previous attempt above 'today' was incorrect

marble jackal
#

which will leave out the result of 11:00, which is the highest one

#

this {% set today = now().replace(minute=0).replace(second=0).replace(microsecond=0).isoformat() %} returns "2023-03-24T12:00:00+01:00"

floral shuttle
#

and with: {% set today = now().strftime('%Y-%d-%m') %} which is 2023-24-03, andn using |selectattr('0','search',today) the template evaluates to 0.... because its unknown and the default kicks in

#

full template: {% set today = now().strftime('%Y-%d-%m') %} {% set data = value_json.result.watts.items() |selectattr('0','search',today) | sort(attribute='1', reverse=True) %} {{ (data | first | default(("Unknown",0)))[1] }}

marble jackal
#

thats because you should switch the month and day

floral shuttle
#

........

marble jackal
#

first month, then day, longest period first

floral shuttle
#

o dear o dear o dear... ๐Ÿ˜ฌ

#

now it works.... thx Petro and Martijn. ,much appreciated! as ever

upper matrix
#

How do I check if a string starts with a specific value in a template?

grand quarry
#
{{ "test".startswith("test") }}
floral shuttle
#

maybe a final touch: using the last actual template line like this {{ (data | first | default(("Unknown",0))) }} give s the KVP. if I would like to display that in the frontend as state like 1836 W om 11 uur how would I have to go about doing that. Or, Id only use the value as state, but maybe a secondary line in a template-entity-row.

upper matrix
marble jackal
upper matrix
#

Hi again, I have the following event

event_type: rfxtrx_event
data:
  values:
    Command: Group off

Now I try to check if Command by using {{ trigger.event.data.values.Command == 'Group off' }} but it does not work? what am I missing? (I tried to cast it to a string using |string but that didn't work.

upper matrix
#

looks like values is a dict now i just need to find how i get a value from it

upper matrix
#

After trial and error the following did the trick trigger.event.data['values'].Command

mighty ledge
#

values and items need to be ['values'] or ['items']

upper matrix
#

yea I figured that out after much pain ๐Ÿ˜›

mighty ledge
#

the error in your logs should have pointed you to accessing that

#

I'd wager it would say something like NameError, values function doesn't have 'command' blah blah

floral shuttle
#

ugh... so Ive got this {% set data = value_json.result.watt_hours_day.items() | list | sort(attribute='1', reverse=True) %} {% set peak = (data | first | default(("Unknown",0))) %} {{ peak[1] }} W op {{ as_datetime(peak[0]).strftime('%-d-%-m') }}working now as template based on the direct rest sensor data. However, I vcan notdo that on the attribute of the sensor, with```
{% set attr =
state_attr('sensor.solar_forecast_estimate_watt_hours_day','watt_hours_day') %}

{% set peak = (attr | first | default(("Unknown",0))) %}
{{ peak[1] }} W op {{ as_datetime(peak[0]).strftime('%-d-%-m') }}```

#

the {{attr}} returns Attr: {'2023-03-24': 6115, '2023-03-25': 9795} and not [('2023-03-24', 12224), ('2023-03-23', 9643)]. I did test to fake a list surrouding the set with [], but that wont go..

#

this being the result of the rest sensor data:```
{
"result": {
"watt_hours_day": {
"2023-03-23": 9643,
"2023-03-24": 12224
}

}
}```

#

also, if I add |list to the set, it transforms the output to a useless Attr: ['2023-03-24', '2023-03-25'] and loses the KVP

half pendant
#

Trying to figure out how to add a condition to an automation checking if the automation hasn't been run in a specified time frame (example "since 2 seconds") but i'm not sure how to write it. I figured it should be something like {{ this.state.last_triggered != 2 seconds }} but that obviously isn't it. Any tips?

marble jackal
#

to convert the dict to a list of kvp tuples

floral shuttle
floral shuttle
# marble jackal to convert the dict to a list of kvp tuples

magic! and as said, still new to those dicts.... changed it to {% set attr = state_attr('sensor.solar_forecast_estimate_watt_hours_day','watt_hours_day').items() %} {% set peak = (attr |max| default(("Unknown",0))) %} {{ peak[1] }} W op {{ as_datetime(peak[0]).strftime('%-d-%-m') }} to give me a meanigful secondary line. Show state as current, secondary the highest of the 2 listed days. so very useful

half pendant
floral shuttle
half pendant
#

How would that look like?

floral shuttle
half pendant
#

yeah. they sent me here ๐Ÿ˜†

floral shuttle
#

oops, yeah well its a bit of both ๐Ÿ˜‰

#

describe the template you'd need?

half pendant
#

If "automation x or y hasn't run in z seconds" do this

#

or If triggerID x or y hasn't been triggered could work as well

ancient lynx
#

Hi everyone! I'm looking to have a template that goes through all of my calendars with a for state in states.calendar, and only return calendars that have an event for that day. And if so, return the message attribute for that calendar. I can get the message attribute to show, no problem, but am unsure how to test whether that event happens today or not.

marble jackal
ancient lynx
#

@marble jackal Holy cow. That's amazing. I really wish I could wrap my head around templates. Is there a way to show the calendar that the message came from if it returned anything?

marble jackal
#

Where do you want to use this? On a dashboard?

ancient lynx
#

Planning on using it as a daily briefing where TTS would say something along the lines of "The house calendar has an event today called cleaning" where house is the name of the calendar and cleaning is the message.

marble jackal
#

Okay

marble jackal
# ancient lynx Planning on using it as a daily briefing where TTS would say something along the...

Something like this?

{% set tomorrow = (today_at() + timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S') %}
{% set ns = namespace(cal=[]) %}
{% for c in states.calendar | selectattr('attributes.start_time', 'defined') | selectattr('attributes.start_time', '<', tomorrow) %}
  {% set ns.cal = ns.cal + [ c.name ~ ' has an event called: ' ~ c.attributes.message ] %}
{% endfor %}
{{ ns.cal[:-1] | join(', ') ~ ' and ' ~ ns.cal[-1] if ns.cal | count > 2 else ns.cal | join(' and ') }}
#

You can try it in developer tools > template

#

If you change the number of days in the first line, you will see more events

ancient lynx
#

That definitely gets me close enough where I can tweak from there.

#

Where can I find documentation on namespace? That's the first time I've seen that used.

#

@marble jackal Tweaked it to:

{% set tomorrow = (today_at() + timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S') %}
{% set ns = namespace(cal=[]) %}
{% for c in states.calendar | selectattr('attributes.start_time', 'defined') | selectattr('attributes.start_time', '<', tomorrow) %}
  {% set ns.cal = ns.cal + [ 'the calendar named ' ~ c.name ~ ' has an event called: ' ~ c.attributes.message ] %}
{% endfor %}
{{ ns.cal[:-1] | join(', ') ~ ' and ' ~ ns.cal[-1] if ns.cal | count > 2 else ns.cal | join(' and ') }}

So that it says "the calendar named" before each item.

marble jackal
#

Normally the data in the for loop is not available outside the loop. So that's where the namespace comes in

ancient lynx
#

If I want it to say "today" at the very end of the text, do I add that after join(' and ')?

marble jackal
#

So the calendar named X has an event called: Y and the calendar named Q has an event called: P today

#

So only today at the end of the total message

ancient lynx
#

Correct.

marble jackal
#

{{ (ns.cal[:-1] | join(', ') ~ ' and ' ~ ns.cal[-1] if ns.cal | count > 2 else ns.cal | join(' and ')) ~ ' today' if ns.cal }}

ancient lynx
#

I was close. Thanks so much again!

somber siren
#

afternoon all!

#

I have a question with splitting yaml configs (include_dir_merge_list) and the trigger based templated sensors.... first time Im trying to use the trigger/template/sensor ๐Ÿ˜ฑ
Up to now when I created template based sensors I would start with:

- platform: template

but I see the trigger/template/sensor complains and the tutorials show:

template:

Is that equivalent? Any kind soul to guide me? thanks!

marble jackal
#

platform: template is used for the legacy format which falls under the sensor integration

#

The new format is an integration of its own

plain magnetBOT
somber siren
#

@marble jackal Ahh I see.. so I should be using the template: to include all my templates in its own section in the configuration file...

marble jackal
#

Yes

somber siren
#

k will dig deeper.. thanks @marble jackal that was one of the step I wasnt fully in sync on... old timer, legacy habits ๐Ÿ™‚

#

surprise, surprise, that worked! @marble jackal thanks again

pale star
#

hello, I have this timestamp value from a forecast integration.
2023-03-25T11:00:00+00:00
Is there any way I could convert it to some usable data so I can display it in grafana dashboard? Cause I can't use it like this ๐Ÿ˜ฆ

plain magnetBOT
bronze dirge
#

I got UndefinedError: 'volume' is undefined

marble jackal
#

@bronze dirge That's because you are using double quotes inside and outside your template, which will cause an error

#

After you fix that, this code will also give errors when the media player was off, because the volume level attribute will not exist then.
So in the last step you will try to set the volume_level to none

silent vector
#

Can you do a nested for each in automations? Meaning a for each inside of a for each? And still access the repeat.item for both?
I am trying to loop over a list of entities. Then loop over another list 4 times.
https://dpaste.org/4kM0a

Loop over target_switches then loop over switch entities and do something along the lines of this. The challenge is sensor would need to come from the first for each. Then item from the current nested for each. There is probably a better cleaner way of doing this. I'm trying to avoid creating a massive dict with those 4 switch_entities.
The end result is a number.set_value service call per switch_entity
https://dpaste.org/xQonG

hard venture
#

This is a UI/template question, I started out asking in #frontend-archived in the hopes that this was the right place, but I don't think so, so I've come here:
I found this article: https://cyan-automation.medium.com/using-a-template-to-change-a-sensors-icon-in-home-assistant-41766a959ddf that describes how to use templating to change an icon.
I have a basic, default "Light Card" that I'd like to change the icon for under certain circumstances. Do I simply click the Show Code Editor button on the card then replace the icon: mdi:lightbulb line at the bottom with the icon_template: >- code bit from the bottom of that linked article to look at the sensors I want and the icons I want?
Is it really that simple or am I missing something entirely?

#

I tried that and when I have icon_template: >- in the YAML editor, I get the standard icon no matter what state the input_boolean is that I'm looking at. Also, it changes icon_template: >- to icon_template: |- when I save it and it tells me that "Key 'icon_template' is no expected or not supported by the visual editor", which I can deal with.
If I use icon: with the template there, I get no icon at all, just the text string displayed in the visual editor.
Obviously, I'm missing some important details. Can someone help me out please?

#

I pasted the template code into the template editor in devtools and it toggles exactly as I'd expect it to, so maybe it's not a template issue after all...

marble jackal
#

The link you shared describes creating a template sensor for that

#

Did you actually do that, as you are only sharing the code for the icon

hard venture
#

Well, no, I didn't. Looking at it, I thought I could directly check the value of the input_boolean. Do I need to go the whole 9 yards and create the template sensor to make this work?

#

Do I need to edit that directly into configuration.yaml, or is there now a GUI editor that might be preferred?

#

OK, I see where it has to be manually edited. No problem, I can do that.

frail scarab
#

Hello guys,
could you please help me with that:

  - name: "name_minuten"
    state: "{{ state_attr('sensor.name', 'time') }}"```
the attribute "time" of "name" gives me back 0:30, but i need 30
i'm fine with the removal of "0:" or the calculation
marble jackal
#

And what if the current state is 2:30

inner mesa
#

{{ '0:30'.split(':')[1] }}

#

But yes, perhaps the problem is under specified

frail scarab
#

2:30: yes, that could become a issue in future

#

under specified: what do you mean?

#

split(':')[1]: where do i have to put this?
Between time') and }}?

hard venture
frail scarab
#

@marble jackal and @inner mesa thank you very much!

spark flame
marble jackal
hard venture
hard venture
#

I guess this needs to head back to #frontend-archived since that's where my problem really seems to exist. Thanks all.

plain magnetBOT
sterile condor
#

Is there any kind soul knowing how to fix that, please?

inner mesa
#

You need to surround the template in quotes

plain magnetBOT
sterile condor
#

No idea why, but that hyphen is double. I used area_id: "{{ area_names }}"

marble jackal
#

how did you call the script?

sterile condor
#

Like this:

service: script.lights_toggle_previous_scene
data:
  area_names:
    - studio
    - camera
marble jackal
#

that doesn't match with what you posted above, there you don't have camera

sterile condor
#

this is my latest try, I've got a list of area_names, so there could be any number

#

I'm trying to provide the whole list into the params of the light.turn_off service

marble jackal
#

so, what is the result with this latest try

sterile condor
#
Result:
params:
  domain: light
  service: turn_off
  service_data:
    transition: 3
    area_id:
      - - studio
        - camera
  target:
    area_id:
      - - studio
        - camera
marble jackal
#

okay, it seems to put the input a new list

#

but I can't see why it does that. Maybe because it's past my bedtime...

#

If I figure it out while I'm sleeping I'll let you know in the morning

sterile condor
#
      - service: light.turn_off
        data:
          transition: 3
        target:
          area_id: >
            {{ area_names|list }}
#

this is my last try, same result as above

#

thanks ๐Ÿ™‚

#

goodnight

#

oh... if I use entity_id with the other list I compute, it works:

      - service: light.turn_off
        target:
          entity_id: >
            {{ entity_ids | list }}
#
params:
  domain: light
  service: turn_off
  service_data:
    transition: 3
    entity_id:
      - light.studio_1
      - light.studio_2
      - light.camera_1
      - light.camera_2
#

it seems like it had to do with the area_id specifically... thanks anyway ๐Ÿ™‚

floral shuttle
#

forgot to guard my template of solar forecast against now() being not availble in the dict after 19 hours (now, will be later when the season advances) , so figured I need to check whether now is in there. {% set nu = now().replace(minute=0, second=0 , microsecond=0).isoformat() %} {% set watts = state_attr('sensor.solar_forecast_estimate_watts','watts')%} {% set data = watts.items() %} {% if nu in watts %} {{ (data|selectattr('0','eq',nu)|first|default('Unknown',0))[0] }} {% else %} No production estimated {% endif %} would that be ok? COuld probably also check sun state being above_horizon, but for the sake of manipulating these KVP, what should I do ?

#

btw, this is what I have now {% set nu = now().replace(minute=0, second=0,microsecond=0).isoformat() %} {% set data = state_attr('sensor.solar_forecast_estimate_watts','watts').items() %} {{(data|selectattr('0','eq',nu)|first|default('Unknown',0))[1]}} and it renders a silly n, which I don't understand, other than the list being empty, phrased more correctly: UndefinedError: No first item, sequence was empty.

marble jackal
#

The n seems to be the 2nd character of Unknown

#

There was already a default provided in case there is no data

#

Ah, I see what happens

#

You need to put an extra pair of brackets around 'Unknown', 0

#

I expect petro added that as a default kvp in case nothing was reported, but now it uses only 'Unknown' as the default

#

The 'Unknown' part is the default for the timestamp, the 0 part is the default for the Watt value

#

So it does work if you do this
{{ (data | selectattr('0', 'eq', nu) | first | default(('Unknown',0)))[1] }}

#

BTWwhydoyoualwaysremovethespaces,itreallydecreasesreadability

floral shuttle
#

how can this be... ```
{{is_state('binary_sensor.wintertijd','on')}}
{{now().timetuple().tm_isdst == 0}}

#

the binary has the timetuple() template as template...

floral shuttle
#

Probably hours: 0 in the trigger โ€ฆ.

marble jackal
#

If it's trigger based it will update at midnight

#

And last time it triggered it was not dst

floral shuttle
#

Yep. Iโ€™ve moved those to the hourly trigger section now. Had forgotten about that.

#

this one is still having a detail issue though```
next: >
{%- set ns = namespace(previous = 3,spring=none,fall=none) %}
{%- set today = strptime(states('sensor.date'),'%Y-%m-%d').astimezone().replace(hour=ns.previous) %}
{%- for i in range(365) %}
{%- set day = (today + timedelta(days=i)).astimezone() %}
{%- if ns.previous - day.hour == -1 %}
{%- set ns.spring = today + timedelta(days=i) %}
{%- elif ns.previous - day.hour == 1 %}
{%- set ns.fall = today + timedelta(days=i) %}
{%- endif %}
{%- set ns.previous = day.hour %}
{%- endfor %}
{%- set next = [ns.spring, ns.fall]|min %}
{%- set phrase = 'verliezen een uur' if next == ns.spring else 'krijgen een uur extra' %}
{%- set clock = 'vooruit' if next == ns.spring else 'terug' %}

#

it still sees next as todays

#

where I would have wished, after the actual change it moved that to the next change of fall

#

wait, this fell of that paste: {"spring": "{{ns.spring.isoformat()}}", "fall": "{{ns.fall.isoformat()}}", "event": "{{next.isoformat()}}", "days_to_event":{{(next-today).days}}, "phrase": "{{phrase}}", "clock":"{{clock}}"}

#
          next: >
            {"spring": "2023-03-26T03:00:00+01:00",
             "fall": "2023-10-29T03:00:00+01:00",
             "event": "2023-03-26T03:00:00+01:00",
             "days_to_event":0,
             "phrase": "verliezen een uur",
             "clock":"vooruit"}``` is the current output
silent vector
#

Any ideas why the automation editor doesn't like the regex_findall_index but the template editor takes it? As soon as I remove that the automation editor turns blue. Put it back and it's red.. I have used this exact regex_findall_index before.

entity_id: "number.{{ (sensor.split('_presence')[:1] | join('') if 'presence' in sensor else sensor.split('_illuminance')[:1] | join('')) | regex_findall_index('\.([^\.]+)$') + '_' + item }}"
floral shuttle
marble jackal
#

@floral shuttle no trigger for this one?

floral shuttle
#

Hourly

#

But the dev tools are minutely so the issue becomes clear

marble jackal
#

It will not update minutely, as it doesn't use now()

floral shuttle
#

What I mean is if you enter the template in dev tools you will see what happens. Next still shows today, even after it has already happened

marble jackal
#

This partially solves it
{%- set next = [ns.spring, ns.fall] | reject('<', now()) | min %}

#

It will still show ns.spring as today, but it will ignore it for next

#

Btw, you can replace strptime(states('sensor.date'),'%Y-%m-%d') with today_at()

floral shuttle
#

Thx! Will test when I get home ๐Ÿ˜‰ appreciated

plain magnetBOT
sonic ember
#

hours.value should be a float? and so is my input number. What am I doing wrong here?

plain magnetBOT
#

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

gleaming schooner
visual dawn
#

mqtt:
switch:
name: "Garage Door"
state_topic: "garage/door/status"
command_topic: "garage/door/set"
payload_on: "open"
payload_off: "close"
retain: true
icon: mdi:garage-open
value_template: "{{ is_state('switch.street_rele_l1', 'on') }}"

I have a switch switch.street_rele_l1, and I need to create a virtual switch that will remember its status. In this configuration, the switch isn't workin

How can I solve this problem?

marble jackal
sonic ember
#

Yes I do.

#

But I think I found the error a few seconds ago... It will work again tomorrow...

#
- start: '2023-03-26T03:00:00+02:00'
  end: '2023-03-26T03:00:00+02:00'
  value: null
#

It's probably just because of the missing hour today (is my guess)

gleaming schooner
# gleaming schooner Sorry for the long message. I'm trying to add a condition like below: condition...

I found at least one solution:

`action:

  • repeat:
    count: 4
    sequence:
    - condition: template
    value_template: "{{ trigger.to_state.state == states[trigger.entity_id].state }}"
    - service_template: switch.turn_{{trigger.to_state.state}}
    enabled: true
    target:
    entity_id: "{{ trigger.entity_id }}"
    - delay: 2
    enabled: true`

What this does is that it only repeats if my lates configuration of the switch is the same as the loop is repeating for. This is to protect the loop from me switching on and off to fast

marble jackal
#

What are you trying to do here? Why are to turning an entity to the state it justed turned to

gleaming schooner
#

๐Ÿ™‚ The RF 433 is just one-way, and sometimes the device misses

marble jackal
#

And service_template is depreciated for 3 years now. You can just use service

gleaming schooner
#

Thanks

marble jackal
gleaming schooner
marble jackal
#

I was clearly not replying to you, as I'm doing a direct reply to a post of another user

gleaming schooner
sonic ember
floral shuttle
marble jackal
floral shuttle
#

though replacing that in the temoplate changes the tz details:```
2023-03-26 00:00:00+01:00
2023-03-26 00:00:00+01:00

2023-03-26 03:00:00+01:00
2023-03-26 03:00:00+02:00```

#

being the output of:```
{{today_at()}}
{{strptime(states('sensor.date'),'%Y-%m-%d').astimezone()}}

{{strptime(states('sensor.date'),'%Y-%m-%d').astimezone().replace(hour=3) }}
{{today_at().replace(hour=3) }}

#

adding the astimezone there fixes that: {{today_at().astimezone().replace(hour=3) }}