#templates-archived

1 messages Β· Page 151 of 1

olive moth
#

any idea how is can make a template that excludes part of entity_id?
i want to make a custom popup for my vacuum which looks like this in the config:

type: custom:vacuum-card
entity: {{ entity_id }}
image: default
compact_view: false
map: camera.xiaomi_vacuum_upstairs_map <<<< Fior this I need also a template that gives out this entity

so something like replace vacuum with camera.{{ entity_id }}_map
or how could i get the right map from the vacuum i call with {{ entity_id }} ?

marble jackal
#

Templates generally don't work in cards

olive moth
#

they do πŸ™‚

mighty ledge
#

unless you're using lovelace_gen

#

which it might look like it does

slate tundra
#

for testing propose: how do you set the state of a sensor in a template with {% set sensor.name=?? %} or how

#

?

#

i've tried a few things did not work

mighty ledge
#

make a variable and use the variable

#
{% set xyz = state_attr('sensor.xyz', 'friendly_name') %}
{{ if xyz == 'abc' %}...

vs

{% set xyz = 'abc' %}
{{ if xyz == 'abc' %}...
slate tundra
#

unfortunate i cant use value_template: "{{ not is_state('sensor.hacs', 'unknown') and (states('sensor.hacs')|int > 1) }}" with a variable

mighty ledge
#

you can, see above

slate tundra
#

or if i can i have to do a lot of ifs that has nothing to do with templates in my automation

#

ok

#

thanks @mighty ledge appreciate it

mighty ledge
#

it's programming, you can basically do anything you dream up if you have the patience and persistence

slate tundra
#

how would i test this value_template: "{{ not is_state('sensor.hacs', 'unknown') and (states('sensor.hacs')|int > 1) }}" for example

#

i am interested to be able to set the state of that sensor to 1, 2, 5, 0, etc

#

if i can't do this i have to imagine what happens, no?

#

i can't actually see, test

mighty ledge
#

same as what I wrote above...

slate tundra
#

i dont see a way to do it if you guys can help

mighty ledge
#
{% set x = states('sensor.hacs')|int %}
{{ not is_state('sensor.hacs', 'unknown') and (x > 1) }}
#

then change x

#

to whatever number you want to test

#

same as above

slate tundra
#

i'll try it out thanks

#

works, not as expected but good enough

#

ty

marble jackal
#

you can also set the state you want to check against in devtools > States

slate tundra
#

how

#

this is what i wanted

marble jackal
#

With the big blue SET STATE button

mighty ledge
#

I don't suggest going this route as your state will now have this value

slate tundra
#

@marble jackal you are truly the boss of templates πŸ˜„

#

yah i can reset it after

marble jackal
#

No, I'm not πŸ™‚

#

But as petro said it will have this state until it changes by another way

#

Can give unwanted results, eg trigger automations or whatever

slate tundra
#

it's fine

#

i can re set it to whatever it was before whan i am done

#

and done, it's fixed, took 2 minutes

#

ty again

nimble marsh
#

idk if you'd be interested in int, but there's a set_state.py script floating around. i'll link it.

slate tundra
#

what can u do with it?

nimble marsh
#

this lets you set the state of any sensor in an automation, for example, including entities that don't have a service already (binary_sensor, for instance).

#

i personally use it to set the state of a z-wave door/window sensor in our mailbox that sometimes freezes open in the winter, so it stops nagging us to go get the mail πŸ˜„

marble jackal
#

I would just add an input_boolean for that, to disable the automation

#

No reason to change the state

nimble marsh
#

sure if you want to have two entities just for that. different mindset i suppose.

#

i did end up setting up a "mail waiting" input boolean (which is turned on when the mailbox sensor goes 'on') which is what the automation works off of. but the sensor state still triggers my OCD.

mighty ledge
#

I just use MQTT with MQTT discovery and actually create the entities through conventional means. Keeps the entity updated, maintains state through restart, can be attached to devices, and can be managed through the UI.

#

I use a script to set the configuration and state with an automation.

nimble marsh
#

hundred ways to complete pretty much any given task. love it! πŸ™‚

mighty ledge
#

it's using the raw api and if you odn't understand what it does, you can shoot yourself in the foot.

slate tundra
#

i am also good, dont need it, but that doesn't mean we don't appreciate it @nimble marsh

#

ty

silent barnBOT
restive seal
#

Hi everyone, does anybody know how can I "sum" each property value to get my current month water consumption ? Here the result from
{{ states.sensor.suez_water_client.attributes.this_month_consumption }} : https://hastebin.com/qumicovijo

inner mesa
#

{{ states.sensor.suez_water_client.attributes.this_month_consumption.values()|sum }}

restive seal
fierce robin
#

I think I'm making a dumb mistake but I'm not sure how to resolve it. Can anyone help? Template warning: 'round' got invalid input 'unknown' when rendering template '{{ float(states("sensor.gem_power_ch29")) + float(states("sensor.gem_power_ch32")) | default(NaN) | round (2) }}' but no default was specified.

inner mesa
#

First, you can't round NaN. Second, adding a default later won't fix the fact that earlier calls get garbage

fierce robin
#

Okay, so round can be defaulted directly like round(2, argument3 = NaN) if I'm reading that correctly? and I'm not trying to "fix" that there was garbage, I'm trying to "fix" that homeassistant is claiming this template syntax won't work in 2022.1 and higher. If the sensor value is unavailable, I just need unavailable to make it all the way through (as NaN is fine) without breaking :)

#

(if I had the option I'd use the previous value that wasn't unavailable but I haven't figured out how to do that yet)

inner mesa
#

I don't know that Jinja understand what NaN is, but if it's just for you, I guess it's fine. Ideally, you would add defaults to the float() calls and ensure that the result of the addition is numeric

fierce robin
#

I can try that (sorry, I didn't know the functions could accept defaults until reading that link you sent - I thought it had to be a filter)

#

I don't know why the sensors are "unavailable" sometimes, I just need HA to not break when that happens :)

#

Thank you for the help!

fierce robin
#

Adding a default argument to the float() method worked!

mighty ledge
floral shuttle
#

havent used that for a while, and must have a look if we can skip that python there, and use core HA functionality

#

admit that I use the hass.states.set() in other python scripts though, including their attributes. Those entities(states) are not created in HA itself, so cant do any harm

chilly ferry
#

I'm trying to create a bayesian sensor to determine when I'm cooking, probably I'll fail on it, but I'd like to explore this type of sensor as I find it very interesting.
What I'm thinking to do is to create a script that will tell me for how long presence have been detected for the last X seconds (30, 60, 90, etc). I know I can find all that info in the States table, so I was thinking to run a SQL query in the script, but is there any better way to achieve this from a script?

fickle cedar
#

Hello guys,

How can I write a template that will return a true or false if the energy consumption went above X in the last 5 minutes? :x

chilly ferry
#

thanks I just found it! I was about to replay you with that

#

now I just wondering how can I make it part of a script so I can have dynamic duration

marble jackal
fickle cedar
chilly ferry
fickle cedar
chilly ferry
fickle cedar
#

yes... one for each time range

chilly ferry
#

So if I set it to 5m, will I have to wait 5 minutes per update?

fickle cedar
#

ah! tha's a good question.. I use 3 sensor of those, to check how many times we turn on/off the lights in the last minute.... the sensor returns always the correct value, but I dont know how many times the sensor checks...

chilly ferry
#

oh then it might be good enough for it... I'll give it a check and see

fickle cedar
#
  • platform: history_stats
    name: Small Bedroom Lights on 1min
    entity_id: light.small_bedroom_lights
    state: "on"
    type: count
    end: "{{ now() }}"
    duration: 00:01:00
chilly ferry
#

that's what I have now but with time

#

I guess with count should be good enough too, but I wanted to know the time for the probs, but the time is in hours so not very accurate if I want to make it in seconds

#

still that should work for what I'm trying to do

chilly ferry
clear barn
#

Hi, I'd like to loop through an array and set attributes to a person with values in that array. The person entity is available in that array, so matching works. How do I set the values in an automation according to my plan? Thanks!
Automation:
service: python_script.set_state
data_template:
loop start ....
var1:
var2:
entity:
loop end...

chilly ferry
chilly ferry
mighty ledge
silent barnBOT
chilly ferry
mighty ledge
silent barnBOT
clear barn
mighty ledge
#

I have no idea what you're asking

clear barn
#

Ok :) i'll try to Figure

mighty ledge
#

or you can rephrase the question to be more explicit

#

this is the template channel, so the questions are usually related to templates

chilly ferry
# mighty ledge history_stats

is there anyway to check the history stats with time from the UI or from templates? Or am I forced to create new sensors? I'd like to have some "one-time" checks, like to see for how long X history sensor was greater than 0 during a specific range of time, but I won't need it more than once for that range of time

#

last time I created a small script in NodeJS (just because I'm faster with JS) checking the states table from the DB, but I find it a bit tedious specially seeing that sometimes the state of my occupancy sensor changes from ON to UNKOWN to ON

mighty ledge
#

that's how it's designed

#

you add on, you don't modify

chilly ferry
#

I see

#

well, I guess I'll end up deleting them and that's it

#

it was more for analysis

mighty ledge
#

Yep

chilly ferry
#

I installed JupyterLab, but I'll have to spend some time to learn how to use panda and whatnot to achieve what I want

#

so maybe it's easier just create 10+ sensors lol

mighty ledge
#

I have full testing entities that I add / delete whenever I'm trying to figure out the best way to do things

#

if you're good with python scripts you can do the same however that env is limited

chilly ferry
#

limited in what sense? in the way that the DB doesn't have the info as up to date as HA?

young jacinth
#

hi,
how do I pick the second item of a list?

mighty ledge
#

Yourlist[1]

young jacinth
#

this is working aslong as rgb_color is a list

{% set rgb_color = [255,0,250] %}
{% set rgb_red = rgb_color[0]-1 %}
{% set rgb_green = rgb_color[1]+5 %}
{% set rgb_blue = rgb_color[2]-1 %}
{{ [rgb_red,rgb_green,rgb_blue] }}

but i get rgb_color as a string like that
{% set rgb_color = '[255,0,250]' %}
as rgb_color is defined in an input text in a blueprint

is it possible to convert rgb_color so the template works?

mighty ledge
young jacinth
#

i just made an example here

mighty ledge
#

Feel free to @ me so I can respond faster

rigid chasm
#

Hi all you great people.. I am having issue with template sensors that i am trying to get to work. I have my config split up into packages, and my sensor seems to be ok in the yaml file but when i try to add the sensor in the lovelace Ui Homeassistant can't find the sensor?

#

i get this message Entity not available sensor.weekly_water

young jacinth
#

so it's not working currently as Iam getting an error

mighty ledge
#

then in your template....

#
{% set rgb_color = rgb_color.split(',') | map('int', 0) | list %}
#

if you keep the [ ] as the input....

#
{% set rgb_color = rgb_color[0:-1].split(',') | map('int', 0) | list %}
young jacinth
#

it works in the service_call editor
lets see if it works with the blueprint

#

it works, thanks alot @mighty ledge πŸ₯³

frank gale
#

I want to filter an object with selectattr so to return the ones that are not in the list. That means I am trying to do the opposite of:
{{ states.sensor | selectattr('state','in',['on','unavailable'] }}
Is there any test that can replace the 'in' with 'not in' ? Didn't find any...

mighty ledge
frank gale
#

Oh it's from...to

marble jackal
frank gale
#

Wow! I have already used that and totally forgot about that!

#

Thanks!

#

Hmm no that doesn't help

#

So I still need to check if something isn't in list

#

No, no it works!

mighty ledge
#

or map and then check if the item is in the mapped array/list

#

you have many many options

#

how about you post what you want and people can help you

frank gale
#

Thank you, already solved with rejectattr ;)

#

I used to do it with mapped array list but I found it ugly. Wanted to just use a filter and totally forgot about rejectattr till TheFes mentioned that

pine musk
#

[9:20 AM] Jazz: Good Morning (afternoon, evening) wise beings. I am trying to display a list of all geo location events
[9:23 AM] Jazz: I know I need a markdown card, just not sure how to reference the ephemeral geo_location items.

#

nevermind. I got lucky with the template

pine musk
#

ok, at least lucky enough to be in the right ballpark.

mighty ledge
floral shuttle
pine musk
#

petro: I am trying to enumerate all the geo_location items, and explode out all the attributes, as part of a markdown card

#

I have this much, working, so far:
{% for state in states.geo_location %}
{{ state.state_with_unit }}: {{ state.name }},
{% endfor %}
which is giving:
263.7 km: M 1.1 - 7 km SE of Marston, Missouri,
and so on.

mighty ledge
mighty ledge
odd condor
#

Hello, a quick help, please. What am I missing here? Must be something really simple, but it's late and my brain is probably just off.

{% set output = namespace(switches=[]) %}

{% for state in states.switch %}
  {% if state.state == "off" %}
    {% set output_nr = output_nr + 1 %}
    {% set output.switches = output.switches + [state.name] %}
  {% endif %}
{% endfor %}

{{ output_nr }}
{{ output.switches }}```
Result: output_nr = 0, but output.switches has a list of them all that are currently off. Also, if I move output_nr line outside of the loops, then it works. ?? Am I stupid or blind? Thanks!
dreamy sinew
#

output_nr needs to be in the namespace

odd condor
dreamy sinew
#

but you could also do {{ output.switches|length }}

odd condor
#

You're right, that's even simpler. Thanks!

void kestrel
#

In examples I see things like
{% code %}
{%- code %}
{%- code -%}
{% code -%}

Does the "-" do anything? Seems like it might just help you clearly see the start and end of case statements, but it isn't really needed?? Or is there another reason for it?

quaint crystal
#

it chomps newlines

void kestrel
#

thanks!

inner mesa
#

It's generally unnecessary unless you're generating a string and white space matters for presentation. It doesn't matter for logic

celest tinsel
#

I built these template sensors to help me keep track of running appliances based on the energy draw from the smart outlet. The entities are not being created after restart. What am I doign wrong?

- platform: template
  sensor:
    - name: "Keezer running"
      delay_on: 00:00:02
      state: "{{ {% if states('sensor.keezer_power_current')|float(0) > 0.3  %} on {% else %} off {% endif %} }}"
    - name: "Sump running"
      state: "{{ {% if states('sensor.bsmt_sump_smartenergy_metering')|float(0) > 100  %} on {% else %} off {% endif %} }}"
    - name: "Dehumid running"
      delay_on: 00:00:02
      state: "{{ {% if states('sensor.bsmt_dehumid_smartenergy_metering')|float(0) > 100  %} on {% else %} off {% endif %} }}"
inner mesa
#

You're nesting templates

#

You can get rid of all the {{ }}

#

And it would be clearer if you convert them into multi line templates, but it should work like that

celest tinsel
#

understood

inner mesa
#

Or even better {{ x if y else z }} style

celest tinsel
#

so {% on if states('sensor.keezer_power_current')|float(0) > 0.3 else off %}

inner mesa
#

Or the new iif(y, x, z)

celest tinsel
#

not seen that syntax

#

I did see that

inner mesa
#

No, see my message again

#

{{ }}

#

And you need to quote the strings in there

celest tinsel
#

{{ "on" if states('sensor.keezer_power_current')|float(0) > 0.3 else "off" }}

inner mesa
#

'on' and 'off', but yes

#

You're also mixing up the old and new template formats

celest tinsel
#

I think I run across too many example. getting my head around templates is taking me a long time

#

are you referring to the -name construct

inner mesa
#

Stick to the docs and you'll be fine

#

state: is incorrect in that format

celest tinsel
#

was using the first example in the docs for state-based

inner mesa
#

You have a little of the new format and a little of the legacy format

#

That's not what you posted above

celest tinsel
#

I see now

#

And I realized my templates file wasn't included I never could have solved it

formal ember
#

Is there a way to make a list via a template of say, color palettes of a WLED light, so you can rotate through that with a remote (via automation)?

acoustic arch
#
{% set max_value_on_list = max(rain_values_list) %}```
#

how can i get the second highest value? and thirth? etc?

mighty ledge
mighty ledge
formal ember
coarse sable
#

How do I address the fields from this rest api result ?

[
  {
    "number": "0113",
    "name": "John",
    "time": "2022-02-25T10:31:31.023"
  },
  {
    "number": "0114",
    "name": "Jane",
    "time": "2022-02-25T10:31:26.103"
  }
]```
acoustic arch
#

This is gonna get complicated real fastπŸ˜†

mighty ledge
#

Not really, (rain_values | sort)[-2]

marble jackal
#

I expect he has another list with dates or something, which is related, and for which he combines data based on the index

#

But not sure πŸ™‚

silent barnBOT
#

The XY problem is asking about your attempted solution rather than your actual problem.

This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.

The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.

marble jackal
coarse sable
acoustic arch
#

I'm super novice so this is tough for me.

marble jackal
acoustic arch
#

Can I put 2 values on one indexnumber? Like a nested list?

#

That way I can sort and extract them

coarse sable
marble jackal
#

Easiest is to create a list with ditionaries, in which your data is combined together

marble jackal
marble jackal
formal ember
#

So pretty much I have the following template - "{{ state_attr('light.wled_henrys_light', 'effect_list') }}" which returns a long list of the options available to that state attribute. how would I be able to cycle through them in an automation? i.e. if I have a left and right button, i would like to be able to scroll through the list, and go back...

mighty ledge
formal ember
#

ah right, thanks for the nudge in the right direction

formal ember
mighty ledge
#

you use a normal light.turn_on service call using the effect

marble jackal
#

Guess this should also work:

service: light.turn_on
target:
  entity_id: light.your_light
data:
  effect: >
    {% set light = 'light.your_light' %}
    {% set effect = state_attr(light, 'effect') %}
    {% set effect_list = state_attr(light, 'effect_list') %}
    {% set index_current = effect_list.index(effect) if effect in effect_list else 0 %}
    {% set next = 0 if index_current + 1 > effect_list | count else index_current + 1 %}
    {{ effect_list[next] }} 
formal ember
#

Are we meant to call you TemplateGod instead of TheFes?

marble jackal
#

No please πŸ™‚

formal ember
#

hahaha

#

let me try and work my brain around that one

#

{% set light = 'light.light.your_light' %} how come there is two light. here? typo?

mighty ledge
marble jackal
#

{% set index_current = effect_list.index(effect) if effect in effect_list else 0 %} this became more complicated than I expected because the standard effect is None and even if I explicitly enter that as a string, the template editor still converts it to null, which is not in the effect_list

mighty ledge
formal ember
#

so when I added it to the automation and saved, it changed the template. sigh...

marble jackal
#

It probably formats it as a one line template

#

the GUI does that

formal ember
#

ah yep. changing via code editor now

marble jackal
formal ember
#

this isn't working

#

oh jesus i see why

#

hmmm, nup, still no go.

mighty ledge
formal ember
#

nice

#

lets get + 1 % working first eh?

#

πŸ˜›

#

service call works fine

#

must be the trigger

mighty ledge
#

why are you doing a blueprint

#

just make a script

#

and then make an automation that calls the script

marble jackal
formal ember
#

ah nice

mighty ledge
#

blueprints are for when you're repeating a process with other entities, but you're hard coding it. So you're just making the process harder

marble jackal
#

I tested it myself, and it has some troubles to select effect_list[0]

#

wait, my bad

formal ember
coarse sable
formal ember
#

but yeah good point on the scripts

marble jackal
#

Okay, 2 things:

  1. the highest value is not effect_list | count but effect_list | count - 1
  2. because Jinja translates "None" to null it can not apply effect_list[0] after 1) is corrected.
#

Any idea about that 2nd one petro?

mighty ledge
#

is this when the light is off?

marble jackal
#
service: light.turn_on
target:
  entity_id: light.your_light
data:
  effect: >
    {% set light = 'light.your_light' %}
    {% set effect = state_attr(light, 'effect') %}
    {% set effect_list = state_attr(light, 'effect_list') %}
    {% set index_current = effect_list.index(effect) if effect in effect_list else 0 %}
    {% set next = 0 if index_current + 1 > (effect_list | count -1) else index_current + 1 %}
    {{ effect_list[next] }} 
mighty ledge
#

you can use -1 as an index

#

and it'll choose the last item

#

and you don't need to subtract 1 from count

#

just do >=

marble jackal
#

This is the effect list:

effect_list:
  - None
  - Fast Pulse
  - Slow Pulse
  - Strobe
  - Flicker
  - Random
#

The first one is simply no effect, so on normally, no special things

mighty ledge
#

so "None" is the object none

#

or the resolution after the fact is adjusting it to none

#

I see

marble jackal
#

but Jinja translates that to null, so it will try to apply effect null

mighty ledge
#

can't get around that

#

it's not jinja

#

it's the template resolution

#

jinja only outputs strings

#

we try to smarten the typing after the jinja is resolved

#

and look for a bunch of shit

#

None, none, '', and a few others resolve to null

formal ember
#

good thing there isn't a none on my effect list?

#

Android, Aurora, Blends, Blink, Blink Rainbow, Bouncing Balls, Bpm, Breathe, Candle, Candle Multi, Candy Cane, Chase, Chase 2, Chase 3, Chase Flash, Chase Flash Rnd, Chase Rainbow, Chase Random, Chunchun, Colorful, Colorloop, Colortwinkles, Colorwaves, Dancing Shadows, Dissolve, Dissolve Rnd, Drip, Dynamic, Dynamic Smooth, Fade, Fairy, Fairytwinkle, Fill Noise, Fire 2012, Fire Flicker, Fireworks, Fireworks 1D, Fireworks Starburst, Flow, Glitter, Gradient, Halloween, Halloween Eyes, Heartbeat, ICU, Juggle, Lake, Lighthouse, Lightning, Loading, Meteor, Meteor Smooth, Multi Comet, Noise 1, Noise 2, Noise 3, Noise 4, Noise Pal, Oscillate, Pacifica, Palette, Percent, Phased, Phased Noise, Plasma, Police, Popcorn, Pride 2015, Railway, Rain, Rainbow, Rainbow Runner, Random Colors, Ripple, Ripple Rainbow, Running, Running Dual, Saw, Scan, Scan Dual, Scanner, Scanner Dual, Sine, Sinelon, Sinelon Dual, Sinelon Rainbow, Solid, Solid Glitter, Solid Pattern, Solid Pattern Tri, Sparkle, Sparkle Dark, Sparkle+, Spots, Spots Fade, Stream, Stream 2, Strobe, Strobe Mega, Strobe Rainbow, Sunrise, Sweep, Sweep Random, TV Simulator, Tetrix, Theater, Theater Rainbow, Traffic Light, Tri Fade, Tri Wipe, Twinkle, Twinklecat, Twinklefox, Twinkleup, Two Dots, Washing Machine, Wipe, Wipe Random

πŸ˜„

mighty ledge
#

if there is no none in your list, you're fine

formal ember
#

cheering

mighty ledge
#

if there is a none, you'd just have to skip that effect

formal ember
#

ah yep

marble jackal
#

Okay πŸ™‚

#

No problem then

mighty ledge
#

I can't think of a way to make that work

formal ember
#
    data:
      effect: >
        {% set light = 'light.wled_monitor' %}
        {% set effect = state_attr(light, 'effect') %}
        {% set effect_list = state_attr(light, 'effect_list') %}
        {% set index_current = effect_list.index(effect) if effect in effect_list else 0 %}
        {% set previous = 0 if index_current + 1 > (effect_list | count - 1) else index_current - 1 %}
        {{ effect_list[previous] }} 
#

would that be the previous one?

mighty ledge
#

Actually.......

formal ember
#

and I am probably going to reduce this to about 5 effects btw, for my kids...

mighty ledge
#
service: light.turn_on
target:
  entity_id: light.your_light
data: >
    {% set light = 'light.your_light' %}
    {% set effect = state_attr(light, 'effect') %}
    {% set effect_list = state_attr(light, 'effect_list') %}
    {% set index_current = effect_list.index(effect) if effect in effect_list else 0 %}
    {% set next = 0 if index_current + 1 > (effect_list | count -1) else index_current + 1 %}
    {{ {'effect': effect_list[next]} }}
formal ember
#

no need for their reading lights to be strobing haha

mighty ledge
#

@marble jackal my last post should work with None

#

skirt around the issue by templating the entire data section. The resolver doesn't recursively move through your object so the none should stay a string

formal ember
marble jackal
#

Ah yes, it works

mighty ledge
#

you can template the entire section to bypass voluptuous validation (the python lib) and to bypass templating typing on specific fields

marble jackal
#

Will do!

mighty ledge
#

it's sneaky fuckery. Don't tell to many people

marble jackal
#

Well I've been doing some tricks as well to try to store data surviving reboots (to store media_players states, and restore them later)
Example, you leave house in the morning, states are stored, but at office you reboot HA because of an custom component update, and back at home the data is still available to restore the media_player on the right channel/spotify account etc

formal ember
#

so much to learn. i get how it all works but no idea how you'd put the ground work down and put that on paper

marble jackal
#

I created a ordered dict with a for loop, write it to a file using the file integration and take it out again using a command line sensor

mighty ledge
#

I have an automation that creates the config on startup, and an automation that plops my data into MQTT which in turn updates sensors

formal ember
mighty ledge
#

it's basically a different way to have template sensors that persist startup

mighty ledge
#

if you want to call the action and skip waiting for the result (to call another action), use script.turn_on

formal ember
#

ahhh

mighty ledge
#

script.toggle turns it on or off depending on it's current state

#

it's also non-blocking like script.turn_on

formal ember
#

this is the trace from when I try to run it via an automation

#

it does work via a service call tho in the dev tools section

#

but if I do it via a service call it is fine, has to be the blueprint.

#

Thanks a lot legends!

marble jackal
#

there seems to be some kind of check in the blueprint related to your Zigbee integration, which is blocking execution

silent barnBOT
mighty ledge
# silent barn

what do you mean neater idea? That seems fine @coarse sable

coarse sable
#

neater...more efficient...more elegant... but if this is fine, then i'll gladly accept that !

mighty ledge
#
{{ expand("sensor.rest_get_last_person_0", "sensor.rest_get_last_person_1", "sensor.rest_get_last_person_2") | map(attribute='attributes.idNumber') | list | random }}
coarse sable
#

Related question : will this trigger refresh the REST sensor it uses, before setting the random sensor state ?

#

Allowing me to set the REST sensor's scan_interval to a huge value.

#

From me watching devtools , i'd say Yup, but I need to be sure.

obsidian marten
#

Looking for suggesting re templating the following: I have an LED strip running wled, integrated just fine. I want to set the level (brightness) of the wled strip to match the corresponding brightness from a zwave dimmer switch that controls overhead lights. So if dimmer set at 50%, want the LED strip to be set at 50% (brightness/level). I don't expect them to match exactly so will map out the appropriate conversion through trial and error. Thanks so much!

dreamy sinew
#

step 1, create a formula for your conversion

obsidian marten
dreamy sinew
#

template trigger on the brightness attribute has increased on the zwave entity. light.turn_on service call with a template value of brightness: {{ (trigger|int(default=0) * .8)|round(0) }}

obsidian marten
glacial creek
#

I am trying to find a list of all the functions that can be used in templates. Are they documented anywhere? Functions such as area_entities(β€˜area name’)

inner mesa
#

those are the mostly HA-specific ones, and the Jinja docs show the "standard" ones

silent barnBOT
paper hazel
#

I have a template sensor which calculates the time remaining on a print from the finish time as reported by OctoPrint. This works well if a print is running, but if there is nothing printing, the estimated finish time sensor has a value of 'unknown' and this is generating warnings in my log file. as seen below, this was my idea of working around it, but the value is showing '0', but the errors are still popping up in the log. Any suggestions will be appreciated...```
{% if states('sensor.octoprint_estimated_finish_time') == 'unknown' %}
{{ 0 - 0 }}
{% else %}
{{ (as_timestamp(states.sensor.octoprint_estimated_finish_time.state) |int - as_timestamp(now())) | timestamp_custom('%H:%M:%S', false) }}
{% endif %}

marble jackal
#

Are you sure the state is unknown and not unavailable

paper hazel
#

Yip - verified it in the "States" page and also with a template ```
{{ states('sensor.octoprint_estimated_finish_time') }}

floral shuttle
#

this works: service: cover.set_cover_position target: entity_id: > {% set stil = '_stil' if is_state('input_boolean.discrete_covers','on') %} cover.rolluik_voorkamer{{stil}},cover.rolluik_logeerkamer{{stil}} but feels a bit insecure without else guard.

#

the alternative would be{{'cover.rolluik_voorkamer_stil,cover.rolluik_logeerkamer_stil' if is_state('input_boolean.discrete_covers','on') else 'cover.rolluik_voorkamer,cover.rolluik_logeerkamer' }} but thats even more awkward, with those to strings for entity_id's..

#

would appreciate code quality improvement suggestions...

manic onyx
#

HI everyone. How can I check if my sensor value is the same for two consecutive hours? Trying to get an alert on a water leak

#

or create another sensor (like utility one) that resets hourly and compare current and previous value? I am using mini-graph-card and it somehow can group by hour, so it must be possible to do in a template?

dreamy sinew
#

templates mainly deal with what is not with what was

#

exceptions exist in the automations framework

manic onyx
#

@trim oak I did not want to create yet another sensor just to fire off an automation

manic onyx
#

can you do multiple state comparisons in one line with like AND/OR to give true/false in the end?

#

{{ (states('sensor.sensor1') | int > 0 AND (states('sensor.sensor2') | int > 0) }}

inner mesa
#

with a lowercase "and", yes

dull stone
#

hi guys, trying to add a couple of sensors via the template action, 1/3 shows up in HA after restart and config checks out, the bottom one works, the others dont. https://pastebin.com/gaxhi7q6 This is added to configuration.yaml Anyone got any ide whats wrong?

#

the templates works in developer/templates

noble fern
marble jackal
#

Only add template: once. Remove line 23 and 35

dull stone
#

that did the trick. thanks guys!

noble fern
#

See, @marble jackal is awake and explained it with the expurgated version. I waffle when I'm tired. I'm off to bed. Glad it worked!

dull stone
#

πŸ™‚

plain forge
#

Hey everyone, I'm looking for a way to find the first value in a list that is above a set threshold. Is there a way to do that in a template?

marble jackal
#

What do you mean with first?

{% set list = [ 7, 3, 9 ] %}
{{ list[0] }} {# returns 7 #}
{{ list | min }} {# returns 3 #}
{{ list | max }} {# returns 9 #}
{{ list | sort | first }} {# returns 3 #}
inner mesa
#

or if they want the first value appearing in the list that's above a certain value:

#
{% set data = [4, 3, 5, 2, 6] %}
{{ data|select('gt', 4)|first }}
#

-> 5

sacred marten
#

sensor platform: min_max reports 'unknown' for mean of 3 temperature sensors - Only error in status of the min_max sensor is "unit_of_measurement: ERR" - but all temp sensors status shows β€˜unit_of_meas’ defined as Β°F - I am using core-2022.2.9 homeassistant/components/min_max/* @thorny snow - Please have look, why min_max is issueing "unit_of_measurement: ERR" and ig that's why Value of mean is returning 'unknown'?

plain forge
gusty bloom
#

Folks, this isn't a template, but it's nested JSONS within yaml, so I'm thinking it might fit best in this channel, pleae forgive me if it's misplaced. I'm having trouble with my payload, in the below snippet.

  - resource: http://192.168.0.129/api
    method: POST
    payload: '{ T: "Q", M: "ST", P: {} }'
    scan_interval: 120
    headers:
      Content-Type: "application/json"
      Accept: "*/*"
    sensor:
      - name: FalconTemp
        value_template: "{{ value_json }}" #| float | round(1) }}"
inner mesa
#

you're treating that whole dict as a string. is that what you wanted?

#

and you need to quote the keys

#

it's not valid JSON as it is

gusty bloom
#

I'll try quoting the keys, yes, mean for the whole thing to be treated as a string litteral, This payload produces the output I'm looking for in postman.

inner mesa
#

what trouble are you having with it?

gusty bloom
#

The service is complaining that it's not valid JSON

#

Where as in postman, it's fine.

inner mesa
#

it's not valid JSON

gusty bloom
#
 payload: '{ "T": "Q", "M": "ST", "P": {} }' 
inner mesa
#

πŸŽ‰

gusty bloom
#

tried that before I pasted it, but now I've got no sensor created, where as before I had a sensory with the error string that was being returned, turning up degug level to see what I can see

inner mesa
#

I'm not sure what you're doing there. what platform are you using?

gusty bloom
#

This is to talk to a Falcon F16v4 LED controller.

#

I think that did it

#

the return code in debug has data now, going to put back a few things I Was doing to debug

#

oh, my snippet missed :rest

#

@inner mesa Thanks so much, that did it!

formal ember
#

"{{ states.light | map(attribute='entity_id') | list }}"

I have this template for turning off all my lights. Is there a way to omit one entity from the template?

vapid stratus
#

Really struggling to get this template to work. I am trying to return a value of 4 if this iif is true and 0 if else. Here is the template:

{{ iif(is_state('counter.count') | int >= 4, 4, 0) }}

And I get the error

TypeError: is_state() missing 1 required positional argument: 'state'
formal ember
#

matter of putting a - light.dunny on the end?

inner mesa
#

{{ states.light | map(attribute='entity_id') | reject('eq', 'light.whateer')|list }}

#

no

inner mesa
vapid stratus
#

@inner mesa haha figured there had to be! Would love any help

inner mesa
#

okay, not many: {{ iif(states('counter.count') | int >= 4, 4, 0) }}

#

is_state() checks for equality to a value

vapid stratus
#

Ah! Makes sense. So I was likely trying to combine two conditions but only providing one

inner mesa
#

yes

vapid stratus
#

One more question. I was looking to use this (after my testing with this counter) with the repeat.index variable in a looped script. Would this work in that case?

{{ iif(states('repeat.index') | int >= 4, 4, 0) }}

inner mesa
#

it's not a state, it's a variable

#

{{ iif(repeat.index >= 4, 4, 0) }}

vapid stratus
#

Can I still call it in a template like that?

#

Oh cool let me try that!

inner mesa
#

it's also already an int

vapid stratus
#

Good deal. That worked. Thanks for the help @inner mesa

inner mesa
#

equal

silent barnBOT
formal ember
#

awesome cheers

obsidian lintel
#
  selectattr('state','eq','on') |
  rejectattr('attributes.type','eq','browser_mod' ) | list | join("\n ")
 }}```

How do I retrieve just the name of the entity?
inner mesa
#

See above for map()

#

map(attribute='name')

fossil venture
#

Change the icons and units to something representative of your sub-sensors.

rocky crypt
#

Hello. I'm wanting to create sensors based off another sensors value. Can someone point me in the correct direction? Each field segment is separated by a comma. So, I'm wanting to create three new sensors.
So for example,
MasterSensor Value: xxxxxx,yyyyy,zzzzz
SubSensor1 Value: xxxxxx
SubSensor2 Value: yyyyy
SubSensor3 Value: zzzzz

#

Opps! Sorry @fossil venture I didn't see that you already posted in here for me!

#

Thank you!!!

rocky crypt
#

So, I got it to work, but now I have another question. Can you use if statements for state: ?

#

I tried: {% if 'MYSEARCHSTRING ' in states('sensor.sub_sensor_4') %}

#

But doesn't seem to work as the value of my sensor is "Unavailable"

fossil venture
rocky crypt
#

Well, I got it working, but only if I use text. So, for true, if I put yes, it works. But what if I want a zone state?

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
#

Cant tell unless you show what you have done.

#

Also see my example before your post.

rocky crypt
#

In your example, it doesn't have an if else though?

#

Or am I missing something?

fossil venture
#

This "{{ "MYSEARCHSTRING" in states('sensor.master_sensor_here').split(',')[0] }}" will return true if the string is in the result. No else required.

rocky crypt
#

Ok. I see that now, but that's not exactly what I'm looking for.. Let me post my sample... One sec..

#

So, if it finds "fault ", then return the state of the split record. Otherwise, leave the state blank.

fossil venture
rocky crypt
#

Ok, now if FAULT isn't there, it says "Unknown" status. And if "Fault" is there, it says "states('sensor.sub_sensor_4').split(' ')[1]"

#

It doesn't actually pull the value for the state πŸ™‚

#

Ah! Fixed it πŸ™‚

#

Had to put the {{ around the states part πŸ™‚

#

Got it now! Thanks @fossil venture !

rocky crypt
#

When using a template sensor, is there a way for it to only update if value is true? Otherwise leave the sensor as is? I originally had it set it to "" (blank), but I actually need it to hold it's original value.

#

https://hatebin.com/mftvkknybc Is what I have now. But, if 'Fault ' isn't in the sensor, it sets the value to blank. I want it instead to hold it's current value in "faulted Zone Number"

marble jackal
#

Let it refer to it's own state, so {{ states('sensor.faulted_zone_number') }}

rocky crypt
#

Thanks @marble jackal πŸ™‚

#

That worked!

rocky crypt
#

What would be the best way to setup/program this? I have an automation that sends an email out. The email references a sensor. The sensor is a number value (1-50). In the email, I want it to say a value based on the number. Example, if the number is 1 on the sensor, say apples. If the number is 2, say oranges. Etc...
Am I best off creating another sensor and base it's value off the existing sensor?

rocky crypt
#

N/M. I ended up just creating a sensor and using if elif statements.

daring comet
#

Hey!
Ive got a 'game mode' which triggeres some things like shutting of distraction and turn lights off. Ive got a program that sends over the active window as a sensor and if the current active window is a game it'll active game mode.
Now my problem is that it works with the two other games but not with valorant. The value is exactly what its checking for, but it doesnt trigger for some reason.
My config: https://i.imgur.com/J2mlxOl.png
Playing Valorant: https://i.imgur.com/qHegZlg.png
Playing a game other than valorant:https://i.imgur.com/KwtaIVF.png
How do i go about fixing it? Ive copied the valorant value straight from the sensor and no matter how i sort the "or" lines its always the same, i cant find anything in the logs either

silent seal
silent barnBOT
marble jackal
#

And don't share screenshots of code

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.

daring comet
marble jackal
#

and what does devtools > States show when you have VALORANT open on your screen?

daring comet
#

VALORANT

#

wait i think i mightve figured it out

#

there are 2 whitespaces after the name

marble jackal
#

That will be important πŸ™‚

#

BTW is your game mode sensor a binary_sensor?

daring comet
#

the whitespaces didnt change anything, or do i need to format them in some special way in my config?

marble jackal
#

Then I would change it into one, you don't need the if statement then, and a binary_sensor only has the states on and off

#

And you can simplify your template

#

But what do you get in devtools >templates when you enter {{ states('sensor.activewindowsensor') }} with Valorant open?

daring comet
#

VALORANT

#

without whitespaces idk if discord would format that

#

in developer>state its
VALORANT

mighty ledge
#
{% set mode = states('sensor.activewindowsensor') | lower %}
{{ mode in ['valorant', 'brawlhalla', 'osu!'] }}

How are you including that code in your configuration?

daring comet
#

oh sweet! i think thats exactly what ive been searching for to make the whole thing simpler

#

ill give it a try

marble jackal
#

But that will give True or False

#

That's exactly why I proposed to make it a binary_sensor

daring comet
#

ok, ill make it a binary sensor with this code then! ill get back here when im done

marble jackal
#

Well, I wanted to propose this:

{% set game_list = ['valorant', 'brawlhalla', 'osu!'] %}
{{ states('sensor.activewindowsensor') | lower in game_list }}
#

πŸ™‚

daring comet
#

I hope its okay to use the discord code feature since its more convenient;

  - platform: mqtt
    name: "Tablet Lock"
    state_topic: "homeassistant/tablet/lock"
  - platform: template
    sensors:
      gamemode:
        friendly_name: "gamemode"
        value_template: >
          {% set game_list = ['valorant', 'brawlhalla', 'osu!'] %}
          {{ ('sensor.activewindowsensor') | lower in game_list }}```
so ive got this now, but it always stays off, no matter what program is active, do i need to tell it that true is open and false is off?
#

nvm petros suggestion works

#

but valorant still doesnt work...

mighty ledge
#

ensure that the reference sensor is actually updated to that state

daring comet
#

what do you mean?
I used devtools > template

{{ states('sensor.activewindowsensor') }}```
to check wether it works. If i open osu, gamemode turns on, if i open brawhalle gamemode goes on, but if i open valorant it stays off
mighty ledge
#

does {{ states('sensor.activewindowsensor') }} update to valorant?

daring comet
#

yes

mighty ledge
#

are you sure valorant is spelled correctly in lower case?

daring comet
#

yes
config: 'valorant'
sensor value: VALORANT

mighty ledge
#

hold on

#

do this for me

#
{{ states('sensor.activewindowsensor') | list | map('ord') | list }}

and paste results

#

@daring comet

daring comet
#

sec

#
[
  86,
  65,
  76,
  79,
  82,
  65,
  78,
  84,
  32,
  32
]
mighty ledge
#

ah

#

ok, this is what you need then

#
{% set mode = states('sensor.activewindowsensor').strip() | lower %}
{{ mode in ['valorant', 'brawlhalla', 'osu!'] }}
daring comet
#

yes it works

#

thanks so much for the help :D

silent seal
#

.strip() is exactly what I was going to suggest, but of course Petro beat me πŸ˜„

marble jackal
#

states was missing in my template

#

So, with strip() and states added, this should also work

{% set game_list = ['valorant', 'brawlhalla', 'osu!'] %}
{{ states('sensor.activewindowsensor').strip() | lower in game_list }}
marble jackal
mighty ledge
#

32 is space

#

0-31 are a bunch of values that represent shit that doesn't show up on screen

#

all ascii btw

marble jackal
#

Ah okay

mighty ledge
# marble jackal Ah okay

I just used that to see all characters that aren't visible and don't come through a copy/paste

#

the template editor strips things

marble jackal
#

Clear!

rocky crypt
#

When configuring templates in configuration.yaml, is there a way to specify "Entity.id" value? It looks like it defaults to "Name", but there is no option for "Friendly Name". Is there a way around this?
I ask because my homekit config includes all binary_sensors.alarm*. However, all my templates for my zones are the actual name. Example: binary_sensors.living_room_window

#

So is the only way to include/exclude my devices is to list each one?

marble jackal
#

If you mean template sensors, and then the new format, you can give them a unique_id and that allows you to change the entity_id in the GUI. Or the other way around, you can set the name so it will give you the correct entity_id, and change the friendly name in the GUI

rocky crypt
#

Gotcha. So either way I'm having to do something in the GUI πŸ™‚

marble jackal
#

yep

noble fern
marble jackal
#

It's a jinja template, so feel free to ask here

noble fern
#

Excellent. Will make a cup of tea whilst I work out the most succinct way to ask. Want one whilst I'm there?

marble jackal
#

Already got that covered

noble fern
#

No worries. Got myself a lotus biscuit too because you can't find proper speculaas in Australia without some looking. Ok. Here comes the question.

#

I'm coding a markup card to pull data from the 17track sensors so display my package status on a card on my main view. It was working but something has changed that I can't put my finger on. If one of the sensors doesn't have any packages to show (in_transit, ready_to_be_picked_up or delivered), it is returning a null value in the attribute 'packages'. I'm having a hard time checking for this with an if statement because if I leave it without it breaks the code and doesn't display any packages. I know I haven't included any code just yet but is there a particular trick to checking for null values in attributes?

#

I've even tried {% if state_attr("sensor.seventeentrack_packages_in_transit", "packages") != null %}

#

And versions of 'if not' etc

marble jackal
#

Well, I'm Dutch. Speculaas is not an issue here πŸ™‚

noble fern
#

Ha. Spoilt πŸ™‚

marble jackal
#

is this the case now, or is there actually a package being tracked?

#

if there are no packages now, what does {{ state_attr("sensor.seventeentrack_packages_in_transit", "packages") }} return in devtools > Templates?

#

Well, anyway, I think {% if iif(state_attr("sensor.seventeentrack_packages_in_transit", "packages")) %} will give a result you can work with πŸ™‚

#

Sorry, added an if

noble fern
#

Out of all three sensors, I have two populated with packages. The Delivered returns a null. The in-transit returns: [{'friendly_name': 'Core Stuff', 'info_text': 'In transit to next facility in HORNSBY NSW', 'timestamp': datetime.datetime(2022, 2, 28, 20, 5, tzinfo=<UTC>), 'status': 'In Transit', 'location': '', 'tracking_number': 'NUMBEROBFUSCATED'}]

marble jackal
#

for the one returning null the iif('sensor') should return false, the others true

noble fern
#

Ok..Testing...

#

Argh...I think its got to do with the multiple if checks I have. I think it's best if I post the code. Let me work out how to do a proper code past so the bot doesn't get upset

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
#

use one of those

noble fern
#

Oh...That easy eh? Right. Here we go

#

ooh....i see an errant backslash in the url in delivered now that it's in the codepile...lemme fix that

marble jackal
#

Okay, and what is the problem with the template? What does it return in it's current form?

#

And do you get any error messages when you paste it in devtools > templates

noble fern
#

Not a sausage!

#

Blank card - just the title

#

In Templates, it shows all the stuff but the HTML is literal rather than rendered

marble jackal
#

you need to use if iif('sensor')

#

not iif ('sensor')

#
              {% if iif(state_attr("sensor.seventeentrack_packages_in_transit", "packages")) %}
                {% for package in states.sensor.seventeentrack_packages_in_transit.attributes.packages %}
                   <font face=Arial size=3>**{{ package.friendly_name }}:** {{ package.info_text }} - {{ package.location }}</font>
                   <font color=gray>(<a href="https://auspost.com.au/mypost/track/#/details/{{ package.tracking_number }}">{{ package.tracking_number }}</a>) &nbsp; &nbsp; &nbsp; &nbsp;  {{ as_timestamp(package.timestamp) | timestamp_custom ('%a %d %b, %-I:%M %p') }}</font>    
                {% endfor %}
              {% endif %}
noble fern
#

Ahh cmon...did I? Seriously? Lemme check...<shame>

#

So not the state_attr?

marble jackal
#

See my code above

noble fern
#

Ok. Sorry Sorry

#

Right. That returns the In transit and the Waiting to be picked up

#

With one small problem

#

It's not rendering the HTML in the waiting to be picked up and is displaying the <font face .....etc

#

What the hell is this

#

Mind you, I suppose HTML is not exactly 'encouraged' in templates so I can't really complain too much πŸ™‚

#

Thanks for your help @marble jackal on the logic side of things. I was very close.

marble jackal
#

Can't you just format it in Markdown?

noble fern
#

I'll. have to, yes.

#

At least the logic works now. I've played with this so many times for weeks and got myself confused. Your iif is the most robust check.

marble jackal
#

I did a test with the HTML in a Markdown card though, that worked well

noble fern
#

Yeh...It works for the first one (in transit) but fails on the waiting to be picked up one that i check next. =There's something small somewhere. I'll have a scout around.

#

I love this sort of thing, diagnosing things, trying different logic but sometimes I could print the code out and set it on fire and jump up and down on the ashes. πŸ™‚

marble jackal
#

Well, would be nice if you put that on Youtube then

noble fern
#

πŸ™‚

#

What's the difference between {%- if something here -%} and {% if something here %} ? I can't seem to find out what the -'s are for.

#

Is it just a whitespace thing?

marble jackal
#

whitespace control, but these are ignored anyway, so not important πŸ™‚

noble fern
#

ahh right. Okay! Thanks!

#

I'll fill you in if I work out what this HTML thing is if it's relevant to templating. If it turns out to be a rookie error, I'll casually saunter past and not mention it! πŸ™‚

#

AHA! I have news....Oh so bloody simple AND a good lesson in templating...

#

Yuk....hang on

#

oh i can't work out how to post a picture but basically, the <font statement has to be in-line with the <for statement start and close, NO indent

fervent girder
#

Hmm how do i get a boolean out of this? " {{ states('sensor.temperature_kitchen')|int}} > {{ state_attr('climate.ac', 'current_temperature')|int +5}} "

inner mesa
#

by using a single template πŸ™‚

#

{{ states('sensor.temperature_kitchen')|int > state_attr('climate.ac', 'current_temperature')|int +5}}

fervent girder
#

thanks @inner mesa

neon gazelle
#

Question:
I have a list of objects that represent all invitees to a meeting, format {'email': 'attendee-email@doman.com', 'type': 'required'}.

I need a binary_sensor that can check if a subset of emails are in that list with type required. It could be my email directly, or it could be a known mailing list which I'm a member of. If either of them are marked as required, the sensor would be true; else it'd be false.

I can do this in Python easily enough, but Jinja is confusing to me and it won't let me modify variables inside a for loop. Any ideas?

spare summit
#

Hi all. I have issues with a template binary sensor. My problem is that i listen to an event and it ends up going into "unknown". And i tried to fix that, but apparently it doesnt want too.

https://paste.debian.net/1232680/

Any ideas how to make it force unknown to "closed".

marble jackal
#

You don't have a endif, but you can simplify your entire template to {{ 'Open' if trigger.id == 'on' else 'Closed' }}

#

Also note that after a reboot of HA or a template reload the state will be unknown until there has been a trigger. If you don't want that, include triggers for Home Assistant start and template reload

spare summit
#

Aha so with only this template alone it would still be unknown without that after a reboot.

marble jackal
#

Yes, trigger based template sensors only change state after a trigger

spare summit
marble jackal
#

You can add these two triggers

  - platform: homeassistant
    event: start
  - platform: event
    event_type: event_template_reloaded
spare summit
#

Ill try to add that to the template, thanks πŸ˜„

spare summit
marble jackal
#

Oh, sure, forgot about that one :)

spare summit
#

Also figured that binary sensor is either on or off, and i define the state with the device_class.
So state: "{{ trigger.id == 'on' }}" is kind of enough.

mellow knot
#

hey guys. i am using the rest platform to get data from a server that is able to output in JSON format.
sample json: https://pastebin.com/AZnzAN8h
i am unable to get data from the nested items. the code i have worked out so far only gets data from 1st child objects however i have no clue how to get data from nested objects.
for example (if you can see the json - pastebin), i can get data from the variable "relayed" however i dont know how to get data from the child object of fan_status_list i.e. temperature. Heres the YAML i have so far, it works, just need some expertise. https://pastebin.com/cStApKtB

fossil venture
#

Is this a valid solution for an availability template?

availability: "{{ states('sensor.some_sensor_here')|float(false) }}"
mighty ledge
#

Yah

#

But zero will also return a false potentially

#

Zero or false equals false

#

@fossil venture

#
availability: "{{ states('sensor.some_sensor_here')|float(none) is not none }}"
#

Or….

#
availability: "{{ states('sensor.some_sensor_here')|is_number }}"
full radish
#

I have a fun challenge I am trying to get working, I have a yaml data object being passed by the script service call lets calls it extra_data , I want to merge this with an existing yaml list lets call this data... if data doesn't exist its really easy to just do data: '{{ extra_data }}' but what would be the correct way to have the yaml merge...

fossil venture
#

|float(none) is not none }}" would seem to be the best option.

mighty ledge
#

Choice is yours

mellow knot
#

i have a value template setup as follow which returns the sensor value. value_template: "{{ states('sensor.height') }}" however if i try any math functions in the expression it stops giving a value. example: "{{ states('sensor.height') / 100 }}" returns nothing. can someone guide me on this please.

mighty ledge
mellow knot
#

got it, once converted then how can i do math operations on the value.

buoyant pine
#

Not to be a smartass, but with math symbols

mellow knot
#

lmao.

buoyant pine
#
  • / + -
mellow knot
#

i meant to say | float | * 100 for example

buoyant pine
#

Oh gotcha. Drop the second pipe

#

| float(0) * 100

#

The (0) is setting a default value which HA now requires

mellow knot
#

whats float(0)

#

got it

#

thank you

buoyant pine
#

I promise I wasn't trying to be a smartass πŸ˜‚

#

I could have asked for clarification

mellow knot
#

no worries buddy.

#

appreciate the humor. not that serious lol

#

how would this work if i had to lets say multiply values from two sensors. i.e. {{ states('sensor.height1') | float(0) * states('sensor.height2') | float(0)}}. sorry for dumb question, i did my research but still very much trying to figure it out.

#

forgot to enjoy the best part about putting together code (in between my questions lol) trying and learning..... it works

vestal aspen
#

Can someone help me with filtering some json, So i have a call that returns a list of files. i want to strip the file extension off the name of the file.

#

{% set output = namespace(value_json=[]) %}
{% for value_json in value_json.files %}
{{ value_json.name }}  
{% endfor %} ```
#

gives me 29-n.eseq

#

i need just 29-n striping the .eseq

#

I looked here under filtering with regular expressions but am having trouble with the syntax

mighty ledge
frozen turret
#

Trying to replace repeat code in the ui-lovelace.yaml and make it a bit more dynamic but can I write yaml code with jinja2?
Example:

- template: >-
          {% set ns = namespace(person = [], qty=0) %}
          {% for state in states.person | selectattr('attributes.entity_picture', '!=' , '') %}
          {%- set ns.qty = ns.qty + 1 -%}
          - action: none
            entity: {{ state.entity_id }}
            state_image:
              home: {{ state.attributes.entity_picture }}
              not_home: {{ state.attributes.entity_picture }}
            style:
              background-color: "rgba(255, 255, 255, 0.0)"
              border-radius: 10vw
              height: 4.2vw
              left: {{ 0.8 + 5 * ns.qty }}
              top: 72%
              width: 4.2vw
            tap_action: none
            type: image
          {% endfor %}
silent barnBOT
mighty ledge
vestal aspen
mighty ledge
#

then split the name on the period

#
{{ value_json.name.split('.')[0] }} 
#

however, keep in mind that your template doesn't do anything other that give the name

#

your script after stripping the period will return abcd

#

not sure if that's what you want

#

but that's what your code will do

#

@vestal aspen

vestal aspen
#

yea stripped off . so i have a sensor that spits out an away_ id. as a 2 digit number. i have a bunch of .eseq that are on my show player. so i take away_id and test to make sure (away_id).eseq exists if no trigger an alert.

mighty ledge
#

when you have more than 1 file, if you strip just to the number, you won't have a 2 digit number

#

you'll have a 4 digit number for 2 files, 6 for 3, etc

#

if that's what you want, then you just need to get the number out by adjusting the split to .split('-n.')

vestal aspen
#

yea sorry had just woken up and re-read your message.

#

havent got that coffee in me yet.

#

so i wonder if this is even necessary. i think i can just try and match on the original json input and return true if it finds what it's looking for,

#

i started playing with this.

#
{% for value_json in value_json.files %}
{{ value_json.name | string is search(find="20.eseq" , ignorecase=True) }} , {{ state_attr( 'sensor.flames', 'away_id' )}}.eseq 
{% endfor %}```
#

but my problem became. can i change out the "20.eseq" for the value of away_id.eseq

#

right now this gives me a list of files and a true/false for each

#

but i can't figure out how to use a template value as my "needle" to search for.

#

so right now hard coded to 20.eseq

mellow knot
#

hey guys. im trying to get some data from helium stats api. Using the rest platform with few other json apis without issue however stuck at this one. can anyone give me some pointers to what im doing wrong. help appreciated.... https://pastebin.com/T4Ju5Vh3

mighty ledge
mighty ledge
#

theres a ton at that rest endpoint

mellow knot
#

had it in pastebin so i wouldnt be flooding the channel with my code snippet.

vestal aspen
#

i am pulling in a list of files on a remote device with api and and need to see if based on another sensor value a file named for that state exists on that remote device or not.

mighty ledge
#
  - platform: rest
    name: helium_stats_api
    resource: https://api.helium.io/v1/stats
    value_template: "{{ value_json.data.token_supply }}"
mellow knot
#

so i dont need to grab this from the json attributes via a template sensor?

#

or this is another way to achieve the same

mighty ledge
#

if you just want that token_supply number, that's all you need

mellow knot
#

got oit

mighty ledge
mellow knot
#

its simpler. thank you

vestal aspen
#

the 2 digit value i am after. so like away_id = 8 im looking for if 8.eseq exist on the remote device.

#

{{ state_attr( 'sensor.flames', 'away_id' )}}.eseq

#

works to display the value.

#

but i need that as my needle value in the string search

mighty ledge
#

no clue what you mean when you say needle value

vestal aspen
#

the find vale

#

the crap between the find="" qoutes

#

needle in haystack.

mighty ledge
#

so you're just trying ot select from the list of names the filename

vestal aspen
#

so i can hard code in the 8.eseq. but i need it dynamically from the template value.

mighty ledge
#
{% set value_json = {"status":"ok","files":[{"name":"29-n.eseq","mtime":"02\/15\/22  06:58 PM","sizeBytes":207360020,"sizeHuman":"197.76MB"}]} %}
{% set target = '%02i-n.eseq'%(states('sensor.xyz') | int(0)) %}
{{ target in value_json.files | map(attribute='name') | list }}
#

You should search for the full expected filename instead of parsing the filename

#

this gives you a true/false if the sensor value is in the filename list

mighty ledge
#

make the filename from your sensor value, and check that inside the filenames instead

mellow knot
mighty ledge
vestal aspen
#

well the filename isn't an actual filename on the sensor. just a 2 diget id so i need to append the .eseq to it.

mighty ledge
vestal aspen
#

(and sometimes 1 digit)

mighty ledge
#

is it zero padded or not?

mellow knot
#

variable error: 'value_json' is undefined when rendering '{{ value_json.data.token_supply }}'

vestal aspen
#

no

#

like today it's returning 8

#

yesterday 20

#

so today i am looking to see if 8.eseq exsists

mighty ledge
#
{% set value_json = {"status":"ok","files":[{"name":"29-n.eseq","mtime":"02\/15\/22  06:58 PM","sizeBytes":207360020,"sizeHuman":"197.76MB"}]} %}
{% set target = states('sensor.xyz') ~ '-n.eseq' %}
{{ target in value_json.files | map(attribute='name') | list }}
#

still pretty easy

vestal aspen
#

yea sorry let me go test

mighty ledge
#

you'll have to put your sensor in it

mighty ledge
mellow knot
mighty ledge
#

Then it should be working as is

#

the only way value_json is not defined is if the value is not json

vestal aspen
#

this is perfect @mighty ledge thankyou

#
{{ target in value_json.files | map(attribute='name') | list }}```
mellow knot
#

i do see that it is slightly different from another json data stream. is there some way i can parse/convert this into a consumable form of data via rest or other api.

mighty ledge
#

You can do alot with jinja. If it's very complex, it's better to make an integration

mellow knot
#

i will def start researching and reading up more on intrgrations. that is def on my to do list.

vestal aspen
#

@mighty ledge this is part of getting this all automated.

#

checks to see if my live scoreboard player has the logo for the teams or not to build the images on my window.

#

alert's me if the next game needs graphics made.

mighty ledge
#

nice

vestal aspen
#

the scores and overlay text come from an NHL api and all get sent automatically during the game live

#

plays the goal horn when the home team scores.

mighty ledge
#

is this just for parties or something?

vestal aspen
#

Naw i do animated christmas shows. was looking for something else to do with my lights

#

lol

mighty ledge
#

ah

vestal aspen
#

this is all controlling FPP on a rasp pi.

#

for lights and matrix display

#

a couple of us are looking to get event type lights/actions for as many sports as we can,

#

we have nascar in the works too.

#

and i did a bit with NFL

mighty ledge
#

Nice, and this is just an outside light display?

vestal aspen
#

yea. well i have wled devices that trigger inside on goals and stuff too

#

but yea everything else is outside

stable gazelle
mighty ledge
#

that doesn't make sense, it either triggers when it goes above 23 or it doesn't trigger

stable gazelle
#

I want only trigger every 5 minutes

mighty ledge
#

yeah, but your logic is flawed

#

what do yuou want it to say when it's below 23?

#

and what entity_id will it choose?

stable gazelle
#

I want to alert me every 1 hour if one of the temperature is below 23

mighty ledge
#

then you want to make an alert instead

#

or use a loop

#

in the actions

stable gazelle
#

I have a nest, I want it to say it when the temperature is below 23

mighty ledge
#

yes I get that

#

but you want it to repeat, correct?

stable gazelle
#

Yes

mighty ledge
#

your trigger as defined will only notify you when it drops below 23

stable gazelle
#

Every 1 hour

mighty ledge
#

ok, then...

silent barnBOT
mighty ledge
#

or

#

create a repeat for your automation

#

and your automation doesn't account for when it goes back above 23

stable gazelle
#

Okay. I'm gonna try it

bronze horizon
#

Hello! I'm using a simple template with a state trigger to track which of my PIR sensors most recently turned on. I was wondering if there's any way to generate the entity ID list programmatically?

It looks like the list doesn't support templates, and if I use a group then it would only capture first on/last off changes and not update the name correctly... Is there anything I'm missing?

rose scroll
hollow moat
#

Hey all

I posted a question in automations and they pointed me to here for an answer

I'm trying to create a group.set automation/template that will set all lights that are in area x as light.x_lights

is this possible or am i wasting time

fossil venture
#

It's possible I just have not worked out how to select all entities with the domain "light" from area_entities() yet.

#

This does not work with my Outside area that has lights, {{ expand(area_entities('Outside'))|selectattr('domain' 'eq' 'light') }}

hollow moat
#

whats the reasoning behind the expand(***)

fossil venture
#

It may not be needed. I was just trying a few things.

#

I can get a list of all entities in the area, just filtering them to the light domain is the issue.

hollow moat
#

what sytax are you using to list them?

fossil venture
#

jinja

hollow moat
#

i will probably be playing w this for a few hours so any baseline you have would be great

hollow moat
# fossil venture jinja

sorry i meant what is the code you have to list them when i put the above into template i get -

<generator object select_or_reject at 0x14dbcd3bd660>

fossil venture
#

{{ area_entities('Outside') }}

#

Where 'Outside' is the name of my area, case sensitive.

hollow moat
hollow moat
#

so yea im getting no where with this lol

#

trying again tomorrow

#

actually this is a step forward

{{ expand(states.light) 
    |selectattr('entity_id', 'in', area_entities('Living Room'))
    |map(attribute='entity_id')
    |join(',') }}
bronze horizon
#

I've got them in a group, they're also similarly named so a substring match should find them from the global entity list

inner mesa
fossil venture
#

I was looking at trying to use area_entities() to avoid having to query all states.

#

Is there no way to select a domain from this?

hollow moat
#

@fossil venture - i got what i needed from this, appreciate the help - let me know if you figure out the area_entities() version

void tartan
#

How can I get the current version of the Version & website
Trying to replace this with the new version sensor:

service: notify.notify
data_template:
  message: >-
    Home Assistant {{ state_attr('binary_sensor.updater', 'newest_version') }}
    is available.

I can see the version in the UI but can not seem to get a template to accept {{states(sensor.home_assistant_website)}} to pull the latest value.

#

Got it: {{states("sensor.home_assistant_website")}}

rose scroll
rose scroll
bronze horizon
#

It is, but the issue I'm facing is that templates aren't supported by the entity ID list on a template trigger

marble jackal
#

you mean on a state trigger? Because templates are allowed on a template trigger πŸ™‚

#

Oh, wait, you mean a trigger based template sensor. If you want to use templates in the trigger, you will need to use a template trigger

marble jackal
rose scroll
#

More generally, is pythonic list comprehension possible in templates? Would much rather write something like [sensor for sensor in sensors.entity_id if 'motion' in sensor]

marble jackal
#

Don't think so, but I don't know any python, just jinja πŸ™‚

feral turtle
#

Howdy

#

it's possible to include json data to configuration file ?

marble jackal
#

Please eleborate.. What are you trying to do?

feral turtle
#

1sec

#

I want to be able to extract the values with an input select, for example if I select "seedling" in the input select the seedling data (temp, hum ect) will be transferred to input_numbers entities

fallen tulip
#

Hi ... need some help to define a MQTT binary sensor parsing a JSON string in topic : routeursolaire/param/solar1

#

solar1 = {"zeropince":-5.9,"coeffPince":0.021739,"coeffTension":0.0233,"seuilTension":54.6,"toleranceNeg":0.8,"actif":false}

#

I want to define the binary sensor according to the "actif" field

#

I definined my binary_sensor as :

#
    state_topic: "routeursolaire/param/solar1"
    name: 'routeur_solaire'
    value_template: "{{ value_json.actif }}"
    qos: 1
    payload_on: "true"
    payload_off: "false"```
#

but it not returning anything (unknow)

#

can't find my mistake 😦

marble jackal
feral turtle
#

thanks I'll take a look

marble jackal
fallen tulip
#

@marble jackal I didn't check πŸ™‚

marble jackal
#

Well, then do that πŸ™‚ I can't do it for you, and it might give some valuable insights..

fallen tulip
#

the question is

#

which loggeR ?

#

the broker one ?

marble jackal
#

the home assistant log. Configuration > Settings > Logs

#

Not sure which broken log you are referring to

fallen tulip
#

ok so no specific message in the main log

marble jackal
#

ah, maybe the issue is that you have quoted true and false in your payloads, but the data reports a boolean value

#

so try without the quotes

fallen tulip
#

ok

#

restarting HA ...

marble jackal
#

Are you sure that is needed? You can't reload them from Configuration > Settings > Server Controls?

fallen tulip
marble jackal
#

No problem πŸ™‚

hybrid merlin
#

So, I want to write a template to get the number of people in a given zone (and to set a helper to that number). Right now I have the following, which outputs a list of zones that entities in the group are currently in
{% for at_zone_home in expand('group.all_people') %} {{ at_zone_home.state }} {%- if not loop.last %} {% endif -%} {% endfor %}

mighty ledge
#

why set it to a helper? just make a template sensor

hybrid merlin
#

Yeah, that would work too. Haven't made a template sensor before, but that sounds like it would cut out a middleman

mighty ledge
#
{{ expand('group.all_people') | selectattr('state','eq', 'home') | list | count }}
hybrid merlin
#

oh, that's perfect. thank you!

pine musk
#

Good evening (morning, afternoon, Night). I am trying to string 2 templates together:
{{states.geo_location|selectattr('attributes.source','eq','usgs_earthquakes_feed') |map(attribute='name') |join(', ') }}
{{ states.geo_location |selectattr('attributes.source','eq','usgs_earthquakes_feed') |map(attribute='state') |join(" km away,\n") }}

#

but I am not sure how to stitch them together.

#

each works by itself

rose scroll
#

What's the intended output that you're hoping to get? Currently I suppose you're getting one comma-separated string of all the earthquake locations and another comma-separated string of distances. You're aiming for a single comma-separated string of name-distance pairs?

rose scroll
pine musk
#

rexactly.

rose scroll
#

But maybe someone knows of the Jinja way to do a pythonic zip? That would be more elegant!

inner mesa
#

Regrettably doesn't exist

rose scroll
#

Lol too bad! Maybe one day...

pine musk
#

found easy way!!
{% for state in states.geo_location |selectattr('attributes.source','eq','usgs_earthquakes_feed') %}
{{ state.name }} is {{state.state_with_unit}} away.
{% endfor %}.

rose scroll
#

Nice!

spring moth
#

Need help I am trying to create a mqtt trigger value_template I keep getting error and I am stuck.

#

value_template: {% if camera == '*' %} '{{ value_json.type }}' {% else %} '{{ value_json[''after''][''camera''] }}' {% endif %}

inner mesa
#

What...error?

#

It's probably because you're not using >- to introduce a multi line template, but I can't tell without proper formatting and the error

spring moth
#

missed comma between flow collection entries at line 174, column 19:
value_template: {% if camera == '*' %} '{{ value_ ...
^

#

no I tried that

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).

inner mesa
#

And where did 'camera' come from?

#

You've declared no such variable

silent barnBOT
inner mesa
#

that looks like a blueprint

spring moth
#

yes it is

#

this is the working version

silent barnBOT
flint crown
#

After the new Version the autocomplete does not work. Do I have to enable something ?

royal rampart
#

So, I'm trying to include a package yaml file for my mower (packages/landroid.yaml) , this whole section is red in vvscode and none of those sensors are available but it's not telling me why, any ideas

royal rampart
#

I uh forgot to paste the pastebin oh well I fixed the read, it wanted to be an array... now I just have to figure out why the sensors don't work

lyric night
#

Is there a way to list all attributes of an entity ?

marble jackal
#

states.your.entity.attributes

#

It will be a dictionary though

lyric night
#

yes just found out, thanks

marble jackal
#

You can expand the group, and then look at the attributes of the entities in it

#

And possible trigger on it, if you give some more insight in what you want to do πŸ™‚

lyric night
#

I have multiple entities with an 'over_temp' attributes I would like to trigger if any of them goes over temps

marble jackal
#

Okay, something like this as template trigger:

{% set temp = 50 %}
{{ expand('group.your_group') | selectattr('attributes.over_temp', '>', temp) | list | count > 0 }}
#

However this will trigger if the first goes over the threshold, and not again if there is a 2nd one.
If you want to trigger for that as well, you can create a template sensor with a count of the group members with the over_temp attribute above the threshold and trigger on a state change of that

lyric night
#

So if I understand it correctly, it wil trigger if any goes over 50 ?

#

i will use a template_sensor, I guess there is no magic there ? I also need to manually input every entities

marble jackal
lyric night
#

yes what I mean is that i'n eed to declare all entities in the sensor

marble jackal
#

So like this:

{% set temp = 50 %}
{{ expand('group.your_group') | selectattr('attributes.over_temp', '>', temp) | list | count }}
#

You already have them in the group right?

lyric night
#

yes

marble jackal
#

If you also want to know which entities are above 50, you can add that as an attribute

#
template:
  - sensor:
      - name: "Sensors overtemp"
        state: "{{ expand('group.your_group') | selectattr('attributes.over_temp', '>', 50) | list | count }}"
        attributes:
          entities: "{{ expand('group.your_group') | selectattr('attributes.over_temp', '>', 50) | map(attribute='entity_id') | list  }}"
lyric night
#

ho nice thanks a lot

marble jackal
#

whoops, there are some errors in the quotes

#

fixed

analog plover
#

If I make a template sensor with a syntax that works when tested in the template editor, but only says "unavailable" when implemented in my sensors file, any idea what I might be doing wrong?

#
  • platform: template
    sensors:
    shellyplug_s_8019cf_ip:
    value_template: '{{ state_attr(device_tracker.shellyplug_s_8019cf, ip) }}'

Just trying to create a sensor so I can see the IP of a smartplug. πŸ™‚

silent seal
#

You formatted it wrong.

silent barnBOT
#

YAML is the mark up language used by Home Assistant, consistent indenting (two spaces per level) is key. Here is a primer, and this explains multi-line templates. For validating YAML see YAML Lint.

silent seal
#

At least it looks badly formatted on mobile.

#

You need to quote the device and attribute properties.

#

Those are not variables.

analog plover
#

Thanks...! Got it working with the following:

  • platform: template
    sensors:
    shellyplug_s_8019cf_ip:
    value_template: '{{states.device_tracker.shellyplug_s_8019cf.attributes.ip}}'
silent seal
#

That’s not correct.

#
- platform: template
  sensors:
    shellyplug_s_8019cf_ip:
      value_template: '{{ state_attr("device_tracker.shellyplug_s_8019cf", "ip") }}'

But do yourself a favour and don't start by using a legacy template.

analog plover
#

Look, I barely know what I computer is - I'm just glad it's working lol.

#

But I will look into what a legacy template is, thanks!

silent seal
#

The legacy ones are at the bottom, don't use those, use the format at the top

analog plover
#

Ooh, you mean what I've done is some sore of obsolete way of doing it? Might cause issues down the line?

silent seal
#

Yes, there's a reason why the title above the similar examples uses the word "Legacy"

analog plover
#

I've always thought of legacy as something positive, but this might explain why we label old shitbin projects as "legacy" projects at work then.

#

TIL.

silent seal
#

Legacy means "it's existed like this, and we can't kill it, but don't do things like this/use this unless there is absolutely zero other way", at least in programming terms.

analog plover
#

Makes sense. Thanks a bunch Rosemary πŸ™‚

silent seal
#

It's a step above "deprecated" usually πŸ™‚

#

You're welcome πŸ™‚

frank gale
#
      and ( ( now() - states.sensor.spotify_source.last_changed | as_local ).total_seconds() >= states('input_number.ohne_spotify') | int ) ) }} ```
this template returns true exactly after the list in `state_attr('sensor.spotify_source','players')` gets an item and ignores the time delay which should get after the last_change attribute. Also tried with a sensor.date_time_iso in the place of now() which evaluates every minute
Am I missing something?
silent seal
#

You need more brackets in all probability

#
{{ ( ( ( state_attr('sensor.spotify_source','players') | list | count > 0 )
      and ( now() - states.sensor.spotify_source.last_changed | as_local ).total_seconds() >= states('input_number.ohne_spotify') | int ) ) }} 
#

Whoops, had a few too many brackets myself, but try wrapping your first clause in brackets at minimum

frank gale
#

no the brackets are ok i didn't post the wholesome code

#

The question is when the last_changed attribute change? Does it evaluate after the sensor changes or the sensor change (which means my template is true for the last last_changed) and then changes the last_changed attribute?

sonic nimbus
#

how to check if some variable is passed to a script?

#

{{if is defined var1}} ?

mellow knot
#

hey guys. is there a way to take data coming from command_line platform and insert as attributes of a sensor (new, not any existing sensor).

#

sorry this is kind of a general question not even knowing what kind of data but to give some clarity to my question, i am using awk on a device console log, i can use -F index locations in text to grab certain data like date, time, ping ms however trying to see how these three can be input as attribute data.

sonic nimbus
#

why I cant do this: - service: persistent_notification.create data: title: "{{wled_light_entity}}" message: "{{ state_attr('wled_light_entity', 'effect_list') | random }}"

#

it's broken script.. message part is not working

#

Error executing script. Error for call_service at pos 1: Error rendering data template: TypeError: object of type 'NoneType' has no len()

marble jackal
marble jackal
#

{{ state_attr('sensor.spotify_source','players') | list | count > 0 and ( ( now() - states.sensor.spotify_source.last_changed ).total_seconds() >= states('input_number.ohne_spotify') | int ) }}
Does this work? If not what do you get in devtools > templates

winged star
#

can anyone message me with help combining two media player entities into one using the universal media player integration? :/

marble jackal
#

What do you have already?

stuck remnant
#

is there a template to make one numeric state helper reflect the value of a numeric state sensor?

#

I have a helper that alters my pc volume but it has no feedback,
and I have a separate sensor that reflects my pc volume

#

I need to automate the former to reflect the latter

marble jackal
#

Create an automation that triggers on state changes of the sensor, and then set input_number to the new state

stuck remnant
#
trigger:
  - platform: state
    entity_id: sensor.thegoat420_currentvolume
condition: []
action:
  - service: input_number.set_value
    data:
      value: 0
    target:
      entity_id: input_number.volume_level
#

it asks what value

#

thats my question, how do I tell it to change to whatever value the sensor happens to be?

marble jackal
#

Please don't share code like that

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.

stuck remnant
#

its ten lines

marble jackal
#

Well, at least format it as code

stuck remnant
#

fair enough

marble jackal
#

But you use a template for that:

action:
  - service: input_number.set_value
    data:
      value: "{{ states('sensor.thegoat420_currentvolume') | float }}"
    target:
      entity_id: input_number.volume_level
frank gale
marble jackal
#

It's not how that works, the template is rendered at one moment. You can not enter a delay in rendering a template

frank gale
#

so last_changed changes after the sensor get's it's update status

marble jackal
#

What you are doing in that second part is checking if the source has changed at least a certain number of seconds ago

#

Yes, correct

frank gale
#

thank you! +1 knowledge πŸ˜„

frank gale
#

I'm pretty sure I have made a template before with a time delay using last_changed value, having the results I wanted...

#

Is there anything I can do to delay a template after some time?

marble jackal
frank gale
#

I want to return true after an amount of time that the empty list get's some items sensor.spotify_source

#

This sensor has an attribute Players

#

After adding some items in this list i want to trigger a template but not directly, delaying it some seconds

#

I though checking the number of items of the list, if it is at least one and then compare how many seconds passed since this change will give me the result i wanted

marble jackal
#

Yes, indeed, but that should work with the template you have now

frank gale
#

No, it doesn't it returns true direct after the list get's at least one item

#

It ignores the part with last_changed

marble jackal
#

last_changed is only updated on state changes, not on attribute changes

frank gale
#

As state I have the first item of this list

#

so the last_changed should also render direct after the change

#

but you gave me some good thoughts. I will check if state is not empty and not the attribute to check if there is a problem

#

To make it clear I'm using it as trigger, because in template it renders true only after that delay, so I thought that it triggers only momentary

marble jackal
#

Are you sure that the input_number is correct btw, because if you made a typo there, the int filter will default to 0 making that 2nd part always true

marble jackal
#

I'm off to bed now, so good luck with troubleshooting!

frank gale
#

If this action is repeated between the delay the delay works (it's not triggered direct)

#

Gnight

#

Yes! Checking the state and not the attribute results to trigger the template with delay

fierce turret
#

I have a template sensor that grabs an attribute from a calendar event, end_time. Is there a way I can stop the sensor from updating? As it stands, when the last event for the day is over, the sensor then shows β€˜unknown’ as there is no more calendar events for today. I need to store the last end_time and use it elsewhere. Can this be done?

inner mesa
#

you can add a trigger to your template sensor to tell it when to update

#

8AM, noon, not after 6pm, etc.

fierce turret
inner mesa
#

then you can trigger on it not being "unknown"

fierce turret
marble jackal
#

Check for the list of events being empty, if that is the case, use the current state

fierce turret
#

this would work, wouldn't it?

  sensors:
    calendar_end_time :
      unique_id: calendar_end_time
      friendly_name: "Calendar End Time"
      value_template: >-            
        {% if state_attr('calendar.lou_work', 'end_time') != 'unknown' -%}
        {{ state_attr('calendar.lou_work', 'end_time') }}
        {%- endif %}```
