#templates-archived

1 messages · Page 103 of 1

inner mesa
#

or something liek that

calm kettle
#

Yes, I had that at one point, so as long as wed is anywhere it will trigger

#

in the description that is

#

I should have tried that, thank you!

inner mesa
#

that works for me even with a stray newline

calm kettle
#

lets see if it works

#

hum... still something is off...
{{ is_state('calendar.ouachita_hills_academy', 'on') and in_state_attr('calendar.ouachita_hills_academy','description', 'wed') }}

inner mesa
#

lol, that's not how that works 🙂

#

look at my example above

#

you seem to have made something up

#

a quick example that I just tested on my system: {{ 'Re' in state_attr('calendar.garbage_collection', 'message') }}

daring tide
#

Could someone help me with a command_line ?, I need to pass the data from a dict / JSON to a template

silent barnBOT
mighty ledge
#

@pale python are you restarting? Also, why are you even creating the template sensor. They are 100% pointless, you can just place the booleans inside the group.

pale python
#

I know,...It's not the real case... I will modify and repost the code. Gimme some minutes

#

But the point is...why if I use an if-then-else template on sensor templates and I put them in a group, the group state is Unknown ?

mighty ledge
#

don't know without seeing your setup 😉

#

So post everything

silent barnBOT
pale python
mighty ledge
#

because those aren't on/off home/not home states

#

it's not going to propagate states that groups can't be

pale python
#

ok...so groups works just on binary

#

on-off

mighty ledge
#

groups just work on states groups understand

pale python
#

ok I undestand

#

thanks

mighty ledge
pale python
#

yes...thanks

#

I missed this

because those aren't on/off home/not home states
@mighty ledge

thorny snow
#

Hi! I've been looking around for ages, and trying to get this to work.. but i have had little to no success. (also noob here)
My custom sensor output only shows "true" or "false" but I managed to get the "raw" data by using {{states.sensor.kvbdep_245}}. This provides me with a dynamic list which auto updates with the next tram from the station. The data output is as follows:

