#templates-archived
1 messages Β· Page 47 of 1
yeah, but easy_time does that whole thing
one of the macros does that
speak_the_days
qwrrg, if I rebuild, I have to start with this, as its the source of my complete alarm clock system
speak_the_days('sensor.next_alarm_timestamp')
and you can use count_the_days to get the number
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'
what's the state of 'sensor.next_alarm_timestamp'
{{states('sensor.next_alarm_timestamp')}} returns 1689309000.0
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
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
seems like a bug in speak the days
yep, {% from 'easy_time.jinja' import speak_the_days %} {{speak_the_days('sensor.next_alarm_datetime')}}
it should work
returns 'in 1 day'
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
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)
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?
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/)
Okay, Thanks alot!
@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
Wouldn't a template fan make more sense here?
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) %}
After deleting a template sensor from the configuration, how do I delete the entity fully in HA?
Calling service recorder.purge_entities apparently
Thatβs the only way
Time that jinja introduces some type filter or list test as are available in phyton
That could be you!
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
Thanks. Finding these docs a little confusing though. They are talking about operators for disabling lstrip_blocks and trim_blocks, but want those enabled
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 %}
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
sure, you can return any native type
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
I think the list part could be an attribute. states must be strings
you probably just remove "count" π
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
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
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?
{{ states.sensor|selectattr('attributes', 'contains', 'distance')|selectattr('state', 'eq', 'living_room')|list|length }}
oh thats much cleaner
{{ 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
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>)>]```
Ok, so thats how you select a specific value to list - thank you!
Could anyone help me figure out how to investigate available attributes for an entity. Specifically I am looking for if my tv is paused
Go to Dev tools > States then find your entity there. It will have all it's attributes listed
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?
You're welcome to put * in
-> Events and see. But it would probably be documented in whatever integration you're using
I totally bought the wrong tv it seems π¦
If it's a samsung then from what I've heard, yes lol
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
Can you short circuit (return) from a macro?
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
{{ states.input_datetime | selectattr('object_id', 'search', '^bla') | map(attribute='entity_id') | list }}
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?
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 }}
thanks again!
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?
just post the source sensor states, thier entity_id's and your code
My template: https://paste.debian.net/1285840/
The source sensor: https://paste.debian.net/1285841/
Not sure how that ever worked
Haha, it worked flawlessly till yesterday
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
Lemme check and reboot...
Yeah saw them both.
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
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.
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'
can you copy/paste this into the template editor and post the results here
{{ state_attr('sensor.energyprices','raw_today') }}
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},
the whole thing please
Sorry not repeating, but you know what I mean π
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
No worries, just wanted to skip the pastebin thing
[hours.start.strftime("%Y-%m-%d %H:%M:%S")]
Sorry for ugly paste: https://paste.debian.net/1285844/
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
π
Let's see if that works...
Still strange that it worked until today, I did HA update, but there was no Nordpool update
You mean the ones from Nordpool, or my sensor?
Problem isn't resolved yet, so deeper down the rabbit hole we go
nordpool
How do I see if they are objects or strings? Can I see that in the entity states?
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') }}
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.
what are the errors in your logs at startup?
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) π
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
Under system...log there's nothing. But I'll open the log manually and see what I find
Yeah, but if I reload the Nordpool integration, that should force it to update right?
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
not if the information hasn't changed
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
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.
that makes no sense
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
You'll get errors in your logs if things aren't working
In the core log right? Maybe I'm looking in the wrong log?
Did you enter that sensor directly into your configuration.yaml, and did you maybe add a 2nd template: section by doing that?
yes core log
FYI I don't care if you ping me
so ping away
Maybe make a small gif about that to reply with if people don't ping π
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 π
Ah haha. Ok I'll try and remember that π
Agreed
I do it to tink tho on purpose sometimes, don't be like me
We need a "noping" icon in the names π
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
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?
yes
assuming you placed in in this templates.yaml and it is indented the same as the existing one
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)
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
Wait.. sensor after trigger doesn't have to be indented to be related?
Here's my templates.yaml (first lines)
the first sensor in my snippet is related to the trigger
ah this is why it's not working
Your sensor is nested the same way as my other sensors
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
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!
Did you link that on purpose?
I know youβve been here before but youβre about to be removed if your account is Compromised
Is there a way to get the time a sensor last updated?
sensor.litter_robot_status_code
states.sensor.litter_robot_status_code.last_updated
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) }}
Possibly, but this is shorter
{{ (now() - states.sensor.litter_robot_status_code.last_updated).total_seconds() | timestamp_custom('%H:%M:%S', false) }}
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.
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) }}
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?
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
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
What have you tried? state_attr('sensor.weatheralerts_1','event') should grab it
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
It's definitely a way to grab a sensor's attribute
What does {{ states.sensor.weatheralerts_1.attributes }} show
Oh, that might work, if I understand right. I was doing experimenting with something else, but I'll swap over since yours seems cleaner: data: > {% set res = dict(entity_id=entity_id) %} {% res[brightness] = 2 if brightness is defined %} {{ res }} To be clear mine doesn't work because my syntax for updating the dictionary is wrong, but I'm going to try your approach now.
@obtuse zephyr it just shows the attributes in the same screenshot, just looks like all text
"event": "Heat Advisory",
Then {{ state_attr('sensor.weatheralerts_1','event') }} should show that string
Show a screenshot for the attributes output
It works!! And that looks pretty clean, too:``` data: |
{{ dict.from_keys([
('entity_id', entity_id),
('brightness', brightness if brightness is defined),
('rgb_color', rgb_color if rgb_color is defined),
('transition', transition if transition is defined),
] | selectattr('1')) }}
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.
Seems decent to me
Wahoo, you are a genius NSX, thank you... {{ state_attr('sensor.weatheralerts_1','alerts')[0]['event'] }}
You can also just slap JSON in there
YAML being a superset of JSON
Make the value of data: a JSON dict
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".
Feel free to come back for more, there's plenty left π
Is there a similar way to exclude elements based on conditions if you'd just be defining it through plain JSON?
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
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```
I want to turn on an input_boolean if the percentage is set to a non-0 value, off otherwise
oh yeah
it still doesn't pass the yaml check with the endif. "found character '%' that cannot start any token" on the first %
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' }}
ah ha, it was the spaces.
and that second form is much nicer anyway. Thank you!
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?
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
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 %}
You don't need to let it return on or off
As 0 is falsely already, this should be enough (also according to the docs.) https://www.home-assistant.io/integrations/template/#state
state: "{{ states('sensor.system_updates') | int(0) }}"
You can also replace the icon line with device_class: update that will also provide the right translations for the frontend
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
It's under binary_sensor and then state
The sensor is
onif the template evaluates asTrue,yes,on,enableor 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
yeah i found it now.. i was blind or tired yesterday π
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
Hey, does anyone know how I could pad this to the left? I'd like to make it look like my second image https://imgur.com/a/lRw6iLD
@radiant spindle I converted your message into a file since it's above 15 lines :+1:
I'm not sure if I can do it without editing the custom:mushroom-entity-card, I'm newish to templating
I didn't even know or think about a template fan...lol. I'll keep researching and learning.
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?
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...
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') }}```
{{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 %}
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! π
You can expand the group directly, no need to use the attribute
{{expand('fan.fans')
|map(attribute='state')
|select('eq','on')|list|count}}
But yes, expand will go to the groups in the groups again and use the single entities, if you don't want that, don't use expand.
That's why the second one works for you
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?
Add .state at the end when outputting or use the states method instead
Thank you!
So isoformat() has '+00:00' on the end instead of zulu. It may mean the same thing, but it might matter for string based date comparisons.
So:
'2023-07-16T12:54:00.087940Z'
'2023-07-16T12:54:00.088211+00:00'
That's what I thought and what I ended up doing.... how frustrating. Thanks anyway.
Doesn't really make a difference then, the part until the microseconds is the same. String comparison goes character by character
I see
@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!
There is a default setting, I think it's one weight point per hour
It should be in the result
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).
@tight adder I converted your message into a file since it's above 15 lines :+1:
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 ?
Probably longer than 255 characters. Why do you want all that JSON in the state?
'cause I don't know I should select result π how can I do that ?
select only some attributes. I thought it was your question
select which key?
you can select whatever you want. {{ state_attr('weather.home', 'forecast')[0].wind_speed }}, for instance
you said : Why do you want all that JSON in the state?
I want to read it in esphome after with usiong the attribute paramter
in that way no need to create trhousand of sensor
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?
yes 5 for day one to five. If I follow you example, i will need to create 10 sensors per day
I believe that you'll need to define each attribute using the format I provided above: https://www.home-assistant.io/integrations/template/#attributes
- sensor:
- name: forecast_d0
state: Whatever
attributes:
wind_speed: "{{ state_attr('weather.home', 'forecast')[0].wind_speed }}"
for instance
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
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.
You want a Template select... Example #2 from https://community.home-assistant.io/t/template-select/451830/4
Unless there is a need to allow multiple to be on at once, you may also want to set up something like https://community.home-assistant.io/t/mode-select/417300/2
@cursive ice I converted your message into a file since it's above 15 lines :+1:
@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 }}
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}}
worked instantly thank you, lol sods law I would try to over complicate it
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
was doing all that just to have a pretty battery meter on picture elements card lol.
Why not create a more advanced macro which accepts parameters, like which group to use, and what to output
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 %}``` ...
yes that would be awesome. though I admit my package 'samenvatting' contains various Jinja templates that are not easily moved to a single structure on all states/attributes...so ti wont be a single mold that would fit them all
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
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```
Because one is in UTC, and the other in the local timezone
But it is the same time, just displayed differently.
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
This would be the start of the same thing as you have now, but with more dynamic input
{%- macro group_summary(group, states, output) -%}
{{- expand(group)
| selectattr('state','in',states)
| map(attribute=output)|join(',') -}}
{%- endmacro -%}
{{ group_summary(group='light.groep_huis', states=['on'], output='entity_id') }}
Output:
light.booglamp,light.eettafel_template
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.
for a quicky, can you spot how I could manage #templates-archived message ?
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
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 -%} π
How do I convert input_datetime from a string to time?
Time only, date only, or date and time?
Time only
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
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```
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
How do you want to use this? And where does the value for lighting Count come from
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
But should this be a trigger, or another template sensor or what? Explain what your goal is
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
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"
Not sure if this is what you mean, but this will remove everything but the hour and minute: {{ now().timestamp() | timestamp_custom('%H:%M') }}
@analog mulch I converted your message into a file since it's above 15 lines :+1:
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?
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"
- platform: time
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.
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
You can't mix yaml from separate integrations. Seconly, the file integration does not write to a file, it only reads to a file. If you want to write to a file, you'll most likely have to use the command line sensor with a linux command that writes to a file.
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.
can you post the full automation? what you're saying doesn't make sense.
Here is the full script: https://pastebin.com/fifuQiXM
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
Also the log has this error: https://pastebin.com/3940YZZz
are you pressing the 'run actions' button?
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
Could it be some old instance of the script still running?
did you press run actions when testing in the past? it is set to queued
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?
I would assume running ones are untouched, but I've never looked into that.
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.
turn off the script
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!
np
{{ now().replace(microsecond=0) }}
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 ?
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)}}
Yes, they're separate fields
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..
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 ???
you would want to use a trigger
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
template:
- trigger:
- platform: state
entity_id: input_number.test
sensor:
- name: Keep Last
state: "{{ states('input_number.test') }}"
attributes:
previous: "{{ trigger.from_state.state }}"
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 ?
ouf ok π
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:
...
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 π
no.
sorry, hit enter too quick
- trigger:
- some yaml
sensor:
- name: my sensor that need a trigger
notice how sensor: doesn't have a -
my templates.yaml start with
- sensor:
and then all sensors
but now I'm confused with what you mention petro
some yaml = files ?
that + the code I provided above
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
in the example from the docs, yes
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: ...
sources is any sensors in the state part
any entities
any entities , so any update events coming , ohh
you can stick the template in
-> Templates and it will tell you what it's monitoring
any entities in the template
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
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
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 π
you can get the previous state from this.state
that's the previous state when the template runs
in attributes it does not
in state yes ?
in value_template or state, it's the previous state as you're currently calculating the next state
as soon as you chagne it, it's new
it's impossible to avoid this
they wanted an attribute with the previous state
ah ok
but if it's not in attribute , it's ok for me
I thought that it always represented the previous state object, but it's dynamic
I just need the previous value and I found may be attribute is the key
that's correct but it when it's calculating the current state it can only be the previous state
it doesn't make sense to put it anywhere else (i.e., the state)
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
it was, but a certain somebody wanted to not recalc the state
yes, the whole thing is weird
you have to know the order of resolution with the current method
which is availability -> state -> everything else
yeah
and don't even start with attribute order
that's async
so it's the wild wild west
I tried to do something for my consumption . I have the absolute value of a energy counter.
- 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) - 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
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
I use the camera reading ai-edge from Jomjol
to read the number?
yes
oof
ok
does it reset at midnight?
or, more importantly, do you know when it resets?
never reset
so it just counts up forever?
yes , it represent the value on the counter
then it shouldn't go negative ever
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
Help with template sensor for registering blade timer from Landroid robot mower
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.
- repeat:
count: "{{ template }}"
No colon after repeat?
Sorry, added it now
I'll give that a shot. I'm curious why count is required only when using a template, though.
I never saw that short hand notation you were using before, don't see it in the docs
https://www.home-assistant.io/docs/scripts/#repeat-a-group-of-actions
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:
Ah, that's something totally different
I missed the vacuum part, I thought you were creating a repeat action
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
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
I would advice to use {{ states('input_select.vacuum_repeats') | int }}
I mean, sure, but that also spits out the same integer of 2
So I'm not sure it'll fix anything
Yeah, it will not help, it was more of a sidenote
@bronze prawn I converted your message into a file since it's above 15 lines :+1:
Do you have this in an automation?
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?
In a script
What does the trace show for that service call?
Are you sure this entity_id input_number.daily_max_windgust is correct? If not, it will be treated as 0 because of you default
You are using a different one in the service call
Nothing of note. It sends the command and and vacuum starts (but runs only once, rather than the specified number). No error returned by the service call.
It will show in the trace of it used the repeat setting and with which number
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
If it shows 2 there, the issue is in the integration
Another one of those 'doh' moments. Thanks for picking up on the obvious goof. I think it'll work now! π
Is it? Because when I put a "2" there instead of a template, the vacuum hits all specified segments twice...
Well, the template is correct, the result of the service call is as expected
{{ 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?
What if you run it from devtools > services with the template?
Same result from there. With a number it works, with the template it only runs once
Add a default to the round filter
Or an availability template to your template sensor if that's where you are using it
Then I don't know, I can't test it right now, I'm off to bed
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).
Okay, well then I would advice the availability template
But I'm really putting my phone down now π
Time for bed
had to google how to specify default to round(), but it works. Thank you. Good night
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
So...
{{ state_attr('calendar.trash_schedule', 'start_time') | timedelta(days=1) }}
?
{{ state_attr('calendar.trash_schedule', 'start_time') | as_local }}
AttributeError: 'str' object has no attribute 'tzinfo'
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
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
awesome thanks!
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
Yes, they can be compared. Does it not work?
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
{% 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
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
Ah I see thanks. I guess since I don't really care about the times, I was worried about them creating confusion with things like HA potentially starting after the expression becomes true
idk. date math makes my head hurt
you can remove the times like you did if you want, but they're comparable
cool thx
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 }}
{% 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?
Is this a trigger? I would just use a time trigger and check on the date in the condition
{% set filter_changed = as_datetime(states('input_datetime.filter_changed')).date() %}
{{ today >= filter_changed + timedelta(seconds=789000) }}
And why 789000 seconds?
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
use round() perhaps?
{{ temp | round(1) }}```
try in dev-tools if it does what you need
HomeTemps: {{ states('sensor.temperature', with_unit=true, rounded=true) }}|{{ states('sensor.atc_3ae6_temperature', with_unit=true, rounded=true) }}|{{ states('sensor.atc_35bb_temperature', with_unit=true, rounded=true) }}
The suggestion from Jorg only works if you set the precision in the entity settings
and rounded=true is not needed then, because it will do that by default if you use with_unit=true
https://www.home-assistant.io/docs/configuration/templating/#formatting-sensor-states
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 π
I could have sworn I just used a 1 decimal precision sensor, showing 2 decimal precision in the template with with_unit=true. Now it isn't anymore π
Thanks Fes mate. The reason for 789000 seconds is that equates to 3 months.
no it doesn't, it's roughly 219 hours (9 days and a bit)
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
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?
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... π
or {{ now().day == event.day and now().month == event.month }}
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)) }}
Thanks, that worked haha. And was alot easier π
Where is this decimal precision set please?
in the entity settings in the gui
Ah, thanks π
It is per device then I suppose, can it be set at system-level as well?
It's per entity
@undone jungle I converted your message into a file since it's above 15 lines :+1:
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.
nah 7890000 seconds. left off a zero π
i ilke the timedelta much easier
Ah okay, you can still use days in the timedelta if you want
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
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
2nd link has a lot of time examples
Beauty π
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 }}```
This template will give a count, not the entity_id's
And do all lights in those area's support brightness and color changes?
??
([ 0, output, 100] | sort)[1]
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?
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
@undone jungle I converted your message into a file since it's above 15 lines :+1:
In other words the whole template would look like that
Just that I could drop the default later as well
I would add the temperature sensors to the availability template
{{ states.light | selectattr("state","eq","on") | map(attribute="name") | list
}}
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
@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.
Very valid point. This said, would you recommend all of them. I'll have to look up syntax for checking if it's a number
states('your.entity') | is_number
This will fail if there is a light which doesn't support brightness. And you should put that template on the next line
Wouldn't it be is_state?
no, is_state is not a thing
I know there were some changes recently with states
You mean it's not a thing for numerical values, correct? Since I am using it for binary sensors
you could use that as well, but as you want it to be a numeric value, I would use is_number
No, I mean there is no such thing as is_state, I guess you are confusing it with has_value
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
- 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
I am not disagreeing, but then I must have a lot of strange outdated templates in my yaml, since most my sensor availability looks like this for binary sensors availability: "{{ is_state('binary_sensor.ventilation_bypass', ['on', 'off']) and is_state('binary_sensor.fan_operational', 'on')
oh, wait
yes, thats valid
I was to focussed on filters
of course the function is_state() is valid
but also there you could use 'binary_sensor.ventilation_bypass' | has_value
Many ways to skin the cat.
note that you need to use that on the entity_id directly, not on the state
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?
is it possible to be with a slider and not press button, because i have to make another button for lower the brightness
In addition, is that a valid way of going about it
availability: "{{ 'binary_sensor.ventilation_bypass' | has_value and is_state('binary_sensor.fan_operational', 'on') and states ('sensor.incoming_air_temperature' and 'sensor.room_supply_temperature' and 'sensor.room_exhaust_temperature' ) | is_number }}"
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
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
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},
No you canβt. You can make a macro file that contains those maps and import them
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 π
Thank you, I've corrected it!!
@sonic night I converted your message into a file since it's above 15 lines :+1:
@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
@sonic night I converted your message into a file since it's above 15 lines :+1:
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
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
I'm trying to follow this; https://www.home-assistant.io/blog/2023/04/05/release-20234/#macros-for-your-templates
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.
Itβs a static dictionary, you can just set it to a variable and import the variable (after doing what rob said)
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?
Well, I am trying to convert a working sensor into this instead, and yes, I expect mishaps... π
Basically
I'm trying to understand the logic, and not really succeeding
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"
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
This is my first try with this, so I won't object if it makes more sense
the goal is achieving your goal, of course
Thanks, I appreciate that. Time for test I suppose!
Can I call this from dev-tools too?
yes
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
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?
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 π
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 %}
- name: Batch 1 temperature
{% if state_attr('sensor.fermenting_batches', 'data') | list | count > 1 %}
{{state_attr('sensor.fermenting_batches', 'data')[0].current_temperature}}
{% else %}
0
{% endif %}
sounds like you didn't move the paren as I suggested
I copied the whole thing you pasted... put in in front of the pipe?
you need to understand what you're doing
but agreed, there is still something there
that's why I asked if it was copied - one makes sense, the other doesn't
think about the test you're doing
Oh, sorry, I missunderstood then and answered something irrelevant, sorry for that
did you just repeat the same thing twice there?
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.
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?
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
you can use a macro, as hassian is trying to do above
I'm having trouble using state_class with a value template sensor... is that to be expected?
If you are using the legacy template format it won't work
Please use a code share site to share code or logs, for example:
- https://dpaste.org/ (select YAML for the language, and consider picking a longer expiry)
- http://pastie.org/ (select YAML for the language)
- https://paste.debian.net/ (you guessed it, select YAML as the language)
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.
ah... I guess I need to move over to the new version
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. π
What do you want to do with this info message? Should it be sent to your phone? Displayed on a dashboard?
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).
They just want help with templates in general. I'll again point to the links in teh channel topic
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
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```
how can I get the current zone of a person inside of a template?
It's just the state of the person entity
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?
You could create a macro that returns it
A macro in a macro?
No, a macro to return the data structure that you call from other macros
Presumably it would work
Ok, will try, thanks π
{% macro foo() %}
{{ 'blah' }}
{% endmacro %}
{% macro bar() %}
{{ foo() }}
{% endmacro %}
{{ bar() }}
-> blah
Yeah, I'm about to test this; https://dpaste.org/Rw6q8
No, agreed, will redo according to your example
I believe this should be close, but no... https://dpaste.org/Q87Uc
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?
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
Agreed, looks a bit complicated. I will give it some thought and try some more. Thanks for the help so far! π
Probably because there are lights which don't support changing color
All the lights that i left on to test it, supports color change
Check the trace or log for errors
About the trace, where would be the correct channel to ask about it?
As they are provided by scripts and automations, I would say #automations-archived
@sonic night I converted your message into a file since it's above 15 lines :+1:
@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
do template sensors have to go in the main configuration.yaml or can I add another file somewhere for them?
you can split your configuration up however you want
Here is now to split your configuration into multiple YAML files
sweet, thanks @mighty ledge
that's a pro tip right there, it would have tripped me up!
Is there any performance (or other) gains to use template macros instead of other config? Simply love that they kind of act as functions π
not sure what you mean, but there is a limitation to macros. Macros only return strings, because of this, you end up adding more processing time if you have to convert values from macros
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
Ah, that is something to consider then, but guess you need to really push to notice, right?
but if the result is a string, then there's really no problem
It is. I was thinking on expanding on that, but should rethink that then I suppose
what do I need to type in select: state:
You mean in a template select?
Yes
The template that determines the state of the select entity
it is the state of the entity
The state is not determined by what you select. If it was, then youβd just have an input_select helper.
sorta. this lets you define what to do with the option without a separate automation
So you come up with the template that determines the state based on another entity
unfortunately, the state can't be derived from the option chosen
Correct, because then it would just be an input_select
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
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
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
Itd be pretty easy to add optimistic
it does have its own state, after all
@crimson lichen I converted your message into a file since it's above 15 lines :+1:
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"
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 π
Not directly. If you want this because you are sharing your config only, you could put it in an input_text using YAML config, and then use the state of the input text
if strikes().split(',')|reject('eq','') returns an empty list, it just won't do your loop
so it will never get to that output
but why do you need a loop here
what do you have in that strikes variable
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
yes, its {%- macro strikes() -%} {{- states.geo_location |selectattr('attributes.source','defined') |selectattr('attributes.source','eq','blitzortung') |map(attribute='entity_id') |join(',') -}} {%- endmacro -%}
if you expand it, you can just use selectattr()
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 ..
but why?
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
But I don't think a for loop is more efficient then expanding the list of entity_ids
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
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
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
I don't agree on that, I think it makes the custom_templates more usefull
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?
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
I see, that is indeed very nice. can I also combine that with the distance of the other template? #templates-archived message
if so, it would actually be much very versatile π
set a really big default for km
Id simply use the max of the input entity?
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
https://github.com/mrk-its/homeassistant-blitzortung it seems the default is 100km, but you can set it yourself
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
I was looking at this one
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
You are never interested in the entity_id's itself I guess, just build everyting in the macro and return the count
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
{%- 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
ooh that is nice yes, thanks!
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
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
so you need to use >
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.
that also means you need to use a high default for period instead of 0
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 π )
someone can help me
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
that's not an anwer to my question, what is that state of that sensor?
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) }}```
It will take the value 175.9 from the txt file
I have sensor
- platform: file
name: Tongou T1 Energy Today
file_path: /config/www/tongou/tongou_t1_today.txt
value_template: '{{ value.split("-")[something] }}'
unit_of_measurement: "kWh"
it only take 185.49
you had that with [1] before. I want to know what it outputs if you have that
with value_template: '{{ value.split("-")[1] }}' will is 185.49
Is there any way to get the previous or previous line?
Not with the file sensor you are using
many thanks.
So with which template can I save the value to the json file
you can use the notify to file technique, and create a dedicated log file for those values https://www.home-assistant.io/integrations/file/#notifications
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}}
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?
I am using notification to file. Now I want to get the value from that txt file
Is there a way to get the 231 value of Light level in this
You need to use Javascript templates in custom:button-card, which is in #frontend-archived , this # is for Jinja templates (backend)
Thanks so much! Have a good day
as TheFes already said, there isn't. But, if your only interested in that specific last item, you could save it in an input_text I guess? Or simply check the history of the entity. Maybe the better approach is: what are you trying to do?
thanks
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
custom button card only accepts JS templates, it does not allow Jinja Templates. Check out the custom button card docs for more details.
no... use datetimes.
I'm not sure why your're even still using sensor.time
me neither... its been there forever, and I was revisiting..
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
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?
otoh, there's nothing simpler and closer to human speech than that sensor.time output..
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
Not possible
it can be done in templates, however there's nothing in the frontend that allows multi-select
You mean with yaml as "templates"?
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
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
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 π
yeah but even still, it's not really necessary. You're also using timestamps, which are largely obsolete now that we use datetimes everywhere
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
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
Wait how does it receive the inputs when multi selecting can be done in templates?
so all in all, most of that is useless IMO
it doesn't, taht's why I said it's not possible. Yes templates can select multiple items in a list, but you as a user has no way to define which ones to select because the UI can't do it.
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
Couldn't it be possible with picture elements or something like that?
Yep, exactly
how, there's nothing to define what the user selects
your best option is to make a series of input_booleans and turn on/off the ones you want
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.
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'}}
yes, you can move that to a condition
https://github.com/PiotrMachowski/lovelace-xiaomi-vacuum-map-card
There is little down there full_demo.mp4 and after 17th second he starts to select things
IIRC at also supports weekday? maybe I'm thinking of the condition
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
issue there is not so much the weekday, but the repetetive triggers
that's a 100% custom thing he built that uses code (on top of HA)
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
Oh
@marble jackal does your energy calculator support this comment?
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)
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
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