#templates-archived

1 messages · Page 43 of 1

floral shuttle
#

is the state of the sensor

mighty ledge
#

Just use the generator with | list | count

floral shuttle
#

argh, you mean {{media_players_active()|list|count}}...

mighty ledge
#

no, I gave you the generator above

#

here

#

just add | count

plain magnetBOT
#

@steel swift I converted your message into a file since it's above 15 lines :+1:

marble jackal
#

I would suggest to adjust the first sensor so it only gives the power value if the switch is on

#

then use that sensor in a Riemann Sum Integral (available under Helpers) to convert it to kWh

#

In any case, you won't be able to create a sensor which you can use in the Energy Dashboard using the old template sensor format, as you can't add the state_class in the old format

steel swift
#

Would that help anything, that sensor is reporting. When on/off I must admit though that I am really not sure what the Riemann sum does. The sensors are customized ´´ homeassistant:
customize:
sensor.varmekabel_garderobe_runtime:
state_class: measurement
last_reset: '1970-01-01T00:00:00+00:00'
sensor.varmekabel_garderobe_totalt_forbruk:
device_class: energy
unit_of_measurement: "kWh"
state_class: total_increasing
last_reset: '1970-01-01T00:00:00+00:00'

utility_meter:
varmekabel_garderobe_runtime:
source: switch.varme_garderobe
cycle: hourly´´

marble jackal
#

if you would just use the new template sensor format, you don't need all this customizations

#

and you don't need last_reset for both

plain magnetBOT
marble jackal
#

oh wait, you were already checking if the switch was on

#

just use that first sensor in the Riemann Sum integral, and you will have kWh as return

#

in the new format that would be:

template:
  - sensor:
      - unique_id: power_sensor_varmekabel_garderobe_forbruk
        name: "Varmekabel Garderobe Forbruk"
        unit_of_measurement: "W"
        state: >
          {% if is_state('switch.varme_garderobe', 'on') %}
            {% set voltage = states('sensor.voltage_phase2_hjemme') | float %}
            {% set resistance = 105 %}
            {% set power = (voltage * voltage) / resistance %}
            {{ power | round(2) }}
          {% else %}
            0
          {% endif %}
        device_class: power
        state_class: measurement
        availability: "{{ 'switch.varme_garderobe' | has_state and 'sensor.voltage_phase2_hjemme' | has_state }}"
floral shuttle
#

just so I understand better, why is that optimal?

steel swift
#

Ok, I will try that. Still pretty new in Home Assistant world and try to learn by doing, appreciate all the help I get.

marble jackal
#

which will result in sensor.varmekabel_garderobe_forbruk based on the name

floral shuttle
#

had my quakes template look like this now: {% set km = states('input_number.quakes_near')|float %} {% set location = states('input_select.quakes_near') %} {% from 'quakes.jinja' import quakes %} {% set ns = namespace(count=0) %} {% for s in quakes().split(',')|reject('eq','')|list if distance(s.entity_id,location) < km %} {% set ns.count = ns.count + 1 %} {% endfor %} {{ns.count}}

mighty ledge
#

when you use | list, you generate all items

#

the for loop will only generate what it needs

#

remove the |list

steel swift
marble jackal
#

You can just set it up under helpers.
I don't expect the sum method really matters here, the power value will be quite stable as the only variable is the voltage (besides the state of the switch)

uneven pendant
#

not sure if this is a template question or something that already exists.

I have a router that will tell me every 5 seconds the current KB/s but not data usage totals. I want to take the values, find the average of the four seconds not reported on based on the value of the two values surrounding them, then calculate the total data used for the entire day.

#

Is that something I can do with existing helpers, or do i need to come up with some template to do this

steel swift
# marble jackal You can just set it up under helpers. I don't expect the sum method really matte...

Just states unknown so I am probably doing something wrong `` sensor.garderobe_forbruk_varme
Garderobe Forbruk Varme
unknown state_class: total
source: sensor.varmekabel_garderobe_totalt_forbruk
icon: mdi:chart-histogram
friendly_name: Garderobe Forbruk Varme
sensor.varmekabel_garderobe_belastning
Varmekabel Garderobe Forbruk
549.49 unit_of_measurement: W
friendly_name: Varmekabel Garderobe Forbruk ```

marble jackal
marble jackal
#

Is that the config for the Riemann Sum Integral? Just set it up in the GUI

steel swift
steel swift
steel swift
lofty mason
#

your input sensor for the riemann should have device_class: power, and then I believe the riemann sensor will automatically have device_class: energy

#

if it doesn't I guess you can just add it with customize, or fix the source sensor

steel swift
marble jackal
#

State class is only supported in the new format

#

I already mentioned that 🙂

steel swift
#

And the new format is " Template: " Tried that, but probably did something wrong again, slow learner.

steel swift
plain magnetBOT
#

@steel swift I converted your message into a file since it's above 15 lines :+1:

mighty ledge
#

@steel swift you keep putting in the sensor section

#

the new style does not go in the sensor section

#

it goes in configuration.yaml

steel swift
#

So I cant have a sensor.yaml?

mighty ledge
#

literaly copy/paste of what thefes wrote

#

you can, but what thefes wrote goes in configuration.yaml

#

not sensor.yaml

steel swift
mighty ledge
#

I don'tknow what you're asking

#

the new template styles goes in configuration.yaml

#

that's it

#

there's nothing else to it

#

it does not go in sensor.yaml and it's contents are meaningless to what thefes wrote

steel swift
#

ok, so If I keep my sensor.yaml. It will be for the sensors I already have, and not have converted to the new style.

#

Thank you, for youre patience, appreciate it.

plain magnetBOT
#

@steel swift I converted your message into a file since it's above 15 lines :+1:

kindred crow
#

I have silly question, quite new to HA, I'm designing my dashboard via minimalist theme, but somehow I can't add any custom cards

#

I add files to custom_cards folder, but they dont get detected

mighty ledge
icy jay
#

any idea?

craggy adder
#

hey everybody!

really struggeling with this organizational thing.

I want to either:

  1. have multiple yaml files for template sensors (eg. my_computer.yaml,aparment_sensors.yaml,xyz_sensors.yaml) which i could include into configuration.yaml

or

  1. have custom "headlines" or "brackets" inside the sensors.yaml, for easier navigation (as inside the code.txt)

but here I get the error: Missing property "value_template"

plain magnetBOT
#

@craggy adder I converted your message into a file since it's above 15 lines :+1:

marble jackal
steel swift
dreamy sinew
#

is_state() is a thing. could do not is_state() and not is_state()

haughty breach
haughty breach
marble jackal
#

My bad

fast kettle
steel swift
craggy adder
#

it does not work indefinitely, just one Level of "brackets"/comments is possible

floral shuttle
#

is there a preferred extension? there's a whole list of them ..

marble jackal
#

I use better jinja, not sure if that is the best one

floral shuttle
#

thanks, wil. install. could you please have a look with me here:```
{% set km = states('input_number.quakes_near')|float %}
{% set location = states('input_select.quakes_near') %}

      {% from 'quakes.jinja' import quakes %}
      {% set ns = namespace(count=0) %}
      {% for s in quakes().split(',')|reject('eq','')
         if distance(s.entity_id,location) < km %}
          {% set ns.count = ns.count + 1 %}
      {% endfor %}
      {{ns.count}}```
#

and I am trying to write it in the fomr of {{expand(quakes().split(','))|reject('eq','') |map(attribute='state') |map('int',default=0) |select('<',km) |list|count}} but get stuck with the distance()

#

or cant I do that without the namespace

marble jackal
#

What's the result of this quakes macro?

#

If they are entity_ids, you need to use map('states') instead of map(attribute='state')

floral shuttle
marble jackal
#

Oh wait, I missed the expand

floral shuttle
#

so if I set the km to 500, and select my phone, wanr me if quakes are within 500km near me

marble jackal
#

Which you don't need anyway

floral shuttle
#

the expand version was merely c&p of my battery sensor... which is way easier ofc

marble jackal
#

But quakes() returns a comma separated string with entity_ids right?

floral shuttle
#

yes, the custom_template is:{%- macro quakes() -%} {{- states.geo_location |selectattr('attributes.source','defined') |selectattr('attributes.source','eq','usgs_earthquakes_feed') |map(attribute='entity_id') |list|join(',') -}} {%- endmacro -%}

#

this was my original pre-macroe jinja template: {% set km = states('input_number.quakes_near')|float %} {% set location = states('input_select.quakes_near') %} {% set ns = namespace(count=0) %} {% for s in states.geo_location |selectattr('attributes.source','defined') |selectattr('attributes.source','eq','usgs_earthquakes_feed') if distance(s.entity_id,location) < km %} {% set ns.count = ns.count + 1 %} {% endfor %} {{ns.count}}

#

sorry pasted the wrong template..

marble jackal
#

You don't need both list and join()

floral shuttle
#

heck , I have that in all my custom_templates... ergh, c&p monster, thanks for spotting that

marble jackal
floral shuttle
#

that is what I posted?

icy jay
#

Hey

Ive got the sensor thats giving me
[‘sensor.x_diesel‘, ‘sensor.x_diesel‘, ‘sensor.x_diesel‘]

And i want to get a output in a notification like:

  • friendlyname1 value1
  • friendlyname2 value2
  • friendlyname3 value3

Can somebody help pls?

floral shuttle
#

you would want this: {% set d = expand('sensor.x_diesel1', 'sensor.x_diesel2', 'sensor.x_diesel3') %} {% for x in d %} {{x.name}} : {{x.state}} {% endfor %}

marble jackal
#

But you don't need to expand it

#
 {{ quakes().split(',') 
      | reject('eq','')
      | map('states')
      | map('int',default=0)
      | select('<', km)
      | list | count
}}```
#

Also the default to 0 is working against you here, as you are now going to count the ones which are unavailable

#

Better to default it to km

floral shuttle
#

a yes, that is already much cleaner. what this doesnt do yet, is take into account the if distance(s.entity_id,location) < km %} form the original template

#

and I cant see how I can do that without the namespace..

#

same as that I can list the low level batteris like that: {% set alert_level = states('input_number.battery_alert_level')|int(default=0) %} {% from 'batteries.jinja' import batteries %} {{batteries().split(',') |reject('eq','') |map('states') |map('int',default=0) |select('<',alert_level) |list|count}} but still require the namescpace to list those: {%- set alert_level = states('input_number.battery_alert_level')|int(default=0) %} {% from 'batteries.jinja' import batteries %} {%- set ns = namespace(batt_low=[]) %} {%- for s in expand(batteries().split(',')) if s.state|int(default=0) < alert_level %} {%- set ns.batt_low = ns.batt_low + [' ' + s.entity_id] %} {%- endfor %} {{- ns.batt_low|join(',')}}

marble jackal
#

Unfortunately distance() is not available as filter, do you can't use it in map()

floral shuttle
#

1 error on reloading templates: Error validating template result 'unavailable' from template 'Template<template=({{states('sensor.presence_icon')|default('mdi:account-off')}}) renders=5>' for attribute '_attr_icon' in entity sensor.familie_samenvatting validation message 'contains non-whitespace: unavailable' happening on an icon template: icon: > {{states('sensor.presence_icon')|default('mdi:account-off')}}

