#templates-archived
1 messages · Page 79 of 1
I don't know why... but it makes me a little queasy. 🤢
and you make the same dict twice
definitely some jinja get-around-limitations-fuckery
Jinja has been an adjustment after years of Python, it's like it's mostly python but with the fuckery 😛
yep, if you know python, you can get around some of the jinja issues
but jinja is restricted
I stick my foot in it a lot trying to python a jinja yaml only to realize jinja doesn't like my python because, reasons. Then I walk away and design a dash for a while 😄
Filters are quite often how I do it. Trial and error and picking up tricks on the forums
Can someone please help me, I'm trying to play random mp3 files from a folder. I've already set the folder integration and added a sensor for that folder. It can see all my files
For some reason I can't get the media path right. The folder is located in /config/www/media/toilet - yest the MP3s are of funny comments when someone flashes the toilet 🙂
I've tried many variations of the path using this in "services" tab but no dice
service: media_player.play_media
target:
entity_id: media_player.office_gh
data:
media_content_type: music
media_content_id: "/media/toilet{{ state_attr('sensor.toilet', 'file_list')|random }}"
"/local/media/toilet/{{ state_attr('sensor.toilet', 'file_list')|random }}"
TIL people play MP3s for the toilet flushing... 🤣
nothing unfortunately
service: media_player.play_media
target:
entity_id: media_player.office_gh
data:
media_content_type: audio/mp3
media_content_id: "/local/media/toilet/{{ state_attr('sensor.toilet', 'file_list')|random }}"
what's your filelist contain?
MP3 files
Ahh, can't update screenshots
yes I've tried the path within the sensor but still didn't work
"/config/www/media/toilet/"
I've tried playing a single file from that folder and it works
media_content_id: /local/media/toilet/Ahh great, now we can't use the bathroom for at least an hour!.mp3
yeah but even media_content_id: "{{ state_attr('sensor.toilet', 'file_list')|random }}" still doesn't work
right because your path is wrong in your list
/config/www is wrong
that's what's in your list
so just that won't work
then when you combine it with the other path, you're adding 2x the path
and then use "/local/media/toilet/{{ state_attr('sensor.toilet', 'file_list')|random }}"
Ahh, ok interesting. Well that gets auto generated by the sensor. It's in the attributes
This is what I put into the sensor
- platform: folder
folder: "/config/www/media/toilet/"
well, just change that to /local/
if that doesn't work, then you need to remplace after the random
So "/local/www/media/toilet/"?
media_content_id: "{{ state_attr('sensor.toilet', 'file_list')|random|replace('config/www', 'local')}}"
- platform: folder
folder: "/local/media/toilet/"
Integration couldn't be setup error
ok, then keep your original setup and use this template
getting the following
Failed to call service media_player.play_media. template value should be a string for dictionary value @ data['sequence'][0]['data']. Got {'media_content_type': 'audio/mp3', 'media_content_id': "{{ state_attr('sensor.toilet', 'file_list')|random|replace('config/www', 'local'}}"}
When I test the template in template tab it's working fine.
{{ state_attr('sensor.toilet', 'file_list')|random }}
Gives me /config/www/media/toilet/Did you unleash a beast? That smells so vile! I mean OH MY GOD!.mp3
try this in the template editor {{ state_attr('sensor.toilet', 'file_list')|random|replace('config/www', 'local')}}
/local/media/toilet/Jesus... What died in your stomach mate.mp3
That worked!!!
service: media_player.play_media
target:
entity_id: media_player.office_gh
data:
media_content_type: audio/mp3
media_content_id: "{{ state_attr('sensor.toilet', 'file_list')|random|replace('config/www', 'local')}}"
Much appreciated Petro! I was pulling my hair out for a few hours
This is nice! Maybe a little gross but still nice. I wanted to do something with more than two elements in each list or tuple though, so unless you can enlighten me i think this hack is only relevant to two-element tuples?
I am editing my llama3 configuration and it is returning 'exposed_entities' is undefined for the line {%- for entity in exposed_entities: %}. Is there any way to add the exposed_entities list?
{% set exposed_entities = [your_list] %} above your for loop should work. Not sure what exposed_entities is supposed to be or how it's built though.
Ah, I dont want to type my entities manually, is there any way to get a list of all entities?
Yes, what is the criteria of your entities for exposed_entities? You can create a list using filters, such as:
{% set exposed_entities =
states.binary_sensor |
selectattr('attributes.device_class', 'defined') |
selectattr('attributes.device_class', 'eq', 'vibration') |
rejectattr('name', 'search', 'dryer', ignorecase=True) |
rejectattr('state', 'in', ['unavailable', 'unknown', 'off'])
%}
Is there a way to set a sensor state to the current system time so I can show the last time that a webhook was triggered? Or is there a better way to do this?
Ideally, I'd also be able to perform an action with the time, like if more than an hour has elapsed since the last update, notify me
state: "{{ now() }}"
If your webhook triggers an automation, then last_triggered is already an attribute of the automation entity, could use that.
Ok, thanks!
if I use now() does the value get stored as a datetime that I can then format, or does it store it as a string?
states of entities are always strings.
but an input datetime has a timestamp you can use in an attribute to make formatting slightly easier
I get the always strings bit, I don't get the second bit
I do see last updated as a secondary information on all these sensor values, so i can definitely see when they were last updated
I don't know how to do anything with that value, but i'll google some more
I have a number sensor, and I want to display the change since the last update, Ex: "-5" or "+5". How can I achieve this?
Also, how do I convert a string to a number? I have this as an action in my automation for when my string changes, but it's not working. service: input_number.set_value data: entity_id: input_number.value_number value: >- {% set value = states('sensor.value_string') %} {{ value.split(' ')[1] | float }}
Trigger on state changes of that input number and compare the trigger.from_state.state and trigger.to_state.state with each other
it's not working is not really clear. What exactly is the issue?
The value template is not displaying a number
I need it to convert the string to a number and set it to the input number helper
Test the template in developer tools > templates
What is the state of sensor.value_string
209
UndefinedError: list object has no element 1
{{ '209'.split(' ')[0] | float }} will return 209 instead of that error you mentioned
But does the sensor also have states including a space to split on?
I got it to work, had. a typo in my entity id
With the "random" play of audio clips. Is there a way I can set it to play random but not play anything that's already been played until every clip has been played once, and then restart the process again?
I understand this could be very complicated, but very interested to see if there's a way
Store the clips played in an attribute of a trigger based template sensor using an event trigger, and reject those from your selection. Reset the attribute when the last clip is selected
if I'm getting a timestamp from an API ("startTimestamp" : "2024-09-17T16:20"), how can I convert that to a sensor with a timestamp device_class with the correct timezone? I've tried {{ value_json.startTimestamp }}-05:00 but that didn't work and said timezone was missing :/ (and also doesn't account for daylight saving time)
adding -05:00 threw an error that timezone was missing
adding -0500 "worked" but was in UTC
{{ value_json.startTimestamp }} is in UTC
{{ value_json.startTimestamp | as_datetime | as_local }}
that did it. thank you ♥️
Guys I have a sub-folder in the media directory, I can't seem to get this template to work as I'm trying to play the files in that folder randomly
media-source://media_source{{ state_attr('sensor.Test', 'file_list')|random |replace('/media/','/local/Test/')}}```
However, specifying the file within that folder does work
```media_content_id: "media-source://media_source/local/Test/Test.mp3"```
I'm probably going blind, and am sleep deprived 🙂
what does {{ state_attr('sensor.Test', 'file_list') }} return in
-> Templates?
first, sensor.Test isn't an actual entity_id - they're all lowercase
but it may fix that for you automatically
Apologies, made the mistake when I edited the name for discord. Yes it's all lower case.
Testing it in templates returns all the filenames inside that folder
"/media/Test/test.mp3",
No I only copied one line.
you gotta provide all the data
hard to help otherwise
what does media-source://media_source{{ state_attr('sensor.Test', 'file_list')|random |replace('/media/','/local/Test/')}} show there?
TypeError: object of type 'NoneType' has no len()
there ya go
I didn't because there are over 65 files in there
something doesn't add up
I suspect you just have the wrong entity_id there
in other words, it's not what you're actually testing
you're editing stuff to be different from what you're really doing
Sorry, Just fixed it.
media_content_id: "media-source://media_source{{ state_attr('sensor.test', 'file_list')|random |replace('/media/','/local/')}}"
Can't for the life of me figure out what was wrong, I could swear I've tried this before lol
Thanks anyway Rob for your time mate
Hey there,
I did not find it (I guess I was blind).
I got an energy counter for consumption. I multiplied it with an entity helper to calculate the total costs. Tomorrow the price changes, so I want to make a cut, create a new helper which contains the current costs and calculate the new costs by mutiplyng the new price with the consumption beginning tomorrow and add the costs until today.
Like
current price 30ct
current consumption 2000kWh
so I got 600€
Tomorrow i have a price of 40ct
Now I want to save 600€ as a helper and calculate everything from 2000kWh with 40ct and add the helper
so when I reach 3000kWh it should display a total cost of 1000€.
no idea what you're even asking, post an equation and we can help
Hehe
Like
I got energy consumption * energy price from 1.1. Until today. This product shall now be added to energy consumption beginning tomorrow multiplied with the new energy price.
Hey all - posted on the HA Community Forums about this too but is there any way to get a list of exposed entities that can be used in template? I'm looking for a way to iterate over the list of entities that are exposed to Voice Assist
Thanks - the shell command doesn't work elegantly for docker containerised setups (as it requires you to know the volume and absolute paths of your setup). The command itself works fine from the Terminal if running it through the container itself (ie Terminal addon).
That’s not correct. The shell_command runs in the context of HA regardless of Container or HAOS. I have a few that run just fine in my Container setup.
This is the command I can execute at terminal in HA: jq '[.data.entities[] | select(.options.conversation.should_expose == true) | {entity_id}]' .storage/core.entity_registry
I can change the path to /homeassistant/.storage/core.entity_registry and that also works
but it does not work when run as shell_command as this gets executed out of the container scope
Looks like you didn't try /config/...
You can shell into the container and see what's in there and what's mounted where
I can absolutely tell you that it does execute in the container scope: https://imgur.com/a/FnK5Bha
I'm running a supervised install - shell commands get executed in the host environment
There is zero question about that.
I sure have
stderr: >-
/bin/sh: jq '[.data.entities[] | select(.options.conversation.should_expose ==
true) | {entity_id}]' /config/.storage/core.entity_registry: not found
returncode: 127
Thats the response from the shell_command call
And it's the same error with just ./.storage/core.entity_registry?
Yes
If you docker exec into the core container and just run the command, what does it return?
Do that
Even on a supervised install, it still executes in the Core container.
This is when I am bash'd into my container:
iot-server:/config# find . -name core.entity_registry
./.storage/core.entity_registry
iot-server:/config#
It works when i run the command from within the ha container
Can you post what you have in your shell_command?
It's weird cause I set up a dummy shell_command to ls -al and it shows the container filesystem
Yup. That's my point. shell_command always executes in the Core container, regardless of installation type.
I'm an idiot - I had:
exposed_entities: >-
"jq '[.data.entities[] | select(.options.conversation.should_expose == true) | {entity_id}]' /config/.storage/core.entity_registry"
instead of:
exposed_entities: >-
jq '[.data.entities[] | select(.options.conversation.should_expose == true) | {entity_id}]' /config/.storage/core.entity_registry
works now
lol
yay!
fookin quotes
That will do it
I have an entity camera.workshop but entity_id.name in my automation returns None even though the interface shows Workshop how do I get that value? If I edit the entity, the name field is indeed blank so where is Workshop coming from?
The name and entity_id are separate
The entity_id is initially derived from the name, which has a default assigned by the integration
If you want the name in a template, you would do {{ states.camera.workshop.name }}
@crimson wadi ☝️
Hmm, though if I'm targetting multiple cameras, how can I get the name in a generic way?
{{ states[entity_id.entity_id].name }} ?
okay, the best I can giver you is this:
{{ ((float(states('sensor.hm_es_tx_wm_iec_energy_counter_ch2')) - 2 ) * float(states('input_number.energyprice'))) | round(2) }}
this gives me the energy costs based on a helper entity and the energycounter from hm-es . Now I have a changing energy price. So I would like to have the costs until yesterday, and add it to the energy counter multiplied with th enew energyprice
oldCosts + hm_es_sensor_beginning_from_30th_of_june * new_energy_price
how do I get the energy counter starting from 30th of june?
You can't do that in template entities
calculations that span periods are performed by statistics integrations, utility meter, or other similiar integrations.
SQL lets you perform a query and a calculation as well.
Okay, Unfortunately I have no time right now to learn about that. I think I will create new helper entities holding the necessary values and simply substract / add them like
oldCosts_from_helper + {{ ((float(states('sensor.hm_es_tx_wm_iec_energy_counter_ch2')) - 2 - old_energy_count_from_helper ) * float(states('input_number.energyprice'))) | round(2) }}
just use the built in integrations that do this
in some cases, if you just want this in the UI, ou don't even need to make entities
@stoic bison I converted your message into a file since it's above 15 lines :+1:
It appears I could be using rejectattr(, , ) in the template, but I do not know how to implement it correctly to make something like rejectattr('datetime', <, now().strftime)
I don't know that the rejectattr can compare dates like that as strings to be honest. You might be better off using foreach to iterate over them or similar.
It can as long as both arguments are a datetime
That's handy to know!
like:
{{ states.alarm_control_panel|selectattr('last_changed', '>', now() - timedelta(hours=2))|map(attribute='entity_id')|list }}
The last line might end up looking something like this then:
{{ today_forecast | rejectattr('datetime', '<', now().strftime('%Y-%m-%dT%h:%M')) | sort(attribute='electricity_price', reverse=True) | first }}
you shouldn't need the strftime() call as long as datetime is a datetime
that's just converting it to a string
Excellent, I don't have anything like that integration on my install so it's hard to test.
I don't know what it is either, just speculating
it depends on the integration, as these datetime attributes are actually strings (boo!!!):
you can't convert during a comparison without losing the state object, so that requires a loop
Huh, I thought the MET office integration died for a while 🤔
you can compare strings though
isoformatted strings
just make sure you remove microseconds
and keep the value in UTC
True
entity_id:
- sensor.night_end
value_template: "{{(as_timestamp(now())-as_timestamp(state.state))/3600}}"
above: 14
id: Awake time```
is there something wrong with this trigger? its not working. its for a timestamp
i used this elsewhere and it works fine
but for this it seems to not trigger, but if i manually set the date of the timestamp outside of the condition and then back into the condition, it triggers
it only triggers when the state of sensor.night_end changes
it doesn't check the template every minute
oh
if you want that, use a template trigger
oops, that makes more sense
platform: template
value_template: "{{ (as_timestamp(now()) -as_timestamp(states('sensor.night_end'))) / 3600 > 14 }}"
id: Awake time
awesome, ty
Good morning! I am getting this error, Error: TypeError: object of type 'bool' has no len(), and I think it has to do with this variable I am setting in a script. I think it might be because notify_always or notify_if_home, both multiple entities, are not set. At least one should be set. Is there a better way to join these arrays together when one may be blank?
variables:
entities_to_notify: >
{{ notify_always | expand | map(attribute='entity_id') | list +
notify_if_home | expand | selectattr('state', 'eq', 'home') |
map(attribute='entity_id') | list }}
notify_always or notify_if_home is a boolean
that's what the error is telling you
if they are lists of entity_id's, then you're doing a ton of extra work for nothing
{{ notify_always + notify_if_home | select('is_state', 'home') | list }}
again, both have to be lists
@outer oyster I converted your message into a file since it's above 15 lines :+1:
notify_always is a string
it's not a list
notify_if_home: []
notify_always: group.parents
you'll still need expand though if you're planning on using groups
Cool, thank you!
and you should format the value coming in from your service call
i.e. if it's a single entity that's a string, turn it into a list of entities
also, if the list is empty, make sure to stop execution or account for that.
Good point, thanks for all the input
@silent seal @inner mesa @mighty ledge I now implemented this
{% set forecast = state_attr('sensor.zonneplan_current_electricity_tariff', 'forecast') %}
{{ forecast | selectattr('datetime', '>', now().strftime('%Y-%m-%dT%h:%M')) | sort(attribute='electricity_price', reverse=false) | list }}
which generates a list sorted on electricity price. The selectattr filter however only seems to care about the days. So I get a list based on tomorrow, excluding the remaining hours of today. (Which is 50% of what I want)
I tried this, but it again only generated a list based on the hours of tomorrow
{{ forecast | selectattr('datetime', '>', now().strftime('%Y-%m-%dT%h:%M')) | rejectattr('datetime', '<', now().strftime('%Y-%m-%dT%h:%M')) | sort(attribute='electricity_price', reverse=false) | list }}
Do you have any suggestions?
that format is wrong
You need to match the timezone that's in your forcast datetime attribute and you need to remove microseconds
it's aslo a bit redundant
you select things greater than now, but reject things less than now
which is 2 ways to do the same thing
@stoic bison ^
Thanks for the response @mighty ledge!
Well if I have a list containing all hours of today and tomorrow and I want the remaining hours of today in a variable I should exclude the passed hours and all hours of tomorrow, that is what I try to achieve. I will look into matching the timezones. Is this related to the now().strftime() method?
just post the output of {% set forecast = state_attr('sensor.zonneplan_current_electricity_tariff', 'forecast') %}
well, seeing that you haven't, I'm assuming they output in this format 2024-07-01T00:00:00.000000Z
so you need to figure out if Z means your tz or if it means utc
if it's your timezone...
{% set midnight = today_at() + timedelta(days=1) %}
{% set fmat = '%Y-%m-%dT%H:%M:%S.%fZ' %}
{{ forecast | selectattr('datetime', '>', now().strftime(fmat)) | selectattr('datetime', '<', midnight.strftime(fmat)) | sort(attribute='electricity_price', reverse=false) | list }}
if it's utc you should do a for-loop
The output looks like this
[{'electricity_price': 3482971, 'electricity_price_excl_tax': 2166491, 'tariff_group': 'high', 'solar_percentage': 0, 'solar_yield': 0, 'datetime': '2024-07-01T18:00:00.000000Z', 'sustainability_score': 488},
It is like a list of dictionaries with each list entry is a new hour
Yes use what I posted
Hey all, I hear there is a way to use templates and context to determine if the last state change in an input_boolean was triggered by a certain automation. How would I do that?
for a bit of context, I have an input_boolean and a sensor, and two automations to keep them in sync. One updates the input_boolean if the sensor state changes, the other calls a service (which amounts to updating the sensor value) when the input_boolean changes
Right now, that causes a chain reaction if the sensor is updated from outside HA. I'm looking to prevent that. (And yes, I am entirely open to completely different alternative solutions=
sounds like you should be using a template switch instead
@petro by instead you mean instead of an input_boolean?
correct
Ok, I'll look into that.
post your atuomation and I can help you build it @abstract maple
@petro I'll do that as soon as I can, but I have to figure out why my server seems to have crashed first.
I swear I'll rip this failing drive out bodily if the bloody system doesn't get on with migrating it to a hotspare...
Well, it looks like my nas has a major problem, so it may not be until later or tomorrow that I can get back to you
I'm trying to create a template fan. As shown in the docs, I'm using attrs like value_template: "{{ states('input_boolean.state') }}" but that results in a fan state that is never updated and log warnings like: [homeassistant.helpers.service] Referenced entities input_boolean.state are missing or not currently available
Have I configured something incorrectly or are these placeholders in the docs that need to be replaced with newly created helper entities? The docs aren't clear on this point.
Yeah, you would need to use the entity_id of the input_boolean that you create/created.
OK. That's how I've done it for templates in the past but I was hoping that there was some cleaner way to do it for these "internal" helpers where the entity is solely to be used as an attr for a templated entity.
Post the full fan template and we might be able to clean it up.
listens to crickets
@cinder pendant I converted your message into a file since it's above 15 lines :+1:
@minor halo I converted your message into a file since it's above 15 lines :+1:
right, this is nonsense: states.hvac_mode
that's not an entity_id, or how you would retrieve the state or an attribute from an entity. Where did that come from?
Ok, I am using this https://github.com/jcwillox/hass-template-climate
so would it be fine to just use hvac_mode alone?
I try to set the value to 1 for "heat" and to 0 for "off" depending on the variable hvac_mode given in the set_hvac_mode
based on the documentation there, yes
it's a variable that's made available in that section
data_template was deprecated many, many years ago in favor of data
So data_template still works or is this the first problem?
Would it be a better thing to do it like this?
value: >-
{% if is_state('hvac_mode', 'heat') %}
- 1
{% elif is_state('hvac_mode', 'off') %}
- 0
{% else %}
- 0
{% endif %}
But I would assume that the is_state is also not working in this case? Am I right?
no, data_template still works
and you're surrounding the variable with quotes, which turns it into a string, and you're treating the hvac_mode as an entity_id, which it isn't
there's just a bunch of stuf weird there
hvac_mode is a variable, and you should just evaluate it as one
value: "{{ iif(hvac_mode == 'heat', 1, 0) }}"
if you need a list, then value: "{{ [iif(hvac_mode == 'heat', 1, 0)] }}"
Oh man thanks a lot 😉
Your list template works like a charm! It can be so easy if you know what you do 🙂
Hey 👋
I have a weird issue with expand() in notification messages. Below example only spits out Device unavailable! through an automation, but when manually checking the template in the Template section of Developer tools, it spits out Device bedroom window unavailable! correctly. Note: state=on only used for testing.
`id: critical_device_unavailable
alias: Send notification if a critical device goes unavailable
trigger:
- platform: state
entity_id:- binary_sensor.critical_devices
to: unavailable
action:
- binary_sensor.critical_devices
- service: notify.persistent_notification
data:
message: Device {{ expand('binary_sensor.critical_devices') | selectattr('state', 'eq', 'on') | map(attribute='name') | list | join(', ') | lower }} is unavailable!`
What am I missing?
How are you testing this?
@compact pond I converted your message into a file since it's above 15 lines :+1:
The jinja isn't formatted as a string
value_template: >-
{{
states("sensor.meterkast_groep_1_vermogen")| float(0) +
states("sensor.meterkast_groep_2_vermogen")| float(0) +
states("sensor.meterkast_groep_3_vermogen")| float(0) }}
https://www.home-assistant.io/docs/configuration/templating/#building-templates
It talks about the multiline string in the docs here
Thx
Hi guys,
I working on template...
My idea is that I will end up with a sensor "one each for north, east, south and west," comination of day and azimuth (value beteen) which will give me true or false for the current day (now).
Example:
Wednesday July 4rd 4:30pm azimuth for south is between 51 and 207 = true
Something I already have...
{% set start = now().replace(day=1, month=7).date() %}
{% set end = now().replace(day=15, month=7).date() %}
{% set low, high = [start, end] | min, [start, end] | max %}
{% set current = low <= now().date() <= high %}
{{ not current if start > end else current }}
{{ states('sensor.sonne_solar_azimuth')|float >= 202 and states('sensor.sonne_solar_azimuth') | float < 308 }}
is there anyone here who can help me with this matter
I have also already created a list of azimuth for the whole year at intervals of 2 weeks
This looks like this,
from day to day north nort-east/east east-south south-west/west
16. Dez 01. Jan -no shading- -no shading- 126-207 202-232
17. Jun 01. Jul 55-106 51-128 51-207 202-308
Hello, I'm making a script with fields, I want the action of the script depend on the provided filed (i.e if color is provided do X, if color temp is provided do Y) but I'm struggling to understand what to write in the condition template {{ color is not none }} wouldn't work, also tried
{% if '{{color}}' == '' %}
False
{% endif %}```
I tried '', 'none', 'null'
also, is there a way to see what the filed returns?
You're nesting templates
I tried color without {{}}
so whats is the correct condition? '' or 'none'
{{ color is defined }}
Dangit... stupid, slow internet.
Whichever you want
You can store your lookup table in the custom_template folder so that it is accessible to multiple sensors.
I'm just a bit inexperienced here, so I'm asking carefully how I can do this
I'm just a bit inexperienced here, so I'
I'm looking to set a calendar event by voice and curious if someone can tell me how I might get a date if the user uses somethink like "create a calendar event called breakfast on Wednesday at 8am" Is there an easy way to convert Wednesday to a calendar date using a template or otherwise?
@eternal stag I converted your message into a file since it's above 15 lines :+1:
I literally don't see how that's any better ^
You have to template the entire field
nvm, I figured it out:
- service: scene.create
data:
scene_id: before_lighting
snapshot_entities: >
{% set switches = states.switch | rejectattr('state', 'eq', 'unavailable') | map(attribute='entity_id') | list %}
{% set lights = states.light | rejectattr('state', 'eq', 'unavailable') | map(attribute='entity_id') | list %}
{{ switches + lights }}
Hard to imagine that does what you want
If you change states.switch + states.light to states.switch, it should
i am just trying to save all switch and light states in the house
then later i will restore it
errr, i see what you mean, yeah that's not actually what i have in my file, sorry i'll update
I was trying to combine the domains before going through the function pipe, but it didn't like concatenating domains and this is good enough for me
Good morning, I've just started using ha, so please be patient 🙂
I've a esp32, that is reading some values from my inverter. I would like to add these readings to ha.
Therefore I've created a rest sensor:
sensor:
# RESTful Sensor to get the JSON data
- platform: rest
resource: http://esp32-943cc637b4d8.local/data
scan_interval: 5
name: inverter_data
value_template: "{{ value_json.gridFrequency }}" # Dummy value, required but not used
json_attributes:
- gridFrequency
Then I've added a template sensor:
template:
- sensor:
name: "Grid Frequency"
state: "{{ state_attr('sensor.inverter_data', 'gridFrequency') }}"
state_class: "measurement"
unit_of_measurement: "Hz"
I know, that the json is returned from the rest endpoint. I've added a temp command to dobule check.
The returning json looks like
{
"gridFrequency": 50
}
But the state of the template sensor is always "unkown". Can someone please give me a hint, what's wrong?
so does the rest sensor give the right vaule in it's gridFrequency attribute?
I also don't really understand why you are using a rest sensor, which will have this 50 value as it's state (and in an attribute as well) and then you create another template sensor which will have the same state of 50
I have an automation that checks whenever a specific TV switches channel it sets the source to a matching source in a list. When the TV turns of i'd like it to set it to Off (which isn't a channel) or if there is not a match in the list i'd like to set it to a default. How can i achieve this? This is how i set the input right now.
target:
entity_id: input_select.lg_inputs
data:
option: "{{state_attr('media_player.lg_c2', 'source')}}"```
option: "{{ 'Off' if is_state('media_player.lg_c2', 'off') else state_attr('media_player.lg_c2', 'source')}}"
something like that?
I am a total n00b, so maybe it's simply wrong.
I've a lot of values coming from the rest endpoint. I just started with one to see if its working. And I used gridFrequency as I know the expected value.
I've created a command to test and see the result from the request. The response is fine
what would be the default value then?
option: >
{% if is_state('media_player.lg_c2', 'off') %}
Off
{% elif state_attr('media_player.lg_c2', 'source') in state_attr('input_select.lg_inputs', 'options' %}
{{ state_attr('media_player.lg_c2', 'source') }}
{% else %}
Unknown source
{% endif %}
What is the current state of sensor.inverter_data, which is your rest sensor
Default would be off
{% if state_attr('media_player.lg_c2', 'source') in state_attr('input_select.lg_inputs', 'options' %}
{{ state_attr('media_player.lg_c2', 'source') }}
{% else %}
Off
{% endif %}```
how could I see the state of the sensor.inverter_data? I am only aware of the state tab in the dev tools and from my point of view, this is the template sensor, right? (sorry cannot attach a pic). Current state of sensor.grid_frequency is unknown
your rest sensor is sensor.inverter_data, your template sensor is sensor.grid_frequency
you can see the current state in developer tools > states
Open your Home Assistant instance and show your state developer tools
A question about template switches, just so I know if I understood correctly: The switch will update to whatever value_template evaluates to, whenever what that refers to changes, but it will NOT execute whatever is configured in turn_on or turn_off unless it is switched by interacting with the template switch directly, right?
there is only the sensor.grid_frequency. No entity with inverter_data
That will work, you can also do it as one line:
option: "{{ state_attr('media_player.lg_c2', 'source') if state_attr('media_player.lg_c2', 'source') in state_attr('input_select.lg_inputs', 'options') else 'Off' }}"
then your rest sensor isn't working, which would fit with the state of the template sensor
check your log for issues
ah ok.
In the logs, there is not too much to see.
2024-07-05 11:16:48.408 INFO (MainThread) [homeassistant.components.sensor] Setting up rest.sensor
2024-07-05 11:16:48.410 DEBUG (MainThread) [homeassistant.components.rest.data] Updating from http://esp32-943cc637b4d8.local/data
I've set log level to
logger:
default: info
logs:
homeassistant.components.rest: debug
homeassistant.components.sensor.rest: debug
thanks
based on the configuration you shared, you should have a sensor.inverter_data. If you don't have it, there is something wrong in your rest sensor configuration.
You did restart HA after adding the rest sensor right (or reload rest entities if you already had other rest sensors).
yes, I restarted several times.
@short thicket I converted your message into a file since it's above 15 lines :+1:
well, again, you should have a sensor.inverter_data based on that config
do you have an idea, what I can test? i am lost right now ...
I am also confused by the documentation. Here https://www.home-assistant.io/integrations/sensor.rest/#fetch-multiple-json-attributes-and-present-them-as-values the structure is different, isn't it?
yes, that is using the rest integration, you are using the sensor integration
both work
what is the output from http://esp32-943cc637b4d8.local/data
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.
@short thicket I converted your message into a file since it's above 15 lines :+1:
@short thicket I converted your message into a file since it's above 15 lines :+1:
@short thicket you don't have a sensor.jsontest in developer tools > states now?
sorry, now the sensor.jsontest is visible
okay, well, it should work the same for your inverter
hmm true 🙂 don't really understand why my rest sensor is not working the same. when firing the request with postman, it is responding like expected
actually, the hostname was a problem. using the ip now, and it is getting the values.. thanks for your help 🙂
anyway, it should have 50.00009 or something like that as it's state, which makes teh template sensor a bit redundant
and if you want to create multiple sensors from that resource, you can better use the rest integration, which allows you to create multiple sensors based on one rest call
understood. i removed the template sensor. From my understanding based on the documentation I was thinking the restful sensor is used for multiple sensors?
hmm probably i misunderstood it. https://www.home-assistant.io/integrations/rest
so i need one sensor for each value in the json response, right?
I've now one sensor inverter_data with ~50 values. is that best practice or would you recommend using the rest integration and create one sensor for each of these values?
I am now trying to add the energy-solar-graph card to the dashboard. but I am not sure how the data is linked to the cards?
best to ask in #frontend-archived
@tardy nimbus I converted your message into a file since it's above 15 lines :+1:
you can store it in a template sensor (or in attribute if you expect this will go over 255 characters)
why are you creating the second sensor? For state_class and unit_of_measurement? If yes, you also need device_class
ah, i see that I was tricked by discord cache again
and the fes already helped you
Yeah, that's what I meant. Looks good.
Thanks! Trying to figure this out now, but it's not really working, sate just keeps saying Unavailable, but it might be me doing something wrong
share what you have now
I found this, which is more or less perfect for what I want https://community.home-assistant.io/t/template-sensor-configuration-for-calendar-events/697691
So far just trying this, but it doesn't give any output
- trigger:
- platform: time_pattern
seconds: /10
action:
- service: calendar.list_events
target:
entity_id: calendar.tommeplan
data:
duration:
days: 14
response_variable: trash_pickups
sensor:
- name: Food Waste Collection Events
state: |
{{ trash_pickups['calendar.tommeplan']['events'] }}
If I just do {{ trash_pickups }} it gives the message Invalid state with length 348. State max length is 255 characters., so it seems there is indeed something inside that variable
put it in an attribute instead
template:
- trigger:
- platform: time_pattern
seconds: /10
action:
- service: calendar.list_events
target:
entity_id: calendar.tommeplan
data:
duration:
days: 14
response_variable: trash_pickups
sensor:
- name: Food Waste Collection Events
state: "OK"
attributes:
events: "{{ trash_pickups['calendar.tommeplan']['events'] }}"
how can I see those attributes?
and should the UI show them? or do I need to define these variables in the config files? (and does that mean I need to restart for every change?) Trying to learn how to use this stuff
Hi, I'm making template binary sensor that is true when any alert in alert domain state is on. Why is this template does not work?
{% set is_any_alert_on = false %}
{% for alert in states.alert %}
{% if alert.state == 'on' %}
{% set is_any_alert_on = true %}
{% break %}
{% endif %}
{% endfor %}
{% if is_any_alert_on %}
true
{% else %}
false
{% endif %}
Try this instead:
{{ states.alert | selectattr('state', 'eq', 'on') | list | count > 0 }}
it doesn't work because jinja scoping doesn't allow access to variables that are assigned during a for loop
you'd have to use namespace to get past that
however, what rosemary posted is the way you should go
Thank you
you can see those attributes in developer tools > states
you can use them in templates.
You can also use the output of the calandar service call to create separate sensors for each trash type
Hm, for some reason it still just shows up as Unavailable in the state, and there is no attributes 😦
did you reload template enitites after making the change?
check your log for issues
HA log or LogBook in GUI?
Should the whole thing be pasted in State template* in the GUI? Including template:?
Yeah, trying, but if it's not supported, I can add it to config file instead
that doesn't work for trigger based template sensors, they need to be created in YAML in you configuration.yaml
Aha, thanks, let me try that and see!
@abstract maple I converted your message into a file since it's above 15 lines :+1:
Why is it claiming it doesn't have any unique id?
did you restart?
if you reloaded, that will create a second entity and the first will remain unchanged
whenever you add a unique_id, you should restart
otherwise you just shot yourself in the foot
Shot in the foot? how so?
because if the entity exists without a unique_id and you add it, then reload, a second entity will be created with the config entry
which means your only recourse is to restart HA, delete the original sensor from the UI if it exists. If it doesn't exist, just rename the entity_id to remove the _2 from the end of it
what are you trying to achieve with this template switch
@petro: reloading sorta fixed it
because those actions won't be performed when the switch changes because of the device tracker state change
Don't know anything about the condition of my feet yet.
@marble jackal That is actually exactly the issue I'm trying to address. I want the actions to be triggered when the switch is actively thrown, but not when the state of the binary sensor changes, because that would cause an endless loop.
as long as you're aware that you need to press the switch for the script to be ran
that set_pet_location service sets the state of the thing represented by that binary sensor
the idea is to keep the state of the switch in sync if the state of the external thing is changed outside ha, but call a service to update it if the switch is changed inside ha.
when you say "changed inside ha", you mean when a user (like yourself) clicks 'turn on' for the switch in the HA UI?
pretty much, yes.
what does that binary_sensor indicate?
where my cat is.
is it on when it's inside?
the plan is to export that switch to alexa and throw it with a routine.
@marble jackal I've tested it in the dev tools and that seems to be how it is.
actually the state is internally represented by 1 and 2 apparently, but the integration exports it as true and false.
with all I know about the system of the company that built that appliance, if I was in charge there, I'd have a thing or two to say about it.
okay, so if the binary sensor indicates that the cat is inside (binary_sensor state is on) the switch will be on as well.
Which means the action you can perform is to switch it off
as you can't turn on a switch which is already on
makes sense. What are you getting at? Did I do it the wrong way round or something?
no, I wanted to make sure you were aware of that
No that's fine. If the system already reflects the cat being inside and I for whatever reason updated it to be inside, nothing would happen anyways.
except a log entry saying the state was updated.
Good. That was the easy part. Now comes the hard part of enabling Alexa to speak the status of the cat. I can get the status by state_translated, but getting Alexa to speak it fluently might be a whole different kettle of fish.
make a routine
@petro that is what I'm planning. But since Alexa has no conditionals, I'll have to somehow trigger the reply in HA, and that's where the problems start.
make 2 separate binary sensors, one for inside, one for outside, use that as the triggers
You're not quite understanding what I want to do. An announcement when the cat comes in would be easy. What I want to do is actively ask Alexa "Where's the cat at?" and that's HARD to do right.
I'm seriously contemplating a custom skill
But I'm probably going to replace my echos with esphome devices instead, because Alexa's ruffling my feathers anyways.
I don't think it's that hard. Use a routine (speech trigger of 'where is the cat?') to execute a script and have the script speak whatever you want via Alexa Media Player
@small elk I converted your message into a file since it's above 15 lines :+1:
Hmm, should I start a thread for this if the message is too long?
@RobC the problem is, whenever you trigger a script, Alexa says "OK" before the script runs, which can't be suppressed by any means I know of so it would work, but it would never feel right. Also alexa_media_last_called has been REALLY unreliable for me
You can just add a test that the state is not 'unavailable' to the beginning of your template
the whole alexa media player integration is unreliable
I never had an issue with doing tts through them, but I transitioned off of it a few releases ago
That was all I used it for, and I just moved to my Onju devices
I changed my Alexa acknowledgement to a tone years ago, but I don't know if it's possible to eliminate it entirely
mine is just a tone
Ok, what is the correct way to do that?
Should I use something like
{{
if(has_value(states('sensor.p1s_nozzle_temperature')) and has_value(states('sensor.p1s_bed_temperature'))){
(states('sensor.p1s_nozzle_temperature')|float(100)) < 50 and
(states('sensor.p1s_bed_temperature')|float(100)) < 50
}
}}
Right. I don't know what the stray { } are doing there
has_value() and has_value and x <y and a < b
@inner mesa {{ expand(integration_entities('alexa_media') | select('search', 'media_player')) | selectattr('attributes.last_called','eq',True ) | map(attribute='entity_id')|first }} That's kinda important if you want to simlulate a question/ response thing with alexa media player. It updates eventually, but definitely not in time to route a reply to the right device.
Ok
Ah I see, so this would be correct?
{{ has_value(states('sensor.p1s_nozzle_temperature')) and has_value(states('sensor.p1s_bed_temperature')) and
(states('sensor.p1s_nozzle_temperature')|float(100)) < 50 and (states('sensor.p1s_bed_temperature')|float(100)) < 50 }}
no, you don't need states method for has_value
Ok, thanks
you also most likely don't need to supply defaults to floats if you use has_value before hand because it doesn't execute the functions later on in the syntax if it fails early
Yeah that's what I was thinking, was just wanting to play it safe as I wasn't sure
I'll remove those
@inner mesa The problem is really that amazon apparently doesn't see alexa as a marketable product they want to promote but as sort of an internal thing they don't want to share, a bit like apple does. They have tons of APIs, but you have to jump through a million hoops to be allowed to use them, and the system really isn't designed with flexibility and expandablity in mind. I honestly have no idea what they were trying to achieve with it or where they want to take it. It's been suggested that the main purpose was to gather data to train their stt engine. If that's the case they have failed miserably, because that sucks too
I know I can use a senro template to display the status of a switch in the UI, but not sure how
Unfortunately, this didn't work and the automation never finished correctly, do you have any further suggestions about how I can get it to work?
@small elk I converted your message into a file since it's above 15 lines :+1:
Currently it evalutes to true in the devtools template tab, but the old one used to give an error when evaluating during the "blackout" period, and then true afterwards, so I'm expecting it's probably the same thing happening for this one where it doesn't catch the error even with checking has_value first
I can upload a trace if that would help with debugging?
Ok so I did this and the template remained false until both variables were < 50 and then turned true (although I had to copy and paste the same template to get it to update to true on the dev tools page), but the automation didn't turn off the light like it should
Then review the trace
The same automation works if I add a 15 sec delay to before the wait_template, so I'm pretty sure it's the template not handling the error or something
And do basic testing of the action
The light turn off action does work, for example if I run the exact same automation now it turns off the light immediately because both values are already < 50
The trace says the template completed with 3599.89 secs remaining out of the 1 hour timeout, so it completed in 0.1 secs which shouldn't happen because it takes around 7+ mins for the printer to cool down and for the 2 values to go below 50C
Then it was already true
But if it was already true then why didn't it run the action to turn off the light?
The trace would tell you that
I'm not sure how to interpret it exactly or which of the tabs within the trace to pay attention to
I've never really used the HA trace before now
The main difference I can see is that the original trace does not have a logbook entry for P1S Chamber light turned off triggered by automation Turn off P1S light at end of print triggered, whereas the new trace for the time I ran it manually just now does have that entry.
So does that imply the light turn off action didn't run for the first trace, or that it did run but for some reason failed to turn off the light?
The trace shows you what parts executed
Ok, so given that it shows the light turn off step executed for both traces, then that implies the light didn't turn off even though HA told it to?
I can see it's possible if the printer was just running the last bits of its code just after the "print finished" event fired for example, then maybe it overrode HA's command to turn off the light, and instead kept it on
You can test all this
Manually set the state of the temp sensors to whatever you want, trigger the automation action manually
Can confirm that adding a 4 second delay action before the wait_template fixed the issue.
It seems that it was like what I was suspecting, which is that the printer briefly sends a very low incorrect sensor temperature value up to about 4 seconds after the print finished event has fired.
Therefore, even though the template would complete as true too early and execute the light turn off service, the light wouldn't actually turn off because the printer wouldn't accept any instructions to do so in the brief period after the print finished event.
This is probably because it was still executing the last bits of the gcode or other code 4 second after the event fired.
Hi all, I got redirected here. I'm transferring from homey which has a room activity. Basically add sensors to a room, motion or door contact and it will mark a room as active when a sensor is triggered. Instead of linking to individual sensors id simply check if a room is active or not for my flows. I'd like to achieve a similar thing with home assistant. Could anyone assist?
lol that’s a different question than you asked before. With that said, you can do this, but not sure it’s the best approach to be honest. So, by active you mean that an area has sensors or switches or lights that are on?
Just motion sensors and door sensors, sorry, I tried some approaches already and I'm not sure what's the best or even possible way 🙂
If by any means I could retrieve the room a device is in by tracking events that would be ideal, I could then log a timestamp to a helper
Honestly, just trigger off the entities. That is the easiest approach.
{{ area_name(entity_id) }} will give you the area name for an entity IF you have assigned it to an area.
Hi guys. I think this is where my question should be asked, but I'm not sure. Please slap me if not.
I am using multiscrape to scrape a webpage that is made by adruino. the webpage is as follows:
23.69<br>37.85<br>967.22<br>789.32<br>143.07<br>Girls 2023-04-27 Giraffe CalTemp:-0.74 CalHum:0.00
Of course, the numbers change. It's an environment sensor. Here's my code for the sensor:
- resource: http://192.168.1.31
scan_interval: 5
sensor:- unique_id: bme680_girlsroom_temperature
name: bme680 girlsroom temperature
select: ""
value_template: "{{ value }}"
- unique_id: bme680_girlsroom_temperature
I do not know what to put in select to get each number. Or the value template for that matter. Can you help?
Am I able to attach a calculated value from a template to the device itself so it has everything? like a temperature and humidty sensor having a real feel added to it so I can see all 3
you can if you create a template entity from the UI
can someone explain bereifly but surly what are remplates are for? begginer here
The docs page explains it pretty well 🙂
https://www.home-assistant.io/docs/configuration/templating/
When it tells me I need a basic understanding of things I don't know anything aobut I'm starting to get scared
But underneath that paragraph it tells you what templates do.
Thanks !
[{'name': 'Living Room', 'type': 'area', 'id': '5c5d54b7c86f4223ae8f6acf614d2c45'}, {'name': 'LR Lamps', 'type': 'entity', 'id': 'light.monoprice_z_wave_on_off_plugin'}, {'name': 'LR Standing Lamp', 'type': 'entity', 'id': 'light.sonoff_awp04l_1'}]
I'm getting rusty. How can I pull id for all elements in this list?
| map(attribute='id') | list
Thanks so much!
I have a triggered template sensor and would like to turn it to unavailable based on certain inputs. How can I do so? True unavailable, not a string "unavailable" ... Is it possible?
Ah. availability template in the definition of the sensor.
You need to set the availability:
availability template (optional, default: true)
Defines a template to get the available state of the entity. If the template either fails to render or returns True, "1", "true", "yes", "on", "enable", or a non-zero number, the entity will be available. If the template returns any other value, the entity will be unavailable. If not configured, the entity will always be available. Note that the string comparison is not case sensitive; "TrUe" and "yEs" are allowed.
https://www.home-assistant.io/integrations/template/#configuration-variables
template:
- binary_sensor:
- unique_id: template_bs_livingroom_activity
name: Living Room activity
state: "{{ area_entities('living_room') | select('match', 'binary_sensor.') | select('is_state_attr', 'device_class', 'opening') | select('is_state', 'on') | list | count > 0 }}"
delay_off:
minutes: 5
the above template sensor relates to: #automations-archived message
@lusty ridge I converted your message into a file since it's above 15 lines :+1:
Hey TheFes, thanks for pointing that out. If I'm correct though with that template I would still have the issue that if I had 2 contact sensors in the one area, lets say a door and a window in the same area, the time on the helper wouldnt be updated when the door opens and the window was open already?
I wouldn't say that matters, in both cases your room/area will count as active right?
as long as one of them is on, the area is active
@lusty ridge this is not related to #templates-archived, this channel is for jinja templates. Not sure what the right channel should be though
yes, but the last active time would be the time of the window opening. The area would be marked as "inactive" regardless of the window still being open.
the timestamp is what marks the area as inactive, not the state of the sensors
eg: a door opening is an indication that something is active, but an open door isnt, it could be that someone forgot to close the door
actually, skip that, I can work with the time of the first sensor being tripped 🙂
ah okay, you want the last time it changed as the indicator that it is active
ideally yes
Ideally I need both... an indicator for how long an area was in an active state and when it last detected activity. my motion sensors are still coupled to another system but both contact sensors and motion sensors would be used in an area to mark it as active
template:
- binary_sensor:
- unique_id: template_bs_livingroom_activity
name: Living Room activity
state: >
{% set last_change = area_entities('living_room')
| select('match', 'binary_sensor.')
| select('is_state_attr', 'device_class', 'opening')
| expand
| map(attribute='last_changed')
| last
%}
{{ last_change > now() - timedelta(minutes=5) }}
that will create a binary sensor which is on when an opening sensor changes state, and turns off 5 minutes after the last cahnge
5 minutes ± 1 minute
the binary sensor created here, is only for within the template right? or is it an actual thing that I can access outside of the specific automation?
that creates an entity that can be used anywhere
Hi guys,
I'm trying to create 2 template sensors for energy monitoring:
- a template sensor for energy that will increment daily with 0.96 kWh each time a specific switch is on at 7AM or between 7AM and 8AM
(use case: This will monitor my electric pump for sprinklers as I dont have a separate meter on it) - a template sensor for energy that will subtract daily from another energy sensor 0.425 kWh. I cannot subtract directly as I get a lot of negative values.
(use case: This will subtract my daily average consumption (without air conditioning) from the total phase C energy consumption (air conditioning included), so the result would be AC energy consumption)
Any ideas how can i use that?
Thanks!
Not a direct answer, but I would recommend to check out Powercalc https://github.com/bramstroker/homeassistant-powercalc. Solves a lot of these kinds of issues.
That, or create template sensors with a fixed power value (for the first case include an if statement making it 0 if the the switch is off) and integrate those to energy
That's what I thought, but I don't know how to write the if statement with time constraints.
Or I can make somehow the increment at 7:30AM only if the switch is on? 🤔
Where can I find some documentation about all possible if conditions?
I have a Markdown Card with a text showing the total number of lights in my house, and the number of lights that are turned ;
`There are {{ states.light | selectattr('entity_id', 'in', label_entities('Light'))
| list
| count }} lights in the house, {{ states.light | rejectattr('entity_id', 'in', label_entities('Lightgroup'))
| selectattr('state', 'eq', 'on')
| list
| count }} are turned on`
This results in it showing; There are 39 lights in the house, 1 are turned on
How do I change this to show; There are 39 lights in the house, 1 is turned on when there is only 1 light turned on?
I would probably assign the calculation to a variable (or template helper if thats your jam)
Then you could do {{ varName }} {{ varName == 1 and 'is' or 'are' }} turned on.
So something like this I think would work (could probably be simplified 🙄):
{% set num_lights = states.light | selectattr('entity_id', 'in', label_entities('Light')) | list | count %} {% set lights_on = states.light | rejectattr('entity_id', 'in', label_entities('Lightgroup')) | selectattr('state', 'eq', 'on') | list | count %} There {{ num_lights != 1 and 'are' or 'is' }} {{ num_lights }} light{{ num_lights != 1 and 's' or '' }} in the house, {{ lights_on }} {{ lights_on == 1 and 'is' or 'are' }} turned on.
that works, awesome, thank you 🙂
I've found the conditions page (including time constraints), but couldn't find the "do" part.
Can you give more details on that? 🫤
Because if I see there is rain coming next day I deactivate the relay that supply the pump with energy at 22:00 or even if there's a storm during the night I might remember I left the relay on and turn it off
Then I turn it on anytime during the day
condition: state
entity_id: switch.releu20A
state: on
- condition: time
after: "7:00:00"
before: "8:00:00"
But if you just use the state of the relay, you have your consumption right?
I assume it also consumes power if it's turned on at 6:00
No. The relay ON is just the power supply. For the actual sprinklers I have a programmable device that selects certain zones and open valves.
It's only mandatory for the relay to be on in the interval 7-8AM
well, anyway, you can't use these kind of conditions you posted in templates, you can compare times to the current time
have a look at the templating docs, they are linked to from this channel
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
Hi guys, does anyone have any idea how to find the closes value using jinja?
I have a value from an entity, and then I have 3 values in helpers. I want to know which helper has the closest value to the entity
I think it's not gonna be an easy ride
Top of my head:
Set the initial value as a variable
Set two more variables: minimum difference (init it to something big) and closest helper (to empty value)
Loop through the three values and compare each value to the inital value
If the new value is smaller than the previous, assign it to the result variable
Something like that, hopefully that could point you in the right direction. 🙂
thanks 🙂
closest in regards to distance or what?
can you describe what you're trying to do?
big picture, not what you want the jinja to do
Managed 🙂 got some assistance from chatGPT and made it work 😄
@vale osprey I converted your message into a file since it's above 15 lines :+1:
finding which entity (helper) has the closes value to the new state value
Basically i'm using this for a scale... 3 people use the same scale. Each weighting a bit different than the other. So when you go on the scales the new value is checked against the current weight of the 3 people, the closes one is updated with the new value
{% set target = states('sensor.a') | float(0) %}
{% set entities = ['sensor.b', 'sensor.c', 'sensor.d'] %}
{% set ns = namespace(items=[]) %}
{% for v in entities | select('has_value') %}
{% set ns.items = ns.items + [{'e': v, 'd': target - v | float}] %}
{% endfor %}
{{ ns.items | sort(attribute='d') | reverse | first }}
that works with any number of sensors, not just 3
wow, thanks 🙂
to make it easier to maintain which entities to check, you could use labels
so if the entity id changes, you won't need to update the template right 🙂
yes, or if you want to add or remove entities
I assume there is some function getEntityByLabel or something...
sorry for the questions but i'm not a developer... 🙂
label_entities('label_id')
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
it's mentioned in the templating docs
much appreciated 🙂 thank you all
I think labels are being abused right now in all aspect. I think HA needs to split the concept in different properties
I would assume if labels are also being used in templates, the list of labels is huge on your end
How so? Labels work damn near perfectly.
it's up to the user how to use them 🙂
abused is a harsh term
it's a great way to group items without needing a group entity
agreed. but I feel like it being used by a lot of different scenarios. and together that makes it confusing. yes abused is a harsh term 🙂
I love labels, don't get me wrong
"a lot of different scenarios" Compared to what we had, labels should apply to a lot of different uses, imho.
exactly, and the name suits it well. As a label is quite generic and can be used for anything
but I feel that because of lack of certain other functionality for classification, etc, labels are being 'overused'
Areas, devices, helpers, entities, labels, categories, how much do you need?
I wouldn't say "overused". They're doing exactly what they are built for. Yes, you can overuse them in a sense I suppose, but I haven't hit that scenario at all. For instance, I have all my Zigbee router devices labelled with "Router". I can easily filter on all my routers and even break that down by areas if I choose to.
ye that is how i'm using them too, to group the device (router, socket, etc)
but then there are situations where I but a lable like 'Always On' , so when I switch off all the sockets for example, those with 'always on' are not switched off
which to me that sounds more like a 'tag' than a label
lol I was just typing that
🙂
yes, so what Im saying is that those two scenarios are both being handled by labels. I would assume most of you have huge lists of labels
Nope, rather small
oh okay 🙂
maybe I'm over complicating it, but what if you are able to create a label with sub labels? 🙂
I actually haven't used them at all in any automations/scripting, most of my usecases for many entities are already on the same domian
You can do that, you can add multiple labels to entities
but you cannot set a parent to a label, right?
I have 24 labels right now
you don't need a parent label
just mark everything with one label, then filter your list to said lable, and add your second label
and if you want to filter... label_entities('x') | select('in', label_entities('y'))
or don't even bother with that, and just go for label_entities('y')
I definitely think you're over complicating things
I'm at 19
19, 24 are fine. quite controlled
I think one of my issues for example is organising helpers. But that would be sorted the moment the device linking is done for all helpers and not just template helpers.
It's already done for more
glad to hear 🙂
Is it possible from a template to update a value of another entity? I guess not right?
has to be done through automations I guess
uh, you should avoid that type of logic
is there a way to translate in templates?
got this
Goedemorgen, het weer voor vandaag is {{
states('weather.forecast_thuis')}}
but weather.forecast_thuis = english, and it doesnt "Work" in the TTS XD
it says "cloudy" and it should be "bewolkt"
https://www.home-assistant.io/docs/configuration/templating/#state-translated-examples
{{ 'weather.forecast_thuis' | state_translated }}
Or {{ state_translated('weather.forecast_thuis') }} - same thing, other format
Hey all,
Is it possible to get history data from 24 hours back as an int to use ?
Only the SQL integration can do that
Any documentation on that?
Yes, in the sql integration
Thanks ❤️
Hi! I'm trying to create a binary sensor that will be on if my bedroom1 motion sensor has detected anything in the past 5 minutes. I think I'm close but can't wrap my head around the template anymore.
The current behavior is: sensor is always off, turns unavailable when bedroom1 motion detects, then back to off. Here's the YAML: https://dpaste.org/Gg6Nz
is there also a way outside of general to specify what language it needs to be, because i like my interface in english and not dutch XD
I would just do this:
sensor:
- platform: template
sensors:
bedroom1_motion_recently_on:
friendly_name: "Bedroom1 Motion Recently On"
value_template: "{{ is_state('binary_sensor.bedroom1_module_bedroom1_motion', 'on') }}"
delay_off:
minutes: 5
Well, actually I would use the modern template binary sensor format instead of the legacy format
Invalid config for 'template' from integration 'sensor' at configuration.yaml, line 33: 'delay_off' is an invalid option for 'sensor.template', check: sensors->bedroom1_motion_recently_on->delay_off
think i tried this before too, i remember this warning
also, is there a new format? i only knew about this one
you need to switch to the new template format for that
AFAIK you would have to translate the possible states yourself in a template
no, I linked to the legacy binary sensor configuration format
where it's not listed
but the anchor for delay_off is the same for the modern format and the legacy format, if you click on the anchor it moves to the new format
it's listed in my docs
oops, was looking at the wrong one
for some reason my image upload is'nt working, but you seem to have found it 🙂
yeah, images in Discord have been broken for a couple of days
they don't have any trouble showing the poop emoji
then I tried imgur, which gave me an unsupported filetype message, are they using the same backend?
anyways @tame axle you could try if it works in the modern format
When templating a for: in an entity state trigger, can we template the entire for: or just the hours, minutes, seconds? The docs show the indivial properties, but nothing for the for: itself.
template:
- sensor:
- name: "Bedroom1 Motion Recently On"
state: "{{ is_state('binary_sensor.bedroom1_module_bedroom1_motion', 'on') }}"
delay_off:
minutes: 5
I think it uses the same syntax as delay so you can also template the number of seconds.
Gotcha. Ok. That makes sense. I've been trying to do dynamic fors and it's fighting me. lol
prob if state = cloudy then say bewolkt
then i only need all the states it can give me XD
Invalid config for 'template' at configuration.yaml, line 33: 'delay_off' is an invalid option for 'template', check: sensor->0->delay_off
seems to be the same error
here's a truncated version of the whole config yaml, tho i think i put it where i should: https://dpaste.org/dF7x3
You're missing a space before minutes: 5 (you only have 1 space there)
oh, my bad. should have checked intendation

