#templates-archived

1 messages · Page 159 of 1

inner mesa
#

what's the output of that?

#

mdi:account-group?

floral shuttle
#

tadah..... you are completely right!

#

it should have been account-multiple-check currently....

inner mesa
#

so it's just saying that the key isn't there, and you're getting the default you specified

floral shuttle
#

adding the int makes that happen 😉

#

exactly

#

thx!

#

have another challenge....

#

using the new This variable, I can not get it to work in an availability template

#

consider: attributes: id: mijn_mobiel availability: > {% set x = ['unavailable','unknown'] %} {{states('sensor.mijn_mobiel_connection_type') not in x and states('sensor.mijn_mobiel_ssid') not in x}}

#

which is the verbose template, and now use it with the this variable attributes: id: mijn_mobiel availability: > {% set x = ['unavailable','unknown'] %} {{states('sensor.' ~ this.attributes.get('id','Not yet set') ~ '_connection_type') not in x and states('sensor.' ~ this.attributes.get('id','Not yet set') ~ '_ssid') not in x}}

#

the replacement works fine in all other spots in the rest of that same template sensor, just not in the availability template

#

example: - unique_id: map_connection_mijn_mobiel name: > Mijn Mobiel: {{states('sensor.' ~ this.attributes.get('id','Not yet set') ~ '_connection_type')}} - {{states('sensor.' ~ this.attributes.get('id','Not yet set') ~ '_ssid')|replace('_',' ')}} icon: > {% if states('sensor.' ~ this.attributes.get('id','Not yet set') ~ '_ssid') != 'Not Connected' %} mdi:router-wireless {% else %} mdi:wifi-off {% endif %}

inner mesa
#

could be. the availability template determines whether the state is even evaluated, and could also impact whether the variables are set

floral shuttle
#

I see. so this might actually be an unexpected result of a correct template.... preventing the full template to be even set. guess I need to ask Erik to have a look at that then.

inner mesa
#

it could be a completely consistent and expected result

floral shuttle
#

yeah, thats what I meant.... technically speaking that is. In real life it is blocking a correct template

inner mesa
#

since the availability template determines whether the template is evaluated at all

floral shuttle
#

thx Rob, have to get some sleep now, will take it to next week 😉

atomic blade
#

I'm really struggling with a lot of entities reporting unknown, particularly after restart. I've tried a few things like making a separate template that does something like this, but it just isn't working:

{% if is_state('sensor.original', 'unknown') %}
  {{ states('sensor.masking') }}
{% else %}
  {{ states('sensor.original') }}
{% endif %}

Does anyone have other tricks to prevent this? Can the new this var in templates help?

forest pumice
#

So it only updates if it is not unknown.

#

The rest is just sanity checking, because sometimes the radio picks up something wrong.

fossil venture
#

What about the unavailable or none states? A better test would be {% if not states('sensor.gas_meter')|is_number %} Also your first line will generate errors and (in a future release) stop the template from rendering if the value is non numeric. You need to supply a default, or check that the value is a number before attempting to apply the float filter.

#

Maybe this:```
{% if value|is_number %}
{% set ft3 = (value | float) / 100 %}
{% if (ft3 != 0) and (ft3 < 5) %}
{{ ft3 }}
{% elif (ft3 == 0) or ((((states('sensor.gas_meter') | float ) - ft3) | abs) > 100) %}
{{ states('sensor.gas_meter') }}
{% else %}
{{ ft3 }}
{% endif %}
{% else %}
{{ ft3 }}
{% endif %}

peak juniper
#

Can anyone point me in the right direction for putting my calendar date in a more palatable date format?

#

For example, it is stored as a state attribute:

start_time: 2022-06-12 09:00:00
#

how can I get that to display as something like "June 12th at 9am" or something similar?

deep marsh
#

Not sure if this is the correct channel, but how can I identify an entity which is part of a group and in that group it is set to not hide the individual entities in HA?

Basically: how can I identify a hidden entity? I do not see an attribute that stores this.

My use case is that I do not want to show hidden entities in the lovelace-auto-entities integration from Thomas Loven.

inner mesa
#

You can't, unfortunately

balmy wedge
#

I want to show when my washing machine is running - I have an automation that runs when it turns on or off, based on power usage. I'm thinking of using a toggle helper, switch it on/off using the automation, and using a template binary sensor to show the state in the frontend. Is there an easier way?

#

So my binary_sensor template would be {{ states.input_boolean.washing_machine.state }}

inner mesa
#

Why not just use a a template binary_sensor itself based on the power usage?

#

What does the automaton do for you?

balmy wedge
#

Ah, the automation has hysteresis to avoid false positives/negatives

#

And I expect to have to tune it, so why not have the variables in one place

inner mesa
#

Ok

balmy wedge
#

That warning is useful, thanks!

atomic blade
forest pumice
#

For some reason pulling sensor.original affects the value that is set. Saying only update if not unknown worked better for me.

atomic blade
forest pumice
#

Also, you don't need another storage for old or current if you only update the sensor if not unknown.

#

🤷‍♂️ Works for me. I tried your method prior to settling on what I'm using there.

atomic blade
#

Or does it set it to empty string?

forest pumice
#

Possibly the latter, but unknown doesn't make it through.

#

I suppose I should try stripping out the final {{ ft3 }} in a test sensor and see what happens.

atomic blade
#

I'm particularly looking to keep it at the old value/not set it when the template is evaluated

scarlet sapphire
#

Hello, I am again too stupid for this and request a hint. For my template rest switches I would like to add an icon per on/off state but I am lost where to add it.
I use rest sensors for the state as in

  - platform: rest
    name: lights_endpoint
        json_attributes:
    - item0
    - item1
#

and switches´

switch:
- platform: template
  switches:
    gaestezimmer_licht:
      value_template: "{{ state_attr('sensor.lights_endpoint', 'item0').sumstate.value.split(';')[0] == '1' }}"
      unique_id: gaestezimmer_licht
      turn_on:
      turn_off:
#

where do I enter the icon defition? to the sensor? to the switch? to the template defition or each entity?

inner mesa
#

To the thing you want the icon to apply to. Is that the template switch?

scarlet sapphire
#

yes

inner mesa
#

Then there

scarlet sapphire
#

and I add it to each light?

inner mesa
#

The template switch

scarlet sapphire
#

sorry I was unclear

#

do I add it to each entity under the template switch

#

or once for all entities

inner mesa
#

Each is separate

#

Nothing applies once for all

scarlet sapphire
inner mesa
#

It's not

scarlet sapphire
#

template:

  • binary_sensor:
    • name: Sun Up
      state: >
      {{ is_state("sun.sun", "above_horizon") }}
      icon: >
      {% if is_state("binary_sensor.sun_up", "on") %}
      mdi:weather-sunset-up
      {% else %}
      mdi:weather-sunset-down
      {% endif %}
#

this is from the example page

inner mesa
#

That's a binary sensor

scarlet sapphire
#

and what I am trying to adapt

inner mesa
#

You have a template switch

scarlet sapphire
#

that is correct

inner mesa
#

Use the right docs

scarlet sapphire
#

thanks, I will try this.

#

I am happy to work with the right docs, it's hard to identify the correct ones though, at least for me. thank you very much for this pointer!

#

can I use icon color in this syntax or how do I differentiate lamp on / lamp off icons?

inner mesa
#

You can only specify icons

scarlet sapphire
#

I must misunderstand how todo this the best practice way I guess

inner mesa
#

The logic above that you incorrectly put under icon: is fine

atomic blade
scarlet sapphire
inner mesa
#

Maybe

scarlet sapphire
#

thank you. I read a thread that there is no way to know which of those icons can be used in HA, is this true and I trial and error?

nocturne chasm
#

I have never found one that can’t be used in HAss. That is prob an old thread.

scarlet sapphire
#

great to know, thank you very much

inner mesa
#

They're adding and changing icons regularly, so you have available whatever version is in the HA release you're using

scarlet sapphire
#

ok, thank you

#

thanks for the details and your patience with me

scarlet sapphire
#

ok, I got it working for the off state, it grabs the correct, icon, thanks. For the on state, I am not sure what to turn it to. I use value_template: "{{ state_attr('sensor.lights_endpoint', 'item8').sumstate.value.split(';')[0] == '1' }}" for the switch do determine on/off state, I tried to just grab the state of that switch entity but that didn't work. I tried also to include the same as in the value_template but that didn't work as well. what would be the correct approach?

#

so I was trying to use {% if is_state("switch.entityname", "on"

#

hah, i got it working with just the entity name!

orchid oxide
#

I thought this was front end for some reason

floral shuttle
#

got myself into a type issue once more.... considering https://www.home-assistant.io/integrations/zone/#state and eg states('zone.home') in the template dev tools says it's a number. yet - unique_id: family_home_united name: Family home united state: > {{states('zone.home') == '6'}} needs the number to be a string (or the |int filter on the state ) for the comparison to be correct... maybe a small edit on that page is in order?

inner mesa
#

Again, states are always strings.

#

You keep thinking that is_number returns the type, and it does not

#

It only indicates whether the input value can be evaluated as a number, not that it is an int or float type

#

I really hope that's clear

#

You Jerrold getting confused about exactly the same thing

floral shuttle
#

yeah, I realize that. I was thinking it could be confusing to many others, so a note with what you say above would be enlightning

#

don't you agree though that when the editor explicitly returns 'Result type: number', a test is number would be expected to be True? I know it doesn't, and understand what you say. Yet what good does it do to state its a number, when it can not be used as a number type.

inner mesa
#
{{ 5.0 is float }}
{{ '5.0' is float }}
{{ states('input_number.test') is float }}
{{ states('input_number.test') is string }}
{{ states('input_number.test') }}
True
False
False
True
1.0
floral shuttle
#

yep. and the editor shows Result type: number on those strings {{ states('input_number.test')}} 😉

inner mesa
#

Because they can be evaluated as numbers? shrug

#

I have been confused by that part and just ignore it

#

It's meaningless if you have more than one thing there

floral shuttle
#

well, they cant can they? we need to explicitly cast them to |int before they can be evaluated as numbers

inner mesa
#

No, they can be evaluated as numbers, where 'foo' cannot

#

Are a number type and can be evaluated as a number are not the same thing

floral shuttle
#

I guess I dont understand that after all then 😉 . All I am saying is I 'know' the output of any template is a string. And that we need to either quote the numbers (to make them strings) or cast the template to |int.

inner mesa
#

Going to bed

floral shuttle
#

But 'TypeError: '<' not supported between instances of 'str' and 'int' tells us they can not be evaluated as numbers...

#

goodnight!

marble jackal
#

@floral shuttle it a matter of definition and interpretation, and I agree it can ben confusing. '5.5' CAN be evaluated as a number, but it IS NOT a number (and in that sense the naming of the is_number filter is confusing). It IS as string.
And you can not compare strings to numbers, even if the string only contains a numeric value.

floral shuttle
#

sure. guess what I am looking for is what does 'CAN be evaluated as a number' really mean. where/how can it be evaluated as number? not in a template. In a numeric trigger probably.?

marble jackal
#

You can use strings in a numeric_state trigger, actually, the GUI puts quotes arond it. But in a template for a string to be treated as a number, you need to cast it either to int or float

marble lily
#

I have a ESP32 bluetooth-gateway for some sensors connected with api to ha. When the esp32 it's offline all the sensors are unavailable, how can I keep the last value until it's back online?

marble jackal
#

Store it in a trigger based template sensor

mighty ledge
#

Everything in a template is executed as you see it. The result is always a string and that string is then thrown through a typing resolver. That’s when it gets assigned a type for the field the template is in. So if the returned value resolves to a number a number will be used. If it resolves to a list, a list will be used.

#

Do not confuse is_number with the ending result. Is_number purely checks to see if you can use int or float inside the template to covert your value to a number so you can use it as a number later inside the template. Float or int have no impact on the ending result type that’s resolved after the template is evaluated

marble lily
#
{% if states('sensor.bedroom_battery_level') in ["unknown", "unavailable"] %}
{{states('sensor.bedroom_battery_level_fix')}}
{% else %}
{{states('sensor.bedroom_battery_level')}}
{% endif %}
#

what i'm doing wrong to keep the value on reboot for a ESP32?

marble jackal
#

What is the current state of the source sensor?

marble lily
#

online - 72% batttery

marble jackal
#

okay, so does it work in devtools > templates?

marble lily
#

nope, there's something I miss

marble jackal
#

What does this return in devtools >templates {{states('sensor.bedroom_battery_level')}}

marble lily
#

right now unknown, i just reboot the esp32

#

73 value

#

if I restart the esp32, all values goes unavailable or unknown.

marble jackal
#

Does this work?

{% if states('sensor.bedroom_battery_level') | is_number %}
  {{states('sensor.bedroom_battery_level')}}
{% else %}
  {{states('sensor.bedroom_battery_level_fix')}}
{% endif %}
marble lily
#

on reboot it's the same thing. I don't understand where the _fix should get the value

marble jackal
#

On reboot both are probably unavailable

marble lily
#

on reboot of esp32 I mean.

marble jackal
#

Do you already have a working template sensor?

#

called sensor.bedroom_battery_level_fix

marble lily
#

yes, I tried before writing here

#

should I remove it ?

marble jackal
#

No, what is the state now?

#

of the template sensor

marble lily
#

72

marble jackal
#

.share the complete template sensor

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 lily
#

now it keep the value on esp32 reboot

marble jackal
#

I would make it a trigger based template sensor, as of 2022.5 they keep their state after a reboot, so after HA reboot you will also have a state even if your ESP is not available

marble lily
#

can you explain a bit? I want to make an thermostat for this and I want to keep the value on all restarts

marble jackal
#

But you need to use the new template format then, not the legacy format as you are using now

marble lily
#

and the trigger to be when esp32 it's disconnected? I don't know if I understand the trigger based sensor

marble jackal
#

This will trigger on changes of the battery sensor, and then it will update the state of the template sensor

#

sorry, indentation is off

#

with extra dynamic icon based on the battery percentage

marble lily
#

and I need to remove the old sensor template yes?

marble jackal
#

Yes

marble jackal
marble lily
#

and where should I add the block code? I tried on sensor folder and it says missing property sensors

marble jackal
#

I explicitly mentioned that in the first link (but not in the corrected version)
It is part of the template integration, not the sensor integration.
Add it in configuration.yaml, or create a similar include and folder for the template integration like you have now for the sensor integration

floral shuttle
#

@mighty ledge thx. I note: It’s a pre check you can use to verify that you can change the type without default being used.

mighty ledge
#

yes

#

that's one use

marble jackal
#

I also use it a lot in availlibility templates

mighty ledge
#

Yep

#

that's my main usecase for it

#

and to filter states before casting all the states to a float

#

selectattr('state', 'is_number')

marble lily
#

in that folder I made a file bluetooth-gateway.yaml

#

and it's telling me property template is not allowed

marble jackal
#

Remove the first line with template: and use a different include type, as the template integration expects a list and not a dict

marble lily
#

was missing a - in the line with name

#

@marble jackal thank you so much for your help. It's working now.

blazing echo
#

Looking for some help on an if value is in a range condition...

{% if states('sensor.energy_monitor_electricity_meter') | int < 500 %}
green
{% elif states('sensor.energy_monitor_electricity_meter') | int >= 500 and < 1000 %}
orange
{% else %}
red
{% endif %}

I understand I could just swap the elif and else around in this example, but I also want to use same template for a different thing with 4 options so it'd help if I can understand a way to check if its in a range? In this example above the and < 1000 is not permitted, but i hope it shows what I'm after?

mighty ledge
#

what's the problem...

#

oh, nm

#

{% elif 500 <= states('sensor.energy_monitor_electricity_meter') | int < 1000 %}

blazing echo
#

ah that makes perfect sense! Thanks so much!

mighty ledge
#

but technically you dont need that

#

you can have

#

{% elif states('sensor.energy_monitor_electricity_meter') | int < 1000 %}

#

and it will still work.

#

because the green will always catch less than 500, the elif will always catch whats between 500 and 1000

blazing echo
#

oh really, learnt two new things here then. I always assumed it had to only match one condition, not sure why but it does make sense that it stops once its matched one. Thanks so much @mighty ledge

mighty ledge
#

if -> elif - else will always only have 1 resulting path.

#

regardless how many elif's there are

blazing echo
#

I now wonder how many templates I've made overly complicated due to this misunderstanding...!! Does the if statement work like this in all languages? jinja2 templating is the closest ive ever come to python or any other language.

blazing echo
#

really interesting! Not that I'm planning to learn to code any time soon. A bit of ha templating and yaml is enough for me!

hard garnet
#

I know how to grab the timestamp for a sensor's last change, but how do I get it for the last time a sensor changed to a specific state?

inner mesa
#

You would either need to create a trigger-based template sensor that returns the current time when your condition is met, or use an SQL sensor to search the database

hard garnet
#

yikes

inner mesa
#

The first is easy

hard garnet
#

so something like "if [binary sensor] goes to 'off', set sensor to [current time]" ?

inner mesa
#

If 'binary_sensor turns off' is the thing you care about

torn meteor
#

I think none actually worked for me (wasn't sure if it needed to be capitalized or not None), however I ended up changing the wait_for_trigger to a wait_until with a condition for # of loops, followed by a stop action.

marble jackal
#

Also fine, good that you got it working!

torn meteor
#

(so none or None - either work in general?)

inner mesa
#

I always use none, and that's clear here:

{{ state_attr('sensor.foobar', 'blah') }}
{{ state_attr('sensor.foobar', 'blah') is none }}

->

None
True
{{ state_attr('sensor.foobar', 'blah') is None }}

->

TemplateAssertionError: No test named 'None'.
#

it's confusing because what it displays and what you need to compare against aren't the same, both for None and True/False

#

and sometimes devtools -> Templates also says "null" where again "none" should be used for comparison

torn meteor
#

yeah. always confused about that. seems safer to use lowercase then?

inner mesa
#

not just safer, but required

torn meteor
#

i've also had issues when testing boolean attributes in an automation. 1 is determining if the entity attribute is actually a string or a boolean, and 2, if i type "true" in the UI, it becomes a string when i save it. I have to edit in YAML mode and remove the auto-added quotation marks

inner mesa
#

but in general, you want lowercase

#

yes, there's an open issue for that

torn meteor
#

cool.

stuck dock
#
  - sensor:
      - name: Tariff Price
        unit_of_measurement: Pkr/kWh
        state: >
            {% if is_state('utility_meter.daily_energy', 'offPeak') %}
                {{ 18.010 }}
            {% elif is_state('utility_meter.daily_energy', 'Peak') %}
                {{ 24 }}
            {% else %}
                {{ 24 }}
            {% endif %}
#

is this sensor correct?

#

peak rate is Pkr 24 and off-peak rate is 18

#

ran this in devtools ->templates ```
template:

  • sensor:
    • name: Tariff Price
      unit_of_measurement: Pkr/kWh
      state: >

          24
      