#

I've never seen that before though,. I didnt have the default, so hoped setting that would fix the error, but it doesnt. Any ideas what might happen here?

#

the template for that entity presence_icon is```
sensor:

  - unique_id: presence_icon
    state: &icon
      >
        {% set presence = states('zone.home')|int(0) %}
        {% set mapper = {0:'mdi:account-off',
                         1:'mdi:account',
                         2:'mdi:account-multiple',
                         3:'mdi:account-multiple-check'} %}
        {{mapper.get(presence,'mdi:account-group')}}``` so should be guared againts unknowns itself
marble jackal
#

unavailable is a valid state, so default does nothing there

floral shuttle
#

yes, confirm. ill take that out again 😉

marble jackal
#

Reloading templates will render then all unavailable for a short moment

floral shuttle
#

but contains non-whitespace? is that just cryptic for: the template sensor was unavailable?

#

maybe I should not use another template sensor insiode a template sensors options

marble jackal
#
        icon: >
          {{states('sensor.presence_icon') if 'sensor.presence_icon' | has_value else 'mdi:account-off' }}```
#

I don't see whitespace being relevant here

#

icon: "unavailable" is invalid

floral shuttle
#

ok, yes Ill use that. would be a pity if I had to recreate that template. otoh, makes me think now: i use it in more places in the config, maybe I should make it availble in the custom_templates as macro.

#

btw: Error validating template result 'unavailable' from template 'Template<template=({{states('sensor.presence_icon') if 'sensor.presence_icon'|has_value else 'mdi:account-off' }}) renders=5>' for attribute '_attr_icon' in entity sensor.familie_samenvatting validation message 'contains non-whitespace: unavailable'

marble jackal
#

That should not render unavailable

floral shuttle
#

2 observations: 1) adding the full template in the icon template and reloading fixes the error.
2) when using this in dev templates, reloading templates does not change that for the short moment the templates are unavailable.

mighty ledge
#

most entities restore state now on startup

#

templates are no execption to that

#

and knowing your templates, you're probably self referencing

floral shuttle
#

not in this case..

floral shuttle
#

btw, could it be the intensified use of those custom_templates is memory expensive:

mighty ledge
#

no

#

unless you're talking ram, then it potentially could

#

but it would be minimal

floral shuttle
#

+50% isnt minimal...

mighty ledge
#

then it's probably not coming from that 😉

fickle sand
#

An observed change after a manual change does not directly imply causality when many factors can increase/decrease ram usage

floral shuttle
#

Seems@more than just a correlation tbh. But no hard evidence yet, will need to disable the new additions for that

icy jay
fickle sand
icy jay
#

the state is a list of the sensors like: [‚sensor.x_diesel’,‘sensor.x_diesel‘,‘sensor.x_diesel‘]

x is replaced by the actuall adress of the gas stations nearby

fickle sand
#

A state is always a string so that should either first be transformed to a list type or use it in an attribute that exactly can be any type, including a list

#
{% set d = expand(states('sensor.gasstation').split(',')|list) %}
{% for x in d %}
{{-x.name-}}: {{x.state}}
{% endfor %}
icy jay
#

That doesnt seem to work. Thats the sensor:

        value_template: >
          {% set sensors = integration_entities('tankerkoenig') %}
          {% set ns = namespace(map={}) %}
          {% for s in sensors %}
          {% set ns.map = dict(ns.map, **{s: states(s)}) %}
          {% endfor %}
          {{ (ns.map.items()|sort(attribute='1')|map(attribute='0')|list)[0:3] }}
mighty ledge
#

put that in an attribute and then use what marius wrote

#

having that as the state will cause problems for you

#

You'll be coming here asking us to fix it forever

icy jay
#

Sorry dont know how to do this. The template is from RobC

mighty ledge
#

literally copy/paste that template into an attributes template on that template sensor

icy jay
#

Im sorry but i still dont know how. Im just not really into templating

mighty ledge
#

it's not templating at that point

#

it's yaml

#

you're going to have to try

#

if you cant figure it out, post what youve tried

#

but right now you're giving up without doing anything and that's insulting to anyone trying to help you. Because all you're doing is expecting us to do it for you.

icy jay
#

Nah im not expecting anything. Im just asking for help, if you dont want to help, thats fine. If you help, im really thankful.

mighty ledge
#

do you know how to copy?

#

if yes, then do you know how to paste that value somewhere else?

#

if yes, then all you need to do is add an attributes template to your template senosr by copying and pasting it

#

here's an example binary_senosr with attribute templates

#

here's an example of the legacy format (which you're using)

#

Once you have that setup, we can help you with the tempalte using the attribute you created.

icy jay
#

Got the attributes so far, thx

#

So the sensor gives me the attribute „cheapest“ with the value of sensor.x_diesel, sensor.x_diesel, sensor.x_diesel

mighty ledge
icy jay
#

That works!
If i output this as a notification, how can i show one information per line?

true otter
#

morning , I am looking for any help I can get concerning this template. I have a button card that displays the state of the door and the lock via a sensor template. because I am using sensor templates the standard tap action will not function. I found this tap_action template that Petro had helped someone else with tap_action: action: call-service service: | [[[ return (entity.state === 'locked') ? 'lock.unlock' : 'lock.lock'; ]]] service_data: entity_id: lock.garage_laundry_door_lock_door_lock the problem I think I am having is that in Petro example the entity_id referenced back to the original entity, which is a sensor. Here is the full card http://pastie.org/p/7uWEehpPIHNAcLYHpAO4W4

mighty ledge
#

it's either that or states['lock.garage_laundry_door_lock_door_lock'].state

#

most likely the second one

floral shuttle
#

And you probably be able to use ‘toggle’ instead of that action template

floral shuttle
icy jay
true otter
floral shuttle
#

You could still use that if you set the correct entity in the tap config . You can really set anything there.. it’s the power of custom button-card

mighty ledge
#

IOS does not

#

Can't answer for andriod

icy jay
#

I have a working blueprint that does exactly this on ios, are you sure?

mighty ledge
#

if it's possible, then what was written will work. If it's not possible then what was written will show up as a single line

#

whitespace is retained in templating

true otter
icy jay
mighty ledge
#

Nothing, they both do the same thing

#

blueprint is just a blueprint

icy jay
#

Then its possible on ios to do this or am i wrong

mighty ledge
#

without seeing the blueprint.... 🤷‍♂️

icy jay
#

give me a sec

floral shuttle
marble jackal
#

This tells nothing, as you provided the notification action yourself when setting up the automation

fickle sand
#

I think it's about line:

    {{"⤵ \n- "}}{{result.sensors|join('\n- ')}}
icy jay
#

and this results in a notification:
Homeassistant
Low batteries in: ⤵️

  • sensor1
  • sensor2
fickle sand
icy jay
icy jay
sonic sand
#

hi there, trying to update my HA OS and getting msg that I should move all my sensors that are on configruation.yaml to other yamls
The only sensor i'm not managing to move correctly is this one:

  - platform: template
    sensors:
      any_phone_at_home:
        value_template: "{{ is_state('device_tracker.elians_iphone', 'home') or is_state('device_tracker.ofir_phone', 'home') }}"
        device_class: presence

should I move it to sensors.yaml or templates.yaml ?

mighty ledge
#

sensor.yaml

sonic sand
mighty ledge
#

if it's a binary sensor, then it would go in binary_sensor.yaml not sensor.yaml

sonic sand
#

that did the job, thanks mate

plain magnetBOT
#

@sonic sand I converted your message into a file since it's above 15 lines :+1:

inner mesa
#

you should fix the issue that it reported

#

see the command_line sensor documentation

thorny cargo
#

How would I create a virtual sensor that mimics a input_boolean?

neat prairie
#

the command line stuff is basically:
rather than having:

  type: command_line```

you have 
```command_line:
  sensor:
    sensor definitions go here.```

