#templates-archived

1 messages Β· Page 47 of 1

floral shuttle
#

well,yes, this is from before easy_time...

mighty ledge
#

yeah, but easy_time does that whole thing

#

one of the macros does that

#

speak_the_days

floral shuttle
mighty ledge
#

speak_the_days('sensor.next_alarm_timestamp')

#

and you can use count_the_days to get the number

floral shuttle
#

hmm, if I enter {% from 'easy_time.jinja' import speak_the_days %} {{speak_the_days('sensor.next_alarm_timestamp')}} I get TypeError: unsupported operand type(s) for -: 'NoneType' and 'datetime.datetime'

mighty ledge
#

what's the state of 'sensor.next_alarm_timestamp'

floral shuttle
#

{{states('sensor.next_alarm_timestamp')}} returns 1689309000.0

mighty ledge
#

well that would be why

#

don't use a timestamp

#

use next_alarms datetime

#

well, let me check something, i cant remember how i wrote it

floral shuttle
#

I do have this {% set timestamp = states('sensor.next_alarm_timestamp')|int(default=0) %} {{as_datetime(timestamp)|as_local}} also, so let me try it with that

mighty ledge
#

seems like a bug in speak the days

floral shuttle
#

yep, {% from 'easy_time.jinja' import speak_the_days %} {{speak_the_days('sensor.next_alarm_datetime')}}

mighty ledge
#

it should work

floral shuttle
#

returns 'in 1 day'

mighty ledge
#

that should also be 'tomorrow'

#

I'll have to look at things

#

can you just write that up?

#

with sensor.next_alarm_datetime and it's state

floral shuttle
#

yeah, Ill open a post in the repo, and also add the complete next_alarm_timestamp, because I noticed just now, that when no alarm is set, it throws off the other templates too. (not my current ones, but the ones based on easy_time)

azure ridge
#

Im trying to use the Lovelace card-templater card to display the title of an entities card using a template. Ive got a working template but cant figure out how to use the template as a title. Any ideas?

floral shuttle
#

that would be #frontend-archived and my advice would be to use a custom:button-card or core vertical-stack as first in the entities, so you can do anything you like with it

#
  type: vertical-stack
  cards:

    - type: custom:button-card
      template: button_default_title
      name: >
        [[[ return 'KNMI: ' + states['sensor.knmi_omschrijving'].state; ]]]
      tap_action: none
``` but, as said, thats [#frontend-archived](/guild/330944238910963714/channel/460846676358332417/)
azure ridge
#

Okay, Thanks alot!

fringe sail
#

@mighty ledge , I really appreciate you putting me on the right path yesterday. Your way didn't do exactly what I needed, but it was enough to get me to the next level. I ended up having to change the template switch to describe exactly the correct combination of fan switches, to achieve the desired behavior. I also had to create template sensors to act as the buttons and use service calls to activate the actual switches in the ceiling fans. Here are the code examples. https://pastebin.com/GCrsZYP5
https://pastebin.com/m0jXhDXc

marble jackal
#

Wouldn't a template fan make more sense here?

mighty ledge
#

He wants buttons in the ui

#

But yes, it should be a template fan or select

fickle sand
#

Is there a way to check if a jinja variable is a list/array?
I can only find something for dicts/mappings

#

Nevermind, found a (nasty) workaround

{% if var is iterable and (var is not string and var is not mapping) %}
hushed bison
#

After deleting a template sensor from the configuration, how do I delete the entity fully in HA?

hushed bison
fickle sand
#

Time that jinja introduces some type filter or list test as are available in phyton

inner mesa
#

That could be you!

atomic blade
#

How do I strip newlines from my custom template macros?

#

As in trailing newlines that just seem to be inherently created

#

When this happens in a template in YAML or something I know to use the correct multiline block operand (|, >, etc), but I don't know what to do here

atomic blade
#

Think I got it working, but kinda annoying I need to do this for every block

#

I can't just do like

{% macro foo(bar) -%}
[...]
{%- endmacro %}
severe elbow
#

Hey everyone, first time trying to write template sensors of my own and I was wondering if it was possible to have a template sensor that returns an array of values instead of just a single value

inner mesa
#

sure, you can return any native type

severe elbow
#

I'm trying to create a sensor that maintains a list of the espresence devices that are currently detected in a room, I'm able to return the "count" of those devices right now, but I'd like to have the count and a list

lofty mason
#

I think the list part could be an attribute. states must be strings

inner mesa
#

you probably just remove "count" πŸ™‚

severe elbow
#
platform: template
    sensors:
      living_room_occupancy:
        friendly_name: "Living Room Occupancy"
        value_template: >
          {% set ns = namespace(occupancy=0) %}
          {%- for sensor in states.sensor %}
            {%- if 'distance' in sensor.attributes and sensor.state == 'living_room' %}
              {%- set ns.occupancy = ns.occupancy + 1 %}
            {%- endif %}
          {%- endfor %}
          {{ ns.occupancy }}
#

this is what I have now

inner mesa
#

well, yes, you can't return a type as the state, but you can in the attributes

#

so, you can have the state be the count and a list of devices in the attributes

#

that is unnecessarily complicated

severe elbow
#

ok attributes isn't something I've seen examples of before, looking at the docs

#

oh ok, so its an optional mapping of named key -> template values that the sensor can also store?

inner mesa
#

{{ states.sensor|selectattr('attributes', 'contains', 'distance')|selectattr('state', 'eq', 'living_room')|list|length }}

severe elbow
#

oh thats much cleaner

inner mesa
#

{{ states.sensor|selectattr('attributes', 'contains', 'distance')|selectattr('state', 'eq', 'living_room')|map(attribute='name')|list }}

#

choose somethign else if you don't want the name

severe elbow
#

so in that context, if i wanted to get the list of devices as an attribute, I'd just add an attributes object to the sensor and create a key like device_list and populate it with that template (without the length)

#

Got it

  - platform: template
    sensors:
      bedroom_occupancy_test:
        friendly_name: "Bedroom Occupancy Test"
        attribute_templates:
          device_list: >
                {{ states.sensor|selectattr('attributes', 'contains', 'distance')|selectattr('state', 'eq', 'bedroom')|list }}
        value_template: >
                {{ states.sensor|selectattr('attributes', 'contains', 'distance')|selectattr('state', 'eq', 'bedroom')|list|length }}
#

Ok, so right now now I get an array of <template> objects from that device_list. Would I have to do like a substring if I wanted to just get the friendly_name value if the list looks like this?

[<template TemplateState(<state sensor.drews_phone_bt=bedroom; distance=4.19, friendly_name=Drews Phone BT @ 2023-07-13T16:34:06.946459-07:00>)>, <template TemplateState(<state sensor.peppers_tag_bt=bedroom; distance=2.23, friendly_name=Peppers Tag BT @ 2023-07-13T16:38:38.553882-07:00>)>]```
inner mesa
#

you missed the map() part

severe elbow
#

Ok, so thats how you select a specific value to list - thank you!

restive socket
#

Could anyone help me figure out how to investigate available attributes for an entity. Specifically I am looking for if my tv is paused

atomic blade
restive socket
#

So all I have is off and on :/

#

That's disappointing

#

Is there an event bus or anything that might pick up on playing or paused?

inner mesa
#

You're welcome to put * in devtools -> Events and see. But it would probably be documented in whatever integration you're using

restive socket
#

I totally bought the wrong tv it seems 😦

atomic blade
#

If it's a samsung then from what I've heard, yes lol

restive socket
#

LG C2

#

I expected a bit more than on/off.......my cameras can send a toast when motion is detected, but I can't tell if it is paused

atomic blade
#

Can you short circuit (return) from a macro?

analog mulch
#

Hi, i'd like to return a list of entity_id's which have names containing some string, input_datetime.bla_*. Basically to generate a group by filtering by name

marble jackal
#

{{ states.input_datetime | selectattr('object_id', 'search', '^bla') | map(attribute='entity_id') | list }}

analog mulch
#

OK, now I understand how this works! thanks

#

And another one: can I use a template with a for loop inside variables to generate a list inside an automation to be used somewhere else in that automation, something like:

variables:
  mylist: >
    [
    {% for states in states.sensor %}
    {{state.entity_id if state.state|float > 10}}
    {%endfor%}
    ]

or would I need to generate it at the service call directly and i guess use some namespace variable?

marble jackal
#

you can define it in a variable, but you need to use a namespace there

#

not like you are doing now

#
variables:
  myList: >
    {% set ns = namespace(list=[]) %}
    {% for states in states.sensor %}
      {% if state.state | float(0) > 10 %}
        {% set ns.list = ns.list + [state.entity_id] %}
      {% endif %}
    {% endfor %}
    {{ ns.list }}
analog mulch
#

thanks again!

sonic ember
#

Either I screwed something up in my coding, or an integration changed and I didn't adapt, but I have a template sensor that's suddenly not working. It's a template that re-formats the Nordpool energy prices and adds the additional costs of my energy provider.

#

Anyone know if there was a change recently to the output of Nordpool that might be relevant?

mighty ledge
#

just post the source sensor states, thier entity_id's and your code

sonic ember
mighty ledge
#

Not sure how that ever worked

sonic ember
#

Haha, it worked flawlessly till yesterday

mighty ledge
#

as_local does not translate a datetime without it being a datetime first

#

So if the nordpool changed the datetimes from objects to strings, that might be what happened

#

anyways, to fix the times, change as_local to as_datetime

#

everything else looks fine

sonic ember
#

Lemme check and reboot...

mighty ledge
#

test it in template editor

#

you have 2 as_local btw

#

do both of them

sonic ember
#

Yeah saw them both.

mighty ledge
#

as an aside, @marble jackal made a template macro that does calculations with objects like that

#

and it can get all sorts of information out of it

sonic ember
#

Yeah, I installed his macro, very cool. But I don't think it enables me to plot my prices including the additional costs

#

This used to be used for all my energy costs calculations, but once I've tested the macro properly, I'll use that going forward for all the automations, and just use this for the graph and for my logging of costs.

sonic ember
# mighty ledge test it in template editor

Strange, I'm getting this error, but I don't see anywhere I'm trying to format a datetime as float??
TypeError: float() argument must be a string or a real number, not 'datetime.datetime'

mighty ledge
#

can you copy/paste this into the template editor and post the results here

#
{{ state_attr('sensor.energyprices','raw_today') }}
sonic ember
#

Truncated (just a repeating list)

[{'start': datetime.datetime(2023, 7, 14, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Amsterdam')), 'end': datetime.datetime(2023, 7, 14, 1, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Amsterdam')), 'value': 0.12221}, 
mighty ledge
#

the whole thing please

sonic ember
#

Sorry not repeating, but you know what I mean πŸ™‚

mighty ledge
#

I did that so I could use it

#

to test what's going wrong

#

but I do see what's going wrong I guess

#

so you don't need as_datetime at all. just

sonic ember
#

No worries, just wanted to skip the pastebin thing

mighty ledge
#

[hours.start.strftime("%Y-%m-%d %H:%M:%S")]

sonic ember
mighty ledge
#

no that's fine, try what I posted

#

they are datetimes

#

apparently

sonic ember
#

Ah, that looks better

