#templates-archived

1 messages · Page 122 of 1

deft timber
#

{{ states.person | selectattr("state", "==", "home") | map(attribute="name") | list | join(';')}}

glossy viper
#

amazing

#

ty

mighty ledge
#

Why wouldn’t you make that output json and use a normal rest sensor?

mighty ledge
#

Scrape is a pita, rest is much easier

#

Imo

mighty ledge
#

that's a good question

#

what do you have in the house that he would use?

#

yeah, probably because it's a time

#

I'd assume google home only accepts specific sensors

#

I know alexa only allows temperature and humidity sensors

#

Can you run voice commands in google home?

#

In alexa, I can create a routine and then trigger off that routine with a TTS response

toxic dome
#

Did that work? I'm curious now. I always thought the only sensors that could be exposed to google were ones with a device class of temp or humidity

toxic dome
#

you can but its not as fun as it sounds. I set it up at one point, you can make a bot using DialogFlow. And I did get it all working but once I realized I was going to have to start every conversation with "Hey Google, talk to Home Assistant", wait for it to move into that mode and then start conversing I was like nope, not for me lol

#

I think for that particular use case it might be easier to expose a script to google, tie it to a routine that listens for that phrase and then have the script call the tts_say action to get google to speak the value of the sensor

#

I think that works right? I don't really use tts_say much but I know its pretty popular

coarse tiger
cinder geyser
#

Is there any "sensor" allowing calculate and show measured value increase per some period of time?
Let's say I have sensors which shows "working time since start", now I would like to see "working time in last 60 seconds"
Displayed as (for example) "3 units/minute"

mighty ledge
#

@cinder geyser integration integration

silent barnBOT
#

Integrations integrate Home Assistant with devices or services, or provide functionality within Home Assistant. Add-ons provide additional software or services, which an integration could possibility integrate with. Add-ons are for Home Assistant OS and Supervised only, other install methods can install software other ways.

mighty ledge
#

bad hass bot

queen meteor
#

Bot pulls from sitemap. It is not hard coded.

waxen silo
#

Is this the place to ask about a 'shell_command' in a 'service-call' ? I am struggling with the infamous quotation marks problem passing data.

ornate storm
#

Whats the best way of creating a sensor that will give me the seconds since midnight? So at 8AM it should show 28800 and every day at midnight it should start the count again so it should go from go from 86400 back to 1.

ruby crane
#

Is it possible to use if-statements in the "params" part of a script?

thorny snow
#

Is it possible that the fan speed template isn't working like documented, or is it me ? When I add the line percentage_template: "{{ state_attr('light.bodemwarmtewisselaar_2', 'brightness_pct') }}" it gives me an error : Invalid config for [fan.template]: [percentage_template] is an invalid option for [fan.template] without this line everything works fine.

mighty ledge
mighty ledge
mighty ledge
thorny snow
#

@mighty ledge I am running 2021.1.5 on a ARM kubernetes cluster from docker image "homeassistant/home-assistant" stable

thorny snow
#

@mighty ledge You asked the right question. I changed the tag to latest and did a helm upgrade on my HA container. Now it runs the latest version and the template is working ! My bad. Thanks a lot for taking your time to help me with this. Br N.

mighty ledge
silent barnBOT
tawny valve
#

Why does the platform: mqtt show up as 2 lightning icons off/on while the platform: rest shows up as sliding switch? Which configuration determines the icon? thanks

rare panther
#

how to pick up the latest file name from a directory?

ornate storm
rare panther
#

I am using the following to store the snapshot from the camera. But I also want to send it to mobile phone as a notify. Since I do want to keep a timestamp of the files - for easy search in future. How can I get the file name which is stored by the below and use it in notify? One way is to get the latest file from the directory - looking for the template for the same - service: camera.snapshot target: entity_id: camera.entrance data: filename: '/share/img_store/snapshot_{{ now().strftime("%Y%m%d-%H%M%S") }}.jpg'

mighty ledge
#

Please give more than a vague answer, because what you are looking for is not entirely possible.

mighty ledge
rare panther
#

something like this? But wouldn't the name in the variable change since the name will change due to the exact time indicated ``` variables:
filename_image: '/share/img_store/snapshot_{{ now().strftime("%Y%m%d-%H%M%S") }}.jpg'
action:

  • service: camera.snapshot
    target:
    entity_id: camera.entrance
    data:
    filename: "{{ filename_image }}"```
#

Just checked - it works - thanks. Somehow I was under the impression that when the automation will be executed the file name will change

ornate storm
grim obsidian
#

Is it possible to do math in the below field, like this?

    - platform: numeric_state
      entity_id: sensor.temperature_living_room
      below: "{{ states('input_number.temperature_max') | float * 0.9 }}" 
      for:
        minutes: 5```
Doesn't seem to work.
mighty ledge
mighty ledge
ornate storm
grim obsidian
mighty ledge
#

no need for the if statement

#

for is available for template triggers

grim obsidian
#

Ah, so just:

    platform: template
    value_template: "{{ (states('sensor.temperature_living_room') | float) >
    ( states('input_number.temperature_max') | float * 0.9 ) }}"
    for:
      minutes: 5```
mighty ledge
#

yep

#

but indent the second line of the template or don't use a carriage return

#

Also, you don't need the ()

#
value_template: "{{ states('sensor.temperature_living_room') | float > states('input_number.temperature_max') | float * 0.9 }}"
grim obsidian
#

Thanks!

flint spindle
#

trying to iterate a group to catch turned on lights. Can't figure it out since expand function seems no working as described here https://www.home-assistant.io/docs/configuration/templating/#working-with-groups

This code put in template
{% for light in expand("light.desk_lamp", "light.bigroom_main") %}
{{ states(light) }}
{% endfor %}
generates this error
AttributeError: 'TemplateState' object has no attribute 'lower'

Any ideas?

dreamy sinew
#

you're mixing a bunch of things there that don't work the way you think they do

#

if you want to loop like that do

{% for light in ["light.desk_lamp", "light.bigroom_main"] %}
flint spindle
mighty ledge
#

expand will still work if you just want to get the state out

#
{% for light in expand("light.desk_lamp", "light.bigroom_main") %}
  {{ light.state }}
{% endfor %}
flint spindle
dreamy sinew
#

light.name

mighty ledge
#

what he said

flint spindle
mighty ledge
#

that example is wrong

#

i just made a pr

flint spindle
#

yes, because expand gives state objects not string object names, right?

mighty ledge
#

yep

quiet current
#

I have thermostat, that use room temp to display. I have been able to find the floortemp using rest-api. Is it possible to change the "sensor" that the thermostate use for actual temp?

inner mesa
#

not unless you use the generic thermostat integration

quiet current
#

@inner mesa How do I check that?. The thermostat is through the deconz intergration. And show up as an climate.thermostat_x

inner mesa
#

"no", then

quiet current
#

ok, I thought that the device config was store, and was editable.

inner mesa
#

you might be able to use generic_thermostat as a base to combine the various things you want, some based on your existing thermostat and some based on some other sensor, but you can't just do what you want without more work

quiet current
#

Ok, could be worth looking into 🧐

winged dirge
#

Anyway to make a sensor which displays last known value instead of ‘unavailable’?

#

I was thinking something like this but a sensor can't seem to reference itself: {% if states('sensor.encore_noire_V1') == "unavailable" % {{states('sensor.encore_noire_V2')}} {% else %} {{states('sensor.encore_noire_V1')}} {% endif %}

neon laurel
#

I want to automate the on/off times for each light in an area for every day of the week. I created date/time helpers for each light each day of the week (that's a lot but I don't think there's a way around it). I now have to create an automation for each light to turn on/off based on the helpers

#

is there a way I can create one for each day of the week or do I need to create one for each light each day of the week?

#

I guess I need a template that uses as a trigger the date/time helper that contains the name of the day

#

this is what it looks like right now

mighty ledge
neon laurel
#

thank you so much

mighty ledge
#

no clue if it works

#

you don't need 'day conditions' with that automation because it's handled by the templates.

neon laurel
#

I'll test it and report back

#

even if at the same time I'm looking into SimpleScheduler add-on

mighty ledge
#

there's also schedy or whatever it's called

fierce hornet
#

{{ now().strftime("%B") }} Displays the month name in English. is there a way so it gets displayed in my native language? HA is set to that language

dreamy sinew
#

it should be locale dependent

mighty ledge
#

I don't think language is set for the internals

ebon jasper
#

How to create weather template for climacell?
Best regards

fierce hornet
inner mesa
#

but you can create your own mapping if needed

#

the point is that you get the month as an index and index into your own array of translated values

fierce hornet
#

I will take a look at that, thanks!

mighty ledge
#

@fierce hornet as I said before, it's not translated in the internals. Never has been.

#

There are threads on the forum that cover this exact question

#

has exactly what you're looking for

glacial matrix
#

How would one go about creating a template sensor that shows the maximum value of a sensor over the last 24 hours?

  - platform: template
      Windspeed_max:
        value_template: "{{ state_attr('sensor.wupws_windspeed_stats_mean', 'max_value') }}"
      
      Windspeed_min:
        value_template: "{{ state_attr('sensor.wupws_windspeed_stats_mean', 'min_value') }}"

  - platform: statistics
    entity_id: sensor.wupws_windspeed
    name: Windspeed Average
    sampling_size: 288

I've got this far, but i think it might be terribly wrong. (288 as the sensor updates every five minutes.)

mighty ledge
#

@glacial matrix

silent barnBOT
mighty ledge
#

no need for templates

#

nevermind, i see you're using it

#

what's the problem, that should work fine

#

you might be off by 5 minutes, but you could double the sample size and add max age to 24 hours

glacial matrix
#

I wasn't sure i had got the setup right with template. i didnt realise i could just use statistics.

mighty ledge
#

well the result is the mean, but if you want max you'll need those templates you created

#

i just realized that your template yaml is wrong too

#
- platform: template
  sensors:
    windspeed_max:
      value_template: "{{ }}"
#

you're missing sensors, and you capitalized the field name

glacial matrix
#
      windspeed_min_24h:
        value_template: "{{ state_attr('sensor.wupws_windspeed_stats_mean', 'min_value') }}"

  - platform: statistics
    name: "Windspeed Stats - 24 hours"
    entity_id: sensor.wupws_windspeed
    sampling_size: 600
    max_age:
      hours: 24
#

So what name would i give the template sensor to pick up the windspeed stats? I assume it should be "windspeed_stats_-_24_hours"

mighty ledge
#

it's best if you start up and find out what the entity_id is

#

remove the template sensors then add them in once you have the entity_id

glacial matrix
#

just restarting HA now.

glacial matrix
#

Great, That seems to be working. I think I realised i didnt need the min and the max, average and max makes more sense. Min might be 0. lol

#

🏀🏀🏀🏀🏀🏀. Just seen my mistake! might help if it is set to look at the max value, not the min value!

balmy terrace
#

folks , how can I use {{ trigger.above }} or {{ trigger.below }} in the choose option, without specifying a value?

for example: I'd like my sentence to be like ' if {{ trigger.above }} was used to trigger the automation (no matter was the value), do this '
and NOT this --> {{ trigger.above == 5 }}

inner mesa
#

I don't think you can

#

it's a pretty simple test to say {{ trigger.to_state.state|float > trigger.above|float }}, though. As far as I can tell, trigger.above is just repeating the threshold you provided and not telling you that that's what triggered it

#

could be wrong, didn't know that those variables existed until you mentioned them

mighty ledge
ancient lynx
#

Hey all, I have this template {{state_attr('calendar.2021_fia_formula_one_world_championship_race_calendar', 'message')|title}} that gives Formula 1 Gulf Air Bahrain Grand Prix 2021 - Practice 1. If I want to make two sensors, one with everything before the '-' and one with everything after, how would I go about that? I've tried |split(' - ') but get "TemplateAssertionError: no filter named 'split'".

#

The only stuff I've found on the forums seems to have the old states.sensor.state syntax.

inner mesa
#
{% set title = "Formula 1 Gulf Air Bahrain Grand Prix 2021 - Practice 1" %}
{{ title.split(' - ') }}
#
[
  "Formula 1 Gulf Air Bahrain Grand Prix 2021",
  "Practice 1"
]
ancient lynx
#

So it does have to be handled by two lines. Interesting. Thank you!

inner mesa
#

probably not

#

I just did it that way to test

#

Same result: {{ "Formula 1 Gulf Air Bahrain Grand Prix 2021 - Practice 1".split(' - ') }}

#

the point is that it's a method of a string and not a filter

ancient lynx
#

Hmm. Interesting, works just fine, but if I want to apply filters afterward, it does some weird formatting stuff.

#

I'll dig in more. Thanks.

inner mesa
#

np

balmy terrace
inner mesa
#

‘states’ is the collection of all state objects. Each one has a ‘state’, which is the state that you’d see in devtools -> States

#

I guess more correctly, ‘states’ is a collection of platforms (like ‘light’), which is in turn a collection of objects. Each object has the definition in the link.

dreamy sinew
#

states contain domains contain states (entities)

lime forge
#

Hi I have two sensors with date, how can I make a sensor with a subtraction result?

rose dawn
#

Hi all, new HA user here. I have a temperature sensors which I wanted to add offsets to and found from the forums that people add templates and copied that like this:

"{{ ( states('sensor.etupiha_temperature')|float - 0.7 ) | round(1) }}"

And it basicly works fine. Only problem is that I have a automation that restarts HA at 4am and the template is getting the "offset" (-0.7 in this case) value before sensors come back up and it messes up with my beatiful graphs 😄 anyway,could I make it ignore values after restart or smt like that? Althou I used to restart because I lost some sensors, but dont use those anymore, so maybe I should restart HA so often..

sonic nimbus
#

Hello, Im having an error in my logs Error while executing automation automation.sync_volume_google_home_downstairs: Error rendering data template: TypeError: '>' not supported between instances of 'NoneType' and 'float'

#

is it because parsing to float or something else?

dreamy sinew
#
``` is evaluating to `None` you cannot use gt/lt with `None`
sonic nimbus
#