it's mentioned in the breaking changes
#
  - sensor:
      name: CPU Temperature
      command: "cat /sys/class/thermal/thermal_zone0/temp"
      unit_of_measurement: "°F"
      value_template: "{{ value | multiply(0.001) | multiply(1.8) | round(1) | float + 32}}"```
#

like this 🙂

marble jackal
inner mesa
#

Yeah, that sounds like a poorly-informed human said that

thorny cargo
inner mesa
#

what do you mean by "mimic"?

#

displays the value of an input_boolean?

thorny cargo
#

If the input bool is on the sensor should say on and vice versa

#

yes

inner mesa
#

simplest possible template sensor

thorny cargo
#

I just need a dummy so it cannot be accidentally toggled

inner mesa
#
template:
  - binary_sensor:
    - name: my_boolean
      state: "{{ states('input_boolean.whatever') }}"
thorny cargo
#

Does this require a HA restart?

inner mesa
#

do you already have a template: section?

thorny cargo
#

nope

inner mesa
#

then yes

#

it's clear to you what that does?

thorny cargo
#

I suppose. Does the name not need quotation marks?

inner mesa
#

no

#

I just hope it's a learning opportunity, because it's a really, really simple template

thorny cargo
#

Cannot quick reload all YAML configurations because the configuration is not valid: Error loading /config/configuration.yaml: mapping values are not allowed here in "/config/configuration.yaml", line 47, column 11

inner mesa
#

🤷

#

what's there?

thorny cargo
#

The name line

inner mesa
thorny cargo
#

Ok, there was a missing column colon

#

Reloaded yaml but cant seen the sensor anywhere.

inner mesa
#

sounds like you asked if you needed to restart, I said yes, and then you didn't?

thorny cargo
#

I restart again now.

#

Ok, working now. Thank you!

#

Now it´s gone again. WTF

#

Can I relace on/off by different words on my dashboard?

inner mesa
#

I suggest reading that page

thorny cargo
#

I get that, but where would I use such a iif template?

#

In the dashboard config?

orchid oxide
#

im trying to change my command line sensor over from the old yaml type to the new type, but im getting an error that seems to be related to using a l iteral scalar

extra keys not allowed @ data['command_line'][0]['command']. Got 'cat /config/.storage/person'
extra keys not allowed @ data['command_line'][0]['name']. Got 'devicetrackers'
extra keys not allowed @ data['command_line'][0]['value_template']. Got "{{((value_json['data']['items']| selectattr('name', 'equalto', 'jack5mikemotown') | first)['device_trackers']|select ('in', integration_entities('mobile_app'))|list)}}". (See /config/configuration.yaml, line 219).```
for this:
```    command: |
      echo "$(sed -n '/^{/,/"entries": \[/p' /config/.storage/core.config_entries) $(sed -e 's/^/{/' -e '$ s/,$//' -e 's/,$/},/' /config/.storage/core.config_entries | grep -w "\"domain\"" | sed '$ s/,$//' | awk '!seen[$0]++') ]}}"
#

how am i supposed to fix this 😅

#

and yes, i realize the command is horrendous

#

if i remove the scalar most of the errors go away but then i get
Error loading /config/configuration.yaml: mapping values are not allowed here in "/config/configuration.yaml", line 226, column 51
which is referencing t he : in that line

orchid oxide
#

i might have had bad formatting but, i just went ahead and redid the entire command to be less convouted lmao
command: "jq '.data.entries |= map ({domain: .domain})' /config/.storage/core.config_entries"
prertty sure its fixed now anyways

void robin
#

Hi,
I am trying to calculate the amount of water in a barrel based on the distance from a sensor.
The problem is that to save battery the esp module goes into deep sleep and only sends back values every 10 minutes. This means that the tasmota sensor is in an "unavailable" state most of the time.
How to I retrieve the last numeric value from the sensor and use that in my template?

harsh hull
#

Hi,
can someone give me a hint how to create statistics from a template senser like this?

sensor:
  - platform: template
    sensors:
      og_bad_floor_local_temperature:
        friendly_name: "OG BAD FLOOR local temperature"
        unit_of_measurement: "°C"
        value_template: "{{ state_attr('climate.og_bad_floor', 'local_temperature') }}"
        device_class: temperature
compact rune
#

Change to to a non-legacy format template sensor and add a state class

harsh hull
compact rune
#

I think there isn't, not that I know of anyway.

fickle sand
#

You can only control the interval with a time-based trigger template sensor

plain magnetBOT
#

@sonic sand I converted your message into a file since it's above 15 lines :+1:

#

@sonic sand I converted your message into a file since it's above 15 lines :+1:

sonic sand
#

Fixed this error, nevermind 🙂

mighty ledge
#

@sonic sand that's not a command line switch, that's a template switch.

sonic sand
#

Yeah, I found the command line hidden in the other .yaml file. I thought this error only comes from the main configuriation.yaml file.

mighty ledge
#

the error refers to the integration, not what file it's in

sonic sand
#

yep

#

thanks anyway

mighty ledge
#
{% set hours = states('input_boolean.hours') | int %}
{% set start = today_at(states('input_datetime.a'))) %}
{{ start <= now() <= start + timedelta(hours=hours) }}
#

message was deleted but this is the answer

bronze tide
# mighty ledge message was deleted but this is the answer

thanks for your effort. I had a similar approach, but some bracket was in the wrong position. Here is my - still to be simplified - approach:
{{ (now() >= today_at(states('input_datetime.zb_charger_uh_charging_delayed_start_at'))) and (now() <= (today_at(states('input_datetime.zb_charger_uh_charging_delayed_start_at')) + timedelta(hours = 8, minutes = 0))) }}

mighty ledge
#

yep, just realize that you don't need to specify minutes

#

unless you plan on adding minutes as an input

marble jackal
worthy edge
#

what is the best/most efficient way to get numerical day of the week

#

now().strftime('%w')|int is what i use now

inner mesa
#

{{ now().weekday() }} or {{ now().isoweekday() }}

worthy edge
#

does it return int or 01, 02 etc

inner mesa
#

I just googled for 'python day of week'

worthy edge
#

ha, thanks 😉

#

cool, my convoluted calculation is now as simple as {{ (now().isoweekday()/10 + 3)|round(0) <= states('sensor.water_hater_power_meter')|float }}

#

does it cast it to float upon division?

mighty ledge
#

yes

#

why are you dividing it by 10

#

and then adding 3

#

odd...

worthy edge
#

i want to have 3kwh of quota for mon-thur and 4kwh quota for fri-sun

mighty ledge
#

do //10

#

and remove the round

worthy edge
#

what does it do

#

oh

mighty ledge
#

keeps it an int

worthy edge
#

but then the sensor is float anyway

mighty ledge
#

so what

worthy edge
#

well, i come from ancient times of asm and c 😉

#

i thought the types need to match

mighty ledge
#

most languages can handle int vs double/float without problems

worthy edge
#

kewl

#

thanks

mighty ledge
#

np

worthy edge
#

{{ (now().isoweekday()//10 + 3) <= states('sensor.water_hater_power_meter')|float }}

mighty ledge
#

might need it to be //5

worthy edge
#

i assume i dont need to cast the sensor either

#

hm, true

mighty ledge
#

acutally 4

worthy edge
#

{{ (now().isoweekday()//5 + 3) <= states('sensor.water_hater_power_meter') }} yeah, makes more sense now

mighty ledge
#

to get fri/sat/sun

#

5 only gets you sat/sun

worthy edge
#

5/5 gives out 1 already

#

and isoweekday starts with 1

mighty ledge
#

👍

worthy edge
#

awesome, simple and elegant

inner mesa
#

you should really keep the |float

#

that state is now a string

heavy crown
#

Hi, I added a entity_picture via customize.yaml. It is working in some cards but I want more control for other cards. This value is not shown in the sensor atributes however, is there a way how I can get to its value ?

#

This may be something for frontend but I need it in a template...

mighty ledge
#

it'll be an attribute, look in developer tools -> states page

heavy crown
#

not visible

#

I would have expected it there to but nope

#

sensor.flight_tracker_opensky:
entity_picture: /local/pictures/airplane_1.png

#

is what I have in customize.yaml

#

and it shows e.g. on th emap card

worthy edge
#

or both

inner mesa
#

any time you're trying to do math on a string, and all states are strings

#

you removed the |float

worthy edge
#

but theres no string to the left

inner mesa
#

you should put it back

worthy edge
#

the math returns int

inner mesa
#

yes, that's the problem

heavy crown
#

My sensor shows this as attributes

inner mesa
#

yes

#

and the state is a string

heavy crown
#
restored: true
friendly_name: Flight Tracker Opensky
supported_features: 0
```
worthy edge
inner mesa
#

like you had earlier

worthy edge
#

ok, cool, thanks

mighty ledge
#

Sorry rhqq, when I said "most software handles that", I meant comparing ints/doubles, not int and string

worthy edge
#

no worries, i didnt know the right side would return a string

mighty ledge
#

all states are strings

#

have to cast em if you want a number

worthy edge
#

oh cool

#

okay, something i've learned today

#

thanks

heavy crown
#

as my question got scrambled in other discussion 🙂 ... any idea how I can get to the customized attribute?

mighty ledge
#

it should be showing up, if it's not then I'm not sure what to tell you

heavy crown
#

well... I can only state what I see, usable in e.g. map card, not visble in the sensor itself.

#

github entry?

mighty ledge
#

probably not

#

picture_entity always shows up as an attribute unless it was purposely removed in recent times

heavy crown
#

well. ... I donot know the history, and this is the ONLY customize I have so far so no experience mor ethan this.

mighty ledge
#

did you put it in the correct spot? Is the entity generated with a unique_id?

heavy crown
#

yes, i.e. I can modify it with icon a.o.

mighty ledge
#

well, your image is coming from the entity config then and you can't customize it via yaml

heavy crown
#

ok...hmm.... so how can I add a entity_picture to this type of object then?

mighty ledge
#

you change it in the UI

#

but it won't be an attribute

heavy crown
#

so if I want a custome picture for a few objects (in this case these are flights) and I want to call upon them in templates (ful path).....any idea?

mighty ledge
#

you can add custom attributes that are not 'entity_picture' that hold the info

heavy crown
#

ah.... thanks...will dig into that ... 👍

mighty ledge
#

nothing to dig into, just add something after entity_picture that has the same info as entity_picture

#

in customize.yaml

heavy crown
#

clear...dig was a bit too much 😃

inner mesa
#

assuming you're actually including that under homeassistant:

heavy crown
slow vine
#

can I put literal text {% else %} in a template with out it being proccessed as part of the template? I tried " and ' and it didn't help.

mighty ledge
#

no

#

if you want to comment things, use comment blocks

#