#
sensor:
  - name: "NextEnergy Energy Prices"
    unique_id: 1565ac04-07a1-4a7f-bf09-af7ce93fd5ed
    icon: mdi:currency-eur
    unit_of_measurement: "EUR/kWh"
    state: >
      0.263498
    attributes:
      times: >
        ['2023-07-14 00:00:00', '2023-07-14 01:00:00', '2023-07-14 02:00:00', '2023-07-14 03:00:00', '2023-07-14 04:00:00', '2023-07-14 05:00:00', '2023-07-14 06:00:00', '2023-07-14 07:00:00', '2023-07-14 08:00:00', '2023-07-14 09:00:00', '2023-07-14 10:00:00', '2023-07-14 11:00:00', '2023-07-14 12:00:00', '2023-07-14 13:00:00', '2023-07-14 14:00:00', '2023-07-14 15:00:00', '2023-07-14 16:00:00', '2023-07-14 17:00:00', '2023-07-14 18:00:00', '2023-07-14 19:00:00', '2023-07-14 20:00:00', '2023-07-14 21:00:00', '2023-07-14 22:00:00', '2023-07-14 23:00:00']
      prices: >
        [0.29641, 0.290796, 0.276505, 0.268749, 0.271, 0.26495, 0.270915, 0.282374, 0.276989, 0.277135, 0.270649, 0.261078, 0.263498, 0.257932, 0.261538, 0.268217, 0.268035, 0.267249, 0.276929, 0.302399, 0.3073, 0.3073, 0.288823, 0.270625]
      average: >
        0.27697479166666666
mighty ledge
#

πŸ‘

sonic ember
#

Let's see if that works...

#

Still strange that it worked until today, I did HA update, but there was no Nordpool update

mighty ledge
#

Something made your attributes datetime objects

#

if you restart, are they strings?

sonic ember
#

You mean the ones from Nordpool, or my sensor?

#

Problem isn't resolved yet, so deeper down the rabbit hole we go

mighty ledge
#

nordpool

sonic ember
#

How do I see if they are objects or strings? Can I see that in the entity states?

mighty ledge
#

you can test it in the template editor by looking at the response from what I posted above

#

this

#

{{ state_attr('sensor.energyprices','raw_today') }}

sonic ember
#

Looks like they are datetimes I guess:

{'start': datetime.datetime(2023, 7, 14, 0, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Amsterdam')), 'end': datetime.datetime(2023, 7, 14, 1, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Amsterdam')), 'value': 0.12221},
#

Something is wrong. It works fine in the template editor, but not in my yaml. Let me look into that first.

mighty ledge
#

what are the errors in your logs at startup?

sonic ember
#

Nothing relevant in core.

#

I added a test attribute, and the entity isn't getting that either. So something is actually stopping the sensor from being updated. That might be my main problem that started all this. (in the mean time at least my code is better) πŸ™‚

mighty ledge
#

nothings stopping it from updating

#

it's most likely failing on startup

#

which means there's errors in your logs

#

outside that, that template will only update when the source sensor updates

sonic ember
#

Under system...log there's nothing. But I'll open the log manually and see what I find

sonic ember
#

Would it be in my core logs? I can't find anything relating to this sensor there. There's another one with a small issue, but it's not a related sensor in any way (it's an entity that's unavailable(

#

My core log has nothing related to template sensors. This is the only warning that's not related to "custom integrations":

2023-07-14 12:54:45.070 WARNING (MainThread) [homeassistant.helpers.script] Error in 'choose[1]' evaluation: In 'or' (item 1 of 2):
In 'and' (item 1 of 3):
In 'state':
In 'state' condition: unknown entity switch.floor_heating_socket
mighty ledge
#

HA naturally suppresses state changes

#

if they don't change

#

if your template sensor works, then it works regardless of reload if the information isn't changing

sonic ember
#

I think I've found the problem... This must have happened when I added the sensor for TheFes's script. My YAML syntax must be wrong somewhere, as it looks none of my sensors are updating, and the editor isn't catching the error.

mighty ledge
#

that makes no sense

marble jackal
#

FWIW, the Nordpool raw_tomorrow and raw_today attributes always had datetime objects. Not sure about the seperate attribute with only the list of datetimes as shown above, I never used that

mighty ledge
#

You'll get errors in your logs if things aren't working

sonic ember
marble jackal
#

Did you enter that sensor directly into your configuration.yaml, and did you maybe add a 2nd template: section by doing that?

mighty ledge
#

FYI I don't care if you ping me

#

so ping away

marble jackal
mighty ledge
#

tinkerer would love that

#

Make a bot that repsonds to tinkerers gif

#

with that gif

sonic ember
#

This is the line in my configuration.yaml:

template: !include templates.yaml

Then in my templates file I only have one template:

I do have a sensor: in my configuration.yaml, but it's not a template sensor.

#

Is tinkerer the only one that complains about the pinging? I thought it was a common thing. Personally, if you want my attention, ping me πŸ˜„

mighty ledge
#

tinkerer is one of the few that dislike it

#

there are others

sonic ember
#

Ah haha. Ok I'll try and remember that πŸ™‚

mighty ledge
#

it's just a person by person basis

#

if someone doesn't like it, don't do it

sonic ember
#

Agreed

mighty ledge
#

I do it to tink tho on purpose sometimes, don't be like me

sonic ember
#

We need a "noping" icon in the names πŸ™‚

mighty ledge
#

you can add a note in the persons name

#

it would also be great if you could just make a channel "not ping you"

#

on replies

sonic ember
#

Ok, so to test if things are "in general" working, I tried to create a sensor, maybe I'm being stupid, but since I'm not getting errors, I'm reaching now...

  - name: TEST Entity can be deleted
    unique_id: 873c87db-4db3-442f-a55b-6b6a1a0176d5
    state: MyTest
    attributes:
      test: "This is my test"
#

That should create something right? And it SHOULD add a state and an attribute?

mighty ledge
#

yes

marble jackal
#

assuming you placed in in this templates.yaml and it is indented the same as the existing one

sonic ember
#

Ok, so I did that. It creates the sensor. BUT, State: unknown. Only attribute is friendly_name and there is nothing in the core logs (debug level is warn)

marble jackal
#

ah

#

you placed it under the same sensor section as mine

#

which is a trigger based template sensor

#

add a seperate - sensor: line above it

#
- trigger:
  sensor: 
    - my sensor
- sensor:
    - your sensor
#

like this

sonic ember
#

Wait.. sensor after trigger doesn't have to be indented to be related?

#

Here's my templates.yaml (first lines)

marble jackal
#

the first sensor in my snippet is related to the trigger

#

ah this is why it's not working

sonic ember
#

Your sensor is nested the same way as my other sensors

marble jackal
#

you need to add hypens, template: expects a list

#

which will work if there is only one item, but not if you add a second

#
- binary_sensor:
- trigger:
  sensor:
#

it should be like this

sonic ember
#

Oh, maybe my other sensors in that file never worked then...

#

Ok lemme try

#

BOOM!

#

Thanks you two!

#

Learnt something new too!

#

And just on time, as I have to hop into a meeting. HA messes with your normal life!

mighty ledge
#

yes it does

#

I've gone home from work to fix my system before 🀣

tepid onyx
mighty ledge
#

I know you’ve been here before but you’re about to be removed if your account is Compromised

silent flicker
#

Is there a way to get the time a sensor last updated?

sensor.litter_robot_status_code

marble jackal
#

states.sensor.litter_robot_status_code.last_updated

silent flicker
#

ah thanks.

if i wanted to change that to be the duration of time since it last changed, would this work?

{{ (as_timestamp(now()) - as_timestamp(states.sensor.litter_robot_status_code.last_updated)) | timestamp_custom('%H:%M:%S', false) }}

marble jackal
#

Possibly, but this is shorter

#

{{ (now() - states.sensor.litter_robot_status_code.last_updated).total_seconds() | timestamp_custom('%H:%M:%S', false) }}

modest loom
#

Hi. After a little help on #automations-archived, I'm trying to template an entire dictionary entryβ€”that is, using a template to generate the key as well as the value. My ultimate goal is omitting it based on a condition. Assuming it's true that's possible, can someone help? For now I'm just trying to do the basic of creating a key/value pair that is fully templated, but no variation I can come up with will work. Here's one that works: - service: light.turn_on target: {} data_template: entity_id: "{{ entity_id }}" and one that doesn't: - service: light.turn_on target: {} data_template: '{{ "entity_id: " + entity_id }}'

#

Can someone point me in the right direction? The error I get for the second (and most variations I can think of) is Failed to call service script.light_flash. Error rendering data template: Result is not a Dictionary

#

script.light_flash is the script this code is in.

obtuse zephyr
#

That's because the second one is just a string... this should work if entity_id is in scope

        - service: light.turn_on
          target: {}
          data: >
            {{ dict(entity_id=entity_id) }}
modest loom
#

ty!

#

that's a start.

#

Actually, maybe you can jump me to the ultimate solution: what I want is that with an optional brightness pair. So if brightness is defined in scope, you get entity_id: {{entity_id}} and brightness: {{brightness}} and if not you just get entity_id: {{entity_id}} with no brightness key in the dictionary. I'm just using the jinja to indicate the values for you, I understand I might need to use dict(), etc.

#

