#templates-archived

1 messages · Page 161 of 1

ebon yoke
#

2022-05-19 14:54:12 ERROR (MainThread) [homeassistant.config] Invalid config for [template]: invalid template (TemplateSyntaxError: unexpected ')') for dictionary value @ data['sensor'][0]['state']. Got '{{ trigger.to_state.state | as_datetime - trigger.from_state.state | as_datetime).seconds }}'. (See /config/configuration.yaml, line 133).

marble jackal
#

And, it will not work anymore after a reboot or template sensor reload prior to 2022.5, as trigger based templates do not restore states

ebon yoke
#

there's a missing ( here some where

marble jackal
#

added

#

should be at the start

ebon yoke
#

i guess i need it to run once first?

mighty ledge
#

na, you need to guard against 'uknown' or 'unavailable'

ebon yoke
#

sensor.to_on doesn't exist

mighty ledge
#

unfortunately that was added in 2022.4

ebon yoke
#

hahah

#

ok.. what do i do? i can't believe this is not doable in pre-2022 h-a

#

i have mqtt

#

so i can publish to a node

mighty ledge
#

you could probably do it with the SQL sensor, but you'd have to write the search

ebon yoke
#

sheesh 🙂

#

again: how? 🙂

#

i don't have time for this.. i should be pumping water in the basement 😄

#

SELECT * FROM (SELECT * FROM states WHERE entity_id = 'sensor.temperature_in' ORDER BY state_id DESC LIMIT 2) two_entity ORDER BY state_id ASC LIMIT 1;

marble jackal
#

Which version are you running?

ebon yoke
#

something like this, i guess

#

2022.3.5

mighty ledge
#

that would be a start

ebon yoke
#

yeah, i found the same

#

ok, i have the query

#

how do i combine that with a trigger and then a sensor?

mighty ledge
#

what's the output

ebon yoke
#

select * from (select * from states where entity_id = "switch.pumpe_teknisk_rom" and state = "on" order by state_id desc limit 2) two_entity order by state_id asc limit 1;

mighty ledge
#

so, that's going to output on?

#

not very helpful, you need the date

#

& time

ebon yoke
#

yeah, it's in the output of the query

#
> select * from (select * from states where entity_id = "switch.pumpe_teknisk_rom" and state = "on" order by state_id desc limit 2) two_entity order by state_id asc limit 1;
+-----------+--------+--------------------------+-------+---------------------------------------+-----------+----------------------------+----------------------------+----------------------------+------------+-----------------+--------------+
| state_id  | domain | entity_id                | state | attributes                            | event_id  | last_changed               | last_updated               | created                    | context_id | context_user_id | old_state_id |
+-----------+--------+--------------------------+-------+---------------------------------------+-----------+----------------------------+----------------------------+----------------------------+------------+-----------------+--------------+
| 146908225 | switch | switch.pumpe_teknisk_rom | on    | {"friendly_name":"Pumpe teknisk rom"} | 148139786 | 2022-05-19 12:51:48.497793 | 2022-05-19 12:51:48.497793 | 2022-05-19 12:51:48.497793 | NULL       | NULL            |    146906213 |
+-----------+--------+--------------------------+-------+---------------------------------------+-----------+----------------------------+----------------------------+----------------------------+------------+-----------------+--------------+
#

ough.. maybe not paste this here

mighty ledge
#

you'd need to split the response on the | and extract the correct time, not sure which oen that is. They all the same

#

then you need to convert that to a datetime

ebon yoke
#

doesn't the sql platform separate the fields into attributes?

#

it's not handled as a string, no?

mighty ledge
#

and you have to figure out which TZ that's in

#

I'd assume it's UTC

ebon yoke
#

that's UTC

#

yeah

#

is the mqtt road easier to take?

mighty ledge
#

they both are a pain

ebon yoke
#

but i really can't understand why this is so hard to accomplish?

mighty ledge
#

the MQTT route you have to make an MQTT configuration in yaml

ebon yoke
#

well, i already have mqtt configured

mighty ledge
#

then you'd make an automation that publishes a timestamp to the topic that the MQTT configuration is pointing to

#

you'd probably need 2 mqtt sensors

#

1 for the last on

#

1 for the duration

#
- alias: Update pump sensors
  trigger:
  - platform: state
    entity_id: xyz.abc
    to: 'on'
  action:
  # UPDATE DURATION
  - service: mqtt.publish
    data:
      topic: ....
      payload: "{{ (now() - states('sensor.last_update')).seconds }}"
  # UPDATE LAST UPDATE TOPIC
  - service: mqtt.publish
    data:
      topic: ....
      payload: "{{ now() }}"
#

so you can just make 2 state topics that holds a datetime and one that holds a float

#

then configure them as sensors

#
sensor:
- platform: mqtt
  state_topic: ...
  value_template: "{{ value }}"
#

etc

#

i'm sure I'm missing something there, but you get the idea

#

the value template for the last_updated should be "{{ value | as_datetime | as_local }}"

tepid onyx
#

Out of curiosity what are you running HA on?

ebon yoke
tepid onyx
#

nuh I mean what infra like esxi, KVM or bare metal or ...

ebon yoke
#

Bare metal

ebon yoke
#

i can't reload just sensors individually? i have to restart h-a for that?

marble jackal
#

Depends on the sensor, template sensors can be reloaded from developer tools > yaml

#

Oh no, prior 2022.5 it is configuration > server tools

ebon yoke
#

Mqtt sensor

marble jackal
#

Could be, but if it is the first one you add, you always need a reboot. After that, just check if it shows up in server tools

floral shuttle
#