that means that my entity is off or unavailabkle, and for that reason volume_level attribute is None?

wicked oracle
#

Hi everyone, may I get some help with a template sensor ? I've been struggling with it for a few days without result...I'm almost at what I want to achieve, minus an irritating detail ^^

#
    - platform: template
    sensors:
      feeder_trigger:
        unique_id: feederTrigger
        friendly_name: 'Dernier déclenchement'
        value_template: >
          Il y a {{ relative_time(states.automation.nourrir_le_poisson.attributes.last_triggered) | replace('hours', 'Heures') | replace('minutes', 'Minutes') | replace('seconds', 'Secondes') }}```
#

sorry, paste has destroyed indentation
This is my sensor, and this is how I display it in a card :
https://ibb.co/BtpkhdS

#

(the one in the middle)
The problem is that even if I run the automation, the relative time displayed never updates...
Any clue on what I'm doing wrong ?

#

Ah well in fact it gets updated when I run the automation, but then the value always stays the same. Meaning it displays 0 seconds, and even if I refresh the page 10 minutes later, it still displays 0 seconds. How can I force it to be updated let's say every minute for example ?

mighty ledge
#

Just add now() to your template, doesn’t matter where

wicked oracle
mighty ledge
#

Yep

wicked oracle
#

Sorry but I'm getting an invalid config...I think I don't understand what you mean by "doesn't matter where"

dreamy sinew
#

{% set foo = now() %}

wicked oracle
#

I feel stupid but I really dont understand what you want me to do and where...

#

Okay I think I have found, let's see if it works ^^

#

Yes it works !! many thanks @dreamy sinew and @mighty ledge for the tips, really appreciated !

robust ermine
#

hey can I get some help with a template I had for finding the lowest forecasted pressure in OWM? it was working but apparently the format got changed from datetime to str for some reason and now it doesn't work due to the data types being different. is there some way to convert it back to datetime?:
{% set start = now() %}
{% set end = start + timedelta(hours=48) %}
{{ state_attr('weather.openweathermap', 'forecast') | selectattr('datetime', '>=', start) | selectattr('datetime','<=', end) | map(attribute='pressure') | list | min }}

#

gives: TypeError: '>=' not supported between instances of 'str' and 'datetime.datetime'

dreamy sinew
#

probably need to convert those start and end values to strings via strftime

robust ermine
#

would >= & <= work on it in str format?

dreamy sinew
#

comparing a string to a string yes

robust ermine
#

yes but will the string comparison of datetimes be valid? trying to think about the format

dreamy sinew
#

as long as you match the format correctly it'll work

robust ermine
#

ok thanks. separate question: i kinda want to change this template up. instead of just finding the lowest value i think i want to set up two separate templates - 1) template that gives the difference between the highest val in 48hrs and the lowest val after that point in 48hrs; and 2) template that gives difference between the lowest val in 48hrs and the highest val before that point

#

no idea how i'd set either of those up though

dreamy sinew
#

have one sensor be the list

#

have the others pull what they need from that list

#

pressure_list:

{% set end = start + timedelta(hours=48) %}
{{ state_attr('weather.openweathermap', 'forecast') | selectattr('datetime', '>=', start) | selectattr('datetime','<=', end) | map(attribute='pressure') | list }}```
pressure_min: `{{ states('sensor.pressure_list')|list|min }}`
pressure_max: `{{ states('sensor.pressure_list|list|max }}`
pressure_delta: `{{ states('sensor.pressure_max')|float - states('sensor.pressure_min')|float }}`
robust ermine
#

that would give me max-min, but i want max-min(values after max) & max(values before min) - min

#

maybe there'd be a way to subset pressure_list into something like pressure_list_after_max & pressure_list_before_min

silent barnBOT
zealous drum
#

ugh, it wasn't really that big of a wall. 😕

#

the question was hoping someone can help me with a simple package I'm trying to build. I'm just trying to have the binary sensor icon be consistent. First I wanted it to be icon A or B depending if the binary sensor was on or off, but it kept throwing a loop warning. Next I tried to customize and just maintain a static icon. Every time I change state, it reverts back to the default icon... Here is what I've tried so far.

iron surge
#

I am completely new to HA, and I've had great success so far. most things just work, which is freaking amazing. Now I want to add an automation for my bug zappers. They're controlled by a z-wave paddle switch. I understand how to do an automation for "turn them on at sunset -0:30:00" and 'turn them off at sunset +6:00:00" - but I want to add a condition for the 'on' automation - only turn on between date x and y - I was told to use a template - can someone explain?

inner mesa
#

something like "between month x and y" is pretty simple, but you can add more to it and be more precise

fickle quiver
#

can somebody tell me why this isn't rounding?

#

{{ ("5292913"| float) /125000 |round(1)}}

inner mesa
#

It’s rounding 125000

#

You need another set of parentheses

fickle quiver
#

you are a genius

#

{{ (("5292913"| float) /125000 )|round(1)}}

#

thank you!

grim flicker
#

Does anyone know how i check multiple statements in one line. Does this work within home assistant templates? so like this:

      {%- if (datum == gftafval or datum == restafval or datum == papierafval) -%}
        true 
      {%- endif %}

I would like to make a trigger check if one of the following is true and then trigger an automation. I have set the right variables and datetimes. i only need to know how to check multiple statements

coarse tiger
#

the template section in devtools is great for testing templates

charred dagger
grim flicker
#

so it is or to use multiple

mighty ledge
#

@grim flicker if they are simple types (int, str, float, bool) you can simply do

{{ datum in [gftafval, restafval, papierafval] }}
dreamy sinew
#

gotta use quotes for string checks

grim flicker
#

ok thanks will check that

pallid flower
#

This must be very simple so sorry in advance. I am trying to extract sensor values from mqtt json payload, the same topic can contain multiple value pairs but it rarely contains all in the same topic. I'm using value_template to check if the variable is defined and if it is extract the value for display. The challenge I have is that even if the variable is not defined the sensor itself assumes a zero value and overwrites any previous reading. Is there a way to stop processing the sensor as soon as I find the variable is not defined?

iron surge
#

From the post above by @inner mesa I can get a general sense of a template. Can anyone point me to a 'step by step' overview (hand holding) of how a template gets created/edited, then how it is referred to by a trigger or condition or whatever?

inner mesa
#

there are lots of examples right in that thread

silent barnBOT
gusty nimbus
#

hey i have a problem with my 'template thing'
i have an file.yaml loaded with code:
in that url of hassbot
when the input_boolean.droogkastgevult is on it should switch the automation on and if the boolean is off it should switch off
I don't get any error and it doesn't work
Did i do something wrong
Many thanks on advance

gusty nimbus
#

i found another way to do it tx anyway

pallid flower
silver pewter
#

Is it possible to have 2 states in this template somehhow? :

"{{ not is_state('media_player.jbl_vardagsrum', 'playing, paused') }}"
#

playing or paused

#

that did not work 😛

deft timber
reef ferry
#

is there a function similar to relative_time but that works with future dates? I am trying to figure out how many days until event

mighty ledge
deft timber
#

{{relative_time(now() - timedelta(seconds=as_timestamp(f) - as_timestamp(now()))) }} f being your future date. It creates a date in the past with the same delta than you future date

vagrant kiln
#

hey guys, I'm trying to build a discomode for my light, right now I'm pretty stuck, it seems I'm not completely understanding how to use the "data_template:" especcially the part with the ">" or ">-" behind it. Where can I find what these sign mean to learn how to execute my template without a syntax error? 🙂

#

of course I tried to google, but without a name it's super hard to find something

mighty ledge
spice crow
#

Hi!
I have a question about blinds in HA, i have blinds that are connected via telldus live, but they show up as lights in HA, is there some way to change the unit from light to blinds?

teal umbra
#

Is it possible to parse json from a mqtt message in the template editor?

toxic dome
oak summit
#

Is there a template to get the name of your home assistant installation?

#