(In the end, there are actually 3 variables I'd like to treat this way, so a complicated if/then is possible but not ideal?)

#

This seems to work: {{ dict(entity_id=entity_id, brightness=brightness) if brightness is defined else dict(entity_id=entity_id) }} but it does lead me down a complicated if/then rabbit-hole.

#

Is it possible to build the dict up with individual statements?

obtuse zephyr
#

Kind of ...

{% set input = dict(color=False) %}
{{ dict.from_keys([
  ('brightness', 100), 
  ('color_name', 'red' if input.color )
  ] | selectattr('1')) }}

Could play w/ something like that to assign values based on your input vars, if I'm understanding what you're looking for

cold pawn
#

Hi all - I'm trying to grab a name for a weather advisory in my error, I'd like to have a dashboard that displays the weather advisories in my area, I have "weatheralerts" integration installed, and I'm trying to pull out an attribute, I think I would use a template for this, but am not getting it working and it FEELS like it should be really simple... https://prnt.sc/5wCpHXuezbdi is a screenshot of what I'm TRYING to get, "see the event:" attribute... could someone let me know if i'm on the right track, is a template what I need? and how would I pull just the name of the event into a dashboard (state_attr I assume, but cant get it showing up on template editor

obtuse zephyr
#

What have you tried? state_attr('sensor.weatheralerts_1','event') should grab it

cold pawn
#

I tried that on the template editor just shows me null

#

A template is what i need, correct? Just making sure im barking up the correct tree

obtuse zephyr
#

It's definitely a way to grab a sensor's attribute

#

What does {{ states.sensor.weatheralerts_1.attributes }} show

modest loom
cold pawn
#

@obtuse zephyr it just shows the attributes in the same screenshot, just looks like all text

#

"event": "Heat Advisory",

obtuse zephyr
#

Then {{ state_attr('sensor.weatheralerts_1','event') }} should show that string

cold pawn
#

just shows null.

obtuse zephyr
#

Show a screenshot for the attributes output

cold pawn
obtuse zephyr
#

ah

#

Because alerts is the top level attribute

modest loom
#

LMK if you see any pitfalls there, but seems to work great. Thanks!! [Edit: fixed the code to use "is defined" to avoid warnings/be correct.]

#

It's a script so brightness/rgb_color/transition may or may not be set by the caller.

obtuse zephyr
#

Seems decent to me

cold pawn
#

Wahoo, you are a genius NSX, thank you... {{ state_attr('sensor.weatheralerts_1','alerts')[0]['event'] }}

inner mesa
#

You can also just slap JSON in there

#

YAML being a superset of JSON

#

Make the value of data: a JSON dict

cold pawn
#

LOL... I feel like im drinking water from a fire hose. πŸ™‚ So many rabbitholes to this! Took me longer than I want to admit to know what I was trying to do was a "template".

obtuse zephyr
#

Feel free to come back for more, there's plenty left πŸ˜‰

obtuse zephyr
inner mesa
#

pretty sure that each item can be a template

#

hmm

#

I know I've used it and seen it here to decide whether to add an optional key/value

#

like whether to specify brightness:

#

I don't know that it's any better than what you did, but this works:

service: persistent_notification.create
data: >-
  {
    "message": "I am a message",
    {{ '"title": "I am a title"' if false }}
  }
#

change "false" to "true" and you get a title

heavy island
#

What is the correct syntax to achieve what I want here:

          - service: input_number.set_value
            target:
              entity_id: input_number.kitchen_fan_speed_percent
            data:
              value: "{{ percentage }}"
          - service: |
            {% if percentage > 0 %}
              input_boolean.turn_on
            {% else %}
              input_boolean.turn_off
            data:
              entity_id: input_boolean.kitchen_fan_power```
inner mesa
#

You didn't say what you want

#

I mean...

heavy island
#

I want to turn on an input_boolean if the percentage is set to a non-0 value, off otherwise

inner mesa
#

Start with that next time πŸ™‚

#

You missed the endif

heavy island
#

oh yeah

inner mesa
#

> 0 isn't nonzero either

#

Although I guess it won't be negative

heavy island
#

it still doesn't pass the yaml check with the endif. "found character '%' that cannot start any token" on the first %

inner mesa
#

What did you do?

#

I also suggest >- instead of |

#

You should also indent the whole template by 2 more spaces

#

Or, just
service: input_boolean.turn_{{ 'on' if percentage != 0 else 'off' }}

heavy island
#

ah ha, it was the spaces.
and that second form is much nicer anyway. Thank you!

tired sandal
#

Quick question - I have a template sensor that is used to filter down existing state.

- sensor:
  - name: "Next Trash Holiday"
    state: "{{ state_attr('sensor.next_trash_holiday', 'fubar').date }}"
    attributes:
      fubar: >
        {% set today = utcnow().strftime('%Y-%m-%dT%H:%M:%S.%fZ') %}
        {{ state_attr('sensor.republic_trash_data', 'data')
          | selectattr('LOB', 'eq', 'Residential')
          | selectattr('serviceImpacted', '==', true)
          | selectattr('date', 'gt', today)
          | list
          | first
        }}
#

Is there a way to remap that template expression onto the attributes without having to nest it under a key like that?

marble jackal
#

Isn't today = utcnow().isoformat() the same but easier?

#

But you can't template the entire attributes section. You can make a single attribute and create a dictionary in that

simple tusk
#

I am currently building my Home Assistant dashboard. For this I would like to display certain states (e.g. Ubuntu server needs an update) via notifications.

For this I have successfully implemented a first state this morning. The coding works, but I think it can be implemented even better / cleaner.

- binary_sensor:
  - name: notification_os_system_update_available
    unique_id: notification_os_system_update_available
    icon: mdi:update
    state: |
      {% if (states('sensor.system_updates') | int(0)) > 0 %}
        on
      {% else %}
        off
      {% endif %} 

marble jackal
#

You don't need to let it return on or off

#

You can also replace the icon line with device_class: update that will also provide the right translations for the frontend

simple tusk
#

Thx for the suggestions, i will try it and read the docu again.. i looked into it yesterday.. and didnt see the point you mentioned

marble jackal
#

It's under binary_sensor and then state

The sensor is on if the template evaluates as True, yes, on, enable or a positive number. Any other value will render it as off. The actual appearance in the frontend (Open/Closed, Detected/Clear etc) depends on the sensor’s device_class value

#

The or a positive number part is especially relevant here

simple tusk
#

yeah i found it now.. i was blind or tired yesterday πŸ™‚

keen oriole
#

what am I doinmg wrong here? device_id: 1714a01422e13da8e7c5d165f4a91f76 domain: number entity_id: 5044fcc3e35d8de9cb00c7bd54c42622 type: set_value value: {{states('number.white_lightning_charging_amps') | float(0) -1}}

#

in an automation

radiant spindle
plain magnetBOT
#

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

radiant spindle
#

I'm not sure if I can do it without editing the custom:mushroom-entity-card, I'm newish to templating

fringe sail
haughty breach
#

I feel like I should know this already but.... is there a list of which functions and/or methods are supported in "Limited Templates" and which are not? Every time I read that section in the docs... πŸ˜•

#

Is it just that they don't have access to the state machine or is there something else?

floral shuttle
#

finally settled for: {{trigger.entity_id != 'device_tracker.synology_diskstation' or now() < today_at('22:45')}} note I had a typo on the trigger (entity instead of entity_id before, so it wouldn't process correctly in the first place...

fringe sail
#

Hey guys. How would I pull out how many of the fans in the group fan.fans is on? This gives me the list of the fans in the group.```

{{ state_attr('fan.fans', 'entity_id') }}```

floral shuttle
#
{{expand(state_attr('fan.fans','entity_id'))
  |map(attribute='state')
  |select('eq','on')|list|count}}
#

or {{state_attr('fan.fans','entity_id') |map('states') |select('eq','on')|list|count}}

#

and yo can always check that using smthng like: {% for f in expand(state_attr('fan.fans','entity_id')) %} {{f.entity_id}} : {{f.state}} {% endfor %}

fringe sail
#

Thanks for helping. The first one gave me a value of 10 and the second one gave me a value of 4 and 4 is correct. What is the first one counting?

#

First I'll explain that fan.fans is a group of fans, and each fan is a group of switches. It seems that the first one is counting the number of separate switches that are on, and two is counting the number of fan groups that are on. I can't tell why the difference in the two.

#

But thank you for solving my problem! πŸ™‚

marble jackal
marble jackal
wise sluice
#

hi i'm having a little trouble extracting info from a template sensor. I've got an input boolean that triggers when my son opens the bedroom door. from that i created the following template sensor:

- trigger: - platform: state entity_id: input_boolean.luke_s_door_notification_triggered to: 'on' sensor: - name: "Luke woke up at" state: "{{ now().timestamp() | timestamp_custom('%a %I:%M %p') }}"

but states.sensor.luke_woke_up_at gives me:
<template TemplateState(<state sensor.luke_woke_up_at=Sun 05:44 PM; friendly_name=Luke woke up at @ 2023-07-16T18:05:03.588421+08:00>)>

is there a way to have the state just be the date/time or make this an attribute so i can display it on template cards etc?

mighty ledge
#

Add .state at the end when outputting or use the states method instead

wise sluice
#

Thank you!

tired sandal
tired sandal
marble jackal
tired sandal
#

I see

sonic ember
#

@marble jackal so I just ran the sensor for the first time, and it looks great! I didn't input any no_weight_points, so I guess the macro decided by itself?

#

Very nice macro!

marble jackal
#

There is a default setting, I think it's one weight point per hour

#

It should be in the result

sonic ember
#

Yeah it's in the state if you check states, it's 4

#

Used it for the washing machine (which is much easier to estimate). Worked like a charm. Dishwasher I'll have to wait till the next time I run it, as I turned of HA during the last run (doing electrical work at home).

plain magnetBOT
#

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

tight adder
#

ok I've made a step to goal. I'm using in dev tools : {{ state_attr('weather.home', 'forecast')[0] }} which return : {'datetime': '2023-07-16T05:00:00+00:00', 'cloud_coverage': 56, 'precipitation_probability': 98, 'wind_bearing': 237, 'condition': 'lightning-rainy', 'temperature': 28.5, 'apparent_temperature': 28.9, 'templow': 16.5, 'wind_gust_speed': 25.9, 'wind_speed': 11.1, 'precipitation': 15.2} -> what I want. I've so created a template like this :
`- sensor:

  • name: forecast_d0
    state: >
    {{ state_attr('weather.home', 'forecast')[0] }}`
    but return unknown. Where am I wrong ?
inner mesa
#

Probably longer than 255 characters. Why do you want all that JSON in the state?

tight adder
#

'cause I don't know I should select result πŸ™‚ how can I do that ?

inner mesa
#

do what?

#

what did you want?

tight adder
#

select only some attributes. I thought it was your question

inner mesa
#

select which key?

#

you can select whatever you want. {{ state_attr('weather.home', 'forecast')[0].wind_speed }}, for instance

tight adder
#

you said : Why do you want all that JSON in the state?

inner mesa
#

I stand by that

#

having all that in the state doesn't make any sense

tight adder
#

I want to read it in esphome after with usiong the attribute paramter

#

in that way no need to create trhousand of sensor

inner mesa
#

you said "hi, i'd like to create 5 sensor for my forecast weather", which isn't thousands, but you just want all those keys in the attributes?

#

or do you really want 5 sensors?

tight adder
#

yes 5 for day one to five. If I follow you example, i will need to create 10 sensors per day

inner mesa
#
- sensor:
  - name: forecast_d0
    state: Whatever
    attributes:
      wind_speed: "{{ state_attr('weather.home', 'forecast')[0].wind_speed }}"
#

for instance

tight adder
#

mm intersting.. .let me try that thx

#

perfectly working. I thought I could directly get the array well formated for a sensor. But it's fine. Thanks you

still oar
#

Hmm, Im controlling my house ventilation via modbus. The unit has different modes: eco, comfort, forced, forced-timer and off (never used). Right now Im using modbus switches. So one switch for every mode. Problem with that is that they aren't syncronized. So I can turn on both the eco and the comfort switch at the same time. So HA thinks both switches are on. But its the latest switch command that is the one that is used.

Any good way of solving this? input_select, but unsure on how to sync the normal switches so I always get the correct mode in HA. I have a modbus sensor that reports the current mode.

haughty breach
plain magnetBOT
#

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

marble jackal
#

@cursive ice you trying to convert the entire state object to a number, instead of just the state

#

And that will give an error for the float filter

#

You can also simply do this
{{ states('sensor.tronity_megane_e_tech_level') | round(-1, 'ceil', 0) | int }}

floral shuttle
#

trying to cut down on the expands in my templates Im seeking to moves those to custom_templates. In stuck though. Please see this jinja template

#

I have this in my custom_templates:{%- macro deuren() -%} {{- expand('binary_sensor.deuren') |rejectattr('state','in',['unknown','unavailable']) |map(attribute='entity_id')|join(',') -}} {%- endmacro -%} but all I can do is see the list of entity_ids, and can not manipulate them, other than count {% from 'samenvatting.jinja' import deuren %} {{deuren().split(',')|count}}

cursive ice
floral shuttle
#

ofc, I want to check the open/closed doors, so need the state, and last_changed of those, etc etc, And can not find a way to do so, other than expanding that again.... which make the whole move to custom_templates moot

cursive ice
marble jackal
floral shuttle
#

I can do this btw```

{% from 'samenvatting.jinja' import deuren %}
{% for s in deuren().split(',')|reject('eq','') if states(s) == 'on'%}
{{state_attr(s,'friendly_name')}}: {{states[s].last_changed.strftime('%D %X')}}
{% endfor %}``` ...

floral shuttle
#

so for now I would be very happy if I could simply select the doors that are 'on', and not have to build a for loop for that

forest stirrup
#

Why are these two time values not the same?

{{ as_timestamp(now()) | timestamp_custom("%H:%M:%S", false) == as_timestamp(now()) | timestamp_custom("%H:%M:%S", true)}}

07:13:00+0000 = 09:13:00+0200
False```
marble jackal
forest stirrup
marble jackal
#

They would be the same if you would not covert them to string

#

Yes, but you are doing a string comparison, and they are two different strings

marble jackal
#

Output:
light.booglamp,light.eettafel_template

floral shuttle
#

ooh that is nice indeed, and yes, that would save a lot of expands...I will start a rebuild with that, and have the most generic aspects of my package adapted.

marble jackal
#

In a macro? You could create a separate one, but if you want to output two values out of one state object, you'll always need a for loop

floral shuttle
#

no, sorry, I meant to have that {%- macro deuren() -%} {{- expand('binary_sensor.deuren') |rejectattr('state','in',['unknown','unavailable']) |map(attribute='entity_id')|join(',') -}} {%- endmacro -%} macro and then select the entity_id's that are 'on' in the yaml template directly

#

btw, first iteration of your macro: {%- macro samenvatting(group, operator, states, output) -%} {{- expand(group) | selectattr('state', operator, states) | map(attribute=output)|join(',') -}} {%- endmacro -%} πŸ˜‰

forest stirrup
#

How do I convert input_datetime from a string to time?

marble jackal
forest stirrup
#

Time only

marble jackal
#

today_at(states('input_datetime.foo'))

#

That will be a timezone aware datetime object with the date of today and the time from your input_datetime

forest stirrup
#

Thank you very much.

{{ states('input_datetime.geyser_1_morning_start') }}
{{ today_at(states('input_datetime.geyser_1_morning_start')) }}
{{ now() > today_at(states('input_datetime.geyser_1_morning_start')) }}

2023-07-17 09:59:00.277443+02:00
09:40:00
2023-07-17 09:40:00+02:00
True```
sturdy yarrow
#

Hello all,
I am trying to get the first time a state changes in a lightning sensor.
But the problem is that when a lightning strikes the value can jump from 0-5
so I can't use {% if lightningCount == 1%}. And I guess if I use > 0 this
will update every time a new lightning strikes too? So how can I get it to
only update the current time the first strike lands? Also, this is on a meter
which restarts every day at 00:00

marble jackal
#

How do you want to use this? And where does the value for lighting Count come from

sturdy yarrow
#

I have a meter that tells me how many lightning strikes we have had in the last 24 hours. The sensor I made gives me a count on how many stirkes we have had the last 24 hours. But I would like to add "between XX:XX and XX:XX" the last one is easy as I could use last_changed but the first one is a bit more tricky. I am using a custom sensor for the ligning count, but the data comes from the blitzortung integrations

marble jackal
#

But should this be a trigger, or another template sensor or what? Explain what your goal is

forest stirrup
#

How do I display {{ now() }} without the milliseconds but not convert it to string.
from 2023-07-17 10:20:00.084727+02:00 to 2023-07-17 10:20:00+02:00

sturdy yarrow
#

Oh, I have made a custom sensor that shows the text "No lightnings today" or "X ligtning strikes today" this is just for information. And what I am trying to do is to also add "between XX:XX and XX:XX"

sturdy yarrow
plain magnetBOT
#

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

analog mulch
#

Hi. I have written a script which contains a few wait_for_triggers. Those are templates which involve a variable which is itself based on an entity_id supplied in the field of the script. Schematically

- vacuum_segment_by_segment:
    alias: "Cleaning: Vacuum segment cleaning automation"
    mode: queued
    fields:
      entity_id:
        default: "vacuum.mr_bobot"
    variables:
      vacuum_state: "{{'sensor.'+entity_id.split('.')[1]+'_state_protected'}}"
#

The trigger itself is:

- wait_for_trigger:
    - platform: template
      value_template: "{{is_state(vacuum_state,'cleaning')}}"

This seems fine when I reload my scripts. But then, even though the script is not running, I begin to get errors in the logs that Template variable error: 'vacuum_state' is undefined when rendering '{{is_state(vacuum_state,'cleaning')}}' and similar. Is this to be expected? Do I have to put in an explicit entity_id in any wait_for_trigger even though the script is not running?

crimson lichen
#

Hi,
How to creat the template sensor with trigger for write state to txt file.
I tried but not success
Included templates.yaml

  • trigger:
    • platform: time
      at: "23:59:30"
      sensor:
    • platform: file
      name: Temperature
      file_path: /config/www/sensor.txt
      value_template: "{{ now().month }}.{{now().day}} : {{states('sensor.tongou_t3_summation_delivered')}}"
      unit_of_measurement: "kWh"
plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

marsh cairn
#

What exactly are you trying to do? Meaning - what exactly is this supposed to do and when?

#

And temperature with the unit kWh itself sounds... wrong

mighty ledge
#

I.e. Create a command_line command via the command integration, and use that in an automation that has a trigger at 23:59:30 that runs the command.

mighty ledge
analog mulch
#

I have a couple of automations which call it, but they have not been triggered today. The script itself has not been run since yesterday. Yet iin my log I have a regulal:

Logger: homeassistant.helpers.template
Source: helpers/template.py:563
First occurred: 12:45:29 (6 occurrences)
Last logged: 12:45:29

Template variable error: 'vacuum_state' is undefined when rendering '{{is_state(vacuum_state,'cleaning')}}'
Template variable error: 'vacuum_state' is undefined when rendering '{{(is_state(vacuum_state,'returning') and state_attr(entity_id,'battery_level')|float(75) > 20) or (is_state(vacuum_state,'docked') and state_attr(entity_id,'battery_level')|float(75) > 50)}}'
#

This script it referenced by the Xiaomi Vaccum Map card, but I haven't touched it to start the vacuuming

mighty ledge
analog mulch
#

No

#

I am not touching at all

mighty ledge
#

that doesn't make any sense

#

it would have to be running for that

#

and in all circumstances, that would be populated if you ran it properly

analog mulch
#

Could it be some old instance of the script still running?

mighty ledge
#

did you press run actions when testing in the past? it is set to queued

analog mulch
#

No I've never run it directly (only through the vacuum card, which has all the fields populated. I've also only added the {{vacuum_state}} variable today, so unless it updated a queued instance with the latest version of the script it shouldn't be referencing these in the logs

#

I presume that even if a script is running, and I change it and reload, it will get canceleld?

mighty ledge
#

I would assume running ones are untouched, but I've never looked into that.

analog mulch
#

I will reboot my HA see if it goes away

#

hmm, so far no such errors -- is there some proper way to stop running scripts which may have got into an infinite loop? I presume something like this happened. I am still trying to debug this.

mighty ledge
#

turn off the script

analog mulch
#

still no errors after the reboot. I guess it was old instances which were in the queue from yesterday trying to run as the updated script. THanks for the pointer!

mighty ledge
#

np

marble jackal
final lark
#

Hi everyone,
I'm trying to collect 2 values into one template sensor. Is it possible ? I would like one extra attribute to save the value from another sensor because I will need this value on my actual template

#

this is link to this information in templates ?

attributes map (optional)
 Defines templates for attributes of the sensor.
    attribute: template template REQUIRED
    The attribute and corresponding template.
#

does it mean that I have one template for the attribute and one template for the state ?

floral shuttle
#

concocted this while the thunder is counting {% set period = states('input_number.lightning_strikes_period')|float %} {% from 'lightning.jinja' import strikes %} {%- for s in strikes().split(',')|reject('eq','') if states[s].last_updated > now() - timedelta(hours=period) -%} {% if loop.last %}{{loop.length}}{% endif %} {%- endfor %} and it works alright, but had hoped to do without the for loop like {% set km = states('input_number.lightning_strikes_near')|int %} {% from 'lightning.jinja' import strikes %} {{(strikes().split(',')|reject('eq','') |map('states') |map('int',default=0) |select('<', km ) |list|count)}}

#

can we 'map' that last_updated?

#

so it would be (pseudo_code) {{(strikes().split(',')|reject('eq','') |map('last_updated') |select('>', now() - timedelta(hours=period) ) |list|count)}}

floral shuttle
#

this works also {{expand(strikes().split(',')) |selectattr('last_updated', '>', now() - timedelta(hours=period)) |list|count}} but it makes the custom_template moot, as I need to expand it again..

final lark
#

If any of sensor present in the state statement of a template sensor, an update will be triggered. right ?
now it's the same into the attribute statement ?
if I want to keep in attribute - previous_val = state of the template sensor

#

this will loop ???

inner mesa
#

you would want to use a trigger

final lark
#

that's is where I want to go , ok sound good but now I don't know how to transfer that value

#

can I use variable in trigger and this variable can be used after in the state template statement ?

#

any example is welcome

#

or I'm too much complicated and I just need to test via {% set var = previousvalue %} then used in the state afterwards

inner mesa
#
template:
- trigger:
    - platform: state
      entity_id: input_number.test
  sensor:
  - name: Keep Last
    state: "{{ states('input_number.test') }}"
    attributes:
      previous: "{{ trigger.from_state.state }}"
final lark
#

previous value seems to be under trigger.from_state
But in my configuration.yaml I have : template: !include templates.yaml
and in templates.yaml , it's start with - sensor:

#

if I add - trigger , it will be for all the sensors ?

inner mesa
#

no

#

only the ones under that

final lark
#

ouf ok πŸ™‚

inner mesa
#

from the docs:

# Example configuration.yaml entry with two sections
template:
  # Define state-based template entities
  - sensor:
      ...
  - binary_sensor:
      ...

  # Define trigger-based template entities
  - trigger:
      ...
    sensor:
      ...
    binary_sensor:
      ...
final lark
#

ok perfect πŸ™‚

#

thank you for your help @inner mesa very appreciated

#

so basically ,in my templates.yaml

- trigger:
  some code
- sensor:
   my sensor that need a trigger
- trigger:
(empty)
- sensor:
ma actual lists of sensors which don't need trigger (event state) 
#

right ?

#

seems passing the validation at least πŸ˜‰

mighty ledge
#

sorry, hit enter too quick

#
- trigger:
  - some yaml
  sensor:
  - name: my sensor that need a trigger
#

notice how sensor: doesn't have a -

final lark
#

my templates.yaml start with
- sensor:

#

and then all sensors

#

but now I'm confused with what you mention petro

inner mesa
#

see the example from the docs that I posted above

#

it shows the format

final lark
#

some yaml = files ?

inner mesa
#

that + the code I provided above

mighty ledge
#

no, you wrote some code, i corrected it to some yaml because yaml isn't code

#

but that wasn't the point of what I posted

#

the point was that the dash was on trigger and sensor did not have a dash

final lark
#

ah ok , first is the sensor without trigger !

#

I didn't see that first time

inner mesa
#

in the example from the docs, yes

mighty ledge
#

a template sensor that just updates when it's sources update is simply:

- sensor:
  - name: ...
#

a sensor that updates when a trigger is fired is simply:

- trigger:
  ...
  sensor:
  - name: ...
final lark
#

sources is any sensors in the state part

inner mesa
#

any entities

final lark
#

any entities , so any update events coming , ohh

inner mesa
#

you can stick the template in devtools -> Templates and it will tell you what it's monitoring

mighty ledge
final lark
#

performance wise ... I'm questionning because I was thinking my source for instance is every 5min , there is an event for that template. but if it's going each time there is an update event !

#

then it's all seconds

mighty ledge
#

i'm not sure you understand still

#

if you have a template "{{ states('sensor.abc') }}" inside a template sensor, then it will only update when 'sensor.abc' updates

#

if you use a trigger, that exact same template sensor will only update when the trigger fires

final lark
#

this is what I was understood

#

but for me it's not all entities then just entities that are used inside template

#

ok πŸ™‚

#

trigger is the only way to get previous value , so for my usecase here, it's what I need πŸ™‚

mighty ledge
#

you can get the previous state from this.state

inner mesa
#

that doesn't work

#

it gives you the current state

mighty ledge
#

that's the previous state when the template runs

inner mesa
#

it does not

#

I tried it

mighty ledge
#

in attributes it does not

inner mesa
#

correct

#

in the case the OP wanted

final lark
#

in state yes ?

mighty ledge
#

in value_template or state, it's the previous state as you're currently calculating the next state

inner mesa
#

as soon as you chagne it, it's new

mighty ledge
inner mesa
#

they wanted an attribute with the previous state

mighty ledge
#

ah ok

final lark
#

but if it's not in attribute , it's ok for me

inner mesa
#

I thought that it always represented the previous state object, but it's dynamic

final lark
#

I just need the previous value and I found may be attribute is the key

mighty ledge
inner mesa
#

it doesn't make sense to put it anywhere else (i.e., the state)

mighty ledge
#

right, it does not

#

but people do it πŸ€·β€β™‚οΈ

inner mesa
#

I kinda wish this was an unchanging version of the previous state object

#

the fact that you can reference new values is interesting, but confusing

mighty ledge
#

it was, but a certain somebody wanted to not recalc the state

inner mesa
#

it then depends on the order in which attributes are defined

#

which is weird

mighty ledge
#

yes, the whole thing is weird

#

you have to know the order of resolution with the current method

#

which is availability -> state -> everything else

inner mesa
#

yeah

mighty ledge
#

and don't even start with attribute order

#

that's async

#

so it's the wild wild west

final lark
#

I tried to do something for my consumption . I have the absolute value of a energy counter.

  1. first template to remove some negative part during night via template (there is no injection at night possible)
    2.filter that template (remove peak and bad reading from the ocr)
  2. ongoing : find a way to have return to grid (when the filtered sensor is going down ) and same opposite , when the sensor is growing, it means it's consumption
mighty ledge
#

personally, I hate how HA allows total increasing sensors

#

all it does is create these problems

#

if you can somehow get your energy as a non-total-increasing value, you'll completely remove all chances of having the oddball giant negative consumption

#

All the devices I own have the option of providing total increasing or momentary measurement

final lark
#

I use the camera reading ai-edge from Jomjol

mighty ledge
#

to read the number?

final lark
#

yes

mighty ledge
#

oof

#

ok

#

does it reset at midnight?

#

or, more importantly, do you know when it resets?

final lark
#

never reset

mighty ledge
#

so it just counts up forever?

final lark
#

yes , it represent the value on the counter

mighty ledge
#

then it shouldn't go negative ever

final lark
#

that's fine. I like to know that value because every year , they ask the number to have year annual cost balance

#

When sun is shining, it goes it the reverse way

#

if I don't consume all

weak fog
#

Help with template sensor for registering blade timer from Landroid robot mower

next elm
#

Having a weird issue with a template being ignored when used as part of a vacuum parameter.
This works:
- repeat: 2But this template, which evaluates to 2, gets ignored:
- repeat: "{{ states.input_select.vacuum_repeats.state }}"I've already tried adding |string and |int, but that made no difference.

marble jackal
#
- repeat:
    count: "{{ template }}"
next elm
#

No colon after repeat?

marble jackal
#

Sorry, added it now

next elm
#

I'll give that a shot. I'm curious why count is required only when using a template, though.

marble jackal
next elm
#

It's how the documentation for the vacuum integration says to do it: service: vacuum.send_command data: command: app_segment_clean params: - segments: - 17 - repeat: "{{ states.input_select.vacuum_repeats.state }}" target: entity_id: vacuum.moira

#

You're the first person I've seen suggest adding count: πŸ€·β€β™€οΈ

#

Yeah, no mention of count:

marble jackal
#

Ah, that's something totally different

#

I missed the vacuum part, I thought you were creating a repeat action

next elm
#

No worries, lol

#

But yeah, still can't seem to get it to work with a template, only with an actual number shoved in there

marble jackal
#

It expects a number, you're feeding it a string

#

As all states are strings

next elm
#

Like I said, i tried adding |int to the template. No difference.

#

{{ states.input_select.vacuum_repeats.state | int }} gets ignored just the same.

#

Even though it does spit out an int

marble jackal
#

I would advice to use {{ states('input_select.vacuum_repeats') | int }}

next elm
#

I mean, sure, but that also spits out the same integer of 2

#

So I'm not sure it'll fix anything

marble jackal
#

Yeah, it will not help, it was more of a sidenote

plain magnetBOT
marble jackal
#

Do you have this in an automation?

bronze prawn
#

I'm trying to generate a max wind gust sensor. Unforunately every comparison is true despite the values being different. Can someone spot where I am going wrong?

next elm
#

In a script

marble jackal
#

What does the trace show for that service call?

marble jackal
#

You are using a different one in the service call

next elm
marble jackal
#

It will show in the trace of it used the repeat setting and with which number

next elm
#

The result clearly shows - repeat: 2 for the template {{ states.input_select.vacuum_repeats.state }}

#

So it evaluated it and sent it, but it didn't work

marble jackal
#

If it shows 2 there, the issue is in the integration

bronze prawn
#

Another one of those 'doh' moments. Thanks for picking up on the obvious goof. I think it'll work now! πŸ™‚

next elm
#

Is it? Because when I put a "2" there instead of a template, the vacuum hits all specified segments twice...

marble jackal
#

Well, the template is correct, the result of the service call is as expected

hushed bison
#

{{ state_attr('sensor.zaptec_charger_zap1234', 'total_charge_power_session') | round(0) }} generate errors when the attr is None (not sure if its py None or string "None"). How can I ensure this doesn't fail in this case?

marble jackal
#

What if you run it from devtools > services with the template?

next elm
#

Same result from there. With a number it works, with the template it only runs once

marble jackal
#

Or an availability template to your template sensor if that's where you are using it

marble jackal
hushed bison
#

Yes, its a template sensor, as this integration puts a lot of valuable data as attributes. But sometimes the data is missing (but not the entity with the attrs).

marble jackal
#

Okay, well then I would advice the availability template

#

But I'm really putting my phone down now πŸ™‚

#

Time for bed

hushed bison
tired sandal
#

I'm trying to subtract 1 from a given date. What am I dong wrong here?

{{ state_attr('calendar.trash_schedule', 'start_time') | as_timestamp | timestamp_local - timedelta(days=1) }}

That raises:
TypeError: unsupported operand type(s) for -: 'str' and 'datetime.timedelta'

Which I understand to mean that you cannot do datetime math on a string. The problem however is how one should go about converting that datetime string to a datetime object and/or the correct way to do this ^

#

the value right now is: 2023-07-18 00:00:00 - I'm trying to subtract 1 day from that

inner mesa
#

Try removing the |as_datetime|as_local

#

Oh, you wanted as_local, not timestamp_local

tired sandal
#

So...

{{ state_attr('calendar.trash_schedule', 'start_time') | timedelta(days=1) }}

?

inner mesa
tired sandal
#
{{ state_attr('calendar.trash_schedule', 'start_time') | as_local }}

AttributeError: 'str' object has no attribute 'tzinfo'

inner mesa
#

|as_datetime|as_local

#

Sorry, not I'm not reading so well on my phone

tired sandal
#

boom, there it is!

#

no that's okay

#

btw, how do you know about those filters? I'm assuming they're a HA thing, but I can't find a clear page of filters like that

inner mesa
#

In the channel topic

#

Second link

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

tired sandal
#

awesome thanks!

tired sandal
#

Can these two timestamps be reliably compared?

2023-07-18 22:53:16.508170-04:00
2023-09-03 20:00:00-04:00
#

the first one is basically today plus 1 day, the second is the start of the next event from calendar.

#

I want to reliably evaluate if they're equal. Setting the time of the first one to "00:00:00" would probably help, but I'm not sure how to do that

inner mesa
#

Yes, they can be compared. Does it not work?

tired sandal
#

It didn't, until I did .replace(hour=00, minute=00, second=00, microsecond=00).isoformat()

#

Basically, I have a regular trash pickup day stored in calendar but my trash company also publish a JSON feed of the holidays they observe that interrupt service.

I'm tying to mash the two up so that the night before a scheduled trash pickup I get a reminder that tells me if the trash is coming or not and (optionally) a reminder before the rain date (usually the next day, but not always if it falls across a weekend) to remind me too

#

So my regular trash day is a Tuesday, that means I'd want the reminder on the Monday night at 7pm to tell me to put the trash cans out. However, perhaps the 4th of July falls on a Monday one year so they delay the pickup by a day....in that instance, I'd want the reminder the night before that day as well

inner mesa
#
{% set date1 = "2023-07-18 22:53:16.508170-04:00"|as_datetime %}
{% set date2 = "2023-09-03 20:00:00-04:00"|as_datetime %}
{{ date1 < date2 }}
{{ date2 < date1 }}

->

True
False
tired sandal
#

I realize this is starting to stray into the territory of #automations-archived but I'm hoping that explaining what I'm trying to accomplish might provide more insight into what I'm doing

tired sandal
#

idk. date math makes my head hurt

inner mesa
#

you can remove the times like you did if you want, but they're comparable

tired sandal
#

cool thx

inner mesa
#

if you just care about the dates, you can just do .date()

#
{% set date1 = "2023-07-18 22:53:16.508170-04:00"|as_datetime %}
{% set date2 = "2023-09-03 20:00:00-04:00"|as_datetime %}
{% set just_date1 = date1.date() %}
{% set just_date2 = date2.date() %}
{{ just_date1 < just_date2 }}
{{ just_date2 < just_date1 }}
tired sandal
#

oh neat!

#

didn't know that, thanks!

tepid onyx
#

{% set today = now().strftime('%Y-%m-%d') | as_timestamp | int(0) %} {% set filter_changed = state_attr('input_datetime.filter_changed', 'timestamp') | int(0) %} {{ ( today >= filter_changed + 7890000 ) and states('sensor.time') == '07:00' }}

Does that mean I can do things like input_datetime.filter_changed.date to simplify things a bit?

marble jackal
#
{% set filter_changed = as_datetime(states('input_datetime.filter_changed')).date() %} 
{{ today >= filter_changed + timedelta(seconds=789000) }}
#

And why 789000 seconds?

winter badge
#

Hopefully someone can help me with the following. I got the below template made. But i want to remove one decimal from the 2 last sensors.
HomeTemps: {{ states('sensor.temperature', with_unit=True) }}|{{ states('sensor.atc_3ae6_temperature', with_unit=True) }}|{{ states('sensor.atc_35bb_temperature', with_unit=True) }}

This now desplays the following.
HomeTemps: 25.5 Β°C|25.7 Β°C|25.52 Β°C

pastel moon
#

try in dev-tools if it does what you need

marsh cairn
marble jackal
#

The suggestion from Jorg only works if you set the precision in the entity settings

#

It's not so clear in the docs, but you can see it in the result from the example (and that in the next example they specifically set it it to false)

#

So @winter badge should set the precision to 1 decimal πŸ™‚

marsh cairn
tepid onyx
marble jackal
#

you could do timedalta(days=91) or something similar

#

There is no months option in timedelta, and adding months is complicated. If you just add 3 months to 31st of June by replacing the month value in the datetime, you will get 31st of September, which doesn't exist

floral shuttle
#

talking about those dates/months, I am using this to check if its a yearly event day: {% from 'feestdata.jinja' import vj_marijn %} {% set event = vj_marijn %} {{now().strftime('%m-%d') == event.strftime('%m-%d')}} It was the shortest way I could find to evaluate other than hard writing the actual '07-18'. could it still be optimized?

marble jackal
#

maybe now().date() == event.replace(year=now().year).date()

#

not really shorter

floral shuttle
#

yeah I had the replacer when I started, then found the .date() , added the .strftime() to that, only to find I didnt need the .date() for that in the first place... πŸ˜‰

marble jackal
#

or {{ now().day == event.day and now().month == event.month }}

floral shuttle
#

right!, splitting them can be useful indeed, I'll add that to the options! Using something like that in my counter already: {% from 'feestdata.jinja' import vj_marijn %} {% set event = vj_marijn %} {% set year = 1 if event.month < now().month or (event.month == now().month and event.day < now().day) else 0 %} {% from 'easy_time.jinja' import count_the_days %} {{count_the_days(event.replace(year=now().year + year)) }}

winter badge
pastel moon
marble jackal
#

in the entity settings in the gui

pastel moon
#

Ah, thanks πŸ™‚

marble jackal
pastel moon
#

It is per device then I suppose, can it be set at system-level as well?

marble jackal
#

It's per entity

plain magnetBOT
#

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

undone jungle
#

Where would I go about confining the output to a 0-100% range in this case

#

I've come across the example to put a [output, 100] | min term in, but that would probably not work here.

tepid onyx
#

i ilke the timedelta much easier

marble jackal
tepid onyx
#

I've modified the jinja to use timedelta, cheers

#

is that part of jinja templates or home assistant templates? Is there a doco page with a list of functions/methods for HA

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

marble jackal
#

2nd link has a lot of time examples

tepid onyx
#

Beauty πŸ‘

digital tree
#

hi. new to home assistant. i am trying to find a way the lights of speceific room that are (on) to be able as a group to change color or brightness. i have a template that finds the lights that are on, for those lights to control brightness and color.

{{ states.light | selectattr('state', 'eq', 'on')
       | map(attribute='entity_id') | map('area_name')
       | select('in', ['Office', 'Kids Room', 'Bedroom', 'Living Room'])
       | list | count }}```
marble jackal
#

This template will give a count, not the entity_id's

#

And do all lights in those area's support brightness and color changes?

marble jackal
#

([ 0, output, 100] | sort)[1]

undone jungle
#

Since the particular calculation goes something like that {{ (((t2 - t1) / (t3 - t1)) * 100|float) | round(2, default=0) }}
it would then change to {{ ([ 0, (((t2 - t1) / (t3 - t1)) * 100|float) | round(2, default=0), 100]) | sort)[1] }}

