#templates-archived

1 messages ยท Page 5 of 1

marble jackal
#

you added the json in the GUI, the GUI added quotes around it

#

that's what it does

mighty ledge
#

oof

#

makes automations less useful then

#

convert it to json. but i'd switch to yaml

silent vector
#

Worked (from trace)

set_color_temp:
  Day: 222
  Night: 370
  8pm: 370
  After9pm: 370
color_temp_condition: 7
color_temp: 222
color_temp_condition1: 7
marble jackal
#

I never use the GUI, but I guess it's done to avoid issues with states like on and off and when adding templates

#

but it makes it difficult to check for true and false on attributes, or to add json

mighty ledge
#

I'd assume they just treat it as a 1 dimensional object for easy UI parsing

#

and by it I mean all variables

silent vector
#

Just makes it easier since I'm on mobile doing this 99% of the time when I have a second to just create automations through the UI. If I wasn't using yaml would be fine.

marble jackal
#

something like this is only possible in the GUI when changing it in the raw yaml editor

condition: state
entity_id: light.foo
attribute: is_deconz_group
state: true
mighty ledge
#

why are you always on mobile? That slows down the automation process x10

silent vector
#

I do most of this early in the morning when I get up. Would rather not go sit in front of a computer at 5am lol. It definitely does slow it down. When I have a big issue such as a formatting issue or need to make major changes/testing I do use a desktop to speed this up. I should probably get a cheapo one too lol

mighty ledge
#

I have a cheapo laptop

silent vector
#

I wonder if the UI will ever get to a point where it doesn't mess with yaml?

mighty ledge
#

nope, it never will

#

there's too much variability in yaml, it would be a mess

#

the UI would have to handle anchors, sort order, object typing, sort order of the objects. And that's just what comes to mind off the top of my head

silent vector
#

Interesting. Didn't know all of that.

marble jackal
#

isn't it converted to json before ending up in automations.yaml?

mighty ledge
#

it's returned as a dictionary, yaml accepts json

marble jackal
#

yeah, but I though when saving an automation in GUI, it's converted to json, and then back to yaml for automations.yaml

mighty ledge
#

dictionaries are not sorted, object typing would need to be handled by the UI

#

it may be, I don't have that memorized. Still doesn't change what would need to be handled by the UI

#

the limitation is not yaml, it's the UI

#

it's the UI's ability to mimic yaml or json.

marble jackal
#

I just assume they tried to make the basics as user friendly as possible. So they automatically add quotes everywhere, becuase that is correct in most cases (eg to: "off" in a state trigger, or for a single line template).
But for the exceptions, so when you add json instead of a template, or when you actually want to check on a boolean value, it makes it more difficult

mighty ledge
#

na, I think it was a "hey, everything's a string and it should work" kind of deal

#

extended typing and guessing what the user intentions are, is pretty difficult.

#

and it leads to unintended bugs

split iron
#

Hey everybody, I have a whitespace question.
I have a template sensor with a value_template that uses the indent() filter. This works correctly in Developer Tools, but when I check the state it appears the indentation is removed.

**{{ y.name }}** {{ y.last_changed | as_local | relative_time | indent(25 - y.name|length, true)}} ago

split iron
#
      friendly_name: Alarm Trigger Last 10 Minutes Relative
      value_template: >
        {% set x = expand('binary_sensor.total_alarm')
        | sort(reverse=true, attribute='last_changed')
        | list %}
        {% if x | count > 0 %}
        {%  for y in x %}
        {%-    set diff = as_timestamp(now()) - as_timestamp(y.last_changed) -%}
        {%-    if diff < 60*10 -%}
          **{{ y.name }}** {{ y.last_changed | as_local | relative_time | indent(25 - y.name|length, true)}} ago
        {%    endif -%}
        {%  endfor %}
        {% else %}
          {{ 'No changes found.' }}
        {% endif %}```
mighty ledge
#

so are you saying that the indent between y.name }} ** and {{ y.last... is not working?

#

FYI, states have exterior whitespace removed and they are limited to 254 characters

split iron
#

yes in Developer Tools this jinja looks like

**Main Garage**               5 seconds ago```
but if I  call the state of the sensor in a markdown card ```{{states('sensor.alarm_trigger_last_10_min_realtive')}}``` I get 
```Side Garage 1 minute ago
Main Garage 1 minute ago```
mighty ledge
#

yep, that's the behavior of states

#

use a markdown card or send it as a notification. Storing it as a state with a template sensor will truncate whitespace.

split iron
#

I see. I was trying to save myself from keeping multiple cards all updated with this every time I make a change. (You know what they say about premature optimization ๐Ÿ™‚ )

#

Just for clarification while I have you what are the whitespace trimming rules? it keeps a single space and line return?

mighty ledge
#

all extra whitespace is removed

silent barnBOT
mighty ledge
#

it's possible that's the case as well. But you can just use HTML, which will be preserved.

split iron
#

oh... can you point me to a doc on that I didn't know I could produce html directly (and thanks for all your help BTW)

mighty ledge
#

There really ins't a doc on it, it's HTML

split iron
#

I meant... for the card config

mighty ledge
#

Yes, that's what I mean, it's html

#

markdown accepts HTML and it will be rendered

split iron
#

ah

#

ok

mighty ledge
split iron
#

I can take it from there then ๐Ÿ™‚ (I thought you meant there was some special HTML card or something)

mighty ledge
#

no, all markdown inside and outside home assistant renders html

#

markdown is a language... kinda

#

it's used by many different softwares

split iron
#

Also, I know my example looked dumb, but I have some really long sensor names that can make the list hard to read when multiple entities are showing up. It is just easy to trigger the garage from my desk. Anyway, Thanks again!

silent vector
#

How would I prevent this automation from triggering itself and causing a loop. I just noticed it's doing that.
https://dpaste.org/UW5e3
The goal of the automation is sometimes zha groups when turning on to a different color temp than previous on state will turn on incorrectly and not turn on on the new color temp. This is a Backup to correct that when it happens. However in me targeting the script to run again I'm also triggering off script Start and creating a never ending loop. It needs to be parallel to watch multiple scripts.

rose scroll
#

How many of such scripts do you have that needs monitoring? Perhaps it's easiest to just make one backup automation monitoring each script, instead of one master automation to monitor all scripts?

silent vector
#

A lot. Each light group has a day/night script and some have 2 additional scripts. So at least 18. I do that so the script can be manually triggered from the frontend. In theory I could refactor them to consolidate them to 1 script per group and create a variable to pass which light setting to use. I would rather avoid that for now if possible.

#

I thought of a single automation per script or even including it in the automation that fires the scripts. Or including this In each script but I figured that was a lot of unecessary code duplication.

split iron
rose scroll
#

Yeah...if it is on the scale of say 5 scripts then I would argue it's not worth the effort to write a master automation. But 20...sure, I can see the value proposition.

silent vector
#

Definitely a future state refactor will be to consolidate. But for now I am hopeful there's a way to use this automation.

#

Would be nice if the trigger data for events included what triggered it. Similar to what the logbook does. That would make this easy. But it doesn't show what called the script in the data only the logbook. Is there a way?

rose scroll
#

Seems like there is a need for a bit of memory. Can you write the entity id of the light group that the automation targeted on the previous run to an input_text? Then add a condition to check whether the current run's target is different from the last run's.

split iron
silent vector
#

That's possible. Curious if I need multiple input texts then and a dictionary to avoid Inteference on the chance more than 1 script is fired at exactly the same time. Then just check the last updated of the input text as well.

rose scroll
#

Yup maybe that could work.

#

Of course, another angle is, does the undesired behaviour happen because of the firmware on specific models of bulbs? You could in principle change the bulbs...

silent vector
#

It's the coordinator. The network is great the bulbs are good. Sometimes the way the coordinator processes group messages they fall out of order. They have to be in order.

#

It's a sonoff zigbee 3.0

rose scroll
#

Ah

silent vector
#

Yeah it's rare but would like to fix it.

rose scroll
#

If it's an issue with the coordinator's behaviour, someone in #zigbee-archived may advise better. Surely there is a way to enforce the order of the commands transmitted.

#

Assuming this is an issue with zigpy and not with the dongle specifically.

silent vector
#

I talked to the dev. Not that simple lol. I think I said it wrong it's not an issue with sending. It's an issue with how the bulbs receive it. Because group commands are multicast. Once the message is sent nothing the coordinator can do with how the command is received. I wish it was simple.

rose scroll
#

Right. And who knows what is interfering en route.

silent vector
#

Don't know the network is extremely responsive. Repeaters everywhere. It also caused an issue with the "enhanced transition" feature. That's how I find out about the issue with how the commands are received by group bulbs. Receiving specific commands is fine. But zha groups don't receive a specific command to each bulb. They listen for a group command that's blasted everywhere.

abstract zinc
#

What does Failed to load blueprint: while scanning for the next token found character '%' that cannot start any token mean? Can I not use Jinja Templates as part of the yaml? Or is it only limited to values?

The relevant lines in question look like this:

{%- if true == true%}
  - delay: 10
{%- endif %}
inner mesa
#

You can't do that

#

You can only template values unless you play more advanced games

#

Just use if/then

abstract zinc
#

So there is no way to dynamically add or remove attributes?

inner mesa
#

That's not what that was trying to do

#

What do you mean by that?

#

That was part of a script/automaton action, and like I said 'if/then' among others

abstract zinc
#

What if I have a blueprint for a template that has an entity selector input and an integration which does not support actions on lists. I would do a for loop over all entites and perform the action on each entity itself. E.g.:

action:
{%- for entity_id in input_entites %}
  - service: light.turn_on
    target: "{{entity_id}}"
    data:
      transition: 1
      brightness_pct: 50
{%- endfor %}
inner mesa
#

Right, you can't do that

#

You should use the repeat: construct

#

Maybe read the entire script syntax page in the docs ๐Ÿ™‚

#

Or for each, actually

abstract zinc
#

Yeah the docs are a bit overwhelming as I have to juggle between the Jinja docs, the blueprint docs, the templating docs and the script docs.

But how would I insert all entities in a repeat construct if I am unable to fill the for_each items dynamically?

inner mesa
#

You can use a template

abstract zinc
#

So

repeat:
  - for_each:
    {%- for entity_id in input_entites %}
      - {{entity_id}}
    {%- endfor %}

is fine?

inner mesa
#

No

#

You already have a list

abstract zinc
#

But only as a variable as it's a blueprint

inner mesa
#

Doesn't matter

abstract zinc
#

So like:

repeat:
  - for_each: {{input_entities}}

?

inner mesa
#

I would expect for_each: "{{ input_entities }}"

#

With quotes, yes

abstract zinc
#

Oh ok, thank you very much. I presume macros are basically a no-go then?

inner mesa
#

You can do whatever you want within a given template, but not globally