just discovered I can not use the get() in this mapper? state-badge { {% set speed = states(config.entity)|int(default=0) %} {% set mapper = {0:'green',1:'darkgreen',3:'orange',33:'orangered',66:'maroon'} %} color: {{ mapper[speed] if speed in mapper else 'red'}}; hoped to do color: {{ mapper.get(speed,'red')}}; but that does not kick in

#

(this is in a card_mod, so strictly speaking frontend, but its about the jinja template....)

#

or:```
animation:
{% if speed != 0 %}
{% set mapper = {1:'4',3:'3',33:'2',66:'1'} %}
{% set rotation = mapper.get(speed,'0.3') %}
{{'rotation ' + rotation +'s linear infinite'}}
{% else %} null
{% endif %}

mighty ledge
#

fyi, thats a dictionary

#

I regret that first post I made with mapper all those years ago because people keep calling it that

#

that's just the variable name I decided to use that day 😐

floral shuttle
#

yeah sorry, didnt mean to use the reserved word.... just the variable name, Ill change that. really odd though, because now that I test it. by changing the state in dev tools state, it does work.... huh

mighty ledge
#

yeah, maybe a typo?

#

anyways, I find it best to name the dictionary what it contains

#

like that would be colors, then colors.get(speed, 'red') makes way more sense when reading it

floral shuttle
#

could be a typo, and it wasnt working for over months... might have been winter so the fan didnt have to spin on the Rpi4 😉 and yes, ive changed them to color and fan

pastel moon
#

Hi. Isn't this the correct way to create a variable containing a list? variable_name: "{{ [var_1, var_2, var_3] }}"

ebon yoke
#

@mighty ledge i'm getting Error rendering data template: TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str'

#

@mighty ledge even though i have the value_template "{{ value | as_datetime | as_local }}" for the value from mqtt

mighty ledge
#

When you subtract them in the template sensor, you need to convert the state to a datetime

#

It’s in my example

ebon yoke
#

oh? where?

#

i see that teh value_template mentions | as_datetime | as_local

mighty ledge
#

Ah I forgot it

#

Just add the | as_datetime after the states()

#

You may need to add as_local too

ebon yoke
#

like so: '{{ (now() - states("sensor.pump_last_update") | as_datetime | as_local).seconds }}' ?

#

yeah, that seems like it stuck

#

let's try restarting h-a and see

#

Update pump sensors: Error executing script. Error for call_service at pos 1: Error rendering data template: AttributeError: 'NoneType' object has no attribute 'tzinfo'

#

argh

#

catch-22 here

#

after restart that is empty

#

and then it won't update

#

no way mqtt can poll for the last value?

mighty ledge
#

You have to retain the value on startup

#

It’s part of the sensor configuration

#

For mqtt

young jacinth
#

hey jedis,

{% set x = ['a','b','c'] %}
{% set y = ['b','c','d'] %}

is it possible to print out the intersection of two lists?
so the output would be

['b','c']
mighty ledge
#

{{ x | select('in', y) | list }}

young jacinth
#

thanks alot

stuck remnant
#

hi guys Im tryin to set a template to use a timer entity to reflect how much time is left until the next Android alarm

#

anyone know how to?

stuck remnant
#

the purpose is to have a flipper card show up on my device at the time when I set the alarm, counting down to when the alarm is set to go off

mighty ledge
#

any timer in the UI won't count down like that

inner mesa
marble jackal
#

What's not to love?

stuck remnant
# mighty ledge any timer in the UI won't count down like that

but isn't there a way to have a template tell the automation to subtract 'now' from the set time of the alarm and give the value one time to the timer entity? Or maybe there's a different way to achieve this?
My purpose is to set an alarm via voice while cooking and then to have HA automate the process of pulling up the remaining time til the alarm is set. Like: 'next alarm time' (minus) 'now' (equals) 'timer value'

native sparrow
#

Alexa does that anyway. (assume google does too). Why HA?

marble jackal
stuck remnant
#

oh, ok, I already set the flipper card to reflect the timer but need the template for converting the value formats and to run the operation

stuck remnant
marble jackal
stuck remnant
#

cheers!

native sparrow
stuck remnant
#

oh okay, yes google does it too, but the thing is to do all this on the fly. I have an android in each room and it's neat to be cooking and just say an alarm then have the countdown pull up on every screen to know how long left. Not have to ask it every time

merry delta
#

I created a template sensor for my energy dash in watts that either returns + value or 0 and it works but the sensor i created the changes it to kWh using the template sensor as the source is still showing - value, how can this be?

marble jackal
#

.share your sensor configuration

silent barnBOT
#

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

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

merry delta
#

template:

  • sensor:
    • name: "Solar return to Grid Power (Dashboard)"
      unit_of_measurement: "W"
      state: >-
      {% if states('sensor.meter_min') | float < 0 %}
      {{ 1 - states('sensor.meter_min') | float }}
      {% else -%} 0 {% endif %}
      state_class: measurement
      device_class: power
mighty ledge
#

That equation makes no sense, but it shoud work fine assuming that your spaces are correct

#

basically, whenever it's negative you're output will be the absolute value of the minimum + 1

#

which just doesn't make sense

#

just use absolute value and don't add the one

merry delta
#

The kWh conversion comes out neg - platform: integration
source: sensor.solar_return_to_grid_power_dashboard # <-- the actual name of your sensor
name: return_to_grid_kwh
unit_prefix: k
unit_time: h
round: 2

mighty ledge
#

the integration integration works off your history

#

so if there's still negatives in your history from before you made the template sensor postive, they will still be in the KW calculation

#

clear your history or wait for those values to purge

merry delta
#

Figured but shouldnt it update when the underlying sensor does?

mighty ledge
#

it does, but the integration sensor uses a history to determine the area under the curve

#

so, if your last 2 values in the database are above zero, you should be good

#

if it continues to be negatvie, then you're most likely using the wrong entity_id for the integration sensor

#

you can verify the entity_id through the dev tools -> states page

#

you can also verify that your template sensor is positive there as well. It should be based on your equation

merry delta
#

I also used helper to create a kWh and definitely chise correct sensor

mighty ledge
#

as long as you restarted or reloaded after adding your template sensor too

#

Right, I understand you think that, but the integration integration is simple math. It's only going to calc negative if your source sensor is negative

#

9 times out of 10 in these situations, you're doing something wrong.

#

so it's good to check everything

merry delta
mighty ledge
#

that still doesn't verify anything I've said

#

that's just showing what you've said from the beginning

merry delta
#

Then i dont understand

mighty ledge
#

what's your source for the integration sensor?

#

that's the source.

#

hint: It's your template

merry delta
#

Are you talking about the entity_id or sensor im usung for the the template source?

mighty ledge
#

you have 3 sensors in your setup

#

sensor.meter_min, sensor.solar_return_to_grid_power_dashboard, and sensor.excess_solar_kwh

#

what are the values and history of all 3

merry delta
#

Meter has neg in history

mighty ledge
#

that shouldn't translate to your template sensor though

#

what does your template sensor look like?

#

unless your template sensor has data from when you were playing around and had negatives

merry delta
#

Yes so i just have to wait which is fine just makes me weary of future data being timely or stuck so to speak. A newly created excess_solar gives me unknown

mighty ledge
merry delta
#

Ok and are you saying just delete this whole line {{ 1 - states('sensor.meter_min') | float }}

mighty ledge
#

{{ states('sensor.meter_min') | float | abs }}

merry delta
#

Ty much. So replace above line with yours?

marble jackal
#

replace {{ 1 - states('sensor.meter_min') | float }} with {{ states('sensor.meter_min') | float | abs }}

#

Your version was giving a wrong result as well, as it would end up one kWh too high, if you would have replaced 1 with 0 at leas the result would have been correct 🙂
But anyway, the version using | abs is easier 🙂

thorny snow
#

Question regarding the Statistics sensor. When did it stop surviving reboot? My state_characteristic: change is reset everytime I restart the server.

marble jackal
pine wigeon
#

Hello everybody!

I want to create an automation that is launched on update of the desired temperature of my HVAC, wait until the temp sensor reach that temperature and power off the HVAC

The only blocking point is the waiting template in the automation. Is it possible to use is_state?
Like : wait_template: '{{ is_state(' 'climate.mqtthvac.temperature' ', ' '<= climate.mqtthvac.current_temperature' ') }}'

mighty ledge
pine wigeon
#

Nice, thanks!

scarlet sapphire
#

Hello, I am trying to historize the sun attributes. Can someone please help what's wrong with this syntax?

- platform: template
    sensors:
      sunrise:
      sun_elevation:
        value_template: '{% if states.sun.sun %}{{ ((states.sun.sun.attributes.elevation)) | float }}{% endif %}'
      sun_azimuth:
        value_template: '{% if states.sun.sun %}{{ ((states.sun.sun.attributes.azimuth)) | float }}{% endif %}'
marble jackal
#

Not sure why you are wrapping this in an if it might have something to do which the fact that you are using a way to get the attribute which is advised against

mighty ledge
#

spacing is wrong

marble jackal
#

And sunrise: is empty

mighty ledge
#

or ya, it's emtpy

scarlet sapphire
#

oh yeah, indeed it is empty

marble jackal
#

and these attributes are already a float, but if they were not, casting them to float use useless, as a the state of the sensor will be a string anyway

scarlet sapphire
#

ok so this example is crap then

marble jackal
#

Well, in the time since that forum post a lot has changed, but the post after your example already gave the right way to get the attribute

#

but there is also a new template format now

scarlet sapphire
#

you mean with sth like this?

- platform: template
    sensors:
      sunrise:
        state_attr(‘sun.sun’, ‘sunrise’)
      sun_elevation:
        state_attr(‘sun.sun’, ‘elevation’)
      sun_azimuth:
        state_attr(‘sun.sun’, ‘azimuth’)
marble jackal
#

Why do you want to create these sensors anyway? To put them in a history chart?

scarlet sapphire
#

yes, I want to have historic values

#

so I can determine values to control my shutters

marble jackal
#

You probably don't need separate sensors for that

#

You can use state triggers with an attribute for example

scarlet sapphire
marble jackal
#
trigger:
  - platform: numeric_state
    entitiy_id: sun.sun
    attribute: elevation
    above: 4

This will trigger when the elevation is above 4, no need for a separate sensor

#

That would have been required in 2015, at the time of that topic 🙂

scarlet sapphire
#

ok, I get that, but I am not sure yet what azimuth and elevation triggers I need

#

so I wanted to historize those values and take a look at them over the day to get the trigger values I need best

#

since I have windows in different angles I can't do it all "live"

marble jackal
#

Okay, well you can of course create these sensors if you want

scarlet sapphire
marble jackal
#
- platform: template
  sensors:
    sunrise:
      value_template: "{{ state_attr('sun.sun', 'sunrise') }}"
    sun_elevation:
      value_template: "{{ state_attr('sun.sun', 'elevation') }}"
    sun_azimuth:
      value_template: "{{ state_attr('sun.sun', 'azimuth') }}"
scarlet sapphire
#

thank you very much, this is indeed much easier

#

trying it now

#

works great, thanks so much

#

does it make sense to post that to the forums post above or is it adviced against that due to the age of the post?

marble jackal
#

I wouldn't post corrections/suggestions on very old posts if there hasn't been a recent post, no reason to bump it to the top again

scarlet sapphire
#

ok, thanks

scarlet sapphire
#

I have one more, finding these in my log, everything seems to be working with the template covers, not sure where "none" comes from though:
[homeassistant.helpers.template] Template variable error: 'None' has no attribute 'sumstate' when rendering '{{ state_attr('sensor.blinds_endpoint', 'item13').sumstate.value.split(';')[1] |float }}'
2022-05-20 16:11:30 ERROR (MainThread) [homeassistant.components.template.template_entity] TemplateError('UndefinedError: 'None' has no attribute 'sumstate'') while processing template 'Template("{{ state_attr('sensor.blinds_endpoint', 'item13').sumstate.value.split(';')[1] |float }}")' for attribute '_attr_value' in entity 'number.rollo_ronja_gross'

#

is it just trying some things after restart when the values are not loaded?

mighty ledge
#

Yes

scarlet sapphire
#

great, thank you

surreal kite
#

hi guys, i am in need of rather urgent help as i came back with my wife from holiday and our house is hot as hell - the automation I tried to use apparently did not work. The thing is I don't know where to put the following "- platform: template
sensors:
sun_azimuth: ......." because of the - platform template I thought maybe here is the right place to ask - forgive me if i was wrong

marble jackal
#

@surreal kite Isn't this very similar as the question a couple of posts before

elfin valley
#

for an automation, is there a way to modify / create a variable in a condition template area, before I use a service to notify? IE: the binary_sensor is toggling, i want to pull the state and change it from on/off to say open/closed. Is there a way to do an if block in the notify section?

#

I don't want to change the sensor's data/payload directly, as that would ruin some of my other integrations (as they look for on/off)

#

nm - got it! message: > {% if trigger.to_state.state == 'on' %}

supple forge
#

Hi 🙂 maybe i just need some little start help... i have two problems ... 1.) i've created a template for my energy dashboard (energy -> power grid) .. but sometimes the values jumps to 0 and then back to the old value... what causes that the difference between 0 and the old valued gets added to the total amount:

#

- name: "Netzeinspeisung (Gesamt)" unit_of_measurement: "Wh" state: "{{ states('sensor.photovoltaik_klein_gesamtnetzeinspeisung')|float(0) }}" device_class: energy state_class: total_increasing attributes: last_reset: "2022-05-17T17:35:00+01:00" last_reset_value: "2022-05-17T17:35:00+01:00" availability: > {% if is_state("sensor.photovoltaik_klein_gesamtnetzeinspeisung", "unknown") or is_state("sensor.photovoltaik_klein_gesamtnetzeinspeisung", 0) %} false {% else %} true {%- endif %}

marble jackal
#

Well, last reset is not needed for total_increasing, so remove that

silent barnBOT
inner mesa
#

States are always strings, and you're comparing with an integer. And you can remove the while true/false bit

marble jackal
#

But why is your source sensor becoming 0, is that a template sensor as well?

inner mesa
#

Well, the default is set to zero

supple forge
#

sensor.photovoltaik_klein_gesamtnetzeinspeisung come from modbus

#

(and the other energy-values too)

marble jackal
#
      - name: "PV Tagesertrag"
        unit_of_measurement: "Wh"
        state: "{{ states('sensor.photovoltaik_gross_tagesertrag') | float + states('sensor.photovoltaik_klein_tagesertrag') | float }}"
        device_class: energy
        state_class: total_increasing
        availability: >
          {{  states("sensor.photovoltaik_klein_tagesertrag") | is_number and states("sensor.photovoltaik_klein_tagesertrag") | is_number }}
supple forge
#

🤔 .. i've added the (0) due to the warning in the log-file

inner mesa
#

But you don't actually want zero?

marble jackal
#

You don't need that if you know for sure the input is actually a number

supple forge
marble jackal
#

You should use lifetime sensors for the energy dashboard

inner mesa
#

Right, but you don't rely on the default for that

marble jackal
supple forge
marble jackal
#

Okay, so both reset to 0 at midnight

supple forge
#

no.. the source-sensors keep the values as they where .. but home-assistant reset's it (visually?), when it's added to the energy-dashboard ... but what about the data from the previews day .. the amout of yesterday gets displayed at 00:00 - 01:00 (so the day starts with 150 kWh)

marble jackal
#

Oh, do they are lifetime sensors

marble jackal
supple forge
#

as i understand, the difference between the two values gets added to the total .. today, two times the values dropped from ~5200 to 0 and up again... and now i have a grid-feed (for today) of over 10000 kWh (would be nice if i got paid for this 🤣 )

#

the reality is 67kWh

marble jackal
#

If a total_increasing sensor gets a lower state than the previous, a reset is assumed, so indeed, when it becomes 0 and then gets the correct value again, you'll get it doubled

#

So that is also why Rob stated that you might not want to default your floats to 0

inner mesa
#

You shouldn't need any default if you configure your availability template properly

supple forge
#

ok.. i'll fix my templates and look, if it also fixes my day-start-problem 🙂 thank you all

mossy osprey
#

I am having a hard time returning the current outside temp using a value template as the value templates only seem to be able to return strings.

#

And sorry, I know this is most likely a very simple answer.

native sparrow
#

Are you sure it's a string? Put it in the template editor in developer tool and it will tell you the type

mossy osprey
#

Welp, it was a mix of two mistakes on my end. It does return as a number. The error was on frontend with a typo on my behalf as mini-graph-card reported the output was a string, and given the value_template is encased in "", I figured that was the cause of returning a string.

#

Thanks 🙂

burnt lion
#

Hi, can u guys help me with 1 more thing? This is not working, i cant get the attribute game inside this sensor on my variable:

#

{% set steam_check = states.[sensor.steam_765611980387894].game %}

inner mesa
#

That's broken syntax

burnt lion
#

How can i fix this?

inner mesa
#

The States section

burnt lion
#

Oh

#

state_attr so

inner mesa
#

Kinda curious where you got that

burnt lion
#

My mind is bugging between template sensors and those scripts

#

Thanks again

burnt lion
marble jackal
rapid ivy
#

Hi Everyone, hope you're well.

Hoping someone can help me out with what is probably a fairly simple issue. I have spent hours on this trying multiple methods but I'm just not winning.

In a nutshell, all I am trying to accomplish is to create a binary sensor that returns true/on if the day is e.g Saturday and a defined input boolean named Saturday is on. This part I have gotten to work in a few different ways. Most noteably:

  • binary_sensor:
    • name: zone1dayofweek
      state: >
      {{(now().strftime("%a") == "Sat") and (states.input_boolean.zone1_saturday.state=="on")}}

The above is in my templates.yaml file.

The problem that I am trying to solve is: How can I expand this out to include all other days of the week?

rose scroll
marble jackal
#

You could also create a sensor that displays the name of the current day.
What is your goal with these sensors?

silent barnBOT
#

The XY problem is asking about your attempted solution rather than your actual problem.

This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.

The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.

rapid ivy
# rose scroll Does the above template evaluate properly? Not sure what you mean by expanding t...

100%, sorry this is all pretty new to me.

So to clarify, what I am trying to do is create a binary sensor that will return true if today's day as well as a specific input boolean are on/true

With reference to my above mentioned code, in my mind what I was looking to achieve is something like this:

  • binary_sensor:
    • name: zone1dayofweek
      state: >
      {{(now().strftime("%a") == "Sat") and (states.input_boolean.zone1_saturday.state=="on")}}
      or
      {{(now().strftime("%a") == "Sun") and (states.input_boolean.zone1_sunday.state=="on")}}
#

@rose scroll without the "or" section the template does evaluate properly. In the above example, adding the "or" is what I was trying to say about expanding this out.

mighty ledge
#

you could use string concatenation with now()'s time to select the input_boolean

marble jackal
#
- binary_sensor:
    - name: zone1dayofweek
      state: >
        {{ (now().isoweekday() == 6 and is_state('input_boolean.zone1_saturday', 'on'))
        or
        (now().isoweekday() == 7 and is_state('input_boolean.zone1_sunday, 'on')) }}
mighty ledge
#

@marble jackal you can get the word saturday from strftime

marble jackal
#
{{ is_state('input_boolean.zone1_' ~ now().strftime('%A')|lower, 'on') }}

Guess that is what @petro meant

mighty ledge
#

yes

#

basically a 1 shot template forget it and set it

#

just need to name your input booleans by day

#

why write all the 'or's out when you and just have the template check the correct boolean right off the bat

#

So, I'm on my fathers mac, let me tell you. I don't like a 1 button mouse pad... I can't reply to people in discord. It doesn't accept my rmb clicks on the reply

marble jackal
#

Hehe

rapid ivy
#

Thanks guys! Let me play around with this!

#

@mighty ledge for the mac, if you tap with two fingers does that help at all?

mighty ledge
rapid ivy
#

Thanks again @mighty ledge and @marble jackal Works perfectly

willow rapids
#
              Recycling is this week
            {% else %}
            Recycling is not this week.
            {% endif %}  ```
#

I want that to be a little smarter and know if it is the weekday 2 or not. (Tuesday) based on the weekday sensor.

#

so how do I do a if else, elseif, endif?

#

maybe a helper like this? - binary_sensor: - name: recyclingdayisnow state: > {{(now().strftime("%a") == "Tue") and (states.input_boolean.recylingday.state=="on")}} or {{(now().strftime("%a") != "Tue") and (states.input_boolean.recyclingday.state=="off")}}

marble jackal
#

And use is_state('entity', 'state') instead of what you are using now

willow rapids
#

sensor.recyclingweek is the entity and A is the state {% if is_state('sensor.recyclingweek', 'A' ) %}

#

remove the if? is that what you are saying?

marble jackal
#

No, I meant in your second template

willow rapids
#

oh ok thanks

inner mesa
floral shuttle
#

hmm, why does this no longer work? ```
{% set group_list = states.light
|selectattr('attributes.is_hue_group','eq',true)|map(attribute='entity_id')|list %}

#

have been using this as a base template for a larger markdown template for a ling er time, and now shows nothing because of that error..?

inner mesa
#

Because some light entities don't have it

#

Didn't you first bring this up?

floral shuttle
#

ofc, thats whay this template should do the selection.... and it has done so

inner mesa
#

No

floral shuttle
#

no? what do you mean?

inner mesa
#

I mean you're not filtering on whether or not the entity has the attribute

floral shuttle
inner mesa
floral shuttle
#

corrct! ``` {% set group_list = states.light
|selectattr('attributes.is_hue_group','defined')|map(attribute='entity_id')|list %}

#

thanks!

#

your memory of my posts is better than mine 😉

marble jackal
#

It was logging a warning for a long period already, since 2022.5 it's actually an error making the template unable to render

inner mesa
#

I don't remember there being a warning. Is it related to the change to defaults?

floral shuttle
#

Mm, there have been no warnings in the logs at all, homeassistant.log that is

spiral imp
#

What filter can i use to remove the first 5 characters of a string?

inner mesa
#

not a filter, just [5:]

#

{{ "0123456789"[5:] }} -> 56789

spiral imp
#

perfect, thanks

marble jackal
inner mesa
#

Ok, so this was on purpose then

#

I don't recall it being called out as a breaking change

floral shuttle
#

Im not even sure what ‘it’ means when you’re talking about it… imho, there should have been some explanation why the selectattr suddenly would have stopped working, and we now need to use defined.

marble jackal
#

it is performing selections on non existent attributes

floral shuttle
#

In hindsight it all seems very logical, but when transitioning from perfectly fine working templates it requires some extra info

marble jackal
#

I agree on that, but I don't write the release notes 😅

#

According to Frenck it was announced as a breaking change a long time ago, but he didn't specify when. And then the conversation got sideways

#

So that's all I know

lyric socket
#

Is it possible to put !secret pirateweather_api in place of the actual api key in this sensor?

sensor:
  - platform: rest
    resource_template: 'https://dev.pirateweather.net/forecast/<apikey>/{{states.person.<NAME>.attributes.latitude}},{{states.person.<NAME>.attributes.longitude}}'
    json_attributes:
      - currently
    name: pirateweather_api
    value_template: 'OK'
inner mesa
#

Not unless you put the whole resource in the secret

marble jackal
#

You can put the api key in a input_text

#

And you could even use the secret as initial value if you create it in YAML

lyric socket
inner mesa
#

Yes

lyric socket
#

both are tempting options....
I dont see one being better than the other, unless i am missing something.

#

The all in one secret would be better. Having the input text would allow you to see it in entities in dev tools i would think.

#

Yup, just confirmed it.

hearty sail
#

If I want to get the value of a helper, is this the way? '{{ states("input_text.some_id") }}'

inner mesa
#

Yes. You can test in devtools -> Templates

north ravine
#

I'd like to make a binary sensor template trigger from an event start to turn it on and a separate event for end to turn it off. Can you have two templates updating the same sensor?

inner mesa
#

You can have two triggers and a template based on the one that fired

north ravine
#

Thanks, will give that a try. Is there also a notion of a condition in a template? i don't see it

#

I'd basically like to filter some of the events and ignore them with respect to changing the binary sensor state.

#

To be explicit, i'm using calendar triggers which have an event start & event end, then have a payload with the title, description, etc

inner mesa
#

You can return whatever you want in the state template, including the current state if you want

#

So if you don't like the trigger data, just return the current state

#

Or you can use an availability template, but that will cause it to be 'unavailable'

#

I do think that a condition that potentially leaves the state unchanged would be a most excellent addition

north ravine
#

Thanks! That is very helpful

#

Now time to up my template-fu

tough lily
#

I'm trying to get a list of devices with a battery level under 80%, but this gives me everything below 80, but also 100.0: {% for state in states.sensor|selectattr('attributes.device_class', 'eq', 'battery')|selectattr('state', '<', '80.0') %}

inner mesa
#

You won't be able to do it with a filter because it requires a cast to float to do a proper comparison

tough lily
#

oh, it's just doing a string comparison?

inner mesa
#

I would just get rid of the last bit and use a separate if statement that does the conversion and comparison

#

Yes

tough lily
#

Tricky part is, I'm using it in a Markdown Card where a previous if statement checks a list count see whether it should display a header or not:

{% if states.sensor|selectattr('attributes.device_class', 'eq', 'battery')|selectattr('state', 'ne', '100.0')|selectattr('state', '<', '60')|list|count>0 %}
  ### Battery
{% endif %}
#

I piped it through two selectattr()s as kludge for now that seems to work

pastel moon
#

Hi, trying to get this script https://paste.debian.net/hidden/a1c670a7/ working, but it fails to match from the variable trace , which should be formatted as a list. Can it be written more efficiently, or what can I do to make it work? Thanks

marble jackal
orchid oxide
#

frontend template, im getting the following error for the following like:

missed comma between flow collection entries (7:72)```
``` content: {{state_attr('person.jack5mikemotown', 'friendly_name')}}
#

dont see what the error is about, here

#

card is mushroom chip card

inner mesa
#

Surround it in quotes

#

Rule #1

orchid oxide
#

that was the first thing i tried, idk what i did wrong. works now, thanks

ionic osprey
#

quick question.. Is it possible to search for a value in a input_text, lets say for the latest 1h?
I want to know if a input_text had a value equal to x for the latest 1h ...

marble jackal
marble jackal
fallow ruin
#

morning all,

how to give these 2 templates a default value i can't get it to work

{{ state_attr('calendar.ajax_seizoen_2021_2022', 'message')}}
{{ as_timestamp(state_attr('calendar.ajax_seizoen_2021_2022', 'start_time')) | timestamp_custom('%d-%m-%Y') }}
marble jackal
fallow ruin
#

the first one is working, but the second gives a error

ValueError: Template error: as_timestamp got invalid input 'None' when rendering template '{{ as_timestamp(state_attr('calendar.ajax_seizoen_2021_2022', 'start_time')) | timestamp_custom('%d-%m-%Y', default='Geen wedstrijd') }}' but no default was specified
pastel moon
marble jackal
#

Why not split it in 4 separate variables?

#

Makes it easier to refer to the one you need

pastel moon
#

That is another way of doing it, sure. My aim was to use the 'trace' as a collection of sorts of everything needed. this varies with what script generates it

#

meaning, it's content is not always the same. Would be a lot of variables to keep track of

fallow ruin
woeful night
#

Hello Guys, i want to controll my heater with an calendar. I connected the calendar and already managed to rerieve the start and end time from it. I guess my only option is to create an binary_sensor Template wich turns ON when there is an entry on the calendar and turns off when there is none. And creating an automation on that sensor controling the heater. So far i got this together {% (as_timestamp(strptime(state_attr('calendar.kalender', 'data')[0].start, '%Y-%m-%d %H:%M:%S%z', 0)) - 3600) | timestamp_custom('%Y-%m-%d %H:%M:%S') %} which takes my start Time and sets it on hour before wich should be the time where the heater should start. How can i manage the Sensor turns on and keeps like this until the calendar entry? Is there maybe a simpler solution for this? Thank you

stuck remnant
#

You were right. How would you recommend doing it instead of this?

#

you then asked me what my purpose for this was, and I said it's for having all the heating automations in my house to switch off once a certain outside temp is achieved anually. So far, below 11*C with an offset of 24 hours seemed to work but upon changing it to 36 I can't tell if it's working or not ^^

marble jackal
#

Maybe trigger on every state change though and check if the current state is on

stuck remnant
#

And what about when the datetime is 36h in the past, is that a template too?

marble jackal
#

Both can be done using templates

marble jackal
stuck remnant
#

seeing as it would trigger upon state change of the initial binary sensor, lol

#

wouldn't it be easier to skip the entire binary sensor though? seeing as it's set to trigger on/off when the weather sensor from outside has is below 11degrees

#

in other words, isnt there a template to trigger an input helper to on/off when there has been 36h of below 11 degrees on the meteorologisk default integration?

marble jackal
#

No, you can just use the current binary sensor for that

stuck remnant
#

that does make sense but it shows up as "unknown" if I set it with delay on

#

hmm maybe thats not the way. maybe the delay should be in the template?

#

{{ state_attr('weather.home','temperature') < 11 }}

marble jackal
#

There should be no delay for the binary sensor

#

You are handling the delay using the input_datetime

stuck remnant
#

but if it triggers on state change, it would mean having another binary sensor to determine when this is on/off

marble jackal
#

No

#

Trigger on every state change to set the input datetime.
Use the input_datetime in your automations in combination with a state condition in the binary sensor

stuck remnant
#

oh ok now i get it

#

And what about when the datetime was changed to 'now' 36h in the past, is that a template too?

marble jackal
#

Yes

#

{{ now() - timedelta(hours=36) > as_datetime(states('input_datetime.whale')) }}

stuck remnant
#

thanks a lot dude!

marble jackal
# stuck remnant thanks a lot dude!

You could even combine it with the check on state:

{{ is_state('binary_sensor.petunia', 'on') and now() - timedelta(hours=36) > as_datetime(states('input_datetime.whale')) }}
stuck remnant
#

next lvl

low blaze
#

I know how to use | round (1) function but I do not want to round I just want to drop anything after first decimal. What is the syntax for that? Thx

#

Is round(1, ‘floor’) correct?

marble jackal
stuck remnant
#

trying to do

data:
  datetime: "{{ is_state('binary_sensor.outside_cold', 'on') and now() -
    timedelta(hours=36) > as_datetime(states('input_datetime.cold')) }}"