#

current time is in peak hours

marble jackal
#

You don't need to put those curly brackets around the numbers

#

And you also don't need the elif

gritty sentinel
#

Hello! I have a sensor template that tries to return a 2-element list. Basically, simplifying it to remove templating, I want to do: state: [1,1] But the automation code that reads that sensor using the states function in a {{ template }} doesn’t recognize it as a list with elements 0 and 1. Is a sensor template able to have a state that is a list?

proud ridge
#

Hey, I'm writing a blueprint for a 4 button remote, after inspecting zigbee events, for long press there are two events 'start' and 'stop', I have found existing blueprints that I can copy but they are for remotes that constantly emit 'hold' event, does anyone know of a blueprint that I can modify for my situation (with some sort of a 'start' and 'stop' event)

stuck dock
# marble jackal And you also don't need the `elif`
  - sensor:
      - name: Tariff Price
        unique_id: 'Lesco_Tariff' 
        unit_of_measurement: Pkr/kWh
        state: >
            {% if is_state('utility_meter.daily_energy', 'offpeak') %}
                {{ 18.010 }}
            {% if is_state('utility_meter.daily_energy', 'Peak') %}
                24.330
            {% else %}
                24.330
            {% endif %}
#

like this?

#

resulted in ```
TemplateSyntaxError: Unexpected end of template. Jinja was looking for the following tags: 'elif' or 'else' or 'endif'. The innermost block that needs to be closed is 'if'.

marble jackal
#

No, like this:

        state: >
            {% if is_state('utility_meter.daily_energy', 'offpeak') %}
               18.010
            {% else %}
                24.330
            {% endif %}
mighty ledge
stuck dock
marble jackal
#

Yes, you could even shorten it to this though:

template:
  - sensor:
      - name: Tariff Price
        unit_of_measurement: Pkr/kWh
        state: >
          {{ 18.010 if is_state('utility_meter.daily_energy', 'offpeak') else 24.330 }}
gritty sentinel
marble jackal
marble jackal
#

👍🏼

stuck dock
#

checked in devtools -->templates

#
  - sensor:
      - name: Tariff Price
        unit_of_measurement: Pkr/kWh
        state: >
          18.01
#
      - name: Tariff Price
        unique_id: 'Lesco_Tariff' 
        unit_of_measurement: Pkr/kWh
        state: >
          {{ 18.010 if is_state('utility_meter.daily_energy', 'offpeak') else 24.330 }}
``` I modified it to add unique id
stuck dock
#

I created another sensor to calculate the cost of plug energy usage ```template:

  • sensor:
    • name: MP off-peak cost
      unit_of_measurement: Pkr
      value_template: "{{ (states('sensor.mobile_plug_daily_usage') | float * 18.010 ) | round(2) }}"
      friendly_name: Today's Offpeak Tariff Cost
marble jackal
#

No unique_id there? And you might also want to add an availability template there, to avoid it going to 0 when your source sensor is unavailable (and somewhere in the future it will run in error)

stuck dock
#

is this fine?

marble jackal
#

No, you are mixing the new and legacy format now

#

value_template should be state, friendly_name should be removed, that is set after name already

#

And for your availability template you can use {{ states('sensor.your_sensor') | is_number }}

stuck dock
#
template:
  - sensor:
      - name: MP off-peak cost 
        unit_of_measurement: 'Pkr'
        device_class: monetary
        unique_id: 'MP_offpeak_cost'
        state: "{{ (states('sensor.mobile_plug_daily_usage') | float * 18.010 ) | round(2) }}"
        availability: >
          {{ states('sensor.mobile_plug_daily_usage') not in [ 'unknown', 'unavailable', 'none' ]}}
stuck dock
marble jackal
#

Yes

#

And please stop posting the entire template sensor for each check, it is filling up the entire channel

#

Just put it in your config and try it out 👍🏼

stuck dock
#

sorry I think I should create a thread of

woeful spruce
#

Hello all,
I need a quick help with my sensor.
I need a sensor for Magic Areas that goes on at < 5 for example.
I have it, but after a few seconds it jumps back to off as soon as the light is on.
I have also searched, but so far nothing suitable found in the templates :/ can you help me? Maybe one or the other also uses Magic Areas?

#

So is how my Sensor currently Looks:

  • binary_sensor:
    • name: Dark Schlafzimmer
      unique_id: dark_schlafzimmer
      icon: mdi:brightness-6
      state: >
      {{ states('sensor.bewegungsmelder_schlafzimmer_illuminance')|float < 6 }}
marble jackal
#

No idea what magic areas are, but as soon as you turn on a light in a room, the illuminance will increase, so your template will evaluate to false

woeful spruce
#

That is exactly my problem, the sensor should not update immediately but e.g. every 15 minutes.
Is that possible somehow?

inner mesa
#

delay_off:?

#

but generally, using illuminance to manage a light where the sensor is next to the light is going to be problematic

marble jackal
#

Or a trigger based sensor based on a time pattern

inner mesa
#

Still curious what the heck a "Magic Area" is. Sounds like a Room of Requirement

latent cypress
#

Could anyone help me figure out what I'm doing wrong with this template? It is working in Dev Tools -> Template Editor, but it doesn't seem to work as a trigger:

value_template: >-
  "{% if states('sensor.dryer_4_1min') | float >= 500 or
  states('sensor.dryer_3_1min') | float >= 500 %} true {% endif %}"
for: '00:00:30'
id: dryer_started```
And here is what my template editor looks like where it works:
```{% if states('sensor.dryer_4_1min') | float >= 500 or
  states('sensor.dryer_3_1min') | float >= 500 %}
  Dryer running
{%- else -%}
  Dryer not running
{%- endif %}```
Thanks in advance!
inner mesa
#