the one we set at the top of /config/core

mighty ledge
dim iron
#

can i pull data directly from mqtt and how?

#

im trying to save a message to a file, only 1 message

dim iron
#

ahh ty @inner mesa , the gui is causing issues like usual

celest tinsel
#

Hey, folks. I'm trying to change the look of a lovelace card when a particular event has been trigger for more than, say, 5 mins. I have card-mod loaded and working, but I think I need a template to activate the change. I've read through the templating docs, but I'm not sure where to start. Is there an example I can look at to get started?

celest tinsel
#

How about this for a more narrow question - can I find the time an entity state changed in a template? I should be able to do some math with that.

inner mesa
#

Yes. Each state object has last_updated and last_changed properties

vagrant kiln
formal ember
#

entity_id for heater switch, must be a toggle device. - does this mean I need to create a template switch to toggle the entity on and off? and if so, how do I toggle something that's power options are either heat and off or cool and off?

#
  switches:
    bedroom_aircon:
      value_template: "{{ is_state_attr('climate.master_bedroom_aircon', 'hvac_modes', 'cool') }}"
      turn_on:
        service: script.bedroom_ac
      turn_off:
        service: climate.turn_off
        target:
          entity_id: climate.master_bedroom_aircon```
#

is what I came up with but doesn't seem to work

feral spade
#

I'm trying to convert a value I get as sensor to string. I currently have template_value: '{{ value != 2 }}' which converts it to bool.
Trying to go further to a string, I tried the {% if ... %} {% else %} style, and both C and python style ternary expression.

mighty ledge
formal ember
#

ah so the device already has to be on cool?

#

how would i get it to toggle from off to cool and vice versa?

mighty ledge
#

That's how you wrote the value_template, which is what determines the state, so yes.

formal ember
#

wow i am retarded

mighty ledge
#

if you want cool when turning on, then your turn_on service must turn it to cool

formal ember
#

you would have a good laugh if you looked at my yaml no doubt haha

mighty ledge
#

meh, everyone makes mistakes on their first template device

#

it's a rite of passage

feral spade
#

How to go from bool to string in value_template. Because the various if constructs I tried lead to errors

formal ember
mighty ledge
mighty ledge
formal ember
#

so really should be service: climate.turn_on target: entity_id: climate.bedroom_ac

formal ember
# mighty ledge turn_on list is a list of services and doesn't use a template
  switches:
    bedroom_aircon:
      value_template: "{{ is_state_attr('climate.master_bedroom_aircon', 'hvac_modes', 'cool') }}"
      turn_on:
        service: climate.turn_on
        target: 
          entity_id: climate.master_bedroom_aircon
      turn_off:
        service: climate.turn_off
        target:
          entity_id: climate.master_bedroom_aircon```
Looking better? Or have I still stuffed up `value_template`?
mighty ledge
#

does climate.turn_on set it to cool?

#

the value template is fine

formal ember
#

no, I think i would have to list attributes?

#

but unsure how I would do that

mighty ledge
#

check out all the climate services that set the hvac_mode

feral spade
# mighty ledge Why do you need a string? What are the errors you getting?

Because I want it to be a string in the automaticlaly handled overview thingy

2021-03-26 12:28:51 ERROR (MainThread) [homeassistant.config] Invalid config for [sensor.snmp]: invalid template (TemplateSyntaxError: unexpected '%') for dictionary value @ data['value_template']. Got '{{ {% if value != 2 %} Connected {% else %} Disconnected {% endif %} }}'. (See /home/homeassistant/.homeassistant/configuration.yaml, line 16). Please check the docs at https://www.home-assistant.io/integrations/snmp
The others looked similar. Just with the other syntax in there that I tried

formal ember
#
        target: 
          entity_id: climate.master_bedroom_aircon
            hvac_modes: cool
            fan_modes: medium

like that?

#

this is all the state attributes for the main entity

formal ember
#

ok there is a service service: climate.set_hvac_mode

#

but if I call that, it does not turn it on

#

actually, it does 🙂

#

now i am getting somewhere

little gale
#

how do I create a fan template that controls low/mid/high fan modes on a climate entity?

feral spade
formal ember
#

so strange - now the switch will not turn off the AC

      value_template: "{{ is_state_attr('climate.office_aircon', 'hvac_modes', 'cool') }}"
      turn_on:
        service: climate.set_hvac_mode
        data:
          hvac_mode: cool
        target:
          entity_id: climate.office_aircon
      turn_off:
        service: climate.turn_off
        data: {}
        target:
          entity_id: climate.office_aircon```
formal ember
#

ahhh

#

😄

silent barnBOT
mighty ledge
#

{{ {% %} }} is never valid. {% {{ }} %} is never valid. Any permutation of that is also invalid. You'll only ever have these side by side... {{ }} {% %} {{ }} {% %} etc.

obsidian delta
# silent barn

I would really welcome a pointer - how to achieve a break between each line... tried everything.

mighty ledge
#

remove the -

#

Also, it depends on your notify service, some remove whitespace

formal ember
#

grrr.... still no good....

      value_template: "{{ is_state_attr('climate.office_aircon', 'hvac_modes', 'cool') }}"
      turn_on:
        service: climate.set_hvac_mode
        data:
          hvac_mode: cool
        target:
          entity_id: climate.office_aircon
      turn_off:
        service: climate.set_hvac_mode
        data:
          hvac_mode: 'off'
        target:
          entity_id: climate.office_aircon```
#

it looks right to me

#

it must be something to do with value_template: "{{ is_state_attr('climate.office_aircon', 'hvac_modes', 'cool') }}" no?

#

actually i have an idea...

mighty ledge
#

does the attribute hvac_modes change state to cool or does another attribute do that?

#

or does the main state?

formal ember
#

hvac_modes does both cool and off

mighty ledge
#

no, that's not the question

formal ember
#

i thought i figured it out but no, still broken

mighty ledge
#

does hvac_modes get set to cool?

formal ember
#

ah yes it does

mighty ledge
#

are you sure?

#

spoiler (no it doesn't)

formal ember
#

ugh.... haha....

mighty ledge
#

take a screenshot of the entity in the devtools states page

#

and post it here

#

well nevermind, I have an exmaple

formal ember
#

this

#

?

mighty ledge
#

hvac_modes is set to what?

#

and in your exmaple, what is hvac_modes set to?

formal ember
#

hvac_modes: heat_cool, heat, dry, fan_only, cool, off

mighty ledge
#

ok, is that 'cool'?

formal ember
#

let me turn it on again 🙂

mighty ledge
#

no, its heat_cool, heat, dry, fan_only, cool, off

formal ember
#

just changed from off to cool in the Filter states column

mighty ledge
#

ok, so the state changes from off to cool, so what would that template look like?

formal ember
#
      value_template: "{{ is_state_attr('climate.office_aircon', 'hvac_modes', 'cool') }}"
      turn_on:
        service: climate.set_hvac_mode
        data:
          hvac_mode: cool
        target:
          entity_id: climate.office_aircon```
mighty ledge
#

nope

#

see the link

formal ember
#

reading now

mighty ledge
#

first, do you know what method you are using right now?

formal ember
#

yep.... the one that doesn't work 😉

mighty ledge
#

yes, but what is it

#

I want to see where you sit with templates

#

and this will tell me

#

so, which method are you using?

formal ember
#

an is_state

mighty ledge
#

close, you're using is_state_attr

formal ember
#

or an is_state_attr

mighty ledge
#

yep

#

so, if you want the state, which one should you use?

formal ember
#

is_state I would think

mighty ledge
#

ok, and if you wanted to check an attribute which one would you use?

formal ember
#

is_state_attr no?

mighty ledge
#

Yep

#

you got it

formal ember
#

ok

#

I think I get it now

mighty ledge
#

aight, so modify the template and post it here

formal ember
#

the state is cool but the state attr is heat_cool, heat, dry, fan_only, cool, off

mighty ledge
#

well, hvac_modes attribute is heat_cool, heat, dry, fan_only, cool, off

formal ember
#

ah yes

mighty ledge
#

aight, so try to alter the template

formal ember
#

I would think

      value_template: "{{ is_state('climate.office_aircon', 'cool') }}"
      turn_on:
        service: climate.set_hvac_mode
        data:
          hvac_mode: cool
        target:
          entity_id: climate.office_aircon
      turn_off:
        service: climate.set_hvac_mode
        data:
          hvac_mode: 'off'
        target:
          entity_id: climate.office_aircon```
#

would do it

mighty ledge
#

That looks good

formal ember
#

and it works

#

yeeeehawww

mighty ledge
#

nice

formal ember
#

thank you so much 🙂

mighty ledge
#

np

formal ember
#

I have actually learnt something

mighty ledge
#

that was the goal 😉

formal ember
#

🥣 not just spoon fed

#

now just to wait for my new temp sensors and zzh to arrive and I can finally get this working properly, fingers crossed...

lean trench
#

I want an entity to be the result of three things. Calendar start time + waze travel time + 20 minutes.

#

How can I get a thing that is the result of that math?

#

I tried "{{ state_attr('calendar.xxcalendarnamexx', 'start_time') + state_attr('sensor.waze_travel_time_5','duration') + 20}}"

#

Not it doesn't appear to be logging a number

dreamy sinew
#

what are the actual values of start time and duration?

mighty ledge
lean trench
#

I've googled around and can't see to get the syntax right to find it

#

Do you have a link to one by chance?

eager veldt
#

Need help building a template that determines if the time from a sensor is before noon the next day (or current day if it's before noon).
The sensor outputs as: 2021-03-27T12:07:00.000Z OR Time in Milliseconds

spice crow
#

Can someone help me with cover template? I am stuck. i got the template working so i could open_cover and close_cover, but the state dosen't work, i am trying to change my blinds that show as light.gardin_kok, and have set brightness_pct: "{{ position }}" but still it won't work

restive parrot
#

Hey, I'm doing and if, else if, else if, thing for a weather provider, so, basically, I want it to use my own sensors for wind and rain, but if it isn't raining or windy, I want it to pull it from another weather provider. So, I'm doing this:

#
  condition_template: >
          {% if states('sensor.estacion_meterologica_ratio_de_lluvia') > 3 %}
            pouring
          {% elif states('sensor.estacion_meterologica_ratio_de_lluvia') > 0 %}
            rainy
          {% elif states('sensor.estacion_meterologica_velocidad_del_viento') > 19 %}
            windy
          {% else %}
           {{ states('sensor.aemet_condition') }}
          {% endif %}
#

But for some reason, I can't get it to work

#

If I do this, it totally works:

condition_template: "{{ states('sensor.aemet_condition') }}"
inner mesa
#

where is "condition_template" valid?

restive parrot
#

In the "Template Weather Provider"

inner mesa
#

you need to add |float to the states

#

states are strings

restive parrot
# inner mesa you need to add `|float` to the states

Like this?

    condition_template: >
          {% if states('sensor.estacion_meterologica_ratio_de_lluvia')|float > 3 %}
            pouring
          {% elif states('sensor.estacion_meterologica_ratio_de_lluvia')|float > 0 %}
            rainy
          {% elif states('sensor.estacion_meterologica_velocidad_del_viento')|float > 19 %}
            windy
          {% else %}
           {{ states('sensor.aemet_condition')|float }}
          {% endif %}
#

Oh sorry, I pasted the float there

#

It works!

#

Thank you

mighty ledge
#

you don't need a float on that last one, it wont' do anything

#

but you're going to be returning a number instead of windy, rainy, or pouring

#

Also your order of operation is wrong

#

er, nevermind, it's a separate sensor

inner mesa
#

agreed on the last one. should just stay a string

restive parrot
#

It isn't working

inner mesa
#

just removing |float from the else clause won't break it

#

perhaps you did something else

restive parrot
#

I already did?

inner mesa
#

what isn't working? and how?

restive parrot
#

The weather provider loads, but it shows "Unknown"

inner mesa
#

that could mean that your sensors aren't reporting good data. Does it work in the template dev tool?

restive parrot
#

Yeah

#

And the sensor reports "clear-night" so it should work

#

And all of the other sensors work

#

If I change the wind one to "> 0" it's shows windy

inner mesa
#

ok. I don't use that particular integration, so if it works in the dev tools, I don't know what could be wrong. Unless it's initially getting bad data at start, the sensors update, but the weather template doesn't see the chagne

restive parrot
#

Hang on

#

I just found what wasn't working

#

It's a bug

#

clear-night doesen't work in template weather provider

#

If I just do condition_template: clear-night

#

It doesen't work

#

If I do condition_template: sunny then it works!

inner mesa
#

it probably needs to be quoted

restive parrot
#

I tried that too

#

It isn't working still

grim flicker
#

I have this code which gives false but it should be true. i guess the round(0) isnt doing what it should. Can someone tell me how i write it the right way?
{{ is_state('input_number.jaloezien_in_procenten'| round(0), states('sensor.brel_motor_links_positie')) }}

#

input_number.jaloezien_in_procenten gives the value 0.0 and sensor.brel_motor_links_positie the value 0

#

So thats why i want to round the first one

#

This code is giving me the value 0 so i guess in an is_state i need to write it differently?
{{ states('input_number.jaloezien_in_procenten') | round(0) }}

dreamy sinew
#

You can't use is_state that way. It is expecting an entity for the first parameter

grim flicker
#

so i could use it for the second part

#

An easier way would be if a input_number helper wouldnt comunicatie 0.0 but just 0 Its pretty annoying that you cant tell in home assistant that it has to use round numbers. Especially when you set the increment step to 1.

#

By the way this {{ is_state(('sensor.brel_motor_links_positie'), states('input_number.jaloezien_in_procenten')| round(0)) }} isnt working as well

#

Does anyone have an idea how to fix this in a condition?

thorny snow
#

I noticed some weird behavior in the weather template when using the forecast template. When using {{ states.weather.openweathermap.attributes.forecast }} which generates a list things work alright but when using {{ states.weather.buienradar.attributes.forecast }} which generates a string a error occurs in the log and the weather(templated) entity doesn't work. Is this a fault in the weather_template integration or in the buienradar integration?

grim flicker
#

i gave up.... I made a sensor that first rounds the input_number and use that in a template

fossil venture
#

All you need is this {{ states('sensor.brel_motor_links_positie')|int == states('input_number.jaloezien_in_procenten')|int }}

slate tundra
#

if i have this trigger:

  - platform: device
    domain: mqtt
    device_id: ab8e6b8f333ee21c47bf8070b5d96d8a
    type: action
    subtype: on-press

what should i put on:

  - choose:
    - conditions:
      - condition: template
        value_template: "{{ trigger.?????? == 'on-press' }}"

to make it work?

fossil venture
#

If you change it to an event trigger, then you should be able to use trigger.event_data ==

slate tundra
#

hmm not sure i can do that with zigbee2mqtt

#

but let me try

#

yah no dice can use event on that

#

so only remains to listen on topics

ivory delta
slate tundra
#

@ivory delta yah that works and choose works also with them

#

but

#

i was trying to do it the recommended way 🙂

#

Via MQTT device trigger (recommended)

ivory delta
#

What's recommended depends on what you're trying to do. And I still have no idea what you're even trying to achieve here... your trigger already narrows down the device action to an 'on-press' subtype. What's the condition supposed to do?

slate tundra
#

let me put up something for you to see what i want to do

#

one moment

#

if you look at the commented triggers

#

i need the choose template conditions for the commented triggers

#

but that doesnt work i think

ivory delta
#

I'm not reading through 300 lines. Explain what you're trying to do.

slate tundra
#

take as example only first commented trigger

#

how do i make that:

  - choose:
    - conditions:
ivory delta
#

Ok... so you want to have X different triggers and then use a choose:... use MQTT triggers 🤷‍♂️

#

It doesn't matter if the one person that wrote the z2m docs says that device triggers are recommended. You need to think about the different available tools and pick the right tool for each task.

slate tundra
#

that is already done

#

okay

#

merci

ivory delta
#

De rien

slate tundra
#

ha you are french 😄

ivory delta
#

Non

#

I'm English, I just know a few words 🤷‍♂️

slate tundra
#

i was asking because i am using this @ my work

#

french company 🙂

#

okay thanks man

earnest cosmos
#

Hi there!
I have this

  - choose:
      - conditions: >
          {{ is_state('sensor.utendors_lysstyrke' | float, < 600) and
                is_state('input_boolean.in_bed', 'off') }}

... but it´s totally wrong.

#

The conditions should be like:

(if state_of_sensor is below xxx) and
is_state('input_boolean.in_bed', 'off')
earnest cosmos
#

I ended up doing this, thus conditions will not apply untill tomorrow when it´s not dark outside

action:
  - choose:
      - conditions:
          - condition: numeric_state
            entity_id: sensor.utendors_lysstyrke
            below: 800
          - "{{ is_state('input_boolean.in_bed', 'off') }}"
fossil venture
earnest cosmos
fossil venture
#

You still don't need a template. Use a state condition for the last condition.

earnest cosmos
#
- conditions:
    - condition: numeric_state
      entity_id: sensor.utendors_lysstyrke
      below: 800
    - condition: state
      entity_id: input_boolean.in_bed
      to: 'off'
#

state: 'off' would be it, right?

fossil venture
#

Correct!

earnest cosmos
#

Thanks"

#

I never found several condition: tests in the documentation for the choose: actions, though 🙂

fossil venture
#

Standard condition rules apply, see the condition syntax doc page.
FYI to do it all in one template would have been: {{ states('sensor.utendors_lysstyrke') | float < 600 and is_state('input_boolean.in_bed', 'off') }}

earnest cosmos
#

I tried this at first, but did not succeed

fossil venture
#

No you didn't. Look closely. There is no is_state for the first part of the template.

#

Also there were other issues that I just edited out.

earnest cosmos
#

you got it! It evaluates correct in the template editor here 😉 Thank you

spice crow
#

Hi! I am using a template to convert my light.gardin_kontoret to cover.gardin_kontoret
I did succed to get this working so it now show up as a cover instead of a light, but the problem now is the script can't see the position, so if i change the "brightness" witch is the position in the UI, it works great, but if an automation change the position, ex rolls it down - it won't change and appears as up in the UI, here is my script code

position_cover:
sequence:
- service: light.turn_on
data:
brightness: "{{(float(position)*2.55)|int}}"
entity_id: light.gardin_kontor

Thanks!

little gale
#

How do I create a trigger from a sensor entity that's triggered when its value drops by 2ºC?

#

e.g. I want to turn on a climate entity when bedroom temp drops

inner mesa
#

I would use a state trigger for any change and a condition template that subtracts the to_state from the from_state and compares against 2

#

Or...the other way around

#

That just checks for changes that are 2 degrees at once. You’d need a more complicated solution if you want to measure over time or pick some other reference

mighty ledge
#

That service is correct, but that's not what generates the position state for the cover.

spice crow
trail estuary
#

Good morning everyone!
I am using the github integration to monitor a few repos. Among the data, there is an attribute, latest_release_tag. Can I use some template to identify if there has come a new version? For example, the HA core repo has a latest_release_tag of 2021.3.4 at the moment. I'd like to trigger an automation if there is a newer version available.
I know that HA has an internal fuction for this, but I am using this with other repos. HA is just an example in this case.

magic pike
#

It's currently read out by tts.cloud_say as if it was text, but I would like to report the actual value 🤷🏼‍♂️

little gale
mighty ledge
mighty ledge
silent barnBOT
mighty ledge
#

second link

trail estuary
mighty ledge
mighty ledge
#

however, your trigger needs to be a state trigger.

magic pike
mighty ledge
#

@magic pike Ok so what do you want, the temperature or the state?

inner mesa
#

You can use the same concept. A state trigger can also take an attribute, and your condition template can compare the attributes

spice crow
mighty ledge
#

You have to adjust the template to extract the brightness as the position

#

basically you'll be inverting this equation

{{(float(position)*2.55)|int}}

but instead of using the position variable you'll be pulling the brightness from your light

spice crow
mighty ledge
#

well do you understand how to solve for position from a brightness value?

#

hint: this is 8th grade math, or at least it was taught to me in year 8.

#

y = x * 2.55, how do you invert this to have x = ?

#

getting the brightness requires you to use the state_attr method

spice crow
mighty ledge
#

well, you got the brightness correctly but the rest isn't needed. All you're trying to do is convert 0 - 255 brightness to 0 - 100 percentage.

#

y = x * 255 inverted is x = y / 255. Very simple math. Where x = percentage and y = brightness. So... if state_attr('light.gardin_kontor', 'brightness') gets your brightness and the equation is brighness / 255... then what would you have as a template?

#

are you there?

spice crow
#

yeah sorry

mighty ledge
#

so what do you think the template should be for just the equation?

#

state_attr('light.gardin_kontor', 'brightness') returns the brightness. And the equation is brightness / 255

spice crow
#

{{ brightness / 255 *100}} ?

mighty ledge
#

yep, but what goes in the place of the word brightness?

#

hint: You already figured that part out

spice crow
#

Sorry since English isn't my foreign language i have to think twice for everything you write, so my brain is working like an 56k modem atm, hang tight

#

do you mean something like this? {{ position/ 255 *100}}

mighty ledge
#

nope

#

how do you get the brightness?

spice crow
#

state_attr

mighty ledge
#

yep, so if the equation is brightness /255 * 100... what goes in the place of the word brightness?

spice crow
#

i am so stuck

mighty ledge
#

you've given the answer like 3 times but you aren't combining it

spice crow
#

no i get lost in your words

mighty ledge
#

just look at the equations ignore my words

spice crow
#

haha

mighty ledge
#
brightness / 255 * 100
#

state_attr('light.gardin_kontor', 'brightness') returns the brightness

#

combine them!

#

I'm not sure what you're doing to overthink this. Here's the answer

#
state_attr('light.gardin_kontor', 'brightness') / 255 * 100
#

see how simple that was?

spice crow
#

easy for you to say 🙄

mighty ledge
#

all said and done, your position_template would be:

  position_template: "{{ state_attr('light.gardin_kontor', 'brightness') / 255 * 100 }}"
spice crow
#

told you i were a newbie 🍴

mighty ledge
#

yes but I told you to replace the word brightness

#

I'm not sure how else that could have been conveyed

#

you had the equation. You had the way to get brightness, you just needed to combine "getting the brightness" and the "equation"

fossil venture
#

Is there a need to supply an integer for the position?

mighty ledge
#

i don't think so, floats and int's resolve to a number in the template resolution

spice crow
#

yeah well i know, but since i was lost in the words my brain was freezing, and i just started with this type of coding 3 days ago, so i don't really get the hang of it yet. But i really appreciate you time and effort trying to make my brain figure this out

#

you´r

#

ugh... as it turns out, my shutter dc tells different values everytime it goes to a up or down position, so if it's up it can sometime tell 255, and sometime 90, 150 etc.. so guess i am back at the beginning

proud crater
#

Hi guys, i need change value, when my binary sensor is ON set in template value 2050, when is off set nothing or zero.

`#Boiler Changer when is ON State to 2050 kWh

  • platform: template
    sensors:
    binary_sensor.boiler_state:
    friendly_name: "Boiler 2050 kWh"
    unit_of_measurement: "kWh"
    value_template: "{%if states.binary_sensor.boiler_state.state == 'on'}2050{% elif states.binary_sensor.boiler_state.state == 'off'}0{% endif %}"`
#

where is the problem in the code ? thx

inner mesa
#

You’re missing some %

#

You should also use is_state()

proud crater
#

I don't understand you, write me exactly how you think, thank you @inner mesa

inner mesa
#
#Boiler Changer when is ON State to 2050 kWh
  - platform: template
    sensors:
      binary_sensor.boiler_state:
        friendly_name: "Boiler 2050 kWh"
        unit_of_measurement: "kWh"
        value_template: "{%if states.binary_sensor.boiler_state.state == 'on'%}2050{% elif states.binary_sensor.boiler_state.state == 'off'%}0{% endif %}"
#

and, you should use is_state('binary_sensor.boiler_state', 'on'), for instance

#

you hadn't terminated your {% with %}

#

clear?

proud crater
#

no im go try this is_state('binary_sensor.boiler_state', 'on'),

inner mesa
#

understand the bit about %}?

proud crater
#

no

inner mesa
#

look at the difference between yours and mine

#

you have {%if states.binary_sensor.boiler_state.state == 'on'}

#

I have {%if states.binary_sensor.boiler_state.state == 'on'%}

cunning grotto
#

Hi, I am trying to get a template sensor to work. I have this code:

{{states.group.grocy|expand|selectattr('state', 'eq', '0')|list|count|int }}

It works great, and give the correct result when i test it in template editor, but when i try to validate the config, i get an error saying that there is no filter named expand

#

Can anyone see what I am doing wrong? Don't get why it is working fine in the template editor, but not when i try to validate the config

inner mesa
#

Would need to see the template sensor definition, but you replace that with expand(‘group.xxx’)

cunning grotto
#

Thanks RobC! Using expand() worked

formal ember
#

Got a template question 🙂

  timeout: "00:01:00"```

Will this turn something off if the binary sensor is inactive for one minute?
#

This is the sample from the documentation btw, just trying to figure out which parts I need to alter

mighty ledge
#

that just waits, it does not perform actions

formal ember
#

If the sensor is triggered again, will that reset it?

Trying to make a sensor light that will turn on, then after 2 minutes of no activity, will turn the light off

mighty ledge
#

use a wait_for_trigger with a default

formal ember
#

Ah yep, cheers 🙂

#
  - wait_for_trigger:
      - platform: state
        entity_id: binary_sensor.hallway_sensor_motion
        to: 'off'
        for: 120 ```
#

I’m guessing that would do it in my case, with a call service light.turn_off following it?

#

Hmm doesn’t seem to be

#

Ok - for: needs -minutes after it 😂

grim obsidian
#

Is something like this possible? Can I use a pipe as an OR statement?

  value_template: "{{ trigger.event.data.entity_id.startswith('switch.|light.') }}"```
inner mesa
#

not like that. This says you can provide a tuple:

#

Markup.startswith(prefix[, start[, end]]) → bool
Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

#

{{ "bar".startswith(("foo", "bar")) }} -> True

#

{{ "foo".startswith(("foo", "bar")) }} -> True

#

{{ "blah".startswith(("foo", "bar")) }} -> False

grim obsidian
#

Thank you!

grim obsidian
#

Am I doing something wrong in the first line here? I can't get it to work.

      value_template: >          
        {% set last_triggered = (expand(trigger.event.data.entity_id) | first).attributes.last_triggered %}       
        {{ (as_timestamp(now()) - as_timestamp(last_triggered)) | int > 1 }}  ```
#

If I hard code the entity id instead of trigger.event.data.entity_id, it works as I intend

inner mesa
#

I think expand() returns a list

#

Or a generator

#

Oh, you have |first

#

Do you see the entity_id in the event from devtools -> Events?

mighty ledge
#

or script

silent barnBOT
mighty ledge
#

thats going to fire on every state change

#

you'll get errors for evey item that doesn't have an automation.turn_on_<xxxx>

grim obsidian
#

Right. Could I use something like domain: switch in the trigger?

mighty ledge
#

just make an if statement to check if the automation exists

#
{% set automation = expand('automation.turn_on_' ~ triggered_by) | first %}
{% if automation %}
  ...
{% endif %}
grim obsidian
#

Good idea.

mighty ledge
#

what are you trying to do... this seems over complicated

grim obsidian
#

I'm sure it is. Basically what I want to accomplish is if a light/switch/any device is turned on/off by anything other than an automation (i.e physically, voice command, Lovelace), it will stop that device from being controlled automatically.

# and if it was turned on manually (not by an automation),
# it will override that device's automation and "lock" it in its' new state.```
mighty ledge
#

is this specifically for motion sensors? How are you going to enable the automation again?

#

also, there's a context attached to every state object. You can build a simple auotmation and check the context against an automation id or user id

grim obsidian
#

Depends on the automation, but generally I'm thinking of resetting all overrides once a day, e.g. when exiting sleep mode

mighty ledge
#

well, as someone who's been doing this for years, i'd suggest against all this as it ultimately doesn't work the way you might want

#

I personally moved to other actions to disable things, and only specific things

#

like double tap on a light switch, etc

#

and then double tap to start back up

grim obsidian
#

I appreciate the advice. I'm definitely considering the fact that I'm a bit too deep down the rabbit hole right now.

mighty ledge
#

at this point in time, I only have 3 automations with a 'cancel'

#

and that's automated door lighting when I open a door

#

light stays on for 2 minutes and shuts off. Sometimes I want to keep the light on. So double tap to cancel the turn off

#

thats what I mean by 'specific'

#

because the automation still runs, but you can just cancel that one specific event

grim obsidian
umbral zealot
#

If I have a question about how to configure a Zigbee Switch to i.e turn on and off a light, then it's in here, and not in Zigbee channel, right? 🙂

earnest cosmos
#

Hi, there! I have this template in a script, and there is no other option for an {% else %} clause. Will it still be valid. Is there other methods i would rather use to trigger the scipt only if binary_sensor.dark_inside is true/on?

#
  goodmorning:
    alias: God morgen
    sequence:
      - service: input_boolean.turn_off
        data:
          entity_id: input_boolean.in_bed
      - service: >
          {% if is_state('binary_sensor.dark_inside', 'on') %}
              script.lys_grunnbelysning_on
          {% endif %}
fossil venture
#

Use a state condition above the second service call.

earnest cosmos
#

If the state is false, the execution for the rest of the script is haltet, right?

fossil venture
#

Correct. So you may have to move it to the end of the sequence.

earnest cosmos
#

I sure do 🙂

#

BTW how is the state conditoin put in a script? I always struggle remembering this....

  • service: condition... ??
#

Found it 😉

fossil venture
#

Like this: ```

  • service: some.other_service
  • condition: state
    entity_id: binary_sensor.dark_inside
    state: 'on'
  • service: script.lys_grunnbelysning
earnest cosmos
#
      - condition: state
        entity_id: binary_sensor.dark_inside
        state: "on"
fossil venture
#

Yep 👍

earnest cosmos
#

Could it be single qoute too?

#

around the state?

fossil venture
#

Yes

earnest cosmos
#

Hmmm. had an error checking, and it passed when using double quote.

#

Nice to be certain I can use both

fossil venture
#

Should make no difference.

#

There's a style standard for documentation that calls for double quotes but that is a recommendation for documentation. Single quotes should still work.

earnest cosmos
#

I´ve ended up using single qoutes inside tamplates and for variables, but double outside the entire template

fossil venture
#

Yep, that's the style standard but the other way round does work.

mighty ledge
#

quotes are only needed for on/off because they translate to true/false with all the yaml interpreters. Outside that, you don't need quotes unless you're single line templating

hard pagoda
#

So here's something I'm wondering. I've built some venetian blind motors off of a NodeMCU that's working over MQTT. If I set it to positionCommand = 20, the blinds will be closed down, and if I set them to 0 they are closed up. 10 is open. Is there a way to set the covers in HA to when it's told to be open it sets to 10 by default and closed at 20, but allow some adjustments if I want to adjust them with the slats up if desired?

spice crow
#

Hey!
I am trying to make a template to change the attribute on lovelace UI, for now it shows my cat is "Gone" and "Home" but i wan't it to show "Ute" and "Inne"
But i can't really figure it out, this is what i have to get the attribute from the sensor..
How i try to change it back and forth it only shows "Ute"

#

{% if is_state_attr('binary_sensor.pet_doris', 'where', 'inside') %} Inne {% else %} Ute {% endif %}

#

nevermind... changed 'inside' to 'Inside' and wops it works 🙄

fossil venture
#

You can do it all on one line if you like: {{ Inne if is_state_attr('binary_sensor.pet_doris', 'where', 'Inside') else Ute }}

spice crow
#

oh, i see 🙂

#

Thank you

floral blaze
#

I have a question about rest and templates, is this the right room? 🙂

fossil venture
#

Yes

floral blaze
#

So i'm trying to retreive data from a JSON file but i keep staring blind on that little code. Everything seems to be working'ish, but the sensor wont pick data from the JSON attributes. I need a push in the right direction...

https://paste.ubuntu.com/p/9SYv7QQ5FN/

#

using this tool: https://jsonpathfinder.com/ to get the right path. My corona_dashboard does retreive information from the JSON, however it wont get put through to the sensor.

fossil venture
#

Remove x. X is your sensor.

#

Though I still don't think the path is correct. There's a values missing as well.

floral blaze
#

See and this. remains to be the question...its the wall that i keep running up to

#

I believe the path checks out, seeing as the JSON gets picked up by the tool and i derive all paths from that location

#

So at the moment this line underneath gives me the information in the 'corona dashboard'

json_attributes:
- vaccine_administered_planned

fossil venture
#

state_attr('sensor.corona_dashboard', 'vaccine_administered_planned').values[0].doses

#

Or maybe state_attr('sensor.corona_dashboard', 'values')[0].doses

#

That's for your first template sensor.

floral blaze
#

omw

#

One error:
can not read a block mapping entry; a multiline key may not be an implicit key at line 153, column 24:
friendly_name: "Vaccine Administered"
^

inner mesa
#

need to see the whole thing

floral blaze
inner mesa
#

your spacing is wrong and you need to mix your quotes

fossil venture
#

Double quotes outside the template.

inner mesa
#

you can see from teh color coding on the sharing site

fossil venture
#

Or value_template: "{{ 'running' if is_state('<your_sensor>', 1) else 'stopped' }}"

floral blaze
#

Ok, somethings changed now

Vaccines administred state_attr('sensor.corona_dashboard', 'values')[0].doses persons <-- this is at the suffix location now in the column

fossil venture
#

Have you checked the template in the developer tools template editor?

floral blaze
#

Well, if i load the code in there it says: UndefinedError: 'value_json' is undefined

#

but im affraid i get lost even further when i go there...just because thats the part that seems to be right

#

but i cant say that with full confidence

dreamy sinew
#

{% set value_json = {"your": "json", "payload": "here"} %}

floral blaze
#

where do i put that?

dreamy sinew
#

in the template tester

floral blaze
#

ok

fossil venture
#

You should not have value_json in the template you are testing. Test this one: ```
{{ state_attr('sensor.corona_dashboard', 'vaccine_administered_planned').values[0].doses }}

floral blaze
#

same output; This template does not listen for any events and will not update automatically.

fossil venture
#

And this one: ```
{{ state_attr('sensor.corona_dashboard', 'values')[0].doses }}

floral blaze
#

Look i really appriciate you guys helping out

#

Ok last one brings back this; UndefinedError: None has no element 0

fossil venture
#

Can you link to a screenshot of the sensor.corona_dashboard attributes in the developer tools states menu?

floral blaze
#

max 15 lines right? I could paste it here if thats allowed

#
vaccine_administered_planned: 
values:
  - doses: 514015
    date_start_unix: 1616976000
    date_end_unix: 1617494400
    date_of_insertion_unix: 1617062400
last_value:
  doses: 514015
  date_start_unix: 1616976000
  date_end_unix: 1617494400
  date_of_insertion_unix: 1617062400

friendly_name: corona dashboard
mortal sundial
#

Hi there, i want to create a binary template sensor for my media player to only show true if its playing and the content type is video.

- platform: template sensors: apple_tv_state: friendly_name: A movie is playing. value_template: {{ is_state('media_player.living_room_apple_tv', 'playing') and is_state((state_attr('media_player.living_room_apple_tv', 'media_content_type'), 'video')}}

inner mesa
#

you need to quote the template

#

not sure what's going on with this bit: is_state((state_attr('media_player.living_room_apple_tv', 'media_content_type'), 'video')

mortal sundial
#

that part is supposed to get the state of the "media_content_type"

inner mesa
#

seems like you wait is_state_attr

#

is that an entity?

mortal sundial
#

This is already working

  • platform: template
    sensors:
    apple_tv_state:
    friendly_name: A movie is playing.
    value_template: {{ is_state('media_player.living_room_apple_tv', 'playing')}}
inner mesa
#

a "state" is a technical term that describes the current state of an entity. not just a string comparison

#

you need to quote the template

#

value_template: "{{ is_state('media_player.living_room_apple_tv', 'playing')}}"

mortal sundial
#

Now i also want to include the media_conent_type

media_content_type: video
media_duration: 7108
media_position: 4712
media_position_updated_at: '2021-03-30T20:05:45.416502+00:00'
media_title: The Bourne Identity
app_id: com.netflix.Netflix
app_name: Netflix
friendly_name: Living Room Apple TV
entity_picture: >-
/api/media_player_proxy/media_player.living_room_apple_tv?token=d146e96ae4c7aa874ccb0fb30da17dec4804be82c528bf4e332c18f47dc7949e&cache=com.apple.avkit.207.d9ed8e7b
supported_features: 317363

inner mesa
#

like I said, you probably want is_state_attr to test the value of an attribute

mortal sundial
inner mesa
#

it will, but the YAML parser will probably choke on it

mortal sundial
#

ahh ok thx

#

I'll add them

#

the "playing" state is not an attribute if i got it right?

inner mesa
#

correct, it's the state

mortal sundial
#

ahh ok, that was a bit confusing

inner mesa
#

each entity has a state and (optionally) a set of attributes

mortal sundial
#

so this should work

` - platform: template
sensors:
apple_tv_state:
friendly_name: A movie is playing.
value_template: "{{ is_state('media_player.living_room_apple_tv', 'playing')
and is_state_attr('media_player.living_room_apple_tv', 'media_content_type', video) }}"

