#templates-archived
1 messages · Page 64 of 1
Is it possible to format the output ? Like add a carriage return at the middle or something like this. Because in my lovelace the value go over the card and i miss some info
I'm not sure what the actual ouput of that attriubte is
that's handled by your frontend
because only your frontend knows when it overflows.
No the media player was on
does it change when you use the number outside mushroom cards?
Thansk for spotting it, was not in my code anymore and should not have been either. Could have become a real headbreaker 😂
Hi! I hope to be right here. I am pretty new and try to add a fhem esprgbww controller using mqtt. Unfortunately I can not get hs(v) working and no help in the community forum. However, according to sir_goodenough (forum name), there should be several ways to add hs to a mqtt light template. but whatever I try, I am only getting yaml errors. so far I am having the following config:
@reef pecan I converted your message into a file since it's above 15 lines :+1:
hs_command_template does not work in template schema, but I need this for on/off because of the strange json-format used here...
I would be very happy to get some hints as this is a major show-stopper for me when migrating from fhem to HA
How do I reference a helper entity in an automation if I'm using the UI? Is it correct if I just use "Edit in Yaml" for my action, and then use this yaml for the value of the entity?
data:
temperature: {{ states('input_number.my_entity') | float(2) }}
I ask because I think it's right, but when I go into the automation again the data is gone again.
Surround the template in quotes
Ahh thanks!
I took the attribute into a automation when i leaving Zones and my automation was not trigger. I believe the Zones attributes didnt change ?
You could check that
struggling to figure out how to craft a notification (notify works) that contains a String and an image. Say sensor.name and sensor.image. I know states(sensor.name) isnt right but im struggling to find the right template on https://www.home-assistant.io/docs/configuration/templating/
do you have it working without templates? So with a static name and static image?
seems that no one knows about templates with mqtt/hs/lights 😦
static name, yes. static image, havent tried. Image is a plus, looks like its more of an attachment. just struggling to find the right template to post a text sensor rather than a state
post what you've tried
and post the working call w/ static name and image
@fleet viper
no image yet but this is what i have
service: notify.ryan
data:
message: "Test states(sensor.p1s_01p00a382700721_task_name)"
I've tried message with just "test" and its fine
the message you have there will also send just fine, but it will be exactly as you have it written becuase you aren't following any Jinja rules
I suggest you take a look at the pins in this channel first and try again
- "You can do anything in templates"
- "Jinja uses various delimiters in the template strings.
{% %}..." - "you need to use a namespace if you're planning modify a variable..."
- "I see a lot of folks ask for how to know, of a group, who was th..."
- "To count lights which are on, and exclude light groups, note tha..."
- "Jinja (Template) Built-ins jinja.palletsprojects.com/en..."
- "Distinguishing Yaml from Jinja (templates) community.ho..."
- "Confused about the 2022.2 breaking
defaultchange? c..." - "Understanding types to parse JSON community.home-assist..."
- "@689168555861737485 Here's a template that looks up a friendly..."
take a look at the 2nd pin
Just wondering the way to abbreviate a sensor string? ex: a sensor with the text : Spotify - K-POP (feat. Bad Bunny & The Weeknd) I would like to limit it to like 20 characters
same as slicing a list [:20]
thanks for the tip! looking into it
And would there be away to remove the brackets and whats between them?
you mean the parenthesis?
yeah haha mybad
thanks. i figured i was missing it but was trying to check HA template doc which wasnt giving me the answer. ill try your link
thanks very much
Use the template editor to test templates
Im confused why this doesn't work
"{{sensor.p1s_01p00a382700721_task_name}}"
when it seems it should just be an expression in Jinja
does template editor not pull in HA sensors by default?
It's a string value. is that still a state?
you're not using the right syntax
i know, thats what its telling me 🙂
should it just be " {{ states.sensor.p1s_01p00a382700721_task_name }} "?
that gives you the state object
figured it out i think " {{ states('sensor.p1s_01p00a382700721_task_name') }}"
that will get you the state
which is returnnig the string i want
Hello team! I have a question: I try to extract the value when my dishwasher is finished. I´m halfway through but I want to remove the date from my output. Can someone help me? Currently value_template: "{{ states('sensor.bosch_smv4hde33e_remaining_program_time') }}" has an output of value_template: "2024-01-12T21:09:20+00:00". I would only need the time and in CET time (so one hour on top of the output). Is this possible?
something like: {{ (states('event.repair')|as_datetime|as_local).time().replace(microsecond=0) }}
Many thanks! Works perfectly!
have a odd question that maybe someone can help me out with. Trying to setup an automation in homekit where if a switch changes state to ON that it will play a warning on the homepods in the house. To do this think i need to change the type of sensor from occupancy to switch in HA (using home assistant to Homekit Bridge). This is the sensor: "binary_sensor.driveway_person_occupancy
Homekit wont let me automate on the type occupancy
plus it triggers on the entire room for any occupancy sensor.
I didn't think you could play audio directly from HA to Homepods
I've done it
have any links on how you accomplished that ?
test_good_morning:
sequence:
- service: persistent_notification.create
data:
message: Good Morning!
- service: tts.google_translate_say
data:
entity_id: media_player.homepod
message: "Morning Passed"
just like that
interesting, well that is way less Janky that the path i was trying to take.
haven't used it in a while, but I just test it and it works
do i need to do anything to configure the tts.google service ?
I would just add this block in the automations.yaml ?
been ussing node-red for too long 🙂
this is a service call:
- service: tts.google_translate_say
data:
entity_id: media_player.homepod
message: "Morning Passed"
you would call something like it wherever and however you make service calls
my script is just an example
you could probably do it all in Node Red if you want, but I know nothing about it
Thanks for the help, ill kick it around this weekend.
Can someone help me get this working please? https://www.phind.com/search?cache=d0jh4j6y6itkd6f2uyp4f452
Unlikely, because very few people are motivated to fix stuff GPT breaks.
But... you could have a look at the sensor group helper in the UI.
there wasn't something for him to break to begin with. i mean i don't care if someone wants to start from scratch instead xD
That statement motivates people much more 
so we're back at taking the template gpt made and fixing that instead of making everything from scratch? gotcha
no, its a read some docs and try to work out your own solution using your own system. There are tools built into the product to help you test things
And you got a free hint
GPT really doesn't understand what's going on so you are even worse off using that as a base than if you tried on your own
yeah, as you can read in the chat log i feed the results back to him ^~^
well, if i tried it myself it would probably look like this: {%average(states('sensor.esphome_timos_room_ds18b20_temperature'), state_attr('climate.timos_heizung_thermostat','current_temperature'), states('sensor.space_heater_temperature_ds18b20'), states('sensor.esphome_65_dht11_temperature'))%}
which one looks more correct :'D
That's the problem with 99% of the stuff made by GPT, it looks correct, but it's not 😄
Thanks for the tip :) its not very obvious that you have to create then edit so you can ignore text states and i have no idea how to add a attribute to the group
Things to understand
- All states are strings,
averagedoesn't automatically convert that for you - You need to ensure the state is numeric, otherwise you'll get errors when a sensor is unavailable
- Instead of the state template returning
unavailableyou should use the availability template option - ChatGPT isn't aware a modern template sensor format has been introduced, it's still using the legacy format
@spice current more hints 🙂
Before I go and reinvent the wheel, does anyone have a macro to process the new output from the calendar.get_events service and get a nice date and time ordered list from multiple calendars. Thanks in advance.
I don't, but it sounds like a good idea💡
There is also another UI helper, which can transform an attribute to a sensor's state
Which one of the 509 helpers would that be? The closest ive seento conversion is change device type of a switch and template
Can't I move trigger based template sensors into an include file?
The sensor group helper can calculate an average (arithmetic mean) based on other sensors
Yes, with the right include
Hey guys, quick Question. I use a template sensor to extract one value from an thermostat.
Template:
{{ state_attr('climate.nspanel_buero_thermostat', 'temperature') }}
Is there a way to make it "re-usable" I have multiple devices to extract it an would like reuse the same template and just change the "'climate.nspanel_buero_thermostat" id.
In this specific example, it is not necessary to specify a different ID. However, I may have more complex templates and would like to know what I should pay attention to in order to keep them as "general" as possible and to be able to reuse them.
not in a meaningful way
You could use an input_text entity for the entity_id, but then it would change everywhere you use it. Or you could use a template with a macro wherever you need it, but that's not always possible and it's probably even more typing
it's such a simple template that there isn't anything to optimize
Create a template sensor with a custom event trigger and then use the event data in the template for the state? It all seems unnecessarily complicated
I am fairly new to HA. Coming from CQC. I am working on a template to announce (TTS) the time and temperature on the hour and half hour. I have it working mostly, but the announcement of the minute comes out as "zero zero" and
" three zero" instead of thirty. How can I correct that?
Here is the tmeplate The time is {{ as_timestamp(now())|timestamp_custom ('%-I %M') }}, and the temperature is {{ states('sensor.openweathermap_temperature') | round(0) }} degrees, but it feels like {{ states('sensor.openweathermap_feels_like_temperature') | round(0) }}"
Also, how can I do a return when writing a message without it immediately posting?
Nice, thank you. With the background of "Keep it simple", it is therefore easier to simply customise the ID.
Here on Discord? Use Shift+Enter
Thanks
Which TTS integration are you using?
If you paste your template into the Dev Tools does it resolve correctly?
media_player.vlc_telnet and tts.google_en_com
BTW, you can replace {{ as_timestamp(now())|timestamp_custom ('%-I %M') }} with {{ now().strftime('%-I %M') }}
Those are entity_ids, not an integration. Are you using Google Translate Say?
It will give the same result, it's just a more efficient template
If might also be worth adding the : eg %-I:%M
That will help a lot probably
So it looks like a time
The TTS integration will understand it's a time then
(just wanted to actually finish my sentence, I was already too invested in swiping it)
I think it already hasit
(Been there 🙂
You still don't have the : between the hours and minutes
Which a normal time string has
You have a space
Can a template sensor replace the actual sensor?
no
hi all, the templates {{ as_timestamp(now()) }} {{ as_timestamp(utcnow()) }} both render the same timestamp, although {{ now() }} {{ utcnow() }} are different (1 hour apart). Is that on purpose or it might be a bug?
No. as_timestamp is a linux timestamp, a linux timestamp is always in UTC. https://www.unixtimestamp.com/
thanks!
Quick question. Is it possible to run services in a template?
Rather than calling a script which then writes to a helper, directly call the service, write to a variable and proceas that variable inside the template?
You can't call services directly in a template, but you can add an Action bock to a trigger-based template sensor. https://www.home-assistant.io/integrations/template/#trigger-based-handling-of-service-response-data
Too bad. I was hoping to make it a bit faster and more direct... and without additional helpers.
chances are, you don't need the helper.
Well, since todo lists have no search feature I wanted to use an input_text as search string field and then use a markdown card with template to get the items, store them in a variable, filter the result according to the search string (input_text) and then create a list of matching results or links matching the results.
I think I know how to do it with scripts/automations, but not without (and without anything but the initial input_text).
If I'm adding this to my templates.yaml I get an error: can't figure out what is wrong.
- sensor:
- name: "TempAircoZolderSchuur"
unique_id: TempAircoZolderSchuur
value_template: "{{ state_attr('climate.airco_zolder_schuur', 'current_temperature') }}"
friendly_name: "Temp Werkkamer Zolder Schuur Airco"
unit_of_measurement: "°C"
- name: "NordPool Energyprices"
unique_id: 9e773602-c9d2-4e91-9753-3cdf9d7e6aaf
unit_of_measurement: "€"
value_template I think should be state instead. Value template is the legacy template format
Thanks I changed value_template to state. It's not that I don't try to read the manual... more that I fail to spot the error.
Thanks, I noticed I had one more error and was able to isolate this one. It works as intended now: ```- sensor:
- name: TempAircoZolderSchuur
state: "{{ state_attr('climate.airco_zolder_schuur', 'current_temperature') }}"
unique_id: TempAircoZolderSchuur
unit_of_measurement: "°C"````
It gets the temperature from an airco unit for a graph that accompanies an thermostat entity for the airco unit.
@bright quarry I converted your message into a file since it's above 15 lines :+1:
why isn't my above frontend card colorized in has anymore after updating ?
Probably because you updated card-mod, which has a breaking change
But this is something for #frontend-archived
can I have a newline inserted in a template. this example works but on one line.:
- service: persistent_notification.create
data:
title: "heat"
message: >
prev temp:{{ states('input_number.previous_upstairs_local_temp_heat') }}
cur. temp:{{ state_attr('climate.2nd_floor', 'temperature') }}
message: "{{ states('sensor.aarlo_battery_level_catbox') ~ '\n' ~ states('sensor.aarlo_battery_level_family_room') }}"
I just changed the > to | and it worked. I tried without the ~ it didn't work, i guess that would work.
Which is better?
well the ~ '\n' ~ didn't work either so I guess i'll use message: |
it's works fine, I tested it
service: persistent_notification.create
data:
message: "{{ states('sensor.aarlo_battery_level_catbox') ~ '\n' ~ states('sensor.aarlo_battery_level_family_room') }}"
unavailable
24
but whatever works for you..
yeah I just tried again. I had the closing }} for each line. I guess it boils down to personal pref of what is clearer to read.
I noticed ChatGPT (4) is pretty good at helping debug, find syntax errors, and resolve HomeAssistant template string issues (And yaml issues) 👍
ChatGPT and other "AI" systems do a fantastic job of generating well structured, convincing looking answers... that are either totally garbage or, if you're lucky, have subtle flaws. Don't use them to "help" others, and don't use them yourself.
Side-note: I have seen this message before but that does not mean it should not be used.... I use it frequently just to get me in a certain direction. As long as you know that this has to be treated with care DO use it....and for sure donot come asking for support if it did not help 🙂
You can certainly use it for your own system. If you are able to adjust the output to something working.
But to use AI to give advise to others is something different as not everyone has the knowledge or the ability to see if the code is not (fully) correct or to adjust it accordingly
In case anyone needs it:
{%- from "easy_time.jinja" import easy_time, big_time -%}
{% set ns = namespace(items=[]) -%}
{% for c in calendars %}
{% for i in calendars[c]['events'] %}
{% set ns.items = ns.items + [ {'start':
i.start, 'summary': i.summary} ] %}
{% endfor %}
{% endfor %}
{% for item
in ns.items|sort(attribute='start') %}
{{ easy_time(item.start)}} {{item.summary}}
{% endfor %}
You need Petro31's excellent easy_time macros installed to get a nice read. It takes the variable provided by the calendar.get_events service.
Is there a var in jinja that contains all defined variables?
Something like vars and it's all defined variables in the context.
@pallid pike I converted your message into a file since it's above 15 lines :+1:
You need to assign the input to a variable first to use it in a template
Thanks, @marble jackal . I had tried that, but it wasn't having it. Let me dig deeper into that
action:
- variables:
camera_label: !input camera_label
- service: script.camera_brightness
data:
camera_name: "{{ states(camera_label) | replace('_cam.', '') }}"
command: brightness
brightness: 4
Same problem, sadly.
The trace shows
data:
camera_name: '{{ states(camera_label) | replace(''_cam.'', '''') }}' ```
That's not an issue. That's just something which happens when it's parsed to json
Ah, damn. So it was probably working all this time. Cheers, Fes
Trying to have a sensor value set to the name of the AP a phone is connected to. This template is filtering access points down to the one whose mac address matches the mac address the phone is connected to. Nothing gets returned (the phone is connected to an access point, I checked). Maybe comparing mac addresses like this isn't correct? Any ideas?
# Phone locators
- platform: template
sensors:
tim_phone_location:
friendly_name: Tim Phone Location
value_template: >
{% set ap = states.device_tracker | selectattr('source_type', 'eq', 'router') | selectattr('mac', 'eq', state_attr('device_tracker.tim_s_s21', 'ap_mac')) %}
{{ ap.friendly_name }}
are "source_type" and "mac" attributes of the device_tracker entities you want to filter?
if so, you wanted attributes.source_type and attributes.mac
Yes they are. So it will look like this?
{% set ap = states.device_tracker | selectattr('attributes.source_type', 'eq', 'router') | selectattr('attributes.mac', 'eq', state_attr('device_tracker.tim_s_s21', 'ap_mac')) %}
yes. does it work?
No, this is in the logs
Logger: homeassistant.helpers.template
Source: helpers/template.py:2318
First occurred: 7:33:57 PM (2 occurrences)
Last logged: 7:33:57 PM
Template variable warning: 'generator object' has no attribute 'friendly_name' when rendering '{% set ap = states.device_tracker | selectattr('attributes.source_type', 'eq', 'router') | selectattr('attributes.mac', 'eq', state_attr('device_tracker.tim_s_s21', 'ap_mac')) %} {{ ap.friendly_name }}'
oh, you didn't actually extract the device_tracker
and "friendly_name" isn't part of the state object
{% set tracker = states.device_tracker | selectattr('attributes.source_type', 'eq', 'router') | selectattr('attributes.mac', 'eq', state_attr('device_tracker.tim_s_s21', 'ap_mac'))|list|first %}
{{ tracker.name }}
I'll try that
you can just stick it right in
-> Templates and debug there
That worked, thank you! Why 'name' and not 'friendly_name'?
name will use friendly_name if it exists, and otherwise falls back to name
it's more robust
Got it. Thanks for your help!
it will error out if it doesn't find one that matches
That's fine. Thanks
something like this will fix it:
{% set tracker = states.device_tracker | selectattr('attributes.source_type', 'eq', 'gps')|list|default(['No Device'], True)|first %}
{{ tracker.name if tracker.name is defined else tracker }}
for media_player, how on earth does the Lovelace UI show current position of a TV show time, when none of that data is changing in the state? i'm trying to get time remaining/current percentage played
i see a position attribute for my apple TV media player, but it doesn't change as time progresses. it's always something like 9
duration doesn't change, either
You can work it out with media_position, media_position_updated_at, and duration.
As a general rule we don't want the state machine changing every second to track time elapsing, too much churn. That's how the timer works too.
hmm. but media_position_updated_at doesn't change either
unless i run update_entity on it
yeah. i my guess was it compares last time when state changed play/pause vs duration, etc
otherwise if you have a 10 minute video, and you were at media position 5 minutes, and the updated_at was 2 minutes ago, then you can infer you're at 7 minutes.
the whole reason is i'm trying to add a trigger to wait until an episode is finished (not just paused or idle)
If you know when it was last updated, and what the total duration of the media is, you can calculate how long it will take to end
oh, Discord cache strikes again
hi, i want a template wich i can use in a glance card to show if my washer is on. i want to do it with a power sensor. someting like:
- sensor:
- name: "Status_Waschmaschine"
state: >
if (states['sensor.waschmaschine_power'].state > 2)
return "on";
else
return "off";
but i cant get it to work.
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.
is this even possible? i only want to see it when its "on" (this is possible with the entity filter card right?
you are not using Jinja, which is used for templates
Become a real Jinja2 Ninja! Don't worry my Genin, we are here to help! You can find general Jinja docs at https://jinja.palletsprojects.com/en/3.1.x/templates/, Home Assistant extensions at https://www.home-assistant.io/docs/configuration/templating/, and trigger variables at https://www.home-assistant.io/docs/automation/templating/
This channel is for support with Jinja templates. Some custom Lovelace cards support other types of templates, such as those written in JavaScript, and #frontend-archived is the right channel for that.
Please use http://pastie.org/, https://dpaste.org/, or https://paste.debian.net/ to share code or logs
you should also use a binary sensor, that will return on on true and off on false
template:
- binary_sensor:
- name: "Status_Waschmaschine"
state: "{{ states('sensor.waschmaschine_power') | float(0) > 2 }}"
also, all states are strings, so you need to convert it to a float or int to compare it with 2
If I wanted to display the last time a climate entity was changed from "off" to "heat" in days how might I do that? I want to know how long a heater has been running
I can see it in the logbook.
I want to display it in Lovelace
how do I list all my lights like this?
['light.bagno', 'light.bagno_rf', 'light.bagno_sx']
Something like {{states.climate.zone_1_lounge.last_changed}} insert you own climate entity, will give you the date. If you have easy_time installed you can use that to format it as days since.
by "like this", you mean a list of entity_ids?
{{ states.light|map(attribute='entity_id')|list }}
How would I remove kvp from a list of dictionaries if the key is search foo for example
you have to create a new dict or list and reject it
Do you have a quick example?
do you have an example of your "list of dictionaries"?
[{"SantaFoo":"moon","EveFoo":"mars","Description":"ha"]}
foo is always at the end.
rejectattr
But how would you rejectattr if the key isn't static?
As in if there's a bunch of keys with Foo at the end?
you'd have to convert it to kvps w/ .items() and reject based on searching the key
then turn it back into a dict
I assume that you wanted to flip the order of ]} at the end
Yep I did
Figured it out thank you
is there a date function of some sort that could return the 'next Thursday' from now() or do I have to do some maths with day of week
@paper mortar yes, you'll need to do some math with day of week
{% set date = now() %}
{{ date.date() + timedelta(days=(11 - date.isoweekday()) %7) }}
thanks ya I did something similar but offsets to the next week if it lands on a Thursday. Just wanted to see if there was a simpler function.
Unfortunately That gives the last time "something" changed (like temp) not the last time it changed from off to heat....
2024-01-17 00:32:31.233581+00:00
I thought last_changed was the most recent state change, and last_updated was any state or attribute.
That should be the last time the state changed. Keep in mind the state will change (briefly) during HA restart, so if you didn’t change the mode of your thermostat at that time, then you probably restarted HA at that time.
The other option is a template trigger sensor which updates to the current time when the climate sensor moves to heat from off.
I'm sorry if this is the wrong place.
I'm very new to HA, have a home assistant green running since last week and love it. But I'm by no means a programmer or understand what I'm doing.
Here's my current question:
I have a GPS tracker for my dog. I can see a lot of entities from it. One is a device_tracker that has in it's history exactly the data I want to have displayed on my dashboard (and trigger an automation with it, but that's not as important right now.)
I want to see a card in the dashboard that displays how long ago my dog was outside for the last time.
The data is there. I can click the device_tracker, hover over the history and it shows me exactly what I want to see on the dashboard. But I have no idea how to get it out of there.
#frontend-archived sent me here:
Ah, okay, so a normal HA device tracker. I don't have any, so I have not done it yet.
But I could think of two options (both not so simple):
- Create a card that accepts templates for the state and then using templating to calculate the time between state change from not_home until home.
- Create a template sensor ( menu item devices & services -> helper -> template -> sensor) and do the calculation there.
Option two being a bit simpler and I am sure that someone in templates can help you with the syntax
Here is the original screenshot that I included
https://media.discordapp.net/attachments/460846676358332417/1197118083056291870/Bildschirmfoto_2024-01-17_um_10.50.51.png?ex=65ba1a18&is=65a7a518&hm=4f848ccfeab496105ab0e13f6ea80efad5758b8217a0ac1f0702e639906e7fb0&=&format=webp&quality=lossless&width=479&height=622
I think you could try something like this:
{{ states.device_tracker.dog.last_changed if is_state('device_tracker.dog', 'home') else this.state }}
If the device tracker isn’t currently home the sensor will be unknown until the tracker first changes to home
That will give you a datetime of when the dog last came inside. In the front end you can decide how to display it. Some cards will show past datetimes in a relative format (‘2 hours ago’) or if you want something more specific you can use a template card to calculate the time. The reason that I didn’t provide a template to calculate the time difference directly is because it’s generally poor practice to create a sensor that changes every minute because it clogs up your history database with useless data. If you calculate the time delta in the frontend then it is only calculated when someone looks at it, and it doesn’t store that data.
It is more efficient to store a few datetime states each day as opposed to 1440 time deltas each day.
You could also use 2 date time helpers, one set in an automation when the dog goes out and one when he comes back. Then you can use a simple time difference template on your card to show the last time he came in from outside and how long he was out.
Can someone help me get my head around this?
{{(as_timestamp(now()) - as_timestamp(states.binary_sensor.ac_running.last_changed)) | timestamp_custom("%-d days and %-H hours", false) }} {{(now() - states.binary_sensor.ac_running.last_changed) }} {{now()}} {{states.binary_sensor.ac_running.last_changed | as_local}}
1 days and 8 hours
8:50:44.670461
2024-01-17 22:47:00.321749+11:00
2024-01-17 13:56:15.651231+11:00
Why is the first output showing the time difference as 1 day 8 hours when the difference is just 8 hours?
I managed to get the right output by totally changing my approach but I still want to know why I'm getting an extra day on this
%d is "day of the month", not number of days.
If you printed out the full timestamp custom after your subtraction it would probably be something like Jan 1 1970, 8:50AM.
So that's "day 1, 8 hours"
Maybe you want something like this:
{% set delta = (now() - states.binary_sensor.ac_running.last_changed) %}
{{ delta.days }} days and {{ (delta.seconds/60/60) | int }} hours
OH this explains it! I just kept looking at the difference and not computing where the 1 day was coming from.
Thanks - I got the output I wanted with this:
{%- set last_change_time = states.alert.garage_door.last_changed -%}
{%- set time_difference = current_time - last_change_time -%}
Garage door open for {{ '' if time_difference.days == 0 else time_difference.days ~ ' day' ~ ('s' if time_difference.days != 1 else '') ~ ' and ' }}{{ time_difference.seconds//3600 }} hour{{ 's' if time_difference.seconds//3600 != 1 else ''}} and {{ time_difference.seconds//60 }} minute{{ 's' if time_difference.seconds//60 != 1 else ' ' }}```
Obviously extra fluff in there now, but the real question was why the first attempt didn't do what I expected. thankyou
Garage door open for {{ time_difference.days ~ ' days and ' }}{{ time_difference.seconds//3600 }} hours
Without the fluff
I'm sure someone will tell me a way less convoluted way to remove 0 days and use friendly singular/plural language in strings.
@vague dawn I converted your message into a file since it's above 15 lines :+1:
Sorry I was asking why this works:
hours_till_2am:
friendly_name: "Hours Till 2am"
unit_of_measurement: 'hours'
value_template: >
{% set t = today_at("02:00:00") %}
{% set s = t if now() < t else t + timedelta(hours=24) %}
{{ ((s - now()).total_seconds() / 3600) | round(2) }} ```
but this does not:
friendly_name: "Hours Till Charge Start"
unit_of_measurement: 'hours'
value_template: >
{% set charge_start_time = states('input_datetime.calculated_charge_start_time') %}
{% if charge_start_time not in ['unavailable', 'unknown', 'None'] %}
{% set t = strptime(charge_start_time, "%H:%M:%S") %}
{% set s = t if now() < t else t + timedelta(days=1) %}
{{ ((s - now()).total_seconds() / 3600) | round(2) }}
{% else %}
0
{% endif %}```
You could use https://github.com/TheFes/relative-time-plus
omg, you did not disappoint.
Assuming the input datetime is time only... {% set t = strptime(charge_start_time, "%H:%M:%S") %} returns a time zone naive datetime object for the rendered time on January, 1 1970... now() is non-naive, and you can't compare non-naive and naive types. Just use the same function as the first example {% set t = today_at(charge_start_time) %}.
how to add an icon to this please
steamos_pc:
friendly_name: "SteamOS PC"
value_template: >-
{{ states('sensor.steamos_pc_electric_consumption_w') | float > 10 }}
can someone help me with this template syntax in an automation?
wait_for_trigger:
- platform: template
value_template: "{{ now() - states.trigger.to_state.last_changed >= timedelta(seconds=5) }}"
I'm trying to get my action to wait for x time after the entity has stopped changing.
automation is keeping the power and brightness state of multiple zigbee dimmer switches instate. the hardware behaviour of dimming to turn off upsets the automation when I'm trying to sync brighness, so need it to wait.
That template only updates once a minute. So at the moment of triggering it's false to turn to true at the beginning of the next minute
oh, so is there a way to achieve this without just having a generic 5 seconds or so (which is what I do now)?
by triggering on state change of the entity that triggered the automation
wait_for_trigger:
- platform: state
entity_id: <replace with the trigger entity>
for:
hours: 0
minutes: 0
seconds: 5
is that different to just using the for: delay in the trigger?
Because that would still trigger after the brightness had changed, but hadn't stopped changing.
I'll plug it in and see how i go 🙂
For context, this is my automation: https://hastebin.com/share/hoyasofagi.yaml
Yes you can ditch the wait_for_trigger in the sequence if you add the for: value to the brightness initial trigger
I mean that using for in the trigger didn't do what I expected. It seems to wait from a first change, but continue even if the entity keeps changing.
oh, i doesn't accept this:
wait_for_trigger:
- platform: state
entity_id: {{trigger.entity_id}}
for:
hours: 0
minutes: 0
seconds: 5
That's true indeed, sorry that was a small mistake from me haha
- platform: state
entity_id:
- light.living_room
- light.dining
for:
hours: 0
minutes: 0
seconds: 5
attribute: brightness
continue_on_timeout: false```
trying with this but still not proceeding past the wait
I may just use the for: with the trigger a long delay liek 10 seconds. then it works, it's just speed optimised 🙂
Not sure if the right place, but i've noticed there isn't a service for + or - the temperature of a climate entity.
Is it still possible, did someone managed that?
While there are no dedicated increase/decrease services, you can use the climate.set_temperature service with a template that has the current target temperature and a desired delta.
service: climate.set_temperature
data:
temperature: "{{ (state_attr('climate.awesome_climate_entity', 'temperature') | float) + 1 }}"
target:
entity_id: climate.awesome_climate_entity
service: climate.set_temperature
data:
temperature: "{{ (state_attr('climate.awesome_climate_entity', 'temperature') | float) - 1 }}"
target:
entity_id: climate.awesome_climate_entity
Fine by me! Thanks man!
If you want to get real fancy you can use the target_temp_step attribute as well to determine the jump
Cool, will check that out!
He, I tried the template but it won't work. It gives me the error failed to call service climate/set_temperature. expected float for dictonary value @data['temperature']
I also tried {{ (state_attr('climate.awesome_climate_entity', 'temperature')) - 1 | float }} but same error.
You have to convert to float before subtracting 1
Yeah I did, that was the original code from Ludeeus, but that also didn’t work. Same error.
Have you checked if the climate entity has a temperature in the devtools
And if that entity exists at all
That attribute should already be a float though
I hope it's common knowledge to adjust entities from examples to ones existing in your system
Yeah ofc I checked and did 😄
By default it returns 19.0
I could try without the | float
Where did you run the service? in some card? in the devtools?
In a custom:button-card in a custom_fields
Aha, that explains it
Than you will need to convert the template to a JS variant
"[[[ return states['climate.awesome_climate_entity'].attributes.temperature - 1; ]]]"
or
"[[[ return entity.attributes.temperature - 1; ]]]"
Ah you are right! That works...
Should've thought about that. Thanks! Really appreciate all the help!
Any plc programmer👨💻
@lament maple I converted your message into a file since it's above 15 lines :+1:
It probably expects a number, and all states are strings
So convert the state to a number using the int filter
I can imagine you would expect that, but all states are strings
Yes
That's it. A Jinja filter is preceded by a pipe symbol
So | int uses the int filter
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.
Where are you calling this service call from?
Please use imgur or other image sharing web sites, and share the link here.
Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.
That doesn't do anything sensible
What happens if you issue the service call from developer tools > services
With the template
What does the template show in developer tools > template
Okay
Executing it with command: 0 had the same effect
So the template is resolved correctly, but the service call doesn't work with 0
I'm testing with it now on my Pixel 7 Pro
It seems to go from 1 to 7
7 is 100%
But for music stream it goes to 25
That's still a string
No, all states are strings, I just explained that
The template editor parses it to a number though if it's the only value
That can be confusing
But the service call also works for strings
service: notify.mobile_app_pixel_7_pro
data:
message: command_volume_level
data:
media_stream: notification_stream
command: "1"
This works fine for me
So it shouldn't be a problem without the filter
This doesn't work because you need quotes around your template
You had them initially
This doesn't work because you are using double quotes inside and outside your template
You had single quotes outside the template before
No problem
It's going from 1 to 7
7 is 100%
And 0 should work
You can ask in #android-archived but I guess it you should create an issue about that
0 works for music stream and ring stream
Oh, now it also works for me for 0 with notification stream
It works with the string "0"
Not with the integer 0
Then don't apply the int filter
Hmm, that doesn't work
HA will convert it to int
Wait a second
Use this
service: notify.mobile_app_pixel_7_pro
data:
message: command_volume_level
data: >
{{
{
'media_stream': 'notification_stream',
'command': states('input_number.test') | int | string
}
}}
This will send it as a string
Replace the input_number and notify service with yours
You could still file a bug that 0 only works with a string, while the other values work as integer
Couldn't use just use this?
https://companion.home-assistant.io/docs/notifications/critical-notifications#android-alarm-stream
Oh wait, that's for Android 7 and below
Hmm okay
Morning all,
I'm having some issues with templating and rounding:
sensor.edf_tempo_prix_actuel = 73.24
I am doing this:
value: "{{ states('sensor.edf_tempo_prix_actuel') | float / 100 | round(2) }}"
but it gives me: value: "0.7323999999999999"
any idea why?
Because you are only rounding 100
Add parenthesis around the formula, so the round filter is applied to the formula result
mmm where would you add the parenthesis?
"{{ ( states() | float / 100 ) | round() }}"
yay thanks 🙂
my rest sensors somehow moved to output another timeformat, causing my template to take the wrong turn.... the rest sensors value_template: > {% set today = now().strftime('%Y-%m-%d') %} {% set data = value_json.result.watts.items() |selectattr('0','search',today)|sort(attribute='1',reverse=True) %} {{(data|first|default(('Unknown',0)))[1]}} json_attributes_path: "$.result" and this template {% set nu = now().replace(minute=0,second=0,microsecond=0).isoformat() %} {% set watts = state_attr('sensor.solar_forecast_estimate_watts_z','watts') %} {% if watts %} {% set data = watts.items() %} {{watts[nu] ~' W' if watts and nu in watts else 'No production estimated'}} {% else %} Offline {% endif %} which is supposed to pick the item 'now' dont match anymore
maybe a bit small, but the equation breaks on the timezone which is +00:00 in the dict items, and +01:00 in the template sensor... which would be the best way to fix this? supppose manipulating the template sensor would be optimal?
string manipulating {% set nu = now().replace(minute=0,second=0,microsecond=0).isoformat().replace('+01','+00') %} works, but it is ugly and probably dumb....
I have no idea what you're asking
are you just trying to get a list of dateteimes & values?
I need the template sensor to use the +00:00, to be able to match the dict of items that use that format
Or just show what the date format is from your rest endpoint
that's utc
so utcnow().isoformat()
yes but I use UTC, it moves an hour...
{% set nu = now().replace(minute=0,second=0,microsecond=0)|as_timestamp|timestamp_local %} has the correct hour, but with +01, and {% set nu = now().replace(minute=0,second=0,microsecond=0)|as_timestamp|timestamp_utc %} is an hour earlier, with the correct +00 as used in the rest sensors items...
marius
use utcnow
or post the format of your timestamp, the full format.
I highly doubt the endpoint would show utc time format with the wrong time.
you're either requesting the wrong information the wrong way, or you're mistaken about the hour offset
{% set nu = utcnow().replace(minute=0,second=0,microsecond=0).isoformat() %} makes it happen
so now my template sensor picks the correct item from the dict using the same offset.
and this would bring it back to the correct local hour{% set nu = (utcnow()+ timedelta(hours=1)).replace(minute=0,second=0,microsecond=0).isoformat() %}...
And that does not make any sense
A bug should be written against the API or your need to change your rest endpoint call to get the correct timezone.
if you get UTC values, your result should be UTC
You should not have to add or subtract anything, the display will be UTC which should auto format as local when you view it in the UI
TLDR: You're doing it wrong and it will break when DST is applied.
@floral shuttle ^
yes, completely agree... thing is, my rest is simply using the default, and consider whats written in the documentation at https://swagger.forecast.solar/#/Public/get_estimate_watthours__lat___lon___dec___az___kwp_ I figured that to be local. Apparently we can set 'utc' in that time option, but as it stands it already returns that...
aarrgghhh
hitting myself here, so wait a second...
I had copied the following..... solar_forecast_api_zo: https://api.forecast.solar/estimate/<lat>/<long>/21/-40/1.740?time=utc #ZO so ws explicitly requesting the urc format..
Right but if it really reports that, then the times are correct as in UTC
so you don't want to add anything, you just want to convert it to your local time
yes, Ill await the next update (at the hour) and see what it returns, and whether I need to adjust my template sensor, or all is good now
can you just post the complete template sensor so I can see what it's doing. I really don't think you need the +1 hour bs
I took that out now, only this```
{% set nu = now().replace(minute=0,second=0,microsecond=0).isoformat() %}
{% set watts = state_attr('sensor.solar_forecast_estimate_watts_z','watts') %}
{% if watts %}
{% set data = watts.items() %}
{{watts[nu] ~' W' if watts and nu in watts else 'No production estimated'}}
{% else %} Offline
{% endif %}
Yes, You are definitely making a mistake then
keep everything in UTC and you should be fine without adding the +1
if you add the +1, you'll be off by 1 hour.
restarting to be sure, but I believe taking the time=utc from the rest sensor api call didnt make a difference. Maybe I should add time=cet .
That would work, but utc will work better
I'm still not convinced you understand the issue
if you request UTC information, you just need to use the current UTC time to get the current hour.
even though the hour doesn't look current, it is
you're incorrectly thinking that the current hour is +1, when it's not.
no I am aware of that.... I had hoped to get all data in my local time, and wouldnt need to bother with anything further. I admit not being confident that when I plot these data to a current time sensor in a chart, it picks the right time if I use utcnow() in my template sensors, and the time=utc in the api call
that's how time works
@floral shuttle put this in your template editor and then look at the actual times
{% set x = utcnow().replace(microsecond=0) %}
{% set y = now().replace(microsecond=0) %}
{{ x }} == {{ y }} == {{ x == y }}
the hours will be different but the times are identical
ha, yes, that is very clear. cool. you should add this to the time template docs, never saw it as clear as that.
things is I also have this which was updated 10 minutes ago, so at my local time of 14:00. and check the time in the attributes for that value...
There's no timezone information there
The current state value matches the 12:00 timestamp, which doesn't make much sense for both UTC or GMT +1 (unless you made this screenshot more than 26 minutes ago)
no, it was from after the change of the hour to 14 (local time) . I figured that it shows the utc hours, and because it is a trigger based template takes the previous state.. thus accounting the 2 hours difference
the T and Timezone were gone from that output, so the api call did get changed when I took out the time=utc
it could probably be even simpler, but just taking out the complete timezone bit there in the template sensor, and just compare on the '2024-01-20 17:00:00' string. the api returns it like that without anything set on that time= option.
Sorry work got busy
Just post both of your template sensors
Rest sensor and the template. You can remove the resource if it’s private
no its fine, and dont apologize!
I think I made it work now with this simplification using just the format that is output in my last screen above and this time format: {% set nw = now().replace(minute=0,second=0,microsecond=0) %} {% set nu = as_timestamp(nw)|timestamp_custom %} {% set watts = state_attr('sensor.solar_forecast_estimate_watts_z','watts') %} {% if watts %} {% set data = watts.items() %} {{watts[nu] ~' W' if watts and nu in watts else 'No production estimated'}} {% else %} Offline {% endif %} this makes the 2 identical using `'2024-01-19 14:00:00``
also, given the fact the default for the resource is supposed to be local (and not utc) I can use now() again in the template sensor.
Can you just post both please?
the rest sensor and the full template sensor that uses the rest sensor
rest sensor is:```
rest:
- resource: !secret solar_forecast_api_z
scan_interval: 86400
sensor:- unique_id: solar_forecast_estimate_watts_z
<<: &estimate_watts
unit_of_measurement: W
value_template: >
{% set today = now().strftime('%Y-%m-%d') %}
{% set data = value_json.result.watts.items()
|selectattr('0','search',today)|sort(attribute='1',reverse=True) %}
{{(data|first|default(('Unknown',0)))[1]}}
json_attributes_path: "$.result"
json_attributes: watts
- unique_id: solar_forecast_estimate_watts_z
template sensor: - unique_id: solar_forecast_estimate_current_hour_z state: > {% set nw = now().replace(minute=0,second=0,microsecond=0) %} {% set nu = as_timestamp(nw)|timestamp_custom %} {% set watts = state_attr('sensor.solar_forecast_estimate_watts_z','watts') %} {% if watts %} {% set data = watts.items() %} {{watts[nu] ~' W' if watts and nu in watts else 'No production estimated'}} {% else %} Offline {% endif %}
the rest api resource: solar_forecast_api_z: https://api.forecast.solar/estimate/<lat>/<long>/12/0/6 # ?time=utc
but I exceeded the api limit now... so have to wait another hour. they did return the correct value just before that hit though...
only thing I need to check is whether because of the missing “T” separator now, the Frontend still represents that as a correct value.
this is all you need
rest:
- resource: !secret solar_forecast_api_z
scan_interval: 86400
sensor:
- unique_id: solar_forecast_estimate_watts_z
<<: &estimate_watts
unit_of_measurement: W
value_template: >
{% set today = now().strftime('%Y-%m-%d') %}
{% if value_json is defined %}
{% set data = value_json.result.watts.items() |selectattr('0','search',today)|sort(attribute='1',reverse=True) | first | default %}
{{ data[1] if data else 'Unknown' }}
{% else %}
Unknown
{% endif %}
json_attributes_path: "$.result"
json_attributes: watts
- unique_id: solar_forecast_estimate_current_hour_z
value_template: >
{% set nw = utcnow().replace(minute=0,second=0,microsecond=0).isoformat() %}
{% if value_json is defined %}
{% set production = value_json.result.watts.get(nw) %}
{% if production %}
{{ production }} W
{% else %}
No production estimated
{% endif %}
{% else %}
Offline
{% endif %}
you can get rid of your template sensor
but you'll lose history
and if you need to make selections because the first sensor is providing wrong data (offset by 1), then the first template needs to be altered.
back, that would look like
{% set start = today_at().astimezone(utcnow().tzinfo) %}
{% set end = start + timedelta(hours=24) %}
{% if value_json is defined %}
{{ value_json.result.watts.items() | selectattr('0', '>=', start.isoformat()) | selectattr('0', '<', end.isoformat()) | map(attribute='1') | sort(reverse=True) | first | default('Unknown') }}
{% else %}
Unknown
{% endif %}
Hey guys, i want read out a input value and build a new string to check the state, someone can assist me here where is the problem?
{% if is_state("input_select.advanced_heating_control_wohnzimmer_{{scheduler_value}}", "on") %}
Comfort
{% else %}
Minimal
{% endif %}```
You didn't construct the new string properly. You nested the templates
{% if is_state("input_select.advanced_heating_control_wohnzimmer_" ~ scheduler_value, "on") %}
perfect thank you rob
@mild venture I converted your message into a file since it's above 15 lines :+1:
Hi everyone, I am trying to take a response from OpenAI and put that into an automation template, but getting the error: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
My template to grab the library_name value and do an if/then for what plex is looking for:
data:
media_content_id: '{{response_from_ai.response.speech.plain.speech|from_json}}'
media_content_type: >
{% if (response_from_ai.response.speech.plain.speech|from_json).library_name
== "Movies" -%}
movie
{%- else -%}
EPISODE
{%- endif %}
@mild venture I converted your message into a file since it's above 15 lines :+1:
Sorry was trying to make it not a file and ended up making it 2 files...
Sorry, was away for a bit. Smart! Thx, I’ll rebuild tomorrow .
Got my issue resolved. If was the '{{response_from_ai.response.speech.plain.speech|from_json}}' from media_content_id. Had to remove the from_json to get it to work with Plex
Is there a way to track if a light went on or off in a specific room ?
is there not a way to set delay_on and off in the UI for a binary sensor template?
No. Everything more than a state's template (or a static icon after setup) has to be done in YAML
and I cannot edit the YAML for a UI-created template, right? so I need to delete from the UI and recreate in configuration.yaml?
Correct
cool, thanks for confirming.
can I get away with just a yaml reload or do I need a full HA restart when testing these yaml templates?
What are % and %- called, and how do I search for their description/use?
Rant:
I would like to say, jinja is an extremely lousy way to do templates.
Convenient in simple cases, but anything more, it's a giant pain.
I wish we had something built in without resorting to custom components or hacs integrations that allows us to do native scripting with another type of template that can properly manage data, data types and variables without jumping through hoops.
What I mean:
native scripting - directly in scripts and automations
another type of template - or script block, using python or lua or heck even elixir
hoops - without having multiple lines of if else endif, and piping things through filters and using namespaces or dynamic dicts or creating an entire custom component to do what I need
That's all. Have a nice day all.
Edit: make things clear to myself.
Found this as part of 'a project' that I had to put it in configuration.yaml
sensors:
lights_on:
friendly_name: "Lights On"
value_template: >
{{ states.light | selectattr('state', 'eq', 'on')
| map(attribute='entity_id')
| list | count }}```
In my ``configuration.yaml`` I have ``template: !include template.yaml``so in this template.yaml file I added:
``` - sensor:
- name: lights_on
value_template: >
{{ states.light | selectattr('state', 'eq', 'on')
| map(attribute='entity_id')
| list | count }}```
Restarted HA but no sensor.lights_on when using dev tools
Change the key value_template to state
BTW there is no need to map it to entity_id if you are only going to count it
So my final template is:
- sensor:
- name: lights_on
state: >
{{ states.light | selectattr('state', 'eq', 'on')
| map(attribute='entity_id')
| list | count }}```
It counts all the lights. I also made some grouprs I'd llike to exclude for this template.
Any help would be appreciated how to exclude for example ``lights.all_lights``
- "You can do anything in templates"
- "Jinja uses various delimiters in the template strings.
{% %}..." - "you need to use a namespace if you're planning modify a variable..."
- "I see a lot of folks ask for how to know, of a group, who was th..."
- "To count lights which are on, and exclude light groups, note tha..."
- "Jinja (Template) Built-ins jinja.palletsprojects.com/en..."
- "Distinguishing Yaml from Jinja (templates) community.ho..."
- "Confused about the 2022.2 breaking
defaultchange? c..." - "Understanding types to parse JSON community.home-assist..."
- "@689168555861737485 Here's a template that looks up a friendly..."
Pin 5 📌
I'll start to study... Thanks for your tip!
stupid question: do I have to replace something in the code by my entity_id. I I think it's now unique_id for a group instead of entity_id?
Hi, I want to write a value from an input_text. to another input_text.
data:
value: "test"
does work, but
data:
value: "{{ states(input_text.stored_value) }}"
does not.
What am I missing?
Initial state is:
{{ states.light | selectattr('state', 'eq', 'on')
| map(attribute='entity_id')
| list | count }}```
I changed to
```state: "{{ states.light | selectattr('state', 'eq', 'on')
| rejectattr('attributes.entity_id', 'defined')
| list | count }}"```
and
```state: "{{ states.light | selectattr('state', 'eq', 'on')
| rejectattr('attributes.alle_lampen', 'defined')
| list | count }}"```
but in both last examples the template becomes 'unavailable'
If you go to the developer tools and paste {{ states(input_text.stored_value) }} into the templates section, what does it return?
Go back to the first format with the > and no quotes and just add in the reject.
'input_text' is undefined
🤔
So you haven't created an input text helper named stored_value
It needs to be quoted {{ states('input_text.stored_value') }}
This does the Trick! Thx!
Missed that
🤣
hi guys, i added a simple switch template in my configuration.yaml file. i then renamed it. now i see both switch-templates in my entities, even though the first one doesnt exist in the configuration.yaml anymore. why is this? i have restarted ha multiple times
He also missed that in my example
#automations-archived message 😉
You didn't give it a unique_id
oh ok, ill try with that. thank you
is there a way i can put all the code for my different switches in a separate yaml file? so my configuration.yaml doesnt get so packed?
I don't know where to put this, but it ist Templates related, hence I'll try it here.
Running this line in dev tools does produce the correct link.
https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/{{ states('input_text.coords') }}?include=fcst%2Cobs%2Chistfcst%2Cstats%2Chours&key=<my_api_key>&lang=de&unitGroup=metric&options=beta&contentType=json
but I cannot store this in another input_text (though' the result is only 249 characters long), nor use this as a resource in
rest:
- scan_interval: 300
resource:
Any ideas how to narrow the problem down? (Or how to make it work even?)
oh, pasting the final link into the rest part does work. It's only the dynamic thing that doesn't
You need to use resource_template if you want to use templates.
@inner mesa @lyric comet Reading the documentation thoroughly actually DOES help 😅 That was an unexpected distinction. Thanks again!
I'm sure this is simpler than I'm making it. I want to display an icon of my choosing for the state that I set on some "thing". I assume I need to define a helper toggle as my thing. Then make a template that monitors the toggle state and displays an icon based on the state. But all the template examples are using some physical device.
That is display an icon in a dashboard.
If you just want it for the dashboard, you could simply use a Mushroom template card and template the icon.
You can also do it at the sensor level using a template entity. For the latter option there are some notes of mine here: https://www.rjt.org.uk/home/archives/home-assistant-tip/creating-a-template-entity-with-dynamic-icon/
This example shows my problem. It shows the icon based on 'sensor.moto_g_6_battery_level'. I don't have any such thing, I need a virtual thing that I can set it either on or off from an automation. So I want to define a "thing" (I can't seem to resolve in my mind the abstractions; sensors, helpers, etc.) that has defined states of on and off.
You could define an Input_boolean helper, then just override the icon on the desktop, or define a template switch from scratch in Yaml
can i only use the !include command in the configuration.yaml for 1 "type" of code, for example scripts? i cant for example put all the different code for 1 product, like switchbot in one separate yaml file and then include it?
That's called a package
To enable packages, add packages: !include_dir_named packages to your configuration.yaml so that it looks similar to this:
homeassistant:
...
packages: !include_dir_named packages
Important: The packages: line must be nested under homeassistant:!
For more information on packages, please refer to the packages docs: https://home-assistant.io/docs/configuration/packages/
ah nice that this also exists. thanks!
I am trying to create a template that will show battery powered entities that state < 31.
I've created a group and an input number
the following it doesn't return an error, neither correct results.
{{ expand('group.zigbee_nodes_battery')
| rejectattr('state', 'in', ['unavailable','unknown'])
| selectattr('state', '<', states('input_number.zigbee_low_battery_threshold'))
| map(attribute='entity_id')
| list | join('\n')
}}
What am doing wrong?
Desktop? Template switch from scratch? I think that's what I want, but, I can't find an example of that doesn't use an existing entity.
It's doing a string comparison
All states are strings. Unfortunately it's not possible to do what you want without a for loop
I use MQTT for completely standalone switches, or you might find it easier to set up an input_boolean with a template switch to mirror it with your extra options for icons.
Thanks, I can basically do that, but i'm missing something... I'm sure Ill get to the aha moment after a few more hours of videos. 😎
thanks for the reply. anyway to show battery entities with low battery ?
Question, is there anyway to get a list of services that's tied to a notification group?
I have tried expand(), but that returns an empty list. I'm assuming that's because it's a list of services rather than entities.
I don't think so
Thanks for the reply anyway. Appreciate it.
How do you make a template sensor with the timestamp device class
- trigger:
- platform: state
entity_id:
- vacuum.sl60d
to: cleaning
for:
minutes: 5
sensor:
- name: "Vacuum Last Clean"
state: "{{ now() }}"
device_class: timestamp
icon: mdi:broom
Don't see an issue with that one
ValueError: Invalid datetime: sensor.vacuum_last_clean has timestamp device class but provides state 2024-01-21 16:32:33.708601+10:00:<class 'str'> resulting in ''str' object has no attribute 'tzinfo''
sorry, didnt realise I didn't hit enter
This is the error in logs
@summer arch I converted your message into a file since it's above 15 lines :+1:
Does it work with "{{ now().isoformat() }}"
No, same error I tried that one a while ago when I came across a forum post.
I have also tried as date time and as timestamp even
@summer arch Just did a quick test on my system (2024.1.5) an this is working for me:
- trigger:
- platform: state
entity_id: input_boolean.test
to: "on"
for:
seconds: 2
sensor:
- unique_id: 2351e548-664a-4850-8c58-979d0fbf9e0f
name: "Test 123"
state: "{{ now() }}"
device_class: timestamp
is attribute 'tzinfo' some dependancy thats not installed on my system? runnming haos 2024.1.4
- trigger:
- platform: state
entity_id: vacuum.sl60d
to: cleaning
for:
minutes: 5
sensor:
- unique_id: vacuum_last_clean
name: "Vacuum Last Clean"
state: "{{ now() }}"
device_class: timestamp
icon: mdi:broom
This is more like yours now?
now its working....
what changed
You added a unique id
nvm
This entity is no longer being provided by the template integration. If the entity is no longer in use, delete it in settings.
It probably created a _2 because you now added the unique id
ValueError: Invalid datetime: sensor.vacuum_last_clean has timestamp device class but provides state 2024-01-21 16:32:33.708601+10:00:<class 'str'> resulting in ''str' object has no attribute 'tzinfo''
nope just the one
I don't have a clue then. You have this under template: right?
The error indicates your datetime doesn't provide information about the timezone, but it does (+10:00)
yes, template: !include template.yaml and then the snippet in there
so what do I do 😢
it would suggest my state is a string and a string has no timexone info?
but as showed, yours works
I think I got it but it doesn't make sense (or at least it isn't reading as not supplied now)
I coppied example here to vs code and looked at the indent with rainbow indent https://www.home-assistant.io/integrations/template/
and the -platform is double indent under -trigger?
but sensor is single indent
I indented -platform
2024-01-21T10:19:09+00:00
looks like it workd
I did notice that, but thought it wouldn't matter
Not sure what you mean with - platform: though, that's only used in the legacy format
The trigger platform for templates
yeah, platform for the trigger had to be double indented
so how do I make a template sensor with a triger then? cause docs still show that is the way (*see link)
Oh yes
You were just not using the same indentation for the trigger configuration and the sensor configuration
using a template on an entities state in an automation to create an entry in calendar:```
- service: calendar.create_event
target:
entity_id: calendar.afvalwijzer
data:
summary: >
{{trigger.to_state.attributes.friendly_name}}
start_date: >
{{trigger.to_state.state}}
end_date: >
{{trigger.to_state.state}}
are there other considerations here, or cant we use a template like this at all?
nvm. this is it:Expected minimum event duration of 0:00:01 (2024-01-28, 2024-01-28).
@turbid mural I converted your message into a file since it's above 15 lines :+1:
@twilit kettle
#automations-archived message
You can play around with this is the template editor (developer tools -> template):
{{ expand('binary_sensor.group_fenster_und_turen') | selectattr('state', 'eq', 'on') | map(attribute='name') | join(', ') }}
It is probably a string which looks like a number (all states are strings). Try add
{{ value_json.days[0].hours[states('sensor.time1')|int(0) ].temp }}
this works for the calendar.....:```
start_date: >
{{trigger.to_state.state}}
end_date: >
{{as_timestamp(as_datetime(trigger.to_state.state) +
timedelta(days=1))|timestamp_custom('%Y-%m-%d') }}
This works! Thx a lot. Something new everyday^^
or this, which still is a terrible template for indicating an event:```
action:
- variables:
date: >
{{trigger.to_state.state}}
- service: calendar.create_event
target:
entity_id: calendar.afvalwijzer
data:
summary: >
{{trigger.to_state.attributes.friendly_name}}
start_date: >
{{date}}
end_date: >
{{(as_datetime(date)+ timedelta(days=1))
|as_timestamp|timestamp_custom('%Y-%m-%d')}}
@hybrid halo I converted your message into a file since it's above 15 lines :+1:
Sorry I found a bug!

is this how to run a shell_command with passing args to the command?
shell_command:
manage: '/config/scripts/manage.py "{{ args }}"'
I think it not working but I'm not sure how to debug the output. I tried using a script but i get errors tthere too.
sequence:
- service: shell_command.manage
data:
args: "--help"
response_variable: manage_response
- service: persistent_notification.create
data:
title: "card info:"
notification_id: "manage_response"
message: "{{manage_response['stdout'] }}"
What do the values in the script trace show?
no matter what I try, I cant get a working default for this template secondary: > {% set event = state_attr(config.entity,'datum')|as_datetime|as_local %} {{state_attr(config.entity,'type')}}: {{event.strftime('%d-%m-%Y')}} on the set event. those state_attr(config.entity,'datum') have the '1956-09-12 00:00:00+01:00' form
but on restart (and when on that particular view, the templates in that view sometimes throw: 'TypeError: float() argument must be a string or a real number, not 'NoneType''
It's probably being evaluated before the integration is set up
I would use now() if state_attr(xxx) is not defined else yyy or check against None
Sorry I had to run out.
In developer tools I looked and it seems like the script is not receiving the args properly. it is saying error: unrecognized arguments: --info 123456 when in the actual cli it works
developer tools: service, shell_command
This error?
It's caused by applying datetime before the integration for config.entry is ready
You could do this
its probably caused by the final use of the 'event' in {{event.strftime('%d-%m-%Y')}} ?
No
I also made a suggestion
yep let me try that
I have a PR open to add the default parameter to as_datetime
It's a dumb error right now
confirm the default(0,true) to fix it... I had tried |default(0), but missed the true
I initially made the PR so it would always either return a datetime object or None (when no default was provided) but that was not accepted
I'm using this across a few automations to prevent weird things happening with successive triggers:
{{ (now() - state_attr('automation.sync_living_and_dining_lights_brightness','last_triggered')).total_seconds() > 1 }}
Is there a way to replace the automation.xyz part with a reference to 'this automation' so I can easily use this as a copy/paste?
seems like you could just add a delay at the end of the automation if you're trying to prevent rapid successive triggers
I just ran a quick test:
- id: test_trigger
alias: test_trigger
trigger:
- platform: event
event_type: foobar
action:
- service: persistent_notification.create
data:
message: "{{ this }}"
output was:
{'entity_id': 'automation.test_trigger', 'state': 'on', 'attributes': {'id': 'test_trigger', 'last_triggered': None, 'mode': 'single', 'current': 0, 'friendly_name': 'test_trigger'}, 'last_changed': '2024-01-21T23:31:02.185737+00:00', 'last_updated': '2024-01-21T23:31:02.185737+00:00', 'context': {'id': '01HMQ5SYX9NC69CWW1H68MDRC3', 'parent_id': None, 'user_id': None}}
so... {{ this.entity_id }}
yep! this {{ (now() - state_attr(this.entity_id,'last_triggered')).total_seconds() > 1 }} totally works
the delay method creates more annoyance that it solves I think. Much prefer this.
Note that this.last_triggered is exactly the same
See the output above. It's a state object
sorry not sure I follow that last part. exactly the same as what?
Actually, it's this.attributes.last_triggered
As your state_attr() call
See my experiment. Run your own
OK I will, that's handy to be able to see the trigger outputs. I don't think that's in the docs but it would be helpful for building automations using these. https://www.home-assistant.io/docs/automation/templating/
this is certainly cleaner.
can someone help before i lose my sanity here? i cannot figure out where the syntax error is
`template:
- sensor:
name: hvac_main_binary
state: >
{{ (states('sensor.emporiavue2_circuit_4_power') > int 100) | iif('true', 'false') }}`
Invalid config for 'template' at configuration.yaml, line 138: invalid template (TemplateSyntaxError: expected token ')', got 'integer') for dictionary value 'sensor->0->state', got None
States are strings
state: >
{{ states('sensor.emporiavue2_circuit_4_power') | int > 100 }}
You put '> int 100', which is nonsense
oh duhhh!! that sensor in particular should be an integer value though
That's better
What you're doing with 'true' and 'false' doesn't make sense
Just make a binary_sensor and return the test
thats what this is for - a part of history_stats tracker.
- platform: history_stats name: Main HVAC today entity_id: binary_sensor.hvac_main_binary state: True type: time start: "{{ today_at() }}" end: "{{ now() }}"
i think i'm over complicating this in my head
But the entity resulting from your posted code will be sensor.hvac_main_binary not binary_sensor.hvac_main_binary
yea i just saw that - ive not gotten that far yet
And string a string of true or false, which is weird and unnecessary
For that you will need:
- binary_sensor:
- name:
...
got it - thanks guys
Hey there. I am trying to get a sensor created from a JSON file located through a website. I have to authenticate with a token I have so, I know authentication needs to be "bearer". I have this, but don't think it's correct :(. Can anyone assist on the correct method of doing this? I am wanting the token to pull from my secrets.yaml file as well.
sensor:
- platform: rest
resource: "https://mywebsite.com/test.json"
headers:
Authorization: >
Bearer !secret test_token
value_template: '{{ value_json.TestData[0].TestLevel }}'
name: My Test Sensor
Hi, any that can assist,
# MQTT Generator
mqtt:
sensor:
- name: "Main L1 Watts"
state_topic: "32841/6D2B9ABBCB"
unit_of_measurement: "W"
value_template: "{{ value_json.R060 }}"
- name: "Generator_L3_watts"
state_topic: "32841/6D2B9ABBCB/Generator_L3_watts"
unit_of_measurement: "W"
value_template: "{{ value_json.32841/6D2B9ABBCB/Generator_L3_watts }}"
i'm not winning
this from the broker
@keen heath I converted your message into a file since it's above 15 lines :+1:
I am not sure why you are doing what you are doing neither of those statements look correct.
To start with try putting all the json attributes in the attributes and the samples you posted don't even match the message you are trying to read.
Something like
- name: "battery_volts"
state_topic: "32841/6D2B9ABBCB/Engin_battery_volts"
value_template: >
{{ value_json.6D2B9ABBCB.P004.R005 }}
json_attributes_topic: "32841/6D2B9ABBCB/Engin_battery_volts"
might work, but I am no expert.
If not set the value template to a static value until you can easily see the attributes and workout the correct extraction.
what does the R0## represent?
what does the P0## represent?
So what is R060 and P004 mean?
Your response doesn't seem like it answers my question.
The topic you show is 32841/6D2B9ABBCB/Generator_L-N, where the data is
{
"6D2B9ABBCB": {
"P004": {
"R008": 2326,
"R010": 2322,
"R012": 2328
}
}
}
so in regards to JUST THAT information, what does P004, and R008, R010, and R012 represent? @keen heath
I think the P004 is maybe the gateway, as it not changing but the R008 is like voltage so L-1 to Nutral is volt
ok, and what about the other R data?
The template needs to know what to do, right now the R keys are not static, therefore a static template will not do the job
until you can answer the question about R, there's nothing we can do to help
while {{states(trash)}} outputs ' 2024-02-02' (and the entity is a device_class: timestamp, how come the {% from 'easy_time.jinja' import month %} {{month(trash)}} (or states(trash) ) for that matter outputs the current month januari?
is trash in the wrong format for that macro?
@keen heath at most I can tell you that your template will most likely look something like this, however the ... inside the {{ }} will be replaced with information that grabs from the proper R data>
- name: ???
state_topic: "32841/6D2B9ABBCB/Generator_L-N"
unit_of_measurement: "W"
value_template: "{{ value_json['6D2B9ABBCB'].P004... }}"
month expects an integer
month(1) would be january, if you provide bad data, it defaults to the current month
o in that case I did 😉 (provide bad data....)
{{month(as_datetime(states(trash)).month)}}
Yep was just going to say that
cool, thx
@keen heath can you provide a link to the documentation on your device that covers the MQTT responses?
would you be interested in adding some functionality to that so we can simply drop in a timestamp and easy_time calculates the month?
You can add a issue as a FR
sure, will do. thx for considering
What could I use to make tts spit to this url?
http://wirepodIP:8080/api-sdk/assume_behavior_control?priority=high&serial=##000000
http://wirepodIP:8080/api-sdk/say_text?text=" + "Your family room lights are off etc" + "&serial=##000000
http://wirepodIP:8080/api-sdk/release_behavior_control?priority=high&serial=##000000
I would like so I can just call this some way and then it would work kind of like the media player and template in the text field there
The first line grabs control of the device the second takes the text input the third releases control of the device.
example:
service: notify.alexa_media_robot_vector
data:
message: Your family room lights are off
please can you PM your email
Sorry, I don't offer support outside these channels
can I we transfer the doc
I understand
Hi! They have the following sensors and I would need a template for a new sensor with a name sun_opacity:```
Cloud coverage = sensor.cloud_coverage
PIR-Lx = sensor.pir_je_illuminance_lux
UV-index = sensor.weatherapi_dom_uv_index
Can you just provide a link to the documentation? Or the unit that you have? I'm not sure why you need to email me the doc
as the DSE send me the documents
How large is it?
https://github.com/Petro31/easy-time-jinja/issues/27 hope this makes sense
The wish is as follows ```
Cloud coverage rounded to 1 decimal place! 0.x5 up 0.x4 down rounded
PIR-Lx / 100 and rounded to 1 decimal place! 0.x5 up 0.x4 down rounded
UV-index /10 unless 11 = 1
change the units on each sensor in the entities options (cog)
then make a sensor group w/ average as your selected option
no templates needed.
3 Mb
Hi. Thanks for the reply. I don't know how to work with templates or I don't know how to write code! Im asking for help.
read everything I wrote
no templates needed.
0% of the things your'e asking for require code
Everything can be done via the UI
post the link here
UV index will be a problem for me Cloud coverage = from 0 to 1 UV-index = from 0 to 11 PIR-Lx = from 0 to 100 (in all likelihood)! and PIR-Lx! I would use the score for opacity and the score should be between 0.1 and 1
see page 74
Wow, you're going to have to use that document to figure out what each register means
you basically have to reverse engineer the entire response as if it were modbus, which is no easy feat
at the bottom of page 81, it describes what P and R are
Those are unsigned integers that represent the data.
Typically, an API like this requires a full blown integration
You can probably do it in value_template, but it's going to be challenging
You aren't understanding what I'm saying
The manual covers the data that's coming out of the device, as a modbus protocol
Ok, so do you know what each register means and what it does?
yes
Do you know how to convert the information from the register to your real life value?
if you don't, then you need to figure that out. Simply getting the information from a single register will be
- name: P004 R036
state_topic: "32841/6D2B9ABBCB/Generator_L-N"
value_template: "{{ value_json['6D2B9ABBCB'].P004.R036 }}"
I understand taht, but this requires dev knowledge, not IT knowledge
All this will do is get you the value from the register
and even then, if the register isn't supplied, it will error
- name: P004 R036
state_topic: "32841/6D2B9ABBCB/Generator_L-N"
value_template: "{{ value_json['6D2B9ABBCB'].P004.get('R036') }}"
that will not error, but your sensor will go unavailable whenever the register isn't supplied in the data
- name: P004 R036
state_topic: "32841/6D2B9ABBCB/Generator_L-N"
value_template: "{{ value_json['6D2B9ABBCB'].P004.get('R036', 0) }}"
that will not error and supply 0 when the register isn't supplied in the data
Again, that will only get you the unsigned integer from the register
You still need to know what each register represents, and how to conver said register to your real life value. All of which, may be supplied in that documentation, but probably depends on how it's wired/setup.
add a unique_id, then adjust the precision via the UI
thank you
- name: P004 R036
unique_id: something_unique_to_all_mqtt_entries_you_add
state_topic: "32841/6D2B9ABBCB/Generator_L-N"
value_template: "{{ value_json['6D2B9ABBCB'].P004.get('R036', 0) / 1000 }}"
thank you.
if a line has more value
value_template: "{{ value_json['6D2B9ABBCB'].P004.get('R008', 0)('R010', 0)('R012', 0) }}"
is that correct
I don't know what that means
Dump TTS messages to device
so my main get power for solar so it go in to the - watt as we push back to the grid
@mighty ledge Thank you for all the support. I really really thankful for the support. Next step Victron intergration
hey everyone! I'm having trouble achieving the look I want in the entities card. Here's the picture https://ibb.co/wzLcFcF and here is the code https://pastebin.com/6SbY3UKv. I've read through the entities card tutorial on HA website but can't wrap my head around the function that I need... Any help would be greatly appreciated!
Wrong channel. You want to ask that in #frontend-archived
so sorry, thx!
I'm trying to avoid writing a bunch of if/else blocks in an automation, so I figured a Jinja template would be a nice way to ease some of that, but I'm having a problem getting the template to render for every automation run. Here's a simple example, what am I doing wrong? Do I need to move it somewhere else, or take a different approach?
- service: light.turn_on
metadata: {}
data:
brightness_pct: "{{ 75 if states('sun.sun') == "above_horizon" else 20 }}"
target:
device_id: e126710010c6ba52093b7d8525c2615d
what do you mean by:
I'm having a problem getting the template to render for every automation run
it works sometimes?
Here's a screencap of what I'm seeing visually: https://imgur.com/a/FGvstpa (edited to move to imgur)
(boo, doesn't look like I can upload a gif directly here 😦 )
When I put the jinja string in there, the left of the editor turns red.
It sort of feels like I need to put the jinja template string somewhere else maybe?
please use something like imgur
Please use imgur or other image sharing web sites, and share the link here.
Image posting is blocked in most channels to discourage people from sharing text as images. Sharing text as images assumes that everybody sees the world as you do, which isn't the case. Some people are colour blind, or have visual impairment that means they can't make sense of an image of text.
but I don't see anything wrong with that
it may just be telling you that it doesn't support templates in the UI editor and you need to use YAML
you can try it in
-> Services
Service YAML contains syntax errors, please fix the syntax
shakes fist.
Nothing obvious is jumping out at me.
Maybe removing the metadata: {} part?
Hey all👋
Need help with a Home Assistant template to show if there is any tomorrow's local calendar events. Any tips or templates to share?
@marsh cairn Nope, I don't think that's it. I'm having the same problem doing this directly in Dev Tools -> States, and in that block I'm not using metadata.
Here's what I'm seeing in Dev Tools. You can very clearly see that using 75 and 20 for values directly just works, but the jinja template string is the problem: https://imgur.com/a/vM0xruM
I feel like this should just work.
I got a bit more context by editing the automations.yaml file directly: YAMLSyntaxError: All collection items must start at the same column. YAMLSemanticError: Implicit map keys need to be followed by map values.
And: cannot read implicit mapping pair; a colon is missed
Does this work?
- service: light.turn_on
data: |
{{ {'brightness_pct': 75 if states('sun.sun') == "above_horizon" else 20} }}
target:
device_id: e126710010c6ba52093b7d8525c2615d
that should definitely not be necessary
oh, duh. you were using " both inside and out
- service: light.turn_on
metadata: {}
data:
brightness_pct: "{{ 75 if states('sun.sun') == 'above_horizon' else 20 }}"
target:
device_id: e126710010c6ba52093b7d8525c2615d
would be fine
Quotes... I should pay more attention to those too 😅
Blaaaaah!
Whelp, I feel dumb. Thanks y'all! That's one mistake I'll never make again 😛
Haha, true. But I know I'll never git bit byte it again
Any idea's why I my robot says "unknown" instead of the message I put? https://discord.com/channels/330944238910963714/1198966112239501403
(I may be templating it wrong or maybe you can't template there?)
You need to figure out how to get it to say something without templates before you try to tackle using templates
If I remove the template and put the text in there it says it fine?
Are you referring to this template:
say_text:
url: 'http://10.0.0.111:8080/api-sdk/say_text?text={{ states("input_text.your_text") }}&serial=00######'
?
Yes
If I change that to
say_text:
url: 'http://10.0.0.111:8080/api-sdk/say_text?text="test 1 2 3"&serial=00######'
It works fine he says "Test 1 2 3"
Do you have an input text helper with an entity _id of input_text.your_text?
nope just created one will test again.
That template will provide the state of that input helper. I would suggest you create an input text helper and populate it with some text to it
What...did you think would happen? 🙂
What is the name of your input helper?
I'll try putting some static text in it
your_text
As opposed to what?
hmm
Input text helpers hold plain text
input_text.your_text
Ok so if I manually enter stuff in that box and hit enter then trigger it Vector says what's in that box
When I opened the door he said Test 1 2 3
but the automation doesn't seem to dump text in there and then say it...
Maybe we need to go back to what you’re trying to do.
- service: rest_command.say_text
data:
your_text: 'Your family room lights are off etc'
does that need to be text_input.your_text
No
You have a couple ways you can do this
You could call the service to set the value of the input text helper you created: input_text.set_value
https://www.home-assistant.io/integrations/input_text/#services
Then you would just need to call the service rest_command.say_text and you don’t need to provide data because you put the text into the input text helper
The other method is to ditch the input text helper and have the automation provide the text and you re-write the template to use that text
@humble mortar I converted your message into a file since it's above 15 lines :+1:
How do I accomplish this?
First you need to change the template to expect a variable. Let’s call it your_text
say_text:
url: 'http://10.0.0.111:8080/api-sdk/say_text?text={{ your_text }}&serial=00######'
done
Then you can revert the service call back to what you originally had, where it was providing the your_text variable to the service:
- service: rest_command.say_text
data:
your_text: 'Your family room lights are off etc'
Working thank you for your help!
There's so many examples in the forums of people trying to template a URL and at the end either nobody answers them or they say something like GOT IT... and don't show how it was done 😄 most of them gave up on rest and switched to curl'n a URL with shell_command 😖
Templating a url is just templating any string. Most people template strings for notifications, so a good google phrase is “home assistant template notification”
Anyone know why I'm getting this error in setting up a Template Sensor for Airgradient (ESPHome)?
Sensor None has device class 'aqi', state class 'measurement' unit 'None' and suggested precision 'None' thus indicating it has a numeric value; however, it has the non-numeric value: 'template: - sensor: - name: "AQI (pm2.5)" state: >- 4 unit_of_measurement: AQI device_class: aqi' (<class 'str'>)
Do you have a good example url?
Is the template sensor yaml for the esp device itself or is this home assistant code? If it is code for home assistant you want #integrations-archived and if it is ESPHome you probably want the ESPHome discord but you could try #diy-archived or #add-ons-archived
This was the first result: https://community.home-assistant.io/t/templates-in-automation-push-notification-message/124844
There isn’t much info there but there’s not much you need to know either: creating a string and a template is simply "some normal text combined with {{ some_template }} and that is {{ 'all' if 1==1 else 'blah' }} there is to it"
Oh ok I thought you were saying to convert the automation into a notification
No, sorry for the confusion. Normally people are trying to template strings for a purpose different from what you are trying to achieve. But the method to achieve a string as a result is the same
It's home assistant code, will do. Thanks!
How would I get the templated automation to be used like a notification?
So I could just go into my other notification group and dump this unit into it as well?
- name: ALL_DEVICES
platform: group
services:
- service: mobile_app_1
- service: mobile_app_iphone
- service: mobile_app_android
- service: mobile_app_iphone2
- service: alexa_media_vector
- service: desktop_1
- service: desktop_2
- service: robot_vector #<= add it like this
example
service: notify.ALL_DEVICES
data:
message: Your family room lights are off
To start, you need a notify service called notify.robot_vector
Do you have one or are you asking how to create one?
Can it call an automation ie the one we made and just dump text to it?
Not that I’m aware of. Your best bet is to ask over in #integrations-archived for help with notify services
Ok will try that just thought it would be difficult to explain this all over again to someone unaware of what I was doing already.
Hi, can anyone help me with getting the result of a service call into the attributes of a template sensor. I am trying to enhance the opensky integration with a service call but have no clue to actually get the data 'out' 🙂
I would also like to use it in a card, e.g. map card could then show the flights based on the position
Any example would probably alreayd help me investigating in the right direction
Enhancing an integration with a Service call sounds more like a #developers thing
The enhancing part I can do, I am just not sure how this would be put to use as part of a template sensor
i.e. the service would kick back a dict. The current integration (my enh.) will be adding that to a sensor (the 'opensky' sensor) but I alo want to use this in a different way...if possible
an action: section has been added to trigger based template sensors. You can use service calls in there, and use the service response in the config for the (binary) sensor
ah...yesss... forgot...alike the forecast one
correct
thx
do we have documentation on that? and if yes, where, because this doesnt mention any condition option https://www.home-assistant.io/integrations/template/#configuration-variables
There is no condition option, only action which is documented here: https://www.home-assistant.io/integrations/template/#action
it's covered all over the docs, every service call that might need it.
aargh, i was loking for the wrong info... apologies for that
and then I bumped into that big video and couldnt think straight anymore
this is what I was looking for https://www.home-assistant.io/integrations/template/#trigger-based-handling-of-service-response-data
I'm trying to add a js to a custom card.
To return the attr I have to write:
````${states["sensor.test"].attributes.xxxx}```
But what if I want to return the state itself?
that's #frontend-archived
If I use:
${states["sensor.test"]}
It returns [object Object].
because that's a state object. But still #frontend-archived
How can I get a list of all the automations based on a certain blueprint
There's no attribute or any other indication that an automation is created based on a blueprint. So this is not possible using templates
Hello. I have two solar cards but I want to calc them together as one?
Hey!
I'm trying to create a template [on action tab] that will raise +1 degree temperature to the ac device.
service: climate.set_temperature
data_template:
entity_id: climate.bedroom
target_temp_low: {{ (state_attr('climate.bedroom', 'current_temperature')|round(0)) + 1 }}
What am I doing wrong?
current_temperature is the measured temperature, not the temperature it is set to
You should also wrap your template in quotes
And date_template is depreciated for years already, you can just use data
so instead the current_temprature, what should it be?
States in the developer tools would show:
https://my.home-assistant.io/redirect/developer_states/
My guess would be temperature
hvac_modes: cool, heat, fan_only, dry, heat_cool, off
min_temp: 8
max_temp: 30
target_temp_step: 1
fan_modes: quiet, low, medium, high, auto, strong
swing_modes: stopped, rangefull
current_temperature: 19.3
temperature: 27
current_humidity: 75.5
fan_mode: high
swing_mode: stopped
icon: mdi:air-conditioner
friendly_name: Bedroom
supported_features: 41
service: climate.set_temperature
data:
entity_id: climate.bedroom
target_temp_low: {{ "(state_attr('climate.bedroom', 'temperature')|round(0))" + 1 }}
quotes like that? or even after the + 1 at the end?
Around the curly brackets, not within
service: climate.set_temperature
data:
entity_id: climate.bedroom
target_temp_low: "{{ (state_attr('climate.bedroom', 'temperature')|round(0)) + 1 }}"
that should do it?
EDIT:
Error running action
some but not all values in the same group of inclusion 'temperature' @ data[<temperature>]. Got None
Am I doing this template wrong? it reads the template name instead of the data I'm trying to pass it.
https://discord.com/channels/330944238910963714/1199204698901729401
well in devtools i'm getting this error
ValueError: Template error: round got invalid input 'None' when rendering template '{{ (state_attr('climate.bedroom', 'temperature')|round(0)) + 1 }}' but no default was specified
Your temperature attribute seems not to be numerical
but it's showing 27 in the attribute via devtools -> states
What does {{ state_attr('climate.bedroom', 'temperature') }} say in the dev tools?
Result type: number
27
This template listens for the following state changed events:
Entity: climate.bedroom_ac
climate.bedroom_ac ?
yeah, got few climate entities
And what does climate.bedroom say?
null
That's your problem
but it doesn't matter, when I try the string
service: climate.set_temperature
data:
entity_id: climate.bedroom_ac
target_temp_low: "{{ (state_attr('climate.bedroom_ac', 'temperature')|round(0)) + 1 }}"
it gives an error.
i'm trying to make it work on the entity that showing 27 in dev tools first, then i will try to solve the other climate device
Error running action
some but not all values in the same group of inclusion 'temperature' @ data[<temperature>]. Got None
I would go with something like this:
{{ state_attr('climate.bedroom', 'temperature')|int(7) + 1 }}
If the attribute isn't numerical it defaults to the minimal value of your climate entity - aka setting it to 8 degrees
If other climate entities have another min_temp, you have to adjust that.
Error running action
some but not all values in the same group of inclusion 'temperature' @ data[<temperature>]. Got None
in devtools it's showing 28 btw
Or set it to a default value -1 you prefer.
still not working.. there is something wrong
Does this work?
service: climate.set_temperature
data: |
{{ {'target_temp_low': (state_attr('climate.bedroom', 'temperature')|int(7) + 1)} }}
target:
entity_id: climate.bedroom
let me check
Error running action
some but not all values in the same group of inclusion 'temperature' @ data[<temperature>]. Got None
nope
And this?
service: climate.set_temperature
data:
target_temp_low: "{{ state_attr('climate.bedroom', 'temperature')|int(7) + 1 }}"
target_temp_high: 30
target:
entity_id: climate.bedroom
Error running action
No target temperature provided
I'm using sensibo if it's matter
Does the climate entity bedroom have a high and low setting or does that one just use a single target temperature?
just one I think
Added this when I run the automation it reads the template name instead of what I put in message of the automation he says "vectortext"
configuration.yaml
command_line:
- notify:
name: vectortts
command: "curl -X POST -H 'Authorization: Bearer LongLiveToken' -H 'Content-Type: application/json' -d '{\"message\": \"{{ vectortext }}\"}' http://HAIP:8123/api/services/script/vector_speech"
automation
service: notify.vectortts
data:
message: test
I don't think you can use the target_temp_low: for that one. Try temparature: instead.
You cannot use the " quotes outside and inside the string
What should it look like?
I tried like 10 different combinations of quotes and no quotes all over the place without success.
The line above was the only one that actually let it load the configuration without failure.
What happens, if you are using the following service call?
data:
vectortext: test```
@sonic sand according to the docs you need to provide target_temperature_high as well if you use target_temperature_low
https://www.home-assistant.io/integrations/climate/#service-climateset_temperature
We tried that as well.
Error running action
extra keys not allowed @ data['vectortext']. Got None required key not provided @ data['message']. Got None
I forgot it's a notifyer, not a script 
in addition the the low and high?
@marble jackal Does escaping the " quotes in the command line work this way?
#templates-archived message
I would use the multi line notation so the double quotes are not needed
service: climate.set_temperature
data:
target_temp_low: "{{ state_attr('climate.bedroom_ac', 'temperature')|int(7) + 1 }}"
target_temp_high: 30
hvac_mode: heat_cool
target:
entity_id: climate.bedroom_ac
like that?
How would that look?
command_line:
- notify:
name: vectortts
command: >
curl -X POST -H 'Authorization: Bearer LongLiveToken' -H 'Content-Type: application/json' -d '{"message": {{ vectortext }} }' http://HAIP:8123/api/services/script/vector_speech
And I don't think you need the quotes around the template
However, I don't see templates are supported at all there
https://www.home-assistant.io/integrations/command_line/#notify
After doing that he no longer says anything no errors
the hvac_mode method did not changed anything. still error.
Did you try this suggestion? #templates-archived message
Yes.
So you didn't, please read it carefully
As that would look like this
service: climate.set_temperature
data:
temperature: "{{ state_attr('climate.bedroom_ac', 'temperature')|int(7) + 1 }}"
target:
entity_id: climate.bedroom_ac
It works now, I thought that he meant change the current_temprature to temperature
Thanks man
and to lower by 1 degree i should just change the + to - ?
I am making a remote to that ac
Great that it works! he literally mentioned to change target_temp_low: for temperature:
Thanks Bas.
Is there any way to work around that?
There is a glitch in it that doesn't allow LongLiveToken to work so it just gets a 401 error.
🤔 What kind of glitch
I tried it and got the same issue
Maybe you can see something I did wrong if that is not the state of it?
notify.yaml
- name: vector
platform: rest
resource: http://HAIP:8123/api/services/script/vector_speech
method: POST_JSON
headers:
Authorization: !secret vector_llatoken
Content-Type: application/json
Logger: homeassistant.components.rest.notify
Source: /usr/src/homeassistant/homeassistant/components/rest/notify.py:223
Integration: RESTful (documentation, issues)
First occurred: 12:31:49 AM (1 occurrences)
Last logged: 12:31:49 AM
Client error. Response 401: Unauthorized:
NoneType: None
Why can't you just call the script directly?
I also tried to put Authorization: Bearer !secret vector_llatoken with no success same error.
I wanted the automation to identify as a notification so I can just dump it into notification groups that dump messages to it to say.
What does the script do?
Just dumps text to a robot with a text to speech engine for him to say HA notifications. "Your garage door is open, etc"
The robot doesn't have json compatible url interface just straight args in a url
I was trying everything to work around that.
This is what I did to basically get it working https://github.com/NonaSuomy/WirePodVectorCommandHomeAssistant/tree/main#Extra but my original goal was to get it working like a notification as said above.
headers are a list, not a dictionary
Sorry can you show me an example of what that means?
this is a dictionary
item:
something: value
something2: value
this is a list
item:
- something
- something2
Thank you so you just add the information with a dash and just the variable with no name?
it should be a full string
you should see errors in your logs with your current configuration
- name: vector
platform: rest
resource: http://HAIP:8123/api/services/script/vector_speech
method: POST_JSON
headers:
- "Authorization: !secret vector_llatoken"
- "Content-Type: application/json"
Something like this?
yes, but Authorization should be in your secret
and it should be listed as
- !secret ....
OK I will try that
if that doesn't work, the docs are wrong and a map is acceptable. I haven't looked at the code, the docs could be wrong
I'm starting to think the docs are wrong
Yeah, they are just wrong, ffs
it's a map
or dict, what you had
How do you use a map?
what you originally had
So it is b0rk then
What's in !secret vector_llatoken
just the LongLiveToken from HA
Testing...
notify.yaml
- name: vector
platform: rest
resource: http://HAIP:8123/api/services/script/vector_speech
method: POST_JSON
headers:
Authorization: !secret vector_llatoken
Content-Type: application/json
secret.yaml
vector_llatoken: Bearer ####...
Error running action
Unknown error
Hopefully more details in the log
ffs, the docs are wrong for params and header in all of the rest documentation
The logs will have the actual error.
I smell a PR 😛
I'm at work, otherwise I'd change it
it's not a PR you can do via the github website
If it is, I have no idea how to do it. Never dealt with a PR that touches multiple files from the website.
I have a fork on my desktop at home, if I remember, I'll update it
Ahh yeah, needs a fork. But you can edit your fork in an editor on the website.
good catch
Yay it worked!
Dies...
That was so much relentless mind mash
Thank you everyone!
I still get the error unknown in the log I see these two errors but he says the words ok any idea what it's looking for or how to handle the error is it looking for some kind of response but then timing out?
https://paste.debian.net/1305159/
https://paste.debian.net/1305160/
Are you still pointing at the same Home Assistant instance you are trying to call into? Are you sure you can connect HA to its self on loopback?
@humble mortar I converted your message into a file since it's above 15 lines :+1: