#templates-archived

1 messages · Page 155 of 1

marble jackal
#

But you could have it display something like none or you'll have to walk or whatever

clever dawn
#

haha nice

marble jackal
#

Well depends, if you only need these times, you don't need the attributes at all

clever dawn
#

as I said, time is the only variable that changes, the route # and destination will be the same each time, so why pull them

marble jackal
#
- platform: rest
  name: Bus Times
  resource: https://transperth.maxrumsey.xyz/api/v1/busTimes?stop_number=18418
  value_template: >
    {%- set buses = value_json.buses %}
    {{ buses | map(attribute='time') | join(', ') if iif(buses) else 'no buses' }}
#

or:

- platform: rest
  name: Bus Times
  resource: https://transperth.maxrumsey.xyz/api/v1/busTimes?stop_number=18418
  value_template: >
    {%- set buses = value_json.get('buses', []) %}
    {{ iif(buses, buses | map(attribute='time') | join(', '), 'no buses') }}
clever dawn
#

Tried your first piece of code and it pulled the last 2 stop times for the night

#

Perfect, thanks!

marble jackal
#

last one is most error proof

clever dawn
#

OK, will use that instead

#

Worked like a charm, and updates every 30 seconds. Thanks again.

marble jackal
#

No problem

torn meteor
#

here's a tricky one. i need a wait_for_template that works with now()

#

{{ trigger.to_state.state == now().strftime("%Y-%m-%dT%H:%M:%S-04:00") }}

#

wait... maybe i'm a dummy

#

i thought it was failing because the wait template doesn't 'tick' for anything but entities. it's not going to check every second, for instance

#

yeah even if i change the trigger.to_State to the sensor.state, it's still a static value, which doesn't change

#

so the question is: how do i have a wait trigger fire when the current time equals a static time?

tepid onyx
#

from your question, do you need a wait trigger? would a template trigger work? value_template: "{{ states('sensor.time') == '00:00' }}"

torn meteor
#

template trigger is fine, but it sounds like i still need a sensor that updates every second reporting the time

#

i can't use now()

tepid onyx
#

why

torn meteor
#

because it's not a real sensor

#

there's not state change happening on now() afaik

buoyant pine
#

It would be evaluated once per minute

torn meteor
#

hmm, not accurate enough. going to try the date_time sensor integration... does that update every second?

tepid onyx
#

you want it to evaluate every second??

torn meteor
#

... it's not ideal i know.

#

but Alexa Media Player timers don't give me much of a choice

#

all they do is set the timestamp when the alarm will go off. there is NO state change on the thing when the alarm is actually ringing

buoyant pine
#

You could make an automation that updates an input_datetime with the timestamp and use a time trigger for the main automation

tepid onyx
#

maybe pastebin your script/automation so people can see what you're trying to do

torn meteor
#

the main trigger on the automation is the # of timers on the device going from 0 to 1

torn meteor
buoyant pine
#

There is no frequency check. It will just trigger at whatever time the input_datetime is at

#

And the trigger will update itself whenever the input_datetime is changed

tepid onyx
#

or use an event on sensor.library_dot_next_timer both ideas would work

torn meteor
#

hmm ok. thanks 🙂

buoyant pine
torn meteor
#

ok now i need help getting a valid timstamp out of alexa's format: 2022-03-29T18:39:54-04:00

#

i think it's iso..

#

oh hey. as_timestamp for that string just works. nice.

fossil venture
mighty ledge
#

It’s the python dictionary way of supplying a default

#

Same as value_json.buses | default([])

warped path
#

hey all just starting messing with UI lovelace Minimalist. I believe I got everything installed. but trying to configure a card as a test and always seem to be getting template is missing error?

Button-card template 'card_graph' is missing!

tepid onyx
#

use lovalace normal 😜

#

there's 3 templates there that might work

#

says it's legacy, so good luck. I did a search

#

actually says card_graph should work and 3 variables/entities , dunno legacy stuff why not use the UI that's intended

marble jackal
sacred sparrow
#

{{ states('sensor.nas_throughput_upload')|float < 50 }} how do I make it when the state is under 50 for 20 minutes? in a wait template

winter sleet
#