`

inner mesa
#

'video'

mortal sundial
#

meci

inner mesa
#

sorta. if you can fit it all on one line, then yes. Otherwise, you need to use a multi-line template like this:

#
  - platform: template
    sensors:
      apple_tv_state:
        friendly_name: A movie is playing. 
        value_template: >-
          {{ is_state('media_player.living_room_apple_tv', 'playing') and
              is_state_attr('media_player.living_room_apple_tv', 'media_content_type', 'video') }}
silent barnBOT
#

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

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

For over 15 lines you must use a code share site such as https://paste.ubuntu.com/ or https://www.hastebin.com/.

mighty ledge
#

FYI quoting works with multiline templates like he has it as well

inner mesa
#

just unnecessary

mighty ledge
#

it's just not readable

inner mesa
#

ah, yeah, that makes sense

#

right

mortal sundial
mighty ledge
#

don't worry about it 😉 Just go with @inner mesa's suggestion

#

It was just some info for him

#

for future support

mortal sundial
#

jeah i got that, it was more out of curiosity

#

thank you for the quick help!

mighty ledge
#

Basically there's 2 ways to use multiline templates. With quotes, on the first line and last line. Or with >, >-, |, |- and the template on the next line(s).

fickle quiver
#

I'm having an issue where i can't get a "History" graph to show a bar chart

#
  - platform: file
    name: "Speedtest Download"
    file_path: "external/speedtest.csv"
    value_template: >
      {{ ((value.split(',')[7]|replace('"','')|float)/125000) | round(2) }}
#

Here's one of the sensors. It reads from a csv file

#

in customize.yaml, I'm doing this:

#
  unit_of_measurement: Mbps
#

in entry customizations, I see the Mbps unit of measurement.

#

I only read this file daily - does it need to wait for the next reading to come in to switch over to a sensor with units?

fickle quiver
#

Maybe answered my own question - I created a new sensor like this one with units and it came in as a continuous measure. So, I'll just put the units in here and wait.

inner mesa
#

yes, you need to add unit_of_measurement to have it display a graph

#

and yes, if it still has some old data with it, or that's considerably different, it can confuse it and you need to either flush it out by pruning the database or just wait it out

#

or creating a new sensor, as you did

fickle quiver
#

Nice, thanks for the reply. How does one prune the database?

inner mesa
lethal dawn
#

Anyone got a way to pass color_xy into a template light, or how to get a color_xy out of of one? Looks like it only supports color_hsl but my light only supports color_xy 😦

eager veldt
#

How do I get a dict of a dict? So far I've got

{{ states.media_player.shield_tv.attributes.adb_response }}

Which outputs another dict. I'd like to add .wake_lock_size

lethal dawn
#

ok - I've found the formula to convert between them, but it's rather complex - is there a recommended way/integration that will allow me to add either a js or python function into jinja?

mighty ledge
lethal dawn
#

I'm actually trying to create a template light - but the light only supports xy_color and template light only supports rgb 😦

#

will look into helpers more to see if that will help me

#

the function I thought worked only seems to work for the set of test-data I used - more randomized values fail 😢

waxen rune
#

Sometimes a few of my sensors report a value that is obviously wrong - like after a restart before Z-wave is up to date.
I know there is a function that can handle that - but I can't find it. Tips?

fossil venture
#

It may be that your template sensors using |float or |int are evaluating to 0 when the referenced sensor is unavailable. Using a test in the template or an availability template can rectify this.

waxen rune
#

Ah! Not the solution I had in mind, but thanks! I'll begin with looking in to that.

mortal sundial
#

Is it possible to add an AND condition in a template that checks the history of a value for e.g. in the last 5min and defaults to true if the set state has been active?

mighty ledge
#

yea but you have to code it out. Much easier to just use a yaml and condition

eager veldt
silent barnBOT
formal ember
#

guru's, does this look right?

      friendly_name: "Family Status"
      value_template: >-
        {{ is_state('person.damien', 'home') 
           or is_state('person.olia', 'home') }}
         Home
        { else }
         Away
        { endif }```