{# lkdjalfjdsl d #}

#

see pin 1

slow vine
#

I want it to print it though, as literal text.

inner mesa
#

are you trying to have a template print a template?

mighty ledge
#

then don't put anything around it

inner mesa
#

templateception

mighty ledge
#

{% if ... %}
blah
{% else %}
blah2
{% endif %}

#

if you want to print a template from a template... you have to use {% raw %}.... {% endraw %}

wet olive
#

How do I see that my template got added after reloading my configuration?

mighty ledge
#

developer tools -> states

floral shuttle
#

having a calm moment in the config allows me to revisit template select once more. using an input_select for my themes, and an automation using that as trigger, I tried to rewrite that as:```

  • select:

    • unique_id: thema_selectie
      name: Thema selectie
      state: >
      {{states('input_select.theme')}}
      options: >
      {{state_attr('input_select.theme','options')}}
      select_option:
      • service: frontend.set_theme
        data:
        name: >
        {{option}}```
#

which works fine as such. But, I still need that input_select for its options. (unless I write those options, which now are created in the UI, in a verbose list probably). Making me wonder if I do this correctly, not seeing the advantage of the selec template...

plush willow
#

I have an Aqara temperature sensor which I have set in the UI to use 1 decimal (precision)

In Mushroom I use this code: {{ states('sensor.hal_temperatuur') | replace (".",",") }}. The problem is that it shows 2 decimals precision instead of 1. This is also the case in the developers tools. What do I wrong?

marble jackal
floral shuttle
#

yes, and its not reliable without this: - unique_id: thema_selectie name: Thema selectie state: > {{states('input_select.theme')}} options: > {{state_attr('input_select.theme','options')}} select_option: - service: frontend.set_theme data: name: > {{option}} - service: input_select.select_option target: entity_id: input_select.theme data: option: '{{option}}'

mighty ledge
floral shuttle
#

soin the and this is just a replacement for an automation, ut requires all the same parts..

mighty ledge
#

and instead of using the input select to hold your otions, just list your options as an output of options:

floral shuttle
#

or maybe even more, because this was all i the automation:```

  • alias: Change current theme
    id: change_current_theme
    trigger:
    platform: state
    entity_id: input_select.theme
    action:
    service: frontend.set_theme
    data:
    name: >
    {{states('input_select.theme')}}```
marble jackal
mighty ledge
marble jackal
#

I wrote this WTH on it last year

mighty ledge
#

all other template entities restore state

#

Maybe I'll look into it on my freetime

floral shuttle
#

"they could completely replace" would only hold if we could list those options in the UI?

marble jackal
#

I thought state based template sensors just get re-rendered based on their state template

#

so a state based template select also does that

floral shuttle
#

currently my input_select options are in UI, but the template select is in yaml only? Or is that because I use yaml mode...

mighty ledge
marble jackal
#

basically the bug is that a trigger based select doesn't then

marble jackal
floral shuttle
#

yes, so listing those is yet another disadvantage

marble jackal
#

on the other hand it has the potential to make them dynamic, which you don't have in the GUI

#

if you could list all your themes using a template, you could use a template to define the options

floral shuttle
#

yes, but that would be a moot thing, because the template should be written in yaml too (Ive done that...)

mighty ledge
#

personally, I'd go with the template select entity and hide the input_select

#

you can also completely remove the input select and just have an input_text

#

and put all your logic into your template

#

or a macro

#

well, not macro a variable

marble jackal
#

you can select an icon by using the icon key

mighty ledge
#

my_selects.jinja

{% set themes = {
   'a': 'Theme name',
   'b': 'Theme name 2',
} %}

Then in your template...

{% from 'my_selects.jinja' import themes %}
{{ themes.keys() | list }}
#

for options

#

I'll just write out the whole thing

floral shuttle
#

yeah, because im also strugglin with the state: in the case of ditching the input_select.. what do we use for that in the case of only having a select template

mighty ledge
#
      - unique_id: thema_selectie
        name: Thema selectie
        state: >
          {{ states('input_text.theme') }}
        options: >
          {% from 'my_selects.jinja' import themes %}
          {{ themes.keys() | list }}
        select_option:
          - service: frontend.set_theme
            data:
              name: >
                {% from 'my_selects.jinja' import themes %}
                {{ themes[option] }}
          - service: input_text.set_text
            target:
              entity_id: input_text.theme
            data:
              option: "{{ option }}"
#

(I don't know if set_text is the correct service call, I'll let you look that up)

floral shuttle
#

I'll experiment there. thx. my main issue remaining: if we still need the input_select for the state: of the template select, why not simply use the input_select for all other bits and pieces

mighty ledge
#

my man, no input_select is used, please read the code

#

an input_text and a select entity

#

and 1 dictionary as the source for your options

#

all yaml

#

(and jinja)

floral shuttle
#

input_text, input_select. we need an extra helper.

mighty ledge
#

yes, but the helper does not need options

#

it's just a set and forget

marble jackal
#

about the losing state thing, just to test it again I created this select

- trigger:
    - platform: state
      entity_id: input_text.test
  select:
    - unique_id: test_select_1
      icon: mdi:test-tube
      name: Test Select
      options: >
        {{ ["A", "B", "C"] }}
      state: "{{ trigger.to_state.state }}"
      select_option:
        - service: input_text.set_value
          data:
            entity_id: input_text.test
            value: "{{ option }}"
#

doesn't make sense in usability of course, but after setting a value and a template reload it's back to unknown

#

so, especially since I'm using a trigger based template select, I would expect it to restore the state

mighty ledge
#

yeah, I consider that a bug, espeically if it's using a trigger

marble jackal
#

I'll write up an issue for it

mighty ledge
#

anyways, using the non-trigger approach will definitely "restore" state because it's resolving the helper entity, which retains the value on restart.

mighty ledge
#

You'll need to change the field in data: to value: as well then

floral shuttle
# mighty ledge ``` - unique_id: thema_selectie name: Thema selectie state...

comparing all of that with```

  • alias: Change current theme
    id: change_current_theme
    trigger:
    platform: state
    entity_id: input_select.theme
    action:
    service: frontend.set_theme
    data:
    name: >
    {{states('input_select.theme')}}``` seems to close in favor of the automation. Especially so since we can set the options of the input_select in the UI, and it is immediate, not requiring a reload custom_templates.
mighty ledge
#

You do whatever you want to do, I personally avoid the UI for all tinkering because it takes 10 years

floral shuttle
#

yes, you have a point there.. yet it has taken me months of moving everything possible to the UI, and I must admit its very adequate, responsive, immediate, and doesnt break. Ive grown to love changing names/icons, heck even entity_ids on the fly, without having to open an editor

#

all in my yaml is custom or templates. or the odd integration not yet in config entry

mighty ledge
#

and they never will be

#

So many things would need to happen in the frontend to get templates in the UI

floral shuttle
#

no, that's fine though.

mighty ledge
#

but anything yaml will never be in config_entry

#

as soon as they move the integrations to the UI, you'll get a config entry

floral shuttle
#

yes, that is cool, and from that moment on we have unique_id's, and we can edit the entities in the UI. just like with template now: Ive taken out all icon/name etc from the yaml, as I can set it in the UI. Themes allow for custom colors per domain, so my custom_ui has decreased with 80%. we even can set show_as, or change units in the UI. really its very nice. My Yaml for templates is nowhere near what is used to be 😉

supple tapir
#

Template to create sensor of tide height

#

started a thread, any help appreciated!! thank you 🙂

plain magnetBOT
#

@floral shuttle I converted your message into a file since it's above 15 lines :+1:

livid hearth
#

Problem was solved, thanks 🙂 My bad- consequtive writes to same topic created a rush with overwriting data before processing 😦 Problem was:Stuck on getting data from Tasmota to HA. Tasmota sends to MQTT like this: RESULT = {"SerialReceived":{"Toast":"32"}} but I am having trouble to create a mqtt sensor from it. Is the problem with "" around the 32 data? HA complains: Template variable warning: 'dict object' has no attribute 'Toast' when rendering '{{value_json.SerialReceived.Toast}}'

floral shuttle
#

TheFes, didnt you have some of these translated? its a pain with all of these changing words in Dutch... 😉

mighty ledge
#

aren't you using easy_time?

floral shuttle
#

sure! is that in there too? and the accompanying couter down to dec 31st?

mighty ledge
#
{% from 'easy_time.jinja' import big_time %}
{{ big_time(now().replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0)) }}
livid hearth
#

`mqtt:
sensor:
- name: 'Magamistoa LG toast'
unique_id: lghvacairtempsleep
state_topic: "tele/tasmota_EE44FC/RESULT"

json_attributes_topic: "tele/tasmota_EE44FC/RESULT"

json_attributes_template: >

{"Toast":{{value}}}

  value_template: "{{value_json.SerialReceived.Toast}}`"
floral shuttle
#

that horrific dev tools window.... trying to add the language

#

ooh, but nice! almost perfect! returning '23 weken, 5 dagen, 14 uren en 52 minuten' were would always say 23 weken, 5 dagen, 14 uur en 52 minuten in Dutch..

#

can we use Bigtime also for counting down to next new year?:```
{% set Year = now().year +1 %}
{% set newYear = as_timestamp(strptime('01/01/' ~ Year, '%d/%m/%Y')) %}
{% set now = as_timestamp(now().astimezone())%}
{% set New = newYear-now %}

#

btw given the generic usability of the following, it might be nice for easy_time too?:```
- unique_id: sunset_offset
state: >
{% set nw = now().timestamp() %}
{% set ss = as_timestamp(state_attr('sun.sun','next_setting')) %}
{{'- ' if nw < ss}}{{(nw - ss)|abs|timestamp_custom('%H:%M:%S',false)}}

  - unique_id: sunrise_offset
    state: >
      {% set nw = now().timestamp() %}
      {% set ss = as_timestamp(state_attr('sun.sun','next_rising')) %}
      {{'- ' if nw < ss}}{{(nw - ss)|abs|timestamp_custom('%H:%M:%S',false)}}
floral shuttle
#

yep!, missed big_relative_time, and had to fiddle a bit to get the new new year in there.. {% from 'easy_time.jinja' import big_relative_time %} {% set year = now().year +1 %} {% set new_year = year~'-01-01 00:00:00' %} {{ big_relative_time(new_year, language='nl') }}

marble jackal
#

I issued a PR to have it changed 🙂

floral shuttle
#

cool, in my count down to next new year, is there no easy way of replacing the year +1 in {{now().replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0)}}

#

or would {% set year = now().year +1 %} {{now().replace(year=year,month=1, day=1, hour=0, minute=0, second=0, microsecond=0)}} be shortest

mighty ledge
#

if that really matters to you...

#

do what you did before

floral shuttle
#

well, its on the big screen every Christmas period...

mighty ledge
#

the template?

floral shuttle
#

well no, the output of that template

mighty ledge
#

I'm sorry, I have no idea what you're asking

#

is there a reason you need to shorten everything?

floral shuttle
#

ok, sorry for some confusion. First of all this works fine now: {% from 'easy_time.jinja' import big_relative_time %} {% set year = now().year +1 %} {{big_relative_time(now().replace(year=year,month=1, day=1, hour=0, minute=0, second=0, microsecond=0), language='nl')}}

mighty ledge
#

when dealing with your timezone, there's no replacement.

#

you have to replace all those variables and the year

floral shuttle
#

and is better than my earlier string concatenation in #templates-archived message and outputs over 28 weken, 2 dagen, 8 uren en 26 minuten just perfectly

mighty ledge
#

you could be a lazy ass and subtract

#

well, no that wouldn't work

mighty ledge
#

it assumes local

#
{% from 'easy_time.jinja' import big_relative_time %}
{{ big_relative_time((now().year +1) ~ '-01-01 00:00:00') }}
floral shuttle
mighty ledge
#

you can already do that man, please read the examples

floral shuttle
#

except that is not the same. but I will search those example to see if its in there, sorry if I indeed missed that

#

about the new years count down, they now are all identical , so that is indeed very nice

mighty ledge
#

closest is

#
{% from 'easy_time.jinja' import time_between %}
{{ time_between(now(), 'sun.sun', attr2='next_setting') }}
floral shuttle
#

yeah, guess the others are fine too, it all depends a bit what your eyes need

#

having said all of that, the Frontend has evolved since I made those templates with Phil, and using a type: attribute with format: relative isnt so bad either..

#

it could benefit from the precision of minutes we can show in the templates, but other than that it's quite nice

floral shuttle
#

grr, what am I missing now:```
{% from 'quakes.jinja' import quakes %}
{% set quakes = quakes().split(',')|reject('eq','')|list %}
{% set count = quakes|count %}
{% if count == 0 %} No Quakes registered
{% else %}
{{quakes().split(',')|map(attribute='name')|join(',\n')}}
{% endif %}

#

throws 'TypeError: 'list' object is not callable'. quakes now returns [ "geo_location.m_4_8_4_km_sse_of_courcon_france" ]

#

my custom_template for quakes is {%- macro quakes() -%} {{- states.geo_location |selectattr('attributes.source','defined') |selectattr('attributes.source','eq','usgs_earthquakes_feed') |map(attribute='entity_id') |join(',') -}} {%- endmacro -%}

plain magnetBOT
#

@floral shuttle I converted your message into a file since it's above 15 lines :+1:

floral shuttle
#

this works: {% if count == 0 %} No Quakes registered {% else %} {{quakes|join(',\n')}} {% endif %}

mighty ledge
#

You’re overwriting quakes macro with a variable

#

Change {% set quakes = to some other variable

floral shuttle
#

a yes, didnt spot that, keen eye!

#

but,, in the complex namespace, I dont have that: {% set km = states('input_number.quakes_near')|int %} {% set location = states('input_select.quakes_near') %} {% from 'quakes.jinja' import quakes %}{% set ns = namespace(count=0) %} {% for s in quakes().split(',')|reject('eq','') if distance(states[s].entity_id ,location) < km %} {% set ns.count = ns.count + 1 %} {% endfor %} {% if ns.count == 0 %} No Quake to list within {{km}} km {% else %} Quakes near: {% for s in quakes().split(',')|reject('eq','') if distance(states[s].entity_id ,location) < km %} {{- state_attr(s,'friendly_name') -}}: {{states(s)}} km{{', \n' if not loop.last else ''}} {% endfor %} {% endif %}

#

im struggling t get that saner. its working, and showing the selected quakes on the map, its just that I am positive this can be sanitized.

#

above is for listing in a markdown, for the map I use this listing: {% set km = states('input_number.quakes_near')|int %} {% set location = states('input_select.quakes_near') %} {% from 'quakes.jinja' import quakes %} {% for s in quakes().split(',')|reject('eq','') if distance(states[s].entity_id ,location) < km %} {{- states[s].entity_id -}}{{',' if not loop.last else ''}} {% endfor %} which is a bit cleaner, but it only has to list the entity_id's

cerulean cipher
#

I want to do something like this for hurricanes lol

floral shuttle
#

yah, its working nicely now, though I admit its a bit more complex than what I had before, without using that custom_templates.```
{% set km = states('input_number.quakes_near')|float(0) %}
{% set location = states('input_select.quakes_near') %}
{% for s in states.geo_location
|selectattr('attributes.source','defined')
|selectattr('attributes.source','eq','usgs_earthquakes_feed')
if distance(s.entity_id,location) < km %}
{{- s.entity_id -}}{{',' if not loop.last else ''}}
{% endfor %}