stuck remnant
#

I have an automation for an active window sensor but the name changes with every file I play. It's VLC. I need a template that basically recognises VLC media player within the name that comes in the sensor

marble jackal
# fierce turret this would work, wouldn't it? ```- platform: template sensors: calendar_en...

Are you sure it actually returns unknown when empty?
And you need to add an else. You can try this:

        {% if state_attr('calendar.lou_work', 'end_time') != 'unknown' -%}
        {{ state_attr('calendar.lou_work', 'end_time') }}
        {% else %}
           {{ states('sensor.calendar_end_time') }}
        {%- endif %}

But this will show the end time of the event of the previous day is there is no new event on the current day, not sure if you want that

fierce turret
#

Theres no need to have an else if i dont need it. If the end_time != unknown, it stores the time. Adding an else doesnt achieve anything for me.

marble jackal
#

If you don't add the else, the result of the template will be false. The else will make sure it shows the previous state, which is what you asked for

fierce turret
#

No it wont. Adding a pointless else creates more code which doesnt achieve anything.

#

I have tested it in developer tools and it works as expected.

#

Do you think it will cause an issue when it changes from a time to unknown or vice versa if I dont have an else?

#

I’ll need to wait until 8pm tonight to see what happens when the last event ends πŸ˜‚πŸ˜‚πŸ˜‚πŸ˜‚

marble jackal
#

But you can try with any other entity. Try a light and use attribute brightness, and turn the light on and off

fierce turret
#

I dont need a result when there is no end time. I only need a result when there is an end time

marble jackal
fierce turret
#

lets say it stores the end time as 8pm. After the last event, it SHOULD stay at 8pm and not go to unknown. Then the next day, it will update when the next event happens

marble jackal
#

Yes, that's why I added the else

fierce turret
marble jackal
#

Okay, just wait until 8pm then

fierce turret
#

haha. i'll run a test on a light as you suggested

fierce turret
fierce turret