#templates-archived

1 messages ยท Page 146 of 1

inner mesa
#

I guess

sullen crow
#

I mean, I think my sensors all have the word temperature in them

inner mesa
#

{{ states.sensor|selectattr('attributes.unit_of_measurement', 'eq', 'ยฐF')|map(attribute='entity_id')|list }}

#

works for me

sullen crow
#

thank you

#

the list includes one sensor I don't want - my phone battery temp. Can I just get rid of that sensor all together? I don't really ever care (at least for now)

inner mesa
#

you can disable the entity

sullen crow
#

right, thank you Rob C

#

ah, of course I have a calibration template for all my temp sensors so it won't work afterall. Will need to define the list the original way.

inner mesa
#

"calibration template"?

#

you can generate the list as long as there's something to match on

sullen crow
#

yes, I created a template sensor for each physical sensor with an offset so they all show same temp when in same place

#

just matched it to thermostat display temp since i can't change that

#

so I have sensor.sonoff_TH01_1_temperature and sensor.guest_bedroom_temp the latter being the calibrated temp

#

i don't think it's called a claibration template but it is a template for "calibration"

#

offset is prob a better word

inner mesa
#

And you can still create a list from them

nimble steppe
#

is it posible to split the template config files in to 2, one template.yaml file and a dir list?
Configuration.yaml
template: !include templates.yaml
template split: !include_dir_list ./entities/templates

inner mesa
#

You can try it

tired sandal
#

looking to build an automation that fires is the outside temperature is below x

#

To do that, I'm thinking that I need to somehow grab the current outdoor temperature and turn it into a template sensor

inner mesa
#

not necessarily. why?

#

just being below a certain temperature isn't a singular time, so isn't a trigger

tired sandal
#

Let me recap - I'd like to have a binary sensor for is_below_freezing

inner mesa
#

that's just a template binary sensor

tired sandal
#

I'm trying to build an automation that tells me to turn on my roof heat cables if the temperature is below freezing

#

Right.

#

so I guess my question is - how do I get the current outdoor temperature in such situations, googling for such things just takes me to climate which is more to do with HVAC ...which is not really what I'm after

inner mesa
#

where are you getting it from?

tired sandal
#

uh, right now just the default which I think is....hold on

inner mesa
#

presumably you have the information somewhere in HA?

tired sandal
#

Meteorologisk institutt (Met.no) apparently

inner mesa
#

and it's an attribute of that?

#

weather.home or something?

tired sandal
#

i just have the integration setup and it shows a pretty card in lovelace, I'm not actually doing anything with the data so I've never had to interact with it

#

Right, so I can get weather.home

inner mesa
#

and the temperature is an attribute?

tired sandal
#

yep, looks like it.,

#

so...I can use the state platform to get this?

inner mesa
#

do you want to start with a template binary_sensor for that?

tired sandal
#

yeah, probably.

inner mesa
#

or do you just want an automation that triggers when the temperature drops below 32?

#

or freezing

tired sandal
#

i want an automation that triggers when the temperature drops below freezing, but having a binary sensor to encapsulate that seemed like a neater solution than a magic number of "32" randomly in there

inner mesa
#

not necessarily - you'll have that number somewhere, and if you don't plan to use that template binary_sensor anywhere else, it's not that helpful

#

anyway

#

{{ state_attr('weather.home', 'temperature')|float < 32 }}

tired sandal
#

Gotcha, thanks

#

I mean - I was thinking having the ability to interrogate a sensor as to whether it is or is not freezing might be helpful but i dont know

inner mesa
#

๐Ÿคท

#

the world is your oyster

tired sandal
#

๐Ÿ˜›

#

I should point out that Fahrenheit is not my chosen unit of measurement but hey ho

inner mesa
#

whatever freezing means to you

#

273K or whatever

tired sandal
#

Now you're talking!

#

๐Ÿ˜†

#

Anyway, I use Fahrenheit because:

  • I live in America
  • My wife is American
  • This means that all our thermostats etc. need to be in Fahrenheit
  • Therefore, having HomeAssistant use the same units as the stuff it's controlling makes it less of a headache
#

but that does mean that "oh, 32 = freezing" isn't where my brain would typically go - so having a way to attach semantic meaning to that is nice ๐Ÿ™‚

#

oh and by the way - that thing I was doing earlier with scenes, automations and timers worked a treat so thanks!

ivory lily
#

I'm trying to convert from legacy to modern template sensors, but I can't figure out how to write my files. I have splitted my configuration so that I have one sensor per file, so one of my sensors is like
ยดยดยด
platform: template
air_conditioner_running:
friendly_name: "Varmepumpe kjรธrer"
value_template: "{{ states('sensor.power_air_conditioner') | float(0) > 10 }}"
ยดยดยด

#

How do I write this in the "modern configuration syntax"?

#

I have tried
platform: template
sensor:

  • name: air_conditioner_running
    state: "{{ states('sensor.power_air_conditioner') | float(0) > 10 }}"
#

But HA is complaining...

#

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

marble jackal
#

The new modern template sensors don't fall under the sensor integration, but under the template integration.
So you can't place them in sensor.yaml.
You will have to place them directly in configuration.yaml, or create a template.yaml file and include that one.
But all of this is not a template question, but something for #integrations-archived ๐Ÿ™‚ So please continue there

ivory lily
#

Thanks, I just read that in the docs, I had missed it... I will try, and continue in integrations if I still don't get it ๐Ÿ™‚

sleek wing
#

Hi all, is there a way how to get current automation last_triggered value not knowing its entity id? Something like we can do with triggers? - trigger.entity_id

The reason I need this is, that am writing blueprint and I need to turn off the switch by variable time after the automation was triggered last time.

mighty ledge
sleek wing
#

so this.attributes.last_triggered should be my solution right?

marble jackal
#

yes

sleek wing
#

Awesome guys, appreciate your help, thank you!

marble jackal
#

But, it will not be the current trigger time, it will be the previous trigger

#

last_triggered will only be changed after the conditions are checked, and when they are True

sleek wing
#

yes, that's actually what I need. I bear in mind this. ๐Ÿ‘

wooden marsh
#

hello everyone, is it possible to have a sensor that makes me the list of calendar events?

mighty ledge
#

With templates, you can do pretty much anything. A template that does what your asking wonโ€™t be cookie cutter, youโ€™ll have to make it

olive sparrow
#

Hi all, I am looking to do a template that looks to see if a value is between two numbers

dreamy sinew
#

{{ 10 < states('sensor.mysensor')|int < 99 }}

olive sparrow
#

i an just looking for the syntax to combine them, JS example:
if (sensro >10 && sensor is > 2)

#

``state: >
{% if 10 < states('sensor.mysensor') | int < 99 %}
middle
{% elseif 100 < states('sensor.mysensor') | int < 299 %}
high
{% endif %}```

`

#

Like that?

dreamy sinew
#

should work. you can test that in devtools > templates

#

note that without an else you're going to get an empty return if it doesn't hit either of those paths

olive sparrow
#

sweet - thanks!

#

just wish discovery supported template sensors

olive sparrow
topaz cave
#

Is there a way to do string substitution in jinja? I have a door sensor who's states are on/off and I would like to substitute them with open/closed in my template. Thanks in advance.

marble jackal
#

You can, but if it is a binary_sensor you can change the device_class to door or window and it will show open or closed on your dashboard

#

It will also change the icon accordingly

topaz cave
#

@marble jackal many thanks Iโ€™ll look into that.

topaz cave
#

@marble jackal unfortunately the device_class route doesn't work for my needs, any idea how I would do it in a template script?

mighty ledge
#

Device class translates it on the dashboard, not in the backend. How does this not work for your needs?

topaz cave
#

@mighty ledge I have a door(s) sensor automation which sends a notification on state change. message is {{ trigger.from_state.name }} is {{ trigger.to_state.state }}
I would like to substitute the on/off states with open/closed.

marble jackal
#

Will be even more simple in 2022.2

topaz cave
#

@marble jackal that's amazing thanks so much!

#

BTW how will it be easier in 2022.2?

marble jackal
#

{{ trigger.to_state.state == 'on' | iif('open', 'closed') }}

#

That replaces the if/else

#

Ninja edit ๐Ÿ˜Ž

topaz cave
#

Niiice ๐Ÿ˜Ž

torn meteor
#

is there a way to get "b" returned from this? from_state: ['a', 'b', 'c'], to_state ['a', 'c'] basically a pattern to"get the item from the list that "dropped out" - a diff of sorts

inner mesa
#

Sure

#

{{ from_state|reject('in', to_state)|list }}

torn meteor
#

WITCHCRAFT

#

thank you

floral shuttle
# marble jackal Will be even more simple in `2022.2`

yeah, it's nice, but not sure if its 'much' simpler.```
- service: >
script.alarm_arm_{{is_state('group.family','home')|iif('night','away')}}
script.alarm_arm_{{'night' if is_state('group.family','home') else 'away'}}

#

or even: value_template: > {{(value_json.state.daylight == True)|iif('on','off')}} {{'on' if value_json.state.daylight == True else 'off'}}. guess its more a matter of preference? Used to those ternaries in JS, a translation to Jinja might indeed be more straightforward now. nice indeed.

atomic blade
#

I'm running a shell_command and passing a parameter to it:

service: shell_command.test
data_template:
  foo: '{{ states(''sensor.bedroom_illuminance'')|float * 20|int }}'

In the command I then just reference it as {{ foo }} as a param to the command I'm trying to run.

That template in dev tools shows as an int, however, inside the shell command it seems to be evaluating to a float because the command I'm passing to is erroring out saying something like 90.0 is not valid input. Do I need to convert it to an int with something like {{ foo|int }} again?

atomic blade
#

Kinda seems to be the case, but that almost seems like a bug? I'm specifying the number to be an int in my template and then using that value in the command and it seems to be a float there

inner mesa
#

You're casting 20 as an int

thorny snow
#

Hi guys

#

if you have a sensor made up of, let's say, 3 entities, is it possible to know which entity triggered the last change?

inner mesa
#

No

#

You could test them all, I guess. Put them all in the trigger and test the from_state against the to_state. But that's brute force

thorny snow
#

that's somewhat what I was doing ๐Ÿ™‚

#

thanks

inner mesa
#

Or just look at trigger.entity_id. Was making it too hard

thorny snow
#

I could add an attribute to the sensor with the entity id that has the highest timestamp?

#

last changed timestamp

inner mesa
#

Just do what I suggested. Add them all to the trigger and look at trigger.entity_id

vapid hollow
#

How can I sum the sensor which gives daily power production sensor to make a total energy sensor? I could have used utility sensor but the issue is that this particular daily sensor resets at mid night. Any ideas

inner mesa
#

Statistics or Integration/Riemann Sum

vapid hollow
inner mesa
#

It integrates power over time to make energy

vapid hollow
inner mesa
#

I don't think a 'daily power sensor' makes sense, though

#

Did you read the doc page?

#

Anyway, maybe it will help, maybe not. Just a thought

atomic blade
#

Ah I see. I'd have to wrap that basically in parens and then cast it

lament fjord
#

Hi all,
in tasmota you can adjust the KwH reading by a command in terminal "EnergyReset<x>"
i have a shelly installed with original firmware but require the KwH reading to adjust to match my energy supply meter.
i did manage to in developer tools/template place this code in which netted a result of 407.358
{{ states('sensor.energy_company_power_kwh' ) }}
i would like to adjust this reading by 1200 to display a reading of 1607.358

marble jackal
#

{{ states('sensor.energy_company_power_kwh' ) | float(default=0) + 1200 }} will work to get what you want
Be aware that this will be shortly just 1200 at startup, because the sensor won't be available, and the float filter will then default to 0. As soon as the sensor is loaded it will show the correct result.

sour fractal
#