<template state sensor.kvbdep_245=True; stationname=Subbelrather Strasse, departures=[{'line_id': 143, 'direction': 'Lövenich', 'wait_time': '0'}, {'line_id': 13, 'direction': 'Holweide', 'wait_time': '3'}.... etc

What I am trying to do, is get data from a sensor and present it in a sentence: "The next tram to Am Buzweilerhof will depart in [....] minutes.

Could anyone help me?

deft timber
#

Where do you want to display it? In a card in lovelace ?

#

You can create a card with this template :

thorny snow
#

I want to display it as a state-lable over a picture elements card

deft timber
#

The next tram to Am Buzweilerhof will depart in {{ states.sensor.kvbdep_245.attributes.departures[0].wait_time}} minutes.

thorny snow
#

That gets me in the right direction, but that only gives the time of the next departure, and not the specific tram

deft timber
#

you want to display the line_id? or get the time of a specific line_id?

#

not sur I understand

#

if you want the wait_time of the line 143 for instance you could do something like (to be tested):

#

The next tram to Am Buzweilerhof will depart in {%- for i in states.sensor.kvbdep_245.attributes.departures -%} {%- if i.line_id == 143 -%} {{i.wait_time}} {%- endif -%} {%- endfor -%} minutes.

thorny snow
#

Îm looking for the time of a specific line_id, which would be the wait_time of the line.

mighty ledge
#

@thorny snow

{% set desired_tram = 143 %}
{% set selected = state_attr('sensor.kvbdep_245', 'departures') | selectattr('line_id', 'eq', desired_tram) | list | first %}
The next tram to Am Buzweilerhof will depart in {{ selected.wait_time}} minutes.
deft timber
#

or {{ (states.sensor.kvbdep_245.attributes.departures | selectattr('line_id', 'eq', 143)|first).wait_time }}

mighty ledge
#

for safety you should probably use this instead:

{% set desired_tram = 143 %}
{% set selected = state_attr('sensor.kvbdep_245', 'departures') | selectattr('line_id', 'eq', desired_tram) | list %}
{% if selected | count == 1 %}
  The next tram to Am Buzweilerhof will depart in {{ selected[0].wait_time }} minutes.
{% else %}
  There is no tram.
{% endif %}
thorny snow
#

Thank you very much. @deft timber and @mighty ledge those both work flawlessly.

radiant zephyr
#

I am trying to format an email in HTML, and include state information in it. Is a template the best way to do this? I usually use Node Red but I haven't figured out how to make it happen there either. Does anyone have an example of how to do this?

mighty ledge
#

that's a loaded question

#

how are you creating the email

radiant zephyr
#

That's my issue, I don't even know where to start 🤔

mighty ledge
#

well, you need to figure out what/how you're going to send the email first.

#

Most integrations read emails, I can't think of any that send emails.

radiant zephyr
#

I was planning on sending it using a node in Node Red, I can format the HTML and send the email, but I can't figure out how to include the state information. So far I haven't been able to get any assistance in the Node Red channel so I thought I would look at doing it in yaml and templates

mighty ledge
#

Well I just dug around a bit, and I see there is an smtp integration that will allow you to send them as 'notifications'

#

Either way, need to know the service to form the html and it'll need to be an automation

#

also, if you want to grab info from a sensor to put in HTML, just use the templates to grab data... I.e. {{ states('sensor.xxx') }}

radiant zephyr
#

Seems my Google-Fu failed me, thanks for pointing me in this direction. I'll give it a go ...

small wolf
#

I'm trying to setup up an automation to alert me for each state of my alarm. This is what I have so far - and it works, but it says "Home Alarm as changed from disarmed to armed_away". I'd like to be able to "customize" the text - something like "Home Alarm has changed from disarmed to away"

#
  alias: Alarm Test
  trigger:
  - platform: state
    entity_id: alarm_control_panel.ring_alarm
  action:
  - service: notify.mobile_app_my_iphone
    data:
      data:
        push:
      message: Home Alarm changed from {{ trigger.from_state.state }} to {{ trigger.to_state.state }}!
      title: Attention!```
buoyant pine
#
Home Alarm changed from {{ trigger.from_state.state.replace('armed_','') }} to {{ trigger.to_state.state.replace('armed_','') }}!
small wolf
#

thanks! is there any easy way to capitalize the letters? AWAY instead of away?

#

or even change words altogether?

buoyant pine
#
Home Alarm changed from {{ trigger.from_state.state.replace('armed_','').upper() }} to {{ trigger.to_state.state.replace('armed_','').upper() }}!
small wolf
#

that was fast, thanks! what about changing words altogether? Entry Delay instead of pending?

buoyant pine
#

it'd be a more complex template but nothing too crazy. i wouldn't have time to make it until possibly sometime tonight though

#

if nothing else i'm sure someone else could chime in

small wolf
dreamy sinew
#
Home Alarm changed from {{ map.get(trigger.from_state.state, "UNKNOWN") to map.get(trigger.to_state.state, "UNKNOWN) }}!```
#

where the armed phrases are the raw states

small wolf
#

where does {%- set map.... go in relation to the message?

#

like this: message: {%- set map = {"armed_phrase_one": "MY CHANGE 1", "armed_phrase_two": "MY CHANGE 2"} -%} Home Alarm changed from {{ map.get(trigger.from_state.state, "UNKNOWN") to map.get(trigger.to_state.state, "UNKNOWN) }}!

dreamy sinew
#

Yup

small wolf
#

I keep getting missed comma between flow collection entries at line 340, column 17: line 340 is message: {%- set map.......

dreamy sinew
#

Oh. message: >-

ember lynx
#

Hey guys, I have just updated HA to 0.115 and as a result I am getting an error when starting up, indicating customizer cannot be loaded. I had installed customizer as AFAIK it was the only way to do template base global customization. Has anyone run into this?

small wolf
#

@dreamy sinew haha! I just figured that out as you responded. Got it working, thanks!

winged dirge
#

This is showing as deprecated:

      \ float < 75 %}\n  cover.close_cover\n{% else %}\n  timer.start\n{% endif %}"```
#

What did I miss?

dreamy sinew
#

You upgrade to 115?

winged dirge
#

ye

#

I read docs

#

But I just woke up

dreamy sinew
#

*_template is deprecated

#

Just need *

winged dirge
#

So: - service: "{% if states('sensor.bathroom_humidity_sensor_humidity') |\ \ float < 75 %}\n cover.close_cover\n{% else %}\n timer.start\n{% endif %}"

inner mesa
#

Gotta keep the support folks busy with something. If it’s not telling people to add _template, it’s telling people to remove it 🙂

dreamy sinew
#

Yup

winged dirge
#

yeah that worked 😦

buoyant pine
#

I'd consider making that a multiline template too @winged dirge

winged dirge
#

I prefer this style it's harder to read.

abstract tapir
#

Not sure if this has been brought up:
now we can replace data_template with data, but if my template uses trigger (because this script is in an automation), the new way doesn't work.
HA'd complain:

jinja2.exceptions.UndefinedError: 'trigger' is undefined

dreamy sinew
#

Scoping problem. Script won't have access

#

Gotta share the full thing though

abstract tapir
#

Scoping problem. Script won't have access
@dreamy sinew No it's not a script, it's the action script of an automation, let me share a code snippet.

#
- alias: Occupancy Notifier
  trigger:
    - entity_id: input_boolean.X_present, input_boolean.Y_present
      platform: state
  action:
    - service: notify.telegram_to_X
      data_template:
        message: "
          {% if trigger.to_state.state == 'on' %}
          🏡 {{ trigger.to_state.name }} is Home.
          {% endif %}"

If I replace data_template with data, it won't work, HA'd complain:

jinja2.exceptions.UndefinedError: 'trigger' is undefined

dreamy sinew
#

And you have actually upgraded?

abstract tapir
#

Yes, this works for me like a charm:

- alias: Garage Door Checker
  trigger:
    - minutes: /15
      platform: time_pattern
  condition: "{{ states.cover.opengarage_a80.state != 'closed' }}"
  action:
      service: notify.telegram_to_X
      data:
        message: Garage Door is {{states.cover.opengarage_a80.state|upper}}!!!

See I replaced data_template with data

dreamy sinew
#

I r seen someone else do that already and it worked. How are you testing this?

inner mesa
#

And you’re letting it trigger and not just hitting ‘execute’?

abstract tapir
#

Okay, I hope it's my issue, let me dig a little.

#

@inner mesa dang it, you might be right

#

My bad guys, I'm glad it was my stupidity, not a common issue

inner mesa
#

Okay. You’ll need an else there, too, or it’ll complain. Or a condition before it

abstract tapir
#

Okay. You’ll need an else there, too, or it’ll complain. Or a condition before it
@inner mesa I removed some details, my full code works

#

Thanks for the headup

inner mesa
#

Ok, np

wheat cargo
#

@astral wren: an update on yesterday's issue converting a number of hours to formatted string:

        value_template: >
          {% if states("sensor.history_stats")| float > 24 %}
              {{ states("sensor.history_stats")| round(0) }}:{{ (states("sensor.history_stats")|float - states("sensor.history_stats")| round(0)) | multiply(3600) | timestamp_custom("%M", false) }}
          {% else %}
              {{ states("sensor.history_stats") | float | multiply(3600) | timestamp_custom("%-H:%M", false) }}
          {% endif %}
#

otherwise, if sensor.history_stats is 25, then timestamp_custom just shows the number of hours, which is 1 and you'd have to add %d to show a number of days (also 1) and if the sensor had a number of hours over a month, you'd have to add %m to see the number of months...

acoustic ridge
#

Do i need to remove these entity_idaslo? ```sensor:

  • platform: template
    sensors:
    last_alexa:
    entity_id:
    - media_player.henning_s_echo
    - media_player.henning_s_echo_show
    - media_player.henning_s_echo_dot
    value_template: >
    {{ states.media_player | selectattr('attributes.last_called','eq',True) | map(attribute='entity_id') | first }}```
thorny snow
#

Hi! Yesterday I got some help with one of my sensors. We got it to work but now I need to integrate the "direction" of the tram into the variables. I got it to work in the template developer but the configuration check keeps throwing an error. I'm new at programming.. so help would be appreciated!

- platform: template sensors: kvb_buzweilerhof: friendly_name: "Departures to Am Buzweilerhof" value_template: > {% set desired_tram = 5 %} {% set selected = state_attr('sensor.kvbdep_245', 'departures') | selectattr('line_id', 'eq', desired_tram) | selectattr('direction', 'eq', 'Am Butzweilerhof') | list %} {% if selected[0].direction == "Am Butzweilerhof" %} The next tram to Am Buzweilerhof will depart in {{ selected[0].wait_time }} minutes. {% else %} no trams lol. {% endif %}

deft timber
#

What's the error?

#

(I would replace if selected[0].direction == "Am Butzweilerhof" by {% if selected|length > 0 %}. I think that you will have an error evaluating selected[0] if the list is empty)

thorny snow
#

I'm not sure why it didn't catch the first time; but I now have it up and running!

#

Thanks again for your help @deft timber 🙂

obsidian cypress
#

Apologies as I'm not sure if this is the right place in the Discord to post this - I have a template sensor where the value template is:

value_template: >-
{{((as_timestamp(strptime(states('sensor.date'), '%d.%m.%Y'))-state_attr('input_datetime.softener_salt', 'timestamp')) /60/1440) | int}}

In Dev Tools > Template I'm currently getting 15 but the state of the template sensor itself is "# #15 15", what am I doing wrong?

#

Ignore me, I've just worked it out. I tried to comment out some old lines with # (to keep them in case recent changes broke) and they're being included in the output - I didn't realise it'd actually include the #

mighty ledge
#

@obsidian cypress templates include all strings in between the code. The proper way to comment in a template is to wrap the line like this {# blah blah #}

#

@acoustic ridge the entity_id field is no longer needed in 0.115. Your template sensor will still work.

obsidian cypress
#

Thanks @mighty ledge! Makes sense ☺️

faint salmon
#

Hi, I'm using sensor.random_sensor in my automation, but it doesn't update that frequently. Like every 30 seconds. Can this be faster?

#

I access the value in a template with '{{states("sensor.random_sensor")}}'

karmic oar
#

Can you change the scan_interval?

#

This sensor evaluate properly in the template editor and worked until I updated to 115.0 yesterday. I can't find any breaking changes that would cause the state to be unknown now. Any ideas? corrected_voltage: unit_of_measurement: V value_template: "{{ (((state_attr('sensor.pack_1_avg', 'mean') + state_attr('sensor.pack_2_avg', 'mean')) * 6) | float + ((states('sensor.realtime_solar_gen') | float - states('sensor.realtime_consumption') | float)* -1 / ((state_attr('sensor.pack_1_avg', 'mean') + state_attr('sensor.pack_2_avg', 'mean')) * 6) | float) * 0.00378739327871000214178624973228) }} "

faint salmon
#

@karmic oar Cant find that in the docs. Don't think it is there for the random sensor

#

Your corrected_voltage, can't you break it down in the template editor?

karmic oar
#

It works in the template editor. No issues at all.

faint salmon
#

Are there any log entries which me help you?

karmic oar
#

None

faint salmon
#

So in the States, you find your sensor.corrected_voltage and it has a state unknown

mighty ledge
#

@faint salmon all sensors on an interval accept the scan_interval field even if the docs don’t say it

faint salmon
#

@faint salmon all sensors on an interval accept the scan_interval field even if the docs don’t say it
@mighty ledge I'll give it a try

#

@mighty ledge You made my weekend a better one 😉 Thanks It worked!

wet lodge
#

Hey, folks. Since updating to 0.115, it doesn’t seem like any of my time or date-based template sensors are updating.

The new Template dev tool says they do not “listen for any state changed events and will not update automatically”.

Is this a known issue?

faint salmon
#

Ok, next question. I have a Xiaomi cube and I want to use it to change the brightness of a light by turning it. How do I get the value of the degrees in my automation action? I tried state_attr("trigger.event.data","relative_degrees") but that didn't work

"event_type": "zha_event", "data": { "device_ieee": "xx:xx:xx:xx:xx:xx:XX", "unique_id": "xx:xx:xx:xx:xx:xx:XX", "endpoint_id": 3, "cluster_id": 12, "command": "rotate_left", "args": { "relative_degrees": 91.25999450683594 }

#

So the zha_event is my trigger, that works fine, just how to get the degrees value is my issue

silent barnBOT
sleek coral
#

aw it moved my whole message. sorry

#

I want the entity's attribute to be like

- key1: value1
  key2: value2
  ...
- key1: value1
#

but it becomes a string, i.e. data: [{'key1': 'value1', 'key2': ...

silent barnBOT
arctic sorrel
#

I'd bet that you're using now() and no entities

wet lodge
#

Thanks again.

And FYI - I think the code wall tip was meant for someone else.

arctic sorrel
#

Nah, that was it helps if you share code 😉

#

Hard to diagnose problems with only it doesn't work and no context

#

(except in this case, where I'm guessing my guess was on target)

wet lodge
#

It was.

arctic sorrel
#

That has caught a lot of folks out

wet lodge
#

That doesn’t surprise me... As releases get bigger - and release notes with them - it gets easier and easier for smaller notes like this to get missed. And I suspect that’s a common function that a lot of people use.

arctic sorrel
#

Yeah, when we notice we steer folks towards the date/time sensor for that kind of thing, but it's a pain to use that way

wet lodge
#

Just did a search. I have it in 40 places in my config.

🤦‍♂️

dreamy sinew
#

115 exposes timedelta() now

distant plover
#

Is this the reason why I get 'the entity_id option is deprecated, please remove it from your configuration'? And how do I fix it if so? https://pastebin.com/0w8yrJZm

hollow bramble
#

It's in the breaking changes of 115

distant plover
#

Yeah, that's what I read. But I don't understand how to remove/fix it 🙂

hollow bramble
distant plover
#

Hmm... too complicated 🙂

hollow bramble
#

🤷 that's the way it is now

distant plover
#

Got the template I linked from a package. Don't understand how it works so it's especially hard to rewrite it.

hollow bramble
#

Remove the entity_id line and make an automation that updates the entity state based on time_pattern

distant plover
#

I don't have to touch the lines like this one |rejectattr('entity_id','in',state_attr('group.ignored_entities', 'entity_id')) ?

hollow bramble
#

no, you don't change the template at all

distant plover
#

Well that certainly helps

distant plover
#

So basically remove the entity_id: sensor.time line and add an automation like this? ``` trigger:

  • platform: time_pattern
    minutes: '1'
    condition: []
    action:
  • service: homeassistant.update_entity
    data: {}
    entity_id: sensor.utilgjengelige_entiteter```
arctic sorrel
#
    minutes: '/1'
distant plover
#

What's the difference? I made it in the UI.

arctic sorrel
#
    # Matches every hour at 5 minutes past whole
    minutes: 5
#
    # You can also match on interval. This will match every 5 minutes
    minutes: "/5"
#

(to save you from having to read the docs 😛 )

flint hazel
#

That template iterates all states. You don’t need anything to update it. You can just remove the entity id field.

distant plover
#

Nice. Thanks.

#

Then I guess I don't need the - platform: time_date in configuration.yaml anymore either.

fading plank
#

hello, i need some help. the RF bridge is passing a code to an mqtt. The code is in a json message. I need to extract that code and if it matches with the code that i'm "looking for" i would make some action. The problem is that i don't understand how MQTT Trigger will know to compare the message and the "payload" that i'm expecting

#

sshould i use value_template and compare it somehow?

arctic sorrel
fading plank
#

@arctic sorrel here it is: {"Time":"2020-09-18T18:29:03","RfReceived":{"Sync":9900,"Low":320,"High":960,"Data":"213AA2","RfKey":"None"}}

silent barnBOT
#

@fading plank Generally, don't tag people to ask for help - it comes across as bad manners, you’re demanding somebody answers you. It’s different if you’re thanking somebody, obviously. If you do tag somebody keep it polite and respectful. Remember that everybody is a volunteer, and nobody has to help you, and people may block you.

Similarly, please don’t DM (direct message) people asking for help. It also comes across as demanding, and means that others can’t learn from what you do.

Finally, please keep tagging people in replies to a minimum. That too can become annoying very quickly and should be used only when it's necessary (such as if it's been a long time, or there's multiple conversations going on).

fading plank
#

obviously i need the Data

arctic sorrel
#
{{ trigger.payload_json.RfReceived.Data == "213AA2" }}
#

"Obviously"

fading plank
#

value_template: "{{ value_json.RfReceived.Data }}"

#

aaa, so it's possible to make direct comparison

#

aaa

#

if you only said that before man 😦

arctic sorrel
#

Well, if only you'd actually answered the question I kept asking

fading plank
#

:(:(

arctic sorrel
#

We're good here, but we can't read minds

fading plank
#

Be easy on me

arctic sorrel
#

I am 😉

#

I haven't blocked you for being a help vampire and constantly tagging 😉

fading plank
#

Please, give me your "buy me a coffe" link

arctic sorrel
#

It's on my GitHub, but don't feel you need to

#

Despite my grumpy nature, I'm here to help

dusky bane
#

Hey all

#

i have problems using float it gives me error i didnt have last days in the "template training developper tool"

#

i was wondering if i'm missing something or if it's related to updates

#

do you have same kind of problems ?

inner mesa
#

No

#

But your description is very vague

dusky bane
#

yes indeed

arctic sorrel
#

Today is the day for I have a thing that doesn't work

inner mesa
#

What are you doing, what do you get, what do you expect?

dusky bane
#

my question was do you have guys general problems due to update, but i'll come with more precise question 🙂

inner mesa
#

Then, no

dusky bane
#

well, i'm creating a sensor who gives a medium value from 3 other sensors, it's working, but i don't get de round() to work, the result still have lot of decimals

      medium_temperature:
        friendly_name: 'medium of temperatures'
        value_template: >-
           {{ (float(states.sensor.thermohygro5_temperature.state) + float(states.sensor.thermohygro4_temperature_2.state) + float(states.sensor.thermohygro3_temperature.state)) / 3 | round(1) }}

this is the result in the developper tool :

medium_temperature:
        friendly_name: 'medium of temperatures'
        value_template: >-
           27.933333333333334
#

question : what is the correct syntax to have a 1 decimal number as result ?

hollow bramble
#

Your template is only rounding that 3

arctic sorrel
#

BODMAS 😉

inner mesa
#

You need more parens

dusky bane
#

so i'm rounding the 3 okay haha thats dumb

#

thank you guys

inner mesa
#

It’s the roundest 3 ever

#

And yay for specific questions 🎉

dusky bane
#

i did my best

hollow bramble
#

Your best was good 👏

dusky bane
#

i don't know if you realise the time you all save me every time i'm stuck with my own ignorance 😍

#

well it's a lot

hollow bramble
#

at least 7 probably

dusky bane
#

and it's kind of magic because sometime i just write the question and find the answer before anyone answers

arctic sorrel
inner mesa
#

The best way to learn something is to explain it to someone else, and the best way to solve a problem is often to write it out 🙂

karmic oar
#

So in the States, you find your sensor.corrected_voltage and it has a state unknown
@faint salmon Yes! I don't know why.

lapis musk
#

i'm having trouble with Template Light's set_color method. I am trying {{ h }}, {{ s }} but they are both None when it fires. the samples do not work for me even, any tips? 🙂

faint salmon
#

@karmic oar I really think you need to start from the beginning. Start small, check the state and you might know when it breaks. But I agree the syntax is good.

faint salmon
rotund hazel
deft timber
#

Looks like you are using attributes that do not exist. Could you check in the State tab the attributes of stikalo_moja_soba for instance?

rotund hazel
#

@deft timber thank you, have restarted 2 times and it is ok now😳

oak kiln
#

This is a bit of a niche use-case but can I somehow check if a jinja2 helper exists?

rain quest
#

How would I parse a response like tele/zfbridge/SENSOR {"ZbReceived":{"0xFA4C":{"Device":"0xFA4C","Name":"Osseliecht","Power":0,"Endpoint":1,"LinkQuality":55}}} ? value_template: "{{ value_json['ZbReceived']['0xFA4C']['Power'] }} " doesnt seem to work to parse the state

#

sorry if this is the wrong channel 🤔

unique condor
#

Hi can anyone please help with the following error invalid config for [script]: invalid template (TemplateSyntaxError: expected token ',', got 'volume_level') for dictionary value

#

Invalid config for [script]: invalid template (TemplateSyntaxError: expected token ',', got 'volume_level') for dictionary value @ data['script']['1589123276952']['sequence'][0]['data']. Got OrderedDict([('entity_id', 'var.alexa_living_room_volume'), ('value_template', "{{state_attr('media_player.living_show, 'volume_level')|float}}")]). (See /config/configuration.yaml, line 87).

#

The config was fine until updated to latest version

rugged laurel
#

'media_player.living_show -> 'media_player.living_show'

unique condor
#

@rugged laurel Thank you I've found and corrected it now, for some reason the config check never showed the error nor did i get a script error in notifications until this version

random wing
#

I try a sensor which is displaying the remaining days to a calendar event. But my if-else isn't working with my day calculating. When I set the bday parameter to 0 or 1 it is working. Someone knows where my problem in my "remaining day calculating" is?

{% set bday = (( as_timestamp(state_attr('calendar.contacts', 'start_time')) - as_timestamp(now()) ) / (3600*24) ) | round(0, "ceil") %}

{% if bday == "1"%} if
{% elif bday == "0"%} dummy
{% else %} else
{% endif%}

{{bday}}

south monolith
#

hi everyone I have this error

WARNING (MainThread) [homeassistant.components.template.sensor] The 'entity_id' option is deprecated, please remove it from your configuration

- platform: template sensors: simple_date: friendly_name: "Data" entity_id: sensor.time value_template: "{{ as_timestamp(now()) | timestamp_custom('%d/%m/%Y') }}"

I deleted entity id but now the time is no longer updated how can I solve?

silent barnBOT
#

@random wing Rule #6: Please do not post codewalls (longer than 15 lines) - use sites such as https://hasteb.in/, https://paste.ubuntu.com/, or others.

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

south monolith
#

nobody?

random wing
south monolith
median silo
#

Is someone able to take a quick look at my templating for my input_boolean? I just want to disable the ability to toggle the input boolean's state is 'on'
https://pastebin.com/QLsj4zgw

#

What happens is that I'm unable to toggle it even if it's state is set to 'off'

inner mesa
#

that's not the right template format for the custom button card

median silo
#

Ah okay, I see now... I need to create a separate template for this button and then add it in. Thank you!

inner mesa
#

np. basically, it uses javascript and [[[ ]]]

median silo
#

It seems like I need to add it into my ui-lovelace.yaml/raw config? That seems like an odd place to me, but oh well lol

inner mesa
#

it's no different from what you were doing before when adding the wrong kind of template

#

just use the right format

median silo
#

True true. Yeah, it was pretty simple to add

#

Sweet, it worked! Though, and this is just personal preference, but I wish it didn't ONLY work with javascript for the templating. Seems like this could be more difficult for others. But it does work great!

thorny snow
#

my output is to long.
Might know how I can limit the number of sings to 254 ?

#

! truncate

rugged laurel
#

string[0:254]

thorny snow
#

aww, thats also neat!

#

I love the options 😄 thanks

buoyant pine
#

or string[:254]

wary helm
#

Hey pros, any idea why my template is returning the state: "unknown".
I was working fine before.

      temp_living:
        value_template: '{{ ((float(states.sensor.temperature_living.state)) - (float(states.sensor.outside_temperature.state))) | round(2) }}'

Both sensors are returning the correct states

inner mesa
#

works for me for my sensors

#

did you try it in devtools -> Templates?

#

it's not really best practice, though. (states('sensor.temperature_living')|float - states('sensor.outside_temperature')|float)|round(2) would be more conventional

wary helm
inner mesa
#

please no partial images of text

#

looks like you missed a paren or something

#

I could have, too. But this works fine for me:

#

{{ (states('sensor.wirelesstag_refrigerator_temperature')|float - states('sensor.wirelesstag_master_bedroom_temperature')|float) | round(2) }}

wary helm
#

as a value_template:?

inner mesa
#

in devtools -> Templates. But no reason why it wouldn't work in a template sensor

#

did you try it in devtools -> Templates?

wary helm
#

Haven't used it before, I'll try

#

It's giving me 0.0 there, and it should be around -6 now

inner mesa
#

then your sensors aren't giving you what you thought

#

or you're using the wrong names, or soemthing

#

anyway, get it working there

wary helm
#

I have my first sensor on 23.7 and my other one on 16.1. Triple checked the names and states.

inner mesa
#

🤷

wary helm
#

negative value = unknown?

inner mesa
#

does it say "unknown" in devtools -> Templates?

#

get it working there

#

check each sensor there

wary helm
#

@inner mesa thanks alot for sticking with me but no success: If you want to check out these 3 screenshots. Something doesn't add up
https://imgur.com/a/rNmqYRT

#

nevermind

#

it works now

#

had a .sensor too much after correcting everything 🙂

#

thanks alot

inner mesa
#

I was about to ask what was wrong there

wary helm
#

So after 2 server restarts, sensor.temp_living still returns unknown. (While it works in devtools -> Templates)

temp_living:
  value_template: "{{ (states('sensor.temperature_living')|float - states('sensor.outside_temperature')|float) | round(2) }}"
buoyant pine
#

Is the entity ID right?

#

Just try

{{ states('sensor.temperature_living') }}
``` (and similar for the other entity)
inner mesa
#

what's the rest of that sensor definition?

wary helm
#

Yea, I've done this in the screenshots a bit higher. But it seems to be working now. 5 minutes after home assistant being back up completely

#

Does it need time to update? I thought it was realtime

inner mesa
#

so those sensors must be filled in over time

#

depends on where they came from

wary helm
#

I guess so. thanks alot though!

inner mesa
#

np. you can give them a default if you want them not to be "unknown" at first, or if they're from MQTT (for instance), you can retain the values

wary helm
#

I'll check it out. Thanks.

sinful bison
#

hello :)
I don't know if i should post here or in integration, but i am having issue with the light.template integration
https://www.home-assistant.io/integrations/light.template/ seam to give jinja var like {{ brightness }} and {{ h }} to use in the service, but i can't make it work. i always get python error like voluptuous.error.MultipleInvalid: expected int for dictionary value @ data['brightness']
Does someone have a working exemple ?
https://paste.ubuntu.com/p/QNprWPpvnM/

halcyon dagger
#

hi... is there a way to reference the previous value of a sensor in a template?

sinful bison
#

previous as in back in time, or the value before the automation was triggerd ?

halcyon dagger
#

back in time.

sinful bison
#

ah, i was hoping trigger.from_state.state would be enought ....

halcyon dagger
#

usecase; i'm trying to make a sensor that extracts the forecast of tomorrom from met.no, but i want to reference the 'old' version of it - so that i basically get today's forcast

sinful bison
#

i don't think there is something from the loger, but i know you can query data from the influxdb recorder, but to what extend ...

halcyon dagger
#

I guess i could make an automation that triggers when met.no forecast changes and then store the from_state.state?

sinful bison
#

i don't know met.no, but the weather integration i use will provide me with more data that i get in the state...

#

so it would work, but you may be limited

halcyon dagger
#

which one are you using?

sinful bison
#

meteofrance

#

but ... well for france obviously

halcyon dagger
#

😉

brisk temple
#

@sinful bison I don't see brightness defined for line 20, you look to have it as level_template on line 5

sinful bison
#

thank's @brisk temple, my issue was that i didnt .. use ... data_template ...

#

and i am ashame of it

#

brightness was provided by the integration itself

brisk temple
#

.115 stopped that issue, i almost said something but then stopped

#

gotcha

sinful bison
#

i won't upgrade for now, waiting for some bugfix first and then removing /merging some of my custom component

mighty ledge
#

@sinful bison are you in 0.115? If not, you need to use data_template instead of data.

sinful bison
#

yea i know, but i copy pasted from the doc, without thinking, and i forgot about it

#

thank's

thorny snow
#

good day everyone

#

i am trying to use the new timedelta() function in an automation

#

can somebody help me with that?

inner mesa
#

I'm an idiot with git, but it doesn't look like that PR (adding timedelta) has been released yet and I don't see it in the release notes or docs

thorny snow
#

:))

#

documentation seems to be a bit of an improvement area everywhere IT guys are working 🙂

inner mesa
#

it's in dev, so presumably will make it to 0.116

#

there's still a way to do what you want, it's just more complicated. do a search on the forum

thorny snow
#

that is what I spend my afternoon on 🙂

inner mesa
#

it's not too hard. this provides a timestamp of one minute ago: {{ (now().timestamp() - 60)|timestamp_local }}

thorny snow
#

for time: doesn't work

#

time: '{{ now().strftime(''%H:%M:%S'') }}' that was your input which works great

#

so actually the target is to have an automation that if Time 1 is change, set Time 2 to Time 1 - Variable

south monolith
#

hello everyone what am I wrong in your opinion? it does not return any value to me

- platform: time_date display_options: - 'time_date'

- platform: template sensors: custom_date_time_ita: friendly_name: "Ora e Data" icon_template: mdi:calendar-clock value_template: "{{ as_timestamp(states('sensor.time_date')) | timestamp_custom('%H:%M, %d-%m-%Y', true) }}"

#

the problem are in a template

silent barnBOT
#

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

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

inner mesa
#

you need to use sensor.date_time_iso and have configured that in the time_date platform

#

or reformat the time/date string

south monolith
#

you need to use sensor.date_time_iso and have configured that in the time_date platform
@inner mesa it's working thanks!

karmic oar
#

I've got a sensor that, seemingly randomly, becomes "unknown" and then stays that way for an indefinite period of time. Template evaluates perfectly in the template editor. corrected_voltage: unit_of_measurement: V value_template: "{{ ((state_attr('sensor.pack_1_avg', 'mean') + state_attr('sensor.pack_2_avg', 'mean')) * 6) + (((states('sensor.pwr_avail')|float|abs) / (state_attr('sensor.pack_1_avg', 'mean') + state_attr('sensor.pack_2_avg', 'mean') * 6)) * 0.00378739327871000214178624973228) | round(2) }}"

dreamy sinew
#

got a lot of potential string math going on in there

#

gotta |float any states() or state_attr() calls

#

looks like you got your parens right for order of operation enforcement though

karmic oar
#

Again, works great.

#

Always has... and the template editor shows it evaluating properly. 115 installed and suddenly it's unknown for random periods of time

#

Though I do see this

silent barnBOT
dreamy sinew
#

there's potential divide by 0 issues if some of those aren't available

#

yep, that's another potential result

karmic oar
#

Hmm... I suppose that could be an issue, but they'd be 0 during a reboot only momentarily and I've been running this for probably 9 months now

dreamy sinew
#

cast them all to float and they'll eval to 0.0 when they come back as None

#

just have to be careful with your divide

#

chances are those are failing too but it bails at the first issue

karmic oar
#

I think I used to have them as floats. Just changed it yesterday trying to fix this. I'll go add it back in real quick

#

Well now that I've done that it's upset about there being a zero

dreamy sinew
#

that's what i thought

#

might need to add some defaulting logic

karmic oar
#

I see where this is going with being able to reload templates without rebooting, but something has changed to a point where my templates aren't working now

dreamy sinew
#

your template as written can't handle missing sensors/attributes

#

you've been lucky so far that the problem didn't manifest, but now it does

karmic oar
#

Well, I designed it that way.

dreamy sinew
#

so now you gotta fix it ¯_(ツ)_/¯

karmic oar
#

I had some issues arise when something dropped offline or didn't report

#

So I wrote the templates in a way that allow HA to continue and pick back up when it was good again

dreamy sinew
#

yep, and things changed in the backend and the solution you have will no-longer work

#

divide by 0 is a show stopper

#

going to need to re-write this to bail safely

karmic oar
#

1 step forward, 2 steps back

dreamy sinew
#
{% if base > 0 %}
{{ ((base + (states('sensor.pwr_avail')|float|abs) / base) * 0.00378739327871000214178624973228) | round(2) }}
{% else %}
{{ "Unknown" }}
{% endif %}```
karmic oar
#

And here I thught my yaml was finally going to shrink

warm needle
#

question. my automation has the user_id in the event data. I want to turn that back into the username of the person. is there a template way to do that?

dreamy sinew
#

i don't think so. you would need to make your own map and access that way

warm needle
#

i figured it out. it's a bit groody, but it works

#
  p.attributes.user_id==trigger.event.context.user_id
  %}{{p.attributes.friendly_name }}{%endfor%}
charred haven
#

thats a smart template @warm needle !

dreamy sinew
#
{{person.attributes.friendly_name }}```
#

for the cross post

#

still grody but no loop

#

had to split because it didn't like dot-walking or .get() or even |attr() to get down to friendly_name after |first

hearty prairie
#

I'm using the custom flex-table-card in order to show some json data (from a RESTful sensor) as a table and that works great. I also have some sensor-data/manual data I want to put into a custom template sensor and present as a table, but is there a way to store the attributes in a similar pattern as the restful sensor does? If I inspect the attribute values I see nested YAML(?), but when I make a custom template sensor I see the data as an array or list and flex-table-card doesn't seem to accept that :/

hearty prairie
#

hm.. seems like going python is the only solution, seemed to work

twin cargo
#

hey, I'm not sure if I'm missing something. Is it possible to use templates in the automation trigger for: / minutes: field? Everything I've tried so far returns a syntax error.

buoyant pine
#

What's the error

#

.share that and the trigger

silent barnBOT
twin cargo
#

based on the documentation, I'm going to try it without the hours/minutes/seconds being broken up as the ui editor does.

buoyant pine
#

Wrap the template in double quotes

twin cargo
#

ok

#

ok, cool. that validates and was pretty easy. thanks @buoyant pine !

mellow perch
#

I'm trying to convert b to Mb in a template. I've got "{{ states('sensor.arris_sbg10_router_b_sent') | (float / 10**6) | round(1) }}" If I don't put the float in () it doesn't round, but if I do, I get an error "expected token 'name', got '(') for dictionary value"

dreamy sinew
#

.share the full thing please

silent barnBOT
mellow pulsar
#

Hi all, I am using a value_template in a sensor, and I am getting the error : TypeError: unsupported operand type(s) for -: 'str' and 'str'
The operands are decimal values . When I do the template, I did not specify the data type as it wasn't needed prior to .115.. Does .115 now require them to be defined specifically now?

inner mesa
#

no changes there that I'm aware of. states are always strings, and need to be converted/filtered to numbers (int/float) if you want to compare them (</>/etc.) or perform math operations on them

#

it's possible that it's just calling out more existing issues, but it's likely that it wasn't working properly before

#

but I'm just guessing without the actual template

mellow pulsar
#

here is what i have currently, that was working....
value_template: "{{ state_attr('sensor.statswdaccx', 'max_value') - state_attr('sensor.statswdaccx', 'min_value') }}"
do i then need to convert it to this:
value_template: "{{ state_attr('sensor.statswdaccx', 'max_value')|float - state_attr('sensor.statswdaccx', 'min_value')|float }}"

#

just making sure i have the right syntax

inner mesa
#

yes, that should work. try it in devtools -> Templates

mellow pulsar
#

thanks

#

adding |float to the operands fixed it. thanks!

halcyon ridge
#

HI, after upgrade to 0.115 (now 0.115.2) entity_id is deprecated in templates. I have 1 sensor which calculate days from specific date, but it does not work anymore. Should I use again entity_id: sensor.time or do automation to call update entity ?

- platform: template
  sensors:
    left?:
      value_template: "{{ (( as_timestamp(now()) - as_timestamp(strptime('29.8.2020 13:30', '%d.%m.%Y %H:%M')) ) / 86400 ) | int }}" 
      # entity_id: sensor.time
      icon_template: "mdi:timer-outline"      
      unit_of_measurement: "Days"
inner mesa
#

no, because using entity_id is deprecated

#

I believe you can use states('sensor.date_time_iso') in place of now()

#

assuming that you set that up in the time_date integration

halcyon ridge
#

please explain "assuming that you set that up in the time_date integration" . It is configured in sensors/date_template.yaml file

#

I can't see such a time_date integration in config panel

inner mesa
#

you still have to configure it manually, it appears

halcyon ridge
#

yes, I have this integration enabled and configured manually,

inner mesa
#

if you have sensor.time, you probably already did

halcyon ridge
#

ok, I'll try to change now()

inner mesa
#

so, if you have - 'date_time_iso' there, then use that as I described

#

try it in devtools -> States and make sure that it gives you the right answer

halcyon ridge
#

yes, it is working, Should I replace now() in automations too or it does not matter ?

umbral void
#

Hi All - I'm coming up to speed on all the capabilities and options of automations/scripts et al. I just discovered the "choice" entry allowing me to combine several conditions into one automation. My task at hand is a 4 rocker-button X10 (yeah, X10 - but the wireless stuff is not bad!) which transmits (eg.) A1 ON/OFF for top button, A2 ON/OFF for next button etc. I've installed the w800rf32 integration and it appears to be working fine.
So now I want to deal with those buttons in one automation - at first it seemed i had to create an automation for each button and each state (rocker on/off).
Choose seems to help with that - a choice for each button - but it seems I still need to create a condition for ON and a condition for OFF. Is there not a way to simple pass the state of the "trigger" to the thing I want to control?
i.e someone presses A1 ON. I would want to just pass whatever A1 stste just changed to to the light etc that I want to control.
Am I missing a point here?

silent barnBOT
arctic sorrel
#

There's the docs to have a read through

#

You can do things like:

- service: >
    {% if trigger.to_state.state == 'ON' %}
      switch.turn_on
    {% else %}
      switch.turn_off
    {% endif %}
#

There's much shorter ways of doing that, but longhand is a good starting point

umbral void
#

Been reading those. I must have missed where I can pass automation trigger info to a template

arctic sorrel
#

First link above

#

Also, HA is case sensitive, ON and on and On are three different things

umbral void
#

sigh. How do you jnow which your particular device/entity needs? Look at logs?

arctic sorrel
#

Well, to know the state of any entity, look at devtools -> States

#

That's your truth table for HA

umbral void
#

got it.

arctic sorrel
#

For what service that's linked to the domain, such as switch

uneven tangle
#

I am using a template as an automation trigger which should only trigger when one temperature sensor is above the other one but unfortunately it also triggers a lot of times when it shouldn't. does anyone have any idea what could be wrong?

{{ states('sensor.studiobrick_temperature')|int > states('sensor.gym_temperature')|int }}

dreamy sinew
#

if the right side is ever unknown it would eval to 0

#

"string"|int -> 0

uneven tangle
#

Thanks, I see what's the problem. Guess I have to exclude values 0 in my template then. any idea how to do that?

#

Oh I think just using values 0 as a condition in the automation will work!

obsidian cypress
#

I’m trying to convert an input number into an automation I’m doing. There are two ways that I can see going about it, first is to have the input number and then create a template sensor that multiplies the value of it by 60 so that I can reference the number of seconds in the automation...
My other idea is to have the time formatted version using a template of the input number, however I’m having an issue.
{{"00:0" + states('input_number.hallway_timer') + ":00"}} becomes 00:02.0:00 due to the input number having a decimal place. I want to pipe the input number to an integer but I get an error in the dev tools template section when trying this {{"00:0" + states('input_number.hallway_timer') |int + ":00"}}
Any suggestions?

dreamy sinew
#

{{ "00:{}:00”.format(states('input_number.hallway_timer')) }}

obsidian cypress
#

{{ "00:{}:00”.format(states('input_number.hallway_timer')) }}
@dreamy sinew I wasn’t aware of that formatting method, so thank you! To get the input number to an integer I slightly changed your answer, but wouldn’t have got there without you!
{{ "00:{}:00”.format(states('input_number.hallway_timer')|int) }}

dreamy sinew
#

Since you're making it an integer I think you can add 0 padding

#

Just too much if a pain to type out on mobile

obsidian cypress
#

That’s cool dude, thank you! I need to read up on my Jinja as there’s clearly a lot more to it!

shy badge
#

Hi, just looking for some help with a template for my RF blind. I control this with a Broadlink RM Pro and since HA V115 it stopped working. This is code I think is correct but it still isn't working. Any help would be a appreciated please.

dreamy sinew
oblique raptor
#

What is the best way to get the next occurrence of a certain appointment in a calendar?

uneven tangle
#

Does anyone know if I can can use <= for smaller than or equal to with home assistant templating?

arctic sorrel
#

Yes

uneven tangle
#

great, thanks

silent barnBOT
willow elk
#

How can i change the Output from "2020-09-20T13:27:09.681681+00:00" to a Timer?

dreamy sinew
#

is that the finish time?

willow elk
#

Yes

dreamy sinew
#

and where is it coming from?

willow elk
#

This is a sensor for my washing machine over the Home Connect integrations

dreamy sinew
#

create a time_date sensor and then create a template sensor that evals the two

willow elk
#

OK, i will give this a shot. Thanks

#

I created the date_time sensor, but i cant figure out how to evals the two sensors

sinful torrent
#

I have this working using the template schema, but I cannot implement the RGB portion using that schema because it doesn't support RGB commands on a separate topic.

#

Any help would be greatly appreciated!~

dreamy sinew
#

is it not zwave?

sinful torrent
#

yeah i'm using zwave2mqtt

dreamy sinew
#

should probably take a look at the ozw integration

sinful torrent
#

okay thanks

#

so are you suggesting that it's not possible to do what i want currently?

#

i could look into submitting a pr to add functionality to the mqtt templating if that's the case

dreamy sinew
#

i have no idea, i don't have that device nor do i use that integration

sinful torrent
#

i'm just talking about the mqtt light templatnig

dreamy sinew
#

but, since you're using zwave, you really should consider the ozw integration as it is much more likely to handle this properly

sinful torrent
#

i have everything setup with zwave2mqtt because i'm using a pi in the middle of my house

dreamy sinew
#

it seems like zwave2mqtt is doing something funky with that device

#

ozw supports that flow

sinful torrent
#

okay ill look into that then

#

thanks

void steeple
#

is there a way to set a variable while inside a for loop?

deft timber
#

I don’t think so...

void steeple
#

for example ``` {%- set found=false -%}
{%- for value in textList -%}
{%- if key in value -%}
{%- set found= true -%}

deft timber
#

It won’t work that way

void steeple
#

Yeah.. is there a way to find out if my value has ever been found?

#

I am trying to get it to print false if the key value was never found in the list. Then print the keyCode if it is found in the list and is valid and then print invalid if it is not a valid keyCode..

#

I know I am shoving a lot in to that variable..

#

I have most of it working just cant get it to print out false if nothing is found.

#
           {%- for value in description -%}
             {%- if search in value-%}

                {%- set code = (value.split(":", 2))[1]  -%}
                {%- set code = (code | regex_replace("[^0-9]*", "")) -%}
                {%- if (code | length < 4) or (code | length > 8) -%}
                  Invalid
                {%- else -%}
                  {%- for number in code -%}
                    {{number}}
                  {%- endfor -%}
                {%- endif -%}
              {%- endif -%} 
            {%- endfor -%}
            {%- endif -%}
#

I need something at the end of the for loop that could tell me if I have ever found a key code.

#

search = "K:"

deft timber
#

Why not simply {% if search in description %} ? Is the for really needed ?

#

ah ok, forget my question

void steeple
#

well that might work. If i did that first.

dreamy sinew
#

need to do namespacing

deft timber
#

With macro ?

#

`{% macro isInList(search) %}
{%- set description = ['Jeff', 'K:34333'] -%}
{%- for value in description -%}
{%- if search in value-%}

         {{ true }}
          {%- endif -%} 
        {%- endfor -%}

{%endmacro%}
{% if isInList("K:") %}
found it
{%else%}
did not found it
{%endif%}`

dreamy sinew
#
{% set ns = namespace(found=false) %}
{% for v in temp if "foo" in v %}
{{v}}
{% set ns.found=True %}
{% endfor %}
{{ ns.found }}```
#

looks like the for ... if ... would be useful to you too

#

might need to share the full thing though. where is search coming from?

inner mesa
#

from the macro parameter, it appears. but since you can't have global scope, that's not very useful

void steeple
#

I dont think it is the prettiest but I got it to work.

silent barnBOT
void steeple
#

I am trying to take keycodes out of a google calendar so that I can send it to the zwave lock when the event starts and then remove it from the zwave lock when the event ends.

#

I am trying to automate my vacation property 🙂

#

This way all I have to do is create a new event in the google calendar where I set K:923923 in the description and it will extract it.

dreamy sinew
#

ok, you can slim it a bit by doing {% for value in description if search in value %}

#

looks like you're doing that lookup twice though?

void steeple
#

I am which I know is not the most efficient but I had to do that because it is the limitation of Jinja

dreamy sinew
#

i don't think that would be the result of a limitation

#

oh, you're using that to set false

#

use the namespace example from above

void steeple
#

Does namespace make it a global variable?

dreamy sinew
#

definitely available to anything in the macro, haven't tested beyond that

#

might be truly global

#

(to the scope of the template)

void steeple
#

I think the reason why you can not set variables inside of a for loop is because it is rolling back the memory heap

dreamy sinew
#

no, its namespacing

#

anything inside the loop is scoped to the loop

#

all {% set %} commands are limited to the scope of the loop

void steeple
#

Right that make sense. I was trying to do something like a set found = true if the key code was actually found in the loop.

#

I will try it with the namespace

dreamy sinew
#

yep, so define that namespace and you can then set ns.your_var = <whatever>

void steeple
#

that would improve the BigO of the macro.

dreamy sinew
#

probably don't need the macro at all at that point

#

it isn't hurting anything though

inner mesa
#

right, you're defining a macro to call exactly once 🙂

void steeple
#

That seems to work as well. Thank you for your help.

dreamy sinew
#
{%- set ns = namespace(found=false) %}
{%- for value in description if 'K:' in value -%}
{%- set ns.found = true -%}
{%- set code = (value.split(":", 2))[1]  -%}
{%- set code = (code | regex_replace("[^0-9]*", "")) -%}
{{ code if 4 < code | length < 8 else "Invalid }}
{%- endfor -%}
{{ false if not ns.found }}```
#

one more reduction

void steeple
#

that is much cleaner then what I had written thanks!

dreamy sinew
#

you could combine those 2 code sets but splitting into 2 lines makes each line not as long so i can appreciate that

#

give it a shot to see if it works. i don't have the input data so i can't be sure

void steeple
#

I ran it through all of the test inputs and it worked well..

#

Thank you again. Its interesting to see how much more simplistic it can be.

dreamy sinew
#

pretty complex but easy to read.
Name-spacing, filtered for loop, and in-line if statements

#

also "between" comparisons

#

you might want <= for both of those

#

if 4 and 8 are valid numbers

#

oh, bonus, this protects against unknown

torpid vale
#

This is from a script that requires input data brightness, to_state, color_temp and transition.

      - service: "{{ 'light.turn_' + to_state }}"
        data: >-
          {% if to_state == "on" %}
            brightness: "{{ brightness }}"
            color_temp: "{{ color_temp }}"
          {% fi %}
          transition: "{{ transition }}"
          entity_id: light.outside_bathroom

I can't get it to work and get this error.

Invalid config for [script]: expected dict for dictionary value @ data['script']['hallway_bedroom_to_livingroom']['sequence'][0]['choose'][0]['sequence'][0]['data']. Got '{% if to_state == "on" %}\n brightness: "{{ brightness }}"\n color_temp: "{{ color_temp }}"\n{% fi %} transition: "{{ transition }}" entity_id: light.outside_bathroom' expected dict for dictionary value @ data['script']['hallway_bedroom_to_livingroom']['sequence'][0]['default'][0]['data']. Got '{% if to_state == "on" %}\n brightness: "{{ brightness }}"\n color_temp: "{{ color_temp }}"\n{% fi %} transition: "{{ transition }}" entity_id: light.hallway'. (See /config/configuration.yaml, line 42).
inner mesa
#

it's hard to tell from that unformatted mess 🙂

silent barnBOT
#

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

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

inner mesa
#

to start, the service is light.turn_on, and your template will produce something like light.turnon if you're just passing in on

#

<keep trying 🙂 >)

#

{% fi %} should be {% endif %}

#

recommend consulting templating docs

silent barnBOT
torpid vale
#

@inner mesa discord messed it up. Better in paste link above. endif is a good lead 🙂 I'm testing now

inner mesa
#

you may not be able to group two tags together within a single template as you've done with "brightness" and "color_temp"

#

dunno

torpid vale
#

ok :/ What the heck ? 🙂

inner mesa
#

"entrence" is spelled wrong, but maybe?

#

and if you're just doing the same thing to a bunch of entities, you can just list them like this:

torpid vale
#

"entrence" is spelled wrong, but maybe?
@inner mesa it's by design 😉

inner mesa
#
  fix_scene_states:
    # mode: parallel
    sequence:
      - entity_id:
          - script.fix_fr_scene
          - script.fix_mbr_scene
          - script.fix_kit_scene
        service: script.turn_on
#

in other words, you have multiple, identical blocks when a single one with a list of entities should suffice, I think

torpid vale
#

i don't know if you can change brightness

inner mesa
#

anyway, there's much to chew on there...

edgy dirge
#

How do fe find the date fiffrence from 2 dates?

#

{{ (states.sensor.last_reading_taken_date.state) - (states.sensor.due_date.state) }} Not working

copper spruce
edgy dirge
inner mesa
#

That’s not what the post says and is different from the original dates you were trying to subtract

edgy dirge
#

ya ok, but my sensor.last_reading_taken_date is pooled from electricity company server. So i want to subratct that from todays date

inner mesa
#

Take a closer look at the post

#

And understand what it’s doing

edgy dirge
#

I dont see attribute end_time for my sensor

topaz silo
#

i am having a real hard time with templates. I originally wanted to take the data from my JSON API as a 'state' but i hit the 255 char limit, so i had to put it as an attribute.. now im struggling on extracting the data is a decent way from the attributes.. https://imgur.com/a/tA6ddrh

#

i am basically wanting to be able to display information from each of the 'routes'

#

perhaps with each 'route' as its own sensor?

deft timber
#

what do you want to display exactly?
Here is a template to display the name of the route
{%- for f in states.sensor.bayislandsguide.attributes.route -%} {{f.name}}, {%- endfor -%}

topaz silo
#

i want to be able to display the name of the route, and the 'departstime'

deft timber
#

Well this should make it:
{%- for f in states.sensor.bayislandsguide.attributes.route -%} {{f.name}}: {{f.departstime}}, {%- endfor -%}

topaz silo
#

i will give it a try, thanks.

#

ok, so that is showing the info i want.. ill try to work out what else i need from here

#

i think my end goal should be to make 2 sensors, which i can then display in the UI

#

unless i am doing something wrong?

deft timber
#

No you don’t. It really depends on what you want to do

topaz silo
#

i just feel like i am doing things in way too many steps

#

and i want to display 2 items.. "4:30AM Direct to Redland Bay" and "7:20PM via all islands" or whatever

#

i am currently using the 'rest' integration to fetch the data

rugged laurel
#

I would just make a custom component for it instead, should be doable with around ~50 lines

topaz silo
#

that was my original thought.. but i am very new to all of this

#

of course, there is also the 'gtfs' integration, but its not giving correct data

#

it seems to show 'No more departures' when I know there are.

coarse tiger
#

I have this sensor giving me avg of 2 temperatures

        value_template: '{{ (float(states.sensor.wohnzimmer_motion_1_temperature.state) + float(states.sensor.wohnzimmer_motion_2_temperature.state)) / 2 | round(2) }}'
        unit_of_measurement: °C```
Is there a better way to do this?
Seems like it only updates if one of those 2 sensors changes values
topaz silo
#

well, the average is no different if the values have not changed.. so there is no need to update

coarse tiger
#

problem is it stays "unknown" after reboot UNTIL one of them changes

coarse tiger
silent barnBOT
dreamy sinew
#

if you don't want to do that:

wohnzimmer_sensor_avg:
  value_template: ->
    {%-set sensors = [float(states.sensor.wohnzimmer_motion_1_temperature.state), float(states.sensor.wohnzimmer_motion_2_temperature.state)] | map('float') -%}
    {{ sensors | sum / sensors|reject('eq', '0.0')|list|length }}
  unit_of_measurement: °C
#

this is abusing the fact that {{ "NaN"|float }} evals to 0.0

worn nova
#

Hi all how would I got about creating a template sensor to output text based on two values?

entity_id - sensor.bme680_static_iaq_accuracy
ie
i want an output based on between 0 & 1
different out based on between 1 & 2
and so on

dreamy sinew
#

what if the value is equal to 0, 1, or 2?

buoyant pine
#
value_template: >
  {% set val = states('sensor.bme680_static_iaq_accuracy') | float %}
  {% if val <= 1 %}
    One
  {% elif val <= 2 %}
    Two
  ...
  {% else %}
    One million
  {% endif %}
worn nova
#

Thanks, will give that a go

mental charm
#

Can anyone tell me if there is a state_not you can use in the wait templates?

buoyant pine
#

@mental charm

"{{ not is_state('sensor.whatever', 'something') }}"
mental charm
#

That will work for a wait template?

#

Just wanna make sure because in the dev tools template area it doesn't show as true or false

buoyant pine
#

Yep, use it all the time

#

It should show true or false...what are you trying and what does it say?

mental charm
#

{{ not_is_state('media_player.living_room_speaker', 'playing') }}

buoyant pine
#

{{ not is_state ...

#

Not {{ not_is_state ...

mental charm
#

🤦‍♂️

#

Thanks

sinful ridge
#

I'm working on a template sensor. I have a capacitance soil sensor that gives me readings between ~500 and 1000 that corresponds to 100% wet and 0% wet. I've got the formula sorted, moisture% = 200 - (0.2*soil_sensor). That will take my analog signal and give me a 0-100% moisture reading which is what I want. There will be more work later to limit it to no lower than 0% and not higher than 100% but I digress. Been playing with the templating tool and I got the math working but I'm not sure how to insert the entity into the formula.

My formula is: {{200 -(0.2*X)}} When I change X to a number between 500 and 1000, I get a good result. What I need to have in there in place of X is my entity which is: sensor.soil_sensor_analog_a0. Simply adding it like that didn't work, not putting it in quotes. I know I'm overlooking something fundamental but I just can't figure it out.

hollow bramble
#

{{ 200 -(0.2 * states('sensor.soil_sensor_analog_a0')) }}

sinful ridge
#

That's giving me "unknown error".

#

But I think I get what I was missing. Perhaps it's a formatting thing at this point.

hollow bramble
#

Are you sure that sensor id is correct?

#

oh you might need to cast it to a number first. Try {{ 200 -(0.2 * states('sensor.soil_sensor_analog_a0') | float) }}

sinful ridge
#

That's was it!

#

Cheers!

#

I was assuming it was already a number. Fun stuff 😉

hollow bramble
#

All states are strings, even if they disguise themselves otherwise sometimes

sinful ridge
#

And I'll need to keep it a number if I want to do my comparisons as well. My template sensor will have an if > 100 then cap the value at 100, andif lower than 0, cap at 0, elseif it's just the value.

#

This is what I ended up with:
{{ 200 -(0.2 * states('sensor.soil_sensor_analog_a0') | float) |round }}

#

I can't seem to simply put the above into an if/then statement.
if {{ 200 -(0.2 * states('sensor.soil_sensor_analog_a0') | float) |round }} > 100
Do I need to be using is_state or something else for a comparison?

dreamy sinew
#

What are you trying to accomplish?

#

Might be worth reviewing the docs for the templating language

silent barnBOT
sinful ridge
#

It was just the formatting, I included the {{ }} by mistake

#

Yep, been reading the Jinja stuff. It's a steep learning curve for me though. Working through it slowly 🙂

#

What are you trying to accomplish?
It's an imperfect template sensor conversion. I have an analog sensor that gives me values between 500 and 1000. I'm converting it to a percentage but if it goes above 1000 or below 500 I get a percentage above 100 or a negative number. So I was making an if/then statement to limit it to 100 if it went above 100 and to 0 if it was below zero. That way I alays get a value between 0-100. The Jinja formatting and logic isn't easy for an old fart like myself. Got it working finally though. Thanks to the help here and a lot of trial and error with the templating tool.

dreamy sinew
#

That template tester is probably my most used feature

sinful ridge
#

I was thinking what it would have been like to try and figure this all out in my config file and rebooting each time 😮

dreamy sinew
#

Yeah...

nimble marten
#

Could someone improve upon or advise if what is below is possible Within my automation which cycles through different WLED effects, can i under the data template, for each effect, set is timing, brightness and intensity etc and pallet https://paste.ubuntu.com/p/QTgpNs2GSk/

violet oyster
#

I may have found a bug (or am stupid). I was just adjusting an elaborate template sensor. this template refers to another template sensor. after I was done adjusting it, I used the new 'reload template entities' feature. after reloading, the template sensor entity showed unavailable. In the logs I am seeing ''None' has no attribute 'state'' for any template entities that refer to another template, or 'Template loop detected while processing event' for some of them. All my template entities are showing unavailable if they refer to another template. When I put them in the template tool, they render correctly. If I restart home assistant, everything works correctly. Is this expected behavior for the new reload function for template entities?

dreamy sinew
#

hmm, might be worth something

#

never tried templates calling templates

violet oyster
#

yeah many of mine do

#

maybe that is just so rare that it wasn't considered. im just confused why restarting doesn't have this problem when the reloader does

dreamy sinew
#

are the deps higher in the list?

#

dunno if that matters

violet oyster
#

i moved them around to test that, no difference. one of them is the very last elif in the list

#

oh wait what list do you mean

dreamy sinew
#

in the config.yaml

violet oyster
#

in the actual yaml docs?

dreamy sinew
#

yeah

violet oyster
#

ohhh

dreamy sinew
#

probably need all the deps to load before the things that call them

violet oyster
#

damn yeah so this is a me problem

dreamy sinew
#

its a huge guess

violet oyster
#

gonna be a bitch to fix that since i use packages and they are all spread out. but i bet you are right

dreamy sinew
#

oh gross

violet oyster
#

the config has gotten away from me lol

sturdy cloak
#

Hi All, I've been using HA for 18 months now and I am loving it. I have always managed to find answers on forums/Internet on how to do what I needed but this time I am struggling.
I'm trying to create a binary template referencing two lux sensors in an OR configuration but cannot for the life of me get it to work.
value_template: >-
{{ states('sensor.hall_lux')|float < 5
or state("sensor.study_lux')|float < 5 }}

Any ideas??

inner mesa
#

You’re missing the ‘s’ in ‘states’ in the second one

#

And you have a double quote where a single quote should be

thorny snow
#

Hi all, I have 4 sensor entities to get ink levels and a 5th to get status of my printer. When my printer is on, I have the ink levels like this :
https://ibb.co/LtbQxpD
When my printer is off :
https://ibb.co/9TDPHc4
I'd like to get the last ink levels with normal color drop icon when printer is off
and the update ink levels with personalised ink color (black, yellow, magenta, cyan) drop icon when printer is on

I looked around templates and icon_color with custom UI but without success
Thanks for you help

rugged laurel
#

@sinful ridge "{% set forecast = state_attr('weather.home', 'forecast') or [] %}{{ forecast[0].get('temperature') if forecast}}"

sinful ridge
#

OK, I'll give it a try. Thanks.

sinful ridge
#

The above didn't seem to make any difference.

I was playing around and tried this:
{{ state_attr('weather.home', 'forecast') }}
Which gave me the full forecast array:
https://paste.ubuntu.com/p/5N6bTPbvqy/

What's the formatting to pull specific data out of that array? forecast[1].temperature doesn't pull the temperature for the 1st forecasted day. I get "None" as the result.

rugged laurel
#

If what I gave you does not work, you are using it wrong, or the entity/attribute does not exsist

sinful ridge
#

I don't doubt I'm using it wrong. I simply copy/pasted it directly into the templating tool. It gave no output.

rugged laurel
#

Then the entity or attribute does not exsist, for me it display a temperature

sinful ridge
#

From the forecast array, I can see the data I need. I just don't know how to pull that one specific bit of data.

#

Arrgh! Type-o

#

It works!

#

Thank you.

viral bolt
#

Hi guys, can someone help me translating a curl command in platform: rest config?

#

but it is not working

#

thanks

deft timber
#

What do you mean by 'not working'? You have the logs?

viral bolt
#

the value I get for that specific sensor is null

#

the entire rest entity is like this:

#
  • platform: rest

    resource: "https://data.uradmonitor.com/api/v1/devices/<SysID>/all/60"

    headers:

    "X-User-id": “xxxx”

    "X-User-hash": “xxxx”

    scan_interval: 60

    name: uRad_Cloud_Noise

    value_template: '{{ value_json.data.noise }}'

    unit_of_measurement: "dB"

deft timber
#

any reason why you have '#' before all the lines? everything is commented ?!

viral bolt
#

In my current config I've commented the lines as they are not working

deft timber
#

Not sure X-User-id & X-User-hash should be between quotes

dreamy sinew
#

would be valid if everything was wrapped in {} but yeah

#

bad mix of json and yaml there

viral bolt
#

when running the curl command I get the following results:

dreamy sinew
#

before you paste, you should use a code sharing site

silent barnBOT
viral bolt
#

[{"time":1600956088,"latitude":44.xxxx,”longitude":29.xxxxxx,”altitude":100,"timelocal":4080,"temperature":28.5,"pressure":100072,"humidity":70.599999999999994,"voc":44942,"noise":45,"co2":878,"ch2o":183,"o3":20,"pm1":277,"pm25":369,"pm10":580}]

#

and I want to extract all these values: temp, humidity, etc

deft timber
#

Try {{ value_json[0].noise }} instead of {{ value_json.data.noise }}

viral bolt
#

removed the quotes ... no errors when checking the config but the value is still unknown

#

@deft timber it works!

#

thanks a lot man

#

now, for each value I want to extract I need to create a separate entity or it is possible to get all the values in one shot?

deft timber
#

either you create a rest sensor for each of your measures (temp, humidity, ...) or you create just one a put all the info you want in the attributes

viral bolt
#

I think I'll create a sensor for each value as you can guess I have no clue when coding :))

deft timber
#

Never tested it but this could work, the value of the sensor would be the temp; and humidity, temp & noise would be in the attributes of the sensor:
value_template: {{ value_json[0].temp }} json_attributes: - humidity - temp - noise json_attributes_path: $.[0]

viral bolt
#

@deft timber it works a per your indication

#

temperature: 28.75
pressure: 100079
humidity: 69.6
voc: 48703
noise: 42
co2: 880
ch2o: 172
o3: 20
pm1: 159
pm25: 205
pm10: 299

#

I'll keep each entity separate as I want to graph the values over time for each value

#

thanks again for your help

dreamy sinew
#

if you want to split to different entities, its better to have one sensor for the rest call and do the rest in template sensors pulling from those attributes

#

otherwise you're going to spam the hell out of that endpoint

viral bolt
#

@dreamy sinew I have no Idea how to achieve this...

dreamy sinew
deft timber
#

`sensor:

  • platform: template
    sensors:
    urad_noise:
    value_template: {{states.sensor.urad_cloud_noise.attributes.noise}}
    unit_of_measurement: dB`
dreamy sinew
#

i'd use the state_attr() notation for that

deft timber
#

👍

#

indeed, better

dreamy sinew
#

if the template sensor starts up before the rest sensor does you'd throw an exception with the other method

viral bolt
#

so how value_template: {{states.sensor.urad_cloud_noise.attributes.noise}} would look like using state_attr()?

dreamy sinew
#

if you click the link i posted there's an example

viral bolt
#

please don't get mad at me ... I have no coding skills

deft timber
#

state_attr('sensor.urad_cloud_noise', 'temp')

gilded spire
#

Well I changed my template sensor 3 different times

#

Now I have the old names in history

#

(I really tried searching, so I'm so sorry🙈)

buoyant pine
#

They'll fall off after the next DB purge

#

Which is nightly by default

gilded spire
#

🙏

buoyant pine
#

You could manually edit the DB but I doubt that's worth it

gilded spire
#

I'll put up with it for a while

#

I'd probably edit it, I have too much to do

#

With other aspects of my life. Wish I could just screw off everything and really focus on HA

#

I setup a template sensor for the temp to automate my heater, I was using YR temp before that.

oak kiln
#

Since the fan.mqtt integration requires some work, I need a template which returns a json string

#

{{{"fanSpeed": "value_json.fanSpeed"}}}

this sadly doesn't work :/

#

nvm I'm just very stupid

#

{"fanSpeed":"{{valueJson.fanSpeed}}"}

river blade
#

Hello, maybe someone have a small fix. Since 0.115 this template does not work anymore. The value_template part still works, but the rest...

#
- platform: template
  sensors:
    wz_temp_mean:
      value_template: >
        {{ ( ( (float(states.sensor.wohnzimmer_multisensor_temperature_air.state))
          + (float(states.sensor.ht_livingroom_temperature.state))
          + (float(states.sensor.ht_diningroom_temperature.state)) ) / 3 )
          | round(1) }}
      unit_of_measurement: °C
#

Had a look into the docs, but this should be still the right syntax.

silver pewter
#

Hello all, i want to use my next phone alarm as trigger! i set alarm time on 07:30. See picture https://i.imgur.com/i4QIGlA.png . How can i set that time as trigger? i dont have the same alarm time everyday.
i cant get the attributes of the state with ; "{{ state_attr('sensor.marcus_p30_next_alarm', 'Local Time') }}"
this works but that time is wrong : {{ states('sensor.marcus_p30_next_alarm') }}

deft timber
#

@river blade , I don't understand why you have the 'state' at the end. It shoud be states.sensor.wohnzimmer_multisensor_temperature_air (or states('sensor.wohnzimmer_multisensor_temperature_air')

#

@silver pewter , didn't Tinkerer help you with that yesterday in #automations-archived and recommended you to use an input_datetime for that purpose?

silver pewter
#

like you see on the imgur link, right time is under "Local Time" and state showing 2h wrong

#

or is it right but it showing time as 12h clock am/pm ? i need 24h clock xD

#

@deft timber sry bad english 😛

river blade
#

@silver pewter , didn't Tinkerer help you with that yesterday in #automations-archived and recommended you to use an input_datetime for that purpose?
@deft timber No. That .state ist required at then end of entity. Otherwise it does not work.

deft timber
#

Did you tried to get the time from the attributes?

#

indeed teqqyde, my bad

silver pewter
#

When i att this to the automation : datetime: "{{ state_attr('sensor.marcus_p30_next_alarm', 'Local Time') }}"

#

it doesent work

deft timber
#

Maybe you can try a min/max sensor teqqyde ?

#

which can compute the average

silver pewter
#

but it gets the right time in template under developer tools

river blade
#

Oh. That seems a much better option. Thanks for the recommendation!

silver pewter
#

@teqqyde do you know what is wrong with my template?

deft timber
#

I think it is a problem with the timezone

silver pewter
#

okok, i have this in my docker compose:
volumes:
- /etc/localtime:/etc/localtime:ro
- /etc/TZ:/etc/timezone:ro
environment:
- TZ=Europe/Stockholm

#

I have to look into it

#

thx for answering me 🙂

#

The time is right in ha, like loogbook. strange 😛

earnest cosmos
#

Hi, guys!
Can some of you bright coders here, shed some light on this service_template, which I cannot get to work...
It is part of an action: in an automation

- service_template: "{% if states.sensor.planter_urtehage_fukt.state < '25' %} script.vanning_terrasse_og_urtehage_tidsstyrt"
What am I missing?

deft timber
#

Don’t you miss the {% endif %} statement ?

earnest cosmos
#

Don’t you miss the {% endif %} statement ?
@deft timber I´ve tried that too, and over multiple lines... This do not compile
{%- if states.sensor.planter_urtehage_fukt.state|int < '25' -%} script.vanning_terrasse_og_urtehage_tidsstyrt {%- endif -%}

#

Neither do

- service_template: >-
    {% if states.sensor.planter_urtehage_fukt.state < '25' %}
      script.vanning_terrasse_og_urtehage_tidsstyrt
    {% endif %}
buoyant pine
#

I don't understand why you have the 'state' at the end. It shoud be states.sensor.wohnzimmer_multisensor_temperature_air (or states('sensor.wohnzimmer_multisensor_temperature_air')
@deft timber this is not correct, states.sensor.wohnzimmer_multisensor_temperature_air.state is valid. However, the second method in your message is preferred.

#

@earnest cosmos Remove the quotes around '25'. You're making 25 a string when you put it in quotes. Also if that sensor is above 25 that automation will print an error about a missing service (and it might not continue past that action, but I'm not sure about that)

earnest cosmos
#

@deft timber Keeping the multi line version?

buoyant pine
#

You also need the | int that you had originally. Finally, states('sensor.planter_urtehage_fukt') | int would be better

#

Can you share the entire automation? There might be a better way of accomplishing what you're trying to do

silent barnBOT
deft timber
#

Yes @buoyant pine , I noticed my error 🙂 one moment of distraction 😉

willow elk
#

Hello, im trying to get a Template that shows the Time left unitl my Washingmaschine is finished.

Output of {{ states('sensor.waschmaschine_remaining_program_time') }} is 2020-09-25T14:12:19.957394+00:00

This is also not my TimeZone it is the UTC Timezone.

How do i get this to show something like "2h Remaining" or "02:20:12" (hh:mm:ss)?

waxen rune
#

I think you could use timestamp_local

#

I have a value_template: "{{ state_attr('sensor.utomhus_framsida_temperature', 'lastUpdated') | timestamp_local }}"that works fine
or use something like this:

{{ as_timestamp(strptime(states.binary_sensor.status_smoke_sensor_0.last_updated | string | truncate(19,True,'',0),'%Y-%m-%d %H:%M:%S:%f'))  | timestamp_custom('%Y-%m-%d %H:%M:%S') }}
#

but I you should do the calculation first in UTC and change format last

willow elk
#

I have a value_template: "{{ state_attr('sensor.utomhus_framsida_temperature', 'lastUpdated') | timestamp_local }}"that works fine
or use something like this:

{{ as_timestamp(strptime(states.binary_sensor.status_smoke_sensor_0.last_updated | string | truncate(19,True,'',0),'%Y-%m-%d %H:%M:%S:%f'))  | timestamp_custom('%Y-%m-%d %H:%M:%S') }}

@waxen rune This is giving me the same Timezone as before.

waxen rune
#

which of them?

silent barnBOT
earnest cosmos
#

Can you share the entire automation? There might be a better way of accomplishing what you're trying to do
@buoyant pine
This automation is controlling irrigation, and made to schedule start at set hours, and in conditions where yr_precipitation is below the threshold.

My aim is to trigger a script for this, where each script is (so far) set for two irrigation sections.

script:
  vanning_terrasse_og_urtehage_tidsstyrt:
    sequence:
      - service: homeassistant.turn_on
        entity_id:
          - switch.vanning_terrasse_og_urtehage

... and some notifications and stuff left out here.

silent barnBOT
earnest cosmos
#
automation:
  - alias: '[Vanning] Daglig tidsstyrt'
    trigger:
      - platform: time
        at: '04:00:00'
      - platform: time
        at: '12:00:00'
      - platform: time
        at: '18:00:00'
    condition:
      - condition: template ## there will be no more that 0,5 mm precipitation for the next hour
        value_template: "{{ states.sensor.yr_precipitation.state < '0.5'}}"
    action:
      - service: script.vanning_lavendel_og_pottedrypp_trapp_tidsstyrt
      - service_template: "{% if states.sensor.planter_urtehage_fukt.state < 25 %} script.vanning_terrasse_og_urtehage_tidsstyrt {% endif %}"
#

Sorry for the mess, guys 🙂 @buoyant pine

silent barnBOT
#

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

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

buoyant pine
#

Please read the rules--over 15 lines and you should use pastebin or similar. Keeps it cleaner for those on mobile @earnest cosmos

#

Anyway, just use a numeric state condition between those two actions checking if that sensor is below 25

earnest cosmos
#

Anyway, just use a numeric state condition between those two actions checking if that sensor is below 25
@buoyant pine Could you explain?

#

There wiill be more than just one sensor to check, and more than one areas to irrigate 🙂

analog remnant
#

Hi guys, how can I work around the new template handling since 0.115 no longer uses entity_id as a template update trigger? I've got this template:
{{ is_state('sensor.netatmo_camera_garage_movement', 'movement') and as_timestamp(now()) - as_timestamp(state_attr('sensor.netatmo_camera_garage_movement', 'time_fired')) <= states('input_number.netatmo_events_cooldown_time') | int }}
Before I had a sensor in the entity_id section that would trigger the update every few seconds, since 0.115 I can't do this anymore. The sensor get's stuck with true whereas before it would update after every few seconds and reevaluate the template.

autumn hearth
#

I believe you just have to add this to the top of your template:

#

{% set foo = states('sensor.date_time') %}

#

Or whatever entity you used to use

#

The template just needs to somehow reference an updating entity

#

Even if it doesn't use it

analog remnant
#

Ok, I gues that would work, if anyone has a less "dirty" approach that would be apprechiated 🙂 Otherwise I'll stick with that. Thanks @autumn hearth

autumn hearth
#

I'm pretty sure that was the recommended approach by the folks who made it. It's in the WTH thread

analog remnant
#

I guess I also could replace the now() with a sensor that represents the current time anyways.

#

👌

inner mesa
#

Yes

analog remnant
#

The entity_id section was perfect for that but this also works 🙂

autumn hearth
#

The entity_id section was also a "dirty" approach though. The goods of the change definitely outweigh the bads in this instance

#

But yeah, definitely feels funky 🙂

analog remnant
#

Yeah for this particular template I'd prefer the old way 😛 But thanks again 🙂

chrome halo
#

Hey there, has anyone used 'eventsensor' before?

#

I'm trying to capture an event output into a sensor but unsure how to set this up with eventsensor ... Here is the output of the event ... https://pastebin.com/utEteVb0

#

Got it working!

blazing burrow
#

anyone using the circadian lighting integration?

#

i'm trying to use some of it's values in an automation via a template, but not working out

#

in particular, this in my yaml: brightness: {{ states('sensor.circadian_values') }}

#

gets turned into:

brightness:
  '[object Object]':

when i save it

#
  action:
  - service: light.turn_on
    data:
      entity_id: light.bedroom
      brightness:
        '[object Object]':
#

apparently hassbot likes formatted code lol

dreamy sinew
#

it likes properly formatted yaml

blazing burrow
#

👍

#

ohhh service data in an automation has to be sent as json??

dreamy sinew
#

shouldn't have to be

#

can be because json is valid yaml

blazing burrow
#

ohh ok

hollow bramble
#

What is the current state of the entity?

blazing burrow
#

from the template editor:

brightness: {{ states('sensor.circadian_values') }}
kelvin: {{ state_attr('sensor.circadian_values', 'colortemp') }}
brightness: 97.32123802347765
kelvin: 5419.63714070433
#

those same lines render the "empty" object above when i save the automation that way

hollow bramble
#

You mean the UI automation editor? Have you tried editing the yaml file directly?

blazing burrow
#

yeah, it i put that in there it crashes the ui editor lol

hollow bramble
#

You should also be wrapping the template in quotes brightness: "{{ states('sensor.circadian_values') }}"

blazing burrow
#

think that did it 👍

latent kiln
#

What am I doing wrong here? sensor: !include_dir_merge_list sensors/

#

finn_activity_goal.yaml

    friendly_name: "Finn Activity Goal"
    icon_template: mdi:trophy-outline
    value_template: '{{ state_attr("device_tracker.whistle_finn", "activity_goal") }}'
    unit_of_measurement: "minutes"
#

Invalid config for [sensor.template]: [friendly_name] is an invalid option for [sensor.template]. Check: sensor.template->friendly_name. (See ?, line ?).

#

from the docs

#

friendly_name string(optional)
Name to use in the frontend.

inner mesa
#

You’re missing ‘sensors:’

latent kiln
#

where? none of my other sensor templates have it

inner mesa
#

See the docs and the example

#

And a sensor name

latent kiln
#

the name comes from the file name

inner mesa
#

I don’t do what you’re doing, but it certainly doesn’t follow the example

latent kiln
#

that's because there is no example for !include_dir_merge_list

inner mesa
#

Ok

buoyant pine
#

@latent kiln Rob is saying you're missing sensors: in the third line of the first example on the page he linked above (as well as the sensor name below that line)

#

Well, third line excluding the comment

#
sensor: 
  - platform: template 
    sensors:  <==== this line
      solar_angle:  <==== also this line
latent kiln
#

@buoyant pine yeah that worked, rob was correct as well. weird that my other template sensors don't have those lines and work

buoyant pine
#

What other template sensors?

#

The only part of the config for integrations that's affected by splitting up the config is the integration line (sensor: at the top in this case). The rest of the config stays the same

violet oyster
#

anybody know which github I would post an issue with the template reloader? just /core?

dreamy sinew
#

core

zinc goblet
#

Can anyone help with correct syntax: I want to show brithness of my lamp (data.new_state.attributes.brightness) but i dont know how to write it in this context: [[[ return (states['light.lampa_baksida'].state) ]]]

earnest cosmos
#

When using multiple ´service_template´s in an action: Will the entire action sequence stop if one ´service_template´ evaluate false?

action:
  - service_template: "{% if states.sensor.planter_urtehage_fukt.state < '25' %} script.vanning_terrasse_og_urtehage_tidsstyrt {% endif %}"
  - service_template: "{% if states.sensor.planter_lavendel_fukt.state < '20' %} script.vanning_lavendel_og_pottedrypp_trapp_tidsstyrt {% endif %}"
worldly cypress
inner mesa
violet oyster
#

@worldly cypress you don't need to put 'data:' in the data of the service developer tool. just put entity_id: and message: in line.

#

@zinc goblet need to see what you are trying to do. first off it should be curly braces {} not brackets [].

#

.share the config you are trying to get to work

silent barnBOT
inner mesa
#

That’s from a custom button card or similar and they also cross posted in #frontend-archived (the right place)

violet oyster
#

ah. i don't go over there much ha

earnest cosmos
inner mesa
#

A choose: can do that

inner mesa
#

A different and perhaps better solution is simply to add the condition to the beginning of each script and then just call them normally. The condition can determine whether watering is required for that plant and only continue if it is

#

@earnest cosmos

violet oyster
#

yeah that's definitely better

earnest cosmos
#

A different and perhaps better solution is simply to add the condition to the beginning of each script and then just call them normally. continue if it is
@inner mesa true. Good idea 💡

#

Thanks

lyric snow
#

Hello everyone,
I'd like to write a template to know which light is on of all my lights... Help please?

sly thistle
#

Gents, is there a way of creating a function so I don’t have to write the same code over? For example, to convert Celsius to Fahrenheit the formula is: f = (x * 9 / 5) + 32. How could I create a function and use that in an automation?

brisk temple
daring musk
brisk temple
#

but then how does he get it back to the automation?

#

maybe have the script write it to an input_*

daring musk
#

or fire custom event

brisk temple
#

sounds like more work than just putting in the equation

daring musk
#

yeah

brisk temple
#

can setup a template sensor to convert it, then just reference that

daring musk
#

maybe a template inside input_text.c_to_f

then use it in automation as

data: >-
  {{input_text.c_to_f}}```

i'm not sure if this would work
brisk temple
#

you can set the system unit Developer Tools -> General and in sensors if you set the unit_of_measurement: it will auto convert

sly thistle
#

Something so simple shouldn’t be so complicated to implement :/

arctic sorrel
#

Just switch to using Python through AppDaemon 😉

hallow plover
#

Is it possible to add template sensors through the ui at all?

inner mesa
#

No

untold solar
#

Hey all, is there any easy way to convert a sensor that represents bytes into mb? I essentially want to create a sensor that represents the result of computing: <input sensor> / 1,048,576 From reading the docs i'm assuming that this will involve HomeAssistant's templating language, or possibly filters?

Could it be something as simple as this:

- platform: template
  sensors:
    network_mb_sent:
      value_template: "{{ sensor.unifi_dream_machine_b_sent / 1048576 }}"

Where sensor.unifi_dream_machine_b_sent is a pre-existing entity i want to transform the value of?

#

Or is this correct format:

- platform: template
  sensors:
    network_mb_sent:
      value_template: "{{ state(sensor.unifi_dream_machine_b_sent) | float / 1048576 }}"
inner mesa
#

there ya go

#

sorta

#
- platform: template
  sensors:
    network_mb_sent:
      value_template: "{{ states('sensor.unifi_dream_machine_b_sent') | float / 1048576 }}"
#

test in devtools -> Templates

untold solar
#

Thank you! I would have totally missed the quote marks

#

In the developer tools templates section is get the message "This template listens for all state changed events." with this test:

- platform: template
  sensors:
    network_mb_sent:
      value_template: "{{ state('sensor.unifi_dream_machine_b_sent') | float / 1048576 | float(2)  }}"

But as far as i can tell this should work fine?

inner mesa
#

that's not what I had above

#

there are a few problems there

untold solar
#

oops - states / state

#

My apologies

inner mesa
#
- platform: template
  sensors:
    network_mb_sent:
      value_template: "{{ (states('sensor.unifi_dream_machine_b_sent') | float / 1048576) | round(2)}}"
#

that's probably what you want

untold solar
#

🙂 You're totally right. Thank you! I feel a bit embarrassed that i actually posted that mistake, but super grateful you pointed it out to me 🙂

inner mesa
#

np, it's easy to miss

#

the other main thing I fixed is to round the result of the calculation, rather than just the divisor

untold solar
#

I see that now - (<thing> | float / <int>) | round(2) I've never really used this templating language before. Thanks for the guidance!

hallow plover
#

is it possible to make a template sensor that does not display any icon?

inner mesa
#

template sensors by themselves don't display anything

hallow plover
#

it seems that if i leave out icon_template altogether it gets the eyeball icon

inner mesa
#

again, that's a matter of what's displaying it

#

you'd need to either configure the card not to display an icon, or change the icon, or choose another card that lets you do what you want

#

the basic sensor card doesn't appear to let you not display an icon, but others do (like the custom button card)

hallow plover
#

I'll try that, thanks.

potent dragon
#

n00b question: Have a thermostat which has "humidity" available as an attribute. How do I get this to be able to use it in automations and in Lovelace?

inner mesa
#

depends on how you want to use it

#

what are you trying to do with it?

potent dragon
#

1st I want to display the value in lovelace

#

2nd - I'd like to control a fan to switch on when the humidity is over a certain value

inner mesa
#

you need to decide on a card and the docs will tell you how to display attributes (if they can)

potent dragon
#

ok - I'll have a look at the documentation

#

cheers

inner mesa
spiral flax
#

hello, how can I check in the value_template if the message was a string that's possible to convert to int (I.e. '100') or it's a json object (i.e. {"Time":"1970-01-02T18:54:59","Shutter1":{"Position":100,"Direction":0,"Target":100}})

brisk temple
#

try {{ state_attr('sensor.sensor1', 'Shutter1')['Target'] is string }}

#

hmm probably not an attribute for you

#

{{ states('sensor.sensor1')['Shutter']['Target'] is string }} maybe

spiral flax
#

I've figured it out,

{% if value|int(-1) != -1 %}
  {{ value|int }}
{% elif ('Shutter1' in value_json and 'Position' in value_json.Shutter1.Position) %}
  {{ value_json.Shutter1.Position }}
{% endif %}
elder moon
#

is it possible to create a device_tracker entity from restful data?

#

there's only sensor and binary_sensor in Restful integration, but i was wondering if its possible to template a device_tracker

violet oyster
#

@elder moon there is a workaround to do that. you can make an mqtt device tracker and use the restful data to publish an mqtt topic which would change the state of the device tracker.

#

essentially the same thing as a template device_tracker, just an extra step.

#

no straight up template device_tracker is possible though, at least as of the last time I tried (and discovered the workaround)

elder moon
#

thanks Barbados

#

do you know if there's a ready made solution for a linux service which would fetch rest data and translate it to mqtt

#

?

violet oyster
#

not sure. if you already have the integration set up in HA you could just use an automation though

elder moon
#

ah an automation which sends data to mqtt and then use mqtt device_tracker?

violet oyster
#

correct

elder moon
#

feels awkward but this can work 🙂

violet oyster
#

it is janky but works fine once you have it set up

elder moon
#

too bad i missed WTH month with this

violet oyster
#

lol yeah, template device trackers do seem like a WTH

next bluff
#

Moving my question here:
any python gurus, to help me optimize this block to one-liner, map + filter functions?

{% set nowTime = now() %}
{% set lights_on = expand('group.lights') | selectattr('state', 'eq', 'on') %}
{% set lights_count = 0 %}
{% for light in lights_on if as_timestamp(nowTime) - as_timestamp(light.last_changed) > (10 * 60) -%}
  {% set lights_count = lights_count + 1 %}
{%- endfor %}
{{ lights_count }}```
brisk temple
#

{{ states.light|selectattr('state','equalto','on')|list|length }}

median citrus
#

i cant get to wrap my head around how to template a sensor so it shows the delta of a timestamp to the current time, it would be great if someone could help me out, The sensor holds the finishing time of my dishwasher (2020-09-27T16:35:10.038563+00:00) and i want to have a sensor who shows the remaining running time in minutes

devout plume
#

The professional in me got frustrated with having to put my home assistant base URL in the yaml repeatedly (re: discussion in #frontend-archived ).
From what I've read, concatenating secrets in templates does not work.
I found a bash script I can use to grep the secrets out of the secrets.yaml... but haven't been able to wrap my mind around how to properly call that from a template yet, with a variable of which secret to call.
Does anyone happen to have a working example of such?

#

(of course, if there is a way to more properly call the internal or external URL as configured in home assistant already, rather than storing it in a secret as well, I'm all ears!)

charred dagger
#

A common way to do this is to add the thing you want as an attribute to an entity using customize.

#

So if you have yaml homeassistant: customize: sensor.my_sensor: #or just anything that EXISTS, could be e.g. sun.sun my_secret: !secret my_secret

#

you can then use jinja {{ state_attr('sensor.my_sensor', 'my_secret') + "/rest_or_url_or_whatever" }}

#

Of course it won't be secret anymore, though.

devout plume
#

Only not in the logs I suppose. For sharing config etc. it's still secret. Thanks!

devout plume
#

huh.
This template evaluates OK in the browser's template developer tool.
{{states('input_text.exhabaseurl') + "hassio/dashboard"}}

When I put it in the yaml it fails :(
invalid key: "OrderedDict([('states('input_text.exhabaseurl') + "hassio/dashboard"', None)])"
the alert: https://paste.ubuntu.com/p/sZDn7hKzsQ/

#

(Yes - I figured I could use an input_text rather than tacking it onto a sensor meant for other things)

inner mesa
#

Just put the text after the template

#

huh.
This template evaluates OK in the browser's template developer tool.
{{states('input_text.exhabaseurl') }} "hassio/dashboard"

#

Maybe without the quotes

dreamy sinew
#

Gotta wrap the whole thing in quotes

#

"{{ states... + 'thing' }}"

inner mesa
#

Oh, I see the whole thing now. Yeah

#

Was guessing based on the error

charred dagger
#

Yep. That's yaml biting you again. { indicates the start of a map.

inner mesa
#

If it starts with text and then goes into a template, it works fine

dreamy sinew
#

Yep, best not to rely on the interpretation and just be explicit

devout plume
#

url: "{{states('input_text.exhabaseurl') + 'hassio/dashboard' }}" this is the result which passes ha core check. Great!
Thank you

wispy lodge
inner mesa
#

yes, check the release notes for 0.115

elder moon
#

im trying to do a bunch of Restful sensors, but the Rest API requires a valid Auth Token and this one can be obtained only by another Rest request but its only valid for 8 hours. Is templating such sensors possible in HA?

next bluff
#

{{ states.light|selectattr('state','equalto','on')|list|length }}
@brisk temple This is missing the conditional which I am unable to convert to single line solution.

elder moon
#

i reckon that i would need an input_text sensor which holds the current api token for use in Restful sensors

inner mesa
#

maybe a command_line sensor

dreamy sinew
#

@elder moon might be better off with a custom component in that situation

topaz walrus
#

what am i missing here.. something simple im sure

#
    sensors:
      last_motion:
        friendly_name: 'Last Motion'
        icon_template: 'mdi:motion-sensor'
        value_template: >
          {%- set pirs = [states.binary_sensor.kitchen_motion_sensor, states.binary_sensor.master_bedroom_motion_sensor, states.binary_sensor.master_closet_motion_sensor, states.binary_sensor.living_area_motion_sensor, states.binary_sensor.full_bath_motion_sensor, states.binary_sensor.half_bath_motion_sensor, states.binary_sensor.stairs_motion_sensor, states.binary_sensor.kids_room_motion_sensor, states.binary_sensor.play_room_motion_sensor] %}
          {% for pir in pirs %}
            {% if as_timestamp(pir.last_changed) == as_timestamp(pirs | map(attribute='last_changed') | max) %}
              {{ pir.name }}
            {% endif %}
          {% endfor %}```
#

template message just says "This template listens for all state changed events."

#

hmm maybe the last update changed they way my templates work because another one of my template is broke. 😕

#
    sensors:
      main_level_avg_temp:
          friendly_name: "Average House Temp"
          device_class: 'temperature'
          unit_of_measurement: '°F'
          value_template: >-
            {% set sensors = [
                states('sensor.living_area_temperature')|float,
                states('sensor.master_bedroom_temperature')|float,
                states('sensor.kitchen_temperature')|float,
                states('sensor.kids_room_temperature')|float                
              ]
            %}
            {{(sensors|sum / sensors|reject("eq", 0.0)|list|length)|round(1)}}```
violet oyster
#

@topaz walrus what error are you getting in your logs? or what is it not doing that it should be?

#

and also are any of those sensor entities in the template template sensors themselves? and if so, did you use the 'reload template entities' button?

topaz walrus
#

Nothing in my logs, just checking them in the “template checker” thing under developer tools.

#

But looking at the change log there is some type of breaking change to templates. I honestly just don’t understand what changed.

violet oyster
#

nothing that would affect templates that were already working. the changes to templates were mostly that you don't need to put 'data_template' anymore to use templates in scripts and automations

#

template sensors should be fine. thats why I asked if any of the sensors referenced in the template you shared are template sensors. there is an open issue about that as it relates to the new template reloader

#

but if there's nothing in your logs then it probably isn't that.

dusky bane
#

Hi all! i need help to modify a template sensor :


      medium_temperature:
        friendly_name: 'medium of temperatures'
        value_template: >-
           {{ ((float(states.sensor.thermohygro5_temperature.state) + float(states.sensor.thermohygro4_temperature_2.state) + float(states.sensor.thermohygro3_temperature.state)) / 3) | round(1) }}
        unit_of_measurement: '°C'

Here is the problem :
when one sensor.thermohygro*_temperature is not working the medium don't give any result
Here is my question :
how can i modify the template to avoid using a "not working sensor" in the calculation

marble needle
#

is there a good way to get the timestamp of the last time an entity's state changed?

deft timber
#

@marble needle yes there is: states.domain.entity_id.attributes.last_changed (ex: states.sensor.my_sensor.attributes.last_changed)

marble needle
#

ah cool, it's used in examples but not explicitly described

proud cradle
#

Has there been some recent changes to templates? I've got a few template sensors that show as "unknown" but in dev tools they render correctly?

deft timber
#

@marble needle Correctionstates.domain.entity_id.last_changed without the 'attributes'

dusky bane
#

thank you @deft timber i didnt know about that i'll try it

topaz walrus
#

@violet oyster I’m not sure then. They were working and now they stopped. 😕 like I said if I throw them in the template checker it just says "This template listens for all state changed events."

dusky bane
#

@deft timber it's working, very direct solution, perfect thank you very much

deft timber
#

👍

topaz walrus
#

Anyone know whats wrong here?

#
    sensors:
      last_motion:
        friendly_name: 'Last Motion'
        icon_template: 'mdi:motion-sensor'
        value_template: >
          {%- set pirs = [states.binary_sensor.kitchen_motion_sensor, states.binary_sensor.master_bedroom_motion_sensor, states.binary_sensor.master_closet_motion_sensor, states.binary_sensor.living_area_motion_sensor, states.binary_sensor.full_bath_motion_sensor, states.binary_sensor.half_bath_motion_sensor, states.binary_sensor.stairs_motion_sensor, states.binary_sensor.kids_room_motion_sensor, states.binary_sensor.play_room_motion_sensor] %}
          {% for pir in pirs %}
            {% if as_timestamp(pir.last_changed) == as_timestamp(pirs | map(attribute='last_changed') | max) %}
              {{ pir.name }}
            {% endif %}
          {% endfor %}
small wolf
#

I'm trying to create a sensor for a device's bandwidth on my network using the difference in total data transferred divided by a certain amount of time. Anyone have a sample of something i can look at that is similar to that?

#

EXAMPLE: at 21:00:00 the device had transmitted 100MB, at 21:00:30, the device had transmitted 200MB. So the device transmitted 100MB/30seconds or 3.33MB/s (average)

#

I think I could create the arithmetic part of the sensor, but I don't know how to grab values at t=0s and t=30s and use them in the template.

wide rivet
#

Hi I am working on a interactive floorplan using Picture Elements card.
About state_image, it was like from those example I can recall an entity and then base on its condition, let's say "on"/"off", to show a image overlay.
Is it possible if I can have two conditions?
Let's say,
if light A is on, light B is off, show picture A
else if light A is off, light B is on, show picture B
else if light A is on, light B is on, show picture C
else show transparent.png

is it possible?

#

Thanks

inner mesa
wide rivet
#

I copy&paste overthere then