#templates-archived

1 messages ยท Page 2 of 1

teal gate
#

Good day people. Please advice; I have created a custom sensor, placed it in my configuration.yaml and pressed 'check configuration', but I can't see the sensor anywhere.

template:

  • sensor:
    • name: "Unaccounted power"
      unit_of_measurement: "W"
      state: >
      {{ states("sensor.tibber_total_power") | int - states("sensor.water_heater_meter_power") | int - states("sensor.bathroom_thermostat_meter_power") | int - states("sensor.downstairs_office_thermostat_meter_power") | int - states("sensor.livingroom_socket_aircondition_meter_power") | int }}

The first couple of times I got an error when I pressed 'check configuration, but after some changes to the sensor I no longer get any errors.... So I am pretty sure the sensor is loaded.

inner mesa
#

you said before that you "reloaded", now you're saying that you just checked the configuration

#

that doesn't load anything

#

restart HA

teal gate
#

Yes, at first I thought the button was to reload configuration, but when you asked what I pressed I realized it only said 'check'... Ill do a restart and check... ty ๐Ÿ˜›

abstract sapphire
#

Where abouts would I put the quotes? Tried multiple places but either I'm dumb or it's not working still.

#

Also tried " " for a space but it just adds the quote marks too.

mighty ledge
#

remove the - before the %}

#

that minus removes whitespace up to the next text, which is There is a

abstract sapphire
#

Ahhh awesome. Thanks so much.

#

That did it

#

Did you all do separate study on JSON formatting or did you pick it up over years of using HA?

inner mesa
#