marble jackal
abstract zinc
#

Manually traversing the data structure given by the input selector seems a bit cumbersome but at least I see a way forward now.
Thank you again for your time.l

inner mesa
abstract zinc
inner mesa
#

yeah, that's a fine way to have an optional delay

sonic nimbus
#

Hello. I want to detect an netrance event to the home. This event will be calculated as boolean true or false. I have frontdoor motion sensior, and I have sensor on my doors, on/off sensor.

This is my code:

            {% set frontdoor_last_changed = as_timestamp(states.binary_sensor.front_door.last_changed) %}
            {% set time_diff = (frontdoor_movement_sensor_last_changed - frontdoor_last_changed) | abs %}
            {{ 15 > time_diff > 0.5 }}```
Do you think this is ok? I want to catch time window when I stand in front of my door up to 15 seconds (to open my door by key, or by app) and then to catch last changed event when the door hits status on from off.

What do you think? Should I consider some other approach?
zenith rain
#

newby here. How can i get only the entity_id out of {{ states.media_player | rejectattr('state','eq','unavailable') | list }}? Trying to get the list of all my media players

marble jackal
#

| map(attribute='entity_id') before list

zenith rain
#

Awesome. Thanks

lament dust
#

Not sure if this is really a template or automation question, but if I have a simple trigger using state with time set like:

platform: state
entity_id:
  - sensor.kitchen_camera_detected_object
to: person
for:
  hours: 0
  minutes: 1
  seconds: 0
from: none

Is it possible to make the time conditional based on some factor? For instance Id like to do something like if sun is above horizon 1 minute, otherwise 0

marble jackal
#

You probably want to add quotes around none if that is the state of that entity

marble jackal
lament dust
marble jackal
#

Well, none will be a completely empty state, not the string "none"

marble jackal
lament dust
#

Well dumb question is how can I tell if its none or "none" lol

marble jackal
#

Does the state show the actual word none in devtools > states

#

In that case it is a string, because all states are strings

#

And then you need the quotes

lament dust
#

yes it shows none

marble jackal
#

If it shows nothing at all as it's state, it's none without the quotes, but I've never seen that

lament dust
marble jackal
#

Okay, so use quotes

old apex
slow vine
#

I am trying to use an input_text to be used to produce a list of matched entities. As it is now it works just as expected. I wanted to try to filter using regex not (!) so I can use regex to exclude some entities but its not working, I don't know if my regex is bad or I am doing something wrong.

#

here is my template:

    {%- set device_name_list = states.sensor|selectattr('object_id', 'search',
     states('input_text.entity_selector'), ignorecase=true)| map(attribute='entity_id')| list -%}
mighty ledge
#

Weโ€™d need to see the regen

#

Regex*

slow vine
#

^(!WiFi)(living_room_ac*.*uptime)$

#

I am tring to exclude any sensor that has "WiFi" in the name. And include living_room_ac_anything-else_uptime at the end of the line.

#

Maybe I should make the list first and then search with regex?

#

I tweaked the regex, now it works
^(?!.*WiFi)(living_room_ac*.*uptime)

zenith rain
#

Am I doing something wrong trying to populate an input_select using a template:

service: input_select.set_options
data:
  options: >-
    {%for item in states.media_player | rejectattr('state','eq','unavailable') |
    map(attribute='entity_id') | list  %} - {{item}}
  {%endfor%}
target:
  entity_id: input_select.echo_list

I get State max length is 255 characters. Should I interpret this as my template returns a single string looking like an array, instead of an actual array?

inner mesa
#

Just output the list

#

You don't need that loop

zenith rain
#

I was getting an error saying that it was not a dictionary

#

Let me get the exact error

inner mesa
#

It's looking for a list

#

The code you used is more important

zenith rain
#

hm, can't get the error back again. the code is {{states.media_player | rejectattr('state','eq','unavailable') | map(attribute='entity_id') | list }}, says acttion ran, but I don't see the input_select updated

inner mesa
#

What is the rest of the code?

silent vector
inner mesa
#

My guess is that you're using 'area' before it's actually defined

#

This also looks wrong:

  - service: "{{ trigger.event.data.entity_id }}"
    data: {}
#

An entity_id is not a service

#

Unless it's a script?

#

Oh, never mind. It is a script

zenith rain
# inner mesa What is the rest of the code?
alias: "AUTOMATION: Refresh speaker list daily"
description: ""
trigger:
  - platform: time
    at: "00:00:00"
condition: []
action:
  - service: input_select.set_options
    data:
      options: >-
        {{ states.media_player | rejectattr('state','eq','unavailable') |
        map(attribute='entity_id') | list}} 
    target:
      entity_id: input_select.echo_list
mode: single

Running this with a run action. But it's part of a simple teat runs at midnight

silent vector
#

Move area?

inner mesa
#

I don't know if you can reference one variable from another in that section

silent vector
#

It's weird because it works 99% of the time. Then suddenly explodes with errors.

zenith rain
#

Ok, regarding to the above issue with the template. I went in the developer tools, and looked at the input_select, and the options are updated. Looking in the GUI under helper tho, the options are not. And on reboot it resets ๐Ÿ˜•

mental violet
#

Hello,
I have a template sensor which is on/ off when my TV is on/ off.
I have a Button in LoveLace which should be shown the icon in normal white (when TV is off) and yellow (when TV is on) (these colours are my normal on/ off colors)
If I use an input_boolean in the card it does that automaticly.

silent barnBOT
silent barnBOT
#

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.

inner mesa
#

In both cases, you're applying |int to 60

#

You need to surround the expression in parentheses and remember order of operations

flat lantern
#

I'm having a hard time getting energy sensors to work. Does anybody see anything wrong with this template sensor?

The "state" itself works fine when copied into the template-editor.

template:
  - sensor:
    - name: "Energy House"
      unique_id: house_total_energy
      state: "{{ (states('sensor.house_channel_a_energy')|float + states('sensor.house_channel_b_energy')|float + states('sensor.house_channel_c_energy')|float) | round(4) }}"
      state_class: total_increasing
      unit_of_measurement: kWh
      device_class: energy
rose scroll
flat lantern
rose scroll
#

What is the error that you are getting with this sensor? That it's value is not monotonically increasing?

flat lantern
#

I got the error "float got invalid input 'unknown' when rendering template". So I added "availability" to the sensor. Now the error is gone, but the sensor still doesn't show up.

      availability: >
        {{ states('sensor.house_channel_a_energy') | is_number 
        and states('sensor.house_channel_b_energy') | is_number 
        and states('sensor.house_channel_c_energy') | is_number }}
rose scroll
flat lantern
rose scroll
#

Could you dpaste your full block of yaml under

template:
  - sensor:
#

Maybe it's an indentation issue above or below this yaml for the energy sensor.

silent vector
timber schooner
#

Good people! Can someone help me out? I've been at this for a few days and everything I've tried when wrong in some way or another... I have two power sensors: one measures the electricity usage of the entire house - including the electricity from the solar panels. One measures the electricity the solar panels generate - including what goes back to the grid. I want to have accurate energy reading. This is what I've tried: https://pastebin.com/jvJU1SmF - but I always get very funky results, usually making it appear that I've generated or consumed tens of thousands of kWh.... Don't know why or how to fix it... Thanks in advance!

rose scroll
#

May not be related to the problem you are seeing, but what is {{ nothing }}?

timber schooner
#

I read that having value '0' would cause problems, so I kind of made it generate a faulty value...

#

I'm not very confident about that 'solution', but as I've said, I've been at this for a while and this is just the latest attempt to hopefully magically fix this ๐Ÿ˜‹

flat lantern
rose scroll
timber schooner
#

Is this not necessary for it to be used in the energy dashboard?

rose scroll
#

And {{ nothing }} would refer to the value of a variable named nothing. That doesn't generate errors?

timber schooner
#

Doesn't seem to .. should I lose the brackets then?

rose scroll
#

Let's back up for a second. What's the objective you are trying to achieve? To track total energy consumed in your house? Or total grid energy used in your house?

timber schooner
#

I'm trying to make custom sensors to use in the energy dashboard. One should be 'grid consumption', one 'grid return'

#

Total energy consumption of the house I have, but I can't see how much of it is from the grid and how much from the solar panels..

rose scroll
#

Right...I don't use energy dashboard myself, but I think it expects you to provide direct measurements of the energy coming in via your meter and your solar production. Do you have sensors directly measuring these?

timber schooner
#

Only for the solar production

#

And that works fine

#

So I figure: grid input = house consumption - solar input

#

But only if total house consumption > solar production

rose scroll
#

So grid input needs to be monotonically increasing too. It seems to me that the way you've set up your grid input sensor now, it's value could decrease. Eg. On Day 1, house consumption = 100 and solar production = 50, so grid input = 50. But on day 2, house consumption = 200 and solar production = 160, so grid input = 40.

#

Assuming both your house consumption and solar production sensor are monotonically increasing.

timber schooner
#

Makes sense, but how? ๐Ÿ˜‰

rose scroll
#

The easiest way? Get a sensor that measures the incoming grid energy lol

timber schooner
#

๐Ÿ˜… thanks mate..

rose scroll
#

Otherwise, I think you'd need:

  1. A house consumption sensor that measures total energy consumed every Xmin. After Xmin, reset to 0
  2. A solar production sensor that measures total energy generated every Xmin. After Xmin, reset to 0
  3. A grid input sensor, which starts from 0. Every Xmin, if house consumption > solar production, add (house consumption minus solar production) to the last value of the grid input sensor.
#

But seems to me to be quite janky, esp to keep the values strictly synced by time.

timber schooner
#

I'll look into this when I get home.. thanks for thinking along!

mighty ledge
silent vector
#

Any idea what is causing these errors (added them in the dpaste link)? The automation works a bunch of times and suddenly stops with these errors.
https://dpaste.org/Xfqji

silent seal
#

I think one of your lights is somehow missing an entity id.

#

That's based on a quick glance on my phone though. I could be wrong. But the error seems to be saying it's failing to get an attribute from something at least

velvet sigil
#

How do I integrate mqtt sensor if the value is transmitted under space separated name?
When I try to integrate it into HA like following, I receive a message that space separation isn' allowed.

mqtt: 
#!include_dir_merge_list configs/mqtt
  sensor:
    - name: "CAN-Board"
      state_topic: "voron/klipper/status"
      unit_of_measurement: "ยฐC"
      unique_id: can_board
      value_template: '{{ value_json.status.temperature_sensor CAN-Board.temperature }}'
      device_class: temperature

so value is transmitted under temperature_sensor CAN-Board

inner mesa
#
      value_template: "{{ value_json.status['temperature_sensor CAN-Board'].temperature }}"
silent vector
silent seal
#

It could be missing any other attribute, I just noticed you're specifically looking for that at one point

#

Check all of your entities in that domain using the dev tools. You can grab the whole domain and hopefully it'll help you track it down.

silent vector
#

As in pull this {{ states.light }} it works 99% of the time then it fails not sure on what.

#

Wondering if it's missing the color temp?

silent seal
#

Well, time to break it down. You'll have to look.

silent vector
#

Going to be a lot of sifting lol I have over 50 bulbs

silent seal
#

But this part of your template should be filtering that out: selectattr('attributes.color_temp', 'defined')

silent vector
#

Yeah it should be. Very weird.

#

Especially because it works but at some point on something it fails and stops all runs of the automation.

silent seal
#

Are you sure your area has lights in it? As in, the string manipulation you're using definitely produces the right output and that area has lights?

silent vector
#

Yep pretty sure. Going to double check.

#

I think I had 2 areas that the area was not rendering for. Now that you mentioned it. I just fixed those yesterday for a separate issue.

silent seal
#

Aha!

#

Also, is your input_text variable just [area]_light? If so, I'd set that separately/using the area variable if you can, just to avoid updating it in one place and not the other.

marble jackal
#

You could also put your input_text and script in the area, so you are less dependant on the string manipulations

tepid onyx
#

when one item in the list is play it should show ffffff

silent seal
#

Is the title exactly the name of the list item? Or is it "Family Guy S01E02 - Title Goes Here"?

tepid onyx
#

states.media_player.bhtpc.attributes.media_series_title matches the list item

#

when it's playing

inner mesa
#

don't escape the quotes

tepid onyx
#

I know it's kinda hard as you can't replicate: states.media_player.bhtpc.attributes.media_series_title but my jinja code is correct?

#

the template editor blows chunks if i don't escape the quotes

inner mesa
#
{% set variables = {
         "toons": ['Family Guy', 'The Simpsons', 'South Park']
} %}

{{ variables.toons[0] == "Family Guy" }}
#

-> True

#

you also quoted the list, so it became a string

tepid onyx
#

ah oops

inner mesa
#

that was because you quoted the string, and then used the same quotes for the series names

tepid onyx
#

bang on RobC

#

hides

silent vector
inner mesa
#

{{ expand(area_entities('whatever') )|selectattr('domain','eq', 'input_text')|map(attribute='state')|list|first }}

#

Something like that. Depends on what you want to do

silent vector
#

I see. I can make that work thank you.

tepid onyx
inner mesa
#

That is unnecessarily complicated

tepid onyx
#

i tried using expand() but couldn't get it to work with the varible...

inner mesa
#

it seems like you just want this:

  condition:
    condition: template
    value_template: "{{ state_attr('media_player.bhtpc', 'media_series_title') in toons }}"
tepid onyx
#

oh

inner mesa
#

and if you just want to check whatever triggered, this:

#
  condition:
    condition: template
    value_template: "{{ state_attr(trigger.entity_id, 'media_series_title') in toons }}"
tepid onyx
#

using "in" I should of figured that out. thanks again.

inner mesa
#

np

tepid onyx
#

I know it's not efficient way but out of curiosity is there an equivalent of a while loop that could be used around the for loop. educational purposes

inner mesa
#

loops in Jinja aren't very sophisticated

#

The Jinja docs are linked in the channel topic

#

if you were to try to do what you were trying to do, you would create a namespace with a variable in it, loop through the other list setting the variable to true if you find an entry that you like, then use the value at the end of the loop as the result

#

but it's all very overly complex and I avoid loops in Jinja wherever possible

tepid onyx
#

Yeh that's where I got to, using setting a ns.value running the loop then using the {{ ns.value }} after but couldn't get it to work. agree its complex and will take your advice onboard. Cheers mate.

silent barnBOT
worn cloud
#

I have the following template that will tell me which sensor in the group is on

{{ (states.binary_sensor|selectattr('entity_id','in',state_attr('binary_sensor.ringsensorsall','entity_id'))|selectattr('state','eq','on')|list)[0].name }}

But when nothing is on then it displays unavailable - is there a way from this template to ignore unavailable and just dont display anything?

final mural
#

I'm trying to create a sql sensor but I'm getting value 'unknown'. The goal is to get the value at the beginning of the day of a total kW sensor.

  - platform: sql
    queries:
      - name: "Total Energy BOD"
        unit_of_measurement: "kWh"
        query: "SELECT * FROM states WHERE entity_id = 'sensor.total_energy' AND last_updated > datetime(date('now', 'start of day')) ORDER BY last_updated ASC LIMIT 1;"
        column: state * 1000

Any ideas what I'm doing wrong?

inner mesa
final mural
amber geode
#

Any one able to assist a pleb like me?

I have some MQTT messages coming in, but how to make sensors out of them is hurting brain.
ctp_cr3000_topic,{"connected":"true","tags":{"Water_Tank":{"AI_Slot1_CH0_DA_Raw":6605}},"timestamp":"2022-08-21T05:22:35.000Z"}

Message looks like this, any tips?

#

From what I understand a template and sensor object are required.

fossil hearth
#

is there a way to get unit_of_measurement: be a template unit_of_measurement: > as such

#

i tried didn't work ...

inner mesa
#

No

#

They are static

opaque creek
#

Hm was checking this trend sensor:

      temp_falling:
        entity_id: sensor.outside_temperature
        sample_duration: 7200
        max_samples: 120
        min_gradient: -0.0008
        device_class: cold

I read the manual but still dont get how to mix this around to get what I want. This one indicated if the temp is falling at a rate of at least 3 degrees an hour.
If I want 2 degrees an hour, what setting should I change then? ๐Ÿ˜›

#

Wait there was a formula there, but how do I know how many sensor updates my sensor do?

half pendant
#

Trying to create a template that goes over all my window sensors and then reports back those that are open in a string format. How od i create a list that i can add, remove and iterate over in a template?

inner mesa
#

How do you know which sensors are window sensors?

#

And are they really binary_sensors?

half pendant
#

I have a very simple template today that goes through a number of sensors that i specify (one by one) and then creates a string that returns the one that is open or if multiple are open it returns โ€multiple openโ€. Now i would like to change that to it returning all of the ones that are open. I was thinking i could create a binary sensor group and someone use that one. Just not sure how.

inner mesa
#

Share what you have

#

A group will not help you with the output

half pendant
#

Actually found a sweet solution. I did create a group and the following syntax

{{ states | selectattr('entity_id','in', state_attr('binary_sensor.doors_and_windows_test','entity_id')) | selectattr('state','eq','on') | map(attribute='name') | join(', ') }}

seems to work. But it reports the Entity name rather than the Device name.

#

Not sure how to format as code in discord

silent barnBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example

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

For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).

inner mesa
#

In any case, that's what I would do

half pendant
#

Alright. So the solution would be to rename the binary sensor to the same thing as the device then to get the correct text?

#

For instance for me right now that template returns

Altanndรถrr - Kontaktalarm, Livingroom Left Window - Kontaktalarm, Livingroom Right Window - Kontaktalarm

And i donโ€™t want the โ€ - Kontaktalarmโ€ part in the string

inner mesa
#

You might need .replace(' - Kontacktalarm', ''), and to surround the rest in parens

half pendant
#

Where?

inner mesa
#

At the end

half pendant
#

Awesome! Thanks a lot

inner mesa
#

Did it work?

half pendant
#

Yeah!

#

If all are closed (off) will it just report โ€Offโ€ then?

inner mesa
#

No, it will report nothing

half pendant
#

As in โ€empty stringโ€?

inner mesa
#

You can try it

half pendant
#

Seems like it reports nothing like you said. I wonder how i can test for that. I would like it to say โ€All Closedโ€.

inner mesa
#

|default('All Closed', True) before the join()

rare linden
#

is there a way to check the last time a state changed via templating? i'd like to check that the last change done to the brightness value on my bulbs for example is above a certain threshold

another use case is to check if the last time motion sensory went off is below n seconds for putting into a sensor

half pendant
#

@inner mesa does not seem to work. Reports โ€result type: stringโ€ instead of All Closed

inner mesa
#

what did you do?

half pendant
#

{{ states | selectattr('entity_id','in', state_attr('binary_sensor.doors_and_windows_group','entity_id')) | selectattr('state','eq','on') | map(attribute='name') | default('All Closed', True) | join(', ') | replace(' - Kontaktalarm', '') }}

inner mesa
#

add |list before the |default()

marble jackal
#

Your template only updates once per minute now, if you would expand the group, it will update instantly

half pendant
#

A, l, l, , C, l, o, s, e, d

inner mesa
#

or just states.binary_sensor

#

you put it after, not before

marble jackal
#

Once every second then

half pendant
#

No

inner mesa
#

oh

half pendant
#

{{ states | selectattr('entity_id','in', state_attr('binary_sensor.doors_and_windows_group','entity_id')) | selectattr('state','eq','on') | map(attribute='name') | list | default('All Closed', True) | join(', ') | replace(' - Kontaktalarm', '') }}

#

@marble jackal not sure i understand that

inner mesa
#

just start with states.binary_sensor instead of states

#

put the default() part after the join()

marble jackal
#
{% set bs_list = expand('binary_sensor.doors_and_windows_group') | selectattr('state','eq','on') | map(attribute='name') | join(', ') | replace(' - Kontaktalarm', '')  %}
{{ iif(bs_list, bs_list, 'All Closed') }}
#

That should also work if you can't get the default working

half pendant
#

Moving default to after join and removing the list seems to have done the trick.

#

Final sensor
{{ states.binary_sensor | selectattr('entity_id','in', state_attr('binary_sensor.doors_and_windows_group','entity_id')) | selectattr('state','eq','on') | map(attribute='name') | join(', ') | default('All Closed', True) | replace(' - Kontaktalarm', '') }}

teal cove
#

I'm trying to exclude a user_id from an event trigger using limited templates like this:

- platform: event
  event_data:
    user_id: "{{ not 111222333 }}"
    # or
    user_id: "{{ not in [111222333] }}"

but it doesn't work. How do I do this at trigger level?
I'm trying to avoid regular conditions because I have a lot of different triggers for this automation...

inner mesa
#

yeah, you can't do that

teal cove
#

๐Ÿ˜ฟ

inner mesa
#

you're providing a value, not creating a conditional about what to accept

#

the way to do it is via a condition

teal cove
#

oh so not even 111222333 or 444555666 would work?

inner mesa
#

that will just always be "true"

#

which will match nothing

#

again, you're providing a value, not a test

teal cove
#

okay thanks alot!!

#

wait a minute

#

what about {{ trigger.event.data.user_id if trigger.event.data.user_id in [111222333,444555666] else 'yeet' }}

inner mesa
#

you can do that in a condition

teal cove
#

ahhhh, probably not because "The event_type, event_data and context templates are only evaluated when setting up the trigger, they will not be reevaluated for every event."

inner mesa
#

you can't use trigger.xxx in the trigger

teal cove
#

bummer ๐Ÿ™„

#

thank you!

rare linden
#
    value_template: >-
      {{ state_attr('light.kitchen', 'brightness')|int(0) == 0 and
      (as_timestamp(now()) - as_timestamp(light.kitchen.last_changed)) >
      500 }}```