Hi all,
why would,
state: "{{ (states ('binary_sensor.x')) or (states ('binary_sensor.y')) }}"
not evaluate to true if either binary sensors x or y is true? Am i missing something?

lament fjord
#

thanks, I'll give it a go

median mason
#

i have a timezone set in HA, and i am running HA in HA blue.

lament fjord
#

done the code as @marble jackal worked great, {{ states('sensor.energy_company_power_kwh' ) | float(default=0) + 1200 }} but I'm struggling to add it to my code below is part of my configuration.yaml
sensor 1:

  • platform: integration
    source: sensor.suppliers_energy_power
    name: 'Energy Company Power kWH'
    unit_prefix: k
    round: 3

utility_meter:
daily_energy:
name: "OVO Energy Daily Kwh"
source: sensor.energy_company_power_kwh

marble jackal
lament fjord
#

I'll give it a try

marble jackal
wooden marsh
mighty ledge
north locust
inner mesa
#

Presumably with this, but you'd need to look at the event. Most things like this are easier with state triggers

marble jackal
inner mesa
#

Indeed. Forgot that could just be a word that you could use directly

glad frigate
#

It's possible to create a custom sensor and add them to a already existing device?

I like to extend device from a integration with aggregated (interpretations of the device data.

marble jackal
#

No, you can not add template sensors to a device

stuck remnant
#

hi, I have a rest switch that was on when the laptop suddenly restarted

#

and now the HA won't see the switch entity at all

#

tried resetting rest services, tried restarting HA, even restarting the laptop again, but it won't appear. Checked config, the entry is still there but it seems it just won't load it

mighty ledge
stuck remnant
mighty ledge
#

did the IP address change?

stuck remnant
#

no

#

i pinged, all good

mighty ledge
#

can you access that from the browser on your computer?

#

basically, this is a networking issue as HA doesn't see the endpoint

stuck remnant
#

I cant but Im not certain I could before either. From the browser I mean.

#

I can however trigger the switch from the phone app of the device

mighty ledge
#

typically rest endpoints just contain Json

stuck remnant
#

so it clearly connects

mighty ledge
#

yes but that's your phone

#

is your phone on your network or on the cell network?

#

is your ha using the same network as your phone?

stuck remnant
#

on my hom3 network

#

yes

torn meteor
#

i'm getting an empty value where a string is expected with this Template variable warning: 'mappingproxy object' has no attribute 'player_list' when rendering '{{ trigger.to_state.attributes.player_list|reject("in", trigger.from_state.attributes.player_list|default([]))|list|first }} online' i know it's a lot to unpack, but when the to_state attribute is "['player_one']" and the from state attribute is absent, the from state should default() to an empty list, and the reject filter should give me ['player_one']|first --> 'player_one' -- instead i'm getting '' and a the warning

mighty ledge
#

and does the phone actually use rest to access the sensor or does it have a built in api

#

either way, look towards your network

stuck remnant
#

not certain on that. It's a plug with a dedicated app

#

tenda

#

thing is, I pinged it from the HA terminal

#

so I know for a fact the server can reach it

mighty ledge
#

yes, you can ping it all day, but can it access that port?

stuck remnant
#

good point

mighty ledge
#

pinging != checking connectivity on the port 5000

stuck remnant
#

yes

#

I now used the port to ping

#

and it returns

mighty ledge
mighty ledge
#

anything that says otherwise is "faking it out"

mighty ledge
#

there's a few you can use for chrome

torn meteor
#

which is odd because it's working as expected in the template debugger:

#
{% set fromstate = {} %}
{% set tostate = {"value": ['c']} %}
{{ tostate.value|reject("in", 
fromstate.value|default([]))|list|first }}
#

results in "c"

mighty ledge
#

well no matter what, first will error on an empty list

#

Personally, I'd refactor your code to check to see if the attribute exists

#

it's a dictionary, so you could also just use get

torn meteor
#

ah. i can do that, i thought the default filter protected me though

#

and get supports a default?

mighty ledge
#

yes

#
trigger.to_state.attributes.get('xyz', [])
stuck remnant
#

I reset the switch, reconnected it and now HA sees it too, thanks for your assistance!

#

dont know why I didnt start with that, in retrospect

mighty ledge
#

you should try to see if you can connect to the endpoint in a browser

#

just for shits and giggles

stuck remnant
#

yes

#

I got the addon

#

good thing to have

torn meteor
mighty ledge
#

to_state*

torn meteor
#

ah sorry, to_state will never be empty at this point because i've conditioned that out in prior code.

mighty ledge
#

ah ok

#

then you're good

torn meteor
#

figured it out - get helped for sure (Thanks petro), but i also asked for "player_list" instead of "players_list" (typo) which made the to_state HAVE an empty list, haha

rocky crypt
#

Hello. Hoping someone can point me in the right direction. I have an automation already configured in automations.yaml. I'm wanting to add a condition to only run it if the day is a specific day of the year. Example if the date is "01/01" (Regardless of year). How would I go about doing this?

inner mesa
#

{{ now().day ~ now().month }}

#

so...{{ now().day == whateverday and now().month == whatevermonth }}

strange agate
#

hey all. I'm trying to figure out how to output a timestamp and thought someone might have a relatively easy way to do this.

Currently an automation that is set to run based on a condition that occurs every 2 weeks, based on the week number.
{{(as_timestamp(now())|timestamp_custom ('%U') | int % 4) == 2}} which would output a true/false.

I'm trying to figure out how to output a timestamp now based on the week number. For instance, every Saturday of a certain week number of the year. Not sure why I'm coming up short.....

rocky crypt
#

@inner mesa Thanks! How would I enter that as a condition though? I'm new, so I apologize ๐Ÿ˜ฆ I assume that would be the data, but what would the condition be?

inner mesa
#

a template condition

#
condition: template
value_template: "{{ now().day == whateverday and now().month == whatevermonth }}"
rocky crypt
#

Ok. So in my Configuration.yaml, I need to add the template correct?

inner mesa
#

in the automation you said you had

rocky crypt
#

Oh! Ok. Sorry, I was thinking I had to create the template in configuration.yaml first. But I guess I not ๐Ÿ™‚ Sorry!

inner mesa
#

np

#

you could use that too

rocky crypt
#

One more question.. Would I put in the whateverday and whatevermonth value in quotes or no because it's an int?

inner mesa
#

no, because they're integers

#

you can test all this in devtools -> Templates

rocky crypt
#

Perfect! That's what I was thinking ๐Ÿ™‚ Thanks again!!!

rocky crypt
#

Ok, one more queston.. If I have multiple conditions and I want it on everyday BUT "01/01"? I tried != on both month and day, but this didn't work because it is equal to 1 for the month...

inner mesa
#

Surround it in parens and add 'not' before it

#

New phone and autocorrect is vexing

rocky crypt
#

๐Ÿ™‚ Ok. SO like this:

value_template: "{{ not(now().day == whateverday and now().month == whatevermonth) }}"
inner mesa
#

Yes, but with a space after not

rocky crypt
#

Perfect! THANKS SO MUCH!!!

raven token
#

Is there an easy way to condition a time between say 8pm and 8am the following day without doing some sort of datetime witchcraft?

#

I thought of another solution could have an input boolean with an automation that turns it on/off at a certain time which bypasses this but seems like extra hassle to get working

inner mesa
#

Yes, because time conditions don't work the same way sunset/sunrise conditions do:

Time condition windows can span across the midnight threshold if both after and before keys are used. In the example above, the condition window is from 3pm to 2am.

little lion
#

im messing with a template that i found elsewhere on the internet and i think i understand except for 1 part

value_template: >-
            {% if states.calendar.columbus_blue_jackets.attributes.start_time %}
              {{((as_timestamp(states.calendar.columbus_blue_jackets.attributes.start_time) - as_timestamp(now())) / 60) | int }}
            {%- else -%}
              0
            {%- endif %}

what is the {% if states.calendar.columbus_blue_jackets.attributes.start_time %} of this sensor really doing??

inner mesa
#

it's a wordy way of getting the value of the start_time attribute

#

the right way to do it is state_attr('calendar.columbus_blue_jackets', 'start_time')

little lion
#

see that makes more sense to me

#

is that going to mess up the else 0 endif portion?

inner mesa
#

I don't know why people do it the other way. I think they're all copying random stuff from forums and reddit

#

it's the same thing

little lion
#

or should i do {% state_attr('calendar.columbus_blue_jackets', 'start_time') %}

inner mesa
#

that probably won't return a boolean, so wouldn't make sense

#

oh, I guess it's checking if it's blank?

little lion
#

gotcha. i dont understand the {% portion as of yet lol

#

yeah because it can be blank if nothing scheduled

#

so then it just shows 0

inner mesa
#

I wouldn't count on that working reliably, but if it does, it could be rewritten like this:

#

{{ ((as_timestamp(states.calendar.columbus_blue_jackets.attributes.start_time) - as_timestamp(now())) / 60) | int if state_attr('calendar.columbus_blue_jackets', 'start_time') else 0 }}

#

but the point is that the test needs to return a boolean

little lion
#

i mean that template in developer seems to return the same value as mine currently

#

i guess i dont understand what the if is doing

inner mesa
#

it's checking for a boolean

#

true/false

little lion
#

it seems to me this is all you would really need?
{{ ((as_timestamp(states.calendar.columbus_blue_jackets.attributes.start_time) - as_timestamp(now())) / 60) | int }}

inner mesa
#

that probably won't give you 0 if the start_time attribute is blank

#

it'll more likely cause as_timestamp() to fail and maybe giving a warning, and then fail to do the subtraction

little lion
#

im going to try it with a calendar sensor that doesnt have a scheduled game

inner mesa
#

better to guard against unexpected values than to accept and deal with random results

#

the value of as_timestamp("") (a blank string) could change at any time because it doesn't make sense

little lion
#

yeah when i did {{ states.calendar.michigan_wolverines }} theres no start time attribute

#

because nothings scheduled

#

so when i do {{ ((as_timestamp(states.calendar.michigan_wolverines.attributes.start_time) - as_timestamp(now())) / 60) | int }} i get a TypeError: unsupported operand type(s) for -: 'NoneType' and 'float' which is what i think you were referring to

inner mesa
#

that wasn't a valid test

#

I guess if you dig around the state object. But the easier way to do it is to look at the attributes in devtools -> States

little lion
#

yeah so {{ ((as_timestamp(states.calendar.michigan_wolverines.attributes.start_time) - as_timestamp(now())) / 60) | int if state_attr('calendar.michigan_wolverines', 'start_time') else 0 }} makes it return a 0 like you said

inner mesa
#

I know some stuff ๐Ÿ™‚

little lion
#

im trying to learn it

#

but yes you do lol

#

i hate just copying shit. i wanna know why lol

inner mesa
#

that is a good strategy

#

I was just copying your initial example above, and the better way to do that is:

#

{{ ((as_timestamp(state_attr('calendar.michigan_wolverines', 'start_time')) - as_timestamp(now())) / 60) | int if state_attr('calendar.michigan_wolverines', 'start_time') else 0 }}

little lion
#

yeah i changed it to that. i was just trying to understand why the if state_attr part was needed

inner mesa
little lion
#

cool beans.

#

alright i got another one for you then.
i made a sensor template and added this to my config.yaml

#

{{ state_attr('calendar.columbus_blue_jackets' , 'start_time') }}
and it returns the time correctly but in a 24hr format.

#

this as_timestamp(states('sensor.time_of_next_bluejackets_game')) | timestamp_custom('%I:%M %p') correctly converted it to a 12 hour format but im confused at how to put it toghether now lol

#

hmm might of figured it out.

#

change the config.yaml to
{{ as_timestamp(state_attr('calendar.columbus_blue_jackets' , 'start_time')) | timestamp_custom('%I:%M %p') }}

#

hmm that gave me the correct time now but lost the date

inner mesa
#

so add it back ๐Ÿ™‚

#

you told it to just give you the time

little lion
#

got it. i didnt know what the variables were for it but i guess its %b/%d/%Y

inner mesa
#

there's a link in the link I posted earlier:

#

Supports the standard Python time formatting options.

little lion
#

I looked through that template page and didnโ€™t see it but thereโ€™s a bunch of information on that page lol

gilded acorn
#

Looking through the documentation, I see that Templates says to use ```template:

  • sensor:
    etc....```

and that

  - platform: template
    etc....```
is legacy/deprecated/ not recommended

But in History Stats, the config example is in the legacy format of 
```sensor: 
  -platform: history_stats```

 Is there a "modern" version of the history stats sensor config, or is the legacy-looking version the modern?
inner mesa
#

no, templates were just pulled out to their own section

gilded acorn
#

great, thanks

silent barnBOT
hollow girder
# silent barn

I can call this script with action: true or false... but if I use on or off it converts to string! Can I make any check that on or off are assumed as true and false in the script?

#

because on/yes/true should all map to true

hollow girder
#

I did {% if action|string|lower == 'true' or action|string|lower == 'on' %} but this is very ugly... any alternative?

mighty ledge
#

when you call it, don't wrap on or off in quotes. That converts on or off to a string.

#
something: on # This will resolve True
something: off # This will resolve False
something: 'on' # This will resolve 'on'
something: 'off' # This will resolve 'off'
slender sage
#

Umm, so I'm trying to create a template from my philips hue motion sensor to have a virtual motion sensor that shows if there has been motion within 5 minutes. Basically I was thinking of just having a template sensor mirror the occupancy that I get from hue sensor and add a delay_off to handle the 5 minute thing. I'm not getting it working and I think I may have misunderstood something on how the HA works.

I have this in my configuration.yaml, but the sensor it produces just says "Unavailable"

template:
  - binary_sensor:
    - name: "Olkkari Liike"
      state: >
        '{{ state(binary_sensor.liike_olkkari_occupancy) }}'
      unique_id: template_olkkari_motion
      device_class: motion
      delay_off: 
        minutes: 5
#

What am I fumbling here?

hollow girder
mighty ledge
mighty ledge
hollow girder
#

ok, give me a second

silent barnBOT
hollow girder
# silent barn

this is the service... Now I have it with the if like that because I need to have this working..

mighty ledge
#

that's not the service

#

how are you running it to see the trace?

hollow girder
mighty ledge
#

no it's not

#

it's in however you're calling the script

hollow girder
#
service: script.android_bluetooth
data:
  target: diogo
  action: on
#

this is the call

mighty ledge
#

ok, show me that trace

#

and how are you calling it? Through the service caller?

hollow girder
mighty ledge
#

call it without action

#

and call it with action and see what the differences are

slender sage
hollow girder
#

i changed to

      title: >
        {% if action == true %}
          turn_on
        {% else %}
          turn_off
        {% endif %}
slender sage
#

Oh, states( not state(

mighty ledge
#

you don't need that, just if action

hollow girder
#

now I'll call it with ON

#
service: script.android_bluetooth
data:
  target: diogo
  action: on
mighty ledge
#

that's identical to what you had before

silent barnBOT
hollow girder
#

the result... it assumed the else...

#

if I do just if action it allways does on... because Strinf(on) is assumed as exists

mighty ledge
#

dude, that's not your problem.

#

yaml no matter what will take on and translate it to true

#

and off will translate to false

hollow girder
#

I know... but it's not doing that translations... as least not here

mighty ledge
#

wrapping in quotes will keep it a string. You're doing something else, possibly the fact that your variables match your incoming information

#

incoming variables cannot be overwritten by variables in your variable section

hollow girder
#

i'm doing the call without the '

mighty ledge
#

also, you should use variables to actually see what's coming through

hollow girder
mighty ledge
#

ex:

alias: "Android Bluetooth"
fields:
  target:
    description: Target Name
    example: <<name>>
  action:
    description: Action on Bluetooth
    example: on
variables:
  target_result: "{{ target | default("") }}"
  action_result: "{{ action | default(True) }}"
sequence:
  - service: script.android_message_relay
    data:
      target: "{{ target_result|lower }}"
      message: command_bluetooth
      title: turn_o{{ 'n' if action_result else 'ff' }}
#

then use the variables section to see what's actually being supplied to the script, and you'll see the output as well because you're providing it to your internal variables.

hollow girder
#

I call with on and works, because action_result exists, if I call it with off it does the on also... same problem.... It's not converting off to false.. instead is passing off as sting... making the it trigger, and not the else

silent barnBOT
hollow girder
#

look at action result

#

and this was the call

service: script.android_bluetooth
data:
  target: diogo
  action: off
#

I'm only doing this tests in the service test tab... can it be that? a "problem/bug" in the service tester tab?

#

I'll create a automation to test it out

mighty ledge
#

I have no idea if the service tester properly validates the yaml

hollow girder
#

All that is done in the UI is convrted to string

#

so it converted to 'on' in the UI... and off to 'off'

#

also if I do a automation on the UI I can't use the on/off...

#

I tried to do a automation in the yaml with off and it worked... the same automation created in the UI is converted to 'off' and gives the problem...

#

so the problem is in the UI...

#

don't know if this is a bug or not... but made me walk in circles for some time and wast my time and yours...

#

tks @mighty ledge

hollow girder
craggy rain
#

Hi everyone, this is my first second post here. Iโ€™ve been looking for answers on the forum, ha documentation, YouTubeโ€ฆ but I feel like I must be missing a core concept, as Iโ€™m not finding what I am looking for.

My goal is to have a record of every time my basement sump pump turns on, and for how long it was on each time. My basement sump pump is connected to a Sonoff S31 with power monitoring. When the sump pump turns on, it uses about 300W to run the pump and turns off when there is no more water in the sump basin. I want to use the power reading from the S31 as the trigger for my automation.

I used the Dishwasher example here in the HA docs to create the binary sensor template in my extended configuration.yaml: https://www.home-assistant.io/integrations/template/

My code now: https://www.codepile.net/pile/8ZOwe7ZE

This example appears to have logic built in, but I didnโ€™t have any luck using it. I'd like help with fixing the logic, and or a review of the binary sensor I created to ensure that I'm barking up the right tree. Any guidance would be greatly appreciated in how I can accomplish my goal.

arctic sorrel
#
        {{ states('sensor.s31_03_sump_pump_energy_power')|float > 0 }}
``` that's all you need
#

You can test in devtools -> Templates

craggy rain
#

Ah okay, I see what you mean. I put that code into the Dev Tools > Templates and I can see that it is currently reading false (as the pump is not running)

#

So I just need to clean up that line, ok

#

I'll give that a shot, thank you ๐Ÿ˜„

craggy rain
#

That seems to have worked. Thanks again!

mighty ledge
hollow girder
silent barnBOT
halcyon condor
#

im trying to read a rest api (json) and use value_template
but it gives Unknown and an error in the logs:
Template variable error: 'value_json' is undefined when rendering '{{ value_json.data.0.status.online }}'

#

however, if i save part of the json output in Developer Tools -> Template, then this template just works

mighty ledge
marble jackal
granite steppe
#

I am getting template warnings on my logs regularly. Does anyone know how I find out where it's coming from?

#
Template variable warning: 'dict object' has no attribute 'cluster_id' when rendering '{{ trigger.event.data.cluster_id }}'
Template variable warning: 'dict object' has no attribute 'endpoint_id' when rendering '{{ trigger.event.data.endpoint_id }}'
Template variable warning: 'dict object' has no attribute 'args' when rendering '{{ trigger.event.data.args }}'```
marble jackal
#

Probably and automation, template sensor or blueprint which uses these templates. ๐Ÿ™‚

granite steppe
#

I will take a look but do you know what it is saying? What should i look for?

silent barnBOT
marble jackal
#

You should look for these templates which are throwing these warnings. So eg {{ trigger.event.data.command }}

#

These are templates which are used on a event trigger, and then taking some data out of that event.
If there is no event trigger (for example if you trigger it manually, or by another trigger type) it can not find the data, and will throw an warning

granite steppe
#

Thanks. i dont think i am using any templates in automations. The only was are in the config file - the one above (https://hastebin.com/hurecunuru) and

    sensors:
      robovac_battery:
        friendly_name: "Robovac Battery"
        unique_id: "robovac_battery"
        unit_of_measurement: '%'
        value_template: "{{ state_attr('vacuum.robovac', 'battery_level') }}"
marble jackal
#

Somewhere this template is used, otherwise it won't appear in your logs ๐Ÿ™‚

granite steppe
#

Its annoying it doesn't tell me where

granite steppe
#

is this an event trigger?

  - event: start
    platform: homeassistant
spice otter
#

Trying to figure out how to create a new sensor using only a part of an attribute from another sensor.

I am able to create the new sensor and have it pull the attribute I want but I am struggling to workout how to have it only pull the part that I want.

This is the attribute data that my sensor has but I only want the time and not the date
start_time: 2022-01-13 14:15:00

Here what I have for my sensor so far
tottenham_event_day_start:
friendly_name: "tottenham event start"
value_template: "{{ state_attr('calendar.tottenham_hotspur_fc', 'start_time') }}"

There is probably a way better way of doing this that all you wizards use

Thanks

mighty ledge
halcyon condor
#

Warning about misuse or something

#

Maybe its a headers thing?

mighty ledge
#

No clue without seeing the errors, and I would have to google the error anyways

halcyon condor
#

I mean how the browser gives correct output and curl a different output. But its not ha related then :)

silent barnBOT
median mason
#

I have a sensor that outputs my nuc's uptime as follows:

sensor.intel_nuc5i3_system_uptime >> 01:16:43:28

I am calculating the uptime as a time like this

{% set d, h, m, s = states('sensor.intel_nuc5i3_system_uptime').split(':')  | map('int') %}
{{ as_datetime(states('sensor.date_time_iso')) - timedelta(days=d, hours=h, minutes=m, seconds=s)}}

output to template editor: 2022-01-11 20:12:31

But I get an error for this and get the value 'unknown'

sensor.template_intel_nuc5i3_uptime rendered timestamp without timezone: 2022-01-11 20:12:31

How can I add a timezone to my template?

marble jackal
#

Just use now(), it is timezone aware

{% set d, h, m, s = ('01:16:43:28').split(':')  | map('int') %}
{{ now() - timedelta(days=d, hours=h, minutes=m, seconds=s) }}
#

Or utcnow() if you want the utc time.

floral shuttle
heady cedar
#

I'm using a template to gather all problematic states of all plants. How can I remove a specific state like battery from the loop?

{%- for plant_id in state_attr('group.all_plants','entity_id') -%}
              {%- if is_state(plant_id, 'problem') -%}
                {%- set problems.plants = problems.plants ~ state_attr(plant_id, 'friendly_name') ~ ': ' ~ state_attr(plant_id, 'problem') ~ ', ' -%}
              {%- endif -%}
            {%- endfor -%}
marble jackal
#

You don't need a for loop for this

#

Oh wait, what do you expect as output? A dictionary?

silent barnBOT
heady cedar
marble jackal
#

That does not answer my question. Could you give me an example of how you would imagine the result of your template as shown above

#

Should string which looks like this: Petunia: Too much water, Roses: Not red enough, Violets: Need water

#

And you don't want to include those plants with battery in the the problem attribute

halcyon condor
heady cedar
dreamy sinew
#

i hate it but:

{% for thing in expand('group.living_room') %}
{% set ns.things = ns.things + ["%s: %s"|format(thing.name, thing.state)] %}
{% endfor %}
{{ ', '.join(ns.things) }}```
#

oh, adding extra filters, sec

marble jackal
#

I was just about to post this:

{% set plants = state_attr('group.all_plants','entity_id') %}
{% set problem_plants = expand(plants) | selectattr('state', 'eq', 'problem') | rejectattr('attributes.problem', 'search', 'battery') | map(attribute='entity_id') | list %}
{% set ns = namespace(info=[]) %}
  {% for entity in expand(problem_plants) %}
    {% set ns.info = ns.info +  [ entity.attributes.friendly_name ~ ': ' ~ entity.attributes.problem ] 
  %}
{% endfor %}
{{ ns.info | join(', ') }}
dreamy sinew
#
{% set ns = namespace(things = []) %}
{% for thing in things %}
{% set ns.things = ns.things + ["%s: %s"|format(thing.name, thing.state)] %}
{% endfor %}
{{ ', '.join(ns.things) }}```
dreamy sinew
#

just keep messing with your filter on things in my example

marble jackal
#

But I now see that that won't work though

dreamy sinew
#

expand() is a wonderful thing

marble jackal
#

you should split the problems mentions in problem, then remove the battery ones, and then join them again

mighty ledge
#

without your state_attr

#

expand explodes groups (Not light groups)

marble jackal
#

Well, you could try this @heady cedar

{% set problem_plants = expand('group.all_plants') | selectattr('state', 'eq', 'problem') | map(attribute='entity_id') | list %}
{% set ns = namespace(info=[]) %}
  {% for entity in expand(problem_plants) %}
    {% set ns.info = ns.info +  [ entity.attributes.friendly_name ~ ': ' ~ entity.attributes.problem.split(', ') | reject('search', 'battery') | join(', ') ] 
  %}
{% endfor %}
{{ ns.info | join(', ') }}
#

And thanks @mighty ledge!

heady cedar
#

Aloe: conductivity low, Bogenhanf: moisture low, conductivity low, Gรผnther:

marble jackal
#

Yes, I just thought of that myself

#

@heady cedar This should work

{% set problem_plants = expand('group.all_plants') | selectattr('state', 'eq', 'problem') | map(attribute='entity_id') | list %}
{% set ns = namespace(info=[]) %}
  {% for entity in expand(problem_plants) %}
    {% set problems = entity.attributes.problem.split(', ') | reject('search', 'battery') | list %}
    {% if problems %}
      {% set ns.info = ns.info +  [ entity.attributes.friendly_name ~ ': ' ~ problems | join(', ') ] %}
    {% endif %}
  {% endfor %}
{{ ns.info | join(', ') }}
#

Corrected to better version

mighty ledge
#

so i fyou want a more memory efficient one...

mighty ledge
#
{% set ns = namespace(info=[]) %}
  {% for entity in expand('group.all_plants') | selectattr('state', 'eq', 'problem') %}
    {% set problems = entity.attributes.problem.split(', ') | reject('search', 'battery') | list %}
    {% if problems %}
      {% set ns.info = ns.info +  [ entity.attributes.friendly_name ~ ': ' ~ problems | join(', ') ] %}
    {% endif %}
  {% endfor %}
{{ ns.info | join(', ') }}
marble jackal
#

Ah, yes, I see what I'm doing wrong, or at least inefficient

mighty ledge
#

for loops work on generators

#

if you cast things to list, it forces the generator to resolve everything

#

where a for loop will use the generator properly, especially if you are filtering things

marble jackal
#

Thanks again ๐Ÿ™‚

mighty ledge
#

np

heady cedar
#

It always feels good when the problems of one are not solved in 10 seconds ๐Ÿ˜›
Thanks to all! ๐Ÿ™‚

ornate sundial
#

sorry if this is the wrong thread...Please can anyone help me with my cover/sensor template. The yaml that i have added now lets me to control my mqtt shade from lovelace where i couldnt before and i had to add a template sensor so that i could view the position in lovelace too. I know it is missing something though because i cant set the shade to a specific position in node red and when the shade is fully open or shut it doesn't display "open" or "closed". As i am new to coding i can't work out what im missing, probably the value_template has something to do with it but atm i hav commented it out because it doesn't seem to do anything as it currently is written. see here https://pastebin.com/DdEP8ciK

marble jackal
#

Well, let me thank you first for using a code sharing site. But this code is completely messed up, and if it would be like this in your config you would not have a cover or sensor at all.
Could you try again using on of these sites:

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
ornate sundial
silent barnBOT
small rock
#

Appreciate the help!

inner mesa
#

You've mixed up the old and new template formats

#

state_class is only supported in the new format

small rock
#

Where could I find the new template formats?

inner mesa
#

In the docs you pointed to

small rock
#

I figured it out

inner mesa
#

Not that what you posted is what's described in the section at the end:

#

Legacy Sensor configuration format

small rock
#

instead of platform I need to use template:

inner mesa
#

The new format, yes

#

It's more than just that

small rock
#

Indeed

#

Now I'm facing 'statistics_not_defined' in the energy tab

granite steppe
marble jackal
silent barnBOT
obsidian lintel
#

Was trying to make a lock toggle

#

Doesnt work

#
  action: call-service
  service: |
    [[[
      return (lock.digital_door_lock.state === 'locked') ? 'lock.unlock' : 'lock.lock';
    ]]]
  service_data:
    entity_id: lock.digital_door_lock
#

Anyone can help?

mighty ledge
#

you aren't accessing the state object properly

#

also, your entity for the button card is what you're using, so just use entity.state instead

obsidian lintel
#

Legend

#

Mad respect to you @mighty ledge

#

Saw this on the forums posted by you

mighty ledge
#

with custom button card?

#

must be oooooold

obsidian lintel
#

1 year old

#

1 and a half

mighty ledge
#

yah, makes sense, I haven't touched that stuff in that long

hushed zephyr
#

I'm trying to write JSON to a file using the file notification integration. Shouldn't something like this work?

server: notify.writefile
data:
  message: >-
    {{ {"key": "{{states('sensor.blah')}}",
    "key2": "value"}|to_json }}

It only works if I add a char or something before or after the double curly brackets. but obviously that produces invalid json

mighty ledge
#

remove the inside {{ }}

inner mesa
mighty ledge
#

also, that

inner mesa
#

and this works fine for a persistent_message:

mighty ledge
#

also remove the " " you have around the inside {{ }}

inner mesa
#
set_test:
  sequence:
    service: persistent_notification.create
    data:
      message: >-
        { "key": "{{ states('weather.wf_udp') }}", "key2": "value" }
#

{ "key": "cloudy", "key2": "value" }

mighty ledge
#

message needs to be a string

hushed zephyr
#

Yeah the server thing is my bad, typing on the phone, probs autocorrect.

I tried without the double curly brackets and |to_json, same thing. I get a "template value should be a string for dictionary" error

wary lark
#

hey. i got a silly problem. I have a bunch of humidity and temperature sensors that has been added automatically by mqtt (using espresense). I want to round(1) the values without creating a new template sensor. I tried to customize the sensor with value_template but it doesn't work. any suggestions?

mighty ledge
hushed zephyr
mighty ledge
#

that's not going to work

#

{ trigger template use

#

your whole template needs to return the string

#

{{ }} on the outside, that's the only way.

#

you can attempt to do it the other way, but then you have to use either {% raw %} {%endraw %} or escape them

wary lark
hushed zephyr
#

So I tried that as well, with and without |to_json, same error. That only worked when I added a random char outside of the double curlies

mighty ledge
#

I'm guessing you did something wrong when you had it inside the {{ }}

#

post that version please.

hushed zephyr
mighty ledge
#

both of those are wrong though

#

you have templates in templates

#

that's what I said earlier when I said remove the inside "" and {{}}

#
    {{ {"current_condition": [{"temp_C": state_attr('weather.home_hourly', 'temperature'),
    "weatherCode": "320"}], "weather": [{"mintempC": states_attr('weather.home','forecast')[0].templow, 
    "maxtempC": states_attr('weather.home','forecast')[0].temperature}],
    "nearest_area": [{"areaName": [{"value": "XXXX"}],"country": [{"value": "XX"}]}]} |tojson }}

However that still might get resolved as an object in message

hushed zephyr
#

Yeah same thing

mighty ledge
#

then you have to provide a string unfortunately

#

what are you trying to do?

#

I know this is your current hurdle, but what's the overall goal

hushed zephyr
#

I'm trying to write a JSON file in /config/www with the weather data to grab from a Sonoff NSPanel flashed with tasmota

#

(I agree, end goal is always useful :)

mighty ledge
#

use curl to write to a file with a command line script

hushed zephyr
#

Curling from where?

mighty ledge
#

from the command line

silent barnBOT
hushed zephyr
#

Yes but what url?

mighty ledge
#

I have no idea what you mean by what url

hushed zephyr
#

What url would I curl? I need to build this JSON file from home assistant states

#

Polling weather APIs with straight curl is non trivial (API tokens etc), while I already have all this data at my disposal

mighty ledge
#

just the path to the file, it doesn't have to be a url

hushed zephyr
#

But I need to create this file, that's the problem I have

mighty ledge
#

that should create the file

coarse tiger
#

he wants the sonoff panel to grab the file (with curl)

hushed zephyr
#

Yes, I need home assistant to create a JSON file in /config/www, and subsequently the NSPanel will curl that file to obtain currently weather data.

mighty ledge
#

yes, and you can create a file with curl, can you not?

hushed zephyr
#

No?... Curl is an http/ftp client

coarse tiger
#

oh, you mean he should curl the api for the state and put the output into a file? would work ofc

mighty ledge
#

-o outputs though

hushed zephyr
mighty ledge
#

It's been like 5 years since I've needed to curl anything, so I could be wrong

#

I'm just trying to get it so you can create the file

#

you can use command_line to run ANY command

hushed zephyr
#

You can have curl output the result of an http call to a file of course, but I don't have a url to query

mighty ledge
#

that will create a file

coarse tiger
#

curl your homeassistant api

#

will get you the state and you can format it how you want

#

essentially the same as your notify with template

hushed zephyr
#

Seems so convoluted when a simple template should just work. Works fine in the dev tool template thingy

mighty ledge
#

you have restrictions imposed by the method you are using

#

your output must be a string

#

that's it

#

you can't use what you're trying to use

#

you're welcome to beat that dead horse, but I doubt it will be fruitful

#

no matter what, that template will resolve to an object if you're trying to write an object and the validation doesn't like that

#

so you have to get around that validation by enforcing that it's a string, (you already did that with your X before the output)

#

or use somehting else to output the same template

#

which you can do with command_line

#

does that make sense now?

#

so, you're outputting the same shit, jsut a different method

hushed zephyr
#

That was helpful thanks. Still not working though because shell_command refuses to have a : in it. Using > works as far as the config is concerned but the resulting service doesn't do anything :/

hushed zephyr
#

Ended up writing a bash script that formats the JSON and writes the file and I call that with the state templates as parameters. I know have my tasmotized NSPanel reporting the weather from home assistant data ๐Ÿ‘Œ

mighty ledge
#

I know it's a few hours late... but this would work with your file method...

hushed zephyr
#

Epiphany was last week... ๐Ÿคช

mighty ledge
#

gimme a sec to write it out

hushed zephyr
#

Sure :)

mighty ledge
#
    service: notify.write_weather_hourly
    data: >
      {% set out = {'current_condition': [{'temp_C': state_attr('weather.home_hourly', 'temperature'),'weatherCode': '320'}], 'weather': [{'mintempC': states_attr('weather.home','forecast')[0].templow, 
        'maxtempC': states_attr('weather.home','forecast')[0].temperature}],
        'nearest_area': [{'areaName': [{'value': 'XXXX'}],'country': [{'value': 'XX'}]}] | tojson %}
      {{ {'message':out} }}
#

that get's around the validation on message

olive moth
#

hello friends. I have a question. I have an event data here and would like to know if someone could help me to make a trigger

silent barnBOT
olive moth
#

In fact I need "CardNo": "879076c8", as a trigger. This card number is my rfid from my doorbell. I have 3 badgesso this "CardNo": "879076c8", will change for each badge

#

now my question is: how to create a template trigger with this event data...

glacial matrix
#

Evening Guys and Girls, could someone help me convert this to the "modern configuration" outlined here https://www.home-assistant.io/integrations/template/ please, I can't figure it out. I'm using an RF bridge, but I want to take advantage of the auto_off and delay off features. Thank you.

  - platform: mqtt
    name: "motion_livingroom"
    state_topic: "tele/RF_Bridge/RESULT"
    payload_on: "E664DE"
    payload_off: "E664DEOff"
    qos: 0
    device_class: motion
    value_template: "{{ value_json.RfReceived.Data }}"
olive moth
#

my approach for my question is:

silent barnBOT
mortal shard
#

Hi ๐Ÿ™‚

If I have an array, say from nordpool with tomorrow's value, end and start-time, is there a way to find the n consecutive lowest hours?
So if I want the three lowest hours (say 2-5am, not 1, 3 and 5am), how would I go about that?

dark scroll
#

Hi I hope someone can help me with a sort of concept question, Im new to the system and YAML and am trying to understand if there is a way to create a template that is referenced by a number of different devices/entities etc and whether you can add a custom attribute to that template? Or if that is even the right approach.

marble jackal
# olive moth my approach for my question is:

This won't work, you'll end up with an empty service call if another card is scanned. Use a template condition with {{ trigger.event.data.Data.CardNo in ["8804c91e", "879076c8"] }} or add the card numbers to the event trigger like this:

trigger:
  - platform: event
    event_type: dahua_vto
    event_data:
      Code: AccessControl
      Data:
        CardNo:
          - "8804c91e"
          - "879076c8"
olive moth
#

@marble jackal neat thanks will tr this

fossil venture
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.

fossil venture
dark scroll
fossil venture
topaz cave
#

Hi there, how would I reference the 'pictureUrl' state attribute?

camera.doorbell
inherited:
  state:
    pictureUrl: https:// <some URL>

I've tried the following but to no avail.

{{ state_attr('camera.doorbell', 'pictureUrl') }}
{{ state_attr('camera.doorbell', 'inherited.state.pictureUrl') }}
marble jackal
#

What happens if you enter this in devtools > TEMPLATES
{{ state_attr('camera.doorbell', 'pictureUrl') }}

#

Oh wait, i see.
This probably works {{ state_attr('camera.doorbell', 'inherited').state.pictureUrl }}

#

But check that first in devtools

topaz cave
#
{{ state_attr('camera.doorbell', 'inherited').state.pictureUrl }}

This worked - @marble jackal you're awesome, thanks so much.

cyan star
#

hey, does anybody have any idea how I can debug configuration load paths and order? I'm really lost with why my template binary sensor is not showing up in the states and I'm pretty sure there is something wrong with how I use !include_dir_merge_list

#

even though I basically copied and pasted documentation examples

mighty ledge
#

if you're using !include_dir_merge_list wrong, you'd see errors in your logs

#

if you have 2 template sections, the second one will overwrite the first

#

how about you just post what you have and the contents of the file that are not showing up

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.

cyan star
#

there are 2 examples (first is working, having issues with the other one)

#

let me add that state template is also correct as it shows correct value in the template tool

marble jackal
#

you are missing binary_sensor: in example 2

#

oh wait, dir_merge_named

cyan star
#

yup

#

what is really annoying is that configuration checker shows that everything is ok

marble jackal
#

No need to surround your template in quotes if you use > though

cyan star
#

well, looks like removing quotes helped

#

yep, confirmed, Thank You! Anyway, this is what you get changing configuration on Friday ๐Ÿ˜‰

little lion
#

i think this would be a templating question. i have a sensor that shows off and on but i wanna make it when its "off" show "armed" and when its "on" show "activated" on my lovelace dashboard? how would i do this.
the entity id is binary_sensor.dome_battery_powered_z_wave_plus_enabled_mousetrap_general_purpose

#

the entitiy id is binary_sensor.dome_battery_powered_z_wave_plus_enabled_mousetrap_general_purpose

inner mesa
#

You can often do this with a device_class, but I don't see an appropriate one for this. You'd either need to create a template sensor to transform the state name or use a card that lets you do it there

#

the template itself is simple:

#

{{ 'activated' if is_state('binary_sensor.dome_battery_powered_z_wave_plus_enabled_mousetrap_general_purpose', 'on') else 'armed' }}

little lion
#

i was reading through the documentation of templating and definitely didnt come across that yet lol

#

that made it super easy

inner mesa
#

the if/else syntax is like Python

mortal shard
# fossil venture This is probably beyond the limited capability of jinja templating and you might...

Thanks for your reply. In an attempt to further speciy: https://dpaste.org/ogT4/raw - this is a nordpool (power prices per kwh, start and end) output I've filtered out. In this case, it is sorted by value, but that means that the lowest values could be spread throughout the timespan of the day. What I would like to do is find the lowest consecutive time period (based on an input number, let's say 3) which will give me the cheapest time to perform an action such as charging my car.

little lion
olive sparrow
#

Anyone happen to have some guidance on HVAC controls?

#

In particular, I have one that is working fine (MQTT)

#

I need to include the option of heat source - gas or heat pump. Is there a particular entity I should use? I know I can use an input_select, but I would prefer to have it as an optoin in the climate entity

olive sparrow
#

i have fan mode and regular modes defined

midnight verge
#

Hello! Would someone be able to advise if this is possible? I have a helper dropdown called house_state, this holds two values, daytime and nighttime. I also have two input_numbers daytime_brightness and nighttime_brightness.

Is there a way to write a template string that would substitute hardcoded value"daytime" or "nighttime"_brightness and replace it with whatever the current state of house_state so it dynamically is either daytime_brightness or nightttime_brightness?

This is my current code:

brightness_pct: '{{ states(''input_number.daytime_brightness'') | int }}'

inner mesa
#

yes, there's an example just above your question in this channel

olive moth
#

any idea why this automation does not work ?

silent barnBOT
olive moth
#

this is my event:

silent barnBOT
mighty ledge
#

you can't do that

#

remove CardNo and add that check as a condition. or have 2 triggers, each with each CardNo

olive moth
#

i have three badges .. thats why i want either one of them.. or do i have to make three triggers?

mighty ledge
#

3 triggers or a condition checking the 3 values

olive moth
#

thre triggers seems easier ๐Ÿ˜›

#

let me test

#

how would that look like?

#
        CardNo:
          - a71e12c9
          - 879076c8
#

this part

mighty ledge
#

what does any field look like

#

use your code field as an example

olive moth
#

like t his

#
{
    "event_type": "dahua_vto",
    "data": {
        "Action": "Pulse",
        "Code": "AccessControl",
        "Data": {
            "CardNo": "879076c8",
            "CardType": null,
......
#

so like this

mighty ledge
#

that's your event...

silent barnBOT
olive moth
#

the code will trigger an automation like open the door

mighty ledge
#

why don't you try it out

olive moth
#

will do ๐Ÿ™‚

midnight verge
inner mesa
#

The problem there is that you've nested the templates

#

It's just badly formatted

olive moth
#

@mighty ledge didn't work..

#

dont understand why ๐Ÿ˜ฆ

inner mesa
#

brightness_pct: {{ states('input_number.' ~ states('input_select.house_state') ~ '_brightness') | int }}

midnight verge
#

Ah! Thanks, what does the ~ represent, is that like a concat?

inner mesa
#

yes

#

a more type-tolerant version of "+"

midnight verge
#

Thanks alot

floral walrus
#

Hello, I want to modify the state of a scene with a boolean but I don't see how to do it.
Do you have an example please?

inner mesa
#

Scenes don't have a state other than Scening

floral walrus
#

I thank you @inner mesa for your answer.
So how can I do that I can activate an automation group. The goal is to activate them by pressing a button and deactivating it when needed.

inner mesa
#

That's a group, not a scene

silent barnBOT
#

Groups allow the user to combine multiple entities into one.

inner mesa
#

You can turn groups on and off, and that state is applied to the entities it contains

floral walrus
#

ok I'll see with that

#

thanks

edgy umbra
#

Don't know if the question belongs here but is it possible to template a tap_action that uses a service?

#

This works but i have no idea how it will work with a service action...

#
    action: |
      [[[
        if (entity.attributes.alarm == "remote locking jammed bolt") {
          return "more-info"
        }
        return "toggle"
      ]]]```
inner mesa
grim obsidian
#

My robot vacuum has the sensor sensor.vacuum_last_clean_end which is a timestamp of when it last ran, e.g. 2022-01-13T11:27:37+00:00.

Can anyone help me with an expression that is true if the timestamp of that sensor is over 24 hours ago?

EDIT: This seems to work:
{{ now()|as_timestamp|int - states('sensor.vacuum_last_clean_end')|as_timestamp|int > 24*3600 }}

inner mesa
#

you could also use {{ states('sensor.vacuum_last_clean_end')|as_datetime + timedelta(days=1) < now() }}

#

or something like that

grim obsidian
#

Nice! Looks better

marble jackal
#

Or this
{{ (now() - as_datetime(states('sensor.vacuum_last_clean_end'))).days > 0 }}

inner mesa
#

Nice

grim obsidian
#

Another question: My Android app reports the "Next Alarm" sensor which has an attribute Local Time: Mon Jan 17 06:00:00 GMT+01:00 2022.
How can I format this into e.g. Monday Jan 17th 6:00am?

#

Alternatively, maybe it is easier to achieve the same by converting the Time in Milliseconds: 1642395600000 attribute?

marble jackal
#

Or the state itself, as it is a normal datetime

grim obsidian
#

True, but the state reports the time as UTC, so wouldn't I have to account for my local time zone (and DST) in the template in that case?

marble jackal
#

Use as_local
{{ as_local(as_datetime(states('sensor.pixel_5_next_alarm'))).strftime('%A %b %e %I:%M%p') }}

#

This will give AM/PM (so uppercase). %P should return lowercase am/pm but for some reason it is not working for me in the template checker

#

The timestamp will also be in UTC time btw

#

My example returns Saturday Jan 15 06:30AM for me now

#

It's a bit of a workaround, but this returns Saturday Jan 15 06:30am

{% set next_alarm = as_local(as_datetime(states('sensor.pixel_5_next_alarm'))) %}
{{ next_alarm.strftime('%A %b %e %I:%M') ~ next_alarm.strftime('%p') | lower }}
grim obsidian
#

Beautiful! Thanks a lot

marble jackal
#

I see you actually wanted 17th. I don't see that in the docs.

grim obsidian
#

Me neither. No big deal

queen meteor
grim obsidian
#

Nice one

knotty coral
#

Any suggestion how to start troubleshooting a template error that I think cropped up after an upgrade?

#

"Template variable error: 'None' has no attribute 'attributes' when rendering '{{ states.sensor.weather_station_report.attributes.list[0].lastData["tempf"] }}'"

#

(I get a bunch from all the templates with this particular JSON)

fossil venture
#

{{ state_attr('sensor.weather_station_report', 'list')[0].lastData["tempf"] }}

knotty coral
#

K. I barely remember the details of all this, so it's gonna take a while to remember WTF all this is for

#

but thanks

inner mesa
#

I think new folks always manage to find some cave drawings with states.xxx.xxx.state and such at first, and then it lives on in their config forever

#

sensor.buffalo

fossil venture
#

When I started for some reason using states.xxx.xxx.state did seem more "logical" to me.

manic onyx
#

Hi everyone. Need some suggestions, please. I have a power sensor that sends a cumulative pulse data for hourly and daily pulses. But I have issues with it rebooting at random times and hence starting to count pulses from scratch.
https://ibb.co/1nxNFcq
Just wondering if its possible to somehow sum the max hourly values, so that I can plot total daily ones?

fossil venture
#

You can get a rolling "last hour" total using the statistics sensor integration https://www.home-assistant.io/integrations/statistics/ If you want a "per clock hour" reading you are probably going to have to fix your sensor so you can use the utility meter. What are you using to count the pulses?

late lynx
#

I try to use the Template Alarm Control Panel but It's not clear how the code inputted by the user can be used inside the disarm and arm_* actions.
The example in the documentation shows code taken by secrets file.

prisma locust
#

hey guys! is it possibly to have more than one value_template state? i tried to do this: value_template: "{{ is_state('media_player.playstation_4', 'idle', 'playing') }}" but that is not working... i would like to be "on" when im playing and when its idle

inner mesa
#

yes, like this:

#
value_template: "{{ states('media_player.playstation_4') in ['idle', 'playing'] }}"
prisma locust
#

thanks a lot man :)

thorny snow
#

Hey all - having some small issues with my garage door cover. I used the basic template from the HA website and it works, but only the stop/close_cover states. The Open cover is not available (grayed out). My position template is: position_template: "{{ states('binary_sensor.garage_door_state') }}" Shelly 1 with reed switch.

#

Here's the rest of the cover code (just to the open_cover part). The icon state is working fine

      garage_door:
        device_class: garage
        friendly_name: "Garage Door"
        position_template: "{{ states('binary_sensor.garage_door_state') }}"
        open_cover:
          - condition: state
            entity_id: binary_sensor.garage_door_state
            state: "off"
          - service: switch.toggle
            target:
              entity_id: switch.garage_door```
inner mesa
#

value_template template (optional)
Defines a template to get the state of the cover. Valid output values from the template are open, opening, closing and closed which are directly mapped to the corresponding states. In addition, true is valid as a synonym to open and false as a synonym to closed. If both a value_template and a position_template are specified, only opening and closing are set from the value_template.

#

binary_sensor always reports on or off

#

perhaps: position_template: "{{ is_state('binary_sensor.garage_door_state', 'on') }}" or the opposite

thorny snow
#

Iโ€™ll try that. I had that logic somewhere else but removed it - canโ€™t remember where I had it now. I completely removed the position template line and it worked - but only until a entity refresh

#

Seems that my sensor is getting inconsistent readings which is complicating things. That code worked and the door is opening/closing and the proper arrow is highlighted to open, but the icon is not changing reliably. I'll have to double check my mounting - thanks!

knotty coral
#

OK I'm having a hard time converting an old template line to use state_attr() - getting errors with all the different tweaks

#

value_template: '{{ states.sensor.weather_station_report.attributes.list[0].lastData["humidityin"] }}'

#

how should I be rewriting that with state_attr()?

#

maybe I should rephrase that: I'm trying to extract various values in a json dict (lastData) several levels down. I used to do it with the line above but that stopped working when I upgraded HA last week.

inner mesa
#

value_template: "{{ state_attr('sensor.weather_station_report', 'list')[0].lastData['humidityin'] }}"

#

updating HA wouldn't have caused that not work, so you'll need to dig into that a bit further

knotty coral
#

hm, yeah - looks like it's actually not finding jsonrest in my custom components any more.

silent barnBOT
still dune
#
    actions: >
      {%- for entity in room_entities -%}
      - action: 'autoroom_{{ entity }}'
        title: '{{ state_attr(entity, 'friendly_name') }}'
      {%- endfor %}

becomes

    actions: |-
      - action: 'autoroom_light.wohnzimmer_dimmer'
        title: 'Wohnzimmer Dimmer'

I need the template working without '|-' behind actions. It wont work with '|-' behind actions.

Can someone help me please

inner mesa
#

You can't template both keys and values like that. Only values

prisma surge
#

I am trying to read this JSON in RESTful, but it doesn't seem to work. It is Google Sheet API

#

{
"range": "'Sheet 2022'!A10:B13",
"majorDimension": "ROWS",
"values": [
[
"Tuesday",
"1/11"
],
[
"Wednesday",
"1/12"
]
]
}

#

{{ states.sensor.sheet_2022.values }} doesn't show any value

inner mesa
#

Is that actually the state of that sensor?

#

That template doesn't make sense

prisma surge
#

This is the state of the sensor
{ "range": "'Sheet 2022'!A10:B13", "majorDimension": "ROWS", "values": [ [ "Tuesday", "1/11" ], [], [ "Wednesday", "1/12" ] ]}

inner mesa
#

You should parse that in the REST sensor itself

#

Otherwise you can use this, but it's not optimal

prisma surge
#

I am using Rest: in config YAML with adjustable timeout since it took a min to get the API to response
I tried value_template: "{{ value_json.values }}" but this show up instead <built-in method values of dict object at 0x7f95d16500>

inner mesa
#

You need to do value_json['values']

#

values() is a method for a dict

prisma surge
#

Thank you very much. It works now

torn meteor
#

do we have a template PRESS button yet?

inner mesa
torn meteor
#

wooo. thanks. i need it, unless there is a way to make a select list work like that

#

the thing with select list is if you try to do the thing "again" that's already selected, nothing happens

#

maybe i'm just not setting the select list state right (if that's even possible)

marble jackal
#

You can create a script which does an action based on the selected option, and place that on the dashboard

#

It will show RUN instead of PRESS though

still dune
silent vector
#

I'm trying to figure out how to know if an input number was last updated within the last 5 minutes.

"{{ ( as_timestamp(now(),0) - as_timestamp(state.last_updated('input_number.daniels_temperature'),as_timestamp(now(),0)) ) > 300 }}"

I get this error when testing this in the template editor

UndefinedError: 'state' is undefined

I use a similar template that works.

"{{ ( as_timestamp(now(),0) - as_timestamp(state_attr('automation.winter_3_zones_correction_revised', 'last_triggered'),as_timestamp(now(),0)) ) > 25 }}"
inner mesa
#

That's pretty weird syntax

#

'state' is indeed undefined there and you appear to be calling last_updated as a function?

marble jackal
#

{{ (now() - states.input_number.daniels_temperature.last_updated).seconds > 300 }}
No juggling with timestamps needed at all

silent vector
#

I see thank you

bleak ridge
#

I want to search for a specific word in a entitiy list in a template.. if word is present in any of entity names in the list, then I do something.. but I can't do like "'word' in list" as I could if it was just a string.. doesn't matter if the word is present one or several times within the entity names, just if it's present or not present

inner mesa
#

use search

#

like this?

#

{{ ['foobar', 'barblah', 'foo']|select('search', 'bar')|list }}

#

-> [ "foobar", "barblah" ]

#

you don't mention what "do something" entails, but hopefully that's a start

bleak ridge
#

probably a stupid question.. list here: {% set magnetsensorer = (expand('group.varme_magnet_sensorliste') | selectattr('state','eq','on')| map(attribute = 'entity_id') | list) %}

#

I then just want to verify if a specific word is present within the entity id's in that list

inner mesa
#

then do this:

#
{% set magnetsensorer = (expand('group.varme_magnet_sensorliste') | selectattr('entity_id', 'search', 'whatever')|selectattr('state','eq','on')| map(attribute = 'entity_id') | list) %}
paper hazel
#

Am I missing something? Why would these two render to "None"? 1: {{ state_attr('light.pool_controller_relay_1','last_updated')|as_timestamp }} 2: {{ state_attr('light.pool_controller_relay_1','last_changed')|as_timestamp }}

inner mesa
#

because neither is an attribute

#

if you look at devtools -> States, you won't see them in the attributes column

#

on the other hand:

#
1: {{ states.light.pool_controller_relay_1.last_updated|as_timestamp }}
2: {{ states.light.pool_controller_relay_1.last_changed|as_timestamp }}
boreal sorrel
#

I'm trying to make a template sensor that depends calculating two states with different update intervals. However, I only want to trigger the template sensor update when a specific one changes, as the computed value will be inaccurate if the sensor with the faster update time triggers an update but the slower one hasn't updated. How should I do this?

inner mesa
#

use a trigger in a template sensor

boreal sorrel
#

Ahhh right, thanks!

boreal sorrel
#

I was looking at a way to make states() call not become a dependency heh

upper mulch
#

Hi ๐Ÿ‘‹! Is it possible to use trigger/event based templates directly as value_template for a template light entity somehow? Or would this need an intermediate template sensor?

fossil venture
#

Explain exactly what you want in your template light template.

upper mulch
#

So basically I'm asking if the template_light can hold its state by itself or if it needs another entities state_attr()

cursive ice
#

so I have one of the new dual dials of tuyas, that in mqtt exposes toggle, brightness step up and down (got these working fine) but trying to figure out how to use the color temp step up and down option to control either color or light temperature

marble jackal
#

And this to decrease:

- service: light.turn_on
  target:
    entity_id: light.your_light
  data:
    color_temp: >
      {% set light = 'light.your_light' %}
      {% set step = 10 %}
      {{ [ state_attr(light, 'min_mireds'), state_attr(light, 'color_temp') - step ] | max }}
#

Change light.your_light and the step number to accommodate your needs

cursive ice
#

thanks worked ๐Ÿ™‚

marble jackal
# cursive ice thanks worked ๐Ÿ™‚

You will get errors in your log if you turn the dial when the light is off, as the color_temp attribute is not present then. So it only works when the light is on.
You could add a condition to your automation so it only works when the light is on, or you could add a light.turn_on service call without additional service data before this action

cursive ice
#

its not a issue as the dial only does the temp if your pushing in why rotating

marble jackal
#

okay

analog plover
#

I'm trying to make a template mqtt-sensor and the topic I'm subscribed to has nested arrays, eg: topic = {"wifi_sta":{connected: true}}, how do I reach the value that says "true"?

Right now I'm trying: value_template: "{{ value_json.connected }}" but it returns "unknown".

#

I realize this is very basic, but I'm honestly not finding a simple enough answer for my brain via google. ๐Ÿ˜…

#

Solved it! Seems I just had to add a dot inbetween, so: value_template: "{{ value_json.wifi_sta.connected }}"

obsidian lintel
#

anyway that I can put an input_select into this

background: center / cover no-repeat fixed url('/local/testbg.jpeg')

So that I can change BG through a selector?

marble jackal
#

If that fields accepts templates.

mighty ledge
#

that field does not accept templates

#

I believe you can template the background with a dropdown using card-mod

obsidian lintel
#

Any examples? Im a noob

mighty ledge
#

If you're a noob, I'd just settle with keeping the background associated with the current theme. Card-mod is not for noobs and it can be extremely difficult, this being one of those difficult cases.

#

I guess your first test can be installing HACS and card mod, if you get that far, ask in #frontend-archived

obsidian lintel
#

Thanks

glossy viper
#

hi. i am not a friend with regex and the gang. somebody can help me solve this sensor as for now is unavailable

native axle
glossy viper
#

Ty. I will try

glossy viper
#

same result ๐Ÿ˜ฆ

glossy viper
#

if I look in body values i have something strange before value: =C3=AEn valoare de <strong>70.00</stron= g> lei<br>

viscid fractal
#

Hey everyone,
so I already tried this by myself and already searched but couldn't find a similar solution, so I hope you guys can help me.
So heres my problem: I am working from home and im curious how much Energy I am using while I'm working (so I can calculate how much the energy costs me per year). I do have a Shelly Plug S connected to the desk where I work on and a sensor which determines if I'm currently working. The problem is that I also use the same desk (with Monitors and speakers) for gaming and my private projects. As far as I understood I can only create a template energy sensor which always increases without a way to stop the power increasing based on a condition. But I'm looking for a solution to increase a template energy sensor only while im working. Is this somehow possible?

unreal dawn
#

Hi. I'm trying to update my template to set a default value but struggling to get it to work. Can anyone help? Template is {{ "ยฃ%.2f"|format(float(states.sensor.daily_electricity.state)*0.1852+0.2508) }}

#

Figured it out - "ยฃ%.2f"|format(float(states.sensor.daily_electricity.state,0)*0.1852+0.2508) }}

atomic blade
#

What would be the best way to store a "collection" of something? I'm looking for some data structures I can append to, pop/push, etc. Not sure if this is possible

#

This doesn't necessarily relate to templates so many it's not the right place to ask

#

There don't seem to be helpers that would accomplish this either. The closest one would be the dropdown but that seems to have a static list of items

inner mesa
#

I think the easiest way to do that is by storing, retrieving, and manipulating the data via an MQTT broker

#

but what you're doing sounds like something more suited to PyScript or AppDaemon or external to HA

#

you could do it through attributes of a template sensor

atomic blade
#

Yeah was thinking attributes and maybe that wouldn't be a bad idea. Although, I'm using it as storage and not really as a sensor. So on HA restart I believe all those values would be lost?

mighty ledge
#

I use mqtt for that

#

It persists shutdown

real sigil
#

I have an xbox status sensor that has a value of "Last seen 2h ago: Call of Duty" I would like to create a new sensor from this one that only keeps "Call of Duty" I think I need to use regex_replace and I tried but 2h obviously changes depending on how long ago you stopped playing, so it can be 3h or even 3d. I'm not sure how to do that. This is what I have so far:

#
  • platform: template
    sensors:
    xxxpaul_xbox_gameplayed:
    friendly_name: xxxpaul's Game played
    value_template: >
    {{ states('sensor.xxxpaul_status') | regex_replace(find="Last seen *h ago:", replace='') }}
#

Would anyone be able to help?

atomic blade
inner mesa
atomic blade
#

Actually it looks like you can dynamically set values of an input select. Glad I had this conversation before finding that out lol

real sigil
mighty ledge
#

Test it in the tester

inner mesa
#

I can only guess

mighty ledge
#

Pin #1

real sigil
#

yes it works

#

@inner mesa

#

Thanks

real sigil
#

how do you write "if value of a state contains a certain value"? Same example as before, if the value is :Last seen 2h ago: Call of Duty then can how do I write, {% if states('sensor.xxxpaul_status') contains "last seen" %}

#

then

#

{{ bla bla bla }}

inner mesa
#

in

#

{% if "last seen" in states('sensor.xxxpaul_status') %}

#

depending on what "bla bla bla" really is, you can usually do something like:

#

{{ 'foo' if 'last seen' in states('sensor.xxxpaul_status') else 'bar' }}

real sigil
#

Thanks. Will try

#

this doesn't seem to work

#

{%- if "Last seen" in state('sensor.chezpaul_status') -%}
{{ states('sensor.chezpaul_status').split(': ')[1] }}
{%- else %}
{{states('sensor.chezpaul_status') | regex_replace(find="Classic Edition", replace='') }}
{%- endif %}

#

should it be in_state instead of in state

#

nope

#

it gives this error:

#

UndefinedError: 'state' is undefined

#

Found my stupid mistake

#

lif "Last seen" in states with an s

wise sluice
#

i'm looking for a little help with a template running in an automation.. i am looking to turn lights in a group to 10% if they are off or below 10%. I currently have this for those that are below 10% but couldn't seem to crack how to include also lights that may be off

honest slate
#

How to put text sensor value into automation?

marble jackal
#

A little bit more information would help ๐Ÿ™‚

honest slate
#
data: {{ states('input_text.tv_prompt_text') }}```
#

Doesn't work, i did it wrong somehow

marble jackal
#

you probably need:

service: notify.tv
data: 
  message: "{{ states('input_text.tv_prompt_text') }}"

So you need to specify that you want to send a message instead of just providing data, and you need to wrap your template in quotes (and use other quotes than you do inside your template)

honest slate
#

I Got to learn it eventually

cursive ice
#

hey TheFes thanks for your help yesterday when finished do you think I can bug you with something else (same dial but for living room) to cycle through the imported hue scenes in home assistant ๐Ÿ™‚

silent barnBOT
#

Don't ask to ask, just ask your question. Then people can answer when they're around.

When you do ask a question, try to provide as much background detail as possible. Ask yourself these questions first so that others don't have to:

  1. What version of the Home Assistant are you running? (remember, last isn't a version)
  2. What exactly are you trying to do that won't work?
  3. Is the problem uniform or erratic?
  4. What's the exact error message?
  5. When did it arise?
  6. What exactly don't you "get"?
  7. Can you share sample code, ideally with line errors where the error occurs?
cursive ice
#

Just looking for help in trying to get a dial with up and down values to change between some of the listed scenes in home assistant, so rotating one way to change scenes that way and rotation to change in reverse

#

not looking to include all the scenes just specified ones.

honest slate
#

@marble jackal it still doesn't work, it says "message malformed wrong entity id or UUID for dictionary value" . More than less. Isn't it about that text sensor is a 'helper' ?

#

Entity exists, and it's name is copypasted

#

Wait, maybe I figured it out

honest slate
#

Thank you

silent barnBOT
silent vector
#

I didn't know it was too big to post and it would be converted. Whoops.

I am trying to setup an action condition. The action condition is an OR that either 2 thermostats gap between set temperature and current temperature is less than 1. In other words 0. Then the action as I won't know which actually is less than 1 has to be a template. If I didn't use an OR then it's possible the first is false and the second is true but the first being false stops the remaining actions. This would be a climate set temperature value template. But it returns an error. The template is in the hastebin above.

marble jackal
#

remove the double curly brackets here: {% if "{{ (state_attr('climate.daniel_s', 'current_temperature') - (state_attr('climate.daniel_s','temperature')|float(0))) }}" < 1 and "{{ (state_attr('climate.master_bedroom', 'current_temperature') - (state_attr('climate.master_bedroom','temperature')|float(0))) }}" < 1 %}

#

Like this {% if ( (state_attr('climate.daniel_s', 'current_temperature') - (state_attr('climate.daniel_s','temperature')|float(0))) ) < 1 and ( (state_attr('climate.master_bedroom', 'current_temperature') - (state_attr('climate.master_bedroom','temperature')|float(0))) ) < 1 %}

silent vector
#

Thank you that doesn't turn up an error now. Does the action side look properly formatted? As in is it proper the way I have it setup below the conditional template

'{{ (state_attr("climate.master_bedroom", "temperature")|int) - 2 }}' '{{ (state_attr("climate.daniel_s", "temperature")|int) - 2 }}'
wise sluice
marble jackal
#

If this is a template for a condition, it should return True or False

#

It will not do that now

silent vector
marble jackal
#

You did not add a statement to the {% elif %}

#

But what are you trying to do here, it's still unclear to me

silent vector
#

I thought I did? I have 3 zone heating/cooling. I have an automation to avoid all 3 running at the same time. I prioritize 1 zone and shut the other 2 off if they are all running at the same time. Then when the priority zone turns off these 2 reset. I also have a thermostat that only keeps a 1 degree gap rather than the typical 2. So I have to force a 2 degree threshold. Turns on at 64 and turns off at 66 for example. There's a chance when I restore the temperature that it was already at 66. If it was it will mess up the threshold automation as it's now above what it was. That's why if the gap is 0 then if it's the same temperature as the set temperature -2 to keep the schedule.

{% if ( (state_attr('climate.daniel_s', 'current_temperature') - 
(state_attr('climate.daniel_s','temperature')|float(0))) ) < 1 and ( (state_attr('climate.master_bedroom', 'current_temperature') - 
(state_attr('climate.master_bedroom','temperature')|float(0))) ) < 1 %}
{% elif %} ( (state_attr('climate.daniel_s', 'current_temperature') - 
(state_attr('climate.daniel_s','temperature')|float(0))) ) < 1 %}
'{{ (state_attr("climate.daniel_s", "temperature")|int) - 2 }}'
{% else %} ( (state_attr('climate.master_bedroom', 'current_temperature') - 
(state_attr('climate.master_bedroom','temperature')|float(0))) ) < 1 %}
'{{ (state_attr("climate.master_bedroom", "temperature")|int) - 2 }}'
{% endif %}
marble jackal
wise sluice
#