#

for a sensor if family is home or away

inner mesa
#

No

formal ember
#

plz help

inner mesa
#

It looks pretty bad

#

{% %}

formal ember
#

remind me what the diff between { } {{ }} and {% %} is?

#

i knew it was gonna be bad 😄

inner mesa
#

You should review the templating docs

formal ember
#

yeah there wasn't an example of using an 'or' in there that I could see

fossil venture
#

Where is your if?

fossil venture
#

If/else/endif

inner mesa
#

‘Or’ is just ‘or’

formal ember
#
      friendly_name: "Family Status"
      value_template: >-
        {% if is_state('person.damien', 'home') 
           or is_state('person.olia', 'home') %}
         Home
        {% else %}
         Away
        {% endif %}```
#

I think this may actually work

#

coming back with a result type: string of

      friendly_name: "Family Status"
      value_template: >-
        
         Away```
inner mesa
#

Looks better

fossil venture
#

Convention would have the results (Home / Away) indented one more space. But that's just cosmetic.

formal ember
#

will slap it into the sensor.yaml with correct indentation (I hope)

#

thanks legends

fluid thorn
#

Hi, i cannot seem to figure out how to check if something is = to a number, as an example this doesnt work "{% if '{{ my_test_json.temperature }}' == 25 %}"

dreamy sinew
#

that line won't work on its own

#

oh, you're mixing things together

#

note in jinja {% %} are logic statements and {{ }} are output statements. You do not mix them together in the same line

#

{% if my_test_json.temperature == 25 %}

#

or {{ my_test_json.temperature == 25 }}

fluid thorn
#

Hang on, that might of worked. Thanks!

inner mesa
#

That’s the second case

#

Unless it’s part of a larger if/then/else block

fading bear
#

think i'm asking in the right place for this one, but essentially i've got a command line sensor which does a bit of logic on the curl return to set the value - i'd like to set some more sensors using the response that i'm getting back but it's not as simple as assigning a json value to an attribute, it's more like setting the attributes based on a few operations done on the json response. Can this be done? I'm basically trying to set multiple attributes without having to poll the endpoint multiple times.