(I was about to mention that and got distracted by another ping ๐Ÿ™‚

#

just for the record...

silent barnBOT
flint wing
#

@mighty ledge

I tested the Last Shower Summation sensor with the code above.

It adds too much litres as it uses the instant flow value in L/min of the pulse_counter and increment instant value to each previous value. After about 10 seconds of water flowing, the Last Shower Summation sensor is already displaying more than 100 litres.

I'll dig a little further into possibilities, I'll keep an eye here too. If you come up with a new elegant way to achieve the goal, let me know.

I have also found a Github project that is reporting water consumptions on multiple basis, and also has a meter for "Last consumption: Indicates the last consumption (the measurement continues as long as the meter is running without interruption for more than 5 minutes)."

https://github.com/hugokernel/esphome-water-meter

inner mesa
#

Sounds like you need to use that rate to calculate the volume since the last update

#

I do the same with my water meter pulse counter

flint wing
inner mesa
#

every time you get a flow rate update, convert it to liters/sec and multiply by the number of seconds since the last update

flint wing
# inner mesa every time you get a flow rate update, convert it to liters/sec and multiply by ...

Hello @inner mesa, I created a boolean switch that turns ON where there is flow detected. This boolean works great. But then I tried creating a sensor that calculate the time elapsed since that boolean switch is ON and it does calculate properly but as soon as flow turn OFF, it trigger value back to 0. Is there a way to make that sensor value remain to the last calculated value without it going back to zero as soon as flow is OFF. I'm sure it's a newbie mistake that anyone experienced user can spot.

  • platform: template
    sensor:
    duree_ecoulement_eau_principale:
    entity_id:
    - input_boolean.eau_principale_on_off
    value_template: >
    {% set t = 0 if states('input_boolean.eau_principale_on_off') == 'off' else now().timestamp() - states.input_boolean.eau_principale_on_off.last_changed.timestamp() | round(1) | float %}
    {{ t }}
inner mesa
#

that's because you told it to ๐Ÿ™‚
set t = 0 if

#

yes, this.state

flint wing
#

Can you help correct it? Please ๐Ÿ™

inner mesa
#

you see the 0?

flint wing
#

Yes

inner mesa
#

change it to this.state

flint wing
#

It would become:

  • platform: template
    sensor:
    duree_ecoulement_eau_principale:
    entity_id:
    - input_boolean.eau_principale_on_off
    value_template: >
    {% set t = this.state if states('input_boolean.eau_principale_on_off') == 'off' else now().timestamp() - states.input_boolean.eau_principale_on_off.last_changed.timestamp() | round(1) | float %}
    {{ t }}
#

And if I want calculated value to be rounded to 2 digits, how do I write it?

inner mesa
#

|round(2)

#

I recommend going through the links in the channel topic

flint wing
inner mesa
#

that one, plus the other 2

flint wing
#

Ok thanks ๐Ÿ™‚

flint wing
inner mesa
#

maybe it's only in the new sensor format

#

so just use states('sensor.whatever')

#

or move to the new format

#

and make sure you're using the latest HA

silent vector
inner mesa
#

not sure what you're trying to do there

#

that's surely not it ๐Ÿ™‚

#

there's no dictionary there

flint wing
#

It's working now, but value does not round up to 2 digits: 37.081252098083496

inner mesa
#

ok

silent vector
#

I have a list of sensors that I'm assigning corresponding booleans to. It may be possible that I have a comma separated list of sensors at a time to pull corresponding booleans If the sensors are true. In developer tools input_boolean is result type: dict

inner mesa
#

oh, you called your variable input_boolean

silent vector
#

Yes this is a test in developer tools that's why I did that

#

In that way

inner mesa
#

I'm not really clear on what your end goal is

#

{{ (input_boolean['input_boolean.master_bedroom_away'] + input_boolean['input_boolean.daniel_away'])|join(', ')}}?

#

climate.master_bedroom, climate.daniel_s

#

you seemed to be focused on the syntax

silent vector
#

It's possible 2 or 3 sensors are true/false at a given time so I was wondering if there's a way using a dictionary to pull more than 1 item at a time as that would make this easier. If 2 or more sensors are true/false I would want their input booleans. Extracting 1 item is easy but it's possible the variable will be 2 or more. So i wanted to know if you can get 2 at a time.

#
humidity_sensors: ['sensor.daniels_humidifier_status','sensor.master_bedroom_humidifier_status','sensor.first_floor_humidifier_status']
  select_true_humidifier_sensors: >-
    {{ expand (select_true_humidifier_sensors) | selectattr('state', 'eq', 'True') |
    map(attribute='entity_id') | list | join(',') }}
inner mesa
#

again, it goes back to the actual goal

#

climate entities will never be true/false

silent vector
#

Let's say 2 of those humidity sensors are true. They would be joined in the select variable. Then I would do.
{{ input_boolean[select_true_humidifier_status] }}

#

These are template sensors not climate entities.

inner mesa
#

I'm confused by the mention of a bunch of input_boolean, some climate, and now some sensor entities

#

that's not a thing

silent vector
#

That was just an earlier example. Here's the dict

humidity_sensor: {
    'sensor.daniels_humidifier_status': 'input_boolean.daniels_humidifier_status',
    'sensor.master_bedroom_humidifier_status': 'input_boolean.master_bedroom_humidifier_status',
    'sensor.first_floor_humidifier_status': 'input_boolean.first_floor_humidifier_status'
    }
inner mesa
#

what you had above was closer

silent vector
#

Which one?

inner mesa
#
    {{ expand (select_true_humidifier_sensors) | selectattr('state', 'eq', 'True') |
    map(attribute='entity_id') | list | join(',') }}
silent vector
#

That only gets me to what's true. Now that I know what's true I will need their booleans to turn them on. The dictionary would be helpful. I use this to control a humidifier. The booleans prevent it from turning off if any are on.

{{ select_true_humidifier_status[humidity_sensor] }}
inner mesa
#

you can do that in a separate line

#

something like:

    {% set sensors = expand (select_true_humidifier_sensors) | selectattr('state', 'eq', 'True') |
    map(attribute='entity_id') | list %}
    {{ humitity_sensor.items()|selectattr('0', 'in', sensors)|map(attribute='1')|list }}
flint wing
#

I figured out how to correct it by reading the documentation ๐Ÿ™‚

inner mesa
#

if only everyone were so resourceful ๐Ÿ™‚

flint wing
#

Now trying to set units to display ๐Ÿ™‚

#

*seconds

silent vector
#

Going to try to test that.

#

I never set those humidity sensors up yet so I dropped in placeholders that are true.
https://dpaste.org/QBrUj

<generator object sync_do_map at 0xffff14b47760>

inner mesa
#

|list

silent vector
#

Worked

#

That's pretty cool. Always learning something. The power of Jinja.

#

I also read documentation lol. The Petro post I posted earlier enabled me to do create my first dictionary variable and access it with a variable.

formal frigate
#

Hi, i currently have an automation that decrements an input slider which triggers on a /1 minute time pattern. All is well. However, the condition is that a timer entity attribute numeric state (remaining) value is above 0. The value of remaining shows 0:15:00, which isn't accepted by the numeric state. How would I go about converting this 0:15:00 to seconds, or just plain minutes is fine too. Heck, it doesn't even need to be accurate for my automation to work properly, it just needs to be above 0 when the timer starts

marble jackal
#

Easiest is to check on the state of the timer

#

If it's idle or active

amber hull
#

I have this error in the log ```
Template error: int got invalid input 'unknown' when rendering template '{{ states('sensor.hacs') | default(0) | int > 0 }}' but no default was specified

#

Do I need another default

formal frigate
marble jackal
#

What are you trying to do with this automation and slider anyway?

formal frigate
#

You are 100% correct and I have no idea why I was trying it to do this way.

#

Well this automation is quite 'dumb', but the input slider is in my UI. Sliding it to X minutes starts my AC and starts a timer based on the input slider value. This automation (the one i am asking about now) will check every minute if the timer is active. If it is active, it decrements the slider by 1 minute so I have a (fairly) clear picture of how much time is remaining on the timer

marble jackal
marble jackal
formal frigate
#

I have no idea where to start with that honestly

#

On a secondary note, checking the regular state of the timer (obviously) works so far, so thanks a lot for that. My initial goal is accomplished but your method might be more accurate

marble jackal
#
{% set f = state_attr('timer.dishwacher', 'finishes_at') %}
{% if f %}
  {% set t = (f | as_datetime).replace(microsecond=0) %}
  {{ t - now().replace(microsecond=0) }}
{% else %}
  Timer finished
{% endif %}
#

@formal frigate I've set the microseconds to 0, as I guessed seconds would be accurate enough

#

Replace the timer in the first statement with your own timer

#

Off to bed now

formal frigate
wise tinsel
#

I had figured this out once before and now can't remember how I did it but I've got an input number helper with a button. I've got the button set to publish a message to my MQTT broker. I need a payload template so when I hit the button it published the number from the number helper.

#

I can't remember how I figured out the template before.

warm heron
#

hey I've got this diy template now that gives me following output:

_________________________
|06:00|07:00|08:00|09:00|
|20.7ยฐ|21.7ยฐ|24.0ยฐ|26.0ยฐ|
โ€พโ€พโ€พโ€พโ€พโ€พโ€พโ€พโ€พโ€พโ€พโ€พโ€พโ€พโ€พโ€พโ€พโ€พโ€พโ€พโ€พโ€พโ€พโ€พโ€พ

This is all cool but my time formatter doesn't give the correct time (offset by + 2 hours here)
I am in timezone Berlin.
How can I best modify this to respect the set time zone of HA when the input string is datetime: '2022-07-31T02:00:00+00:00'?
as_datetime(fcast.datetime).strftime('%H:%M')

All answers please @ / reply to me

wise tinsel
#

Awesome, thanks.

warm heron
warm heron
#

I've put as_local(as_datetime()) and it did double the offset

#

huh wait suddenly it worked

#

I think I unkowingly did something different when trying out before...

#

thank you! xD

#

now second issue:

#

I want to use said template in a message body of notify.notify but my phone only displays the newlines

silent barnBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

fossil venture
#

Share your non working config

warm heron
#

hang on I try xD

#

pic from notification following soon

inner mesa
#

<pastes War and Peace on the codeshare site :)>

warm heron
warm heron
#

pls ping with answers

glad glen
#

can someone help me with a template. super simple I think but I can't make it work. value_template: "{{ (states('sensor.total_watts') | min }}" I want to create a sensor that when it goes into a negative it report as 0

fossil venture
inner mesa
#

{{ [states('sensor.total_watts')|float(0), 0] | max }}

glad glen
abstract sapphire
#

I've managed to write a template that pulls a date from a sensor in string format and converts it to datetime format. Unfortunately that datetime format is offset-naive and I can't use it to compare it to the offset-aware now().

How do I write it so that the string converted to datetime format is also given an offset value?

#

{%- if now() > (state_attr('sensor.samba_backup', 'last_backup') | as_datetime) -%}

inner mesa
#

Add |as_local

abstract sapphire
#

I love you Rob

#

I'm finally getting into the nitty-gritty of writing code (albeit very basic) and I think it's worth actually just jumping into Python and learning - at very least - the basics.

#

This might be the kick in the ass I need.

flint wing
#

Hello! I've been writing a template to calculate the volume in litres used for a shower session, and I am 100% sure it's not correct but I've put a lot of efforts to at least make it intelligible. I am sure I do not have the correct syntax and your help would be more than welcome.

The idea with the template is that it first checks the state of my flow meter sensor if it is higher than 0, if so, it sets "current_litres_start" value looking at the total volume of litres value of my sensor.utilisation_d_eau_total. Then, when flow meter sensor value goes back to 0, it subtract the original value of current_litres_start to my new total volume of litres for sensor.utilisation_d_eau_total. In theory, this template seems logical, but the way to write it down is certainly sketchy. Your help would be appreciated!

https://www.codepile.net/pile/6XLbAEjW

silent vector
#

I'm struggling with humidifier_sensors and set_switch https://dpaste.org/A9nTJ
Initially I had humidity_sensors == 'false' and it didn't work. I changed to != 'true' and it semi worked. For the final statement initially I had elif humidity_sensors meaning if true when the boolean Is true which should have been fine as it's a boolean? I have done that elsewhere but it didn't work here
I can see that it's either false/true but the set_switch isn't reading it properly. As in it's not evaluating to on/off

marble jackal
#

You are checking for the string 'true', not the boolean value true

#

Als the variable already contains a boolean value, you can just check for the visible itself

#

if humidity_sensors

silent vector
#

Worked thank you!

abstract sapphire
#

What syntax am I getting wrong here?

{%- if now() < today_at("23:59") ++ now() > {{ (states('sensor.bayswater_north_astronomical_sunset_time_0') | as_datetime) }} -%} 
The sun will rise ~{{ (states('sensor.bayswater_north_astronomical_sunrise_time_1') | as_datetime).strftime('%I:%M%p') }} tomorrow with a {{ states('sensor.bayswater_north_rain_chance_1') }}% chance of rain
{%- elif now() > today_at("00:00") ++ now() < {{ (states('sensor.bayswater_north_astronomical_sunrise_time_0') | as_datetime }} -%}
The sun will rise ~{{ (states('sensor.bayswater_north_astronomical_sunrise_time_0') | as_datetime).strftime('%I:%M%p') }} today with a {{ states('sensor.bayswater_north_rain_chance_0') }}% chance of rain
{%- endif %}
marble jackal
#

Which error do you get?

abstract sapphire
#

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

warm heron
#

{{ }} means "convert these instructions into a string"

#

{% %} roughly means "these are instructions."

abstract sapphire
#

So first line should look more like

{%- if now() < today_at("23:59") ++ now() > (states('sensor.bayswater_north_astronomical_sunset_time_0') | as_datetime) -%} 
#

Or because they're two separate "if" statements do they need to be surrounded by some operator to differentiate between them?

warm heron
warm heron
marble jackal
abstract sapphire
#

Or do I need to separate them and make them two distinct if statements?

#

Rather than statement1 ++ statement2

marble jackal
#

Replace that ++ with and

abstract sapphire
#

Ahhhh

#

Shit I feel stupid

#

Thank you very much

marble jackal
#

You can also do it in one statement

{%- if (states('sensor.bayswater_north_astronomical_sunset_time_0') | as_datetime) < now() < today_at("23:59") -%} 
abstract sapphire
#

Ahh that's handy to compact it. Cheers, I'll try that out.

warm heron
warm heron
marble jackal
marble jackal
#

What is the result you get?

warm heron
warm heron
marble jackal
#

Aah, it doesn't output the template at the end

warm heron
#

yeah, doesn't process any of the {% %} stuff

#

therefore don't output anything because my template's all dynamic

marble jackal
#

Are you sure the template works, I'm trying it now in devtools. I tried several values for the temperature, but it always gives me errors like UndefinedError: None has no element -1

warm heron
#

however you need to make sure that you have weather.home_hourly from the norwegian meteorologist integration

warm heron
marble jackal
#

I replaced the entity_id with a weather entity providing hourly forecasts

warm heron
#

OHH CRAP THERE WERE JUST TOO MANY NEWLINES

#

The notification cut the text off, it was there

#

it's now working!

warm heron
marble jackal
warm heron
#

hmm okay I'll just replace the characters that are different with (ยฐ)

teal umbra
#

How do i round sensor values to 2

{{ states('sensor.solaredge_ac_power') | float - states('sensor.dsmr_power_produced_in_watt') | float + states('sensor.dsmr_power_consumed_in_watt') | round(2)}}

this results in 760.4000000000001 watt

abstract sapphire
marble jackal
#

pemdas ๐Ÿ˜Ž

abstract sapphire
#

I always learned it as bimdas

#

But yes, addition before subtraction

flint wing
#

I guess it's not allowed to re-post, then I am just letting the expert-coding-crew know that I have posted earlier today โ˜๏ธ and I am very eagerly looking for some help if anyone has a minute ๐Ÿ™

inner mesa
#

And...states are strings

#

You're adding a string

marble jackal
#

Which actually worked in his version, as round also converts to float

#

But the version of Taco will fall on the string

celest brook
#

So when I do this in my templates, I am basically grabbing that value, casting it to a float, and putting it in a variable, right? How do I specify what the cast to float action should do when the input is not a number, such as happens when the source in question loses the wifi briefly?

{% set solar = states('sensor.kwh_meter_3c39e72c1e98_active_power') | float %}

#

I know I should be able to find this in docs but I'm not getting results.

#

(the error in the logs is too long to quote in full but the most relevant bit is TemplateError('ValueError: Template error: float got invalid input 'unavailable' when rendering template

#

what I found of docs suggests that the float thing is the float() filter, but that's already supposed to have a default of 0.0 when it fails.

inner mesa
#

float(0)

celest brook
#

wait, is what I should be doing passing it through float and then through default? So that would look like | float | default(0.0)?

#

oooooooh

#

So I was wildly overtyhinking it.

#

thanks.

inner mesa
#

there's a whole forum thread on it

celest brook
#

Thank you. I had not found that one.

#

Definitely does the trick. Still weird that you have to manually specify the default, since the spec seems to say that there is in fact a default value for the default parameter, but it works so my problem is sorted.

jinja-filters.float(value: Any, default: float = 0.0) โ†’ float Convert the value into a floating point number. If the conversion doesnโ€™t work it will return 0.0. You can override this default using the first parameter.

inner mesa
#

I see that, and the original behavior differed based on the function. In the end, I think it's better for the user to explicitly specify a default rather than silently either return "0", or in the case of many functions, just pass the input straight through unmodified

#

I agree that the current behavior appears to be in conflict with the official Jinja docs

#

It's in HA's implementation:

def forgiving_float_filter(value, default=_SENTINEL):
    """Try to convert value to a float."""
    try:
        return float(value)
    except (ValueError, TypeError):
        if default is _SENTINEL:
            raise_no_default("float", value)
        return default
celest brook
#

yeah, that looks like it would do it.

inner mesa
#

where the default Jinja function looks like this:

def do_float(value: t.Any, default: float = 0.0) -> float:
    """Convert the value into a floating point number. If the
    conversion doesn't work it will return ``0.0``. You can
    override this default using the first parameter.       
    """                             
    try:                            
        return float(value)         
    except (TypeError, ValueError): 
        return default 
plucky wyvern
#

Hi, I need a template that adds up the "on" minutes of a binary sensor and compares if they are greater than 20 minutes. It is a rain sensor. Is this possible?

#

The last 24 hours

#

maybe I should use statistics for that?

flint wing
inner mesa
flint wing
#

I am a newbie trying to learn, an expert coder review would help make sure I didn't fall too far from proper syntax

inner mesa
#

ok, you just asked for "help", so wasn't clear

#

two things:

#

Second, this doesn't make sense:

         {% if "sensor.debit_d_eau_instantane" | float(0) > 0 %}    
          {% set current_liters_start = states('sensor.utilisation_d_eau_total') | float(0) %}
         {% else %}
          {% set current_liters_end = states('sensor.utilisation_d_eau_total') | float(0) - current_liters_start | float(0) %}
          {{ current_liters_end | round(2, 'common') }}
         {% endif %}
#

you're setting a variable in your "if" clause that will never be used

#

Also, this part of that doesn't follow any useful syntax:
{% if "sensor.debit_d_eau_instantane" | float(0) > 0 %}

#

turning a string into a float?

#

you're missing the states() call that you have everywhere else

marble jackal
inner mesa
#

it's nonsense

marble jackal
#

Also that

#

But probably a mistake :)

inner mesa
#

@flint wing I suggest trying your templates in devtools -> Templates and debug there. It seems like you're guessing

marble jackal
#

Oh, and @flint wing is mixing double quotes and single quotes in his template, best to stick at one

#

I'm also not sure what that entity_id: key with the list of entities is supposed to do

inner mesa
#

it's more old syntax that used to indicate what entities to monitor for changes in case they weren't obvious or what you want

#

should no longer be needed at all, or replaced with a trigger in the new syntax

#

I think the most important is that the initial current_litres_start is set once, and does not change until the condition of flow meter goes back to 0. This will ensure the calculation in else will be correct.

#

You cannot use a template variable for this, as they only have local scope. If you want to want to maintain a global variable, you need to use an input_number

#

I see that explains the bad "if" logic

marble jackal
#

It's not even mentioned in the docs anymore

flint wing
#

Thank you @inner mesa and @marble jackal, as you can see, that's a big guess I made and I understand it might appear as nonsense. I assume you get the picture of what I'm trying to do, but I lack a lot of knowledge on how to write proper code. I kind of mixed some codes I had been assembling before and trying to apply some logic into it, but I need to use proper syntax. I have the Jinja tab opened in my browser but it's quite a huge chunk to eat, should I read it from top to bottom? Are there other ways to become a master at coding templates?

#

@inner mesa, I don't even know if what I need is a new template. What I need is a simple substraction from an initial volume in litres (that value being stored in a separate sensor) before flow starts minus the resulting volume after the flow stops. I will use that new data afterward to calculate cost of electricity for hot water used for each individual shower.

So basically it's simply current_liters_end minus current_liters_start, and it should give me a number in litres. I don't k now how to get that number.

#

Yesterday I was proud when I had success creating a template counting time elapsed after flow sensor detects flow. https://www.codepile.net/pile/OlqoLOJG But today I'm not so impressed by my template calculating volume used while flow is detected...

inner mesa
#

using a template sensor is fine for that, but you need to store the starting value in an input_number rather than trying to set a Jinja variable (like current_liters_start). you would do that with an automation and a numeric_state trigger to detect when the value goes above 0

#

once you store the initial value in an input_number and reference it properly, the rest of the logic is fine

flint wing
inner mesa
#

ok

warm heron
shell kelp
#

I'm struggling with some sensors.. I'm trying to create a sensor that updates avg consumption watts from a wall plug the issue is the statistics module does not use time as a parameter so I need to make a "fake" sensor that updates every let's say 5 seconds so time is also a factor

I tried with a template sensor and added a tick attribute where I added {{ now().second }} - i can read the attribute but it's always 0?

#

The main issue is actually that the sensor only updates if value is > 5% and when idle it does not really trigger a value update at all on the sensor.. then if it was lets say 1500 watts on last update and now its 4.7w as idle.. then average will be quite high and never go down becuse no new updates are pushed..

inner mesa
#

now() is only evaluated every minute

#

if you want something else, you need to add a time_pattern trigger

shell kelp
#

Ahh.. that makes sense thats why its always 0...

#

But i cant do time_pattern trigger on a template sensor can i?

inner mesa
#

you can

shell kelp
#

Ahh!!!

#

Got it now.. then its a time based trigger..

#

sensor..

shell kelp
flint wing
# inner mesa using a template sensor is fine for that, but you need to store the starting val...

I created an input_number to be used as my initial volume value, then I created an automation that trigger when my binary sensor for water flow turns ON. In action I set it to call service -> input_number.set_value and for data: -> value I used the following:

service: input_number.set_value data: value: '{{ sensor.utilisation_d_eau_total }}' target: entity_id: input_number.volume_de_depart_debit

inner mesa
#

value: '{{ sensor.utilisation_d_eau_total }}' that is incorrect

#

you're randomly using and not using states()

flint wing
#

value: '{{ state(sensor.utilisation_d_eau_total) }}' ???

inner mesa
#

no

#

the "s" matters, the quotes matter

flint wing
#

value: '{{ states(sensor.utilisation_d_eau_total) }} ??

#

I'll read the state page

silent seal
#

You need to add quotes too

flint wing
# inner mesa the "s" matters, the quotes matter

I re-write the call service for my automation, is it OK?

'
service: input_number.set_value
data:
value: '{{ states('sensor.utilisation_d_eau_total') }}'
target:
entity_id: input_number.volume_de_depart_debit
'

inner mesa
#

you're using the same quotes inside and out of that call. It's not parseable like that

flint wing
#

It works when in Developer Tools, but not in automation

inner mesa
#

that's why

flint wing
#

How should it be configured to the automation accept the data:

#

I did it!

#

It works

inner mesa
#

great

flint wing
#

I forgot to make it double quotes before and after the data

inner mesa
#

yes

flint wing
#

You are great teachers here, thanks ROB! ๐Ÿ˜

#

It works but when I go back editing the automation the double quotes at the beginning and end of the string are changed to simple quote and automation does not work anymore. So I edited it back to what was working and I won't go back into editing this automation.

flint wing
inner mesa
#

Templates can do whatever math you want

flint wing
#

Then I guess I could go ahead with templating...

inner mesa
#

You don't need another input_number if you just care about the current value of a sensor

flint wing
#

Yes, getting the value of the subtraction between final value and initial value is my goal. That's what I need. I'm just trying to figure out how to create my string for that

#

But the template will need to wait until the flow if OFF to go ahead with the calculation....

#

When there is flow, input_number is updated, but water will keep flowing for an undetermined number of time... So is using a template the way to go? Or how can I tell template to wait for the flow to end and then do the math

inner mesa
#

It's going to calculate every time one of the entities it references changes

flint wing
#

Yes you are right. It's not that bad, it will simply create a value that I can see goes up

flint wing
#

There must be a minor mistake that you can spot:

  • platform: template
    sensors:
    volume_de_la_derniere_douche:
    friendly_name: Volume de la derniรจre douche
    unit_of_measurement: 'L'
    value_template: '{{ (states("sensor.utilisation_d_eau_total") | float | - states("input_number.volume_de_depart_debit") | round(2, 'common') }}'
inner mesa
#

You have an extra |

#

And you're still using the same quotes inside and out

#

Are you testing in devtools -> Templates?

flint wing
#

Yes, but I don't get any result. I'll keep testing out

#

This is how we learn

inner mesa
#

You're also rounding the last state (which is a string), and not the whole result

flint wing
#

Ok, this is working, I get a result:

value_template: {{ states("sensor.utilisation_d_eau_total") | float - states('input_number.volume_de_depart_debit') | round(2, 'common') }}

#

But you are right, it's not rounding

#

I must add another line to round the result of the operation?

inner mesa
#

No

#

Parentheses

#

It's just math and order of operations

#

And again, states are strings. Be consistent

vestal yoke
#

so if i want to group a bunch of sensors together to template using foreach, what's the best way to do it? there doesn't seem to be a group type that's appropriate

inner mesa
#

you can make a list

vestal yoke
#

ooh

inner mesa
#

either with "-" or as in JSON ['sensor.x', 'sensor.y']

#

or perhaps I'm not following what you want

vestal yoke
#

that is perfect

#

i was wondering if there was some way to group them, like tag them all with "plant sensor" and then iterate over all the plant sensor entities

#

but this list is just fine

flint wing
# inner mesa Parentheses

I think I got it!

value_template: {{ (states('sensor.utilisation_d_eau_total') | float - states('input_number.volume_de_depart_debit') | float) | round(2, 'common') }}

inner mesa
#

you're missing the surrounding quotes

#

and you should provide defaults for the float() calls, but otherwise it should work

flint wing
#

How do you decide value for float() ??

inner mesa
#

whatever you want

flint wing
#

Really? ๐Ÿ˜… I can choose float(99)

inner mesa
#

yes

#

it's your formula

flint wing
#

Ok good, what does the value do exactly?

flint wing
# inner mesa you're missing the surrounding quotes

And which quote are you referring to in this string?
value_template: {{ (states('sensor.utilisation_d_eau_total') | float - states('input_number.volume_de_depart_debit') | float) | round(2, 'common') }}

inner mesa
#

you used to have them and removed them?

leaden perch
#

Is it possible to have the default value be the last value before the entity went unavailable? Im making a new sensor from a solar panel sensor that goes offline every night

#
  - sensor:
      - name: "Zonnefactor"
        state: 3.503
      - name: "Zonvermogen thuis"
        unique_id: zon_thuis_vermogen
        unit_of_measurement: "W"
        state: >
          {{ float(states('sensor.omnik_2_power')) * float(states('sensor.zonnefactor')) | round(2)  }}```
#

this template works during the day but during the night it gives an error of course

inner mesa
#

yes, you can reference the current state with this.state

#

so have your template evaluate to that if the sensor state is unavailable

leaden perch
#

is it correct that the default should be specified in the round parameter?

#

because i want to use round and default, but ive only seen this {{ ((bedroom + kitchen) / 2) | round(1, default=0) }} as an example

#

and i want to use default and round at the same time

#

im going to sleep now. Please @ me if anyone has an answer otherwise i might miss it ๐Ÿ˜…

mighty ledge
#

the only time you need defaults is when your value is not a number

#

so, if bedroom or kitchen are strings, you'd need defaults for those. But the result of bedroom + kitchen / 2 will always be a number or fail before the round occurs

silent vector
#

Without using a bunch of 'replace'. Is there a regex method to strip off_ and _lights and then finally any _ if it exists between 2 words. In this case become script.off_breakfast_room_lights
breakfast room however handle doing nothing for script.off_kitchen_lights

inner mesa
#

{{ "script.off_breakfast_room_lights".split('_')[1:-1]|join(' ') }}

#

-> breakfast room

#

like that?

silent vector
#

Yes but this will be coming from a trigger.object_id with about 5 or more different object_ids so it will need to be a variable.

inner mesa
#

doesn't matter

silent vector
#

I see. You just put it there for an example. (Hard code)

flint wing
inner mesa
#

as always

silent vector
#

Yep I tested it that is perfect. Thank you.

abstract sapphire
#

I've got this sensor in my sensors.yaml but I can't get it to validate. Any ideas?

- platform: template humidity_average: friendly_name: "Average tank humidity" unit_of_measurement: "%"" value_template: >- {{ (((states('sensor.temp_sensor_hot_end_humidity') | float) + (states('sensor.temp_sensor_cold_end_humidity') | float)) / 2 ) | round(1) }}

#

I know the actual template works it's just the way I'm writing the sensor itself.

inner mesa
#

An actual error would be helpful

#

To start, you have 2 " in the UoM

#

You're also not following the proper format

abstract sapphire
#

Legacy format hey? Does that mean I should go rewrite in the "new" format?

inner mesa
#

If you want. But what you have there is neither

#

Just read the example

abstract sapphire
#

Fair enough. Are legacy sensors going to be phased out at some point?

inner mesa
#

Maybe. Probably not soon

abstract sapphire
#

With the very first example on the sensor page, I notice it gives the two entities "nicknames" or whatever they're called. Can those be called from any other template sensor as well or do they apply only to that specific one?

marble jackal
#

The first example in the legacy section, or the first example of the new format?

abstract sapphire
#

`template:

  • sensor:
    • name: "Average temperature"
      unit_of_measurement: "ยฐC"
      state: >
      {% set bedroom = states('sensor.bedroom_temperature') | float %}
      {% set kitchen = states('sensor.kitchen_temperature') | float %}

      {{ ((bedroom + kitchen) / 2) | round(1, default=0) }}`

marble jackal
#

That name is basically the same as friendly_name in the legacy template

abstract sapphire
#

Nah I mean the part below;

set bedroom = states('sensor.bedroom_temperature')

marble jackal
#

That are just variables in jinja

abstract sapphire
#

So they can be called from anywhere after being set once then?

marble jackal
#

No, only in the same key, so only under state: in this case

abstract sapphire
#

Ahh ok. Cool.

#

So do new template sensors have to be written in that format then? Eg for the average one they define both sensors on their own lines then do the math on a separate line?

marble jackal
#

No, you could use exactly the same template in the legacy format

#

Nothing changed in the jinja part between the new format and the legacy format

#

The YAML part changed

silent barnBOT
abstract sapphire
#

I wrote an example of my understanding between old and new format on that link above. Would that be correct?

marble jackal
#

No, you miss sensor: completely at the top of the legacy template

abstract sapphire
#

Oh my sensors are all inside the sensors.yaml file I created. So that's moot, no?

#

Been a long time since I touched sensors sorry.

marble jackal
#

The new format is not part of the sensor integration, it is part of the template integration

#

So you can't place them in sensor.yaml

abstract sapphire
#

Oh man I'm way off the bat here.

marble jackal
#

You need to place them in configuration.yaml, or do something like template: !include template.yaml in configuration.yaml

abstract sapphire
#

So currently inside my sensors.yaml file I've got this here. Works fine, no problems. Is this still perfectly fine as a sensor or is this format also "legacy"?

#

- platform: template sensors: endergreen_hotend_target: friendly_name: 'Ender Green Hotend Target' device_class: temperature unit_of_measurement: 'ยฐC' value_template: >- {{ states.sensor.endergreen_sensor.attributes['extruder']['target'] | float | round(1) if is_state('sensor.endergreen_sensor', 'OK') else None }}

celest brook
marble jackal
abstract sapphire
#

Ahh okay. So even sensors now have a new format. Gonna have to read up on that. Thanks.

marble jackal
#

As far as I know we were talking about sensors the entire time

abstract sapphire
#

Yeah I think being sick is currently getting the best of me. My brain wants to follow but half the time it can't ๐Ÿ˜ž

marble jackal
#

Well, the legacy format is not going away anytime soon, so you might want to get better first then ๐Ÿ‘๐Ÿผ

abstract sapphire
#

Good idea. Thanks anyway.

marble jackal
#

Get well soon then!

abstract sapphire
#

Last thing because I think my brain finally caught up now. Instead of doing template sensors inside the sensor: integration, they now get done under the template: integration? Did I get it right?

marble jackal
#

@abstract sapphire Correct!

silent barnBOT
analog mulch
#

Hi, I am trying t o convert a senso which gets reset every day ('sensor.plug_kitchen_oven_today_energy') to one which always increases. For some reason my template is not triggering. Is there anything obvious I am doing wrong? Thanks!
https://www.toptal.com/developers/hastebin/agibusucag

marble jackal
#

It probably falls on your counter template, as you did not provide a default for the float filter

#

And your template sensor probably doesn't have a numeric value yet

#

counter: "{{states('sensor.plug_kitchen_oven_energy_cumulative') | float('no number') }}"

analog mulch
#

Actually that's one thing I didn't really know hwo to properly deal with -- the initial value of the sensor should be the same as the one it is being derived from, but only this once. I was hoping the outer if statement would solve this?

#

if counter is not a number it just copies the to_state value

marble jackal
#

The problem is that your new sensor doesn't have a value yet, so when the trigger happens, the template for your counter trigger variable will fall

#

Because float requires a default in case the input is not a numeric value

#

My template provided this value, and as it is a string, and not a number, it will be handled correctly in your if statement

analog mulch
#

ok great -- i've never thought of putting a non-float as the float filter's default. It's a nice way of generating some default. Let me try

elfin torrent
#

how can i convert float to hex ? 10.0 ---> A

marble jackal
abstract sapphire
elfin torrent
silent vector
#

Can this be changed to track the state attribute fan_mode eq low instead of state?

'{{ states.climate | selectattr('state', 'eq', 'heat') | list | join(',') }}'
analog mulch
marble jackal
#

So you could remove the counter variable completely and do this

#
        {% if this.state | is_number %}
          {% if to_state < from_state %}
            {{ this.state | float }}
          {% else %}
            {{ this.state | float + to_state - from_state }}
          {% endif %}
        {%else%}
          {{ to_state }}
        {%endif%}
marble jackal
#

Oh, and you might also run in issues when you source sensor becomes unavailable

silent vector
#

Hey thefes can this be changed to track the state attribute fan_mode eq low instead of state?

'{{ states.climate | selectattr('state', 'eq', 'heat') | list | join(',') }}'
marble jackal
#

Yes, of course

#

| selectattr('attributes.fan_mode', 'eq', 'low')

#

You might want to add | selectattr('attributes.fan_mode', 'defined') as well, before the one above

#

In case there are climates without a fan_mode attribute

silent vector
#

Perfect. That makes sense. All 3 of my thermostats are the same and do have that attribute but it's good to know that you can do that if there are differences.

warm heron
shell kelp
leaden perch
silent barnBOT
versed shoal
#

Good day everyone, looking for a sanity check/assistance here. I've attempted to create two separate derivative sensors, one for the Sun's azimuth, one for elevation. The azimuth one is working but elevation is not...See above hastebin link.

marble jackal
#

You are using the same key twice

#

Remove sensors: on line 10

#

And line 3 should be platform: template

#

This all should be under sensor:

#

Either directly, or in something like sensor.yaml

ancient lynx
#

I have a similar question to @silent vector 's. I am trying to get a count of the amount of people on my guest network through the Unifi Network integration. I can find the attribute for 'essid' on an entity, and even doing a
{{ state_attr('device_tracker.xxxx', 'essid') }} returns the name of my guest network perfectly.

However, doing {{ states.device_tracker | selectattr('essid', 'eq', 'Guest Network') | list }} returns an error of UndefinedError: 'homeassistant.helpers.template.TemplateState object' has no attribute 'essid'. Am I missing something?

marble jackal
#

Yes, you first need to select all the device trackers which have that attribute defined

#

As I also mentioned to Dan

ancient lynx
#

{{ states.device_tracker | selectattr('attributes.essid', 'defined') | selectattr('essid', 'eq', 'Guest Network') | list }} gives the same error.

#

Sorry, forgot to edit the fan mode out.

marble jackal
#

Are you sure

ancient lynx
#

Yep.

marble jackal
#

That's because you are not checking for the attribute

#

You are checking for the state object essid which will never exist

#

You need to add attributes. to that one as well

#

{{ states.device_tracker | selectattr('attributes.essid', 'defined') | selectattr('attributes.essid', 'eq', 'Guest Network') | list }}

ancient lynx
#

Ah. I thought that's why you start with selectattr

#

Seems to me like that only looks at attributes on its own.

marble jackal
#

No, how would you check for the entity_id or state then, as they are not attributes

ancient lynx
#

Not use selectattr?

#

(Not being argumentative, or putting it on you. Just saying that the letters 'attr' in the function makes it seem like it's only for attributes. At least that's how I took it.)

marble jackal
#

Well basically the definition jinja uses for attribute is different from the one Home Assistant uses

ancient lynx
#

Ah. That could explain the confusion.

#

Well anyway, that worked. Thank you for the help!

desert crane
#

hello now i'm circling into here.
trying to figure out how to make automation that triggers every full hour and uses the "current_hour" (00, 01) as a name to check boolean for trigger condition.
smarter ppl tell me i need magic template juice for this, can someone point an example to chew on?

marble jackal
#

How are the input_boolean entity ids exactly

#

input_boolean.00?

desert crane
#

so they would correspond to hour

marble jackal
#

Okay, so use the time pattern trigger with "/1"

desert crane
#

example tells me this mean interval, but how does it know to start at full hour

#

restarts n stuff should not throw it off

marble jackal
#

Then use the following condition

condition:
  - condition: template
    value_template: "{{ is_state('input_boolean.' ~ now().strftime('%H'), 'on') }}"
marble jackal
desert crane
#

hassbot no likey typos

marble jackal
#

Finally saw what I did wrong

desert crane
#

guess it doesnt recheck edits?

#

hehe

marble jackal
#

No

desert crane
#

thanks, i'll see where this takes me

leaden perch
#

So is this not how you specify a default? - name: "Zonvermogen thuis" unique_id: zon_thuis_vermogen unit_of_measurement: "W" state: > {{ float(states('sensor.omnik_2_power')) * float(states('sensor.zonnefactor')) | round(2, default=0) }}

desert crane
#

what ya doing there, why u specify default? if u want 2 decimal places max then just leave round(2)

#

if there's less, then less is shown

leaden perch
#

Well, I want a default for when the original sensor is unavailable

grand prism
#

Is there a better place than this to discuss templating out a restful API response that doesn't have much in the way of a named structure?

#

This is the returned information, the data is not in any particular order, and I am literally just looking for a specific "name"[ { "name": "Registry", "pid": 108, "membytes": 40722432, "username": "NT AUTHORITY\\SYSTEM", "id": 0, "cpu_percent": "0.0" }, {...},{...},{...},etc ]

leaden perch
#

A bit too much detail for me ๐Ÿ˜…

#

Oh you have to set the default in the float?

silent seal
#

Yup. That's the place for it ๐Ÿ™‚

marble jackal
#

The default in the round doesn't make sense, as you are rounding the multiplication of two floats, if you want it anywhere, it should be in your float functions

#

But you're better off with an availability template here, it will prevent incorrect results

silent seal
#

Availability sensors are awesome. I love them.

marble jackal
#
        availability: >
          {{ states('sensor.omnik_2_power') | is_number and states('sensor.zonnefactor') | is_number }}
leaden perch
#

I finally got it working by putting the deffault in the float!

#

But now youve just introduced me to this

#

Ill check it out later ๐Ÿ˜›

#

Only took me like 3 days of trying all different kinds of templates ๐Ÿ˜†

#

I think my confusion lied in that I thought you just set a default for the entire sensor. But I couldnt find anything about that anywhere

desert crane
silent seal
#

It's a condition. There is no else.

#

A condition is "only continue if this is true"

desert crane
#

hmm.. then there must be two conditions and two actions.. off must be followed by action "device: off"

#

if no "else" can be given

silent seal
#

You're probably better off with a choose or an if action then.

desert crane
#

correct?

#

okay the ui solution would be i make two automations, one check for on, turns on, other checks for off, turns off

silent seal
#

A condition must always be true for something to continue in that area.
So you'd move your condition for that to the if. Or the option in the choose

desert crane
#

mhm

desert crane
silent seal
#

The if action is documented above the choose.

#

And you can do all of it in the UI

desert crane
#

thanks, checking..

#

ah okay i can skip conditions in ui and action choose gives it's own conditions

silent seal
#

Yup

desert crane
# silent seal Yup

vewy handy, thanks. think i got it together now. Must see if the magic TheFes template juice fills in the hours correctly

#

yarr.. there's no " anywhere.. what does it mean
Message malformed: Integration '' not found

#

oh nvm it was one loose unfilled action in the wizard ui.

#

(it's working, it's working anakin gif)

silent seal
#

Woot! Congrats ๐Ÿ™‚

desert crane
#

now to make 20 more booleans with correct icon ๐Ÿ˜›

#

and quite easy to set button hold to trigger automation if instant change is required mid-hour.

leaden perch
steel marsh
#

I'm stuck with some templating for thomas loven's auto-entities card. I've tried a few ways but can't work out what I am doing wrong. I have two sensors for when the bins go out, sensor.green and sensor.recycling which report x days as the output. I have made a new template sensor to just report the number rather than having the trailing "days" on the end. But, for the life of me cannot work out what to put for the template within the auto-entities filter. here is what I previously had:

            include:
            - entity_id: sensor.anniversary*
            - entity_id: sensor.recycling
              attributes:
                days: "<= 7"
            - entity_id: sensor.green
              attributes:
                days: "<= 7"```

however, it no longer works, any ideas if I can turn this into a template instead to get it working? I only want to show the next upcoming bin, ie. 7 days or less
flint wing
#

When we make a TTS service call in an automation, can we use int or round() functions when we write down a string?

Presently my TTS string is working but shout out the 2 decimals, I'd prefer to change that value to only integer so it doesn't sound strange detailing the value after the dot.

service: tts.google_say
data:
entity_id: media_player.bureau_mini
message: >-
"Votre douche a durรฉ {{ states('sensor.duree_ecoulement_eau_principale') }}
secondes et vous avez utilisรฉ {{
states('sensor.volume_derniere_utilisation') }} litres d'eau. Merci de
penser ร  la planรจte et bonne fin de journรฉe."

inner mesa
#

You can use whatever Jinja functions/filters that you want

#

You should remove the surrounding quotes

flint wing
#

You mean those " quotes at the beginning and end of the TTS speech line

flint wing
# inner mesa You can use whatever Jinja functions/filters that you want

This mean I could write: Votre douche a durรฉ {{ states('sensor.duree_ecoulement_eau_principale') | round | int }} secondes et vous avez utilisรฉ {{ states('sensor.volume_derniere_utilisation') | round | int }} litres d'eau. Merci de penser ร  la planรจte et bonne fin de journรฉe.

inner mesa
#

You're doing it the wrong way. You round an int, not round a string and turn it into an int

#

It might work anyway because of HA's round() function implementation, but in that case you don't need the |int

marble jackal
#

There's no reason to round an int though

inner mesa
#

True

flint wing
#

Ok, I'll just remove the round() and keep the int

#

Thanks for the h | int guys ๐Ÿ˜‰

#

Some jinja jokes ๐Ÿ˜…

sick ice
# flint wing Ok, I'll just remove the round() and keep the int

just consider if you want to read the number before the dot, or the closest rounded number.
| int and | round() will both leave you with an integer, but only | round() will round up from .5
e.g:

{% set x = 1.6 %}
{{ x }}
{{ x | int }}
{{ x | round() }}

1.6
1
2

flint wing
#

Thank you for the explanation @sick ice. It is very clear

sly thistle
#

Can I get some eyes on this shell command?


zzz: "curl http://172.16.68.47/cgi-bin/api/ovpn/client/status -X POST -H 'Content-Type: application/json' -H 'Authorization:{{ states.sensor.token.state }}' > mdata/xxx.json"


#

The template isnโ€™t โ€œexpandingโ€ on the sensor.token.state

#

The log says: Error running command: curl http://172.16.68.47/cgi-bin/api/ovpn/client/status -X POST -H 'Content-Type: application/json' -H 'Authorization={{ states.sensor.token.state }}' > mdata/xxx.json, return code: 6

prisma rivet
#

I used this to get camera id in the filename

- "/config/www/images/{{ camera_entity.split('.')[1] }}_{{ now().strftime('%Y%m%d_%H%M%S') }}.jpg"

But now i get

2022-08-02 10:04:24 ERROR (MainThread) [homeassistant.helpers.template] Template variable error: 'camera_entity' is undefined when rendering 'www/videos/{{camera_entity.split}}{{now().strftime("%Y%m%d-%H%M%S")}}.mp4'

#

so the question is how do i get the device name in to the file?

marble jackal
#

camera_entity is a variable and should be defined somewhere

#

.share your entire automation/script

silent barnBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

marble jackal
#

however, the example in the docs uses them as well

silent vector
#

Any idea why when I add the triggers automation reload, time pattern or event start the automation locks up (trace is greyed out) and does nothing. I get these errors and here is the code I put both on dpaste. I have had a similar error before and I added trigger.platform == state everywhere it was needed and it worked but not here. Not in dpaste is at the last choose option in the condition I did specify trigger.id == 'Fan Fallback'
https://dpaste.org/2GkSV

marble jackal
#

.share your entire yaml as well ๐Ÿ™‚

silent barnBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

marble jackal
#

On a time trigger, or automation reload trigger, there is no entity_id involved, so no trigger.entity_id

silent vector
#

Yep I know. I thought putting trigger.platform == 'state' would help

#

How do I work around this? I use this on other automations and they don't lock up like this. They run anyway.

marble jackal
#

Didn't go through all your templates, but in winter_offset: you only added that check for platform in the first if statement

#

not in the elifs

#

not in all

#

{% elif trigger.entity_id == 'climate.daniel_s' and (now() >= today_at('09:00') or now() <= today_at('07:00')) and state_attr('climate.master_bedroom','hvac_action') == 'heating' %}

#

this one for example

silent vector
#

It's there for all of them in that template but that one good catch. Would this fix the issue?

marble jackal
#

There seem to be more if I look at the errrors

#

You can make it easier for yourself to wrap the entire thing in an if statement

#

threshold_control will also not work

#

as it alo relies on a state trigger

#

and this one ๐Ÿ™‚

#

input_number

#

Why don't you just define all those variables in the choose

silent vector
#

I was just about to say that

marble jackal
#

or something like

action:
  - if: "{{ trigger.platform == 'state' }}"
    then:
      - variables:
          all_variables_which_require_a_state_trigger: template
      - actions_which_require_a_state_trigger
    else:
      - all_other_actions
variables:
  all_other_variables: template
silent vector
#

Interesting I will look into doing this. Here's the last automation I had this issue with and I specified trigger.platform == 'state' and it fixed it. This automation has pure templates though where I can't do that so I'll need to do what you said.

https://dpaste.org/sm97F

marble jackal
#

The variables don't exist outside the choose

silent vector
#

Yeah that what i was going to do. Define the variables at the specific choose that uses the variable and break up winter offset with the trigger.id fallback statements going into that specific choose.

#

Can you set a variable above a condition? As it is needed in the condition?

  - choose:
      - conditions:
          - condition: template
            value_template: '{{ states(threshold_control) == ''True'' and trigger.id == ''Mode'' }}'
marble jackal
#

Then you need to set it outside the choose

silent vector
#

This seems so complex I should just split this into a separate automation lol.

marble jackal
#

in my example I only added those variables which rely on stat triggers in the then, the rest is still in the variables section

#

That's also a good option

#

There is no real benefit of combining automations here

silent vector
#

Is the purpose of if-then only serve to set variables?

marble jackal
#

except a shorter automation list and the nice feeling of achieving this complex task

silent vector
#

Or the choose is nested in the if then?

marble jackal
#

your existing actions relying on the state trigger are nested in the then after the variables are set

#

so that includes the choose

silent vector
#

I see, that makes it a lot easier.

#

I never thought of nesting choose in an if then

terse musk
#

Is it possible to rename a attribute on an object, or add an attribute to an object in a template. for example, I have an object 'a' with an existing attribute a.name, which I want to rename to a.description (or copy the content into a new attribute a.description).

#

More context... I have an MQTT sensor that reports one of its attributes as 'name.' Since name is a reserved attribute in the sensor, that attribute gets dropped by HA. I need to use the content of that attribute, so I need a method of getting that content into an attribute that doesn't conflict with HA sensor default attributes.

wet vortex
#

Hi , Im not sure if I'm in the right section here however I'm trying to create a custom sensor that would give me either true ( if sensors value is above 30 or false if its otherwise. How do i modify the code to achieve that ?
`template:

  • binary_sensor:
    • name: "iaqabove 25"
      state: "{{ states('sensor.bme680_iaq') | float > 30 }}`
inner mesa
#

Looks okay to me, but you're missing the trailing "

inner mesa
terse musk
#

Thanks, but I found a solution that works. I just had to JSONify it and do a string replace. Works perfectly in the MQTT sensor.

      {{ value_json | to_json | replace("\"name\":","\"description\":") }}
inner mesa
#

Ok, sure. I'm surprised if you're saying that HA just doesn't allow 'name' as an attribute

terse musk
#

It's a problem with the mqtt sensor and this particular payload. It's a single json payload and a few attributes in it get dropped. I assume they are dropped because they are named the same as existing default entity attributes (name, state)

inner mesa
#

Those aren't attributes, though

#

The attributes for an entity is just a dict and has no name collisions with other properties of the state object

terse musk
#

While I agree with you that it shouldn't be an issue, those attributes do get dropped by the mqtt sensor for whatever reason. The work around is easy enough though and I can't imagine this situation is encountered very often.

ancient lynx
silent barnBOT
#

Please use a code share site to share code or logs, for example:

Please don't use Pastebin, since it can randomly add spaces to the main view. Please also don't share text as images since it makes it harder for people to help you. Remember that others may have colour blindness, impaired vision, etc.

marble jackal
#

First guess, you didn't place quotes around the template

ancient lynx
marble jackal
#

Did you put this in configuration.yaml

ancient lynx
#

I did.

marble jackal
#

Do you already have other template sensors?

ancient lynx
#

No, first one in this installation.

marble jackal
#

Okay, what if you clear your log, then reload template entities

#

Anything in the log then?

ancient lynx
#

Seems like it needed | count at the end.

#

Ah!

#

It's because I added the state_class as measurement.

marble jackal
#

Then it would not have worked in devtools > template

ancient lynx
#

The lack of count and the measurement state class weren't compatible.

marble jackal
#

Yes, I didn't look closely at the template itself, as you said it was working in devtools and also because I'm on a bicycle ๐Ÿ˜…

ancient lynx
#

Well then answer me later! Don't Discord and ride. ๐Ÿ˜

#

Thanks anyway. Appreciate going the extra step to help.

marble jackal
#

๐Ÿ˜Ž

heavy plaza
#

Hey so I was told I could use templates to make sensor ( an LDR sensor )data I receive from mqtt in an entity I tried looking on the internet and ha website but there isnโ€™t much info about it could someone tell how I can do that?

silent seal
#

They're called template sensors

heavy plaza
#

I just read it but I still donโ€™t know how do I get the state that is written in all the examples? All I have is the mqtt topic

silent seal
#

You probably already have a sensor at least. Try looking under Developer Tools > States

heavy plaza
#

Not sure I understand what you mean under developer tools > states I see my entities and their states what does that have to do with it? ๐Ÿ˜…

inner mesa
#

It sounds like you want an MQTT sensor

#

Which can involve templates

silent seal
#

Under the same Developer Tools you can listen to events, which may be helpful for you ๐Ÿ™‚

heavy plaza
heavy plaza
silent seal
heavy plaza
#

A few listeners but nothing mqtt or sensor related

silent seal
#

I've just remembered, the MQTT integration has a separate listen feature just for MQTT events

#

I can't remember the listen you need in developer tools, but you may be listening to the wrong thing

heavy plaza
#

Thanks for the help

silent barnBOT
wet vortex
#

Hello , looks like Im having issues creating an alert when binary sensor changes it's state - im just not getting a notification on my phone . I have verified that notify service works via dev tools heres my code:

silent seal
#

The hastebin link is not a complete automation or a template

#

At least not that I can see, I can't scroll horizontally

wet vortex
#

thats the only thing Ive got

silent seal
#

But your alert line is too far outdented

#

As are all the things underneath it

wet vortex
#

so they should be all in line with air_quality_iaq: ?

silent seal
#

It'll be worth checking out the docs on YAML and reviewing the sample templates. Indentation is critical to things being read correctly

#

Check your config too when you change it

silent barnBOT
#

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

wet vortex
#

thanks ill do that

silent seal
wet vortex
#

ill start reading

silent seal
#

Where did you get the alert part of the template from? It's not something I've seen before. I wonder if you've confused/combined the scripting/automations and templates

wet vortex
#

i dont think that it is a part of template

silent seal
#

You probably just need an automation ๐Ÿ™‚

wet vortex
#

i followed this :

silent seal
#

That's not a template, that's an integration

#

How important are these notifications? I consider the alert integration to be for things such as "the smoke sensor says the house is on fire" rather than "it would be good to open a window"

#

(Though I am assuming based on the AQI sensors)

wet vortex
#

They're not however this is just an example that I would like to create to see how that works. As you can tell I have very little knowledge of yaml and such

silent seal
#

No worries. I've just re-read the alert docs, and what you'll need to do for this is to create a template binary sensor which is on or off for the sensor, and use that. I'll throw together an example for you

wet vortex
#

so thats what I did here , and the sensor works.

#

`template:

  • binary_sensor:
    • name: "iaqabove 25"
      unit_of_measurement: "iaq"
      state: "{{ states('sensor.bme680_iaq') | float >35 }}"`
#

when IAQ value goes over 35 it changes it's state to :

#

oops I cant paste pictures here ๐Ÿ™‚

#

state is: ON

silent seal
#

Now I understand where your YAML before came from ๐Ÿ™‚

#

If you can define a unique_id or an entity_id for something like this it can be incredibly usefulโ€”so you know what you're referring to in other integrations (like the Alert)

wet vortex
#

reading thru it ๐Ÿ™‚

silent seal
#

One thing to watch is you can only have one template or alert (or indeed one of any) key in your YAML. If you have

template:
  binary_sensor:
... something else
template:
  sensor:

Then the second template will overwrite the first

wet vortex
#

ou I definitely have more than one

silent seal
#

That'll be part of the problem then ๐Ÿ˜„

wet vortex
#

Thank you Ill try that now

silent seal
#

There is also something you can do called splitting your configuration, so you can move templates into one or more separate files. But I'd leave that for a future timeโ€”it won't fix duplicates.

#

Though I'd note that down to look into when you've learnt more about YAML, it'll probably make your life easier ๐Ÿ™‚

wet vortex
#

Correct , I think Ive read about it a bit, so you separate automations , scripts etc in separate files and then include them in main config correct ?

#

or close enough.... ๐Ÿ™‚

silent seal
#

Yup, pretty much!

silent barnBOT
#

Here is now to split your configuration into multiple YAML files

atomic blade
#

Is there something that would act like a "template input_number"? For instance there's a template switch where you can take an action when it's toggled. I would like to take an action when the input_number is updated (with the value scoped accordingly). And yes I know this could be done with an automation.

silent seal
#

What's the action you're trying to take?

atomic blade
#

Call a script

silent seal
#

Usually, it's best to follow the standard paths for things. E.g. for "when X changes, Y happens" that's an automation. "X, Y and Z run" (order not important) is a scene, when the order is important it's a script. And "when X happens this sensor shows that" would be a trigger template sensor

#

A template can't (to my knowledge) call a script.

atomic blade
#

Parallel actions were added to scripts recently in case you didn't know ๐Ÿ™‚

#

I didn't know scenes were parallel though

#

I'm not a fan of scenes so I just avoid them completely

silent seal
#

I do know. By default a script or automation is sequential

#

And scenes are parallel, I don't tend to use them much myself.

#

Though being able to create a scene in an automation is very useful

atomic blade
#

Anyways, I figured it wasn't possible but I thought I'd ask

silent seal
#

So I can create a scene with the current state of devices, and then restore that state later

atomic blade
#

Yeah those dynamic scenes have intrigued me but I never tried them out

#

Yeah for exactly that reason

silent seal
#

Well when I'm watching TV and the doorbell rings (I seem to have trained people well enough this doesn't happen now), the TV pauses and the state of all the things are saved as a scene. Then at certain times of day one or more lights will turn on to specific brightnesses.