ah

marble jackal
wise sluice
#

so if i'm understanding this, it's going to list the entities expanded from the first conditions ('on less than 26'), then add to that list the remaining entities ('off')

marble jackal
#

yes, and no need to join them, lists are accepted

silent vector
wise sluice
#

ok thank you!

#

what is the + sign or how is that used? i hadn't seen that before

silent vector
#

I guess I would also need a template for entity though? Or no I could select both thermostats as entities and the temperature value is the template?

marble jackal
#

it adds the two lists together to one list

wise sluice
#

got it

#

thank you for your help!

marble jackal
silent vector
marble jackal
#

I think you mean to do this:

{% if ( (state_attr('climate.daniel_s', 'current_temperature') - (state_attr('climate.daniel_s','temperature')|float(0))) ) < 1 and ( (state_attr('climate.master_bedroom', 'current_temperature') - 
  (state_attr('climate.master_bedroom','temperature')|float(0))) ) < 1 %}
{% elif ( (state_attr('climate.daniel_s', 'current_temperature') - (state_attr('climate.daniel_s','temperature')|float(0))) ) < 1 %}
  {{ (state_attr("climate.daniel_s", "temperature")|int) - 2 }}
{% elif ( (state_attr('climate.master_bedroom', 'current_temperature') - (state_attr('climate.master_bedroom','temperature')|float(0))) ) < 1 %}
  {{ (state_attr("climate.master_bedroom", "temperature")|int) - 2 }}'
{% endif %}
#