#

whats wrong with that?

teal cove
#

indentation?

#

and you meant |int(default=0) I guess

inner mesa
#

first:

silent barnBOT
#

To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example

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

For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).

teal cove
#

oh and states.light.kitchen.last_changed

rare linden
#

that was it, the missing states, thanks

#

also default= is not required on type filters so I don't use it (didn't actually know you could specify it as default=)

marble jackal
#

brightness is already an int, no need to convert it

rare linden
#

brightness doesnt exist if the bulb is off

#

therefor it needs a default and int(0) is cleaner than default(0)

marble jackal
#

Then check for it being none

#

Or check if the light is off

#

is_state('light.kitchen', 'off')

#

Or state_attr('light.kitchen', 'brightness') is none

rare linden
#

i will probably be changing it to < n so would rather not have the extra check when it's not necessary, if i merley wanted to check for on or off i would do that

#

There seems to be something wrong with (as_timestamp(now()) - as_timestamp(states.light.kitchen.last_changed)) > 500

as that should mean if it last changed more than 500 milliseconds ago should it not? unless timestamp does not equal the unix timestamp format

it worked the first time I triggered the script after fixing it, but is not triggering now and to test i removed that part and it continued past the condition

#

apparently it's in seconds not milliseconds?

teal cove
#

use > timedelta(seconds=500)