a) don't use quotes around multiline templates

#

b) it could be simpler:
{{ states('sensor.dryer_4_1min') | float >= 500 or states('sensor.dryer_3_1min') | float >= 500 }}

#

c) since you didn't have an "else" , it would just return nothing if it wasn't true

latent cypress
#

ahhh gotcha, thanks I'll make some modifications and see if it works!

#

Thanks for the help RobC, it's working now!

vestal aspen
#

how do i convert absolute seconds to mm:ss

- name: intremain
      value_template: "{{ value_json.intermissionInfo.intermissionTimeRemaining / 60 | int }}"
inner mesa
#

Simple math

vestal aspen
#

well up there gives me the proper minutes but how do i format it?

inner mesa
#

"{{ xxx }}:{{ yyy }}"

#

Or...{{ xxx ~ ':' ~ yyy }}

native sparrow
#

I'm checking power usage to create a sensor with the state of my dumb video projector - on, off or transition. Rather than "transition" I would like show "starting up" or "shutting down" based on the previous state of on or off. Any tips?

  - sensor:
      - name: "Projector State"
        state: >
          {% if (states('sensor.projector_checker_current_consumption') | int < 1) %} off
          {% elif (states('sensor.projector_checker_current_consumption') | int > 260) %} on
          {% else %} transition
          {% endif %}
marble jackal
marble jackal
amber oxide
#