Your expression needs to be between the {% and %} of the elif

#

And you also added a statement to the else, which will not work. Either just use {% else %} or use {% elif foo == bar %}

silent vector
marble jackal
#

There is still nothing to return for the first statement in the code from my post

#

You had someting like '{{ (state_attr("climate.master_bedroom", "temperature")|int) - 2 }}' '{{ (state_attr("climate.daniel_s", "temperature")|int) - 2 }}' there, but that will return two values, and that will not work in your service call

silent vector
#

Would I do after the "Or"
2 separate service calls? Using these templates and just do 1 thermostat per call?

marble jackal
#

If you want to adjust two entities, with also two different values, you need 2 service calls

silent vector
#

Sounds good that makes sense now. 2 service calls. And use this template format. But of course with only 1 thermostat per template to return a single value.

marble jackal
#

correct

silent vector
#

If it's false what will the value be? Meaning if it's not. < 1

marble jackal
#

nothing

#

so your service call won't work

silent vector
# marble jackal nothing

That would not change the temperature right? It would just stop and evaluate the next service call?

marble jackal
#

it will stop the sequence completely

#

so it will not go to the next service call

silent vector
#

How do I make it go to the next service call if it's false?

marble jackal
#

Create a choose and only perform the service call if the change is needed would be a way