mighty ledge
silent barnBOT
fading bear
#

alright, i'll look into that. There was a reason i didn't start with rest... can't remember what it is now though!

twin forge
#

Hi

Maybe this is something very obvious but I'm no programmer so forgive me my ignorance - I've tried googling and reading through the documentation but can't find any examples of the correct way to do this so I came here to ask.

The documentation says you should use {{ states('device_tracker.paulus') }} instead of {{ states.device_tracker.paulus.state }} but I can't find any way to get state.last_updated field using the states(... method. What's the correct way of doing this?

#

What I'd like to do is replace this:
value_template: "{{ ((as_timestamp(now()) - as_timestamp(states.sensor.outdoor_temperature.last_changed)) / 60) | round(0) }}"
with the suggested format.

#

states.sensor.outdoor_temperature.last_changed is the format to be avoided.

mighty ledge
#

but it'll have the same problem as states.sensor.outdoor_temperature.last_changed, so it doesn't matter which route you go if you need last_changed

twin forge
#

Thank you guys. I actually stumbled upon that post but apparently didn't read it properly. I'll keep it the way it is then.

balmy terrace
#

Can you guys help me with json_attributes_template? trying to extract "Power" "Voltage" and "Current" with their respective units ( W, V, A)
I'd like the attributes to be like:
Power 52 W
Voltage 123 V
Current 3 A
https://paste.ubuntu.com/p/73TrmsW2z2/

fossil venture
#

Unfortunately the mqtt integration does not have very powerful attribute gathering options. You can grab all the attributes under ENERGY or one.

balmy terrace
#

what is | tojson for in a template?

fossil venture
surreal dust
#

Does anyone know how to create custom helpers for jinja template?

#

I have to create a custom helper, exemple
{{ my_custom_helper() }}

But I don't want to use macro

dreamy sinew
#

macros are the only way to create functions in jinja

#

aside from a PR to core

arctic willow
#

Does anyone know where I can get some help setting up my spotify?

fossil venture
small hatch
#

anyone here an expert on using custom button card template

#

i got lot of these light entity if i can move some of the stuff into a template it would be great

inner mesa
#

I have a bunch of nested templates

#

no need to be an expert, just follow the instructions for the card

glossy viper
#

i have a warning message that annoys me and wnat to stop that. entity_id is deprecated and should be removed. i said ok..... i checked my sensors...i got some places where can be easy to remove like template example, but how to remove from statistics?

fossil venture
#

Do not remove it from the statistics sensors. That is a required option and is not generating the warnings. For the template sensor with the date sensor entity id you can either use the new triggered sensors option in the current beta release or add {% set update = states('sensor.date') %} to your template after removing the entity id. This does nothing to the rest of the template but as the date sensor is now in the template the template will be monitored for changes to the date sensor and the whole template will be updated when it changes.

waxen rune
#

If I remember correctly, last_changed isn't an attribute, it is a.. property? Which would be why state_attr("domain.entity", "last_changed") won't work, but states.domain.entity.last_changedwill.
According to https://www.home-assistant.io/docs/configuration/state_object/, it is strongly advised to use the states(), is_state(), state_attr() and is_state_attr() as much as possible, to avoid errors and error message when the entity isn’t ready yet (e.g., during Home Assistant startup).

Is there a better template for what I now use states.domain.entity.last_changed for?

deft timber
#

nop

waxen rune
#

Darn

fossil venture
#

That should not be causing issues though.

mighty ledge
glossy viper
#

tried your approach tom, but syntax error

mighty ledge
#

set goes inside value_template

#
        value_template: >
          {% set update = states('sensor.date') %}
          {{ states.automation | list | length }}
#

or

#
        value_template: "{% set update = states('sensor.date') %}{{ states.automation | list | length }}"
glossy viper
#

still i have to figure where is single bracket or double by myself to not trouble with silly questions

mighty ledge
#

just use multiline templates and you don't have to think about it

glossy viper
#

thank you

queen viper
#

Does cover.set_position not accept templates, or am I just being silly and messing up a simple thing? 🙂

queen viper
#

Sigh.. I was stoopid. Sorry..
position: >
{{ state_attr('cover.etage_rullgardin_hoger_fonster','current_position') }}

violet mauve
#

hi, I have some 2 code door sensors but I want to have an idea when the battery dies. There is no battery state advice with the sensors so it has been suggested by a friend in automations thhat a template could be used to monitor last activity. Can anyone suggest how this could be achieved please?

ivory delta
violet mauve
#

OK thanks I'll try this. Thanks

nocturne chasm
#

What is the correct way to use true/false in jinja templates? Is it true/false, True/False, TRUE/FALSE, TrUE/FaLsE?

dreamy sinew
#

True/False

#

though i don't think its super picky

#

the first three could work

#

but the 2nd will definitely work (python)

nocturne chasm
#

All lowercase has been working but with the beta attributes template warnings I am trying to make sure to eliminate things. Thanks

dreamy sinew
#

looks like all caps doesn't work

#

or is weird

nocturne chasm
#

And that is the error I am getting

dreamy sinew
#

super strange

nocturne chasm
#

Template variable warning: TRUE is undefined

dreamy sinew
#

ahh ok, trying to use it like a var then

nocturne chasm
#

But I have yet to find TRUE in my config

#

Until now 😉

tribal olive
#

Hi, I'm looking for some help in passing a float in order to assign a random color to an led bulb. The following is throwing an error saying that a float is expected in the hs_color values.

#

service: light.turn_on
data:
hs_color: ["{{ range(360)|random }}", 100]
transition: 1

fossil venture
#

Try this ```
service: light.turn_on
data:
hs_color: >
[{{ range(360)|random }}, 100]
transition: 1

tribal olive
#

Thanks @fossil venture , the error I now get is: Failed to call service light/turn_on. None for dictionary value @ data['hs_color']

#

Do I need to consider a sensor named random first?

fossil venture
#

How about: ```
hs_color: >
{% set h = range(360)|random %}
{{ [ h, 100 ] }}

tribal olive
#

Same error with that, Failed to call service light/turn_on. None for dictionary value @ data['hs_color']

#

Do I need to add this to the configuration.yaml for the random function to work?

sensor:

  • platform: random
fossil venture
#

No

#

It's a built in function of the template engine.

#

Try it in the template editor.

tribal olive
#

I'm trying this from the Dev Tools > Services tab in HA, which template editor should I go to?

fossil venture
#

Right next to services 🙂

tribal olive
#

😄

#

this is the output, service: light.turn_on
data:
hs_color: >

[184, 100]

transition: 1

#

looks like an extra line break is in there

inner mesa
tribal olive
#

data:
hs_color: >-

[202, 100]

transition: 1

inner mesa
#

try it for real

#

"-" removes whitespace

tribal olive
#

It worked!!

#

Thanks so much!

#

So does the Dev Tools > Services use a different "compiler" than the actual automation engine?

inner mesa
#

I believe that it's more YAML vs. Jinja. The template editor interprets Jinja, and the line continuation and whitespace chomping is a function of YAML

tribal olive
#

I see

fossil venture
#

But can dev tools services interpret jinja?

inner mesa
#

no

#

I wish

fossil venture
#

That would be the issue then. HomeAuto's original template should work irl.

inner mesa
#

oh, could be. I didn't review the history 🙂

#

it's a WTH thing as far as I'm concerned

fossil venture
#

Yeah he was testing it in services.

tribal olive
#

This is my first non-visual template, so I'm just getting started. I was running into other issues with the IRL template and decided to go to the DevTools to troubleshoot to save a few clicks with each test. Lesson learned 🙂

inner mesa
#

made more confusing by the fact that some integrations do accept templates in services, like persistent_notification

#

but I digress..

hexed wing
inner mesa
#

ooh, easter egg

neat pivot
#

Hi guys, can someone help me to build a template for an event_type triggered = true? I need something like that "If event.event_type.call_service (domain=cover, service=set_cover_position, service_data=entity_id=cover.my_room_cover) triggered then true

ivory delta
#

Is that going to be used as an automation trigger?

neat pivot
#

Yes i want to use it. At the moment it looks like this:
trigger:

  • platform: event
    event_type: call_service
    event_data:
    domain: cover
    service: set_cover_position
    service_data:
    entity_id: cover.my_room_cover
#

this works but my trigger should be if this call service is Not called with my_room_cover. Thats why i try templating

ivory delta
#