Hey y'all...I've just started wanting to use a sensors.yaml file for sensors (I'm new to adding sensors in yaml). However, whenever I add a sensor in that new yaml file (I have it !included in config.yaml correctly) I get issues like: 'Missing property "state"' and 'Property scan_interval is not allowed.'

#

Why is this?

native sparrow
marble jackal
#

this.get('state') does the same as this.state, but this.state will run in error in case there is no state yet (so after reboot or template reload) and this.get('state') is forgiving, so it will just return none.
But it could be that the entire this object is missing after a reload. Maybe try this:

          {% if states('sensor.projector_checker_current_consumption') | int < 1 %}
            off
          {% elif states('sensor.projector_checker_current_consumption') | int > 260 %}
            on
          {% elif this is undefined or this.state is undefined %}
            unknown
          {% elif this.state == 'on' %}
            shutting down
          {% else %}
            starting up
          {% endif %}```
marble jackal
silent barnBOT
#

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

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

native sparrow
marble jackal
amber oxide
#

It's for a sensor that shows how many lights I have on + a sensor for monitoring my system + a sensor for a custom card for my dashboard to show available HA updates and current version etc

marble jackal
#

indentation of line 8 to 25 is wrong

amber oxide
#

What is the correct indentation?

marble jackal
#

And it seems like you are mixing the the sensor and template integration here

#

how did you include this file from your configuration.yaml?

amber oxide
#

Erm yeah it was suggested by someone else for me to use template: !include sensors.yaml in my config.yaml

marble jackal
#

well, only the first sensor is part of the template integration

#

there is also sensor integration, and a binary_sensor integration

#

They can not be mixed in one file (unless you are using packages)

amber oxide
#

Ohhh right

#

That makes sense 😄

#

Sooo I need to make different files for each type of sensor?

marble jackal
#

lines 67 and 106 are template binary_sensors which are written in the legacy format, and could be rewritten so they will work in this file

#

lines 7 to 65 are not template sensors, but sensors using a specific platform, and should end up in a different file

amber oxide
#

Right okay, yeah I am unsure how to re-write em

marble jackal
#

and if you are at least on 2022.4 you could remove those command line sensors, and create template sensors based on the update entities

amber oxide
#

Ok! So if I work that out (is it very hard? I am somewhat new to HA) the binary sensor I have in there rn will work

marble jackal
#

You could also use this format, but then you would need to create a separate file for this as well

#

configuration.yaml

template: !include template.yaml
sensor: !include sensor.yaml
binary_sensor: !include binary_sensor.yaml
amber oxide
#

I am very tempted just to do that because it's easier haha

#

How long would it take to re-do the sensors if I've never done it before/currently have zero clue how to? Probably a while or?

marble jackal
#

I'm also wondering what you are trying to achieve with these sensors.

amber oxide
#

Tbh for now because it's quicker and easier I'll just pop em on separate files

marble jackal
#

There is an update entity for core, os and supervisor, and also for all the add-ons

#

Why reinvent the wheel

amber oxide
#

Should probs have asked the question regarding that sensor in the Discord server for Minimalist UI 😅

marble jackal
#

Well, I would not advice to start using Minimalist when you are saying you are just a beginner

amber oxide
#

Haha yeah that makes a lot of sense...but I've already spent the past month learning how to make it all work and I actually have a fairly expansive dashboard working right now. I am finding it worth the effort learning it all 😄

marble jackal
#

I'm away from keyboard for now

amber oxide
#

No worries, thanks for your help!

plush wolf
#

I have one question with regards to templates (I believe - might be wrong category if I think about this the wrong way). I have a Synology surveillance station which has the "Home Mode" function, which is set-up to trigger recording or not of cameras. So far so good. I can see the Home Mode switch in HA and its state under DevTools. I now would like to have an input boolean that monitors this - not change it. The boolean is not supposed to be a button but just turn on when the state changes (or off). Trigger for the boolean therefore would be a state change, but how do I monitor this? A template sensor? Would someone have an example?

mighty ledge
#

(you don't need the icon template)

native sparrow
#

Transition state of projector

plush wolf
mighty ledge
#

that's the point of the binary_sensor

#

i.e. you now have a 'binary sensor' that is in sync with your switch and you can't turn it on or off

plush wolf
#

I knew there was a logic mistake in my attempts! Thanks a lot, works perfectly

pastel moon
#

Hi, why does this return zero (0) matches? Is there a better way of finding a substring in a string? {% set t = 'motion' %} {{ t|select('search', 'motion') |list|length }}

#

this is from a test in dev-tools. t is normally a variable I want to parse

inner mesa
#

Use ['motion']

#

It's going letter by letter

pastel moon
#

oh, in the select statement?

inner mesa
#

Yes. It's iterating through the string

pastel moon
#

{{ t|select('search', ['motion']) |list|length }} gives me a TypeError: unhashable type: 'list'...

inner mesa
#

No

#

Reread my post

#

t is a string and needs to be a list

hollow wedge
#

I have a stupid jinja problem. Jinja figures into most of my problems.
Trying to do an automation wherein telegram notifies me of which timer has finished. Telegram works fine. The reference to the entity_id of the timer that went off does not:

`alias: New Automation
description: ''
trigger:

  • platform: event
    event_type: timer.finished
    condition: []
    action:
  • service: telegram_bot.send_message
    data_template:
    message: hi {{ trigger.entity_id }}
    mode: single
    Also tried trigger.event.data.entity_id `, which is what the documentation has suggested would be the correct answer.
pastel moon
hollow wedge
#

Update. This works:
` alias: New Automation
description: ''
trigger:

  • platform: event
    event_type: timer.finished
    condition: []
    action:
  • service: telegram_bot.send_message
    data:
    message: reowr {{ trigger.event.data.entity_id }}
    mode: single
    `
hollow wedge
#

This also works:
`alias: New Automation
description: ''
trigger:

  • platform: event
    event_type: timer.finished
    condition: []
    action:
  • service: telegram_bot.send_message
    data_template:
    message: reowr {{ trigger.event.data.entity_id.split('.')[1].replace('_', ' ') }}
    mode: single
    `
#

I suspect that the virtual keyboard I was using on my smartphone threw an invalid character.

mighty ledge
#

Uh and discord just updated and showed me you already figured it out

tiny ivy
#

Hi, how do I encode double quotes in a value template so that they are not converted to single quotes?

  value_template: >-
    {{
      { 
        "ping": value_json.ping.latency, 
        "download": value_json.download.bandwidth, 
        "upload": value_json.upload.bandwidth 
      }
    }}

Get's converted to 'ping':... that fails to be json parsed.

vestal aspen
dreamy sinew
tiny ivy
#

Thx

stuck remnant
#
      - name: "Bathroom motion"
        delay_off: "00:00:30"
        state: >
          {{ states('sensor.samsung_j3_ipcam_motion')|float > 0 }}```
trying to make this turn on whenever there's a state change regardless of value not just above 0
#

anyone know how?

marble jackal
#

This will trigger on every state change of the sensor, and then evaluate the template

stuck remnant
#

Idunno, it stays on even after the motion stops

#

it's at 51 now, since 8 minutes ago

#

and the binary sensor still on

marble jackal
#

Yes, it is still above 0, so that would be correct

stuck remnant
#

ok, but I'm trying to make it turn on whenever there's a state change regardless of value not just above 0

#

which would then make it turn off whenever there's a lack of state change for 30 secs

marble jackal
#

If you just want it to turn off of there has not been a state change in the last 30 seconds, you can use this:

- binary_sensor:
      - name: "Bathroom motion"
        delay_off: "00:00:30"
        state: >
          {{ (now() - states.sensor.samsung_j3_ipcam_motion.last_changed).seconds < 30 }}
stuck remnant
#

thanks!

marble jackal
#

Sorry, other way around

#

Corrected now.

#

However, now() is only evaluated once a minute, so it will probably take longer than 30 seconds after a state change to turn off

simple sparrow
#

Hi, my device_tracker template is not working anymore. Does someone know why?

{% for device in (states.device_tracker | selectattr('attributes.essid', 'eq', 'MYSSID') | list) -%}
              {{ device.name }}
{% endfor %}

Error: UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'essid'

marble jackal
#

Add a check if the attribute is defined

#
{% for device in (states.device_tracker | selectattr('attributes.essid', 'defined') | selectattr('attributes.essid', 'eq', 'MYSSID') | list) -%}
              {{ device.name }}
{% endfor %}
stuck remnant
marble jackal
stuck remnant
#

that would be great! how to do that?

stuck remnant
#

thank you!

floral shuttle
#

upon reload of templates, the only 'default' issue I seem to have left is a get function in my Python scripts, based on a Ha core template:, which is - unique_id: utc_offset name: Utc offset state: > {{now().utcoffset().total_seconds()/3600}}. The Python uses: utc_offset = hass.states.get('sensor.utc_offset').state try: timeDifference = float(utc_offset) except: ValueError and throws the error when the template reloads...

#

can/should I default that like we do in HA? eg withutc_offset = hass.states.get('sensor.utc_offset',0).state I get get() takes 2 positional arguments but 3 were given

mighty ledge
#

I think I've told you multiple times that you can't mix and match languages. Jinja is not python, jinja is not JS, python is not JS, etc

#

you actually have to look up the API and perform the code based on what the API tells you

floral shuttle
#

yah I am aware of not mixing ofc, my mistake was the dictonary.. but, before I fix that, I tested the new This variable on the utc_offset for experiments sake just now, and it wont pass config.```
- unique_id: utc_offset
name: Utc offset
state: >
{{now().utcoffset().total_seconds()/3600}}
icon: >
mdi:numeric-{{this.state|default(0)|int|abs}}

icon: >

{% set offset = now().utcoffset().total_seconds()/3600 %}

mdi:numeric-{{offset|int|abs}}``` still complains about 'this is undefined when rendering etc'. The commented bit works fine.

#

even though I set a default on it. Cant use the availability with that, so how to proceed in this case?

#

even tried ```
icon: >
{% if this.state is defined %}
mdi:numeric-{{this.state|int|abs}}
{% endif %}

mighty ledge
floral shuttle
#

a yes, that was it. 'this' is the entity, which should be checked for none, not entity.state. thx. This: icon: > mdi:numeric-{{this.state|int|abs if this is defined}} seems to work too.

mighty ledge
#

yeah but you'd wnat an icon when it's not, right?

#

and when the state is non-numeric

floral shuttle
#

yep...

#

too bad we can not default the this.state directly, and have to resort to if's, its makes it way less attractive to use the self referencing This, certainly for these short templates. might as well simply repeat the state template

#

its also a bit of a mixed complexity, because ```
- unique_id: next_alarm
name: Next Alarm
state: >
{% set timestamp = states('sensor.next_alarm_timestamp')|int(default=0) %}
{% if timestamp %}
{{timestamp|timestamp_custom('%H:%M')}}
{% else %} Not set
{% endif %}
icon: >
{{iif(this.state == 'Not set','mdi:alarm-off','mdi:calendar-clock')}}

mighty ledge
#

this is a state object. So checking for the state object is standard

#

just like trigger.to_state and trigger.from_state

floral shuttle
#

yes, I see that, thx. using midway mdi:numeric-{{this.state|int|abs if this is defined and this.state|is_number else 'negative-1'}} for now, to see if I run into more extreme exceptions to be guarded (the previous never caused any trouble so I hope this will suffice). btw, I tried it in an iif() but then even the if this is defined caused it to throw the error.

mighty ledge
#

becuase you remove the if

#

iff(this is defined, ...

#

not

#

iff(if this is defined, ...

rose scroll
#

iif(...)

mighty ledge
#

mdi:numeric-{{ iff(this is defined and this.state|is_number, this.state|int|abs, 'negative-1') }}

#

however, that might not work because it may try to resolve this.state|int|abs inside the iff

#

meaning you HAVE to use the pythonic if else

#

I'd wager that the resolution will happen, forcing you towards the pythonic if else

#

FWIW, I personally wouldn't switch to the iff, it's for beginners who can't read (if-passes) if () else (if-fails)

floral shuttle
#

hehe. and youre right: Template variable error: 'this' is undefined when rendering 'mdi:numeric-{{iff(this is defined and this.state|is_number,this.state|int|abs,'negative-1')}}'

mighty ledge
#

well that settles it, use the pythonic if-else

#

as it will not resolve the if-passes

floral shuttle
mighty ledge
#

well, at least the docs cover that

#

it's advanced understanding

floral shuttle
#

yeah, and you have to understand what it says, before you understand what is says....

#

having settled that (thank you btw) I am back to NameError: name 'timeDifference' is not defined for my Python scripts importing that Utc sensor.

mighty ledge
#

right, and you're getting that because of the exact same issue, but in python

#

you're getting the state object, not checking it's existance, and then providing it the conversion with a bad value

#
utc_offset_obj = hass.states.get('sensor.utc_offset')
utc_offset = utc_offset_obj.state utc_offset_obj is not None else None
try:
    timeDifference = float(utc_offset)
except ValueError as err:
    timeDifference = 0.0
floral shuttle
#

thx! was busy testing this utc_offset = hass.states.get('sensor.utc_offset').state if (utc_offset is not 'unavailable'): timeDifference = float(utc_offset) else: timeDifference = 0.0 which also prevents the error. tested for None first, but since it isn't none (which is the test for the state object) but 'unavailable' given it's the state.state, I hoped that would work.

#

now back to the course and find your solution

#

and, utc_offset = hass.states.get('sensor.utc_offset').state try: timeDifference = float(utc_offset) except ValueError as err: timeDifference = 0.0 works without error too.

#

I just realized it's remarkable these errors show up in the first place, upon reload of templates, since this python script only runs when this automation fires:```

  • alias: Mode selection
    id: mode_selection
    trigger:
    platform: state
    entity_id: select.mode_selector
    action:
    service: python_script.summary_mode
    ``` Somehow the event_template_reloaded triggers that.
proud ridge
#

How do I get the current entity icon? For example a battery entity will change icon depending on the battery status, so I'm wondering how can I get the icon of an entity through template

inner mesa
#

I don't think you can. I think it's determined by the frontend based on the battery level, which you can access

proud ridge
#

But I have some custom components that show the icon of the entity, how are they doing it, javascript?

mighty ledge
#

yes

proud ridge
#

damn that sucks

mighty ledge
#

you can just make a template that gets the same icon

#
{% set level = 11 %}
{% set fullempty = {0:'-outline',100:''} %}
mdi:battery{{ fullempty.get((level // 10) * 10, '-' ~ (level // 10) * 10) }}
proud ridge
#

yep, just did that

marble jackal
#

What does // do? Is it like divide and int afterwards?

mighty ledge
#

it's int division

#

tosses the remainder out

#

but, basically, yes it does what you asked

marble jackal
#

Ah good to know

mighty ledge
#

I only know of it because of python 2. Basically back in the day if you divided 2 int's you'd get an int. If you wanted a float, you'd have to cast crap to a float or use the // to do float division. When they went to python 3, they inverted it. / was always a float and // was an int

normal badger
#

Hey whats wrong here?

#

{{ now().month in [6, 7, 8] }}

#

It says: template value should be a string for dictionary value @ data['value_template']. Got None

inner mesa
#

?

#

first pinned message here?

normal badger
#

When I test the condition within an automations

marble jackal
#

Check the pinned posts

normal badger
#

Oh what did I miss?

normal badger
inner mesa
#

the pinned message

normal badger
#

Ty so I should be fine I guess

#

Hopefully this gets a fix because I really like the quick condition check within automations

thorny snow
#

Sorry for such a basic question, but Ive been struggling with this for like an hour... I'm trying to turn off a charger after a time once the level is greater than a input number: platform: numeric_state entity_id: sensor.nexus_battery_level for: '30' value_template: >- {% if states('sensor.nexus_battery_level') >= states('input_number.charger_high_percent') %}true{%endif%}

#

It needs an "above" or "below".... those blocks don't seem to support templates

inner mesa
#

States are strings

thorny snow
#

THis Should be a condition, not trigger?

inner mesa
#

and you have no "else"

thorny snow
#

RRRRRRrrrr {% if states('sensor.nexus_battery_level') >= states('input_number.charger_high_percent') %}true{%endif%}

inner mesa
#

yes, that's wrong

thorny snow
#

Wait, you need an else?

inner mesa
#

well, it has to evaluate to something

#

plus, you're using a numeric_state trigger and then providing a template

thorny snow
#

in templates, it show blank, but that's a null/false, right?

#

LOL I am so confused

inner mesa
#

I doubt it

thorny snow
#

before I had hardcoded 80% in there, but now I am trying to update the automation with a helper

inner mesa
#
- platform: template
  for: 30
  value_template: "{{ states('sensor.nexus_battery_level')|float >=  states('input_number.charger_high_percent')|float }}"
thorny snow
#

and this is a condition, right? But it still needs a trigger, or it'll never fire, correct?

inner mesa
#

or...

#

you haven't said

#

you could use a trigger for this

#

it will only trigger if it starts below the threshold that you've set and transitions above it, though

#

a better solution is this:

#
trigger:
  platform: state
  entity_id: sensor.nexus_battery_level
condition:
  condition: numeric_state
  entity_id: sensor.nexus_battery_level
  above: input_number.charger_high_percent
#

you can't use a "for:" there, but I don't know if you really care

thorny snow
#

I wanted to stop potential thrashing so I just said for > 30 minutes.... 5 would even be fine I guess.

inner mesa
#

that was "30 seconds"

thorny snow
#

OH... dang

inner mesa
#

just increase the percentage

#

it's not going to "thrash", just add a condition to check that it's still on

thorny snow
#

Well, I think that would be fine, becuase I don't turn the charger back on until the "low" slider is passed

inner mesa
#

right

thorny snow
#

Ok, here's the whole thing, and it looks right:

#
description: ''
trigger:
  platform: state
  entity_id: sensor.nexus_battery_level
condition:
  condition: numeric_state
  entity_id: sensor.nexus_battery_level
  above: input_number.charger_high_percent
action:
  - service: switch.turn_off
    target:
      entity_id:
        - switch.bath_charger
mode: single```
#

I didn't know you could just put the input_number in the above field...... I thought it needed a template

#

Hmmm.. I will test more. Thank you!

inner mesa
#

When in doubt, check the docs!

#

That was added sometime last year

thorny snow
#

I think I made the mistake of looking for examples first, and getting in a rabbit hole

marble jackal
#

If you do want a time delay, I would suggest to create a binary_sensor and use a delay_on

thorny snow
#

I will keep that in mind! Thank you

marble jackal
#

Or a state trigger with a for using the binary_sensor

thorny snow
#

True, that's the direction I would have gone

slow vine
#

is there a way to template state condition for:?

#

this is the rough idea of what I have:

template:
  - binary_sensor:
      - name: "time to check for update"
        state: "{{ is_state('binary_sensor.check_update', 'off') for 24 hours }}"
#

the for 24 hours is where I can't find where to do that in a template. I searched but I didnt find where it says this point.

inner mesa
#

delay_on: should be able to do that

slow vine
#

I guess if it was only based on time. I would want it to also be based on another trigger (besides time) and then have the delay on. If I understand correctly delay_on would ignore that. In an automation I guess I would use wait for trigger...

#

some times the sensor gets false triggers I want it to wait 24hrs after getting triggered to see if it held before changing the state of binary sensor.

#

I see, I didn't understand how it works. I still thought it wouldn't but I tried it and its good so its good, Thanks.

stuck remnant
#

hi, I have a binary sensor that I need to have it check every second for a doods image processing entity if its above 0

      - platform: time_pattern
        hours: "*"
        minutes: "*"
        seconds: "*"
    binary_sensor:
      - name: "Chair motion"
        delay_off: "00:00:30"
        state: >
          {{ states('sensor.image_processing.doods_theothergoat')|float > 0 }} ```
is the code right?
inner mesa
#

I would simplify the trigger to:

      - platform: time_pattern
        seconds: "/1"
stuck remnant
#

and that will make the binary sensor trigger each second right?

inner mesa
#

yes

stuck remnant
#

awesome cheers!

stuck remnant
#

only it doesn't

#

the sensor shows up as Unknown

#

I'm thinkin it has to do with the way that the doods sensor is written

#

like the attributes and such

#

the binary sensor is told by the template to turn on if the doods is above 0

#

the doods sensor's state does show up as above 0 in the developer tab

mighty ledge
#

It'll show up as unknown on first start

stuck remnant
stuck remnant
mighty ledge
#

It'll only update on your trigger

#

it won't update based on dood changing

#

that's what happens when you use a trigger

stuck remnant
#

so it disregards the template completely?

mighty ledge
#

yes

stuck remnant
#

wow

mighty ledge
#

when trigger -> resolve template

stuck remnant
#

makes sense

mighty ledge
#

or no trigger, works off templates state changes

stuck remnant
#

how can I make the binary sensor use the template AND check for the template every 1 sec

mighty ledge
#

why do you need to check the template every 1 second

#

that makes no sense as the template will update live

stuck remnant
#

cos the doods is my motion detection

mighty ledge
#

yeah, but a binary sensor is binary

#

if it goes from 0 to 1 it'll be on, if it goes from 1 to 2, it won't be more on, it'll still be on

#

if it goes from 1 to 0 it'll be off

stuck remnant
#

thats perfect

mighty ledge
#

there's no reason to check it in between

#

then remove the trigger

#

and you're done

stuck remnant
#

that's how it was initially 😄

#

and it didnt work

#

because maybe the thing with the attribute

mighty ledge
#

no clue what you're saying

stuck remnant
#

(from what I know, some sensors show different states in the development tab as opposed to what their actual states are)

#

different formatting, IDK

mighty ledge
#

no...

stuck remnant
#

ok rewind a bit:

mighty ledge
#

there's a translated state for things that have known states. Like a binary sensor that's motion

#

a sensor does not have known states

#

and does not have any translations

#

known state is like 'on', or 'off'.

#

a sensor is just a value

stuck remnant
#

that tracks

#

ok so it was like this:

      - name: "Living Room motion"
        delay_off: "00:00:30"
        state: >
          {{ states('sensor.image_processing.doods_thegoat')|float > 0 }}
mighty ledge
#

yep, that will update when doods changes

stuck remnant
#

only it didn't 😦

#

it stayed off

mighty ledge
#

then dudes wasn't changing

stuck remnant
#

even though I was witnessing doods changing live

mighty ledge
#

then you have the wrong entity id

stuck remnant
#

hmm, I don't think so but doublechecking just to be sure

#

yeah you're right, the entity doesn't have the word "sensor" before it

#

or is that part of the template perhaps

mighty ledge
#

not sure I folllow you

stuck remnant
#

sorry, not that experienced with templates. I thought the entity name went after "sensor"

#

but that was just part of a sensor's name

#

not being experienced, I only swap out parts for other parts

mighty ledge
#

what's the full entity_id?

#

image_processing.xxx

stuck remnant
#

image_processing.doods_thegoat

mighty ledge
#

then that's why it's not working

stuck remnant
#

thats great!

#

ok and just to be sure: this one won't check the template either, correct?

        name: "Bathroom motion"
        delay_off: "00:00:30"
        state: >
          {{ (now() - states.sensor.samsung_j3_ipcam_motion.last_changed) }}```
mighty ledge
#

remove the - before binary_senosr and align it with trigger

stuck remnant
#

so for this one I need it to turn on whenever that motion sensor changes state, and then off if there's no change state for 30secs

mighty ledge
#

why no change for 30 seconds

#

that's effectively the same as delay off

stuck remnant
#

so remove the last bit then

#

edited. like that?

mighty ledge
#

it needs to return on or off, true or false

#

remove the timepattern

#

what is supposed to signify on?

stuck remnant
#

whenever there is a state change in the motion sensor (which sometimes remains stuck at random values)

#

so if it's stuck at 500 when I turn off the light, I need the next time there's any other number apart from 500 to show as on

#

like, whenever there's a state change from 'now'

mighty ledge
#

You're going to have a tough time figuring that out

#

does the value change constantly when it detects motion?

stuck remnant
#

yes

#

it's a motion sensor from an android IPcam

mighty ledge
#

you'll probably need to make a forum post, it's too complicated to come up with here and I'm about to head out

stuck remnant
#

ok

#

thank you for your time and your help!

mighty ledge
#

np

low blaze
#

I'd like to use a time of day sensor but base the times on variables I have already created and set. How would I modify this example to use input_datetime.t1_wake as the time? ```

  • platform: tod
    name: Late Morning
    after: "10:00"
    before: "12:00"```
inner mesa
#

I don't think you can with that integration. You could do the equivalent with a template binary_sensor, though

low blaze
#

thanks what would that look like?

#

Actually it doesn't have to be binary right?

#

I could just use a template sensor, I'd prefer that as I can give the value "Day" and "Night"

#

I'm gonna give it a go

#

have an idea

inner mesa
#

{{ states('input_datetime.xxx')|as_datetime <= now() <= states('input_datetime.yyy')|as_datetime }}

#

or something like that. you (and I) would need to play with it to get it right

low blaze
#

ok let me play with that

#

do I need to enable the time and date function so that sensor.time exists or the above can do that without it

#

I think I've got it !

#

{{ states('input_datetime.t1_wake') <= states('sensor.time') <= states('input_datetime.t1_sleep') }}

#

so that works as long as am>pm isn't bridged

#

but not if say wake is 9pm and sleep is 4am, it fails

#

Got it (with help from the forums)

#
          {% set slt1start = states('input_datetime.t1_wake') [0:5] %}
          {% set slt1stop = states('input_datetime.t1_sleep') [0:5] %}
          {{ (slt1start <= time < slt1stop) if (slt1start < slt1stop) else (slt1start <= time or time < slt1stop) }}
plucky heron
#

how do I reference the value in a value template?

low blaze
#

@plucky heron easiest way is to define a variable for it at the start of your template and then reference it's name

#

you can see it above in the unrelated template i just added. First you set "time" equal to the value of anything you want, then you use simply "time" in your statements

#

the defined variables live only inside the single value_template so you do not need to worry about using specific labels they just need to be unique inside that one sensor

#

@inner mesa so I have it working with true/false, how can I modify that to output Day if true and Night if false?

#

Done.

#
          {% set slt1start = states('input_datetime.t1_wake') [0:5] %}
          {% set slt1stop = states('input_datetime.t1_sleep') [0:5] %}
          {% if ((slt1start <= time < slt1stop) if (slt1start < slt1stop) else (slt1start <= time or time < slt1stop)) %}
              Day
          {% else %}
              Night
          {% endif %}  ```
plucky heron
#

i have a mqtt switch, and the mqtt value for the state isn't on\off. i don't see the mqtt topic value in states(). how do i assign it to a variable?

low blaze
#

what is the entity name?

#

switch.something?

plucky heron
#

yes

#

switch.garage_motion

low blaze
#

{% set switchstate = states('switch.garage_motion) %}

#

you can test it in the template under developer tools by writing

#

{{ states('switch.garage_motion) }}

#

that will output on or off

#

so now you know what value you are setting your "switchstate" to

#

once you set it, you can put {{ switchstate }} on the next line and you will get a matching output as well

#

If I was playing around with templates I would use the following in that box

#
{% set switchstate = states('switch.garage_motion') %}
{{ switchstate }}```
#

result will be off, off

#

which lets you know your value is getting assigned to your variable, and then you can pull the variable, and now you can use simply switchstate in your if statements

#

when I am workign on long ones I'll add plain text labels around them like this ```This is the raw state [{{ states('switch.p1_ro_feeder') }}]
{% set switchstate = states('switch.p1_ro_feeder') %}
This is the output variable [{{ switchstate }}]

#

{% means a calculation or logical statement while {{ means output this value

plucky heron
#

'value' is the variable i was looking for. it has the mqtt topic data in it

#

value_template: "{{ value is search('motion=1', ignorecase=False) }}"

marble jackal
#

Guess it would have made it easier if you would have told you were talking about an MQTT topic 🙂

fluid horizon
#
sensor isha:
  - platform: rest
    resource: https://dailyprayer.abdulrcs.repl.co/api/london
    name: Isha
    value_template: "{{ value_json.today.isha'a }}"
    scan_interval: 20

im trying to get the isha'a in value template to work

#

but it wont

#

how do i put ' in a that

arctic sorrel
#
    value_template: "{{ value_json.today.isha\'a }}"
``` should work AFAIK
fluid horizon
#

@arctic sorrel not working bro

#

check dms

silent barnBOT
#

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

fluid horizon
#

`
Configuration invalid!

Error loading /config/configuration.yaml: while scanning a double-quoted scalar
in "/config/configuration.yaml", line 54, column 21
found unknown escape character "'"
in "/config/configuration.yaml", line 54, column 47
`

arctic sorrel
#

Now use a code share site to share the YAML of what you've done

fluid horizon
#
sensor isha:
  - platform: rest
    resource: https://dailyprayer.abdulrcs.repl.co/api/london
    name: Isha
    value_template: "{{ value_json.today.isha\'a }}"
    scan_interval: 20
mighty ledge
#

because it's the dot notation, you need all characters and no special characters.

mighty ledge
#

you can't create a function or macro with special characters and that rule is also applied to calling them. attrs of a dictionary are wierd like that. The safest way to get any attribute to avoid that stuff is xx.get('attr'), however it's not as nice as xx.attr or xx['attr']. All 3 of those methods work when you're dealing with a alpha-numeric key unless it steps on the toes of a function name. If it's non alpha-numeric or a function shares the same name, you have to use xx['attr'] or xx.get('attr').

fluid horizon
#

👍

#

thanks bro

silent vector
#

Can a template be made to add an hour to the current hour

{{ now().strftime("%I:%M %p") }}

returns 07:08 am. If I wanted it to return 08 am as in current hour + 1 how would I do that?

mighty ledge
#

what are you trying to do

#

big picture

silent vector
#

Text to speech using it with Amazon Polly to say at 10am it will be x degrees outside

mighty ledge
#

ok, and howare you getting that?

silent vector
#

Rather than saying in 1 hour

fluid horizon
#

its giving me errors

silent vector
#

I have everything set for knowing the temperature. It's just a matter of it would be cool to know the hour vs just saying in 1 hour, in 2 hours etc. Instead at 08 am, 09 am it will be x degrees outside.

mighty ledge
fluid horizon
#
sensor isha:
  - platform: rest
    resource: https://dailyprayer.abdulrcs.repl.co/api/london
    name: Isha
    value_template: "{{ value_json.today['isha\'a'] }}"
    scan_interval: 20

Error loading /config/configuration.yaml: while scanning a double-quoted scalar
in "/config/configuration.yaml", line 53, column 21
found unknown escape character "'"
in "/config/configuration.yaml", line 53, column 48

@mighty ledge

mighty ledge
fluid horizon
#

oh wait

#

thats not ur code

#

hold on

#

i think thats something i did

#

wait nah its urs

silent barnBOT
mighty ledge
mighty ledge
# fluid horizon wait nah its urs

That doesn't make sense, it will pass validation. You can try this instead if you want but the result will be the same.

    value_template: >
      {{ value_json.today["isha'a"] }}
silent barnBOT
fluid horizon
#

but now wont display

mighty ledge
#

post the json

#

@silent vector haven't forgotten, hold a sec

silent vector
#

No problem.

fluid horizon
#
sensor isha:
  - platform: rest
    resource: https://dailyprayer.abdulrcs.repl.co/api/london
    name: Isha
    value_template: >
      {{ value_json.today["isha'a"] }}
    scan_interval: 20

#

api im using

mighty ledge
#

@silent vector

<speak> {% if now().strftime('%H')|int < 12 %}
          Good morning.
        {% elif now().strftime('%H')|int >= 12 and now().strftime('%H')|int < 17 %}
          Good afternoon.
        {% else %}
          Good evening.
        {% endif %} It is {{ now().strftime("%I:%M %p") }}. The high today is {{ (state_attr('weather.home_hourly',
        'forecast') | map(attribute="temperature") | list)[0:16] | max }}
        degrees and the low is {{ (state_attr('weather.home_hourly', 'forecast')
        | map(attribute="temperature") | list)[0:16] | min }} degrees. <break
        time=".03s"/> It is currently {{state_attr('weather.home_hourly',
        'temperature') }} degrees outside.
        {% for hourly in state_attr('weather.home_hourly','forecast')[:2] %}
        - <break time=".03s"/> at {{ (hourly.datetime | as_datetime | as_local).strftime("%I %p") }} it will be {{ hourly.temperature }} degrees outside.
        {% endfor %} </speak>
mighty ledge
silent vector
#

That is perfect thank you!

mighty ledge
silent vector
#

How would I keep the logic with the addition of the loop to get the time that you gave me?

{% if
        state_attr('weather.home_hourly','forecast')[0] .temperature | float(0)
        - state_attr('weather.home_hourly', 'temperature') | float(0) > 3 %} 
at 08 am it will be x degrees  {% else %} {% endif %}

The for loop you gave also provides 2 times as an output

- <break time=".03s"/> at 08 AM it will be 58 degrees outside.
        
        - <break time=".03s"/> at 09 AM it will be 60 degrees outside.

I assume it should only provide one? As I would only want to know the next hour, next 2 and next 3 but only if the conditions of each if is met at that time would I want to know the next 2 and 3. That's why I spaced them out in separate if statements so that if necessary it would say every hours temperature and If not only 1 or 2 or even 0 if the conditions aren't met.

mighty ledge
#

what is the condition, that the templerature is greater than 3 degrees from the previous?

silent vector
#

Yep that's it. the next hour, 2 hours from now and 3 hours out. Then I would want to know what the temperature is at that hour. If not nothing. To avoid. It will be 59 at 09 and 60 at 10 and 61 at 11 for example. Pretty small changes I would rather not waste the time hearing lol

#

This is the current output of the code I posted in the first hastebin

<speak> 
          Good morning.
         It is 07:48 AM. The high today is 72 degrees and the low
        is 58 degrees. <break
        time=".03s"/> It is currently 52 degrees outside. 
        <break time=".03s"/> in 1 hour it will be 58 degrees
        outside.       </speak>
mighty ledge
#
<speak> {% if now().strftime('%H')|int < 12 %}
          Good morning.
        {% elif now().strftime('%H')|int >= 12 and now().strftime('%H')|int < 17 %}
          Good afternoon.
        {% else %}
          Good evening.
        {% endif %} It is {{ now().strftime("%I:%M %p") }}. The high today is {{ (state_attr('weather.home_hourly',
        'forecast') | map(attribute="temperature") | list)[0:16] | max }}
        degrees and the low is {{ (state_attr('weather.home_hourly', 'forecast')
        | map(attribute="temperature") | list)[0:16] | min }} degrees. <break
        time=".03s"/> It is currently {{state_attr('weather.home_hourly',
        'temperature') }} degrees outside.
        {% set ns = namespace(previous=-300) %}
        {% for hourly in state_attr('weather.home_hourly','forecast')[:3] %}
        {% if hourly.temperatere - ns.previous > 3 %} 
        - <break time=".03s"/> at {{ (hourly.datetime | as_datetime | as_local).strftime("%I %p") }} it will be {{ hourly.temperature }} degrees outside.
        {% endif %}
        {% set ns.previous = hourly.temperature %}
        {% endfor %} </speak>
#

actually

#

can optimze

#
<speak> {% if now().strftime('%H')|int < 12 %}
          Good morning.
        {% elif now().strftime('%H')|int >= 12 and now().strftime('%H')|int < 17 %}
          Good afternoon.
        {% else %}
          Good evening.
        {% endif %} It is {{ now().strftime("%I:%M %p") }}. The high today is {{ (state_attr('weather.home_hourly',
        'forecast') | map(attribute="temperature") | list)[0:16] | max }}
        degrees and the low is {{ (state_attr('weather.home_hourly', 'forecast')
        | map(attribute="temperature") | list)[0:16] | min }} degrees. <break
        time=".03s"/> It is currently {{state_attr('weather.home_hourly',
        'temperature') }} degrees outside.
        {% set ns = namespace(previous=-300) %}
        - <break time=".03s"/> at {{ (hourly.datetime | as_datetime | as_local).strftime("%I %p") }} it will be {{ hourly.temperature }} degrees outside.
        {% set ns.previous = hourly.temperature %}
        {% endfor %} </speak>
silent vector
#

What's the difference between the 2? This is slightly over my head as I haven't used for loops before.

mighty ledge
#

it just moves the if statement in the for loop line

#

you can keep whichever one you want

#

unfortunately we need namespace in order to capture the previous result. Jinja has a scoping issue where you can't define variables inside a loop and expect it to update. You ahve to use namespace in order to do that.

#

either way, that should work as long as I didn't add any typos

silent vector
#

Other than temperatere in the first one no typos it worked. Thanks again. This is addicting as I'm building out a full temperature briefing now. Next additions will be cloudy,sunny and precipitation.

marble jackal
#

Ah, you can put breaks in an amazon polly TTS, would be nice if that was also possible for Google Home

mighty ledge
#

hourly.condition

#

same with wind direction, etc

silent vector
#

How would I add condition for example? And yes when I first used this with cloud say It was too fast and Polly is amazing. The breaks are customizeable and it can do a lot more.

mighty ledge
silent vector
#

I wasn't sure if it would mess up the loop. But yes that makes sense. The precipitation addition would be different as I wouldn't care if the precipitation was 0% only if above 60% chance so that would require additional logic vs condition is simply dropping an additional variable. What does the -300 do

mighty ledge
#

so the first hourly temperature will be output

silent vector
#

Interesting alright. I noticed the met.no weather is pretty behind just now. AccuWeather shows 60 degrees and met.no shows 52 but it's the only integration I found so far with a forecast so it's better than nothing.

mighty ledge
#

it's probably your location and what met.no has access to

silent vector
#

Usually they are closer and not off by that much but thank you for the help I'll look for additional integrations with forecast and modify the template for that so it's more accurate.

stuck remnant
#
  • binary_sensor:
    - name: "Outside heat"
    delay_on: "1:12:00"
    state: >
    {{ state_attr('weather.home','temperature') > 25 }}
#

I wanna have this turn on only after there's been 36h of temp over 25

#

and the way it is now, it is on when I restart HA

#

right now there are 27 degrees outside

#

so Im guessing the delay on didnt trigger?

visual matrix
#

@mighty ledge you helped me out with a days_left sensor a while back but it's not updating everyday, except on restarts, any way of fixing this?

#

{% set n = today_at().date() %} {% set t = n.replace(day=8) %} {% set ns = namespace(dates = [ t.replace(year=n.year - 1, month=12), t.replace(year=n.year + 1, month=2) ]) %} {% for m in range(2, 14, 2) %} {% set ns.dates = ns.dates + [ t.replace(month=m) ] %} {% endfor %} {% set end = ns.dates | sort | select('>=', n) | first %} {% set start = ns.dates | sort | select('<=', n) | reverse | first %} {{ (end - n).days }}

mighty ledge
#

you're supposed to use that with a time pattern trigger

#

i.e. add a trigger to your template sensor

visual matrix
#

Oh ok i see, i was just using it in a markdown card

#

thank you

marble jackal
proud plank
#

guys I use this restapi to set target temperature on my TRVs

rest_command:
  mihome_kitchentrv_set_15:
  url: "https://mihome4u.co.uk/api/v1/subdevices/set_target_temperature"
  payload: '{"id":14965,"temperature":15}'
  method: POST
  content_type: application/json
  username: !secret mihome_username
  password: !secret mihome_password

also have a sensor that can read set temp and current temp

  - platform: rest
    name: "MiHome KitchenTRV"
    resource: 'https://mihome4u.co.uk/api/v1/subdevices/show'
    method: POST
    authentication: basic
    username: !secret mihome_username
    password: !secret mihome_password
    payload: '{"id":149565}'
    value_template: '{{ value_json.data.power_state }}'
    json_attributes_path: "data"
    json_attributes:
      - label
      - id
      - device_id
      - power_state
      - startup_mode
      - device_type
      - remote_id
      - voltage
      - voltage_reported_at
      - updated_at
      - target_temperature
      - last_temperature
    headers:
      Content-Type: application/json
    force_update: true
    scan_interval: 60

I would like to have it a bit smarter. Is there a way to make some template turn it into thermostat and when I set new value it will be automatically set to this restaip as "temperature:"

fossil venture
inner mesa
#

Sheesh

proud plank
low blaze
#

Is it possible in a template switch to include an action if the condition fails?

#
        friendly_name: "T1 Hummer"
        value_template: "{{ states('switch.t1hum1') }}"
        turn_on:
        - condition: state
          entity_id: input_boolean.enabler_t1_hum1
          state: 'on'
        - service: switch.turn_on
          target:
            entity_id: switch.t1hum1
        turn_off:
        - service: switch.turn_off
          data:
            entity_id: switch.t1hum1    ```
#

could i run a notify if it fails the condition?

inner mesa
#

Use a choose:?

low blaze
#

just found that suggestion as I'm trying to research in parallel

#

that would let me have an anternate action

inner mesa
#

Or if/else

low blaze
#

can you give an example of how you would add if/else to that template switch

#

where would it go ?

inner mesa
#

It's in the script syntax docs

#

Along with choose:

low blaze
#

k will go look thanks Rob!

#

I've used plenty of if/else just not inside and respective with conditions

#

oh wait can i just write the turn_on: section like a template sensor?

#

just what I would use for a value template ?

inner mesa
#

Like a script, which it is

orchid oxide
#

Template warning: 'int' got invalid input 'None' when rendering template

{{ state_attr('light.hallway', 'brightness')|int < (75*2.55)|int }}
{%else%}
{%if states('sensor.light_sensor_illuminance')|int > 350 %} {{state_attr('light.hallway', 'brightness') != 'None'}}
{%else%}
{{state_attr('light.hallway', 'brightness') |int < ((75-sqrt((((states('sensor.light_sensor_illuminance'))|int-2)/350))*75)*2.55)|round}}
{%endif%} 
{%endif%} 
{{state_attr('light.hallway', 'brightness') }}```
 but no default was specified. Currently 'int' will return '0', however this template will fail to render in Home Assistant core 2022.6
#

what exactly does this warning mean

#

i dont really wanna mess with something i dont understand, but it looks there theres something i need to change

inner mesa
low blaze
#

I can not find an example close enough to my current template switch sytax that shows me how to work the if/else into my switch, and with it being a template switch need to reboot home assistant every single time to test a guess, can you perhaps point me at an example I can work from ? (Sorry I'm not trying to have you do it for me just can't translate the examples)

#

or is there a way to just keep testing my code inside Developer Tools that way you can with a sensor?

inner mesa
#

You can reload template entities at runtime, you don't need to restart HA

low blaze
#

thanks that helps

low blaze
#

got it! Thanks for the push @inner mesa

#

🙂

orchid oxide
#

is there a way i can stop an entity from reporting its values so i can mess with it in the template editor

low blaze
#

@orchid oxide you want to just have it report dummy data? you could make a helper that is input_number type and just use that as a place holder till you are done

main lodge
#

Hi All, I am very new to HA, so I'm not sure if this is the correct forum of category for my questions. I have created some hardware that is publishing to mqtt in raw text data, not using json. I have added a sensor card to the dashboard but cannot get any connection to the mqtt broker. I add a sensor in config.yaml as below

#

sensor:

  • platform: mqtt
    name: "Tank 2"
    unique_id: tank2_level
    state_topic: "Bills_Mesh/master/tank2/level"
    unit_of_measurement: "%"
    value_template: "{{ state.value.level }}"
#

I suspect the value_template is not correct but can't find any examples to know what to use

#

Any help would be greatly appreciated

atomic blade
#

A lot of sensors seem to support a value_template. Is there a value_template I could use for any sensor that supports value_template that would prevent that sensor from ever being unknown or unavailable, most importantly EVEN AFTER A RESTART?

main lodge
#

Scott this is something i saw in an example to fix non-numeric value when the value is unknown etc : value_template: "{{ states('sensor.pv_power') | float }}"

marble jackal
#

@atomic blade For a template sensor you can add an availability template, the best template for that will differ based on how many source entities you are using and what kind of states they can have (only numbers, or also other string values).

silent vector
#

What is the simplest way to say greater than positive 3 or - 3. -3 would mean the temperature fell. Positive 3 it went up. Can that be done in the same statement?

{{ state_attr('weather.openweathermap','forecast')[0] .temperature | float(0)
        - state_attr('weather.openweathermap', 'temperature') | float(0) < - 3 or < 3 }}

I didn't think that would work but I'm wondering if there's a way it could?

marble jackal
#

Don't to mean < -3 or > 3

silent vector
#

Oh yeah that lol. That's what I have in the script I am using that just has > 3 as a condition. I quickly put that together and didn't think about the sign for the positive number.

marble jackal
#

{{ (state_attr('weather.openweathermap','forecast')[0].temperature - state_attr('weather.openweathermap', 'temperature')) | abs > 3 }} will do the trick

#

btw, these attributes are already stored as number, you don't need to convert them to float

silent vector
#

Perfect and should I just get rid of float then? Int is not necessary either?

marble jackal
#

int is also not needed

silent vector
#

Sounds good thank you

marble jackal
#

I've adjusted the template above

silent vector
#

Perfect thank you.

earnest cosmos
#

I need some help creating an automation using a template to list the items in a for-each list. I have several scripts I need to traverse through and needs to be killed.
The scripts are in the format: script.vacuum_
https://www.home-assistant.io/docs/scripts/#for-each
An example to such a template would be very much appreciated.

marble jackal
#

@earnest cosmos No need for a for_each here

#
- service: script.turn_off
  target:
    entity_id: "{{ states.script | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | select('match', '^script.vacuum_') | list }}"
earnest cosmos
lethal dawn
#

Hi - I've got 2 sensors that I'm merging with a template and was wondering if there was a way to get the average value only if both sensors are responsing properly?

At the moment, if I pipe this to average - then if one sensor is offline, I only get half the value.

{{ (state_attr('binary_sensor.lounge_door_sensor_occupancy', 'temperature') | int, state_attr('binary_sensor.lounge_sofa_sensor_occupancy', 'temperature') | int) | min }}
mighty ledge
lethal dawn
#

currently I don't - | int is converting the None to a 0, which results in the halved averages - previously it was just breaking the sensor completely

#

basically - if the sensor is misbehaving - the attribute doesn't exist

mighty ledge
#

ok, that's what I wanted to know

lethal dawn
#

normally I'd search for "filter" - but that means something different in template land, so I'm hitting a brick wall 😂

#

effectively, I want to pre-filter the list of sensor attributes with is_number or > 0 before I average it

mighty ledge
#
{% set sensors = expand('binary_sensor.lounge_door_sensor_occupancy', 'binary_sensor.lounge_sofa_sensor_occupancy') %}
{% set temperatures = sensors | selectattr('attributes.temperature', 'defined') | selectattr('attributes.temperature', 'is_number') | map(attribute='attributes.temperature') | list %}
{{ temperature | average if temperatures | length == sensors | length else none }}
#

that will be unavailable if either temperature is unavailable

lethal dawn
#

{{ expand('binary_sensor.lounge_door_sensor_occupancy', 'binary_sensor.lounge_sofa_sensor_occupancy') | selectattr('attributes.temperature', 'defined') | map(attribute='attributes.temperature') | list | average }} perfect

#

thanks

mighty ledge
lethal dawn
#

yeah I tweaked it further - but the important bit is you pointed me at expand / list

#

and map I guess

#

but that bit I kind of knew, just didn't know how to apply it here

#

min/max will do and/or logic on truthy values too it seems 🙂

mighty ledge
#

yep

lethal dawn
#

I've got 2 hue motion sensors that like to trip out occasionally - this should finally resolve that issue

#

they're secondary sensors just to add extra reliability to the detection, the irony being they're unreliable themselves 😂 now at least they won't take the entire automation down if they act up

mighty ledge
#

That's sensors for you, I haven't found any that are 100% reliable

#

they all have issues somewhere

atomic blade
marble jackal
#

It will affect if your template sensor will return unavailable or will render the state for the value template

#

So you can for example check if your source sensor is available, if not, return unavailable for the template sensor as well

atomic blade
#

I'm wondering if this would help with issues I've had in the past with template sensors still rendering unknown even if I have what I thought were guards against it

marble jackal
#

If you give an example for one of the sensors for which you have issues, that might help in giving the best advice

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.

atomic blade
#

I've tried this and the template sensor would still render unknown sometimes, I believe after startup:

{% if is_state('sensor.base_sensor', 'unknown') %}
  {{ states('sensor.this_template_sensor') }}
{% else %}
  {{ states('sensor.base_sensor') }}
{% endif %}
#

Basically base_sensor would report unknown sometimes and I wanted to use the last value

#

So I tried making a template sensor (this_template_sensor) that would wrap base_sensor to protect it from reporting as unknown

#

And with recent HA updates where template sensors are supposed to report their last state on startup, I thought this would be bulletproof but it doesn't seem to be

marble jackal
atomic blade
marble jackal
#

No, because not everything can be loaded at the same time during startup, and before your template sensor is loaded, it will report unknown

atomic blade
#

I think I'd be OK with it reporting unknown during startup, but I'd like it to eventually converge on using it's last value

hollow lily
#

I've added a template to configuration.yaml. Is there a way to reload the config without restarting HA completely. I can see several options for YAML configuration reloading under developer tools->YAML but wasn't sure which one would reload templates/sensors

inner mesa
#

yes, there's an option to reload template entities there

hollow lily
inner mesa
#

template sensors are templates

#

if you had no template entities at all before, then you need to restart HA for that to show up

mighty ledge
orchid oxide
#

is it possible to do a single line if else set?

#

something like this, but obivously im doing it wrong

#

{%set elevation = state_attr('sun.sun', 'elevation' - minelevation) if state_attr('sun.sun', 'elevation') > '-5' else -5 %}

#

this one gets me TemplateSyntaxError: Expected an expression, got 'end of print statement'

inner mesa
#

Yes, you're doing math within the function

#

'elevation' - minelevation?

orchid oxide
#

should be ('sun.sun', 'elevation' ) - minelevation

inner mesa
#

And then you're comparing the attribute to a string

#

'-5'?

orchid oxide
#

huh, didnt catch that, sorry. getting rid of quotes there makes it work

sonic nimbus
#

Hello, how can I make a binary sensor through templating to show how much light entity was on during one day?

waxen rune
#

If you want to show how much, a binary_sensor is not your best choice. They only indicate yes/no, on/off.
But if you describe your case a bit more, I'm sure there's some other sensor that can do what you want.

#

Another thing: I was about to update my old binary_sensor templates to the new format. It seems there's no "friendly_name" in the new template format.
I typically want my entities to have names in English, but friendly names in Swedish.
Is traditional customize the way to go then? I thought they wanted to move away from customizing?

sonic nimbus
mighty ledge
#

So…. Not a binary sensor

marble jackal
#

That's what history_stats can do for you

silent vector
#

Not sure what I'm doing wrong here

{% if '{{ entity_id }}' == media_player.bedroom_speaker %}
        media_player.bedroom_speaker {% elif '{{ entity_id }}' ==
        media_player.family_room %} media_player.family_room {% else %}  {%
        endif %}

There's the possibility the entity_id is another one that I don't want to have the source changed for otherwise I would just use the variable entity_id. I'm attempting to only set the source if the entity_id is one of those 2. The variable works elsewhere in the script. I assume I just didn't do this template properly.

inner mesa
#

You're nesting templates

silent vector
#

For more context.

- service: media_player.select_source
    data:
      source: TV
    target:
      entity_id: >-
        {% if '{{ entity_id }}' == media_player.bedroom_speaker %}
        media_player.bedroom_speaker {% elif '{{ entity_id }}' ==
        media_player.family_room %} media_player.family_room {% else %}  {%
        endif %}
inner mesa
#

and not quoting strings

#

And you have nothing in your else clause

#

Kinda a mess

silent vector
#

Welp can you assist me lol that's why I came here to untangle the mess.

inner mesa
#

Where does entity_id come from?

silent vector
#

I'm passing it from a service call

inner mesa
#

alright

silent vector
#
service: script.outside_temperature_tts
data:
  entity_id: "media_player.bedroom_speaker"
inner mesa
#
- service: media_player.select_source
    data:
      source: TV
    target:
      entity_id: "{{ entity_id }}"
#

right?

silent vector
#

Well yes but I'm trying to not set it for a specific entity Id. One of the speakers isn't connected to a tv so I'm trying to avoid telling it to set the source to tv by filtering out one of them.

Specifically media_player.master_bedroom

inner mesa
#

you can't not set it

#

you need to use a condition above that action to not run the action

#

you can't just leave it blank

silent vector
#

I see. What would the condition be as it's a variable?

inner mesa
#

a template condition

silent vector
#

Not media_player.master_bedroom?

#

Not sure how to make that though.

inner mesa
#

easy

#

- condition: "{{ entity_id != 'media_player.master_bedroom' }}"

silent vector
#

Thank you.

#

What do you mean?

inner mesa
#

I'll just delete the nonsense

lucid bramble
#

Hi, I`m getting the "default warning" on my template and can't seem to figure out where/how to set the default value

  • sensor:
    • name: "Generator Energy Meter"
      unit_of_measurement: "kWh"
      device_class: energy
      state_class: total_increasing
      state : "{{ '%0.2f'|format(state_attr('sensor.generator_average_power','energy') | float / 1000 * (now().hour + now().minute/60)) }} "

2022-05-14 18:52:44 WARNING (MainThread) [homeassistant.helpers.template] Template warning: 'float' got invalid input 'None' when rendering template '{{ '%0.2f'|format(state_attr('sensor.generator_average_power','energy') | float / 1000 * (now().hour + now().minute/60)) }}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.6

silent barnBOT
silent vector
#

Float(0) sets the default to 0 for example.

#

float(0) / 1000

lucid bramble
#

Tried that but still gets a "None" from the state_attr function

silent vector
#

I forgot the spaces, your spacing is correct? as in float(0) / 1000

lucid bramble
#

Yes but still gets me
'Template warning: 'float' got invalid input 'None' when rendering template '{{ '%0.2f'|format(state_attr('sensor.generator_average_power','energy')|float / 1000* (now().hour + now().minute/60), 0) }}' but no default was specified. Currently 'float' will return '0', however this template will fail to render in Home Assistant core 2022.6'

I think it`s complaining about getting a "None" result from either format or state_attr but not sure where the default value should go

silent vector
#

Did you reload templates that's not the same template

#

Or restart

#

Now that you updated it, it should show float(0) / 1000 and it doesn't

lucid bramble
#

Oh well... I thought that using the "reload" template entities was actually doing the same thing. I did a restart and seems to have fixed it. So I had the right syntax at some point just the wrong way of implementing it.
Thanks for the guidance

silent vector
#

Reload does reload them but sometimes a restart is necessary to clear the erorr.

fossil venture
#

What am I doing wrong here? {{ states.binary_sensor | selectattr('attributes.icon', 'eq', 'mdi:mailbox') | list | count }} there definitely is a binary sensor with that icon attribute. I get "UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'icon'".

inner mesa
#

There was an earlier discussion about that. I think if you'll get it if you have entities that don't have that attribute

#

I don't know if it's new, but it sounded like maybe it is

#

I see some changes earlier this year where there was a move from MappingProxy to a new ReadOnlyDict type

#

You have to test that it's defined first

fossil venture
#

Yeah that will be it. Some sensors have device_classes instead of icons. How do I check if it is defined?

inner mesa
marble jackal
#

It seems to be new that a template runs in error because of undefined attributes

silent vector
#

Any idea why this is resulting In a 0 value in trace?

'{{ state_attr("media_player.family_room", "volume_level") | float | round(2) }}'

Template editor results '0.4'

#

Trace

domain: input_number
  service: set_value
  service_data:
    value: 0
    entity_id:
      - input_number.family_room_volume
  target:
    entity_id:
      - input_number.family_room_volume
north locust
#

Does anyone know if it's possible to add a service call into an input_select ? My doorbell has selectable mp3 tunes , but I want to add a google TTS to it as well ?
https://pastebin.ubuntu.com/p/t5wJBfT8NR/

marble jackal
silent vector
#

But the template editor retrieved the volume right before

#

And it was off

marble jackal
#

If a media_player is off (in devtools > states) it doesn't have the attribute volume_level

#

So even the template editor can not retrieve it then

silent vector
#

But the template editor is retrieving it. I just checked again.

marble jackal
#

Check the state in developer tools

silent vector
#
'{{ state_attr("media_player.family_room", "volume_level") | float | round(2) }}'
#

Returns

Result type: string
'0.4'
This template listens for the following state changed events:

Entity: media_player.family_room
marble jackal
#

Is it is idle it can retrieve it

silent vector
#

It's paused

marble jackal
#

Then the attribute exists, but not when it's off

silent vector
#

It's a sonos that's always on.

#

So it's weird why in trace it is setting 0 but the template evaluates the correct volume.

marble jackal
#

Well, Google Home speakers are well, but they do show as off in HA

#

I expect Sonos speakers to act the same

#

.share the entire script/automation

silent barnBOT
#

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

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

silent vector
#

You were helping me with a different part yesterday.

#

Trace

params:
  domain: input_number
  service: set_value
  service_data:
    value: 0
    entity_id:
      - input_number.family_room_volume
  target:
    entity_id:
      - input_number.family_room_volume
marble jackal
#

If it is a Sonos, why not use the snapshot service

silent vector
#

I didn't know it existed. That stores volume and source?

marble jackal
#

It should, I don't own Sonos devices, so I never used it

silent vector
#

Perfect thank you.

marble jackal
#

Not sure if it restores volume though, but it will resume what is playing

silent vector
#

If it doesn't, you see nothing wrong with the template/script that should result in a 0 value?

marble jackal
#

Is it doesn't, you don't need to write the old volume to an input_number, you can use a variable in the automation

silent vector
#

Which would be using the template by itself. volume: template?

marble jackal
#
  - variables:
      volume_old: '{{ state_attr(entity_id, "volume_level") |float | round(2) }}'
#

Ah, you are nesting templates, that is why it is not working

#

Corrected above

silent vector
#

I see now. Thank you.

marble jackal
#

But still, the input_number is not needed :)

silent vector
#

Yep I will use this and restore the volume value as volume_old

#

If sonos restore doesn't do volume*

plush willow
#

I have a question about the alarm control panel template. I do all my automations in Node-RED. My template looks like this:

  • platform: template
    panels:
    safe_alarm_panel:
    value_template: "{{ states('alarm_control_panel.real_alarm_panel') }}"
    disarm:
    service: nodered.trigger
    data:
    entity_id: switch.safe_alarm_panel_disarm_switch

The problem is that I don't get the entered pin code with this service call so that I could check all kind of things (I have connected a Ring Keypad so that I can give sound/light messages).

How do I get the entered pin within this service call?

marble jackal
#

That's not how a template trigger should look

#

Or a service call

plush willow
#

The nodered trigger works perfect. (It is a HACS integration) I use it for the communication between HA and NodeRed

The only problem is that I don't the extra information

marble jackal
#

What you posted above looks like a mix of a template trigger, a service call and setting variables. I have no clue what you are trying to achieve with it

plush willow
#

So when I arm home / arm away / disarm there are 3 seperate switches triggered in Node-RED so that I know what the user has done so that I can start teh correct automation.

This all work perfectly only I need the entered code in the alarm panel in Node-RED. So that should be sent as data with the service call

marble jackal
#

Ah okay, sorry, I'm getting it now

#

My bad

mighty ledge
#

You have to make an automation based on your alarm panel state

plush willow
#

To the point: everything almost works with the combination of the Ring Keypad and the HA alarm control panel. But I'm know busy with playing the sound on the keypad when the wrong code is entered

mighty ledge
#

Yes but to your original question, it’s not a service call it’s a template sensor. So if you want the info in your service call, you just need to use a variable from your trigger and send it through. If your automations are in nodered then you’d probably need to do this in node red

plush willow
#

I now get some information in Node-RED but the code is not parsed.

What do I? The alarm is armed and then I entered a wrong code and pressed disarm on the template alarm panel.

Has the alarm control panel a "code" property?

    disarm:
      service: nodered.trigger
      data_template:
        entity_id: switch.safe_alarm_panel_disarm_switch
        payload:
          ccode: "{code}"
mighty ledge
#

Last I remember, alarm codes were events

#

I could be wrong as I don’t use them. Either way, you need to look at all your items in the events tab and look for an event that might fit the bill

#

If it’s not events, it might be a built in trigger or a sensor. In both of those cases you’d need to search for that info

plush willow
#

okay i will search for it

marble jackal
plush willow
#

That is right. But unfortunately i think it is not possible to get the entered alarm code in this alarm control panel template.

crude tartan
#

Can I make a template that just allows a user to toggle it on and off. Which then runs a node red sequence?

crude tartan
#

Yea. That’s sounds about right. Thank you.

orchid oxide
#

is it possible to include plain text in a single line if-then template? im trying to turn this into one line, but i cant figure out the proper way to format it so that it recognizes that the text is part of the output

Cleaning ({{states('sensor.current_clean_duration')}} min)
{%else%} 
{{states('vacuum.robot_vacuum')|title}} 
{%endif%}```
inner mesa
#

@orchid oxide state: "{{ iif (is_state('vacuum.robot_vacuum', 'cleaning'), 'Cleaning (' ~ states('sensor.current_clean_duration') ~ ' min)', states('vacuum.robot_vacuum')|title) }}"

orchid oxide
#

awesome thanks

scarlet sapphire
#

how can I add another template sensor for the same platform?

inner mesa
#

There are examples in the docs for adding multiple template sensors

#

Pretty sure there's a section for exactly that

scarlet sapphire
inner mesa
#

Yes

#

you mean like this?

template:
  - sensor:
    - name: test
      state: "{{ iif (is_state('vacuum.taileater_2_0', 'cleaning'), 'Cleaning (' ~ states('sensor.aarlo_total_cameras') ~ ' min)', states('vacuum.taileater_2_0')|title) }}"

    - name: Sun Angle
      unit_of_measurement: "°"
      state: "{{ '%+.1f'|format(state_attr('sun.sun', 'elevation')) }}"
scarlet sapphire
#

ah my bad, I have a restful sensor in there

inner mesa
scarlet sapphire
#

and the doc says, this only works for a single sensor per endoint

#

yeah I tried it with above and didn't work, but it's not the format but the type of sensor

inner mesa
#

a rest sensor isn't a template sensor

scarlet sapphire
#

ah my bad, I have it combined in a template with a template switch

#

based on the rest sensors on/off state

#

sorry for the inconience

#

I need to figure out a way to convert this

tidal sinew
#

{{ states.binary_sensor | selectattr('state', 'eq', 'on') | selectattr('attributes.device_class', 'eq', 'door') | list | count }}

#

I am getting this error

#

UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'device_class'

#

these are door sensors and this code was working fine until the last update

#

any ideas

inner mesa
sacred sparrow
#

I keep getting a log error because my NAS isn't on all the time. Is there a way to make a template sensor ignore if sensor.nas_status is "unavailable" ?

    nas_uptime_minutes:
      friendly_name: NAS Uptime
      unit_of_measurement: "mins"
      value_template: >
        {{ ((as_timestamp(now()) - as_timestamp(states('sensor.nas_last_boot'))) // 60)| int }}```
inner mesa
#

An availability template

sacred sparrow
#

the error I am getting is:
TemplateError('TypeError: unsupported operand type(s) for -: 'float' and 'NoneType'') while processing template 'Template("{{ ((as_timestamp(now()) - as_timestamp(states('sensor.nas_last_boot'))) // 60)| int }}")' for attribute '_attr_native_value' in entity 'sensor.nas_uptime_minutes'

#
nas_uptime_minutes:
      friendly_name: NAS Uptime
      unit_of_measurement: "mins"
      availability_template: >-
          {%- if not is_state("sensor.nas_status", "unavailable") %}
            true
          {%- endif %}
      value_template: >
        {{ ((as_timestamp(now()) - as_timestamp(states('sensor.nas_last_boot'))) // 60)| int }}```
#

like that?

inner mesa
#

It can be much simpler

#

{{ not is_state('xxx', 'unavailable') }}

sacred sparrow
#
    nas_uptime_minutes:
      friendly_name: NAS Uptime
      unit_of_measurement: "mins"
      availability_template: >
        {{ not is_state('sensor.nas_status', 'unavailable') }}
      value_template: >
        {{ ((as_timestamp(now()) - as_timestamp(states('sensor.nas_last_boot'))) // 60)| int }}
inner mesa
#

That's not what I wrote

sacred sparrow
#

how about now

inner mesa
#

Still not 🙂

sacred sparrow
#

jesus

#

sorry -monday morning here haha

#

now?

tidal sinew
inner mesa
#

There's a solution there

#

I linked to it

tidal sinew
#

I guess I don't understand the solution

inner mesa
tidal sinew
#

|rejectattr('attributes.lights', 'defined')

#

add this into my template?

inner mesa
#

Understand what it's doing and yes

tidal sinew
#

Thanks

tidal sinew
#

{{ states.door | selectattr('state', 'eq', 'on') | rejectattr('attributes.device_class','search','all')| list | count }}

#

I tried this but it only returns 0

#

I know there is one door open

inner mesa
#

I'm not aware of a "door" domain

#

you probably wanted states.binary_sensor or something else

tidal sinew
#

You are right but then how can I be sure that it only counts the binary sensors with device_class door?

#

Oh I think I got it

#

will test it now 🙂

#

nope still doesn't work

marble jackal
#

@tidal sinew The problem with your initial template is that you are taking all binary_sensors, and then select on a device class, even for those which don't have a device class defined

#

So the solution is to select only those who have a device class defined first, Rob gave you a pointer in that direction

marble jackal
# tidal sinew nope still doesn't work

try this:
{{ states.binary_sensor | selectattr('attributes.device_class', 'defined') | selectattr('state', 'eq', 'on') | selectattr('attributes.device_class', 'eq', 'door') | list | count }}

tidal sinew
#

Yes works perfect, but I don't understand this part. selectattr('attributes.device_class', 'defined')

marble jackal
#

That part does what I described above

#

With states.binary_sensor you are getting the state objects of all binary sensors. The selectattr('attributes.device_class', 'defined') takes out of this complete list, all binary_sensors which have the attribute device_class defined

#

You were getting errors because you were trying to select on a device class on binary sensors which do not have a device class attribute

tidal sinew
#

AHHHHH Ok I understand now, that makes total sense to me now. Thanks so much 🙂

mild mica
#

hey, i have this for avg humidity in my apt.

{{ (float(states('sensor.living_room_humidity')) +      
float(states('sensor.kitchen_humidity')) +           
float(states('sensor.office_humidity')) +    
float(states('sensor.master_bathroom_humidity')) + 
float(states('sensor.guest_bathroom_humidity'))) / 5 | round(2) }}%

but when i try to show it on a graph, it doesn't show as a line, but a gauge....

#

i'm trying to figure out the sensor templates, but the docs for them are a little confusing.