When I then resume playback, states are restored.

#

So even if I then trigger other lights or devices to run/turn off, what they were doing is put back how I wanted it when I sit back down

atomic blade
#

Yeah my light game is kinda weak. Right now I have a script I use basically to set scenes as the night goes on. I'd like to just have that be completely automated though. I tried out some of those circadian integrations but I dunno they just were doing stuff I didn't want them to

silent seal
#

You'll figure it out over time

atomic blade
#

Problem with my current setup though is that it'll turn lights on if they're off

silent seal
#

As a note, that's where scenes are really helpful, when you have lights in a state where you want to reuse them, make a scene. Then you have all the entities and properties saved for later so you can re-use them without figuring it all out again

atomic blade
#

The one thing I do really like about my lighting setup is my NR flow that matches up motion sensors with lights. So I have 1 flow for all my lights

atomic blade
silent seal
#

Well, your goal is to not turn on lights you don't want to turn on.

#

I heavily use areas, and have custom template occupancy sensors (they combine various other sensors to determine if a room is occupied or should be considered occupied). When an area is not occupied, lights turn off, and they only turn on again when something in that area triggers them

atomic blade
#

I think I should try giving one of those circadian integrations a shot again. Ideally I wouldn't have to set these scenes manually throughout the day anyways

atomic blade
silent seal
atomic blade
#