silent vector
#

Create a choose inside of a sequence? This has to come after the temperature was adjusted earlier in the sequence. Meaning the temperature will be adjusted in the action but one it's adjusted I want to check to see if they are < 1 then make a final adjustment.

marble jackal
#
- choose:
    - conditions:
        - determine somehow if master bedroom needs to change
      sequence:
        - change the tempperature of master bedroom
- choose:
    - conditions:
        - determine somehow if daniel's bedroom needs to change
      sequence:
        - change the tempperature of daniel's bedroom
silent vector
#

Well the issue is that would trigger when the automation didn't run previously.

#

Making the thermostat turn off before it's supposed to potentially. If there was an attribute for when the automation was executed that could work but there's Only a triggered attribute. It will trigger for each thermostat and may not actually execute anything so that's not going to work as a condition. For example I just had the automation run and it worked but there's a miniscule chance the thermostat was about to shut off before this automation is executed and it will on reset restore the temperature to the temperature it was previously at but it also matches the current temperature therefore messing up the 2 degree threshold as it's not higher than it was supposed to be if that makes sense. It might make more sense if you see the automation yaml I sent in your dms

silent vector
#

I realized I could just call a script from the action and use choose there and the templates.

silent barnBOT
sour canopy
#

Hey guys, I want to turn on/off a template switch and make that based on a different entity_id. It comes down to this:
https://pastebin.com/EBY8cVYd
But I can't get it to work. Any idea how I can set the condition of a specific entity ID with this