target:
  entity_id: input_datetime.cold```
#

but it won't let me

#

says invalid datetime specified, value false

inner mesa
#

please format any code properly

stuck remnant
#

and if I take out the first part -- is_state('binary_sensor.outside_cold', 'on') -- it says cant compare offset-naive and offset-aware values

inner mesa
#

that's because that expression evaluates to a boolean

#

you need to add |as_local

stuck remnant
#

oh so i need a boolean entity as a target

stuck remnant
inner mesa
#

what are you doing now?

stuck remnant
inner mesa
#

no

stuck remnant
#

Im trying to devise a way to determine when the outside temperature has been below 11degrees

#

for 36h straight

inner mesa
#

and you're trying to set a datetime to that?

stuck remnant
#

the fes said it would work best like that, Im just trying to make it work

inner mesa
#

I leave you in his capable hands, then 🙂

stuck remnant
#

okay thanks for your help but just curious, where did you mean to add "as_local"

inner mesa
#

to fix this:

-- it says cant compare offset-naive and offset-aware values

stuck remnant
#

I get that but I meant where in the template to add it

inner mesa
#

now() - timedelta(hours=36) > as_datetime(states('input_datetime.cold'))|as_local

ionic osprey
marble jackal
stuck remnant
#

but it doesn't work

marble jackal
stuck remnant
#

invalid datetime, false dictionary value

marble jackal
#

That's not what I meant, what is your current code

stuck remnant
#

sorry

#
data:
  datetime: "{{ now() -
    timedelta(hours=36) > as_datetime(states('input_datetime.cold'))|as_local }}"
target:
  entity_id: input_datetime.cold```