I think I was using Adaptive Lighting

silent seal
#

All the others behind it might be a bit mad, but I can live with that

atomic blade
#

Is there a lot going on with binary_sensor.presence_lounge or is it just a PIR sensor?

silent seal
#

It's a combination of 2 PIR sensors, and the FP1 sensor from Aqara. I think the TV might have snuck in there at some point too

atomic blade
#

Been thinking about grabbing an FP1

#

I kinda want to try one of the DIY ones though. I feel like if I get one I'd just want it in every room lol

silent seal
#

It's a good device. I also have a thermal camera DIY sensor I'd like to try soon

wet vortex
silent seal
#

Anything in the logs when it should trigger?

wet vortex
#

found this , homeassistant.exceptions.ServiceNotFound: Unable to find service notify.notify.mobile_app_iphone_11

atomic blade
#

Have the state template mirror the input_number and then use set_value to call whatever service you want with the value

silent seal
silent seal
atomic blade
wet vortex
#

barabing !!! it works ! youre the best - thank you for your help

#

@silent seal Thank you

silent seal
silent seal
atomic blade
#

I don't think there's really anything wrong with the way that would be set up

silent seal
#

Probably not. I'm just very familiar with the XKCD spacebar comic

atomic blade
#

Is that the one where it heats up the CPU?