I'm trying to program an ofset for my Aqara humity sensor. I've tried the template below (both with single ' and double " ) and I can't get it to work 😦

Any tips?

  • platform: template
    sensors:
    humidity_sensor_offset:
    value_template: '{{ states('sensor.temperature_sensor_humidity') | float + 1}}'
    friendly_name: 'humidity'
rose scroll
winter sleet
#

Ok, so basically 2 sets, single inside, double outside

#

Could you write it out for me, do I'm sure I get it right?

rose scroll
#

"{{ states('sensor.xxx') | float + 1 }}"

#

Should consider also setting a default value for float, in case the state is not a number.

winter sleet
#

I tried exactly this (double qoutes outside, single around the sensor) and it didn't work

#

You can see why I am so confused

rose scroll
#

Try putting that jinja into Developer Tools > Template. What error do you get?

floral shuttle
#

counting domain entities light, that should not be groups, so contain attributes 'entity_id' or contain attribute 'lights' (for the Hue groups), I cant get the reject filter right. {{states.light |rejectattr('lights')|rejectattr('entity_id')|list|count}} 'lights' does nothing, and 'entity_id' filter them all 😉

floral shuttle
#

wait, this is is I believe:{{states.light |rejectattr('attributes.lights') |rejectattr('attributes.entity_id')|list|count}} .....

floral shuttle
#

and yet there's this Warning:```Template variable warning: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'lights' when rendering '{{states.light
|rejectattr('attributes.lights')
|rejectattr('attributes.entity_id')|map(attribute= 'name')|list|count}}'

marble jackal
#

It will also give you this warning if you put it in developer tools, because the are lights without those attributes

#

It's only a warning though, the template will do what it should

#

If you really don't want warnings in your log, you can use a namespace and a for loop.

mighty ledge
marble jackal
mighty ledge
#

🤷‍♂️ I don't know if it's documented

#

if it is, it would be under 'tests'

floral shuttle
#

btw:```
2022-03-30 13:19:45 WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'lights' when rendering '{{states.light
|rejectattr('attributes.lights')
|rejectattr('attributes.entity_id','defined')|map(attribute= 'name')|list|count}}
{{states.light
|rejectattr('attributes.lights')
|rejectattr('attributes.entity_id','defined')|map(attribute= 'entity_id')|list}}'

#

and yet the result is perfect....

#

o wait... my bad, forgot the 'lights'... nvm me

marble jackal
floral shuttle
mighty ledge
#

Warnings don't show up in the template editor, only errors

#

warnings -> logs, errors -> template editor & logs

#

it's pretty annoying tbh

floral shuttle
#

yeah, that s why I always have a second window of the same instance open with the logviewer addon

mighty ledge
#

I just roll with logexpert

#

but I do everything from a windows box

floral shuttle
#

dont know that, is that also a HA addon?

mighty ledge
#

no, it's a windows software that tracks rolling logs

#

like baretail, but more customizability and not 7899852834 years old

floral shuttle
mighty ledge
mighty ledge
floral shuttle
#

it's just that the entities weren't created by that integration(now back up and running) and because of that, the automation couldn't be set up. I guess it would happen with any non-existing trigger entity_id? I would have hoped some condition (is not none) to prevent that, but apparently not

#

{{states.sensor.not_exist}} returns 'null' in dev tools, and in States, no column is populated at all. This time, there's nothing in the logs either....

mighty ledge
#

because the states machine has guards against that

#

if you add .state at the end, you'd get an error

floral shuttle
#

right. and {{states('sensor.not_exist')}} renders 'unknown' ofc, so maybe I can add that to the conditions

#

trigger.to_state.state not in ['unknown,'unavailable']

mighty ledge
#

the reason you're getting the error is because of the order you're doing things

#

order of operations matter

#

your first condition should be:

        {{trigger.to_state is not none and
          trigger.from_state is not none and
          trigger.to_state.state != trigger.from_state.state}}
#

not the second

#

and functions and or functions in code resolve left to right, and if in a list, first to last

#

For and, every statement must resolve true. As soon as something resolves false, it bails out with False

#

for or, any statement must resolve true, as soon as something resolves true, it bails out with true

#

this is true for every single language that exists

#

and it's true for home assistant conditions

floral shuttle
#

I understand that yes. the reason I put the is_number() first was that seemed the quickest and shortest test available to see if the input was valid. And tbh, It cant have passed that, so why would the automation considered the rest at all? Put differently, why would it make a difference in this case? Not a number? halt.

mighty ledge
#

you're accessing the trigger object first in that

#

unsafely

#

objects also resolve left to right

#

trigger.x.y

#

trigger resolves first, then x, then y

floral shuttle
#

ok, well, Ive adjusted all automations. just for testing purposes will create a new one with a non existing trigger entity, and the same conditions to see what gives at automation reload.

#

nope, that order wasnt the reason, I get the same warning for 2 new automations on a non existing entity, both with my original order, and the changed order in your instruction

mighty ledge
#

Then it's beyond your control

floral shuttle
#

Error initializing 'Marijn bijna thuis tester 2' trigger: In 'numeric_state' condition: unknown entity sensor.here_marijn_huis. Meaning there is some check in place before the actual conditions are processed, and we can not influence that

#

crosspost...

mighty ledge
#

I didn't realize you're getting the error on reload, I thought you were getting it during execution

floral shuttle
#

yet this feels like an issue. Ill post it as such in the tracker so to see what the dev team says

mighty ledge
#

it's not an issue

#

your entity should exist

#

otherwise the automation is doing nothing

#

This is why things like that 'set state' python script are work arounds and shouldn't be used

floral shuttle
#

just to be clear, this was of a faulting core integration, not one of my Python contraptions....

#

But I guess you're right, the warning does exactly what it should do, warn us for an invalid / unknown entity... back to templates 😉 thanks!

mighty ledge
floral shuttle
tired kindle
#

Hi everyone,
Does anyone know a way, or a guide to control what entities are displayed on a lovelace using templates?
I'm trying to avoid extra bloat using automations to control helpers, or creating extra entities in the config.
For Example:
I have my son's bedroom light, I know I can use
{% if now().strftime('%T') > strptime('20:30:00', '%T') %}
to compare now to 8:30pm.
But I'm not sure how to then say only show the entity on the card if now>8:30pm

rose scroll
# tired kindle Hi everyone, Does anyone know a way, or a guide to control what entities are dis...

#frontend-archived would probably suggest some solutions, first of which is the conditional card and not far behind being custom:state-switch. Both would require you to put your template into a template sensor then use the state to determine whether a card displays or not.

Why do you want to avoid more helpers? In this case, I think the helper could save you a lot of copy pasta, as you can control the display of multiple cards based on one helper's state, rather than having to reproduce the template logic in every card.

tired kindle
# rose scroll <#460846676358332417> would probably suggest some solutions, first of which is t...

Well my ultimate goal was to create a lovelace that is frequent tasks.
Usually around 8:30 my son needs to go to bed, so only display the button when his light is on in that window
Usually shortly after the tv turns on, so only display the tv if it's off in that window
exc exc
I've got my automations of course, but sometimes I still want a "yes proceed"
I was trying to avoid bloating the system and possibly confusing myself with countless helpers

tired kindle
crude heart
#

Is it possible with a fan template to get fan speed not as a percentage in UI? I have a 7 speed fan, and would like to see 1, 2, 3, 4, ... instead of 14, 29, etc..

tired kindle
crude heart
#

@tired kindle I saw that, and tried a few things with it, but couldn't seem to get it to do what I wanted.

mighty ledge
crude heart
mighty ledge
#

it is for fan speed, it's for whatever you want it to be

#

that's how you'll get a dropdown with 7 speeds

crude heart
#

I guess I'm not looking for a drop down, but to just display speed in a different means than as percentage

rose scroll
#

Or would you consider graphically representing the speed? I use custom:slider-button-card to display the fan speed percentage as a bar chart. It is quite neat and intuitive!

crude heart
mighty ledge
crude heart
mighty ledge
#

The template will be very similar to what I linked above

#

and it's missing the set_number action list.

#

which would be a service call that uses value to set the value of your fan with a fan.set_percentage service call

crude heart
mighty ledge
#

that example is showing you the yaml, you do not want to use the code

#

you want to use the code from the previous example

mighty ledge
#

template = jinja tempate, i.e. the code

#

not the yaml

#

read pin 3 to figure out the differences between jinja/templates and Yaml

crude heart
#

@mighty ledge sorry, I'm now confused by the references. Which example should I be looking at?

mighty ledge
#

they both have relevant information

#

the 2nd example is showing you the yaml for an template number. The 1st example has the templates that you can use and alter for your template number.

#

template number is the integration.

#

templates, as in this channel, refer to jinja templates

#

which are not to be confused with the template integrations

#

which is what you're doing

#

read pin #3 on this channel to understand the differences between templates & yaml (template integration)

#

then combine the 2nd examples yaml (template integration for number), with code cherry picked from the 1st example (the template/jinja code)

crude heart
#

Can you repost to the link to the 1st example

thorny snow
#

Hey

#

I want to round my values in weather forecast

#
show_forecast: true
type: weather-forecast
entity: weather.home
secondary_info_attribute: humidity
``` how do I see the attributes to control
mighty ledge
thorny snow
#

Ah!

#

How do you suggest doing it

mighty ledge
#

There really isn't a way to format the numbers in that card. You'd have to make something custom or use a custom card.

thorny snow
#

I went from this:

to this:

      {% if value > -20 and value < 125 %}
        {{ value }}
      {% else %}
        {{ states('sensor.patio_temperature') }}
      {% endif %}

and now all states are unknown...

#

what did I do wrong??

#

The sensor it came from looked like this:

#
  - platform: mqtt
    name: "Patio Temperature"
    state_topic: "/rtl_433/1/temperature_F"
    unit_of_measurement: 'F'
    value_template: "{{ [value|round(1)|float, 125.0]|min }}"
mighty ledge
thorny snow
#

create yet ANOTHER sensor?

mighty ledge
#

well, do you want a working sensor or do you want to chase templating errors for hours?

#

If that first one is a template sensor, I'd just remove it for the filter sensor

thorny snow
#

no, it's an MQTT sensor

#

I am just trying to suppress the spurious readings

mighty ledge
#

yes, then use the filter sensor

thorny snow
#

and they end up being 125F which is still nonsensical when it's 50F outside

mighty ledge
#
sensor:
- platform: filter
  entity_id: your_mqtt_entity_id
  filters:
  - filter: range
    lower_bound: -20
    upper_bound: 125
#

no template, just yaml

#

that might not be what you want, but you can use the outlier filter instead

#

to ensure that there aren't any crazy temperature jumps from erroneous readings

crude heart
# mighty ledge here

I feel like I'm so close with:

template:
  - number:
    - name: "Kumar Fan Speed"
      unique_id: kumar_speed
      state: "{{ (( (state_attr('fan.office_fan', 'percentage')) / state_attr('fan.office_fan', 'percentage_step'))) | round | int}}"
      min: 0
      max: 7
      step: 1
      set_value:
        service: fan.set_percentage 
        target:
          entity_id: fan.office_fan
        data:
          percentage: "{{ states('number.kumar_fan_speed') * 14.28 | int }}"
#

I get:

thorny snow
#

Ok, so I end up with ```
sensor:

  • platform: mqtt
    name: "Patio Temperature"
    state_topic: "/rtl_433/1/temperature_F"
    unit_of_measurement: 'F'
  • platform: filter
    entity_id: sensor.patio_temperature
    filters:
    • filter: range
      lower_bound: -20
      upper_bound: 125
crude heart
#

[homeassistant.helpers.script.kumar_fan_speed] Kumar Fan Speed: Error executing script. Invalid data for call_service at pos 1: expected int for dictionary value @ data['percentage']

mighty ledge
thorny snow
#

150?

#

F?? 😄

mighty ledge
mighty ledge
#

I have no idea why you'd apply a filter to a temperature

#

but you're trying to do it

thorny snow
#

because I am trying to suppress spurious readings

#

I often get a 240F reading

crude heart
mighty ledge
#

Ok, so when you get 240F, your filter will be 125, is that what you want?

#

I'm pretty sure the answer is no

thorny snow
#

no, that's the same result as the original template

mighty ledge
#

which is why you'll probably want outlier

thorny snow
#

i just want to ignore value from out of bounds and use the previous

mighty ledge
#

Yes, outlier

mighty ledge
thorny snow
#
  - platform: mqtt
    name: "Patio Temperature"
    state_topic: "/rtl_433/1/temperature_F"
    unit_of_measurement: 'F'
  - platform: filter
    entity_id: sensor.patio_temperature
    filters:
      - filter: outlier
        window_size: 5
        radius: 10.0
#

ok, given the above, I am looking at the last 5 states (minutes in my polling case) and alllowing the F to change 10F within that time?

mighty ledge
#

that will replace the outlier - removed value with an average of the last 5 values

thorny snow
#

oh, it keeps the outlier instead of removing it?

#

"The Outlier filter (outlier) is a basic Band-pass filter, as it cuts out any value outside a specific range."

mighty ledge
#

it replaces the removed value with an average of your window size

#

continue reading the paragraph

thorny snow
#

OH.. so it keeps it, but makes it averaged?

#

that works....

mighty ledge
#

"The included Outlier filter will discard any value beyond a band centered on the median of the previous values, replacing it with the median value of the previous values. If inside the band, the current state is returned."

thorny snow
#

reading is fundamental

mighty ledge
#

personally, i'd just keep the window_size to 1

thorny snow
#

I am trying to read and undertand 😄

mighty ledge
#

you aren't going to have a 10 degree change

thorny snow
#

right....

#

it's entirely possible in 5 minutes

#

it's based on the window, right?

mighty ledge
#

yes

thorny snow
#

couldn't the temperature crawl outside the window if its replaced with a median?

#

I mean it is possible to change 10F in 5 minutes

#

rain, etc....

#

and if the returned values are constantly outside the window at that point, replacing with the mean as the temp continues to drop will result in mean values, not actual

#

so what's the fix, increase the radius?

#

the weather is crazy here sometimes

#

what if the last 5 readings are outside the window

mighty ledge
#

you think your temperature is going to change 10F over 1 minute?

thorny snow
#

no, over 5

mighty ledge
thorny snow
#

Thank you Petro, I'll see how it performs.

crude heart
# mighty ledge np

Is there somewhere in the docs that mentions to use of value variable?

tepid onyx
#

{{ media_players | first if media_players | length > 0 else none }}

#

i'm guessing first selects the first in the list here. Is there any documentation on this anywhere?

silent barnBOT
mighty ledge
tepid onyx
#

ah so it's shorthand for loop.first ?

mighty ledge
#

it's "If the there are media players, choose the first media player, otherwise choose none"

tepid onyx
#

got it thanks

vast juniper
#

guys any ideas why I'm getting Unexpected scalar at node end YAML here : {{ states('sensor.anniversary_saule_days_old')|int /7 |int | round(0, "floor",default)}}

rose scroll
earnest cosmos
#

I was hoping this would work for displaying state via the icon for a motion sensor in a picture-glance Lovelace card.

  - entity: binary_sensor.cam_terrasse_ost_motion
    name: Motion Sensor
    icon: |
      [[[
        if is_states('binary_sensor.cam_terrasse_motion', 'on')
          return mdi:motion-sensor;
        else
          return mdi:motion-sensor-off;
        endif
      ]]]
#

This setup show no icon, removing the icon: section reveals the icon, but it is static, not state dependant. What am i missing here?

inner mesa
#

I don't see anything in the docs that says that it supports a template there

earnest cosmos
#

Well, at least that´s good news; It´s not possible, then 😉

#

I took a shot, though

inner mesa
#

Also, you have a mix of jinja and JavaScript in there, so it wouldn't work as is if it did

earnest cosmos
#

Same syntax works for label: in a custom:button-card, so I was just testing

#

Any suggestions how I can make the motion icon change eg. color in the picture-glance Lovelace card?

marble jackal
#

This also works {{ 'test' | round(3, 'floor', 'no number') }}

vast juniper
rose scroll
#

I see, good to know!

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.

marble jackal
#

You still do not provide what the default is. you have only default, this should be default=something

#
  - platform: template
    sensors:
      baby_weeks:
        friendly_name: "Baby Weeks Old"
        value_template: "{{ states('sensor.anniversary_saule_days_old')|int /7 |int | round(0, 'floor')}}"
        availability_template: "{{ states('sensor.anniversary_saule_days_old') | is_number }}"
        icon_template: mdi:baby
#

If you add availability_template like this, there is no need for default. And you need to differentiate the quotes inside your template and outside it (double quotes outside, single quotes inside, or the other way round)

#

The quotes were your main issue

#

{{ 'test' | round(3, 'floor', default) }} this will just return nothing (as there is no default provided)

vast juniper
marble jackal
#

This will break the template like this {{ states('sensor.anniversary_saule_days_old')|int /7 |int | round(0, // floor // )}}

#

if you add default without providing what the default is, the default will be none

vast juniper
marble jackal
#

If it is not providing a number (eg unavailable which is probably the case just after a reboot) the template sensor will also be unavailable

#

BTW congratulations with the baby 🙂

vast juniper
marble jackal
#

@vast juniper you did rount it, by using round(0, "floor") I took that from your code

#

oh wait

#

it didn't round, that's because you should it only rounds 7 now

#

BTW, I guess int will be fine here, as your are using floor, so: "{{ ( states('sensor.anniversary_saule_days_old') | int / 7 ) | int }}"

#

int and round(0, 'floor') have the same result

#

But brackets around the total formula are needed if you want to round the formula result. Filters are applied first in the order of operations

tepid onyx
marble jackal
tepid onyx
#

got it thanks, I'm still learning 👍

vast juniper
tepid onyx
marble jackal
# vast juniper Thanks alot for your help, this templating is above my current understanding 😩

It's quite basic though. What you need to know is that the state of an entity is always a string. So text. An integer is a number without decimals (eg 5), a floating point number is a number with decimals (eg 5,7)
| int converts something to an integer (if possible) and | float to a floating point number.
| is used for filters, and filters are always applied first (from left to right if more are entered)

vast juniper
#

I will play with it more when time permits, 🤣 and surely will come back for guidance 😉

mighty ledge
marble jackal
#

This is your service data (from the example you provided) scrap that

method: Playlist.Add
item:
- episodeid: plid
playlistid: 1
entity_id: media_player.lhtpc
mighty ledge
#

He did not. Also, I don't see any events in the zip that show a Playlist.GetItems

marble jackal
#

Oh you are right, I was looking at the call_method

mighty ledge
#

wait

#

I see it

#

it's shittily formatted

#

@tepid onyx I see why it's not working. The get is returning a list, are you expecting it to play the first item in the list?

marble jackal
#

I was also thinking the problem might be that

mighty ledge
#

well also, his set is not correct

#

unless i'm missing something

#

the plid is not passed to anything

marble jackal
#

I guess he tries to do that here, but forgot to format it as template

  kodi_set_playlist_test:
    alias: "kodi set playlist test"
    sequence:
    - service: kodi.call_method
      data_template:
        method: Playlist.Add
        item:
          - episodeid: plid
        playlistid: 1
        entity_id: "{{ entity_to }}"
mighty ledge
#

there's even an event that bitches about it being invalid

#

Event 24 fired 10:46 AM

#

"message": "Invalid params."

marble jackal
#

Should probably be - episodeid: "{{ plid }}"

mighty ledge
#

I would assume so

marble jackal
#

Guess he needs to crate a list with a dict like episodeid: id per item. I know how to do that with a for loop an namespace, but I kinda expect it can be done without

mighty ledge
#

I feel like we are missing another automation

#

I vaguely remember posting something about passing through a custom event

#

and this post does not have it

marble jackal
#

from this list:

  items:
  - id: 7625
    label: The Madness of King Zøg
    type: episode
  - id: 7608
    label: Stairway to Hell
    type: episode
#

But maybe I'm missing that information you vaguely remember 🙂

mighty ledge
#

Ah yes, that has the same problem

#

and that's what needs to be changed.

marble jackal
#

As far as I can see, this needs to become:

    - service: kodi.call_method
      data_template:
        method: Playlist.Add
        item:
          - episodeid: 7625
          - episodeid: 7608
        playlistid: 1
        entity_id: "{{ entity_to }}"
mighty ledge
#

how so? Are you looking at the code?

marble jackal
#

no, I can not read python, and don't have kodi to test it 🙂

mighty ledge
#

then it's safe to assume it only allows you to play one item

#

it's playlist.Add

marble jackal
#

ah okay

mighty ledge
#

I would assume you can only add 1 thing

marble jackal
#

the an counted repeat 🙂

mighty ledge
#

I wouldn't bother

#

unless he's trying to match a whole playlist

marble jackal
#

He's quite silent know while we are discussing his issue 🙂

mighty ledge
#

But, he's still missing his piece of the puzzle

#

in the other automation he was trying to move things from 1 item to 1 of 2 others, with it 'guessing' the player

#

and the get / set actions do not pass extra data, meaning he'll need to use an event send and a wait for trigger in order to keep the context

#

in a single automation

#

like I set up in that other automation.

marble jackal
#

didn't bother looking at the other post, will do now

#

@tepid onyx do you mind giving some more insight in the actual issue? 😛

marble jackal
#

But I guess that needs some work on the entity_to variable, because this will be the same entity as from which the data is coming 🙂

tepid onyx
#

sorry had dinner, let me catch up

#

yes im trying to grab a whole play list from one kodi box and add it to another kodi box

#

instead of one item, the json returns a bunch

#

I was able to add multiple items using playlist add statically but couldn't retrieve them in to a yaml list

#

petro solved the issue in the other post with the entity_to variable the only problem I have now is getting the json items in to a yaml list

#

let me check that codepile code.

marble jackal
#

BTW, you can just put the sequence from that script in the automation itself, no need to call a script here

#

Unless it can fail on one of the items in the list, then you could call the script once per item and run them in sequence

#

I added a version where it is all combined in the automation

tepid onyx
#

ok thanks, let me take a look...midnight again woop

mighty ledge
#

It's setting the playlist on where it got the playlist from

#

It needs the interim event

marble jackal
#

yes, I know, that's why I said the entity_to variable needs work

#

but I think that is handled in the other forum topic

#

But I saw that one was solved, so I guess he needs to combine the two now

mighty ledge
#

well the other thread was about files

marble jackal
#

TLDR 😅

mighty ledge
#

yeah, the other thread is about playing a single file and playing it on another device

#

this one is about playing a playlist on another device

#

same shit, different data set

#

if it was me, i'd make an automation that handles both

#

I don't have a kodi either

marble jackal
#

Don't know how many kodi instances he has, but I guess, two, so he could use "{{ 'media_player.kodi_1' if trigger.event.data.entity_id == 'media_player.kodi_2' else 'media_player.kodi_2' }}"

mighty ledge
#

he has 3

marble jackal
#

Oh

mighty ledge
#

which is his problem

#

he wants buttons that take the currently playing XYZ and push them to one or the other without creating all these automations with the events

marble jackal
#

Ah

#

Just use a shared library then 😛

#

That was the reason I started to use Emby, I couldn't get the MySQL database working. Now I just use Emby

mighty ledge
#

🤷‍♂️

#

I don't have or use kodi

#

so my knowledge is limited to the events

marble jackal
#
            target:
              entity_id: "{{ ['media_player.kodi_1', 'media_player.kodi_2', 'media_player.kodi_3'] | reject('eq', trigger.event.data.entity_id) | list }}"
#

But I guess a safeguard is also needed to don't let the automation trigger on the changes caused by the automation 🙂

mighty ledge
#

so, there was that aspect. You can see it in the other automation

#

the problem is that the event doesn't pass it, so it needs to be in a single automation with a wait so that the context is kept

next flax
#

Generate template for APEX Chart generator.

marble jackal
tacit glen
#

Hi. I want to create a template for a condition where the automation is only triggered under the condition that two sensors (IPs) do not match. I used the following template, but whether or not they match, the template always outputs true:

{{ not is_state('sensor.oneplus8_public_ip_address', 'sensor.fritz_box_7530_external_ip') }}

#

Where did I mess up?

#

Only run automation when IP of OnePlues does not match IP of FritzBox

shell arrow
#

or, a little easier to read:

{{ states('sensor.oneplus8_public_ip_address') != states('sensor.fritz_box_7530_external_ip') }}
tacit glen
#

ohh, you're right

#

thanks!

inner mesa
#

it's an attribute for an automation, if that's what you're looking for

#

so you can get the value just like any attribute

inner mesa
#

so you want to know the most recent last_triggered date/time of all your PIR sensors?

#

that should be straightforward with a template

#

but "last triggered" isn't a thing for sensors. you would want "last_changed"

#

{{ states.binary_sensor.aarlo_motion_back_door.last_changed }}

wary helm
#

Hey Pros, what would be the correct way to add an input number (percentage_side_blinds) into my payload message, replacing the value (50 in this example)?
payload: '{ "lift": 50 }'

#

would the following be correct?
payload: '{ "lift": {{percentage_side_blinds}} }'

inner mesa
#

Nope

#

Just a random recent post on how to get a state

wary helm
#

What do you mean exactly? I'm trying to have a slider to put a restful command (value between 0-100) to the api.

#

payload: '{ "lift": 50 }'
This works and now I'm trying to replace the value with an input number so I can use an automation that triggers on the input number to send the command.

#

in the automation action data the input_number state will be added

inner mesa
#

I mean that this is not the way to get the state of an entity:

would the following be correct?
payload: '{ "lift": {{percentage_side_blinds}} }'

#

And I pointed you to an example

wary helm
#

Don't get me wrong, it's very much appreciated. I don't know much about templates.
How come this works for the person in the example?
payload: '{"staircase":{"segment-delay-ms": {{ wipe_speed }},"on-time-s": {{ aan_tijd }}}}'
wipe_speed and aan_tijd are input numbers

I'm trying to figure out your example to come up with one that works for me.

inner mesa
#

To start, you're not using the whole entity_id. It starts with input_number.

#

Second, you need to use states('input_number.whatever')

wary helm
#

In that case I'm looking at
payload: '{ "lift": {{states('input_number.percentage_side_blinds')}}}'

inner mesa
#

You probably also need to use payload_tenplate:

wary helm
#

payload_template: '{ "lift": {{states('input_number.percentage_side_blinds')}}}'

#

Am I going in the right direction?

dusty hawk
#

Is is possible to create sensors, automations, scripts using jinja macros (much like what one can do in lovelace using #lovelace_gen) ? I have a number of each type that are nearly identical except for certain elements that i'd like to parameterize. I'm getting a validation error. input_text: {% macro triggered(zonename, dest) -%} {{zonename}}_triggered_{{dest}}_alert_ids: name: {{zonename}} Triggered Weather Alert IDs - UI initial: None {%- endmacro }

wary helm
#

payload_template: '{ "lift": {{states('input_number.percentage_side_blinds')}} }'
Sorry for the spam but the code above is giving me the correct value in developer-tools > Template, but is not accepted in configuration.yaml, any idea what went wrong?

dreamy sinew
#

payload_template: "{{ {'lift': states('input_number.percentage_side_blinds')} }}"

wary helm
#

Amazing, thanks, so it was " instead of '.

#

and misplaced some things. Thanks.

dreamy sinew
#

oh, you had that problem too

#

i was just generating the entirety of the dict inside the template and happened to fix your quotes at the same time

dusty hawk
#

I wonder if you may also need to cast the value to int ? payload_template: "{{ {'lift': states('input_number.percentage_side_blinds') | int(0)} }}"

inner mesa
#

Likely not in the JSON. Since states('xxx') will just return 5 and not "5", it will be interpreted by the receiver as a number. The whole payload_template is a string

rose scroll
wary helm
tired lily
#

Hey guys, are we allowed to use templates in service call buttons?

Mine keep resetting from:

type: button
tap_action:
  action: call-service
  service: zwave_js.set_lock_usercode
  service_data:
    code_slot: {{states.input_number.code_slot | int | string}}
    usercode: {{states.input_number.pin | int | string}}
  target:
    entity_id:
      - lock.assure_key_free_lever_touchscreen
      - lock.touchscreen_deadbolt_z_wave_plus
      - lock.touchscreen_deadbolt_z_wave_plus_2
name: Set Code
icon: mdi:lock-alert
silent barnBOT
tired lily
#
type: button
tap_action:
  action: call-service
  service: zwave_js.set_lock_usercode
  service_data:
    code_slot:
      '[object Object]': null
    usercode: '[object Object]'
  target:
    entity_id:
      - lock.assure_key_free_lever_touchscreen
      - lock.touchscreen_deadbolt_z_wave_plus
      - lock.touchscreen_deadbolt_z_wave_plus_2
name: Set Code
icon: mdi:lock-alert
#

for some reason the template just gets reset. I'd fire an event, but the option to do so doesn't seem to be here anymore

frank gale
#

@tired lily you missed the '' in your first post

inner mesa
#

And: no

tired lily
# frank gale <@138019747919953930> you missed the '' in your first post
type: button
tap_action:
  action: call-service
  service: zwave_js.set_lock_usercode
  service_data:
    code_slot: "{{states(''input_number.code_slot'') | int }}"
    usercode: "{{states(''input_number.pin'') | int }}"
  target:
    entity_id:
      - lock.assure_key_free_lever_touchscreen
      - lock.touchscreen_deadbolt_z_wave_plus
      - lock.touchscreen_deadbolt_z_wave_plus_2
name: Set Code
icon: mdi:lock-alert
#

You're right, the formatting is a bit new to me I must admit!

inner mesa
#

I say: no

#

Did that work?

tired lily
#

No it didn't, I tried it in the template section and receive back the correct value, but not too sure how to implement it here

inner mesa
#

Not surprised. Call a script and do it there

tired lily
#

It seems to work when called via script, which is great. Thanks for the tip Rob!

inner mesa
#

Almost none of the standard cards support templates

marble jackal
#

Guess Markdown is the example

mental violet
#

Hi, does anyone know a way to create a template sensor that adds up each inputNumber with the name: temperature_*
?

marble jackal
mental violet
#

thank you so much 😄

tepid onyx
#

looking at it now petro thakns

tepid onyx
mighty ledge
#

did you see the response on the forums

tepid onyx
#

I sure did, i've implemented it but it's bombing out with that error.

#

the new code you put in the last - service: kodi.call_method with the for loop seems to be causing the issue but i'm not sure how to debug that

#

that's new to me

mighty ledge
#

I need to see the full error and the trace variables

#

it's best to respond on the forums

tepid onyx
#

ok

mighty ledge
#

that way I'll get notificaitons for it

#

include the trace, the variables in the trace and the error

tepid onyx
#

ok i'll do that.
it's the wait trigger timing out

tepid onyx
#

I included the event trace, how do I include variables in the trace?

#

oh right the automation trace where you said put an id: in the automation

#

fukn 1 am again

mental violet
#

Hi, can I trigger an automation, whenever an input_boolean is changed from on to off with a shared name?
like:
if inputboolean.temperature_bath
or inputboolean.temperature_door
or inputboolean.temperature_floor
turns from off to on?
but I dont wanna hard code it. Is that possible with a tenplate?

vast juniper
#

guys, I'm trying to wrap my head around how all this templating works, I want to extract numeric value from sensor that displace the date. I need only month from date "2022-02-04" to be display as integer. "{{ (state_attr('sensor.anniversary_saule_days_old', 'date'))}}"

vast juniper
tribal cedar
vast juniper
tribal cedar
#

oh you would have to run the split on the final string ,does this work

"{{ state_attr('sensor.anniversary_saule_days_old, date').split("-")[2] }}"

#

ie the output from state_attr should be your date string "2022-02-04" and its on that you would try the split?

mental violet
#

@vast juniper yeah that I know. But there will be more added down the line so I dont want to create for each new device a new rule.

#

Can I just compact it in a filter rule?

vast juniper
tribal cedar
#

spektus, this should convert the date to a string if its not already in string format, otherwise the split wont work.

'{{ (state_attr('sensor.anniversary_saule_days_old, date')|string).split("-")[2] }}'

#

@mental violet I'm not an expert but also interested in something like you are trying to achieve. Is it that you want to trigger on something like sensors that match a certain pattern, and over time, even if more sensors get added matching that pattern, you want to trigger on them.

If true, I'd love to get something like this working also. Is there some template you need to write to first find all sensors that have a certain string in their name, in a loop maybe?

inner mesa
#

it's fairly straightforward if you do it like this:

#
trigger:
  platform: event
  event_type: state_changed
condition:
  - condition: template
    value_template: "{{ trigger.event.data.entity_id is match('input_boolean.temperature') and trigger.event.data.new_state.state == 'on' }}"
tribal cedar
#

Nice, I spent the last hour coming up some crazy loop and then saw your simple value_template and 'match', nice.

inner mesa
#

I've done it before 🙂

tepid onyx
tepid onyx
#

where do i find a specific doco page of all these jinja functions like match, first, last etc

inner mesa
#

there's a link in the channel topic

#

and

silent barnBOT
inner mesa
#

and Jinja is its own thing that's used elsewhere, so you can Google for things

tepid onyx
#

like first I understand the concept but where is the doco?!@!

inner mesa
#

Those are they

tepid onyx
#

yeh they and this

#

I go back to work and reuse what i've learnt some of the guys look at me like I've invented fire but I'd like to increase my rate and commit it to memory...Just frustrated. Yeah I probably work in a shit shop 🙂

#

But if i learn then I whinge less here 🍭

marble jackal
marble jackal
#
trigger:
  platform: event
  event_type: state_changed
  event_data:
    new_state:
      state: "on"
condition:
  - condition: template
    value_template: "{{ trigger.event.data.entity_id is match('input_boolean.temperature') }}"
little thistle
#

I am familiar with yaml and Jinja, but am struggling with where and how templating is to be used.

This template in dev options works fine:

    {% set domain = 'light' %}
    {% set entities = states[domain] | map(attribute='entity_id') | list %}
    {% for entity in entities %}
    - {{ entity }}: off
    {% endfor %}

But when I try to use it in a scene, I get an error:
2022-04-02 09:38:23 ERROR (MainThread) [homeassistant.config] Invalid config for [scene]: expected dict for dictionary value @ data['states'][0]['entities']. Got None. (See /config/scenes.yaml, line 0). Please check the docs at https://www.home-assistant.io/integrations/scene

Meaning the data source is not available there. Docos for templating mention "limited templates" for "triggers", and docos for scenes don't mention templating at all..

Can someone provide some basic guidance here on what docos I failed to read? Or is this all tribal knowledge for now? I don't mind updating documentation

#

Keep in mind that I have no idea if scenes are even appropriate to be used here... My idea was to have "turn off all lights" button on the lovelace UI, and potentially as something I can trigger with a physical button, too

nocturne chasm
#

I don’t think you can template scenes

#

But what you want to do can easily be done with a script or automation

#

And either an input_boolean as a switch or something lovelace related from #frontend-archived

little thistle
#

Thank you, that's a good pointer right there. I'll go google some more

#

I think I don't need the input boolean at all for this, as it's a declarative change across many devices, but reading up on input_boolean was useful. Thanks!

nocturne chasm
#

You said you wanted turn off all lights button on the lovelace ui. Anyway, depending on what you are doing, setting up groups in the ui is in the current beta, due for release on Wed. Might be something you can use.

#

With groups, you have to list entities though, I don’t think you can template them either.

little thistle
#

The key thing here is for it to be dynamic - without me manually enumerating each light

nocturne chasm
#

Are you trying to only turn off lights that are on?

little thistle
#

Doesn't matter - if I want to turn off all lights, why would I care if some were on or off 🙂

nocturne chasm
#

So then, what’s the dynamic part?

#

Just trying to understand

little thistle
#

All lights without manually typing them out

#

dynamic as in <something> (script/automation/whatever) figures out at the time of me hitting that switch what the lights are

#

I will also take advice in a form of "you are thinking about this completely wrong, try this, instead" 😄

nocturne chasm
#

So then you basically want to loop through the light domain and set a group

#

There is an example loop in the template editor and group.set is a service

little thistle
#

oooh

#

brb

nocturne chasm
#

But depends on how dynamic you want it. You could just make a group once and be done with it.

little thistle
#

Ah, no - that's why I want the dynamic part - so I don't have to re-execute this

nocturne chasm
#

That’s what I thought

little thistle
#

Then again - I might be a bit nitpicky here... I'm not going to have 1000s of lights

nocturne chasm
#

Exactly

#

Groups in the ui is a very neat feature coming in the next release.

little thistle
#

This is very good to know, thank you

#

Also, I guess the Areas feature can also be used if I properly set up all devices

nocturne chasm
#

Really depends on your use case 😉

little thistle
#

I'm trying to discover my use case, which is the hardest part 🙂

#

I don't have a clear idea (yet) on how I want to use HA

nocturne chasm
#

Get something working. 4 years later and my stuff still changes on the regular ☺️

little thistle
#

that's the idea!!

#

Thank you very much

marble jackal
#

Just use this in script, no template needed (this was broken, but has been fixed)

service: light.turn_off
target:
  entity_id: all
little thistle
#

I decided on having this:

  1. Define a input_button called all_lights_off
  2. Through the UI, create an automation that will trigger off that "button" state - call service / Lights off / all (all has to be typed in as an entity, though...)
  3. Add the all_lights_off button to lovelace
#

I like the script approach, too. less moving parts

tepid onyx
#

seems inefficient, If you want to do it that way just add all your lights to a groups.yaml file and use that without the input_boolean, Or do what TheFes said 3 line script...

little thistle
#

you are right

#

*input_button

glacial matrix
#

Morning all, Could someone tell me if on the correct lines of template to calculate cost in £ please.

{{ (states('sensor.washing_machine_energy_today') | float ) * (states('input_number.electric_per_kwh') | float) }}

energy_today is measued in kWh
electric_per kWh is recorded in p i.e. (29.4) so i guess i just need to divide the answer by 100?

{{ (states('sensor.washing_machine_energy_today') | float ) * (states('input_number.electric_per_kwh') | float) / 100}}
#

i think i jyst need to round it to two figures.

tepid onyx
#

There's round(2)

#

that one helped me

marble jackal
#

Make sure to use parentheses then, to ensure you're not just rounding 100

mortal sundial
#

Hi Guys, I'd like read the power values of my solar system which are exposed via json. Could someone please help me to extract only the actual value in W?
{"address":"_sum/EssActivePower","type":"INTEGER","accessMode":"RO","text":"AC-side power of Energy Storage System. Includes excess DC-PV production for hybrid inverters. Negative values for charge; positive for discharge","unit":"W","value":1210}
This is the returned json when I setup the sensor like this:

  - platform: rest
    name: EssActivePower
    resource: http://x:user@192.168.178.25/rest/channel/_sum/EssActivePower
tepid onyx
#

put it in a post in the ha forum and format it

marble jackal
#

Looks like {{ value_json.value }} should work

mortal sundial
mortal sundial
glacial matrix
#

I assumed that the template would be

Morning all, Could someone tell me if on the correct lines of template to calculate cost in £ please.

{{ (states('sensor.washing_machine_energy_today') | float ) * (states('input_number.electric_per_kwh') | float) / 100 | round(2)}}

How do I then get the sensor unit in front of the value? I.e. £0.11 rather than 0.11 £?

marble jackal
#

The unit of measurement is always shown behind the value

#

You could add it to the template itself

#

{{ '£ ' ~ ((states('sensor.washing_machine_energy_today') | float ) * (states('input_number.electric_per_kwh') | float) / 100) | round(2) }}

fossil venture
#

You're also rounding the integer

marble jackal
#

But then it will be string and not a number

fossil venture
#

100 | round(2)

#

Needs some parentheses

marble jackal
#

Ah, true

#

But I already said that 2 hours ago 😅

glacial matrix
#

thanks, i'm not sure what you mean by i'm rounding the integer, is this better?

{{ (states('sensor.washing_machine_energy_today')|float * states('input_number.electric_per_kwh')|float)|round(2) /100}}
inner mesa
#

Just what toml said. I don't see an issue with that one

glacial matrix
#

so it is, sorry. was looking at it on my phone on the go. Thank you.

mental violet
#

Hello,
I need a template that finds all inputnumber.temperature_ variables (I got that part). But I also have inputboolean.temperature_ that share the same name with the numbers. So my template should add up every inputnumber with temperature_ in name while their inputboolean counterpart is true/on.

#

So for example:
input_number.temperature_bath + input_number.tempature_kitchen while input_boolean.temperature_bath == on and input_boolean.temperature_kitchen == on and input_boolean.temperature_bedroom == off

inner mesa
#

perhaps this will help:

#
{% set entities = states.binary_sensor|selectattr('object_id', 'search', 'occupancy')|selectattr('state', 'eq', 'on')|map(attribute='entity_id')|list|replace('binary_', '')|replace('_occupancy', '_temperature') %}
{{ states.sensor|selectattr('entity_id', 'in', entities)|map(attribute='state')|select('is_number')|map('float')|sum }}
#

with modifications for your specific needs

mental violet
#

NICE really really cool thanks 😄

inner mesa
#

it should be simpler, but I found a bug that makes it more complicated. could only be in the beta

#

you can try this for the second line and see if it works for you:
{{ expand(entities)|map(attribute='state')|select('is_number')|map('float')|sum }}

floral shuttle
#

so a platform: group template {{state_attr('binary_sensor.active_devices','entity_id')}} results in a [ ] list, while an 'old style' group template {{state_attr('group.indoor_temp_sensors','entity_id')}} results in a (list) and needs |list...

#

seems no issue, but wondering if thats per design.

marble jackal
#

Noticed that as well, btw the () list is called a tuple, in case you want to dig into it further.
The template editor shows them as a list though, if it is the only result, which can be confusing

floral shuttle
#

yeah, I just used the same wording, to accent the style of template was indentical. its not only confusing, it's quite inconsistent.

silent barnBOT
karmic prism
#

Hi due to changes in defaults ie float at the moment will return 0 if the value isn't valid I was changing floats to be float(0) this seems to be effective in getting rid of the warning in most integrations i used | float but this sensor broke https://www.codepile.net/pile/6xlg51DE and after a few days i noticed it had stopped updating reverting it started working again. I would like to understand why.

acoustic trail
marble jackal
#

If I would have a list with dicts like this [ { 'where': 'basket', 'what': [ 'apples', 'bananas' ] }, { 'where': 'fridge', 'what': [ 'grapes', 'pears' ] } ] called fruit, can I somehow take out the whats and combine them in a list?
I can do {{ fruit | map(attribute='what') }} but then, how to create one list out of this selector

inner mesa
#

{{ fruit|map(attribute='what')|list|sum(start=[]) }}

#

like that?

#

['apples', 'bananas', 'grapes', 'pears']

marble jackal
#

Let me check that, but looks good.
I came up with this, but yours looks better

{% set fruit = [ { 'where': 'basket', 'what': [ 'apples', 'bananas' ] }, { 'where': 'fridge', 'what': [ 'grapes', 'pears' ] } ] %}
{{ (fruit | map(attribute='what') | map('join', ',') | join(',')).split(',') }}
#

But while reading the docs on what start does, I realized this is even better:
{{ fruit | sum(attribute='what', start=[]) }}

nocturne chasm
#

Why no cherries in the fruit bowl?

inner mesa
marble jackal
#

This works as well {{ fruit | sum('what', []) }}

ember dragon
#

Hi there!
How do I go about setting a input Boolean equal to the state of a light?
I'm trying to capture the state of a light when an automation is trigger.

I have an input Boolean named "input_boolean.garagelightstateondooropen".
I have a light called "switch.garage_light".

I dont know the correct syntax... But my thought is something like this:
{% {'input_boolean.garagelightstateondooropen' = 'switch.garage_light'}%}

I would want to also do this to restore the state of the light when a different automation is triggered.
{% {'switch.garage_light'='input_boolean.garagelightstateondooropen' }%}
Cheers!

inner mesa
#

You use the service for input_boolean

silent barnBOT
inner mesa
#

Templates don't do anything to the HA state machine. They just provide output that can be used somewhere in HA

marble jackal
mental violet
#

hi, I search for a template, that does the following:
I have 2 batterylevels (A and B) and 2 devicetracker. (From me and my gf)
The batterylevel is only important, if I or my gf is at home.
The template should be on, if: A(while A.devicetracker == home) < 80 OR B(while B.devicetracker == home) < 70 and should be off, if: A(while A.devicetracker == home) >= 90 AND B(while B.devicetracker == home) >= 85
I had many if states, but now every time both our phones get charged over the threshold a loop occurs.

marble jackal
#

What if battery level A is 85 and battery level B is 75? Then they don't fit on and off

mental violet
#

ah yes, so if one of the batterylevels fall under the 80/70 threshhold the template should be on until both batterylevels are over the 90/85 threshhold and then turn off until one of them falls under the 80/70 threshold

#

i did this, because I feared if I only make it: be on if >85 and be off =<84 then the template (and therfore my switch) would be like on/off/on/off after 1% charge /discharge

mental violet
#

how can I put 2 entitie ids in a variable?

{% entites =+ deviceid 2 %}
{{entities}}``` output: ```['deviceid 1' , 'deviceid 2']```
#

oh wow ok thanks you

marble jackal
#

sorry, pressed enter too soon

#
{% set entities = [ 'device_id1' ] %}
{% set entiteis = entities + [ 'device_id2' ]
{{ entities }}
#

As far as I know the =+ notation doesn't work in jinja

#

But you can add lists to lists

half pendant
#

Is there anyway i could craete a mediaplayer that uses everything from the Apple TV media player i already have except for the volume, that would be my sonos beam?

marble jackal
mental violet
#

is there a similar filter to replace that just adds a string?

marble jackal
#

Could you give an example?

mental violet
#

|replace(homeentities,homeentities+'_battery_level') I tried this, but that just changes the array to a string and adds battery_level behind that... 😦['sensor.test2', 'sensor.test1']_battery_level

marble jackal
#

Hmm, you can if you loop through them, not sure if there is an easier way:

{%- set ns = namespace(battery=[]) %}
{%- for tracker in homeentities %}
  {%- set ns.battery = ns.battery + [ tracker + '_battery_level' ] %}
{%- endfor %}
{{ ns.battery }}
floral shuttle
#

yes. and with the test for 'home': {%- set ns = namespace(battery=[]) %} {% for d in states.device_tracker if d.state == 'home' %} {% set ns.battery = ns.battery + [d.entity_id~'_battery_level'] %} {% endfor %} {{ns.battery}} The allenentities you use in your test is not needed. you already select the device_tracker domain, so just leave that out.

#

thinking this might need an extra test, to see if the actual entity exists

marble jackal
#

BTW, this will result in device_tracker.something_battery_level so I think you also neet to replace device_tracker with sensor

floral shuttle
#

{%- set ns = namespace(battery=[]) %}
{% for d in states.device_tracker 
 if d.state == 'home' %}
{% set ns.battery = ns.battery + [(d.entity_id~'_battery_level')|replace('device_tracker','sensor')] %}
{% endfor %}
{{ns.battery}}
marble jackal
#

you could use:

{%- set ns = namespace(battery=[]) %}
{% for d in states.device_tracker | selectattr('state', 'eq', 'home') %}
{% set ns.battery = ns.battery + [ 'sensor.' ~ d.object_id ~ '_battery_level' ] %}
{% endfor %}
{{ns.battery}}
floral shuttle
#

or that 😉 (much better)

#

maybe this: {%- set ns = namespace(battery=[]) %} {% for d in states.device_tracker %} {% set id = 'sensor.' ~ d.object_id ~ '_battery_level' %} {% if d.state == 'home' and states(id) not in ['unknown','unavailable'] %} {% set ns.battery = ns.battery + [id] %} {% endif %} {% endfor %} {{ns.battery}} or TheFes's format: {%- set ns = namespace(battery=[]) %} {% for d in states.device_tracker| selectattr('state', 'eq', 'home') %} {% set id = 'sensor.' ~ d.object_id ~ '_battery_level' %} {% if states(id) not in ['unknown','unavailable'] %} {% set ns.battery = ns.battery + [id] %} {% endif %} {% endfor %} {{ns.battery}}

tepid onyx
#

👍

#

when you set a variable what does the tidle(~) do

tepid onyx
#

The ~ (read as "tilde") operator is used to join operands as strings. It converts neighboring operands into strings and concatenates them.

#

and you have to declare it first if it's part of an array

#

that fixed an issue. nice

marble jackal
mighty ledge
marble jackal
#

Ah right

mighty ledge
#

states.sensor | map(attribute='entity_id') will iterate the collection every entity

#

that's typically bad

tepid onyx
#

yo petro

glossy aurora
#

currently in the template devtool and i get the TemplateSyntaxError: unexpected char '\\' at 2327

mighty ledge
#

@tepid onyx I just replied on the trhead

glossy aurora
#

my template is only 173 lines

#

and i dont use the \ anywhere.

tepid onyx
#

really I was going to give up and go with a rest temple

mighty ledge
marble jackal
#
{%- set ns = namespace(battery=[]) %}
{%- for d in states.device_tracker| selectattr('state', 'eq', 'home') %}
  {%- set ns.battery = ns.battery + [ 'sensor.' ~ d.object_id ~ '_battery_level' ] %}
{%- endfor %}
{{ ns.battery | select('in', states.sensor | map(attribute='entity_id') | list) | list }}

Like this?

tepid onyx
#

ok thank you Petro

mighty ledge
#

it has to be on a separate line

marble jackal
#
{%- set ns = namespace(battery=[]) %}
{%- for d in states.device_tracker| selectattr('state', 'eq', 'home') %}
  {%- set ns.battery = ns.battery + [ 'sensor.' ~ d.object_id ~ '_battery_level' ] %}
{%- endfor %}
{%- set sensors = states.sensor | map(attribute='entity_id') | list %}
{{ ns.battery | select('in', sensors) | list }}
mighty ledge
#
{% set filter = states.sensor | ... %}
{{ ns.battery | select('in', filter) ...
#

yes

#

although, I think I might be mistaken with that

#

your 1 liner might work

#

I'd have to see the debugging

floral shuttle
mighty ledge
#

select is a method, so it's probably resolved once before getting placed into select

mighty ledge
marble jackal
#

Hehe, okay! Good to know

mighty ledge
#

morning fog

marble jackal
#

Time for coffee ☕

tepid onyx
#

Exciting

mighty ledge
#

I.e. you probably won't understand how to do it unless you set up a dev environment and learn the development process

floral shuttle
#

..... thanks for the compliment 🙂

mighty ledge
#

It's no easy feat, so it's not meant to be an insult

#

if you haven't setup a dev environment before, it's very hard

#

that's before even using the debugging ability

floral shuttle
#

I know!

mighty ledge
#

then, once you're there, you need to understand the objects and code flow (the stack trace)

floral shuttle
#

ok, so well just keep asking you 😉

tepid onyx
#

im going for a smoke

marble jackal
#

{{ service_calls | selectattr('entity_id', 'defined') | map(attribute='entity_id') | list }} can I check somehow if the entity id is provided as a string or as a list? If it is a list I want to sum them, if it is a string I want to create a list

mighty ledge
marble jackal
#

okay, but nobody will provide a dict when they enter entity_id's in a service call right?

mighty ledge
#

hahahaha, never trust users

marble jackal
#

So I guess select('string') will do it

#

Okay true

#

I will do it fool proof

tepid onyx
#

.. let me check

mighty ledge
marble jackal
#

hehe

#

So this will do I guess

{% set e_s = service_calls | selectattr('entity_id', 'defined') | map(attribute='entity_id') | reject('mapping') | select('string') | list %}
{% set e_l = service_calls | selectattr('entity_id', 'defined') | map(attribute='entity_id') | reject('mapping') | reject('string') | select('iterable') | sum(start=[]) %}
{% set e = e_s + e_l %}
#

And then add data.entity_id and target.entity_id.. So many ways to enter an entity_id to a service call 😛

mighty ledge
marble jackal
#

Well, from a script call, in which it is possible to provide actions (using the action selector)

#

It's for my Google Home Resume script, I let them provide the service calls in the script call, so I can determine which entities are the target, so which need to resume afterwards

#

The script performs the actions later on, using a repeat (and I take out the service calls out of the provided actions, because service calls have template support on service, data and target)

#

Now I think of it, the entities I should only take out those provided in data and target als the others ones are not used in the repeat

mighty ledge
#

when you provide 1 item without it being a list, does the configuration accept that?

#

if yes, that would be a mapping

marble jackal
#

I will do some tests, but thanks!
I had a lot of for loops to this before, this is much better

#

This works:

{% set service_calls = [
              {
                "alias": "Send TTS message",
                "service": "meida_player.media_play",
                "entity_id": "media_player.woonkamer_mini ",
              }
            ] %}
{% set e_s = service_calls | selectattr('entity_id', 'defined') | map(attribute='entity_id') | reject('mapping') | select('string') | list %}
#

Isn't this what you just said? 1 item without it being a list?

mighty ledge
#

yes but how is this being passed?

#

to the script

#

home assistant did this "smart" thing where service calls don't require a -

#
action:
  service: ....

is the same as

action:
- service: ...
#

top is a dict, bottom is a list

#

if that isn't possible for whatever you're creating, don't worry about it

#

fyi | select('string') effectively rejects mapping, so the | reject('mapping') isn't needed

marble jackal
#

Ah, that's what you mean, I'll give that a test

grizzled scarab
#

hoping someone can help me, I'm trying to figure out why a single light entity would be counted as two when using a state sensor to display number of lights on.

If the light is on, it shows 2. If I turn it off, it shows 0. There is only one light.desk entity so I'm very confused

mighty ledge
#

that depends on your template

#

and if you have a light group using said light

grizzled scarab
#

I'm just using {{ states.light | selectattr('state','eq','on') | list | count }}

#

I think it is in a group actually, does that see the group as an additional entity?

marble jackal
#

is it a light group?

grizzled scarab
#

yeah it is

marble jackal
#

A light group is also a light entity, so it will be listed under states.light

#

{{ states.light | rejectattr('attributes.entity_id', 'defined') | selectattr('state','eq','on') | list | count }} should remove the group

#

Unless that has been added in 2022.4

#

{{ states.light | selectattr('state','eq','on') | map(attribute='entity_id') | list }} will at leas show you which lights were included in your count

marble jackal
mighty ledge
#

Yeah that works

marble jackal
#

could have use iif 🙂 iif(action is mapping,[ action ], action)

#

or in one line {{ iif(action is mapping,[ action ], action) | selectattr('service', 'defined') | list }}

fallow ruin
#

guys,

on home assistant website, i read that this
{{ states.sensor.formula_one_sensor.attributes.next_race.Circuit.circuitName }}

is not the right way to do this, but how to get this value the right way??

{{state_attr('sensor.formula_one_sensor', ??)}}

marble jackal
#

{{ state_attr('sensor.formule_one_sensor', 'next_race').Circuit.circuitName }}

fallow ruin
#

that isn't working

#

it is working

#

formula instead of formule

#

👍

#

thanks

marble jackal
#

Sorry 'bout that

fallow ruin
#

no problem it's working now

silent barnBOT
astral ginkgo
#

Can someone help out? 🙂

marble jackal
#

Where do you want to use this template?

astral ginkgo
#

I want to use this in a markdown card 🙂

marble jackal
#

What is it that you actually want to display. What would be an example of the text? In Dutch would be fine

astral ginkgo
#

I want to display all the energy cost components in a detailed way, preferably in a table, column 1 will contain the name and column 2 the price

#

I am able to format the table, that's no problem

#

But I am having issues with iterating in an interation

#

{% for kost in energie.elektriciteit.kosten %} {% for kost_detail in kost %} {{ kost_detail }} {% endfor %} {% endfor %}

#

i thought this would be correct, but unfortunately it's not

marble jackal
#

What would you expect to get as result of your template? It's still not clear to me what you want to achieve

astral ginkgo
#

I will try to explain it differently

#

So we have the following array:

#

{%
set array = {
"colors": {
"blue":"1",
"red":"2",
},
"animals": {
"dog":"1",
"cat":"2",
},
}
%}

#

If I want to list all possible options, I use this code:

#

{% for test in array %} {{ test }} {% endfor %}

#

the result I get is:

#

`colors

animals`

#

what I want as a result is:

#

`blue

red

dog

cat`

silent barnBOT
astral ginkgo
#

but that doesn't work either 🙂

marble jackal
#
{% set ns = namespace(values=[]) %}
{% for d in array %}
  {% set ns.values = ns.values + array[d].keys() | list %}
{% endfor %}
{{ ns.values }}

returns [ "blue", "red", "dog", "cat" ]

astral ginkgo
#

that works, thanks

#

Now I am trying to make it work for my original template

#

And that isn't working 😦

silent barnBOT
astral ginkgo
#

fixed it!

#

{% set ns = namespace(values=[]) %}
{% for d in energie.elektriciteit.kosten %}
{% set ns.values = ns.values + energie.elektriciteit.kosten[d].keys() | list %}
{% endfor %}
{{ ns.values }}

#

thank you so much! :d

marble jackal
#

Please stop posting code walls

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.

marble jackal
#

And use code formatting for smaller posts containing code

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://www.codepile.net/ (pick YAML for the language) or https://paste.debian.net/ (pick YAML for the language).

astral ginkgo
#

Ok will do

silent barnBOT
dense stream
#

specific error for that code it "TypeError: can only concatenate list (not "str") to list"

inner mesa
#

You need [item], but it's still not going to do what you want. You need to use a namespace and do {% ns.newList = ns.newList + [item] %}

dense stream
#

awesome that worked thanks!

exotic nexus
#

What would a template look like that randomly pick one of about 20 strings and changes it every 30 seconds?

inner mesa
#

The first part is a simple list and |random. The second is an automation or template sensor.

- trigger:
    platform: time_pattern
    seconds: "/30"
  sensor:
    - name: random_string
      state: >-
        {% set strings = ["foo", "bar", "blah"] %}
        {{ strings|random }}
young jacinth
#

hey,
iam trying to get a list of all my entities with the device class "motion" i tried this but it throws me an error

{{states.binary_sensor|selectattr('device_class','motion')}}

okay states.binary_sensor does not make sense ....

grizzled scarab
#
  Currently {{ states.light | rejectattr('attributes.entity_id', 'light.other')
  | selectattr('state','eq','on') | list | count }} lights are on.```

light.other is the light group that that light was in
viscid jewel
#

Hello! I am having some issues with ESPHome and pulling some existing entity values via Yaml, any chance someone can help?

grizzled scarab
#

never mind, think I fixed it!

analog mulch
#

I want to get a baniry sensor that will give me a result from a bunch of vector algebra of the sun position and variables describing the window (binary sensor to see if the sun is outside of the window, but checking if window is not covered by e.g. a balcony). The algebra I can handle, but doing this in jinja2 seems a little inefficient. Is there an alternative approach?

mighty ledge
analog mulch
#

is there some neat way of writing a long template that just brute-forcing it?

mighty ledge
#

I don't know what you mean

#

if you have the calculation, it's probably an easy template

mighty ledge
analog mulch
#

I mean that I will have to define lots of variables, functions for scalar products, I guess trigonometry is there in jinja2 and wrap everhyitng in {%%}. and code server doesn't seem to be able to do parenthesis checking or entity_id lookup inside templates, so my code's always very buggy

marble jackal
#

entity_id lookups are supported in the template editor of HA itself

#

devtools > Templates

#

It immediately shows if the template can be rendered and the result

#

syntax highlighting is a bit better in VSCode though (with the HA configuration extension) and you can also optionally do bracket highlighting there

#

entity_id lookup in templates in VSCode would be nice though

analog mulch
#

yeah, I like having the whole thing in vscode. But point taken than I should just do the template in the editor -- i usually play around there and then move it to vs

marble jackal
#

I also usually just do it in VSCode, but also because I usually have a lot of variables defined somewhere else in my scripts, or even coming from other scripts, which doesn't make it easy to have a working template in the template editor

#

And the entity_id autocomplete is new since 2022.3, so I'm kinda used to having to enter them myself

mighty ledge
#

if you share your code, I can help you with the buggyness

marble jackal
#

Oh, I use CTRL + [ and CTRL + ]

crystal tide
#

Hi all, I need your help to understand how is working templates... Could you please tell me what's the main difference between templates and inputs that we can create in HA (automation/entry...) ?
I also tried to understand the example on the website of HA : https://pastebin.com/F2kyZ7zs
I can create it, import it on my lovelace card, but if I click on it, the button goes back to off after about 3 seconds: I don't understand this behaviour.
Thanks for your help.

marble jackal
#

This is the actual template part in that code {{ is_state_attr('switch.blind_toggle', 'sensor_state', 'on') }

#

there is more explanation in the pinned posts on this channel

crystal tide
mighty ledge
#

If your value_template was correct, you wouldn't see the behavior.

crystal tide
crystal tide
dense stream
#

very confused, the message portion with templating works fine in the developer tools but i get an error when trying to save the script that "Message malformed: extra keys not allowed @ data['test_script']"
https://pastebin.com/FAMPeN1i

marble jackal
marble jackal
dense stream
marble jackal
#

Well the term message in the error message does not necessarily refer to the message in the notify service call

#

So don't pin on that. You can replace it with just a simple string like "test" and see if that resolves the error. If not, it's caused by something else

#

What is the code now?

dense stream
#

was a stupid issue......

#

i added a name at the top but was testing by pasting into the visual editor

#

i.e. at the top was the name of the script where as it should have just been the alias

floral shuttle
#

have these for my Hue tap switches: state: > {% if state_attr('sensor.auditorium_tap_switch','last_triggered') is not none %} {{trigger.event.data.subtype}} {% else %} Not yet tapped {% endif %} attributes: time_fired: > {{as_timestamp(trigger.event.time_fired)|timestamp_custom()}} last_triggered: > {{trigger.event.time_fired.isoformat()}}

#

starting up with Unknown. which is expected. However, If I click the first time, it shows 'Not yet tapped' for state. Seems 1 step behind.?

unborn ivy
#

I get a value (=0.03) in the template editor for following:
{{states('sensor.switch_01_current')}}

But I get an error when I try to compare:
{% if {{states('sensor.switch_01_current')}} | float > 0 %}
Appliance running
{% else %}
Appliance not running
{% endif %}

TemplateSyntaxError: expected token ':', got '}'

Any idea what may be wrong with the comparison syntax above?

inner mesa
#

You're nesting templates

#

Remove {{ }}

unborn ivy
final parcel
#

Is this will be working assuming climate.radiator_obyvak has attribute current_temperature which I previous status want to store in sensor "Radiator obyvak - posledni teplota please? This is template for platform template which will be in config.yaml "```- trigger:

  • platform: state
    entity_id:
    • climate.radiator_obyvak
      sensor:
    • name: "Radiátor obývák - poslední teplota"
      state: '{{ trigger.from_state.attributes.current_heating_setpoint }}'```
final parcel
#

So I have this but it does not give me previous state but current. Ie if heating setpoint is set to 21 and I set it now to 0 the sensor should give me 21 but gives me 0. Why so pls?

marble jackal
#

It triggers on all changes

#

You should change the trigger so it only triggers on the change of that specific attribute

#
  - platform: state
    entity_id: climate.radiator_obyvak
    attribute: current_heating_setpoint
final parcel
#

In that case I can also use scene variable name

marble jackal
#

Many roads to Rome

final parcel
#

can I load attributes from scene entities?

#

Unfortunatelly I will need that sensor :/

marble jackal
#

Well, change the trigger then :)

tacit hedge
#

Hey folks, I am just starting to learn how to work with templates. I wanted to test a simple template. (If spot 1 or 2 on send message {{ trigger.id }} is on). That works I get that message only thing that confuses me is that istead of the id "Spot1" or "spot2" it shows 0 and 1 like "0 is on" Can someone tell me how I get him to take the correct ids? Or is it possible to make him spill out friendly names?

mighty ledge
#

trigger.id is correct, but what id you actually put in the id field for your trigger?

tacit hedge
#

it has the entity id and device id

marble jackal
#

You probably either want {{ trigger.entity_id }} or you need to provide a trigger id ( that's what {{ trigger.id }} refers to).

tacit hedge
#

ah ok thanks I will try that

final parcel
#

dears, why does this do not want to work? ```
service: climate.set_temperature
data:
temperature: sensor.radiator_obyvak_posledni_nastavena_teplota
target:
entity_id: climate.radiator_obyvak

marble jackal
#

Because you need to use a template and not direct reference to the entity

final parcel
#

okay.Thank you! 🙂

#

But I do not know why this for example works without template ```platform: numeric_state
entity_id: climate.radiator_obyvak
attribute: current_temperature
above: sensor.0x00158d0003f0d48a_temperature

buoyant pine
#

because that's designed to work without needing a template

final parcel
#

okay 🙂 guys thank you! 🙂

tribal prairie
#

HI Guys,
I would like to create an entity for e.g. my water meter where I manually update the value on my Dashboard. I have been looking at Input Number, I I don't think this is what I am looking for. It should behave like a utility meter, just with me beeing the "input sensor". Any hints / directions on where to look?

The goal is to already collect some data until I have a automated solution. But having an update like once a week is still a lot better than not having it at all...

marble jackal
#

You can create an utility meter out of your input_number

tacit hedge
#

Hello, I am trying to get a notification if one of my plantsensors detects low water. I get how I could use a Template but every plant has a different min_water value. Is there a way to work around this (without studdying rocketscience preferably)

tacit hedge
marble jackal
#

Or provide an id to the trigger and use that

tacit hedge
marble jackal
#

Check the pinned posts of this channel

tacit hedge
marble jackal
#

Should work, but not if you run the automation from Configuration > Automations, as there is no trigger then

tacit hedge
#

I think I need a break of fresh air... well that was dumb XD

#

Later I will get back on the topic of getting the plant sensor values int templates

tepid onyx
#

Winner, thanks again @mighty ledge your the man.👍

#

you're even

north locust
#

how do i pull open_sensors: null attribute from alarm sensor for in a actionable notifications tried {{open_sensors}} but doesnt work ?

inner mesa
#

but I don't know what you mean by this:

pull open_sensors: null attribute

#

if you mean "display the attribute", then {{ state_attr('alarm_control_panel.something', 'open_sensors') }}

#

the null there is confusing

north locust
#

yes when one door or windows is opened it says which door/window , null = nothing open

#

ty

#

yes it now displays the binary_sensor which is opened , can i attr more from open_sensors like friendly name ?

inner mesa
#

if it outputs an entity_id, then yes

north locust
#

is its output when triggering from frontdoor {'binary_sensor.frontdoor_contact':'open'} like to clean it up

#

to only display frontdoor

inner mesa
#

some test code;

#
{% set attr = {"binary_sensor.office_motion_sensor": "open"} %}
{{ expand(attr.keys())|map(attribute='attributes.friendly_name')|join(', ') }}
#

-> Office Motion Sensor

north locust
#

can i set a wildcard for .office_motion_sensor ? * ?

inner mesa
#

you said that the attribute contains the sensors that you care about. what would a wildcard do?

north locust
#

well alarmo open_sensors attribute has multiple sensors which can populate it ?

inner mesa
#

that's just test code that you need to modify for your needs

#

I showed you how to get the attribute, then a way to take the attributes and extract the friendly name for each and display it as a comma-separated list

#

all the pieces are there

north locust
#

thnks ill go experimenting !

#

great help

pine musk
#

trying to trigger an automation every minute... what's the best way to accomplish this?
tried triggering on a template of {{ now() }}

inner mesa
#

not with a template

#

see the crosspost

slender whale
#

how do i achieve the following
i have sensor attribute "today" its a fixed format with 24 values per day. comma separated. first value is for 00:00 next value is for 01:00 etc.
i want to create a template sensor that gives me the average value out of the three next hours from the attribute value.

Sensor attribute value: 0.6, 0.3, 0.3, 0.3, 0.3, 0.7, 2.1, 2.3, 2.3, 2.1, 1.3, 1, 1, 1, 0.9, 1, 1, 1.6, 2.1, 2.3, 2.2, 1.7, 1.4, 0.8

inner mesa
#
{% set values = [0.6, 0.3, 0.3, 0.3, 0.3, 0.7, 2.1, 2.3, 2.3, 2.1, 1.3, 1, 1, 1, 0.9, 1, 1, 1.6, 2.1, 2.3, 2.2, 1.7, 1.4, 0.8] %}
{% set hour = now().hour %}
{{ values[hour:hour+3]|sum/3 }}
#

there are definitely corner cases and maybe off-by-one errors left as an exercise to the reader

slender whale
#

cool, thanks, ill give it a go

slender whale
inner mesa
#

Yes, getting the attribute is trivial

#

That is sample code

tribal prairie
#

HI Guys,

I did ask this here earlier today.
I would like to create an entity for e.g. my water meter where I manually update the value on my Dashboard. I have been looking at Input Number, I I don't think this is what I am looking for. It should behave like a utility meter, just with me beeing the "input sensor". Any hints / directions on where to look?

The goal is to already collect some data until I have a automated solution. But having an update like once a week is still a lot better than not having it at all...

TheFes suggested I use an input number within the utility meter. My problem is now:
The input number requires a min and a max value. That seems wrong for my purpose. What do you think?

#

…and more important: Utility meter does only accept a sensor as source no input_number. So this does not work.

fossil totem
#

append your meter reading to that file when you collect it and the sensor will pick it up and record in the database with the timestamp. set it up with the proper units and you can use it w/ the energy dashboard etc

tribal prairie
#

@fossil totem That is interesting. I would prefer having a way to use an input filed in the app to populate the sensor. But this is an interesting way. I am just wondering on how to get the readings into the file with as little effort as possible now.

#

Thanks!

fierce hornet
#

I'm trying to display everyone that is home in one sensor with some nice formatting. With a lot of help here a few weeks ago I managed to get this working:

{% for person in expand('input_boolean.luukaanwezig', 'input_boolean.rensaanwezig', 'input_boolean.joostaanwezig', 'input_boolean.arjanaanwezig', 'input_boolean.jennyaanwezig')| selectattr('state','eq','on')  | sort(reverse=true, attribute="name") %}
{%- if loop.first %}{% elif loop.last %} en {% else %}, {% endif -%}
  {{ person.name }}
{%- endfor %}```
Unfortunately it doesn't work as intended when everyone is away. It just remembers the last person that was home. How can I add something to this so it display "none" or something like that.
#

Probably not the best template but it does the job

rose scroll
#

Hmm why use input_booleans to track person presence, as opposed to device trackers or the actual person entity? Those also take states on and off only.

#

But anyway, I would suggest to first simplify your code for testing purposes. Can you remove all but 2 of the input_booleans, then manually set them to off in Dev Tools > States, then see what this template returns in Dev Tools > Templates?

fierce hornet
#

Yea I'm experimenting with it myself right now. Not figured it out yet

#

I use booleans so I can manually enable and disable them for testing purposes. The booleans get enbabled/disabled by a group state. That group contains multiple device_tracker entities for each person.

fossil totem
#

maybe wrap the whole thing in an if statement, with one big or condition

#

if at least one of them is home, then do the template you have above, if not, some other text you want when nobody is home.

#

also i'm confused by the if loop.first followed immediately by an else clause. feels like a rudandant statement maybe?

fierce hornet
#

Honestly, I have no idea😅 My templating skills aren't very good, someone else made most of this for me.

fierce hornet
#

If that's possible

rose scroll
fierce hornet
#

Template currently works fine, but when using it in a sensor it "remembers" the last person when no one is home. Don't know what's the problem with the booleans, also works fine and the state gets changed by Node-Red. I do this with quite a lot of sensors.

rose scroll
#

So when all input_booleans are off and you put the template into Dev Tools > Template, what is the output?

hybrid tide
#

Good day folks. I use a input_select to store the state of my washing machine. Values are either empty, running or full. The state changes based on a few sensors on the machine. An automation monitors an zwave plug then sets it to "running" when a certain wattage is hit. Once that wattage drops for a period of time an automation sets it to "full". Then when a door sensor detects the door being opened for 15 seconds, an automation sets the value to "empty". On my lovelace (dashboard), I have an Entity card, which I'd like the icon to change based on the state of the input_select. But, I can't figure out how to make it do that.

#

I've looked at a select template, but that requires an action...but I don't want an action to occur when it changes. Am I missing an option somewhere?

hybrid tide
# fierce hornet I'm trying to display everyone that is home in one sensor with some nice formatt...

Here's how I do that:

{%- set peopleHome = states.person | selectattr('state', 'eq', 'home') | map(attribute='name') | list -%}
{%- set peopleNumber = peopleHome |length  -%}
{%- if peopleNumber == 0 %}
Nobody is home!
{%- elif peopleNumber == 1 %}
{{ peopleHome[0] }} is home!
{% else %}
{{ peopleHome[:-1] | join (', ')~' and '~peopleHome[-1] }} are home!
{%- endif %}
{{ now().timestamp() | timestamp_custom('%a %-I:%M %p') }}```
#

I use that as a template widget for my Android watch.

rose scroll
#

Or you can use a custom:button-card with the icon changing based on the state of your input_select, using a template.

hybrid tide
#

Thank you!

grim geyser
#

Hello. I need some help changing a template. I have tried various combinations with no success. I need to change the variable room["climate"] to variables.climate. This is a template from dwains which im trying to use in a different project. Any help would be great. https://www.codepile.net/pile/Rd0DJEd8

#

This is supposed to go inside a custom button card.

grim geyser
#

Hello

#

ok I have figured out its this that doesnt work. The is defined check doesnt let the card load. Am I doing something wrong? I cant even get this test to work. https://www.codepile.net/pile/xYA0MDGB
{% if states.media_player.some_name.state is defined %}
if it exists actions
{% else %}
if it doesn't actions
{% endif %}

marble jackal
floral lichen
#

I have MQTT lights, but if I group a large amount together i get an issue of only some doing what they are meant to when I change them. Adding a delay works for simple on off commands or a pre determined value "blue" "red" etc but is there a way that I can use the colour wheel / temperature / brightness and then "send" that information through to all the lights one by one?

silent vector
#

I know the plan is to move a lot to the UI. Does that mean templates will be done away with or will they be possible to do from the UI where you would create the name for example in the UI and just drop in the template and it would format for you rather than doing it in the configuration or templates yaml?

silent vector
#

That's good thank you.

fierce hornet
analog mulch
#

Is it safe/possible to refer to the state of the sensor itself in the template defining the sensor? I am trying to add a condition in the template in a trigger-based sensor and return the value unchanged if it fails to pass.

inner mesa
#

That should be fine

lime olive
wanton ledge
#

I want to know how long a sensor (binary_sensor.test) was in the state off. With history_stats I was able to create an entity that shows the cumulated off-state for today, but not how long the current off time is (i.e. since last state change). I just want to have a time like "binary_sensor.test has been off since 2 hours" which resets with the next on/off toggle.

The templates I have found in the forums always use some complicated set of actions, triggers etc. - right now I have the binary sensor with its attached state. The data all seems in the logbook already, so i pretty much want to display the time from the last entry from the logbook

inner mesa
wanton ledge
inner mesa
narrow topaz
#

I have a fun jinja coding challenge! I want the average temperature of occupied rooms based on motion within the last n minutes. Any smart way to do this without a ton of if statements?

lime olive
# inner mesa It's never been supported for a sensor. Perhaps you want a binary_sensor?

Thanks, so I put the following under binary sensor

It's working fine without delay. But when I put the delay HA gives me the following

Invalid config for [binary_sensor.template]: [off_delay] is an invalid option for [binary_sensor.template]. Check: binary_sensor.template->sensors->testsensor->off_delay. (See ?, line ?).

https://www.toptal.com/developers/hastebin/ibitubunik.yaml

I've been trying to get this to work for the last 2 hours lol

#

Would be great if you can put something together for me to test out, please 🙂

inner mesa
#

your indentation is still off. please see the examples in the docs

narrow topaz
willow rapids
#

Rest Sensor Templating issues.

when I do a curl, with the api key it works. (from a different box on same network)

curl -X 'GET' 'http://thisismyipaddress/api/meal-plans/today' -H 'accept: application/json' -H 'Authorization: Bearer myapikeygoeshere

#

it spits out all of the expected JSON

silent barnBOT
marble jackal
willow rapids
#

Any thoughts on 255 char of sensor.rest_command limitation?

inner mesa
#

It's a thing

willow rapids
#

if I follow it to the letter I'm getting ''' homeassistant.exceptions.TemplateError: UndefinedError: 'value_json' is undefined '''

inner mesa
#

probably isn't returning JSON, or is just failing

tepid onyx
hallow peak
#

newb question: i'd like to customize the device_class of multiple binary sensors based on an attribute shared by the devices. i know that i can do this in customize.yaml for each specific entity. just wondering if there is a way to do this with less toil. i thought maybe templates could be used.

willow rapids
willow rapids
slate mist
#

Hi guys. A very simple question, but I cant seem to get my head around template sensor rounding. I have a water meter that reports in m3. I want to display liters that were used daily, but without any decimals. I now have this sensor: https://www.codepile.net/pile/JQBARag7. How do I get rid of the decimal?

rose scroll
#

Try round(0) or, if it returns the same number of decimal places all the time, string indexing. Eg. "(xxx.000 | string)[:-4]" will give you "xxx"

marble jackal
#

by use of | round(0), but make sure to add parenthesis around the formula, otherwise you are only rounding 1000. Filters are applied first in the order of operations.

#

as round also automatically cast the value to a float, you could also use | round(3) instead of | float in this case

wanton ledge
#

how do I set the entity_ID using a template? It always seem to be name, but the name I want to be a friendly name and I can't seem to be able to set a friendly name using the "new" format (compared to legacy) https://www.home-assistant.io/integrations/template/

#

I tried setting the unique_id but it doesn't seem to have any impact on entity id

marble jackal
#

The unique_id is as an identifier by HA itself, it has no influence on the entity_id (unless you con't provide a name). However if an unique_id is provided, you can change the enitity_id by editing the entity in the GUI

#

If you omit the name the entity_id will be sensor.template_{{ unique_id }}

wanton ledge
#

ah! very interesting. I would really love to be able to set more entity_id's. This seems to be a thing all over the system that entity_id is something I set later via the UI. Maybe I should go ahead and omit the name and set that later then to get "clean" entity_Ids

sacred sparrow
#

with my wait template

{{ is_state('input_boolean.office_status', 'off') or is_state('input_select.home_status', 'off') }}

how can I make it to wait for the OFF state to be off for 2 minutes before moving on with the automation?

#

the OFF state of input_boolean.office_status anyway - the other can stay is it is

#

so technically wait until input_boolean.office_status is off for 2 minutes

thorny snow
#

The following template is still not doing what I want to achieve:
{{ 'Deutschlandfunk' in states('media_player.sonos_kuche.media_channel') }}

What I actually want to do: I want to check whether the device (media_player.sonos_kuche) is playing a certain channel (Deutschlandfunk).
The issue is that the channel name is not fixed and can be extended by whatever is currently playing, e.g. ("Deutschlandfunk" or "Deutschlandfunk - Nachrichten").
So, I cannot simply check the content but need to workaround to use a template.

Sadly, this seems to not work yet, as I get:
Result:
result: false
entities:
- media_player.sonos_kuche.media_channel
even though the channel is indeed "Deutschlandfunk".

I think the mixing of entity and state is probably wrong. But I do not know how to fix it. I simply do not understand the documentation.

Any idea what I'm doing wrong?

If I check
{{ 'Deutschlandfunk' in states('media_player.sonos_kuche.media_channel') }}
in the template tab, I do get a "false".

But if I check media_player.sonos_kuche in the states tab, it says:
media_channel: Deutschlandfunk

Just did some testing:

{{ (state_attr('media_player.sonos_kleines_bad', 'media_channel')) in 'Deutschlandfunk' }} returns "true"
{{ 'Deutschlandfunk' in states('media_player.sonos_kleines_bad') }} returns "false"
{{ 'Deutschlandfunk' in states('media_player.sonos_kleines_bad.media_channel') }} returns "false"

Essentially, I would like
{{ (state_attr('media_player.sonos_kleines_bad', 'media_channel')) in 'Deutschlandf*' }}
or
{{ (state_attr('media_player.sonos_kleines_bad', 'media_channel')) in 'Deutschlandf.*' }}
(or something similar) to return "true".

I really don't get it.

wanton ledge
wanton ledge
#

Can I attach a template-entity to a device? I.e. I have an existing device (e.g. binary sensor with on/off & battery) - can I add a templated entity to that device? Would I use groups for that?

marble jackal
#

Nope, you can not add entities to device

solid fox
#

Is it possible to have multiple riemann sums in your config file? I’ve double and triple checked but my 2nd integral is not working

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.

fossil venture
solid fox
#

Somewhere halfway the first sector. I've made 1 file for both tempate and config but got it configured seperatly in HA

fossil venture
analog mulch
#

I'm experimenting with writing down a time something triggered into a sensor. This below never seems to trigger -- the state is always unknown. Any idea why?

- trigger:
    - platform: state
      entity_id: input_boolean.test_switch
      from: "off"
      to: "on"
  sensor:
    - name: Kids Pani Hana Arrival Time
      icon: mdi:baby-bottle
      unique_id: "woutmpo4utmp384tmp348ytpmj3984yt"
      state_class: measurement
      device_class: date
      state: "{{ now() - timedelta(hours=1) }}"
inner mesa
#

Did you want hours=1 or hours=-1?

#

Try the template in devtools -> Templates

analog mulch
#

of course. a typo. thanks!

#

ok, so I've edited the stupid typo in the timedelta, but it still doesn't trigger when I flip the test_switch

#

I get this in the log
"sensor.kids_pani_hana_arrival_time rendered invalid date 2022-04-08 15:23:46.702796+02:00"
I thought I was supposed to supply a datetime object to the state if the device_class is a date?

marble jackal
#

You should use device_class: timestamp. device_class: date only expects the date YYYY-MM-DD

analog mulch
#

Is there a device_class for a sensor which would contain a time duration? I want to keep track of the time that someone was present during the day and not sure if I should return seconds, which I could then convert/display in hours or I should just fix my unit of time and track hours>

marble jackal
analog mulch
marble jackal
#

Yep

fierce hornet
#

Does someone know what is going wrong here? I've a template sensor that displays the volume of my Sonos One speaker. Using a very simple {{ state_attr('media_player.one', 'volume_level') | float * 100}}. In state developer tools the volume shows as 0.28. But the template dev tools & the sensor shows 28.000000000004 for some reason

inner mesa
#

It's just the way computers handle floating point numbers.

#

just round it

fierce hornet
#

Ahh okay, I'll do that. Thanks!

fierce hornet
#

Maybe I'm forgetting something but when adding a simple | round(1) to the end of my template nothing changes?

inner mesa
#

you're probably rounding 100

#

add parens

fierce hornet
#

What are parens? English isn't my first language😅 and where?

inner mesa
#

Parentheses

#

Around the thing you want to round

fierce hornet
#

That did the trick, thanks!

marble jackal
#

Is it possibe somehow to remove a key from a dict in jinja?

inner mesa
#

Nope

#

You need a new dict without it

marble jackal
#

So loop through all keys and build a new dict but ignore the ones I don't want

inner mesa
#

Or with a filter

marble jackal
#

Let me think about that 🙂
Assume I have:

{% set example = { 'a': 1, 'b': 2, 'c': 3 } %}

How would I remove example.a then?