floral shuttle
pastel moon
#

Hi, trying to read my areas and exclude a few, not going great. This is what I would like to do, can't find what syntax I need for areas

{% set reject_areas = ['bathroom', 'closet'] %}                                           
{{ areas() | reject(reject_areas) | list }}```
#

I checked the docs, and areas() lists all of them, but how do I exclude some?

floral shuttle
#

try {{ areas()|reject('in', reject_areas)|list}}

still plank
#

what is my best approach for turning a date into a string "Today", "Tomorrow", "Monday" etc

sacred sparrow
#
    - name: "Living Room Warmed Up"
      availability: "{{ states('sensor.living_room_feels_like_temperature') | is_number }}"
      state: >
        {{ states('sensor.living_room_feels_like_temperature')|float >= 22.0 
        or state_attr('climate.mitsubishi_hvac','current_temperature')|int >= 23 }}"```
for some reason this won't turn on. - when I put it in the template editor it shows as on
#

but the sensor won't turn on in HA

obtuse zephyr
#

Get rid of the last " at the end

sacred sparrow
#

great pick up! thanks 🙂

sonic sand
#

morning guys,
Is there a way to set 2 different scripts depending on the state of the entity?
I will be more specific - I got input.select AC which indicates the status of the device (On / Off).
I want my tablet to be able to turn it off/on with the same button and not have two buttons for each state.

http://pastie.org/p/4HiKG5981SJQOKKpn0JrQZ
I wanna do something that if state equals On then when a click action is performed it will send the 'script.ir_turn_off_bedroom_ac'the and if state is Off it will send the other script of turning it on.
the
Thanks!

inner mesa
#

With a choose: in your script

sonic sand
fast kettle
#

Create an automation that calls one script or the other depending on the state, and use automation.trigger for the service on your button.

sonic sand
fast kettle
#

Actually no, I'm dumb, do the exact same thing but with a script, and then call that script from your button.

sonic sand
#

Let me try that

edgy grotto
#

howdy, got a strange one. i cant test the value of a attribute. see attached

#

{{ state_attr('sensor.steamdeck_power', 'status') == state_attr('sensor.steamdeck_power', 'status')}}
{{ state_attr('sensor.steamdeck_power', 'status')}}
{{ is_state_attr('sensor.steamdeck_power', 'status', "Charging")}}
{{ is_state_attr('sensor.steamdeck_power', 'status', 'Charging')}}

{{states.sensor.steamdeck_power}}

#

outputs:

#

True
Charging

False
False

<template TemplateState(<state sensor.steamdeck_power=94
; battery_present=on, charge_full=5102000
, charge_now=4806000
, level=Normal
, status=Charging
, voltage_min_design=7800000
, voltage_now=8776000
, unit_of_measurement=%, device_class=battery, icon=mdi:battery, friendly_name=Steamdeck Power @ 2023-06-18T00:43:29.931248-07:00>)>

#

any help" id like to know if its sharging or not

#

dev tools show:

#

battery_present: 'on'
charge_full: |
5102000
charge_now: |
4772000
level: |
Normal
status: |
Charging
voltage_min_design: |
7800000
voltage_now: |
8783000
unit_of_measurement: '%'
device_class: battery
icon: mdi:battery
friendly_name: Steamdeck Power

mighty ledge
#

.strip()

heavy plaza
#

hey so i am trying to create an mqtt sensor to get data from tasmota throught mqtt and i got everything to work but when i try to add "availability_topic" or "availability" to check get the online status the sensor stops working. any help is appreciated. https://pastebin.com/B3HCps5N

heavy plaza
#

Fixed it by pushing payload_available and payload_not_available right under -topic and not availability. Might be a syntax error in the mqtt sensor docs because the way shown in the example at the bottom doesn’t work (at least for me )

lyric comet
#

I was considering converting my platform: template sensors to the new template format, but I can not see how to carry over the friendly name, having to use the customise.yaml seems a strange way to have to do it, does anyone know, if there is a way to do it more logically. I have quite a lot of template sensors so it will be a big job.

inner mesa
#

You can change the name in the UI if you give it a unique ID

#

the name: is the starting point

lyric comet
#

Shame that is the only way, I will have to sort out a long list to change after I convert all of them. I have loads such as formatted_sunrise which I just want a friendly name of Sunrise.

#

It seems strange, support for it has been dropped.

mighty ledge
#

basically, a templated friendly name is what caused the conflicts.

lyric comet
#

I can obviously get around it or just not bother until the powers that be drop support for the old format as they did with the commands and I have to.

mighty ledge
#

it's not going to happen

#

the discussion has been had about 8394823984 times and there's no way to get object_id back that works with the 'naming convention' built into HA

#

with the new style

#

half of it's stupid politics

#

you can however make a script that builds your customize for you

#
{% for s in states %}
{%- if s.attributes.friendly_name is defined %}
{{ s.entity_id }}:
  friendly_name: {{ s.attributes.friendly_name }}
{%- endfor %}
#

and now you just need to transfer over and you're done

#

so make your name equal to your object_id

#

you can even write a script that does that

lyric comet
#

Thanks for that. I will write a script in lua to covert the old formats, as I can't write python.

mighty ledge
#

I just looked at lau... never heard of that language, most of that code would run in python with like 2 changes

#

selling yourself short by not just learning python IMO

lyric comet
#

I will probably get the hang of it eventually. I started programming in assembler and BASIC in 1980 on a Research machine. So I am about 15 programming languages in at this point.

lyric comet
mighty ledge
#

IDE's do that for you

#

just hit enter on the keyboard 😉

#

download VSCode, set your filetype to python, select python as the interpreter, then start writing

lyric comet
#

Me and Visual Studio code have a love hate relationship, but I have to admit it is good for editing Yaml files.

#

I have the Home Assistant extension loaded so it makes it easier.

carmine flicker
#

PyCharm > VSCode for python at least

mighty ledge
#

Lol, no way

#

maybe if you have professional edition

#

bare bones to bare bones, vscode has way more resources to just setup and run with google at your fingertips

carmine flicker
#

Students get the professional edition for free

#

And it's a full featured ide, as opposed to VSCode which is a text editor with some fluff imo

mighty ledge
#

I used pycharm for ~6 years and switched to VSCode without looking back, it's no where near a "text editor with fluff". That would be notepad++

carmine flicker
#

I've used it a bit and was underwhelmed, it's possible extensions and stuff add the features I was missing though

lyric comet
#

You do need to add in the extensions to match the languages you want to use, to get VSCode to work well.

feral sentinel
#

stupid issue, my rhasspy is doing this when im trying to pull the temperature data 'It is <template TemplateState(<state sensor.temperature=26.46; state_class=measurement, unit_of_measurement=°C, device_class=temperature, friendly_name=Temperature @ 2023-06-18T23:11:17.677035+01:00>)> degrees

inner mesa
#

it looks like you forgot to add .state

#

or something like that. You'll need to show exactly what you did

feral sentinel
#

that sounds about right

#

it's just dumping the entire sensor data instead of the state, trying that now

#

yup\

#

that fixed it

inner mesa
#

otherwise, you need to show what you did, not just the bad output

#

ok

#

then you should really be doing states('xxx')

feral sentinel
# inner mesa then you should really be doing `states('xxx')`

i honestly have never messed this before, i just pulled this from the docs to test intent_script: GetTemperature: # Intent type speech: text: We have {{ states.sensor.temperature }} degrees action: service: notify.notify data: message: Hello from an intent!

inner mesa
#

yes, like I said: states('sensor.temperature')

feral sentinel
#

these

inner mesa
#

well, that's wrong

#

created PR to fix it

sick ice
#

Can someone help me get my desired output from a template
I have four sensors like this: sensor.daily_energy_offpeak
That have attributes like this:

status: collecting
friendly_name: Off Peak

Only one is collecting at a time, I'd like to display the friendly name of the tariff that is collecting.

#

I'm doing this at the moment with The tariff period is {{states('select.daily_energy')}} but that state is not formatted like the friendly_name field is.

inner mesa
#

What does it mean that they're "like this"? Are they all options in that select entity?

#

if so:
{{ expand(state_attr('select.daily_energy', 'options'))|selectattr('attributes.status', 'eq', 'collecting')|map(attribute='friendly_name')|first }}

sick ice
#

they all have the same structure off attributes which incudes status: and friendly_name:

inner mesa
#

it's the names that I was getting at

#

you need a way to find all the entity_ids

sick ice
#

yes they are. was just trying to save text.
sensor.daily_energy_offpeak
sensor.daily_energy_peak
sensor.daily_energy_shoulder
sensor.daily_energy_superoffpeak

inner mesa
#

alright. I don't know what's in that select entity

#

what is its state?

#

you only said "that state is not formatted like the friendly_name field is."

sick ice
#

Ah, sorry.
select.daily_energy

