#templates-archived

1 messages · Page 70 of 1

quasi frost
#

thx!

fossil frost
#

Hi! I'm trying to use the markdown card to use jinja2 code that lists all battery entities with the device_class battery and show the ones below 25%. Has anyone done this before and might give some pointers in the right direction? I know I can use battery state card, but I would like a clean text-based list of entities.

mighty ledge
#

Can you post the jinja that you've tried?

bronze prawn
#
message: Helen Adams Keller was an American author, disability rights advocate, political activist and lecturer. Born in West Tuscumbia, Alabama, she lost her sight and her hearing after a bout of illness when she was 19 months old. She then communicated primarily using home signs until the age of seven, when she met her first teacher and life-long companion Anne Sullivan. Sullivan taught Keller language, including reading and writing. After an education at both specialist and mainstream schools, Keller attended Radcliffe College of Harvard University and became the first deafblind person in the United States to earn a Bachelor of Arts degree.

I've got a large blob of text. Sometimes on these searches I get a lot like this but others not as much. Is there an easy way to limit to just the first two or three sentences? if not, is there an easy way to limit by number of characters and then add the ... to the end?

mighty ledge
#

split the message by periods to get number of sentences

#

or [:255] for everything before the 255th character

marble jackal
#

{{ "large text" | truncate }}

#

that will limit it to 255 characters (including ... at the end) and split on the last full word

smoky tinsel
#

is there a way to get the device_id of the device that triggered an automation?

Trying to do something like:

value_template: "{{ trigger.device_id == 'xxxx' }}"
marble jackal
#

what is your trigger?

#

but I expect "{{ device_id(trigger.entity_id) == 'xxxx' }}" will work

smoky tinsel
#

It's a motion sensor. First time trying to work out a more custom automation (rather than just using a blueprint).

Aiming to get this flow:

https://i.imgur.com/x1ffbIm.png

Ill try what you mentioned 👍

smoky tinsel
#

Ah, worked it out, so, entity_id seems to be only available on some platforms, switched to using state from device and seems to be working now. Thanks for your help

marble jackal
#

That's why I asked what the trigger was

lone coyote
#

How do i get this condition to work? It should pass, but it doesnt.. and is there a simpler way to find an item in an array?

alias: Jafaris alert
description: ""
trigger:
  - platform: time_pattern
    minutes: "10"
condition:
  - condition: template
    value_template: |
      {%- for post in (state_attr('sensor.jafaris', 'schedule') | list) -%}
        {{ post.place == 'Ed' }}
      {%- endfor -%}
action: []
mode: single
lone coyote
mighty ledge
#
{{ state_attr('sensor.jafaris', 'schedule') | map(attribute='place') | select('match', 'Ed') | first | default == 'Ed' }}
#

basically it gets the first item if it exists and compares it to ed, if it doesn't exist, it'll fail the condition

#

also, it removes the need for () and other things you had

lone coyote
#

thanks :)

#

looks a bit safer ye

mighty ledge
#

test it out first

#

might need a | list before the | first

lone coyote
#

it worked

zealous rose
#

If I add a template sensor based on some other sensors, should the results be available immediately or do I need to wait for more data? I'm trying to calculate energy usage for last 24h, yesterday, last week, ... Or is there a better way of doing that? I need it as a value so I can later use it in estimating the cost.

smoky tinsel
#

I dont know if this is best for here or #automations-archived but, trying to set some variables based on some conditions and then use them in a service call but I cant seem to get it working, i have a feeling the variables aren't being set but cant work out what I am doing wrong.

I am switching between yaml and the UI editor as I am new to this, so trying to learn the yaml by seeing what the UI is doing and then tweaking it.

http://pastie.org/p/3YZz1UHZNIiHg8Fce6Iw9T

mighty ledge
#

you have to template the entire variable at the same level where you use it

#

meaning anything in an if-then action section will not work outside the if-then action section

smoky tinsel
#

gotcha, so based on that im probably better just doing the end action in multiple places, than setting a variable and using it later

mighty ledge
#

or just template the whole variable

#

brightness: "{{ iff(today_at('12:00') < now() < today_at('18:00'), 2, 100) }}"

#

oh wait, you have more logic

smoky tinsel
#

yeah, if the trigger was a door sensor, i want always 100%, but i like your idea, thats far cleaner

mighty ledge
#
brightness: >
  {% if today_at('12:00') < now() < today_at('18:00') %}
    2
  {% elif trigger.id == 'DOOR_SENSOR' %}
    100
  {% else %}
    100
  {% endif %}
smoky tinsel
#

Thanks, will try this

mighty ledge
#

do the same for delay

#

If you really want to get cheeky....

smoky tinsel
#

My main aim is to learn as much of this as I can, i work as a software developer so i just need some exposure and i should start understanding it.

So yes cheeky for sure 🙂

mighty ledge
#
variables:
  settings: >
    {% if today_at('12:00') < now() < today_at('18:00') %}
      {'brightness': 2}
    {% elif trigger.id == 'DOOR_SENSOR' %}
      {'brightness': 100, 'delay': 300}
    {% else %}
      {'brightness': 100, 'delay': 60}
    {% endif %}

Then later..

  - service: light.turn_on
    data: "{{ settings }}"
    target:
      device_id:
        - 8a5ed3da4078996d696c1669aef7a6e0
        - b49e5722c65191ff0d1d4886404a6d9a
#

if you want to learn complex templating, just look at my repo

#

I avoid yaml when I can and use templates as much as possible to reduce overhead

smoky tinsel
#

Thanks I will defo take a look. Its one of those things, I can read it and undestrand it, but the moment I try to write something from scratch, im a bit lost. So I will definitely take a look as it will just add to the understanding

mighty ledge
#

it's python with extra flavor

#

but also less flavor

#

jinja is weird

#

take a look at the pins

toxic light
#

Hi, you can help me to convert timestamp ?
I use a multiscrap sensor, but he doen't work :/
actual timestamp : 1709920796 and lastsee : 1709916039

#
  • unique_id: see_last
    value_template: "{{ (states('value_json.lastsee') | as_datetime | as_local).isoformat() }}"
#

I don't understand how to get the date in correct form, thanks

mighty ledge
toxic light
#

result : 2024-03-08 17:40:39+01:00
Many thanks, is it possible to remove the +....

mighty ledge
#

it won't be the correct time if you do

#

add device_class: timestamp

#

and it'll show up in the UI as your formatted time

#

e.g.

  value_template: "{{ value_json.lastsee | as_datetime | as_local }}"
  device_class: timestamp
toxic light
#

with devise_class the result is 2024-03-08T16:40:39+00:00
i would like to have just : 2024-03-08 17:40:39

mighty ledge
#

don't look at the states page

#

e.g.

toxic light
#

Oh ! really

mighty ledge
#

Yes

toxic light
#

it's true thanks, it's work

#

very well

#

Thanks 🍻

quiet kite
#

I use integration for ipmi. It gives me a button to turn the computer on and off. Pressing the button causes the computer to switch on after about a minute. Until then, the status of the button is Off, this means that I can press it to send the on/off commands to ipmi. Which can result in the computer stopping turning on.... I would like my button to be able to be pressed again only one minute after it was pressed. How do I achieve this?

mighty ledge
#

Make a script with mode single. The script will turn on the switch then delay 1 minute. Next make a template switch that’s turn on function is the script. Its turn off is the turn off of the switch in the script. The value template is state of the switch in the script

winged hare
#

trying to create a sensor to measure how long my car is driven each week
- platform: history_stats name: Fiat Connected entity_id: binary_sensor.fiat_connection state: "on" type: time start: “{{ as_timestamp( now().replace(hour=0, minute=0, second=0) ) - as_timestamp(now().weekday() * 86400 )}}” end: “{{ now() }}”
but the log complains "start must be a datetime or a timestamp: could not convert string to float"

marble jackal
#

Replace those fancy quotes with normal double quotes

#

You could simplify that template to
"{{ today_at() - timedelta(days=now().weekday()) }}"

winged hare
#

thanks - let me try that. I'm not sure where those fancy quotes came from though 🙂

winged hare
#

That worked - thanks TheFes

silent vector
#

Any idea how I could efficiently take a list of numbers get the 2 highest numbers, if the difference between them is >= 15 for example try the next 2 highest until the difference between the 2 highest is <= 15 then output the highest number?

obtuse zephyr
#

Here a way:

{%- set numbers = [11,27,26,30,46] -%}
{%- for number in numbers | sort(reverse=True) -%}
{%- if loop.nextitem is defined and (number - loop.nextitem) <= 15 -%}
    {{- number -}}
    {%- break -%}
{%- endif -%}
{%- endfor -%}
silent vector
#

I was so close lol I just started down the nextitem and reverse sort path

#

Just was not sure how to stop the loop

#

Thank you!

obtuse zephyr
#

You bet

silent vector
#

In a template sensor you can do this.attributes.yourvar can you do the same in an automation for a variable with a yaml dictionary so keys with jinja can reference other key values in the same dictionary.

mighty ledge
#

I don't follow your question

heavy minnow
#

https://www.home-assistant.io/integrations/switch.template/

Hello, I have a switch to toggle my AC using a universal IR remote, but the current switch code can't know if the ac is on or off, so I hooked an energy meter to the AC, how can I add this condition to the switch? like if the current is over 3 amps say that it is on and vise versa?

#
  switches:
    dining_room_ac_switch:
      value_template: "{{ states('sensor.ac_current') | float > 3 }}"
      turn_on:
        service: script.dining_room_ac_on20
      turn_off:
        service: script.dining_room_ac_off
      friendly_name: "Dining Room AC"
