#templates-archived
1 messages · Page 71 of 1
@thin spindle I converted your message into a file since it's above 15 lines :+1:
Yep, I will start a thread with the pieces I have
Do you have a power sensor for the charger?
yes, power and energy!
thats soo nice! thank you already🙏
Calculate individual devices energy costs
Quick question...
{{ states.sensor.office_sensor_temperature.state | round > 74 }}
Would only be rendered every minute as a Template Trigger according to the docs right?
Ok, so if the sensor is updating it would then update based on the update time.
and should be written as follows:
{{ states('sensor.office_sensor_temperature')|float(0)|round > 74 }}
you're confusing a template that just starts with states|.... with one that specifically targets an entity
yeah, well
better safe than sorry
ahh ok thanks!
round float's the value, taht's why round accepts a default
Hi folks... I am newbie with HA and I would like to create a sensor from weather.get_forecasts service. When I call following using dev tools, it works:
service: weather.get_forecasts
target:
entity_id:
- weather.chambery
data:
type: hourly
But following template does not set my sensor state:
- trigger:
- platform: event
event_type: refresh_1h
action:
- service: notify.mobile_app_black
data:
message: test
- service: weather.get_forecasts
target:
entity_id:
- weather.chambery
data:
type: hourly
response_variable: hourly_forecast
sensor:
- name: Météo dans 1 heure
unique_id: h1_outdoor
state: "{{ hourly_forecast['weather.chambery'].forecast[1].condition }}"
attributes:
temperature: "{{ hourly_forecast['weather.chambery'].forecast[1].temperature }}"
Where I am wrong?
I try this trigger :
- trigger:
- platform: time_pattern
hours: /1
but seems there is a bug : https://github.com/home-assistant/core/issues/99914
So i use this workarround : https://github.com/home-assistant/core/issues/99914#issuecomment-1773882847
I try to add a notification as action, and when I call the refresh_1h event, the notification is sent
The bug only makes a warning in the logs
When a state trigger has a for property and an empty to property (i.e. sensor must be at a fixed value for at least 1 minute), what will the trigger.from_state.state value be? Will it be the previous value it was at, or the previous value it was at for 1 minute ?
it will be whatever value it was before it changed and stayed the same for 1 minute
the for: clause has nothing to do with the previous value
clear, thank you very much!
Can anyone help with the value template for a rest sensor?
https://discord.com/channels/330944238910963714/1219436082022580257
nevermind i figured it out. way easier than i expected
@tardy saddle I converted your message into a file since it's above 15 lines :+1:
good mrning, i am trying to calculate 2 entys and round the result:
{{ states("sensor.nas1_volume_2_gesamtgrosse") | float - states("sensor.nas1_volume_2_belegter_speicherplatz") | round(2) }}
Bute the result is not roundend:
Result: 3.1200300871680007
whats wrong?
You're only rounding the last one
Convert the last one to float as well, add parenthesis around the calculation and then apply the round filter
@tardy saddle that code is for a card on your Dashboard, not for a template sensor. It uses JavaScript, which is only used on the #frontend-archived in specific cards
Hello, which LLM AI is best for generating home-assistant templates?
They are all pretty bad
none of them "get it right"
no matter what, it will require knowledge to fix
Yep I assumed it won't give me 100% result. I just want to create "light proxy" with light template (https://www.home-assistant.io/integrations/light.template/)
to proxy the commands to lights behind it and I wanted to save some work.
Yep I assumed it won't give me 100% result. I just want to create "light proxy" with light template (https://www.home-assistant.io/integrations/light.template/)
to proxy the commands to lights behind it and I wanted to save some work.
that's not a template
that's a light provided by the template integration
this channel is specifically about jinja templates
which is everything in {{ }} or {% %}
I have problems casting the right value to a input number.
Can you tell me how I have to declare it?
metadata: {}
data:
value: '{{ sensor.auto_ladevorgang_netzstromkosten }}'
target:
entity_id: input_number.auto_ladevorgang_netzstromkosten_vor_ladebeginn```
That example is a pretty good starting point
sensor.auto_ladevorgang_netzstromkosten is a helper of type riemann integrator
how do you get values from an entity?
normally by states
ok then, so what are you missing from your template
🙂
so this is good?
metadata: {}
data:
value: states('sensor.auto_ladevorgang_echtstromkosten')|float(0)|round(2)
target:
entity_id: input_number.auto_ladevorgang_echtstromkosten_vor_ladebeginn```
now what are you missing?
or do I have to cast with {{ }}
what is required in pin 2 for all templates?
so like this:
metadata: {}
data:
value: {{ states('sensor.auto_ladevorgang_echtstromkosten')|float(0)|round(2) }}
target:
entity_id: input_number.auto_ladevorgang_echtstromkosten_vor_ladebeginn```
Now you're missing another requirement for yaml
- "You can do anything in templates"
- "Jinja uses various delimiters in the template strings.
{% %}..." - "you need to use a namespace if you're planning modify a variable..."
- "I see a lot of folks ask for how to know, of a group, who was th..."
- "To count lights which are on, and exclude light groups, note tha..."
- "Jinja (Template) Built-ins jinja.palletsprojects.com/en..."
- "Distinguishing Yaml from Jinja (templates) community.ho..."
- "Confused about the 2022.2 breaking
defaultchange? c..." - "Understanding types to parse JSON community.home-assist..."
- "@689168555861737485 Here's a template that looks up a friendly..."
ok so I need to quote for yaml <=> jinja and {{ }} for the inside jinja part
yep
so this should be good right?
metadata: {}
data:
value: "{{ (states('sensor.auto_ladevorgang_echtstromkosten')|float(0))|round(2) }}"
target:
entity_id: input_number.auto_ladevorgang_echtstromkosten_vor_ladebeginn```
yep
thanks for the link also - I didnt saw a explaination like this yet 👍
take a moment to read all the pins, they have good info
I will do so! Thanks 🙂
Thank you for your help. Maybe eventually I will figure this stuff out.
Hey, I have some matrix switches with 4 buttons with led behind each. I have a script where I turn off all 4 leds to reset the color. However I want to make it more smarter, since I dont want to add a script for each switch. How can i do that.
The script looks like this now, for one device.
service: light.turn_off
data: {}
target:
entity_id:
- light.matrix_kontor
- light.matrix_kontor_2
- light.matrix_kontor_3
- light.matrix_kontor_4
If I understand you correctly, the 4 lights make up a color?
I have to set a zwave parameter on the device instead
service: zwave_js.bulk_set_partial_config_parameters
data:
parameter: "31"
value:
"65280": 0
"16711680": 0
"4278190080": 0
target:
device_id: 3db9cf9bd81b65a28baabf976ede9bcd
alias: Button 2 LED indicator OFF
I still don't see what you need multiple scripts for
I don't anymore 🙂 its was mostly because of a setting, where it didn't turn off the light correctly after indicating a push
Would any templating experts mind helping me on this one. I basically have an input_select which has a list of entity ids for various motion sensors in my house. I then use a template like below on a custom template sensor, per room (eg utility room below) where I check for any motion sensors that have the word 'utility', if any of their states are 'on', then my overarching sensor is also on.
{{ (states.input_select.all_motion_sensors.attributes.options | select('search', 'utility') | map('states') | select('search', 'on') | list | count) > 0 }}
This has been working fine for many months, however I have various cases where my motion sensors messages that motion is no longer detected on a sensor (or if HA reboots) are not reaching HA for various reasons. This causes the motion sensors to get stuck in an 'on' state until someone again walks past them. It has meant some cases where some lights are left on all night, or unexpectedly left on during other period after a HA restarts.
As a workaround I was thinking of updating the template above to also only mark this overarching sensor as 'on' if some of the motion sensors attributes.last_triggered was eg in the last 5 minutes. And to filter out any who are 'stuck' for longer than this. I have been trying to no avail to get the template to filter these out. Any ideas of a way to do it? Hoping to find some way to maybe 'reject' items using something like
((as_timestamp(now()) - as_timestamp(state.attributes.last_triggered)) | int) > 300
But now to get that into my existing template, I'm getting lost.
@ocean bear I converted your message into a file since it's above 15 lines :+1:
Please see #energy-archived for screenshots of the problem
Just curious, but does template report that the two strings are equal?
{{ states('input_select.abb_charging_mode') == states('input_select.keba_charging_mode') }}
@tribal cedar
{{ expand(state_attr('input_select.all_motion_sensors', 'options')) | selectattr('entity_id', 'search', 'utility') | selectattr('state', 'eq', 'on') | selectattr('last_changed', '<', now() - timedelta(minutes=5)) | list | count > 0 }}
But why use the options for an input select for this? A binary sensor group would make more sense I would say
what does everyone think would be the best way to tackle a switch that sometimes goes unavailable. It is Meross plug, which has two switches (one local/lan and the other one cloud based). So say I wanted the switch to primarily use the local option, but if the local one was unavailable, then it uses the cloud one. Would some type of switch template be the best method?
returns False
oooooh - I got my errror
Option was called 'PV-Überchuss ' with a space at the end......what the hell...
Used this helper for over a year only in an automation - so I just clicked the option, never had the need to rewrite it...
thanks for helping
maybe something to implement - shouldnt be alowed imho
There is a local Meross hacs integration that is very reliable for me for my devices at least. If not — does the state of your local switch go unavailable?
You could drive your desired state with an input_boolean helper. And then have an automation which would flip the local switch if available else switch the cloud and flip the local switch to match the input_boolean whenever it came back alive
Or just create a switch entity which basically does the same
Hi friends, I'm trying to make a template that takes in multiple doors and uses their "open" state as a trigger; that is, trigger an action when any of them transition to open, even if another one was already open (so I can't do "when this group transitions to on..." as a trigger). Is there a good way to do this? I couldn't figure out how to do a multi-select in the automation variables. I was trying to use a fairly complex numeric state template as an alternative (that way I could make a door group outside of the blueprint and expand and check from there), but that doesn't seem to work (even though the template itself works in the template preview in dev tools when I sub in the entity ID for state.entity_id: {{ now() | as_timestamp - states[expand(state.entity_id) | sort(attribute='last_changed', reverse=true) | map(attribute='entity_id') | select('is_state', 'on') | list | first].last_changed | as_local | as_timestamp }} has a result of 0.005... right after I open the door).
Any ideas?
Are you looking to get a read out off what doors are open? So then if {trigger id} opens then = action or are you just looking to get a read of which doors are open?
Just "if any door opens (regardless of the state of any of the other ones in the group), turn the lights on".
Sent you a SS of how id set it up
timestamp sensor will do that
template:
- sensor:
- name: last open
unique_id: alsdkfjaoiehavajksdlkj
device_class: timestamp
state: >
{{ expand(... your list of entities to track) | selectattr('state','in', ['on','open']) | map(attribute='last_changed') | sort(reverse=True) | first }}
availability: >
{{ expand(... your list of entities to track) | selectattr('state','in', ['on','open']) | map(attribute='last_changed') | sort(reverse=True) | first | default(None) is not none }}
that just points out that template sensors need a variables: section
Keep in mind, if you use states without (), your template will be throttled to at most 1 update per minute.
shhh
⁽ᵇᵘᵗ ʸᵉˢ⁾
Ooh okay I'll try this!
Sorry what does "states without ()" mean? Once per minute is fine for my use cases just trying to learn 🙂
using just states
I just made a post about this on the forums
How frequent will a template update? Click here to see.
you can create variables in the action section. You just need to rebuild your normal template sensor to a trigger based one by triggering on all source entities used in the template sensor 🙂
That's a thought
Yep, usually I just use the local one. It has been super solid. Then recently and suddenly it just stopped. So it made me think it would be good to have the cloud one as a backup switch for when the local one stops working. But I just don’t have the knowledge to turn that into a switch…
Basically something like this:
In the turn_on/off keys you can write a short script checking if the local switch is available and flipping one or the other depending
The multiple command version in the docs is the relevant one
thats the part that gets me
{{expand('group.assist_satellites') | selectattr('attributes.mic_device', 'eq', states('sensor.assist_last_called')) | map(attribute='attributes.display_device') | list |first}}
I hope this is the last time I am asking for help on this. I have this and it works great, but I would now also like to modify this for a different call where it will return the entity from the group that matches sensor.assist_last_called. I think I need to do something with map(attribute='attributes.display_device') to return just the entity name but try as I might I am not able to figure it out.
I'm getting this error Template error: as_datetime got invalid input '2024-03-21 04:00:09-06:00', but if I run as_datetime("2024-03-21 04:00:09-06:00") in the template devtools it's fine.
The error does later say no default was specified as well, but I don't get why it's saying that input is bad in the first place...
is that like a value template or some type of conditional command? this is the part where I get stuck and cant work out what to put
It probably already is a datetime object
I have a PR open to make that work (it will just not do anything with it, and return the input as output)
Nice, good to know. And I thought about that being the case but I wasn't able to reproduce it again so I kinda stopped thinking about it
try as_datetime(now()) and you will see the same error
Yeah probably a good idea to have that overloaded on the backend
It's just hard to see in the error message what type it is
you could do:
{% set date = now() %}
{{ date if date is datetime else as_datetime(date) }}
or
{% set date = now() %}
{{ as_datetime(date, date) }}
Doesn't some version of that give a 'cannot convert to float' error?
That's always a weird one
the last one will return de input as output in case it can not convert it
Datetime objects are "overloaded" in the backend
the normal output for a datetime object is not 2024-03-21 04:00:09-06:00
I think it's the same use case
when stringified
normal output for a datetimeobject is datetime.datetime(year=..., day=.......) when stringified
so it may be missleading, but that's done on purpose specifically for variables in automations and outputs from templates
Not sure what you mean that the object is overloaded, I just meant that template until method to accept a date object
yes, but you're talking about the error which is
But yeah if that's the stringified version then it doesn't seem like it was a date object after all?
Template error: as_datetime got invalid input '2024-03-21 04:00:09-06:00'
I instantly know what the problem is, because I know a stringified datetime in HA will output YY-mm-dd HH:MM:SS-ZZ:ZZ
the error should probably not use the HA __str__
Ahh ok so it is a datetime
yes
Or the error can just be sure to include the type
a string with the format YY-mm-dd HH:MM:SS-ZZ:ZZ will always resolve to a datetime and won't produce the error
so this is just a rule you should keep in the back of your mind
or as_datetime() could just return the datetime object instead of throwing an error 🙂
This whole setup is kinda janky anyways how I'm using imap. I think the imap integration should be fixed to not emit events but make use of the new event entity
It also re-emits events when the integration is loaded. So I had to add something to check for the email date. Having it not re-emit would also fix this
ah, you were using it for imap events
those are indeed datetimes already
and I had the same issues
with the integration emitting events every time it's reloaded
been chillin' for a while
Nice, I've never heard anyone else using it and was surprised
Would you agree converting that to use the new event entity would be appropriate?
new event entity?
newish. Introduced maybe mid last year?
yeah, if it outputs events, any ingration using old events should change to the event entity
but that doesn't always happen
I want to say the imap change was made maybe a little before the event entity was introduced?
The event has quite some data though
Q: I made an overview for monthly, bi-monthly, quarterly [...] recurring tasks from a dedicated calendar. Working fine, now in the optimization phase. Is it possible to 'template' the definition of attributes, so I could write something like '[Jan, Feb, Mar ....]' in the definition file and write the code once to shorten it? It's 12 times more or less the same code --> screenshot here | code to optimize here.
@bronze prawn I converted your message into a file since it's above 15 lines :+1:
ughh.. that's ugly. Reposting:
Still stuck.
{{expand('group.assist_satellites') | selectattr('attributes.mic_device', 'eq', states('sensor.assist_last_called')) | map(attribute='attributes.display_device') | list |first}}
Which returns the entity in the group who's associated mic was last called. This returns the display_device attribute of that entity.
I now want the same type of thing but instead I just want the entity member of the group to be provided. I've tried altering this to get rid of the attributes portion but I am getting back a lot of data and I'm not sure how to pull just what I need from it:
{{ expand('group.assist_satellites') | selectattr('attributes.mic_device', 'eq', states('sensor.assist_last_called')) | list }}
It returns this as an example:
[<template TemplateState(<state sensor.assistsat_viewlrthinksmart=; title=Wikipedia Search, message=, image=, timer=, alarm=, cycle_view=, mode=normal, mic_device=sensor.thinksmart_lr_stt, mediaplayer_device=media_player.thinksmart_lr, display_device=sensor.thinksmart_lr_browser_path, browser_id=Thinksmart-LR, view_timeout=20, message_font_size=3vw, friendly_name=AssistSat_ViewLRThinksmart @ 2024-03-19T12:34:43.354585-05:00>)>]
I can see the name I'm looking for which is the very first part "state sensor.assistsat_viewlrthinksmart=" and I want the "sensor.assistsat_viewlrthinksmart" returned. I'm sure this is easy but I've been scratching my head on this for a long while now. Can someone show me what I'm doing wrong?
you're missing a map() call
you need to specify what you want returned out of that object
in this case, probably |map(attribute='state')|list|first
Thanks for this. Unfortunately I'm getting "sensor.thinksmart_lr_browser_path" back when using:
Group is defined as:
assist_satellites:
name: Assist Satellites
entities:
- sensor.assistsat_viewlr
- sensor.assistsat_viewlrthinksmart
To be clear, I'm wanting to check the attributes of each one of the group entities to see if the attribute mic_device matches the 'sensor.assist_last_called' value and then return the name of the group entity member that matches.
I'm not sure why it's returning the value it is returning but note that the state is null from the example I show above
so you want the entity_id
so: {{ expand('group.assist_satellites') | selectattr('attributes.mic_device', 'eq', states('sensor.assist_last_called')) |map(attribute='entity_id')|list|first}}
ohhh.. I didn't realize that was an attribute
it's confusing terminology. it's not an attribute of an entity as defined by HA, but it's an attribute of the state object
Right. I see that now. I was thinking that it's not listed as a attribute so that's not the way but I get it. Thanks for clearing this up. NOW I think I have all the pieces to support multiple assist satellite devices with different screens.
yeah, I opted not to introduce yet more confusion 🙂
nevermind that map(attribute='attributes.xxx') is a thing
You probably thought I'd stay away longer but here I am again.
variables:
target_display_device: "{{states('input_text.assist_target_display_device')}}"
target_satellite_device: "{{states('input_text.assist_target_satellite_device')}}"
target_mediaplayer_device: "{{states('input_text.assist_target_mediaplayer_device')}}"
So I'm declaring these variables. Works great.
service: chime_tts.say
target:
entity_id: media_player.thinksmart_lr
data:
chime_path: www/viewassist/broadcast.mp3
tts_playback_speed: 100
volume_level: 1
message: "{{ states.sensor.assistsat_viewlr.attributes.message }}"
tts_platform: google_translate
I'm wanting to replace the message line to show the state of target_satellite_device variable's .attributes.message. So something like:
message: "{{ states.[target_satellite_device].attributes.message }}"
Is it possible for me to replace that portion with the variable I'm declaring in variables block?
or even a:
message: "{{ states." + {{ target_satellite_device }} + ".attributes.message }}"
Type thing. Is that even possible? Wow.
don't ever nest templates like that
it's unnecessary
just remove the extra {{ }}
and use different quotes inside and out
actually, the quotes are kind of mess there
message: "{{ state_attr(target_satellite_device, 'message') }}"
fyi that doesn't work with target selectors
(talking to dinki)
target selectors return a dict
if it's an entity selector set to 1 entity, that will work (what rob said)
You guys are great. I've learned a lot in my month or so working on this project. Found out a lot more about CSS, templating, and JS than I ever thought I might know!
Pass it on!
Certainly trying. I'm trying to structure things to make it easy for folks to use and also documenting and explaining what I'm doing. Maybe it will make sense to other folks than just me.
another one. How can I get an entity_id if I have the device_id?
{{ device_entities('43a9ed37b1ef81e194be835371c8292d')|first}}
Got it. This is the one I need. Thanks!
You might want to do a more specific selection instead of using first... IIRC, list order isn't guaranteed.
BTW, lots of useful info here: https://www.home-assistant.io/docs/configuration/templating/
message: "{{ state_attr(target_satellite_device, 'message') }}"
Is there any standardization or best practice regarding use of quotation marks? Or is it just a matter of preference? I usually use single-quotes on the outside and double-quotes on the inside.
Yikes. Thanks for the info. I'll try to see if I can figure out a better way to ensure I get what I need.
oh pleaaaaseee… why not just start a brand new holy war? 😄
In the YAML style guide for documentation they use double quotes outside and single quotes inside
https://developers.home-assistant.io/docs/documenting/yaml-style-guide#templates
I think my practice of single/outside; double/inside quotes comes from the docs of the custom:button-card. It was the first card I used when I started designing my dashboard. value: '[[[ return variables.index + 2; ]]]'. Looking at the doc above, it states this:
Quoting style
Templates are strings, and thus are double-quoted. As a result of that, single quotes should be used inside the template.
Guess I'll have to go through and update... everything...
I think Frenck sent me that link once, and I'm following it since
I think JSON is the only place where it matters
Trying to save this
- if:
- condition: template
value_template: "{{ foo != [] }}"
then:
- event: Test Event
event_data: "{{ memory_event_data }}"
Where memory_event_data is a dictionary.
But I keep getting this trying to save
Message malformed: expected dict for dictionary value @ data['action'][0]['then'][0]['event_data']
Spacing got messed up when pasting
But memory_event_data is a dictionary
For example memory_event_data corresponds to
foo: adam
I'm using dict.from_keys in jinja. This has worked for other fields requiring dictionaries
For example this works
- service: light.turn_{{ set_lights }}
target:
entity_id: "{{ target_lights }}"
data: "{{ light_setting }}"
What does the service call result look like in the trace?
For this?
params:
domain: light
service: turn_off
service_data:
transition: 5
entity_id:
- light.kitchen_lights
target:
entity_id:
- light.kitchen_lights
running_script: false
Yeah I can't even save it
I'm thinking it's a bug in the config validation for that action
Because it should work
As long as the jinja is actually a dictionary
The send custom event action probably doesn't accept templates for that field. Only for the value fields of the respective keys
yeah, probably true
so just give it a key:
test_event:
sequence:
- variables:
eventdata:
foo: bar
blah: foo
- event: foo
event_data:
data: "{{ eventdata }}"
Yeah that can work. Would be nice to not need to do that though
- id: event_test
alias: Event Test
trigger:
- platform: event
event_type: foo
action:
- service: persistent_notification.create
data:
message: "{{ trigger.event.data.data.foo }}, {{ trigger.event.data.data.blah }}"
works fine with that
When I put this in a condition statement, it doesn't pass... however, when I put the exact same template in dev tools, it shows true...
{{ state_attr('light.mudroom', 'xy_color') == (0.701, 0.299) }}
any ideas?
I saved the automation, and it now works. That template is the actual condition
I meant the actual YAML, but if it works...
seems like, value template condition won't work unless first saved?
condition: template
value_template: "{{ state_attr('light.mudroom', 'xy_color') == (0.701, 0.299) }}"
I don't know what you mean by this:
seems like, value template condition won't work unless first saved?
you mean the preview that shows up in the visual editor?
meaning, I added it as a new condition in an automation, and when testing it from the visual editor... the condition doesn't pass even though it should
as in:
you mean the preview that shows up in the visual editor?
then, I saved the automation with the new condition and ran the test again, and now it passed
alright, so you're good now
yes... just pointing out potential bug in the visual editor condition testing function for the value template conditions.
Feel free to report that
Want to see what issues are open (or were open and are now closed)?
- The core (backend) - for HA itself, and integrations
- The frontend (UI) - for cards and display issues
- The Supervisor
- HAOS
- The documentation
Don't forget to check for any alerts
If you think an upgrade broke something then:
- Downgrade to the previous version to check if it works correctly there
- If it does then change the
loggersettings for that integration todebug - Upgrade to the new version again
- Look in the logs for errors
- Open an issue, following the template provided and including the log information
The system has 6 media players named media_player.soundxxxxxx.
Is there an elegant way to write a template to check that the volume on them does not exceed the specified value?
I have been trying to create "dummy" templates so that I can use the values in other areas but plain templates dont seem to work... I must be missing something...
template:
sensor:
- unique_id: my_var
state: somevalueid
sensor.my_var or sensor.template_my_var does not exist, and sometimes it does but its unavailable instead of "somevalueid"
That's a weird use of template sensors
You're not following the proper syntax
Consider any of the input_xxx helpers instead
In jinja you can variabalize + - but can >= <= be variabalized so you can do
(x - y) ~ (v ~ 2)?
Where v is >=
Essentially variabalize a comparison operator
You can do something like this
{% set a = 5 %}
{% set b = 3 %}
{% set test = '>=' %}
{{ [a] | select(test, b) | list | count > 0 }}
So, with your input
{{ [x-y] | select(v, 2) | list | count > 0 }}
Interesting very nice.
TemplateError('ValueError: Template error: int got invalid input 'unavailable' when rendering template '{{ (states('sensor.qbittorrent_down_speed') | int / 1000) | round(1) }}' but no default was specified') while processing template 'Template<template=({{ (states('sensor.qbittorrent_down_speed') | int / 1000) | round(1) }}) renders=6>' for attribute '_attr_native_value' in entity 'sensor.bytes_sent'
TemplateError('ValueError: Template error: int got invalid input 'unavailable' when rendering template '{{ (states('sensor.qbittorrent_up_speed') | int / 1000) | round(1) }}' but no default was specified') while processing template 'Template<template=({{ (states('sensor.qbittorrent_up_speed') | int / 1000) | round(1) }}) renders=6>' for attribute '_attr_native_value' in entity 'sensor.bytes_upload'
Hi, how can I ignore OR show 0 when state equals to unavailable also to prevent this error from showing up in my logs?
Sensor: http://pastie.org/p/62BiaFfoLfieAa7qkSCTVo
| int(0) after each states function
but how this will prevent the error of when state is unavailable?
because unavailable is a string that cannot be converted to an integer, so the default of 0 will be returned
value_template: "{{ (states('sensor.qbittorrent_down_speed') |int(0) | int / 1000) | round(1) }}"
like that?
ideally you would add an availability test to your sensors
well, now you're using the int filter twice...
yeah because if i'll not do /1000 it will show it in kbps
but i still need the /1000 one
fine, but that wasn't the problem
i will ask it differently, is there a way to keep it /1000 but ignore if state equals to unavailable?
in any case, you can add an availability_template to prevent the value_template from being evaluated if the states are unavailable
yes, with an availability_template
availability_template: "{{ state_attr('sensor.qbittorrent_down_speed') is not unavailable}}"
is that ok?
no, several problems with that
first, unavailable is a string and needs to be quoted
second, use != instead of is not
!=
third, you're using state_attr without specifying an attribute
unit_of_measurement: KiB/s
device_class: data_rate
icon: mdi:cloud-download
friendly_name: qBittorrent Download speed
those my attributes, so it should be state not att
I suspect you wanted availability_template: "{{ states('sensor.qbittorrent_down_speed') != 'unavailable'}}"
or availability_template: "{{ states('sensor.qbittorrent_down_speed')|is_number }}"
Thanks!
I have a input_number with a time in minutes, I'm trying to start a time with the service timer.start but the duration needs it in HH:MM
I've tried something like this and it just isn't doing what I am expecting:
{{ states('input_number.mag_counter') | int*60 | timestamp_custom('%H:%M', False) }}
Discord formatting
The resultant is 00:0000:0000:0000:0000:00...........
timestamp_custom is expecting a timestamp, and you just gave it a number of minutes
What would I use instead?
just use seconds:
Duration in seconds
in other words, just get rid of the whole timestamp_custom() part
The error says that it should be in the format HH:MM for dictionary value ['duration']
Ugh
Figured it out
So I tried this but it still doesn't work
tap_action:
action: call-service
service: timer.start
target:
entity_id: timer.mag_timer
data:
duration: '{{ states("input_number.mag_counter") | int*60 }}'
Says it has to be in the format HH:MM
You can't use templates in a tap action
🤦♂️
So the service call gets the full template text, which isn't what it expects
Call a script
Thank you
Hi, I'm new to this topic and I don't understand why my automation isn't working. Could someone possibly help me find the error?
I think I might have done something wrong with the sensor.
The sensor is displaying the correct value. The automation just isn't being triggered.
Remove the quotes around 50
I had tried that already. Then the 50 turns red, but it still doesn't work.
What value does the sensor have now?
100%
Understood. I also have the automation set for "off". If I now set the value to "below 100", it should work, right?
I'm not following
like this
https://dpaste.org/xByCt
You have 1 trigger. The sensor needs to transition from below 50 to above 50
Does it transition from above 100 to below 100?
Maybe read that whole section again
It works. Thanks for the help.
my fan lights do a nice fade in/out when going between brightness percentages, but on light_on/off it is a harsh direct to off or direct to whatever the previous % brightness was. I was thinking about a template so that if it is going on to change brightness to 1% and then to whatever it should go to and when going off, set to 1%, then to off. problem is tracking what the original brightness was (so turning it on doesn't go to 100% when it previously was on at 50%) and also do I need to make the on/off a script and call the script in the template or can I do that directly inside the template definition?
I want to use the EnergyZero integration to get a nice graph of all energy tariffs for today and tomorrow, similar to how my energy provider does it. Does anyone know how I could make a graph like that?
https://tibber.com/nl/energieprijzen For reference.
You need to store the price forecast in a template sensor, similar as I did here: https://github.com/TheFes/cheapest-energy-hours/blob/main/documentation/1-source_sensor.md#creating-a-forecast-sensor-using-the-service-call
Then you can use something like Apex Charts to put them in a graph
Hi. What's the efficient method of doing the following:
I would like get a list of my climate entities which do not have their temperature attribute set to the value that I have stored in a dictionary. I get the list of the entities via:
{{states.climate|selectattr('entity_id','search','trv')|selectattr('state','eq','heat')|expand}}
which gives a list of entities with ids of the form climate.trv_<area>
and then I have a dictionary which looks like:
{% set eco_temps = {'gabinet':20, 'kids': 20, 'salon':20, 'bedroom':20.5, 'bath':21,'shower':21}%}
where the keys in the dictionaries map onto the <area> substring in the entity_id
what
you want to take the temperature and map it to the area?
{% set ns = namespace(items=[]) %}
{% for climate in states.climate|selectattr('entity_id','search','trv')|selectattr('state','eq','heat') %}
{% set ns.items = ns.items + [ (area_name(climate.entity_id), climate.attributes.temperature) ] %}
{% endfor %}
{{ dict.from_keys(ns.items) }}
but I have no clue what you're actually asking
he wants to know which climate entities are not on the temp from the eco_temps dict
I somehow missed that line
OK, so something this?
{% set eco_temps = {'gabinet':20, 'kids': 20, 'salon':20, 'bedroom':20.5, 'bath':21,'shower':21}%}
{% set ns=namespace(count=0)%}
{% set trv_list = states.climate|selectattr('entity_id','search','trv')|selectattr('state','eq','heat')%}
{%for trv in trv_list%}
{% if trv.attributes.temperature == eco_temps.get(area_id(trv.entity_id),20) %}
{% set ns.count = ns.count + 1 %}
{% endif %}
{%endfor%}
{{ns.count}}
oh, how many
Hmm, maybe not 1 line
are the climate entities also assigned to an area?
yeah I forgot to tell you that - the area_id's are the keys of the dict
I half came up with the above, but I don't know if that's the effiient thing to do
{% set ns = namespace(items=[]) %}
{% set eco_temps = {'gabinet':20, 'kids': 20, 'salon':20, 'bedroom':20.5, 'bath':21,'shower':21}%}
{% for climate in states.climate|selectattr('entity_id','search','trv')|selectattr('state','eq','heat') %}
{% set target = area_id(climate.entity_id) %}
{% set temp = eco_temps.items() | selectattr('0', 'eq', target) | map(attribute='1') | first | default(None) %}
{% if temp is not none %}
{% set ns.items = ns.items + [ climate.entity_id ] %}
{% endif %}
{% endfor %}
{{ ns.items }}
that'll just give you a list of entity_id's that aren't matching their area, if it has a matching area
now you may need to change {% set target = area_name(climate.entity_id) | slugify %} instead of what's there
it depends on when/how you created the area.
if you want a list of area names, it'll be different
Ok I think I can manage from here -- I was wondering if there is some map-filter magic one can do but iterating through the list is the simple thing. Thanks a lot!
i have 2 identical template sensors. ever since upgrading from 2024.2.5 to 2024.3.3, they do not seem to update after the initial update they get from the raw sensors. in addition, 1 of the template sensors does not save its state, so on reboot it reverts back to unavailable instead of the last value, whereas the 2nd template sensor does save its state.
here is my configuration: https://dpaste.org/53dBz
im wondering why this worked before, and now doesnt work on 2024.3.3, and what i have to do to fix it
also i noticed in states that the last updated and last changed of the "stable" is not changing every minute as configured in the template. i cant recall if it was like this before, but it seems like the time pattern of every minute "/1" is not being followed
the rest sensors don't work?
if they don't look in your logs for errors
the rest sensors work, they just take a few minutes to start working (and are api throttled). so on restart, they are set to unknown for up to 10 minutes
the template sensors are the ones that are the problem
so what's the problem with that? You're pulling the states every 1 minute, so I'd wager that those will be unknown too
until the source gets values
i was under the understanding that template sensors persist on reboot, and only update if the source was a valid value (not unknown or unavailable)?
Is there some way of getting a list of entity_id's from a list state objects which are generated by selectattr without iterating in a for loop?
i guess the 2nd part of that is solved by calling "states()" but thats part of my template sensor
the goal of stable sensor was to eliminate the noise i get from the raw with random api failures, gaps because of restarts, etc.
but again, this worked in 2024.2.5, but now is not working in 2024.3.3, so i feel something changed that either broke something, or changed how these work but i cant find the change in any docs so im not entirely sure
yes but the time trigger will update immediately
that's how you have it set
if it takes 10 minutes to get a state, but you ask for a state during those 10 minutes, you're going to get whatever is in the rest sensor
but using "states(sensor)" prevents that if the sensor is unknown or unavailable, yes?
oh, thats not how it worked before (because these have worked flawlessly for the last month). i can try the template sensor to check "is_state" first, but im curious. why does 1 template sensor still have the last value, but the other template sensor doesnt?
this is right after a restart
hmm, i cant seem to add an image to the chat like you did
are you in between a poll period?
it checks every minute on the minute IIRC with that trigger
that was right after i restart HA
in fact, the basement stable doesnt update to a value until the raw updates, and then it wont update if the raw gets changed.
so there are 2 issues as i originally mentioned, but im not sure if they are related
are there errors in your logs?
yes i see
Error doing job: Exception in callback _TrackPointUTCTime._run_action()
<additonal error messages>
ValueError: could not convert string to float: 'unknown'
<stack trace>
ValueError: Sensor sensor.basement_remote_sensor_stable has device class 'temperature', state class 'measurement' unit '°F' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'unknown' (<class 'str'>)
so i see it as a byproduct of the sensor not pulilng the right value, because i think it is trying to convert the "unknown" to int
my rest sensor also has an error, but thats expected because it requires some rotating tokens and is rate throttled, so that is why it is a bit intermitent (and why i wanted a stable sensor) as i get errors daily
So you should either provide a default for your int conversion with int(0) (or whatever you want) or use the availability field to prevent rendering if the source value isn't a number
i can add "is_state" to check first, but im still confused why the 2 sensors act differently. why would 1 need it, but not the other?
The source sensor is different
they both from source from an identically designed sensor. their name is different, but they act the same
no. theres a difference in the value, but i dont understand why
Yes, so basically you can't return a value when it doesn't have one
most likely the onboarding process for the 1 that has 65 is failing at the one with unkonwn meaning it never loads the 65 one
which is why your 65 one isn't updating
so your yaml is this:
which makes sense
that's the issue with yaml
if i set the state through dev tools, shouldnt it store the state for the next reboot?
no
set_state does not do what you think it does
this is why we always tell people to never set state
Just set availability for each
it won't give what he want's then
needs to use this.state
and always return a value
that's numerical
for it to not error in the beginning
i thought this.state was not supposed to be used anymore?
IIRC thats what i saw, and saw instead to use "states()". but this was from a month ago so maybe i am remembering wrong
sorry im very confused. i looked up is_state and saw there is no way to set is_not_state, so i just used a | and i am getting different results. and then i also noticed it is listening for entity unknown (is this correct?).
https://imgur.com/a/PXJm9Lp
for some reason line 9 evaluates to unknown but should be an int, or line 10 should not evaluate to 4. this combination should not work
{% set raw = 'sensor.basement_remote_sensor_raw' %}
{% if raw | has_value %}
{{ states(raw) }}
{% elif this.state is defined and this.state | is_number %}
{{ this.state }}
{% else %}
0
{% endif %}
if sensor.basement_remote_sensor_raw is unknown then this is undefined
this.state is looking at itself, not the raw
let me try this in the template, because the dev tool is throwing an error
because this.state doesn't exist in the template editor
you can test there by adding
{% set this = {'state': 40} %}
before that whole thing above
good afternoon - is it possible to do a count of objects in a response? For example, if an API returns an array (say of devices connected to wifi) is there a way to count the number of objects, instead of listing each one?
|length
the specific use case is a RESTful connection to a wifi router that sends back a list of all devices connected, I would just like to know how many
|count
cool - thanks! I dont mess with templates much, I do most in NR and MQTT but I am trying to make a package I can share with other router owners for their use as well
the next question is - without MQTT discovery, is there a way to create a device and then the entited off of that?
probably through websockets 🤷
Sorry I am trying to dive you a screenshot
i use MQTT discovery currently to create the device, and then sensors off of that device
I am hoping there is away to do that without MQTT discovery (i am trying to convert from the dark side (Node Red) )
gotcha, thanks I was not sure I was exlaining correctly, I was not ignoring
generally, you'd create a companion integration that communicates with external software or a device and creates devices & entities for HA
there's already one for NR, but I have no idea what it does
not sure I am up to making an integration, but above my pay grade!
but might be worth the attempt - juyst what I needed another project 🙂
this appears to be working, but i have been trying to add and test while on a call for work. so i will continue testing but i think this fixed it, thanks.
i didnt realize this defaulted to 0 though as the last exception, so now i have to figure out how to remove this value from history because it makes my graphs look wonky. if you happen to know how id appreciate it, but otherwise i realize its my mistake and a different topic all together
how can I set the value of a jinja2 variable to be unknown?
Is possible to access the last_changed of an attribute?
Like this:
{entity.attribute}.last_changed
no, that's not recorded
Ok
you'd need to make it a proper sensor first
please explain more
@mighty ledge: question.. In my relative_time_plus macro I forgot to use quotes in one place. I should have used 'error' instead of error (see this simplified version)
but why this this work for me (okay it didn't pass the if, and went to the else) and did this person get an error about a variable not being defined https://github.com/TheFes/relative-time-plus/issues/41
What should enter as time condtion to make a template trigger at the start of every week?
template:
- trigger:
- platform: time
at: "00:00:00"
- platform: time
Thats for every day, but what do I enter for every week?
seems like undefined errors aren't raised anymore
what's the start of every week?
monday 00:00
so they were using an older version of HA probably
typically, you do that trigger with a condition pointing out monday then
that would be my guess, I know they were raised in the past. Now they don't seem to be
the devs be like
There it issues a warning, wonder why it doesn't do that with the template above then 🙂
no warning
I thought it might have to do with it being used in tests
but then:
funny that it retruns true
how can i get the index of a timestamp in an array? i want to start from that index and to the end in a calculation ...
like array | indexof(timestamp)
or whatever 🙂
{% set list = ['a', 'b', 'c'] %}
{{ list.index('b') }}
This wil return 1
ah so it was that easy 🙂
hey, why can't I use a template in the beginging of the message sentence, like this:
- service: tts.speak
data:
cache: true
media_player_entity_id: media_player.basement_family_room
message: {{trigger.id}}, your phone is now ringing.
target:
entity_id: tts.piper
you can, what's the number 1 rule of in-line templates?
🙂 ' or '' ?
🎉
whatever floats your boat
thank you
good morning - this is likely something simple, but I am running into an issue when there is a number in the path for value_templates:
"value_template": "{{ value_json.cellular.sim.1.simCardDetected}}",
if I change the '`1' to 'one' in the corresponding MQTT data, it works, but the data coming back from the API call I am making has the numeric 2
the source data is:
"cellular": {
"network": "LTE-A",
"mobileType": "LTE-A",
"modulePowerOn": true,
"sim": {
"1": {
"active": true,
blah['1'].blah
LOL Crap 🙂 I tried blah[1],blah - blah.[1].blah but now that you point that out, that;s a forehead slapper 🙂
@mighty ledge Thank you!
I have another template question, if anyone is around.
I am trying to create a MQTT binary_sensor.
Here is the definition:
unique_id: Pepwave Router 111Cell SIM 1 Active
state_topic: integration/pepwave/status/wan/cellular
value_template: '{{ value_json.cellular.sim['1'].active}}'
payload_on: 'True'
payload_off: 'False'
device:
manufacturer: Pepwave
identifiers: 293B-1637-2F63
sw_version: 1711471720472
name: Pepwave Router
model: Pepwave MAX BR1 Pro 5G
platform: mqtt```
the value of sim['1'].active is "true", but regardless of whether I set payload_on: True or payload_on: true it still shows unknown
i have that value already in a sensor, so I can confirm it is reading the right values
Did you also try without quotes?
when I open up the entity in the displaty, it says "Unknown" but there is a log entry that it turns on \
let me try a few things - maybe the API pull is coming down with a different format
outside quotes should not match inside quotes
you have '{{ ' ' }}', it needs to be "{{ ' ' }}" or opposite '{{ " " }}'
question? I have my template set like this:
{% set next_event=as_timestamp(state_attr('calendar.school_days','start_time')) | timestamp_custom("%Y-%m-%d",true) %}
{% set tomorrow=(now().date() + timedelta(days=1)) | string %}
{{ next_event == tomorrow }}
I get the state as off when my calendar clearly shows school for tomorrow (The state should show 'on'). i cant figure out what is wrong on my template.
Just compare two dates:
{% set next_event=as_datetime(state_attr('calendar.school_days','start_time')).date() %}
{% set tomorrow=(now() + timedelta(days=1)).date() %}
{{ next_event == tomorrow }}
I still get the state being off when it should be on?
Put it all in the template editor in developer tools, and add the lines
{{ next_event }}
{{ tomorrow }}
Then paste the result of the template here. Format it with backticks ```
I pasted and got false for result
{% set tomorrow = (as_timestamp(now()) + 86400) | timestamp_custom('%Y-%m-%d', True) %}
{{ next_school_day[:10] == tomorrow }}```
What is the result of this:
{% set next_event=as_datetime(state_attr('calendar.school_days','start_time'))%}
{{ next_event }}
{{ now() }}
2024-03-26 16:08:00.519287-05:00```
Okay, so your next event has the same date as today
It's probably the current event though
And then tomorrow would be 2024-03-27 so your comparison will be false
Oh i want it for the next day so i can set automations for the next day
If you have an all day event today, it will show that event the whole day today
oh ok i set school day as a all day on my calendar
If you want to check if there is an event tomorrow, you need to to create a trigger based binary sensor and use the service call in the action part
correct as i was trying to create a template binary sensor helper. but getting this error
No, you were using the actual state of the entity, which will show the all day event of today.
You need to use the service call to be sure you check for tomorrow
Are the only events on that calendar the all day school days?
template:
- trigger:
- platform: time_pattern
hours: "/1"
action:
- service: calendar.get_events
target:
entity_id: calendar.school_days
data:
start_date_time: "{{ today_at() + timedelta(days=1) }}"
duration:
hours: 24
response_variable: result
binary_sensor:
- unique_id: 827a6f7d-b3fa-4eb4-92cf-c1542fac4d97
name: School tomorrow
state: "{{ result['calendar.school_days'].events | count > 0 }}"
Something like this, note that it will be unknown until it triggers
Thank you
By all accounts, this automation should work:
- service: script.single_press_{{ (trigger.event.data.devicename|slugify) }}
however it results in a calls an unknown service: script.single_press_thomas.
The called script exists and has the correct name, what gives?
you don't need the parentheses, but it should be fine
Hi, it's possible to expose script to HomeKit ? or to start script when i stop roomba by using siri ?
it's ok, i forgot to reload homekit bridge --"
Im trying to make a sensor that stores the minimum temperature of the week, using a template trigger. But it never seenm to trigger, why?
`
template:
- trigger:
- platform: template
value_template: "{{ states('sensor.temp') < states('sensor.temp_min_week') }}" - platform: template
value_template: "{{ now().weekday() == 0 and now().hour == 0 and now().minute == 0 }}"
sensor: - name: Temp Min Week
unique_id: emp_min_w
unit_of_measurement: "°C"
device_class: temperature
icon: mdi:thermometer-chevron-down
state: "{{ states('sensor.temp')}}"
attributes:
datetime: "{{ now() }}"
`
- platform: template
You are doing a string comparison. And you should account for the initial state of your template sensor being unknown
Yes, I have set an intial value form template sensor so its not unknown
Both templates renders correctly in templates developer tools
If change the date template to the current time it render true , so it should be correct
{{ now().weekday() == 2 and now().hour == 9 and now().minute == 18 }}
Yes, but it will only trigger if it changes from false to true
The problem is in your other template
template:
- trigger:
- platform: template
value_template: "{{ states('sensor.temp') | is_number and this.state | is_number and states('sensor.temp') | float < this.state | float }}"
Ok, thanks I gonna try that
You could also use this https://www.home-assistant.io/integrations/statistics/
Oh wait, that won't start at Monday
Hmm, I gonna look into that
If I use a statistics sensor for determining the min value is also possible to have the datetime_value_min as an attribute to that sensor, or do need to create an additional sensor for that?
Nope, it does still not trigger.
I removed the weekday trigger, for testing. And sensor.temp has a initial state set.
Here is the full code, that I tested
template:
- trigger:
- platform: template
value_template: >-
{{ states('sensor.temp') | is_number and this.state | is_number and states('sensor.temp') | float < this.state | float }}
sensor:
- name: Temp Min
unique_id: ute_temp_min_v
unit_of_measurement: "°C"
device_class: temperature
icon: mdi:thermometer-chevron-down
state: "{{ states('sensor.temp')}}"
attributes:
datetime: "{{ now() }}"```
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
Please properly format your YAML
It still won't trigger until it changes from false to true
Change your temp sensor value in devtools > states to something above the current value of your template sensor, and then change it back to the current value
And you shouldn't have removed the 2nd trigger, now it won't reset on Monday anymore
Yes, but I have been doing that all the time, that's what mean by it has an intital state
I removed it just for testing
No, change the state of sensor.temp to something above the current state of sensor.temp_min and then change it back to what sensor.temp was before
Ok I will test that. It is set to 100 now and I will set it 101
Nope, it it still won't trigger 😦
Doesn't seem to update no matter how I change the states
A different method. Instead of using a Template trigger I use a State trigger.
this object can’t be used in the trigger definition
I don’t think this is available in the actions section either?
It definitely is
What does it populate with when multiple sensors are defined under a single trigger?
it doesn't this can't be used outside the sensor itself, mekaneck is correct
in drews case, your or is always defaulting to the second case on the or statement
Thanks. Really second guessing myself after looking at the docs and those are wrong too
https://www.home-assistant.io/integrations/template/#template-and-action-variables
State-based and trigger-based template entities have the special template variable
thisavailable in their templates and actions
well, it needs to be verified then
I could see how it might exist, if each sensor has it's own this associated with it
I haven't dove into the code, but it's possible each sensor is loaded separately but all have the same listener, so each have their own this
which means the actions are parallel
and this would make sense, but I could see that not being the case
@lucid thicket Sorry for the insistence... apparently I completely misremembered how I set my original sensor up. I do indeed have this in the state template, not the action block.
Yeah you may still be right, no worries. I’ll run a test some time later to see what happens. I’m no good at looking at the code.
Hi, I'm just beginning trying to understand templates, so this is probably a very basic question. I have
{% for state in states.sensor | selectattr('attributes.device_class','==','temperature') %}
which works fine, but I have sensors that don't have a device class, can I still use this method for making a list?
If you add |selectattr('attributes.device_class', 'defined') before the existing selectattr()
that includes devices that don't have a class?
I'm looking at a tutorial that uses this as an example:
`{% set output = namespace(sensors=[]) %}
{% for state in states.sensor | selectattr('attributes.device_class','==','temperature') %}
{% if 0 <= state.state | int(-1) %}
{% set output.sensors = output.sensors + [state.name ~ ',' ~ state.state ] %}
{% endif %}
{% endfor %}
{{ output.sensors | join ('\n') }}`
This outputs every device with an attribute of temperature. I have multiple devices with a camera attribute and want to output that list. If I change 'temperature' to 'camera' nothing shows.
I think you're confusing devices and entities... the template returns sensor entities who's device class is temperature.
Camera isn't an allowed device class for sensors (the terminology is a bit confusing).
okay, I get it, I think. I have sensor.double_take_bob, which has an attribute for camera. But in order for this to work, this entity would need a device class of camera, which does not exit, correct?
This template is only looking for things that have a device_class of temperature, duh. So then, how would I look for all entities that have an attribute of camera? If that makes sense.
What do you mean "which has an attribute for camera"? Is it like camera: true?
it's camera: officetable1
Ok, then you can just check for that attribute being defined similar to Rob's answer above
{% for state in states.sensor | selectattr('attributes.camera','defined') %}
okay, that works, thank you! One step closer.
By chance do you have any recommendations where one could start learning about templating in HA? I feel like these are basic concepts that I'm missing.
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
start with the second link
I've been using the second as a reference, if I had read through it all instead, would I have understood the answer to my own question?
maybe?
lol, fair point, silly/difficult question
search here and the forums
you are never the first or even the 1000th person to ask any question, really
home assistant how do I do something is an excellent Google search
I've been using that a lot, and chatgpt which is sometimes helpful in understanding when it's right. I just feel like I"m jumping around and not necessarily in order.
When I started out skalavala's Jinja helpers was helpful, just be aware that it hasn't been updated in a while so there are now better ways to do some things in his examples.
thanks, I'll check that out. Without an actual templating for ha class to take, various tutorials, explanations and trying things out will have to do
And as I mentioned, search the forums and discord
but playing in
-> Templates gives you realtime feedback and is a great place to try things and learn
yeah, it's a god send. I wish I could make it much larger to see more at once. I've spent hours each day trying almost random things to see what works
it would be nice if were reformatted into a vertical layout
or some bars to change the size, I have a 49" ultrawide that could use that realestate better imo
all the dev tools really need to be rethought, as there's often value in using results from each tab in other tabs, especially now that service calls can return results in a variable, but you can't then easily use that in the template dev tool
@bright lark I converted your message into a file since it's above 15 lines :+1:
you're not following the format from the docs
you at least need to add a - before sensor:
Yep, that was it @inner mesa
Thanks
I think I'd been looking at it so much, I couldn't see the wood for the trees 🤦🏻♂️
I want to create a template sensor that self-references (because it accumulates). So in the template code I need to obtain the state of the sensor I am writing the code for. How can I know with 100% certainty what the entity_id will be for this sensor, so that I can correctly self-reference it in its own code?
How can i set a numeric value to the current numeric value minus 30, so to say.
metadata: {}
data:
value: 20
target:
entity_id: input_number.living_room_virtual_brightness```
i basically want the value to go higher or lower. not set to 20.
evening! trying to get a "Home for x hours" sensor going on my person card and I'm pretty close, but this only returns home and not_home. how can I get the sensor value based on my zone, e.g. Home, Work, Store, Town, etc.? {{ ( states.person.myuser.state )|capitalize }} for {{ relative_time( states.myuser.jason.last_changed ) }}
You'll have to use a lambda to pick up {{ states('input_number.living_room_virtual_brightness') | int + value }}
euuhhhh... 😅
states('person.myuser') is the way
You can use the this variable for self referencing. In this case you'll need this.state
https://www.home-assistant.io/integrations/template/#self-referencing
@haughty kiln I use a template sensor that resets each day. This won't give you exactly what you're looking for, but it gives an aggregate of hours home per day
i tried the following, but executing it returns a error 😅
data:
value: "{{ states('input_number.living_room_virtual_brightness') | int - 40 }}"
cunningham's law
lol i just googled that.
it works more often than you'd think
a wrong answer because code isnt working, still i copied that from the haos forum.
ah, had to include a entity in that above yaml. now works 🙂
yeah, I forgot the quotes in the initial reply as well
for the life of me, I can't get this script to call another script with a templated name
it even passes the value_template: '{{ states(entity) != ''unknown'' }}' conditional
Result:
result: true
entities:
- script.single_press_officeceiling```
`Error executing script. Service not found for call_service at pos 4: Service script.single_press_officeceiling not found.`
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.
Share your entire script
Hello, I can't extract parameter from json. what is correct syntax ?
{{ states.sensor.sms_network.state}} show me {"NetworkName": "Unknown", "State": "NetworkStatusUnknown", "PacketState": "NetworkStatusUnknown", "NetworkCode": "", "CID": "", "PacketCID": "", "GPRS": "Detached", "PacketLAC": "", "LAC": "18337908"}
I want to extract network name, but I'm unable to, {{ states.sensor.sms_network["NetworkName"] }}
{{ (states('sensor.sms_network') | from_json)["NetworkName"] }}
all states are strings, so you need to convert the json string to a dictionary first
might be better to put it in an attribute if you created the sensor yourself
I also expect the 255 character limit for states to become an issue here
use a card which support templates, like a Markdown card, or create a template sensor using that template and use that
how do I check an array length? is this right?
{{ trigger.payload_json.after.entered_zones | length > 0 }}
also, is there a best practice for that dot-walking method vs using
trigger.payload_json['after']['entered_zones']
Dots are a shortcut that you can use if the field doesn't start with a number, isn't a variable, and doesn't have spaces in it
Doesn't have 'special' characters
is that the right way for checking that an array isn't empty?
piping to length and then > 0?
It's fine
Hii, I have a newbie question, can any one explain and help me solve this - why do I get [object object]
- type: custom:more-info-card
entity: climate.aciravoda_4
title: {{ states("binary_sensor.salon_sensor") }}
You need to quote your template
like this?
title: "{{ states('binary_sensor.salon_sensor') }}"
Yes. Does it work?
Easy to check
I'm assuming that you've already established that that card even supports templates there
nope and nope
what can I do if it doesn't?
Find one that does
Initial automation: http://pastie.org/p/53UrLurDIP8fFZkYaJgJCJ
script.single_press_global http://pastie.org/p/2jIJoJq1EgOmU1IGHDq5PC
script.single_press_officeceiling http://pastie.org/p/6aWN5Xh4J1HARZlvQCudcm
First thing I notice you slugify the device name in one template, but not in the one for the entity variable
Is it correct that when I do this:
mid: "{{as_local(state_attr('sensor.wu_other_sun_solar_midnight','today'))}}"
h7: "{{mid+timedelta(hours=7)}}" # 7 h after last solar midnight
where the sensor in mid is a datetime, defining h7 complains that I am concatenating a str and a datetime? Are all variables defined through variables always strings?
the sensor.wu_other_sun_solar_midnight is 2024-03-27T22:48:48+00:00
@marble jackal I've been playing around with whether it needs to be slugified, I must have left it. Let me make them uniform and give it a go
What does that event send
Which you use for the trigger
Anyway, it will be something for tomorrow for me
the event looks like
event_type: esphome.single
data:
device_id: 90f442478b2298e0c654d9c313bfc52f
devicename: officeceiling
name_friendly: Office Ceiling
action: single_press
mode: Always On
brightness: "off"
Mode can be ["Always On", "Switched", "Always Off"]
brightness can be ["off", "bright", "medium", "low", "night"]
I don't know what that "today" attribute's value is (you mentioned the sensor state itself), but this works for me with a random entity with an attribute:
{% set mid = state_attr('alarm_control_panel.area_001','changed_by_time')|as_datetime|as_local %}
{{mid+timedelta(hours=7)}}
perhaps that will help
Thanks -- the weird thing is that it works ok in the template editor, just like you have, but it fails to work in the variables statement in an automation. it seems that the datetime gets coverted to a string when the variable is defined
this particular 'today' attribute is just a datetime string
if it treats it as a string, just convert it (again?)
yeah, i've ended up droing this:
h7: "{{as_timestamp(as_datetime(mid)+timedelta(hours=7))}}" # 7 h after last solar midnight
but is that the expected behaviour or a bug
datetime objects are weird in that they're not serializable, and that restricts where they can be used
yet again timestamp wins. 😉
@inner mesa Automation works correctly now. I had to delete script.single_press_officeceiling and recreate. Originally I made the generic script without specifying an entity_id, then I edited the script in the UI and added the entity_id.
This time I specified the entity_id when creating the script, and it loads properly
I have a template as a string inside of a variable. I simply want to print the contents of that variable, but it seems to get evaluated first instead of just printing it. Here is a simplified example:
script:
test_script:
alias: 'Test script'
sequence:
- variables:
my_var: "{% raw %} {{ (value | float(0) * 14.503773) | round(1) }} {% endraw %}"
- service: notify.test_log
data:
message: >-
{{ my_var }}
When the script is executed, I get the error that 'value' is undefined
How can I get the contents of the variable without evaluating it as a template?
Hi there,I'm a NEWBEE in HA and Templates at all. I'm looking for a simple Template to invert a binary_sensor output. I need help. Thanks.
You are sending the template to the notify service, and then it's rendered there. Where the value variable doesn't exist
hey there!
was wondering if I can use notify.phone to be able to send a photo that located in /config/www/tmp/snapshot_vacuum.jpg in addition to the template below.
service: notify.home_assistant_group
data:
title: :broom: Vacuum Robot has finished and returned to base!
message: >-
It took {{ ( states('sensor.roborock_s8_pro_ultra_last_clean_duration') |
int / 60 ) | round(1) }} minutes and covered {{
states('sensor.roborock_s8_pro_ultra_current_clean_area') }} m².
Is there a way to work around that, so that it doesn’t get rendered? Maybe this behavior changed? I’m using this post as inspiration but it has the same problem with the template inside the variable being rendered.
What is your goal here, why do you want to send a template?
Stats of last run of the vacuum cleaner with photo of where did he excatly cleaned in this specific run.
I’m doing the same thing as the post (writing a script that uses mqtt.publish to create a bunch of mqtt sensors via autodiscovery). Using notify was just easier to make a simple example.
Some of those sensors utilize a value_template or a json_attributes_template
Create a template helper and use this code:
{{ not states('binary_sensor.my_source_sensor') }}
service: notify.phone
data:
title: foo
message: >
bar
data:
image: /local/tmp/snapshot_vacuum.jpg
@sonic sand It is all explained on this page https://companion.home-assistant.io/docs/notifications/notification-attachments
And as easy to implement by the example from mekaneck
Thanks!
Anyone much smarter than me that know this simple, i guess template? i want to test two states, one attribute and one state of same entity. this is only attribute and works:
{% if 'tv.emby.embyatv' in state_attr('media_player.shield_tv_adb', 'app_id') %}
on
{% else %}
off
{% endif %}
But i want it like this, but this is not working ofc just added " & " :
{% if 'tv.emby.embyatv' in state_attr('media_player.shield_tv_adb', 'app_id') & if 'playing' in state('media_player.shield_tv_adb') %}
on
{% else %}
off
{% endif %}
Thanks! 🙂
replace & if with and
all you need is
{{ 'tv.emby.embyatv' in state_attr('media_player.shield_tv_adb', 'app_id') and is_state('media_player.shield_tv_adb', 'playing') }}
you don't need the if statement saying explicit on/off
depends on what they're doing with the result, but generally yes
if they are outputting on/off then something else isn't configured correctly
i.e. they are amking a sensor when it should be binary, or payloads aren't set to True/False, etc
Thank you both so much!!! 🙂 I want a input_boolean to auto turn on/off by that state 🙂 to block oone automation. but maybe Binary sensor is the correct way then? i have to try!
I return on and off sometimes when using a template to construct a service name, but that's probably a more advanced use case 🙂
Trying to write an automation that will rotate through a list of views. The list looks like this:
cycle_view: "clock,weather,traffic"
Can I use a template with an automation like:
repeat:
for_each:
{{ my template }}
sequence:
maybe, if you format them properly
definitely, if you do this:
cycle_view:
- clock
- weather
- traffic
and
repeat:
for_each: "{{ cycle_view }}"
sequence:
The cycle_view is part of a custom device template that I have. I am open to ideas on how to store those values but it is stored as a single line of text as of now
Is there a way to store a list as a line of text?
why does it need to be a line of text?
I don't know what your first sentence means
do you mean that it's a custom template that you've imported?
Click on the entity id, it will show you the structure with proper YAML
Copy, and paste that
Is that for me? Not sure I'm understanding what you are telling
Yes, that was referring to your posts, see the screenshot
Oh, I got you. I can set the state fine, I'm just not sure I'm going about it properly for how I pull that data back out to go into a for_each
I'll give it a try and see what happens 🙂
Yes, and having it properly formatted will help getting the data out in the right way
It is possibly a list already, but that attribute column won't show it like that
I created the template sensor myself. I did not set any specifics on data type for any of the attributes if that is even a thing
attributes can have native Python types, including lists
so if you created the sensor yourself, make the attribute a list
@bronze prawn I converted your message into a file since it's above 15 lines :+1:
So:
{{ state_attr ('sensor.assistsat_viewlrthinksmart', 'cycle_view').split(',')}}
gives me:
['clock', 'weather', 'info']
So that should be usable with the for_each right?
you declare a type simply by making the value of the attribute conform to the syntax of that type
I gave you an example above
I'm coming at this from a novice level so please excuse my ignorance.
Yep. I did see that, but I am unsure how I would format it that way. Am I just setting those values like shown? Add a hypen space viewname carriage return then repeat for each?
hmm, I guess it doesn't like that for some reason
yes, that's how lists are denoted in YAML
Yeah, I just tried and it doesn't retain the carriage returns. I end up with something that looks like this:
cycle_view: "- clock - weather - info"
Do I need to use the \n \r instead?
this works fine
- sensor:
- name: test_list
state: something
attributes:
cycle_view: "{{ [ 'foo', 'bar', 'blah' ] }}"
Thanks. Will give that a try.
Okay, defintely able to replicate this now. Thanks for showing me this. Further, if I want to create a dictionary, I can use the same type of thing just so long as I format it correctly? I may want to do something like [ 'clock' : '25', 'weather' : '30', 'front' : '25' ]
this would allow me to set the amount of time to show the view before cycling to the next view
oops. yeah, wrong bracket type. This is awesome
hello, how to say for my input variable for my script for if-then condition if that variable is not null?
{{!my_variable1}} ?
{{ my_variable is not none }}
Hi again, still working on my car sensors and I'm stuck. Is this proper format for json_attributes_template? It looks good in template editor but even if I hardcode the values I do not get any attributes.
json_attributes_template: >-
{ {% for i in states('sensor.car1_pids_supported_1_32') -%}
{% if i == '1' and loop.index | string in states.sensor.pids.attributes -%}
"{{ loop.index }}": "{{ state_attr('sensor.pids', loop.index | string) }}"{% if not loop.last %}, {% endif %}
{% endif %}
{% endfor %} }
Can somebody please help me create a condition? I want to check if the value from an entity is above the value from a specific helper (type: number).
The value from the entity looks like this: 281h 14m 49s
It's sufficient when the first number (281) is checked against the helper value
I'm happy to point you in teh right direction, but you will need to fill in the details yourself
?
Is there any way to md5 hash a value in templating?
...I have a rest API login that needs the user/pass hashing along with a session key that's returned by an initial request before the login one.
{{ states('sensor.someentity')|regex_replace('([0-9]+).*', '\\1')|float > states('number.someentity')|float }}
Sorry, I'm not sure were I have to fill in this code. I have insert a "numerical state" in the condition area and filled in this code in the YAML editor
```{{ states('sensor.v2_5162_totals_print_time')|regex_replace('([0-9]+).*', '\1')|float > states('input_number.nevermorewechsel')|float }}````
But I get a error:
Message malformed: Entity is neither a valid entity ID nor a valid UUID for dictionary value @ data['condition'][0]['entity_id']
You can if you install the Spook custom integration.
Perfect thanks
You need to switch from the Numeric State condition type to a Template condition
I can't get it I have tried every which way and been struggling all day. Do attributes update even if the state value doesn't change?
they can
I don't know what you've been struggling with, but this simple template sensor demonstrates it. I just watched the attribute update:
- sensor:
- name: time_test
state: foo
attributes:
current_time: "{{ now() }}"
Trying to do mqtt sensor with json_attributes_template.
json_attributes_template: >-
{ {%- for i in states('sensor.car1_pids_supported_1_32') -%}
{% if i == '1' and loop.index | string in states.sensor.pids.attributes -%}
"{{ loop.index }}":"{{ state_attr('sensor.pids', loop.index | string) }}"
{%- if not loop.last %},{% endif -%}
{% endif -%}
{% endfor %}}
Even if I hardcode some values I don't get any attributes. Do you know if I have to specify json_attributes_topic? I haven't tried that.
I think I just answered my own problem. Must specify mqtt topic. Wow the whole day I spent on this stupid thing lol
Is there a way to check when the mqtt integration was last reloaded? I have an automation that triggers when some important (to me) entities go offline. So I'm triggering on the unavailable / unknown states. Reloading the mqtt integration (e.g. enabling an mqtt entity like lqi, which is disabled by default, causes a reload) triggers a lot of false alerts. If I could add a template condition to check the mqtt integration was not just reloaded this should fix it.
Perfect. Thanks.
Hmm. Actually using that event to create a triggered template sensor (to store the last reload time) would create a race condition with the automation state trigger.
@waxen junco
{% set events = states.calendar.bay_1.attributes %}
{% set next_event_time = events['start_time']|as_datetime %}
{% set current_time = now() %}
{% if next_event_time - current_time <= timedelta(seconds=300) %}
turn on the plugs
{% endif %}
Is there a way to create a dictionary from two lists (one list with keys, the other list with values) without looping?
Like the Python zip() function
No, there's no zip
Something like this?
{% set keys = 'a', 'b', 'c', 'd' %}
{% set values = 1, 2, 3, 4, 5 %}
{% set ns = namespace(zip={}) %}
{% for i in range([keys|count, values|count]|min) %}
{% set add = {keys[i]: values[i]} %}
{% set ns.zip = dict(ns.zip, **add) %}
{% endfor %}
{{ ns.zip }}
Result
{
"a": 1,
"b": 2,
"c": 3,
"d": 4
}
Keys must be strings
Thanks! That’s where I was heading if there wasn’t a loop-free method.
Was hoping there was some clever use of jinja’s batch() or something else that I missed
Shouldn't be too hard to add a zip function/filter though
I have a PR in the works for about 4 years now for zip
it would be an easy add.
jinja really just needs single line loops in cases
a 1 liner w/ zip would be {{ dict.from_keys(*zip(keys, values)) }}
That would be nice. What’s the protocol with stale PR’s, what does it take to get someone to either merge or reject it?
oh no, I never submitted it
I did the work and let it sit 🤣
it can be less than 100 lines of code, mostly a test case
I have been testing your code and the min logic seems to works fine. But shouldn't trigger.platform == 'time' be
template instead of time? To trigger the weekly reset? There is no - platform: time in the code🤔
have a template sensor to convert to datetime
- name: food_waste_cart
unique_id: redacted
state: >-
{{ min(((state_attr('calendar.food_refuse','start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int,2) }}
attributes:
days: >-
{{ ((state_attr('calendar.food_refuse','start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int }}
friendly_name: "Food Waste Cart"
as its giving some startup errors with the calendar not being available
Add an availability template to check on the attribute
- name: food_waste_cart
unique_id: redacted
state: >-
{{ min(((state_attr('calendar.food_refuse','start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int,2) }}
attributes:
days: >-
{{ ((state_attr('calendar.food_refuse','start_time') | as_timestamp - today_at('00:00') | as_timestamp) / 86400) | int }}
friendly_name: "Food Waste Cart"
availability: >
{{ state_attr('calendar.food_refuse', 'start_time') not in [None, 'unknown', 'unavailable'] }}
like the above
- name: Food Waste Cart
unique_id: redacted
state: >-
{{ min((state_attr('calendar.food_refuse','start_time') | as_datetime | as_local - today_at('00:00')).days | int,2) }}
attributes:
days: >-
{{ (state_attr('calendar.food_refuse','start_time') | as_datetime | as_local - today_at('00:00')).days }}
availability: "{{ state_attr('calendar.food_refuse','start_time') is not none }}"
This is what I would do
You could even refer to the attribute in the state
- name: Food Waste Cart
unique_id: redacted
state: >-
{{ [ this.attributes.days | default(2), 2] | min }}
attributes:
days: >-
{{ (state_attr('calendar.food_refuse','start_time') | as_datetime | as_local - today_at('00:00')).days }}
availability: "{{ state_attr('calendar.food_refuse','start_time') is not none }}"
Done
fyi, you can skip default by using get
this.attribute.get('days', 2)
#less typing
I also removed the friendly name attribute and put it in the name field
Yeah, I had that first
Thought this might be easier to understand
thanks! Jusg wonderig, there are a couple of options you presented, it looks like the the second the one if a but more concise for this case, which is preferred
I think I have template entities which use this.get('attributes', {}).get('some_attribute') for extra failsafe
they really should populate this with an empty state object instead of nothing
that would be an easy PR
all this safety that needs to be done is normal coding. Should be easier for the layman
coud probably make something for this
thanks again for explaining that and providing the code 🙂
Yes, that should be "template". I adapted it from a daily min sensor and apparently missed that bit.
So uh, what’s the protocol for getting someone to finish a PR that hasn’t been touched for 4 years
well, I looked through my branches and apparently never put it anywhere
I think it would be 3 lines of code to add it. And 97 lines to test it.
literally 3 lines, you should try to add it
This would be a good one for me to try out editing the code. I might be able to figure out the 3 lines. Creating the tests probably not so much.
a good example to follow would be math.pi
zip already exists in python, so it seems like it would just be a 1 line change to implment it
then for testing, I would test zipping and unzipping a dataset
probably nothing else. Then see if the PR makes it through
probably won't get added til august, but it would be a good first PR
Unless you want to add a default parameter I guess, then it'll be some extra lines and extra tests
default for what?
it should error out if you don't give it an iterable
if you feed it a state (string), with another state (string), it will use the characters
I'd expect zip to only be used to zip 2 iterables together, and unzip into 2 lists
Yeah, makes sense
zip(*collection) for unzipping
zip(a, b) for zipping
collection needs to be [('a','b'),('c','d')]
and a, b need to be lists
of single items
have another issue with this. I modified Allan Porter's conversation blueprint here to do TTS on motion.
https://gist.github.com/Anto79-ops/d926fa8655da7cad0a383e1fa35c40de
But when I try to run it, i get an some errors:
Conversation agent Agenda Notification with tts on motion: Error executing script. Error for call_service at pos 3: Error rendering data template: UndefinedError: None has no element 0
Im not sure where pos 3 is?
ahh, I shared the edit link..updated the link now
im starting to think its this line,
{%- set forecast = state_attr(weather_entity, 'forecast')[0] %}
there is no (more) forcast attribute?
Correct
oh wow, what a process to simply get a forecast, creating a new sensor, etc
Ok so I figured out a hacky way to zip two lists into a dict without looping. Just because I couldn’t accept that it couldn’t be done
{% set keys = ['a','b','c','d'] %}
{% set values = [1,2,3,4] %}
{% set my_dict = ('{"' ~ (keys | join('\":%s,\"') ~ '\":%s') | format(*values) ~'}' ) | from_json %}
{{ my_dict }}
hehe
you could have spent that time in writing a PR to add a zip function/filter 😛
Haha. That will probably take me weeks. Manipulating jinja to do my bidding is easier. But I’m still going to take a crack at the pr.
following this example, how do I place two trigger templates in my templates.yaml file? I already have a trigger-based template sensor (unrelated to weather forecast)
sensor seems to stay unknown. Perhaps I set it up wrong.
- trigger:
- platform: time_pattern
hours: "12"
action:
- service: weather.get_forecasts
data:
type: daily
target:
entity_id: weather.home
response_variable: daily
sensor:
- name: Daily Temperature Forecast
unique_id: ba182774-d2f2-4ef3-a6ba-ffb22b8e8fc1
state: "{{ daily['weather.forecast_home'].forecast[0].temperature }}"
unit_of_measurement: °C
example output from the sevice call is:
weather.forecast_home:
forecast:
- condition: partlycloudy
datetime: "2024-03-30T18:00:00+00:00"
wind_bearing: 175.8
temperature: 6.3
templow: -1.2
wind_speed: 15.5
precipitation: 0
humidity: 19
Probably hasn't triggered
It triggers at 12:00
ok that makes. I used the update entity feature but I guess that runs everything starting from the trigger
Trigger based template sensors only update on the trigger
ok, I changed the trigger to this:
- trigger:
- platform: time_pattern
minutes: "1"
still unknown
after 6 minutes
Also
{{ now().weekday() == 0 }}
Will be true the whole first weekday, which is not supposed to be I guess?
It triggers when it becomes true, which is at midnight
lol of course it didn't work because I had the entity_id wrong for the service call 🙂 live an learn
ok, I've made 3 entities now:
sensor.weather_conditions
sensor.probability_of_precipitation
sensor.daily_temperature_forecast
the old way would simply use the attribute of the same entity, with this:
{%- if weather_entity is defined %}
{%- set forecast = state_attr(weather_entity, 'forecast')[0] %}
{%- set temperature_unit = state_attr(weather_entity, 'temperature_unit') -%}
Weather: {{ forecast.condition }} ({{ forecast.temperature }}{{ temperature_unit }}, {{ forecast.precipitation }}% precipitation)
{%- endif %}
you could just recreate the forecast entity, like the docs show
or...make the calls inline and don't create new entities
you mean like this:
{%- if weather_entity is defined %}
{%- set temperature_unit = degree Celsius%}
Weather: {{ sensor.weather_conditions }} ({{ sensor.daily_temperature_forecast }}{{ temperature_unit }}, {{ sensor.probability_of_precipitation }}% precipitation)
{%- endif %}
I'm not sure what you're solving with that
I'm just saying that you seem to be complaining that you had to create a bunch of entities
and I'm saying that if you just followed the example in the docs to create a forecast template sensor, then you could just use that exactly as you did before
instead, you chose to separate out individual parts of it
the old way would simply use the attribute of the same entity, with this:
you mean I didn;t have to make 3 seperate entities?
but, that uses attributes, I thought attributes are on their way out...which is what caused the problem in the first place
no
attributes aren't going anywhere
unconditionally dumping lots of data into attributes without it being explictly requested is what went away
so, like I said, you could also just do it inline and not create any additional entities
or...you can just recreate the entity
that's why I pointed you to the docs
I know you did
because it shows you exactly how to do it
and I thought I understood you, but I didn't
ok
my bad
thanks again @inner mesa this really worked
what did your final code look like? (I want to take what you did) lol
Let me get the code for you when im on the computernext...for some reason I can't copy-paste from the phone app
Buts it's this exactly, except i changed it to daily and used the proper weather entity_id
Oh and I changed the time pattern to 12 hrs
@floral steeple I converted your message into a file since it's above 15 lines :+1:
@floral steeple I don't really understand why you update this only at noon, that means you have yesterday's forecast in that attribute for half of the new day
Lol you're right. I should change it to midnight...should it be 0:00
I think I remember there being a helper to get the "translated" variant of a binary_sensor state in jinja templates (e.g. "open" instead of "on" for a door sensor). Unfortunately though, I can't seem to find it via google.
Does it really exist or am I just hallucinating things into existence?
Unless you mean the template (binary) sensor helper, I don't think there is something like that
If you want the actual state to change to "Open", etc you would need a separate template sensor... but if you just want the same frontend representation you need to add a device class. For some user-defined binary sensors this can be done in their configuration, otherwise you can add it via manual entity customization.
Yes! Thanks 🙂
how do I put an actual fixed value for temperature_unit in this code:
{%- if weather_entity is defined %}
{%- set forecast = state_attr(weather_entity, 'forecast')[0] %}
{%- set temperature_unit = state_attr(weather_entity, 'temperature_unit') -%}
Weather: {{ forecast.condition }} ({{ forecast.temperature }}{{ temperature_unit }}, {{ forecast.precipitation }}% precipitation)
{%- endif %}
like this?
{%- set temperature_unit = degrees Celsius -%}
You just want a string?
yes, just a string
awesome, thanks!
Does anyone know if these is a way to simulate a workday sensor with an offset of 1 without actually creating it? It seems like you can do so with a service call, but I cant figure out if there is a way to do it in a template. I basically just want a way to indicate if it thinks tommorrow is a workday or not as I am testing some automation/sensors
Just change the state in
-> States
Can you elaborate or give an example?
If you want an entity to have a different state temporarily, change it there
Well I only want it changed within the context of a template not outside of it
There no way to get a workday sensor to pretend that it's tomorrow
Well its possible with the check date service call so I was hoping there was a way to do that in a template
hi all, is there a way to go from ["a:b","c:d"] to {"a":"b","c":"d"} ?
The first condition works lovely in the dev tools but not in the automation: http://pastie.org/p/2fpBcJqqWIItjKPVgpySwR
Assembled in the GUI editor
You're using multiline notation in combination with quotes
use multiline notation or quotes, not both.
if you're using the UI, just omit the quotes.
ahhhhh, I assumed it would be one line when I put it into the UI template.
Grand! collects up "'s
you could do it all with replace functions, assuming none of the keys or values contain special characters that are being replaced:
{% set input = ["a:b","c:d"] %}
{{ input | string | replace('[','{') | replace(']','}') | replace(':','\':\'') | replace('\'','"') }}
or you could do it by looping. in this case you just have to ensure no colons are in the keys or values:
{% set input = ["a:b","c:d"] %}
{% set ns = namespace(pairs={}) %}
{% for pair in input | reverse %}
{% set ns.pairs = dict([(pair.split(':'))], **ns.pairs) %}
{% endfor %}
{{ ns.pairs | to_json }}
Thx!
Hi all 🙂 Anyone knows how to do this easy? i want a automation that notifies me when only one or both binary sensors state is above 35 or above.
i dont know how to template it 😛 i tried google 😦
I want a message like this:
"sensor1 AND sensor2 needs to be cleaned"
or
sensor2 needs to be cleaned"
but i dont know how to template that in the message. must be a simple trick someone knows :D.
Notify message would be like:
You don't need templates for this
just make an automation with 2 triggers, one for each sensor. Then make a condition that checks both sensors. Then your notification will tell you to clean both sensors.
oops, missed one or both
Oh i see, thanks anyway 🙂
@gray urchin I converted your message into a file since it's above 15 lines :+1:
Seems as a #frontend-archived question
{% if states.binary_sensor.sensor1.state == '35' and states.binary_sensor.sensor2.state =='35' %}
green
{% elif states.binary_sensor.sensor1.state == '35' and states.binary_sensor.sensor2.state =='35'
deepskyblue
How do i change == into above > & below < correctly ? like:
{% elif states.binary_sensor.sensor1.state < '35'
As petro said you don't need templates and can build the logic easily in the automations GUI
Don't do a string comparison with numeric states
But for templates it is first best practice to use the states() function, convert that to a float or int, than you can compare with >= or <=; < or > depending if the value itself should also be accounted for.
{% if states('sensor.sensor1') | float > 35 and states('sensor.sensor2') | float > 35 %}
Although the value of a binary_sensor can only be on, off, unavailable or unknown
oh it is a sensor, not binary, sry my bad 😛
thank you! 🙂
@heavy minnow I converted your message into a file since it's above 15 lines :+1:
the switch.turn_off works fine, and turns off the AC, but the switch.turn_on shows the above error
Share the script that actually has the error
hi, i want to set speed by number at the nspanel. i think the whole syntax is wrong. maybe someone can help:
speed: >-
{{if states('sensor.wechselrichter_battery_power')|float(0) < 0}}
20
{{if states('sensor.wechselrichter_battery_power')|float(0) > 0}}
-20
{{if states('sensor.wechselrichter_battery_power')|float(0) = 0}}
0```
what i am missing here?
I have the total energy my household needed and the energy I am currently getting/sending to the grid
sadly, the energy usage graph doesn't understand that if total energy needed is decreasing it means that I am returning it to the grid
how can i calculate the energy I return to the grid? is there some sort of variable system I can use to save the last total energy and subtract that to from current total energy?
Statements go between {%%}, {{}} is for expressions to print to the template output #templates-archived message
So the if statements should be between {%%}
And you need and endif
And each statement after the first could be an elif
Otherwise you need 3 endifs
{%if states('sensor.wechselrichter_battery_power')|float(0) < 0%}
20
{%elif states('sensor.wechselrichter_battery_power')|float(0) > 0%}
-20
{%elif states('sensor.wechselrichter_battery_power')|float(0) = 0%}
0
{%endif%}```?
You can test it in dev-tools > templates
The last statement could also be simplified to only {% else %}
speed: >-
{% if states('sensor.wechselrichter_battery_power')|float(0) < 0%}
20
{% elif states('sensor.wechselrichter_battery_power')|float(0) > 0%}
-20
{% else %}
0
{% endif %}```
if it works i will see tomorrow if the state changes to positive:) thanks a lot.
You can always change manually the value of the sensor until the next update in dev-tools > states to test the template
Hhaha split-screen with the both tabs open 😉