icon: mdi:clock-outline
friendly_name: daily_energy```
status: `shoulder`
#

it's state is changed based on the times that my tariffs change

#

Basically, for the template, if select.daily_energy is superoffpeak then I'd like to display that name in a print friendly format, like Super Off Peak

#

I can do this:

The tariff period is 
{%- set tariff = states('select.daily_energy') -%}
{% if tariff == 'offpeak' -%}
  {{ ' ' }}off peak
{% elif tariff == 'superoffpeak' -%}
  {{ ' ' }}super off peak  
{% else -%}
  {{ ' ' }}{{tariff}} 
{% endif %}

But it doesn't feel very smart, I'll need to maintain it if I change tariffs

inner mesa
#
{% set tariff = states('select.daily_energy').replace('off', ' off ') %}
{{ tariff if tariff == ' off peak' else ' ' ~ tariff }}
sick ice
#

oh clever!, I was trying to understand how it works for 'super off peak'. It adds a traileing space too. Always a simple way to skin it.

inner mesa
#

actually, that's not quite right either

sick ice
inner mesa
#

yeah, that won't work for you

sick ice
inner mesa
#

it won't add a leading space for "super off peak"

sick ice
#

Ah I see.
what does the ~ do?

inner mesa
#

concatenates

sick ice
#

well there you go.

#

There's probably a prettier way but {{ ' ' }} will always add a leading space?

#

but then we'd get two for 'off peak'

inner mesa
#

yes, but that will add an extra space

#

yes

sick ice
#

My thought was:

Read state of select.daily_energy
set that as 'something'
Than substitute in to sensor.daily_energy_{{something}}
Then use that in state_attr('','')

Not sure if or how we can do the substituting part.

inner mesa
#

it's all overthinking it at this point

#

what you had originally was also fine

sick ice
#

yeah, what I thought was super simple turns out to be a lot of overthinking.
this illustrates what I'm trying to do - but I know that's jsut a print statement.

{% set something = states('select.daily_energy') %}
state_attr('sensor.daily_energy_{{something}}','friendly_name')
sick ice
#

More about learning how to template well, rather than the problem at hand.

inner mesa
#

that comes back to what I provided originally

inner mesa
#
{% set map = ['offpeak', 'peak', 'shoulder', 'superoffpeak']|map('regex_replace', '^', 'sensor.daily_energy_')|list %}
{{ expand(map)|selectattr('attributes.status', 'eq', 'collecting')|map(attribute='attributes.friendly_name')|list|first }}
sick ice
#

I'm just unpacking this at my slow pace ha!

sick ice
inner mesa
#

Do they?

#

Oh

#

Try again

sick ice
#

I'm testing it in /developer-tools/template - assuming that is the right way to do this?

inner mesa
#

Sure

haughty breach
#

attributes.friendly_name

inner mesa
#

Yes, I fixed it

sick ice
#

aha, sorry I missed the edit. Wasn't sure what I was trying again! that seems to be working

#
{% set options = state_attr('select.daily_energy','options') %}
{% set map = options|map('regex_replace', '^', 'sensor.daily_energy_')|list %}
{{ expand(map)|selectattr('attributes.status', 'eq', 'collecting')|map(attribute='attributes.friendly_name')|list|first }}

This is working and if I change or add more tariffs it should continue to work, rather than providing the list? right?

inner mesa
#

If they're in that select entity and have their own entities, yes

#

Should just work

sick ice
#

I like it. thanks for your help. Always learning. I will now head off and read about |map filter and regex_replace and how it's used.

sonic sand
marble jackal
#

if so, add
availability_template: "{{ 'sensor.feed_record_timestamp' | has_value }}"

sonic sand
sonic sand
marble jackal
#

that error comes from the other sensor

#

which I guess you didn't change

marble jackal
#
    {% set feed_record = state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1')|from_json %}
    {{ as_datetime(feed_record.timestamp)|timestamp_local }}
#

this is the template it errors on, which is not in the code you provided above

#

just use the same a you did in the code you provided

sonic sand
#

the availability_template?

marble jackal
#
    {% set feed_record = state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1')|from_json %}
    {{ as_local(as_datetime(feed_record.timestamp)) }}
#

that

#

I don't know where you are using this {{ as_datetime(feed_record.timestamp)|timestamp_local }} but that's not valid

sonic sand
marble jackal
#

timestamp_local expects and integer, not a datetime

sonic sand
#

so I should change line 14, right?

marble jackal
#

yes

#

what do you expect as a result there? a datetime like 1970-01-01T01:00:01+01:00?

#

of a timestamp, like 1687166020.810728

sonic sand
#

Well that's might explain why the automation that uses this sensor never triggered

marble jackal
#

no, because that sensor was actually working

sonic sand
marble jackal
sonic sand
#

maybe the sensor wasn't available then for few days because it missed some feeding a week ago and one fish died 😦

marble jackal
#

you still didn't answer my question above

#

and sorry about the fish 😢

sonic sand
#

well I don't mind how will it look like... I just want to get a notification on if it fed them or not

#
Result type: string
- platform: template
  sensors:
    feed_record_result:
      value_template: >-
                          Trueavailability_template: "True"
      attribute_templates:
        timestamp: >-
              2023-06-18 19:14:51+03:00friendly_name: "Automatic Feeder"
      device_class: problem
This template listens for the following state changed events:

Entity: switch.hfjh_v2_eadb_fish_tank_2

looks fine now

#

thats from dev tools

marble jackal
#

is this a binary sensor?

sonic sand
#

yeah, you helped me with that btw

marble jackal
#

ages ago, and you didn't include the binary_sensor part

sonic sand
#

yeah it was in a diff yaml file

marble jackal
#

but anyway, the state of this binary sensor will be on or off

#

just remove that attribute as you already have another sensor providing the same data

sonic sand
#

and how do I set a trigger for case the fed time was 2 days ago + 2 hours?

marble jackal
#

like you are doing

sonic sand
#

You mean get rid off the

feed_is_missing_timestamp

right?

marble jackal
#

no

#

that's totally not what I meant

sonic sand
#

so what attribute?

marble jackal
sonic sand
#
      attribute_templates:
        timestamp: >-
          {%- if state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1') -%}
              {% set feed_record = state_attr('switch.hfjh_v2_eadb_fish_tank_2','event.4.1')|from_json %}
              {{ as_datetime(feed_record.timestamp)|timestamp_local }}
          {%- endif -%}

This part

marble jackal
sonic sand
#

is it causing any problems?

#

ok will remove it right away, so I keep my trigger as it is?

marble jackal
#

the attribute as you have it now is causing problems

#

and you were not using it for the feed_is_missing_timestamp sensor, you were using sensor.feed_record_timestamp there

sonic sand
marble jackal
#

yes, that one is not using template sensors at all

#

it is using the values directly from the switch

sonic sand
#

mmm got it

#

ok so I removed the attributes from the binary

marble jackal
#

everything does rely on the switch being available though

#

so if the switch is not available for 2 days, nothing of this works

sonic sand
#

yeah it's Chinese aquarium so it's not that stable 😦

#

thanks for help!

#

one more thing related to templates
I got watchman report thingy and it says i have problem with two groups in my templates.yaml

| group.tvs                      | unknown | templates.yaml:17                                            |
| group.temp                     | unknown | templates.yaml:37   

http://pastie.org/p/173YR1Kplyq4oyRV1cimfd
What did I do wrong there?

marble jackal
#

There is nothing wrong probably, but these groups you defined have entities of which HA can not define a group state

#

so it defines the state as unknown

#

and in your templates, you are probably using them for expand, to get data from the group members

#

watchman doesn't understand that, and it sees you are using an entity with unkown as it's state

#

and it reports that

#

watchman isn't that smart

sonic sand
#

oh ok, thanks for the explanation.
is there a smarter addon I can use that scans my yaml files like Watchman?

marble jackal
#

There's Spook, but according to it's license terms you are not allowed to use it

sonic sand
#

Alright, thanks man.
I tried to create those groups via the UI in the helpers menu but it has no counter, I just need to count how many entities are within the group and how many of them are on/off state

silent vector
#

This is probably really easy.

{{ states.sensor.hvac_operating_mode.last_updated }}
Is 2023-06-19 04:59:07.962340+00:00 while developer tools is

Last updated:
June 19, 2023 at 12:59:07 AM
#

Why is the template showing 04 and not 00

mighty ledge
#

because that's UTC

marble jackal
#

use as_local to get it to your local time

mighty ledge
#

but it's pointless if you're just displaying it in the frontend because the frontend handles that for you.

#

and it's already a datetime object, so as long as you compare it to another TZ aware datetime, it doesn't matter if it's in UTC or local, the comp will work

marble jackal
silent vector
#

I'm using this for an automation so I would need as_local. I figured this would be something simple, thank you guys.

mighty ledge
#

no you don't

#

if you compare it to a local datetime, it compares the times properly

#

you can compare now() to a last_updated and even perform math and it will work as if it's in your TZ

#

@silent vector

silent vector
#

Oh I would be comparing it to a sensor attribute that's {{ now() | string }}

marble jackal
#

Is that an attribute of a trigger based template sensor?

silent vector
#

Yep

mighty ledge
#

that should be a string at all

silent vector
#

states.sensor.thermostat_automation_memory.attributes you said to use {{ now{} | string }}

#

To store time in attributes and access it with that ^

mighty ledge
#

My memory is fuzzy

#

if it did, then just use utcnow() | string instead

silent vector
#

Nope it works without issues

mighty ledge
#

if it doesn't care about datetime objects, then just keep it a DT object

#

then it doesn't matter

#

I honestly can't remember

silent vector
#

As in comparing the utc | string time to a now() | string should work?

mighty ledge
#

if you're comparing as strings, they both need to be in the same TZ and same format

#

if you're comparing as datetimes, it doesn't matter

silent vector
#

Makes sense thank you

hearty prairie
#

Looking for a way to store the first datetime for when a binary_sensor was triggered today. Is it possible to do that with templates or would I need to rely on an automation to store and reset the value? My point is that I have a history_stats sensor where I want to measure the amount of times a sensor is opened from it's first time and 5 minutes into the future from then.

mighty ledge
#

best option IMO

hearty prairie
#

I guess and then just reset it every midnight, so two automations it is

marble jackal
#

or an additional trigger

#
trigger:
  - platform: time
    at: "00:00:00"
  - platform: state
    entity_id: binary_sensor.foo
    to: "on"
condition:
  - condition: template
    value_template: >
      {% set last_trigger = this.attributes.last_triggered %}
      {{ last_trigger < today_at('00:00:02') if trigger.platform == 'state' or not last_trigger else true }}
action:
  - service: input_datetime.set_datetime
    target:
      entity_id: input_datetime.foo
    data:
      datetime: "{{ now() }}"
#

something like that

spiral grove
#

Hi #templates-archived !
I have a Hue lightstrip (and some other Hue color lights) that unfortunately don't have an available "colorloop" effect. I think the best way to go about adding on this effect would be with a light template. My idea would be to create new light template (e.g. light.strip_template) that has its state and all of its attributes inherited from light.strip, except replace the effect_list_template, effect_template, and set_effect with custom code that adds a "colorloop" effect that calls a colorloop script or automation (how that automation functions is a separate issue). So my question are: Is this a good way to go about my little project? Is there a quick way to have a light template simply inherit all of its attributes and state from a parent light? Also, what does "inclusive" mean in the documentation (e.g. "effect_list_template template (inclusive, default: optimistic)")?

lyric comet
#

I think you will need to manually set all the values. Then have a script defined to run any effects. If I was doing it, I would write the script first to make sure you can get the effect you want before creating the templated light.

mighty ledge
#

i.e. if you don't include that other field, the check config will fail

#

Also, there is no "quick way" to make it inherit fucntions from another light. You have to painstakingly build it all. 🎉

spiral grove
#

Thanks guys!

#

Maybe we'll get a default colorloop effect (and maybe some other fun ones) in a future Hass update, similar to the recent "favorite colors" light feature.

mighty ledge
#

doubtful

#

All effects are provided by the hardware (or software) that HA talks to. HA does not create any effects.

#

@spiral grove ^

spiral grove
#

Yea, I guess this would be more in the realm of an Integration

mighty ledge
spiral grove
#

Yea, I'm not too worried about that part.

#

I'm just imagining an integration that extends the features of smartlights to include a few things they are physically capable of but don't yet have the software for

mighty ledge
#
alias: cycle colors
variables:
  colors:
  - [255, 0, 0]
  - [0, 255, 0]
  - [0, 0, 255]
  target_light: >
    {{ entity_id | default }}
sequence:
- condition: template
  value_template: "{{ target_light is not none }}"
- repeat:
    for_each: "{{ colors }}"
    sequence:
    - service: light.turn_on
      target:
        entity_id: "{{ target_light }}"
      data:
        brightness: 255
        rgb_color: "{{ repeat.item }}"
    - delay: "00:00:05"
#

You'd need another repeat for indefinitely

mighty ledge
#

it just doesn't do anything automatic

spiral grove
#

I mean, kind of... it's missing the implementation.

#

And the average user would never take the time

mighty ledge
#

Well an average user isn't going to understand inheritance

spiral grove
#

Hence, a user-friendly integration.

mighty ledge
#

average users (who've been doing this for years), just make a script with a dropdown

spiral grove
#

Kind of like how "switch-as" could pretty easily be accomplished with templates

mighty ledge
#

switch as only works because the domains it changes to supports on/off

#

or some variation of on/off

#

otherwise, it wouldn't work

#

lights are very rigid and have many requirements. It would be very doubtful that an integration like this would be built

#

not to mention, it would be a ton of code, just to get it to mimic another light, but have an extra effect

#

when you can simply just make a template select that does the same thing or a input_select w/ an automation that does the same thing

spiral grove
#

Couldn't you make the same argument about the recent "Favorite Colors" feature.

mighty ledge
#

not really

spiral grove
#

I honestly don't know enough about the backend to say yay or nay

mighty ledge
#

that just extends existing supporting colors into separate buttons

#

it does not link a dropdown to some script

#

not to mention, that's all handled by the frontend and the backend has no concept of it

spiral grove
#

Gotcha.

#

So, like, hypothetically adding a toggle next to those Favorite Color buttons that cycles through them every 30 seconds would be a much bigger ask?

#

Disregarding the utility (or lack ther-of) of such a feature

mighty ledge
#

Yes, the frontend doesn't run automations

#

it simply runs a service when it's told to by the user

spiral grove
#

Well thanks for taking the time to answer my questions, @mighty ledge ! Much appreciated.

flint vapor
#

hi there just curious what is the best way to add a wake on lan service that i can add to a zigbee based smart button.

#
# wake_on_lan:
# switch:
#   - platform: wake_on_lan
#     name: x
#     host: x
#     mac: x
#

This is what i have no and it works only to use as a button on my dashboard

#

but when putting it to my smart button

#

it gives an error

marble jackal
#

I don't see any templates here

graceful whale
#

Missing something obvious as a noob. Looking at templates. There seems to be lots of info on syntax and such. What do you use a template for? Do you incorporate them in cards somehow?

#

Are they card templates? Automation templates?

#

The demo template produces a string. How do you use it?

#

I only see space for one in the editor. Is this for testing only & then you cut and past somewhere?

#

I started down this road of googling how you get HA to use tts to say the weather. Someone advised “use a template,” which seems to be a way to build the speech string. Now, how do I use it in a card or script?

haughty breach
# graceful whale Are they card templates? Automation templates?

Templates allow you to extract and modify data from entities' states, attributes, and properties. Some custom cards allow templates, but most core cards do not. They can be used in some parts of scripts and automations including variables, template conditions and triggers, as well as in service call actions.

graceful whale
#

So, they are essentially inline functions or code for building strings?

haughty breach
#

They can output data types other than strings.

inner mesa
#

Data structures. Not just strings

graceful whale
#

Where can you use them? Tried various types of cards with no luck. Scripts?

inner mesa
#

I pointed you to a whole page with examples

#

And to the history of this channel

graceful whale
#

Going back to link….

#

The info at the link talks about editing system files. I was just looking for a way to add sensor data to a script or card. This seems more like a developer kind of thing? A little too new to this to go mucking about in the file system. I guess that’s done via ssh and your favorite editor, remembering back to Unix and college days.

slate fossil
#

I'm trying to create a light group that contains all light entities that are currently on, ignoring groups, and ignoring Fully Kiosk Browser screens. Here's my template that works in Dev Tools

{{ states.light 
  | rejectattr ('entity_id', 'in', integration_entities('group'))
  | rejectattr ('entity_id', 'in', integration_entities('fullykiosk'))
  | selectattr( 'state' , 'eq' , 'on' ) 
  | map ( attribute = 'entity_id' ) 
  | list 
}}```which returns `['light.bedroom1', 'light.kitchen', 'light.stove', 'light.living_room1', 'light.living_room2', 'light.bedroom2']`
#