``` would this work?
marsh cairn
#

Looks ok

heavy minnow
#

great, chatgpt knows his stuff

#

thank you too : )

marsh cairn
#

If sensor.ac_current exists in your HA. ChatGPT makes up stuff sometimes.

heavy minnow
#

yes it's making it up, i'll just have to replace it

silent vector
marsh cairn
#

If you have some power measuring, it is usually called something with power and the unit of measurement is W

torn meteor
#

i have commands working, but no matter what i try, state is still optimistic and not using the state i want

#
mqtt:
  - fan:
      - name: Fan
        unique_id: fan0
        command_topic: "fan/on/set"
        state_topic: "fan/on/state"
        state_value_template: "{{ states.input_text.current_fan.state }}"
#

i tried w/ and w/o the state_value_template but that didn't make a difference

#

just seeing two lightning bolts for the entity controls, instead of it actually showing the fan as on or off 😦

silent vector
#

That's what I thought

silent vector
mighty ledge
#

It’s a state object in the template sensor

#

Variables are not part of the state object

plain magnetBOT
#

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

marble jackal
wanton cove
#

Hello here, when I am creating a sensor template, do I still need to put the code into the configuration.yaml? I have troubles recreating the one saving temperatures from the weather forecast: https://community.home-assistant.io/t/outside-temperature-add-to-history/452230/15
I put the code into the configuration.yaml file, but cannot find any new entity. Also how does the name of entity works? Is it created from the name attribute, so if the name would be "Outside temperature" the entity would be called sensor.outside_temperature?

wanton cove
#

ok, nevermind, seems like restart of the system did fix it

cosmic hamlet
#

Heya. Is there some home assistant template that makes a string commandline save like escaping & | ' and "

mighty ledge
#

Use multiline yaml notation to avoid escaping.

#

\ escapes in yaml

lucid thicket
feral dust
#

Next alarm trigger not working anymore

cedar jay
#

Remaining Charging Time for PV Battery

maiden magnet
#

hey
how can i store the data from a "get" request, for example from "get.items", in an entity

lucid thicket
#

Not sure I understand the question, but an input helper or a template sensor are the two main ways to store data

summer arch
#

Hey, I am looking for some guidance. I have contact sensors on my doors upstairs and I want to make a sensor that updates for when the vacuum cleans rooms based on when the doors are open.

plain magnetBOT
#

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

summer arch
#

I think I have done it right but what I am confused on is what if the door is not open? I want to leave the value as it

mighty ledge
#

what does the door have to do with cleaning a room?

summer arch
#

Well if the doors closed... how does the vacuum get in...

marble jackal
#

first thing I notice is the quotes around your output

#

remove those

#

and what if the door is opened like 2 minutes after the vacuum started, it will still clean the room

mighty ledge
marble jackal
#

you can define both sensors under the same trigger

summer arch
summer arch
mighty ledge
#

check the pins

#

quotes are needed for specific situations with yaml

#

they are not needed for jinja

mighty ledge
#

"Distinguishing Yaml from Jinja (templates) community.ho..."

marble jackal
#
- trigger:
    - platform: state
      entity_id: vacuum.upstairs_vacuum
      to: cleaning
      for:
        minutes: 1
  sensor:
    - unique_id: upstairs_vacuum_last_clean
      name: "Upstairs Vacuum Last Clean"
      state: "{{ trigger.to_state.last_changed }}"
      device_class: timestamp
      icon: mdi:broom
      
    - unique_id: bedroom_last_cleaned
      name: "Bedroom Last Cleaned"
      state: |
        {% if states('binary_sensor.bedroom_door_sensor_contact') and states('binary_sensor.spare_room_door_sensor_contact') %}
          {{ trigger.to_state.last_changed }}
        {% else %}
          {{ this.state }}
        {% endif %}
#

Do both doors have to be open for the vacuum to be able to clean the bedroom?

summer arch
marble jackal
#

that makes sense 🙂

plain magnetBOT
#

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

summer arch
#

Ok so remiving quotes in the multiline states?
this.state if door not open
last clean uses trigger last changed not now

#

think that covered all the suggestions?

Late at night so won't get to test it now

marble jackal
#

as you base it on the same trigger, I would just use trigger_to_state.last_changed as input for all sensors

harsh vessel
#

Is a template sensor the best way to convert the text output of a binary sensor?

Example: My door sensors gives "opened" or "closed", but the blueprint I am using expects "on" or "off"

inner mesa
#

a binary_sensor is already on/off

#

it's just displayed differently depending on the class

harsh vessel
#

hm ok maybe something else is broken then

#

So in the backend that's already translated then, it's just on the UI I see opened/closed

inner mesa
#

the other way around, but yes

grizzled grove
#

Hey,
I'm outputting a string, and the only option to separate it, as a list, is by using 'double space':

value_template: |
  {%-set value = value.split("  ")-%}
  {%for x in value%}
  - {{x}}
  {%-endfor-%}

Unfortunately, there's a final 'double space' at the end of the string - creating a blank:

- text...
- text...
-

Any idea of a solution?

marble jackal
#

what kind of value template is this? if it expects a list, this should be enough {{ value.split(" ") }}

mighty ledge
#

I don't know of any value_template field that accepts anything other than a string, bool, float, or int

marble jackal
#

yeah, me neither..

#

maybe something custom

grizzled grove
#

It's from multiscrape.

#

For some reason the attr comes as a list, but without the value_template it stays as a string when {{state_attr('sensor...', 'attr')}}.

#

Wait, in the template it comes as a list - but in a card it comes as a string. mindblown

marble jackal
#

if the result of that is the state of your entity, it will always be a string

#

states are always strings

grizzled grove
marble jackal
#

how does the attribute look in devtools > states?

grizzled grove
# marble jackal how does the attribute look in devtools > states?

Without the value_template, it comes as:

17:30 Gaziantep FK Besiktas SPORT TV1   18:00 Belenenses Leixões SPORT TV+   19:30 SD Amorebieta Leganés ELEVEN SPORTS 4   19:45 Lazio Udinese SPORT TV2   20:00 Almería Sevilla ELEVEN SPORTS 2   20:00 Chelsea Newcastle ELEVEN SPORTS 1   20:15 AVS SAD Feirense SPORT TV3   20:15 Gil Vicente Desp. Chaves SPORT TV1
marble jackal
#

yeah, so split that using the template I gave

grizzled grove
#

If I do:

[
  "",
  "17:30 Gaziantep FK Besiktas SPORT TV1",
  " 18:00 Belenenses Leixões SPORT TV+",
  " 19:30 SD Amorebieta Leganés ELEVEN SPORTS 4",
  " 19:45 Lazio Udinese SPORT TV2",
  " 20:00 Almería Sevilla ELEVEN SPORTS 2",
  " 20:00 Chelsea Newcastle ELEVEN SPORTS 1",
  " 20:15 AVS SAD Feirense SPORT TV3",
  " 20:15 Gil Vicente Desp. Chaves SPORT TV1",
  ""
]
marble jackal
#

where do you see this output?

grizzled grove
# marble jackal where do you see this output?

In devtools > template; if I check the devtools > state:

friendly_name: Football Game
list: , 17:30 Gaziantep FK Besiktas SPORT TV1,  18:00 Belenenses Leixões SPORT TV+,  19:30 SD Amorebieta Leganés ELEVEN SPORTS 4,  19:45 Lazio Udinese SPORT TV2,  20:00 Almería Sevilla ELEVEN SPORTS 2,  20:00 Chelsea Newcastle ELEVEN SPORTS 1,  20:15 AVS SAD Feirense SPORT TV3,  20:15 Gil Vicente Desp. Chaves SPORT TV1, 
marble jackal
#

okay, so it is a perfectly fine list

marble jackal
#

for your markdown card you could use:

{% for item in state_attr('sensor.your_scrape_sensor', 'list') %}
- {{ item }}
{% endfor %}
#

oh, and you might want to change the template for your attribute to {{ value.split(" ") | select() | list }} to remove the empty ones

torn meteor
#

final:

mqtt:
  - fan:
      - name: Fan
        unique_id: fan0
        command_topic: "fan/on/set"
        state_topic: "fan/on/state"
        state_value_template: "{{ states(states.input_text.current_fan.state)|upper }}"
        payload_on: "ON"
        payload_off: "OFF"
halcyon sun
#

Hi Guys, i'm struggling with this template for some times, the result is always Unavaible, somebody can help me Please :
`{% set today = as_timestamp(now().date()) %}
{% set garbage_dates = state_attr('calendar.chalet_service', 'events') %}

{% set prochains_dates_ordures = garbage_dates | selectattr('summary', 'eq', 'Ordures') | selectattr('all_day', 'eq', True) | map(attribute='start_time') | map('as_timestamp') | select('>=', today) | list %}
{% set prochain_date_ordures = prochains_dates_ordures | first %}
{% set jours_jusqua_ordures = ((prochain_date_ordures - today) / 86400) | int if prochain_date_ordures is not none else None %}

{% set prochains_dates_recyclage_compost = garbage_dates | selectattr('summary', 'eq', 'Recyclage et compost') | selectattr('all_day', 'eq', True) | map(attribute='start_time') | map('as_timestamp') | select('>=', today) | list %}
{% set prochain_date_recyclage_compost = prochains_dates_recyclage_compost | first %}
{% set jours_jusqua_recyclage_compost = ((prochain_date_recyclage_compost - today) / 86400) | int if prochain_date_recyclage_compost is not none else None %}

{% if prochains_dates_ordures | length == 0 and prochains_dates_recyclage_compost | length == 0 %}
Aucun événement de collecte d'ordures à venir.
{% else %}
{% if jours_jusqua_ordures == 0 %}
C'est le jour des ordures.
{% elif jours_jusqua_ordures == 1 %}
Demain, c'est le jour des ordures.
{% elif jours_jusqua_recyclage_compost == 0 %}
C'est le jour du recyclage et du compost.
{% elif jours_jusqua_recyclage_compost == 1 %}
Demain, c'est le jour du recyclage et du compost.
{% else %}
{% if jours_jusqua_ordures is not none %}
Prochaine collecte des ordures dans {{ jours_jusqua_ordures }} jours.
{% endif %}
{% if jours_jusqua_recyclage_compost is not none %}
Prochaine collecte du recyclage et du compost dans {{ jours_jusqua_recyclage_compost }} jours.
{% endif %}
{% endif %}
{% endif %}`

plain magnetBOT
#

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

#

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

fringe sail
#

Hey guys. I have an Ecobee thermostat and I can see when it's heating in HA. How would I write a template sensor that would tell me
how long the heat ran?

lofty mason
haughty breach
maiden magnet
sonic sand
#

hey!
I'm currently using a sensor I created to monitor my boiler time on

- platform: history_stats
  name: Boiler On
  entity_id: input_select.switcher_boiler_status
  state: "On"
  type: time
  start: "{{ now().replace(hour=0, minute=0, second=0) }}"
  end: "{{ now() }}"

However even when the Boiler is off it's showing the last time it was on and for how long.. also how can I convert it to minutes instead of hours? Thanks!

marble jackal
#

It will always use hours, if you add a unique id in your config you can simply change the unit of measurement

sonic sand
marble jackal
#

That's not how that sensor works

#

It shows how long it has been On today, regardless of it's current state

sonic sand
floral shuttle
#

loving the new state_translated() templates. however, is it a bug, or just not yet implemented that 'unknown' is not translated?

#

cause now I need to do this on my entities: {% if is_state(config.entity,'unknown') %} Uit {% else %} {{state_translated(config.entity)}} {% endif %} in a template-entity-row..

#

which is correct in itself, as Ive turned_off the switch. just wondering why it doesnt say 'Onbekend'.

#

feels buggy because this {{states('binary_sensor.achterdeur_buiten_sensor_motion')| state_translated}} even errors with

marble jackal
#

I've already seen that before, that unavailable and unknown are not translated, so it's known. Not sure if it's intended

marble jackal
floral shuttle
#

just to be sure, and it shouldnt throw an error on the filter

marble jackal
#

@floral shuttle In the first example you are using state_translated on the state, you should use it on the entity_id

#

{{ 'binary_sensor.achterdeur_buiten_sensor_motion' | state_translated }}

#

That's what causes the error on the filter

mighty ledge
#

The error even points to what was done wrong TemplateError: Invalid entity ID 'unkonwn'

#

I'd remove that from the issue because all it's going to do is make the code owner overlook the issue.

lucid thicket
# maiden magnet but how would be the code? idk how to write attribuetes

If you want the data to persist through a HA restart you’ll need a trigger-based template sensor. You’ll need to create it in YAML following these docs. Your sensor will need a state and so if you only want to define attributes you can just set something like state: 'ok' Attributes are simply added as a separate fields:

attributes:
  my_attribute: "{{ template_goes_here }}"
marble jackal
lucid thicket
#

Thanks. That whole post was garbage 😅

sonic sand
marble jackal
#

then you should use the time it turned On as the start parameter, not midnight

sonic sand
floral shuttle
marble jackal
#

BTW, a PR I created was just merged to replace that template with {{ today_at() }} in the History Stats docs

#

I guess this will work:

- platform: history_stats
  name: Boiler On
  entity_id: input_select.switcher_boiler_status
  state: "On"
  type: time
  start: "{{ states.input_select.switcher_boiler_status.last_changed }}"
  end: "{{ now() }}"
#

It will show the time it has been set to On since the last time the entity changed its state

#

It will reset if you restart HA though

mighty ledge
#

but it's a step in the right direction for sure

sonic sand
mighty ledge
#

I was talking to thefes and his PR change

marble jackal
#

might have been more clear what it does

dry kettle
#

Wondering if something changed in the configuration yaml in regards to calculating totals..

I have a sum of a sensor using this code:

     - name: "Solar totaal"
       unique_id: "solar_totaal" 
       unit_of_measurement: "W"
       state: >
          {{ states ('sensor.solaredge_ac_power') | float(0) | round(0)
           + states (' sensor.smart_meter_zonnepanelen_schuur_electric_consumption_w_filterspikes' ) | float(0) | round(0) }}

but that seems to have stopped working somewhere recently.. that second/last line is not added as a sum to the solar_totaal sensor that's created in the configuration.yaml here. Am I doing something deprecated here?

mighty ledge
#

space

#

also, you don't even need a template for this, just make a sensor group with 'sum' as your group option.

dry kettle
#

oh slap my bum and call me sally.. let me see if that fixes it smile

#

no the space doesn't seem to make a difference. Let me check that sensor group option

#

doing a few others with subtract as well, let me see if you can do some math in those

mighty ledge
#

you can't move subtraction to the sensor group

#

only sum, average, etc

dry kettle
#
  - sensor:
     - name: "Stroomverbruik in huis"
       unique_id: "stroomverbruik_huis" 
       unit_of_measurement: "W"
       state: >
          {{ states ('sensor.solaredge_ac_power') | float(0) | round(0)
           + states ('sensor.smart_meter_zonnepanelen_schuur_electric_consumption_w_filterspikes' ) | float(0) | round(0)
           - states ('sensor.smartmeter_power_production') | float(0) | round(0) 
           + states ('sensor.smartmeter_power_consumption') | float(0) | round(0) }}

another one I use.. it's basically to add up the total of the solar inverters, subtract the total production and/or consumption value as reported by my smart meter to get the actual in-house power usage of all appliances .. so that uses a combination of add and subtract

mighty ledge
#

yes, all that kind of stuff needs templates still

dry kettle
#

hmm think I found the culprit

#

sensor.smart_meter_zonnepanelen_schuur_electric_consumption_w_filterspikes <-- this one

refers to a spike filter method, as the zwave kwh meter tends to be a bit weird with its values sometimes when it reconnect..
Which is this formula:

# Aeotec power filter (get rid of nonsense spikes)
  - platform: filter
    name: "sensor.smart_meter_zonnepanelen_schuur_electric_consumption_w_filterspikes"
    entity_id: sensor.smart_meter_zonnepanelen_schuur_electric_consumption_w
    filters:
     - filter: outlier
       window_size: 4
       radius: 10.0

and although that works fine as a sensor still and it has values, it seems it's not being recognised in the configuration.yaml template to use as such

#

if I change the non-working sensor template to the original 'sensor.smart_meter_zonnepanelen_schuur_electric_consumption_w' it works

#

not a big issue tbh

#

but it used to work

#

(also yes, the spike filter comes before the other template functions)

quartz heron
#

Hello guys need some help please: been using this template to get a time but after the sun2 integration update it now supplied a timestamp like this (2024-03-13T06:25:16+00:00) and not just a time. so my previouse template is no longer working but have no clue what i need to change.

'{{ (as_timestamp(states.sensor.sun_next_rising) + (states("input_number.sunrise_offset") | int) * 60) | timestamp_custom("%H:%M") }}'

any help is appreciated thanks!

mighty ledge
#

as_timestamp(states.sensor.sun_next_rising) has never been correct syntax

#

the rest seems fine

#

but, this is easier now anyways.

#

well easy is relative

#
{{ states('sensor.sun_next_rising') | as_datetime | as_local + timedelta(minutes = states('input_number.sunrise_offset') | float) }}
#

I'd change your sensor to a device_class: timestamp too. Then the UI will translate the time to whatever your system has set up.

#

and you'll be able to use the sensor in automations

#

if you keep it HH:MM, you won't have those luxuries

inner mesa
#

And maybe consider using sun elevation for whatever you're doing

#

Kinda seems like you're trying to fix a light level issue

quartz heron
mighty ledge
#

You either changed something, or it never worked the way you think it did

#

states.sensor.sun_next_rising from when HA first introduced templates always returned state objects, not states. So as_timestamp would always return 0 (beyond 3 years ago) or an error (starting around 3 years ago).

quartz heron
#

it definetly worked

#

been working for years

#

putting the new template in though isnt working though i guess how its in config has changed too

#

" sunrise_with_offset:
friendly_name: 'Sunrise Time'
value_template: '{{ states('sensor.sun_next_rising') | as_datetime | as_local + timedelta(minutes = states('input_number.sunrise_offset') | float) }}'"

mighty ledge
#

does sensor.sun_next_rising exist?

quartz heron
#

yes if i past just the template into dev template it works

#

must be my formatting in the config file that it doesnt like

mighty ledge
quartz heron
#

ive done it as a helper template now and its working how can i set it to only show HH:mm dont need the date please

mighty ledge
#

make it device_class: timestamp

#

and it will translate the unreadable state in your frontend when you use it

#

no formatting required, it uses what you set in your settings

quartz heron
#

i dont see timestamp as an option in template helper

mighty ledge
#

scroll down

quartz heron
#

its an hour ahead for some reason none of my other time based stuff is an hour ahead

#

time zoen is all set ok

#

ok looks like my old sensor was an hour behind hahaha

#

ah no i see issue used a + not a - im an idiot

#

thanks for help looks like its all good now

unique turret
scenic verge
#

Evening all. I just tried to add the following to configuration.yaml, but the added sensor says "not available". whats wrong here?

  - binary_sensor:
      - name: "Car Parking Spot Helper"
        delay_off:
          seconds: 15
        state: >
          {{ states('binary_sensor.car_parking_spot_car_occupancy')|float > 0 }}```
errant dome
#

Hi all, I was trying to list and sort all my utility meters that start with sensor.week_energy. But the sort is done by string value , instead I need it by numeric value. For example the value 3.17 kW/h would be sorted before 13.65 kW/h , because the 3 string is greater than the 1 string.

How should I change this code?

| sort(reverse=true, attribute='state')%}
{{state.name[20:]}}: {{state.state | float(default=0.0) | round(2) }} kW/h{% endfor %}```

Thanks!
fickle sand
scenic verge
#

how would i then put it?

fickle sand
#

What do you want to achieve?

scenic verge
#

basically want this binary sensor to be a exact copy of binary_sensor.car_parking_spot_car_occupancy

#

just goes off 15s later when the actual binary sensor turns off.

mighty ledge
#

remove the | float > 0 then

scenic verge
#

thank youuuu ❤️

marble jackal
wary yew
#

I've tried creating a template binary_sensor based on 2 door sensors:
{{ is_state('binary_sensor.living_room_door_contact', 'open') or is_state('binary_sensor.utility_room_door_contact', 'open') }}
I want it to show as open whenever any of the 2 doors is open, to show my cat has free access to its food.
But it's not reacting as expected. Rn one door is open but the sensor shows closed. What did I do wrong?

I did it via UI. Choosing "Show as door".

marble jackal
#

Just create a binary sensor group, you can do that in the GUI under helpers

#

No templates required

#

Your template isn't working because the state of a binary sensor is on or off

#

Not open or closed. It's translated on your Dashboard based on the state class

#

Check in developer tools > states what the actual state is

wary yew
#

ahh, got confused with that

#

yeaah, I was playing around there but got confused. Thanks

#

never used the group helper

#

I see I can choose whether to use All or Any

#

nice, thanks

gaunt umbra
#

Hello! Im trying to make a template that counts how many people are on the bed. i have the sensor set up using esp home and sensor.bedsensor_hx711_value value ranges from <150lbs no one on the bed >150lbs 1 person >200lbs 2 people. I not very good at templating and could not find someone doing something simular on google or the forms. Could someone help me please? thank you!

plain magnetBOT
#

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

quasi frost
#

and i added now the 2 new devices "Labor" and "Garage", but they dont work

#

found the problem
instead of notify.alexa_abstellkammer i need to use notify.alexa_media_abstellkammer 🙂

rocky crypt
#

Hey there. I am having a strange problem that I can't figure out... I have a BASIC script and it is failing..

set_power_cost:
  alias: Automation - Set Cost of Power
  squence:
    - service: input_number.set_value
      target:
        entity_id: input_number.utility_cost_aps
      data:
        value: 0.5

Any idea why it wouldn't work? The error I'm getting is:

2024-03-13 03:11:04.144 ERROR (MainThread) [homeassistant.components.script] Script with alias 'Automation - Set Cost of Power' could not be validated and has been disabled: extra keys not allowed @ data['squence']. Got [{'service': 'input_number.set_value', 'target': {'entity_id': 'input_number.utility_cost_aps'}, 'data': {'value': 0.5}}]
#

Oops!

#

Haha!

#

SEQUENCE 🙂

#

Wow!

#

Well, thanks! ROFL 🙂

#

Was a great chat!

marble jackal
plain magnetBOT
#

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

fickle sand
#

state_class is not supported in a legacy-type template sensor, also measurement contains a typo

rocky crypt
#

Got it. Ok. Thanks. I guess I'll just use the customize function then.

fickle sand
#

You could also create the sensor from the GUI

#

That uses interally the new template configuration

rocky crypt
#

Got it. Thank you. Is HA going away from YAML configuration and trying to make everything GUI? Is that why it's supported in GUI, but not YAML?

fickle sand
#

Not particularly, it's also supported in yaml as part of the template integration which is not the same as the legacy template sensor in your example

#

And a sidenote don't use the states object directly, but use the states function to extract the state.

value_template: "{{states('sensor.forecast_temp')}}"
rocky crypt
#

Ok. Perfect! Thank you for your help!

rocky crypt
#

@fickle sand Thanks again! I converted it to the template integration and it worked perfectly! One other question. You said to access the states function instead of the states object directly.. Is there a reason? I did change it as you recommeneded, but just trying to learn from my mistakes 😉

mighty ledge
#

why do you want to get rid of unavailable

#

you can't use the switch if it's unavailable

#

that will misslead you

#

if it's a binary sensor, a template sensor is the best route. But for anything that's controllable, you don't want to do that.

rocky crypt
#

Hey there. Another quick question. I was using Legacy Templates and trying to convert them to template integration.. I see there is template integration for sensors, binary sensors, numbers, and weather... Is there still not a template integration for covers? Does anyone know if there ever will be?

rocky crypt
#

Right, but that's the legacy way so to speek isn't it? That's how I was doing sensors before... Just using sensor: then platform template... The template integration sensor goes under template... Maybe I'm wording this wrong....

#

So, for template integration way... I would have expected to see:

template:
  - cover:
      - name: "My Cover Name"
lofty mason
#

hmm that I am not sure.

rocky crypt
#

Does that makes sense? Am I wording that correctly? So, it seems as if "covers" are still stuck in legacy mode...

lofty mason
#

I see what you're saying, I don't know what is the right answer.

#

As far as I know "legacy mode" is only applicable to sensor and binary_sensor. No other domains have deprecation warnings.

rocky crypt
#

Ok. Well, at least I feel better and not thinking I'm going crazy haha 🙂

#

Got it... Well, maybe it's in the works to convert the others? who knows... 🙂

#

I see on the template page, it says:

Sensors, binary (on/off) sensors, buttons, images, numbers and selects are covered on this page. For other types, please see the specific pages...

And weather is listed as a separate page, HOWEVER, if you scroll down, weather is actually in the "newer" template way... So very strange...

#

Hmm. And then it says:

Button, image, number, and select template entities are defined in your YAML configuration files under the template: key and cannot be configured via the UI.

However, this is also not true... So, I guess the documentation is out-dated? You CAN create new buttons and numbers via UI...

inner mesa
#

Buttons, at least, are not quite the same

#

In a template button, you provide an action for 'press', while in a button helper you just create the entity and then I guess you need an automation to actually have it do something

#

I rarely use the UI outside of helping folks here, so 🤷

rocky crypt
#

Gotcha. That's how I am as well. I prefer to configure everything in YAML. 🙂

marble jackal
#

A template button is like creating an input button and an automation in one go

#

It actually is a bit of a strange oddling within the template integration as it doesn't require any templates 🙂

rocky crypt
#

Hey there. Question regarding Climate template...

#

On a normal thermostate, you have the options "Heat/Cool", "Heat", "Cool", and "Off"... When creating a template, I only see the option to add "Heat".. Am I missing something?

#

"entity_id for heater switch, must be a toggle device. Becomes air conditioning switch when ac_mode is set to true."... So, can I link AC_Mode to a entity_id to toggle True/False?

inner mesa
rocky crypt
#

This is what I tried...

climate:
  - platform: generic_thermostat
    name: Virtual T-Stat
    heater: switch.tstat_heat_switch
    target_sensor: sensor.virtual_tstat_temp
    ac_mode: >
      {% if states('switch.tstat_cool_switch') -%}
        {{ true }}
      {%- else -%}
        {{ false }}
      {%- endif %}
    min_temp: 50
    max_temp: 100
#

And doesn't like it 😦

#
nvalid config for 'generic_thermostat' from integration 'climate' at configuration.yaml, line 363: invalid boolean value {% if states('switch.tstat_cool_switch') -%}
  {{ true }}
{%- else -%}
  {{ false }}
{%- endif %} for dictionary value 'ac_mode', got "{% if states('switch.tstat_cool_switch') -%}\n  {{ true }}\n{%- else -%}\n  {{ false }}\n{%- endif %}\n"
#

So, looks like it has to be hard coded to "true", but then how do you turn on/off AC?

fickle sand
#

You passing true and false as variables without having a value..

rocky crypt
#

Ok, I hard coded it to true, now it only has cool.. No Heat...

#

It seems you can't have both cool and heat like a normal t-stat... 😦

fickle sand
#

Needs ac_mode to be on when the switch is on?

rocky crypt
#

Yes.

#

But again, there is no way to have the traditional buttons in HA for cool/heat... It's only cool OR heat it looks like...

#

This seems odd to me... Considering my ecobee t-stat has all 4 options/buttons... Auto, Cool, Heat, Power.... But generic looks like you can only have two!

#

Per documentation:

Currently the generic_thermostat climate platform supports ‘heat’, ‘cool’ and ‘off’ HVAC modes. You can force your generic_thermostat to avoid starting by setting HVAC mode to ‘off’.

However, I think they are using the word "and" wrong. Should be "or" 🙂 I can live without the "auto", but I really needed heat and cool...

fickle sand
#

One Generic Thermostat entity can only control one switch. If you need to activate two switches, one for a heater and one for an air conditioner, you will need two Generic Thermostat entities.

rocky crypt
#

Ugh. Wonder why that would be???!!! Hmm....

mighty ledge
#

is ac_mode set?

rocky crypt
#

Yes. I tried setting ac_mode: true... This forced it to be an AC thermostat. No heat mode.

mighty ledge
#

right, it can only be one or the other

rocky crypt
#

That's why I thought ac_mode: should be a template... Not a hard coded true/false... This way it could change automatically from heat to ac...

fickle sand
#

I don't think it is even templateable

mighty ledge
#

nothing is templateable in that

#

generic thermostat serves 1 purpose

#

it's not a template thermostat

#

it controls a switch based on a temperature

#

it's not for a nice UI to merge a bunch of things together

#

if you want that, you have to use the custom integration template climate or whatever it's called

rocky crypt
#

Gotcha... So, I need a template thermostat and that doesn't exist 😦 So, how does the ecobee plug in create it then I wonder?

mighty ledge
#

integrations can create entities

rocky crypt
#

Hmm. I may have found a simple solution, but then the device shows in the UI, but only the title of the device haha 🙂 ... Interesting...
I decided to try:

homeassistant:
  allowlist_external_dirs:
    - /config/automation
  customize:
    climate.virtual_t_stat:
      hvac_modes: off, heat, cool, heat_cool

As these are the exact settings my ecobee has...

#

The device isn't adjustable in the UI... It shows in HomeKit correctly though! HAHA

#

Now the question is, can is customize templateable?

#

Can I use if statements in it for values?

high geyser
#

Hello there, I have a template that returns me a list of sensors. Some of the names of the sensors contains underscore that sends bonkers the markdown parser of telegram. Is there a way to escape (replace _ with \_) the output string of a template?
*The alarm is triggered!* Cause: {{open_sensors}}?

mighty ledge
#

just make a template climate using the custom integration, you're wasting your time otherwise because things won't work. Your virtual climate device will cause issues with your actual device because it's designed to turn on and off the configured switch

rocky crypt
#

I am unfamilure with how to create a custom integration 😦

mighty ledge
#

you've never used HACS before?

rocky crypt
#

No.

mighty ledge
rocky crypt
#

ROFL 🙂

valid kelp
#
if:
  - condition: template
    value_template: '{{zone}} == 2'
then:
  - service: denonavr.get_command
    metadata: {}
    data:
      entity_id: media_player.marantz_sr6012_2
      command: zone2
else:
  - service: media_player.turn_on
    metadata: {}
    data:
      entity_id: media_player.marantz_sr6012
#

I must be missing some really annoying syntactical thing, but I can't seem to get this to evaluate to true

inner mesa
#

'{{zone}} == 2' isn't right

#

where does zone come from?

valid kelp
#

It's a template variable

#
fields:
  zone:
    selector:
      number:
        min: 1
        max: 2
        step: 1
    name: zone
    default: 1
    required: false
inner mesa
#

then you need "{{ zone == 2 }}"

valid kelp
#

that would be the dumb syntax thing

#

so any evaluations must be between the closures?

inner mesa
#

{{ }} outputs, {% %} is logic, {# #} is a comment

#

your == 2 was just hanging out in no man's land

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

rocky crypt
#

Hey there. I am looking for a way to have an automation trigger if a file hasn't been modified in a specific length of time. The data may not change in the file, so using "platform: file" isn't working. Because the data stayed the same, so HA doesn't show that it has been updated even thought the Date Modified of the actual file is updated...

#

Not sure if I need a template or not do this, that's why I'm asking in here instead of in #automations-archived.

lucid thicket
rocky crypt
#

Well, I found this: https://community.home-assistant.io/t/shell-command-sensor-for-last-modified-date-of-files/402567/2, but this gives errors on restart 😦

2024-03-13 13:21:13.041 ERROR (MainThread) [homeassistant.components.sensor] Error while setting up command_line platform for sensor
Traceback (most recent call last):
  File "/usr/src/homeassistant/homeassistant/helpers/entity_platform.py", line 350, in _async_setup_platform
    await asyncio.shield(awaitable)
  File "/usr/src/homeassistant/homeassistant/components/command_line/sensor.py", line 66, in async_setup_platform
    name: str = sensor_config[CONF_NAME]
                ~~~~~~~~~~~~~^^^^^^^^^^^
TypeError: 'NoneType' object is not subscriptable
#

Hmm. I was unaware of that integration. I can try that 🙂 Thank you!

abstract ruin
#

Hey! I am trying to get this time remaining to show as XX:XX. What do i need to change in this return code:
{% if int(rem_h) > 0.9 %} {{ rem_h }} hour(s) and {{ rem_m }} minute(s) {% else %} {{ rem_m }} minute(s) {% endif %}

Full code here:

                {% set rem_m = (as_timestamp(states.sensor.washer_washer_completion_time.state) - as_timestamp(now())) | timestamp_custom('%-M', false) %}
                {% if int(rem_h) > 0.9 %} {{ rem_h }} hour(s) and {{ rem_m }} minute(s)  {% else %} {{ rem_m }} minute(s) {% endif %}```