marble jackal
#

No, that's not right. In the input_datetime you simply need to set "{{ now() }}"

stuck remnant
#

ooh

#

that makes sense

#

and the rest is a value template

marble jackal
#

Correct

stuck remnant
#

I liked yours the most because it also took into consideration the binary sensor

marble jackal
#

Where you compare the current time to your input_datetime to see if the last state change of your binary_sensor was over 36 hours ago

stuck remnant
#

makes sense

#

lemme see if I can sort out where to put it in an automation 😄

marble jackal
#

You can add it as a template condition

stuck remnant
#

will try this one :
{{ is_state('binary_sensor.petunia', 'on') and now() - timedelta(hours=36) > as_datetime(states('input_datetime.whale')) }}

marble jackal
#

You need the | as_local

#

Or the similar function:
{{ is_state('binary_sensor.petunia', 'on') and now() - timedelta(hours=36) > as_local(as_datetime(states('input_datetime.whale'))) }}

stuck remnant
#

ok so this is what I understood: please dont laugh 😄
I created a datetime named Now and set it to actualize itself every minute with the 'now' value
I then created a second automation and gave it the 36h trigger as well as the value template condition from above. BUT it doesn't work when I click test, saying it needs a string value and got none
https://pastebin.com/5U5Ey9Qm

marble jackal
#

I assume this was only for testing then? Because the trigger should be your binary sensor changing state

#

And the test button doesn't work for template conditions

#

The trigger to to set the input_datetime should be something like:

- platform: state
  entity_id: binary_sensor.its_a_bit_chilly
stuck remnant
#

ok but this means the trigger will make it check against itself

#

if it changes state now, it will check if it hasn't changed state again in the last 36h

marble jackal
#

No, it's a separate automation just to set this input_datetime

stuck remnant
#

you mean apart from the two in my paste?

marble jackal
#

Okay, for my suggestion to work, you need:

  • an binary_sensor which is on when the temperature is below 11 degrees (eg binary_sensor.cold)
  • an input_datetime which can store both date and time ( eg input_datetime.cold)
  • an automation to set the input_datetime to now() on every state change of the binary_sensor
  • (optionally) a second binary_sensor which uses the value_template above to make it easier to use it in your other automations (eg binary_sensor.cold_for_36_hours)
stuck remnant
#

oh now it all makes sense

marble jackal
#

I did not see the 2nd automation before, but I don't know what you expect of that one

stuck remnant
#

I had it backwards

#

didnt expect anything, was just showing what I did

#

ok so I;ll get to work

#

thank you for putting it plainly so my old brain can see

marble jackal
#

Additional suggestion, use this trigger instead of the one I proposed for the automation to set the input_datetime. It prevents it to set it after a reboot because the binary sensor is loaded

#
- platform: state
  entity_id: binary_sensor.its_a_bit_chilly
  to:
    - "on"
    - "off"
  from:
    - "on"
    - "off"
stuck remnant
#

also the additional binary sensor

#

but then I thought why not be able to also action it manually if36 is too much or not enough so I used an input boolean instead:
https://pastebin.com/Nj5F5J9t

fierce turret
#

Anyone have an idea of how I can get the info from the last instance if a sensor? I have tried this but it fails

{{ state_attr('sensor.calendar', 'data')[-1].start_day }}

inner mesa
#

yeah, that's not it 🙂

#

the easiest way to do it is to create a trigger-based template sensor whose state is trigger.from_state.state

#

there's no built-in way to do what you want

spice jasper
#

nevermind it does not work either: homeassistant.exceptions.HomeAssistantError: Template rendered invalid service: cover.close_cover ['cover.finestra_sala', 'cover.finestra_cucina']

marble jackal
#

The template is fine, but you can't use templates in that field

#

you need to put it in target or data

marble jackal
spice jasper
#

wouldn't it repeat entity_id twice?

#

one from map one statically before the template?

marble jackal
#

Huh, you lost me here, what do you mean with before the template

spice jasper
#
service: cover.open_cover
target:
  entity_id: "{{ expand('cover.finestra_sala') | map(attribute='entity_id') |list }}"
  ^^^^^^^^^^
marble jackal
#

entity_id: is a key, which expects a (list of) entitie(s) as value

#

you provide that list using the template

spice jasper
#

i'm not totally sure how map works in this case, the doc says it's a filter but we're not supplying a KV struct to filter against

marble jackal
#

Just test it in developer tools > templates and see what the result is

#

I did not write the program language, I'm just providing you a way to get the list of entity_ids you need for your service call

#

You can use map to take out one specific attribute out of your expanded state object generator

spice jasper
#

yea i think i was lost on the expand

#

it seems it substitute the '' with an object

#

instead of interpretating it like a string

marble jackal
#

It's because you've put a group in, it expands the group members of that group

spice jasper
#

so when you say cover.something it becomes the cover itself, not a string

#

and then yes it can find the attribute with the map

marble jackal
#

without quotes jinja expects a variable, which you have to define first

spice jasper
#

now the real problem is that it outputs it as an array ["cover.one", "cover.two"] instead of what the service expects (i think) -cover.one\n-cover.two

marble jackal
#
{% set petunia = 'cover.finestra_sala' %}
{% set whale = 'entity_id' %}
{{ epand(petunia) | map(attribute=whale) | list }}
#

No, the service expects a list, and ["cover.one", "cover.two"] is a perfectly fine list

#

YAML is a different way to write json
This:

target:
  entity_id:
    - cover.1
    - cover.2

Is exactly the same as:

target:
  entity_id: [ 'cover1', 'cover.2' ]
spice jasper
#

huh it works in services too?

marble jackal
#

Yes

#

you can use the json notation in your yaml

#

it will work fine

#

also fine

spice jasper
#

yea the stack of different languages makes it confusing i think

marble jackal
#
target: { 'entity_id': [ 'cover1', 'cover.2' ] }

(had backticks instead of quotes)

#

And that also explains why you need to put quotes around you templates if you use a single line notation. Otherwise it things it's a very badly written dictionary

spice jasper
#

but it does not explain why my try with the for loop didn't

#

i would have expected it to output the list in yaml at runtime before the service was called

marble jackal
#

Because you didn't put it under target or data

#

You put it directly under entity_id in the service call where templates are not allowed

spice jasper
#

isn't jninja interpreted before the section is executed?

marble jackal
#

And your template resulted in a list of complete state objects, which is wrong anyway

spice jasper
#

or is the config passed as is and then interpreted at runtime after the yaml expansion?

marble jackal
#
setAllWindowsOpen:
  action:
    service: cover.open_cover
    entity_id:
      {% for cover in expand('cover.slaapkamer_groep') %}
      -{{ cover }}
      {% endfor %}
#

result:

setAllWindowsOpen:
  action:
    service: cover.open_cover
    entity_id:
      
      -<template TemplateState(<state cover.slaapkamer_links=open; current_position=0, device_class=blind, friendly_name=Slaapkamer links, supported_features=15 @ 2022-05-23T04:27:11.164509+02:00>)>
      
      -<template TemplateState(<state cover.slaapkamer_midden=open; current_position=0, device_class=blind, friendly_name=Slaapkamer midden, supported_features=15 @ 2022-05-23T04:27:11.164073+02:00>)>
      
      -<template TemplateState(<state cover.slaapkamer_rechts=open; current_position=0, device_class=blind, friendly_name=Slaapkamer rechts, supported_features=15 @ 2022-05-23T04:27:11.165971+02:00>)>
#

Does that look good?

#

Oh, and you need to add a > for a multi line template