Now, I'm trying to figure out what to do next with it. Is this what I would need to put into configuration.yaml?

light:
  - platform: template
    light:
      all_lights_on:
        friendly_name: 'All Lights On'
        value_template: "{{ states.light 
          | rejectattr ('entity_id', 'in', integration_entities('group'))
          | rejectattr ('entity_id', 'in', integration_entities('fullykiosk'))
          | selectattr( 'state' , 'eq' , 'on' ) 
          | map ( attribute = 'entity_id' ) 
          | list 
          }}"
#

I'm confused because when I used to make light groups in YAML (a long time ago), it would be ```yaml
light:

  • platform: group
    name: All Lights
    entities:
    • light.bedroom1
    • more entities follow```
inner mesa
#

You can't create a group like that

#

The only way to create a dynamic group is to use group.set

slate fossil
#

Okay. So, ultimately, I need to create an automation that updates every so often to make the group dynamic and the entities based on the template? Example found:```yaml
sequence:

  • service: group.set
    data_template:
    object_id: my_lights
    entities: |
    {{ states.light | map(attribute='entity_id') | join(',') }}
    mode: single
    alias: Create 'my_lights' group for every lights
    icon: mdi:lightbulb```
inner mesa
#

Yes

#

and data_template: went away many years ago

#

Many

slate fossil
#

IIRC, group doesn't handle brightness like a light group does. Is there any way to get this to work as a light entity? This is why I used to used the ```light:

  • platform: group```method.
inner mesa
#

That's not a valid thing

#

You can't just do it differently

#

And groups actually do handle brightness. It will affect any lights in the group

#

Try it

slate fossil
inner mesa
#

Not with a template

#

Which is the point

slate fossil
inner mesa
#

You should try other things

slate fossil
#

That's rather cryptic.

inner mesa
#

not really. brightness:, like you want

slate fossil
#

not following you

inner mesa
#

I'm not following you

#

Make a group, turn it on and specify brightness

#

That's the point, right?

slate fossil
#

how does it work if it doesn't have the attribute? (I tested and it does adjust brightness.)

#

Actually, it only kind of works.

inner mesa
#
service: homeassistant.turn_on
data:
  entity_id: group.whatever
  brightness: 100
#

So it works

slate fossil
#

Reverts back to "100%" after a couple of seconds. (Brightness slider card.) So it can send the brightness but the group itself doesn't actually retain the value.

inner mesa
#

That's probably the card

marble jackal
#

You could try to create a template light

#

Which is on when any light (excluding groups and kiosk mode) is on

inner mesa
#

Yes, I suppose they could do that too

marble jackal
slate fossil
#

Big Slider Card is the one I was testing. Light Card refuses to work with a group. Mushroom Light Card brightness slider disappears when the group is selected. Custom:button-card can't "see"/return brightness of the lights.

marble jackal
#

Which can all be solved by creating a template light 🙂

slate fossil
marble jackal
#

Yes, which should return true or false

#

That one determines the state of the light (so on or off)

inner mesa
#

It's all just more complicated than a group, IMO

slate fossil
#

But, briefly looking over it, it doesn't look like there is an option to define entities.

#

Right, but the group doesn't work for what I want. I need the attributes of a light entity which a group does not have.

floral shuttle
#

have a template with state: {% set event = '1997-06-20'|as_datetime|as_local %} {% set year = 1 if event.month < now().month or (event.month == now().month and event.day < now().day) else 0 %} {% from 'easy_time.jinja' import count_the_days %} {{count_the_days(event.replace(year=now().year + year)) }} and today it's returning 0, whihc is correct ;-0

#

now why wont this attribute not return true, or on:```
feest: >
{{states(this.entity_id)|int(default=-1) == 0}}

#

or using {{this.state}} for that matter. guess I ll just have to use another hard coded template...{{now().strftime('%m-%d') == '06-20'}}

marble jackal
marble jackal
marble jackal
#

and is it a trigger based template sensor, or a state based?

floral shuttle
#

trigger based..... and if I make it a regular binary template, it works as expected.

#

I am moving to deleting all this variables out of the configs, its just to unreliable

marble jackal
#

The templates are rendered on trigger, so before the state has been changed

#

You can add an additional trigger a second later so it will use the new state

#

They are not unreliable, but they work different than your expectation

floral shuttle
marble jackal
#

it's not the this variable what causes this

#

if you would have used states('sensor.your_sensor') | default(-1) | int == 0 you would have had the same result

#

what causes is is the fact that the templates for trigger based templates are rendered on the trigger, so before the state change in your state template

#

so when the attribute template is triggered, your state value is still "1"

floral shuttle
#

yes, and one has to consider that very carefully, and check trickle down. In my config, I have some binaries based on the state of the trigger template, and they would turn on, triggered by:```
template:

  • trigger:
    • platform: time_pattern
      hours: 0
      minutes: 0
    • platform: homeassistant
      event: start
    • platform: event
      event_type: event_template_reloaded``` . Ive moved that to regular template binary,, and now it is immediate, based on the same template trigger from the above trigger...
#
      - unique_id: count_celebrations
        state: >
          {{expand(state_attr('binary_sensor.feest_alerts','entity_id'))
             |rejectattr('state','in',['unknown','unavailable'])
             |selectattr('state','eq','on')
             |list|count}}
        icon: >
          mdi:numeric-{{this.state}}-box