marble jackal
#

Just list all entities in the trigger, and use {{ trigger.entity_id }} to get the one which triggered the automation

marble jackal
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.

silent vector
marble jackal
#

If you use separate choose blocks like I did in my example, it will execute both, if the conditions for both are true

#

If you put them in one choose, it will only execute the first one that is true

silent vector
marble jackal
sour canopy
#

The idea is that I long press a button on the Nextion panel, which opens a details page with info about the light. So I want to set the on/off state on that page. Which is triggered by sensor.sonoff_nspanel1_zolder_light_details_id which knows that that button has been pressed

marble jackal
#

Is sensor.sonoff_nspanel1_zolder_light_details_id the actual name of the entity?

#

And if so, what would be an example of the state of this entity?

sour canopy
#

Yes. If I press one of the light buttons it sets this entity_id to button_1 or button_7 etc.

#

But that is custom made, so I can change it if needed

marble jackal
#

okay, no that's fine

sour canopy
#

I was also thinking about setting that sensor to the entity_id value, that's possible too

marble jackal
#

so, assume it is button_7, what should your template return?

#

should it check if the entity matching that button is on?

sour canopy
#

Exactly

#

I want to toggle the light with that button. So if the entity is ON, it should turn off, if it is OFF it should turn on

marble jackal
#