Its also showing 43 minutes remaining even though the washer is off
inner mesa
#

what is the state of sensor.washer_washer_completion_time?

#

and how does it compare to the current time?

abstract ruin
#

Um it shows a date and time

#

Idk why

#

currently says 2024-03-13T23:50:32+00:00

#

Smart things shows the washer as off

inner mesa
#

is that 43 minutes ago for you?

abstract ruin
#

Maybe. Not really sure when the washer ended

inner mesa
#

doesn't matter

#

is it 43 minutes ago for you?

#

literally that time vs. the clock on your wall 🙂

#

in other words, is the template working and the time there is not what you expect?

abstract ruin
#

Its an hour off since daylight savings

#

so its technically behind

#

Take that back. The time it shows was the time it ended the cycle

#

So yes the time would have been correct but it's not updating the time within the states on dev tools

#

So the entity isn't updating since the washer turns off

#

And it's continuing to count down

silent vector
#

If I have a yaml dictionary in a automation.

foo:
  bar: 'mary'
  eve: ''
  adam: ''

Is it possible without a jinja loop to get the values from the dict and select != '' and print the first one?

sonic sand
#

Template variable warning: 'None' has no attribute 'last_changed' when rendering '{{ states.input_select.switcher_boiler_status.last_changed }}'
also a warning right under that error

mighty ledge
#

xxx.items() | rejectattr('1', 'in', ['']) | first

silent vector
#

This time it's actually home assistant lol

#

Trying to setup an automation to control a humidifier/dehumidifier and break the logic up using yaml dicts to keep it clean vs a big jinja variable

#

Hm the automation doesn't like rendering that. I don't think it likes items()

action_calculation:
  humidifier: ''
  dehumidifier: turn_on_dehumidifier
  emergency_stop: ''

This is the variable I'm trying to get what isn't '' from

mighty ledge
#

if .items() doesn't work, it's not a dictionary

#

works for me

silent vector
#

Hm but it's a yaml dict does that matter?

mighty ledge
#

wtf is a yaml dict

#

a dict is a dict

#

you can't use yaml in jinja if that's what you're asking... post your full code

marble jackal
sonic sand
plain magnetBOT
#

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

silent vector
#

Oops

mighty ledge
#

ok in a separate variable all you need to do is use the template

#
{{ action_calculation.items() | rejectattr('1', 'in', ['']) | first }}
silent vector
#

Yeah I did and I'm getting

Error rendering variables: ValueError: too many values to unpack (expected 2)
Error rendering variables: ValueError: not enough values to unpack (expected 2, got 0)
#

Which is weird

mighty ledge
#

you're doing something wrong, I do this all the time

#

post the full template, not your abbreviated stuff.

silent vector
mighty ledge
#

and when you run the automation?

silent vector
#

Oh I have a different error downstream from the var lol. It's confusing sometimes how automation errors show in the logs. I'm getting a split error somewhere else. Let me fix that.

abstract ruin
#

@mighty ledge I know you wanted me to post everything so here it is. I tagged you to make it easier to find later:)

Currently I am trying to fix the issue by creating a sensors.yaml with he following code:

  - sensor:
    - name: 'Washer Remaining Time'
      state: >-
        {% set rem_h = (as_timestamp(states.sensor.washer_completion_time.state) - as_timestamp(now())) | timestamp_custom('%-H', false) %}
        {% set rem_m = (as_timestamp(states.sensor.washer_completion_time.state) - as_timestamp(now())) | timestamp_custom('%-M', false) %}
        {% if int(rem_h) > 0.9 %} {{ rem_h }}hr {{ rem_m }}m  {% else %} {{ rem_m }}m {% endif %}
    - name: 'Dryer Remaining Time'
      state: >-
        {% set rem_h = (as_timestamp(states.sensor.dryer_completion_time.state) - as_timestamp(now())) | timestamp_custom('%-H', false) %}
        {% set rem_m = (as_timestamp(states.sensor.dryer_completion_time.state) - as_timestamp(now())) | timestamp_custom('%-M', false) %}
        {% if int(rem_h) > 0.9 %} {{ rem_h }}hr {{ rem_m }}m  {% else %} {{ rem_m }}m {% endif %}```

It doesn't seem to work within the config.yaml or if I create a seperate sensor.yaml file
#

The current format of sensor.washer_washer_completion_time is 2024-03-14T17:25:01+00:00.

lofty mason
#

If you were complaining about minutes being 1 instead of 01, then you should remove the minus here: (%-M)

#

%M is zero padded, %-M is not

fickle sand
# abstract ruin <@372843932096397333> I know you wanted me to post everything so here it is. I t...

This is actually very helpful information to be noticed by others that can answer your question 🎉
I am sure petro or others can help you with it.

I will mention some small things now, because I have to leave in a minute.

This is part of the template integration and should not be posted directly under sensors or in sensor.yaml, that will not work unfortunately.

If you want written style relative time you can check the easy_time or relative-time-plus macro's

mighty ledge
abstract ruin
marble jackal
#

What exactly does doesn't work mean

#

Discord cache strikes again

mighty ledge
# abstract ruin <@372843932096397333> I know you wanted me to post everything so here it is. I t...
template:
  - sensor:
    - name: 'Washer Remaining Time'
      availability: >
        {% set end = states('sensor.washer_completion_time') | as_datetime %}
        {{ end and end > now() }}
      state: >
        {% set end = states('sensor.washer_completion_time') | as_datetime | as_local %}
        {% set current = now().replace(microsecond=0) %}
        {% set sec = (end - current).seconds %}
        {% set h = sec // 3600 %}
        {% set m = (sec // 60) % 60 %}
        {{ h ~ 'hr ' ~ m ~ 'm' if h else m ~ 'm' }}
#

sorry got pulled away again

#

anyways, that will be unavailable when the end time is older than the current time

#

if you wanted a real duration sensor, I can also provide that. But it will be HH:MM:SS format

#

but the template would be easier to understand

#

which is...

abstract ruin
marble jackal
#

I don't think you need to remove the microseconds, .seconds already returns an integer

mighty ledge
#

I do it always for timedeltas if you plan to output the result

#

just a habbit at this point

#
template:
  - sensor:
    - name: 'Washer Remaining Time'
      availability: >
        {% set end = states('sensor.washer_completion_time') | as_datetime %}
        {{ end and end > now() }}
      device_class: duration
      unit_of_measurement: s
      state: >
        {% set end = states('sensor.washer_completion_time') | as_datetime | as_local %}
        {% set current = now().replace(microsecond=0) %}
        {{ (end - current).total_seconds() }}
#

anyways, that will also be graphable (history) and it will show up as HH:MM:SS in the UI wherever you put it

abstract ruin
#

Once I get back to my PC I will test this. Thank you so much

floral shuttle
#

based on a timestamp sensor for my next-alarm, what is the cleanest way to create a binary for alarm on for tomorrow? thing is, the timestamp sensor returns 0 if no alarm is set, and then the .day returns funny things...

#

so now I re-enter another binary {% set next = states('sensor.next_alarm_timestamp')|as_datetime() %} {% set gezet = is_state('binary_sensor.wekker_gezet','on') %} {{gezet and (now()+timedelta(days=1)).day == next.day}}

#

that check for 2 booleans {{is_state('input_boolean.alarmclock_wd_enabled','on') or is_state('input_boolean.alarmclock_we_enabled','on')}}

#

if that is on, it is safe to test for the .day equality

#

otherwise it would do this...

marble jackal
#
{% set next = states('sensor.next_alarm_timestamp') | as_datetime %}
{{ next is datetime and (next.date() - now().date()).days == 1 }}
floral shuttle
#

that returns a typeerror

marble jackal
#

Sorry, accidentally added parenthesis after next. Fixed

floral shuttle
#

yes, that works!

#

now I need t understand why 😉

#

is that first test still essential? this wrks too {% set next = states('sensor.next_alarm_timestamp') | as_datetime %} {{ (next.date() - now().date()).days == 1 }} and next will always be a datetime?

#

just tested that in all conditions (booleans on/on, on/off, off/on, off/off) ...

marble jackal
#

next.date() will not work when you don't have an alarm set

floral shuttle
#

the template then returns False, which is correct, but not because next is datetime would fail. that always returns true, also when no alarm is set

marble jackal
#

next is datetime will return false when the state of the sensor is not a datetime string

#

Eg when it is unavailable

floral shuttle
marble jackal
#

Because the as_datetime filter will return none

floral shuttle
#

need to check if my base sensor timestamp itself isnt doing that already... but it wont harm to be safe

#

much cleaner anyway, thx!

marble jackal
#

You could also add now() as default for the datetime filter

floral shuttle
#

Even nicer… was just about to paste the timestamp sensor when my keyboard on the Mac started acting up

#

Weird, can’t type anymore at all on the device

#

This helps a lot!

abstract ruin
mighty ledge
bronze prawn
#
  - name: Assist_Last_Called
    state: "{% set sensor_states = namespace(last_sensor='', last_changed=None) %}{% for entity_id in ['sensor.thinksmart_lr_stt','sensor.firehd_7_stt' ] %}   
    {% set state_obj = states[entity_id] %}   
    {% if state_obj.state == 'start' and (sensor_states.last_changed is none or state_obj.last_changed > sensor_states.last_changed %}     
            {% set sensor_states.last_sensor = entity_id %}     
            {% set sensor_states.last_changed = state_obj.last_changed %}   
    {% endif %} 
{% endfor %} 
{{ sensor_states.last_sensor if sensor_states.last_sensor else 'None' }}"
#

Can someone tell me how to format this correctly? Do I need to do
state:| or something to get a multiline valid yaml?

#

I guess I could string it all together but that is maybe more of a mess than this.

abstract ruin
bronze prawn
#
  - name: Assist_Last_Called
    state: >
      "{% set sensor_states = namespace(last_sensor='', last_changed=None) %}
        {% for entity_id in ['sensor.thinksmart_lr_stt','sensor.firehd_7_stt' ] %}   
          {% set state_obj = states[entity_id] %}   
            {% if state_obj.state == 'start' and (sensor_states.last_changed is none or state_obj.last_changed > sensor_states.last_changed %}     
              {% set sensor_states.last_sensor = entity_id %}     
              {% set sensor_states.last_changed = state_obj.last_changed %}   
            {% endif %} 
        {% endfor %} 
      {{ sensor_states.last_sensor if sensor_states.last_sensor else 'None' }}"
#

Second attempt. Still not working

dreamy sinew
#

2 timer entities?

inner mesa
#

Remove the surrounding quotes

dreamy sinew
#

oh

#
{% set sensors = expand(['sensor.thinksmart_lr_stt','sensor.firehd_7_stt' ])|selectattr('state', 'eq', 'start') %}
#

could probably do more with stuff like that

bronze prawn
bronze prawn
# dreamy sinew oh

Truth be told I'm going by an example I was provided but I will look at what you provided for sure. Thank you

dreamy sinew
#

that'll give you a list of those things that have that status

#

and its already in object form

#

i'm kinda anal about avoiding loops when i can though

#

if it works, it works

bronze prawn
#

Hmm. So I removed the quotes and I'm still not seeing the new entity. Am I doing something else wrong?

dreamy sinew
#

you can't string compare a date to none

bronze prawn
#

hmm. Okay. Please bear with me. This works fine in dev tools template and just trying to figure out how to make it a sensor so I can determine which assist device last called for some custom stuff I'm doing.

dreamy sinew
#
{{ sensor.entity_id if sensor else 'None' }}```
#