So first knock off the entity ID and you have a trigger that knows set_cover_position was called for some cover:

  trigger:
  - platform: event
    event_type: call_service
    event_data:
      domain: cover
      service: set_cover_position```
#

Then your condition will check which entity ID was inside the event. The template would be something like: {{ trigger.event.data.entity_id == 'some_id' }}

#

Tweak the logic in the template as needed but that's the general approach I'd suggest.

neat pivot
#

Wow thank you mono for that fast answer! sounds good to me, i will try that. And to say that it is not triggered with some ID {{ trigger.event.data.entity_id != 'some_id' }}?

ivory delta
#

Exactly

neat pivot
silent barnBOT
#

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

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

For over 15 lines you must use a code share site such as https://paste.ubuntu.com/ or https://www.hastebin.com/.

ivory delta
#

Like that ☝️

#

If you want the colours, you can also specify the language after the first backticks, then make sure to add a new line.

neat pivot
#

Thank you! The solution was:

{{ trigger.event.data.service_data.entity_id == 'cover.my_room_cover' }}
silent barnBOT
neat pivot
#

{{ trigger.event.data.service_data.entity_id == 'cover.my_room_cover' and is_state('switch.down_8','on') }} can't figure out the problem 🥲

fossil venture
silent barnBOT
ivory delta
#

Easy with the code walls 😉

silent barnBOT
#

@neat pivot Rule #6: Spam will not be tolerated, including but not limited to: self-promotion, flooding, text walls (longer than 15 lines) and unapproved bots.

Please take the time now to review all of the rules and references in #rules.

For sharing code or logs use https://paste.ubuntu.com/.

neat pivot
#

sry 😓 did you see my last ubuntu paste?

ivory delta
#

I saw. I don't know the answer, so I'll let someone else help 😄

fossil venture
idle gyro
#

Can somone tell me if I am missing something obvious here?!

data:
  master: >
    {{ states('input_text.sonos_group_master') }}
  entity_id: media_player.sonos_lounge

Results in the following:
Failed to call service sonos/join. Entity ID {{ states('input_text.sonos_group_master') }} is an invalid entity ID for dictionary value @ data['master']
In the template editor, {{ states('input_text.sonos_group_master') }} correctly shows a valid entity ID of another sonos media player.

ivory delta
#

Are you testing the service call in the Dev Tools?

#

@idle gyro ☝️

#

If so, templates don't work there

inner mesa
#

Until...2021.4 🎉

nocturne chasm
#

Lmao.....was that copy pasta Rob?

inner mesa
#

Nope, a celebratory response

inner mesa
#
service: homeassistant.turn_on
data:
  entity_id: {{ 'switch.fr_table_lamp' }}
inner mesa
#

I tried with and without

#

does it work for you?

mighty ledge
#

I can’t try it atm

#

On mobile

edgy fulcrum
#

i have a simple(ish) one time need. I just want a "days to go" counter to a big house move, so was thinking I could create a template sensor for that, but am having trouble getting it to surface in HA. It reports "Unavailable" on lovelace dash, but when tested in the devtools template section it reports back it's value correctly. Thoughts?
{{as_timestamp('2021-05-04T06:00:00+10:00') - as_timestamp(now()) }}

edgy fulcrum
#

actually, I figured part out - the problem is me not reloading the template sensor from config ! 😐

#

Now I can't get the sensor to pass config check

#

it passes in file editor, but not server controls

#
    sensors: 
     daystomove:
      value_template: {{(as_timestamp('2021-05-04T06:00:00+10:00'))-(as_timestamp(now()))}}
      friendly_name: 'Days until we move'

reports Error loading /config/configuration.yaml: invalid key: "OrderedDict([("(as_timestamp('2021-05-04T06:00:00+10:00'))-(as_timestamp(now()))", None)])" in "/config/configuration.yaml", line 82, column 0

#

hmm, broke it up and think I have it working now. All cool 🙂

rare panther
#

How can I retrieve all (with filter)the attributes of a entity? I meant something like this - {{state_attr('sensor.bus_stop1','%_tracked_%')}} Where there are bunch of attributes which has tracked in their attr name

frank gale
#

goodmorning from Germany! Following a template, first line returns True (not equal) but having the two logic check seperately seems to return the same string.
Please help me before I got mad!
{{(strptime(state_attr('calendar.feiertage_feiertage', 'start_time'), '%Y-%m-%d')) != (strptime((strptime(states('sensor.date'), '%Y-%m-%d') + timedelta(days=1)), '%Y-%m-%d'))}} {{ (strptime(state_attr('calendar.feiertage_feiertage', 'start_time'), '%Y-%m-%d')) }} {{ strptime(strptime(states('sensor.date'), '%Y-%m-%d') + timedelta(days=1), '%Y-%m-%d') }}

#

For test purposes It's the same with:
{{(strptime('2021-04-05 00:00:00', '%Y-%m-%d')) != (strptime((strptime(states('sensor.date'), '%Y-%m-%d') + timedelta(days=1)), '%Y-%m-%d'))}} {{(strptime('2021-04-05 00:00:00', '%Y-%m-%d')) }} {{strptime(strptime(states('sensor.date'), '%Y-%m-%d') + timedelta(days=1), '%Y-%m-%d') }}

frank gale
#

So I found what is wrong but don't know why. state_attr('calendar.feiertage_feiertage', 'start_time') returns: 2021-04-05 00:00:00 and sensor.date returns 2021-04-04 that doesn't contain time.
If I remove time from the first one everything works as it should. But if it has the time the check isn't any more false

#

so here's what is working for me:

#

{{(strptime(state_attr('calendar.feiertage_feiertage', 'start_time'), '%Y-%m-%d 00:00:00')) != (strptime((strptime(states('sensor.date'), '%Y-%m-%d') + timedelta(days=1)), '%Y-%m-%d'))}} {{ (strptime(state_attr('calendar.feiertage_feiertage', 'start_time'), '%Y-%m-%d')) }} {{ strptime(strptime(states('sensor.date'), '%Y-%m-%d') + timedelta(days=1), '%Y-%m-%d') }}

fossil venture
#

It will considerably simplify your template.

#

Either that or use now() instead of sensor.date_time

frank gale
frank gale
fossil venture
#

Yeah it can. Try this and see if it returns true/false {{ state_attr('calendar.feiertage_feiertage', 'start_time') == now() }} the only issue is that now() contains milliseconds and your calendar may not. Which is why {{ state_attr('calendar.feiertage_feiertage', 'start_time') == states('sensor.date_time') }} may be better.

frank gale
#

or is it a more efficient way to get only the date from calendar (skipping time) and check it if it is tomorrow?

#

I want simply now if it is a workday tomorrow according to my "holidays" calendar

#

(checking also my "vacation", "illness" calendars 😛 )

mighty ledge
#

Add 24 hours or 1 day to now using the timedelta and compare that to your start time

#

Only compare the date strings

frank gale
mighty ledge
#

Why

frank gale
#

it is a template for a binary_sensor in configuration.yaml

mighty ledge
#

Ok that changes nothing

frank gale
#

have you used now() in configuration.yaml?

mighty ledge
#

Yes you can use now anywhere in a value_template inside the sensor section

frank gale
#

I think i did it and failed... but i can be wrong.

mighty ledge
#

You are wrong... you did something else wrong and are correlating it to using now

frank gale
#

Ok thank you for the info!

mighty ledge
#

value_template: “{{ as_timestamp(now() + timedelta(days=1)) | timestamp_custom(....) in state_attr(‘entity_id’, ‘start_time’) }}”

#

You’ll have to replace .... with the format that’s in your start time for a date and change entity_id to your entity_id

#

On mobile so you may have to remove typos

#

For the format, %Y is year, %m is month and %d is day. So if the date in starttime is year-month-day, the format would be ‘%Y-%m-%d’

frank gale
#

I will try it! thank you very much for your time 🙂

#

how can I drop the time and check only the date? the time is irrelevant and could cause problems if it isn't always 00:00:00 according to your template

mighty ledge
#

The code checks if only the date is inside the timestamp so you dont have to drop it

frank gale
#

that's lovely!

#

thank you a lot!

#

now i saw the "in"

#

it checks if it is in the string

#

very clever!

#

yeah

#

last question is it wrong to use or for multiple state_attr after in?
value_template: “{{ as_timestamp(now() + timedelta(days=1)) | timestamp_custom(....) in (state_attr(‘entity_id’, ‘start_time’) or state_attr(‘entity_id2’, ‘start_time’) or state_attr(‘entity_id3’, ‘start_time’)) }}”

mighty ledge
#

Yes, it’s not correct. Set the date string to a variable and compare the variable in each starttime with ors between

frank gale
#

beautiful! thanks!

ruby crane
#

I have a template sensor set up that calculates the difference between two sensor values. These to values only have one decimal, but the template sensor more often than not outputs values with like ten decimals (like .9999999999999999999991 or .000000000000000000000000003). How is this possible?

ivory delta
#

Without seeing your template, you're just asking people to guess.

analog beacon
#

I'm getting a yaml error (parsing a block mapping) when trying to use a sensor template in config, and I really can't tell why:

sensor:
  - platform: template
    sensors:
       washer_door_lock:
#

Pretty sure I'm following the right syntax and spacing

ivory delta
#

Your snippet doesn't show a template... 🤔

analog beacon
#

the template's further down, and wasn't part of the error

ivory delta
#

The error will also likely tell you the position of the error. You need to give the full error message.

analog beacon
#

looks like it was maybe a badly pasted tab from someone else's snippet (which is weird considering i copied from their config file)

ivory delta
#

Quite likely. That message is saying your YAML is poorly formatted. But since you say it's nothing to do with the template, you want #integrations-archived

mighty ledge
#

You can’t mix tabs and spaces

analog beacon
#

It didn't look like i was. Atom was showing spaces for everything, and it was copied direct from another config file 🤷‍♂️

sleek rain
#

Hmm, template doesn't seem to like the entity from zigbee, for example {{ states.binary_sensor.0x00124b0022ff6569_contact.last_changed }} returns TemplateSyntaxError: expected token 'end of print statement', got 'x00124b0022ff6569_contact' - i could change the entity id but out of curiosity wondering why it fails, works otherwise fine as a sensor and stuff?

#

Testing on Developer tools template tab, as per regular workflow i ensure there first the stuff works before i put it into configs..

inner mesa
#

seems like you have something else in the template dev tool that's causing that

#

this works fine for me: {{ states.binary_sensor.aarlo_motion_back_door.last_changed }}

sleek rain
#

hmm, let me clean it up, it works fine for me on "regularly" named binary sensor, not with those zigbee address-named

inner mesa
#

did you exclude them from recorder:?

#

it works fine for a selection of entities here, but I have no Zigbee stuff

sleek rain
#

nope, no exclusions of any kind, they are visible on logbook just fine and i am trying to get their last_changed timestamp (which is properly shown on the states-tab

inner mesa
#

hmm, maybe that naming is broken. I think that object names need to start with a letter

#

that's what the error message is complaining about - the leading '0'

sleek rain
#

Now that i started to think it, sounds plausible, however that's the very default after a device is added to zigbee, it only have address as a name and it works for HA but suppose it causes issues to some subfunctions

inner mesa
#

try using states['binary_sensor.0x00124b0022ff6569_contact'].last_changed

mighty ledge
#

It’s the number

sleek rain
#

That seems to work, thanks. Timestamp is off by 3 hours, maybe by design (ie. gtm time) but that can be ignored for now.

mighty ledge
#

Using . Doesn’t work with numbers

#

Timestamp is utc

#

You have to convert to local

sleek rain
#

Yeah so it seems, no problem with that, thanks. I've got some issues renaming the z2m provided devices but that's not for template

mighty ledge
#

If manually configured add a unique_id

sleek rain
#

Added few door sensors to z2m, gave them friendly name (Frontdoor, Backdoor) in there but did not select the "Update Home Assistant entity ID" - results in devices named by friendly name (Frontdoor, Backdoor) from z2m but sensor names are crafted from ieee address . {{ state_attr('binary_sensor.0x00124b0022ff6569_contact', 'friendly_name') }} -> Backdoor contact

Thanks all for your assistance! Progress and learning, i'll move rest to the proper channel should i fail to fix the renaming

sage zodiac
#

I have a hopefully simple question for someone to answer, if I have a template like this that grabs the current value of a sensor how do I grab the value that it was previously set to? {{states.sensor.plant_sensor_5_moisture.state }}

ivory delta
#

You don't.

#

Templates represent current information. What's the use case?

sage zodiac
#

I have some humidity (moisture) sensors in my plants, i'm hoping to create a template to inform me of when the plants have been watered then take a timestamp. My thought was to compare the value of the previous state with the current to see if it increased. i.e the plant was at 10% humidity then jumped to 30% so it must have been watered, then save a timestamp.

inner mesa
#

this would typically be done through an integration that triggers on a state change, where you have access to the "from" and "to" states

#

what you're describing is an automation, not a template

#

an automation that uses a template, perhaps

sage zodiac
#

Hmm OK, i'm hoping to find some similar example as this is a new concept to me.

inner mesa
#

sounds like you'd want a trigger that triggers on any state change for your sensor, a condition that checks the from and to states to see if they meet your criteria, and an action that does something when they do

sage zodiac
#

Thanks @inner mesa, taking a look at this now.

formal stone
#

Hi everyone waveslight_smile Trying to create an automation that triggers when current hour on the clock matches an integration's sensor attribute that annoyingly only outputs numeric state between 00-23
Any ideas on ways to go about this? Thanks!
*Sorry for the double post, wasn't quite sure where best to ask 🙂