spice jasper
#

mmh interesting... no because they get substituted with the object by the engine

#
setAllWindowsOpen:
  action:
    service: cover.open_cover
    entity_id: >
      {% for cover in (expand('cover.slaapkamer_groep') | map(attribute=entity_id) | list)%}
      -{{ cover }}
      {% endfor %}
``` perhaps?
marble jackal
#

needs a space between : and >

#

That would work, but makes no sense

#

you are just using a loop to format a perfectly fine list into the yaml format

#

that's just a waste of resources

spice jasper
#

Failed to call service cover.close_cover. Template rendered invalid entity IDs: nope doesn't like it

marble jackal
#

BECAUSE YOU NEED TO PUT IT UNDER TARGET OR DATA!

#

Sorry for the yelling

spice jasper
#

it is

#
target:
  entity_id: >
      {% for cover in (expand('cover.finestra_sala') | map(attribute=entity_id) | list) %}
      -{{ cover }}
      {% endfor %}```
marble jackal
#

entity_id needs quotes

spice jasper
#

Failed to call service cover.close_cover. Template rendered invalid entity IDs: -cover.finestra_sala with quotes

marble jackal
#

But again, why do you so desperately want it like this?

#

Just use the json formatted list

spice jasper
#

just to understand how the logic works behind it

#

it wants the - inside the {{ }}

#

but does not like more than one cover

#

¯_(ツ)_/¯

marble jackal
#

Well I also can't get it working, but as it is pointless anyway I won't spend more time in it. Just use the list the template provides in json format

spice jasper
#

yep i just wanted to get a good grasp to not bother again for some trivial error out of a misunderstanding of the stack

lyric crown
#

I want to count the number of seconds a switch is on. I am using the history stats integration but the problem is that it only measures to the hundredth decimal place so it's only accurate to every 36 seconds. How can I accomplish this behavior with a template?

- platform: history_stats
  name: "Bag Duration"
  entity_id: switch.volcano_air_state
  state: "on"
  type: time
  start: "{{ states('input_button.change_bag') }}"
  end: "{{ now() }}"
marble jackal
#

Does it need to be that precise? How is there between bag changes?

lyric crown
#

Yeah it's not any use if it's not more accurate then to 36

#

Ideally accurate to a second, if it's much more it's not very useful

marble jackal
#

So, if I understand correctly, you press a button (input_botton.change_bag)

#

after that you turn on a swith, turn it off again, turn it on, turn it off, etc

#

and after a while it has been on for a number of seconds, which alerts you it is time to change the bag again

lyric crown
#

yes

marble jackal
#

Okay, you can write the number of seconds to an input_number, and reset it on a press of the button

lyric crown
#

yeah, I can get the elapsed time since the last btn press with {% set elapsed_time = ((as_timestamp(now()) - as_timestamp(states('button.volcano_power_button')))) %}

#

but I wasn't sure how to actually add that number to an input_number

#

I guess I could maybe just have template sensor storing that and then an automation or python script to just add that number to the running elapsed total

marble jackal
#
- service: input_number.set_value
  target:
    entity_id: input_number.whale
  data:
    value: "{{ states('input_number.whale') | float + ((as_timestamp(now()) - as_timestamp(states('button.volcano_power_button')))) }}"
lyric crown
#

ok perfect

#

lemmie try that

marble jackal
#

This will not do what you want though

lyric crown
#

I think I can adapt it

#

I get the idea now tho

marble jackal
#

you need to do this every time you switch the switch to off and use trigger.state_from.last_changed in your template

lyric crown
#

ok I tried something similar to that eailer but I wasn't using triggers and was getting confused why I had no .last_changed, but that makes sense now because I was trying to get the last_changed attribute instead

marble jackal
#

last_changed is not an attriubte (in HA terms)

#

this will not work properly after a reboot though, as last_changed will be the time of HA start

#

so if it was already on for 1 hour before reboot, it will not count that time

#

and as 36 seconds difference wasn't accurate enough

#

I suggest an automation which writes the datetime it was turned on to an input_datetime and then the state of that and compare it to now() when it gets turned off again

silent vector
#

By itself the second statement works however when it's used with an or it does not. Is there a way to keep this as one template with an or?

{{ states('weather.openweathermap') |regex_replace(find='fog', replace='foggy', ignorecase=False) or states('weather.openweathermap') |regex_replace(find='partlycloudy', replace='partly cloudy', ignorecase=False) }}

Works this way:

{{ states('weather.openweathermap')  |regex_replace(find='partlycloudy', replace='partly cloudy', ignorecase=False) }}
marble jackal
#

No, you can only use or for logical expressions

#

{{ a == b or c > d }}

#

You can do something like this:

{% set conditions = { 
                      'fog': 'foggy',
                      'partlycloudy': 'partly cloudy'
                    }
%}
{{ conditions[states('weather.openweathermap')] if states('weather.openweathermap') in conditions.keys() }}
silent vector
#

Would I replace what I have in this statement with that?

{% if state_attr('weather.openweathermap','forecast')[0] .temperature -
        state_attr('weather.openweathermap', 'temperature') | abs >= 3 %} <break
        time=".03s"/> at {{ (state_attr('weather.openweathermap','forecast')[0]
        .datetime | as_datetime | as_local).strftime("%I %p") }} it will be
        {{ state_attr('weather.openweathermap','forecast')[0] .temperature }}
        degrees outside and {{ state_attr('weather.openweathermap','forecast')[0] .condition |regex_replace(find='fog', replace='foggy', ignorecase=False) or state_attr('weather.openweathermap','forecast')[0] .condition |regex_replace(find='partlycloudy', replace='partly cloudy', ignorecase=False) }}. {%
        else %} {% endif %}
marble jackal
#

Guess this would work:

{% set conditions = { 
                      'fog': 'foggy',
                      'partlycloudy': 'partly cloudy'
                    }
%}
{% set s = states('weather.openweathermap') %}
{% set condition = conditions[s] if s in conditions.keys() else s %}
{% if state_attr('weather.openweathermap','forecast')[0].temperature - state_attr('weather.openweathermap', 'temperature') | abs >= 3 %} 
  <break time=".03s"/> at {{ (state_attr('weather.openweathermap','forecast')[0].datetime | as_datetime | as_local).strftime("%I %p") }} 
  it will be {{ state_attr('weather.openweathermap','forecast')[0].temperature }} degrees outside and {{ condition }}.
{% endif %}
#

I removed the {% else %} as it was empty

silent vector
#

As I have 3 similar if statements would I need to use this before each if statement or just once?

marble jackal
#

Are they all in the same template?

silent barnBOT
marble jackal
#

You only need to do it once then

#

just place it at the top as I did above

#

and replace what you did with {{ condition }}

silent vector
#

Sounds good thank you.

#

If it's not fog or partlycloudy it will just evaluate to what the state is right? Such as sunny or clear

marble jackal
#

yes

silent vector
#

Perfect

silent vector
#

I just noticed it only tracks the state. I have separate statements for forecast 0 through 3. I think I would need to repeat what you had prior to each statement and change {{ condition }} to something else for each one right?

For example