#

I guess I could simplify the default=0?

marble jackal
#

I would do:

{% set output = (((t2 - t1) / (t3 - t1)) * 100|float) | round(2, default=0)  %}
{{ ([ 0, output, 100] | sort)[1] }}
#

the default in your round filter can be removed, if one of those variables is not a number it will error way before it gets to the round

plain magnetBOT
undone jungle
#

In other words the whole template would look like that

#

Just that I could drop the default later as well

marble jackal
#

I would add the temperature sensors to the availability template

digital tree
#

No all the lights are not the same

#

with this i can fix a button that every time you press increase the brightness

#

sequence:
- variables:
lights_on: >
{{ expand(area_entities('Living room') | select('match', 'light'))
| selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}
- condition: "{{ lights_on | count > 0 }}"
- service: light.turn_on
target:
entity_id: '{{ lights_on }}'
data:
brightness_step_pct: 10

plain magnetBOT
#

@digital tree To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

undone jungle
marble jackal
marble jackal
undone jungle
marble jackal
undone jungle
#

I know there were some changes recently with states

marble jackal
#

you want it be a number

#

there is has_value

undone jungle
marble jackal
#

you could use that as well, but as you want it to be a numeric value, I would use is_number

marble jackal
undone jungle
#

Just realized I have a bunch of these statements in other templates, which you may have very well recommened to me a long time ago. Sorry for being thick! states('sensor.electricity_meter_power_active_phase_3') | is_number

marble jackal
# digital tree sequence: - variables: lights_on: > {{ expand(area_entitie...
    - variables:
        lights_on: >
          {{
            expand(area_entities('Living room'))
              | selectattr('domain', 'eq', 'light')
              | selectattr('attributes.brightness', 'defined')
              | map(attribute='entity_id')
              | list
          }}
    - condition: "{{ lights_on | count > 0 }}"
    - service: light.turn_on
      target:
        entity_id: '{{ lights_on }}'
      data:
        brightness_step_pct: 10
#

I would do something like this

undone jungle
marble jackal
#

oh, wait

#

yes, thats valid

#

I was to focussed on filters

#

of course the function is_state() is valid

undone jungle
#

Happens to me all the time!

#

Thanks for the clarification.

marble jackal
#

but also there you could use 'binary_sensor.ventilation_bypass' | has_value

undone jungle
#

Many ways to skin the cat.

marble jackal
#

note that you need to use that on the entity_id directly, not on the state

undone jungle
#

Right, so it's checking if the entity has the value, as opposed to determining the nature of the state the entity has

#

And I assume logically that unavailable or unknown are not values, but anything else e.g. on/off/number/int/float/ would be considered available?

digital tree
undone jungle
#

You may find I left one is_state for the main on/off switch check, since I want the sensor to become unavailable when the HVAC is OFF

marble jackal
#

No, this won't work

#

either
states('sensor.sensor1') | is_number and state('sensor.sensor2') | is_number and state('sensor.sensor2') | is_number
or something like
[ 'sensor.sensor1', 'sensor.sensor2', 'sensor.sensor3' ] | map('states') | reject('is_number') | list | count == 0

pastel moon
#

Hi, I have a sensor like this https://dpaste.org/SgGof. Can I read the mapping values from a script or automation somehow? Or can this be modified to allow that of not?

#

This line should have been in the example as well, these are the values I want to read out; "cloudy": {"low":65,"high":85},

mighty ledge
pastel moon
#

Ah, was afraid of that. I wanted to present what thresholds the sensor was setting pending the weather. So what you suggest is interesting. I will see if I can get that to work, thanks πŸ™‚

undone jungle
plain magnetBOT
#

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

mighty ledge
#

@sonic night you'll most likely have to create sensors from each of those values and rebuild the json, unless the json allows you to just send the single temperature.

#

TBH, I would assume the command topic would allow things like that, but it's your device that would make/break that functionality

plain magnetBOT
#

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

mighty ledge
#

Then you should make 8 separate sensors, 1 for each value in 24hrs. Then you have to manually create the json pulling the values from each sensor

#

the select will use value | int for the current select it resides in

pastel moon
#

Hi, trying to create a macro so I can also get the values from it (not there yet) but is this on the right track? https://dpaste.org/WObJG

inner mesa
#

Looks mostly okay to me. The naming of "weather_state" is little confusing, since the code expects an entity_id. I also don't see default_highlow defined anywhere.

mighty ledge
#

It’s a static dictionary, you can just set it to a variable and import the variable (after doing what rob said)

inner mesa
#

actually, it looks like you're trying to compare an integer to the strings "lux_low" and "lux_high"

#

is the assumption that the high value of default_highlow will be 0 or non-zero?

pastel moon
#

Well, I am trying to convert a working sensor into this instead, and yes, I expect mishaps... πŸ™‚

#

Basically

inner mesa
#

I'm trying to understand the logic, and not really succeeding

pastel moon
#

what I want it to do is to take the current weatherstate (cloudy) and then look that up in the map, then based on it being more or less than the value for "high",return either "lux_low" or "lux_high"

inner mesa
#

oh, you probably wanted to move the right-paren in teh final test

#

you want this whole thing to be the test result that's passed into iif()?
(states('sensor.avg_illuminance')|int) < mapping[states(weather_state)]['high']

#

as in, you wanted: (states('sensor.avg_illuminance')|int < mapping[states(weather_state)]['high'])

#

it didn't make sense the other way

pastel moon
#

This is my first try with this, so I won't object if it makes more sense

inner mesa
#

the goal is achieving your goal, of course

pastel moon
#

Thanks, I appreciate that. Time for test I suppose!

#

Can I call this from dev-tools too?

inner mesa
#

yes

pastel moon
#

I set this in dev-tools {% from 'sensors.jinja' import lux_high_low %} {{ lux_high_low('cloudy') }}, and got this error UndefinedError: 'dict object' has no attribute 'unknown'

#

I had forgot to reload, sorry, but still an error

inner mesa
#

did you fix all the things I mentioned?

#

my guess is that you didn't do anytihng about this:

I also don't see default_highlow defined anywhere.

#

did you copy this from somewhere?

pastel moon
#

No the sensor I did myself

#

I added the defaul_highlow, yes

#

but found an issue

#

I was trying to get state from a value, so corrected that, but now getting TypeError: '<' not supported between instances of 'int' and 'str' instead

#

so I do some nasty comparison I need to figure out πŸ™‚

fresh oyster
#

Is there an easier way of doing this?

#

template:

  • sensor:
    • name: Batch 1 temperature
      unit_of_measurement: "Β°C"
      state_class: measurement
      device_class: temperature
      state: >
      {% if state_attr('sensor.fermenting_batches', 'data') | list | count > 1 %}
      {{state_attr('sensor.fermenting_batches', 'data')[0].current_temperature}}
      {% else %}
      0
      {% endif %}
#

{% if state_attr('sensor.fermenting_batches', 'data') | list | count > 1 %}
{{state_attr('sensor.fermenting_batches', 'data')[0].current_temperature}}
{% else %}
0
{% endif %}

inner mesa
pastel moon
#

I copied the whole thing you pasted... put in in front of the pipe?

inner mesa
#

you need to understand what you're doing

pastel moon
#

but agreed, there is still something there

inner mesa
#

that's why I asked if it was copied - one makes sense, the other doesn't

#

think about the test you're doing

pastel moon
#

Oh, sorry, I missunderstood then and answered something irrelevant, sorry for that

inner mesa
plain magnetBOT
#

To format your text as code, enter three backticks on the first line, press Shift+Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.

pastel moon
#

Ok. So this part now returns true, as expected
{{ (states('sensor.avg_illuminance')|int) < (mapping['cloudy']['high']|int) }}

#

I am going at this wrong aren't I...? If the above comparasion is true, I need the macro to return "lux_low" ( and if possible also the value for "low")

#

Got it! {{ (states('sensor.avg_illuminance')|int < mapping['cloudy']['high']) | iif('lux_low', 'lux_high')}}

#

Thanks @inner mesa !

#

Now onto the reason why I chose this macro... Can I somehow also return the threshold value? Now it returns lux_low. Can it be made to do lux_low (65) for example?

fresh oyster
#

sorry @inner mesa

#
  - sensor:
    - name: Batch 1 temperature
      unit_of_measurement: "Β°C"
      state_class: measurement
      device_class: temperature
      state: >
             {% if state_attr('sensor.fermenting_batches', 'data') | list | count > 1 %}
             {{state_attr('sensor.fermenting_batches', 'data')[0].current_temperature}}
             {% else %}
             0
             {% endif %}```
#

I've got a list that may have nothing in it or several items, I'm counting it at the moment in the state and seeing if it has enough in for the sensor or coalescing to 0

#

I've got potentially quite a few of these to do and I was hoping there was a function or something I could use instead of the long form abovew

inner mesa
#

you can use a macro, as hassian is trying to do above

ivory harbor
#

I'm having trouble using state_class with a value template sensor... is that to be expected?

marble jackal
#

If you are using the legacy template format it won't work

plain magnetBOT
#

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.

ivory harbor
static shuttle
#

Was told this would be the best place to post this. Sorry for the noobie-ness. πŸ™‚
Is there anywhere I can find documentation on how to add "info" messages? I found code {{ states.light|selectattr('state','equalto','on')|list|length }} to put in a message "There are A lights on." and I'd like to add a whole bunch of info to that card. "The average temperature inside is B" (I have a helper entity that finds the mean of the temp sensors already), "There is motion detected in C rooms." "D doors are open." Etc. etc. etc. πŸ˜›

marble jackal
#

What do you want to do with this info message? Should it be sent to your phone? Displayed on a dashboard?

static shuttle
#

Just displayed on the dashboard. Using a Mushroom Title card and putting it in the subtitle section, but it appears to work just like a Markdown card, (which I'm open to using if the Mushroom title card gives me troubles with anything).

inner mesa
#

They just want help with templates in general. I'll again point to the links in teh channel topic

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

digital tree
#

Why this working with brightness but not with color? The lights support color change

#
  - variables:
      lights_on: |
        {{ expand(area_entities('Living room') | select('match', 'light'))
          | selectattr('state', 'eq', 'on') | map(attribute='entity_id') | list }}
  - condition: "{{ lights_on | count > 0 }}"
  - service: light.turn_on
    target:
      entity_id: "{{ lights_on }}"
    data:
      color_name: red```
indigo haven
#

how can I get the current zone of a person inside of a template?

inner mesa
#

It's just the state of the person entity

indigo haven
#

ah

#

that was easy

#

thanks

pastel moon
#

Hi, I got great help getting started with TemplateMacro's; https://dpaste.org/yj2nB. But now I see another challenge. I want different return values based on same data... So the mapping table witin the macro, can that somehow be defined only once and then reused in several macros?

inner mesa
#

You could create a macro that returns it

pastel moon
#

A macro in a macro?

inner mesa
#

No, a macro to return the data structure that you call from other macros

#

Presumably it would work

pastel moon
#

Ok, will try, thanks πŸ™‚

inner mesa
#
{% macro foo() %}
{{ 'blah' }}
{% endmacro %}

{% macro bar() %}
{{ foo() }}
{% endmacro %}

{{ bar() }}

-> blah
pastel moon
inner mesa
#

Syntax is kinda broken

#

I also don't think that will work. It's not what I showed

pastel moon
#

No, agreed, will redo according to your example

#

I think I defined the mapping macro ok(?) but the call to it is what I am thinking of now... How do I look up data in such object?

inner mesa
#

it's a little more annoying that I thought:

{% macro map() %}
{{ {"a": 1, "b": 2}|to_json }}
{% endmacro %}

{% macro test() %}
{% set data = map()|from_json %}
{{ data.a ~ ' ' ~ data.b }}
{% endmacro %}

{{ test() }}

-> 1 2
pastel moon
#

Agreed, looks a bit complicated. I will give it some thought and try some more. Thanks for the help so far! πŸ™‚

marble jackal
digital tree
#

All the lights that i left on to test it, supports color change

marble jackal
#

Check the trace or log for errors

pastel moon
#

About the trace, where would be the correct channel to ask about it?

marble jackal
plain magnetBOT
#

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

mighty ledge
#

@sonic night I already explained what you need to do

#

You cannot go the path you are going. Replace changes the value to a string

#

Again, you have to make 8 MQTT sensors, each one pulling out 's' and 't' for each item in the 24hrs dictionary

#

Then, in your command template, you pull each value into the dictionary that YOU create by hand. You cannot grab it from an existing sensor.

#

From there, you an do | to_json and your result will be json

#

If you put the dictionary into a sensor's attributes, you can also do it that way

#

but you cannot replace a dictionaries value in jinja, you HAVE to reconstruct it

#

That's a limitation of Jinja

fresh oyster
#

do template sensors have to go in the main configuration.yaml or can I add another file somewhere for them?

mighty ledge
#

you can split your configuration up however you want

plain magnetBOT
fresh oyster
#

sweet, thanks @mighty ledge

mighty ledge
#

np

#

FYI, template requires the merge dir list one

#

same with sensor

fresh oyster
#

that's a pro tip right there, it would have tripped me up!

pastel moon
#

Is there any performance (or other) gains to use template macros instead of other config? Simply love that they kind of act as functions πŸ™‚

mighty ledge
#

that's why I was mentioning that you should set a variable for that dictionary you were making the other day

#

instead of making a macro

pastel moon
mighty ledge
#

but if the result is a string, then there's really no problem

pastel moon
#

It is. I was thinking on expanding on that, but should rethink that then I suppose

thorny snow
#

what do I need to type in select: state:

marble jackal
#

You mean in a template select?

thorny snow
#

Yes

mighty ledge
#

The template that determines the state of the select entity

thorny snow
#

I'm confused

#

What is state actually

inner mesa
#

it is the state of the entity

mighty ledge
#

The state is not determined by what you select. If it was, then you’d just have an input_select helper.

inner mesa
#

sorta. this lets you define what to do with the option without a separate automation

mighty ledge
#

So you come up with the template that determines the state based on another entity

inner mesa
#

unfortunately, the state can't be derived from the option chosen

mighty ledge
#

Correct, because then it would just be an input_select

inner mesa
#

sorta. this lets you define what to do with the option without a separate automation

#

input_selects don't do anytihng

#

having the option variable available to define the state would be helpful

#

if that's all you want

mighty ledge
#

I get what you’re saying but I don’t see the benefit of making a select template without it having a state that’s generated with code

#

I’m sure optimistic could be added to it, but it would just be out of sync with your intentions at some point

inner mesa
#

in any case, to the OP, I suppose the solution is an input_select to provide the dropdown and an automation that triggers on a state of change of that entity to make whatever service call is needed based on the new state

mighty ledge
#

Itd be pretty easy to add optimistic

inner mesa
#

it does have its own state, after all

plain magnetBOT
#

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

torn gorge
#

Is it possible to use secrets in templates so that I could add other text to it? I want to do this:
pixoo_rest_imageurl: method: POST payload: "imageurl={{ Imageurl }}&x={{ x }}&y={{ y }}&push_immediately=true" content_type: "application/x-www-form-urlencoded" url: "{{ secrets.pixoo_rest_base_url }}/imageurl"

floral shuttle
#

tried to set a loop.length, but that does not work when there is no loop... and I cant find a way to have it default to 0, so is this the only way to count? {% set period = states('input_number.lightning_strikes_period')|float %} {% from 'lightning.jinja' import strikes %} {% set ns = namespace(count=0) %} {%- for s in strikes().split(',')|reject('eq','') if states[s].last_updated < now() - timedelta(hours=period) -%} {% set ns.count = ns.count + 1 %} {%- endfor %} {{ns.count}} if the 'if' does not evaluate to true?

#

something like {% set period = states('input_number.lightning_strikes_period')|float %} {% from 'lightning.jinja' import strikes %} {%- for s in strikes().split(',')|reject('eq','') if states[s].last_updated < now() - timedelta(hours=period) -%} {{loop.length if loop.last}} {%- endfor %} but apparently there is no loop at all in the case of 0 πŸ˜‰

marble jackal
marble jackal
#

so it will never get to that output

#

but why do you need a loop here

#

what do you have in that strikes variable

floral shuttle
#

because I couldnt find a way to map the last_states, like I do with my 'near' strikes

#
          {% set km = states('input_number.lightning_strikes_near')|int %}
          {% from 'lightning.jinja' import strikes %}
          {{strikes().split(',')|reject('eq','')
           |map('states')
           |map('int',default=0)
           |select('<', km )
           |list|count}}```
#

I tried to replace the map('states') in there, with the last_updated

marble jackal
#

but what is in strikes? A list of entity_id's ?

#

or states objects?

floral shuttle
#

yes, its {%- macro strikes() -%} {{- states.geo_location |selectattr('attributes.source','defined') |selectattr('attributes.source','eq','blitzortung') |map(attribute='entity_id') |join(',') -}} {%- endmacro -%}

marble jackal
#

if you expand it, you can just use selectattr()

floral shuttle
#

hehe, yes, but I was trying to move away from all of those expands, as much as possible.... was the foremost reason to use those custom_templates in my case ..

marble jackal
#

but why?

floral shuttle
#

because on more than 1 occasion, I had those expands on the state and several attributes in 1 template.

#

moving that to a single custom_template seems way more efficient

marble jackal
#

But I don't think a for loop is more efficient then expanding the list of entity_ids

floral shuttle
#

tbh, I am not sure.... I do have montrosities like```
{% set km = states('input_number.quakes_near')|int %}
{% set location = states('input_select.quakes_near') %}
{% from 'quakes.jinja' import quakes %}

        {% set ns = namespace(count=0) %}
        {% for s in quakes().split(',')|reject('eq','')
           if distance(states[s].entity_id ,location) < km %}
            {% set ns.count = ns.count + 1 %}
        {% endfor %}
        {% if ns.count == 0 %} Geen aardbevingen binnen {{km}} km
        {% else %}
        {% for s in expand(quakes())
           if distance(s,location) < km %}
        - {{s.name}}: {{s.state_with_unit}}{{'\n' if not loop.last else ''}}
        {% endfor %}
        {% endif %}```
#

notice it uses the import for the count there, but then expand that again to create that {{s.name}}: {{s.state_with_unit}} later on

#

i could probably replace those with {{state_attr(s,'name')}} etc

marble jackal
#

I'm just comparing this:

           {% set period = states('input_number.lightning_strikes_period')|float %}
           {% from 'lightning.jinja' import strikes %}
           {%- for s in strikes().split(',')|reject('eq','')
                if states[s].last_updated < now() - timedelta(hours=period) -%}
           {{loop.length if loop.last}}
           {%- endfor %}

to this

           {% set period = states('input_number.lightning_strikes_period')|float %}
           {% from 'lightning.jinja' import strikes %}
           {{ expand(strikes()) | selectattr('last_updated', '<' now() - timedelta(period)) | list | count }}
#

or just built in some selection filters in your macro

#
{%- macro strikes(period=0) -%}
{{- states.geo_location
      |selectattr('attributes.source','defined')
      |selectattr('attributes.source','eq','blitzortung')
      |selectattr('last_changed', '<', now() - timedelta(hours=period))
      |map(attribute='entity_id')
      |join(',') -}}
{%- endmacro -%}
#

you can still use strikes() to list them all, but strikes(period=states('input_number.lightning_strikes_period')|float) will filter on that

floral shuttle
#

Yes, I also figured about that, but that would make the whole custom_templates a bit moot, as I try to make those as generic as possible, and only do so when reusable. otherwise it just complicates things

marble jackal
#

I don't agree on that, I think it makes the custom_templates more usefull

floral shuttle
#

hmm, I see now that you added that as a config option, not as a fixed selector. So if not actually used in the template sensor, it would simply no influence the output?

marble jackal
#

yes, that's the idea. It just defaults to 0 if you don't enter anything because of the period=0 when setting the macro

floral shuttle
#

if so, it would actually be much very versatile πŸ˜‰

marble jackal
#

set a really big default for km

floral shuttle
#

Id simply use the max of the input entity?

marble jackal
#

not sure what this blitzordnung entity does, I assume it doesn't respond on every lightnitng strike in the world

#

so it must have some distance setting already

floral shuttle
marble jackal
#

so I would use that setting

#

the problem there is that states are strings πŸ™‚

floral shuttle
#

tbh, I was thinking of my quakes alerts, and I have that a bit more complicated, as I set a max distance, but also a zone to relate to

marble jackal
floral shuttle
#

and since I copied my config from before (when using wwnnl source) they use the same methods. Ive only started using this CC recently, so have to find the best settings just yet

marble jackal
#

You are never interested in the entity_id's itself I guess, just build everyting in the macro and return the count

floral shuttle
#

well, not 100% true, I do list them on a map: type: custom:auto-entities show_empty: false entities: - zone.home card: type: map filter: template: > {% set km = states('input_number.lightning_strikes_near')|int %} {% from 'lightning.jinja' import strikes %} {% set ns = namespace(count=0) %} {% for s in strikes().split(',')|reject('eq','') if states(s)|int < km %} {{s}}{{',' if not loop.last}} {% endfor %}

#

and the distance setting works perfectly fine, its really cool to see those maps show what near a certain distance

#

but I dont need those inside an attribute as they are meaningless

marble jackal
#
{%- macro strikes_count(period=0, km=100) -%}
{{- states.geo_location
      | selectattr('last_changed', '<', now() - timedelta(hours=period))
      | map(attribute='entity_id')
      | map('states')
      | select('is_number')
      | map('int')
      | select('<=', km)
      | list
      | count 
}}
{%- endmacro -%}


{{ strikes_count(period=5, km=10) }}

You can do something like this to return the count based on both period and distance

floral shuttle
#

ooh that is nice yes, thanks!

marble jackal
#

one thing though (which I just changed)

#

you were using < I would say it makes more sense to look for recent strikes, instead of old strikes

floral shuttle
#

great for the counters. I guess I do need to write an extra macro to be able to do this in the template sensors: {% set km = states('input_number.lightning_strikes_near')|int %} {% from 'lightning.jinja' import strikes %} {% for s in strikes().split(',')|reject('eq','') if states(s)|int < km -%} {{'Inslagen op: ' if loop.first}} {{- states(s)}} km{{', ' if not loop.last}} {%- else %} Geen bliksem binnen {{km|int}} km {% endfor %} where I need those states themselves

marble jackal
#

so you need to use >

floral shuttle
#

yes, I had been playing with that, and even though the output did change when sliding the period selector, I didnt yet figure out if that was what I was looking for.

marble jackal
#

that also means you need to use a high default for period instead of 0

floral shuttle
#

I now do understand why it stopped making a difference over 100 km... ( I had completely forgotten about those main settings in the CC config πŸ˜‰ )

marble jackal
crimson lichen
# marble jackal what does it return now?

How to do it can get 175.9 in txt file with value_template: '{{ value.split("-")[something] }}':

Home Assistant notifications (Log started: 2023-07-18T02:44:00.431119+00:00)

18/Jul/2023-175.9
19/Jul/2023-185.49

marble jackal
#

that's not an anwer to my question, what is that state of that sensor?

floral shuttle
# marble jackal that also means you need to use a high default for `period` instead of `0`

just as a final one for this specific challenge, Ill use templates like below and be able to slide those dynamically in the Dashboard:```
{%- macro strikes_count(period=5, km=1000) -%}
{{- states.geo_location
| selectattr('last_changed', '<', now() - timedelta(hours=period))
| map(attribute='entity_id')
| map('states')
| select('is_number')
| map('int')
| select('<=', km)
| list
| count }}
{%- endmacro -%}

{% set near = states('input_number.lightning_strikes_near')|int %}
{% set hours = states('input_number.lightning_strikes_period')|float %}
{{ strikes_count(period=hours, km=near) }}```

crimson lichen
crimson lichen
#

it only take 185.49

marble jackal
#

you had that with [1] before. I want to know what it outputs if you have that

crimson lichen
#

with value_template: '{{ value.split("-")[1] }}' will is 185.49

marble jackal
#

okay

#

it will always use the last line, as also stated in the docs

crimson lichen
marble jackal
#

Not with the file sensor you are using

crimson lichen
#

So with which template can I save the value to the json file

floral shuttle
#

its a bit clumsy, but it gets the thing done

#

it can do things like: 17 Jul 22:19:36: Dark: on - Elevation: -4.15 - Light level: 3242 18 Jul 05:20:23: Dark: off - Elevation: -3.8 - Light level: 3242 18 Jul 22:18:30: Dark: on - Elevation: -4.17 - Light level: 3242 19 Jul 05:21:53: Dark: off - Elevation: -3.78 - Light level: 231 19 Jul 22:17:21: Dark: on - Elevation: -4.19 - Light level: 231 20 Jul 05:23:26: Dark: off - Elevation: -3.77 - Light level: 3242

#

and in the template you set what you want to log:```
script:

file_daylight_variables:
mode: restart
sequence:
service: notify.filed_daylight_settings
data:
message: >-
{% set nu = now().strftime('%-d %b %X') %}
{% set level = state_attr('sensor.driveway_buiten_sensor_illuminance','light_level') %}
{% set dark = states('binary_sensor.donker_buiten') %}
{% set elevation = state_attr('sun.sun','elevation') %}
{{nu}}: Dark: {{dark}} - Elevation: {{elevation}} - Light level: {{level}}

lost adder
#

this is my code type: custom:button-card
name: Avvia Timer
tap_action:
action: call-service
service: timer.start
service_data:
entity_id: timer.timer_cucina_main
duration: |
{% set minutes = states('input_number.timercucina') | int %}
{{ minutes * 60 }}
show_icon: true
show_name: false
icon: mdi:play
and i would liek to take the durations by my input type, it's called input_number.timercucina
if i start this it's gives me failed to start
How i can resolve it?

crimson lichen
crimson lichen
floral shuttle
lost adder
#

Thanks so much! Have a good day

floral shuttle
floral shuttle
#

must be completely missing the obvious, but is this really the shortest to check if now == input_datettime.... {{states('sensor.time') == state_attr('input_datetime.cover_dorm','timestamp')|timestamp_custom('%H:%M',False)}} ?

#

other than maybe a silly string manipulation: {{states('sensor.time') == states('input_datetime.cover_dorm').split(':00')[0]}}

#

or even worse: {{states('sensor.time')~':00' == states('input_datetime.cover_dorm')}} .. really too bad those input_datetime s use seconds ;00 in templates/states even though they are not set or ever needed/configurable in the Dashboard

mighty ledge
mighty ledge
#

I'm not sure why your're even still using sensor.time

floral shuttle
#

me neither... its been there forever, and I was revisiting..

mighty ledge
#

well, try using datetimes. TBH it seems like you ask the same time questions every few weeks and the answer is always the same

#

datetimes datetimes datetimes

#

anything else is going to be verbose

#

however your "even worse" would also work

thorny snow
#

What I wanted was a list selecting like there is a list and you can select one but you can also select multiple ones how do I make a template like that?

floral shuttle
#

otoh, there's nothing simpler and closer to human speech than that sensor.time output..

mighty ledge
#

right, but you don't really need it

#

you can make a template or use clock() in easy_time

#

Sorry, I just don't see the point of the sensor.time entity

mighty ledge
#

it can be done in templates, however there's nothing in the frontend that allows multi-select

thorny snow
mighty ledge
#

no i mean templates

#

template entities are not templates, they allow templates in them

#

see the pins

#

one lets you understand the difference between jinja and yaml

#

jinja are "home assistant templates"

#

they are also the topic of this channel

plain magnetBOT
#
The topic of this channel is:

Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/

This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.

Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs

floral shuttle
# mighty ledge you can make a template or use `clock()` in easy_time

a ok, I wasn't aware there was such a thing in easy_time, will check that now. The other template would be smthng like: {{now().strftime('%H:%M') == state_attr('input_datetime.cover_dorm','timestamp')|timestamp_custom('%H:%M',False)}} which in itself would explain the use of sensor.time πŸ˜‰

mighty ledge
#

yeah but even still, it's not really necessary. You're also using timestamps, which are largely obsolete now that we use datetimes everywhere

floral shuttle
#

but wait, I see clock outputs the same as that sensor.time indeed. But the issye is the input_datetime adds those :00 seconds we dont want there

mighty ledge
#

timestamps also don't have timezones

#

then you can do clock() ~ ":00"

#

You also don't even need that template anywhere because you can trigger off input_datetimes now

thorny snow
#

Wait how does it receive the inputs when multi selecting can be done in templates?

mighty ledge
#

so all in all, most of that is useless IMO

mighty ledge
floral shuttle
#

that is indeed s

#

what I missed in this specific trigger!!```

  • id: clock_open_cover_dorm
    trigger:
    platform: template
    value_template: >
    {{states('sensor.time')~':00' == states('input_datetime.cover_dorm')}}
    can be
  • id: clock_open_cover_dorm
    trigger:
    platform: time
    at: input_datetime.cover_dorm
thorny snow
mighty ledge
#

your best option is to make a series of input_booleans and turn on/off the ones you want

glacial matrix
#

Afternoon All,
I have a sensor that gives me the current 1/2 hourly rates from my energy supplier. The sensor has attributes that show this. How would I go about creating two new sensors from this Energy lowest and energy highest? the state attributes look like this.
https://pastebin.com/pq4QN6Ae
There are two sensors here one shows the rates for 24 hours, and the other shows the current and upcoming rates with the previous rating automatically going. There is also current rate, last rate, and next rate.
The tariff give me the next 24 hours at around 4pm, but that covers from the current day to around 22:00/22:30 the following day. I would like the sensor to tell me the cheapest and most expensive time of day (in simple format) and the cost at those times for both the current day, and for the next day if possible.

floral shuttle
#

however, my problem persists when this is required... {{states('sensor.time') == '20:20' and now().strftime('%w') == '5'}} though I might be able to move that second part to the conditions (and Id need to create 3 input_datetimes because: trigger: - platform: template value_template: > {{states('sensor.time') == '20:20' and now().strftime('%w') == '5'}} - platform: template value_template: > {{states('sensor.time') == '20:25' and now().strftime('%a') == 'Fri'}} - platform: template value_template: > {{states('sensor.time') == '20:35' and now().strftime('%a') == 'Fri'}}

mighty ledge
#

yes, you can move that to a condition

thorny snow
mighty ledge
thorny snow
#

Technicallt this is exactly what I want but it is only compatible with Mi Home but I want to use Roborock App and Roborock Integration

floral shuttle
#

issue there is not so much the weekday, but the repetetive triggers

mighty ledge
#

and technically speaking, his multiple selection is just switches that are on or off

#

i.e. input_booleans or the like

#

He does not have a dropdown list that supports multiple-select

thorny snow
#

Oh

mighty ledge
marble jackal
#

let me check

#

interesting though πŸ™‚ half hour rates

mighty ledge
#

half hour rates and the key is the datetime...

#

very odd way of doing things

marble jackal
#

it doesn't support this (yet)

#

it expects list items with a dict with two kvp (one for the datetime and one for the value)

mighty ledge
#

yeah, i'd argue that his integration should change to that method IMO

#

he could just transform his data and then use your calc

#

w/ namespace

marble jackal
#

yes indeed

#

normally there are also different attriubtes for todays prices and for tomorrow

#

but that also is possible to do in a template sensor of course, shouldn't be that difficult

mighty ledge
#
{% set ns = namespace(items=[]) %}
{% for k, v in items %}
  {% set ns.items = ns.items + [ {'datetime': k, 'price': v } ] %}
{% endfor %}
#

no clue what attr's your thingy requires

#

does your calc handle half hour incs?

marble jackal
#

well, it can be any attriubute, it has a default, but also options to provide your own

#

I need to check, I didn't expect it to be needed