#templates-archived

1 messages · Page 90 of 1

sinful ridge
#

The value template is wrong though, it's not a template
@arctic sorrel I wasn't sure what to put here. I want the switch to toggle it between on and off but I assume that is done in the automation. I put 'off' there just as a starting state. Or am I just going about this wrong?

arctic sorrel
#

You can't change the state of a sensor 😉

#

If you want the switch to turn it on and off, you need an entity that turns on and off (such as the switch) in there

#

You could have the automation turn on and off an input_boolean and use the state of that in the tempalte

#
        value_template: '{{ states("input_boolean.garage_door") }}'
sinful ridge
#

Ah, OK! Taking a step back, am I going about this the right way or is there an easier way to track the status of a door where my only indication of it's status is a guess based on an initial state of closed and a switch that toggles it between open and clsoed?

#

its'? /grammarfail

buoyant pine
#

"its" is the possessive form 😛

sinful ridge
arctic sorrel
#

I'd put an actual sensor on the door though 😛

sinful ridge
#

Was thinking that too. An inexpensive Xaomi door sensor would do the trick.

#

Could have one for both positions to be 100%

#

I think I'll have too as usually the garage door is being activated by the remote, not my switch.

thorny snow
#

hi, anyone can help me templating some sensor values? I need to hook up 6 soil humidity sensors but the reading I have is ~6000 for 100% water emerged probe and 14000 with fully dry probe.
Now I need to template what i receive from the ESP and on HA convert it to 0-100% scale.
Can someone help me understant this formula?

  • platform: template
    sensors:
    humidity_plant1_percent_templated:
    unit_of_measurement: "%"
    value_template: "{{ (172.04819247 - states('sensor.growbox_analog_A0') | float * 0.240963855) | round(0) }}"

I have it runing before but with esp internal ADC now im trying to use ADS1115 with multiple devices

#

But I havent found yet how to create the maths for that conversion

arctic sorrel
#

So, you have a 20,000 point scale

#

At the simplest, add 6,000, then divide the total by 200. That'll give you 0 for wet, 100 for dry. Subtract it from 100 if you want it the other way around

silk owl
#

@arctic sorrel Thank you! I got it to display the correct friendly name using your instructions, but I am having an issue setting up the notify.your_notifier_here. I am having a very difficult time setting up the notify.notify. Do you know if it would be possible to setup the notification to send to something that would then allow me to see it in homekit?

arctic sorrel
#

Take your pick of options 🤷

#

I have zero HomeKit, so I've no idea about it

silk owl
#

Do you have an example of how to setup any of the notify.notify services? I haven't been able to figure that part out at all, and once I see how it is setup with any integration and then I can try to tinker with it to make it work for my use. I am so inept on the notify.notify that I had to use the persistant notification action just to confirm that the correct friendly name would appear for the alarm

arctic sorrel
#

Pick one that works for you, then somebody can help

silk owl
#

Thank you!

fallow quarry
#

can I ask for quick support ? trying to set loop in template ... goal is to show status of all switches:

#

{%- for i in [1,2,3,4,5,6,7] -%}
{{ states('switch.rainbird_zone_[i]') }},
{%- endfor %}.

#

haw to pass "i" to states function below

#

must be trivial 🙂

queen meteor
#
 {{ states('switch.rainbirdzone' + [i] |string) }},
fallow quarry
#

thanks @queen meteor but still not good ... simple {{ states('switch.rainbird_zone_1') }} shows off

#

but when put in the loop

#

{%- for i in [1,2,3,4,5,6,7] -%}
{{ states('switch.rainbird_zone_'+[i]|string) }},
{%- endfor %}.

#

i got unknown,unknown,unknown,unknown,unknown,unknown,unknown,

queen meteor
#

@fallow quarry that's because you are missing underscore

fallow quarry
#

sic .. _ is being removed by discord

#

nono

#

in my script I do hev them 🙂

#

only here discord removes for some reason .. I do no know how to past code 🙂

#

*have not *hev

silent barnBOT
#

@fallow quarry 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:

```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G

fallow quarry
#

OMG so simple .. .

#
 
{%- for i in [1,2,3,4,5,6,7] -%}
 {{ states('switch.rainbird_zone_' + [i] | string) }},
{%- endfor %}. ```  simple to paste it but still does not work 😦
silent barnBOT
thorny snow
#

But im not suposed to calculate the slope and constant to put on that formula?
Ive been trying with this formula

https://paste.ubuntu.com/p/P7ytXj99v3/

But when i test i get 160% with wet and 60% at dry.....

#

I have a strange feeling that im making a mistake in terms of maths

#

My guess is that somehow im making mistakes when calculating the slope because the dry gives me 60% as you can see at following excel

#

but strangely the deviation remains 60% on the upper and lower thresholds so maybe just a simple -60% could do the trick

thorny snow
#

Still with no more ideias how to make the 4500 100% wet and 14500 0%

buoyant pine
#

@thorny snow to return a number between 0% and 100% where 4500 is 100% and 14500 is 0%, do something like this:

{% set val = 14500 %}
{{ ((((val - 4500)/10000)-1)*100) | abs }}
thorny snow
#

@thorny snow to return a number between 0% and 100% where 4500 is 100% and 14500 is 0%, do something like this:

{% set val = 14500 %}
{{ ((((val - 4500)/10000)-1)*100) | abs }}

@buoyant pine
You mean in this field

- platform: template
    sensors:
      Humidity_plant_percent:
        unit_of_measurement: "%"
        value_template: "{{ (170.967718 - states('sensor.your_sensor') | float * 0.3225806) | round(0) }}"
#

Sorry bad templating

buoyant pine
#

better yet:

{% set val = 4500 %}
{{ ((((4500 - val) / 10000) + 1) * 100) }}
#

and yes, it would go in the value_template field

thorny snow
#

better yet:

{% set val = 4500 %}
{{ ((((4500 - val)/10000)+1) * 100) }}

@buoyant pine

Sorry could you explain me better the calculation? Need to understand it to apply it to HA

#

the term val is my sensor.your_sensor

#

?

buoyant pine
#

the difference between the highest and lowest values is 10000. to compare the values to a scale of 0 to 10000, you subtract the value from 4500. then you divide that value by 10000. you then add 1 to the value since the lowest value is supposed to be 100%. then you multiply by 100 to display it as 100%, 55%, etc.

thorny snow
#

Sorry im kind of newbie in this so making this "complicated" templates just go out of my knowledge

buoyant pine
#

this is more math than it is templating

thorny snow
#
- platform: template
    sensors:
      Humidity_plant_percent:
        unit_of_measurement: "%"
        value_template: "{% set val = 4500 %}
{{ ((((4500 - sensor.yoursensor)/10000)+1) * 100) }}"

I am right?

buoyant pine
#

you don't need the first line of my template if you're going to use sensor.yoursensor in the second line

#

the first line just defines a variable named val

thorny snow
#

well im going to copy this chat for future reference in case i make things crazy

buoyant pine
#

play around with that template i gave you at developer tools > template with different values for val and you'll see how it works

thorny snow
#
- platform: template
    sensors:
      Humidity_plant_percent:
        unit_of_measurement: "%"
        value_template: "{{ ((((4500 - >sensor.yoursensor)/10000)+1) * 100) }}"
#

Thank you very much for your kind help @buoyant pine

buoyant pine
#

you have two options:

value_template: >
  {% set val = states('sensor.yoursensor') | float %}
  {{ ((((4500 - val) / 10000) + 1) * 100) }}
#

or

#
value_template: "{{ ((((4500 - states('sensor.your_sensor') | float) / 10000) + 1) * 100) }}"
thorny snow
#

Could you explain the pros and cons of each? or same thing via different ways?

buoyant pine
#

same thing via different ways. defining one or more variables can be nice if you're referencing multiple entities in the template

#

it can also make the template itself shorter and cleaner

thorny snow
#

I will use multiple esp's for the maryjanes greenhouse eheheh.
I have one 2ch dimmer for 2 extractors.
This one will read 6 soil probes and 1 dht22

#

Watering system is another ESP8266 with mcp23017 for multiple water valves.

#