{{ state_attr('weather.openweathermap','forecast') [1] .condition
{{ state_attr('weather.openweathermap','forecast')[2] .condition
mighty ledge
#

Remember that time I made a for loop that did all that without specifying which index? Peperridge farm remembers.

silent vector
#

I do lol. But I had an issue where it repeated the same temperature. For example it would repeat at 7am it will be x.

mighty ledge
#

well, you should have posted that and tried to fix it

#

I'm sure there was an easy fix

#

That's what the template editor is for

#

test in the editor and go from there

silent vector
#

https://dpaste.org/xwn9m

Results in

<speak> 
          Good morning.
         It is 06:38 AM. The high today is 71  degrees and the low is 56 degrees. <break time=".03s"/> It is currently 56 degrees outside. - <break time=".03s"/> at 06 AM it will be 56 degrees outside.  </speak>
#

It's already 06:40 past 06:00. Ideally it wouldn't say that and not say the same temperature as current.

marble jackal
#

Put in an if statement checking if the datetime attribute is later than it is right now

#

replace {% if hourly.temperature - ns.previous > 3 %} with {% if hourly.temperature - ns.previous > 3 and hourly.datetime | as_datetime | as_local > now() %}

mighty ledge
#

looking at mine, it's the next 10 days

silent vector
#

Certain.

mighty ledge
#

ok, well this will work

#
<speak> {%- set t = now() %}
{%- set weather = expand('weather.dark_sky') | first %}
{%- set forecast = weather.attributes.forecast %}
{%- set temps = forecast | map(attribute="temperature") | list %}
{%- if t.hour < 12 %}
  Good morning.
{%- elif 12 <= t.hour < 17 %}
  Good afternoon.
{%- else %}
  Good evening.
{%- endif %}
It is {{ t.strftime("%I:%M %p") }}.  The high {{ temps | max }} degrees and the low is {{ temps | min }} degrees. <break time=".03s"/> 
It is currently {{ weather.attributes.temperature }} degrees outside.
{%- set ns = namespace(previous=-300) %}
{%- for hourly in forecast[:3] | rejectattr('datetime', '<', utcnow().strftime("%Y-%m-%dT%H:%M:%S+00:00")) %}
{%- if hourly.temperature - ns.previous > 3 %} 
- <break time=".03s"/> at {{ (hourly.datetime | as_datetime | as_local).strftime("%I %p") }} it will be {{ hourly.temperature }} degrees outside.
{%- endif %}
{%- set ns.previous = hourly.temperature %}
{%- endfor %} </speak>
#

Edited to remove whitespace

#

the -'s seem redundant with the break times. I'd just make the breaks longer as that's what the dashes do IIRC

silent vector
#

Sounds good I will try this thank you.

silent vector
#

Is it also possible this template would be able to work with a temperature that is 3 degrees lower than previous and not just greater than previous? In my template I'm using abs >= 3. Also can it besides just doing greater than previous also do greater than current which is {{state_attr('weather.openweathermap', 'temperature') }}

#

To add precipitation probability would it be hourly.precipation_probability for example hourly.precipation_probability > 70

mighty ledge
#

Just put the abs in the check

silent vector
#

Also it doesn't seem to be rejecting an equal temperature to current.

<speak>
  Good morning.
It is 07:56 AM.  The high 71 degrees and the low is 55 degrees. <break time=".03s"/> 
It is currently 58 degrees outside. 
- <break time=".03s"/> at 08 AM it will be 58 degrees outside. </speak>
mighty ledge
#

Set the previous in the namespace to the temperature as well

#

On mobile so you’ll have to make the changes

silent vector
#

Nevermind the abs fixed it.
{%- if hourly.temperature - ns.previous | abs >= 3 %}

mighty ledge
#

Remplqce the -300

#

Pedmas

#

Math order of operations

#

If you want to apply the abs on the result of the subtraction… what would you do?

silent vector
#

I honestly don't know.

mighty ledge
#

Parenthesis

marble jackal
#

Let me give you a ( clue ) 🙂

#

Too late, and I'm not even on mobile

mighty ledge
#

Pedmas-> parenthesis, exponent, division, multiplication, addition, subtraction

#

Bring yourself back to 6th grade math

silent vector
#

I remembered that lol but I wasn't sure if parentheses would be used. We used "please excuse my dear and Sally" and some McDonald's thing too but I wasn't sure if parentheses should be used.

marble jackal
#

There is no filters in pedmas.. 😉

silent vector
#

So it would be previous=(300)?

mighty ledge
#

No, you asked 2 questions and you got 2 answers and your mixing them

silent vector
#

Oh yes greater than current and greater than previous.

mighty ledge
#

Right. That’s the parenthesis

#

Replace the -300 with weather.attributes.temperature

silent vector
#

If I'm getting this right

{%- if hourly.temperature - ns.previous | abs >= 3 %}

marble jackal
#

in the second template you are only applying the abs to ns.previous

silent vector
#

How would I fix that?

marble jackal
silent vector
#

Where would the parentheses go though?

{%- if hourly.temperature - ns.previous | int (3) %} 
marble jackal
#

{%- if (hourly.temperature - ns.previous) | abs >= 3 %}
It's not that difficult, just put parenthesis around the part you want to apply first

silent barnBOT
marble jackal
#

It's not the first time today that this happened isn't it?

mighty ledge
#

Is there a problem?

silent vector
#

https://dpaste.org/SmCsK
The output isn't including the {{ state_attr('weather.openweathermap','forecast')[3] .temperature }} which is 3 degrees greater than current right now.

mighty ledge
#

it checks for 3 degrees above the previous temperature

#

so, do you want it 3 degrees above the current or 3 degrees above the prevous temperature

silent vector
#

Is it possible to do both?

mighty ledge
#

that wouldn't change your current output

silent vector
#

3 above previous or 3 above current

marble jackal
#

{%- if (hourly.temperature - ns.previous) | abs >= 3 or (hourly.temperature - weather.attributes.temperature) | abs >= 3 %}

silent vector
#

Would this work? There were no errors in the template editor but I'm curious as to whether it would work in the loop.
https://dpaste.org/4C0TD

mighty ledge
#

try it

#

there's a template editor

silent vector
#

I used the editor and it evaluates with no errors. I was curious as to whether it would be sequential meaning would it output 0 temperature from the forecast and then the precipitation probability or would it loop through the forecast 0-3 first then loop precipitation probability. Potentially resulting in at 10 it will be 60 degrees at 11am it will be 63 degrees at 12 am it will be 66 degrees. At 10 am it will be 71% chance of rain. At 11 am it will be 75% chance of rain etc.

marble jackal
#

you can play with that by changing the comparison values in the template editor

#

change the 3 to 0 and change > 70 to >= 0 and you will get it all

mighty ledge
#

because you'd see on screen exactly what you're asking

#

what are you trying it in?

#

developer tools -> template?

#

unless it's not raining, then I could see this being an issue

silent vector
#

Here's the output

<speak>
  Good morning.
It is 09:04 AM.  The high 71 degrees and the low is 55 degrees. <break time=".03s"/> 
It is currently 61 degrees outside.  
- <break time=".03s"/> at 10 AM it will be 61 degrees outside.
 <break
        time=".03s"/> at 10 AM The chance of rain is 0%. 
  
- <break time=".03s"/> at 11 AM it will be 62 degrees outside.
 <break
        time=".03s"/> at 11 AM The chance of rain is 0%. 
 </speak>
#

Exactly what I was looking for

#

Now how would I fold the regex replace we were talking about with fog and partlycloudy into the loop?

{% set conditions = { 
                      'fog': 'foggy',
                      'partlycloudy': 'partly cloudy'
                    }
%}
{% set s = states('weather.openweathermap') 
{% set condition = conditions[s] if s in conditions.keys() else s %}
marble jackal
#

I was wondering when this would come in the picture again

silent vector
#

Lol I didn't forget

marble jackal
#

What do you want as result here for the next hours? Only when it differs from the current and/or previous?

silent vector
#

When it differs from current and/or previous would be best

finite peak
#

Is there a way to save a template that will be used over and over in many automations or do I have to paste the template code in each time?

marble jackal
finite peak
fossil totem
#

I think the template sensor is just what you want

marble jackal
#

I still see only 2 templates. one for today and one for tomorrow

finite peak
#

that's correct

#

and template sensors are created only via the configuration file?

marble jackal
#

yes

silent vector
#

It says 404 not found?

marble jackal
#

Now it doesn't anymore (new link)

finite peak
#

ok, so I just need to determine how to write the template to get what I want out of it then. For example if I wanted to take the value of precipitation_amount and precipitation_probability over the span of 2 days and create a value out of that...🤔

silent vector
marble jackal
#

Are you sure you copied everything relevant, including this line {% set h_cond = hourly.condition | replace('fog', 'foggy') | replace('partlycloudy', 'partly cloudy') %}

silent vector
#

Missed that. Now it says hourly is undefined. Is that because hourly isn't defined until the next line?

marble jackal
#

Just take the entire thing and only replace your entity at the top

edgy isle
#

Hi,
what is wrong with this one? The addition does not work, the value is simply equal to the first:
template:
sensor:
name: power_consumption_total
unit_of_measurement: 'W'
state: '{{ states("sensor.l1_power") + states("sensor.l2_power") + states("sensor.l3_power") }}'

silent vector
#

Working now thank you.

marble jackal
marble jackal
edgy isle
#

ah, that is what the "| int" is for. thx, will try that

marble jackal
#

use | int if you don't care about decimals (or if the sensor doesn't have decimals), use | float otherwise

silent vector
#

Hm I don't think it was supposed to say the 12pm condition

<speak>
Good morning.
It is 10:06 AM. The high 71 degrees and the low is 55 degrees. <break time=".03s"/>
It is currently 63 degrees and sunny outside.

  • <break time=".03s"/> at 11 AM it will be partly cloudy.
  • <break time=".03s"/> at 12 PM it will be partly cloudy. </speak>
marble jackal
silent vector
#

That's true. Is it possible to be different from current or previous but not repeat the way it did at 12pm? If not it's fine.

marble jackal
#

I guess only checking if it is different as the previous one would suffice then

silent vector
#

Hm yeah that makes sense, the only reason I wanted greater than 3 from current or previous was for temperature as it is possible to be 60,61,63. For condition it doesn't appear to make a difference sunny,cloudy,cloudy,sunny,rainy for example those are different from previous and it would work to not have different from current.

marble jackal
#

then remove the comparison to cond in the if statement

silent vector
#

I tried h_cond != ns.prev_cond and h_cond != cond and its still repeating for some reason

marble jackal
#

wait, my bad

marble jackal
#

replace this at the end:

{%- endif %}
{%- set ns.previous = hourly.temperature %}
{%- endfor %} </speak>

with

{%- endif %}
{%- set ns.previous = hourly.temperature %}
{%- set ns.prev_cond = h_cond %}
{%- endfor %} </speak>
#

and replace:

{%- if h_cond != cond or h_cond != ns.prev_cond %}  

with:

{%- if h_cond != ns.prev_cond %}  
silent vector
#

That worked.

marble jackal
#

And the max value of the probability, and also sets that as a variable

finite peak
#

I see. But if precipitation is an amount (in mm) and not a percentage, how would that work?

marble jackal
#

How would what work? I knew it was an amount in mm, that's why I summed them to get the total of the the two days

opaque creek
#

Hey! I have a template sensor showing my sunrise with offset of -45 minutes. How do I make it show this based on my timezone (GMT+1) ?

{{ state_attr('sun.sun', 'next_rising') | as_datetime - timedelta(minutes = -45) }}

young jacinth
#

i got a sensor that has a text and emoji in every state, how would i remove the the emoji with a template?

mighty ledge
#

depends on how the emoji is represented as text in the sensor

young jacinth
#

i just copy and pasted an emoji from Whatsapp

mighty ledge
#

Ok and what does it look like in the sensor state in HA?

young jacinth
#

the emoji just shows up
I can't actually see the format

young jacinth
marble jackal
#

Is the emoji always at the end? Maybe you can split on space and remove the last part and join it again

mighty ledge
young jacinth
mighty ledge
#

then [:-1] would be everything before the emoji and [-1] would be the emoji

stuck remnant
#

@marble jackal sorry to bother you again with this but you didnt confirm yesterday if that automation was the same as what you told me to do. I believe it is but can you please take a quick peak just to be sure? https://pastebin.com/Nj5F5J9t

#

I also did it the exact way you said (with the additional binary sensor to check for 36 elapsed hours) but then thought an automation on an input boolean would be more useful. If it isn't good I can switch back to the sensor

marble jackal
#

No, this doesn't look right

#

The automation with this trigger should set your input_datetime to now(). Nothing more than that

#

And it should not have this condition

stuck remnant
#

oh no, I did that separately, for the datetime

#

this is a boolean

#

thisone is instead of the binary sensor with the 36 condition check

#

I figured I can't action a binary sensor, but I can action a boolean if I happen to need it to trigger

inner mesa
marble jackal
stuck remnant
#

and the binary sensor

      - name: "Cold"
        state: >
          {{ is_state('binary_sensor.outside_cold', 'on') and now() - timedelta(hours=36) > as_local(as_datetime(states('input_datetime.cold'))) }}```
marble jackal
#

Do you have two binary sensors cold now?

stuck remnant
#

yes

marble jackal
#

Oh I see

#

I'm one mobile, so it's a bit hard to get the overview

#

So binary sensor cold outside just checks if it is below 11 degrees right?

stuck remnant
#

yes

#

sorry for the naming

#

its confusing

#

but didnt know what to use :))

marble jackal
#

No that's fine

#

Okay, great. Now just use your new binary_sensor.cold as condition in your automations

#

Don't turn them off

stuck remnant
#

oh that's even better!

opaque creek
inner mesa
#

where it was before

#

I just gave you the part that changed. Although subtracting a negative timedelta is a strange thing to do

#

I would either subtract or add a positive timedelta

#

you should really stop messing around with offsets from sunrise/sunset and just use sun elevation

opaque creek
#

oh ok! maybe that's better? 🙂 Because I want my outside lights to go on just when it gets dark. And +45 minutes after sunset seem to be a good time. But how do Elevation work? should I just notice the elevation when its dark and notice and use that in automation?

inner mesa
#

that's what I did

#

with the advantage that it's the same year-round

opaque creek
#

Oh it is? well that's interesting will try it out! thx

opaque creek
# inner mesa that's what I did

So I found what elevation should be good here when its dark. Its -4.63. But should that go in "below" or "above" in the automation to turn on the lights? 😛

#

But wait, it's -4.63 2 times during a day, right?

inner mesa
#

You can use a numeric_state trigger to differentiate if you want

orchid oxide
#

Maybe there's a simpler way to do this but is there a way to include the state of one entity as part of an entry for another entity? Something like

{{(sensor.state_attr('person.Morgan', 'friendly_name')}}

Where friendly name is Morgan and the result of the tensor would be sensor.Morgan

inner mesa
#

Yes, it's just a string

#

If that's what you want

#

'sensor.' ~ state_attr()

opaque creek
inner mesa
#

Should be fine, but you need separate triggers

opaque creek
#

yes I use 2 automations one for on and one for off

brisk lava
#

Is it possible to pull measurement history and convert that to a value template? I'd like to get a 3 day moving average for my download speed from sensor.speedtest_download but am struggling as it's not a readable state or attribute.

inner mesa
#

the only way to retrieve history is either to create a template sensor or sensors that sample every so often and retain the number of historical points you want, or to use the SQL sensor

#

or, just use the statistics sensor

brisk lava
#

I tried statistics sensor, but was getting an error [state_characteristc] is an invalid option for [sensor.statistics]

#

which is what the documentation uses to explicitly call "mean"

inner mesa
#

and it's optional, with the default being "mean"

mighty ledge
inner mesa
#

That's the British English spelling

brisk lava
#
  • platform: statistics
    state_characteristic: mean
    name: "3 Day Avg Download Speed"
    entity_id: sensor.speedtest_download
    max_age:
    hours: 72
#

That's the sensors.yaml entry, and it spits out an unavailable error in dev tools>states

low blaze
#

is it ok to still use state_attr or should I be using States always?

stuck remnant
#

Hi I have a template sensor for my bathroom cam that works and an identical one for my kitchen cam that shows up as unavailable

      - platform: time_pattern
        seconds: "/1"
    binary_sensor:
      - name: "Bathroom motion"
        state: >
          {{ (now() - states.sensor.samsung_j3_ipcam_motion.last_changed).seconds < 30 }}
#

I checked them both physically as well as inside HA and the individual motion sensors are working live

#
      - platform: time_pattern
        seconds: "/1"
    binary_sensor:
      - name: "Kitchen motion"
        state: >
          {{ (now() - states.sensor.fig_lx1_ipcam_motion.last_changed).seconds < 30 }}```
#

this last one shows up Unavailable

inner mesa
inner mesa
#

as far as why it evaluates to 'unavailable', plug the template into devtools -> Templates and see

stuck remnant
#

like the other one does

#

but it doesn't, it shows up as unavailable

inner mesa
#

I suggest just removing the trigger from both of them

stuck remnant
inner mesa
#

it sounds like it's not actually triggering

stuck remnant
#

hmm interesting. So not adding anything instead of the trigger part? just removing it

inner mesa
#

you can use some other trigger that helps filter how often it runs, but it's indiscriminate now, so now how much worse can it get?

#

yes, just let the entity updates drive the sensor

#

template sensors didn't have a "trigger" section until a few months ago

stuck remnant
#

cool

#

ooh now I remember why

#

someone said whenever you work with 'now(0)' it triggers only once a minute

#

like it evaluates the template and checking conditions only once every minute or so

#

which is why I thought of adding the trigger every second

inner mesa
#

you're also referencing an entity, but I don't know if it will pick that up

#

you should just use a state trigger instead, based on the sensor entity

#

then it will definitely only trigger when it changes state

stuck remnant
#

that would be ideal indeed

#

so how do I type that? sorry, template noob here :p

inner mesa
#

it's not related to templating

stuck remnant
#

this is my sensor.fig_lx1_ipcam_motion entity

inner mesa
#
  - trigger:
      - platform: state
        entity_id: sensor.fig_lx1_ipcam_motion
#

it's just a trigger like any other trigger

stuck remnant
#

oh

#

thought there was a special way to type it

#

cheers

#

yep worked like a charm

orchid oxide
#

since this is a template question, is it possible to include a template here? what would the proper way to do this be (if even possible)

    {% for person in states.person %}
      {% if states('sensor.'~person.attributes.friendly_name~'_home_value')|float > 0  %}
          {{
            {
              'type': 'template',
              'entity': 'person.entity_id',
              'content': '{{content}}'
              
            }
          }},
      {% endif %}
    {% endfor %}```
#

id want a template where {{content}} is

inner mesa
#

You can't nest templates

#

If you can, you would just not quote it behaves it's not a string

orchid oxide
#

do you mean like this:
'content': content

#

got it, thanks

#

this.entity_id (auto-entities) doesnt work there for some reason

inner mesa
#

in the template editor?

#

there's no reason why it wouldn't work where it's valid

#
{% set this = {"entity_id": "foo.bar"} %}
{%- for person in states.person -%}
      {%- if true  -%}
          {{
            {
              'type': 'template',
              'entity': 'person.entity_id',
              'content': this.entity_id
              
            }
          }},
      {%- endif -%}
    {% endfor %}
#

->

[
  {
    "type": "template",
    "entity": "person.entity_id",
    "content": "foo.bar"
  },
  {
    "type": "template",
    "entity": "person.entity_id",
    "content": "foo.bar"
  }
]
orchid oxide
#

it doesnt work in to get state or attribute values here, but it does work otherwise

#

ah but neither does person.entity_id

#

so states('person.entity_id') doesnt work but person.state does

#

last question, i think, how would i include

     action: more-info```
inner mesa
#

this works fine for me:

              'content': states('input_text.test')
#

"content": "floop"

orchid oxide
#

yeah but try 'content': states('input_text.entity_id') and it wont work

#

or 'content': states('this.entity_id')

inner mesa
#

Do you have an input_text entity called that?

#

It doesn't make sense

orchid oxide
#

i was using person.states, and no, i dont have an entity called that

inner mesa
#

Ok, then it won't work shrug

orchid oxide
#

right but, it works in the dev tools template but not in auto-entities

#
      {% if states('sensor.'~person.attributes.friendly_name~'_home_value')|float > 0  %}
          {{
            {
              'type': 'template',
              'entity': 'this.entity_id',
              'content': states(person.entity_id),
              'icon': 'mdi:home' if person.state=='home' else 'mdi:home-export-outline',
              'icon_color': 'grey',           
              'tap_action': {
              'action': 'more-info'}
            }
          }},
      {% endif %}
    {% endfor %}```
inner mesa
#

And again, this.entity_id is a variable and shouldn't be in quotes

orchid oxide
#

eh either way, its honestly a non-issue

inner mesa
#

Great. But I hope you'll see what's wrong

#

There are some fundamental misunderstandings there

orchid oxide
#

me too, but right now i just dont have the brainpower for it 😅

orchid oxide
#

i see whats up now..

#

so does anyone know how to fit a tap action in the above?

proven needle
#

Hi 🙂 Any way to format a number based on the users current locale, and not that of the server?

marble jackal
floral shuttle
#

check: filter: template: >- {% set threshold = states('input_number.battery_alert_level')|float(0) -%} {%- for s in states.sensor|selectattr('entity_id','search','battery_level') if s.state|float < threshold -%} {{ { 'type': 'custom:button-card', 'template':'custom_ui_hack_for_button_card_template', 'entity': s.entity_id } }}, {%- endfor %}

waxen rune
#

I want to show when an entity last changed state in my dashboards. For example when a door (that now is open), was opened.
Today I use {{ as_timestamp(states.binary_sensor.altandorr.last_changed) | timestamp_custom('%Y-%m-%d %H:%M') }} which works fine.
But it is not always correct since last_changed is reset when HA is restarted, and hence all open sensors that hasn't changed state since HA's last restart now show HA's restart time instead of the actual/physical state change. The actual state change is stored in the logbook. Can I fetch it there? Or some other way that is not reset by HA restarts?

marble jackal
#

logbook uses the database, you can also get it out using a sql sensor, but that requires you to create an sql sensor for all your entities.
BTW, you can also do {{ states.binary_sensor.altandorr.last_changed.strftime('%Y-%m-%d %H:%M') }}

waxen rune
#

Ok, so possible, but a hassle 🙂

#

Thanks, and thanks for the smarter template

buoyant sapphire
#
{{states('input_datetime.staubilastrunkueche') }}
{{ now().strftime('%Y-%m-%d') }}

both entities result in 2022-05-24.

Question: how can i put this into a template that returns true/false on comparing those two entries?

marble jackal
low blaze
#

I've managed to correctly convert my input_datetime's into seconds so i can work with them, but I can't do the same with "now"

#

states('sensor.time') gives me the correct hours:minutes of right now

#

but trying to convert it, I get 0 or unknown.

#

What I am trying to actually accomplish is this. I have a time (input_datetime, like 9am (9:00). I also have a buffer variable (input_number) which is a number of minutes

#

Just need to determine if right now it is within (buffer minutes) of that time.

#

The only thing stopping me from accomplishing this is that I can't turn "now" into seconds so that I can compare them.

#

state_attr('input_datetime.t1_sleep', 'timestamp') gives me the time I want in seconds, but I switching that out for sensor.time does not work

#

{% set nowseconds = (as_timestamp(states.sensor.time.state)) %} i get "none"

mighty ledge
low blaze
#

just a time

#

I have a set time of 9am

mighty ledge
#

ok, and what are you trying to do

low blaze
#

I have set my "grace period of 20 min" (an input_number)

#

I just want to determine if it's between 8:40 and 9:20

#

during a template sensor

#

I guess the problem is that my sensor.time doesn't have a date, but I don't need one nor does my other calculation but that does not seem to mind not having a date

mighty ledge
#
{% set offset = timedelta(minutes=20) %}
{% set alarm = today_at(states('input_datetime.t1_sleep')) %}
{{ alarm - offset < now() < alarm + offset }}
low blaze
#

need to use a sensor for 20 it will be an input_number

mighty ledge
#

ok

#
{% set number = states('input_number.xyz') | int(default=20) %}
{% set offset = timedelta(minutes=number) %}
{% set alarm = today_at(states('input_datetime.t1_sleep')) %}
{{ alarm - offset < now() < alarm + offset }}
low blaze
#

thank you let me take a look at and play with this

#

appreciated 🙂

mighty ledge
#

np

low blaze
#

can I drop the default, it will always have a value

mighty ledge
#

sure

#

still needs int

#

if you're using it as a template sensor, it may error on startup

#

you'll be fine if it's in an automation

low blaze
#

yes I left the |int

#

should be ok, It's part of an if/else

#

so if it errors on startup, it would just "else"

#

which is fine

mighty ledge
#

the take a way is that today_at will error if the input_datetime returns 'unknown', which is unlikely

low blaze
#

good thanks

#

and also the use of timedelta

mighty ledge
#

if you swap them to sensors instead of helpers, you'll have errors

#

i.e. things that can go unavailable or unknown

low blaze
#

gotcha

#

would it actually error or would it just not pass true and thus drop to the else?

mighty ledge
#

it would error out

low blaze
#

im only using helper so it should be fine

mighty ledge
#

yep

limpid venture
#

Sorry, folks wish to paste some code how do I do that politely?

#

Trying to create multiple If statements to change icon, what am I doing wrong? {% elif s = 'Eco+' %} mdi:leaf-circle

#

Sorry {% set s = states('select.myenergi_zappi_20435419_charge_mode') %} {% if s = "Stopped" %} mdi:stop {% elif s = "Eco+" %} mdi:leaf-circle {% elif s = "Eco+" %} mdi:leaf-circle-outline {% else %} mdi:run-fast {% endif %}

inner mesa
#

You're using = when you need ==

orchid oxide
#

is there any way to return only the value from a key value pair? and is there a way to do this systematically without necessarily listing out each key?

marble jackal
orchid oxide
#

yeah so i have an input_text.entity which contains a string (or i can make it an array with states.input_text.entity.state.split(', ')) of key value pairs {'BT-ID':'MAC-address'} and I want to do something like

{% set = device_list states.input_text.entity.state.split(', ')%}
{%for device in device_list%}
{{devicevalue in state_attr('sensor.pixel_4a_bluetooth_connection','connected_paired_devices')}}
{%endfor%}```
#

where device is any single key:value pair from the list and devicevalue is the value of the key value pair (not sure how to tell it to return devicevalue)

#

id like to match the value and perhaps (but less importantly so) return which key it belongs to

#

example value of the input_text.entity is {'BK01':'EB:06:EF:26:45:94'}, {'Lexus':'94:B2:CC:D6:89:1C'}, {'Bond':'DE:63:AD:73:7A:D1'}

marble jackal
#
{% set d = "{'a': 'b'}, {'c': 'd'}".split(', ') %}
{{ d }}

Results in:

[
 "{'a': 'b'}",
 "{'c': 'd'}"
]
#

So you will end up with a list of strings, not a list of dicts

orchid oxide
#

yeah, how do i turn it into a list of dicts is part of what im trying to figure out

marble jackal
#

But I think we are having an xy-issue here

silent barnBOT
#

The XY problem is asking about your attempted solution rather than your actual problem.

This leads to enormous amounts of wasted time and energy, both on the part of people asking for help, and on the part of those providing help.

The problem occurs when people get stuck on what they believe is the solution and are unable to step back and explain the issue in full.

orchid oxide
#

haha, ive no doubt that im taking a bit of complicated route here, but in the name of simplicity later. i'd like to match for bluetooth mac addresses based on one entity, so that i can add/remove them with relative simplicity (changing the entity rather than editing the automation). this is simple enough with split, but i also want to return the name of the bluetooth device that was connected. the best answer i can think of is dictionaries with name:mac-addr to match the mac address and return the name which the mac address belongs to, so thats what im trying to go for here

coarse tiger
#

when I try it in the template editor in devtools i get:
UndefinedError: 'homeassistant.util.read_only_dict.ReadOnlyDict object' has no attribute 'scanner'
what is going on?

marble jackal
#

Sorry for the crappy indentation, I'm on mobile

coarse tiger
#

works. that part I figured - that it stumbles upon the entities without the attr and fails but the definedis new to me thanks.

#

but I wondered why it works as template sensor but not in dev tools

#

seems dev tools is a bit more strict

mighty ledge
#

That’s the best way to store complex structures to serialize and deserialize them

orchid oxide
#

ok, ill give that a try, thanks

silent vector
#

<speak>
Good morning. It is 05:34 AM. The high today is 72 degrees and the low is 52 degrees. <break time=".03s"/> It is currently 52 degrees and clear-night outside. The humidity is currently 84%. - <break time=".03s"/> at 06 AM it will be sunny - <break time=".03s"/> at 07 AM it will be partly cloudy

#

Its weird because it said 5:34 likely because it recognized it as time even though It said 05:34 above however the 06 and 07 were pronounced 06 and 07 rather than 6 and 7am

orchid oxide
#

got one more question on this here. in my testing the following template evalutes to boolean true if there is exactly one entry that is true or boolean false if all entries are false, but if multiple entries are true, it evalutes True as a string for each entity

#
{%set device_list = states.input_text.car_bluetooth_connections.state.split(', ')%}
{%for device in device_list if device in state_attr('sensor.pixel_4a_bluetooth_connection','connected_paired_devices')%}
{{true}}
{%endfor%}```

for example, in my test there are 2 matching entries and the result i get is 
```Result type: string
True

True```

how can i make this example result to a boolean true
marble jackal
marble jackal
#

{{ device_list | select('in', state_attr('sensor.pixel_4a_bluetooth_connection', 'connected_paired_devices')) | list | count > 0 }}

#

Otherwise you have to make sure it is a correct list using the json filters

amber hull
#

I added to my template due to getting spikes ```
value_template: >
{{states('sensor.bill_br_govee5075_humidity') | is_number and
states('sensor.bill_bathroom_average_linear_3h') | is_number}} {{(states('sensor.bill_br_govee5075_humidity') | float -
states('sensor.bill_bathroom_average_linear_3h') | float) |round (1)}}

#

The check is_number. Do I need to add something between this and the rest of the template? I no longer get a graph in history

#

Developers tools shows true and a value i.e .3

marble jackal
#

The first part should be added as availability_template and should not be part of the value_template

amber hull
#

That was the link Petro sent me yesterday, I did not understand from the docs how to format it correctly. So does this statement go in the template by itself and then the value statement?
So Reading some of the forums I need to add a separate line in my template called availability_template and then the is number?

crystal sparrow
#

Hi template gurus.

Is there a best practice to validate a state as a datetime before running as_datetime()?

I have a sensor (mobile phone next alarm time) that is only a valid datetime when an alarm is set.

{{ now() >= as_datetime(states('sensor.phone_next_alarm')) - timedelta(minutes = 15) }}

This fails if the alarm is not set.

marble jackal
silent vector
#

Output:
<speak>
Good morning. It is 05:34 AM. The high today is 72 degrees and the low is 52 degrees. <break time=".03s"/> It is currently 52 degrees and clear-night outside. The humidity is currently 84%. - <break time=".03s"/> at 06 AM it will be sunny - <break time=".03s"/> at 07 AM it will be partly cloudy

#

Its weird because it said 5:34 likely because it recognized it as time even though It said 05:34 above however the 06 and 07 were pronounced 06 and 07 rather than 6 and 7am

marble jackal
amber hull
#

Got this error when I run config check. Error loading /config/configuration.yaml: invalid key: "OrderedDict([("states('sensor.bill_br_govee5075_humidity') | is_number and states('sensor.bill_bathroom_average_linear_3h') | is_number", None)])"
in "/config/integrations/../entities/sensors/bill_delta.yaml", line 21, column 0

#

No error in developers tools.

#

availability_template: {{states('sensor.bill_br_govee5075_humidity') | is_number and states('sensor.bill_bathroom_average_linear_3h') | is_number}}

marble jackal
amber hull
#

Thank you!!

marble jackal
#

Change the format for your time strings

silent vector
#

Perfect that worked.

crystal sparrow
marble jackal
#
{% set s = states('sensor.phone_next_alarm') %}
{{ now() >= as_datetime(s) - timedelta(minutes = 15) if not s in ['unavailable', 'unknown'] else false }}
orchid oxide
#

so im back on dictionaries now, and ive got things mostly working, the 2 things i cant seem to find in my search are how to a) list all values without iterating and b) how to get the key from the value. current example im messing with

  "BK01": "EB:06:EF:26:45:94",
  "Lexus": "94:B2:CC:D6:89:1C"
}```
silent vector
#

I never used %H. The fix was %-I %H was only used for the rejectattr you created for me not for what would be spoken.

mighty ledge
orchid oxide
#

yeah i mean, it goes both ways. i the human, want to get the name when the device gives me back a mac address, but conversely if i give the device a name, itll want the mac address. so i'd like to make it work both ways

mighty ledge
#

you have to turn it into tuples

#

or a list of tuples

#

@orchid oxide can you post what you're pushing to the input_text and and post how you're using the input_text.

#

Post all the Jinja.

orchid oxide
#

text input: {"BK01": "EB:06:EF:26:45:94", "Lexus": "94:B2:CC:D6:89:1C", "Bond": "DE:63:AD:73:7A:D1"}
and the jinja i have. this right now is a condition/trigger

{%set device_list = (devices.values()|list)%}
{{device_list | select('in', state_attr('sensor.pixel_4a_bluetooth_connection', 'connected_paired_devices')) | list |count < 1}}```

I think I have this part worked out. But I then want to be able to return (in a notification for example) the name of the bt device
crystal sparrow
orchid oxide
#

using connected devices to test since its way easier, so I have this part which is what im trying to get

{%set device_list = (devices.values()|list)%}
device_list|select('in', state_attr('sensor.pixel_4a_bluetooth_connection', 'connected_paired_devices'))|list```
except this last part returns the mac address (value) and i want some way to get the device name (key) from the value so I can display that isntead
vague ice
#

I'm looking to replicate something like

{% for i in states.switch and states.sensor and states.binary_sensor and states.lock and states.input_boolean %} {% endfor %}

in a trigger. I ultimately would like any entity state change in any of those domains (and new domains I add to this in the future) to trigger home assistant to call my own API.

I just dont know how to do this in templates, or maybe I shouldn't do it in templates at all. I know I could just list out all the entities in a regular state trigger but there are so many of them.

#

I could use the event state_changed trigger as well as I was pointed to a little bit ago, however that triggers the automation on and off way too much for my likings. I want to prevent any automation/script state changes from triggering the automation.

inner mesa
mighty ledge
#
{%set devices=(states('input_text.car_bluetooth_connections')|from_json)%}
{{ devices.items() | selectattr('1', 'in', state_attr('sensor.pixel_4a_bluetooth_connection', 'connected_paired_devices')) | list }}
#

that will return [('key', 'value'), ('key', 'value') ]

#

using selectattr('1' will check against the value

#

using selectattr('0' will check against the key

#

i forgot, then after you make your list, you access each one with a [0] or a [1], depending on what you want

mighty ledge
orchid oxide
#

uhh, well for the time being i was just writing it manually. i had considered making a some kind of device picker, but i havent gotten that far yet

#

also thanks both for the help

mighty ledge
#

how do you plan on getting it?

orchid oxide
#

a device picker? i use an automation app on my phone that I know could do that pretty easily. home assistant doesnt even store the device names afaik (and i'm not as familiar with home assistant tbh) so i dont even know where i'd start if i went that route

mighty ledge
#

So, is this just a configuration then?

#

the input_text I mean

#

I'm just trying to figure out how that input_text is populated and what is expected of it in the future.

orchid oxide
#

yeah right now it is. In the future I will probably use a device picker like i said, have it output all key and values properly formatted and then use an api call to change the input_text in ha

mighty ledge
#

by device picker, do you mean a template sensor or something?

orchid oxide
#

oh, no, just some sort of dialog box that lets me check off the options

#

of bluetooth devices i want to include

mighty ledge
#

you should have this structure for your attribute:

[{'name': 'BK01', 'mac': 'EB:06:EF:26:45:94'}, ... ]
#

@orchid oxide then, you can simply use selectattr the normal way. Assuming your attribute in the sensor is named devices and the template sensor has a name sensor.bluetooth_connections, the syntax would be

{{ state_attr('sensor.bluetooth_connections', 'devices') | selectattr('name','eq', 'BK01') ...

or

{{ state_attr('sensor.bluetooth_connections', 'devices') | selectattr('mac','eq', 'EB:06:EF:26:45:94') ...
#

and you wouldn't need to use |tojson or |from_json

orchid oxide
#

ok gotcha. that does make sense. ill look into setting that up

mighty ledge
#

Personally, I'd set that up first before going with some other option

#

otherwise, going backward might not help

#

although, there is a 'new' development style where people work backwards with their data and it's proving to be a good process

orchid oxide
#

im kinda just all over the place, i never really follow a process even though I should 😅 . I definitely decided to do more with this than I had initially planned though, otherwise I probably would have started there

merry marsh
#

Small question, before starting to play around with this: Are trigger.to_state.state etc. available in trigger-template-sensors as well. Or only within autmations?

mighty ledge
final pulsar
#

Hey I have a little problem, has anybody an idea why sometimes the icon color doesent update until i refresh the browser or switch the dashboard?

marble jackal
pine kestrel
#

brainstorming,
I have sensor.basement_hvac_mode
which I want to know how many minutes it has been in "cooling" in the last 2 hours... but cannot just use last_changed since it can go from cooling to idle and idle to cooling.... to make it harder, I want
sensor.basement_hvac_mode is cooling OR sensor.other_hvac_mode is cooling
since they both same same compressor

#

theory is that if its running for too long... something is wrong