{{ is_state('light.your_light', 'on' }}

sour canopy
#

I had this: {{ is_state('group.staande_lamp_woonkamer', 'on') }}
But giving errors. Let me have a look what it said

marble jackal
#

define errors

sour canopy
#

Damn, I think I found it. Template was fine but target entity_id was wrong. Sorry sorry

#

I'll check better next time ๐Ÿ’ฉ

marble jackal
#

Yes, I was just about to say that

#

And the {% else %} is not needed

sour canopy
#

Okay, thanks!

marble jackal
#

But if you would enter the entity instead of button_on you could really simplify it

#

You could simply use {{ is_state(states('sensor.sonoff_nspanel1_zolder_light_details_id') , 'on') }}

sour canopy
#

Hmm, yeah. I'm gonna try to rewrite, that makes all my automations for that specific page much better

#

Thanks mate!

#

The reason I went for button_1 etc. instead of entity_id is because that didn't work with this. Because the value of a sensor couldn't be used for entity_id
- service: homeassistant.toggle target: entity_id: | {% set state = states('sensor.sonoff_nspanel1_zolder_light_details_id') | trim %} {% if 'button_1' in state %} group.staande_lamp_woonkamer {% elif 'button_2' in state %} light.houten_lamp_woonkamer {% endif %}

#

But if you have a smart idea how to use the value of the sensor as entity_id for service call, then I can re-write everything

marble jackal
#

Something like this works fine for me:```yaml
service: light.toggle
target:
entity_id: "{{ states('input_text.test') }}"

marble jackal
#

you are missing a step in your template, I also missed it

#

I didn't want to temper with it too much because of the double single quotes ๐Ÿ˜›

wise sluice
#

lol what do you mean?

#

i removed the last line from yours (adding the 'off' entity) but still didn't work

marble jackal
#

at least you can use it in the template checker then

#

But the main problem was that you should map the entity_id's

#
{% set low = expand('group.hall') | selectattr('domain', 'eq', 'light') | selectattr('state', 'eq', 'on') | selectattr('attributes.brightness', 'lt', 26) | map(attribute='entity_id') | list %}
{% set off = expand('group.hall') | selectattr('domain', 'eq', 'light') | selectattr('state', 'eq', 'off') | map(attribute='entity_id') | list %}
{{ low + off }}
#

| map(attribute='entity_id') was missing

wise sluice
#

ah ok! man every time i think i understand this i get more confused lol

marble jackal
#

If you want to use the template above, you need to do it like this (example using target)

target:
  entity_id: >
    {% set low = expand('group.hall') | selectattr('domain', 'eq', 'light') | selectattr('state', 'eq', 'on') | selectattr('attributes.brightness', 'lt', 26) | map(attribute='entity_id') | list %}
    {% set off = expand('group.hall') | selectattr('domain', 'eq', 'light') | selectattr('state', 'eq', 'off') | map(attribute='entity_id') | list %}
    {{ low + off }}
#

I'm doing the same as before, but now I've split it in two parts, to make it more readable

#

and I've added the missing filter (| map(attribute='entity_id'))

sour canopy
#

Okay. I re-wrote almost everything, but one thing is still missing and that's the brightness value sending back to the screen. It was like this: https://pastebin.com/6NdTzbuq
How to calculate the brightness of a templated entity_id? ๐Ÿ˜„

marble jackal
#

If it's not a light, it doesn't probably have brightness

wise sluice
sour canopy
marble jackal
#

ah okay, I understand your question now. But the same as for the state, {{ state_attr(states('sensor.sonoff_nspanel1_zolder_light_details_id'), 'brightness') }}

#

You might want to check if it is a light first though

sour canopy
#

Excellent, thanks. This helps a lot!

marble jackal
wise sluice
#

yes i did. trying it in dev tools now because vscode was throwing all kinds of comments about missing commas and bad indentation but it looked ok to me

#

from dev tools i get: UndefinedError: 'mappingproxy object' has no attribute 'brightness'

#

**if i run the automation i get those errors like before in the trace
**Error: Template rendered invalid entity IDs: [<template TemplateState(<state light.above_store=on; supported_color_modes=['brightness'], color_mode=brightness, brightness=8, friendly_name=Above Store, supported_features=32 @ 2022-01-18T17:49:49.903238+08:00>)>, <template TemplateState(<state light.dining_room=on; supported_color_modes=['brightness'], color_mode=brightness, brightness=8, friendly_name=Dining Room, supported_features=32 @ 2022-01-18T17:49:49.898966+08:00>)>, <template TemplateState(<state light.entry_1=on; supported_color_modes=['brightness'], color_mode=brightness, brightness=8, friendly_name=Entry 1, supported_features=32 @ 2022-01-18T17:49:47.557094+08:00>)>, <template TemplateState(<state light.living_2=on; supported_color_modes=['brightness'], color_mode=brightness, brightness=8, friendly_name=Living 2, supported_features=32 @ 2022-01-18T17:49:47.555413+08:00>)>, <template TemplateState(<state light.study_area=on; supported_color_modes=['brightness'], color_mode=brightness, brightness=8, friendly_name=Study area, supported_features=32 @ 2022-01-18T17:49:49.891817+08:00>)>]

#

this is the call i placed in dev tools:
- service: light.turn_on target: entity_id: > {% set low = expand('group.hall') | selectattr('domain', 'eq', 'light') | selectattr('attributes.brightness', 'lt', 26) | map(attribute='entity_id') | list %} {% set off = expand('group.hall') | selectattr('domain', 'eq', 'light') | selectattr('state', 'eq', 'off') | map(attribute='entity_id') | list %} {{ low + off }} data: brightness_pct: '10' transition: '5'

wise sluice
#

hey @marble jackal sorry i got this working! not sure what was wrong before but i messed around in the template checker and got it implemented. thanks for your help!

marble jackal
#

Looking at the error you did not reload automations yet

#

and I added | selectattr('state', 'eq', 'on') to my templates. But I think you copied them before I did that the first time

hazy musk
#

Hi, I'm trying to extract the value of action_user on this topic "zigbee2mqtt/DoorlockAvant"

Here's what I get on the topic when I unlock the door(used mosquitto_sub): "{"action":"unlock","action_source":0,"action_source_name":"keypad","action_user":6,"auto_relock_time":0,"battery":96,"linkquality":63,"lock_state":"unlocked","state":"UNLOCK","voltage":5700}"

sensor:

  • platform: mqtt
    name: "User 6 FrontDoor"
    state_topic: "zigbee2mqtt/DoorlockAvant"
    json_attributes_topic: "zigbee2mqtt/DoorlockAvant"
    value_template: "{{ value_json.action_user == '6' }}"

The sensor always return false when I unlock the door, have an idea why or what I missed ?

ionic pecan
#

I have a card with my ikea led lamp. It automatically adds a slider for brightness, but this lamp also has color_temp (cold-warm) how can I add another slider to the card?

mighty ledge
tawdry drift
#

Hi, I am trying to use the cover template but I get the following error while adding code to my YAML file: "[covers] is an invalid option for [cover.templte]. Did you mean [discovery]?" Does someone knows how to fix this?

hazy musk
marble jackal
#

There aren't any quotes around the 6 in the json, so that indicates it's not a string, but a number

#

That also applies to booleans. true is a boolean, "true" is a string

hazy musk
#

Oh, finally it doesn't work.. the state seems to change for a fraction of second and return to false.. It's really weird. I looks like the doorlock send a message to the topic with the action_user and immediately send another one with the current state of the lock and it's like this message always overwrite any trigger or template I try to make

hollow girder
#

A quick question... Are packages still good to use, or should we start migrating and stop using packages? I ask this because of the fact that the new sensor template not being compatible with package.

hardy moon
#

How do you set a template value if a certain condition is met? For example Im just checking the app_name attribute of a media player and want it to say something other than "unknown" if the state attribute isnt present

#

Right now I've got just
value_template: "{{ state_attr('media_player.backyard_tv_chromecast', 'app_name')}}"

#

I want it to just say "None" instead of "unknown"

hollow girder
#

Do a if

#
value_template: >
  {% if is_state('media_player.tv','unknown') %}
  None
{% else %}
  {{ states('media_player.tv') }}
{% endif %}
hardy moon
#

if im checking specifically for the app_name attribute shouldnt it be

#
value_template: >
              {% if is_state_attr('media_player.backyard_tv_chromecast', 'app_name', 'unknown') %}
                None
              {% else %}
                {{ state_attr('media_player.backyard_tv_chromecast', 'app_name') }}
              {% endif %}```
#

?

#

This returns the app name if something is playing but it still comes out as "unknown" when theres nothing playing

#

hm- I suppose because the attribute isnt actually 'unknown'- it just doesnt exist

#

{{state_attr('media_player.backyard_tv_chromecast', 'app_name')}} returns null as a dict, but {{is_state_attr('media_player.backyard_tv_chromecast', 'app_name', null)}} returns false ๐Ÿค”

hardy moon
#

Ok I got it working- but for anything except "None" as a string. Lmao wtf

#

This returns null as a dict

{% if states.media_player.backyard_tv_chromecast.attributes.app_name %}
  {{ state_attr('media_player.backyard_tv_chromecast', 'app_name') }}
{% else %}
  {{ 'None' }}
{% endif %}```
While this (which is just replacing "None" with "Nothing" returns "Nothing" as a string.
```yml
{% if states.media_player.backyard_tv_chromecast.attributes.app_name %}
  {{ state_attr('media_player.backyard_tv_chromecast', 'app_name') }}
{% else %}
  {{ 'Nothing' }}
{% endif %}```
#

I don't understand that behaviour

inner mesa
#

Yes, 'None' is a special word

hardy moon
#

odd

buoyant pine
#

It's a Python keyword that means null/no value