#templates-archived
1 messages · Page 81 of 1
Hah. Yes exactly that.
how? ```service: weather.get_forecasts
data: {}
tried quite some combinations, pasting "{{ hourly['weather.openweathermap'].forecast[0].precipitation_probability }}"
in there, but no luck.
Dev tools > services > weather.get_forecasts. Choose your entity and the data gets returned. That's how you see the structure.
Well, exactly the same as you do it in the code for the sensor
service: weather.get_forecasts
data:
type: hourly
target:
entity_id: weather.openweathermap
response_variable: hourly
thanks, that worked....but more confusing.
How so? This is what you are using as input for your template sensor
so it returns times that are in the past, is the clock perhaps incorrect then of this integration or something?
The times are UTC
it shows 19:00 as earliest time, but it's 21:29 here.
See the +00:00 at the end. You are in the Netherlands and daylight savings is active, so you are in timezone +02:00
So the first time is 21:00
Which is the forecast of the current hour
so i need to set the +02:00 somewhere?
No
The times are shown in UTC
HA knows how to handle those
It knows your current timezone
ok
so openweathermap'].forecast[0], would grab the top datetime state?
openweathermap'].forecast[1] would grab the hour after?
correct
thanks a lot everyone here, think i got forecasts set up now, and with these examples its easier to build up additional things i might need. can probably easily create copies now.
Can you try this?
{{ string(state_attr('sensor.viewassist_masterbedroom_intent',
'intent_output')['response']['speech']['plain']['speech']) !=
"Sorry, I couldn't understand that"}}
Thanks for the help. I've embarassed myself. I had another test automation that was causing the issue. My original automation was working fine.
hey, I am looking to improve one of my automations but I am struggling with how to template part of it.
The automation is fairly simple, it compares the dew point inside the house vs outside and if any windows are in the "wrong" state and someone is at home it will send a mobile app notification to that person and also announce on the assist speaker that the windows should be closed / opened.
What I am trying to do is enhance the notification (both mobile and TTS) so that it actually includes which windows specifically are in the "wrong" state.
TL;DR is there a way to pass a dynamic list of sensor entities in a specific state to the notify_mobile_app and tts service ?
I try with map('device_name')
{{ integration_entities('mqtt') | select('is_state', 'unavailable') |map('device_name') | unique | list | join('\n') }}
But error:
TemplateRuntimeError: No filter named 'entity_name'
How to get Name of device
device_name is not a filter that exists.
{{ integration_entities('mqtt') | select('is_state', 'unavailable') | map('device_attr', 'name') | unique | list | join('\n') }}
Thanks
- platform: template
sensors:
dag:
value_template: "{{ ['Pazartesi', 'Salı', 'Carsamba', 'Persembe', 'Cuma', 'Cumartesi', 'Pazar'][now().weekday()] }}"
dato:
value_template: "{% set months = ['ocak', 'subat', 'mart', 'nisan', 'mayis', 'haziran', 'temmuz', 'agustos', 'eylul', 'ekim', 'kasim', 'aralik'][now().day | string + ' ' + months[now().month-1]}}"
whats problem here
aside from the fact that you didn't format it properly here
value_template: "{% set months = ['ocak', 'subat', 'mart', 'nisan', 'mayis', 'haziran', 'temmuz', 'agustos', 'eylul', 'ekim', 'kasim', 'aralik'][now().day | string + ' ' + months[now().month-1]}}"
it looks like you started with setting a variable and then went straight into some output logic
so you're missing the end of the first part and your output part is misformatted
The easiest way to proceed is to apply the format you used in the first one to the second. For some reason, you decided to do something different
can you do this for me?
@inner mesa
All you need to do is replace the [ before now().day with %} {{ so the statement gets completed and the expression is properly started.
No, they need to replace {% set months = with {{
Just like in the first one, like I said earlier 🤷
curious about how something works, if i were to use the following in the templates developer tool i am returned the result null
{{ states.sensor.afvalinfo_home_trash_type_tomorrow.state }}
However if i were to add this below that line i get None , twice.
{{ states('sensor.afvalinfo_home_trash_type_tomorrow') }}
if i were to go to the entity in the GUI i am also shown None
Why is there a difference in stating it twice?
can u send full code
That wouldn't fix the unpaired [ and either the mapping or the day clause would need to be moved as well...
This is just how the template tool, and I think Python in general, works. Python is dynamically typed, and you can see the Result type displayed next to the output. If you put {{ None }} as the only thing on the template tool, it gets typed as a dict (Result type: dict) and it will render null. If you add anything else outside of that template, like {{ None }} a then the entire template will be rendered as a string and you’ll see None a because that’s how the NoneType variable gets rendered when joined into a string
Or more explicitly replicating what you saw, enter one line and then both lines of this into the template tool:
{{ None }}
{{ None }}
Asked a question in blueprints but will ask here as well as it may be more applicable. I have a BP that is accepting an input which contains a python list. I believe this is being returned as a string and the automation is not validating. Can I convert a string to a list in jinja?
- if:
- condition: template
value_template: >-
{{ trigger.slots.mode in ['normal', 'night', 'hold', 'cycle'] | trigger.slots.mode in ['do not disturb'] }}
Hold on. So I think it is my formatting. Can I not do this? If I remove one of the options and the pipe it validates
I changed the pipe to 'or' and it is working.
I guess I made an assumption that I could use pipe in place of or. Apologies for the bother.
I did not give a lot of context. If interested, this is the blueprint:
https://github.com/dinki/View-Assist/blob/main/View Assist custom sentences/Device Functions/blueprint-devicefunctions.yaml
trying to create a time of day sensor and im getting a error for my template:
{% set current_time = now().astimezone('America/Chicago').hour %} {% if current_time >= 5 and current_time < 12 %} mdi:weather-sunset-up {% elif current_time >= 12 and current_time < 17 %} mdi:weather-sunny {% elif current_time >= 17 and current_time < 21 %} mdi:weather-sunset-down {% else %} mdi:weather-night {% endif %}
"a error"?
TypeError: tzinfo argument must be None or of a tzinfo subclass, not type 'str'
are you trying to use the time in a different time zone than the one you've set for your HA instance?
well HA has my time zone wrong as my lights come on during the day than at night. i have updated the time zone but it still thinks it night when its day. Im using a HA VM on my unraid server
fix that before trying to work around it
I have updated the time zone but it still thinks its night right now
What does {{ now() }} return in developer tools > templates
TemplateSyntaxError: expected token ':', got '}'
pretty sure not
Hey guys. How would I sync an input number to a timer counting down?
What are you looking to achieve?
I'd like to have an input number which already dynamically sets a timer, countdown as the timer does
Right, but that's just restating the solution you mentioned above. What are you actually looking to do with the result of this? For example, you can just use an entities card (or other cards) to display the timer duration on a dashboard if you're looking to observe the timer
There's no other reason than trying to better understand how to make templates. In my attempt to learn, I imagine a scenario and then try to do it with a template.
To be clear, I timer doesn’t actually count down. It stores a finishes_at attribute with the datetime that it should finish. Then it fires an event and changes state to idle when that datetime is == now. It’s only the frontend that makes it appear that something is counting down. Changing an input number every second would create a lot of useless entries in your history database and waste cpu time.
HA prevent people from doing what you want to do exactly because of the reasons I mentioned. Specifically, templates with now() are throttled to only execute once per minute
Oh ok, gotcha
Just for learning’s sake, yes you could create an automation or a trigger-based template sensor and trigger it using a time pattern of every second.
I hate mentioning that because someone will inevitably see this and start doing that instead of using timers, and then will come back complaining about how slow HA is and how large their database is
Yeah, you're probably right...lol. I was gonna do it by minute though.
If you really want to learn templates, a good place to start is things like complex binary sensors. For instance, detecting when you are home/away during times of the day or something. Or combining different sensors together. That’s really how I learned how to do some interesting templates. Also, asking for ideas is sometimes a good idea as well.
I have a couple that check various conditions and combines them up into a single binary sensor. Works great for scripts and automations.
I've gotten ok at those scenarios. It's the timed based things that throw me.
Ah, gotcha. Yeah, those get complicated quickly. lol
Those damn time codes look like Mandarin to me
For a simple starter, try creating an automation that triggers at a specific time, but use a template trigger instead of a time trigger
And tempting state holds. That was a pain to get my head around at first. lol
I think that this {{ now() }} is at the present, but don't understand the how and why.
You’ll need to give this a read: https://www.home-assistant.io/docs/configuration/templating/#time
Hello, I ll need your help regarding a binary sensor template.
Do you know how I can fix this state template code to tell me when a battery is low or not ?
{{ states.sensor | selectattr('attributes.device_class', 'eq', 'battery') | selectattr('state', 'is_number') | selectattr('state', 'le', 15) | list | length > 0 }}
map the state, then map the states value to an int, then select <= 15
@mighty ledge thanks
Can you template gods please help me, I am too stupid to write a sensor for current (hourly) weather forecast (temperature in degrees celsius)... I know that this service provides this data, and more... But i cant manage to write a sensor which updates this info on hourly basis.... I would greatly appreaciate your help!
service: weather.get_forecasts
data:
type: hourly
target:
entity_id: weather.home
thank you...! It was in the example box which I needed to clap open, got you
sensor:
- name: Temperature forecast next hour
unique_id: temperature_forecast_next_hour
state: "{{ hourly['weather.myhome'].forecast[0].temperature }}"
unit_of_measurement: °C
UndefinedError: 'hourly' is undefined
although I am sure that my integration/entity weather.myhome provides hourly data... how can I proceed to get the hourly value?
service: weather.get_forecasts
data:
type: hourly
target:
entity_id: weather.myhome
provides hourly forecasts, so I am not sure why I am failing
response_variable: hourly is failing, neither the service call nor the template understands this line...
I'm not sure that you're really following the docs there
Are you following that example completely? Or are you taking bits and pieces)
My guess is that you're trying to put all that in sensors.yaml or something
Or you're using some ancient version of HA
you guessed correctly. Thank you for your support, I guess I need to read how to correctly insert this and where... I just pasted it all in there and I guess I am wrong.
You put it in configuration.yaml
I'm not understanding something. The following does list some of my entities, but one of the entities has 100% battery level. Also, is this searching for "battery_level" as part of the entity id name?```
- sensors:
low_batteries:
friendly_name: Low Batteries
unique_id: "83ns7b4d82nd"
value_template: >-
{{ states.sensor | selectattr("entity_id", "search", ".*_battery_level")
| selectattr("state", "is_number")
| selectattr("state", "le", "20")
| map(attribute="entity_id") | list }}
icon_template: mdi:battery-low```
you have to use namespace if you want to count numeric states
you can't use a one liner
states are strings and 100 is less than 20 in regards to string comparisions
as for your question about search, no that's not correct. change it just to "_battery_level"
When you say count, would that be different than making a list
count, making a list, same difference
The reason I asked that was I did put some other code in and it gave a number of the devices and not the device names
what would I need to put to get actually the devices less than my threshold
Does "_battery_level" include any battery entity, or just the entities with battery_level in the id name?
That'd be the latter, it's checking the entity ID only there
Hey, hope everyone is well.
Im not sure if this is the right place to ask but i would like some help to see if a custom sensor can be made via the template helper for my Innr Zigbee Smart Plug. I want to create a sensor that would show the total consumed energy in kWh for the month like with one of my Tapo Smart Plug has as standard. Could anyone help me with some guidance on how to do this if its possible. Thanks
Hey guys, I'm trying to do a sensor that will detect how much time my server went down. I have the integration ping that knows when my server is up and down. So when my server is up again, it will send a notification and I want this notification to show how much time my server was down. So I want to do a template that gets my uh when it went from offline to online this time and get the time that was to online to offline. Get this time and subtract them to get the time that it was offline. But I cannot find a way to do this template. Could you help me please? Thank you!
use a state trigger on the binary_sensor entity that indicates the state of the server and use something like {{ trigger.to_state.last_changed - trigger.from_state.last_changed }} to get a timedelta object
or, {{ trigger.from_state.last_updated|relative_time }}
I think I didn’t understand your idea, but I could not implement it. I didn’t know where I can put my entity. My entity is binary_sensor.ubuntu_server and I think you didn’t understand because I don’t want to compare this current state with its last state and compare this time. I want to compare its last state with its penultimate state and find this time.
oh, I forgot they deprecated relative_time in favor of time_since, so {{ trigger.from_state.last_updated|time_since }}
a binary_sensor only has two states - on and off
when your server becomes unavailable, the binary_sensor turns off. When it becomes available, it turns on
when it turns on, the last state was "off"
the time between now and when it turned off is the amount of time it was unavailable
So when my server is up again, it will send a notification and I want this notification to show how much time my server was down.
Am I misunderstanding that statement?
Yes, you're correct. I was thinking another thing. I was thinking that I would trigger this automation after, but no, I'm triggering it in the moment that it will turn on. So yes, you're correct. I can compare my real time because it's the time that he turned on. Thank you for your help.
Actually, it will not work. I was here implementing the solution, but it will not work because it will run the automation when the states are already changed to on. So it will get the time that the state went from off to on and compare it with the current time, which will be zero. Instead of getting this off time, I need to get the penultimate time.
So, when the automation is triggered, the entity is already on. So, it will get the time that it was off. The last time it was off, that was 0 seconds before, because the automation was triggered right when it was on and switched. So, I need to know the time that it will be before that. So, when it's the last time it was on, basically. I don't know if you understand, this is the code that I'm using, the template code.
{% set desligado = states.binary_sensor.ubuntu_server.last_changed %}
{% set ligado = now() %}
{{ (ligado - desligado).total_seconds() | timestamp_custom('%H:%M:%S', false) }}
That's nothing like what I gave you
If you're not going to use what I suggested, you'll have a bad time
And waste mine
I didn't understand how I can implement your solution.
Clearly
Could you help me?
trigger:
platform: state
entity_id: binary_sensor.ubuntu_server
to: 'on'
action:
service: persistent_notification.create
data:
message: Server has been down {{ trigger.from_state.last_updated|time_since }}
Server has been down 9 seconds
fixed a typo and tested
would love something like this, but my server -is- my ha server, so ... looping dependency 😛
Okay, so while I'm poking bugs and stuff, I've been trying to test out a statistics sensor to address the bathroom temp sensor throwing spikes when the shower is used and triggering automations. Wanted to do a rolling 1 hour average so a five minute spike won't make it freak out (high temp warning on a grow light). But I have these gaps in data from that sensor that I can't explain with any activity from the base thermometer https://imgur.com/a/lKoO6qd
It's been a while I know but did you figure this out?
The statistics sensor will go unavailable if there hasn’t been an update to the source sensor for longer than your configured window. In your case you are doing the average of the previous hour, and there is no data from the source sensor in that previous hour
grumbles
Hello everyone, I've been using the ui minimalist theme for a few days now, and I need your help.
Indeed I manage to make work a lot of cards, but when I try to add some cards in custom-cards and I create the .yaml file, the card makes me a custom elemet doesn't exist or I have an error cannot read properties.
I have the impression that I may have an error in my way of accessing button-card-templates via the ui-lovelace.yaml file and I'd like your help. (P.S : not sure to be in the good channel)
#frontend-archived is where you should be
thank you !
@quiet bison I converted your message into a file since it's above 15 lines :+1:
If you just want to grab the first model from the list {{ state_attr('sensor.solaredge_inverters', 'inverters')[0].model }} should work
❤️ TYSM!
You're welcome!
Hello,
I have 2 template conditions for my welcome home automation/announcement, they check for a state change within a certain time frame.
One to check if the front door has been opened recently (within 30 mins),
and the other to check how long the system has been up (for after restarting - beyond 30mins).
But I don’t think it’s working correctly as I just rebooted HA and not long after this the welcome home massage played :-s
@next helm I converted your message into a file since it's above 15 lines :+1:
Not sure if this message is supposed to be in here:
#frontend-archived message
I'm so confused with the channels lol
@next helm in both cases you are checking if the time is less than 30 minutes. Which will be true after a restart for both, as the last_changed value will be reset after a HA restart
I replied to your message, not possible in HA
Man I dorked up my sensors by adding a unique id and now there are two of them:
(are pasting images from clipboard disabled in here?)
Anyway they both have the same friendly_name now...
sensor.solar_status_panels
solar_status_panels
unavailable
friendly_name: solar_status_panels
restored: true
supported_features: 0
sensor.solar_status_panels_2
solar_status_panels
on
friendly_name: solar_status_panels```
Delete the old one (might need a restart before you can delete it) and rename the entity ID of the second one later
Entities page - select mode (button besides the search bar with the little checkmark) - select the old one -
menu - delete selected
ty. that was weird but I got that worked out. delete the old, rename the new to the old .etc
hopefully next time i'll be smart about this up front
if you add a unique_id to any template sensor, just restart and you won't get yourself in any mess
reloading is what gets you in the mess
Can you expand on this?
what do you mean?
I’m interested to know the difference of reloading vs restarting
if you add a unique_id to an existing entity and reload HA see's it as a new entity
because the other one is already loaded, you now have a new one that has a unique_id
Since 2022.4, the issues() function exists to output all the repairs. Has anyone used this to count the number of outstanding repairs, or forward the list via a push notification? And, if so, could you share the code to do it?
Something seems broken with {{ issues() }} for me. I get a giant error in the log when I try that which starts with 2024-07-30 18:13:06.118 ERROR (MainThread) [homeassistant.components.websocket_api.messages] Unable to serialize to JSON. Bad data found at $.event.result<key and then appears to list all the repairs ever, or so it appears. And I get no output in
-> Templates, not even an empty list
I currently have no issues, but this isn't the behavior that I was expecting
it's a pretty unfortunate error message when using exactly the examples in the docs
it also seems to still list all issues ever, not just issues yet to actetd on
here's an example of one:
[
"hacs",
"restart_required_167885769_tags/v0.7.4b19"
],
🤷
well it returns exactly what it says in the docs, just because you can't output it to the template editor doesn't mean it's not working
iterate the dictionary as items and output each value
{% for issue, value in issues().items() %}
{{ issue }}: {{ value }}
{% endfor %}
sure, and I'm saying that when I turn it into a list, it's not telling me that I have no open issues. It's just listing every issue I might have had ever
yep, but you ahve to use the keys inside the dict to determine if it's active
I think the outstanding ones are identified by ‘is_persistent’: True
the docs show this as an example:
{{ issue('homeassistant', 'python_version') }} # {"breaks_in_ha_version": "2024.4", "domain": "homeassistant", "issue_id": "python_version", "is_persistent": False, ...}
as though it should list some of them with is_persistent: False, yet none of mine have that key at all
they all have that key
Mine all do, except one active one.
what goes between the ( ) for issues is the key, which is a tuple
fair enough, just doing {{ issues()|list }} isn't a good idea
it just gives me a list of lists for the first tuple of each item
it's a key value pair
the key is a tuple of strings
this is common in coding, but not common so far in HA templates
use .items()
I can parse the list pretty well by reading it, but I’m no jinja expert, so I have no idea what code is required to extract the details I’m looking for. That’s why I’m asking for help.
Appreciate the responses so far.
Are you looking for ones that are persistent?
and what value do you want out?
because this is all useless under the hood info IMO
To start, I’d settle for a count of persistent ones…. Then I could build a template sensor to surface that.
Longer term, I was hoping to forward the relevant details in a push notification when a new one is created. Though, looking more closely, I see what you mean…. The details you see in the HA UI don’t seem to be returned by this function.
Well, just the count for now, I suppose.
if you want active repairs, you can use spook
and then build automations from there
spook is custom
I had that before, but it was a lot more than I was looking for…. Maybe I’ll take another look at it.
anyways, for count
{{ issues().items() | list | selectattr('1.is_persistent', 'eq', True) | list | count }}
Thanks!
Hello :)
Did i miss something obvious ? a basic template condition never get passed, but when i use the same trigger data the the template page, it does return true
condition:
- condition: template
value_template: >-
"{{ trigger.from_state.state in ['standby', 'empty', 'cold_no_control',
'warm_no_control'] }}"
trigger:
from_state:
state: empty
It's the multi-line string sign (>-) accompanied with the "" the first should be enough
value_template: >-
{{ trigger.from_state.state in ['standby', 'empty', 'cold_no_control',
'warm_no_control'] }}
that not my writing, but yes.
I just put the template in the gui and it alwayse does funny stuff
but it "should work" anyway ...
no ?
You need to remove the double quotes around the template if you use the multi line notation
The way you have it now it's just a string, not a template
Oo
I've removed it, i guess it's been a while since i've done jinja in HA, because "putting jinja in quote" is hard engrave in my mind.
It will have to wait for the next coffee cup to check if it change something
thank's :)
@fiery hamlet I converted your message into a file since it's above 15 lines :+1:
I am running 2024.7.3, let me know if updating first would be suggested
{{ "Antin AirPods Max" in state_attr('sensor.xxx', "Active Audio Output") }}
that will tell you if that item is in the list
Is it possible to make a template binary sensor that only changes state if the underlying template is true for a specified length of time?
yes with delay_on option
https://www.home-assistant.io/integrations/template/#delay_on
is that something that is available in the template binary sensor UI?
And there is no way to have just the delay on and delay off part in the yaml (and the template is defined in the UI)
Just realised your doing this from a json call, this will be coming in the 2024.8 release, I scrolled too far back in my search results.
I added an example template sensor to the documentation to get all the dinner items for today to give you a start.
https://rc.home-assistant.io/integrations/mealie/#examples
Interesting, thank you for the follow-up!
I have a question, I'm looking for a design for my system that is modern but also clean. Does anyone have an idea?
Sounds like a #frontend-archived question
Hey all, can you help me make this work: https://dpaste.org/PG81A ?
I think the entity id bit won't work if I place the statement into a variable instead of inside the service call directly.
The idea is to construct a nice timestamped file name and use that to store a snapshot and point a local_file camera to it
you're nesting templates
that seems common for some reason
I also don't know what entity_id.entity_id is supposed to be
is that supposed to be passed in somehow?
I think that's the problem. imagine for a moment the variables section wasn't there and the temlate was where the variable is referenced now. In that case, it would see the entity_id property of the service call, but in the variables I don't have that. So I'd have to define it ahead of time somehow.
But I don't know how.
there's no way to reference the entity_id in a service call as a varaible in a tempalte
there's only one entity_id, so don't make it more complicated than it needs to be
That's a good point, I can simply take that out.
Hi. I keep getting this error in my logs WARNING (MainThread) [homeassistant.helpers.template] Template variable warning: 'dict object' has no attribute 'action' when rendering '{{ value_json.action }}'. This seems to be related to my Aqara vibration sensor setup in Zigbee2MQTT. Is there anyway I can change my value_template to avoid this error?
state_topic: "zigbee2mqtt/vibration/postbox"
availability_topic: "zigbee2mqtt/vibration/postbox/availability"
value_template: "{{ value_json.action }}"```
@inner mesa apropos of what we talked about yesterday regarding nested templates, I just wanted to say that in the right context, that nested statement did perform exactly as designed. So could one say "while nested templates aren't guaranteed to work, they aren't guaranteed to not work either"?
The classic "undocumented feature" so to speak?
Use an availability_template to check if the received value contains the expected attribute
Thanks. I've just searched discord and found something that works. For the benefit of others who have the same issue this is how it is now
{% if "action" in value_json %}
{{ value_json.action }}
{% else %}
0
{% endif %}```
Or just
{{ value_json.action | default(0) }}
That also works and is a lot more simple. Thanks!
Can you share the template?
Sure can, here it is: https://dpaste.org/nXq3Q
I'm not the original author, so please don't ask me why it was done the way it was done.
wtf is that template attempting to do
why is it outputting a template in the template?
where did you get it
As for what it's supposed to do, it's supposed to generate well-formed name for snapshots from diferent cameras, with a timestamp. So if you have a camera named camera.livingroom, it would generate the string "livingroom_20240802_120402".
As for where I got it, someone on github gave it to me. https://github.com/home-assistant/core/issues/123014#issuecomment-2262798917
Not sure why you'd need a nested template for that though.
Well if you don't know, don't ask me. I'm just acting like the average software developer copy-pasting the code of people with (presumably) more knowledge than me.
🤣
By the way, in the context of the automation posted, it works flawlessly for the time being.
I am so confused how that works
Let me think... The value of a string part inside a template is that string, right?
{{ 'this is a string' }} would become this is a string
the template will output this:
//config/videos/pics/{{ entity_id.entity_id|replace('camera.','')}}_20240802_090000.jpg
so if we apply some computational theory and assume an end-recursive evaluation loop, you could nest as many templates into each other as memory permits, so long as they all eventually evaluate to a string, the end result would be a string I think.
so it makes no sense how the template is evaluated a second time and where entity_id object comes from
templates are only resolved once
Oh that's easy, it seems to take the value of the entity_id stanza in the same statement.
no, what you're saying does not make sense
there's a second resolution that's occuring
and it's not clear where, nore is it clear where the namespace has the entity_id object added to it
As Benjamin Franklin put it: If your theory does not match ovservable reality, it's your theory that's at fault.
my man, I write code for templates
there's 2 resolutions occuring
if that works
and the base template engine only does 1
And I'm in computer sciences for 25 years now, so respect from one professional to another.
Well. technically now().strftime('%Y%m%d_%H%M%S') already is a term requiring to be evaluated before the template itself gets evaluated, so SOME sort or recursive evaluation MUST be taking place here.
"now it is {{ now().strftime('%H%M%S") }} o clock" is a valid, evaluable template string am I correct?
And so is {{ 'this is a string' }} right?
I'd have to dig out the old Abelson-Sussman to get the terminology correct, but then so must be {{ "now it is {{ now().strftime('%H%M%S") }} o clock" }} because it would be recursively evaluated
no, it doesn't recursively evaluate
it resolves exactly 2 times
once when the service is called prior to sending the data to the service call, and a second time inside the service itself
This is most likely the ONLY service in all of HA that behaves this way
Anyways, knowing how this works now, what's your question?
template ->
string containing template ->
string -|
template ->
function ->
string -|
<-string
<- string
<- string
|- string
At this point, it's mostly an academic discussion. RobC pointed out that this would only be relevant if I was iterating over multiple entities, but since I'm always using the same, the whole point of resolving the entity is moot.
And I've certainly understood that nested templates evaluating correctly isn't guaranteed and I should avoid it unless absolutely necessary.
there's no need to even use the double resolution
I believe ya. I've simplified that yaml significantly since then. And actually, since the blink integration I was planning on using is about as reliable as a chocolate teapot, I'll chuck the whole thing kit and kaboodle anyways.
Yeah, that's a simple template and you can just use the camera entity instead of doing the replace. What's posted there is just... no.
I still don't know what your issue is, there's nothing wrong with the template
Ok, consider this yaml then: https://dpaste.org/UbaOa
imagine for a moment you had the yaml I originally posted and wanted to move that template into a variable so you could re-use it in the way I did here.
you don't need to do that
It wouldn't work because it wouldn't have any entity_id to parse, right?
How to make THAT work, that was my original question I came here with.
But as I said, RobC convinced me that it was a moot point.
alias: Rekognition Kuechenterrasse
sequence:
- variable:
my_camera: camera.kuchenterrasse
my_name: "{{ my_camera.split('.')[-1] }}"
- service: blink.trigger_camera
data: {}
target:
entity_id: "{{ my_camera }}"
- delay:
hours: 0
minutes: 0
seconds: 25
milliseconds: 0
- variables:
timestamp: "{{now().strftime('%Y%m%d_%H%M%S')}}"
- service: camera.snapshot
data:
filename: /config/videos/pics/{{ my_name }}_{{ timestamp }}.jpg
target:
entity_id: "{{ my_camera }}"
- service: local_file.update_file_path
data:
entity_id: "{{ my_camera }}_file"
file_path: /config/videos/pics/{{ my_name }}_{{ timestamp }}.jpg
- service: image_processing.scan
target:
entity_id: image_processing.rekognition_kuechenterrasse_file
data: {}
description: ""
icon: mdi:camera-wireless
if you want to provide the camera as a variable to the script...
Never doubted you for a moment😉
alias: Rekognition
sequence:
- variables:
my_name: "{{ my_camera.split('.')[-1] }}"
- service: blink.trigger_camera
data: {}
target:
entity_id: "{{ my_camera }}"
- delay:
hours: 0
minutes: 0
seconds: 25
milliseconds: 0
- variables:
timestamp: "{{now().strftime('%Y%m%d_%H%M%S')}}"
- service: camera.snapshot
data:
filename: /config/videos/pics/{{ my_name }}_{{ timestamp }}.jpg
target:
entity_id: "{{ my_camera }}"
- service: local_file.update_file_path
data:
entity_id: "{{ my_camera }}_file"
file_path: /config/videos/pics/{{ my_name }}_{{ timestamp }}.jpg
- service: image_processing.scan
target:
entity_id: image_processing.rekognition_{{ my_name }}_file
data: {}
description: ""
icon: mdi:camera-wireless
Thanks, I'll put that in my library folder for future reference.
But odds are if I get proper cameras instead of those useless pieces of junk, I won't have to jump through hoops to obtain a simple snapshot anyways...
That's the whole point of that script. To beg a simple snapshot off the blink camera so I have something to feed the image recongniton. It's absolutely ridiculous.
But I'm a bone-headed ass who won't give up until somebody hits him in the face with a clue-bat.
all of this "jumping through hoops" is normal for all cameras in HA
it's not unique to blink
Thanks for the warning.
the camera snapshot service is provided by the base camera class
But I assume in most other cases, it actually works reliably if you jump the hoops in the proper way?
Not sure what you mean?
I think that only applies to battery cameras though. With my POE cameras, I can call the snapshot service directly with no other service calls needed.
You see, last night that very script worked reliably seventeen times in a row when I tested it. Since then, no matter what I do, it will always return a snapshot from some time last night.
is the file updating? If the file is updating but the snapshot is old, then it's the camera
if the file is remaining the same name/time, it's your automation
I've got teethered blink cameras as well, and they don't perform an iota better. The issue is that blink cameras aren't really cameras but cloud devices intended to be used with the blink app and no other way.
It's creating fresh files, but the content is identical
that would be the camera then
I assume so.
I'm surprised it worked at all, because usually the blink cameras are very prone to shooting back a "busy, come back later" if you try to do anything with them in quicksequence.
That's true even when used the official way.
Very annoying if you get a motion alert and want to jump in to live view to see what's going on, and your camera tells you "go away I'm busy recording a clip"
It's just shit engineering is what it is.
@ocean tusk I converted your message into a file since it's above 15 lines :+1:
Need some help to trigger an offset time on a blueprint
you might have to ask in #blueprints-archived . From a non-blueprint perspective the only way I know how to trigger on a time offset is to use a template trigger: {{ my_datetime_object + timedelta(seconds=600) < now() }}
I asked there and they sent me here 🤷♂️
Well if all you needed was a template that gives you a time offset, then what I wrote should be what you need.
@ocean tusk I have a blueprint on the Blueprint Exchange you may be able to use as reference... https://community.home-assistant.io/t/time-trigger-with-offset/713826
Thank you i saw it but i need to set duration and i want it to trigger it a couple of times
If there is no other way i will go wit that with many duration helpers
But i have it in automations dont know why i cannot transfer it to a blueprint
You're second trigger is going to have to be a Template trigger:
platform: template
value_template: "{{now() >= today_at(var_hora) + timedelta(seconds=600)}}"
I tried something similar and didnt work, let me try this, thanks
I'm working on a voice command that will get the condition/temperature of a forecast service call at a specific time (eg What will the weather be like at 5:00 PM?) . I already have this from a different automation that converts the time to date time :
{{strptime(today_at().date() ~ ' ' ~ trigger.slots.time, '%Y-%m-%d %I:%M %p')}}
which produces something like this:
2024-08-02 17:00:00
Do I need the value in the response variable to match exactly? How do I go about finding the matching date time in the data?
Here's what the response looks like (edited)
weather.kagc:
forecast:
- detailed_description: ""
datetime: "2024-08-02T14:00:00-04:00"
condition: partlycloudy
temperature: 80
- detailed_description: ""
datetime: "2024-08-02T15:00:00-04:00"
condition: lightning-rainy
temperature: 82
I know that this will give me the value for the first element, but how do I iterate and check through the list and does the format I have above need to be modifed to match?
forecast['weather.kagc'].forecast[0].datetime
{% set x = (strptime(today_at().date() ~ ' ' ~ trigger.slots.time, '%Y-%m-%d %I:%M %p')|as_local).isoformat() %}
{% set selected = forecast['weather.kagc'].forecast | selectattr('datetime', 'eq', x) | first %}
.....
What are you trying to do with the values from the list item?
Not working...
Oh it worked
But i did 10 second to try and it took 1 min
So its not checking seconds but is perfect for what i need thanks
The use of now() causes it to throttle to only render the template once a minute... which is why I have so many caveats in the description in my blueprint.
Wich one is it? Wold love to check it
Ohh sorry
Lol
Thanks for the help
I want to use them in a response. So if I say "What will the weather be like at 3:00 PM" it will return "It will be 82 and rainy". So I would need to be able to pull the condition and temperature attribute for the matching datetime
From what I see, I should just be able to pull those values from selected assuming that will provide the dictionary values. I will give this a test soon. Thank you for sharing that code!
{% set x = (strptime(today_at().date() ~ ' ' ~ trigger.slots.time, '%Y-%m-%d %I:%M %p')|as_local).isoformat() %}
{% set selected = forecast['weather.kagc'].forecast | selectattr('datetime', 'eq', x) | first %}
It will be {{selected['temperature']}} and {{selected['condition']}}
Thank you!
So this is my first template/binary_sensor, it doesnt appear to be showing up anywhere - not in dev tools or entities, what am i missing? i reloaded my conf and restarted several times already, the template is working in the template dev tool.
I put this in my configuration.yaml:
template:
- binary_sensor:
- name: Washing Machine Status
unique_id: washing_machine_status
state: >
{{states('sensor.washing_machine_outlet_power')|float > 1.0 }}
I'm looking to show icon based on which input_boolean is currently only turned on. Also, I want to pull the icon from the entity, rather than having to manually defining the mdi icon.
How do I go abouts doing this? thanks
{% else %}
{% if is_state("input_boolean.away_mode", "on") %} mdi:away
{% endif %}
Did you reboot HA after adding it to your config file? I bet you think I can read, right? lol
Do you have any other sections that are labelled "template:" including secondary files that you are importing or something
There are a couple of ways of doing this - if you are literally just looking to display an icon then you could just do it with conditional lovelace cards...
That said, is there a reason why you have home and away as 2 different booleans? is there ever a time when you want it to be both home and away or both not home and not away? If not it would make sense to redefine away as input_boolean.home_mode = false
{{ iif(is_state("input_boolean.home_mode", "on"), "mdi:home", "mdi:away") }}
I don't see anything wrong with it, you're sure you don't have another template: section in your configuration.yaml?
I'd like to add multiple input booleans icons, and pull the icon from their entity rather then define one manually
You just want to see the world burn 😉
{% if is_state('input_boolean.home_mode', 'on') %}
{{ state_attr('input_boolean.home_mode', 'icon') }}
{% elif is_state('input_boolean.away_mode', 'on') %}
{{ state_attr('input_boolean.away_mode', 'icon') }}
{% elif is_state('input_boolean.another_one', 'on') %}
{{ state_attr('input_boolean.another_one', 'icon') }}
{% endif %}
Thanks, but that still doesn't pull the icon from the entity, isn't there a way to do so?
So basically, use the icon of the input_boolean
Brilliant, thank you as always 😀
Anytime 🙂 Just know that you'll probably want to add a |default('mdi:<something>') to the state_attr calls in case you forget to add an icon as it will return None otherwise.
Alternative
{% set booleans = [
'input_boolean.home_mode',
'input_boolean.away_mode',
'input_boolean.another_one'
] %}
{{ booleans | select('is_state', 'on') | map('state_attr', 'icon') | first | default('mdi:whatever', true) }}
You need to add true to the default filter if you want to have it applied to none (or other falsely input)
Like | default('mdi:something', true)
Yup. I forgot to add the , true to it.
Thank you both
Just trying this and getting this error:
Error: UndefinedError: No first item, sequence was empty.
What is the best way to troubleshoot?
Well it says you're trying to get first on an empty list
so just look at your list and work backwards
Right. I'm looking at traces and don't see any changed variables. I guess I could just do some returns on the variables as conversation responses.
Oh sure. I just need to get the response variable in and I can do that. thanks
pffft. Easy fix. I hadn't changed to the hourly forecast so the data was not correct to parse. Sorry for the bother. Still early here 🙂
How do i make a custom notify action that executes a existing notify action + some other service (mainly a rest_command)
and also how am i supposed to delete the following group if it doesnt have a delete button? https://i.vgy.me/oNIjzP.png
Delete is usually in the entity properties, not group options
One option for your other question is to use a notify group containing your existing notify service along w/ a restful notification
A script.
How did you create the group?
ui
Hello all, I am trying to create a sensor with the following code
- name: Co Charger Power state: > {% if (states('sensor.solax_local_load_power')|float > 7200) and (is_state('binary_sensor.bluey_charger_plug', 'off')) %} 7200 {% else %} 0 {% endif %} unit_of_measurement: W
whoever im getting the followig error:
Invalid config for 'template' at templates.yaml, line 553: 'name' is an invalid option for 'template', check: name Invalid config for 'template' at templates.yaml, line 554: 'state' is an invalid option for 'template', check: state Invalid config for 'template' at templates.yaml, line 561: 'unit_of_measurement' is an invalid option for 'template', check: unit_of_measurement Invalid config for 'template' at templates.yaml, line 562: 'device_class' is an invalid option for 'template', check: device_class
Invalid config for 'template' at templates.yaml, line 552: 'name' is an invalid option for 'template', check: name Invalid config for 'template' at templates.yaml, line 553: 'state' is an invalid option for 'template', check: state Invalid config for 'template' at templates.yaml, line 560: 'unit_of_measurement' is an invalid option for 'template', check: unit_of_measurement
not sure what to do here
Where (what file) did you put that code, and what heading is above (indented less than) that code
template.yaml
and the config is referring to the file (have other sensors there and working)
- sensor:
right at the top
the - name is the 1st indentation after - sensor:
The top heading needs to be template:
You probably have a bunch of sensors in that file, and this is your first entity on the template platform. All your other sensors probably need to get moved to sensor.yaml
all the other ones are working (have been working)
wait let me show you the config reference
template: !include templates.yaml
They are either other types of sensors, or they are the old format template sensors
the file has a template: at the top, right at the config
template: doesn't belong in that file
Shouldn't the config.yaml have a
template: !include templates.yaml
?
My knowledge is very very basic
Yes. I thought you were implying that you had template; at the top of templates.yaml with #templates-archived message
No no, at the top of templates.yaml there's
- sensor:
Your posts are hard to read without formatting...
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
Sorry 😐
To recap, in configuration.yaml you should have:
template: !include templates.yaml
In your templates.yaml file it should start with
- sensor:
Then your code should be
- name: blah
state: >
{{ blah }}
I think I have all of those until we get here
The error message is telling you those configurations are being applied to template: and not to sensor:
Check your indenting
No problem
Hello. I'm trying to get the minimum a sensor has read in the last 10 minutes... I thought this was working before, but it no longer is. Am I doing this correctly?
- platform: statistics
name: "Humidity last 10 minutes"
entity_id: sensor.h5101_6f54_humidity
state_characteristic: value_min
max_age:
minutes: 10
When I look at the history of the humidity sensor, the lowest it has been in the last 24 hours is 43.8! However, my sensor has a reading of 36.4 and says it hasn't been updated in 16 hours??!!
Ok, well, I restarted HA and it updated.. So, I'm not sure what happened. But maybe it'll work now...
@undone spruce I converted your message into a file since it's above 15 lines :+1:
I have a bit of a complicated setup I'm trying to fix and actually make work properly. I have a Utility Meter helper that collects energy_spent which is fined as a template. This is then used in another template as energy_spent_daily. The final templates are here:
https://gist.github.com/spiceywasabi/743253436f7ef97c7499e230ce19f64d
Now these do all generate data however when I try to use Calculated Home Daily Combined Consumption or Energy Spent Daily in the Energy tab it says that its the wrong units/type. How do I fix this and are there things I can do to simplify this template configuration?
(Could a mod remove the converted post by the bot since its really unreadable Thanks.).
Hello, anyone know if my weather service is normal ?
https://pasteboard.co/d4Ee5hZChnKZ.png
I don't understand why the first and second forecast are the same day, and why some value are null for the first forecast.
This break my template and card
Maybe it's normal but I don't understand why
First step would be to fix unit_of_measurement and device_class. Keep in mind the dashboard is for energy and not power. Power would be units of kW or W and is how fast energy is consumed. Energy would be units of kWh and that is what you are charged for.
If you have a sensor that measures consumption, it should probably be state_class: energy and unit_of_measurement: kWh
You also have a lot of indentation problems in that code. Hopefully that was a copy/paste issue.
Hello! I'm new to templates -- trying to essentially add two voltage numbers together, and then take total W consumed at the house, divide by voltage, and come up with a rough guess for amperage - trying to make sure I can start to set some alerts and automations if we approach maximum consumption for the panel.
I'm trying the following template code, but the preview keeps coming up with Unavailable.
{% set voltage = ((value('sensor.phase_a_voltage') | float) + (value('sensor.phase_b_voltage') | float)) %}
{{ ((value('sensor.total_power') | float) / voltage) }}
I'm brand new ... so not entirely sure what it is I'm doing here. Any help would be super appreciated!
There is no such function called value(). You want states().
You’ll want to bookmark this page and refer to it often: https://www.home-assistant.io/docs/configuration/templating/
oh duh. I had tried value() when states() didn't work -- totally forgot to change it back.
perfect - that worked. I have the templating page open ... just forgot to set it back. It's working now - back into the rabbit hole I go.
Sounds good. Also make use of the template tool in Developer tools-> template. And start with small bits of code and add to it as you validate each piece
Not related to templates, but from an electrical standpoint I don’t see how adding voltages from two phases makes any sense
Phase A is at 110, Phase B is at 115.. trying to understand total voltage across both phases divide by consumption. Total panel is (sadly) 100A, so trying to make sure we don't flirt with that.
The Emporia Vue (esphome) doesn't provide a total amperage value.
Are you using the Vue utility connect (reads meter info over Zigbee) or the Vue that has current clamps?
Regardless, if the only info you have is voltage from each phase, and total power, then you’d have to assume equal power from each phase and you’d take the average of the two phase voltages
Or take power/2 and calculate amperage on each phase separately and then add the two together. Mathematically it’s the same result but it might be easier to follow logically.
I thought the usage of the energy meter would convert active (kW/W) to kWh? Thats why I go through the template to the utilty helper and back to a template. Is there a way to cut out this middleman because it doesn't seem to be helping. Or I guess my real question is how can I convert in template form from active usage (W/kW) to kWh?
That's an interesting idea - might be more "true" too. I'll give that a whirl next.
Using the one with the current clamps.
You can do this using the riemann sum integration calculation https://www.home-assistant.io/integrations/integration/ AFAIK utility meter does not offer the conversion (or at least I can't find how)
Hello, one of my integration has 1 entity but a lot of sensor.
Any idea how I can merge everything and have one sensor + multiple attribute ?
Those are all entities
As expected
but on card they always expect one entities so I m a bit lost
What are you actually trying to do?
I m trying to display a card if the machine is on and display the remaining duration
You can either use two cards or create an additional template sensor
I guess I need a template sensor because I have all the value I need but none in the format I need
ok something like this:
Any idea how to hardcode program time ? Should I use helper to do that or can I do it directly in the template
Do anyone know how I can get the value in the energy dashboard for the self consumed solar energy ?
agree with snighere that Riemann sum is the right way to do this. If you want to keep down the path of using the history_stats sensor to calculate HVAC duration in hours, and then multiply it by an assumed power of 4.232kW, then your template sensor is doing the calculation and your units of measurement in that sensor should be kWh and not kW that you currently have specified. Whatever you specify is what HA is going to use, it isn't smart enough to do unit conversion and override what you incorrectly specified.
In your "home daily combined consumption" sensor you should be adding two sensors that are each already in units of kWh and therefore the units of this sensor should also be kWh and the device_class should be energy instead of power.
You mention a utility helper, but I don't see anywhere in your code that you define a utility meter entity.
Another comment about your code is you only need the first entry of - sensor: underneath the template: heading. I don't think repeating it hurts, but it's not necessary.
For program time, you are better off calculating the ending datetime instead of updating this sensor attribute every minute for no purpose other than to subtract off a minute.
Unrelated, but you can make this a binary_sensor instead of a sensor, and your state simply becomes {{ not is_state('sensor.lave_vaisselle_operation_state', 'Ready') }}. That will also give you an icon that updates with a check mark when on and and empty circle when off (see binary_sensor device classes here if you want to specify something other than the default, which is shown in the chart as 'None')
try in #energy-archived . You'll need an entity that contains that value, and they can help with that.
I will ask them
You are right I ll do some change and do the calculation in the lovelace
If the entity itself is a datetime (device_class: timestamp) then lovelace will do the calculations by default and simply show the time remaining. If it's an attribute then I'm not sure if this is done automatically or if you have to write some code in your dashboard. If you need help with it the kind people in #frontend-archived can help
I m thinking, the ending datetime should be calculated too, because I don't have this value anywhere.
Sorry if this seems stupid, trying to use a bubble card to send a wake on lan packet to wake a windows machine and using hass agent to shut it off. I can't get my config file quite right.
type: custom:bubble-card
card_type: button
button_type: switch
switches:
name: Yggdrasil
turn_on:
- service: wake_on_lan.send_magic_packet
data:
mac: xx:xx:xx:xx:xx:xx
turn_off:
service: button.press
target:
entity: button.yggdrasil_yggdrasil_shutdown```
@somber basin To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
looks like you're mixing card config and a template switch
Oh man, you're mixing a card config, legacy template yaml and modern template yaml
nice, was trying to get them all in one. I'm not too familiar with config files.
You can't do that, you have to make a separate config for each.
each being, your card and your template entity
Ok thank you. I knew I'd messed up in the yaml file, just couldn't find any examples on how other people have done it, which I usually do
How do I find out the aliases to an area given an area_id?
area_name
That seems to give the name, not the aliases
What do you mean “alias”
You can add aliases to an area in Settings -> Area -> Update area -> Aliases
"Aliases are alternative names used in voice assistants to refer to this area."
You can by looking at the area details in the GUI, but not using a template
ugh, but how does voice assistant get these?
By using Python functions built in HA. A template function could probably be built for it, but so far nobody did
Why would you need to have them listed?
To pass them into extended openai conversation because gpt4o-mini is too dumb to infer the area names lol. I am sticking to 3.5-turbo because of this, but otherwise 4o-mini seems to be better at following instructions and also faster
@somber basin I converted your message into a file since it's above 15 lines :+1:
how do you get multiple switches working in configuration.yaml?
As I have some running with template platform and some with wol but can't seem to get them both working. Also the power state on hass.agent doesn't seem to update correctly for me
Any idea why my Weather: Get forecasts srvice return null for the temperature during the night ?
how can I fix that :/
If I check hourly I have the temperature
Using this template, is it possible to bypass the daily value if null / unknow and use the hourly value ?
I got the same issue yesterday and the template was fine during the day
You need to put them all under the same switch key, sounds like you are repeating the key in different parts of your configuration
when I did that I couldn't have multiple platforms.
Not sure what you mean with that
well I had
- platform: template
switch1:
- platform: wake_on_lan
switch2:```
minus the awful indexing
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
Well, that should work fine
ill give it a go again then
Where exactly do you have that problem?
https://pasteboard.co/zMqNiHGc65F3.png
in the daily forecast weather service
temperature and wind bearing time are null every night but are ok the morning
Hey guys,
I'm trying to send myself a notification about the amount of rain of the current day, everyday at 11:59pm. I'm stuck with how to extract the amount of rain from the sensor and put that into a variable. I have this code:
service: notify.mobile_app_pixel_7a
data:
message: >-
{% set SENSOR =
'sensor.gw2000a_daily_rain_rate_piezo' -%}
{{ 'Warnung: test'+SENSOR.state|string }}
but this will only show "warning: test" and nothing more. I'm really lost, looking for the answer to this simple question 😦
{% set SENSOR = states('sensor.gw2000a_daily_rain_rate_piezo') -%}
{{ 'Warnung: test' ~ SENSOR }}
All states are strings by default. Use ~ for concatenation in jinja templates.
ah, ok
There, that's a bit better.
If I add it:
- service: weather.get_forecasts
target:
entity_id: weather.home
data:
type: hourly
response_variable: hourly
Do you think I can fix by doing something like that (this code doesn't work)
temperature: >
{% set temp = daily['weather.home'].forecast[0].temperature if daily['weather.home'] is not none else hourly['weather.home'].forecast[0].temperature %}
{{ temp }}
switches:
yggdrasil:
friendly_name: "Yggdrasil"
value_template: "{{ is_state('sensor.yggdrasil_monitorpowerstate', 'PowerOn') }}"
turn_on:
service: wake_on_lan.send_magic_packet
data:
mac: ""
turn_off:
service: button.press
target:
entity_id: button.yggdrasil_yggdrasil_shutdown```
My power state doesn't update from hass.agent still. Everything else works
you're mixing up daily and hourly
@half fable To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
I know but daily is not working the last hours of the day
oh sry didn't read the template to the end
I m thinking mixing both, anyway I want to use the hourly service for a detailled view
But I don't know how to achieve that
It just gives an unknown. I have the monitor powerstate on in sensors config
so you are saying daily['weather.home'].forecast[0].temperature is working during daytime, but not during the night? That seems strange.. Which weather integration are you using?
Royal Meteorological Institute of Belgium
oh, I just removed that one today
https://pasteboard.co/IL1b9NiXN3zf.png you can spot the missing temperature in the entitie
Any idea why this is throwing an error? Can I not define variables outside of the service?
{% set RAINTITLE = "Regenmelder" -%}
service: notify.mobile_app_pixel_7a
data:
title: test
message: RAINMESSAGE
No. That's not valid at all.
Did you manage to find a better forecast ?
You'd have to do this:
- variables:
RAINTITLE: "Regenmelder"
- service: notify.mobile_app_pixel_7a
data:
title: test
message: "{{ RAINMESSAGE }}"
ohhh, ok
Ah, I see, it is actually null
temperature: null
templow: 16
wind_gust_speed: 10
wind_speed: 7
yes for 2 values
but it exists, so basically you can just do:
{{ daily['weather.home'].forecast[0].temperature or hourly['weather.home'].forecast[0].temperature }}
I ll try, didn't know how to write that 😉
That will use daily unless the result is faslely, in that case it will use the hourly one
doesn't work probably because of the float for this attribute:
{% set T = (daily['weather.home'].forecast[0].temperature or hourly['weather.home'].forecast[0].temperature | float) %}
is there another way to write that ?
{% set T = (daily['weather.home'].forecast[0].temperature or hourly['weather.home'].forecast[0].temperature) | float(0.00) %}
doesn't work :/ sadly I can't use the template tester with action in the template
it will already be a float
Huh, I thought it would come through as a string like states(). Anyhow...
{% set T = daily['weather.home'].forecast[0].temperature or hourly['weather.home'].forecast[0].temperature %}
no, only entity states are string by definition. Attributes or service response variables can be any type
Got it. So all my casts can be dropped 😉 lol
well, it depends a bit on the integration, it could be that it's still a string. But in this case you can see that it's a float in the service response
well, actually an integer 🙂
it's not the best weather integration I know of, not very precise with all values being integers, and that precipitation_probability being null instead of 0 is also a bit annoying
Ah, gotcha... ok, so it's not a broad "this is how it is" then, but by integration/service response?
oh it work
I tought reloadeding the yaml was enough xD
I had to restart HA completly
in most cases a number will actually be a number, datetimes are even more annoying, some use a string, some a datetime object, and you can't see that in the yaml representation
so the float cast is needed ? I had it removed but I don't think it was the issue
it's not needed
and trigger based template sensors only update when triggered
so YAML reload won't work
Once again you saved me and I ll be able to sleep not too late 😉
a restart worked in this case because that is one of your triggers
you could also add an event trigger using a custom event, so you can trigger it by sending that event
I thnked it was only the first time and after it was ok because once I got the value updated. But I was probably luck with the hourly reload
oh I think I kow where it can be done
I'm trying to play around with the inbuilt noaa_tides integration, and I wanted to build some template sensors off of it... In the jinja2 developer panel, I tried this simple template to display the sensor state:
tide info: {{ states('sensor.tides') }}
And what comes out is: tide info: unknown.
In my states panel, I do see a state that looks like Low tide at 9:16 PM. I'm kind of feeling stupid here; other sensors are returning states, but this one is not.
Can you show a screenshot of what you see in states panel
https://imgur.com/a/b1iqLxi @lofty mason
can you also show a screenshot from the template editor, showing the template and the result?
https://imgur.com/a/o6f1sMm @marble jackal
@lofty mason @marble jackal it's werid right?
Hah. Ok. Weird… maybe I should restart, when in doubt…
a restart fixed it... ooooooooooK lol
{% set input_cameras = "{'front':'camera.front_camera','doorbell':'camera.mydoorbellcamera'}" %}
{% set cameras = (input_cameras | from_json) %}
This gives me this error:
JSONDecodeError: unexpected character: line 1 column 2 (char 1)
Where am I going wrong? I am wanting the user to be able to enter the dictionary in a blueprint and then I am wanting to take it from a string and make it into something that can be used in the automation.
I suspect that you need to flip your quotes. Proper JSON uses " for its strings
dang it. I think I've been through this before. let me check
{% set input_cameras = '{"front":"camera.front_camera","doorbell":"camera.mydoorbellcamera"}' %}
{% set cameras = (input_cameras | from_json) %}
{{ cameras }}
``` ->
{
"front": "camera.front_camera",
"doorbell": "camera.mydoorbellcamera"
}
Anyone have an example of a template sensor that uses power metering to determine if the object pulling the power is using more or less than normal watts/amps? Looking for a means to trigger an automation based on if the average overall normal current being drawn ever jumps or just climbs in general
I'm trying to capture a value of an entity only once at startup, so I created a trigger on homeassistant start. However, the entity return "unavailable" and I think that is because the device which this entity is being read is not available yet. Is there a trigger I can use when homeassistant starts and when the entity becomes available for the first time?
trigger on the home assistant start event, and then add a wait template as first step of the automation
wait_template: "{{ not is_state('your.entity', 'unavailable') }}"
I'm finding a lot of examples for creating automations, but not so many about template-trigger-sensor. Is using automations the common way to update entity values?
Thanks. I'm still trying to figure out how to plug this into a template-sensor (with trigger) configuration. I google a bit, but not finding any clear examples with template sensors.
It's probably me that haven't connected all the dots yet
I have a group numeric sensor helper. how can i reference it's value in a template?
Using states(“<your entity id>”)
can i show it with no decimals?
Yup, with the | int(0) filter you can.
Hey. trying to fix a broken template sensor.
wind_direction:
value_template: >
{% set direction = ['N','NNE','NE','ENE','E','ESE','SE','SSE','S','SSW','SW','WSW','W','WNW','NW','NNW','N'] %}
{% set degree = states('sensor.openweathermap_wind_bearing')|float %}
{{ direction[((degree+11.25)/22.5)|int] }}
no longer using open weather map
now using pirate weather.
the new sensor needs to read an atribute ( wind_bearing: 39 ) of weather.home_pirate_weather
Middle line would be {% set degree = state_attr('weather.home_pirate_weather','wind_bearing')|float %}
beauty... thanks.
Im currently trying to get a RESTful sensor to work. Turned on debug logging. however, the sensor state is unknown all the time.
Here is the debug log and the value_template
2024-08-07 11:52:32.124 DEBUG (MainThread) [homeassistant.components.rest] Finished fetching rest data data in 0.081 seconds (success: True)
2024-08-07 11:52:32.125 DEBUG (MainThread) [homeassistant.components.rest.data] Data fetched from resource: { "realtime" : [
{
"text":"2024-08-07 11:58:55 Lägenhetsdörr 155, summer aktiv"},
{
"text":"2024-08-07 11:58:55 DAC/Dörr 1 ändrad"},
]}```
So it must be something with this: value_template: "{{ value_json['realtime'][0]['text'] }}" that isn't correctly done right?
I want to fetch the text "2024-08-07 11:58:55 Lägenhetsdörr 155, summer aktiv" and then write it into sensor state so I could make use of it in a event.
What's the config of your rest sensor?
@marble jackal ```rest:
- resource: http://192.168.1.166/cgi-bin/cgi.cgi?action=12
username: xxxxxx
password: xxxxxx
authentication: basic
scan_interval: 1
sensor:- name: "Kortläsarlogg"
value_template: "{{ value_json['realtime'][0]['text'] }}"
unique_id: "sensor.door.cardreader.eventlog"```
- name: "Kortläsarlogg"
the log may be empty at times, but if it cannot parse the whole JSON it should not update the sensor right?
A empty log looks like this:
{ "realtime" : [ ] }
Tested the value_template in the template builder and it seems to work too
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
Updated the messages now with right formatting. The strange thing is that, I do understand that the empty log message may result in a "unknown" state for the sensor, the right messages should be shown in the sensor event log right?
You should guard for that incorrect input
Something like this:
{% set data = value_json['realtime'] %}
{{ data[0]['text'] if data else 'unknown' }}
Or this
{{ (value_json['realtime'] | first | default({})).get('text', 'unknown') }}
@marble jackal If possible, I would want to ignore empty logs completely, and just retain the latest message it was set to, ergo not update the sensor at all if a empty log line was received
There must be a way to, like treat the sensor as no update was received kind of
Still unknown in the homeassistant interface even tough adding that guard
Hello! I use a smart plug with power metering on my 3d printers. Based on their W consumption I know if ['ready', 'printing', 'completed', 'off'].
The completed happens when its previous state was printing. If I had to create an automation that would be simple, but I'm trying to create a sensor.
Can somebody please help me?
https://pastebin.com/qYYLT91V
You did reload rest entities after applying the change right?
Use this.state to check on the current state of the sensor at the moment the template is rendered. If this.state == 'printing' and the power consumption is within your thresholds, you know the new state should be completed
Thanks, will try!
@marble jackal TheFes: Yes, did a compelete hass restart
So probably this. The template in developer tools doesn't print errors so I assume it's correct. Currently testing it
{% elif
states('sensor.tasmota_133_energy_power') |int >= 20 and
states('sensor.tasmota_133_energy_power') |int < 35 and
states(this.state) == 'printing' %}
Not states(this.state) that will return unknown
Just this.state
Your whole if-statement is more complex than required BTW
But I'm currently on mobile, so I can't easily correct it
gotcha. updated! Well yes there's also a off too much which I just removed. Are you referring to ternary operators or similar ways to improve the code? Probably! I generally don't use them because I luckily don't have to think about lines of code or memory constraints 😐
There is no need to check on two power values in each part on your if statement, eg, you already know it's above 20 because otherwise a previous statement would have been true. So there is no need to check on that again
I suspect the restful sensor somehow does not like a string value.
Found out now. The restful sensor returns the correct CURRENT value, but in the log, all string values seem to resolve to "Unknown". So basically, I need to completely ignore empty values, and just retain the last log line if the empty log is returned
Did you give it a device class or only of measurement?
Neither of
tested with: value_template: "{{ (value_json['realtime'] | first | default({})).get('text', 'SEBBE TEST') }}" and it works, the sensor's value is set to "SEBBE TEST". But as the history shows "Unknown", I need to just retain the last log line if a empty line is sent from card reader
oof, you may flood the event bus if you have a slow system with a 1 second scan_interval
Petro: The action=12 only returns the events from the last second, thats why I need such a low scan_interval. Looked in the log and it looks fine
make a separate script that passes the info to HA
so basically, I want to do: value_template: "{{ (value_json['realtime'] | first | default({})).get('text', last_sensor_value ) }}" kind of. But how I do "last_sensor_value"?
Petro: It shouldn't flood the sensor bus if the sensor is unchanged right?
You'll be flooding the main loop of HA
not just your sensor
it may not be a problem, but if you have an active HA, it can slow it down
I tried to use the full event log, returning the events for the last minute instead, but that script instead crashes the access controller so it reboots
you made this script?
and by script I mean, this is separate from HA as in a python or some other language script?
no, the access controller have 2 methods of getting events: action=12 returns the events for the last 1000 milliseconds, or action=17 where I can specify starttime=<UNIX> and endtime=<UNIX> to get events from a longer period
hitting action=17 too often crashes the access controller
but action=12 seems to be fine to spam
So are you just using HA and nothing in between?
yep correct, im talking directly to access controller
i.e. HA (Rest) <-> Device
ok, I suggest you make a script using python or some other language that just always runs on the OS
that script watches the rest endpoint, and then creates a webhook
then you make a template sensor from the webhook trigger
otherwise, if you go down this route, you'll need your rest endpoint with the low scan interval that could flood your event loop. And on top of it, you'll likely need a template sensor to ensure you only have the latest value.
Also, HA has a rest api, so if your device has the ability to send to an endpoint, that's also an option
So a event is fired even if a sensor changes value from "THIS DATA" to "THIS DATA"?
No
then it shouldn't fire anything in the event loop
as long as a new log line isn't printed
I know, it runs the actual HTTP GET action
whether that action creates a state change is a moot point
and that's what's flooding the event loop 😉
aha now I understand, I tought the "event loop" was the thing collecting state changes and firint the events
it could not be a problem, but if you are running on a rpi or something else that's crappy hardware, it will slow you down significantly
it does all of that, on top of running everything else
rpi zero 2w lol... but seems it might be ok. Else I need to find a REST <--> MQTT client instead
and the rest integration does not create a dedicated thread
you're running ha on a rpi zero 2w???
yep
I hope all you're doing is the rest sensor...
the rest sensor and some MQTT
that's defiitely going to run into issues if you have a ton of MQTT updates on top of the 1 second scan_interval
are you just running HA Core?
(hopefully)
if you are, then you're probably gonna be fine but I'd probably still consider creating a python script that handles all the rest stuff. You can hammer the endpoint too with a separate script.
yep just HAcore
Do you know python?
no, but I know perl and other script languages. Im thinking of finding some HTTP endpoint <--> MQTT client and then have that MQTT client push the update into hass when it detects a new log line
Yeah thats a good path too
if you go that path, you can do an MQTT trigger. But I'd try to make your script not send empty data to the MQTT topic
so then all you need is a simple sensor in HA
yeah thats the idea basically, only send a MQTT message when it actually detects a log line.
right
but trying to find some good software that could do it
I'd just write a script in perl if you know perl
I'm sure there has to be examples out there
"perl get info from rest", "perl send info to MQTT topic"
then a while loop that checks the rest endpoint every x ms, and if the data has a value, post to mqtt topic
super lightweight script
and it'll make HA do what it should be doing, automating
without forcing HA to do the polling
not only will you get faster response time, you'll have 2 lightweight softwares instead of 1 bus that's potentially flooded on a low spec system
anyways, that's just my 2c
should try that. Im trying to just use as little software as possible, as I prefer a integrated monolithic block
I get it
typically, small scripts like that rarely need any changes or maitenence
I wouldn't be surprised if you could do all of that with a cron job either
Not sure how to do that. I imagined that using a range of values for each state was enough. 1-20, 20-35, 35-up. I'm also not sure the this.state the way I wrote it before works because I did not notice any change in templates-> dev_tools when the state changed (I search in the forum for other people using this.state but couldn't figure it out how to use it)
edit: tested by manually updating the sensor value and 'this' is undefined is what I get in the template of dev_tools
this wouldn't be available in the template editor. The only way to test this would be to tweak the sensor definition and then manually adjust the state in dev tools > states.
value_template: >
{% set power = states('sensor.tasmota_133_energy_power') | int(0) %}
{% if power >= 35 %}
printing
{% elif power > 20 and this.state == 'printing' %}
completed
{% elif power > 0 %}
ready
{% else %}
off
{% endif %}
you can test this in devtools > template if you add this at the top
{% set this = dict(state = 'printing') %}
oh wow! thanks a lot will test asap!
I see! thx!
testing it now. from ready to printing and back to complete works great! I basically update the value of the tasmota sensor manually. When the sensor goes back to > 0 after it hit the complete condition, it remains in complete. now it's at 14 and it's not ready
update: it just updated and it's ready. I guess this 100% works. Can't thank you enough for providing this code!
Is there a way to move template sensors from yaml to the UI without losing their history, if I were to give them the same names ?
History stays with the entity id. Delete the sensor, add new sensor, rename to old entity id, should keep the history.
Thanks. This gets the meal scheduled for the current day (dinner) and displays it nicely- I'm more interested in showing ALL the meals that are available as just text-based links- the use case is I'm in the kitchen and want to make X for dinner- I use the kitchen screen and scroll through the list until I see it, click it, and the recipe pops up so I can cook it. Do you have any thoughts or suggestions on how to create that card/display?
I have the following code in a markdown card, but it leaves a large blank space at the top (I can't get an image to paste in discord for some reason):
<div>Recipes</div>
<table>
{% set recipes = state_attr('sensor.list_all_mealie_recipes','items')%}
{% for i in range(0, recipes | count ) %}
{% if recipes[i]['name'] %}
<tr>
<td>
[{{ recipes[i]['name'] }}](http://localhost:9925/g/home/r/{{ recipes[i]['slug'] }})
</td>
</tr>
{% endif %}
{% endfor %}
</table>
@split urchin make sure to manually delete the entity first after removing the YAML config and reloading template entities. Otherwise your new entity will be added with a _1 suffix, and you won't be able to rename it as the old entity_id is still in use.
There isn't an action in the integration to get all recipes, that would be a lot of data to handle. Mealie does this via paging in its UI which I don't think that would translate well to display in a HA card. As for the HTML, I've not tried something like that so can't help fix that.
Interesting! I'm surprised there hasn't been more (any?) demand for a use case like this, to me that's the usefulness of an integration such as this. In no way do I have the foresight to schedule out dinners more than 5 minutes in advance 🙂 I understand a thousand recipes would indeed be a lot to handle, but even in a scroll window or something, with just the names? (Apologies, I'm speaking to you as if you're the developer for this integration, no clue if you are or not!)
Your explanation does help me feel feel less crazy though, thank you for sharing that information
Would it be possible to add a search box or something, so I can pull the recipe up on the kitchen screen?
One quetion:
For this:
trigger:
- platform: state
entity_id: "{{ states.sensor | selectattr('object_id', 'match', 'uptimekuma_') | map(attribute='entity_id') | list }}"
i get this error
Message malformed: Entity {{ states.sensor | selectattr('object_id' is neither a valid entity ID nor a valid UUID for dictionary value @ data['entity_id']
Can anyone help me figure out why passing this to spotcast - it won't play?
playlist: |
{% set rand = range(1,100) | random %}
{% if rand < 30 %}
spotify:playlist:37i9dQZF1DWVvXA824aCbn
{% elif rand < 60 %}
spotify:album:3gmIxTApzfuuADskO9zFBB
{% elif rand < 100%}
spotify:playlist:37i9dQZF1E8FuFynUXCIfR
{% endif %}
I have a notification that sends to my phone of what {{ playlist }} is, and it looks correct
For both of you:
To format your text as code, enter three backticks on the first line, press Enter for a new line, paste your code, press Enter again for another new line, and lastly three more backticks.
```yaml
example: here
```
Don't forget you can edit your post rather than repeatedly posting the same thing.
You cannot use a template in a state trigger.
thank wrong symbol
There isn't a straightforward way to do what you want to do there
oh ok thanks
didnt want to list all manually
Yes, it can be done, but it's complicated. I suggest just listing them
ok, so I guess that also means you can't keep the history if you delete the entity first.
History is not deleted when you delete an entity
If I do the template directly on spotcast it plays as expected, only when it is passed in as a variable does it do nothing.....traces shows no errors
Why do completed?
You can just do
{{ [ 'uri1', 'uri2', 'uri3'] | random }}
Okay, they will all have the same chance then, instead of 0.3, 0.3 and 0.4
I suppose I didn't know this method lol
Hah, naturally this works - which breaks my brain since logically they're the same. Would love to know the disparity
Oop spoke too soon, I can unbreak my brain. The common failure seems to be passing these as a variable
What do you mean with passing it as a variable?
@restive socket I converted your message into a file since it's above 15 lines :+1:
skip_condition: true
variables:
playlist: |-
{{ ["spotify:playlist:37i9dQZF1DWVvXA824aCbn",
"spotify:album:3gmIxTApzfuuADskO9zFBB",
"spotify:playlist:37i9dQZF1E8FuFynUXCIfR"] | random }}
Ah, you can't use templates in a tap action
that is why I can see the entire block instead of one item
It will just pass the whole template as a string
what is the most elegant way to get around this limitation
and I say that because a script isnt elegant lol
Put it in a script and call the script
🤦♂️
lol
is there a way to determine what called a script from inside the script
As mentioned in the link I shared above
You can still pass variables
oh duh
variable passing is pretty new to me, as in I learned it yesterday. Told the wife......this - changes everything
You could pass the playlists as list, and then just perform the random filter in the automation (which probably should be a script anyway)
oooh you mean like playlist: [list,of,uri] and then in the automation do the random?
I kind of like that idea
data:
skip_condition: true
variables:
playlist:
- uri1
- uri2
- uri3
this assumes a known fixed length
I am one of the code owners for the integration though mainly worked on the shopping list elements and the sensor documentation. I've not seen anything else within HA that has a search box/deals with this volume of data, if those were available it would be possible, but that would be more of a common functionality not for this integration to implement.
No, not if you always choose one randomly. Using #templates-archived you could even check if the input is a list, and only apply the random filter then
bingo! there it is. Thank you @marble jackal - this is much better than a script 😄
I have a sensor that shows total water usage as m3, this value is always increasing. Now i want to make a daily water usage sensor. If i make a new sensor with the utility meter it shows the value as liter, which i want but it gives a error in the logs because the original sensor has the value as m3. Is there anyway to make just one sensor without first making a template sensor that calculates m3 to L? I know I can change the value of the default sensor to L but i want to keep this as m3.
Entity sensor.water_consumed_daily (<class 'homeassistant.components.utility_meter.sensor.UtilityMeterSensor'>) is using native unit of measurement 'L' which is not a valid unit for the device class ('current') it is using; expected one of ['A', 'mA']; Please update your configuration if your entity is manually configured
That error is telling you that you're using the wrong device_class
current is for electrical entities
which has a unit of measurement in Amps or milliamps
(A, mA)
so, change your device_class to be volume
Seems that this can’t be done from the UI?
Can’t share a screenshot but i don’t have that option in the mobile app.
Then it would need to be done in yaml if you set the entity up in yaml, otherwise it's coming from the integration and you'd have to override it with customize.yaml
This is the sensor, it shows device_class: water so no idea where the A/mA is coming from?
unit_of_measurement: m³
device_class: water
friendly_name: Water Consumed
your source sensor
That’s the source sensor…
It’s just the default consumed water sensor from slimmelezer+.
then it's the sensor you're trying to create
It’s just weird because I’m using the utility meter from the UI and just want to count the daily water usage.
it's not really weird, the device_class is current when it shouldn't be
Ok but it definitely shows water so where is the “current” coming from. 🙂
most likely the integration, which is why I said multiple messages ago that you'll have to override it in customize.yaml 😉
With the integration you mean utility meter from the UI or esphome where the sensor is coming from.
it seems like utility meter is the cause
I have this template sensor but it's complaining at boot that None has no element 1. What can I do? template: sensor: - name: Kaffesitater state: "{{ state_attr('sensor.kaffesitater', 'sitater')[1] }}" attributes: sitater: > {{ [ "Må kaffen din være sterk og mandagen kort."...]
how do i get auto complete when testing a template?
that looks like a fragment of a template definition, but you've created a self-referencing template. When the state is evaluated the attribute doesn't yet exist
Auto complete in what sense?
That isn't available. You can get autocomplete on entity ids, but that's about it.
lol it is or isn't?
Will that be a problem other than it complaining at boot? I actually would prefer state to be | random of an element in the attribute list but I couldn't figure out how.
Looks like | default (0) took care of the warning at least
|random should work fine to pick a random item from that list
{{ this.attributes.get('sitater', ['Nothing']) | random }}
or
{{ this.attributes.sitater | default(['Nothing']) | random }}
You could also use an input select for the list of texts, if you use a GUI one for that, you can easily add or remove them without having to adjust YAML
is there a way to set a var out of a for loop scope?
Nope.
I've been making use of input_text helpers. There's also a template on the forums that kinda helps too. Let see if I can find the link.
use namespace
whats input_text?
{% set ns = namespace(count=None) %}
{% for x in y %}
{% if x == 7 %}
{% set ns.count = 'foo' %}
{% endif %}
{% endfor %}
Aw crap... lmao... I swear I thought this was #automations-archived
Yeah... what petro posted... you want to use namespace. Derp.
your setting in a loop
and?, you can aslo set outside the loop
but thats out of the scope no?
please explain what you mean about scope
because I don't think you're using it correctly
@still geode I converted your message into a file since it's above 15 lines :+1:
namespace...
what is namescape and how would i use it in my case?
i literally just gave you an example
pardon my ignorance but im confused
{% set sensors = [
'sensor.',
'sensor.',
'sensor.',
'sensor.',
'sensor.',
'sensor.',
'sensor.',
] %}
{% set ns = namespace(upcoming_sensor = None) %}
{% for sen in sensors %}
{% if now() < as_datetime(states(sen), default) %}
{% set ns.upcoming_sensor = sen %}
{% endif %}
{% endfor %}
{{ns.upcoming_sensor}}
im getting 'namaespace' is undefined
spelling
aha i forgot i need to search jinja not home assitant
in short namespace makes it a global var
at least thats what i understood
Pretty much, yeah
it makes an object that allows you to modify it's values that's safe for jinja
it's not global
im thinking php global but i get what you mean
how do i convert 2024-08-08T00:08:00+00:00 to a HH:MM in the time zone of the home assistant instance?
as_local().strftime('%-I:%M %p') or is there a better way?
that's the most straightfoward way
{{ ('2024-08-08T00:08:00+00:00'|as_datetime|as_local).strftime('%-I:%M %p') }}
this is giving me a value:
{{ state_attr(ns.upcoming_sensor, friendly_name) }}
this is not:
{{ state_attr(ns.upcoming_sensor, friendly_name) }}
what am i doing wrong?
ten faw
I am making a template sensor for my automover, using some of the sensors it provides, but when using one of them in the template i get some internal value instead of the value the same sensor displays when added to a card on its own. Any tips on how to get that value instead?
I'm currently using states('sensor.willy_error')
I'm pirating(?) a neighbours FineOffset weather station and am trying to get the correct UV index. What kind of measurement is this? I'm struggling to find any relevant results while searching. This is the sensor in question. https://i.imgur.com/EqFXUJX.png
It says "UV Index" which suggests https://en.wikipedia.org/wiki/Ultraviolet_index
Scale of 0 to (at least where I live), 14
If you live somewhere with a higher quantity of ozone layer, pehaps a lower number
Also nice work getting weather station data without buying a weather station 😄
Yeah, that's the standard, but this sensor reports numbers in the thousands and it doesn't look right if I'd just do /1000
Oh I thought that was a decimal point, wasn't quite paying enough attention apparently
What's the biggest value you get at midday?
Heh yup, I saw someone did this as well and thought to myself hmm let me try. I think this is from the near biotechnical faculty, lots of sensors I can catch.
Not sure, started gathering data yesterday. Might need to wait a little and examine the data more. This is all the data I have now https://i.imgur.com/gTfMrhx.png
Here's the reported values from one of the local science institutions where I live: https://webstatic.niwa.co.nz/static/uv-data/uvi_today/irl_wellington_today.png
Gets to about 13 in mid summer on a clear day
Today's high should be around 6-7 according to Apple and some other local sites. I'll monitor the data and get back later. Thanks for the help!
hi i am trying to create a summary sensor with the weather data for the next day but when i use this template {{ state_attr('weather.openweathermap', 'forecast')[0].temperature }} i get None has no element 0
Question i wanna add a button in a notification that opens a website
is this possible?
Sure, set the tap_action in the button card to URL and enter a valid URL.
a button in a notify.
Ugh... I can not read today apparently. You mean a mobile device notification or a persistent notification or something else?
data:
message: >-
Geschatte tijd die joey erover doet om thuis te komen is:
{{state_attr("sensor.google_travel_time","duration_in_traffic") |
replace("hour","Uur") | replace("mins","Minuten")}}
data:
url: "https://www.google.nl/maps/dir/{{state_attr('person.joey','latitude')}},{{state_attr('person.joey','longitude')}}\{{state_attr('zone.home','latitude')}},{{state_attr('zone.home','longitude')}}"
action: notify.mobile_app_joey_s24
i guess something goes wrong
If you take the message template and the url template and test them in dev tools > template, what do you get?
those work
it only gives the the message as
blablabla
url: "Link in plaintext here"
Ah, you have a \ that's being interpreted into the URL.
the url is fine
the message is also fine, you can only not press the URL in the notification
to go to the website
iOS or Android?
For Android it's clickAction:.
do i add that in the message part?
data:
message: >-
Geschatte tijd die joey erover doet om thuis te komen is:
{{state_attr("sensor.google_travel_time","duration_in_traffic") |
replace("hour","Uur") | replace("mins","Minuten")}}
clickaction: "https://www.google.nl/maps/dir/{{state_attr('person.joey','latitude')}},{{state_attr('person.joey','longitude')}}\{{state_attr('zone.home','latitude')}},{{state_attr('zone.home','longitude')}}"
action: notify.mobile_app_joey_s24
Got it like this atm
No. clickAction: needs to be under another data:.
there's a nice section on it in the companion docs documentation
Looks like what you had before would work for iOS, but not for Android
cant work like this
data:
message: >-
Geschatte tijd die joey erover doet om thuis te komen is:
{{state_attr("sensor.google_travel_time","duration_in_traffic") |
replace("hour","Uur") | replace("mins","Minuten")}}
data:
clickaction: "https://www.google.nl/maps/dir/{{state_attr('person.joey','latitude')}},{{state_attr('person.joey','longitude')}}\{{state_attr('zone.home','latitude')}},{{state_attr('zone.home','longitude')}}"
action: notify.mobile_app_joey_s24
No. Your indentation is all wrong there.
Follow the example in the docs.
besides indentation (and the repeated data key) , it's clickAction with a capital A
it doesnt like to be on the same row as message
data:
message: >-
Geschatte tijd die joey erover doet om thuis te komen is:
{{state_attr("sensor.google_travel_time","duration_in_traffic") |
replace("hour","Uur") | replace("mins","Minuten")}}
data:
clickAction: "https://www.google.nl/maps/dir/{{state_attr('person.joey','latitude')}},{{state_attr('person.joey','longitude')}}\{{state_attr('zone.home','latitude')}},{{state_attr('zone.home','longitude')}}"
action: notify.mobile_app_joey_s24
you already have a data key, put both the message and the clickAction under that same key
oh sorry
no
that seems to be correct
lol
yeah, it's always been confusing
Follow the example in the docs @marble jackal !
automation:
- alias: "Notify Mobile app grouping"
trigger:
...
action:
- action: notify.mobile_app_<your_device_id_here>
data:
title: "Smart Home Alerts"
message: "Something happened at home!"
data:
group: "example-notification-group"
this is what im following, but it doesnt like this setup
just add the clickAction under group with the same indentation
action:
- action: notify.mobile_app_<your_device_id_here>
data:
title: "Smart Home Alerts"
message: "Something happened at home!"
data:
group: "example-notification-group"
clickAction: https://do-not-use-this.thefes.casa
action: notify.mobile_app_bills_iphone_ha
data:
title: "This is a test"
message: "This is a test"
data:
url: "https://www.google.com"
Works perfectly on my phone.
action:
- action: notify.mobile_app_joey_s24
data:
title: "Smart Home Alerts"
message:
Geschatte tijd die joey erover doet om thuis te komen is:
{{state_attr("sensor.google_travel_time","duration_in_traffic") |
replace("hour","Uur") | replace("mins","Minuten")}}
data:
clickAction: "https://www.google.nl/maps/dir/{{state_attr('person.joey','latitude')}},{{state_attr('person.joey','longitude')}}\{{state_attr('zone.home','latitude')}},{{state_attr('zone.home','longitude')}}"
doesnt work
also with the group above the click action
i dont get it :/
Your indentation is still wrong.
i copyed this 1
action: notify.mobile_app_joey_s24
data:
title: "This is a test"
message: Geschatte tijd die joey erover doet om thuis te komen is: {{state_attr("sensor.google_travel_time","duration_in_traffic") | replace("hour","Uur") | replace("mins","Minuten")}}
data:
url: "https://www.google.nl/maps/dir/{{state_attr('person.joey','latitude')}},{{state_attr('person.joey','longitude')}}\{{state_attr('zone.home','latitude')}},{{state_attr('zone.home','longitude')}}"
copyed yours also nothing
what is the goal of that backslash in the URL?
nothing thats just a typo
Yup, it's the backslash that is causing the issue as I said before.
action: notify.mobile_app_bills_iphone_ha
data:
title: "Smart Home Alerts"
message: 'Geschatte tijd die joey erover doet om thuis te komen is: {{state_attr("sensor.google_travel_time","duration_in_traffic") | replace("hour","Uur") | replace("mins","Minuten")}}'
data:
url: "https://www.google.nl/maps/dir/{{state_attr('person.bill','latitude')}},{{state_attr('person.bill','longitude')}}/{{state_attr('zone.home','latitude')}},{{state_attr('zone.home','longitude')}}"
That works.
ok when i change it to clickaction it works
cool now for it to be a fysical button
Oh, that's a brilliant idea. None of the quotes are longer than 255 chars so it should work perfectly. Thanks!
A bit annoying it's not possible to EDIT the options though. Have to delete and add again to fix a small typo.
I also see I was wrong about the 255 chars max length but the UI won't show more than like 60 chars, hehe.
@real girder Now that you've had another 12 hours to collect data, what sort of UV figures did you get?
@half fable I converted your message into a file since it's above 15 lines :+1:
Hello, is anyone understand why I got this error in the template I try to setup: https://pastebin.com/4ajCQTB7
Invalid config for 'template' at template.yaml, line 500: 'platform' is an invalid option for 'template', check: binary_sensor->0->platform Invalid config for 'template' at template.yaml, line 500: required key 'state' not provided Invalid config for 'template' at template.yaml, line 501: 'sensors' is an invalid option for 'template', check: binary_sensor->0->sensors
Invalid config for 'template' at template.yaml, line 500: 'bin_collection_day' is an invalid option for 'template', check: bin_collection_day```
in the developeur sectionn the template is working fine
oh I figured out this was my mistake:
bin_collection_day:
friendly_name: "Bin Collection Day"
should only be name: xxx
Looks like your mixing the modern and legacy format
It went a bit over 3000, local sites and Apple Weather said that the index should be 6-7, which seems that the value itself is not just /1000. No clue what it represents. https://i.imgur.com/xnJ6Q3D.png
I found some mentions of a uvi-value for the WH65 that should be the UV index.
Dividing it by ~400 seems to match up with many examples i found with both uv an uvi readings...
This might work, if I divide the yesterday's peak by 400, I get the value reported by Apple Weather. I'll monitor some more, but thanks, this is great!
It’s probably lux, at least that’s my guess. The manual shows the same sensor is used for UV index and light. And light can be output in lux, foot candles, or w/m^2
Hey guys. Suppose I wanted to pass a device as a parameter to a script and then use that device in a template, what would that have to look like? As in, what could I expect to actually arrive in that parameter, and how can I work with it, for example, access its entities?
In your script, you’ll add a field with a type of device. Then, further down, you can use something like {{ device_entities(device_field) }} to get the entities of the device.
Ok, if that works, it should be RELATIVELY easy... They wrote on his toobstone.
Yup. I can give you some samples when you get to the point that you’re writing the script.
Oh I think I can handle the template part now, but you could explain to me how to use a selector type field. How is the options stanza supposed to be formatted?
In YAML? This is one of mine:
speakers:
selector:
entity:
multiple: true
filter:
domain: media_player
integration: sonos
Pardon the formatting… 😦
Not what I meant, but never mind, I figured it out.
Oh? What did you mean? Like in other actions?
Like ```fields:
direction:
selector:
select:
options: [hoch, runter, links, rechts]
I couldn't figure out the options list, but now it seems to swallow it.
Use the YAML list syntax. It always works better for me.
Options:
- One
- Two
- Three
🤦♂️ Why didn't I figure that out?
You’re still learning 🙂 It’s all good!
I'm juggling too many variables here. One cat is still missing in the being-fed list, one is playing "the floor is lava" with my new carpet, and my fan keeps falling over.
Can you give me a hint how to filter device_entities(..) by device type, e.g. button? I know I could simply do select ('search'... but I don't enjoy being crude...
{% set spkrs = integration_entities("sonos") | expand | selectattr("attributes.device_class", "eq", "speaker") | map(attribute='entity_id') | list %}
This is how I do it in one of my scripts.
I’m not sure it’s the “best” way, but it works and it’s fast.
NP!
what exactly is that expand command supposed to do there?
It expands out the entities from the integration_entities.
Actually, I wonder if I really need that there… 🤔
Yup. I need it there to expand out the return value.
I sent you one of my scripts in a DM that has a lot of logic in it.
Hm... {{ device_entities('dcf5ecf5efb15ee7f3dad2406ec485d2') | expand | map(attribute='attributes.device_class') |list}}gives back a list of "Undefined". could be a problem.
The attributes may not contain device_class. Let me check
Yeah, on mine, not a lot of the entities have device_classes defined.
You don't need to use expand, you can use is_state_attr as test
{% set spkrs = integration_entities("sonos") | select("is_state_attr", "device_class", "speaker") | list %}
Ooohhhhh that’s cleaner!
Had to make some fixes, should be correct now
Yeah, I like that a lot better.
You can do ```py
{{ device_entities('dcf5ecf5efb15ee7f3dad2406ec485d2') | map('state_attr', 'device_class') | select() | list }}
Also here `expand` is not required as `state_attr` can be used as filter
And `select()` without parameters will select anything which is considered `true` (so in this case anything which isn't `none')
But how does that help me cleanly identify all entities that will behave like buttons?
No, you probably want this
{{ device_entities('dcf5ecf5efb15ee7f3dad2406ec485d2') | select('match', 'button.') | list }}
doesn't really work, returns an empty list. It works if I replace 'match' with 'search' though
Perhaps the "buttons" aren't really buttons?
Can you give me an example entity_id?
This template:
{% set ns = namespace(lights=[]) %} {% set groups =
integration_entities('group')| select('search', '^light.') | list %} {%
for group in groups %}
{% set individual_lights = state_attr(group,'entity_id')%}
{% for individual_light in individual_lights %}
{% if "group" not in individual_light and state_attr(individual_light, 'rgb_color') and states(individual_light) == 'on' %}
{% set ns.lights = ns.lights + [individual_light] %}
{% endif %}
{% endfor %}
{% endfor %} {{ ns.lights }}
Sometimes work, and sometimes return TypeError: 'NoneType' object is not iterable .
What could cause that?
What are you trying to do with that template?
Get every individual light with the "rgb" capacity
I have a custom sentence that I am trying to use as an automation trigger:
convert {amount} {fromcurrency} to {tocurrency}
Unfortunately this does not work as Assist doesn't know how to separate the two variable values so I am considering changing it to this:
convert {amount_and_fromcurrency} to {tocurrency}
My question is this. Is there an easy way to take something like:
convert 100 US Dollars to Euros
and break it down to maybe a list what would be ['100','US Dollars'] using Jinja for the amount_and_fromcurrency value?
It's very old code, but worked for the longest time and recently broke
I'm confused as to why it works sometimes and sometimes not
I "think" i was pulling all the groups and then the lights from within those groups
Yeah, I’m not sure to be honest. I tried it here and it works fine on repeated refreshes of the editor. 🤔
Can you split the numbers from the text?
{% set amount_from = '100 US Dollars'%}
{{ amount_from | select('in', '0123456789') | join }}
{{ amount_from | reject('in', '0123456789') | join | trim}}
Wow. Will try this soon. Thank you
Why does this:{{ states.number.somenumber.state |float * 1.1 | int }} return the ummultiplied state as a float instead of the multiplied state as an int? What am I doing wrong?
LIke so: {{ states.number.somenumber.state |(float * 1.1) | int }} It doesn't like that at all.