silent seal
#

Yup

atomic blade
#

Haha, never gets old though

silent seal
#

The advantage with an automation is you have traces, and can turn it on or off or add other conditions to it. And the turning on and off can happen in the GUI or through another automation. To me template sensors are "I need a sensor from this data" and as a byproduct the service is called

#

Not that you can't use things like this. It just doesn't make sense to me ๐Ÿ™‚

atomic blade
#

Well I think almost anything that you could do in a template you could do in a automation. I think in this case, what I'm trying to do is pretty simple so it seems to make sense as a template. When a value changes, call a service with that value.

silent seal
#

I just always try to look at the name, e.g. the intention. Template sensor is a template creating a sensor. Automation has trigger, conditions, actions. Why create a template if I don't need one?

atomic blade
#

I mean if you look at the template docs, there are a lot of template sensors in there that allow you to map it to an action, no? Like the select or button

silent seal
#

I always read them as "you also need this sensor for other things" rather than them being a pseudo automation

atomic blade
#

Yeah I think the distinction with a trigger is a good one to indicate you might want it to be an automation

silent seal
#

Yes. It can be very useful to slow down or speed up how often a template is updated, or to avoid it being updated under certain conditions (e.g. update my thermostat target temperature default when the temperature drops, but only if it's during the day), but it really depends on what your goal is

atomic blade
silent seal
#

The switch as X feature is a template platform, rather than a template sensor.

#

Like the generic thermostat/hygrostat/camera integrations.

atomic blade
silent seal
#

binary or non-binary

atomic blade
#

Because this is essentially a boolean version of what I'm looking for. If this is appropriate to use then I'm not sure I'd understand why a number version of it wouldn't be

silent seal
#

Those are platforms. You see it's under "switch"?

atomic blade
#

I'm not sure I understand how that differs fundamentally from say the select template

#

It provides an input to the user that they can interact with and when it's updated an action is performed using the given input data

#

I haven't actually used a select btw, so maybe I'm wrong about how it works. I was actually just about to try to play around with it

silent seal
#

The switch template is intended (at least as I see it) for something where perhaps you need to control multiple devices to turn something on/off.

#

I suspect the template select is intended for people who are using a heating system (or generic thermostat) like myself who need to map various states to certain calls. I have to say I've never used it nor seen it used

atomic blade
#

Not sure I'd agree. I'm using one right now that acts as the state of my desktop monitor. The state is updated with a ssh command, and the on and off actions turn it on and off with other ssh commands. It seems very succinct and a perfect use case rather than having what I think would be multiple automations?

silent seal
#

I'd probably have used the command line integrations for that

atomic blade
#

Oh this is interesting, I don't think I've seen the former at least

silent seal
#

But this is Home Assistant, there's always 1000 ways to solve a problem. The key is that it works and you're open to learning about new ways to do things. I'll have to look at the select template again myself.

atomic blade
#

No I mean this is why I have convo's like this. I find better ways of doing things

silent seal
#

We all do ๐Ÿ˜„

atomic blade
#

These still kind of fundamentally seem like the same thing though. switch.template and switch.command_line. The former just seems more versatile since it doesn't need to call something on the command line

silent seal
#

Well, it all depends on what the thing is calling

#

Underneath it's all python.

atomic blade
#

I've also been trying to move in the direction of calling everything via scripts. Seems more organized that way and leaves the door open for me to expand the action easier if needed

#

And other benefits like tracing

silent seal
#

It's certainly very useful. Though with one automation being able to have multiple triggers. I've got plenty of things in those too

atomic blade
#

I'm a NR guy so pretty much all my automations are in flows

#

I might move back some day. I think it's really the visualization that does it for me

#

Is there a particular way the "sub" integrations are organized? The switch integration doesn't mention there's a switch.command_line

#

Ah I guess on the main integration page

silent seal
#

There are 155 switch integrations, so I think they just pick a few.

atomic blade
#

Anyways, I've forgotten what I was even trying to do in the first place so I'm off haha. Thanks for the help

heavy plaza
#

So now I have an MQTT sensor ( configured using MQTT sensor integration ) that is giving Time, Illuminance1 under ANALOG, Temperature under ESP32 and TempUnit. First I was getting the sensor readings as a string so I added Json_attribute_topic now when I print the sensor in template under developer tool the result type is dict and I get all the readings I said above but when I try to print a specific attribute like Time it doesnโ€™t work. What I am trying to use the template for is to make it that the illuminance1 reading is OFF if 0 and ON if any other number

silent seal
#

I believe this is the data structure based on the error you had yesterday:

{
  "Time": "2022-08-03T00:57:54",
  "ANALOG": {
    "Illuminance1": 0
  },
  "ESP32": {
    "Temperature": 56.7
  },
  "TempUnit": "C"
}
heavy plaza
#

Yes thatโ€™s it

silent seal
#

What do you get if you put

{{ state_attr('sensor.mqtt_sensor', 'ANALOG') }}

into dev tools?

heavy plaza
#

{โ€œIlluminance1โ€ : 0}

silent seal
#

Good start ๐Ÿ˜„

#

I'm trying to find something of mine with nested attributes

#
{{ state_attr('sensor.mqtt_sensor', 'ANALOG')['Illuminance1'] }}

Try that.

#

No guarantees, probably not the best way to do it, but if it works...

heavy plaza
#

Yeah it works

silent seal
#

Bingo

heavy plaza
#

Yay

#

Now I added float > 0

#

So itโ€™s showing as Boolean

#

Onto the automation we go!

marble jackal
#

no need for the float, it's already a number

#
{{ state_attr('sensor.mqtt_sensor', 'ANALOG').Illuminance1 }}โ€Š

Should also work BTW

silent seal
#

I did think it would, but I wasn't sure ๐Ÿ˜„

heavy plaza
silent seal
#

If it's in a binary sensor then 0 is falsey

heavy plaza
#

Ah will try it without it then

#

If I get the unique Id working ๐Ÿ˜…

#

is there a reason why with this still cant find the template anywhere

#

template:

  • binary_sensor:
    Unique_id: "AC_state"
    name: "AC State"
    state: >
    {{ state_attr('sensor.mqtt_sensor', 'ANALOG')['Illuminance1'] }}
inner mesa
#

You also capitalized Unique. Don't do that

heavy plaza
#

So unique Id should be before binary sensor?

marble jackal
#

No

#

- binary_sensor: should contain a list, not a dictionary

#

And the key unique_id: should be lower case

heavy plaza
#

Alright

#

Works now thanks

silent seal
#

You can format the code you share here too ๐Ÿ™‚ (See below)

silent barnBOT
#

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

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

For over 15 lines you must use a code share site such as https://dpaste.org/ (pick YAML for the language), https://www.codepile.net/ (pick YAML for the language), or https://paste.debian.net/ (pick YAML for the language).

silent vector
#

In an auto entities card with mushroom template I'm using this to reformat the entity name to be readable.

{{ entity | replace('light.','') | replace('_',' ') | replace('lights','') | upper }}

I want each word to have a capital first letter.
Meaning
Master Bedroom vs right now Master bedroom is that possible with Jinja? I could harcode with replace but that isn't clean.

inner mesa
#

|title

silent vector
#

Thank you!

inland stag
#

Hi everyone, for a mqtt select entity, I want to translate some values before sending the command_topic, and for this we have command_template. But how do I access the mqtt select's current value in the template?

marble jackal
silent vector
#

That is it's entity name. I didn't try using entity name I wonder if that would work

#

Nope the {{ entity_name }} didn't work

inner mesa
#

what is that?

marble jackal
#

{{ states[entity].name }} or {{ state_attr(entity, 'friendly_name') }}

inner mesa
#

did you set that variable name?

marble jackal
#

It's just a variable referring to the entity_id

inner mesa
#

just saying that adding "_name" to an existing variable doesn't do anything useful ๐Ÿ™‚

silent vector
#

Nope it doesn't lol I wasn't sure if it was available

marble jackal
#

The Mushroom template cards generates it automatically

silent vector
#

Thank you. Much cleaner.

inner mesa
#

you should use the first one because friendly_name is not the recommended way to provide a name going forward

silent vector
#

Yep I used the first one.

paper hazel
#

I'm a bit stuck - I have a template, which returns the expected value, a single entity_id, but it returns it in brackets - ['zone.brooklyn']. I would like to compare this value with the trigger.id - E.g. {{trigger_zone == 'trigger_id' }}, but it returns False, even if the trigger_id is zone.brooklyn```
{% set trigger_zone = states.zone | selectattr('entity_id') |
selectattr('attributes.friendly_name', 'eq', 'Brooklyn') |
map(attribute='entity_id') | list %}

inner mesa
#

that looks broken to me

#

you can add |first to return the first item in the list (which is what those square brackets indicate), but I don't know what selecattr('entity_id') is doing there

paper hazel
#

It is returning a result when testing it - still new to this, so learning jinja little by little

inner mesa
#

you can see a proper use that function immediately after that one

#

what do you expect selectattr('entity_id') to do?

paper hazel
#

Spotted the selectattr('entity_id') too when I posted it, and removed it, and the result still looks good. It was added there in my lack of knowledge, thinking in terms of SQL... select THIS from This ๐Ÿ˜‚

inner mesa
#

it might have been confused and just passed the input straight through

#

anyway, if you only ever expect to have a single entity_id, just add |first

paper hazel
#

That solved it - Thank you so much! Been trying to figure it out myself now for over an hour....

marble jackal
#

selectattr('entity_id') will remove all with entity_id none or falsely which will never be needed here.
{{ [1, 'a', none, true, false, 0] | select() | list }}
result [1, 'a', true]

copper quail
#

Since it doesn't look like we can set the billing date to a specific day of the month โ€“ I'm looking at creating a few template sensors to figure out my billing rate.

Any ideas on creating a template sensor that is billing start date == billingStartDate โ€“ and then an event that fires on the 15th of every month (I have that piece already) to increment the month value by 1?

rocky crypt
#

Hello. I am wanting to assign entity_id by a state of a input_select. Here is what I have:

#

entity_id: >- {% if states('input_select.radio_speaker') in ['Study Speaker', 'All Speakers', 'Night Speakers'] %} media_player.study {% endif %} {% if states('input_select.radio_speaker') in ['Kitchen Speaker', 'All Speakers', 'Night Speakers'] %} media_player.kitchen {% endif %} {% if states('input_select.radio_speaker') in ['Bedroom'] %} media_player.bedroom {% endif %}

#

However, this isn't working as I would expect. I want it to basically add multiple speakers to the entitiy_id if you select "All Speakers", it will add the Study, Kitchen, and bedroom..

rocky crypt
#

Is this possible?

marble jackal
#

What part is not working, is it not working at all, or is the issue that it only uses one speaker even though All Speakers is selected?

rocky crypt
#

It's only using one speaker. It doesn't "Add" the values together.

marble jackal
#

That's because an if statement doesn't work like that, it will stop when one option is true

#

You will have to build it otherwise

#

Oh wait, you have separate if statements, that makes it even more unlikely to properly work.

rocky crypt
#

๐Ÿ˜ฆ

#

So, I would have to build it out saying if "All Speakers", then do speaker 1, speaker 2, speaker 3 etc....

#

and then use elif...

marble jackal
#

One minute

rocky crypt
#

Oh nice!

#

Ok, that looks good! Thank you! Let me give it a shot!

#

Thanks again! Learning as we go ๐Ÿ™‚

#

Thanks again @marble jackal Much appreciated!!

marble jackal
paper hazel
#

I'm trying to understand the difference, and what makes one better than the other. Any insight will be appreciated.```
{{ states('input_boolean.kitchen_security_gate_helper') == 'off' }}
vs.
{{ is_state('input_boolean.kitchen_security_gate_helper','off') }}

night bay
#

Hello, I need help in templates configuration...

silent barnBOT
night bay
#

When I try to configure my fan preset modes it gives me that error: "Platform error fan.mqtt_template - No module named 'custom_components.mqtt_template.fan'"

#

after adding it to the configuration.yaml

#

can anyone tell me how to add the preset modes?

marble jackal
night bay
#

Yes

marble jackal
marble jackal
paper hazel
marble jackal
#

No, states('light.foo') is preferred above states.light.foo.state

flint wing
#

Sorry for posting this here, but I can't find help in #installation-archived and I am trying to solve a rather simple problem. I'm running Home Assistant Supervised on Debian 11 Bullseye on a RPi4 Model B Quad Core 64 Bit WiFi Bluetooth (8GB). I recently realized my system was not supported and the reason is because of docker_configuration. The link provided is the following: https://www.home-assistant.io/more-info/unsupported/docker_configuration

The daemon.json is OK. Then the next correction that must be applied is the following:

To fix issues with the cgroup level, addjust the /etc/default/grub and add systemd.unified_cgroup_hierarchy=false to GRUB_CMDLINE_LINUX_DEFAULT and run sudo update-grub

I don't know how to proceed.... Any help would be appreciated. I'm sure expert-coders like you here know how to proceed. Thanks in advance!

silent seal
#

You need to ask in the #installation-archived channel. This channel is for creating templates such as sensor within Home Assistant

flint wing
silent seal
#

The chats arenโ€™t a forum. People donโ€™t tend to go back and search for older posts which havenโ€™t been answered. Try posting again in a while.

fast owl
#

I'm having troubles with this template trigger:

platform: template
value_template: >-
  {{ (as_timestamp(now()) -
  as_timestamp(states.sensor.meter_plus_humidity.last_changed)) / 60 > 4 }}

the template evaluates to true in Developer Tools right now, but doesn't trigger after > 1 min has passed

#

anyone know why it doesn't trigger?

inner mesa
#

isn't that looking for 4 minutes?

fast owl
#

yes but it evaluates to true right now because last_changed is pretty old

inner mesa
#

then it won't trigger

#

it needs to transition from false to true

#

that's how triggers work

marble jackal
random notch
#

Hi! I need help with a template sensor. Ive got the current energy price from Nord pool, and want to add VAT to the price and then further add tax and additional costs. As for now it is "unavailable" in home assistant. Any ideas what im diong wrong? https://pastebin.com/Hc5DYqmu

distant plover
#

I have a device with an attribute like this 22:22:22:22:22/10.0.0.55/Something,33:33:33:33:33/10.0.0.56/Something2, etc... How do I get the following in the markdown card? 1. Substitute / with a space and 2. Line break instead of comma

inner mesa
#

The first one is straightforward:
'22:22:22:22:22/10.0.0.55/Something,33:33:33:33:33/10.0.0.56/Something2'.replace('/', ' ')

#

The second depends on how the markdown card interprets linebreaks. Might be <br> or \n

#

but same tactic applies

marble jackal
#

And I think you also want to add some brackets around the values you are multiplying this state with

random notch
#

@marble jackal It is just multiplied with the first (1.25 , VAT)

#

Then the second and third number is added

#

Got it working! Thanks

#
      electricity_price_with_tax:
        value_template: "{{((states('sensor.nordpool_kwh_se3_sek_2_10_0') | float) * 1.25 + 0.263 + 0.45 ) | round(2)}}"
        friendly_name: "Electric price including tax"
        unit_of_measurement: "SEK/kWh"
marble jackal
random notch
#

Im not familiar with those, have been away from HA for some time. I guess I will have to take a look in the documentation tomorrow.

#

But thanks!

distant plover
inner mesa
#

what do you mean by "behind"?

#

it's already behind it

distant plover
#

mac address is first, then IP then name. I'd rather see MAC last

inner mesa
#

yes, with split()

#
{% set data = '22:22:22:22:22/10.0.0.55/Something,33:33:33:33:33/10.0.0.56/Something2'.split(',') %}
{% for item in data %}
  {%- set newlist = item.split('/') -%}
  {{ "%s %s %s" % (newlist[1], newlist[2], newlist[0]) }}
{% endfor %}
#

->

10.0.0.55 Something 22:22:22:22:22
10.0.0.56 Something2 33:33:33:33:33
distant plover
#

Thanks!

marsh hull
#

I give up. What is the incantation to add 2 (or 4 or 8) to a n "input_number" I can set the "input_number" to 1 with the code
- service: input_number.set_value
data:
value: 1
target:
entity_id: input_number.test_number
but how do I add 2 to it. I tried:
- service: input_number.set_value
data:
value_template: "{{('input_number.test_number')|int + 2}}"
target:
entity_id: input_number.test_number
but that doesn't do anything.

desert plover
#

what am I doing wrong with my template for a garage door opener
I want to use this cover template as a cover switch in my dashboard but the "close" button is always greyed out

https://pastebin.com/xDcmvinb

inner mesa
#

Did you read the link I posted?

#

Your template is wrong

desert plover
#

@inner mesa I guess you are talking to me now?

inner mesa
#

No

desert plover
#

damn ๐Ÿ˜„

marsh hull
#

@inner mesa is that your response to my question?

inner mesa
#

Yes, read the link I posted earlier

marsh hull
#

@ robc I just joined this thread. To which link do you refer?

#

@inner mesa I just joined this thread. To which link do you refer?

inner mesa
marsh hull
#

Please understand this @inner mesa , I'm new to this. I really don't want to be trying every key combination on the keyboard and sent down links I don't understand. I need a big hint here to help me on the way, like a hint of exactly how my code should look. I just tried:
value_template: "{{(states('input_number.test_number'))|int + 2}}"
and guess what, it got an error message when I tried to execute. I don't have a clue of why that is. That's why I'm here.

inner mesa
#

Start with the error message

#

I pointed to exactly the relevant section and you implemented what was there correctly, so ๐Ÿคท

marsh hull
#

error message stays on screen for about 2 seconds, something about "extra keys not allowed"

inner mesa
#

I'm not sure where you got value_template from. It's just value

marble jackal
desert plover
#

it wont switch anytime to open, it starts with closed but it doesn't get open

desert plover
marble jackal
#

Or reverse the actions

#

It could be your understanding of open and closed are the opposite of what HA thinks about it

marsh hull
#

@inner mesa Thank you for noting that. The line is now
value: '{{(states(''input_number.test_number''))|int + 2}}'
and it seems to work. Why the single quote around the whole thing? Why the double brace? Why two single quotes on either side of "input_number.test_number"? Why the "|int"? Where is the documentation that informs one on how to formulate a "template" If I understood these things it would be a lot easier.

silent barnBOT
inner mesa
#

there are three links in the channel topic that explain various parts of what Jinja is and how it works

marble jackal
#

There are also some more pinned posts in this channel

#

Which Rob also just said ๐Ÿ˜…

paper hazel
#

I'm trying to get a list of certain input_datetime entity_ids, but it keeps returning []. Still very new to these type of templates, trying to play around and learn. I do have quite a few input_datetime with 'reminder_service' in their entity_id. Figured it out```
{{ states.datetime | selectattr('entity_id', 'search', 'reminder_service') |list }}

sick ice
stuck dock
#

I have a two uptime sensor for a router and a modem, both report time in seconds, how can I create a sensor from those to report time in hours and mins?

#

Should just change the unit or create a new sensor?

#

I mean days hours mins sec

stuck dock
#

found some code

#
sensor:
  - platform: template
    sensors:
      esp_01_uptime_readable:
        friendly_name: "ESP 01 Uptime"
        value_template: >-
          {% set uptime = states.sensor.huawei_igd_uptime.state | int %}
          {% set days = (uptime / 86400) | int %}
          {%- if days > 0 -%}
            {{ days }} days, {{ (uptime - (days * 86400)) | int | timestamp_custom('%H:%M:%S', false) }}
          {%- else -%}
            {{ uptime | int | timestamp_custom('%H:%M:%S', false) }}
          {%- endif -%}
#

resulted in this

#
sensor:
  - platform: template
    sensors:
      esp_01_uptime_readable:
        friendly_name: "ESP 01 Uptime"
        value_template: >-
          
          4 days, 19:36:22
#

Is this code fine according to new formatting?

#

or this formatting is correct

#
template:
  - sensor:
      - name: "Huwarei Modem uptime"
        unit_of_measurement: "ยฐ%H:%M:%S"
        state: >
          {% set uptime = states.sensor.huawei_igd_uptime.state | int %}
          {% set days = (uptime / 86400) | int %}
          {%- if days > 0 -%}
            {{ days }} days, {{ (uptime - (days * 86400)) | int | timestamp_custom('%H:%M:%S', false) }}
          {%- else -%}
            {{ uptime | int | timestamp_custom('%H:%M:%S', false) }}
          {%- endif -%}
marble jackal
#

Both are correct, but the first one is the legacy format, and the last one is the new format

marble jackal
#

That topic seems to concern ESPHome config files, they don't use jinja

stuck dock
#

which provides this data

marble jackal
#

ah okay

stuck dock
#
Uptime Human Readable    7m 59s    
Uptime Sensor    479 s
marble jackal
marble jackal
#

The first one provides the time in seconds, but is only used in the ESP itself and not exposed to HA

#

The second one uses the first one to provide a timestamp at boot

marble jackal
#

Yes, ip provides eg 2022-08-05T04:58:40+00:00

#

As someone just commented that internal: true is not needed, I basically use the same config as was posted in that topic

#

You don't want a sensor providing the number of seconds sins uptime in your HA database

marble jackal
#

because it is creating a record in your database every second with unnecessary data. If you have the timestamp of the last boot, you can calculate it when you need it

distant plover
echo knot
#

Is there a way to get the caller of my script inside the script so that I can make something else happen for different people

#

Like I know that we get parent IDs but how do I get the parent name from the id

marble jackal
# distant plover Final question: How do I sort by the IP? :)```{% set data = state_attr('sensor.r...
{% set data = '22:22:22:22:22/10.0.0.55/Something,33:33:33:33:33/10.0.0.41/Something2'.split(',') %}
{% set ns = namespace(values=[]) %}
{% for item in data %}
  {%- set newlist = item.split('/') -%}
  {% set ns.values = ns.values + [ dict(ip=newlist[1], s=newlist[2], m=newlist[0]) ] %}
{% endfor %}

{% for item in ns.values | sort(attribute='ip') %}
  {{ "%s %s %s" % (item.ip  , item.s, item.m) }} 
{% endfor %}
marble jackal
distant plover
marble jackal
echo knot
#

But how do I convert the ID to a context

#

Since I only get id of the parent context

marble jackal
# distant plover Cool. Possible to have IP 10.0.0.20 before 10.0.0.100 in the sorting as well? ๐Ÿ˜†
{% set data = '22:22:22:22:22/10.0.0.100/Something,33:33:33:33:33/10.0.0.14/Something2'.split(',') %}
{% set ns = namespace(values=[]) %}
{% for item in data %}
  {%- set newlist = item.split('/') -%}
  {% set ns.values = ns.values + [ dict(ip=newlist[1], s=newlist[2], m=newlist[0], ip_sort=newlist[1].split('.') | last | int) ] %}
{% endfor %}

{% for item in ns.values | sort(attribute='ip_sort') %}
  {{ "%s %s %s" % (item.ip  , item.s, item.m) }} 
{% endfor %}
marble jackal
echo knot
#

No problem, I'll try to explain itbetter

marble jackal
#

the user_id is passed through, if a button press, or a input_boolean toggle activates a script or automation, the context is passed through

#

so the button and the script will both have the context.user_id

echo knot
#

So I have a script which when ran give me a context I want to know which phone called the script, so I want to read the parent id of the script to see which automation called the script

#

Because I know that the context.parent_id is a context_id but I would Ike to get the original context from it not just the id

marble jackal
#

Please explain in more detail, and step by step. A phone doesn't do anything, so I assume you are referring to the user holding the phone
Example:

  • user toggles an input boolean on his/her phone
  • automation is triggered by the input_boolean state change
  • script is triggered by the automation
#

and then you want to know the user who toggled the input_boolean?

echo knot
#
  • user presses a widget on their phone
    -widget calls script which asks if they are sure
    -once sure the script calls another which opens the garage
    .

Separate from this
-automation checks if the gara has been open for X amount of time
-if yes sends notification
"Garage has been open for X amount of time, opened by {{template stuff}}"
That last part is the one im struggling with

marble jackal
#

Well, I'm not sure if you can, but if you can, I don't know how to do that ๐Ÿ™‚ I tried with a button calling an automation which calls a script, and I don't see way to link them

echo knot
#

Thanks for the help anyway

#

๐Ÿ˜ƒ

marble jackal
#

oh wait

#

the script parent_id is the same as the button id

#

so there is a link, however, the automation doesn't have a parent_id

#

@echo knot what does the widget do?

#

does it immediately call the first script?

echo knot
#

Yes it does

marble jackal
#

I think it would be easiest to create a template sensor which stores the last person who opened the garage

#

by using the context.user_id of the the script opening the garage

pastel moon
#

I use this condition in a script; ```

  • condition: template
    value_template: "{{ states.light
    | selectattr('state', 'eq', 'on')
    | rejectattr('entity_id', 'in', ['light.bathroom_roof', 'light.closet_ct'])
    | map(attribute='entity_id') | list | length > 0}}"```
    How can I conditionally 'rejctattr' light.hallway only if a variable (trigger_id) is set to "xyz"?
marble jackal
#

few other comments

  1. best to use the multi line format if you format your template in multiple lines ๐Ÿ˜›
  2. you don't need to map the entity_ids if you are only going to count them
pastel moon
wispy crown
#

hi