So this calculation is the key that will drive the self watering system.
(still have to add nut's by hand) but is supposed that in near future 5 peristaltic pumps will add nut's as per my request. The ideia is to be a hassle free grow

#

Maybe this will read also a VEML6070

#

you have two options:

value_template: >
  {% set val = states('sensor.yoursensor') | float %}
  {{ ((((4500 - val) / 10000) + 1) * 100) }}

@buoyant pine

Humm now im stoped by HA itself

nvalid config for [sensor.template]: invalid slug Sonda_de_humidade_com_conversao_templated#1 (try sonda_de_humidade_com_conversao_templated_1) for dictionary value @ data['sensors']. Got OrderedDict([('Sonda_de_humidade_com_conversao_templated#1', OrderedDict([('unit_of_measurement', '%'), ('value_template', "{{ ((((4500 - states('sensor.growbox_soil_probes_dth22_ads1115_48_a0') | float) / 10000) + 1) * 100) }}")]))]). (See ?, line ?). 

buoyant pine
#

Can only use lowercase letters, underscores, and numbers in the sensor name

#

It provides a suggestion in the error message

thorny snow
#

Do you want to see the code

stray raptor
#

So i have a guage card with a min/max value. Can i use a template to set a max value?

#

I've tried but can't seem to get the card to recognize the value that the template should return.

buoyant pine
#

@thorny snow read the first sentence in the error message, it tells you what to do

thorny snow
#

@thorny snow read the first sentence in the error message, it tells you what to do
@buoyant pine I removed the # signal but same trouble

#

maybe too long name?

stray raptor
#

I'd like to do something like:

    type: gauge
    entity: sensor.nextcloud_system_mem_free
    min: 0
    max: {{states('sensor.nextcloud_system_mem_total') | int}}
    unit: bytes
    name: Nextcloud Free Memory
buoyant pine
#

@thorny snow can't use capital letters either

thorny snow
#

@thorny snow can't use capital letters either
@buoyant pine This way im going to buy you dinner 🙂

#

Restarting the HA to see if the code will give the values I want

buoyant pine
#

You can (should) test templates at developer tools > template

#

That way you can check if they work before adding to a template sensor and restarting

stray raptor
#

nvm. i just realized that templating isn't supported on built-in lovelace cards :/

ebon yoke
#

is there a way i can figure out how long a sensor has been in its off state?

#

through a template?

#

i basically want to calculate a time delta for the time between whenever a sensor goes from on to on again

#

do i need a "variable template" just to store the previous time?

arctic sorrel
#

If you're using a state trigger, you can get it from the .last_changed value

#

Probably {{ trigger.from_state.last_changed }}

#

Never tried it though

ebon yoke
#

i have a binary sensor.. so i want the time interval between each time this sensor goes into the "on" state

#

trigger is the sensor?

arctic sorrel
#

You have read the templating docs?

silent barnBOT
ebon yoke
#
{{ (states.binary_sensor.float_switch_top.state) }}
#

that shows "off"

#

.from_state outputs nothing

arctic sorrel
#

Look at the first link I just shared

ebon yoke
#

yes, i see that.. but what is "trigger"? is that a hardcoded something?

arctic sorrel
#

The trigger data made is available during template rendering as the trigger variable.

#

Yes...

ebon yoke
#

so i can't access these variables through template editor?

arctic sorrel
#

No

#

You only get those in automations

ebon yoke
#

but, if this is a binary sensor.. that is either off or on.. whenever the sensor goes into "on", wouldn't then .from_state then refer to when the state was in "off"?

#

i'm looking for the time delta between each "on"

arctic sorrel
#

Right, and that's what you'll get

#

If you have the previous state object then the .last_changed value is when it turned off

#

Aka the end of the previous on time

ebon yoke
#

yes, but i'm looking for the start of the previous on time

arctic sorrel
#

That isn't what you'd initially asked

ebon yoke
#

off -> on (when?) -> off -> on (when?)

arctic sorrel
#

is there a way i can figure out how long a sensor has been in its off state?

#

Yes, but now you'll have to resort to other logic

ebon yoke
#

yeah, i asked because resorting to just using the off to on could potentially be good enough, since the sensor is in its on state for roughly the same time each time

#

i already have an automation that starts a pump whenever this binary sensor goes into on state.. would it make sense to add another action to this?

arctic sorrel
#

Sure, you could toggle a boolean, then you can track how long the boolean was on

ebon yoke
#

sigh this is giving me a headache 🙂

#

what i want to end up with is a simply sensor called "pump_interval" that is the number of seconds between each pump run

#

the pump starts every time the binary sensor binary_sensor.float_switch_top goes into the on state AND the binary_sensor.float_switch_bottom is in on state

#

and then the pump stops when the float_switch_bottom goes into off state

#

so i need to know the time delta between each on to see if the intervals are increasing or decreasing

#

how would you go about solving that?

arctic sorrel
#

Toggle a boolean

ebon yoke
#

but i need a sensor that is the number of seconds

#

because i want to graph the change in intervals

arctic sorrel
#

You know, how about I finish

#

Or, just leave you to it?

ebon yoke
#

ah, sorry..

arctic sorrel
#

Automation runs
Checks how many seconds the boolean has been in the current state
Stores that somewhere (input_number?)
Toggles it
Turns on the pump

#

Or some other thing, this ain't hard, and I'm done...

ebon yoke
#

why would you use input_number for this? the documentation says that this is for defining values that can be controlled via the frontend.. isn't it better to use a simple numeric sensor?

arctic sorrel
#

but i need a sensor that is the number of seconds

ebon yoke
#

input_number looks like it's meant to be used as input for automations.. and something that is intended to be changed by the user

arctic sorrel
#

Tell you what, since you want to argue, I'm out

ebon yoke
#

i'm trying to understand. i'm not here to argue.

inland hazel
#

You can set the value of an input_number, which might be what he’s suggesting you do. Every time the entity turns on, set the value of the input_number to the current time minus the last updated time of the input_number.

ebon yoke
#

@inland hazel the logic makes sense, but i don't understand why i should use an input_number for this instead of a sensor?

arctic sorrel
#

You can't update a sensor

ebon yoke
#

from what i'm reading input_number seems to be something that's to be used for "input".. meaning something that the user should manipulate directly through the frontend

arctic sorrel
#

You can update those any way you want

inland hazel
#

You cannot set the value of a sensor.

arctic sorrel
#

Not a single one of my input_x entities are updated by humans

inland hazel
#

In this case, you’re using “input number” as a variable.

#

(Research my historical configurations...I do it a lot)

ebon yoke
#

oh? but i'm able to update any sensor through developer-tools/state .. but this is not the same?

inland hazel
#

(And those were updated last around Nov 2017)

arctic sorrel
#

Not the same

inland hazel
#

No, it is not the same.

ebon yoke
#

ok, so h-a can't update the state of sensors through automations? developer-tools is kind of a backdoor into the states?

inland hazel
#

You can set the value of any entity via the REST API, but in this situation I do not recommend doing just that.

arctic sorrel
#

Or, look at it this way, look in devtools -> Services - find the service that updates the sensor 😉

inland hazel
#

Correct.

#

Hence the name developer tools.

arctic sorrel
#

Dev tools is basically allowing you to mess with HA's "memory" directly

#

You can tell it that reality is not what it though, for testing

ebon yoke
#

ah, ok.. thanks for the clarification 🙂

inland hazel
#

Sensors are intended to be read-only.

ebon yoke
#

then input_number makes more sense

#

but they need to be defined beforehand in configuration.yaml, right?

inland hazel
#

In this use case, input number is what makes most sense to me.

arctic sorrel
#

And yes they do, but you can reload that

ebon yoke
#

is there a list of the "valid" unit_of_measurement that can be used?

#

"seconds"? is that a valid unit_of_measurement?

arctic sorrel
#

So is banana

ebon yoke
#

hehe

inland hazel
#

The only other thing I would think to use is a SQL sensor, but that would entail a lot more than updating an input number each time it’s turned on.

arctic sorrel
#

You can use anything, it's used for graphing

ebon yoke
#

yeah, but it seems like some units triggers some special meaning.

arctic sorrel
#

Well, when linked with a device_class

inland hazel
#

Some units do, but that’s based on the front end.

ebon yoke
#

is there a list of those units somewhere?

arctic sorrel
#

Which units?

ebon yoke
#

those "Some units" that @inland hazel mentioned

inland hazel
#

unit_of_measurement @arctic sorrel

arctic sorrel
#

🤣

inland hazel
#

They are defined in the source code.

arctic sorrel
#

Other than for graphing, where it purely cares that it's set, I've never noticed the frontend care 🤷

inland hazel
#

@arctic sorrel you’re better at HassBot than I am, so I’ll leave this one to you.

arctic sorrel
#

Eh, I don't remember all the magic incantations

#

I did have a sensor on a test install that had bananas as the unit of measurement, graphed that just fine 😄

inland hazel
#

@arctic sorrel There are a few times where C/F come into play and get overridden.

arctic sorrel
#

Yeah, but I think that's the back end trying to be "smart"

ebon yoke
#

haha

#

the pump is operated using a neo coolcam power plug.. this already has an entity called "interval" :p

#

guess what that does.... :p

#

btw., what is the exporting entity for z-wave devices? what does that do?

arctic sorrel
thorny snow
#

Hi, I have made a template sensor to keep track of the sun hours per day, the sensor is switching status as it should, but when I try to use the history_stats component to list the ammount of hours I get into issues, it seems like the template sensor is not part of the history. How do I make sure it/they are added to the history? I have restarted HA a few times already.

this is the code for the sensor:

# Sun counter binary sensor
  - platform: template
    sensors:
      sunny:
        friendly_name: "Sunny"
        value_template: >-
          {{is_state('weather.lovkulla', 'sunny')
            and is_state('sun.sun', 'above_horizon')}}

This is the code for the history_stats:

# History stats for sun
  - platform: history_stats
    name: Sun last 48h
    entity_id: binary_sensor.sunny
    state: 'true'
    type: time
    end: '{{ now().replace(hour=0, minute=0, second=0) }}'
    duration:
      hours: 48
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:

```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G

arctic sorrel
#

Check and see if the entity is showing history in the more info popup

thorny snow
#

Ah, it says "this entity does not have any unique ID, therefore it can not be handles from the UI", or similar (translated by me), so how do I add that... need to search...

arctic sorrel
#

You can still use it - you still customize it, just not change the entity_id

thorny snow
#

You can still use it - you still customize it, just not change the entity_id
@arctic sorrel can you please explain, I have found it using the "states" panel under "developer tools", but I cant find the arrow to change the ID, I did find thou that it is not true/false it "on/off" as it seems...

arctic sorrel
#

There's an info next to it (docs are outdated)

#

But you can go configuration -> Customizations

thorny snow
#

Yeah, but that gives me the same error, "no ID, cant handle in the UI"

arctic sorrel
#

Doing what... I have zero issues changing the icon/device class/etc of any entity

thorny snow
#

Sorry for the links, I cant upload screenshots here it seems....

#

But I have solved it using the the correct states, it should have been "on" or "off" instead of "true" or "false"

sinful ridge
#

Looking at the docs for the cover template. In the beginning it states that the open_cover and close_cover are scripts that are run when the cover is opened/closed. Later on they give an example with a switch.garage_door and implies that the switch is controlling the garage (at least, that's how I understood it). So is open_cover or close_cover something that happens when the cover is moved or something that moves the cover?

arctic sorrel
#

Moves the cover

sinful ridge
#

Good, that makes more sense.

#

Am I crazy in how it was written early on makes it a bit confusing?

arctic sorrel
#

It's what happens when devs write stuff, and/or their native language isn't English

#

The wording is technically correct, if unhelpfully misleading

sinful ridge
#

I have enough trouble with English and it is my native language.

arctic sorrel
#

As a discussion I was having with somebody else today went - and which version of English do you mean 😉

#

Not just which country, but which part of it, 'cos when I'm full on local dialect my London colleagues can't work out a damn thing I'm saying 😄

sinful ridge
#

Yeah, I moved from the UK to the US when I was younger and had to learn "US" English 😉

#

I asked a classmate for a rubber, got a funny look 😄

arctic sorrel
#

I had a colleague I worked with for a while, and we wrote a Scots <> Canadian translation guide

sinful ridge
#

I'm in Germany now and most Germans have a near impossible time understanding Scottish (or Irish for that matter) acents.

#

Hell, I can't understand it half the time

arctic sorrel
#

Most Scots struggle with another Scot from any distance away 😉

#

It's ... an odd set of dialects and accents

sinful ridge
#

So, if I make a Github account can I suggest an edit to help my fellow noobs understand cover templates? Or how does the edit process normally work?

arctic sorrel
#

Pretty much

#

Top right of the page Edit this page and submit a PR with your proposed clarification

#

There's a template you get for the PR to help ensure you've followed the documentation standards, are using the right branch, etc etc

sinful ridge
#

...correct version of English.

buoyant pine
#

at least you didn't ask for a Handy

sinful ridge
#

First week in Germany we went to the supermarket and asked for 500g of "Kinderhackfleisch" 🤦‍♂️

#

Rinderhackfleisch = Ground beef. Kinderhackfleisch means ground children

arctic sorrel
#

Close...

buoyant pine
#

Well did you want ground beef or ground children?

sinful ridge
#

Well did you want ground beef or ground children?
@buoyant pine Ask me after the lockdown 😉

buoyant pine
#

😱

sinful ridge
#

OK, made my first PR.

thorny snow
#

I want to use a fan template to control my AC, is there any way to block controls of the fan device as long as the device is turned off?

midnight flare
#

Hi team. Can someone tell me why my code is throwing render error.

{% set date_now = strptime(now().strftime("%Y-%m-%d 00:00:00"),'%Y-%m-%d %H:%M:%S').timestamp() %}
{% set date_last = as_timestamp(state_attr('automation.notify_arrival_m','last_triggered')) %}
{{ date_now > date_last }}

#
 {% set date_now = strptime(now().strftime("%Y-%m-%d 00:00:00"),'%Y-%m-%d %H:%M:%S').timestamp() %}
 {% set date_last = as_timestamp(state_attr('automation.notify_arrival_m','last_triggered')) %}
{{ date_now > date_last }}
#

Got it I had the wrong automation name

rich yacht
#

Need a little help with this template. Not sure why its not working

{% for x in range(24) %}
{{ state_attr('sensor.axpert_power_output', x) }}
{% endfor %}

it loops through but returns None 24 times but if i put {{ state_attr('sensor.axpert_power_output', '17') }} it returns the correct value

#

ignore that. |string fixed it

rich yacht
#

My final goal was to sum all 24 attributes as a value_template for another sensor. For the life of me Im just not getting it right

dreamy sinew
#

probably hitting namespacing issues

#

test code for your reference:

{{ ns.sum }}
{%- for x in range(4) -%}
{%- set ns.sum = ns.sum + x -%}
{% endfor %}
{{ ns.sum }}```
rich yacht
#

that did the job!! thanks

dreamy sinew
#

where are you trying to use this template?

rich yacht
#

template sensor

dreamy sinew
#

ok, just as a heads up, it won't auto-update

rich yacht
#

it does update because the state changes too

#

Will monitor it to confirm

silent barnBOT
#

@serene merlin 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:

```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G

ebon yoke
#

would a binary sensor from template be set to on if the template returns "True"?

#

or, to ask another way, what is the correct way of setting a binary sensor to on/off based on other binary sensors?

#

i've used is_state('binary_sensor.something', 'on')

fast mason
#

Rinderhackfleisch = Ground beef. Kinderhackfleisch means ground children
@sinful ridge hahaha living in Austria myself and I can confirm knowing zero German I have had countless misunderstanding of the same kinder

ebon yoke
#

hehe

lunar osprey
#

Hello

#

How can I write a sensor that stores the last known values/attributes of another sensor?

#

This is my original sensor:

#
- platform: command_line
    name: Face Veranda 2
    json_attributes:
      - Faccia1
      - Faccia2...
    command: 'python C:\GoogleHome\Python\CameraFaceDetection.py Veranda2 rtsp://admin:xxxxxx@192.168.1.12:14000/tcp/av0_0'
    value_template: '{{ value_json.Stato }}'
    scan_interval: 10
    command_timeout: 120

silent barnBOT
#

@lunar osprey 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:

```
code here
```
Watch the animated gif here: https://bit.ly/2GbfRJE
DO NOT repeat posts. Please edit previously posted message, here is how -> https://bit.ly/2qOOf1G

arctic sorrel
#

Please format your code so that it's fully readable

#

@lunar osprey ☝️ Please edit your post and format your code

lunar osprey
#

done

rich yacht
#

Any idea why this doesnt trigger a template sensor? {{ states.person | selectattr('state','eq','home') | list | count > 0 }}

arctic sorrel
#

Because it has no reason to update

#

There is no entity in there that changes state

rich yacht
#

but if no person is home and then anyone arrives home surely it should trigger?

arctic sorrel
#

Nope

#

There's no entity in that template

rich yacht
#

does it have to reference a specific entity and not just the domain

arctic sorrel
#

Specify an entity that forces an update, or re-write the template to specify entities

#

Using, say, a group of the entities would force it to update on first arrival/last departure

rich yacht
#

I was hoping to get a dynamic list of entities so that I dont need to change it

arctic sorrel
#

Then templates would be processed every second

#

That would be a performance nightmare

#

Depending on your goal, the time_date option may work

rich yacht
#

ok back to the old manual way of adding entities i guess

arctic sorrel
#

Or that...

rich yacht
#

Depending on your goal, the time_date option may work
@arctic sorrel how now? I have the date sensor but how does that tie into the template?

arctic sorrel
#

Read what it says there 😉

#

If you have a sensor that updates every... minute, then the template will update every ... minute

rich yacht
#

so something like {{ states.person | selectattr('state','eq','home') | list | count > 0 or states('sensor.date') == '' }} as sensor.date will never = ''

arctic sorrel
#

No

#

Are you looking at the docs I've linked to?

rich yacht
#

i just figured it out lol

#

so pretty much

      entity_id: sensor.date
      value_template: "{{ states.person | selectattr('state','eq','home') | list | count > 0 }}"
arctic sorrel
#

Yup, except that sensor updates once a day 😉

rich yacht
#

oh fook

arctic sorrel
#

There's other options there 😉

rich yacht
#

i will use my sensor.uptime then. that updates every minute

#

I have my moments when i shine. this wasnt one of them

arctic sorrel
#

It's easy to get lost in the details

rich yacht
#

just a gradule glow

rich yacht
#

if an entity has many different states you cant specify say only 3 to listen for in a state trigger? you would have to use a template trigger right

arctic sorrel
#

Or a template condition and a state trigger

#

State triggers don't need to or from 😉

rich yacht
#

Im currently monitoring a weather entity but only want to action on 3 states. without to or from it will trigger on any change including attributes. was wondering if this would be the better way of doing it or just a template

arctic sorrel
#

Template trigger is an option, I'm just saying there's more than one way to solve it

rich yacht
#

Im sometimes pedantic on being efficient. prefer minimum code and load on server

#

template does seem the better way in this case

arctic sorrel
#

I suspect it's not very different in this case

#

It'd be interesting to run tests and find out though

tired lily
#

Is there a way to fallback to an empty string in case of an UndefinedError? jinja's default() didnt work for {{ trigger.to_state.attributes.friendly_name }} (looked like this, but didnt work: {{ trigger.to_state.attributes.friendly_name|default("") }})

dreamy sinew
#

Don't trigger manually?

tired lily
#

Yeah, but wanted to make sure it always works. Got it working btw:

{% if trigger %}
{{ trigger.blabla }}
{% endif %}
dreamy sinew
#

You can't use the trigger object of there is no trigger

thorny snow
#

Hello everybody. Is it possible to use the combination of the status from more than one entitiy to get a status on a card in lovelace? I got the hint to the template from the #frontend-archived channel. Does anyone have a card like this working?

arctic sorrel
#

You need a template sensor

#

Or the markdown card

#

(with a template)

thorny snow
#

I am already working through the template help site.

#

but i do not know anything about templates. so i thought if there's anyone who had this problem in the past.

arctic sorrel
#

Without knowing what you're wanting to do ... nobody can help you

thorny snow
#

i know what i want to do

#

but i dont how to 🙂

arctic sorrel
#

We don't know what you want to do

#

How can we help you if you don't tell us exactly what you want?

thorny snow
#

Hm. Sorry.

#

I installed a 4 channel relais in my network which is controlling our house ventilation. Status 0 to 3 for different ventilation strength. I got 4 switches in home assistant from the relais. For setting the ventilation on strength 2 for exmaple , the switches 1 has to be on, all other 3 off. For the ventilation strength 1, the switches 1 and 3 have to be on, 2 on and 4 off. So for each ventilation step there is an other combination ob witches on and off.

#

All i want to have in lovelace is a card with 4 Switches. Ventilation Step 0 to 3. Behing every step, there must be a combination of the sates of the 4 switches from the relais

arctic sorrel
#

Ok, that actually doesn't sounds like a status thing

thorny snow
#

Is this understandable? 😄

arctic sorrel
#

That sounds like some automations

#

You'd have an input select or input number to select the speed, and an automation to control the relays

#

You're not after displaying a status after all

thorny snow
#

my wish would be to see the status of the ventilation.

#

but it would be enough to see which lever is active

arctic sorrel
#

Do you have the relays in HA already?

rich yacht
#

I would think 4 binary template sensors reading the states of your relays would be fine. then on the frontend add 4 buttons with the binary sensor as the entities

arctic sorrel
#

Yup

#

Though, automations to manage it seems like the actual goal

thorny snow
#

Yes, i have switch.sonoff_10009f091d_1 to switch.sonoff_10009f091d_4

arctic sorrel
#

An input select for off through full speed, automation to toggle things, and then a glance card to display the state

thorny snow
#

Okay, i'll have a look into binary template sensors. Uff

arctic sorrel
#

Depends on what you really want

#

A display showing the mode (template sensor)
A control (see above)
A display showing the state of each switch (just cards)

thorny snow
#

I already have the last one (A display showing the state of each switch (just cards)) but thats only the switch position of the relais, not the "resulting heating level"

rich yacht
#

is each level a combination of 2 relays?

arctic sorrel
#

Then you want a single template sensor

#

It's basically a set of if statements

#
{% if is_state('switch.sonoff_10009f091d_1','on') and is_state('switch.sonoff_10009f091d_2','on') and ... %}
  Full power!
{% elif is_state('switch.sonoff_10009f091d_1'...
thorny snow
#

Okay, let me see what i can make 🙂

#

when i create atemplate sensor, can i create card to get the status from it?

#

Ah got it.

arctic sorrel
#

Cards display entities...

#

So, yes

thorny snow
#

wasnt sure if it creates a entitiy, sorry.

#

reastared and whup, it's there

arctic sorrel
#

Pretty much everything is an entity - if it isn't it's a service

thorny snow
#

Got it working. Thank you very much guys

rich yacht
#

only thing i would change is {% to {%- to remove line break in case you use the value in a notification

violet oyster
#

hey does anybody know how to add an offset to

{{ now() }}

so that it will always return 5 hours earlier than the actual time?

bleak river
#

probably something like {{ now() - now().timedelta(hours=5) }}

#

not sure it will let you do the - operation, but if it does, that should do it

#

or you might try the timedelta on it's own

violet oyster
#

it is saying 'datetime.datetime object' has no attribute 'timedelta'

bleak river
#

Well, now is supposed to be a datetime object for python, and pythin 3 has a timedelta on it's datetime object, so maybe it's an old integration

#

you can look for how to do it on a python timedate object it should give you the answer

violet oyster
#

ok thanks

bleak river
violet oyster
#

i just realized this works

{{ (as_timestamp(now()) - (5*3600)) }}
#

i can just convert my sensor over to using timestamps instead of formatted time

#

nah that won't work either. damn i may give up on this. starting to think what i want to do is not possible the way I'm trying to do it

bleak river
#

you can always turn that timestamp into a real number

violet oyster
#

i realized i was going about it all wrong in the first place

bleak river
#

also, it's easier to just use : now().timestamp()

violet oyster
#

im trying to make a tracker that tells me how much time i'm spending on my computer and i was trying to use history_stats. but that integration relies on relative time only so i can't make one that can track for one day but start/stop at 5am instead of midnight.

#

(without changing my timezone)

#

so i'm just gonna use an input number and a series of automations and sensors

bleak river
#

Ah, yeah, that sounds complicated... Good luck tho

violet oyster
#

haha a lot of effort for basically no benefit at all. story of my HA life

bleak river
#

We all do that at times, it's part of the fun, I spent like two hours today making an automation for my bedroom lights on HA that i've had working on the HUE bridge for months

violet oyster
#

oh yeah ive spent days redoing stuff that was already working lol

dreamy sinew
#

do what now?

violet oyster
#

lol fr

#

tf he deleted it?

winged dirge
#

It was written poorly

#

I figured out the required string manipulation and got the desired output

violet oyster
#

in the future, share the whole thing if you need help

thorny snow
#

Hi, any idea why this code seems to work when checking in template tool but not when I add it in the config and reboot?

# Sun counter binary sensor
  - platform: template
    sensors:
      sunny:
        friendly_name: "Sunny"
        value_template: >-
          {{is_state('weather.lovkulla','sunny')
            or is_state('weather.lovkulla','partlycloudy')
            and is_state('sun.sun', 'above_horizon')}}
arctic sorrel
#

Did you run a config check?

thorny snow
#

Yes

#

No issues

#

It works it just gives me a "false" result, while in the template tool it gives me a "true"

#

I guess the logic could be questioned, I want the first "or" part to run first and then check for the "and" state, maybe that is not correct way to formulate my code

arctic sorrel
#

Priority ordering may be the problem, maybe you need some brackets so that it's clear what you mean

thorny snow
#

Like this?

# Sun counter binary sensor
  - platform: template
    sensors:
      sunny:
        friendly_name: "Sunny"
        value_template: >-
          {{(is_state('weather.lovkulla','sunny')
            or is_state('weather.lovkulla','partlycloudy'))
            and is_state('sun.sun', 'above_horizon')}}
#

Would epic if that would be that simple...

arctic sorrel
#

If that's what you're looking for, yes 🤞

thorny snow
#

But still weird that it shows one result in the template tool and a different one when integrated into configuration.yaml

arctic sorrel
#

It is...

thorny snow
#

Well that code above now gives me a "false" in template tool, lol, but that is change so one step forward I guess...

dreamy sinew
#

simplify in your testing. {{ True or (True and False) }}

mighty ledge
#

that's True

rich yacht
#

is from_state available in a template sensor or only in automation

dreamy sinew
#

Automation only

gusty radish
#

I want to buy a sonoff mini for behind my wall switch. I already have smart lights everywhere. Is there a possibility to create a light template so when i turn on a light, the sonoff mini goes on and i can change the light brightness etc?

#

With the sonoff the power is switched so otherwise i can't turn on my light

silent barnBOT
rich yacht
#

How does one get rid of the milli/micro seconds from a timedelta object?

rich yacht
#

How does one get rid of the milli/micro seconds from a timedelta object?
Figured it out. Need to do .replace(microsecond=0) on both datetime objects before the calculation

ornate pecan
#

i'm doing this way and it's not working

- Invalid config for [media_player.universal]: value should be a string for dictionary value @ data['attributes']['source_list']. Got ['INPUT 1', 'INPUT 2', 'INPUT 3', 'INPUT 4', 'INPUT 5', 'INPUT 6', 'INPUT 7', 'INPUT 8', 'INPUT 9', 'INPUT 0']. (See ?, line ?).
buoyant pine
#

@ornate pecan it has to be an entity ID and its attribute separated by a pipe (|)

#

From the example:

source_list: media_player.receiver|source_list
ornate pecan
#

@buoyant pine the thing is this is a manual media player and I want to provide custom source list that does not exist in other place

#

but i already managed to do it via input_select|options

buoyant pine
#

Right, I was just explaining the syntax that the docs state

cinder tulip
#

I've read a lot that starting with 0.108.x there's a {{ user }} for templating which holds the current users name. I'm on 0.108.9 and the variable is empty for me. Does anyone know how I can access the name of the current user?

arctic sorrel
#

That's for the Markdown card only

cinder tulip
#

oooh, thanks for the clarification

arctic sorrel
#

No worries

nova nimbus
#

Getting more into using templates and I am looking to get the previous state of an input select... I have looked into this and found 3 ways this is commonly approached. 1) Templates getting the from_state of a template sensor; 2) HACS Variable to store a value as a history and recall the variable; 3) Appdaemon. I would love some input on achieving the ability to have a pop-up on an input select, “yes” completes the action and “no” returns the input to the previous value. If anyone has any input on how to best go about this and perhaps some example code of an automation calling the from_state of an input select or sensor. Or is this something another plug in does natively?

arctic sorrel
#

In an automation, you can do that with {{ trigger.from_state... }}

nova nimbus
#

This will work with the input select directly or still need the template sensor to record the history?

silent barnBOT
arctic sorrel
#

It works with any entity - see the first link

nova nimbus
#

So perhaps I am missing something in that document as I have read it and several others from HA. I can’t seem to find an example of exactly what we are trying to do. Below is some of my code from the automation but for the life of me I’m not wrapping my head around the format or one of the keywords.

action:

  • data_template:
    option: "{{ trigger.from_state.state }}"
    entity_id: input_select.tv
    service: input_select.select_option
arctic sorrel
#

Ok, so that selects the previous state when run in an automation

nova nimbus
#

Gotcha! And this automation can be triggered by the “no” button. It does not have to have a trigger?

arctic sorrel
#

It needs to have a trigger - the entity in question changing

#

Otherwise, there's no state object for it to work with

nova nimbus
#

Gotcha! That may have been my issue then and not the template! Thanks for the input!

velvet glen
#

AAAARGGGHH! Trying to round a simple number - please someone put me out my misery! What stupid thing am I doing?? This works fine in the template editor, but does nothing in the sensor card configuration

near rune
#

I need some help with my templates. I want to create a for loop that find all my calendar.rolfberkenbosch items. If i look into the Dev Tools -> States. I see only 1 event. But when I search in the SQL lite database of home assistant I find more (sqlite> select * from states where entity_id LIKE 'calendar.rolfberkenbosch';). Can anybody help me with this ?

velvet glen
#

Just returns: Expected a value of type undefined for value_template but received {"[object Object]":null}.

arctic sorrel
#

The sensor card doesn't support templates 🤔

weary jasper
#

surrond in ""

#

oh i dont know about a card LOL

arctic sorrel
#

You're right though, for templates you need that, but the card docs shows nothing about templates 🤷

weary jasper
#

yea i dont do fancy ui stuff

jagged obsidian
#

template sensor then display that one instead?

weary jasper
#

^^^^^

silent barnBOT
#

@velvet glen Your message has been deleted as it contains a link or a domain name 'pasteboard_dot_co' that is on the blocked list because of: 'Virus detected!'.
Please re-post by removing/changing the domain name/link. Your original message has been DM'ed to you.

velvet glen
#

Ok so to have a sensor card with a rounded number (ie not displaying 20.6253745648563475475455C ), then best route is to just recreate the whole card as a custom card and this'll let me round it? (I thought templates could be applied to all cards, but obviously not!)

buoyant pine
#

@velvet glen they're saying make a template sensor

silent barnBOT
stark palm
#

has anyone set up homeassistant supervisor on unraid?

verbal bramble
#

Can i access the area of a sensor from a template?

dreamy sinew
#

@verbal bramble I haven't tried that. Might be able to dig around in the state object to see what's available

arctic sorrel
#

The last time I poked, it looked like areas contain entities, rather than entities being linked to areas

verbal bramble
#

The last time I poked, it looked like areas contain entities, rather than entities being linked to areas
@arctic sorrel is there a way to access areas from a template and figure it out?

arctic sorrel
#

Probably

shell lynx
#

I'm making changes to my sensors.yaml file and trying to test. Should I be reloading core? or do i have to restart hass (from file editor) for changes to take affect.

rugged laurel
#

restart "hass"

silent barnBOT
#

Always run the configuration check command when you make changes. Don't trust the UI check - it misses some problems.

shell lynx
#

great, thanks

verbal bramble
#

Probably
@arctic sorrel any hints? I have all my sensors sorted by area and it seems redudant to have to put the area name also in the device name just to access its location in a template

arctic sorrel
#

If I had anything detailed I'd have shared it - I'm afraid I've had zero interest myself so don't know

verbal bramble
#

No prob. I'd be suprised if this couldn't be done as it seems like an obvious use case

rich yacht
#

Anyone know of a way to filter out entity_ids from a domain that start with a given string? For instance all lights that match light.room__%

buoyant pine
#
{% for state in states.light if 'room_' in state.entity_id %}
{{ state.entity_id }}
{% endfor %}
#

better yet:

{% for state in states.light if state.object_id.startswith('room_') %}
{{ state.entity_id }}
{% endfor %}
rich yacht
#

That seems to do the job. Is there no way to apply some type of filter instead of looping through each item?

dreamy sinew
#

there's a |reject() filter but its just doing a loop in the backend

rich yacht
#

reject() doesnt seem to have a test that can match with wildcards or a startswith

dreamy sinew
#

reject("in", "thing")

rich yacht
#

its the wildcard thats the problem.
I tried selectattr('object_id','in','room*') but didnt work

dreamy sinew
#

remove the *

#

its extraneous

rich yacht
#

without the * it only returns the light if the object_id = 'room' and not any object_id that starts with room

#

with the * it returns nothing 😩

dreamy sinew
#

looks like it won't work that way as you need to be a level deeper in the lookup

#

because this works:

{{ l1|reject("in", "1-thing")|list }}```
#

['2-other-thing', '3-foo']

#

so need to be in a loop

rich yacht
#

a loop will have to do then. Thanks

lament salmon
#

i wanted to get the "state" value from the sensor.latest_vesion but im not being able to get just the state. i tried many templates such as {{state_attr('sensor.latest_version', 'state')}} but i am not being able to get the value

#

any clue?

dreamy sinew
#

states('sensor.latest_version') should be enough

lament salmon
#

@dreamy sinew i tried that,but it doesn't return the state value

#

i am testing it in the templates section

#

okay, scratch that

#

my bad

dreamy sinew
#

Go to the states page and look at the attributes

lament salmon
#

works now, thanks

#

i had a typo

nova nimbus
#

I am trying to have an automation reference the last state that an input select is in... I had this working on it's own, but adding complexity seems to have broken the chain... Anyone have any ideas on why the trigger.from_last.state would not work properly under these circumstances?

- alias: Previous State Recall
  description: ''
  trigger:
  - entity_id: input_boolean.popup_no_display_boolean
    platform: state
    to: 'on'
  condition: []
  action:
  - data_template:
      option: '{{ trigger.from_state.state }}'
    entity_id: input_select.display_1
    service: input_select.select_option
  - delay: 00:00:03
  - data: {}
    entity_id: input_boolean.popup_no_display_boolean
    service: input_boolean.turn_off
dreamy sinew
#

Because the trigger is the toggling of the input Boolean

nova nimbus
#

The automation cannot be triggered by the input boolean being turned on and then reset it to off?

dreamy sinew
#

It will trigger by that toggle but the trigger entity will be that bool not the select

nova nimbus
#

Sorry if we are misunderstanding... I am trying to trigger the last state of an input select when another automation chanes the input boolean to "on".

humble beacon
#

Is there a way to work here without the group and specify some entities?
{% set open_windows = states | selectattr('entity_id','in', state_attr('group.fenster_alle','entity_id')) | selectattr('state','eq','on') | map(attribute='name') | list %}

dreamy sinew
#

That is not possible here as you are not triggering an automation based on that change

silent barnBOT
dreamy sinew
#

Share the whole thing

humble beacon
dreamy sinew
#

Ok, what are you trying to do?

humble beacon
#

I want to remove the group and specify entities.

dreamy sinew
#

And do you still want the open check?

humble beacon
#

Yes

dreamy sinew
#

It's possible but the group would be a bit easier

humble beacon
#

Can you tell me how?

dreamy sinew
#

I'm on mobile, kindof a pain to work out

nova nimbus
#

Thought that pulling together the code would help explain my situation. It is a complex scenario for me personally and all of my steps are pulled from HA resources and forum posts. Not sure if this is the best way to go about it. Suggestions welcome. (will send beer) 🍻
https://hastebin.com/wahusatogi.http

upbeat iron
#

So I have a odd dimmer that supports MQTT but it only will post a single value of 1 through 127 for britness I made a template that i can turn it on and off but how would i add dimmin support

#

there is no seperate britness value

arctic sorrel
#

Which of the three schemas?

upbeat iron
#

I tryed britness however the format the dimmer outputs is just a value of say 0 of off or 127 for full brite so the mqtt value is (topic)=127 no other values

#

I made the template i got now but its eather full on or off and the dimmer slider wont adjust the value at all

arctic sorrel
#

~images @upbeat iron

silent barnBOT
#

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

arctic sorrel
#

Show us what you've done

upbeat iron
#

ok

arctic sorrel
#

You can "simply" apply some maths to the value to adjust it to cover 0 to 255

arctic sorrel
#

your topics 🤔

upbeat iron
#

think thats what you wanted

#

this is my first attempt at doing one like this

arctic sorrel
#

your actual config would have been handy, rather than something made up 😉

upbeat iron
#

I used auto discovery for the others

arctic sorrel
#

If that is your actual config, it's very wrong

upbeat iron
#

oh my full yamal?

arctic sorrel
#

No

#

The actual config for that light

#

Because your topics is clearly not valid

upbeat iron
#

is the config page for the dimmer

#

I changed the topic tho

#

to rec\devicename

arctic sorrel
#

So, show us the actual light config

upbeat iron
#

I must be confused m8t im sorry

arctic sorrel
#
    state_topic: "your topics"
#

That is not valid

upbeat iron
#

oh

arctic sorrel
#

Not even in the same continent as valid

upbeat iron
#

one sec

upbeat iron
#

The device only understands a value of 0-127 the other info is completly innored from what the dev told me

arctic sorrel
#

So... brightness scale 😉

#

And you can use the state value to have 0 being off and not zero being on

upbeat iron
#

is basicaly what i was trying to use last time i attempted this

#

It turns on and off fine and if i manualy push a command to change the = to a valuse of say 50 it dimms

arctic sorrel
#

Those topics are still wrong 😉

#
    state_topic: "REC/HA-Utility-Room-Switch"
``` is more likely to be right
upbeat iron
#

I dont realy understand MQTT yet im super new to this

arctic sorrel
#

I'm also not sure what

#
    brightness_state_topic: "/REC/HA-Utility-Room-Switch/brightness"
    brightness_command_topic: "/REC/HA-Utility-Room-Switch/brightness2"
```is doing for you
#

Given that you said it doesn't have those 🤷

upbeat iron
#

it dont do anything rn i think

arctic sorrel
#

The state and command topic will be the main topic, and you'll need the scale I linked to

upbeat iron
#

I was told i should use it by some on on a nother discord but what it does is nuthing i can tell

arctic sorrel
#

Of course, anything other than 127 is neither on nor off, so ... not sure how that's gonna work

#

You may want to junk it and get something that's vaguely standard 😛

upbeat iron
#

I tryed setting the britness to the same topic as the on off value but the slider goes gray

#

and only reflect the current on or off value and i cant slide it to adjust it

#

if i manualy change it it does move tho

#

its like somthing in HA dont like having the same topic for on off and britness

#

< is so overwelmed lol

#

I ended up removeing it thats why the topics went set in the first post

#

Im adding the other devices first then going to restab it when im done getting all the autodiscovery stuff working

#

I get overwelmed easly (part of my mental state) so i step back and take nibbles at it

inner gulch
#

Im tryging to decode a json respons from a automation trigger.event.data

but when im trying this i get an error:

'{{ trigger.event.data | value_json.args[0].degrees }}'

#

when just using trigger.event.data i get the full json respons

charred dagger
#

In jinja templates | is a pipe. So you're trying to run the results of trigger.event.data through the function value_json.args[0].degrees - which doesn't exist.

#

That's why it fails. It's trying to find a function with that name, but function names can't contain [, thus the syntax error.

inner gulch
#

oh

#

so how do i parse it then with jinja

charred dagger
#

I don't know what the data looks like, but maybe trigger.event.data.args[0].degrees?

inner gulch
#

will try

#

nice 😄

#

thx Thomas

rich yacht
#

Hey all. So heres an interesting thing. In template editor this works 100% but when I put it into a template sensor it give me an error
{{ states.group.tracked_things|expand|selectattr('state','eq','home')|list|count }}

#

Error as follows:
Invalid config for [sensor.template]: invalid template (TemplateAssertionError: no filter named 'expand') for dictionary value @ data['sensors']['tracked_things']['value_template']. Got "{{ states.group.tracked_things|expand|selectattr('state','eq','home')|list|count }}". (See ?, line ?)

dreamy sinew
#

what's the error

arctic sorrel
#

What's the full sensor too...

rich yacht
#

value_template: "{{ states.group.tracked_things|expand|selectattr('state','eq','home')|list|count }}"

arctic sorrel
#

That sensor will almost never update

rich yacht
#

I initially tried to have a sensor from person.xxx but HA had an issue with that

arctic sorrel
#

Your sensor will update when group.tracked_things changes state

rich yacht
#

Other than it not updating it just doesnt work

charred dagger
#

That can be fixed in other ways. The problem is that expand isn't a thing.

#

For some reason.

arctic sorrel
#
        {{ dict((states|selectattr('entity_id', 'in', state_attr('group.tracked_things', 'entity_id'))|list)|groupby('state'))['on']|length }} 
``` is from one of mine
#

(quickly hacked, brackets may be off)

rich yacht
#

I dont need the sensor actually. I just wanted the count for the frontend to change the icon but HA didnt like that hence me making the sensor

#

I wanted this icon_template: "mdi:numeric-{{ states('sensor.tracked_things') }}-box-outline"

arctic sorrel
#
    value_template: "{{ dict((states|selectattr('entity_id', 'in', state_attr('group.tracked_things', 'entity_id'))|list)|groupby('state'))['home']|count }}"
``` should give you something similar
#

The problem still is that it won't update until the state of the group changes

rich yacht
#

Yay no errors

arctic sorrel
rich yacht
#

Thanks

arctic sorrel
#

Somebody else wrote the templates above, I just use them without fully understanding the magic 😂

rich yacht
#

And here I thought you were a wizard of sorts

arctic sorrel
#

I'm lazy, it works, that's enough for me until I need to change it

rare panther
#

if you are getting json - you could probably store the Key-value pair from {% set keyvalue = ( trigger.event.data | from_json) %}

#

was responding to earlier comments - somehow my feeds are being delayed

dreamy sinew
#

yeah, discord does that sometimes

thorny snow
#

Hello everyone. I would like to use the output of a shell script in a template. The output is text, not a value. I tried creating a command_line sensor but I only want the script to be executed when the template is actually to be used. Any ideas how to do this?

teal phoenix
#

Could somebody point out what is wrong with this:
service: climate.set_preset_mode data: entity_id: climate.thermostaat preset_mode: > {% if states('sensor.people_home') | int == 0 %} away {% else %} Winter {% endif %}

#

the error: Preset mode '{% if states('sensor.people_home') | int == 0 %} away {% else %} Winter {% endif %} ' not available

dreamy sinew
#

Rule 1 of templating

teal phoenix
#

being?

dreamy sinew
teal phoenix
#

thanks man

#

data_template:
preset_mode: |
{{ 'away' if states('sensor.people_home') | int == 0 else 'Winter' }}
entity_id: climate.thermostaat
service: climate.set_preset_mode

thorny snow
#

Other than IF/THENs.. what's the best way to assign the text based on value with this sort of data? An array?

#

Is there a more elegant way to do this?

#
          {%- set eventlist = {
              '1':'No events',
              '2':'High line voltage',
              '3':'Brownout',
              '4':'Loss of mains power',
              '5':'Small temporary power drop',
              '6':'Large temporary power drop',
              '7':'Small spike',
              '8':'Large spike',
              '9':'UPS self test',
              '10':'Excessive input voltage fluctuation' } %}
           {{ eventlist[value] }}

#

in this scenario, can I reuse "eventlist" (since i am going to copy and paste this all over now) or is it global for some reason?

dreamy sinew
#

Array is probably the easiest

thorny snow
#

Is this fine at the end there? {{ eventlist[value] | "Unknown" }}

#

neverminsd, I can test derp

dreamy sinew
#

Might be able to do eventlist.get(value, 'Unknown')

thorny snow
#

nice!

#

You're killin it today

#

... and again, it doesn't hurt to reuse "eventlist" since it's instantiated each template?

buoyant pine
#

Yup

#

Local only

thorny snow
#

awesome, thanks!

spark mantle
#

hey folks, is it possible to put a !secret into a value_template or say a url. examples:
url: "http://" + '!secret base_ip + "/api/location"
AND
value_template: "{{ is_state('!secret device', 'on') }}"

buoyant pine
#

No, but you can put the entire URL and value template in secrets

spark mantle
#

booo - that would mean 15 different secrets :(
i'm trying to create a package and pull from one common value

#

the IP of the host

#

is there another way to do that by any chance?

#

it will be used by more than just me, so trying to enable a user to just specify the IP and then re-use it

candid valve
#

I mean if you're really open to anything you can write a script in any programming language that generates and saves yaml to a spot home assistant will read it from but that's quite advanced and will just lead to more problems

spark mantle
#

thanks for the reply @candid valve its for a theme, and there was a glimpse of hope that it could be relatively simple to install with 3 steps.
!secret was basically a way for me to easily use a global value in the package

#

nvm

heady cedar
#

Is there an easy way to trigger an update for a template sensor that is waiting for a attribute change in a group?

arctic sorrel
#

Depends on the template, but typically you'd have to define an entity that updates regularly enough, such as using a time sensor

heady cedar
#

So the template is for gathering problematic plants and it has set entity_id: group.all_plants. But after an update/restart etc. the sensor always displays "unknown" till something happens. Is there no "manual" way? Updating it all the time is unnecessary

arctic sorrel
#

homeassistant.update_entity may work

#

That's a service call

#

However, it sounds like the way you've prepared the sensor means it's just going to rarely update without help

stone lintel
#

I'm trying to create a template (i think) that shows when a speedteest was last run, using the speedtest integration, can anyone point me in the right direction please?

glossy glen
#

Hello 🙂 I got this simple sensor setup:

  • platform: template
    sensors:
    ftx_power:
    friendly_name: FTX power usage
    unit_of_measurement: "W"
    value_template: "{{ float(state_attr('switch.sonoff_10007ca1b5', 'power')) }}"

Is there any way to also calculate kWh into this sensor?

arctic sorrel
glossy glen
#

Yeah but how? Isn't there some calculation that needs to be done?

buoyant pine
#

You'd have to divide by (1000 x hours)

arctic sorrel
glossy glen
#

hm..... Okey. Looks promising. Because my Sonoff Pow R2 only gives me Watt in realtime.

#

But isn't that utility meter for when you have accumulated kWh?

heady cedar
#

I don't get it. I've got a template sensor which work fine in the Dev tools but always display unknown in the Front end:

{%- if is_state('group.all_plants', 'ok') -%}
            Good
          {%- elif is_state('group.all_plants', 'problem') -%}
            {%- set problems = namespace(plants = '') -%}
            {%- for plant_id in state_attr('group.all_plants','entity_id') -%}
              {%- if is_state(plant_id, 'problem') -%}
                {%- set problems.plants = problems.plants ~ state_attr(plant_id, 'friendly_name') ~ ': ' ~ state_attr(plant_id, 'problem') ~ ', ' -%}
              {%- endif -%}
            {%- endfor -%}
            {{ problems.plants | regex_replace(', $','') }}
          {%- else -%}
            Unknown
          {%- endif %}
arctic sorrel
#

It'll only update when group.all_plants changes state

glossy glen
#

how the F did u see that so fast?

heady cedar
#

@arctic sorrel Even if I have removed #entity_id: group.all_plants?

arctic sorrel
#

Templates update when the entities update

#

You have one entity in there

heady cedar
#

Hm, makes sense. So I can change the entity_id from the sensor to something better. Is there an easy was to have it changed if any of the sensors of any of the plants changes?

arctic sorrel
#

Sure, list them all 😉

heady cedar
#

Ok ok, you convinced me. Something inside of me wants to manage these things not through time but through events. But listing 20 sensors is stupid too.

arctic sorrel
#

There's elegant, and then there's elegant but time consuming

heady cedar
#

You sound like my supervisor.

arctic sorrel
#

Call it... experience

#

Sometimes elegance is the right solution, sometimes hitting it with a hammer until it works is

#

Sometimes finding somebody else to solve it is the right solution 😛

heady cedar
#

I guess you're right :(
I added sensor.time (works in the state view) and changed my config:

    plants_detail:
        friendly_name: "Pflanzen Detail"
        entity_id: sensor.time
        value_template: >
          {%- if is_state('group.all_plants', 'ok') -%}
            Good
          [etc]

It still displays unknown 😦

#

Uh, it works... It just took like 5 minutes after restart to change. Better late than never

glossy glen
#

What are you doing with your plants?

sick orbit
#

Does anyone know if a value template can be used for a friendly name of a template sensor?

arctic sorrel
#

Docs don't show that, so I'd say no

rigid basalt
#

Hey guys has anyone got any idea of a "how to do templates with no prior knowledge at all?"

I tried to look into learning templating yesterday but it's all just gobbledegook to me. I was very tired though.

What I'm trying to learn to do is make a cheap smart bulb that doesn't have transition capabilities gain said ability from a script or automation maybe, so my bedroom light turns down over a period of say 15 minutes when I call it though my bedtime power off automation.

The trouble i had yesterday was using data_template: in the UI, it didn't like it for some reason. I was trying to call a script i found that lowers the level by X from current value.

I'm assuming this means I'm going to have to try editing the automations.yaml to do anything.

#

This is what I was trying to call in the services part of the dev tool

data_template:
brightness: '{{states.light.light_name.attributes.brightness + 10}}

arctic sorrel
rigid basalt
#

Actually I changed it to - 30. I tried removing the attributes part. It kept saying that it was expecting an int

#

@arctic sorrel what I'm looking for is a way to loop something like that until the light is off. I was thinking of dropping it 10/255 every 30 seconds

arctic sorrel
#

Sure, but you don't need templates for that

#

There's services for stepping the light brightness up and down 😉

rigid basalt
#

So I just stick that in a script with delays in the middle?

arctic sorrel
#

Rather than the template, yes

rigid basalt
#

Ok thanks I'll look into that. It was kind of half a project that needed doing and half a project to learn templates though. Know what I mean? I was looking for some kind of noob proof templating guide

#

I use an app called Tasker to automate my Tuya bulbs on my phone through IFTTT. Smart Life just notified me that they're taking away IFTTT support

arctic sorrel
rigid basalt
#

Do I was going to try to learn how to do everything on my pi instead

arctic sorrel
#

No reason you can't 🙂

#

I use webhook triggers from Tasker

rigid basalt
#

So do I, I just copied what I was putting in IFTTT and it worked

#

But my Tasker script is a bit crap, you can see the brightness lowering in steps. I was looking at how to put brightness setting in the webhook but got lost

arctic sorrel
#

Don't 😉

#

Have Tasker trigger an automation, have the automation do the magic

#

At most, pass data about how far you want it dimmed, in the JSON

rigid basalt
#

I've seen that last link before. I'll have a go at doing something similar when I get to sit down at my pc

arctic sorrel
rigid basalt
#

Thanks for these

#

Nice, I'll have a dig in there

#

I'm sending

#

{"action":"call_service","service":"light.turn_on", "entity_id":"light.740660434c11ae14c791"}

#

ATM and have no idea why it works lol

arctic sorrel
#

Probably you're hitting up the IFTTT webhook API

#

Which is designed to let you do that

rigid basalt
#

Ok makes sense

arctic sorrel
rigid basalt
#

So using that I could just call a script up

arctic sorrel
#

Sure, but I'd move the intelligence to HA

#

Have Tasker send a webhook saying dim and let HA handle what that means

left patio
#

hi, how can i use my regex strings from regex101.com in a ha value_template: ?

I have the following string:
WDC_WD40AFRX-68N22N0_WD-W17K02E9YF5: 34
and want to extract 34
which works with : (.*) on that website

silent barnBOT
left patio
#

": (.*)"

rigid basalt
#

You're awesome. I'm gonna have to bookmark all this.

arctic sorrel
#

So, you need to do that in Jinja2 - rather than a regex @left patio

rigid basalt
#

So I use your example to set up the webhooks with that walkthrough, write a script following that example and call it through Tasker. Thanks @arctic sorrel

dreamy sinew
#

could still use regex in jinja, but that's overkill

#

{{ string|split(': ')[-1] }}

arctic sorrel
rigid basalt
#

I was considering doing that with the brightness, have a variable that I set to whatever however on my phone and have a task send a webhook and change the brightness to the variable I set, then ramp the brightness with a loop in Tasker

arctic sorrel
#

As I said, let HA handle that "ramp"

#

Move the brains to HA, otherwise you've got logic in multiple places, and it'll cause you confusion later

rigid basalt
#

This was before I asked here

#

That last link was just like reading Chinese

arctic sorrel
#

🤣

#

It'll get easier with practice, probably 😛

rigid basalt
#

It already has. I bought a Pi 5 weeks ago as a lockdown project. No idea what to do with a pi, but after a week I had Hassio running

#

Now I'm looking at templates

arctic sorrel
#

Templates are like what happens when somebody gives you a toolbox full of random tools you've never seen before...

left patio
#

{{ string|split(': ')[-1] }}
@dreamy sinew this is called jinja? -> value_template: '{{ value | regex_findall_index(": (.*)") }}'
ill try yours now

dreamy sinew
#

you haven't said where the data is coming from

#

|split(': ')[-1] is a valid way to pull something out of a string in jinja2. but you need to have the "thing" in the front to actually work with

left patio
#

from an linux server over snmp

#

dont know why but i dont get it with your regex working

dreamy sinew
#

ah, i got it wrong but here:

{{ string.split(': ')[-1] }}```
left patio
#

ah youre doing this in the webinterface

#

i wrote this in my config.yml

arctic sorrel
#

Doesn't matter, templates are templates

#

That there is just a convenient place to test things

left patio
#

i think it works 🙂

#

now i have to find a way to get this long name out of my sensor card 😄

#

anyway thx for your help @arctic sorrel & @dreamy sinew !

karmic oar
#

Searching isn't getting me too far on this one: I've got some sensor templates that get updated based on a rest sensor returning some JSON data. Works fine, but occupationally the server times out for whatever reason and the resulting sensors based on the JSON data blank out, throwing off the graphs that do some math based on those sensors. Is there a more graceful way to handle the error: Empty reply found when expecting JSON data?

digital verge
#

(removed) oops - wrong section

#

something easy and user friendly

#

template aka skin

dreamy sinew
#

@karmic oar might be able to add a check to see if it is a valid response before trying to do stuff with it

karmic oar
#

Thought about that, but haven't tried it. Was thinking logically... whatwould I do with it? Say NaN? Not sure that would help me

dreamy sinew
#

yeah, that's the tricky part

spark mantle
#

random question - why is the value_template for a binary_sensor different in that it needs a statement to be true = ON
rather than an if statement?

buoyant pine
#

You can use an if statement but it's redundant and unnecessary

#
{{ x == 1 }}
``` is nicer than

{% if x == 1 %}
True
{% else %}
False
{% endif %}

spark mantle
#

not if i want the result to be false

buoyant pine
#
{{ x != 1 }}
spark mantle
#

if i have 5 things that mean the sensor is ON, but 1 that is off, how can i simplify without naming all the things that is could be with OR statements

#

that is an if statement

buoyant pine
#

You can use if statements

#

No one is saying you can't, but depending on what you're testing it could be unnecessary

spark mantle
#

{% if is_state('sensor.blah'), 'not_home' %}off{% else % }on{% endif %}

spark mantle
#

the docs state it cant be an if (and i've tried without any luck)

buoyant pine
#

Right. It needs to be True or False. So replace on and off with true and false

#

Or do

{{ not is_state('sensor.blah', 'not_home') }}
#

That will be True (on) when it's in a state other than not_home

spark mantle
#

thats what i'm looking for, will try that - thanks

buoyant pine
spark mantle
#

docs made it sound like only true was possible

#

got it, didnt know you could throw a not in there 🙂

buoyant pine
#

That's talking about what the template evaluates to

#

If it evaluates to True the binary sensor will be on, if False it will be off

spark mantle
#

right, but my limited knowledge only knew how to formulate a true statement lol

#

so many sensors i can remove all the list of states it could be ha - thanks!

buoyant pine
#

No prob!

austere surge
#

Has anyone ever had an issue where the Light Template cannot update color and brightness at the same time?

buoyant pine
#

Share what you're trying to do

silent barnBOT
austere surge
#

OK, here is the template: https://hastebin.com/vuhokubedu.cs
This is convoluted but the only way i could figure out how to do it. I have RGB lights controlled via HTTP. Most of what makes it annoying is that the set_color part only gives hs color, not RGB, and there are no util/helpers available in templating, so I have to set the HS value and then grab the converted RGB from it into input_numbers
And here is what I am trying to do:

- service_template: light.turn_on
  data_template:
    entity_id: light.room1_color_lights
    color_name: red
    brightness: 76.5 # 0.30 * 255
#

The above service example will set the brightness but not the color. If I separate them and set them one at a time it works. Adjusting the light from Lovelace works fine

buoyant pine
#

What do you mean "but not the level"?

dreamy sinew
#

That's not a template 😛

buoyant pine
#

That too lol. None of that requires _template either

austere surge
#

Typo sorry. It sets the level but not the color. edited

#

oh lol yes I don't need the _template stuff. The issue is really with the light template platform not behaving properly

#

It seems that when I call light.turn_on, it only runs set_color or set_level or it does both but messes one up

austere surge
sick haven
#

hello 🙂

#

can someone tell me, how to get a trend of a graph ?

arctic sorrel
#

Share the link to the code you previous posted please 😉

sick haven
#

i want to light on only if the trend go up

arctic sorrel
#

You've got the maths working correctly?

sick haven
#

on my template ?

arctic sorrel
#

Yes

#

So that it shows increase or decrease as you want?

sick haven
#

yes the result :

arctic sorrel
sick haven
#

😮

#

All time for this 🤧

#

You re the boss !

arctic sorrel
#

🤣

sick haven
#

Did you know if it's normal if this template don't accept icon templating ?

arctic sorrel
sick haven
#

pfff sorry

#

icon template is in template but not in trend, so maybe not..

arctic sorrel
#

Yeah, relatively few things support icon templates

#

There's various CSS wizardry you can do in the #frontend-archived but I've never investigated

sick haven
#

No need icon for automation... Maybe do another template just for use icon. But i think this may be implemented...

small rock
#

I have a template with several if condition, how can I hide the visual white row when the if condition is not met?

rugged laurel
#

with -

split mica
#

Is it possible to change custom css on a card based on the currently active theme?
Something like:
"""{if: states(theme) | string dark}"""

arctic sorrel
split mica
#

Okay, thanks

rare panther
#

Need a help. When I execute this command echo -en '\xfa\x24\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x24\xfb' | mosquitto_pub -t topic -s the techlife Pro bulb work fine. However, when the same hex chars are directly published from developer tools -> Mqtt they do not {{'\xfa\x24\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x24\xfb'}}.
See the image of the messages. First message is from command line tool and the second one from the direct message publish thru HA. See that the first and last byte are different https://imagebin.ca/v/5Ky3vZhEasy2

Is there some way to send exactly what command line sends?

thorny snow
#

Quotes? @rare panther

#

quotes mean literal, right?

rare panther
#

well I was providing as {{'\xfa\x24\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x24\xfb'}} in MQTT payload

thorny snow
#

put that as the data payuload? "{{'\xfa\x24\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x24\xfb'}}"

#

quotes around the whole thing so HA doesn't treaf those ticks as special?

#

I am taking an education guess but I am bad at math

rare panther
#

nope does not work. They should match the output from the echo command as in the screenshot I shared. Those start and end part of the message in echo command are generated as a '�'

thorny snow
#

hmm... ok

rare panther
#

Looks like the MQTT payload generates a ASCII but does not match the bytes from what is generated from echo command

#

just found out that The '�' character is what shows up when an invalid encoding is encountered. So the MQTT explorer I am using to display the codes does not correctly recognize the encoding from echo command

thorny snow
#

How can I create a binary sensor where the payload differs slightly? I have a RF motion sensor which sends signals varying from payload "70A860", "70A868", "70A86C" and "70A86F". So the last characters changes. Can I use a wildcard "70A86*" for this to trigger? If I search for 'binary sensor wildcard payload' on the internet, I get several other results..

thorny snow
#

Found it;
value_template: '{{ value_json.RfReceived.Data[:5] }}'

gusty nimbus
#

hey i have a question

#

i use a sonoff to monitor temperature & hum

#

but i want it in my HA show as curve

#

not blocks

#

sensor:

  • platform: template
    sensors:
    temperature_purifier:
    friendly_name: Temperature
    device_class: temperature
    value_template: "{{ state_attr('switch.sonoff_10009e86ef', 'temperature') }}"
    humidity_purifier:
    friendly_name: Humidity
    device_class: humidity
    value_template: "{{ state_attr('switch.sonoff_10009e86ef', 'humidity') }}"
#

is the code i have now in configurations

#

what could i do?

#

i'm not that good in coding 😉

arctic sorrel
gusty nimbus
#

i tryed that but wasn't working

arctic sorrel
#

Well, that's how you get line graphs 🤷

gusty nimbus
#

unit_of_measurement: '°'

#

?

arctic sorrel
#

Yup

#

It just needs to be set to something

#

Normally it'd be '°C' (or F) for temperature and '%' for humidity

gusty nimbus
#

oh ok

#

sensor:

  • platform: template
    sensors:
    temperature_purifier:
    friendly_name: Temperature
    unit_of_measurement: '°'
    device_class: temperature
    value_template: "{{ state_attr('switch.sonoff_10009e86ef', 'temperature') }}"
    humidity_purifier:
    friendly_name: Humidity
    device_class: humidity
    value_template: "{{ state_attr('switch.sonoff_10009e86ef', 'humidity') }}"
#

i have now for testing

#

HA looks the same after F5 hm

#

oh damn i have to restart HA 😉

#

ok works

#

but it only shows graph of 2minutes

#

how could it show of 24h or more?

arctic sorrel
#

It'll show up to 24 hours in the more info pop-up

#

Beyond that you need to use a card in the #frontend-archived to show up to the duration you've got in the history

gusty nimbus
#

oh ok

#

i filled in 60h in there 😉

#

guess i have to wait 😉

#

tx for everything

silent barnBOT
#
:ping_pong: ping?

PONG!

queen meteor
#

Bot working in all channels? Saw a message in #botspam Just checking.

silent barnBOT
south monolith
#

hello everyone I modified this script to make an audio fadein for the alarm clock ... instead of the maximum volume 0.3 I would like to put an input_number to be able to change this value of mine at will ... how should I write it? thanks

buoyant pine
#
{% if state_attr('media_player.googlehome5227', 'volume_level') < states('input_number.whatever') | float %}
south monolith
#

thanks I try ubito unfortunately with the templates I'm still not good

buoyant pine
#

would be a good idea to switch from

states.media_player.googlehome5227.attributes.volume_level 
``` to

state_attr('media_player.googlehome5227', 'volume_level')

#

that's what i did above

south monolith
#

ok I correct it

arctic sorrel
#

Last couple of days it's been acting up - but maybe only for me - in channels at random @queen meteor 🤷

dreamy sinew
#

likely discord side issues. its been a bit wonky

queen meteor
#

Likely something to do with discord. Everything looks good on the bot server side. I see some errors with discord server being disconnected - which is pretty normal for the bot. Bot auto-connects when that happens almost 99% of time.

arctic sorrel
#

That would be my bet, that or gremlins 😄

rugged flume
#

Hi, Any help on this would be awesome. I have a sensor that displays the rgb_color of a light, any idea how to get it to showthe color name? I tried color_name but it does not show anything. I currently have: light.soda_ash_night_light.attributes.rgb_color and this shows the rgb numbers but I would love it to show the color name.

arctic sorrel
#

You'd have to build a lookup table from the RGB to the name, and account for fuzzy matching. It's not likely to be trivial

dreamy sinew
#

"Red", "Mostly Red", "Kinda Yellow"

#

"Orangish?"

arctic sorrel
#

Dark goldenrod

rugged flume
#

Nuts I was afraid of that. can i circumvent that if I only need know one color. Fo example How could I get it to show: if(light.soda_ash_night_light.attributes.rgb_color =0,255,63, "Green", "Red")? When I use that it always shows red even if the rgb matches the 0,255,63

arctic sorrel
#

Well, you can simply display the name if it matches and "unknown" otherwise

#

Of course, that attribute isn't a string, which is likely the issues

#
{{ "Greenish" if state_attr('light.soda_ash_night_light','rgb_color') = [0,255,63]) else "Unknown" }}
#

Probably

rugged flume
#

I will try that, thanks

arctic sorrel
#

"Some" tweaking may be required - test in devtools -> Templates

rugged flume
#

thank you

#

I tested it but my igniorance is showing now. I get the following error: Error rendering template: TemplateSyntaxError: expected token ',', got '='

#

I altered it a lot but can not figure out the issue

arctic sorrel
#

Are you testing in the templates menu?

dreamy sinew
#

==

arctic sorrel
#

Always get that wrong wail

rugged flume
#

yes

#

got it, thanks

feral sage
#

Question regarding mqtt binary_sensor with template
Basically , I need this sensor turn on when I some1 press button on Intercom.
the user just turn on --> the topic DahuaVTO/BackKeyLight/Event get json with Action == 'Pulse' and later on automation i decide on which button he pressed by extracting the attribute( value_json.Data.State)

#
  - platform: mqtt
    name: intercom_calling
    state_topic: DahuaVTO/BackKeyLight/Event
    value_template: "{{ 'ON' if value_json.Action == 'Pulse' else 'OFF' }}"
    json_attributes_topic: DahuaVTO/BackKeyLight/Event
    json_attributes_template: >-
      {"state":"{{value_json.Data.State}}"}
    payload_not_available: offline
#

all is working but I need to go back to off and not stay on

#

meaning --> user press button --> sensor show on and return off

#

after 2-3 seconds

#

I tried add expire_after: 3
but it setting the sensor to unavailable

mighty ledge
somber hamlet
#

Hi, I would like to have a mqtt sensor that is on by default. This:"- platform: mqtt
name: "rob_present":
state_topic: "domoticz/out/floorplan/rob"
value_template: "{{ is_state(value_json.nvalue, 'on') }}"
payload_on: "1"
payload_off: "0"doesn't do the trick. Can someone suggest me how to do this?

dreamy sinew
#

{{ value_json.nvalue == 'on' }}

somber hamlet
#

That simple? 🤨 Thanks @dreamy sinew !

#

Mmmm, after a restart of HA he's still off.

sage zodiac
#

I have temperature sensors in all of the rooms in my house, I'd like to create a "coldest room" sensor. Essentially just take all of the temperatures from the sensors I have and find which one is the lowest and display it. Can anybody reccomend some way I can do this?

mighty ledge
#

@sage zodiac

sage zodiac
#

@mighty ledge Thanks I'll check that out

lusty silo
#

Does this look correct? It is returning "None" for me for some reason.

    sensors:
      ping_google_average:
        value_template: "{{ state_attr('states.binary_sensor.internetping', 'round_trip_time_avg') }}"
        unit_of_measurement: ms```
#

The binary_sensor is working, I verified that

buoyant pine
#

Remove states.

#

The first argument for state_attr() is the entity ID

#

You can also test templates at developer tools > template before deploying them in sensors

buoyant pine
#

@lusty silo ☝️

fossil summit
#

@feral sage I think that what you're looking for is: off_delay: 3

#

I need somehow help.. I can't figure this out after hours of tests.. I created an MQTT Binary Sensor, but it keeps remainin on "off" state even if the payload is "true" (As far as I remember a payload of true would translate to on, no?) This is the code: ```state_topic: "zigbee1mqtt/bedroom_luca_light_1"
value_template: "{% if value_json.update_available is defined %}{{ value_json.update_available }}{% endif %}"

#

(I also tried to add payload_on: "true" without success)

#

The payload is JSON coming from zigbee2mqtt, I think the path is right but maybe I am not seeing something very clear? {"state":"OFF","linkquality":57,"last_seen":"2020-05-03T14:32:59.356Z","brightness":255,"color":{"x":0.323,"y":0.329},"update_available":true,"device":{"friendlyName":"bedroom_luca_light_1","model":"LED1624G9","ieeeAddr":"0x680ae2fffe24c059","networkAddress":12060,"type":"Router","manufacturerID":4476,"manufacturerName":"IKEA of Sweden","powerSource":"Mains (single phase)","applicationVersion":17,"stackVersion":87,"zclVersion":1,"hardwareVersion":1,"dateCode":"20170315","softwareBuildID":"1.3.002"}}

rich yacht
#

why not just value_template: '{{ value_json.update_available }}'
or does it err if update_available doesnt exist?

fossil summit
#

I tried that too, ssame result

#

That was just a validation I copied from the PIR sensor just to test something else

#

Kind of a failover in case zigbee2mqtt doesn't send a value for that somehow

sonic nimbus
#

Im having wled integration, and now I want to create a script that when I call it randomly sets animations of my led strip

#

I have already setup everything

#

I want just set up effect randomly each time when I press a button

#

{{ state_attr("light.wled_lights", "effect_list") | random }}

#

maybe something like this

sonic nimbus
#
  - service: mqtt.publish
    data_template:
      topic: wled/all/api
      payload: "{{ state_attr("input_select.wled_presets", "options") | random }}"```
#

Im getting an error

#

its underlines wled/all/api error: cannot read an implicit mapping pair ; a colon is missed

#
  in "/config/scripts/lights/setup_on_wled.yaml", line 5, column 7
expected <block end>, but found '<scalar>'
  in "/config/scripts/lights/setup_on_wled.yaml", line 6, column 32```
jagged obsidian
#

what are your input selec values?

sonic nimbus
#

these are my input_select.wled_pressets:

#
  - "[PL=01] Preset 1"
  - "[PL=02] Preset 2"
  - "[PL=03] Preset 3"
  - "[PL=04] Preset 4"
  - "[PL=05] Preset 5"
  - "[PL=06] Preset 6"
  - "[PL=07] Preset 7"
  - "[PL=08] Preset 8"
  - "[PL=09] Preset 9"
  - "[PL=10] Preset 10"
  - "[PL=11] Preset 11"
  - "[PL=12] Preset 12"
  - "[PL=13] Preset 13"
  - "[PL=14] Preset 14"
  - "[PL=15] Preset 15"
  - "[PL=16] Preset 16"```
#

I tested in template editor in HA

#

and I receive correct

#

string

arctic sorrel
#

Please, use a code share site for things over 15 lines @sonic nimbus

sonic nimbus
#

I know..here are just 2 lines over

#

🙂

arctic sorrel
#

Yup, and... don't

#

😉

sonic nimbus
#

if I put just like to get the value from input_select what is selected currently

#
    data_template:
      topic: wled/all/api
      payload: "{{ states('input_select.wled_presets') }}"```
#

it works

#

but if I just want to randomize my input_select.wled_pressets

#

my coinfig is wrong

#
"{{ states('input_select.wled_presets') }}"

#Doesnt work
"{{ state_attr("input_select.wled_presets", "options") | random }}"```
#

this works: '{{ state_attr("input_select.wled_presets", "options") | random }}'

#

single quotes 😉

#

and how to catch that ranndom option and updated my input_select

#
    data_template:
      topic: wled/all/api
      payload: '{{state_attr("input_select.wled_presets", "options") | random }}'
  - service: input_select.select_option
    data_template:
        entity_id: input_select.wled_presets
        option: '{{state_attr("input_select.wled_presets", "options") | random }}'```
dusty hawk
#

I'm having fun with templates. I want sensors reporting how many doors, windows are open, or lights that are on. Here's the generic template. (Note that the expand() function recurses through groups of groups to the complete atomic entity list)

#
      value_template: >
        {% macro countgroupstate( group, state_test ) %}
        {%- for state in expand( group ) %}
          {%- if is_state(state.entity_id, state_test) %}
             {% set ns.count = ns.count + 1 %}
          {%- endif -%}
        {%- endfor -%}
        {%- endmacro -%}
        {% set ns = namespace( count = 0) %}
        {{ countgroupstate( 'group.all_lighting', 'on' ) }}
        {{- ns.count }}
#

You can also pass a series of {{ countgroup...}} and they'll be added together

dreamy sinew
#

That one probably won't auto update though

mighty ledge
#

@dusty hawk You should read up on filters, can save you some complexity.

{% set state_test = 'on' %}
{% set group = 'group.all_lighting' %}
{{ expand(group) | selectattr('state','eq', state_test) | list | count }}
#

@sonic nimbus you'd have to make a script and send the random option to it.

script:
  my_script:
    sequence:
    - service: mqtt.publish
      data_template:
        topic: wled/all/api
        payload: '{{ option }}'
    - service: input_select.select_option
      data_template:
          entity_id: input_select.wled_presets
          option: '{{ option }}'
#
service: script.my_script
data_template:
  option: '{{state_attr("input_select.wled_presets", "options") | random }}'
fossil summit
#

Anyone had a chance to see my message from yesterday?

mighty ledge
#

@fossil summit you're returning true but what does payload_on require? By default it's 'ON' or 'OFF' so you should be returning one of those in all paths. Or use true/false without quotes for on/off setting.

sonic nimbus
#

@mighty ledge this option is like input variable to my script right?

#

when I calling my script, I just pass option that I will randomize it ad hoc? 🙂

mighty ledge
#

@sonic nimbus option is passed to the script through the variable 'option'. See the service call that I posted calling the script. That's exacty how it would be called.

fossil summit
#

@mighty ledge Yep I got that, but also if I configure payload_on: "true" it doesn't seems to "accept" it.. also, the json is like "update_available": true, so it is returning a clean "true" value without quotes

#

ah... maybe I got what you mean, I should use payload_on: true instead of "true"

#

I'll try that

#

It worked! Thanks @mighty ledge , I thought I had to wrap in quotes... Well I actually thought a true from the json would had been enough 😄

dusty hawk
#

Thanks, @mighty ledge. And, it works across multiple groups too, and filters out duplicates as well:

#
{% set state_test = 'on' %}
{% set group = 'group.all_lighting','group.dining_kitchen_lights', 'group.office_lights' | join %}
{{ expand(group) | selectattr('state','eq', state_test) | list | count }}
sonic nimbus
#

@sonic nimbus option is passed to the script through the variable 'option'. See the service call that I posted calling the script. That's exacty how it would be called.
@mighty ledge zup, that I meant when I said that zou are passing a input argument called option

wary fiber
#

hey all i m working on my first templates / intents and i wonder howdo i get the siteId value from the json of the intent

#

{{ siteId }} doesnt seem to work

mighty ledge
#

your question is ambigous, we need to know what you're doing.

wary fiber
#

mmm well

#

ChangeLightState:
action:
- service_template: 'switch.turn_{{state}}'
data_template:
entity_id: 'switch.{{room}}_{{objet}}'

#

this intent is working alright

#

but i want to replace {{room}} with siteid

#

and siteId doesn t return any value

#

when listening to the MQTT intent i have that json:

#

{
"input": "on 0 lumière",
"intent": {
"intentName": "ChangeLightState",
"confidenceScore": 1
},
"siteId": "salon",
"id": "8986546d-9468-4723-b849-d4a41585ee02",
"slots": [
{
"entity": "state",
"value": {

#

dont know how to grab this value "siteId": "salon",

wary fiber
#

anyone ? 🙂

fast mason
#

Anyone had any success with input_selects for the media_player.play_media service? Been tried to make a radio list and echo device to pick from and play but it doesn't recognise the template on the automation/script 😦

buoyant pine
#

share what you've tried

silent barnBOT
fast mason
buoyant pine
#

should just be

sequence:
  - data_template:
      entity_id: '{{ states.input_select.playback_device.state }}'
      media_content_id: '{{ states.input_select.radio_station.state }}'
      media_content_type: TUNEIN
    service: media_player.play_media
#

i don't know if that's a valid content type or if the resulting template is a valid content id though

fast mason
#

I made it through the UI and did that automatically