something like that might work

#

might need to drop the |first

bronze prawn
#

Getting a No aggregated item, sequence was empty. when trying

#

with or without |first

dreamy sinew
#

they're all getting rejected

#

do this to test

#
{{ sensor }}```
bronze prawn
dreamy sinew
#

rejectattr

#

my bad

bronze prawn
#

🙂

dreamy sinew
#

too much regex for me

bronze prawn
dreamy sinew
#

add a |list

#

to either

bronze prawn
#

Empty list then when I call it I get:

[<template TemplateState(<state sensor.thinksmart_lr_stt=start; engine=stt.home_assistant_cloud, metadata=language=en-US, format=AudioFormats.WAV, codec=AudioCodecs.PCM, bit_rate=AudioBitRates.BITRATE_16, sample_rate=AudioSampleRates.SAMPLERATE_16000, channel=AudioChannels.CHANNEL_MONO, icon=mdi:numeric-2, friendly_name=ThinkSmart-LR STT @ 2024-03-14T18:17:25.613942-05:00>)>]
dreamy sinew
#

ok, there's only one object there

bronze prawn
#

And that's what I was hoping for

dreamy sinew
#

but its not doing the last changed bit yet

#

i have to run, but i have another idea

bronze prawn
#

Understood and thanks for the help. Please share your idea when you have time.

dreamy sinew
#
{{ sensors|max(attribute="last_changed")|attr('entity_id') if sensors|list|length > 1 else 'None'}}
#

i think that'll do it

#

@bronze prawn

#

couple of ninja edits

bronze prawn
#
TemplateSyntaxError: Encountered unknown tag 'sensor'. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.

#

That's with the edits.

dreamy sinew
#

oh oops

#

another edit

bronze prawn
dreamy sinew
#

further edits

#

could condense it further but it starts getting harder to follow

bronze prawn
#

sorry man

dreamy sinew
#

lol more condensed with a fix

bronze prawn
#

There's a lot going on in there

dreamy sinew
#

changed again

#

oops, one more change

#

it doesn't like those previous forms of pulling an attribute because of how its pulling things

bronze prawn
#

Good news bad news. Good news: It shows 'None' with no errors. Bad news, it never changes but the other code I was using before does (your example) change so this one is just not noticing the change

dreamy sinew
#

i'm a little rusty

#

oh, length >=1

#

got lost in edits

bronze prawn
#

So it picked it up this time and threw that error

#

result type: string

dreamy sinew
#

change |attribute() to |attr()

bronze prawn
dreamy sinew
#

weird

bronze prawn
#

At some point I'm going to be back to the same question as to how to add this into the template sensor.

dreamy sinew
#
```it looks like this?
bronze prawn
#
{% set sensors = expand(['sensor.thinksmart_lr_stt','sensor.firehd_7_stt'])|selectattr('state', 'eq', 'start')|rejectattr('last_changed', 'eq', None) %}
{{ sensors|max(attribute="last_changed")|attr('entity_id')
dreamy sinew
#

it shouldn't be throwing that because if the list is empty it wouldn't get there

#

unless you dropped the if check

bronze prawn
#

Alright. So maybe I got things goofy in the copy/paste but this is what I have based on me piecing everything together:

{% set sensors = expand(['sensor.thinksmart_lr_stt','sensor.firehd_7_stt'])|selectattr('state', 'eq', 'start')|rejectattr('last_changed', 'eq', None) %}
{{ sensors|max(attribute="last_changed")|attr('entity_id') if sensors|list|length > 1 else 'None'}}

This is back to not changing from None

dreamy sinew
#

you dropped the >=

bronze prawn
#

No aggregated item, sequence was empty.

Alright. I don't want to try your patience. I added the >= back in and that's what I'm getting when calling the mic

dreamy sinew
#

so weird

#

because this works:

{{ foo|max if foo|list|length >=1 else "bar" }}```
#

-> bar

#

oh

#

figured it out

#
{{ sensors|max(attribute="last_changed")|attr('entity_id') if sensors|length >= 1 else 'None'}}```
#

had to put the |list earlier

bronze prawn
#

Bingo!

dreamy sinew
#

putting it all together:

    state: >-
      {%- set sensors = expand(['sensor.thinksmart_lr_stt','sensor.firehd_7_stt'])|selectattr('state', 'eq', 'start')|rejectattr('last_changed', 'eq', None)|list -%}
      {{ sensors|max(attribute="last_changed")|attr('entity_id') if sensors|length >= 1 else 'None'}}```
bronze prawn
#

Giving it a shot now

#

That did it. Thanks so much. This is one of the missing pieces I need to do more with my Echo Show replacement project.

dreamy sinew
#

haha good luck!

modern sluice
#

Hi,
can somebody help me fix/finish my simple template? I receive an error (TypeError: '>' not supported between instances of 'NoneType' and 'datetime.datetime') in HA: {{ state_attr('serge_s_apple_watch', 'away') > now() - timedelta(minutes=30) }}

I'm just trying to conditionalize if the watch has been away for more than 30 mins

inner mesa
#

Seems like there's no such attribute

haughty breach
#

Your entity is missing it's domain... it should likely be sensor.serge_s_apple_watch but you haven't provided enough information.

bronze prawn
#

Hey @dreamy sinew Is there a way to modify the template so that it keeps the value of the last called mic and only change it when a new mic makes a call? Right now it will only show the value when 'ok nabu' is said but as soon as you say anything else like 'turn on the living room light' the value goes back to 'None' which doesn't provide much. Apologies.

dreamy sinew
#

hmm, that's a lot harder

#

might need a 2nd entity

#

maybe an input text and an automation to set it when the sensor.Assist_Last_Called is updated but not when its none

bronze prawn
#

Gotcha. Will check that out later. Running on fumes right now.

modern sluice
haughty breach
#

As Rob stated above, away is not a common attribute, so that is the next most likely source of your issue. Can you clarify where you are trying to use this template? For example, are you trying to trigger an automation when the watch is away for >30 minutes or are you setting up a Template sensor....?

floral shuttle
silent vector
# mighty ledge

Finally got this automation working and this code does work. How would I get it to just show the value other than using a list index? In your example it would show just turn_on_dehumidifier and not the key 'dehumidifier' as well.

mighty ledge
#

Map the second value

silent vector
#

How would I do that?

#

What does 1 do in rejectattr?

marble jackal
#

1 refers to the value, 0 would be the key

silent vector
#

Ah that's what I thought.

primal ridge
#

Hi, trying to retain my attributes over a restart. Understood that a trigger based sensor will keep it, so I am copying it. But it turns the array to a string, and I am stuck. Anyone with some tip on how to move along. (it is nordpool data).

#

`template:

  • trigger:
    • platform: time
      at: "11:17:00"
      sensor:
    • name: nordpool_idag_recal_ts3
      state: 0
      attributes:
      raw_today: "{{ state_attr('sensor.nordpool_recalculate_new6', 'raw_today') }}"`
marble jackal
#

how do you see that it is a string?

#

becasue this should work

primal ridge
#

I can not pull a specific position in the array

#

Looks identical, but is treated as a string

#

[{'start': datetime.datetime(2024, 3, 15, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'end': datetime.datetime(2024, 3, 15, 1, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'value': 1.285}, {'start': datetime.datetime(2024, 3, 15, 1, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'end': datetime.datetime(2024, 3, 15, 2, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'value': 1.285}, {'start': datetime.datetime(2024, 3, 15, 2, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'end': datetime.datetime(2024, 3, 15, 3, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'value': 1.285}, {'start': datetime.datetime(2024, 3, 15, 3, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'end': datetime.datetime(2024, 3, 15, 4, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'value': 1.285}, {'start': datetime.datetime(2024, 3, 15, 4, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'end': datetime.datetime(2024, 3, 15, 5, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'value': 1.285}, {'start': datetime.datetime(2024, 3, 15, 5, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'end': datetime.datetime(2024, 3, 15, 6, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'value': 1.285}, {'start': datetime.datetime(2024, 3, 15, 6, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'end': datetime.datetime(2024, 3, 15, 7, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Oslo')), 'value': 1.418}]

mighty ledge
#

you need to convert each datetime into a string in order for it to treat it as a list, this will also affect the code and the behavior of whats displaying the information

#

What do these values represent and what are you trying to do with them?

primal ridge
#

It is energy prices for each hour

mighty ledge
#

and what are you doing with those prices?

primal ridge
#

I collect them from the nordpool intergration, do a python script for calculation of additional costs

#

Then i am using it for energy usage optimization

mighty ledge
#

e.g. which hours to turn things on when it's the cheapest?

primal ridge
#

Yes

mighty ledge
#

ok, well I have a few recommendations then.

primal ridge
#

Works well, untill i do a restart before next days prices are available

mighty ledge
primal ridge
#

I could compensate in other ways, just forllowin this track for now

mighty ledge
#
  1. Continue using whatever you derrived, but do the same thing. Run the calculation when you get the data, only store the result in a trigger template sensor.
primal ridge
#

tried alternative 2. it does not retain the data written from the python script over a restart...

mighty ledge
#

don't use the python script to set a state

#

use it to do the calculation

#

then have a trigger based template entity store the value

#

i.e. fire an event from your python script that has the data, then use a trigger based template enttiy that triggers off the event and uses the data

#

or just use thefes's macro in a trigger based template entity.

primal ridge
#

Thanks for your time and help. I will certainy take a look at TheFes and also see if I can change somethng in my logic. The fun of HA this 🙂

mighty ledge
#

then your trigger

#
trigger:
- platform: event
  event_type: hello_world_event
#

accessing data in templates

#
trigger.event.data
marble jackal
#

why do you need yesterday's data?

#

it would be nice if the Nordpool or Entso-e integrations would add the response service calls. That would make it easier to create a sensor with all the data you need, including yesterday's data

primal ridge
#

I am doing a period from 18-07

marble jackal
#

okay, you can use a trigger based template sensor at eg 17:00 to determine the best time in that period

#

as it is trigger based template sensor it will not change until 17:00 the next day

primal ridge
#

I am doing graphs and price limits, all works but with a restart I loose proper function till Norpool updates around 13:30...

marble jackal
#

well, if you're interested in 18:00 - 07:00 you're data loss will be at midnight

primal ridge
#

You are right I will be able to compensate for this and be as good as before my latest journey to make things harder for myself

lethal bison
#

I'm struggling trying to return the name of an attribute that matches a value.
Entity: [<template TemplateState(<state plant.pothos_golden=problem; species=Epipremnum aureum 'Golden Pothos', moisture_status=ok, temperature_status=ok, conductivity_status=Low, illuminance_status=ok, humidity_status=None, dli_status=ok, species_original=epipremnum aureum 'golden pothos', device_class=plant, friendly_name=Pothos Golden @ 2024-03-15T11:53:42.565631-05:00>)>]

In this case, I would like to return the attribute name "conductivity_status". This should work, but I guess the plant domain doesnt have the same attributes as the sensor domain.

{% for key, value in a.items() if value.text == "Low" %}
{{ key }}
{% endfor %}```
mighty ledge
#

On mobile but

#

if key == 'conductivity_status'

#

Or if you want to find low, if value == 'Low'

lethal bison
#

any one of those keys can be "Low", I'm trying to return the name of whatever status low

#

ahh

#

I guess there's no .text suffix

mighty ledge
#

No, it’s not suffix

lethal bison
#

I'm having a hard time coming up with the actual word for it, you're right

mighty ledge
#

What you’re asking there is to get the text key from value but value isn’t a dictionary

lethal bison
#

that was it, if value == "Low". I can't believe it was that simple

mighty ledge
#

Over thinking it 😉

lethal bison
#

Now to figure out how to use multiple keys
if value in ["Low", "High"] ?

mighty ledge
#

in

#

Not ==

lethal bison
#

sweet, again simple

rancid copper
#

Hi Guys, i would like to create a setup panel for the lights, I'll explain better with an example, I have 10 lights, I would like to create booleans to use in an automation that only turns on the lights that are "on" in the booleans, this is something that can be done for you? I don't want to create groups but a real control panel where I decide which individual lights to turn on.

lethal bison
#

What's the difference between.. (I know the example's malformed, just assume I got it right)
states.plant.pothos_golden.attributes
and
states('plant.pothos_golden').attributes ?

marble jackal
#

The first one will give you all the attributes from the state object, the second will give you an error

fickle sand
lethal bison
#

I"m trying to utilize a variable + concat to turn

variables:
  triggering_entity: "{{ trigger.entity_id }}"```
into 
```sensor: >
    {% for key, value in 'states.'~triggering_entity~'.items()' if value in ["Low", "High"] %} {{
    key.split('_')[0] }} {% endfor %}```
#

I have a working example in a different automation, but that automation is only outputting a string, it's not trying to use the concatted string as an entity

marble jackal
#

states[triggering_entity].attributes.items()

lethal bison
#

with square braces specifically?

marble jackal
#

Yes

haughty breach
rancid copper
#

in fact I would like to leave myself the possibility of adding new lights..

#

what do you mean with "consistent naming convention for all the input booleans and lights involved"

#

call input boolean and lights the same way?

haughty breach
#

If you're going to add entities, you would be better served putting them in a group. That would reduce the places you have to edit... especially if you use a card like Auto Entities or one that accepts templates. HAving the names the same is easiest, but the names do not need to be the same as long as the way they are different follows a pattern.

lethal bison
#

looking for an example for templating an action..

{% for key, value in states[plantid.entity_id].attributes.items() if value 
in ["Low", "High"] %}{% if loop.first %}{{plantid.attributes.friendly_name}} needs: {%endif%}
{{ key.split('_')[0] }}{% endfor %}
{% endfor %}```
does pretty much what I want.  

Pothos Manjula needs: conductivity
Pothos Marble needs: moisture
Pothos Golden needs: conductivity

Basically for every plant returned by the above, I want to run the action 
```yaml
action:
  - service: notify.wife
    data:
      title: I'm dying! :warning::radioactive::skull_crossbones:
      message: >
        {{state_attr(plantid.entity_id,"friendly_name") }} :herb: needs: {{
        sensor }}
inner mesa
#

templating the action isn't the way to do that

lethal bison
#

sorry, power went out

#

I'm mainly interested in a dynamic action that applies to all plant entities, even ones added later will just automagically be included

inner mesa
#

right, see the link

lethal bison
#

so you're suggesting the automation call a script, and the script handle the template actions

inner mesa
#

you can do that right in the automation action

#

the action of an automation is a script

lethal bison
#

this is similar to what I've already tried:

action:
  - repeat:
      for_each: "{{ plant_list }}"
      sequence: []
variables:
  plant_list: "{{states.plant|map(attribute="entity_id")|list}}"

fails when saving, with error `template value should be string for dictionary value @data['action'][1]

#

aha

inner mesa
#

You're not actually doing anything in the sequence, but I don't think that's invalid, just useless

lethal bison
#

agreed, I"m just trying to verify syntax before adding the sequence

inner mesa
#

understood

lethal bison
#

It's a trick I've learned from years of being an idiot. Don't change too much, you may not know what you did that broke it

inner mesa
#

I'm not sure that you can just stick the variables section out there like that

#

maybe you can, but I can't find the documentation to support it

#

oh, you're using the same quotes inside and out

#

at least that, maybe other stuff, too

lethal bison
#

quotes, that was it

inner mesa
#

this script validates and works fine for me:

repeat_test:
  sequence:
    - variables:
        plant_list: "{{states.alarm_control_panel|map(attribute='entity_id')|list}}"
    - repeat:
        for_each: "{{ plant_list }}"
        sequence:
          - service: persistent_notification.create
            data:
              message: "{{ repeat.item }}"
lethal bison
#

good news is I may have figured a way to handle an individual run immediatly on state change as well as an aggregate reminder of all problem sensors with a single for loop

inner mesa
#

ok

#

VSCode just immediately freaks out with quotes like that, so it's quite obvious

distant abyss
#

are you using plants.yaml ? or have them all separate?

torpid elm
#

Hey all, I'm having trouble creating a binary_sensor using a motion sensor that updates a "time" value whenever it's triggered. I'm using some old sensors via rtl_433 and the time value is the only thing that updates in MQTT when triggered.

torpid elm
haughty galleon
#

Can I tell you what I did wrong?

#

],
"received_at": "2024-03-16T05:46:16.004320157Z",
"uplink_message": {
"session_key_id": "AY5DIq6NZbVG/u2dR1N4mQ==",
"f_port": 2,
"f_cnt": 164,
"frm_payload": "AAAAAAAAAAAAAAAAnu93QBSuq0HS3HpEAJltQg==",
"decoded_payload": {
"batteryVoltage": 3.874000072479248,
"humidity2": 59.3994140625,
"pressure2": 1003.4503173828125,
"temperature2": 21.459999084472656
},

#

mqtt:
sensor:
- name: Balcon-Sensor-Temp5
state_topic: "v3/my-sensor01@ttn/devices/eui-70b3d57ed0065ebe/up"
unit_of_measurement: "°C"
value_template: "{{ value_json [uplink_message.decoded_payload].temperature2'}}"

#

I think it depends value_template: "{{ value_json [uplink_message.decoded_payload].temperature2'}}"

#

I also tried it like in this video

haughty galleon
#

That doesn't work either

plain magnetBOT
#

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

lucid thicket
marble jackal
#

The square brackets are especially useful when you want to use a variable

{% set var = 'key1' %}
{{ value_json[var] }}
lucid thicket
#

The mqtt sensor yaml code you shared looks correct, but it’s not possible to tell for sure without the entire json string. Are you sure uplink_message is the first level of the json object (and also not a member of a list)? Share the JSON on dpaste.org

haughty galleon
#

I can't upload

#

was that right

plain magnetBOT
#

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

haughty galleon
#

now I get an output

spark vortex
#

how can I create a template that contains all the friendly names for a list of entities where state is "on"?

#

my problem is that the entities are not of same type, but they are binary_sensors, sensors, switch

slate fossil
#

@spark vortex This might work for you. Included a couple of examples on how to exclude some entities. yaml {{ states | selectattr ('domain', 'in', ['light','binary_sensor','switch']) | rejectattr ('entity_id', 'in', integration_entities('group')) | rejectattr ('entity_id', 'eq', 'light.all_lights_on') | rejectattr ('entity_id', 'search', '_screen') | sort(attribute = 'entity_id') | map(attribute = 'name' ) | list }}

spark vortex
#

but I don't want to check all entities in these domains, but just some of them

#

excluding is hard, can I just include what I need?

#

I mean, I have more than 100 entities, I just need to check less than 10, so it is easy to add than exclude

#

I created an old stype group, becase I can add different type of entities in the same group and then used this "{{ expand('group.elettro_on') | selectattr('state', 'eq', 'on')| map(attribute='name') | list | join(', ') }}"

#

I am not happy to use the old style group, but I guess there is nothing better to use

slate fossil
#

Are you wanting to hard-code the list of entities into the template?

spark vortex
#

I'd prefer to not hard-code it, that is why I am using the group that is easier to add/remove entities

slate fossil
#

What about the group don't you like because that seems to work pretty well using the code you provided?

spark vortex
#

it works, I am just usign old style group, is it still ok or it will be removed soon?

marble jackal
#

You can do the same with a GUI created binary sensor group

spark vortex
#

with helpers?

marble jackal
#

Yes

spark vortex
#

it supports different type of entities in the same group?

#

it seems not

#

group: elettro_on: name: elettro on entities: - binary_sensor.caffe_state - switch.tv_letto_switch - switch.tv_cucina_switch - switch.tv_salone_switch - switch.tv_gabry_switch - binary_sensor.piano_cottura_state - binary_sensor.thermostat_state - sensor.ac_cucina_state - sensor.ac_salone_state - sensor.ac_camera_da_letto_state
this is my group, if I can do the same with not old stype syntax, I would be happy 🙂

cosmic hamlet
#

{{ state_attr('calendar.persoonlijk', 'start_time') }} gives null if calender is not set but it gives true if check is defined.

#

How can i make a check that does not break my state_attr('calendar.persoonlijk', 'start_time') code

marble jackal
marble jackal
strong oriole
#

this doesnt seem to work like i expect it to work, it stops at midnight, am i reading the documentation wrong or is this a bug?

- platform: history_stats name: in bed entity_id: binary_sensor.test_still_target state: "on" type: time start: "{{ today_at('20:30') }}" duration: hours: 17

slate fossil
#

@spark vortex TheFes I wonder if you could use something like this: ```yaml
elettro_on:
name: elettro on
entities:
- binary_sensor.binary_sensor_entities_group_from_UI
- switch.switch_entities_group_from_UI
- sensor.sensor_entities_group_from_UI

marble jackal
#

That should work

#

I think

spark vortex
marble jackal
inner mesa
#

Turtles all the way down

sonic sand
grand walrus
#

Hello.. I need some help on a sensor, which is supposed to calculate the weighted average of the several marks from school.. the retrieve or the marks is working, but it seems that total_notes and total_coefficients are reset at each loop when they shall sum up at each loop..
Any clue on what is wrong in my code?
Here is is:
https://dpaste.org/4A3cQ

inner mesa
#

yes, you need to use a namespace for variables changed inside the loop to be reflected out side it

marble jackal
grand walrus
lethal bison
spiral grove
#

What am I doing wrong here? Any and all help appreciated.

"{{ int([states.light.nursery_1,
states.light.nursery_2,
states.light.nursery_3,
states.light.nursery_4]
| selectattr('state', 'eq', 'on')
| list | count) == 1
}}""

#

seems to work as expected in dev tester, but always evaluates false when entered in config

fossil venture
#

What does this have to do with templates?

spring mesa
daring swan
#

I need a pointer because I cant seem to get my head around jitsi2. I want to iterate over elements of a calendar. I'm in the developer tools and tried {% for calevent in calendar.xxxxx %} but it complains that calendar is undefined. How do I refer to the calendar I want to access?

#

I am missing something obvious, that much is certain. Somehow, I cannot use calendar. inside the developer tools despite it being suggested to me when I type calendar. (it opens a dialog with suggestions including the calendar I'm looking for).

bronze prawn
#

I'm still working on my project. I'm wondering if I can create a group with my custom sensors and somehow use a template that searches the members in the group for one of them that has state of 'assisting' . Is that something easy to do with templates?

plain magnetBOT
#

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

marble jackal
merry furnace
#

No I'm using it in an automation yaml file

#

I'd past the whole part in, but I think I remember that pasting too much code in the discord here is frowned upon 😉

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
#

Use one of those

#

You could also create a light group out of the 4 lights and check if the group is on

#

BTW, I now noticed you were responding to my reply to someone else

merry furnace
#

https://dpaste.org/6eiZT
This is the heating automation part I created to increase / decrease an integer, so later I can use that integer to turn pumps and heating on or off.

marble jackal
#

I'm not sure I understand what you are trying to achieve. You have several climate entities. But what are you trying to achieve by comparing them with each other?

merry furnace
#

The comparison is between the temperature sensor of them and the thermostat setting. Based on that I now if that device would like to get heat.

#

I then want to increase the value of the number higher if heat is needed and lower based on devices that do not need heat. I should however push the number higher with the total number of thermostats and decrease only by one.

#

The way I have written this now however looks like it should be done differently and more efficiently probably.

marble jackal
#

Why do you have these numbers in your entity_id's?

merry furnace
#

The are coming from fibaro

sonic sand
marble jackal
#

Yes, you should use it in the history stats sensor

daring swan
#

Ok so by all I now understand,

{% for event in calendar.xxx %}

should actually work. Just how can I prevent the dev tools from telling me that calendar is undefined? It does the same for sensor and any other element type I can think of.

#

it seems I can access something with {{ states("calendar.xxx") }} but that only reutrns off, I still fail to find the structure of a calendar object

marble jackal
#

Only the current or next calendar event is shown in the entity itself

#

For all events in a certain period you need to use the list_events service call

daring swan
#

my point is it already fails at calendar

#

I don't understand how to retrieve a list of entries, like with which syntax.

marble jackal
#

states.calendar will give you the state objects of all calendars

ripe steeple
#

Hey guys,

Can someone tell me why my template (which is working) still throws
errors in logs that my power_sum variable is undefined

all inputs to my variable power_sum should default to 0 on any error if I understand float(0)

https://dpaste.org/8BUsf#L12
"Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined"

sonic sand
marble jackal
#

That's not what history stats will do

#

4:50:16 is the time (UTC) it was last changed

#

Not the time since the last change

plain magnetBOT
#

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

marble jackal
#

Try:
if states(entity) | bool(false)
or
if is_state(entity, 'on')

#

States are strings, and Jinja will use both "on" and "off" as True

sonic sand
quasi frost
#

Good morning, i use a window sensor to check the status of a lock. But the displayed status is wrong. If the lock ich locked, it shows me open, because the windows sensor is at this moment not active. But at this moment the status should be locked. How can i invert the displayed status?

clear mist
quasi frost
#

i tried to add a template sensor to my configuration.yaml

  - platform: template
    sensors:
      garage_tor_schloss_invertiert:
        value_template: "{{ is_state('binary_sensor.garage_sensor_tor_schloss_contact', 'off') }}"
        friendly_name: 'Garage Tor Schloss Invert'
#

but when i try to add device_class: lock, i got a error message during checking the configuration.yaml

fickle sand
#

device_class: lock is not available for the sensor domain

quasi frost
#

ah got it, so how can i change the template sensor to a binary sensor?

fickle sand
#
  binary_sensor:
    - platform: template
      sensors:
        garage_tor_schloss_invertiert:
          value_template: "{{ is_state('binary_sensor.garage_sensor_tor_schloss_contact', 'off') }}"
          friendly_name: 'Garage Tor Schloss Invert'

If you put it directly in configuration.yaml else you can add what you have into binary_sensor.yaml

#

Or create it in the GUI and it will be build in the (new) format

quasi frost
#

then i recive: Invalid config for 'sensor' at configuration.yaml, line 166: required key 'platform' not provided

fickle sand
#

The hyphen(-) before binary_sensor is not needed

sonic sand
#
- platform: history_stats
  name: Boiler On
  entity_id: input_select.switcher_boiler_status
  state: "On"
  type: time
  start: "{{ states.input_select.switcher_boiler_status.last_changed | default(now(), true) }}"
  end: "{{ now() }}"

Using this sensor on the 'Current' part of this card:
http://pastie.org/p/1wgurLyTU1CPJe4pawEHam
What should I modify to show time preferred by the number of minutes and not the number of hours since the state changed to On, I have read the documentation a few times but I'm stuck.

quasi frost
#

then i got errors, it should be placed at the right position in the cinf...yaml

#

figured the right position out, its working now 🙂 Thank youuuu!

marble jackal
sonic sand
marble jackal
#

yes

quasi frost
#

How can i change the colour of a state depending of the staus?

sonic sand
# marble jackal yes

Thanks, managed to change it to minutes now.
Why do I have to add unique_id to be able to access those settings? and what do I need to do with the start line to let it show the minutes its state is On and not the timestamp?

fickle sand
marble jackal
#

only entities with a unique_id can be changed in the GUI settings

#

and you don't need to do anything with the start line to do that, the state of this history stats sensor will be the numer of minutes it's On

sonic sand
#

I also changed the entity settings to Display Precision to 0 (so it won't show big numbers like those and just the minute)

marble jackal
#

because there is a minor difference between the start and end now()

fickle sand
#

Display precision is only applied in the frontend, not in the dev-tools/states tab

marble jackal
#
- platform: history_stats
  name: Boiler On
  unique_id: dc81f153-e9fc-4521-823c-24dcd23b968e
  entity_id: input_select.switcher_boiler_status
  state: "On"
  type: time
  start: "{{ states.input_select.switcher_boiler_status.last_changed | default(now().replace(microsecond=0), true) }}"
  end: "{{ now().replace(microsecond=0) }}"
#

this will probably resolve that

sonic sand
marble jackal
#

what kind of card is that, unless you use a template to show it, it should use the set precision in the entity

sonic sand
marble jackal
#

It should do that with the version I pasted above

plain magnetBOT
#

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

fickle sand
sonic sand
fickle sand
#

That should support it

marble jackal
#

no, he uses a template

#

use this to use the precision set:

secondary: Current: {{states("sensor.boiler_power", with_unit=true) }}
#

it will also automatically use the unit of measurement

sonic sand
#

so should I remove the change you've done to the start&end few minutes ago or keep it?

fickle sand
#

Oh right, it depends on the template states() extracts the raw state right, unless the variable rounded=true or with_unit=truei s set

marble jackal
#

you can

#

I think it's best to leave it as is

#

but if you only want it to show on that card, you could just create a template which shows the time it has been on

mighty ledge
#

it should already do that

sonic sand
#

Okay I will give it a shot

mighty ledge
#

IIRC history stats shows duration sensors

sonic sand
marble jackal
#

okay

#

anyway, this should also work:

secondary: >
  {% set entity = 'light.booglamp' %}
  {% set last_change = states[entity].last_changed %}
  {% set minutes = ((now() - last_change).total_seconds() / 60) | round(0) if is_state(entity, 'On') else 0 %}
  Current: {{ minutes }} minutes
ripe steeple
#

@mighty ledge got time for a q? 🙂

mighty ledge
#

just post it, anyone can help

ripe steeple
#

Ay its posted earlier without response 🙂 I can copy paste

#

repost:
Can someone tell me why my template (which is working) still throws
errors in logs that my power_sum variable is undefined

all inputs to my variable power_sum should default to 0 on any error if I understand float(0)

https://dpaste.org/8BUsf#L12
"Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined"

#

basically got a working sensor that always shows values, no errors in UI/graph view yet my logs are spammed with errors

mighty ledge
#

post the full error

#

and lines before it

ripe steeple
#

thats it unfortunately, i get nothing more than that .__.

mighty ledge
#

no, it's missing the module and timestamp

#

and the erroring template

ripe steeple
#

just am oment

#

need to reactivate it and wait for an error, was spitting out to many faults so i disabled it

#

From older timestamps (while i wait)
2024-03-18 10:59:10.970 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'power_sum' is undefined when rendering '{{ power_sum }}'
2024-03-18 10:59:10.971 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined

sonic sand
mighty ledge
#

there has to be an error before that

#

outside that, I wouldn't even use a tempalte sensor for this, I'd just make a sensor helper group with sum selected

#

i'd then have a second template sensor that outputs 'Error' 'Idle', etc

ripe steeple
#

afraid not , i ctrl-f my log and there is nothing else related to my power2 sensor oother than repeats of the lines i posted thats why im confused

#

2024-03-18 11:06:52.648 WARNING (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Already running
2024-03-18 11:06:52.648 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined
2024-03-18 11:06:52.649 WARNING (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Already running
2024-03-18 11:06:52.649 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined
2024-03-18 11:06:52.649 INFO (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Running template script
2024-03-18 11:06:52.650 INFO (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Executing step setting variables
2024-03-18 11:07:00.162 INFO (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Running template script
2024-03-18 11:07:00.162 INFO (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Executing step call service
2024-03-18 11:07:25.768 WARNING (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Already running
2024-03-18 11:07:25.769 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined
2024-03-18 11:07:25.769 WARNING (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Already running
2024-03-18 11:07:25.770 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined

#

heres a longer snippet

ripe steeple
#

just wasn't expecting all the errors even across reboots

#

and now that I re-enabled it it's spamming errors again

#

2024-03-18 13:09:17.655 WARNING (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Already running
2024-03-18 13:09:17.655 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined
2024-03-18 13:09:17.656 WARNING (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Already running
2024-03-18 13:09:17.656 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined
2024-03-18 13:09:17.663 INFO (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Running template script
2024-03-18 13:09:17.663 INFO (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Executing step setting variables
2024-03-18 13:09:24.781 ERROR (MainThread) [moonraker_api.websockets.websocketclient] Websocket connection error: Cannot connect to host 192.168.1.86:4409 ssl:default [Connect call failed ('192.168.1.86', 4409)]
2024-03-18 13:09:50.657 WARNING (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Already running
2024-03-18 13:09:50.657 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined
2024-03-18 13:09:50.658 WARNING (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Already running
2024-03-18 13:09:50.658 ERROR (MainThread) [homeassistant.helpers.sensor] Error rendering state template for sensor.house_heatpump_power2: UndefinedError: 'power_sum' is undefined
2024-03-18 13:09:50.659 INFO (MainThread) [homeassistant.helpers.script.trigger_update_coordinator] Trigger Update Coordinator: Running template script

#

guess I could report it as a bug on github since neither you nor I see any errors in my template

mighty ledge
#

how fast are these updating?

ripe steeple
#

on state change from 3 different entities from the same devices (a shelly 3PM)

#

so 30s i think?

mighty ledge
#

yeah, just use a sensor group and a separate template sensor

#

it appears to be updating too fast

ripe steeple
#

ah ofc.. 3 updates every 30s when shelly updates the 3 entities ..

mighty ledge
#

or yoru script has an error in it and it failed the first time and now it's stuck

ripe steeple
#

ill try just using a single entity on the state

marble jackal
plain magnetBOT
#

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

sonic sand
#

Thanks for help

bronze prawn
#

I'd like to create a group that contains all of the microphones tied to assist. these show up as sensor types. I added a helper with these but it seems to have made them into a combined sensor instead of a group.

Can I group sensors together so that I can expand them and use them in templates or am I thinking about this the wrong way?

mighty ledge
#

use oldschool group, yaml only

marble jackal
#

you can also use expand on a GUI created sensor helper group

mighty ledge
#

no he won't be able to

#

the entity will be unkonwn if thye aren't numeric

marble jackal
#

ah yes

mighty ledge
#

I"m assuming these won't be numeric

marble jackal
#

I was just looking into that

#

makes sense

mighty ledge
#

yeah, but someone else in the ass the other week, fresh in my mind

#

would be nice if we had a sensor group that just output the timestamp of the last entity update

#

auto made it into a timestamp sensor

bronze prawn
#

No. They will not be numeric. hold strings. Will configure in yaml. Thanks

devout dragon
#

if i have a sensor like nordpool, with attributes that is prices etc, can i make another sensor that monitors a specific attribute in the nordpool sensor for state changes? like when new price comes in the attribute changes

fickle sand
devout dragon
#

@Bas ok, can i make a trigger somehow that triggers on that changes from false to true, or whatever the state is ? 🙂

fickle sand
#

Yep you could do that

#

I am using the trigger directly in an automation, but it should also work similar in a trigger sensor

trigger:
  - platform: state
    entity_id:
      - sensor.nordpool
    attribute: tomorrow_valid
    for:
      hours: 0
      minutes: 0
      seconds: 0
    from: false
    to: true
devout dragon
#

thanks 🙂 gonna try it out .. have had trigger at 15:00 so far each day and sure that works but it keeps working on old data from when i get the data until 15:00 🙂

sonic sand
marble jackal
#

is it still On?

sonic sand
#

input_select.switcher_boiler_status is On now

marble jackal
#

Maybe it's better to create a template sensor using this template:

{% set entity = 'light.booglamp' %}
{% set last_change = states[entity].last_changed %}
{{ ((now() - last_change).total_seconds() / 60) | round(0) if is_state(entity, 'On') else 0 }}

You can paste this as the template in a GUI tempalte helper

sonic sand
#

let me try that

#

Perfect!
Thank you

bronze prawn
#

I'm back asking questions but hopefully I'm almost done. @petro helped me last week in creating a sensor that shows the last used assist microphone device (sensor.assist_last_called).

The final piece will need to take that sensor value (sensor.assist_last_called). , and compare it to a list of Assist satellite devices (group.assist_satellites) that has an attribute (mic_device) that contains the same name stored in sensor.assist_last_called and reutnr the matching entity name from the list of satellite devices.

I THINK what I need to do is something like:

expand(['group.assist_satellites'])|selectattr('mic_device', 'eq', sensor.assist_last_called)

Does that make sense?

#

{{ expand(['group.assist_satellites'])|selectattr('mic_device', 'eq', sensor.assist_last_called) |list}}

Tried this but I am getting a 'sensor' is undefined . Not sure how to pull that variable value for the comapre

mighty ledge
#

if the output of sensor.assist_last_called is an enitty_id, get it's state with the states() method

bronze prawn
#

tried this:

{{ expand(['group.assist_satellites'])|selectattr('mic_device', 'eq', states(sensor.assist_last_called)) |list}}

erorr is 'sensor' is undefined. I guess that's not what you mean. The value of sensor.assist_last_called is a text string that returns a value like 'sensor.thinksmart_lr_stt'

inner mesa
#

surround the entity_id in quotes

mighty ledge
#

quotes

inner mesa
#

you're treating it as a variable

mighty ledge
#

im too slow

bronze prawn
# inner mesa surround the entity_id in quotes

Someday I might get this straight!

So now I am getting back :

[]sensor.thinksmart_lr_stt

Not sure why I'm seeing the empty set (square brackets) but more importantly I'm getting back the value storage in snesnor.assist_last_called OR the value of the mic_device attribute from the group.assist_satellites member entity. What I'm needing is the the group.assist_satellite member entity name. Not sure if I'm making sense but it's not returning what I need.

inner mesa
#

I suspect that 'mic_device' needs to be 'attributes.mic_device'

spiral grove
bronze prawn
#

[<template TemplateState(<state sensor.assistsat_viewlrthinksmart=; title=, message=, image=, timer=, alarm=, cycle_view=, mode=normal, mic_device=sensor.thinksmart_lr_stt, mediaplayer_device=media_player.thinksmart_lr, view_timeout=20, message_font_size=3vw, friendly_name=AssistSat_ViewLRThinksmart @ 2024-03-18T10:28:36.587060-05:00>)>]sensor.thinksmart_lr_stt

So this is what is returned. I'm only interested in getting the 'sensor.assistsat_viewlrthinksmart' portion. Can you tell me how to grab that?

#

This is what I'm working with

marble jackal
marble jackal
bronze prawn
#

Thank you both VERY much. I think this is the last piece in the puzzle

bronze prawn
#

I got it. attributes.mediaplayer_device

cosmic hamlet
#

how do i get all words from a sentence except the 1st word.

#

found it split(first_word, 1)[1].strip()

bronze prawn
# marble jackal `{{ expand('group.assist_satellites') | selectattr('attributes.mic_device', 'eq'...
service: browser_mod.navigate
data:
  path: /dashboard-tablet/weather
target:
  device_id: "{{ device_id('sensor.tabletfullkiosk_browser_path') }}"

Example ^^^^

I'm needing to get a device_id for rather than the entity_id from an altered version of what you gave me:

{{ expand('group.assist_satellites') | selectattr('attributes.mic_device', 'eq', states('sensor.assist_last_called')) | map(attribute='attributes.display_device') | list }}

Is it easy to modify this to provide device_id? I see the function call but I'm not sure how to format it.

marble jackal
#

Is that display_device an entity_id?

bronze prawn
#

Sorry. Yes, it is storing an entity_id

urban rune
#

Is there a way to "mutex" a trigger-based template sensor? I have one which triggers on (among other things) 2 binary sensors that may change state at "exactly the same time" (they have the same device as source), and somehow it is not able to perform an "increment" action on one of the output sensors. I guess this is due to the async way HA is written, and the trigger on one of the 2 BSs not being done (but being in an await call) while the other starts executing/calculating. But I really need to trigger on both binary sensors.

So can I add a mutex, or does anyone have an idea how to work around this issue?

inner mesa
#

it's impossible for both entities to change state at exactly the same time

#

there will be two separate events no mater what

#

if you want to trigger on both changing to the same state, add both as triggers and use a condition that theyr'e both in the desired state

urban rune
#

right, which is why I put it in quotes. But from what I can see the 2 triggers are close enough for the template to trigger quickly after another, resulting in 2 calculating being simultaneously executed.

bronze prawn
# marble jackal Is that `display_device` an entity_id?
{{ device_id ("expand('group.assist_satellites') | selectattr('attributes.mic_device', 'eq', states('sensor.assist_last_called')) | map(attribute='attributes.display_device') | list") }}```

I tried this but I got back a bunch more than expected:

[<template TemplateState(<state sensor.assistsat_viewlrthinksmart=; title=, message=, image=, timer=, alarm=, cycle_view=, mode=normal, mic_device=sensor.thinksmart_lr_stt, mediaplayer_device=media_player.thinksmart_lr, display_device=sensor.thinksmart_lr_browser_path, view_timeout=20, message_font_size=3vw, friendly_name=AssistSat_ViewLRThinksmart @ 2024-03-18T13:58:52.049367-05:00>)>]sensor.thinksmart_lr_stt

inner mesa
#

you have a stray " in there

#

actually, two of them

bronze prawn
#

It throws an error without

inner mesa
#

this part is wrong:
"expand('group.assist_satellites') | selectattr('attributes.mic_device', 'eq', states('sensor.assist_last_called')) | map(attribute='attributes.display_device') | list"

bronze prawn
#

TypeError: unhashable type: 'list'

inner mesa
#

then add |first

bronze prawn
#

get rid of quotes and pipe to first after list?

inner mesa
#

think about what you're doig

bronze prawn
#

🙂 Got it. Thanks!

inner mesa
urban rune
#

And what if I need to be able to distinguish all 4 different combinations of 2 binary states?

inner mesa
#

do it in the action: section with a choose

marble jackal
# bronze prawn 🙂 Got it. Thanks!

device_id can be used as a filter, so you can also do

{{ expand('group.assist_satellites') | selectattr('attributes.mic_device', 'eq', states('sensor.assist_last_called')) | map(attribute='attributes.display_device') | map('device_id') | list | first }}
urban rune
inner mesa
#

ok

rocky hawk
#

How to check if an attribute is defined?

haughty breach
plain magnetBOT
#

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

fickle sand
clear mist
#

ah, sorry, wasn't sure where it sat - thanks!

modern sluice
# haughty breach As Rob stated above, `away` is not a common attribute, so that is the next most ...

Hi, sure I can clarify: For this device tracker, Home and Away are used to determine if the device is Home or not. I can verify this by watching the state of the device tracker. In the automation UI, I can conditionalize the device state to Home, Away, Unavailable, Unknown, so I know the state of Away is correct. What I'm trying to do is conditionalize an automation so that it only runs if my watch has been away for 30 + mins {{ state_attr('device_tracker.serge_s_apple_watch', 'away') > now() - timedelta(minutes=30) }}. Right now it's welcoming me home even if I take the dog out for 5 mins.

haughty breach
#

The actual state of a device tracker is home, not_home, or the name of the zone it is in. Home and Away are "friendly" frontend representations of the state.
None of that has anything to do with the state_attr() function you are trying to use because the state is not an attribute.

modern sluice
#

I understand what you're saying and I was suspicious that I was using state_attr() incorrectly. Do you know which function I'm supposed to use?

rocky hawk
#

Rest value_tempate for Signal Messenger

haughty breach
modern sluice
#

when the watch changes to home

#

if the watch has been gone 30 mins, then run the automation

haughty breach
#
{{ now() - trigger.from_state.last_changed >= timedelta(minutes=30)}}
modern sluice
north tapir
#

Hi! I have a sensor with attributes that I can see on the state card if I expand the Attributes-drawer. However I can't seem to access them with state_attr('sensor.sensorname', 'attributename') - it gives me None. Any hints on what to do?

marble jackal
#

the GUI will doe cahnges to the attribute (eg capitalize the first letter, change underscores to spaces)

#

check in devtools > states what the actual attribute key is

thick loom
#

Hi. I have a two way-valve that controls the water source for my vegetables watering. If there is water in the cistern, it is used and otherwise I use water from the tap (I use a pressure based sensor to measure the water level in the cistern). The valve is controlled with a Shelly Uni which provides 2 switches in HA. If I turn
switch A on switch B off -> the valve uses water from the cistern
switch A off switch B on -> the valve uses water from the tap
The switches turn off after 30 seconds automatically.
What I am looking for:
a new (virtual) "Master" switch, that stores its own state and sets the state of A and B when being switched. I was able to create a template sensor, that triggers the actions, but it does not keep its state. Can anybody point me in the right direction?

thick loom
thin spindle
#

Hey, I would like to calculate the real energy cost of charging my EV because I have a mix of grid energy and solar energy.
I have done that per charging cycle but its not very accurate.
I do (speudo code) consumption_of_charging_cycle * energy_cost / 100 * (100 * grid_energy / (grid_energy + solar_production - grid_feed))
Is there a way to better track this as a template?

mighty ledge
#

why don't you just add this to the energy panel

thin spindle
#

because this gives me the overall price if my grid.
I want to have a dedicated price for charging the EV only

mighty ledge
#

right, that's an option

thin spindle
#

(not included my home consumption)

lofty mason
#

I don't think energy can do that?

mighty ledge
#

individual devices can't do that?

lofty mason
#

No they don't track costs

thin spindle
#

thats my problem 😄

lofty mason
#

It's the second top FR

#

soon to be first I guess 😂

thin spindle
#

Problem is, I want to have it soon ... not to say, today or tomorrow 😂

#

I mean, my method works, but it just takes the integral values of the energy consumptions.
If there are clouds or the sun goes down its looses accuracy, because it only takes the energys kWh values, whan everything is done. (no real time tracking)

#

Its even harder for me to do this on a daily bases.
Next step: I want to see the "real" costs on a daily basis and not "per charging cycle".

#

If I use my approach, then the values are completely messed.

lofty mason
#

I guess maybe what you want is a sensor that is the instantaneous cost of your charging electricity, and then riemann sum it while the car is charging?

thin spindle
#

something like this maybe?

fickle sand