``` is another example...
marble jackal
#

same thing, this.state is the state before the new state template is rendered. it's like the trigger.from_state.state in an automation

floral shuttle
#

ok. I figured I might also need to guard that icon template so added mdi:numeric-{{this.state|int(default=-1)}}-box and see what happens on reload, it somehow gets a state of 0, and the icon is updated to -1

marble jackal
#

yes, that's because it changed state from unavailable to 0

#

so this.state was unavailable

floral shuttle
#

but the state should be 1

marble jackal
#

the others are template binary_sensors too, so it will be a race on template reload

floral shuttle
#

ah yes, that might be it

marble jackal
#

the one which should have made it 1 was still unavailable

floral shuttle
#

well, moving it to a regular template fixes it (and yes, also with the this variable)

golden plaza
#

I have a mqqt sensor that is the cumlative of a week of data (Resets every sunday), I need to see this data for today instead, what would be the best way to do this?

plain magnetBOT
steep plume
#

Is it possible to define a binary_sensor that is not a template sensor using configuration.yaml instead of helper entities?

#

I'd like to have the custom sensor at hand in the scripts, but be able to add a toggle representing it in the UI too

marble jackal
#

a template switch?

#

or a simple input_boolean?

steep plume
#

one that saves the state, but has not a template value

#

oh

#

yeah...

#

facepalm. thanks

slate fossil
# marble jackal You can define the entities in the service call

I appreciate all the work that you put into that template. It definitely puts me on the right track for what I'm trying to accomplish. (Shame it takes so many lines to make it work.) I may try to expand the template so it can also handle RGB and color_temp.
I would like to note a typo on Line 15: level_template: > has an extra space before it.

#

It is interesting, though, the state does not return to off if all the lights are off. It stays on with the brightness at its last value. Only way that I have been able to reset it has been with a quick reload. https://i.imgur.com/7VlxCD3.gif

#

I think the problem is... the template sees itself so it is on because it is on... mindblown

marble jackal
#

It's a light entity, so that might be it

#

Exclude it from the template

#

| rejectattr('entity_id', 'eq', this.entity_id)

slate fossil
#

Now it is working how I was expecting. https://i.imgur.com/kz8JcRd.gif
If I wanted to adjust the brightness of all lights that are currently on, I couldn't adjust brightness for lights.all_lights because it would turn on lights that were off. Now, with the template, I have a lights.all_lights_on entity that can adjust brightness for everything on. (The slider under the All Lights button has its entity set to lights.all_lights_on.)

rapid tinsel
#

Can someplease please help me to write the right template for that.

#

Right now I am having this template code: "{{ value_json.params[1].bms_bmsStatus.f32ShowSoc }}" Which is not working

bright quarry
#
  - condition: template
    value_template: >-
      {{ '30:DF:17:C1:28:D0' in
      state_attr('sensor.pixel_6a_bluetooth_connection','connected_paired_devices')
      }}

anything wrong with this, assuming the mac address is correct? doesn't seem to be triggering.

mighty ledge
#

That’s a condition not a trigger

#

Check your trace and see what it resolves

golden plaza
# plain magnet

Thanks for this @marble jackal, can this be calculated retrospectively, or is it only for now forward?

marble jackal
#

It can't calculate retrospectively

golden plaza
#

Thanks @marble jackal, The issue I have is that the sensor that is populated in HA is already cumaltive by week; I want to split it by day. So if you look at the below, it started at 7.3 at 00:00 and increasd to 12.3 by 00:00 the next day. I need the net of 7.3 and 12 for the day, and reset at 00:00.

marble jackal
#

The utility meter does that

#

Just set up a daily utility meter

#

Based on your weekly sensor

golden plaza
#

Thank you, let me try that, when I did initially, it seemed to use the first value and sum all other values, meaning the starting balance was wrong.

#

Correct in saying that they are not deltas (its cumulative) so left that unticked.

rapid tinsel
#

I do need some help with rounding sensor values. I would like to round to the values to 100-based values. For example 154 should be rounded to 100 and 444 should be rounded to 400, does somebody how how I can archive this?

golden plaza
marble jackal
marble jackal
golden plaza
#

Only noticed now, will do

steep plume
#

I'm using a few fixed entity names in the templates, for example an illuminance sensor. Is it possible to define a list of sensors, or a group, in the UI that are pickable? I'd like to ideally pick one sensor from the list so I can reference it then in the templates. I saw there is an input_select integration, so maybe defining the possible options using a template is possible?

#

Okay I can see there's a set_options service. So an automation that will trigger every once in a while and fill the options using a template will do. I wonder if there's a better way

plain magnetBOT
#

@deft comet I converted your message into a file since it's above 15 lines :+1:

inner mesa
#

I keep getting undefined trigger error.
where do you see that?

#

are you trying to test the automation without letting it trigger?

deft comet
#

I sent an email, the IMAP integration incremented the count, so it received the email correctly. but I don't see any new sensor/entity. I went to the logs and it showed that error in the logs

inner mesa
#

what is the actual error you see?

deft comet
#
Source: components/imap/coordinator.py:364
Integration: IMAP (documentation, issues)
First occurred: June 20, 2023 at 2:45:34 PM (21 occurrences)
Last logged: 9:25:42 AM

Error rendering imap custom template (Template<template=(template : - trigger : - platform: event event_type : "imap_content" id : "custom_event" event_data : sender : "notifications@alarm.com" sensor : - name : alarmdotcom_armed state : > {% if 'Disarmed' in trigger.event.data["subject"] %} disarmed {% elif 'Armed Stay' in trigger.event.data["subject"] %} armed_stay {% elif 'Armed Away' in trigger.event.data["subject"] %} armed_away {% endif %}) renders=8>) for msgid 18 failed with message: UndefinedError: 'trigger' is undefined```
#

Each log entry occurs when I receive the email

inner mesa
#

I think you should remove the space before all the :

deft comet
#

I didn't have any space before earlier, and I had the same error. thought perhaps that was the reason.

inner mesa
#

ok, you shouldn't have added them

#

where did you put that block of code?

deft comet
#

On the imap integration, there's a field called "Template to create custom event data"

inner mesa
#

that block of code belongs in configuration.yaml

wanton girder
#

Im not sure wether this is the right place - but. I have solar panels, and the power-flow-card-plus can tell me the amout of power used in the house...i would like to know how many kwh im sending to the grid as a entity...but as of now I can only see the power producion, grid usage, and battery.. I would like a sensor or something to give me the remaing kwh that I have NOT used myself...
I would like to use it for charging things when I have alot to spare...

inner mesa
#

it doesn't belong in a field in the UI

deft comet
#

Oh I see

#

Oh that works perfectly! Thank you so much!

#

I restarted the system and it seems I don't need this sensor automation at all haha. The alarm.com integration is now updating status before the email comes in🤥

wanton girder
#

Can anyone tell me what Im doing wrong here

{{ states('sensor.al7002022041414_instantaneous_generation') | float(0) - states('sensor.al7002022041414_instantaneous_grid_i_o_total' + 'sensor.al7002022041414_instantaneous_battery_i_o') | float(0) }}
inner mesa
#

yes, you're adding two strings and then trying to get the state of the resulting string

#

which is two entity_ids concatenated together

wanton girder
#

Tried this but I it dosen't seem right:

{% set forbrug = states('sensor.al7002022041414_instantaneous_grid_i_o_total') | float(1) + states('sensor.al7002022041414_instantaneous_battery_i_o') | float(1) %}
{% set produktion = states('sensor.al7002022041414_instantaneous_generation') | float(1) %}

{{ forbrug - produktion }}
inner mesa
#

looks ok to me

#

from a syntax perspective, at least

wanton girder
#

is this correct:

      - name: "OverUnderForbrug"
        state: >  
          {% set forbrug = states('sensor.al7002022041414_instantaneous_grid_i_o_total') | float(0) + states('sensor.al7002022041414_instantaneous_battery_i_o') | float(0) + states('sensor.al7002022041414_instantaneous_generation') | float(0) %}
          {% set produktion = states('sensor.al7002022041414_instantaneous_generation') | float(0) %}
          {% set overunderforbrug = produktion - forbrug %}
#

Would that give me a sensor with the remain kwh

inner mesa
#

you're not outputting anything

#

from your last attempt, you swapped the order of your subtraction, but also just assigned a variable rather than outputting the result

wanton girder
#

This is in my config but returning 02:00 :S

      - name: "OverUnderForbrug"
        state: >  
          {% set forbrug = states('sensor.al7002022041414_instantaneous_grid_i_o_total') | float(0) + states('sensor.al7002022041414_instantaneous_battery_i_o') | float(0) + states('sensor.al7002022041414_instantaneous_generation') | float(0) %}
          {% set produktion = states('sensor.al7002022041414_instantaneous_generation') | float(0) %}
          {% set overunderforbrug = produktion - forbrug %}
          {{ overunderforbrug }}
inner mesa
#

test it in devtools -> Templates

#

I have no idea how it could return something with a colon in it

wanton girder
#

Result type: number
-3580.7440000000006

inner mesa
#

so no colon

wanton girder
#

Not when I test it..

inner mesa
#

perhaps you're looking at the wrong entity, then

wanton girder
#

sensor.overunderforbrug
OverUnderForbrug
02:00

inner mesa
#

or perhaps you didn't reload template entities

wanton girder
#

I was a fool...works now... 😄 Thanks @inner mesa

glossy spear
#

Hi there!

I want to create template sensor that will calculate sensible temperature based on actual temperature and humidity. I added this into my configuration.yaml:

template:
  - sensor:
      - name: "Sensible temperature"
        state: >
          {% set temp = states('sensor.air_monitor_lite_4e4c_temperature') | float %}
          {% set hum = states('sensor.air_monitor_lite_4e4c_humidity') | float %}
          {{ (temp + 0.3 * hum - 12) | round(1, default=0) }}

But in UI I see Sensible temperature - Unknown. sensor.air_monitor_lite_4e4c_temperature and sensor.air_monitor_lite_4e4c_humidity are shown correctly in UI.

What am I doing wrong?

inner mesa
#

Put it in devtools -> Templates

glossy spear
inner mesa
#

Then you probably didn't reload template entities

glossy spear
#

I clicked "Restart" -> "Quick reload" and "YAML configuration reloading" -> "All YAML configuration"

#

Changes nothing

inner mesa
#

Not sure what to say

#

Problem is not evident from this chat

marble jackal
#

Do you already have another template section?

#

In you configuration

glossy spear
#

No. But I have few more elements in this sections. Will try to remove them

#

Works now. Thanks!

deft comet
#

Is there a templates FAQ section?

patent shadow
#

I need a template to use in an automation that will be used as a trigger. (Hope I understand that correctly) . I need to alert if the current temperature attribute is 5 degrees higher than target temperature on an entity of a Nest Thermostat. When I pull up the entity in a history love lace card I can see their values. I don't see them listed under the entity or device.

neat prairie
#

So you need to create a template sensor, which is based off an attribute of the entity.

marble jackal
neat prairie
#

The fun of multiple ways of doing things.

#

I'd probably go with the first, but that's down to how I thik.

paper hazel
#

How often do a template evaluate using now()? Nevermind - Found it in the docs.

neat prairie
#

First thing to do though, is to create your base template.
go to the developer tools, then click on templates. Then you'll want something along the lines of:
{{state_attr("nest device here. something like nest.thermostat or something. I don't have one ", "current temperature")|float +5 }}

#

get that to the point it's returning the number you think it should be.

#

Then you need to add to your configuration.yaml, something like

  - sensor:
      - name: "triggertemperature"
        unit_of_measurement: "°C"
        state: your_template_goes_here  ```

make sure to go to developer tools and click the check configuration button on the yaml page
#

(I do my editing using the file editor add on, but that's only one of many options.)

#

if it's good, you can restart (reload might work, but it never does for me 😉 )

#

then you'll have a new sensor which you can use in an automation.

paper hazel
#

How can I get a template to evaluate every 15 seconds? The template is using now().second and based on this value a decision is made. The use case is to create a template sensor, and based on its value, True/False, a sensor value will be displayed on a picture elements card.

#

The aim is to cycle through temp and humidity values on the picture elements card every 15 seconds, or value chosen using an input_number helper.

neat prairie
#
  - time_pattern
    seconds: "/15"```
paper hazel
#

Thx, but its not an automation, but a conditional card on a picture elements. It only accepts a state, hence using the template sensor. According to the docs now() only evaluates every minute. An example syntax of the conditional card looks like this:```
- type: conditional
conditions:
- entity: binary_sensor.doors_all
state: 'on'
elements:
- type: icon
icon: mdi:door

neat prairie
#

template sensors can be trigger based, using time based triggers

#

which is why I said 🙂 (I may be wrong, as I haven't used it.)