#

or (now-last).seconds > 500

marble jackal
rare linden
#

ah

marble jackal
#

And that is indeed seconds

teal cove
#

is the template a trigger or a condition?

marble jackal
#

Use 0.5 instead of 500

rare linden
#
  - condition: template
    value_template: "{{ state_attr('light.kitchen', 'brightness' )|int(0) == 0 and (as_timestamp(now()) - as_timestamp(states.light.kitchen.last_changed)) > 5 }}"
teal cove
#

sorry I misread until now

marble jackal
#

No need to convert everything to timestamps
now() - states.light.kitchen.last_changed > timedelta(seconds=0.5)

rare linden
#

thanks

silent barnBOT
inner quiver
#

Hey there, i am trying to setup a switch.command_line.
Currently i am facing issues with the command_state and value_template.
While my sensor.rest works like a charm, the same template does not work with a switch.
any ideas?

https://hastebin.com/aqisajagel

inner quiver
slim elk
#

you can GET or POST with the RESTful switch

inner quiver
#

how exactly would i do this?
Per Documentation you can choose between post, put and patch.
URLencoding is not mentioned anywhere.
the only viable solution i can see is to utilize the params with a template. where the current state would have to be inverted, which would invalidate switch.turn_on or switch.turn_off srevices or can the intent of the switch-action be read from within the template?

inner quiver
#

I just got it...

value_template: "{{ value_json.monitor == 'on'}}"

possible return values are only "on" or "off". but i still need a comparison..
the sensor accepts "on" or "off" directly

dusk edge
#

What would be the correct way in an automation to update a dynamic list (ie. input_boolean.chore_*) of input booleans to off. I can get the list of all current chores, but I am not sure how to call the input booleans service turn_off from my teplate in the automation. I currently have https://kopy.io/mwe7o for my automation

inner mesa
#

Most definitely not that

#

I'm almost certain I posted a similar solution here in the last week

#

Templates don't do anything, services do

dusk edge
#

awesome... ill play around with that.. still learning the whole "Scripting" part of HA. I have been a super user of node-red in HA, but trying to covert everything to automations/scripts now

#

Thank you for the guidance!

#

while i have you, is there a way to loop over an automation with different params? example: I have a daily "validate enough chores are done for {child}" that makes sure they are up to date on their weekly chores. I have 3 automations, one for each child. The only difference in the automation is the input boolean match (chore_{childName}_chore_name) and then I have a script that sends a phone notification to them which i made script names be the same, except for the child name. Does that make sense? is it possible to combine into one script with a list to iterate over, or do i need an automation for each child that checks their own chores? https://kopy.io/V4fZr is the automation

waxen meadow
inner mesa
#

Your start is later than the end for most of the day

waxen meadow
#

I have to rewrite it the other way around, do I understand correctly? @inner mesa

inner mesa
#

You'll have the opposite problem then

waxen meadow
#

and how should I do it then??

#

or is it not possible?

inner mesa
#

When do you want it to start ?

#

I don't know what you mean by 'reset'

waxen meadow
#

all sensors in ha restart time on 00:00

#

and this i want change on 5am

inner mesa
#

That integration measures statistics for a period of time

#

That's not true

#

At all

#

There's no 'reset' for that integration

waxen meadow
#

๐Ÿ™ƒ

#

thx

opaque marlin
#