Invalid config for 'template' at configuration.yaml, line 34: 'delay_off' is an invalid option for 'template', check: sensor->0->delay_off
i just don't think that's possible https://dpaste.org/KpNfa
think i'll make it work with some automations and timers
ok found them
CLEAR_NIGHT
CLOUDY
FOG
LIGHTNING_RAINY
PARTLYCLOUDY
POURING
RAINY
SNOWY
SNOWY_RAINY
SUNNY
then ill do it like this
You can't use that with a sensor, only a binary_sensor. A sensor doesn't have "on" or "off" states
{% if is_state('weather.forecast_thuis', 'SUNNY')}} %}
Zonnig
{% if is_state('weather.forecast_thuis', 'CLOUDY')}} %}
Bewolkt
it works. thanks!
or should i take this diffrent?
do you have switch statements?
Switch(state('weather.forecast_thuis')){
"Sunny" = "Zonnig"
"Cloudy" = Bewolkt
}
Something like this?
There is no switch statement.
ok what is the best practis in this case then ?
you can do something like that with a straightforward map/lookup
{% set map = {'foo': 'bar', 'blah': 'floop'} %}
{{ map['foo'] }}
{% set map = {'weather.forecast_thuis'} %}
{{ map['sunny'] }}
{{ map['Cloudy'] }}
like this?
wait let me show you the whole concept
service: tts.speak
metadata: {}
data:
media_player_entity_id: media_player.sonos
cache: false
language: nl
message: >-
Goedemorgen, het weer voor vandaag is
{{state_translated('weather.forecast_thuis')}}. En de temperatuur is
{{state_attr('weather.forecast_thuis','temperature') }} graden. Vandaag
moet je naar {{state_attr('calendar.werk','message') | replace ("Service
Call:","") | replace(" B.V.","") }}. Geschatte reistijd is
{{state_attr("sensor.google_travel_time", "duration_in_traffic") |
replace("mins","minuten")}}.
entity_id: tts.google_en_com
{{state_translated('weather.forecast_thuis')}}.
This part needs to be translated to dutch
but i dont wanna change my general to dutch
{% set map = {'Sunny': 'Zonnig', 'Cloudy': 'Bewolkt'} %}
{{ map[states('weather.forecast_thuis')] }}
aaah
sick this works
thx allot @inner mesa
is it allowed like this
{% set map = {'Sunny': 'Zonnig',
'Cloudy': 'Bewolkt',
'rainy': 'regenachtig'} %}
{{ map[states('weather.forecast_thuis')] }}
try it?
nice it works
if some1 else wants it
{% set map = {'Sunny': 'Zonnig',
'Cloudy': 'Bewolkt',
'rainy': 'regenachtig',
'Clear_Night': 'een heldere nacht',
'fog': 'Mistig',
'lightning_rain': 'Bliksem & regen',
'partlycloudy': 'Gedeeltelijk bewolkt',
'pouring': 'Zware regen',
'snowy': 'Sneeuwerig',
'snowy_rainy': 'Nattesneeuw'}%}
{{ map[states('weather.forecast_thuis')] }}
Translated to dutch
it would be strange for the integration to reports states like "Sunny", "Cloud", "rainy", and "lightning_rain"
they are usually consistent in case and space handling
also seen this 1
"clear-night": "Clear, night",
"cloudy": "Cloudy",
"exceptional": "Exceptional",
"fog": "Fog",
"hail": "Hail",
"lightning": "Lightning",
"lightning-rainy": "Lightning, rainy",
"partlycloudy": "Partly cloudy",
"pouring": "Pouring",
"rainy": "Rainy",
"snowy": "Snowy",
"snowy-rainy": "Snowy, rainy",
"sunny": "Sunny",
"windy": "Windy",
"windy-variant": "Windy"
"sunny" is not "Sunny"
and then the right side is good
that doesn't matter, it's not the real state
you think the left side is the right 1 ?
looks better, but I'm also reading the thread there
What kind of weather is it when an integration states exceptional
exceptional rain and thunder and hurricaney
{% set map = {'sunny': 'Zonnig',
'cloudy': 'Bewolkt',
'rainy': 'regenachtig',
'clear, night': 'een heldere nacht',
'fog': 'Mistig',
'lightning, rain': 'Bliksem & regen',
'partly cloudy': 'Gedeeltelijk bewolkt',
'pouring': 'Zware regen',
'snowy': 'Sneeuwerig',
'hail': 'Hagel',
'snowy, rainy': 'Nattesneeuw'}%}
This should be better then
you say like this
Yeah, I started typing that, and then you corrected it. Now you made it wrong again
its wrong now?
"Nattesneeuw" is a wonderful word
Yes
clear-night is correct
your table is right here: #templates-archived message
yea and then the left side
"clear-night": "Clear, night",
yea but i wanna have it translated
Change clear, night here to clear-night
TheFes will help 🙂
like this
'clear-night': 'een heldere nacht',
You did that while I was about to say it was wrong, and then I made it confusing by changing my message instead of just not sending it
{% set map = {'sunny': 'Zonnig',
'cloudy': 'Bewolkt',
'rainy': 'regenachtig',
'clear-night': 'een heldere nacht',
'fog': 'Mistig',
'lightning-rainy': 'Bliksem & regen',
'partlycloudy': 'Gedeeltelijk bewolkt',
'pouring': 'Zware regen',
'snowy': 'Sneeuwerig',
'hail': 'Hagel',
'snowy-rainy': 'Nattesneeuw'}%}
{{ map[states('weather.forecast_thuis')] }}
There's also some inconstancy in the use of capital letters in your translations, but that's not an issue for the template itself
you dont hear that in the TTS
just offends my OCD
ah yea
i see now
when i change the state to snowy-rainy it says in the history snowy, rainy
good
cool the translate part also works now so this is all done 🙂
How do I about creating a binary_sensor based on Mobile app connection type? so for example the if the mobile is connected to 'WiFi', they are shown as 'Home' and vice-versa, thanks
you dont wanna use Device_tracker.Yourmobile ?
Create a binary template sensor helper with the following template: {{ is_state('sensor.[your mobile device]_connection_type', 'Wi-Fi') }}
better sensor to use in this case is
sensor.Yourmobile_wifi_connection
this way you can filter with SSID
It would've made my life easier, but person have concerns of battery drainage etc
That's only available on Android. iOS doesn't have that.
uh but your still giving them the app right?
_connection_type is available on both
yes ofcourse, and but since they don't approve location, it is always shown as 'Home'
ah that sucks XD
i just installed it and pressed on my own allow location 🙂
they dont even know >:)
you have unifi ?
Another wish of mine lol
something else you can track them on on your SSID?
would go that route, when they connect with your wifi they are "Home"
unless you dont have that ofc
Awesome, thank you! 😀
Ooohhhh and now you can also attach it to the mobile device itself! Love that new feature.
I've just noticed this as well, awesome feature 
only for sensors or also for text helpers?
Only for sensors. I think it's going to come to the other helpers as well.
Can the binary sensor be shown as a device_tracker, so I can replace the default one?
It could be, it's a scanner entity rather than a tracker one: https://developers.home-assistant.io/docs/core/entity/device-tracker
You can also set the device class to Presence to simulate it as well. Either way should work.
I've classed it as Presence and it works well, but HA doesn't detect it as a device_tracker even when linking the template. So, if I used the Person entity in frontend cards, it will only detect the default device tracker and not the template binary_sensor
Beyond my scope unfortunately
IIRC (it's been a few years since I've done this), you'd just create a device tracker in known_devices.yaml (if it doesn't exist, you can create it). It would look like:
wifi_device_tracker:
name: Wifi Device Tracker
icon: mdi:cellphone
track: true
Then, you would need an automation to trigger (this is where you can use your binary template sensor) and call the device_tracker.see service.
Ah good old known_devicse, I'll look in to it, thanks! 🙂
That file is deprecated, so you may want to consider that it's going away 🙂
True... but I think it's been on the chopping block now for what, 2+ years? lol
I just create MQTT device trackers, HA can then publish to make them "move"
(Technically it says it's being phased out, rather than that it is deprecated: https://www.home-assistant.io/integrations/device_tracker/#known_devicesyaml)
Same same
Interesting, thank you all
Since version 0.94 lol
Sometimes you realise early on you made a mistake, but it's already really difficult to unpick
How would I get it to appear on frontend?:
{{ state_translated(binary_sensor.person_presence) }}
you're missing quotes
oh my bad, thanks
That’s just life 🙂
@weak cradle I converted your message into a file since it's above 15 lines :+1:
I have a moving IKEA Desk that i want to build a sensor around if it's moving or not. I can see the current height but i'm unsure on how to build a template around if it's changing or not. I'm thinking i should be able to check when it was last change and if that's greater than a very small number then it's most probably moving (doesn't have to be bulletproof) still. I'm just not sure how to achieve that. Any ideas?
Use a derivative sensor to get the rate of change. If the rate of change is > 0 it's moving.
doesn't seem to work. THe height is reporter as number.megadesk_current_height and can't seem to be used in derivate sensor
make a template sensor from the number
{{ states('number.megadesk_current_height') }}
What settigns do i use for the derivative?
You have to figure that out
ok because i tried the standard one and it does not give me 0 when the desk i standing still
it depends on how fast your sensor changes state and what the values are
Hmm. I don't think it will work. When i use the buttons on the desk it does update the sensor in near real time but if i tell it to go to a postition nothing updates until it's done
paul, go bakc to automations and click that link
The derivative sensor will (usually) never go to zero because (most) sensors are prevented from reporting repeated values.
That won't always be true because state reported was added to address that
@tulip ibex I converted your message into a file since it's above 15 lines :+1:
Templates are not supported in card actions in most card types. You need to move your service call to a script, then call the script from the card's action.
That did the trick, thank you!
Did that change actually do anything on its own? I assumed the change had no impact on its own until each integration was updated to take advantage of it
yes, but it was specifically added to address integration and derivative
At least Riemann was updated to support a max sub-interval, which I think takes advantage of the last reported. Derivative has had no such update
I think you're not understanding my original statement
It seems like you're aruging that derivative doesn't have it when I said that it will be changed in the future
that won't always be true
Hello. I am trying to reuse a RESTful Sensor that is connected to a dashboard gauge. It currently displays water level for a pump, but I have two of them. For it to work as desired, I would need to pass it a different variable (device id). Is this possible at all?
name: Water Level
unique_id: water_level
resource: http://api.ptdevices.com/token/v1/device/1234
scan_interval: 900
params:
api_token: !secret api_token
value_template: "{{ value_json['data']['device_data']['percent_level'] }}"
unit_of_measurement: "%"```
Sure. Just create 2 sensors in YAML and use the different device ids.
You'll want to use two different names and unique_ids as well.
Can I pass the device ID as an input text from the gauge?
so I don't repeat that block of code
You could, but if you have 2 devices, wouldn't you want 2 sensors?
You're right
Sorry, last question. Is there a way to create 2 sensors based off the same code, but with different inputs?
I'm just trying not to repeat the code above twice, but maybe I'm overthinking it..
Using the same api call?
If I understand your goal, you would have to set up a second one with the according template again
Ok. Thank you @frail dagger and @marsh cairn
hi, can i mark a todo item as completed by only specifying the number of the array?
for example: todo.example[1] or something like that? i know i have to do it with the get service, but can i do this with the outputvariable?
The todo.update_item service takes the name of the item, so nothing there about taking an index in a list
You could get the name of the item by the list index and pass that
i can now get a list of all items, yes, but how do i output only the first item of the list?
How to identify the device used when triggering a scene?
https://www.home-assistant.io/docs/automation/templating/
The trigger data 😉
Can trigger data be used when running a scene too?
What exactly are you trying to achieve?
If a have a physical device in an area. I trigger a scene, I then depending on in what area the device is located turn of the lights in that area.
So I can have a generic scene that works for all areas.
Scene “turn of lights” triggered, what device triggered the scene, what area is that device located, turn of all lights in that area.
That sounds like an automation
In those, you can use the trigger data, Rosemary suggested
best plugin for good lovelaces?
Wrong channel?
and in which channel should i post it?
Yes I can use trigger data, but what data locates the device triggered the automation?
The trigger tells you which device did, if you look at the docs page I linked you to, it tells you about the trigger data...
For example, the template {{ area_name(trigger.entity_id) }} would return the (friendly) name of the trigger's area.
https://www.home-assistant.io/docs/configuration/templating/#areas
Hi all. New to HASS and Jinja. Got a project where I am trying to calculate solar clipping using the forecast.solar API and a script. Even if I set the clipping threshold to a lower number than the current forecasted values I always get 0.0kWh result from the script. Here's the sensor and script config, and help would be awesome, the traces don't show any failures so I think it must be the logic in the script.
You are running into an issue with the scope of variables
You can’t set or modify a variable inside a for loop and see the results outside that for loop
You need to use a namespace
How to template using the current device used. Eg using a physical panel in an area and only displaying entities in that area were its assigned. Eg a For loop of entities in an area but only entities in the area were the physical device is located.
[{% set area_filter = states('device.room') %}
{%- for light in area_entities(area_filter) | select('search', '^light.') -%}
Ah OK - so perhaps an intermediate input number to be used outside of the loop?
Scroll down to the heading titled “scoping behavior”:
https://jinja.palletsprojects.com/en/3.1.x/templates/#list-of-control-structures
I’m on my phone otherwise I’d type up an example for you
But that link has a good example for how to use namespace
Ah that makes sense. Unless I am mistaken, HASS seems to have a more limited implementation of Jinja?:
SCOPE OF VARIABLES
Variables have local scope. This means that if a variable is changed in a nested sequence block, that change will not be visible in an outer sequence block.
Inside the if sequence the variables action will only alter the people variable for that sequence.
No it is not a limited version. This should do what you want:
sequence:
- variables:
clipped_energy: >
{% set ns = namespace(clipped_energy = 0) %}
{% set interval_hours = 15 / 60 %}
{% for timestamp, value in data.items() %}
{% set value = value | float %}
{% if value > threshold %}
{% set ns.clipped_energy = ns.clipped_energy + ((value - threshold) * interval_hours) %}
{% endif %}
{% endfor %}
{{ (ns.clipped_energy / 1000) | float }}
You would need to ask in #frontend-archived . The backend doesn’t know anything about users or what device a certain user is using
Nice! Thanks so much. Working now 👍
{{ area_entities(area_id('sensor.office_average_temperature')) | select('search', '^light.') | list }}
Hey all, it seems everything in HA is a sensor or binary_sensor. I'm looking for ways to discern sensors by the type of device they belong to. Can that even be done?
as an example, I want all batteries that belong to switches as opposed to batteries that belong to temperature sensors etc. I also want to make sure if one device offers multiple functionalities, I only want to select it once.
Everything in HA is an entity. But, there are some different ways to do this. The easiest by far is with labels. It's a bit more time upfront (especially if you have over 2K entities), but allows for some really neat things. Especially since devices are defined by the integration they belong to and there really aren't many concrete standards in terms of how an integration exposes devices and entities.
You could also do some stuff with domains as well.
Hm. That sounds like a lot of work.
Upfront, sure. But it pays off in the end and allows for some interesting use cases.
true that.
Guess I'll just dig deeper into the various integrations and their attributes and see what I can come up with.
For instance, one thing that cannot be done via devices if using something like Zigbee2MQTT is to grab all my routing devices. With labels, all my routers are marked and I can just do a {{ label_entities('router') | list | count }} and get a count of all my Zigbee routers. Can't do that with device lookups.
You can also skip the looping entirely. Something like this:
sequence:
- variables:
clipped_energy: >
{% set interval_hours = 15 / 60 %}
{{ data.values() | map('add', -threshold) | reject('lt', 0) | sum * interval_hours }}
Nice, thats elegant. Now I have this information I can set overnight SoC, I need to work out when to set the batteries to charge in the day to soak up the clipped energy, might be more trouble than it's worth though, clipping only occurs ~11am-2pm... and if this is summer for the UK I dont think there will be any clipping to worry about
I am going slightly crazy. I am trying to dynamically change the image_entity in the Picture card. I have a text helper with the text of the image entity. I would like get that value in the field, but no matter how I try, I always get Entity is unavailable. This is all I am trying to do:
Thanks. Is there any other way you can recommend achieving making that field dynamic? I do have an automation that saves a snapshot as latest.jpg and thats the image i can point to. I thought there could be a better way through the template.
default frontend in general just doesn't use templates at all. that's a backend thing.
I have a few custom templates in /custom_templates changing icons and colors of icons based on entity values. Is that not the same things?
I'm not familiar with custom_templates
What am I doing wrong here? http://pastie.org/p/5xWnzrNDbA8ndGaKtk6qNa
I keep getting Template variable warning: 'dict object' has no attribute 'events' when rendering '{{ birthdays.events }}'
it's telling you that birthdays does not have events as a key inside it.
correct syntax is {{ birthdays['calendar.family_birthdays'].events }}
so in the actual state or state_attr?
state or state_attr has nothing to do with it
the response from get_events is a dictionary with key value pairs in it. The key being entity_id and the value being a dictionary with the events key.
so this then?
- variables:
events: "{{ birthdays['calendar.family_birthdays'].events }}"
descriptions: "{{ events | map(attribute='message') | join(', ') }}"
Yes
I got all that from one of your old posts 😉 kinda
no way I created those start/end templates
oh, no...I did that
they can be reduced to 2 lines
{% set days = states('sensor.family_birthdays_days') | int %}
{{ today_at() + timedelta(days=days) }}
oh and end would be
{% set days = states('sensor.family_birthdays_days') | int %}
{{ today_at() + timedelta(days=days + 1) }}
if you don't care about long lines...
after making this change, sensor went to unavailable
{{ today_at() + timedelta(days=states('sensor.family_birthdays_days') | int) }}
I am guessing message is wrong?
it is local calendar
it's most likely summary
thats what I thought
custom_templates are also backend
still unavailable
is this what you mean:
message: Test1 Birthday
all_day: true
start_time: 2024-07-12 00:00:00
end_time: 2024-07-13 00:00:00
location:
description:
friendly_name: Family Birthdays
supported_features: 7
then message is the field
maybe it is unavailable because it hasn't triggered yet?
are there errors in your logs?
it's unavailable because it didn't load
if it didn't trigger, that would be unknown
Thank you. Helpful to know. I will stick with automation and overwriting the same file.
nope, no errors
setting the state of sensor.family_birthdays_days in dev_tools states wont actually trigger the sensor will it
? that doesn't really make sense
There's a very good chance that you can solve your issue with template entities over whatever you're doing with that input_text and automations.
ok, I think I see what happened
it created a entity_id_2
need to make some alterations
2024-07-12 00:00:00-04:00 will the -4:00 mess with the start and end date?
now I am getting errors:
Template variable warning: 'dict object' has no attribute 'events' when rendering '{{ birthdays.events }}'
Template variable warning: 'dict object' has no attribute 'message' when rendering '{{ events | map(attribute='message') | join(', ') }}'
those are most likely old
if you use a unique_id, reloading templates won't create _2 entities.
yea, i changed the unique_id which was the problem
so now it reports a state of 2 but I want the actual calendsr event
can you just post all the code
Test1 Birthday
yea, hold on...will do another link
what I am ultimately trying to do is send birthday notifications 3 days out. 2 days out, 1 day out and then other stuff with voice assistants on the actual day
so, your template sensor will not contain birthdays on separate days
if you have 2 birthdays with 3 days of eachotehr this thing will not work
if that's not a problem... then what you're doing is fine
oooh, I think I got it
friendly_name: Today's Birthdays
birthday_events:
- start: '2024-07-12'
end: '2024-07-13'
summary: Test1 Birthday
description: ''
- start: '2024-07-12'
end: '2024-07-13'
summary: Test2 Birthday
description: ''
- start: '2024-07-12'
end: '2024-07-13'
summary: Test3 Birthday
description: ''
now to figure out how to say Happy Birthday to Test1, Test2, and Test3 😜
yea, my big problem is 3 birthdays on one day
and I am still getting Template variable warning: 'dict object' has no attribute 'message' when rendering '{{ events | map(attribute='message') | join(', ') }}'
I think i need summary now

thank you for your help @mighty ledge
well, if you have 3 birthdays, each 1 day apart, youll only get 1 birthday in your template sensor with your current setup
and because HA is async, you never know which one you'll get
ha, no all on the same day
this one is just for immediate family
later I will only trigger on 0 for extended family
I think you're missing my point though
I have an automation that takes a camera snapshot and saves it as /media/latest.jpg. Then I just point the image field of the Picture card to that image path. I just can’t figure out how to do with templating entities, so will just go with the good enough solution.
but all birthdays are more than 3 days apart
ah ok
only 5 people 😜
Just make a template image entity
then use that
or a generic camera entity
and use that
no input_text or automation needed.
just point to the media file.
My idea is I have 5 cameras and wanted to show the image of the of the one the one that triggered. I use frigate, so I could access it at image.camera_name. I made a helper to get the latest camera that showed the image and my plan was, to insert the image_entity of the camera entityid. The issue was, I couldn’t even get it to get the value from a text helper. So templates no allowed, made sense, I couldn’t use the helper or a custom template to do that I was trying to do.
You don't need any of that. That can all be done with a template entity.
at most
fully post what you have and I can show you what I mean
This gives the correct entityid. http://pastie.org/p/5yKTBHj1NZFdNkqNRRPTm6
That was in the helper. and i was trying to get it to work getting the state of the helper
what do you mean "without getting the state of the helper"
trying to get it to work with the state. * image_entity: '{{states(sensor.getlatestperson)}}'. sensor.getlatestperson is the id for the helper
Thats all it was. The helper to store it and the picture card to show it.
Yes, then all you need is a template image entity, nothing more.
I have tried. I am just not getting it. Thanks anyway.
@rich temple I converted your message into a file since it's above 15 lines :+1:
Someone pleae help me with this, im tryna to create a custom sensor for this because TAPO removed it 😄
The legacy template sensor platform does not support state_class and it will not be added. You need to use the new template integration.
and will i be able to still use it in the Energy tab?
Yes
# configuration.yaml
template:
- sensor:
- name: Total Consumption
state_class: total_increasing
device_class: energy
unit_of_measurement: "kWh"
state: "{{ states('input_number.total_consumption') }}"```
Also confusingly this would have been better off in #integrations-archived as it is not actually a question about the template itself. But it's quite in here. Remember for next time.
Okay! im new to HASS so idk what this was 😄
No probs.
❤️
@thick matrix I converted your message into a file since it's above 15 lines :+1:
Looking for some help on a template cover configuration. The resulting cover entity in HA and HK are not updating despite the LG washer (and sensor status) changing.
Goal: expose a sensor/switch/cover from HA to HomeKit which is toggled when the washing machine is finished (then configured to alert us via the native apple home activity notifications functionality).
Working integration from LG via the https://github.com/ollo69/ha-smartthinq-sensors HACS add-on.
Here's what's in my configuration.yaml:
@thick matrix I converted your message into a file since it's above 15 lines :+1:
If everyone can see these file conversions I'm SO SORRY (and mortified) 😅
Please go to #integrations-archived and describe what you want, not the problem with your current very badly configured template cover. This is probably the wrong integration for what you want.
How do I get the response to weather.get_forecasts in a template to work with? Guessing there’s some function to call
The state function seems to only work with sensors, not services
Should I be looking for these functions in the Jinga docs, HA docs, or integration docs?
I have zigbee innovelli blue lightswitches, and they have a number. innovellixxxxxx entity that sets the default indicator led color by hue. It is a 0-255 value, where zero is white and the hue rotates through for the other values. What I would like to do is define a template light to remap the 1-255 range to degrees, so that I can use a light entity in a card and have the hue coloring for the slider.
You specify a response_variable in the service call, and then you can use that variable in your template.
https://www.home-assistant.io/docs/scripts/service-calls/#use-templates-to-handle-response-data
See examples specific to weather.get_forecasts on the weather integration page:
https://www.home-assistant.io/integrations/weather/#examples
make a template select, with the following template for the state:
{{ states('number.innovellixxxxxx') | int(0) / 255 * 360 }}
then the template in your set_value will be
{{ value / 360 * 255 }}
... did you completly forget our entire conversation and all the help I provided the other day? Like literally 100% of it?
Thanks for the example, I did not really know about select template. My understanding is that I'll need to make an actual template light if I want to use the colorize attribute hue on the slider in lovelace, or it won't apply that.
`type: entities
entities:
- type: custom:slider-entity-row
entity: number.inovelli_vzm31_sn_default_all_led_on_color
name: LED Bar hue
colorize: true
attribute: hue`
Maybe I can instead set up a hue picker that works directly like a template select? The main thing I want is a visual colormap in the lovelace interface, not just the rescaling of the input.
Well, you can just make a select to adjust the color. If you want it to be a light in the UI, that will take alot more work and alot more tempaltes.
I meant template number not template select, my b
I think I asked the wrong question. Is my understanding correct that a Service is something that is immediately executed and waits for a return value/ status (asynchronous function call) and a sensor is a value that is periodically updated, so it’s value can be read instantly? I know that I can get a value from a service call into a template by calling the service separately before getting to the template part. However, I see that I have something called an “entity” named “outside” and “weather.kw99_daynight”. That seems to already contain weather data, including all forecasts. Is this already accessible somehow in a template (and periodically updated without having to call the service constantly ), or is the entity-viewer just calling the service?
weather entities do not have forecast attributes
what you're seeing is old information wherever you found it
weather entities used to have forecast attributes, but htat was removed to keep the large data out of the database
Settings -> devices and services -> entities -> Outside (weather.kw99_daynight)
is that a custom integration?
if yes, custom integrations... all bets are off, they can do whatever they like
“National Weather Service”. Not listed in HACS. Any other way to determine if it is “custom?”
If it's in the integrations page on the HA website, it's a native integration.
NWS does not have the forecast attribute
Are you referring to the list on the entities more info page?
that's a special window.
go to developer tools -> states page to see the available attributes