Trying to split out the hourly forecasts of the weather.openweathermap entity and found this template:

  Timestamp: {{ (i.datetime//1000) | timestamp_local }} Temperature: {{ i.temperature }}
{% endfor %}```

from the following webpage: https://community.home-assistant.io/t/beginners-templating-question/182773

When I try it out in the template preview page on the developer tools I get an error:

```TypeError: unsupported operand type(s) for //: 'str' and 'int'```
#

This:

  Timestamp: {{ (attr.datetime//1000) | timestamp_local }} Temperature: {{ attr.temperature }}
{% endfor %}```

returns the same as well
inner mesa
#

There's no difference between the two

opaque marlin
#

Sure I just wanted to double check that there was not an issue with just iterating on i. Any idea why I am getting that type error?

inner mesa
#

What value does that attribute have?

silent barnBOT
inner mesa
#

Right, so it's a string

#

attr.datetime|as_datetime|as_local

opaque marlin
#

Yeah, the biggest issue I am running into is my lack of understanding of the way HA structures attributes like that and why there is a specific entity type called weather but all of the forecast data is packed into a single attribute

inner mesa
#

It's just how it was written

opaque marlin
inner mesa
#

What is what?

#

This was your problem:

opaque marlin
#

Whoop replied to the wrong message. You said:
attr.datetime|as_datetime|as_local

inner mesa
#
Timestamp: {{ (attr.datetime//1000) | timestamp_local }}
#

This is the solution:

Timestamp: {{ attr.datetime|as_datetime|as_local }}
opaque marlin
#

Oh gotcha, thank you so much!

Out of curiosity, what is the difference between the two?

inner mesa
#

The first assumes that value is a timestamp in seconds, not a string

opaque marlin
#

Ohhh alright that makes sense

#

So the final piece to the puzzle, if I wanted to create a new template sensor that pulled in just the first set of attributes, how would I go about that? I found this:
https://farmer-eds-shed.com/weather-forecast-based-automation-and-notifications-with-home-assistant/

Where it looks like they address a specific element in the set of attributes. I am still a little lost on the structure of the attributes. Can I do a similar thing as they did? Is there any way to see an entities attributes in like a json structure or something?

inner mesa
#

the structure is a list

#

a list of dicts, specifically

opaque marlin
#

So in this case each hour is a separate dict?

inner mesa
#

yes

#

you can stick this in devtools -> Templates to see the attributes in JSON if that helps:
{{ states.weather.openweathermap.attributes }}

opaque marlin
#

Yeah that does help thank you

#

So how do I access a single element in that dict? ie [1]states.weather.openweathermap.attributes?

inner mesa
#

you were already doing that in the loop above

#

states.weather.openweathermap.attributes.temperature

#

but better as state_attr('weather.openweathermap', 'temperature')

#

linked in the channel topic

opaque marlin
#

Ah yeah perfect that returns a single value, how to you select the next element in the list?

inner mesa
#

[1]

opaque marlin
inner mesa
#

[2]

#

you reference list items just like you would in Python

opaque marlin
# inner mesa [2]

as in:
{{ state_attr('weather.openweathermap[2]', 'temperature') }}?

inner mesa
#

Jinja docs are in the channel topic as well

#

no

#

that woudn't make any sense

#

first, "temperature" there is just an integer, not a list

opaque marlin
inner mesa
#

you would need to find a list, like "forecast", which you already used above

#

they are completely different

#

state_attr('weather.openweathermap', 'forecast') is a list. state_attr('weather.openweathermap', 'forecast')[0] is the first element of the list

#

and so on...

opaque marlin
#

Wow thank you so much. This has been massively helpful

inner mesa
#

I suggest playing with it in devtools -> Templates, where you see the results in real time

opaque marlin
#

Yupp that is what I have been doing. Very useful feature

inner mesa
#

are you talking about Node Red?

#

otherwise, what "nodes" are you talking about?

inner mesa
worn cloud
#

right - ok thanks

unreal merlin
#

Morning ๐Ÿ™‚

#

I'm experimenting with excluding loop from this one https://dpaste.org/vnzGM and I think I need a little help ๐Ÿ™‚
This is part of a cert expiry notifier, and the base logic is: if something is below the set X days threshold, send a notification.

Now I can get as far as mapping state as_timestamp, but I'm stuck with running math operations after doing this.

#

I've got this far:

   |selectattr('attributes.error', 'equalto', 'None') 
   |selectattr('attributes.is_valid', 'true')
   |map(attribute='state') | map('as_timestamp')```
#

the values look like: 2029-03-14T08:13:08+00:00

#

so essentially what I'd need to do here is: as_timestamp(state)|float - as_timestamp(now()))/86400) to have the diff, and |int compare that to my input_number (which is set in days), and |count

#

is there a way to do that in the stack of filters, or I really need to split things up and run the math ops in a loop, build up some ns var and |count at the end?

#

something like: selectattr ( 'as_timestamp(state)|float - as_timestamp(now()))/86400', 'gt', input_number...|float))|count

analog mulch
#

Hi is there a simple way to have template sensors trigger on State changes as per usual, but to limit the rate to no more than once every say 30 s? I am triggering off something that mostly changes once every few minutes, but sometimes itโ€™s every second and I want to ignore it then.

velvet sigil
#

Help needed. How do I fix this to show sensor.idle_state when switch.plug_voron is on?

{% if is_state('switch.plug_voron', 'on') %}
   sensor.idle_state
{% else %}
Off
{% endif %}
marble jackal
marble jackal
analog mulch
#

I have a trigger-based template sensor with the following variables defined:

- trigger:
    - platform: state
      entity_id: sensor.plug_kitchen_oven_energy_last_state
      variables:
        from_state: "{{trigger.from_state.state | float('no value')}}"
        to_state: "{{trigger.to_state.state | float('no value')}}"
        counter: "{{this.state | float('no value yet')}}"
  sensor:
    ...

What does this.state contain -- the trigger state or the state of the sensor being defined in the sensor section

marble jackal
#

this.state will be the state at the moment of the trigger

mighty ledge
#

unless this is new, but I don't remember seeing anything like that.

marble jackal
#

That's new

mighty ledge
#

when was it added?

marble jackal
#

You can add variables on a trigger

#

Few months ago

mighty ledge
#

only for templates?

charred dagger
#

Any trigger I think

mighty ledge
#

hmm, nice

#

TIL

#

Ah, the new part is that they have this

#

they are limited templates, makes sense.

#

They were only available on MQTT triggers and something else for a long time

mighty ledge
#

yeah, they had the trigger_variables (or something like this) for a long ass time, but they were useless unless you were using MQTT. These seem much better.

marble jackal
#

The trigger_variables can be used in the trigger themselves, the variables in the trigger are rendered after the trigger happened, and are not limited to limited templates as far as I know

#

The trigger_variables are limited

marble jackal
mighty ledge
#

that makes them pretty powerful for template sensors. Time to rework some crap.

#

oh man, I can rework just about all my template sensors to reduce code

#

and remove unwanted sensor changes from triggers

#

Have to get inventive with the triggers tho, but you could probably use yaml anchors to dupliacte the code from one trigger to another

charred dagger
#

I really need to get into trigger entities sometime...

mighty ledge
#

so, they have a niche use, but now they have a much better use

marble jackal
red flame
#

Is there any option to sum some enititys? Like any Helpers oder anything?

inner mesa
#

a non-specific question gets a non-specific answer:
{{ states('sensor.a')|float + states('sensor.b')|float }}

red flame
#

Can i sum all entitys of an specific area?

inner mesa
#

now you're getting more specific ๐Ÿ™‚

#

perhaps just ask the final question

#

{{ expand(area_entities('some area'))|map(attribute='state')|map('float')|sum }}

#

like, what exactly are you trying to do?

red flame
#

I have multiple power outlets that can measure power consumption. Now I want to get the sum of every sensor in my room. After this i want the sum (W) converted to kWh.

inner mesa
abstract zinc
#

Am I correct in the assumption, that there is no other way to access last_changed apart from using the state object, i.e. states.sun.sun.last_changed?

inner mesa
#

Correct

red flame
#
sensor:
  name: Leistungsaufnahme Jakob
  state: >
    {{ expand('group.steckdosen_leistung')|map(attribute='state')|map('float')|sum }}
  device_class: power
  unit_of_measurement: W

now i have my sensor with my sum of all W. The Problem is i don't find my enitity in the Riemann Sum integration... Any Idea?

inner mesa
fringe dune
#

Hi there. Keen for a little help here please. I have an entity called sensor.solaredge_inverters and want to be able to extract the attribute connectedOptimizers from it. Here's the State attributes:

#
inverters:
  - name: Inverter 1
    manufacturer: SolarEdge
    model: SE8250H-AUL00BNU4
    communicationMethod: WIFI
    cpuVersion: 4.15.119
    SN: xxxxxxxxx
    connectedOptimizers: 24
friendly_name: solaredge (Inverters)```
#

I figure I have to do something like: {{ state_attr('sensor.solaredge_inverters.inverter 1', 'connectedOptimizers') }} ?

#

...but that doesn't work. Help? ๐Ÿ™‚

harsh patrol
#

hello everybody

#

I've managed to confuse the hell out of myself and my lack of yaml is frustrating me. I'm trying to calculate out my houses power consumption, however, my inverter and battery doesn't provide a single value for that. So I have to do a calculation:

#

battery_day_discharge + grid_active_power + (input_power - grid_exported)

#

the code i have:

#

{{states('sensor.battery_day_discharge')|float|round(0)+states('sensor.grid_active_power')|float|round(0) + states('sensor.input_power')|float|round(0) - states('sensor.grid_exported')|float|round(0)}}

#

except what that does is: battery_day_discharge + grid_active_power + input_power - grid_exported

silent barnBOT
#

@harsh patrol To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks. Here's an example

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

For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).

marble jackal
#

But 5 + 4 + 3 - 2 and 5 + 4 + (3-2) have the same result

deft timber
fringe dune
mighty ledge
fringe dune
topaz silo
#

how can i check if the last_updated of an entity is older than 2hrs from now?

#

So i can get the last_updated with {{ states.sensor.mi_11_battery_level.last_updated }} but i want to see how long ago that was, basically,

marble jackal
#

{{ now() - states.sensor.whatever.last_updated > timedelta(hours=2) }}

topaz silo
#

ok, wow, i didnt know that.. thanks a lot

#

my wife seems to have trouble keeping her phone charged... so i set up HA Companion app on it, so she can see its battery level etc, and i can notify her when it gets low

#

but sometimes she does not have the app running, and HA just shows "93%" or whatever, even though it was last updated like 20hrs ago

mighty ledge
#

that's going to happen

#

iOS also does other goofy crap like pop up messages that say "Are you sure you want this app to have access? click here to revoke" Etc

topaz silo
#

well now i can atleast show it in the HA UI's throughout the house, that her battery level has not updated in quite some time

mighty ledge
#

so if your wife is bad with tech, it's going to be a problem because of iOS.

#

I don't know if android does that, but it's a constant problem for me with my family with iOS

topaz silo
#

yeah, android tries to 'battery save' constantly

#

i even have the HA app set to 'autostart' and not locked to avoid battery saving etc.. but it still closes sometimes

#

really frustrating

topaz cave
#

Hi there, I'm having problems getting 'scan_interval' to work with a rest API call. I have the code in a rest.yaml file so could it possibly be a formatting issue?

  - resource: https://transportapi.com/v3/xxx
    scan_interval: 86400
    sensor:
    - name: Departures
      json_attributes_path: "$.departures"
      json_attributes:
        - "all"
      value_template: "ok"

Due to rate limits I only want the API to be called once a day, then use a button calling homeassistant.update_entity to trigger an update.

mighty ledge
topaz cave
#

Thanks @mighty ledge, will need to debug some more then.

unreal merlin
#

howdy ๐Ÿ™‚ can I get all plex media players with anything like integration_entities('plex')?

#

it looks like these are available in the core device registry with a plex identifier, but that above doesn't turn up much:

...
        "identifiers": [
          [
            "plex",
...
inner mesa
#

works for me

#

{{ integration_entities('plex')|select('match', 'media_player')|list }}

unreal merlin
#

I get a "[]" back in template dev

mighty ledge
mighty ledge
unreal merlin
#

yep

#

that the reason?

inner mesa
#

if you also do expand(), yeah

unreal merlin
#

yeah I expand - ok that makes sense

inner mesa
#

I get a total of three, so I imagine that any perf diff is in the noise

unreal merlin
#

trying to build a sensor that lights up when any of those clients are available - looks like that's gonna be much easier than I originally thought haha

inner mesa
#

since you have to do expand(), anyway

#

then you need to look at the state

unreal merlin
#

let me turn one on and see what's up that way

#

actually the server was off ๐Ÿ˜„

#

oh perfect, thanks folks, that solved it all

mighty ledge
#

that's a bug IMO

#

should show up regardless of state

analog mulch
#

Can anyone explain to me what the โ€œscopeโ€ of a Yaml anchor is: must it be within the same file, or even within the same key at the parent level. Secondly where does it end โ€” does it include everything that is on a level under the key in which it is defined, ie until it hits the next key on the same level?

charred dagger
#

It's per lline. The scope is from the definition onwards in the same file. It ends when the same anchor is redefined (which Hass yaml processor doesn't support IIRC).

#

And yes, the definition is for everything below the same level.

marble jackal
#

I use them mostly for my dashboard, for example so I don't have to repeat the config for all cards when I use lovelace-state-switch which was created by some genius ๐Ÿ˜‰

inner mesa
#

I use them for card_mod styles ๐Ÿ™‚

mighty ledge
#

You guys should use lovelace_gen...

#

no need for anchors

#

I use anchors for repeated triggers/entity lists in automations. I.e. the trigger has an entity_id list, which I use as a variable to do crap later.

#

Tbh Iโ€™m surprised neither of you use it. Itโ€™s basically โ€œuse jinja to write your configโ€

#

I wrote a whole autogenerated UI that builds my interface based on entity type and organizes each page nicely depending on the number of entities on screen

charred dagger
#

I like the GUI editor better.

mighty ledge
#

The nice thing for me is that I just add an entity to my lovelacegen config, reload, and the entity is in all the places I expect it to be

charred dagger
#

Does lovelace_gen even work now?

mighty ledge
#

Yeah

charred dagger
#

Cool. I really thought it didn't.

mighty ledge
#

Iโ€™ll maintain it if you abandon it

charred dagger
#

I'll keep that in mind.

#

It's definitely been on the back burner for a while.

mighty ledge
#

Yeah but it doesnโ€™t need any updates

#

I think I wrote the last 1 or 2 PRs that fixed things

#

Tbh I thought it would break with bdracos yaml loading changes but it worked without a hitch

charred dagger
#

That's what I assumed too.

#

I just thought the lack of upset people meant there were not that many users...

mighty ledge
#

Hahaha

#

I think there are more users than you think

#

Although mushroom cardsโ€ฆ. Make it less useful

#

In conbo with your auto entities

tepid onyx
#

๐Ÿ‘

marble jackal
ebon yoke
#

hi, is it possible to create a sum helper.. where i can add and subtract values from?

#

kind of like the shopping list, but all elements should be summed together

lean yacht
#

Hi, I'm looking for more documentation around the Jinja2 select('search', 'xxx') filter

#

I can find the default userdoc around select(), but it doesn't explain how to use the search...
Can I provide multiple values to have as OR statement ?

inner mesa
#

It's with the rest of the extensions

lean yacht
#

if you are referring to the pinned post, then I already looked at that... the select is described in 3 sentences, but the tests are not explained

inner mesa
#

Test string is search(find, ignorecase=False) will match the find expression anywhere in the string using regex.

#

The link in the channel topic

lean yacht
#

cna I do select('search', 'value1', 'value2' ) ?

inner mesa
#

No, but you make a regex for that

lean yacht
#

not that easy to use regex... I want to search for 2 specific mac addresses in a list

inner mesa
#

They're just strings

#

If I recall, it's just 'foo1|foo2'

lean yacht
#

I'll give that a try, thanks

mighty ledge
marble jackal
#

How would it look then?

sick ice
#

I've got this little template to tell me how many days since my utility meter reset. It increments after 24 hours. What I'd really like is for it to increment when it's the next day. How can I easily substitute the time of last_reset for midnight to achieve this?

{{(now() - state_attr('sensor.monthly_energy_offpeak','last_reset') | as_datetime).days | int }}

mighty ledge
#

here's my media player one

#

that shows media-players using the media-control card

#
  - type: custom:auto-entities
    card: 
      type: vertical-stack
    card_param: cards
    filter:
      include:
      - domain: media_player
        entity_id: '*_echo_dot*'
        options:
          type: media-control
      exclude:
      - state: standby
      - state: unavailable
      - state: 'off'
#

vertical-stack could be replaced with the entities card as well.

#

you can use auto entities to do anything, even combine it with layout card

#

which really isn't needed anymore but it's possible

#

So, you combine that with mushroom cards, entity field is auto populated on the cards

#

so you omit that from options

marble jackal
#

Ah, I'll dig into this after my holiday

mighty ledge
#

yah, take your time. Lemme know if you have questions. I doubt you will because once you see the yaml, it's straight forward.

marble jackal
sick ice
mighty ledge
#

you have to math it out if you want it from midnight

#

use today_at() to get midnight

sick ice
#

Oh, so you can't just substitute 00:00:00 from a datetime? I'll take a look at `today_at()' I haven't come across that yet.

mighty ledge
#

depending on what you want it could be as simple as replacing now() with today_at().

#

today_at() gives a datetime object

#

if you leave it blank, it returns midnight

#

if you provide a time, it'll give you that time of day

#

i.e. today_at('07:00') is 7am

sick ice
#

Just been mucking around in the template dev tool to understand this.

{%- set reset = state_attr('sensor.monthly_energy_offpeak','last_reset') | as_datetime %}
{{(today_at() - reset).days | int }}
{{today_at() - reset}}

returns

0
11:25:24.600799

It's getting close - I'd like it to be 0 if today_at() is the same day, 1 if the next and so forth.

sick ice
#

a-ha!

{%- set reset = state_attr('sensor.monthly_energy_offpeak','last_reset') | as_datetime %}
{%- set reset_day = strptime(reset.date() | string, "%Y-%m-%d") | as_local %}

{{today_at()}}
{{reset_day}}
{{(today_at() - reset_day).days}}
2022-08-24 00:00:00+10:00
2022-08-23 00:00:00+10:00
1
#

Accidentally edited this message in to oblivion ๐Ÿ˜ฆ

I'll try to recreate it...

entity.date() was what I needed. Then just had to change it to a datetime again.

mighty ledge
#
{%- set reset = state_attr('sensor.monthly_energy_offpeak','last_reset') | as_datetime | as_local %}
{{ (now().date() - reset_day.date()).days }}
sick ice
#

Sorry about that mess of editing. I turned off the PC, switched to mobile and somehow edited my message when I thought I was replying.

#

Gah, that is much nicer. Thank you. I will update my template:

      {%- set reset_day = strptime((state_attr('sensor.monthly_energy_offpeak','last_reset') | as_datetime).date() | string, "%Y-%m-%d") | as_local %}
      {{(today_at() - reset_day).days}}```
With what you've written.

I'm really learning coding as I'm going and as such I keep stumbling in to messy solutions. Much clearer in hindsight ๐Ÿ™‚
mighty ledge
#

you keep adding crap

#

you don't need to strptime anything

#

you have 2 datetime objects, you don't need to adjust anything.

#

Just this:

#
{%- set reset = state_attr('sensor.monthly_energy_offpeak','last_reset') | as_datetime | as_local %}
{{ (now().date() - reset_day.date()).days }}
#

as_datetime makes a datetime object

#

as_local takes the object and turns it into your timezone

#

strptime is redundant in your case.

sick ice
#

Yes, I was trying to show you what I ended up with, and saying that I will use your code now that I've seen it.

mighty ledge
#

strptime takes a string and turns it into a datetime object, which as_datetime already does

#

ah

sick ice
#

Just thought I'd share my end result before I shred it ha! I follow what you're saying completely. Thank you as always

#

So, now().date() and today_at() effectively provide the same output. Any reason to use one over the other? Does now cause the sensor to update often as now is constantly updating?

mighty ledge
#

no, now().date() returns a date, today_at() returns a datetime. Dates are just dates, Times are just times. Datetimes are dates and times combined.

#

there are plenty of reasons to use one over the other, it depends on what you're trying to do

#

now will cause the template to update once a minute

#

today_at would require you to add a trigger to your template sensor because it would only update when sensor_monthly_energy_off_peak updates

#

but that might update enough

marble jackal
#

now().time() returns a time (just for the sake of complemeness) ๐Ÿ˜œ

mighty ledge
#

and dates, times are not timezone aware, where datetimes are

sick ice
#

Ah, got it. That's all pretty intuitive with the naming then. I had it in my head that I needed to work with date times when subtracting dates or times. I see.

mighty ledge
#

lots of crap with times

sick ice
#

I found an epic community post on all things dates and times tonight but there's a lot to digest in it.

This is all because utility_meter can't take a fixed length billing cycle (28 days). So I've made an input_text for the billing cycle and an automation that resets the meters just before midnight. All I have to do is call the service at some point in the day and it will reset every 28 days there after.

I'm sure this is where I find out there was a heaps easier way...

mighty ledge
#

The guy who originally posted it made it when as_datetime, as_local, timedelta, and today_at didn't exist and he hasn't kept up with the times

#

he also doesn't know templates well but pretends he does

#

I'd take that whole thread with a grain of salt.

#

I'm not saying you can't learn something from it, but it's really outdated and it has bad information in many of the posts

sick ice
#

So you know the one I mean. There's useful basics in it for me all the same. One thing I've learned with HA is that post content gets deprecated very quickly and I'm always comparing what some post said, compared to the documentation.

#

Ended up finding .date() through the links within template documentation of course.

mighty ledge
#

it's the one by finity, correct?

sick ice
#

Yes, that's the one.

mighty ledge
#

Yep, then heed my warning ๐Ÿ˜‰

#

it's mostly copy/paste from other sources

#

think of it as 'word of mouth'

#

or the 'password' game

#

where one thing is passed to another and another, and you end up with something completely different

sick ice
#

Yep, understood. Good from far, but far from good.

mighty ledge
#

right

#

Your best resources for templates on the forums comes from a small list of people

sick ice
#

I'm sure I'll learn who they are with time. Still very new to this

mighty ledge
#

123, robcoleman (robc), thefes, myself, pdbruckner, and there's a few up and comers who are actually learning it instead of copy/pasting

sick ice
#

I already recognise a few of those

mighty ledge
#

I'm sure I'm missing names, but that's active people

#

there's another guy, I can't remember his name

#

also topics/questions from mariushvdb have alot of good information on templates in complex situations

sick ice
#

I'll take a look

half pendant
#

I have a tuya switch (connected through localtuya) that reports W, A and V as attributes rather than separate sensors. How can i make it into a kWh sensor so that i can add it to my energy dashboard.

mighty ledge
#

so you'll end up having 2 additional sensors

half pendant
#

how do i create a template extracting the attribute?

mighty ledge
#

you'd use state_attr('entity_id', 'attribute') replacing your entity_id and attribute

#

as the code

#

but all you need for the code is "{{ state_attr('entity_id', 'attribute') }}"

half pendant
#

Thanks!

half pendant
#

Managed to get the sensor working. Now what method for the Reimann helper do i use? Tried reading the docs but was unclear.

scenic ivy
#

Hi - Looking to create a template that tells whether the logged in user is on the home wifi or not. First step would be getting the user name in the template. To simplify the first step I am testing the below template but nothing seems to be working as expected and the documentation I can find is very limited though it seems it is possible to retrieve the user name.

How would I create an if statement like below where "user" is the current logged on user?

`binary_sensor:

  • platform: template
    sensors:
    user_on_wifi:
    friendly_name: User Wifi
    value_template:
    {% if user == 'Test1' %}
    true
    {% endif %}
    false`
inner mesa
#

the backend doesn't know who is logged in

#

you could have lots of people logged in

half pendant
inner mesa
#

"logged in" is a frontend thing

scenic ivy
#

that makes sense, so would have to happen on the front end... the end purpose is for use in a dashboard.

mighty ledge
#

just keep in mind that you'll only be able to see the user on the browser you're on. The other browsers will see what user is logged on there

#

so it's rather pointless as you can already see that information.

#

in the lower corner

inner mesa
#

several custom cards provide the ability to change behavior based on the user who's currently logged into that browser instance

mighty ledge
#

i.e. Me logged on device A will not be able to see who is logged into device B

scenic ivy
#

The end goal is for cameras. While on home wifi I want the camera card shown to be WebRTC as it is near real time. However this will not work off the network so then I want it to use the custom frigate card. So my thought was to get who is logged in, then check if their device (phone) is on the home network, then choose the correct camera card.

#

Thanks

marble jackal
#

You can use state-switch-card for that

#

Maybe combined with conditional cards

scenic ivy
#

I'll check it out, thanks

half pendant
mighty ledge
eager kettle
#

so I have a restful sensor for remaining time of battery charge, but when not plugged in it returns the value of unknown, I have tried searching the forums and web to change this to text of my choice, any ideas ?

silent seal
#

You need to set the availability template I suspect, but without seeing your sensor it's hard to say

tawny coral
#

Is it possible to create a sensor that has the lowest value of a one hour sliding window?

marble jackal
#

Yes, with a trigger based template sensor. Time pattern trigger on each hour to reset it to that value, and trigger on each state change of the source sensor, compare that to this.state and pick the lowest

eager kettle
#

https://hastebin.com/uxoxuhujif.swift this is the code, it basically gives me a time remaining for a charge, I just want to try to get the template to return (not charging or unplugged) instead of unavailble when the charge is not operating.

silent vector
#

Are the variables ('switches/trigger_switches') not dicts? switches.items()| it appears the error is saying it's not a dict
https://dpaste.org/Wsv3J

marble jackal
#

I would just write them as YAML, then it's a dict for sure

#

But I think the mult line format is making it a string

silent vector
#

Ah yes remove >-? That fixed it. The GUI automatically converts it to a yaml dict. After saving*

silent vector
#

I want to create a single script that handles persistent notifications. Is it possible to variablize actions because some notifications may have more than one action. Is it possible to variablize it so that a single action could be passed to a script or even 2 or 3? I assume it's possible as it's a list I'm just not sure how
Here's an example of what I'm referring to with more than 1 action in a notification https://dpaste.org/1QcfA

mighty ledge
#

it's the same as any other variable, you just have to build the list of information to pass it

#
actions: "{{ actions }}"
#

now it's a variable

silent vector
mighty ledge
#

it's a list of dictionaries

#

[{}, {}]

silent vector
#

Still a little confused. How would I convert what I sent for example to what you're saying? 2 separate actions

mighty ledge
#

right now you have 2 lists as a tuple

marble jackal
#

In your example you are creating separate lists, it should be only one list

#

You had this ([{}],[{}])

mighty ledge
#

no, he was missing the dictionary {}s

silent vector
#

So this?

{% set test = ['action: 22','test: true','action: 44','test: false'] %}
{{ test }}
mighty ledge
#

so he just had 2 lists of incorrect syntax

#

you're missing the dictionary indicators

marble jackal
#

Oh yeah, whoops

mighty ledge
#

{} -> dictionary

#

[] -> list

#

[{...}, {...}]

#

list of dictionaries

#

list -> [ item1, item2 ]

#

dictionary -> { 'key1': 'value1' }

#

now put them together with what you have above

silent vector
#
{% set test = {'action': '22','test': 'true'},{'action': '44','test': 'false'} %}
{{ test }}

Better?

mighty ledge
#

that might work, but it's not a list

#

that's a tuple

#

a tuple is ()

#

but tuples are special in that they are implied when you use a comma without the () surrounding the item

#

also, keep in mind that you're turning your numbers and booleans into strings

#

which is a separate issue

silent vector
#

I noticed that I wasn't sure if I needed it to be a string

mighty ledge
#

it can be whatever you want

#

the key needs to be a string

#

because that's what yaml requires

#

in normal circumstances, key's can be any object as well

silent vector
#

I see. So what would work for sure since you said "might" earlier lol

mighty ledge
#

make it a list of dictionaries

#

you're missing the list indicators

#

[]

silent vector
#
{% set test = [{'action': '22','test': 'true'},{'action': '44','test': 'false'}] %}
{{ test }}
mighty ledge
#

your ending ] is in the wrong spot

#

oh now it's in the right spot but you have an extra one

#

and now its fixed

#

your list...

{% set test = [{'action': '22','test': 'true'},{'action': '44','test': 'false'}] %}
               \-----------item1------------/  \----------item2--------------/
#

your dicts

{% set test = [{'action': '22','test': 'true'},{'action': '44','test': 'false'}] %}
                \-key1/         \k2/
silent vector
#

I fixed it lol. I was just copy and pasting from above. Alright perfect this should make creating these notification automations 10x easier.

#

Makes sense

mighty ledge
#

yep

#

should be good to go

#

but keep in mind

#

you don't need to do that for your variable

#

you can use yaml

silent vector
#

What should I do?

#

A yaml dictionary

mighty ledge
#

in your yaml, you're simply going to pass exactly what you would normally pass

#

your script will have:

actions: "{{ actions }}"
#

and your script data will simply be what you normally pass

#

using your example above....

#
service: script.my_notify_script
data:
  actions:
  - action: 22
    test: true
  - action: 44
    test: false
silent vector
#

I would pass that ^? It didn't occur that's the same thing as what I did.

mighty ledge
#

yep, it's the same

#
  • indicates a listed item
#

in yaml

silent vector
#

Learning a lot from Pepperidge farm

mighty ledge
#

when you have multiple lines that have key: value, it makes it a dictionary

#

so paring it with my examples above

#

this is a dictionary in yaml

#
key1: value1
key2: value2
#

a list...

#
- item1
- item2
#

so a list of dictionaries....

#
- key1: value1
  key2: value2
- key1: value1
  key2: value2
silent vector
#

Yep I didn't think about that. I remembered that for lists but I don't use dictionaries that often to remember they can be done in 2 different ways and are read the same.

#

Thank you for the additional explanation

mighty ledge
#

np

uncut fractal
#

Hi, I'm working on adding something like this project to my setup: https://community.home-assistant.io/t/screen-time-for-the-kids/452149
I've created the history stats as described in the post and created some helpers (toggle) to turn screentime on and off. I've also created a helper (number calles time_available_for_foo_this_week) with the available screentime for that week, during holidays that will be more and it can happen that I manually give them extra time, love to do that with an automation. I need some help for two things:

  1. When I look at the history stat, it could be that the total time is 1.75 -> how can I display that as 1 hour and 45 minutes.
  2. How can I display the amount of time that is left for that week or where can I calculate that -> so time_available_for_foo_this_week - time_used_by_foo_this_week
mighty ledge
#

also, post a screenshot of the entity on the same page that contains the time_available_for_foo_this_week

silent vector
#

I want the various variables to be {} when '' because I am trying to use a single service call to start the persistent notification and then a single to remove it. When removing a bunch of the variables will need to be {} but it seems my iif statements aren't working as I see in debug '' when it should be {}
https://dpaste.org/v7oFX

mighty ledge
#

it needs to be an empty list

#

[] without quotes

#

also, you don't even need to do that

#

just use chooses in your script based on the presence of the variable

#
{{ actions is defined }}
#

if you want it to dynamically add or remove actions if it's present or not, that's much harder to do and i'll have to write the code for you probably

silent vector
#

channel: "{{ iif(channel != '',channel,{}) }}" that didn't work. I'm doing something similar in an automation and '{}' works.

mighty ledge
#

well channel isn't a dictionary, is it?

silent barnBOT
silent vector
#

No. Just trying to get it to pass it. Seems to work for this. Just as data is {} when empty . Formatting is off there in the link. But it works.
https://dpaste.org/hPaEz

mighty ledge
#

@uncut fractal use a share site

silent barnBOT
#

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

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

mighty ledge
#
^
|
#

@uncut fractal your pastes don't include the state, which is the most important part

silent vector
#
- service: notify.mobile_app_daniels_s21
  data:
    message: "\"clear_notification\""
    data:
      tag: Garage

This is the alternative I'm trying to do in a single Service call. The rest of the variables will not be passed.

uncut fractal
mighty ledge
#

@silent vector what's a normal service call look like

silent vector
#

Then the clear notification service call is the one I just sent ^

velvet sigil
#

Hello,
could you please point me, why this secondary information doesn't work?

primary: PS5
secondary: |-
  {% if is_state('sensor.ps5_175_activity', 'playing') %}
  '{{ state_attr(''sensor.ps5_175_activity'', ''title_name'') }}'
  {% else %}
  '{{ states(''sensor.ps5_175_activity'') }}'
  {% endif %}```
silent vector
#
type: custom:mushroom-template-card
primary: PS5
secondary: |-
  {% if is_state('sensor.ps5_175_activity', 'playing') %} {{ state_attr(''sensor.ps5_175_activity'', ''title_name'') }}
  {% else %} {{ states(''sensor.ps5_175_activity'') }}
  {% endif %}

I think..

eager kettle
#

yep. tried to add some stuff to my restful sensor so it shows something else other than unavailable when its not showing time remaining and it justs , does not work lol oh weel there goes that idea

mighty ledge
#

@uncut fractal you'll have to make tempalte sensors.

template:
- sensor:
  - name: Time Used
    state: >
      {% set t = timedelta(hours=states('sensor.schermtijd_jinte_deze_week') | float) %}
      {{ t.seconds // 3600 }} hours and {{ t.seconds % 3600 // 60 }} minutes
    availability: "{{ states('sensor.schermtijd_jinte_deze_week') | is_number }}"
  - name: Time Remaining
    state: >
      {% set t = timedelta(hours=states('sensor.schermtijd_jinte_deze_week') | float) %}
      {% set r = timedelta(hours=states('input_number.beschikbare_schermtijd_deze_week') | float) %}
      {% set d = r - t %}
      {{ d.seconds // 3600 }} hours and {{ d.seconds % 3600 // 60 }} minutes
    availability: "{{ states('sensor.schermtijd_jinte_deze_week') | is_number }}"
mighty ledge
mighty ledge
silent vector
#

What does it say? To not 'work'?

velvet sigil
#

it just displays the whole if ... else statement as secondary information

#

not the status of that sensor

mighty ledge
#

are you sure that field accepts templates?

velvet sigil
#

yes

silent vector
#

Try >? It does accept templates
Instead of |-

velvet sigil
#

its a template card

mighty ledge
#

that doesn't mean that field accepts templates

#

the docs say that field accepts templates

uncut fractal
# mighty ledge <@779270819608133672> you'll have to make tempalte sensors. ``` template: - sens...

Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected '}', expected ')') for dictionary value @ data['sensor'][1]['state']. Got "{% set t = timedelta(hours=states('sensor.schermtijd_jinte_deze_week') | float) %} {% set r = timedelta(hours=states('input_number.beschikbare_schermtijd_deze_week') | float %} {% set d = r - t %} {{ d.seconds // 3600 }} hours and {{ d.seconds % 3600 // 60 }} minutes\n". (See /config/configuration.yaml, line 92).

mighty ledge
#

so it should work.

velvet sigil
#

it accepts, if i just put {{ state_attr(''sensor.ps5_175_activity'', ''title_name'') }} it will display titel of the game

mighty ledge
silent vector
#

And playing is a valid state? As in, in developer tools it's there?

eager kettle
#

I use this https://hastebin.com/uxoxuhujif.swift tells me how much time is left for charging ev battery, but when not plugged in I have been trying to get it to display disconnected or un plugged rather than unavailible

mighty ledge
#

yay backup

marble jackal
#

Mushroom template cards just show the template when it errors, try to fix it in devtools

silent vector
eager kettle
mighty ledge
#

i.e. what does it look like when it has 4 hours and 10 minutes

eager kettle
#

I tell you what ill plug it in now and tell you ๐Ÿ˜›

silent vector
velvet sigil
silent vector
#

Can you post to dpaste the developer tools section of this entity

mighty ledge
#

in your script use,

variables:
  passed_data: >
    {% set ns = namespace(fields=[]) %}
    {% if actions is defined %}
      {% set ns.fields = ns.fields + [ ('actions', actions) ] %}
    {% endif %}
    {% if persistent is defined %}
      {% set ns.fields = ns.fields + [ ('persistent', persistent) ] %}
    {% endif %}
    {% if sticky is defined %}
      {% set ns.fields = ns.fields + [ ('sticky', sticky) ] %}
    {% endif %}
    {% if tag is defined %}
      {% set ns.fields = ns.fields + [ ('tag', tag) ] %}
    {% endif %}
    {% if channel is defined %}
      {% set ns.fields = ns.fields + [ ('channel', channel) ] %}
    {% endif %}
    {{ dict.from_keys(ns.fields) }}
#

@silent vector

#

then in your notification

#

use

#
service: ...
data:
  message: ...
  data: "{{ passed_data }}"
#

just fill out the ... with whatever you were planning on doing

silent vector
#

Makes sense thank you. Not something I would have thought of. Maybe in a few more months something like that will come naturally

mighty ledge
uncut fractal
mighty ledge
#

๐Ÿ˜‰

mighty ledge
eager kettle
#

max number it goes too from empty is 4:15

mighty ledge
#

what's it look like at 0 hours?

#

0:00?

eager kettle
#

unavailble

#

gets to 0:01 then when it hits 0:00 it auto stops the charge in car so it becomes unavailible.

mighty ledge
#

right, but you aren't using the terms I like

#

so when it becomes unavailable, what does the actual attribute say

#

does it actually have the word unavailable?

eager kettle
#

yep

mighty ledge
#

can you show this to me, take a screenshot of the attributes in developer tools -> states page

#

use imgur

silent barnBOT
#

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

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

mighty ledge
#

I'm very confused by your statements vs your code, so I'm having trouble trusting what you're saying.

#

your code is looking for the letters H and M, and then you change the result to be 00:00

#

however you're telling me that the information coming out of states.sensor.peugeot_308_hybrid.attributes["energy"][0]["charging"]["remaining_time"] is already in the HH:MM format.

#

so, either your code never worked, or you're not telling me the correct information

eager kettle
#

took screen shot of why on, just shooting downstairs to disconnect

mighty ledge
#

ok, so you're not telling me the correct information

#

my man, i'm not asking about your template sensor.

#

I'm asking about sensor.peugeot_308_hybrid

#

in order to fix your template sensor, I need to see sensor.peugeot_308_hybrid

#

not your template sensors state.

eager kettle
#

ok sorry bud, my bad here you go

#

its the whole car, energy 0 is battery, energy 1 is the combustion engine

mighty ledge
#

ok, sorry to ask this again, but can you plug it in and show me the attributes when it's plugged in?

#

specifically, I need to see the format of this field

eager kettle
#

no need to be sorry, you are trying to help

#

remaining_time: PT3H30M

mighty ledge
#

thanks

#

last thing, can you post your whole yaml for the template sensor?

eager kettle
mighty ledge
# eager kettle https://hastebin.com/gabupeyiko.yaml
      308_hybrid_remain_time:
        friendly_name: "remaining charging time"
        unique_id: "r3ma1n1ngcharg1ngt1m3"
        icon_template: "mdi:timer-outline"
        value_template: >
          {% set battery = state_attr('sensor.peugeot_308_hybrid', 'energy') | first %}
          {% if battery.charging.remaining_time %}
            {{ strptime(battery.charging.remaining_time, 'PT%HH%MM').strftime('%H:%M') }}
          {% else %}
            Not Charging
          {% endif %}
        availability_template: >
          {{ states('sensor.peugeot_308_hybrid') not in ['unknown', 'unavailable'] }}
eager kettle
#

replaced and rebooting now yo try

mighty ledge
#

you don't need to reboot

#

reload templates

#

developer tools -> yaml -> check config, then if passes, click reload template entities

eager kettle
#

lol really all this time i thought if its in config and changing reboot lol

mighty ledge
#

you almost never have to reboot

#

at most you'd have to restart

#

reboot = reboot hardware

eager kettle
#

soz restart lol

mighty ledge
#

there's 3 levels to HA

#

reboot = rebooting the hardware
restart = restarting home assistant (hardware stays on)

#

and reload = reloading a configuration (home assistant and hardware stay on)

eager kettle
#

HA the never ending learning curve ๐Ÿ™‚ not a bad thing.

#

100% bud, thank you again

#

state disconnected.... now not charging ๐Ÿ™‚

mighty ledge
#

np

eager kettle
#

its also valuble help if I change car in future as I will base template off of current one if it reports null unplugged.

mighty ledge
#

most cars don't have this kind of thing

#

I wish I could link up to my cars

eager kettle
#

its quite crazy what info some of the intergrations can get, I would say the bmw and vw ones are more in depth (windows, dooors, locks etc).

#

the peugeot one is sketchy, the location one is down (not intergration, but peugeots own as even official app shows my car at home when I am 100 miles away lol).

#

so for now I have the tronity added which allows me to use the tracker still as well as log trips on map card for tracking side of things

velvet sigil
mighty ledge
#

you don't need to escape your quotes in the template editor, only have 1 in each spot

#

'' = escaping your quotes

#

' non escaped quote

velvet sigil
#

If I put this in {{ state_attr('sensor.ps5_175_activity', ''title_name'') }} i receive TemplateSyntaxError: expected token ',', got 'title_name'

mighty ledge
#

so what do you notice?

silent vector
#

Because you're using 1 ' and 2 '' 1 or the other you can't mix inside the template.

eager kettle
mighty ledge
#

I'm sure I would, but then I have to buy that and pay for it

silent vector
velvet sigil
#

thanks that worked

silent vector
#

Thanks to petro and a few others (TheFes, etc.) over the last few months I'm learning enough to actually be able to help lol.

eager kettle
#

on my older car it needed a dongle for net pulls, but over here in uk the network 3 used to offer a data pay as you go sim that even if you did not top up they still gave you 600mb data a month more than enough... anyway thank you I wont take the chat off template talk anymore. Thanks for your time again.

velvet sigil
#

One more question.
Will this construct work to put an image instead of icon if condition is met?
Like this

  {% if is_state('sensor.ps5_175_activity', 'playing') %}
  {{ state_attr('sensor.ps5_175_activity', 'title_image') }}
  {% else %} 
   mdi:sony-playstation
  {% endif %}```
mighty ledge
silent vector
#

Even when mixing icons and pictures?

mighty ledge
#

it depends on the mushroom card

#

if you can use an image for the mushroom card in the icon field, then you can do it

#

if you can't, then no

#

this of course assumes you can template that field as well

silent vector
#

No you can't. You need picture for a picture. It only takes icon as far as I know. You can template in picture I use it all over. But I tried using picture in icon in a template and found out you can't mix. Picture is solely for url

mighty ledge
#

ah, ok then no you can't

eager kettle
#

a year later they done another promo for 250mb one and that ran out after a week they have not done it again, but I kept both sims as they still work.

silent vector
#
type: horizontal-stack
cards:
  - type: custom:mushroom-template-card
    entity: switch.printer
    primary: Printer
    secondary: '{{ states(''switch.printer'') | title }}'
    picture: >
      {% set status = states('switch.printer') %} {% if status == 'on' %}
      local/icons/custom_icons/plug.png {% elif status == 'off' %}
      local/icons/custom_icons/plug-off.png {% endif %}
    hold_action:

@velvet sigil that's one way you can template pictures only in a mushroom template card though

silent vector
#

I could do an if else.

#

And I think use entity

marble jackal
#

All Mushroom cards support pictures

silent vector
#

entity_picture yes but not picture

marble jackal
#

You need to set icon_type to picture

#

And then set the picture url in the icon field

silent vector
#

Pretty sure you can't I just tried. I remember asking the dev.

#
type: horizontal-stack
cards:
  - type: custom:mushroom-cover-card
    entity: cover.bedroom_shades
    icon_type: picture
    icon: local/icons/custom_icons/light-bulb-off.png
    name: Daniels
#

That doesn't work ^

marble jackal
silent vector
marble jackal
#

Ah, you mean like a picture card

marble jackal
silent vector
velvet sigil
marble jackal
#

Well, seems clear what you should use then

#

@silent vector it should indeed be entity_picture

velvet sigil
#

yeah, but its useless for me as the idea was to replace an image on condition

silent vector
#

If there's only a few images you could just save them and pass them as urls. But you can't mix icons and pictures as far as I know. you would need to make the icon a picture too.

velvet sigil
#

I guess the images are passed as urls as a state of attribute

silent vector
#

That would be the only way for it to show an image. Show the dev tools. It is likely a url

marble jackal
#

Aaah, right, I finally see what you mean. You can't provide the picture, it already needs to be provided in the entity config

silent vector
#

I wish I was wrong though I would love to use pictures everywhere at the card level not customizations

#

I still think you can use pictures @velvet sigil if the title_image is a url. But you can't use the icon mdi: .. you will need to make that an .png to use both the way you intended.

velvet sigil
#

this works

  {% if is_state('sensor.ps5_175_activity', 'playing') %}
  {{ state_attr('sensor.ps5_175_activity', 'title_image') }}
  {% else %}
  /local/icons/custom_icons/PlayStation-logo-1994.png
  {% endif %}```
silent vector
#

There you go

velvet sigil
#

great, thank you all for help

gentle zealot
#

Hello all. I had a template break on one of the new updates. I have done some research and trial and error but can not get it to work again. not sure what needs to be changed to get this working again. This was to calculate the rain rate from a rain input from my weather station.

state: >-
    {% if ((states.sensor.atlas_rain.state|float) - (states.sensor.rain_10_minutes_ago.state|float)) > 0 %}
      {{ (((states.sensor.atlas_rain.state|float) - (states.sensor.rain_10_minutes_ago.state|float))*6) }}
    {% else %}
      0
    {% endif %}
marble jackal
#

You should use states('sensor.foo') instead of states.sensor.foo.state and you should add defaults to your float filters

#
state: >-
  {{ [0, )states('sensor.atlas_rain') | float(0) - states('sensor.rain_10_minutes_ago') | float(0)) * 6] | max }}
#

Or add availability in case of a template sensor:

state: >-
  {{ [0, (states('sensor.atlas_rain') | float - states('sensor.rain_10_minutes_ago') | float) * 6] | max }}
availability: >-
  {{ states('sensor.atlas_rain') | is_number and states('sensor.rain_10_minutes_ago') | is_number }}
gentle zealot
#

that gives me a value but incorrect. I should explain more the sensor.atlas_rain is the value from weather station. I need to subtract the value of sensor.atlas_rain that was recorded 10 minutes ago by current value.

marble jackal
#

You have so many unneeded parenthesis that it's hard to figure out what you are actually trying to calculate

marble jackal
gentle zealot
#

with the old way i had it it take rain input - rain input reading from 10 mins ago then multipled that number by 6 to give estimated rain rate per hour

marble jackal
#

That's what my example does as well

#

It makes an array with 0 and the result, and takes the highest value of those two

marble jackal
gentle zealot
#

@marble jackal it should give me a value of 0 at the moment since its not raining . I get 19.85 with first example you gave me. My weather station does an incremental reading so if i have a reading of 4.45 now and it rains .20 inches the reading will increase to 4.65. that why i need to subtract the 2 readings to get the rain amount then multiple by 6 to get in/hr. i hope i am relaying this right.

marble jackal
#

So what are the values of both sensors are this moment

gentle zealot
#

3.33 is the reading of sensor.atlas_rain. sorry the value with the template is 19.98 not 19.85

#

that makes since 3.33 *6 is 19.98. it looks like it is not finding the value at 10 mins in the past. how do i get the reading of sensor.atlas_rain 10 minutes ago. is there a template to get the value 10 minutes in the past

marble jackal
#

Aaah, I was under the assumption you already had a sensor for that

#

Did you just make sensor.rain_10_minutes_ago up?

#

If this sensor doesn't exist, your previous sensor might have worked, but never gave the correct result

#

It just always defaulted that to 0

gentle zealot
#

i have a sensor it uses influxdb for stats. here is the example.

- platform: influxdb
  host: 123454-influxdb
  port: 8086
  database: xxxxx
  queries:
    - name: Rain 10 Minutes Ago
      unit_of_measurement: in
      value_template: "{{ value | float }}"
      group_function: first
      measurement: '"autogen"."in"'
      field: '"value"'
      database: homeassistant
      where: 'time > now() - 10m AND "entity_id"=''atlas_rain'''